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