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