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