TransformState::move should not round offset to int
[WebKit-https.git] / Source / WebCore / page / FrameView.cpp
1 /*
2  * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
3  *                     1999 Lars Knoll <knoll@kde.org>
4  *                     1999 Antti Koivisto <koivisto@kde.org>
5  *                     2000 Dirk Mueller <mueller@kde.org>
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
7  *           (C) 2006 Graham Dennis (graham.dennis@gmail.com)
8  *           (C) 2006 Alexey Proskuryakov (ap@nypop.com)
9  * Copyright (C) 2009 Google Inc. All rights reserved.
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public License
22  * along with this library; see the file COPYING.LIB.  If not, write to
23  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #include "config.h"
28 #include "FrameView.h"
29
30 #include "AXObjectCache.h"
31 #include "BackForwardController.h"
32 #include "CachedResourceLoader.h"
33 #include "Chrome.h"
34 #include "ChromeClient.h"
35 #include "DocumentMarkerController.h"
36 #include "EventHandler.h"
37 #include "FloatRect.h"
38 #include "FocusController.h"
39 #include "FontCache.h"
40 #include "Frame.h"
41 #include "FrameActionScheduler.h"
42 #include "FrameLoader.h"
43 #include "FrameLoaderClient.h"
44 #include "FrameTree.h"
45 #include "GraphicsContext.h"
46 #include "HTMLDocument.h"
47 #include "HTMLFrameElement.h"
48 #include "HTMLFrameSetElement.h"
49 #include "HTMLNames.h"
50 #include "HTMLPlugInImageElement.h"
51 #include "InspectorClient.h"
52 #include "InspectorController.h"
53 #include "InspectorInstrumentation.h"
54 #include "OverflowEvent.h"
55 #include "RenderArena.h"
56 #include "RenderEmbeddedObject.h"
57 #include "RenderFullScreen.h"
58 #include "RenderIFrame.h"
59 #include "RenderLayer.h"
60 #include "RenderLayerBacking.h"
61 #include "RenderPart.h"
62 #include "RenderScrollbar.h"
63 #include "RenderScrollbarPart.h"
64 #include "RenderTheme.h"
65 #include "RenderView.h"
66 #include "ScrollAnimator.h"
67 #include "ScrollingCoordinator.h"
68 #include "Settings.h"
69 #include "StyleResolver.h"
70 #include "TextResourceDecoder.h"
71 #include "TextStream.h"
72
73 #include <wtf/CurrentTime.h>
74 #include <wtf/TemporaryChange.h>
75 #include <wtf/UnusedParam.h>
76
77 #if USE(ACCELERATED_COMPOSITING)
78 #include "RenderLayerCompositor.h"
79 #include "TiledBacking.h"
80 #endif
81
82 #if ENABLE(SVG)
83 #include "RenderSVGRoot.h"
84 #include "SVGDocument.h"
85 #include "SVGSVGElement.h"
86 #endif
87
88 #if USE(TILED_BACKING_STORE)
89 #include "TiledBackingStore.h"
90 #endif
91
92 #if ENABLE(TEXT_AUTOSIZING)
93 #include "TextAutosizer.h"
94 #endif
95
96 namespace WebCore {
97
98 using namespace HTMLNames;
99
100 double FrameView::sCurrentPaintTimeStamp = 0.0;
101
102
103 // REPAINT_THROTTLING now chooses default values for throttling parameters.
104 // Should be removed when applications start using runtime configuration.
105 #if ENABLE(REPAINT_THROTTLING)
106 // Normal delay
107 double FrameView::s_normalDeferredRepaintDelay = 0.016;
108 // Negative value would mean that first few repaints happen without a delay
109 double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
110 // The delay grows on each repaint to this maximum value
111 double FrameView::s_maxDeferredRepaintDelayDuringLoading = 2.5;
112 // On each repaint the delay increses by this amount
113 double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0.5;
114 #else
115 // FIXME: Repaint throttling could be good to have on all platform.
116 // The balance between CPU use and repaint frequency will need some tuning for desktop.
117 // More hooks may be needed to reset the delay on things like GIF and CSS animations.
118 double FrameView::s_normalDeferredRepaintDelay = 0;
119 double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
120 double FrameView::s_maxDeferredRepaintDelayDuringLoading = 0;
121 double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0;
122 #endif
123
124 // The maximum number of updateWidgets iterations that should be done before returning.
125 static const unsigned maxUpdateWidgetsIterations = 2;
126
127 static inline RenderView* rootRenderer(const FrameView* view)
128 {
129     return view->frame() ? view->frame()->contentRenderer() : 0;
130 }
131
132 static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
133 {
134     RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
135     if (didFullRepaint) {
136         flags &= ~RenderLayer::CheckForRepaint;
137         flags |= RenderLayer::NeedsFullRepaintInBacking;
138     }
139     if (isRelayoutingSubtree && layer->isPaginated())
140         flags |= RenderLayer::UpdatePagination;
141     return flags;
142 }
143
144 Pagination::Mode paginationModeForRenderStyle(RenderStyle* style)
145 {
146     EOverflow overflow = style->overflowY();
147     if (overflow != OPAGEDX && overflow != OPAGEDY)
148         return Pagination::Unpaginated;
149
150     bool isHorizontalWritingMode = style->isHorizontalWritingMode();
151     TextDirection textDirection = style->direction();
152     WritingMode writingMode = style->writingMode();
153
154     // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
155     // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
156     // is vertical, then the direction of the verticality dictates the choice.
157     if (overflow == OPAGEDX) {
158         if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
159             return Pagination::LeftToRightPaginated;
160         return Pagination::RightToLeftPaginated;
161     }
162
163     // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
164     // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
165     // is vertical, then we use TextDirection to choose between those options. 
166     if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
167         return Pagination::TopToBottomPaginated;
168     return Pagination::BottomToTopPaginated;
169 }
170
171 FrameView::FrameView(Frame* frame)
172     : m_frame(frame)
173     , m_canHaveScrollbars(true)
174     , m_slowRepaintObjectCount(0)
175     , m_layoutTimer(this, &FrameView::layoutTimerFired)
176     , m_layoutRoot(0)
177     , m_inSynchronousPostLayout(false)
178     , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
179     , m_isTransparent(false)
180     , m_baseBackgroundColor(Color::white)
181     , m_mediaType("screen")
182     , m_actionScheduler(adoptPtr(new FrameActionScheduler))
183     , m_overflowStatusDirty(true)
184     , m_viewportRenderer(0)
185     , m_wasScrolledByUser(false)
186     , m_inProgrammaticScroll(false)
187     , m_safeToPropagateScrollToParent(true)
188     , m_deferredRepaintTimer(this, &FrameView::deferredRepaintTimerFired)
189     , m_disableRepaints(0)
190     , m_isTrackingRepaints(false)
191     , m_shouldUpdateWhileOffscreen(true)
192     , m_deferSetNeedsLayouts(0)
193     , m_setNeedsLayoutWasDeferred(false)
194     , m_scrollCorner(0)
195     , m_shouldAutoSize(false)
196     , m_inAutoSize(false)
197     , m_didRunAutosize(false)
198 #if ENABLE(CSS_FILTERS)
199     , m_hasSoftwareFilters(false)
200 #endif
201 {
202     init();
203
204     // FIXME: Can m_frame ever be null here?
205     if (!m_frame)
206         return;
207
208     Page* page = m_frame->page();
209     if (!page)
210         return;
211
212     if (m_frame == page->mainFrame()) {
213         ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
214         ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
215     }
216 }
217
218 PassRefPtr<FrameView> FrameView::create(Frame* frame)
219 {
220     RefPtr<FrameView> view = adoptRef(new FrameView(frame));
221     view->show();
222     return view.release();
223 }
224
225 PassRefPtr<FrameView> FrameView::create(Frame* frame, const IntSize& initialSize)
226 {
227     RefPtr<FrameView> view = adoptRef(new FrameView(frame));
228     view->Widget::setFrameRect(IntRect(view->location(), initialSize));
229     view->show();
230     return view.release();
231 }
232
233 FrameView::~FrameView()
234 {
235     if (m_postLayoutTasksTimer.isActive()) {
236         m_postLayoutTasksTimer.stop();
237         m_actionScheduler->clear();
238     }
239     
240     removeFromAXObjectCache();
241     resetScrollbars();
242
243     // Custom scrollbars should already be destroyed at this point
244     ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
245     ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
246
247     setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
248     setHasVerticalScrollbar(false);
249     
250     ASSERT(!m_scrollCorner);
251     ASSERT(m_actionScheduler->isEmpty());
252
253     if (m_frame) {
254         ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
255         RenderPart* renderer = m_frame->ownerRenderer();
256         if (renderer && renderer->widget() == this)
257             renderer->setWidget(0);
258     }
259 }
260
261 void FrameView::reset()
262 {
263     m_cannotBlitToWindow = false;
264     m_isOverlapped = false;
265     m_contentIsOpaque = false;
266     m_borderX = 30;
267     m_borderY = 30;
268     m_layoutTimer.stop();
269     m_layoutRoot = 0;
270     m_delayedLayout = false;
271     m_doFullRepaint = true;
272     m_layoutSchedulingEnabled = true;
273     m_inLayout = false;
274     m_doingPreLayoutStyleUpdate = false;
275     m_inSynchronousPostLayout = false;
276     m_layoutCount = 0;
277     m_nestedLayoutCount = 0;
278     m_postLayoutTasksTimer.stop();
279     m_firstLayout = true;
280     m_firstLayoutCallbackPending = false;
281     m_wasScrolledByUser = false;
282     m_safeToPropagateScrollToParent = true;
283     m_lastViewportSize = IntSize();
284     m_lastZoomFactor = 1.0f;
285     m_deferringRepaints = 0;
286     m_repaintCount = 0;
287     m_repaintRects.clear();
288     m_deferredRepaintDelay = s_initialDeferredRepaintDelayDuringLoading;
289     m_deferredRepaintTimer.stop();
290     m_isTrackingRepaints = false;
291     m_trackedRepaintRects.clear();
292     m_lastPaintTime = 0;
293     m_paintBehavior = PaintBehaviorNormal;
294     m_isPainting = false;
295     m_visuallyNonEmptyCharacterCount = 0;
296     m_visuallyNonEmptyPixelCount = 0;
297     m_isVisuallyNonEmpty = false;
298     m_firstVisuallyNonEmptyLayoutCallbackPending = true;
299     m_maintainScrollPositionAnchor = 0;
300     m_disableRepaints = 0;
301 }
302
303 void FrameView::removeFromAXObjectCache()
304 {
305     if (AXObjectCache::accessibilityEnabled() && axObjectCache())
306         axObjectCache()->remove(this);
307 }
308
309 bool FrameView::isFrameView() const
310
311     return true; 
312 }
313
314 void FrameView::clearFrame()
315 {
316     m_frame = 0;
317 }
318
319 void FrameView::resetScrollbars()
320 {
321     // Reset the document's scrollbars back to our defaults before we yield the floor.
322     m_firstLayout = true;
323     setScrollbarsSuppressed(true);
324     if (m_canHaveScrollbars)
325         setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
326     else
327         setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
328     setScrollbarsSuppressed(false);
329 }
330
331 void FrameView::resetScrollbarsAndClearContentsSize()
332 {
333     resetScrollbars();
334
335     setScrollbarsSuppressed(true);
336     setContentsSize(IntSize());
337     setScrollbarsSuppressed(false);
338 }
339
340 void FrameView::init()
341 {
342     reset();
343
344     m_margins = LayoutSize(-1, -1); // undefined
345     m_size = LayoutSize();
346
347     // Propagate the marginwidth/height and scrolling modes to the view.
348     Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
349     if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
350         HTMLFrameElementBase* frameElt = static_cast<HTMLFrameElementBase*>(ownerElement);
351         if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
352             setCanHaveScrollbars(false);
353         LayoutUnit marginWidth = frameElt->marginWidth();
354         LayoutUnit marginHeight = frameElt->marginHeight();
355         if (marginWidth != -1)
356             setMarginWidth(marginWidth);
357         if (marginHeight != -1)
358             setMarginHeight(marginHeight);
359     }
360 }
361     
362 void FrameView::prepareForDetach()
363 {
364     detachCustomScrollbars();
365     // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
366     // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
367     removeFromAXObjectCache();
368 }
369
370 void FrameView::detachCustomScrollbars()
371 {
372     Scrollbar* horizontalBar = horizontalScrollbar();
373     if (horizontalBar && horizontalBar->isCustomScrollbar())
374         setHasHorizontalScrollbar(false);
375
376     Scrollbar* verticalBar = verticalScrollbar();
377     if (verticalBar && verticalBar->isCustomScrollbar())
378         setHasVerticalScrollbar(false);
379
380     if (m_scrollCorner) {
381         m_scrollCorner->destroy();
382         m_scrollCorner = 0;
383     }
384 }
385
386 void FrameView::recalculateScrollbarOverlayStyle()
387 {
388     ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
389     ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
390
391     Color backgroundColor = documentBackgroundColor();
392     if (backgroundColor.isValid()) {
393         // Reduce the background color from RGB to a lightness value
394         // and determine which scrollbar style to use based on a lightness
395         // heuristic.
396         double hue, saturation, lightness;
397         backgroundColor.getHSL(hue, saturation, lightness);
398         if (lightness <= .5)
399             overlayStyle = ScrollbarOverlayStyleLight;
400     }
401
402     if (oldOverlayStyle != overlayStyle)
403         setScrollbarOverlayStyle(overlayStyle);
404 }
405
406 void FrameView::clear()
407 {
408     setCanBlitOnScroll(true);
409     
410     reset();
411
412     if (m_frame) {
413         if (RenderPart* renderer = m_frame->ownerRenderer())
414             renderer->viewCleared();
415     }
416
417     setScrollbarsSuppressed(true);
418 }
419
420 bool FrameView::didFirstLayout() const
421 {
422     return !m_firstLayout;
423 }
424
425 void FrameView::invalidateRect(const IntRect& rect)
426 {
427     if (!parent()) {
428         if (hostWindow())
429             hostWindow()->invalidateContentsAndRootView(rect, false /*immediate*/);
430         return;
431     }
432
433     if (!m_frame)
434         return;
435
436     RenderPart* renderer = m_frame->ownerRenderer();
437     if (!renderer)
438         return;
439
440     IntRect repaintRect = rect;
441     repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
442                      renderer->borderTop() + renderer->paddingTop());
443     renderer->repaintRectangle(repaintRect);
444 }
445
446 void FrameView::setFrameRect(const IntRect& newRect)
447 {
448     IntRect oldRect = frameRect();
449     if (newRect == oldRect)
450         return;
451
452     ScrollView::setFrameRect(newRect);
453
454     updateScrollableAreaSet();
455
456 #if USE(ACCELERATED_COMPOSITING)
457     if (RenderView* root = rootRenderer(this)) {
458         if (root->usesCompositing())
459             root->compositor()->frameViewDidChangeSize();
460     }
461 #endif
462 }
463
464 #if ENABLE(REQUEST_ANIMATION_FRAME)
465 bool FrameView::scheduleAnimation()
466 {
467     if (hostWindow()) {
468         hostWindow()->scheduleAnimation();
469         return true;
470     }
471     return false;
472 }
473 #endif
474
475 void FrameView::setMarginWidth(LayoutUnit w)
476 {
477     // make it update the rendering area when set
478     m_margins.setWidth(w);
479 }
480
481 void FrameView::setMarginHeight(LayoutUnit h)
482 {
483     // make it update the rendering area when set
484     m_margins.setHeight(h);
485 }
486
487 bool FrameView::avoidScrollbarCreation() const
488 {
489     ASSERT(m_frame);
490
491     // with frame flattening no subframe can have scrollbars
492     // but we also cannot turn scrollbars off as we determine
493     // our flattening policy using that.
494
495     if (!m_frame->ownerElement())
496         return false;
497
498     if (!m_frame->settings() || m_frame->settings()->frameFlatteningEnabled())
499         return true;
500
501     return false;
502 }
503
504 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
505 {
506     m_canHaveScrollbars = canHaveScrollbars;
507     ScrollView::setCanHaveScrollbars(canHaveScrollbars);
508 }
509
510 void FrameView::updateCanHaveScrollbars()
511 {
512     ScrollbarMode hMode;
513     ScrollbarMode vMode;
514     scrollbarModes(hMode, vMode);
515     if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
516         setCanHaveScrollbars(false);
517     else
518         setCanHaveScrollbars(true);
519 }
520
521 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
522 {
523     if (Settings* settings = m_frame->settings()) {
524         if (!settings->allowCustomScrollbarInMainFrame() && m_frame->page() && m_frame->page()->mainFrame() == m_frame)
525             return ScrollView::createScrollbar(orientation);
526     }
527
528     // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
529     Document* doc = m_frame->document();
530
531     // Try the <body> element first as a scrollbar source.
532     Element* body = doc ? doc->body() : 0;
533     if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR))
534         return RenderScrollbar::createCustomScrollbar(this, orientation, body);
535     
536     // If the <body> didn't have a custom style, then the root element might.
537     Element* docElement = doc ? doc->documentElement() : 0;
538     if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR))
539         return RenderScrollbar::createCustomScrollbar(this, orientation, docElement);
540         
541     // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
542     RenderPart* frameRenderer = m_frame->ownerRenderer();
543     if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR))
544         return RenderScrollbar::createCustomScrollbar(this, orientation, 0, m_frame.get());
545     
546     // Nobody set a custom style, so we just use a native scrollbar.
547     return ScrollView::createScrollbar(orientation);
548 }
549
550 void FrameView::setContentsSize(const IntSize& size)
551 {
552     if (size == contentsSize())
553         return;
554
555     m_deferSetNeedsLayouts++;
556
557     ScrollView::setContentsSize(size);
558     ScrollView::contentsResized();
559     
560     Page* page = frame() ? frame()->page() : 0;
561     if (!page)
562         return;
563
564     updateScrollableAreaSet();
565
566     page->chrome()->contentsSizeChanged(frame(), size); //notify only
567
568     m_deferSetNeedsLayouts--;
569     
570     if (!m_deferSetNeedsLayouts)
571         m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
572 }
573
574 void FrameView::adjustViewSize()
575 {
576     RenderView* root = rootRenderer(this);
577     if (!root)
578         return;
579
580     ASSERT(m_frame->view() == this);
581
582     const IntRect rect = root->documentRect();
583     const IntSize& size = rect.size();
584     ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !m_frame->document()->printing(), size == contentsSize());
585     
586     setContentsSize(size);
587 }
588
589 void FrameView::applyOverflowToViewport(RenderObject* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
590 {
591     // Handle the overflow:hidden/scroll case for the body/html elements.  WinIE treats
592     // overflow:hidden and overflow:scroll on <body> as applying to the document's
593     // scrollbars.  The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
594     // use the root element.
595
596     // To combat the inability to scroll on a page with overflow:hidden on the root when scaled, disregard hidden when
597     // there is a frameScaleFactor that is greater than one on the main frame.
598
599     bool overrideHidden = m_frame->page() && m_frame->page()->mainFrame() == m_frame && m_frame->frameScaleFactor() > 1;
600
601     EOverflow overflowX = o->style()->overflowX();
602     EOverflow overflowY = o->style()->overflowY();
603
604 #if ENABLE(SVG)
605     if (o->isSVGRoot()) {
606         // overflow is ignored in stand-alone SVG documents.
607         if (!toRenderSVGRoot(o)->isEmbeddedThroughFrameContainingSVGDocument())
608             return;
609         overflowX = OHIDDEN;
610         overflowY = OHIDDEN;
611     }
612 #endif
613
614     switch (overflowX) {
615         case OHIDDEN:
616             if (overrideHidden)
617                 hMode = ScrollbarAuto;
618             else
619                 hMode = ScrollbarAlwaysOff;
620             break;
621         case OSCROLL:
622             hMode = ScrollbarAlwaysOn;
623             break;
624         case OAUTO:
625             hMode = ScrollbarAuto;
626             break;
627         default:
628             // Don't set it at all.
629             ;
630     }
631     
632      switch (overflowY) {
633         case OHIDDEN:
634             if (overrideHidden)
635                 vMode = ScrollbarAuto;
636             else
637                 vMode = ScrollbarAlwaysOff;
638             break;
639         case OSCROLL:
640             vMode = ScrollbarAlwaysOn;
641             break;
642         case OAUTO:
643             vMode = ScrollbarAuto;
644             break;
645         default:
646             // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
647             ;
648     }
649
650     m_viewportRenderer = o;
651 }
652
653 void FrameView::applyPaginationToViewport()
654 {
655     Document* document = m_frame->document();
656     Node* documentElement = document->documentElement();
657     RenderObject* documentRenderer = documentElement ? documentElement->renderer() : 0;
658     RenderObject* documentOrBodyRenderer = documentRenderer;
659     Node* body = document->body();
660     if (body && body->renderer()) {
661         if (body->hasTagName(bodyTag))
662             documentOrBodyRenderer = documentRenderer->style()->overflowX() == OVISIBLE && documentElement->hasTagName(htmlTag) ? body->renderer() : documentRenderer;
663     }
664
665     Pagination pagination;
666
667     if (!documentOrBodyRenderer) {
668         setPagination(pagination);
669         return;
670     }
671
672     EOverflow overflowY = documentOrBodyRenderer->style()->overflowY();
673     if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
674         pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
675         pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style()->columnGap());
676     }
677
678     setPagination(pagination);
679 }
680
681 void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
682 {
683     m_viewportRenderer = 0;
684
685     const HTMLFrameOwnerElement* owner = m_frame->ownerElement();
686     if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
687         hMode = ScrollbarAlwaysOff;
688         vMode = ScrollbarAlwaysOff;
689         return;
690     }  
691     
692     if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
693         hMode = ScrollbarAuto;
694         // Seamless documents begin with heights of 0; we special case that here
695         // to correctly render documents that don't need scrollbars.
696         IntSize fullVisibleSize = visibleContentRect(true /*includeScrollbars*/).size();
697         bool isSeamlessDocument = frame() && frame()->document() && frame()->document()->shouldDisplaySeamlesslyWithParent();
698         vMode = (isSeamlessDocument && !fullVisibleSize.height()) ? ScrollbarAlwaysOff : ScrollbarAuto;
699     } else {
700         hMode = ScrollbarAlwaysOff;
701         vMode = ScrollbarAlwaysOff;
702     }
703     
704     if (!m_layoutRoot) {
705         Document* document = m_frame->document();
706         Node* documentElement = document->documentElement();
707         RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0;
708         Node* body = document->body();
709         if (body && body->renderer()) {
710             if (body->hasTagName(framesetTag) && m_frame->settings() && !m_frame->settings()->frameFlatteningEnabled()) {
711                 vMode = ScrollbarAlwaysOff;
712                 hMode = ScrollbarAlwaysOff;
713             } else if (body->hasTagName(bodyTag)) {
714                 // It's sufficient to just check the X overflow,
715                 // since it's illegal to have visible in only one direction.
716                 RenderObject* o = rootRenderer->style()->overflowX() == OVISIBLE && document->documentElement()->hasTagName(htmlTag) ? body->renderer() : rootRenderer;
717                 applyOverflowToViewport(o, hMode, vMode);
718             }
719         } else if (rootRenderer)
720             applyOverflowToViewport(rootRenderer, hMode, vMode);
721     }    
722 }
723
724 #if USE(ACCELERATED_COMPOSITING)
725 void FrameView::updateCompositingLayersAfterStyleChange()
726 {
727     RenderView* root = rootRenderer(this);
728     if (!root)
729         return;
730
731     // If we expect to update compositing after an incipient layout, don't do so here.
732     if (m_doingPreLayoutStyleUpdate || layoutPending() || root->needsLayout())
733         return;
734
735     // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
736     root->compositor()->cacheAcceleratedCompositingFlags();
737     root->compositor()->updateCompositingLayers(CompositingUpdateAfterStyleChange);
738 }
739
740 void FrameView::updateCompositingLayersAfterLayout()
741 {
742     RenderView* root = rootRenderer(this);
743     if (!root)
744         return;
745
746     // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
747     root->compositor()->cacheAcceleratedCompositingFlags();
748     root->compositor()->updateCompositingLayers(CompositingUpdateAfterLayout);
749 }
750
751 void FrameView::clearBackingStores()
752 {
753     RenderView* root = rootRenderer(this);
754     if (!root)
755         return;
756
757     RenderLayerCompositor* compositor = root->compositor();
758     ASSERT(compositor->inCompositingMode());
759     compositor->enableCompositingMode(false);
760     compositor->clearBackingForAllLayers();
761 }
762
763 void FrameView::restoreBackingStores()
764 {
765     RenderView* root = rootRenderer(this);
766     if (!root)
767         return;
768
769     RenderLayerCompositor* compositor = root->compositor();
770     compositor->enableCompositingMode(true);
771     compositor->updateCompositingLayers(CompositingUpdateAfterLayout);
772 }
773
774 bool FrameView::usesCompositedScrolling() const
775 {
776     if (m_frame->settings() && m_frame->settings()->compositedScrollingForFramesEnabled()) {
777         RenderView* root = rootRenderer(this);
778         return root && root->compositor()->inForcedCompositingMode();
779     }
780     return false;
781 }
782
783 GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
784 {
785     RenderView* root = rootRenderer(this);
786     if (!root)
787         return 0;
788     return root->compositor()->layerForHorizontalScrollbar();
789 }
790
791 GraphicsLayer* FrameView::layerForVerticalScrollbar() const
792 {
793     RenderView* root = rootRenderer(this);
794     if (!root)
795         return 0;
796     return root->compositor()->layerForVerticalScrollbar();
797 }
798
799 GraphicsLayer* FrameView::layerForScrollCorner() const
800 {
801     RenderView* root = rootRenderer(this);
802     if (!root)
803         return 0;
804     return root->compositor()->layerForScrollCorner();
805 }
806
807 TiledBacking* FrameView::tiledBacking()
808 {
809     RenderView* root = rootRenderer(this);
810     if (!root)
811         return 0;
812
813     RenderLayerBacking* backing = root->layer()->backing();
814     if (!backing)
815         return 0;
816
817     return backing->graphicsLayer()->tiledBacking();
818 }
819
820 uint64_t FrameView::scrollLayerID() const
821 {
822     RenderView* root = rootRenderer(this);
823     if (!root)
824         return 0;
825
826     RenderLayerBacking* backing = root->layer()->backing();
827     if (!backing)
828         return 0;
829
830     return backing->scrollLayerID();
831 }
832
833 #if ENABLE(RUBBER_BANDING)
834 GraphicsLayer* FrameView::layerForOverhangAreas() const
835 {
836     RenderView* root = rootRenderer(this);
837     if (!root)
838         return 0;
839     return root->compositor()->layerForOverhangAreas();
840 }
841 #endif
842
843 bool FrameView::flushCompositingStateForThisFrame(Frame* rootFrameForFlush)
844 {
845     RenderView* root = rootRenderer(this);
846     if (!root)
847         return true; // We don't want to keep trying to update layers if we have no renderer.
848
849     ASSERT(m_frame->view() == this);
850
851     // If we sync compositing layers when a layout is pending, we may cause painting of compositing
852     // layer content to occur before layout has happened, which will cause paintContents() to bail.
853     if (needsLayout())
854         return false;
855
856     // If we sync compositing layers and allow the repaint to be deferred, there is time for a
857     // visible flash to occur. Instead, stop the deferred repaint timer and repaint immediately.
858     flushDeferredRepaints();
859
860     root->compositor()->flushPendingLayerChanges(rootFrameForFlush == m_frame);
861
862     return true;
863 }
864
865 void FrameView::setNeedsOneShotDrawingSynchronization()
866 {
867     Page* page = frame() ? frame()->page() : 0;
868     if (page)
869         page->chrome()->client()->setNeedsOneShotDrawingSynchronization();
870 }
871
872 #endif // USE(ACCELERATED_COMPOSITING)
873
874 bool FrameView::hasCompositedContent() const
875 {
876 #if USE(ACCELERATED_COMPOSITING)
877     if (RenderView* root = rootRenderer(this))
878         return root->compositor()->inCompositingMode();
879 #endif
880     return false;
881 }
882
883 bool FrameView::hasCompositedContentIncludingDescendants() const
884 {
885 #if USE(ACCELERATED_COMPOSITING)
886     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
887         RenderView* renderView = frame->contentRenderer();
888         RenderLayerCompositor* compositor = renderView ? renderView->compositor() : 0;
889         if (compositor) {
890             if (compositor->inCompositingMode())
891                 return true;
892
893             if (!RenderLayerCompositor::allowsIndependentlyCompositedFrames(this))
894                 break;
895         }
896     }
897 #endif
898     return false;
899 }
900
901 bool FrameView::hasCompositingAncestor() const
902 {
903 #if USE(ACCELERATED_COMPOSITING)
904     for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent()) {
905         if (FrameView* view = frame->view()) {
906             if (view->hasCompositedContent())
907                 return true;
908         }
909     }
910 #endif
911     return false;
912 }
913
914 // Sometimes (for plug-ins) we need to eagerly go into compositing mode.
915 void FrameView::enterCompositingMode()
916 {
917 #if USE(ACCELERATED_COMPOSITING)
918     if (RenderView* root = rootRenderer(this)) {
919         root->compositor()->enableCompositingMode();
920         if (!needsLayout())
921             root->compositor()->scheduleCompositingLayerUpdate();
922     }
923 #endif
924 }
925
926 bool FrameView::isEnclosedInCompositingLayer() const
927 {
928 #if USE(ACCELERATED_COMPOSITING)
929     RenderObject* frameOwnerRenderer = m_frame->ownerRenderer();
930     if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
931         return true;
932
933     if (FrameView* parentView = parentFrameView())
934         return parentView->isEnclosedInCompositingLayer();
935 #endif
936     return false;
937 }
938     
939 bool FrameView::flushCompositingStateIncludingSubframes()
940 {
941 #if USE(ACCELERATED_COMPOSITING)
942     bool allFramesFlushed = flushCompositingStateForThisFrame(m_frame.get());
943     
944     for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame.get())) {
945         bool flushed = child->view()->flushCompositingStateForThisFrame(m_frame.get());
946         allFramesFlushed &= flushed;
947     }
948     return allFramesFlushed;
949 #else // USE(ACCELERATED_COMPOSITING)
950     return true;
951 #endif
952 }
953
954 bool FrameView::isSoftwareRenderable() const
955 {
956 #if USE(ACCELERATED_COMPOSITING)
957     RenderView* root = rootRenderer(this);
958     if (!root)
959         return true;
960
961     return !root->compositor()->has3DContent();
962 #else
963     return true;
964 #endif
965 }
966
967 void FrameView::didMoveOnscreen()
968 {
969     if (RenderView* root = rootRenderer(this))
970         root->didMoveOnscreen();
971     contentAreaDidShow();
972 }
973
974 void FrameView::willMoveOffscreen()
975 {
976     if (RenderView* root = rootRenderer(this))
977         root->willMoveOffscreen();
978     contentAreaDidHide();
979 }
980
981 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
982 {
983     return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
984 }
985
986 static inline void collectFrameViewChildren(FrameView* frameView, Vector<RefPtr<FrameView> >& frameViews)
987 {
988     const HashSet<RefPtr<Widget> >* viewChildren = frameView->children();
989     ASSERT(viewChildren);
990
991     const HashSet<RefPtr<Widget> >::iterator end = viewChildren->end();
992     for (HashSet<RefPtr<Widget> >::iterator current = viewChildren->begin(); current != end; ++current) {
993         Widget* widget = (*current).get();
994         if (widget->isFrameView())
995             frameViews.append(static_cast<FrameView*>(widget));
996     }
997 }
998
999 inline void FrameView::forceLayoutParentViewIfNeeded()
1000 {
1001 #if ENABLE(SVG)
1002     RenderPart* ownerRenderer = m_frame->ownerRenderer();
1003     if (!ownerRenderer || !ownerRenderer->frame())
1004         return;
1005
1006     RenderBox* contentBox = embeddedContentBox();
1007     if (!contentBox)
1008         return;
1009
1010     RenderSVGRoot* svgRoot = toRenderSVGRoot(contentBox);
1011     if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
1012         return;
1013
1014     // If the embedded SVG document appears the first time, the ownerRenderer has already finished
1015     // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
1016     // embeddedContentBox() returns 0, as long as the embedded document isn't loaded yet. Before
1017     // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
1018     // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
1019     // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
1020     // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
1021     RefPtr<FrameView> frameView = ownerRenderer->frame()->view();
1022
1023     // Mark the owner renderer as needing layout.
1024     ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
1025
1026     // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
1027     ASSERT(frameView);
1028     frameView->layout();
1029 #endif
1030 }
1031
1032 void FrameView::layout(bool allowSubtree)
1033 {
1034     if (m_inLayout)
1035         return;
1036
1037     // Protect the view from being deleted during layout (in recalcStyle)
1038     RefPtr<FrameView> protector(this);
1039
1040     // Every scroll that happens during layout is programmatic.
1041     TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1042
1043     bool inChildFrameLayoutWithFrameFlattening = isInChildFrameWithFrameFlattening();
1044
1045     if (inChildFrameLayoutWithFrameFlattening) {
1046         if (doLayoutWithFrameFlattening(allowSubtree))
1047             return;
1048     }
1049
1050     m_layoutTimer.stop();
1051     m_delayedLayout = false;
1052     m_setNeedsLayoutWasDeferred = false;
1053
1054     if (!m_frame) {
1055         // FIXME: Do we need to set m_size.width here?
1056         // FIXME: Should we set m_size.height here too?
1057         m_size.setWidth(layoutWidth());
1058         return;
1059     }
1060     
1061     // we shouldn't enter layout() while painting
1062     ASSERT(!isPainting());
1063     if (isPainting())
1064         return;
1065
1066     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(m_frame.get());
1067
1068     if (!allowSubtree && m_layoutRoot) {
1069         m_layoutRoot->markContainingBlocksForLayout(false);
1070         m_layoutRoot = 0;
1071     }
1072
1073     ASSERT(m_frame->view() == this);
1074
1075     Document* document = m_frame->document();
1076     ASSERT(!document->inPageCache());
1077     bool subtree;
1078     RenderObject* root;
1079
1080     {
1081         TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1082
1083         if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !inChildFrameLayoutWithFrameFlattening) {
1084             // This is a new top-level layout. If there are any remaining tasks from the previous
1085             // layout, finish them now.
1086             m_inSynchronousPostLayout = true;
1087             performPostLayoutTasks();
1088             m_inSynchronousPostLayout = false;
1089         }
1090
1091         // Viewport-dependent media queries may cause us to need completely different style information.
1092         // Check that here.
1093         if (document->styleResolver()->affectedByViewportChange()) {
1094             document->styleResolverChanged(RecalcStyleImmediately);
1095             InspectorInstrumentation::mediaQueryResultChanged(document);
1096         } else
1097             document->evaluateMediaQueryList();
1098
1099         // If there is any pagination to apply, it will affect the RenderView's style, so we should
1100         // take care of that now.
1101         applyPaginationToViewport();
1102
1103         // Always ensure our style info is up-to-date. This can happen in situations where
1104         // the layout beats any sort of style recalc update that needs to occur.
1105         TemporaryChange<bool> changeDoingPreLayoutStyleUpdate(m_doingPreLayoutStyleUpdate, true);
1106         document->updateStyleIfNeeded();
1107
1108         subtree = m_layoutRoot;
1109
1110         // If there is only one ref to this view left, then its going to be destroyed as soon as we exit, 
1111         // so there's no point to continuing to layout
1112         if (protector->hasOneRef())
1113             return;
1114
1115         root = subtree ? m_layoutRoot : document->renderer();
1116         if (!root) {
1117             // FIXME: Do we need to set m_size here?
1118             return;
1119         }
1120     } // Reset m_layoutSchedulingEnabled to its previous value.
1121     // The only reason the scoping was closed here is allow fontCachePurgePreventer
1122     // to outlive the change and reset of m_layoutSchedulingEnabled.
1123
1124     FontCachePurgePreventer fontCachePurgePreventer;
1125     RenderLayer* layer;
1126     {
1127         TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
1128
1129         m_nestedLayoutCount++;
1130
1131         if (!m_layoutRoot) {
1132             Document* document = m_frame->document();
1133             Node* body = document->body();
1134             if (body && body->renderer()) {
1135                 if (body->hasTagName(framesetTag) && m_frame->settings() && !m_frame->settings()->frameFlatteningEnabled()) {
1136                     body->renderer()->setChildNeedsLayout(true);
1137                 } else if (body->hasTagName(bodyTag)) {
1138                     if (!m_firstLayout && m_size.height() != layoutHeight() && body->renderer()->enclosingBox()->stretchesToViewport())
1139                         body->renderer()->setChildNeedsLayout(true);
1140                 }
1141             }
1142
1143 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1144             if (m_firstLayout && !m_frame->ownerElement())
1145                 printf("Elapsed time before first layout: %d\n", document->elapsedTime());
1146 #endif        
1147         }
1148
1149         autoSizeIfEnabled();
1150
1151         ScrollbarMode hMode;
1152         ScrollbarMode vMode;    
1153         calculateScrollbarModesForLayout(hMode, vMode);
1154
1155         m_doFullRepaint = !subtree && (m_firstLayout || toRenderView(root)->printing());
1156
1157         if (!subtree) {
1158             // Now set our scrollbar state for the layout.
1159             ScrollbarMode currentHMode = horizontalScrollbarMode();
1160             ScrollbarMode currentVMode = verticalScrollbarMode();
1161
1162             if (m_firstLayout || (hMode != currentHMode || vMode != currentVMode)) {
1163                 if (m_firstLayout) {
1164                     setScrollbarsSuppressed(true);
1165
1166                     m_firstLayout = false;
1167                     m_firstLayoutCallbackPending = true;
1168                     if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
1169                         m_lastViewportSize = fixedLayoutSize();
1170                     else
1171                         m_lastViewportSize = visibleContentRect(true /*includeScrollbars*/).size();
1172                     m_lastZoomFactor = root->style()->zoom();
1173
1174                     // Set the initial vMode to AlwaysOn if we're auto.
1175                     if (vMode == ScrollbarAuto)
1176                         setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
1177                     // Set the initial hMode to AlwaysOff if we're auto.
1178                     if (hMode == ScrollbarAuto)
1179                         setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
1180
1181                     setScrollbarModes(hMode, vMode);
1182                     setScrollbarsSuppressed(false, true);
1183                 } else
1184                     setScrollbarModes(hMode, vMode);
1185             }
1186
1187             LayoutSize oldSize = m_size;
1188
1189             m_size = LayoutSize(layoutWidth(), layoutHeight());
1190
1191             if (oldSize != m_size) {
1192                 m_doFullRepaint = true;
1193                 if (!m_firstLayout) {
1194                     RenderBox* rootRenderer = document->documentElement() ? document->documentElement()->renderBox() : 0;
1195                     RenderBox* bodyRenderer = rootRenderer && document->body() ? document->body()->renderBox() : 0;
1196                     if (bodyRenderer && bodyRenderer->stretchesToViewport())
1197                         bodyRenderer->setChildNeedsLayout(true);
1198                     else if (rootRenderer && rootRenderer->stretchesToViewport())
1199                         rootRenderer->setChildNeedsLayout(true);
1200                 }
1201             }
1202         }
1203
1204         layer = root->enclosingLayer();
1205
1206         m_actionScheduler->pause();
1207
1208         {
1209             bool disableLayoutState = false;
1210             if (subtree) {
1211                 RenderView* view = root->view();
1212                 disableLayoutState = view->shouldDisableLayoutStateForSubtree(root);
1213                 view->pushLayoutState(root);
1214             }
1215             LayoutStateDisabler layoutStateDisabler(disableLayoutState ? root->view() : 0);
1216
1217             m_inLayout = true;
1218             beginDeferredRepaints();
1219             forceLayoutParentViewIfNeeded();
1220             root->layout();
1221 #if ENABLE(TEXT_AUTOSIZING)
1222             bool autosized = document->textAutosizer()->processSubtree(root);
1223             if (autosized && root->needsLayout())
1224                 root->layout();
1225 #endif
1226             endDeferredRepaints();
1227             m_inLayout = false;
1228
1229             if (subtree)
1230                 root->view()->popLayoutState(root);
1231         }
1232         m_layoutRoot = 0;
1233     } // Reset m_layoutSchedulingEnabled to its previous value.
1234
1235     bool neededFullRepaint = m_doFullRepaint;
1236
1237     if (!subtree && !toRenderView(root)->printing())
1238         adjustViewSize();
1239
1240     m_doFullRepaint = neededFullRepaint;
1241
1242     // Now update the positions of all layers.
1243     beginDeferredRepaints();
1244     if (m_doFullRepaint)
1245         root->view()->repaint(); // FIXME: This isn't really right, since the RenderView doesn't fully encompass the visibleContentRect(). It just happens
1246                                  // to work out most of the time, since first layouts and printing don't have you scrolled anywhere.
1247
1248     layer->updateLayerPositionsAfterLayout(rootRenderer(this)->layer(), updateLayerPositionFlags(layer, subtree, m_doFullRepaint));
1249
1250     endDeferredRepaints();
1251
1252 #if USE(ACCELERATED_COMPOSITING)
1253     updateCompositingLayersAfterLayout();
1254 #endif
1255     
1256     m_layoutCount++;
1257
1258 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
1259     if (AXObjectCache::accessibilityEnabled())
1260         root->document()->axObjectCache()->postNotification(root, AXObjectCache::AXLayoutComplete, true);
1261 #endif
1262 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
1263     updateAnnotatedRegions();
1264 #endif
1265
1266     ASSERT(!root->needsLayout());
1267
1268     updateCanBlitOnScrollRecursively();
1269
1270     if (document->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
1271         updateOverflowStatus(layoutWidth() < contentsWidth(),
1272                              layoutHeight() < contentsHeight());
1273
1274     if (!m_postLayoutTasksTimer.isActive()) {
1275         if (!m_inSynchronousPostLayout) {
1276             if (inChildFrameLayoutWithFrameFlattening) {
1277                 if (RenderView* root = rootRenderer(this))
1278                     root->updateWidgetPositions();
1279             } else {
1280                 m_inSynchronousPostLayout = true;
1281                 // Calls resumeScheduledEvents()
1282                 performPostLayoutTasks();
1283                 m_inSynchronousPostLayout = false;
1284             }
1285         }
1286         
1287         if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || inChildFrameLayoutWithFrameFlattening)) {
1288             // If we need layout or are already in a synchronous call to postLayoutTasks(), 
1289             // defer widget updates and event dispatch until after we return. postLayoutTasks()
1290             // can make us need to update again, and we can get stuck in a nasty cycle unless
1291             // we call it through the timer here.
1292             m_postLayoutTasksTimer.startOneShot(0);
1293             if (needsLayout()) {
1294                 m_actionScheduler->pause();
1295                 layout();
1296             }
1297         }
1298     } else {
1299         m_actionScheduler->resume();
1300     }
1301
1302     InspectorInstrumentation::didLayout(cookie, root);
1303
1304     m_nestedLayoutCount--;
1305     if (m_nestedLayoutCount)
1306         return;
1307
1308     Page* page = frame() ? frame()->page() : 0;
1309     if (!page)
1310         return;
1311
1312     page->chrome()->client()->layoutUpdated(frame());
1313 }
1314
1315 RenderBox* FrameView::embeddedContentBox() const
1316 {
1317 #if ENABLE(SVG)
1318     RenderView* root = rootRenderer(this);
1319     if (!root)
1320         return 0;
1321
1322     RenderObject* rootChild = root->firstChild();
1323     if (!rootChild || !rootChild->isBox())
1324         return 0;
1325
1326     // Curently only embedded SVG documents participate in the size-negotiation logic.
1327     if (rootChild->isSVGRoot())
1328         return toRenderBox(rootChild);
1329 #endif
1330
1331     return 0;
1332 }
1333
1334 void FrameView::addWidgetToUpdate(RenderEmbeddedObject* object)
1335 {
1336     if (!m_widgetUpdateSet)
1337         m_widgetUpdateSet = adoptPtr(new RenderEmbeddedObjectSet);
1338
1339     // Tell the DOM element that it needs a widget update.
1340     Node* node = object->node();
1341     if (node->hasTagName(objectTag) || node->hasTagName(embedTag)) {
1342         HTMLPlugInImageElement* pluginElement = static_cast<HTMLPlugInImageElement*>(node);
1343         pluginElement->setNeedsWidgetUpdate(true);
1344     }
1345
1346     m_widgetUpdateSet->add(object);
1347 }
1348
1349 void FrameView::removeWidgetToUpdate(RenderEmbeddedObject* object)
1350 {
1351     if (!m_widgetUpdateSet)
1352         return;
1353
1354     m_widgetUpdateSet->remove(object);
1355 }
1356
1357 void FrameView::setMediaType(const String& mediaType)
1358 {
1359     m_mediaType = mediaType;
1360 }
1361
1362 String FrameView::mediaType() const
1363 {
1364     // See if we have an override type.
1365     String overrideType = m_frame->loader()->client()->overrideMediaType();
1366     InspectorInstrumentation::applyEmulatedMedia(m_frame.get(), &overrideType);
1367     if (!overrideType.isNull())
1368         return overrideType;
1369     return m_mediaType;
1370 }
1371
1372 void FrameView::adjustMediaTypeForPrinting(bool printing)
1373 {
1374     if (printing) {
1375         if (m_mediaTypeWhenNotPrinting.isNull())
1376             m_mediaTypeWhenNotPrinting = mediaType();
1377             setMediaType("print");
1378     } else {
1379         if (!m_mediaTypeWhenNotPrinting.isNull())
1380             setMediaType(m_mediaTypeWhenNotPrinting);
1381         m_mediaTypeWhenNotPrinting = String();
1382     }
1383 }
1384
1385 bool FrameView::useSlowRepaints(bool considerOverlap) const
1386 {
1387     bool mustBeSlow = m_slowRepaintObjectCount > 0 || (platformWidget() && hasViewportConstrainedObjects());
1388
1389     // FIXME: WidgetMac.mm makes the assumption that useSlowRepaints ==
1390     // m_contentIsOpaque, so don't take the fast path for composited layers
1391     // if they are a platform widget in order to get painting correctness
1392     // for transparent layers. See the comment in WidgetMac::paint.
1393     if (contentsInCompositedLayer() && !platformWidget())
1394         return mustBeSlow;
1395
1396 #if PLATFORM(CHROMIUM)
1397     // The chromium compositor does not support scrolling a non-composited frame within a composited page through
1398     // the fast scrolling path, so force slow scrolling in that case.
1399     if (m_frame->ownerElement() && !hasCompositedContent() && m_frame->page() && m_frame->page()->mainFrame()->view()->hasCompositedContent())
1400         return true;
1401 #endif
1402
1403     bool isOverlapped = m_isOverlapped && considerOverlap;
1404
1405     if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
1406         return true;
1407
1408     if (FrameView* parentView = parentFrameView())
1409         return parentView->useSlowRepaints(considerOverlap);
1410
1411     return false;
1412 }
1413
1414 bool FrameView::useSlowRepaintsIfNotOverlapped() const
1415 {
1416     return useSlowRepaints(false);
1417 }
1418
1419 void FrameView::updateCanBlitOnScrollRecursively()
1420 {
1421     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
1422         if (FrameView* view = frame->view())
1423             view->setCanBlitOnScroll(!view->useSlowRepaints());
1424     }
1425 }
1426
1427 bool FrameView::contentsInCompositedLayer() const
1428 {
1429 #if USE(ACCELERATED_COMPOSITING)
1430     RenderView* root = rootRenderer(this);
1431     if (root && root->isComposited()) {
1432         GraphicsLayer* layer = root->layer()->backing()->graphicsLayer();
1433         if (layer && layer->drawsContent())
1434             return true;
1435     }
1436 #endif
1437     return false;
1438 }
1439
1440 void FrameView::setCannotBlitToWindow()
1441 {
1442     m_cannotBlitToWindow = true;
1443     updateCanBlitOnScrollRecursively();
1444 }
1445
1446 void FrameView::addSlowRepaintObject()
1447 {
1448     if (!m_slowRepaintObjectCount++) {
1449         updateCanBlitOnScrollRecursively();
1450
1451         if (Page* page = m_frame->page()) {
1452             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1453                 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
1454         }
1455     }
1456 }
1457
1458 void FrameView::removeSlowRepaintObject()
1459 {
1460     ASSERT(m_slowRepaintObjectCount > 0);
1461     m_slowRepaintObjectCount--;
1462     if (!m_slowRepaintObjectCount) {
1463         updateCanBlitOnScrollRecursively();
1464
1465         if (Page* page = m_frame->page()) {
1466             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1467                 scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
1468         }
1469     }
1470 }
1471
1472 void FrameView::addViewportConstrainedObject(RenderObject* object)
1473 {
1474     if (!m_viewportConstrainedObjects)
1475         m_viewportConstrainedObjects = adoptPtr(new ViewportConstrainedObjectSet);
1476
1477     if (!m_viewportConstrainedObjects->contains(object)) {
1478         m_viewportConstrainedObjects->add(object);
1479         if (platformWidget())
1480             updateCanBlitOnScrollRecursively();
1481
1482         if (Page* page = m_frame->page()) {
1483             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1484                 scrollingCoordinator->frameViewFixedObjectsDidChange(this);
1485         }
1486     }
1487 }
1488
1489 void FrameView::removeViewportConstrainedObject(RenderObject* object)
1490 {
1491     if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->contains(object)) {
1492         m_viewportConstrainedObjects->remove(object);
1493         if (Page* page = m_frame->page()) {
1494             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1495                 scrollingCoordinator->frameViewFixedObjectsDidChange(this);
1496         }
1497
1498         // FIXME: In addFixedObject() we only call this if there's a platform widget,
1499         // why isn't the same check being made here?
1500         updateCanBlitOnScrollRecursively();
1501     }
1502 }
1503
1504 LayoutRect FrameView::viewportConstrainedVisibleContentRect() const
1505 {
1506     LayoutRect viewportRect = visibleContentRect();
1507     viewportRect.setLocation(toPoint(scrollOffsetForFixedPosition()));
1508     return viewportRect;
1509 }
1510
1511 IntSize FrameView::scrollOffsetForFixedPosition() const
1512 {
1513     IntRect visibleContentRect = this->visibleContentRect();
1514     IntSize contentsSize = this->contentsSize();
1515     IntPoint scrollPosition = this->scrollPosition();
1516     IntPoint scrollOrigin = this->scrollOrigin();
1517     float frameScaleFactor = m_frame ? m_frame->frameScaleFactor() : 1;
1518     return WebCore::scrollOffsetForFixedPosition(visibleContentRect, contentsSize, scrollPosition, scrollOrigin, frameScaleFactor, fixedElementsLayoutRelativeToFrame());
1519 }
1520
1521 bool FrameView::fixedElementsLayoutRelativeToFrame() const
1522 {
1523     ASSERT(m_frame);
1524     if (!m_frame->settings())
1525         return false;
1526
1527     return m_frame->settings()->fixedElementsLayoutRelativeToFrame();
1528 }
1529
1530 IntPoint FrameView::lastKnownMousePosition() const
1531 {
1532     return m_frame ? m_frame->eventHandler()->lastKnownMousePosition() : IntPoint();
1533 }
1534
1535 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
1536 {
1537     if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
1538         hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1539         return true;
1540     }
1541
1542     const bool isCompositedContentLayer = contentsInCompositedLayer();
1543
1544     // Get the rects of the fixed objects visible in the rectToScroll
1545     Region regionToUpdate;
1546     ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
1547     for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
1548         RenderObject* renderer = *it;
1549         if (!renderer->style()->hasViewportConstrainedPosition())
1550             continue;
1551 #if USE(ACCELERATED_COMPOSITING)
1552         if (renderer->isComposited())
1553             continue;
1554 #endif
1555     
1556         // Fixed items should always have layers.
1557         ASSERT(renderer->hasLayer());
1558         RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
1559         
1560 #if ENABLE(CSS_FILTERS)
1561         if (layer->hasAncestorWithFilterOutsets()) {
1562             // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot 
1563             // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
1564             return false;
1565         }
1566 #endif
1567         IntRect updateRect = pixelSnappedIntRect(layer->repaintRectIncludingNonCompositingDescendants());
1568         updateRect = contentsToRootView(updateRect);
1569         if (!isCompositedContentLayer && clipsRepaints())
1570             updateRect.intersect(rectToScroll);
1571         if (!updateRect.isEmpty())
1572             regionToUpdate.unite(updateRect);
1573     }
1574
1575     // 1) scroll
1576     hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1577
1578     // 2) update the area of fixed objects that has been invalidated
1579     Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
1580     size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
1581     for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
1582         IntRect updateRect = subRectsToUpdate[i];
1583         IntRect scrolledRect = updateRect;
1584         scrolledRect.move(scrollDelta);
1585         updateRect.unite(scrolledRect);
1586 #if USE(ACCELERATED_COMPOSITING)
1587         if (isCompositedContentLayer) {
1588             updateRect = rootViewToContents(updateRect);
1589             RenderView* root = rootRenderer(this);
1590             ASSERT(root);
1591             root->layer()->setBackingNeedsRepaintInRect(updateRect);
1592             continue;
1593         }
1594 #endif
1595         if (clipsRepaints())
1596             updateRect.intersect(rectToScroll);
1597         hostWindow()->invalidateContentsAndRootView(updateRect, false);
1598     }
1599
1600     return true;
1601 }
1602
1603 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
1604 {
1605 #if USE(ACCELERATED_COMPOSITING)
1606     if (contentsInCompositedLayer()) {
1607         RenderView* root = rootRenderer(this);
1608         ASSERT(root);
1609
1610         IntRect updateRect = visibleContentRect();
1611
1612         // Make sure to "apply" the scale factor here since we're converting from frame view
1613         // coordinates to layer backing coordinates.
1614         updateRect.scale(1 / m_frame->frameScaleFactor());
1615
1616         root->layer()->setBackingNeedsRepaintInRect(updateRect);
1617     }
1618     if (RenderPart* frameRenderer = m_frame->ownerRenderer()) {
1619         if (isEnclosedInCompositingLayer()) {
1620             LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(),
1621                             frameRenderer->borderTop() + frameRenderer->paddingTop(),
1622                             visibleWidth(), visibleHeight());
1623             frameRenderer->repaintRectangle(rect);
1624             return;
1625         }
1626     }
1627 #endif
1628
1629     ScrollView::scrollContentsSlowPath(updateRect);
1630 }
1631
1632 // Note that this gets called at painting time.
1633 void FrameView::setIsOverlapped(bool isOverlapped)
1634 {
1635     if (isOverlapped == m_isOverlapped)
1636         return;
1637
1638     m_isOverlapped = isOverlapped;
1639     updateCanBlitOnScrollRecursively();
1640     
1641 #if USE(ACCELERATED_COMPOSITING)
1642     if (hasCompositedContentIncludingDescendants()) {
1643         // Overlap can affect compositing tests, so if it changes, we need to trigger
1644         // a layer update in the parent document.
1645         if (Frame* parentFrame = m_frame->tree()->parent()) {
1646             if (RenderView* parentView = parentFrame->contentRenderer()) {
1647                 RenderLayerCompositor* compositor = parentView->compositor();
1648                 compositor->setCompositingLayersNeedRebuild();
1649                 compositor->scheduleCompositingLayerUpdate();
1650             }
1651         }
1652
1653         if (RenderLayerCompositor::allowsIndependentlyCompositedFrames(this)) {
1654             // We also need to trigger reevaluation for this and all descendant frames,
1655             // since a frame uses compositing if any ancestor is compositing.
1656             for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
1657                 if (RenderView* view = frame->contentRenderer()) {
1658                     RenderLayerCompositor* compositor = view->compositor();
1659                     compositor->setCompositingLayersNeedRebuild();
1660                     compositor->scheduleCompositingLayerUpdate();
1661                 }
1662             }
1663         }
1664     }
1665 #endif
1666 }
1667
1668 bool FrameView::isOverlappedIncludingAncestors() const
1669 {
1670     if (isOverlapped())
1671         return true;
1672
1673     if (FrameView* parentView = parentFrameView()) {
1674         if (parentView->isOverlapped())
1675             return true;
1676     }
1677
1678     return false;
1679 }
1680
1681 void FrameView::setContentIsOpaque(bool contentIsOpaque)
1682 {
1683     if (contentIsOpaque == m_contentIsOpaque)
1684         return;
1685
1686     m_contentIsOpaque = contentIsOpaque;
1687     updateCanBlitOnScrollRecursively();
1688 }
1689
1690 void FrameView::restoreScrollbar()
1691 {
1692     setScrollbarsSuppressed(false);
1693 }
1694
1695 bool FrameView::scrollToFragment(const KURL& url)
1696 {
1697     // If our URL has no ref, then we have no place we need to jump to.
1698     // OTOH If CSS target was set previously, we want to set it to 0, recalc
1699     // and possibly repaint because :target pseudo class may have been
1700     // set (see bug 11321).
1701     if (!url.hasFragmentIdentifier() && !m_frame->document()->cssTarget())
1702         return false;
1703
1704     String fragmentIdentifier = url.fragmentIdentifier();
1705     if (scrollToAnchor(fragmentIdentifier))
1706         return true;
1707
1708     // Try again after decoding the ref, based on the document's encoding.
1709     if (TextResourceDecoder* decoder = m_frame->document()->decoder())
1710         return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, decoder->encoding()));
1711
1712     return false;
1713 }
1714
1715 bool FrameView::scrollToAnchor(const String& name)
1716 {
1717     ASSERT(m_frame->document());
1718
1719     if (!m_frame->document()->haveStylesheetsLoaded()) {
1720         m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
1721         return false;
1722     }
1723
1724     m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
1725
1726     Element* anchorNode = m_frame->document()->findAnchor(name);
1727
1728     // Setting to null will clear the current target.
1729     m_frame->document()->setCSSTarget(anchorNode);
1730
1731 #if ENABLE(SVG)
1732     if (m_frame->document()->isSVGDocument()) {
1733         if (SVGSVGElement* svg = static_cast<SVGDocument*>(m_frame->document())->rootElement()) {
1734             svg->setupInitialView(name, anchorNode);
1735             if (!anchorNode)
1736                 return true;
1737         }
1738     }
1739 #endif
1740   
1741     // Implement the rule that "" and "top" both mean top of page as in other browsers.
1742     if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
1743         return false;
1744
1745     maintainScrollPositionAtAnchor(anchorNode ? static_cast<Node*>(anchorNode) : m_frame->document());
1746     return true;
1747 }
1748
1749 void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
1750 {
1751     m_maintainScrollPositionAnchor = anchorNode;
1752     if (!m_maintainScrollPositionAnchor)
1753         return;
1754
1755     // We need to update the layout before scrolling, otherwise we could
1756     // really mess things up if an anchor scroll comes at a bad moment.
1757     m_frame->document()->updateStyleIfNeeded();
1758     // Only do a layout if changes have occurred that make it necessary.
1759     RenderView* root = rootRenderer(this);
1760     if (root && root->needsLayout())
1761         layout();
1762     else
1763         scrollToAnchor();
1764 }
1765
1766 void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
1767 {
1768     m_frame->document()->updateLayoutIgnorePendingStylesheets();
1769
1770     LayoutRect bounds = element->boundingBox();
1771     int centeringOffsetX = (rect.width() - bounds.width()) / 2;
1772     int centeringOffsetY = (rect.height() - bounds.height()) / 2;
1773     setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
1774 }
1775
1776 void FrameView::setScrollPosition(const IntPoint& scrollPoint)
1777 {
1778     TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
1779     m_maintainScrollPositionAnchor = 0;
1780
1781     IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint);
1782
1783     if (newScrollPosition == scrollPosition())
1784         return;
1785
1786     if (requestScrollPositionUpdate(newScrollPosition))
1787         return;
1788
1789     ScrollView::setScrollPosition(newScrollPosition);
1790 }
1791
1792 void FrameView::delegatesScrollingDidChange()
1793 {
1794 #if USE(ACCELERATED_COMPOSITING)
1795     // When we switch to delgatesScrolling mode, we should destroy the scrolling/clipping layers in RenderLayerCompositor.
1796     if (hasCompositedContent())
1797         clearBackingStores();
1798 #endif
1799 }
1800
1801 void FrameView::setFixedVisibleContentRect(const IntRect& visibleContentRect)
1802 {
1803     bool visibleContentSizeDidChange = false;
1804     if (visibleContentRect.size() != this->fixedVisibleContentRect().size()) {
1805         // When the viewport size changes or the content is scaled, we need to
1806         // reposition the fixed and sticky positioned elements.
1807         setViewportConstrainedObjectsNeedLayout();
1808         visibleContentSizeDidChange = true;
1809     }
1810
1811     IntSize offset = scrollOffset();
1812     ScrollView::setFixedVisibleContentRect(visibleContentRect);
1813     if (offset != scrollOffset()) {
1814         repaintFixedElementsAfterScrolling();
1815         if (m_frame->page()->settings()->acceleratedCompositingForFixedPositionEnabled())
1816             updateFixedElementsAfterScrolling();
1817         scrollAnimator()->setCurrentPosition(scrollPosition());
1818         scrollPositionChanged();
1819     }
1820     if (visibleContentSizeDidChange) {
1821         // Update the scroll-bars to calculate new page-step size.
1822         updateScrollbars(scrollOffset());
1823     }
1824     frame()->loader()->client()->didChangeScrollOffset();
1825 }
1826
1827 void FrameView::setViewportConstrainedObjectsNeedLayout()
1828 {
1829     if (!hasViewportConstrainedObjects())
1830         return;
1831
1832     ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
1833     for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
1834         RenderObject* renderer = *it;
1835         renderer->setNeedsLayout(true);
1836     }
1837 }
1838
1839
1840 void FrameView::scrollPositionChangedViaPlatformWidget()
1841 {
1842     repaintFixedElementsAfterScrolling();
1843     updateFixedElementsAfterScrolling();
1844     scrollPositionChanged();
1845 }
1846
1847 void FrameView::scrollPositionChanged()
1848 {
1849     frame()->eventHandler()->sendScrollEvent();
1850     frame()->eventHandler()->dispatchFakeMouseMoveEventSoon();
1851
1852 #if USE(ACCELERATED_COMPOSITING)
1853     if (RenderView* root = rootRenderer(this)) {
1854         if (root->usesCompositing())
1855             root->compositor()->frameViewDidScroll();
1856     }
1857 #endif
1858 }
1859
1860 void FrameView::repaintFixedElementsAfterScrolling()
1861 {
1862     // For fixed position elements, update widget positions and compositing layers after scrolling,
1863     // but only if we're not inside of layout.
1864     if (!m_nestedLayoutCount && hasViewportConstrainedObjects()) {
1865         if (RenderView* root = rootRenderer(this)) {
1866             root->updateWidgetPositions();
1867             root->layer()->updateLayerPositionsAfterDocumentScroll();
1868         }
1869     }
1870 }
1871
1872 bool FrameView::shouldUpdateFixedElementsAfterScrolling()
1873 {
1874 #if ENABLE(THREADED_SCROLLING)
1875     Page* page = m_frame->page();
1876     if (!page)
1877         return true;
1878
1879     // If the scrolling thread is updating the fixed elements, then the FrameView should not update them as well.
1880     if (page->mainFrame() != m_frame)
1881         return true;
1882
1883     ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
1884     if (!scrollingCoordinator)
1885         return true;
1886
1887     if (!scrollingCoordinator->supportsFixedPositionLayers())
1888         return true;
1889
1890     if (scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread())
1891         return true;
1892
1893     if (inProgrammaticScroll())
1894         return true;
1895
1896     return false;
1897 #endif
1898     return true;
1899 }
1900
1901 void FrameView::updateFixedElementsAfterScrolling()
1902 {
1903 #if USE(ACCELERATED_COMPOSITING)
1904     if (!shouldUpdateFixedElementsAfterScrolling())
1905         return;
1906
1907     if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
1908         if (RenderView* root = rootRenderer(this))
1909             root->compositor()->updateCompositingLayers(CompositingUpdateOnScroll);
1910     }
1911 #endif
1912 }
1913
1914 bool FrameView::shouldRubberBandInDirection(ScrollDirection direction) const
1915 {
1916     Page* page = frame() ? frame()->page() : 0;
1917     if (!page)
1918         return ScrollView::shouldRubberBandInDirection(direction);
1919     return page->chrome()->client()->shouldRubberBandInDirection(direction);
1920 }
1921
1922 bool FrameView::isRubberBandInProgress() const
1923 {
1924     if (scrollbarsSuppressed())
1925         return false;
1926
1927     // If the scrolling thread updates the scroll position for this FrameView, then we should return
1928     // ScrollingCoordinator::isRubberBandInProgress().
1929     if (Page* page = m_frame->page()) {
1930         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) {
1931             if (!scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread())
1932                 return scrollingCoordinator->isRubberBandInProgress();
1933         }
1934     }
1935
1936     // If the main thread updates the scroll position for this FrameView, we should return
1937     // ScrollAnimator::isRubberBandInProgress().
1938     if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
1939         return scrollAnimator->isRubberBandInProgress();
1940
1941     return false;
1942 }
1943
1944 bool FrameView::requestScrollPositionUpdate(const IntPoint& position)
1945 {
1946 #if ENABLE(THREADED_SCROLLING)
1947     if (TiledBacking* tiledBacking = this->tiledBacking()) {
1948         IntRect visibleRect = visibleContentRect();
1949         visibleRect.setLocation(position);
1950         tiledBacking->prepopulateRect(visibleRect);
1951     }
1952
1953     if (Page* page = m_frame->page()) {
1954         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
1955             return scrollingCoordinator->requestScrollPositionUpdate(this, position);
1956     }
1957 #else
1958     UNUSED_PARAM(position);
1959 #endif
1960
1961     return false;
1962 }
1963
1964 HostWindow* FrameView::hostWindow() const
1965 {
1966     Page* page = frame() ? frame()->page() : 0;
1967     if (!page)
1968         return 0;
1969     return page->chrome();
1970 }
1971
1972 const unsigned cRepaintRectUnionThreshold = 25;
1973
1974 void FrameView::repaintContentRectangle(const IntRect& r, bool immediate)
1975 {
1976     ASSERT(!m_frame->ownerElement());
1977
1978     if (m_isTrackingRepaints) {
1979         IntRect repaintRect = r;
1980         repaintRect.move(-scrollOffset());
1981         m_trackedRepaintRects.append(repaintRect);
1982     }
1983
1984     double delay = m_deferringRepaints ? 0 : adjustedDeferredRepaintDelay();
1985     if ((m_deferringRepaints || m_deferredRepaintTimer.isActive() || delay) && !immediate) {
1986         IntRect paintRect = r;
1987         if (clipsRepaints() && !paintsEntireContents())
1988             paintRect.intersect(visibleContentRect());
1989         if (paintRect.isEmpty())
1990             return;
1991         if (m_repaintCount == cRepaintRectUnionThreshold) {
1992             IntRect unionedRect;
1993             for (unsigned i = 0; i < cRepaintRectUnionThreshold; ++i)
1994                 unionedRect.unite(pixelSnappedIntRect(m_repaintRects[i]));
1995             m_repaintRects.clear();
1996             m_repaintRects.append(unionedRect);
1997         }
1998         if (m_repaintCount < cRepaintRectUnionThreshold)
1999             m_repaintRects.append(paintRect);
2000         else
2001             m_repaintRects[0].unite(paintRect);
2002         m_repaintCount++;
2003
2004         if (!m_deferringRepaints)
2005             startDeferredRepaintTimer(delay);
2006
2007         return;
2008     }
2009     
2010     if (!shouldUpdate(immediate))
2011         return;
2012
2013 #if USE(TILED_BACKING_STORE)
2014     if (frame()->tiledBackingStore()) {
2015         frame()->tiledBackingStore()->invalidate(r);
2016         return;
2017     }
2018 #endif
2019     ScrollView::repaintContentRectangle(r, immediate);
2020 }
2021
2022 void FrameView::contentsResized()
2023 {
2024     ScrollView::contentsResized();
2025     setNeedsLayout();
2026 }
2027
2028 void FrameView::visibleContentsResized()
2029 {
2030     // We check to make sure the view is attached to a frame() as this method can
2031     // be triggered before the view is attached by Frame::createView(...) setting
2032     // various values such as setScrollBarModes(...) for example.  An ASSERT is
2033     // triggered when a view is layout before being attached to a frame().
2034     if (!frame()->view())
2035         return;
2036
2037     if (!useFixedLayout() && needsLayout())
2038         layout();
2039
2040 #if USE(ACCELERATED_COMPOSITING)
2041     if (RenderView* root = rootRenderer(this)) {
2042         if (root->usesCompositing())
2043             root->compositor()->frameViewDidChangeSize();
2044     }
2045 #endif
2046 }
2047
2048 void FrameView::beginDeferredRepaints()
2049 {
2050     Page* page = m_frame->page();
2051     if (page->mainFrame() != m_frame) {
2052         page->mainFrame()->view()->beginDeferredRepaints();
2053         return;
2054     }
2055
2056     m_deferringRepaints++;
2057 }
2058
2059 void FrameView::endDeferredRepaints()
2060 {
2061     Page* page = m_frame->page();
2062     if (page->mainFrame() != m_frame) {
2063         page->mainFrame()->view()->endDeferredRepaints();
2064         return;
2065     }
2066
2067     ASSERT(m_deferringRepaints > 0);
2068
2069     if (--m_deferringRepaints)
2070         return;
2071
2072     if (m_deferredRepaintTimer.isActive())
2073         return;
2074
2075     if (double delay = adjustedDeferredRepaintDelay()) {
2076         startDeferredRepaintTimer(delay);
2077         return;
2078     }
2079     
2080     doDeferredRepaints();
2081 }
2082
2083 void FrameView::startDeferredRepaintTimer(double delay)
2084 {
2085     if (m_deferredRepaintTimer.isActive())
2086         return;
2087
2088     if (m_disableRepaints)
2089         return;
2090
2091     m_deferredRepaintTimer.startOneShot(delay);
2092 }
2093
2094 void FrameView::handleLoadCompleted()
2095 {
2096     // Once loading has completed, allow autoSize one last opportunity to
2097     // reduce the size of the frame.
2098     autoSizeIfEnabled();
2099     if (shouldUseLoadTimeDeferredRepaintDelay())
2100         return;
2101     m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
2102     flushDeferredRepaints();
2103 }
2104
2105 void FrameView::flushDeferredRepaints()
2106 {
2107     if (!m_deferredRepaintTimer.isActive())
2108         return;
2109     m_deferredRepaintTimer.stop();
2110     doDeferredRepaints();
2111 }
2112
2113 void FrameView::doDeferredRepaints()
2114 {
2115     if (m_disableRepaints)
2116         return;
2117
2118     ASSERT(!m_deferringRepaints);
2119     if (!shouldUpdate()) {
2120         m_repaintRects.clear();
2121         m_repaintCount = 0;
2122         return;
2123     }
2124     unsigned size = m_repaintRects.size();
2125     for (unsigned i = 0; i < size; i++) {
2126 #if USE(TILED_BACKING_STORE)
2127         if (frame()->tiledBackingStore()) {
2128             frame()->tiledBackingStore()->invalidate(pixelSnappedIntRect(m_repaintRects[i]));
2129             continue;
2130         }
2131 #endif
2132         ScrollView::repaintContentRectangle(pixelSnappedIntRect(m_repaintRects[i]), false);
2133     }
2134     m_repaintRects.clear();
2135     m_repaintCount = 0;
2136     
2137     updateDeferredRepaintDelayAfterRepaint();
2138 }
2139
2140 bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
2141 {
2142     // Don't defer after the initial load of the page has been completed.
2143     if (m_frame->tree()->top()->loader()->isComplete())
2144         return false;
2145     Document* document = m_frame->document();
2146     if (!document)
2147         return false;
2148     if (document->parsing())
2149         return true;
2150     if (document->cachedResourceLoader()->requestCount())
2151         return true;
2152     return false;
2153 }
2154
2155 void FrameView::updateDeferredRepaintDelayAfterRepaint()
2156 {
2157     if (!shouldUseLoadTimeDeferredRepaintDelay()) {
2158         m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
2159         return;
2160     }
2161     double incrementedRepaintDelay = m_deferredRepaintDelay + s_deferredRepaintDelayIncrementDuringLoading;
2162     m_deferredRepaintDelay = std::min(incrementedRepaintDelay, s_maxDeferredRepaintDelayDuringLoading);
2163 }
2164
2165 void FrameView::resetDeferredRepaintDelay()
2166 {
2167     m_deferredRepaintDelay = 0;
2168     if (m_deferredRepaintTimer.isActive()) {
2169         m_deferredRepaintTimer.stop();
2170         if (!m_deferringRepaints)
2171             doDeferredRepaints();
2172     }
2173 }
2174
2175 double FrameView::adjustedDeferredRepaintDelay() const
2176 {
2177     ASSERT(!m_deferringRepaints);
2178     if (!m_deferredRepaintDelay)
2179         return 0;
2180     double timeSinceLastPaint = currentTime() - m_lastPaintTime;
2181     return max(0., m_deferredRepaintDelay - timeSinceLastPaint);
2182 }
2183     
2184 void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
2185 {
2186     doDeferredRepaints();
2187 }
2188
2189 void FrameView::beginDisableRepaints()
2190 {
2191     m_disableRepaints++;
2192 }
2193
2194 void FrameView::endDisableRepaints()
2195 {
2196     ASSERT(m_disableRepaints > 0);
2197     m_disableRepaints--;
2198 }
2199
2200 void FrameView::layoutTimerFired(Timer<FrameView>*)
2201 {
2202 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2203     if (!m_frame->document()->ownerElement())
2204         printf("Layout timer fired at %d\n", m_frame->document()->elapsedTime());
2205 #endif
2206     layout();
2207 }
2208
2209 void FrameView::scheduleRelayout()
2210 {
2211     // FIXME: We should assert the page is not in the page cache, but that is causing
2212     // too many false assertions.  See <rdar://problem/7218118>.
2213     ASSERT(m_frame->view() == this);
2214
2215     if (m_layoutRoot) {
2216         m_layoutRoot->markContainingBlocksForLayout(false);
2217         m_layoutRoot = 0;
2218     }
2219     if (!m_layoutSchedulingEnabled)
2220         return;
2221     if (!needsLayout())
2222         return;
2223     if (!m_frame->document()->shouldScheduleLayout())
2224         return;
2225     InspectorInstrumentation::didInvalidateLayout(m_frame.get());
2226     // When frame flattening is enabled, the contents of the frame could affect the layout of the parent frames.
2227     // Also invalidate parent frame starting from the owner element of this frame.
2228     if (m_frame->ownerRenderer() && isInChildFrameWithFrameFlattening())
2229         m_frame->ownerRenderer()->setNeedsLayout(true, MarkContainingBlockChain);
2230
2231     int delay = m_frame->document()->minimumLayoutDelay();
2232     if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
2233         unscheduleRelayout();
2234     if (m_layoutTimer.isActive())
2235         return;
2236
2237     m_delayedLayout = delay != 0;
2238
2239 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2240     if (!m_frame->document()->ownerElement())
2241         printf("Scheduling layout for %d\n", delay);
2242 #endif
2243
2244     m_layoutTimer.startOneShot(delay * 0.001);
2245 }
2246
2247 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
2248 {
2249     for (RenderObject* r = descendant; r; r = r->container()) {
2250         if (r == ancestor)
2251             return true;
2252     }
2253     return false;
2254 }
2255
2256 void FrameView::scheduleRelayoutOfSubtree(RenderObject* relayoutRoot)
2257 {
2258     ASSERT(m_frame->view() == this);
2259
2260     RenderView* root = rootRenderer(this);
2261     if (root && root->needsLayout()) {
2262         if (relayoutRoot)
2263             relayoutRoot->markContainingBlocksForLayout(false);
2264         return;
2265     }
2266
2267     if (layoutPending() || !m_layoutSchedulingEnabled) {
2268         if (m_layoutRoot != relayoutRoot) {
2269             if (isObjectAncestorContainerOf(m_layoutRoot, relayoutRoot)) {
2270                 // Keep the current root
2271                 relayoutRoot->markContainingBlocksForLayout(false, m_layoutRoot);
2272                 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2273             } else if (m_layoutRoot && isObjectAncestorContainerOf(relayoutRoot, m_layoutRoot)) {
2274                 // Re-root at relayoutRoot
2275                 m_layoutRoot->markContainingBlocksForLayout(false, relayoutRoot);
2276                 m_layoutRoot = relayoutRoot;
2277                 ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2278                 InspectorInstrumentation::didInvalidateLayout(m_frame.get());
2279             } else {
2280                 // Just do a full relayout
2281                 if (m_layoutRoot)
2282                     m_layoutRoot->markContainingBlocksForLayout(false);
2283                 m_layoutRoot = 0;
2284                 relayoutRoot->markContainingBlocksForLayout(false);
2285                 InspectorInstrumentation::didInvalidateLayout(m_frame.get());
2286             }
2287         }
2288     } else if (m_layoutSchedulingEnabled) {
2289         int delay = m_frame->document()->minimumLayoutDelay();
2290         m_layoutRoot = relayoutRoot;
2291         ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
2292         InspectorInstrumentation::didInvalidateLayout(m_frame.get());
2293         m_delayedLayout = delay != 0;
2294         m_layoutTimer.startOneShot(delay * 0.001);
2295     }
2296 }
2297
2298 bool FrameView::layoutPending() const
2299 {
2300     return m_layoutTimer.isActive();
2301 }
2302
2303 bool FrameView::needsLayout() const
2304 {
2305     // This can return true in cases where the document does not have a body yet.
2306     // Document::shouldScheduleLayout takes care of preventing us from scheduling
2307     // layout in that case.
2308     if (!m_frame)
2309         return false;
2310
2311     RenderView* root = rootRenderer(this);
2312     return layoutPending()
2313         || (root && root->needsLayout())
2314         || m_layoutRoot
2315         || (m_deferSetNeedsLayouts && m_setNeedsLayoutWasDeferred);
2316 }
2317
2318 void FrameView::setNeedsLayout()
2319 {
2320     if (m_deferSetNeedsLayouts) {
2321         m_setNeedsLayoutWasDeferred = true;
2322         return;
2323     }
2324
2325     if (RenderView* root = rootRenderer(this))
2326         root->setNeedsLayout(true);
2327 }
2328
2329 void FrameView::unscheduleRelayout()
2330 {
2331     if (!m_layoutTimer.isActive())
2332         return;
2333
2334 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2335     if (!m_frame->document()->ownerElement())
2336         printf("Layout timer unscheduled at %d\n", m_frame->document()->elapsedTime());
2337 #endif
2338     
2339     m_layoutTimer.stop();
2340     m_delayedLayout = false;
2341 }
2342
2343 #if ENABLE(REQUEST_ANIMATION_FRAME)
2344 void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
2345 {
2346     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext()) {
2347         frame->view()->serviceScrollAnimations();
2348         frame->animation()->serviceAnimations();
2349     }
2350
2351     Vector<RefPtr<Document> > documents;
2352     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext())
2353         documents.append(frame->document());
2354
2355     for (size_t i = 0; i < documents.size(); ++i)
2356         documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
2357 }
2358 #endif
2359
2360 bool FrameView::isTransparent() const
2361 {
2362     return m_isTransparent;
2363 }
2364
2365 void FrameView::setTransparent(bool isTransparent)
2366 {
2367     m_isTransparent = isTransparent;
2368 }
2369
2370 bool FrameView::hasOpaqueBackground() const
2371 {
2372     return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
2373 }
2374
2375 Color FrameView::baseBackgroundColor() const
2376 {
2377     return m_baseBackgroundColor;
2378 }
2379
2380 void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
2381 {
2382     if (!backgroundColor.isValid())
2383         m_baseBackgroundColor = Color::white;
2384     else
2385         m_baseBackgroundColor = backgroundColor;
2386
2387     recalculateScrollbarOverlayStyle();
2388 }
2389
2390 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
2391 {
2392     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
2393         if (FrameView* view = frame->view()) {
2394             view->setTransparent(transparent);
2395             view->setBaseBackgroundColor(backgroundColor);
2396         }
2397     }
2398 }
2399
2400 bool FrameView::shouldUpdateWhileOffscreen() const
2401 {
2402     return m_shouldUpdateWhileOffscreen;
2403 }
2404
2405 void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
2406 {
2407     m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
2408 }
2409
2410 bool FrameView::shouldUpdate(bool immediateRequested) const
2411 {
2412     if (!immediateRequested && isOffscreen() && !shouldUpdateWhileOffscreen())
2413         return false;
2414     return true;
2415 }
2416
2417 void FrameView::scheduleEvent(PassRefPtr<Event> event, PassRefPtr<Node> eventTarget)
2418 {
2419     m_actionScheduler->scheduleEvent(event, eventTarget);
2420 }
2421
2422 void FrameView::pauseScheduledEvents()
2423 {
2424     m_actionScheduler->pause();
2425 }
2426
2427 void FrameView::resumeScheduledEvents()
2428 {
2429     m_actionScheduler->resume();
2430 }
2431
2432 void FrameView::scrollToAnchor()
2433 {
2434     RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
2435     if (!anchorNode)
2436         return;
2437
2438     if (!anchorNode->renderer())
2439         return;
2440
2441     LayoutRect rect;
2442     if (anchorNode != m_frame->document())
2443         rect = anchorNode->boundingBox();
2444
2445     // Scroll nested layers and frames to reveal the anchor.
2446     // Align to the top and to the closest side (this matches other browsers).
2447     anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
2448
2449     if (AXObjectCache::accessibilityEnabled())
2450         m_frame->document()->axObjectCache()->handleScrolledToAnchor(anchorNode.get());
2451
2452     // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
2453     m_maintainScrollPositionAnchor = anchorNode;
2454 }
2455
2456 void FrameView::updateWidget(RenderEmbeddedObject* object)
2457 {
2458     ASSERT(!object->node() || object->node()->isElementNode());
2459     Element* ownerElement = static_cast<Element*>(object->node());
2460     // The object may have already been destroyed (thus node cleared),
2461     // but FrameView holds a manual ref, so it won't have been deleted.
2462     ASSERT(m_widgetUpdateSet->contains(object));
2463     if (!ownerElement)
2464         return;
2465
2466     // No need to update if it's already crashed or known to be missing.
2467     if (object->showsUnavailablePluginIndicator())
2468         return;
2469
2470     // FIXME: This could turn into a real virtual dispatch if we defined
2471     // updateWidget(PluginCreationOption) on HTMLElement.
2472     if (ownerElement->hasTagName(objectTag) || ownerElement->hasTagName(embedTag) || ownerElement->hasTagName(appletTag)) {
2473         HTMLPlugInImageElement* pluginElement = static_cast<HTMLPlugInImageElement*>(ownerElement);
2474         if (pluginElement->needsWidgetUpdate())
2475             pluginElement->updateWidget(CreateAnyWidgetType);
2476     }
2477     // FIXME: It is not clear that Media elements need or want this updateWidget() call.
2478 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
2479     else if (ownerElement->isMediaElement())
2480         static_cast<HTMLMediaElement*>(ownerElement)->updateWidget(CreateAnyWidgetType);
2481 #endif
2482     else
2483         ASSERT_NOT_REACHED();
2484
2485     // Caution: it's possible the object was destroyed again, since loading a
2486     // plugin may run any arbitrary javascript.
2487     object->updateWidgetPosition();
2488 }
2489
2490 bool FrameView::updateWidgets()
2491 {
2492     if (m_nestedLayoutCount > 1 || !m_widgetUpdateSet || m_widgetUpdateSet->isEmpty())
2493         return true;
2494     
2495     size_t size = m_widgetUpdateSet->size();
2496
2497     Vector<RenderEmbeddedObject*> objects;
2498     objects.reserveCapacity(size);
2499
2500     RenderEmbeddedObjectSet::const_iterator end = m_widgetUpdateSet->end();
2501     for (RenderEmbeddedObjectSet::const_iterator it = m_widgetUpdateSet->begin(); it != end; ++it) {
2502         objects.uncheckedAppend(*it);
2503         (*it)->ref();
2504     }
2505
2506     for (size_t i = 0; i < size; ++i) {
2507         RenderEmbeddedObject* object = objects[i];
2508         updateWidget(object);
2509         m_widgetUpdateSet->remove(object);
2510     }
2511
2512     RenderArena* arena = m_frame->document()->renderArena();
2513     for (size_t i = 0; i < size; ++i)
2514         objects[i]->deref(arena);
2515     
2516     return m_widgetUpdateSet->isEmpty();
2517 }
2518
2519 void FrameView::flushAnyPendingPostLayoutTasks()
2520 {
2521     if (!m_postLayoutTasksTimer.isActive())
2522         return;
2523
2524     performPostLayoutTasks();
2525 }
2526
2527 void FrameView::performPostLayoutTasks()
2528 {
2529     m_postLayoutTasksTimer.stop();
2530
2531     m_frame->selection()->setCaretRectNeedsUpdate();
2532     m_frame->selection()->updateAppearance();
2533
2534     LayoutMilestones milestonesOfInterest = 0;
2535     LayoutMilestones milestonesAchieved = 0;
2536     Page* page = m_frame->page();
2537     if (page)
2538         milestonesOfInterest = page->layoutMilestones();
2539
2540     if (m_nestedLayoutCount <= 1) {
2541         if (m_firstLayoutCallbackPending) {
2542             m_firstLayoutCallbackPending = false;
2543             m_frame->loader()->didFirstLayout();
2544             if (milestonesOfInterest & DidFirstLayout)
2545                 milestonesAchieved |= DidFirstLayout;
2546             if (page) {
2547                 if (page->mainFrame() == m_frame)
2548                     page->startCountingRelevantRepaintedObjects();
2549             }
2550         }
2551
2552         // Ensure that we always send this eventually.
2553         if (!m_frame->document()->parsing() && m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad())
2554             m_isVisuallyNonEmpty = true;
2555
2556         // If the layout was done with pending sheets, we are not in fact visually non-empty yet.
2557         if (m_isVisuallyNonEmpty && !m_frame->document()->didLayoutWithPendingStylesheets() && m_firstVisuallyNonEmptyLayoutCallbackPending) {
2558             m_firstVisuallyNonEmptyLayoutCallbackPending = false;
2559             if (milestonesOfInterest & DidFirstVisuallyNonEmptyLayout)
2560                 milestonesAchieved |= DidFirstVisuallyNonEmptyLayout;
2561         }
2562     }
2563
2564     m_frame->loader()->didLayout(milestonesAchieved);
2565     
2566     // FIXME: We should consider adding DidLayout as a LayoutMilestone. That would let us merge this
2567     // with didLayout(LayoutMilestones).
2568     m_frame->loader()->client()->dispatchDidLayout();
2569
2570     RenderView* root = rootRenderer(this);
2571     if (root)
2572         root->updateWidgetPositions();
2573     
2574     for (unsigned i = 0; i < maxUpdateWidgetsIterations; i++) {
2575         if (updateWidgets())
2576             break;
2577     }
2578
2579     if (page) {
2580         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
2581             scrollingCoordinator->frameViewLayoutUpdated(this);
2582     }
2583
2584 #if USE(ACCELERATED_COMPOSITING)
2585     if (RenderView* root = rootRenderer(this)) {
2586         if (root->usesCompositing())
2587             root->compositor()->frameViewDidLayout();
2588     }
2589 #endif
2590
2591     scrollToAnchor();
2592
2593     m_actionScheduler->resume();
2594
2595     if (root && !root->printing()) {
2596         IntSize currentSize;
2597         if (useFixedLayout() && !fixedLayoutSize().isEmpty() && delegatesScrolling())
2598             currentSize = fixedLayoutSize();
2599         else
2600             currentSize = visibleContentRect(true /*includeScrollbars*/).size();
2601         float currentZoomFactor = root->style()->zoom();
2602         bool resized = !m_firstLayout && (currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor);
2603         m_lastViewportSize = currentSize;
2604         m_lastZoomFactor = currentZoomFactor;
2605         if (resized) {
2606             m_frame->eventHandler()->sendResizeEvent();
2607
2608 #if ENABLE(INSPECTOR)
2609             if (InspectorInstrumentation::hasFrontends()) {
2610                 if (page) {
2611                     if (page->mainFrame() == m_frame) {
2612                         if (InspectorClient* inspectorClient = page->inspectorController()->inspectorClient())
2613                             inspectorClient->didResizeMainFrame(m_frame.get());
2614                     }
2615                 }
2616             }
2617 #endif
2618         }
2619     }
2620 }
2621
2622 void FrameView::postLayoutTimerFired(Timer<FrameView>*)
2623 {
2624     performPostLayoutTasks();
2625 }
2626
2627 void FrameView::autoSizeIfEnabled()
2628 {
2629     if (!m_shouldAutoSize)
2630         return;
2631
2632     if (m_inAutoSize)
2633         return;
2634
2635     TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
2636
2637     Document* document = frame()->document();
2638     if (!document)
2639         return;
2640
2641     RenderView* documentView = document->renderView();
2642     Element* documentElement = document->documentElement();
2643     if (!documentView || !documentElement)
2644         return;
2645
2646     RenderBox* documentRenderBox = documentElement->renderBox();
2647     if (!documentRenderBox)
2648         return;
2649
2650     // If this is the first time we run autosize, start from small height and
2651     // allow it to grow.
2652     if (!m_didRunAutosize)
2653         resize(frameRect().width(), m_minAutoSize.height());
2654
2655     IntSize size = frameRect().size();
2656
2657     // Do the resizing twice. The first time is basically a rough calculation using the preferred width
2658     // which may result in a height change during the second iteration.
2659     for (int i = 0; i < 2; i++) {
2660         // Update various sizes including contentsSize, scrollHeight, etc.
2661         document->updateLayoutIgnorePendingStylesheets();
2662         int width = documentView->minPreferredLogicalWidth();
2663         int height = documentRenderBox->scrollHeight();
2664         IntSize newSize(width, height);
2665
2666         // Check to see if a scrollbar is needed for a given dimension and
2667         // if so, increase the other dimension to account for the scrollbar.
2668         // Since the dimensions are only for the view rectangle, once a
2669         // dimension exceeds the maximum, there is no need to increase it further.
2670         if (newSize.width() > m_maxAutoSize.width()) {
2671             RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
2672             if (!localHorizontalScrollbar)
2673                 localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
2674             if (!localHorizontalScrollbar->isOverlayScrollbar())
2675                 newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
2676
2677             // Don't bother checking for a vertical scrollbar because the width is at
2678             // already greater the maximum.
2679         } else if (newSize.height() > m_maxAutoSize.height()) {
2680             RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
2681             if (!localVerticalScrollbar)
2682                 localVerticalScrollbar = createScrollbar(VerticalScrollbar);
2683             if (!localVerticalScrollbar->isOverlayScrollbar())
2684                 newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
2685
2686             // Don't bother checking for a horizontal scrollbar because the height is
2687             // already greater the maximum.
2688         }
2689
2690         // Ensure the size is at least the min bounds.
2691         newSize = newSize.expandedTo(m_minAutoSize);
2692
2693         // Bound the dimensions by the max bounds and determine what scrollbars to show.
2694         ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
2695         if (newSize.width() > m_maxAutoSize.width()) {
2696             newSize.setWidth(m_maxAutoSize.width());
2697             horizonalScrollbarMode = ScrollbarAlwaysOn;
2698         }
2699         ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
2700         if (newSize.height() > m_maxAutoSize.height()) {
2701             newSize.setHeight(m_maxAutoSize.height());
2702             verticalScrollbarMode = ScrollbarAlwaysOn;
2703         }
2704
2705         if (newSize == size)
2706             continue;
2707
2708         // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
2709         // unless autoresize has just been turned on or the maximum size is smaller than the current size.
2710         if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
2711             && !frame()->loader()->isComplete() && (newSize.height() < size.height() || newSize.width() < size.width()))
2712             break;
2713
2714         resize(newSize.width(), newSize.height());
2715         // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
2716         // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
2717         setVerticalScrollbarLock(false);
2718         setHorizontalScrollbarLock(false);
2719         setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
2720     }
2721     m_didRunAutosize = true;
2722 }
2723
2724 void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
2725 {
2726     if (!m_viewportRenderer)
2727         return;
2728     
2729     if (m_overflowStatusDirty) {
2730         m_horizontalOverflow = horizontalOverflow;
2731         m_verticalOverflow = verticalOverflow;
2732         m_overflowStatusDirty = false;
2733         return;
2734     }
2735     
2736     bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
2737     bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
2738     
2739     if (horizontalOverflowChanged || verticalOverflowChanged) {
2740         m_horizontalOverflow = horizontalOverflow;
2741         m_verticalOverflow = verticalOverflow;
2742         
2743         m_actionScheduler->scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
2744             verticalOverflowChanged, verticalOverflow),
2745             m_viewportRenderer->node());
2746     }
2747     
2748 }
2749
2750 const Pagination& FrameView::pagination() const
2751 {
2752     if (m_pagination != Pagination())
2753         return m_pagination;
2754
2755     if (Page* page = m_frame->page()) {
2756         if (page->mainFrame() == m_frame)
2757             return page->pagination();
2758     }
2759
2760     return m_pagination;
2761 }
2762
2763 void FrameView::setPagination(const Pagination& pagination)
2764 {
2765     if (m_pagination == pagination)
2766         return;
2767
2768     m_pagination = pagination;
2769
2770     if (m_frame)
2771         m_frame->document()->styleResolverChanged(DeferRecalcStyle);
2772 }
2773
2774 IntRect FrameView::windowClipRect(bool clipToContents) const
2775 {
2776     ASSERT(m_frame->view() == this);
2777
2778     if (paintsEntireContents())
2779         return IntRect(IntPoint(), contentsSize());
2780
2781     // Set our clip rect to be our contents.
2782     IntRect clipRect = contentsToWindow(visibleContentRect(!clipToContents));
2783     if (!m_frame || !m_frame->ownerElement())
2784         return clipRect;
2785
2786     // Take our owner element and get its clip rect.
2787     HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
2788     FrameView* parentView = ownerElement->document()->view();
2789     if (parentView)
2790         clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
2791     return clipRect;
2792 }
2793
2794 IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
2795 {
2796     // The renderer can sometimes be null when style="display:none" interacts
2797     // with external content and plugins.
2798     if (!ownerElement->renderer())
2799         return windowClipRect();
2800
2801     // If we have no layer, just return our window clip rect.
2802     const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
2803     if (!enclosingLayer)
2804         return windowClipRect();
2805
2806     // Apply the clip from the layer.
2807     IntRect clipRect;
2808     if (clipToLayerContents)
2809         clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
2810     else
2811         clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
2812     clipRect = contentsToWindow(clipRect); 
2813     return intersection(clipRect, windowClipRect());
2814 }
2815
2816 bool FrameView::isActive() const
2817 {
2818     Page* page = frame()->page();
2819     return page && page->focusController()->isActive();
2820 }
2821
2822 void FrameView::scrollTo(const IntSize& newOffset)
2823 {
2824     LayoutSize offset = scrollOffset();
2825     ScrollView::scrollTo(newOffset);
2826     if (offset != scrollOffset())
2827         scrollPositionChanged();
2828     frame()->loader()->client()->didChangeScrollOffset();
2829 }
2830
2831 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
2832 {
2833     // Add in our offset within the FrameView.
2834     IntRect dirtyRect = rect;
2835     dirtyRect.moveBy(scrollbar->location());
2836     invalidateRect(dirtyRect);
2837 }
2838
2839 void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
2840 {
2841     tickmarks = frame()->document()->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
2842 }
2843
2844 IntRect FrameView::windowResizerRect() const
2845 {
2846     Page* page = frame() ? frame()->page() : 0;
2847     if (!page)
2848         return IntRect();
2849     return page->chrome()->windowResizerRect();
2850 }
2851
2852 float FrameView::visibleContentScaleFactor() const
2853 {
2854     if (!m_frame || !m_frame->page())
2855         return 1;
2856
2857     if (!m_frame->settings()->applyPageScaleFactorInCompositor() || m_frame != m_frame->page()->mainFrame())
2858         return 1;
2859
2860     return m_frame->page()->pageScaleFactor();
2861 }
2862
2863 void FrameView::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
2864 {
2865     Page* page = m_frame->page();
2866     if (!page)
2867         return;
2868     if (page->mainFrame() != m_frame)
2869         return;
2870     page->chrome()->client()->notifyScrollerThumbIsVisibleInRect(scrollerThumb);
2871 }
2872
2873 bool FrameView::scrollbarsCanBeActive() const
2874 {
2875     if (!m_frame)
2876         return false;
2877
2878     if (m_frame->view() != this)
2879         return false;
2880
2881     if (Page* page = m_frame->page()) {
2882         if (page->shouldSuppressScrollbarAnimations())
2883             return false;
2884     }
2885
2886     if (Document* document = m_frame->document())
2887         return !document->inPageCache();
2888
2889     return false;
2890 }
2891
2892 ScrollableArea* FrameView::enclosingScrollableArea() const
2893 {
2894     // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
2895     return 0;
2896 }
2897
2898 IntRect FrameView::scrollableAreaBoundingBox() const
2899 {
2900     RenderPart* ownerRenderer = frame()->ownerRenderer();
2901     if (!ownerRenderer)
2902         return frameRect();
2903
2904     return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
2905 }
2906
2907 bool FrameView::isScrollable()
2908 {
2909     // Check for:
2910     // 1) If there an actual overflow.
2911     // 2) display:none or visibility:hidden set to self or inherited.
2912     // 3) overflow{-x,-y}: hidden;
2913     // 4) scrolling: no;
2914
2915     // Covers #1
2916     IntSize contentSize = contentsSize();
2917     IntSize visibleContentSize = visibleContentRect().size();
2918     if ((contentSize.height() <= visibleContentSize.height() && contentSize.width() <= visibleContentSize.width()))
2919         return false;
2920
2921     // Covers #2.
2922     HTMLFrameOwnerElement* owner = m_frame->ownerElement();
2923     if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
2924         return false;
2925
2926     // Cover #3 and #4.
2927     ScrollbarMode horizontalMode;
2928     ScrollbarMode verticalMode;
2929     calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
2930     if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
2931         return false;
2932
2933     return true;
2934 }
2935
2936 void FrameView::updateScrollableAreaSet()
2937 {
2938     // That ensures that only inner frames are cached.
2939     FrameView* parentFrameView = this->parentFrameView();
2940     if (!parentFrameView)
2941         return;
2942
2943     if (!isScrollable()) {
2944         parentFrameView->removeScrollableArea(this);
2945         return;
2946     }
2947
2948     parentFrameView->addScrollableArea(this);
2949 }
2950
2951 bool FrameView::shouldSuspendScrollAnimations() const
2952 {
2953     return m_frame->loader()->state() != FrameStateComplete;
2954 }
2955
2956 void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
2957 {
2958     Page* page = m_frame->page();
2959     if (!page)
2960         return;
2961     if (page->mainFrame() != m_frame)
2962         return;
2963     page->chrome()->client()->recommendedScrollbarStyleDidChange(newStyle);
2964
2965     if (forceUpdate)
2966         ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
2967 }
2968
2969 void FrameView::setAnimatorsAreActive()
2970 {
2971     Page* page = m_frame->page();
2972     if (!page)
2973         return;
2974
2975     if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
2976         scrollAnimator->setIsActive();
2977
2978     if (!m_scrollableAreas)
2979         return;
2980
2981     for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
2982         ScrollableArea* scrollableArea = *it;
2983
2984         ASSERT(scrollableArea->scrollbarsCanBeActive());
2985         scrollableArea->scrollAnimator()->setIsActive();
2986     }
2987 }
2988
2989 void FrameView::notifyPageThatContentAreaWillPaint() const
2990 {
2991     Page* page = m_frame->page();
2992     if (!page)
2993         return;
2994
2995     contentAreaWillPaint();
2996
2997     if (!m_scrollableAreas)
2998         return;
2999
3000     for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
3001         ScrollableArea* scrollableArea = *it;
3002
3003         if (!scrollableArea->scrollbarsCanBeActive())
3004             continue;
3005
3006         scrollableArea->contentAreaWillPaint();
3007     }
3008 }
3009
3010 bool FrameView::scrollAnimatorEnabled() const
3011 {
3012 #if ENABLE(SMOOTH_SCROLLING)
3013     if (Page* page = m_frame->page())
3014         return page->settings()->scrollAnimatorEnabled();
3015 #endif
3016
3017     return false;
3018 }
3019
3020 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3021 void FrameView::updateAnnotatedRegions()
3022 {
3023     Document* document = m_frame->document();
3024     if (!document->hasAnnotatedRegions())
3025         return;
3026     Vector<AnnotatedRegionValue> newRegions;
3027     document->renderBox()->collectAnnotatedRegions(newRegions);
3028     if (newRegions == document->annotatedRegions())
3029         return;
3030     document->setAnnotatedRegions(newRegions);
3031     Page* page = m_frame->page();
3032     if (!page)
3033         return;
3034     page->chrome()->client()->annotatedRegionsChanged();
3035 }
3036 #endif
3037
3038 void FrameView::updateScrollCorner()
3039 {
3040     RenderObject* renderer = 0;
3041     RefPtr<RenderStyle> cornerStyle;
3042     IntRect cornerRect = scrollCornerRect();
3043     
3044     if (!cornerRect.isEmpty()) {
3045         // Try the <body> element first as a scroll corner source.
3046         Document* doc = m_frame->document();
3047         Element* body = doc ? doc->body() : 0;
3048         if (body && body->renderer()) {
3049             renderer = body->renderer();
3050             cornerStyle = renderer->getUncachedPseudoStyle(SCROLLBAR_CORNER, renderer->style());
3051         }
3052         
3053         if (!cornerStyle) {
3054             // If the <body> didn't have a custom style, then the root element might.
3055             Element* docElement = doc ? doc->documentElement() : 0;
3056             if (docElement && docElement->renderer()) {
3057                 renderer = docElement->renderer();
3058                 cornerStyle = renderer->getUncachedPseudoStyle(SCROLLBAR_CORNER, renderer->style());
3059             }
3060         }
3061         
3062         if (!cornerStyle) {
3063             // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
3064             if (RenderPart* renderer = m_frame->ownerRenderer())
3065                 cornerStyle = renderer->getUncachedPseudoStyle(SCROLLBAR_CORNER, renderer->style());
3066         }
3067     }
3068
3069     if (cornerStyle) {
3070         if (!m_scrollCorner)
3071             m_scrollCorner = RenderScrollbarPart::createAnonymous(renderer->document());
3072         m_scrollCorner->setStyle(cornerStyle.release());
3073         invalidateScrollCorner(cornerRect);
3074     } else if (m_scrollCorner) {
3075         m_scrollCorner->destroy();
3076         m_scrollCorner = 0;
3077     }
3078
3079     ScrollView::updateScrollCorner();
3080 }
3081
3082 void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
3083 {
3084     if (context->updatingControlTints()) {
3085         updateScrollCorner();
3086         return;
3087     }
3088
3089     if (m_scrollCorner) {
3090         bool needsBackgorund = m_frame->page() && m_frame->page()->mainFrame() == m_frame;
3091         if (needsBackgorund)
3092             context->fillRect(cornerRect, baseBackgroundColor(), ColorSpaceDeviceRGB);
3093         m_scrollCorner->paintIntoRect(context, cornerRect.location(), cornerRect);
3094         return;
3095     }
3096
3097     ScrollView::paintScrollCorner(context, cornerRect);
3098 }
3099
3100 void FrameView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
3101 {
3102     bool needsBackgorund = bar->isCustomScrollbar() && (m_frame->page() && m_frame->page()->mainFrame() == m_frame);
3103     if (needsBackgorund) {
3104         IntRect toFill = bar->frameRect();
3105         toFill.intersect(rect);
3106         context->fillRect(toFill, baseBackgroundColor(), ColorSpaceDeviceRGB);
3107     }
3108
3109     ScrollView::paintScrollbar(context, bar, rect);
3110 }
3111
3112 Color FrameView::documentBackgroundColor() const
3113 {
3114     // <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
3115     // the document and the body against the base background color of the frame view.
3116     // Background images are unfortunately impractical to include.
3117
3118     // Return invalid Color objects whenever there is insufficient information.
3119     if (!frame()->document())
3120         return Color();
3121
3122     Element* htmlElement = frame()->document()->documentElement();
3123     Element* bodyElement = frame()->document()->body();
3124
3125     // Start with invalid colors.
3126     Color htmlBackgroundColor;
3127     Color bodyBackgroundColor;
3128     if (htmlElement && htmlElement->renderer())
3129         htmlBackgroundColor = htmlElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
3130     if (bodyElement && bodyElement->renderer())
3131         bodyBackgroundColor = bodyElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
3132
3133     if (!bodyBackgroundColor.isValid()) {
3134         if (!htmlBackgroundColor.isValid())
3135             return Color();
3136         return baseBackgroundColor().blend(htmlBackgroundColor);
3137     }
3138
3139     if (!htmlBackgroundColor.isValid())
3140         return baseBackgroundColor().blend(bodyBackgroundColor);
3141
3142     // We take the aggregate of the base background color
3143     // the <html> background color, and the <body>
3144     // background color to find the document color. The
3145     // addition of the base background color is not
3146     // technically part of the document background, but it
3147     // otherwise poses problems when the aggregate is not
3148     // fully opaque.
3149     return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
3150 }
3151
3152 bool FrameView::hasCustomScrollbars() const
3153 {
3154     const HashSet<RefPtr<Widget> >* viewChildren = children();
3155     HashSet<RefPtr<Widget> >::const_iterator end = viewChildren->end();
3156     for (HashSet<RefPtr<Widget> >::const_iterator current = viewChildren->begin(); current != end; ++current) {
3157         Widget* widget = current->get();
3158         if (widget->isFrameView()) {
3159             if (static_cast<FrameView*>(widget)->hasCustomScrollbars())
3160                 return true;
3161         } else if (widget->isScrollbar()) {
3162             Scrollbar* scrollbar = static_cast<Scrollbar*>(widget);
3163             if (scrollbar->isCustomScrollbar())
3164                 return true;
3165         }
3166     }
3167
3168     return false;
3169 }
3170
3171 FrameView* FrameView::parentFrameView() const
3172 {
3173     if (!parent())
3174         return 0;
3175
3176     if (Frame* parentFrame = m_frame->tree()->parent())
3177         return parentFrame->view();
3178
3179     return 0;
3180 }
3181
3182 bool FrameView::isInChildFrameWithFrameFlattening() const
3183 {
3184     if (!parent() || !m_frame->ownerElement())
3185         return false;
3186
3187     // Frame flattening applies when the owner element is either in a frameset or
3188     // an iframe with flattening parameters.
3189     if (m_frame->ownerElement()->hasTagName(iframeTag)) {
3190         RenderIFrame* iframeRenderer = toRenderIFrame(m_frame->ownerElement()->renderPart());
3191         if (iframeRenderer->flattenFrame() || iframeRenderer->isSeamless())
3192             return true;
3193     }
3194
3195     if (!m_frame->settings() || !m_frame->settings()->frameFlatteningEnabled())
3196         return false;
3197
3198     if (m_frame->ownerElement()->hasTagName(frameTag))
3199         return true;
3200
3201     return false;
3202 }
3203
3204 bool FrameView::doLayoutWithFrameFlattening(bool allowSubtree)
3205 {
3206     // Try initiating layout from the topmost parent.
3207     FrameView* parentView = parentFrameView();
3208
3209     if (!parentView)
3210         return false;
3211
3212     // In the middle of parent layout, no need to restart from topmost.
3213     if (parentView->m_nestedLayoutCount)
3214         return false;
3215
3216     // Parent tree is clean. Starting layout from it would have no effect.
3217     if (!parentView->needsLayout())
3218         return false;
3219
3220     while (parentView->parentFrameView())
3221         parentView = parentView->parentFrameView();
3222
3223     parentView->layout(allowSubtree);
3224
3225     RenderObject* root = m_layoutRoot ? m_layoutRoot : m_frame->document()->renderer();
3226     ASSERT_UNUSED(root, !root->needsLayout());
3227
3228     return true;
3229 }
3230
3231 void FrameView::updateControlTints()
3232 {
3233     // This is called when control tints are changed from aqua/graphite to clear and vice versa.
3234     // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
3235     // This is only done if the theme supports control tinting. It's up to the theme and platform
3236     // to define when controls get the tint and to call this function when that changes.
3237     
3238     // Optimize the common case where we bring a window to the front while it's still empty.
3239     if (!m_frame || m_frame->document()->url().isEmpty())
3240         return;
3241
3242     RenderView* root = rootRenderer(this);
3243     if ((root && root->theme()->supportsControlTints()) || hasCustomScrollbars())
3244         paintControlTints();
3245 }
3246
3247 void FrameView::paintControlTints()
3248 {
3249     if (needsLayout())
3250         layout();
3251     PlatformGraphicsContext* const noContext = 0;
3252     GraphicsContext context(noContext);
3253     context.setUpdatingControlTints(true);
3254     if (platformWidget())
3255         paintContents(&context, visibleContentRect());
3256     else
3257         paint(&context, frameRect());
3258 }
3259
3260 bool FrameView::wasScrolledByUser() const
3261 {
3262     return m_wasScrolledByUser;
3263 }
3264
3265 void FrameView::setWasScrolledByUser(bool wasScrolledByUser)
3266 {
3267     if (m_inProgrammaticScroll)
3268         return;
3269     m_maintainScrollPositionAnchor = 0;
3270     m_wasScrolledByUser = wasScrolledByUser;
3271 }
3272
3273 void FrameView::paintContents(GraphicsContext* p, const IntRect& rect)
3274 {
3275     if (!frame())
3276         return;
3277
3278     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willPaint(m_frame.get());
3279
3280     Document* document = m_frame->document();
3281
3282 #ifndef NDEBUG
3283     bool fillWithRed;
3284     if (document->printing())
3285         fillWithRed = false; // Printing, don't fill with red (can't remember why).
3286     else if (m_frame->ownerElement())
3287         fillWithRed = false; // Subframe, don't fill with red.
3288     else if (isTransparent())
3289         fillWithRed = false; // Transparent, don't fill with red.
3290     else if (m_paintBehavior & PaintBehaviorSelectionOnly)
3291         fillWithRed = false; // Selections are transparent, don't fill with red.
3292     else if (m_nodeToDraw)
3293         fillWithRed = false; // Element images are transparent, don't fill with red.
3294     else
3295         fillWithRed = true;
3296     
3297     if (fillWithRed)
3298         p->fillRect(rect, Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
3299 #endif
3300
3301     RenderView* root = rootRenderer(this);
3302     if (!root) {
3303         LOG_ERROR("called FrameView::paint with nil renderer");
3304         return;
3305     }
3306
3307     ASSERT(!needsLayout());
3308     if (needsLayout())
3309         return;
3310
3311     bool isTopLevelPainter = !sCurrentPaintTimeStamp;
3312     if (isTopLevelPainter)
3313         sCurrentPaintTimeStamp = currentTime();
3314
3315     FontCachePurgePreventer fontCachePurgePreventer;
3316
3317 #if USE(ACCELERATED_COMPOSITING)
3318     if (!p->paintingDisabled() && !document->printing())
3319         flushCompositingStateForThisFrame(m_frame.get());
3320 #endif
3321
3322     PaintBehavior oldPaintBehavior = m_paintBehavior;
3323     
3324     if (FrameView* parentView = parentFrameView()) {
3325         if (parentView->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
3326             m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
3327     }
3328     
3329     if (m_paintBehavior == PaintBehaviorNormal)
3330         document->markers()->invalidateRenderedRectsForMarkersInRect(rect);
3331
3332     if (document->printing())
3333         m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
3334
3335     bool flatteningPaint = m_paintBehavior & PaintBehaviorFlattenCompositingLayers;
3336     bool isRootFrame = !m_frame->ownerElement();
3337     if (flatteningPaint && isRootFrame)
3338         notifyWidgetsInAllFrames(WillPaintFlattened);
3339
3340     ASSERT(!m_isPainting);
3341     m_isPainting = true;
3342
3343     // m_nodeToDraw is used to draw only one element (and its descendants)
3344     RenderObject* eltRenderer = m_nodeToDraw ? m_nodeToDraw->renderer() : 0;
3345     RenderLayer* rootLayer = root->layer();
3346
3347 #ifndef NDEBUG
3348     RenderObject::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(rootLayer->renderer());
3349 #endif
3350
3351     rootLayer->paint(p, rect, m_paintBehavior, eltRenderer);
3352
3353     if (rootLayer->containsDirtyOverlayScrollbars())
3354         rootLayer->paintOverlayScrollbars(p, rect, m_paintBehavior, eltRenderer);
3355
3356     m_isPainting = false;
3357
3358     if (flatteningPaint && isRootFrame)
3359         notifyWidgetsInAllFrames(DidPaintFlattened);
3360
3361     m_paintBehavior = oldPaintBehavior;
3362     m_lastPaintTime = currentTime();
3363
3364     // Regions may have changed as a result of the visibility/z-index of element changing.
3365 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3366     if (document->annotatedRegionsDirty())
3367         updateAnnotatedRegions();
3368 #endif
3369
3370     if (isTopLevelPainter)
3371         sCurrentPaintTimeStamp = 0;
3372
3373     InspectorInstrumentation::didPaint(cookie, p, rect);
3374 }
3375
3376 void FrameView::setPaintBehavior(PaintBehavior behavior)
3377 {
3378     m_paintBehavior = behavior;
3379 }
3380
3381 PaintBehavior FrameView::paintBehavior() const
3382 {
3383     return m_paintBehavior;
3384 }
3385
3386 bool FrameView::isPainting() const
3387 {
3388     return m_isPainting;
3389 }
3390
3391 void FrameView::setNodeToDraw(Node* node)
3392 {
3393     m_nodeToDraw = node;
3394 }
3395
3396 void FrameView::paintContentsForSnapshot(GraphicsContext* context, const IntRect& imageRect, SelectionInSnaphot shouldPaintSelection, CoordinateSpaceForSnapshot coordinateSpace)
3397 {
3398     updateLayoutAndStyleIfNeededRecursive();
3399
3400     // Cache paint behavior and set a new behavior appropriate for snapshots.
3401     PaintBehavior oldBehavior = paintBehavior();
3402     setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
3403
3404     // If the snapshot should exclude selection, then we'll clear the current selection
3405     // in the render tree only. This will allow us to restore the selection from the DOM
3406     // after we paint the snapshot.
3407     if (shouldPaintSelection == ExcludeSelection) {
3408         for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
3409             if (RenderView* root = frame->contentRenderer())
3410                 root->clearSelection();
3411         }
3412     }
3413
3414     if (coordinateSpace == DocumentCoordinates)
3415         paintContents(context, imageRect);
3416     else {
3417         // A snapshot in ViewCoordinates will include a scrollbar, and the snapshot will contain
3418         // whatever content the document is currently scrolled to.
3419         paint(context, imageRect);
3420     }
3421
3422     // Restore selection.
3423     if (shouldPaintSelection == ExcludeSelection) {
3424         for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get()))
3425             frame->selection()->updateAppearance();
3426     }
3427
3428     // Restore cached paint behavior.
3429     setPaintBehavior(oldBehavior);
3430 }
3431
3432 void FrameView::paintOverhangAreas(GraphicsContext* context, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect)
3433 {
3434     if (context->paintingDisabled())
3435         return;
3436
3437     if (m_frame->document()->printing())
3438         return;
3439
3440     Page* page = m_frame->page();
3441     if (page->mainFrame() == m_frame) {
3442         if (page->chrome()->client()->paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
3443             return;
3444     }
3445
3446     ScrollView::paintOverhangAreas(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect);
3447 }
3448
3449 void FrameView::updateLayoutAndStyleIfNeededRecursive()
3450 {
3451     // We have to crawl our entire tree looking for any FrameViews that need
3452     // layout and make sure they are up to date.
3453     // Mac actually tests for intersection with the dirty region and tries not to
3454     // update layout for frames that are outside the dirty region.  Not only does this seem
3455     // pointless (since those frames will have set a zero timer to layout anyway), but
3456     // it is also incorrect, since if two frames overlap, the first could be excluded from the dirty
3457     // region but then become included later by the second frame adding rects to the dirty region
3458     // when it lays out.
3459
3460     m_frame->document()->updateStyleIfNeeded();
3461
3462     if (needsLayout())
3463         layout();
3464
3465     // Grab a copy of the children() set, as it may be mutated by the following updateLayoutAndStyleIfNeededRecursive
3466     // calls, as they can potentially re-enter a layout of the parent frame view, which may add/remove scrollbars
3467     // and thus mutates the children() set.
3468     Vector<RefPtr<FrameView> > frameViews;
3469     collectFrameViewChildren(this, frameViews);
3470
3471     const Vector<RefPtr<FrameView> >::iterator end = frameViews.end();
3472     for (Vector<RefPtr<FrameView> >::iterator it = frameViews.begin(); it != end; ++it)
3473         (*it)->updateLayoutAndStyleIfNeededRecursive();
3474
3475     // updateLayoutAndStyleIfNeededRecursive is called when we need to make sure style and layout are up-to-date before
3476     // painting, so we need to flush out any deferred repaints too.
3477     flushDeferredRepaints();
3478
3479     // When frame flattening is on, child frame can mark parent frame dirty. In such case, child frame
3480     // needs to call layout on parent frame recursively.
3481     // This assert ensures that parent frames are clean, when child frames finished updating layout and style.
3482     ASSERT(!needsLayout());
3483 }
3484
3485 void FrameView::enableAutoSizeMode(bool enable, const IntSize& minSize, const IntSize& maxSize)
3486 {
3487     ASSERT(!enable || !minSize.isEmpty());
3488     ASSERT(minSize.width() <= maxSize.width());
3489     ASSERT(minSize.height() <= maxSize.height());
3490
3491     if (m_shouldAutoSize == enable && m_minAutoSize == minSize && m_maxAutoSize == maxSize)
3492         return;
3493
3494     m_shouldAutoSize = enable;
3495     m_minAutoSize = minSize;
3496     m_maxAutoSize = maxSize;
3497     m_didRunAutosize = false;
3498
3499     setNeedsLayout();
3500     scheduleRelayout();
3501     if (m_shouldAutoSize)
3502         return;
3503
3504     // Since autosize mode forces the scrollbar mode, change them to being auto.
3505     setVerticalScrollbarLock(false);
3506     setHorizontalScrollbarLock(false);
3507     setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
3508 }
3509
3510 void FrameView::forceLayout(bool allowSubtree)
3511 {
3512     layout(allowSubtree);
3513 }
3514
3515 void FrameView::forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot shouldAdjustViewSize)
3516 {
3517     // Dumping externalRepresentation(m_frame->renderer()).ascii() is a good trick to see
3518     // the state of things before and after the layout
3519     if (RenderView* root = rootRenderer(this)) {
3520         float pageLogicalWidth = root->style()->isHorizontalWritingMode() ? pageSize.width() : pageSize.height();
3521         float pageLogicalHeight = root->style()->isHorizontalWritingMode() ? pageSize.height() : pageSize.width();
3522
3523         LayoutUnit flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
3524         LayoutUnit flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
3525         root->setLogicalWidth(flooredPageLogicalWidth);
3526         root->setPageLogicalHeight(flooredPageLogicalHeight);
3527         root->setNeedsLayoutAndPrefWidthsRecalc();
3528         forceLayout();
3529
3530         // If we don't fit in the given page width, we'll lay out again. If we don't fit in the
3531         // page width when shrunk, we will lay out at maximum shrink and clip extra content.
3532         // FIXME: We are assuming a shrink-to-fit printing implementation.  A cropping
3533         // implementation should not do this!
3534         bool horizontalWritingMode = root->style()->isHorizontalWritingMode();
3535         const LayoutRect& documentRect = root->documentRect();
3536         LayoutUnit docLogicalWidth = horizontalWritingMode ? documentRect.width() : documentRect.height();
3537         if (docLogicalWidth > pageLogicalWidth) {
3538             int expectedPageWidth = std::min<float>(documentRect.width(), pageSize.width() * maximumShrinkFactor);
3539             int expectedPageHeight = std::min<float>(documentRect.height(), pageSize.height() * maximumShrinkFactor);
3540             FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(originalPageSize.width(), originalPageSize.height()), FloatSize(expectedPageWidth, expectedPageHeight));
3541             pageLogicalWidth = horizontalWritingMode ? maxPageSize.width() : maxPageSize.height();
3542             pageLogicalHeight = horizontalWritingMode ? maxPageSize.height() : maxPageSize.width();
3543
3544             flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
3545             flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
3546             root->setLogicalWidth(flooredPageLogicalWidth);
3547             root->setPageLogicalHeight(flooredPageLogicalHeight);
3548             root->setNeedsLayoutAndPrefWidthsRecalc();
3549             forceLayout();
3550
3551             const LayoutRect& updatedDocumentRect = root->documentRect();
3552             LayoutUnit docLogicalHeight = horizontalWritingMode ? updatedDocumentRect.height() : updatedDocumentRect.width();
3553             LayoutUnit docLogicalTop = horizontalWritingMode ? updatedDocumentRect.y() : updatedDocumentRect.x();
3554             LayoutUnit docLogicalRight = horizontalWritingMode ? updatedDocumentRect.maxX() : updatedDocumentRect.maxY();
3555             LayoutUnit clippedLogicalLeft = 0;
3556             if (!root->style()->isLeftToRightDirection())
3557                 clippedLogicalLeft = docLogicalRight - pageLogicalWidth;
3558             LayoutRect overflow(clippedLogicalLeft, docLogicalTop, pageLogicalWidth, docLogicalHeight);
3559
3560             if (!horizontalWritingMode)
3561                 overflow = overflow.transposedRect();
3562             root->clearLayoutOverflow();
3563             root->addLayoutOverflow(overflow); // This is how we clip in case we overflow again.
3564         }
3565     }
3566
3567     if (shouldAdjustViewSize)
3568         adjustViewSize();
3569 }
3570
3571 void FrameView::adjustPageHeightDeprecated(float *newBottom, float oldTop, float oldBottom, float /*bottomLimit*/)
3572 {
3573     if (RenderView* root = rootRenderer(this)) {
3574         // Use a context with painting disabled.
3575         GraphicsContext context((PlatformGraphicsContext*)0);
3576         root->setTruncatedAt(static_cast<int>(floorf(oldBottom)));
3577         IntRect dirtyRect(0, static_cast<int>(floorf(oldTop)), root->layoutOverflowRect().maxX(), static_cast<int>(ceilf(oldBottom - oldTop)));
3578         root->setPrintRect(dirtyRect);
3579         root->layer()->paint(&context, dirtyRect);
3580         *newBottom = root->bestTruncatedAt();
3581         if (*newBottom == 0)
3582             *newBottom = oldBottom;
3583         root->setPrintRect(IntRect());
3584     } else
3585         *newBottom = oldBottom;
3586 }
3587
3588 IntRect FrameView::convertFromRenderer(const RenderObject* renderer, const IntRect& rendererRect) const
3589 {
3590     IntRect rect = pixelSnappedIntRect(enclosingLayoutRect(renderer->localToAbsoluteQuad(FloatRect(rendererRect)).boundingBox()));
3591
3592     // Convert from page ("absolute") to FrameView coordinates.
3593     if (!delegatesScrolling())
3594         rect.moveBy(-scrollPosition());