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