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