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