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