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