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