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