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