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