6ed0daf55689e86ef68f0cce597b60dc6cca3a3c
[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 "CSSStyleSelector.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 "Frame.h"
40 #include "FrameLoader.h"
41 #include "FrameLoaderClient.h"
42 #include "FrameTree.h"
43 #include "GraphicsContext.h"
44 #include "HTMLDocument.h"
45 #include "HTMLFrameElement.h"
46 #include "HTMLFrameSetElement.h"
47 #include "HTMLNames.h"
48 #include "HTMLPlugInImageElement.h"
49 #include "InspectorInstrumentation.h"
50 #include "OverflowEvent.h"
51 #include "RenderEmbeddedObject.h"
52 #include "RenderFullScreen.h"
53 #include "RenderLayer.h"
54 #include "RenderPart.h"
55 #include "RenderScrollbar.h"
56 #include "RenderScrollbarPart.h"
57 #include "RenderTheme.h"
58 #include "RenderView.h"
59 #include "Settings.h"
60 #include "TextResourceDecoder.h"
61 #include <wtf/CurrentTime.h>
62
63 #if USE(ACCELERATED_COMPOSITING)
64 #include "RenderLayerCompositor.h"
65 #endif
66
67 #if ENABLE(SVG)
68 #include "SVGDocument.h"
69 #include "SVGLocatable.h"
70 #include "SVGNames.h"
71 #include "SVGPreserveAspectRatio.h"
72 #include "SVGSVGElement.h"
73 #include "SVGViewElement.h"
74 #include "SVGViewSpec.h"
75 #endif
76
77 #if ENABLE(TILED_BACKING_STORE)
78 #include "TiledBackingStore.h"
79 #endif
80
81 namespace WebCore {
82
83 using namespace HTMLNames;
84
85 double FrameView::sCurrentPaintTimeStamp = 0.0;
86
87 // REPAINT_THROTTLING now chooses default values for throttling parameters.
88 // Should be removed when applications start using runtime configuration.
89 #if ENABLE(REPAINT_THROTTLING)
90 // Normal delay
91 double FrameView::s_deferredRepaintDelay = 0.025;
92 // Negative value would mean that first few repaints happen without a delay
93 double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
94 // The delay grows on each repaint to this maximum value
95 double FrameView::s_maxDeferredRepaintDelayDuringLoading = 2.5;
96 // On each repaint the delay increses by this amount
97 double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0.5;
98 #else
99 // FIXME: Repaint throttling could be good to have on all platform.
100 // The balance between CPU use and repaint frequency will need some tuning for desktop.
101 // More hooks may be needed to reset the delay on things like GIF and CSS animations.
102 double FrameView::s_deferredRepaintDelay = 0;
103 double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
104 double FrameView::s_maxDeferredRepaintDelayDuringLoading = 0;
105 double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0;
106 #endif
107
108 // The maximum number of updateWidgets iterations that should be done before returning.
109 static const unsigned maxUpdateWidgetsIterations = 2;
110
111 struct ScheduledEvent : Noncopyable {
112     RefPtr<Event> m_event;
113     RefPtr<Node> m_eventTarget;
114 };
115
116 FrameView::FrameView(Frame* frame)
117     : m_frame(frame)
118     , m_canHaveScrollbars(true)
119     , m_slowRepaintObjectCount(0)
120     , m_fixedObjectCount(0)
121     , m_layoutTimer(this, &FrameView::layoutTimerFired)
122     , m_layoutRoot(0)
123     , m_hasPendingPostLayoutTasks(false)
124     , m_inSynchronousPostLayout(false)
125     , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
126     , m_isTransparent(false)
127     , m_baseBackgroundColor(Color::white)
128     , m_mediaType("screen")
129     , m_enqueueEvents(0)
130     , m_overflowStatusDirty(true)
131     , m_viewportRenderer(0)
132     , m_wasScrolledByUser(false)
133     , m_inProgrammaticScroll(false)
134     , m_deferredRepaintTimer(this, &FrameView::deferredRepaintTimerFired)
135     , m_shouldUpdateWhileOffscreen(true)
136     , m_deferSetNeedsLayouts(0)
137     , m_setNeedsLayoutWasDeferred(false)
138     , m_scrollCorner(0)
139 {
140     init();
141 }
142
143 PassRefPtr<FrameView> FrameView::create(Frame* frame)
144 {
145     RefPtr<FrameView> view = adoptRef(new FrameView(frame));
146     view->show();
147     return view.release();
148 }
149
150 PassRefPtr<FrameView> FrameView::create(Frame* frame, const IntSize& initialSize)
151 {
152     RefPtr<FrameView> view = adoptRef(new FrameView(frame));
153     view->Widget::setFrameRect(IntRect(view->pos(), initialSize));
154     view->show();
155     return view.release();
156 }
157
158 FrameView::~FrameView()
159 {
160     if (m_hasPendingPostLayoutTasks) {
161         m_postLayoutTasksTimer.stop();
162         m_scheduledEvents.clear();
163         m_enqueueEvents = 0;
164     }
165     
166     if (AXObjectCache::accessibilityEnabled() && axObjectCache())
167         axObjectCache()->remove(this);
168     
169     resetScrollbars();
170
171     // Custom scrollbars should already be destroyed at this point
172     ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
173     ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
174
175     setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
176     setHasVerticalScrollbar(false);
177     
178     ASSERT(!m_scrollCorner);
179     ASSERT(m_scheduledEvents.isEmpty());
180     ASSERT(!m_enqueueEvents);
181
182     if (m_frame) {
183         ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
184         RenderPart* renderer = m_frame->ownerRenderer();
185         if (renderer && renderer->widget() == this)
186             renderer->setWidget(0);
187     }
188 }
189
190 void FrameView::reset()
191 {
192     m_useSlowRepaints = false;
193     m_isOverlapped = false;
194     m_contentIsOpaque = false;
195     m_borderX = 30;
196     m_borderY = 30;
197     m_layoutTimer.stop();
198     m_layoutRoot = 0;
199     m_delayedLayout = false;
200     m_doFullRepaint = true;
201     m_layoutSchedulingEnabled = true;
202     m_inLayout = false;
203     m_inSynchronousPostLayout = false;
204     m_hasPendingPostLayoutTasks = false;
205     m_layoutCount = 0;
206     m_nestedLayoutCount = 0;
207     m_postLayoutTasksTimer.stop();
208     m_firstLayout = true;
209     m_firstLayoutCallbackPending = false;
210     m_wasScrolledByUser = false;
211     m_lastLayoutSize = IntSize();
212     m_lastZoomFactor = 1.0f;
213     m_deferringRepaints = 0;
214     m_repaintCount = 0;
215     m_repaintRects.clear();
216     m_deferredRepaintDelay = s_initialDeferredRepaintDelayDuringLoading;
217     m_deferredRepaintTimer.stop();
218     m_lastPaintTime = 0;
219     m_paintBehavior = PaintBehaviorNormal;
220     m_isPainting = false;
221     m_isVisuallyNonEmpty = false;
222     m_firstVisuallyNonEmptyLayoutCallbackPending = true;
223     m_maintainScrollPositionAnchor = 0;
224 }
225
226 bool FrameView::isFrameView() const 
227
228     return true; 
229 }
230
231 void FrameView::clearFrame()
232 {
233     m_frame = 0;
234 }
235
236 void FrameView::resetScrollbars()
237 {
238     // Reset the document's scrollbars back to our defaults before we yield the floor.
239     m_firstLayout = true;
240     setScrollbarsSuppressed(true);
241     if (m_canHaveScrollbars)
242         setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
243     else
244         setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
245     setScrollbarsSuppressed(false);
246 }
247
248 void FrameView::init()
249 {
250     reset();
251
252     m_margins = IntSize(-1, -1); // undefined
253     m_size = IntSize();
254
255     // Propagate the marginwidth/height and scrolling modes to the view.
256     Element* ownerElement = m_frame && m_frame->document() ? m_frame->document()->ownerElement() : 0;
257     if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
258         HTMLFrameElement* frameElt = static_cast<HTMLFrameElement*>(ownerElement);
259         if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
260             setCanHaveScrollbars(false);
261         int marginWidth = frameElt->marginWidth();
262         int marginHeight = frameElt->marginHeight();
263         if (marginWidth != -1)
264             setMarginWidth(marginWidth);
265         if (marginHeight != -1)
266             setMarginHeight(marginHeight);
267     }
268 }
269
270 void FrameView::detachCustomScrollbars()
271 {
272     if (!m_frame)
273         return;
274
275     Scrollbar* horizontalBar = horizontalScrollbar();
276     if (horizontalBar && horizontalBar->isCustomScrollbar())
277         setHasHorizontalScrollbar(false);
278
279     Scrollbar* verticalBar = verticalScrollbar();
280     if (verticalBar && verticalBar->isCustomScrollbar())
281         setHasVerticalScrollbar(false);
282
283     if (m_scrollCorner) {
284         m_scrollCorner->destroy();
285         m_scrollCorner = 0;
286     }
287 }
288
289 void FrameView::clear()
290 {
291     setCanBlitOnScroll(true);
292     
293     reset();
294
295     if (m_frame) {
296         if (RenderPart* renderer = m_frame->ownerRenderer())
297             renderer->viewCleared();
298     }
299
300     setScrollbarsSuppressed(true);
301 }
302
303 bool FrameView::didFirstLayout() const
304 {
305     return !m_firstLayout;
306 }
307
308 void FrameView::invalidateRect(const IntRect& rect)
309 {
310     if (!parent()) {
311         if (hostWindow() && shouldUpdate())
312             hostWindow()->invalidateContentsAndWindow(rect, false /*immediate*/);
313         return;
314     }
315
316     if (!m_frame)
317         return;
318
319     RenderPart* renderer = m_frame->ownerRenderer();
320     if (!renderer)
321         return;
322
323     IntRect repaintRect = rect;
324     repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
325                      renderer->borderTop() + renderer->paddingTop());
326     renderer->repaintRectangle(repaintRect);
327 }
328
329 void FrameView::setFrameRect(const IntRect& newRect)
330 {
331     IntRect oldRect = frameRect();
332     if (newRect == oldRect)
333         return;
334
335     ScrollView::setFrameRect(newRect);
336
337 #if USE(ACCELERATED_COMPOSITING)
338     if (RenderView* root = m_frame->contentRenderer()) {
339         if (root->usesCompositing())
340             root->compositor()->frameViewDidChangeSize();
341     }
342 #endif
343 }
344
345 #if ENABLE(REQUEST_ANIMATION_FRAME)
346 void FrameView::scheduleAnimation()
347 {
348     if (hostWindow())
349         hostWindow()->scheduleAnimation();
350 }
351 #endif
352
353 void FrameView::setMarginWidth(int w)
354 {
355     // make it update the rendering area when set
356     m_margins.setWidth(w);
357 }
358
359 void FrameView::setMarginHeight(int h)
360 {
361     // make it update the rendering area when set
362     m_margins.setHeight(h);
363 }
364
365 bool FrameView::avoidScrollbarCreation() const
366 {
367     ASSERT(m_frame);
368
369     // with frame flattening no subframe can have scrollbars
370     // but we also cannot turn scrollbars of as we determine
371     // our flattening policy using that.
372
373     if (!m_frame->ownerElement())
374         return false;
375
376     if (!m_frame->settings() || m_frame->settings()->frameFlatteningEnabled())
377         return true;
378
379     return false;
380 }
381
382 void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
383 {
384     m_canHaveScrollbars = canHaveScrollbars;
385     ScrollView::setCanHaveScrollbars(canHaveScrollbars);
386 }
387
388 void FrameView::updateCanHaveScrollbars()
389 {
390     ScrollbarMode hMode;
391     ScrollbarMode vMode;
392     scrollbarModes(hMode, vMode);
393     if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
394         setCanHaveScrollbars(false);
395     else
396         setCanHaveScrollbars(true);
397 }
398
399 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
400 {
401     // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
402     Document* doc = m_frame->document();
403
404     // Try the <body> element first as a scrollbar source.
405     Element* body = doc ? doc->body() : 0;
406     if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR))
407         return RenderScrollbar::createCustomScrollbar(this, orientation, body->renderer()->enclosingBox());
408     
409     // If the <body> didn't have a custom style, then the root element might.
410     Element* docElement = doc ? doc->documentElement() : 0;
411     if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR))
412         return RenderScrollbar::createCustomScrollbar(this, orientation, docElement->renderBox());
413         
414     // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
415     RenderPart* frameRenderer = m_frame->ownerRenderer();
416     if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR))
417         return RenderScrollbar::createCustomScrollbar(this, orientation, 0, m_frame.get());
418     
419     // Nobody set a custom style, so we just use a native scrollbar.
420     return ScrollView::createScrollbar(orientation);
421 }
422
423 void FrameView::setContentsSize(const IntSize& size)
424 {
425     if (size == contentsSize())
426         return;
427
428     m_deferSetNeedsLayouts++;
429
430     ScrollView::setContentsSize(size);
431
432     Page* page = frame() ? frame()->page() : 0;
433     if (!page)
434         return;
435
436     page->chrome()->contentsSizeChanged(frame(), size); //notify only
437
438     m_deferSetNeedsLayouts--;
439     
440     if (!m_deferSetNeedsLayouts)
441         m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
442 }
443
444 void FrameView::adjustViewSize()
445 {
446     ASSERT(m_frame->view() == this);
447     RenderView* root = m_frame->contentRenderer();
448     if (!root)
449         return;
450
451     IntSize size = IntSize(root->docWidth(), root->docHeight());
452
453     ScrollView::setScrollOrigin(IntPoint(-root->docLeft(), -root->docTop()), size == contentsSize());
454     
455     setContentsSize(size);
456 }
457
458 void FrameView::applyOverflowToViewport(RenderObject* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
459 {
460     // Handle the overflow:hidden/scroll case for the body/html elements.  WinIE treats
461     // overflow:hidden and overflow:scroll on <body> as applying to the document's
462     // scrollbars.  The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
463     // use the root element.
464     switch (o->style()->overflowX()) {
465         case OHIDDEN:
466             hMode = ScrollbarAlwaysOff;
467             break;
468         case OSCROLL:
469             hMode = ScrollbarAlwaysOn;
470             break;
471         case OAUTO:
472             hMode = ScrollbarAuto;
473             break;
474         default:
475             // Don't set it at all.
476             ;
477     }
478     
479      switch (o->style()->overflowY()) {
480         case OHIDDEN:
481             vMode = ScrollbarAlwaysOff;
482             break;
483         case OSCROLL:
484             vMode = ScrollbarAlwaysOn;
485             break;
486         case OAUTO:
487             vMode = ScrollbarAuto;
488             break;
489         default:
490             // Don't set it at all.
491             ;
492     }
493
494     m_viewportRenderer = o;
495 }
496
497 void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode)
498 {
499     const HTMLFrameOwnerElement* owner = m_frame->ownerElement();
500     if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
501         hMode = ScrollbarAlwaysOff;
502         vMode = ScrollbarAlwaysOff;
503         return;
504     }  
505     
506     if (m_canHaveScrollbars) {
507         hMode = ScrollbarAuto;
508         vMode = ScrollbarAuto;
509     } else {
510         hMode = ScrollbarAlwaysOff;
511         vMode = ScrollbarAlwaysOff;
512     }
513     
514     if (!m_layoutRoot) {
515         Document* document = m_frame->document();
516         Node* documentElement = document->documentElement();
517         RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0;
518         Node* body = document->body();
519         if (body && body->renderer()) {
520             if (body->hasTagName(framesetTag) && m_frame->settings() && !m_frame->settings()->frameFlatteningEnabled()) {
521                 vMode = ScrollbarAlwaysOff;
522                 hMode = ScrollbarAlwaysOff;
523             } else if (body->hasTagName(bodyTag)) {
524                 // It's sufficient to just check the X overflow,
525                 // since it's illegal to have visible in only one direction.
526                 RenderObject* o = rootRenderer->style()->overflowX() == OVISIBLE && document->documentElement()->hasTagName(htmlTag) ? body->renderer() : rootRenderer;
527                 applyOverflowToViewport(o, hMode, vMode);
528             }
529         } else if (rootRenderer) {
530 #if ENABLE(SVG)
531             if (!documentElement->isSVGElement())
532                 applyOverflowToViewport(rootRenderer, hMode, vMode);
533 #else
534             applyOverflowToViewport(rootRenderer, hMode, vMode);
535 #endif
536         }
537     }    
538 }
539
540 #if ENABLE(FULLSCREEN_API) && USE(ACCELERATED_COMPOSITING)
541 static bool isDocumentRunningFullScreenAnimation(Document* document)
542 {
543     return document->webkitIsFullScreen() && document->fullScreenRenderer() && document->fullScreenRenderer()->isAnimating();
544 }
545 #endif
546     
547 #if USE(ACCELERATED_COMPOSITING)
548 void FrameView::updateCompositingLayers()
549 {
550     RenderView* view = m_frame->contentRenderer();
551     if (!view)
552         return;
553
554     // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
555     view->compositor()->cacheAcceleratedCompositingFlags();
556     view->compositor()->updateCompositingLayers(CompositingUpdateAfterLayoutOrStyleChange);
557     
558 #if ENABLE(FULLSCREEN_API)
559     Document* document = m_frame->document();
560     if (isDocumentRunningFullScreenAnimation(document))
561         view->compositor()->updateCompositingLayers(CompositingUpdateAfterLayoutOrStyleChange, document->fullScreenRenderer()->layer());
562 #endif
563 }
564
565 bool FrameView::syncCompositingStateForThisFrame()
566 {
567     ASSERT(m_frame->view() == this);
568     RenderView* view = m_frame->contentRenderer();
569     if (!view)
570         return true; // We don't want to keep trying to update layers if we have no renderer.
571
572     // If we sync compositing layers when a layout is pending, we may cause painting of compositing
573     // layer content to occur before layout has happened, which will cause paintContents() to bail.
574     if (needsLayout())
575         return false;
576
577     view->compositor()->flushPendingLayerChanges();
578
579 #if ENABLE(FULLSCREEN_API)
580     // The fullScreenRenderer's graphicsLayer  has been re-parented, and the above recursive syncCompositingState
581     // call will not cause the subtree under it to repaint.  Explicitly call the syncCompositingState on 
582     // the fullScreenRenderer's graphicsLayer here:
583     Document* document = m_frame->document();
584     if (isDocumentRunningFullScreenAnimation(document)) {
585         RenderLayerBacking* backing = document->fullScreenRenderer()->layer()->backing();
586         if (GraphicsLayer* fullScreenLayer = backing->graphicsLayer())
587             fullScreenLayer->syncCompositingState();
588     }
589 #endif
590     return true;
591 }
592
593 void FrameView::setNeedsOneShotDrawingSynchronization()
594 {
595     Page* page = frame() ? frame()->page() : 0;
596     if (page)
597         page->chrome()->client()->setNeedsOneShotDrawingSynchronization();
598 }
599
600 #endif // USE(ACCELERATED_COMPOSITING)
601
602 bool FrameView::hasCompositedContent() const
603 {
604 #if USE(ACCELERATED_COMPOSITING)
605     if (RenderView* view = m_frame->contentRenderer())
606         return view->compositor()->inCompositingMode();
607 #endif
608     return false;
609 }
610
611 bool FrameView::hasCompositedContentIncludingDescendants() const
612 {
613 #if USE(ACCELERATED_COMPOSITING)
614     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
615         RenderView* renderView = frame->contentRenderer();
616         RenderLayerCompositor* compositor = renderView ? renderView->compositor() : 0;
617         if (compositor) {
618             if (compositor->inCompositingMode())
619                 return true;
620
621             if (!RenderLayerCompositor::allowsIndependentlyCompositedIFrames(this))
622                 break;
623         }
624     }
625 #endif
626     return false;
627 }
628
629 bool FrameView::hasCompositingAncestor() const
630 {
631 #if USE(ACCELERATED_COMPOSITING)
632     for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent()) {
633         if (FrameView* view = frame->view()) {
634             if (view->hasCompositedContent())
635                 return true;
636         }
637     }
638 #endif
639     return false;
640 }
641
642 // Sometimes (for plug-ins) we need to eagerly go into compositing mode.
643 void FrameView::enterCompositingMode()
644 {
645 #if USE(ACCELERATED_COMPOSITING)
646     if (RenderView* view = m_frame->contentRenderer()) {
647         view->compositor()->enableCompositingMode();
648         if (!needsLayout())
649             view->compositor()->scheduleCompositingLayerUpdate();
650     }
651 #endif
652 }
653
654 bool FrameView::isEnclosedInCompositingLayer() const
655 {
656 #if USE(ACCELERATED_COMPOSITING)
657     RenderObject* frameOwnerRenderer = m_frame->ownerRenderer();
658     if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
659         return true;
660
661     if (Frame* parentFrame = m_frame->tree()->parent()) {
662         if (FrameView* parentView = parentFrame->view())
663             return parentView->isEnclosedInCompositingLayer();
664     }
665 #endif
666     return false;
667 }
668     
669 bool FrameView::syncCompositingStateIncludingSubframes()
670 {
671 #if USE(ACCELERATED_COMPOSITING)
672     bool allFramesSynced = syncCompositingStateForThisFrame();
673     
674     for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame.get())) {
675         bool synced = child->view()->syncCompositingStateForThisFrame();
676         allFramesSynced &= synced;
677     }
678     return allFramesSynced;
679 #else // USE(ACCELERATED_COMPOSITING)
680     return true;
681 #endif
682 }
683
684 bool FrameView::isSoftwareRenderable() const
685 {
686 #if USE(ACCELERATED_COMPOSITING)
687     RenderView* view = m_frame->contentRenderer();
688     if (!view)
689         return true;
690
691     return !view->compositor()->has3DContent();
692 #else
693     return true;
694 #endif
695 }
696
697 void FrameView::didMoveOnscreen()
698 {
699     RenderView* view = m_frame->contentRenderer();
700     if (view)
701         view->didMoveOnscreen();
702 }
703
704 void FrameView::willMoveOffscreen()
705 {
706     RenderView* view = m_frame->contentRenderer();
707     if (view)
708         view->willMoveOffscreen();
709 }
710
711 RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
712 {
713     return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
714 }
715
716 void FrameView::layout(bool allowSubtree)
717 {
718     if (m_inLayout)
719         return;
720
721     m_layoutTimer.stop();
722     m_delayedLayout = false;
723     m_setNeedsLayoutWasDeferred = false;
724
725     // Protect the view from being deleted during layout (in recalcStyle)
726     RefPtr<FrameView> protector(this);
727
728     if (!m_frame) {
729         // FIXME: Do we need to set m_size.width here?
730         // FIXME: Should we set m_size.height here too?
731         m_size.setWidth(layoutWidth());
732         return;
733     }
734     
735     // we shouldn't enter layout() while painting
736     ASSERT(!isPainting());
737     if (isPainting())
738         return;
739
740     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(m_frame.get());
741
742     if (!allowSubtree && m_layoutRoot) {
743         m_layoutRoot->markContainingBlocksForLayout(false);
744         m_layoutRoot = 0;
745     }
746
747     ASSERT(m_frame->view() == this);
748
749     Document* document = m_frame->document();
750
751     m_layoutSchedulingEnabled = false;
752
753     if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_hasPendingPostLayoutTasks) {
754         // This is a new top-level layout. If there are any remaining tasks from the previous
755         // layout, finish them now.
756         m_inSynchronousPostLayout = true;
757         m_postLayoutTasksTimer.stop();
758         performPostLayoutTasks();
759         m_inSynchronousPostLayout = false;
760     }
761
762     // Viewport-dependent media queries may cause us to need completely different style information.
763     // Check that here.
764     if (document->styleSelector()->affectedByViewportChange())
765         document->styleSelectorChanged(RecalcStyleImmediately);
766
767     // Always ensure our style info is up-to-date.  This can happen in situations where
768     // the layout beats any sort of style recalc update that needs to occur.
769     document->updateStyleIfNeeded();
770     
771     bool subtree = m_layoutRoot;
772
773     // If there is only one ref to this view left, then its going to be destroyed as soon as we exit, 
774     // so there's no point to continuing to layout
775     if (protector->hasOneRef())
776         return;
777
778     RenderObject* root = subtree ? m_layoutRoot : document->renderer();
779     if (!root) {
780         // FIXME: Do we need to set m_size here?
781         m_layoutSchedulingEnabled = true;
782         return;
783     }
784
785     m_nestedLayoutCount++;
786
787     if (!m_layoutRoot) {
788         Document* document = m_frame->document();
789         Node* documentElement = document->documentElement();
790         RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0;
791         Node* body = document->body();
792         if (body && body->renderer()) {
793             if (body->hasTagName(framesetTag) && m_frame->settings() && !m_frame->settings()->frameFlatteningEnabled()) {
794                 body->renderer()->setChildNeedsLayout(true);
795             } else if (body->hasTagName(bodyTag)) {
796                 if (!m_firstLayout && m_size.height() != layoutHeight() && body->renderer()->enclosingBox()->stretchesToViewport())
797                     body->renderer()->setChildNeedsLayout(true);
798             }
799         } else if (rootRenderer) {
800 #if ENABLE(SVG)
801             if (documentElement->isSVGElement()) {
802                 if (!m_firstLayout && (m_size.width() != layoutWidth() || m_size.height() != layoutHeight()))
803                     rootRenderer->setChildNeedsLayout(true);
804             }
805 #endif
806         }
807         
808 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
809         if (m_firstLayout && !document->ownerElement())
810             printf("Elapsed time before first layout: %d\n", document->elapsedTime());
811 #endif        
812     }
813     
814     ScrollbarMode hMode;
815     ScrollbarMode vMode;    
816     calculateScrollbarModesForLayout(hMode, vMode);
817
818     m_doFullRepaint = !subtree && (m_firstLayout || toRenderView(root)->printing());
819
820     if (!subtree) {
821         // Now set our scrollbar state for the layout.
822         ScrollbarMode currentHMode = horizontalScrollbarMode();
823         ScrollbarMode currentVMode = verticalScrollbarMode();
824
825         if (m_firstLayout || (hMode != currentHMode || vMode != currentVMode)) {
826             if (m_firstLayout) {
827                 setScrollbarsSuppressed(true);
828
829                 m_firstLayout = false;
830                 m_firstLayoutCallbackPending = true;
831                 m_lastLayoutSize = IntSize(width(), height());
832                 m_lastZoomFactor = root->style()->zoom();
833
834                 // Set the initial vMode to AlwaysOn if we're auto.
835                 if (vMode == ScrollbarAuto)
836                     setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
837                 // Set the initial hMode to AlwaysOff if we're auto.
838                 if (hMode == ScrollbarAuto)
839                     setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
840
841                 setScrollbarModes(hMode, vMode);
842                 setScrollbarsSuppressed(false, true);
843             } else
844                 setScrollbarModes(hMode, vMode);
845         }
846
847         IntSize oldSize = m_size;
848
849         m_size = IntSize(layoutWidth(), layoutHeight());
850
851         if (oldSize != m_size) {
852             m_doFullRepaint = true;
853             if (!m_firstLayout) {
854                 RenderBox* rootRenderer = document->documentElement() ? document->documentElement()->renderBox() : 0;
855                 RenderBox* bodyRenderer = rootRenderer && document->body() ? document->body()->renderBox() : 0;
856                 if (bodyRenderer && bodyRenderer->stretchesToViewport())
857                     bodyRenderer->setChildNeedsLayout(true);
858                 else if (rootRenderer && rootRenderer->stretchesToViewport())
859                     rootRenderer->setChildNeedsLayout(true);
860             }
861         }
862     }
863
864     RenderLayer* layer = root->enclosingLayer();
865
866     pauseScheduledEvents();
867
868     bool disableLayoutState = false;
869     if (subtree) {
870         RenderView* view = root->view();
871         disableLayoutState = view->shouldDisableLayoutStateForSubtree(root);
872         view->pushLayoutState(root);
873         if (disableLayoutState)
874             view->disableLayoutState();
875     }
876         
877     m_inLayout = true;
878     beginDeferredRepaints();
879     root->layout();
880     endDeferredRepaints();
881     m_inLayout = false;
882
883     if (subtree) {
884         RenderView* view = root->view();
885         view->popLayoutState(root);
886         if (disableLayoutState)
887             view->enableLayoutState();
888     }
889     m_layoutRoot = 0;
890
891     m_frame->selection()->setCaretRectNeedsUpdate();
892     m_frame->selection()->updateAppearance();
893    
894     m_layoutSchedulingEnabled = true;
895
896     if (!subtree && !toRenderView(root)->printing())
897         adjustViewSize();
898
899     // Now update the positions of all layers.
900     beginDeferredRepaints();
901     IntPoint cachedOffset;
902     layer->updateLayerPositions((m_doFullRepaint ? RenderLayer::DoFullRepaint : 0)
903                                 | RenderLayer::CheckForRepaint
904                                 | RenderLayer::IsCompositingUpdateRoot
905                                 | RenderLayer::UpdateCompositingLayers,
906                                 subtree ? 0 : &cachedOffset);
907     endDeferredRepaints();
908
909 #if USE(ACCELERATED_COMPOSITING)
910     updateCompositingLayers();
911 #endif
912     
913     m_layoutCount++;
914
915 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
916     if (AXObjectCache::accessibilityEnabled())
917         root->document()->axObjectCache()->postNotification(root, AXObjectCache::AXLayoutComplete, true);
918 #endif
919 #if ENABLE(DASHBOARD_SUPPORT)
920     updateDashboardRegions();
921 #endif
922
923     ASSERT(!root->needsLayout());
924
925     updateCanBlitOnScrollRecursively();
926
927     if (document->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
928         updateOverflowStatus(layoutWidth() < contentsWidth(),
929                              layoutHeight() < contentsHeight());
930
931     if (!m_hasPendingPostLayoutTasks) {
932         if (!m_inSynchronousPostLayout) {
933             m_inSynchronousPostLayout = true;
934             // Calls resumeScheduledEvents()
935             performPostLayoutTasks();
936             m_inSynchronousPostLayout = false;
937         }
938
939         if (!m_hasPendingPostLayoutTasks && (needsLayout() || m_inSynchronousPostLayout)) {
940             // If we need layout or are already in a synchronous call to postLayoutTasks(), 
941             // defer widget updates and event dispatch until after we return. postLayoutTasks()
942             // can make us need to update again, and we can get stuck in a nasty cycle unless
943             // we call it through the timer here.
944             m_hasPendingPostLayoutTasks = true;
945             m_postLayoutTasksTimer.startOneShot(0);
946             if (needsLayout()) {
947                 pauseScheduledEvents();
948                 layout();
949             }
950         }
951     } else {
952         resumeScheduledEvents();
953         ASSERT(m_enqueueEvents);
954     }
955
956     InspectorInstrumentation::didLayout(cookie);
957
958     m_nestedLayoutCount--;
959 }
960
961 void FrameView::addWidgetToUpdate(RenderEmbeddedObject* object)
962 {
963     if (!m_widgetUpdateSet)
964         m_widgetUpdateSet.set(new RenderEmbeddedObjectSet);
965
966     m_widgetUpdateSet->add(object);
967 }
968
969 void FrameView::removeWidgetToUpdate(RenderEmbeddedObject* object)
970 {
971     if (!m_widgetUpdateSet)
972         return;
973
974     m_widgetUpdateSet->remove(object);
975 }
976
977 void FrameView::setMediaType(const String& mediaType)
978 {
979     m_mediaType = mediaType;
980 }
981
982 String FrameView::mediaType() const
983 {
984     // See if we have an override type.
985     String overrideType = m_frame->loader()->client()->overrideMediaType();
986     if (!overrideType.isNull())
987         return overrideType;
988     return m_mediaType;
989 }
990
991 void FrameView::adjustMediaTypeForPrinting(bool printing)
992 {
993     if (printing) {
994         if (m_mediaTypeWhenNotPrinting.isNull())
995             m_mediaTypeWhenNotPrinting = mediaType();
996             setMediaType("print");
997     } else {
998         if (!m_mediaTypeWhenNotPrinting.isNull())
999             setMediaType(m_mediaTypeWhenNotPrinting);
1000         m_mediaTypeWhenNotPrinting = String();
1001     }
1002 }
1003
1004 bool FrameView::useSlowRepaints() const
1005 {
1006     if (m_useSlowRepaints || m_slowRepaintObjectCount > 0 || (platformWidget() && m_fixedObjectCount > 0) || m_isOverlapped || !m_contentIsOpaque)
1007         return true;
1008
1009     if (Frame* parentFrame = m_frame->tree()->parent()) {
1010         if (FrameView* parentView = parentFrame->view())
1011             return parentView->useSlowRepaints();
1012     }
1013
1014     return false;
1015 }
1016
1017 bool FrameView::useSlowRepaintsIfNotOverlapped() const
1018 {
1019     if (m_useSlowRepaints || m_slowRepaintObjectCount > 0 || (platformWidget() && m_fixedObjectCount > 0) || !m_contentIsOpaque)
1020         return true;
1021
1022     if (Frame* parentFrame = m_frame->tree()->parent()) {
1023         if (FrameView* parentView = parentFrame->view())
1024             return parentView->useSlowRepaintsIfNotOverlapped();
1025     }
1026
1027     return false;
1028 }
1029
1030 void FrameView::updateCanBlitOnScrollRecursively()
1031 {
1032     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
1033         if (FrameView* view = frame->view())
1034             view->setCanBlitOnScroll(!view->useSlowRepaints());
1035     }
1036 }
1037
1038 void FrameView::setUseSlowRepaints()
1039 {
1040     m_useSlowRepaints = true;
1041     updateCanBlitOnScrollRecursively();
1042 }
1043
1044 void FrameView::addSlowRepaintObject()
1045 {
1046     if (!m_slowRepaintObjectCount)
1047         updateCanBlitOnScrollRecursively();
1048     m_slowRepaintObjectCount++;
1049 }
1050
1051 void FrameView::removeSlowRepaintObject()
1052 {
1053     ASSERT(m_slowRepaintObjectCount > 0);
1054     m_slowRepaintObjectCount--;
1055     if (!m_slowRepaintObjectCount)
1056         updateCanBlitOnScrollRecursively();
1057 }
1058
1059 void FrameView::addFixedObject()
1060 {
1061     if (!m_fixedObjectCount && platformWidget())
1062         updateCanBlitOnScrollRecursively();
1063     ++m_fixedObjectCount;
1064 }
1065
1066 void FrameView::removeFixedObject()
1067 {
1068     ASSERT(m_fixedObjectCount > 0);
1069     --m_fixedObjectCount;
1070     if (!m_fixedObjectCount)
1071         updateCanBlitOnScrollRecursively();
1072 }
1073
1074 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
1075 {
1076     const size_t fixedObjectThreshold = 5;
1077
1078     RenderBlock::PositionedObjectsListHashSet* positionedObjects = 0;
1079     if (RenderView* root = m_frame->contentRenderer())
1080         positionedObjects = root->positionedObjects();
1081
1082     if (!positionedObjects || positionedObjects->isEmpty()) {
1083         hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1084         return true;
1085     }
1086
1087     // Get the rects of the fixed objects visible in the rectToScroll
1088     Vector<IntRect, fixedObjectThreshold> subRectToUpdate;
1089     bool updateInvalidatedSubRect = true;
1090     RenderBlock::PositionedObjectsListHashSet::const_iterator end = positionedObjects->end();
1091     for (RenderBlock::PositionedObjectsListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
1092         RenderBox* renderBox = *it;
1093         if (renderBox->style()->position() != FixedPosition)
1094             continue;
1095         IntRect updateRect = renderBox->layer()->repaintRectIncludingDescendants();
1096         updateRect = contentsToWindow(updateRect);
1097
1098         updateRect.intersect(rectToScroll);
1099         if (!updateRect.isEmpty()) {
1100             if (subRectToUpdate.size() >= fixedObjectThreshold) {
1101                 updateInvalidatedSubRect = false;
1102                 break;
1103             }
1104             subRectToUpdate.append(updateRect);
1105         }
1106     }
1107
1108     // Scroll the view
1109     if (updateInvalidatedSubRect) {
1110         // 1) scroll
1111         hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
1112
1113         // 2) update the area of fixed objects that has been invalidated
1114         size_t fixObjectsCount = subRectToUpdate.size();
1115         for (size_t i = 0; i < fixObjectsCount; ++i) {
1116             IntRect updateRect = subRectToUpdate[i];
1117             IntRect scrolledRect = updateRect;
1118             scrolledRect.move(scrollDelta);
1119             updateRect.unite(scrolledRect);
1120             updateRect.intersect(rectToScroll);
1121             hostWindow()->invalidateContentsAndWindow(updateRect, false);
1122         }
1123         return true;
1124     }
1125
1126     // the number of fixed objects exceed the threshold, we cannot use the fast path
1127     return false;
1128 }
1129
1130 void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
1131 {
1132 #if USE(ACCELERATED_COMPOSITING)
1133     if (RenderPart* frameRenderer = m_frame->ownerRenderer()) {
1134         if (frameRenderer->containerForRepaint()) {
1135             IntRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(),
1136                          frameRenderer->borderTop() + frameRenderer->paddingTop(),
1137                          visibleWidth(), visibleHeight());
1138             frameRenderer->repaintRectangle(rect);
1139             return;
1140         }
1141     }
1142 #endif
1143
1144     ScrollView::scrollContentsSlowPath(updateRect);
1145 }
1146
1147 // Note that this gets called at painting time.
1148 void FrameView::setIsOverlapped(bool isOverlapped)
1149 {
1150     if (isOverlapped == m_isOverlapped)
1151         return;
1152
1153     m_isOverlapped = isOverlapped;
1154     updateCanBlitOnScrollRecursively();
1155     
1156 #if USE(ACCELERATED_COMPOSITING)
1157     if (hasCompositedContentIncludingDescendants()) {
1158         // Overlap can affect compositing tests, so if it changes, we need to trigger
1159         // a layer update in the parent document.
1160         if (Frame* parentFrame = m_frame->tree()->parent()) {
1161             if (RenderView* parentView = parentFrame->contentRenderer()) {
1162                 RenderLayerCompositor* compositor = parentView->compositor();
1163                 compositor->setCompositingLayersNeedRebuild();
1164                 compositor->scheduleCompositingLayerUpdate();
1165             }
1166         }
1167
1168         if (RenderLayerCompositor::allowsIndependentlyCompositedIFrames(this)) {
1169             // We also need to trigger reevaluation for this and all descendant frames,
1170             // since a frame uses compositing if any ancestor is compositing.
1171             for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
1172                 if (RenderView* view = frame->contentRenderer()) {
1173                     RenderLayerCompositor* compositor = view->compositor();
1174                     compositor->setCompositingLayersNeedRebuild();
1175                     compositor->scheduleCompositingLayerUpdate();
1176                 }
1177             }
1178         }
1179     }
1180 #endif
1181 }
1182
1183 bool FrameView::isOverlappedIncludingAncestors() const
1184 {
1185     if (isOverlapped())
1186         return true;
1187
1188     if (Frame* parentFrame = m_frame->tree()->parent()) {
1189         if (FrameView* parentView = parentFrame->view()) {
1190             if (parentView->isOverlapped())
1191                 return true;
1192         }
1193     }
1194
1195     return false;
1196 }
1197
1198 void FrameView::setContentIsOpaque(bool contentIsOpaque)
1199 {
1200     if (contentIsOpaque == m_contentIsOpaque)
1201         return;
1202
1203     m_contentIsOpaque = contentIsOpaque;
1204     updateCanBlitOnScrollRecursively();
1205 }
1206
1207 void FrameView::restoreScrollbar()
1208 {
1209     setScrollbarsSuppressed(false);
1210 }
1211
1212 bool FrameView::scrollToFragment(const KURL& url)
1213 {
1214     // If our URL has no ref, then we have no place we need to jump to.
1215     // OTOH If CSS target was set previously, we want to set it to 0, recalc
1216     // and possibly repaint because :target pseudo class may have been
1217     // set (see bug 11321).
1218     if (!url.hasFragmentIdentifier() && !m_frame->document()->cssTarget())
1219         return false;
1220
1221     String fragmentIdentifier = url.fragmentIdentifier();
1222     if (scrollToAnchor(fragmentIdentifier))
1223         return true;
1224
1225     // Try again after decoding the ref, based on the document's encoding.
1226     if (TextResourceDecoder* decoder = m_frame->document()->decoder())
1227         return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, decoder->encoding()));
1228
1229     return false;
1230 }
1231
1232 bool FrameView::scrollToAnchor(const String& name)
1233 {
1234     ASSERT(m_frame->document());
1235
1236     if (!m_frame->document()->haveStylesheetsLoaded()) {
1237         m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
1238         return false;
1239     }
1240
1241     m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
1242
1243     Element* anchorNode = m_frame->document()->findAnchor(name);
1244
1245 #if ENABLE(SVG)
1246     if (m_frame->document()->isSVGDocument()) {
1247         if (name.startsWith("xpointer(")) {
1248             // We need to parse the xpointer reference here
1249         } else if (name.startsWith("svgView(")) {
1250             RefPtr<SVGSVGElement> svg = static_cast<SVGDocument*>(m_frame->document())->rootElement();
1251             if (!svg->currentView()->parseViewSpec(name))
1252                 return false;
1253             svg->setUseCurrentView(true);
1254         } else {
1255             if (anchorNode && anchorNode->hasTagName(SVGNames::viewTag)) {
1256                 RefPtr<SVGViewElement> viewElement = anchorNode->hasTagName(SVGNames::viewTag) ? static_cast<SVGViewElement*>(anchorNode) : 0;
1257                 if (viewElement.get()) {
1258                     SVGElement* element = SVGLocatable::nearestViewportElement(viewElement.get());
1259                     if (element->hasTagName(SVGNames::svgTag)) {
1260                         RefPtr<SVGSVGElement> svg = static_cast<SVGSVGElement*>(element);
1261                         svg->inheritViewAttributes(viewElement.get());
1262                     }
1263                 }
1264             }
1265         }
1266         // FIXME: need to decide which <svg> to focus on, and zoom to that one
1267         // FIXME: need to actually "highlight" the viewTarget(s)
1268     }
1269 #endif
1270
1271     m_frame->document()->setCSSTarget(anchorNode); // Setting to null will clear the current target.
1272   
1273     // Implement the rule that "" and "top" both mean top of page as in other browsers.
1274     if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
1275         return false;
1276
1277     maintainScrollPositionAtAnchor(anchorNode ? static_cast<Node*>(anchorNode) : m_frame->document());
1278     return true;
1279 }
1280
1281 void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
1282 {
1283     m_maintainScrollPositionAnchor = anchorNode;
1284     if (!m_maintainScrollPositionAnchor)
1285         return;
1286
1287     // We need to update the layout before scrolling, otherwise we could
1288     // really mess things up if an anchor scroll comes at a bad moment.
1289     m_frame->document()->updateStyleIfNeeded();
1290     // Only do a layout if changes have occurred that make it necessary.
1291     if (m_frame->contentRenderer() && m_frame->contentRenderer()->needsLayout())
1292         layout();
1293     else
1294         scrollToAnchor();
1295 }
1296
1297 void FrameView::setScrollPosition(const IntPoint& scrollPoint)
1298 {
1299     bool wasInProgrammaticScroll = m_inProgrammaticScroll;
1300     m_inProgrammaticScroll = true;
1301     m_maintainScrollPositionAnchor = 0;
1302     ScrollView::setScrollPosition(scrollPoint);
1303     m_inProgrammaticScroll = wasInProgrammaticScroll;
1304 }
1305
1306 void FrameView::scrollPositionChangedViaPlatformWidget()
1307 {
1308     repaintFixedElementsAfterScrolling();
1309     scrollPositionChanged();
1310 }
1311
1312 void FrameView::scrollPositionChanged()
1313 {
1314     frame()->eventHandler()->sendScrollEvent();
1315
1316 #if USE(ACCELERATED_COMPOSITING)
1317     if (RenderView* root = m_frame->contentRenderer()) {
1318         if (root->usesCompositing())
1319             root->compositor()->frameViewDidScroll(scrollPosition());
1320     }
1321 #endif
1322 }
1323
1324 void FrameView::repaintFixedElementsAfterScrolling()
1325 {
1326     // For fixed position elements, update widget positions and compositing layers after scrolling,
1327     // but only if we're not inside of layout.
1328     if (!m_nestedLayoutCount && hasFixedObjects()) {
1329         if (RenderView* root = m_frame->contentRenderer()) {
1330             root->updateWidgetPositions();
1331             root->layer()->updateRepaintRectsAfterScroll();
1332 #if USE(ACCELERATED_COMPOSITING)
1333             root->compositor()->updateCompositingLayers(CompositingUpdateOnScroll);
1334 #endif
1335         }
1336     }
1337 }
1338
1339 HostWindow* FrameView::hostWindow() const
1340 {
1341     Page* page = frame() ? frame()->page() : 0;
1342     if (!page)
1343         return 0;
1344     return page->chrome();
1345 }
1346
1347 const unsigned cRepaintRectUnionThreshold = 25;
1348
1349 void FrameView::repaintContentRectangle(const IntRect& r, bool immediate)
1350 {
1351     ASSERT(!m_frame->document()->ownerElement());
1352
1353     double delay = adjustedDeferredRepaintDelay();
1354     if ((m_deferringRepaints || m_deferredRepaintTimer.isActive() || delay) && !immediate) {
1355         IntRect paintRect = r;
1356         if (clipsRepaints() && !paintsEntireContents())
1357             paintRect.intersect(visibleContentRect());
1358         if (paintRect.isEmpty())
1359             return;
1360         if (m_repaintCount == cRepaintRectUnionThreshold) {
1361             IntRect unionedRect;
1362             for (unsigned i = 0; i < cRepaintRectUnionThreshold; ++i)
1363                 unionedRect.unite(m_repaintRects[i]);
1364             m_repaintRects.clear();
1365             m_repaintRects.append(unionedRect);
1366         }
1367         if (m_repaintCount < cRepaintRectUnionThreshold)
1368             m_repaintRects.append(paintRect);
1369         else
1370             m_repaintRects[0].unite(paintRect);
1371         m_repaintCount++;
1372     
1373         if (!m_deferringRepaints && !m_deferredRepaintTimer.isActive())
1374              m_deferredRepaintTimer.startOneShot(delay);
1375         return;
1376     }
1377     
1378     if (!shouldUpdate(immediate))
1379         return;
1380
1381 #if ENABLE(TILED_BACKING_STORE)
1382     if (frame()->tiledBackingStore()) {
1383         frame()->tiledBackingStore()->invalidate(r);
1384         return;
1385     }
1386 #endif
1387     ScrollView::repaintContentRectangle(r, immediate);
1388 }
1389
1390 void FrameView::visibleContentsResized()
1391 {
1392     // We check to make sure the view is attached to a frame() as this method can
1393     // be triggered before the view is attached by Frame::createView(...) setting
1394     // various values such as setScrollBarModes(...) for example.  An ASSERT is
1395     // triggered when a view is layout before being attached to a frame().
1396     if (!frame()->view())
1397         return;
1398
1399     if (needsLayout())
1400         layout();
1401 }
1402
1403 void FrameView::beginDeferredRepaints()
1404 {
1405     Page* page = m_frame->page();
1406     if (page->mainFrame() != m_frame)
1407         return page->mainFrame()->view()->beginDeferredRepaints();
1408
1409     m_deferringRepaints++;
1410 }
1411
1412
1413 void FrameView::endDeferredRepaints()
1414 {
1415     Page* page = m_frame->page();
1416     if (page->mainFrame() != m_frame)
1417         return page->mainFrame()->view()->endDeferredRepaints();
1418
1419     ASSERT(m_deferringRepaints > 0);
1420
1421     if (--m_deferringRepaints)
1422         return;
1423     
1424     if (m_deferredRepaintTimer.isActive())
1425         return;
1426
1427     if (double delay = adjustedDeferredRepaintDelay()) {
1428         m_deferredRepaintTimer.startOneShot(delay);
1429         return;
1430     }
1431     
1432     doDeferredRepaints();
1433 }
1434
1435 void FrameView::checkStopDelayingDeferredRepaints()
1436 {
1437     if (!m_deferredRepaintTimer.isActive())
1438         return;
1439
1440     Document* document = m_frame->document();
1441     if (document && (document->parsing() || document->cachedResourceLoader()->requestCount()))
1442         return;
1443     
1444     m_deferredRepaintTimer.stop();
1445
1446     doDeferredRepaints();
1447 }
1448     
1449 void FrameView::doDeferredRepaints()
1450 {
1451     ASSERT(!m_deferringRepaints);
1452     if (!shouldUpdate()) {
1453         m_repaintRects.clear();
1454         m_repaintCount = 0;
1455         return;
1456     }
1457     unsigned size = m_repaintRects.size();
1458     for (unsigned i = 0; i < size; i++) {
1459 #if ENABLE(TILED_BACKING_STORE)
1460         if (frame()->tiledBackingStore()) {
1461             frame()->tiledBackingStore()->invalidate(m_repaintRects[i]);
1462             continue;
1463         }
1464 #endif
1465         ScrollView::repaintContentRectangle(m_repaintRects[i], false);
1466     }
1467     m_repaintRects.clear();
1468     m_repaintCount = 0;
1469     
1470     updateDeferredRepaintDelay();
1471 }
1472
1473 void FrameView::updateDeferredRepaintDelay()
1474 {
1475     Document* document = m_frame->document();
1476     if (!document || (!document->parsing() && !document->cachedResourceLoader()->requestCount())) {
1477         m_deferredRepaintDelay = s_deferredRepaintDelay;
1478         return;
1479     }
1480     if (m_deferredRepaintDelay < s_maxDeferredRepaintDelayDuringLoading) {
1481         m_deferredRepaintDelay += s_deferredRepaintDelayIncrementDuringLoading;
1482         if (m_deferredRepaintDelay > s_maxDeferredRepaintDelayDuringLoading)
1483             m_deferredRepaintDelay = s_maxDeferredRepaintDelayDuringLoading;
1484     }
1485 }
1486
1487 void FrameView::resetDeferredRepaintDelay()
1488 {
1489     m_deferredRepaintDelay = 0;
1490     if (m_deferredRepaintTimer.isActive()) {
1491         m_deferredRepaintTimer.stop();
1492         if (!m_deferringRepaints)
1493             doDeferredRepaints();
1494     }
1495 }
1496
1497 double FrameView::adjustedDeferredRepaintDelay() const
1498 {
1499     if (!m_deferredRepaintDelay)
1500         return 0;
1501     double timeSinceLastPaint = currentTime() - m_lastPaintTime;
1502     return max(0., m_deferredRepaintDelay - timeSinceLastPaint);
1503 }
1504     
1505 void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
1506 {
1507     doDeferredRepaints();
1508 }    
1509
1510 void FrameView::layoutTimerFired(Timer<FrameView>*)
1511 {
1512 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1513     if (!m_frame->document()->ownerElement())
1514         printf("Layout timer fired at %d\n", m_frame->document()->elapsedTime());
1515 #endif
1516     layout();
1517 }
1518
1519 void FrameView::scheduleRelayout()
1520 {
1521     // FIXME: We should assert the page is not in the page cache, but that is causing
1522     // too many false assertions.  See <rdar://problem/7218118>.
1523     ASSERT(m_frame->view() == this);
1524
1525     if (m_layoutRoot) {
1526         m_layoutRoot->markContainingBlocksForLayout(false);
1527         m_layoutRoot = 0;
1528     }
1529     if (!m_layoutSchedulingEnabled)
1530         return;
1531     if (!needsLayout())
1532         return;
1533     if (!m_frame->document()->shouldScheduleLayout())
1534         return;
1535
1536     // When frame flattening is enabled, the contents of the frame affects layout of the parent frames.
1537     // Also invalidate parent frame starting from the owner element of this frame.
1538     if (m_frame->settings() && m_frame->settings()->frameFlatteningEnabled() && m_frame->ownerRenderer()) {
1539         if (m_frame->ownerElement()->hasTagName(iframeTag) || m_frame->ownerElement()->hasTagName(frameTag))
1540             m_frame->ownerRenderer()->setNeedsLayout(true, true);
1541     }
1542
1543     int delay = m_frame->document()->minimumLayoutDelay();
1544     if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
1545         unscheduleRelayout();
1546     if (m_layoutTimer.isActive())
1547         return;
1548
1549     m_delayedLayout = delay != 0;
1550
1551 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1552     if (!m_frame->document()->ownerElement())
1553         printf("Scheduling layout for %d\n", delay);
1554 #endif
1555
1556     m_layoutTimer.startOneShot(delay * 0.001);
1557 }
1558
1559 static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
1560 {
1561     for (RenderObject* r = descendant; r; r = r->container()) {
1562         if (r == ancestor)
1563             return true;
1564     }
1565     return false;
1566 }
1567
1568 void FrameView::scheduleRelayoutOfSubtree(RenderObject* relayoutRoot)
1569 {
1570     ASSERT(m_frame->view() == this);
1571
1572     if (m_frame->contentRenderer() && m_frame->contentRenderer()->needsLayout()) {
1573         if (relayoutRoot)
1574             relayoutRoot->markContainingBlocksForLayout(false);
1575         return;
1576     }
1577
1578     if (layoutPending() || !m_layoutSchedulingEnabled) {
1579         if (m_layoutRoot != relayoutRoot) {
1580             if (isObjectAncestorContainerOf(m_layoutRoot, relayoutRoot)) {
1581                 // Keep the current root
1582                 relayoutRoot->markContainingBlocksForLayout(false, m_layoutRoot);
1583             } else if (m_layoutRoot && isObjectAncestorContainerOf(relayoutRoot, m_layoutRoot)) {
1584                 // Re-root at relayoutRoot
1585                 m_layoutRoot->markContainingBlocksForLayout(false, relayoutRoot);
1586                 m_layoutRoot = relayoutRoot;
1587             } else {
1588                 // Just do a full relayout
1589                 if (m_layoutRoot)
1590                     m_layoutRoot->markContainingBlocksForLayout(false);
1591                 m_layoutRoot = 0;
1592                 relayoutRoot->markContainingBlocksForLayout(false);
1593             }
1594         }
1595     } else if (m_layoutSchedulingEnabled) {
1596         int delay = m_frame->document()->minimumLayoutDelay();
1597         m_layoutRoot = relayoutRoot;
1598         m_delayedLayout = delay != 0;
1599         m_layoutTimer.startOneShot(delay * 0.001);
1600     }
1601 }
1602
1603 bool FrameView::layoutPending() const
1604 {
1605     return m_layoutTimer.isActive();
1606 }
1607
1608 bool FrameView::needsLayout() const
1609 {
1610     // This can return true in cases where the document does not have a body yet.
1611     // Document::shouldScheduleLayout takes care of preventing us from scheduling
1612     // layout in that case.
1613     if (!m_frame)
1614         return false;
1615     RenderView* root = m_frame->contentRenderer();
1616     return layoutPending()
1617         || (root && root->needsLayout())
1618         || m_layoutRoot
1619         || (m_deferSetNeedsLayouts && m_setNeedsLayoutWasDeferred);
1620 }
1621
1622 void FrameView::setNeedsLayout()
1623 {
1624     if (m_deferSetNeedsLayouts) {
1625         m_setNeedsLayoutWasDeferred = true;
1626         return;
1627     }
1628     RenderView* root = m_frame->contentRenderer();
1629     if (root)
1630         root->setNeedsLayout(true);
1631 }
1632
1633 void FrameView::unscheduleRelayout()
1634 {
1635     m_postLayoutTasksTimer.stop();
1636
1637     if (!m_layoutTimer.isActive())
1638         return;
1639
1640 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
1641     if (!m_frame->document()->ownerElement())
1642         printf("Layout timer unscheduled at %d\n", m_frame->document()->elapsedTime());
1643 #endif
1644     
1645     m_layoutTimer.stop();
1646     m_delayedLayout = false;
1647 }
1648
1649 #if ENABLE(REQUEST_ANIMATION_FRAME)
1650 void FrameView::serviceScriptedAnimations()
1651 {
1652     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext())
1653         frame->document()->serviceScriptedAnimations();
1654 }
1655 #endif
1656
1657 bool FrameView::isTransparent() const
1658 {
1659     return m_isTransparent;
1660 }
1661
1662 void FrameView::setTransparent(bool isTransparent)
1663 {
1664     m_isTransparent = isTransparent;
1665 }
1666
1667 Color FrameView::baseBackgroundColor() const
1668 {
1669     return m_baseBackgroundColor;
1670 }
1671
1672 void FrameView::setBaseBackgroundColor(Color bc)
1673 {
1674     if (!bc.isValid())
1675         bc = Color::white;
1676     m_baseBackgroundColor = bc;
1677 }
1678
1679 void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
1680 {
1681     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
1682         if (FrameView* view = frame->view()) {
1683             view->setTransparent(transparent);
1684             view->setBaseBackgroundColor(backgroundColor);
1685         }
1686     }
1687 }
1688
1689 bool FrameView::shouldUpdateWhileOffscreen() const
1690 {
1691     return m_shouldUpdateWhileOffscreen;
1692 }
1693
1694 void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
1695 {
1696     m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
1697 }
1698
1699 bool FrameView::shouldUpdate(bool immediateRequested) const
1700 {
1701     if (!immediateRequested && isOffscreen() && !shouldUpdateWhileOffscreen())
1702         return false;
1703     if (!m_frame || !m_frame->document() || m_frame->document()->mayCauseFlashOfUnstyledContent())
1704         return false;
1705     return true;
1706 }
1707
1708 void FrameView::scheduleEvent(PassRefPtr<Event> event, PassRefPtr<Node> eventTarget)
1709 {
1710     if (!m_enqueueEvents) {
1711         ExceptionCode ec = 0;
1712         eventTarget->dispatchEvent(event, ec);
1713         return;
1714     }
1715
1716     ScheduledEvent* scheduledEvent = new ScheduledEvent;
1717     scheduledEvent->m_event = event;
1718     scheduledEvent->m_eventTarget = eventTarget;
1719     m_scheduledEvents.append(scheduledEvent);
1720 }
1721
1722 void FrameView::pauseScheduledEvents()
1723 {
1724     ASSERT(m_scheduledEvents.isEmpty() || m_enqueueEvents);
1725     m_enqueueEvents++;
1726 }
1727
1728 void FrameView::resumeScheduledEvents()
1729 {
1730     m_enqueueEvents--;
1731     if (!m_enqueueEvents)
1732         dispatchScheduledEvents();
1733     ASSERT(m_scheduledEvents.isEmpty() || m_enqueueEvents);
1734 }
1735
1736 void FrameView::scrollToAnchor()
1737 {
1738     RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
1739     if (!anchorNode)
1740         return;
1741
1742     if (!anchorNode->renderer())
1743         return;
1744
1745     IntRect rect;
1746     if (anchorNode != m_frame->document())
1747         rect = anchorNode->getRect();
1748
1749     // Scroll nested layers and frames to reveal the anchor.
1750     // Align to the top and to the closest side (this matches other browsers).
1751     anchorNode->renderer()->enclosingLayer()->scrollRectToVisible(rect, true, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
1752
1753     if (AXObjectCache::accessibilityEnabled())
1754         m_frame->document()->axObjectCache()->handleScrolledToAnchor(anchorNode.get());
1755
1756     // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
1757     m_maintainScrollPositionAnchor = anchorNode;
1758 }
1759
1760 void FrameView::updateWidget(RenderEmbeddedObject* object)
1761 {
1762     ASSERT(!object->node() || object->node()->isElementNode());
1763     Element* ownerElement = static_cast<Element*>(object->node());
1764     // The object may have already been destroyed (thus node cleared),
1765     // but FrameView holds a manual ref, so it won't have been deleted.
1766     ASSERT(m_widgetUpdateSet->contains(object));
1767     if (!ownerElement)
1768         return;
1769
1770     // No need to update if it's already crashed or known to be missing.
1771     if (object->pluginCrashedOrWasMissing())
1772         return;
1773
1774     // FIXME: This could turn into a real virtual dispatch if we defined
1775     // updateWidget(bool) on HTMLElement.
1776     if (ownerElement->hasTagName(objectTag) || ownerElement->hasTagName(embedTag))
1777         static_cast<HTMLPlugInImageElement*>(ownerElement)->updateWidget(false);
1778     // FIXME: It is not clear that Media elements need or want this updateWidget() call.
1779 #if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
1780     else if (ownerElement->hasTagName(videoTag) || ownerElement->hasTagName(audioTag))
1781         static_cast<HTMLMediaElement*>(ownerElement)->updateWidget(false);
1782 #endif
1783     else
1784         ASSERT_NOT_REACHED();
1785
1786     // Caution: it's possible the object was destroyed again, since loading a
1787     // plugin may run any arbitrary javascript.
1788     object->updateWidgetPosition();
1789 }
1790
1791 bool FrameView::updateWidgets()
1792 {
1793     if (m_nestedLayoutCount > 1 || !m_widgetUpdateSet || m_widgetUpdateSet->isEmpty())
1794         return true;
1795     
1796     size_t size = m_widgetUpdateSet->size();
1797
1798     Vector<RenderEmbeddedObject*> objects;
1799     objects.reserveCapacity(size);
1800
1801     RenderEmbeddedObjectSet::const_iterator end = m_widgetUpdateSet->end();
1802     for (RenderEmbeddedObjectSet::const_iterator it = m_widgetUpdateSet->begin(); it != end; ++it) {
1803         objects.uncheckedAppend(*it);
1804         (*it)->ref();
1805     }
1806
1807     for (size_t i = 0; i < size; ++i) {
1808         RenderEmbeddedObject* object = objects[i];
1809         updateWidget(object);
1810         m_widgetUpdateSet->remove(object);
1811     }
1812
1813     RenderArena* arena = m_frame->document()->renderArena();
1814     for (size_t i = 0; i < size; ++i)
1815         objects[i]->deref(arena);
1816     
1817     return m_widgetUpdateSet->isEmpty();
1818 }
1819     
1820 void FrameView::performPostLayoutTasks()
1821 {
1822     m_hasPendingPostLayoutTasks = false;
1823
1824     if (m_firstLayoutCallbackPending) {
1825         m_firstLayoutCallbackPending = false;
1826         m_frame->loader()->didFirstLayout();
1827     }
1828
1829     if (m_isVisuallyNonEmpty && m_firstVisuallyNonEmptyLayoutCallbackPending) {
1830         m_firstVisuallyNonEmptyLayoutCallbackPending = false;
1831         m_frame->loader()->didFirstVisuallyNonEmptyLayout();
1832     }
1833
1834     RenderView* root = m_frame->contentRenderer();
1835
1836     root->updateWidgetPositions();
1837     
1838     for (unsigned i = 0; i < maxUpdateWidgetsIterations; i++) {
1839         if (updateWidgets())
1840             break;
1841     }
1842
1843     scrollToAnchor();
1844
1845     resumeScheduledEvents();
1846
1847     if (!root->printing()) {
1848         IntSize currentSize = IntSize(width(), height());
1849         float currentZoomFactor = root->style()->zoom();
1850         bool resized = !m_firstLayout && (currentSize != m_lastLayoutSize || currentZoomFactor != m_lastZoomFactor);
1851         m_lastLayoutSize = currentSize;
1852         m_lastZoomFactor = currentZoomFactor;
1853         if (resized)
1854             m_frame->eventHandler()->sendResizeEvent();
1855     }
1856 }
1857
1858 void FrameView::postLayoutTimerFired(Timer<FrameView>*)
1859 {
1860     performPostLayoutTasks();
1861 }
1862
1863 void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
1864 {
1865     if (!m_viewportRenderer)
1866         return;
1867     
1868     if (m_overflowStatusDirty) {
1869         m_horizontalOverflow = horizontalOverflow;
1870         m_verticalOverflow = verticalOverflow;
1871         m_overflowStatusDirty = false;
1872         return;
1873     }
1874     
1875     bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
1876     bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
1877     
1878     if (horizontalOverflowChanged || verticalOverflowChanged) {
1879         m_horizontalOverflow = horizontalOverflow;
1880         m_verticalOverflow = verticalOverflow;
1881         
1882         scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
1883             verticalOverflowChanged, verticalOverflow),
1884             m_viewportRenderer->node());
1885     }
1886     
1887 }
1888
1889 void FrameView::dispatchScheduledEvents()
1890 {
1891     if (m_scheduledEvents.isEmpty())
1892         return;
1893
1894     Vector<ScheduledEvent*> scheduledEventsCopy = m_scheduledEvents;
1895     m_scheduledEvents.clear();
1896     
1897     Vector<ScheduledEvent*>::iterator end = scheduledEventsCopy.end();
1898     for (Vector<ScheduledEvent*>::iterator it = scheduledEventsCopy.begin(); it != end; ++it) {
1899         ScheduledEvent* scheduledEvent = *it;
1900         
1901         ExceptionCode ec = 0;
1902         
1903         // Only dispatch events to nodes that are in the document
1904         if (scheduledEvent->m_eventTarget->inDocument())
1905             scheduledEvent->m_eventTarget->dispatchEvent(scheduledEvent->m_event, ec);
1906         
1907         delete scheduledEvent;
1908     }
1909 }
1910
1911 IntRect FrameView::windowClipRect(bool clipToContents) const
1912 {
1913     ASSERT(m_frame->view() == this);
1914
1915     if (paintsEntireContents())
1916         return IntRect(IntPoint(0, 0), contentsSize());
1917
1918     // Set our clip rect to be our contents.
1919     IntRect clipRect = contentsToWindow(visibleContentRect(!clipToContents));
1920     if (!m_frame || !m_frame->document() || !m_frame->document()->ownerElement())
1921         return clipRect;
1922
1923     // Take our owner element and get the clip rect from the enclosing layer.
1924     Element* elt = m_frame->document()->ownerElement();
1925     RenderLayer* layer = elt->renderer()->enclosingLayer();
1926     // FIXME: layer should never be null, but sometimes seems to be anyway.
1927     if (!layer)
1928         return clipRect;
1929     FrameView* parentView = elt->document()->view();
1930     clipRect.intersect(parentView->windowClipRectForLayer(layer, true));
1931     return clipRect;
1932 }
1933
1934 IntRect FrameView::windowClipRectForLayer(const RenderLayer* layer, bool clipToLayerContents) const
1935 {
1936     // If we have no layer, just return our window clip rect.
1937     if (!layer)
1938         return windowClipRect();
1939
1940     // Apply the clip from the layer.
1941     IntRect clipRect;
1942     if (clipToLayerContents)
1943         clipRect = layer->childrenClipRect();
1944     else
1945         clipRect = layer->selfClipRect();
1946     clipRect = contentsToWindow(clipRect); 
1947     return intersection(clipRect, windowClipRect());
1948 }
1949
1950 bool FrameView::isActive() const
1951 {
1952     Page* page = frame()->page();
1953     return page && page->focusController()->isActive();
1954 }
1955
1956 void FrameView::valueChanged(Scrollbar* bar)
1957 {
1958     // Figure out if we really moved.
1959     IntSize offset = scrollOffset();
1960     ScrollView::valueChanged(bar);
1961     if (offset != scrollOffset())
1962         scrollPositionChanged();
1963     frame()->loader()->client()->didChangeScrollOffset();
1964 }
1965
1966 void FrameView::valueChanged(const IntSize& scrollDelta)
1967 {
1968     ScrollView::valueChanged(scrollDelta);
1969     frame()->eventHandler()->sendScrollEvent();
1970     frame()->loader()->client()->didChangeScrollOffset();
1971 }
1972
1973 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
1974 {
1975     // Add in our offset within the FrameView.
1976     IntRect dirtyRect = rect;
1977     dirtyRect.move(scrollbar->x(), scrollbar->y());
1978     invalidateRect(dirtyRect);
1979 }
1980
1981 void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
1982 {
1983     tickmarks = frame()->document()->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
1984 }
1985
1986 IntRect FrameView::windowResizerRect() const
1987 {
1988     Page* page = frame() ? frame()->page() : 0;
1989     if (!page)
1990         return IntRect();
1991     return page->chrome()->windowResizerRect();
1992 }
1993
1994 #if ENABLE(DASHBOARD_SUPPORT)
1995 void FrameView::updateDashboardRegions()
1996 {
1997     Document* document = m_frame->document();
1998     if (!document->hasDashboardRegions())
1999         return;
2000     Vector<DashboardRegionValue> newRegions;
2001     document->renderBox()->collectDashboardRegions(newRegions);
2002     if (newRegions == document->dashboardRegions())
2003         return;
2004     document->setDashboardRegions(newRegions);
2005     Page* page = m_frame->page();
2006     if (!page)
2007         return;
2008     page->chrome()->client()->dashboardRegionsChanged();
2009 }
2010 #endif
2011
2012 void FrameView::invalidateScrollCorner()
2013 {
2014     invalidateRect(scrollCornerRect());
2015 }
2016
2017 void FrameView::updateScrollCorner()
2018 {
2019     RenderObject* renderer = 0;
2020     RefPtr<RenderStyle> cornerStyle;
2021     
2022     if (!scrollCornerRect().isEmpty()) {
2023         // Try the <body> element first as a scroll corner source.
2024         Document* doc = m_frame->document();
2025         Element* body = doc ? doc->body() : 0;
2026         if (body && body->renderer()) {
2027             renderer = body->renderer();
2028             cornerStyle = renderer->getUncachedPseudoStyle(SCROLLBAR_CORNER, renderer->style());
2029         }
2030         
2031         if (!cornerStyle) {
2032             // If the <body> didn't have a custom style, then the root element might.
2033             Element* docElement = doc ? doc->documentElement() : 0;
2034             if (docElement && docElement->renderer()) {
2035                 renderer = docElement->renderer();
2036                 cornerStyle = renderer->getUncachedPseudoStyle(SCROLLBAR_CORNER, renderer->style());
2037             }
2038         }
2039         
2040         if (!cornerStyle) {
2041             // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
2042             if (RenderPart* renderer = m_frame->ownerRenderer())
2043                 cornerStyle = renderer->getUncachedPseudoStyle(SCROLLBAR_CORNER, renderer->style());
2044         }
2045     }
2046
2047     if (cornerStyle) {
2048         if (!m_scrollCorner)
2049             m_scrollCorner = new (renderer->renderArena()) RenderScrollbarPart(renderer->document());
2050         m_scrollCorner->setStyle(cornerStyle.release());
2051         invalidateRect(scrollCornerRect());
2052     } else if (m_scrollCorner) {
2053         m_scrollCorner->destroy();
2054         m_scrollCorner = 0;
2055     }
2056 }
2057
2058 void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
2059 {
2060     if (context->updatingControlTints()) {
2061         updateScrollCorner();
2062         return;
2063     }
2064
2065     if (m_scrollCorner) {
2066         m_scrollCorner->paintIntoRect(context, cornerRect.x(), cornerRect.y(), cornerRect);
2067         return;
2068     }
2069
2070     ScrollView::paintScrollCorner(context, cornerRect);
2071 }
2072
2073 bool FrameView::hasCustomScrollbars() const
2074 {
2075     const HashSet<RefPtr<Widget> >* viewChildren = children();
2076     HashSet<RefPtr<Widget> >::const_iterator end = viewChildren->end();
2077     for (HashSet<RefPtr<Widget> >::const_iterator current = viewChildren->begin(); current != end; ++current) {
2078         Widget* widget = current->get();
2079         if (widget->isFrameView()) {
2080             if (static_cast<FrameView*>(widget)->hasCustomScrollbars())
2081                 return true;
2082         } else if (widget->isScrollbar()) {
2083             Scrollbar* scrollbar = static_cast<Scrollbar*>(widget);
2084             if (scrollbar->isCustomScrollbar())
2085                 return true;
2086         }
2087     }
2088
2089     return false;
2090 }
2091
2092 void FrameView::updateControlTints()
2093 {
2094     // This is called when control tints are changed from aqua/graphite to clear and vice versa.
2095     // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
2096     // This is only done if the theme supports control tinting. It's up to the theme and platform
2097     // to define when controls get the tint and to call this function when that changes.
2098     
2099     // Optimize the common case where we bring a window to the front while it's still empty.
2100     if (!m_frame || m_frame->loader()->url().isEmpty())
2101         return;
2102
2103     if ((m_frame->contentRenderer() && m_frame->contentRenderer()->theme()->supportsControlTints()) || hasCustomScrollbars())  {
2104         if (needsLayout())
2105             layout();
2106         PlatformGraphicsContext* const noContext = 0;
2107         GraphicsContext context(noContext);
2108         context.setUpdatingControlTints(true);
2109         if (platformWidget())
2110             paintContents(&context, visibleContentRect());
2111         else
2112             paint(&context, frameRect());
2113     }
2114 }
2115
2116 bool FrameView::wasScrolledByUser() const
2117 {
2118     return m_wasScrolledByUser;
2119 }
2120
2121 void FrameView::setWasScrolledByUser(bool wasScrolledByUser)
2122 {
2123     if (m_inProgrammaticScroll)
2124         return;
2125     m_maintainScrollPositionAnchor = 0;
2126     m_wasScrolledByUser = wasScrolledByUser;
2127 }
2128
2129 void FrameView::paintContents(GraphicsContext* p, const IntRect& rect)
2130 {
2131     if (!frame())
2132         return;
2133
2134     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willPaint(m_frame.get(), rect);
2135
2136     Document* document = frame()->document();
2137
2138 #ifndef NDEBUG
2139     bool fillWithRed;
2140     if (document->printing())
2141         fillWithRed = false; // Printing, don't fill with red (can't remember why).
2142     else if (document->ownerElement())
2143         fillWithRed = false; // Subframe, don't fill with red.
2144     else if (isTransparent())
2145         fillWithRed = false; // Transparent, don't fill with red.
2146     else if (m_paintBehavior & PaintBehaviorSelectionOnly)
2147         fillWithRed = false; // Selections are transparent, don't fill with red.
2148     else if (m_nodeToDraw)
2149         fillWithRed = false; // Element images are transparent, don't fill with red.
2150     else
2151         fillWithRed = true;
2152     
2153     if (fillWithRed)
2154         p->fillRect(rect, Color(0xFF, 0, 0), ColorSpaceDeviceRGB);
2155 #endif
2156
2157     bool isTopLevelPainter = !sCurrentPaintTimeStamp;
2158     if (isTopLevelPainter)
2159         sCurrentPaintTimeStamp = currentTime();
2160     
2161     RenderView* contentRenderer = frame()->contentRenderer();
2162     if (!contentRenderer) {
2163         LOG_ERROR("called FrameView::paint with nil renderer");
2164         return;
2165     }
2166
2167     ASSERT(!needsLayout());
2168     if (needsLayout())
2169         return;
2170
2171 #if USE(ACCELERATED_COMPOSITING)
2172     if (!p->paintingDisabled())
2173         syncCompositingStateForThisFrame();
2174 #endif
2175
2176     PaintBehavior oldPaintBehavior = m_paintBehavior;
2177     if (m_paintBehavior == PaintBehaviorNormal)
2178         document->markers()->invalidateRenderedRectsForMarkersInRect(rect);
2179
2180     if (document->printing())
2181         m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
2182
2183     bool flatteningPaint = m_paintBehavior & PaintBehaviorFlattenCompositingLayers;
2184     bool isRootFrame = !document->ownerElement();
2185     if (flatteningPaint && isRootFrame)
2186         notifyWidgetsInAllFrames(WillPaintFlattened);
2187
2188     ASSERT(!m_isPainting);
2189     m_isPainting = true;
2190
2191     // m_nodeToDraw is used to draw only one element (and its descendants)
2192     RenderObject* eltRenderer = m_nodeToDraw ? m_nodeToDraw->renderer() : 0;
2193
2194     contentRenderer->layer()->paint(p, rect, m_paintBehavior, eltRenderer);
2195
2196     m_isPainting = false;
2197
2198     if (flatteningPaint && isRootFrame)
2199         notifyWidgetsInAllFrames(DidPaintFlattened);
2200
2201     m_paintBehavior = oldPaintBehavior;
2202     m_lastPaintTime = currentTime();
2203
2204 #if ENABLE(DASHBOARD_SUPPORT)
2205     // Regions may have changed as a result of the visibility/z-index of element changing.
2206     if (document->dashboardRegionsDirty())
2207         updateDashboardRegions();
2208 #endif
2209
2210     if (isTopLevelPainter)
2211         sCurrentPaintTimeStamp = 0;
2212
2213     InspectorInstrumentation::didPaint(cookie);
2214 }
2215
2216 void FrameView::setPaintBehavior(PaintBehavior behavior)
2217 {
2218     m_paintBehavior = behavior;
2219 }
2220
2221 PaintBehavior FrameView::paintBehavior() const
2222 {
2223     return m_paintBehavior;
2224 }
2225
2226 bool FrameView::isPainting() const
2227 {
2228     return m_isPainting;
2229 }
2230
2231 void FrameView::setNodeToDraw(Node* node)
2232 {
2233     m_nodeToDraw = node;
2234 }
2235
2236 void FrameView::updateLayoutAndStyleIfNeededRecursive()
2237 {
2238     // We have to crawl our entire tree looking for any FrameViews that need
2239     // layout and make sure they are up to date.
2240     // Mac actually tests for intersection with the dirty region and tries not to
2241     // update layout for frames that are outside the dirty region.  Not only does this seem
2242     // pointless (since those frames will have set a zero timer to layout anyway), but
2243     // it is also incorrect, since if two frames overlap, the first could be excluded from the dirty
2244     // region but then become included later by the second frame adding rects to the dirty region
2245     // when it lays out.
2246
2247     m_frame->document()->updateStyleIfNeeded();
2248
2249     if (needsLayout())
2250         layout();
2251
2252     const HashSet<RefPtr<Widget> >* viewChildren = children();
2253     HashSet<RefPtr<Widget> >::const_iterator end = viewChildren->end();
2254     for (HashSet<RefPtr<Widget> >::const_iterator current = viewChildren->begin(); current != end; ++current) {
2255         Widget* widget = (*current).get();
2256         if (widget->isFrameView())
2257             static_cast<FrameView*>(widget)->updateLayoutAndStyleIfNeededRecursive();
2258     }
2259
2260     // updateLayoutAndStyleIfNeededRecursive is called when we need to make sure style and layout are up-to-date before
2261     // painting, so we need to flush out any deferred repaints too.
2262     flushDeferredRepaints();
2263 }
2264     
2265 void FrameView::flushDeferredRepaints()
2266 {
2267     if (!m_deferredRepaintTimer.isActive())
2268         return;
2269     m_deferredRepaintTimer.stop();
2270     doDeferredRepaints();
2271 }
2272
2273 void FrameView::forceLayout(bool allowSubtree)
2274 {
2275     layout(allowSubtree);
2276 }
2277
2278 void FrameView::forceLayoutForPagination(const FloatSize& pageSize, float maximumShrinkFactor, Frame::AdjustViewSizeOrNot shouldAdjustViewSize)
2279 {
2280     // Dumping externalRepresentation(m_frame->renderer()).ascii() is a good trick to see
2281     // the state of things before and after the layout
2282     RenderView *root = toRenderView(m_frame->document()->renderer());
2283     if (root) {
2284         int pageW = ceilf(pageSize.width());
2285         root->setWidth(pageW);
2286         root->setPageLogicalHeight(pageSize.height());
2287         root->setNeedsLayoutAndPrefWidthsRecalc();
2288         forceLayout();
2289
2290         // If we don't fit in the given page width, we'll lay out again. If we don't fit in the
2291         // page width when shrunk, we will lay out at maximum shrink and clip extra content.
2292         // FIXME: We are assuming a shrink-to-fit printing implementation.  A cropping
2293         // implementation should not do this!
2294         int docWidth = root->docWidth();
2295         if (docWidth > pageSize.width()) {
2296             pageW = std::min<int>(docWidth, ceilf(pageSize.width() * maximumShrinkFactor));
2297             if (pageSize.height())
2298                 root->setPageLogicalHeight(pageW / pageSize.width() * pageSize.height());
2299             root->setWidth(pageW);
2300             root->setNeedsLayoutAndPrefWidthsRecalc();
2301             forceLayout();
2302             int docHeight = root->docHeight();
2303             root->clearLayoutOverflow();
2304             root->addLayoutOverflow(IntRect(0, 0, pageW, docHeight)); // This is how we clip in case we overflow again.
2305         }
2306     }
2307
2308     if (shouldAdjustViewSize)
2309         adjustViewSize();
2310 }
2311
2312 void FrameView::adjustPageHeightDeprecated(float *newBottom, float oldTop, float oldBottom, float /*bottomLimit*/)
2313 {
2314     RenderView* root = m_frame->contentRenderer();
2315     if (root) {
2316         // Use a context with painting disabled.
2317         GraphicsContext context((PlatformGraphicsContext*)0);
2318         root->setTruncatedAt((int)floorf(oldBottom));
2319         IntRect dirtyRect(0, (int)floorf(oldTop), root->rightLayoutOverflow(), (int)ceilf(oldBottom - oldTop));
2320         root->setPrintRect(dirtyRect);
2321         root->layer()->paint(&context, dirtyRect);
2322         *newBottom = root->bestTruncatedAt();
2323         if (*newBottom == 0)
2324             *newBottom = oldBottom;
2325         root->setPrintRect(IntRect());
2326     } else
2327         *newBottom = oldBottom;
2328 }
2329
2330 IntRect FrameView::convertFromRenderer(const RenderObject* renderer, const IntRect& rendererRect) const
2331 {
2332     IntRect rect = renderer->localToAbsoluteQuad(FloatRect(rendererRect)).enclosingBoundingBox();
2333
2334     // Convert from page ("absolute") to FrameView coordinates.
2335     rect.move(-scrollX(), -scrollY());
2336
2337     return rect;
2338 }
2339
2340 IntRect FrameView::convertToRenderer(const RenderObject* renderer, const IntRect& viewRect) const
2341 {
2342     IntRect rect = viewRect;
2343     
2344     // Convert from FrameView coords into page ("absolute") coordinates.
2345     rect.move(scrollX(), scrollY());
2346
2347     // FIXME: we don't have a way to map an absolute rect down to a local quad, so just
2348     // move the rect for now.
2349     rect.setLocation(roundedIntPoint(renderer->absoluteToLocal(rect.location(), false, true /* use transforms */)));
2350     return rect;
2351 }
2352
2353 IntPoint FrameView::convertFromRenderer(const RenderObject* renderer, const IntPoint& rendererPoint) const
2354 {
2355     IntPoint point = roundedIntPoint(renderer->localToAbsolute(rendererPoint, false, true /* use transforms */));
2356
2357     // Convert from page ("absolute") to FrameView coordinates.
2358     point.move(-scrollX(), -scrollY());
2359     return point;
2360 }
2361
2362 IntPoint FrameView::convertToRenderer(const RenderObject* renderer, const IntPoint& viewPoint) const
2363 {
2364     IntPoint point = viewPoint;
2365     
2366     // Convert from FrameView coords into page ("absolute") coordinates.
2367     point += IntSize(scrollX(), scrollY());
2368
2369     return roundedIntPoint(renderer->absoluteToLocal(point, false, true /* use transforms */));
2370 }
2371
2372 IntRect FrameView::convertToContainingView(const IntRect& localRect) const
2373 {
2374     if (const ScrollView* parentScrollView = parent()) {
2375         if (parentScrollView->isFrameView()) {
2376             const FrameView* parentView = static_cast<const FrameView*>(parentScrollView);
2377             // Get our renderer in the parent view
2378             RenderPart* renderer = m_frame->ownerRenderer();
2379             if (!renderer)
2380                 return localRect;
2381                 
2382             IntRect rect(localRect);
2383             // Add borders and padding??
2384             rect.move(renderer->borderLeft() + renderer->paddingLeft(),
2385                       renderer->borderTop() + renderer->paddingTop());
2386             return parentView->convertFromRenderer(renderer, rect);
2387         }
2388         
2389         return Widget::convertToContainingView(localRect);
2390     }
2391     
2392     return localRect;
2393 }
2394
2395 IntRect FrameView::convertFromContainingView(const IntRect& parentRect) const
2396 {
2397     if (const ScrollView* parentScrollView = parent()) {
2398         if (parentScrollView->isFrameView()) {
2399             const FrameView* parentView = static_cast<const FrameView*>(parentScrollView);
2400
2401             // Get our renderer in the parent view
2402             RenderPart* renderer = m_frame->ownerRenderer();
2403             if (!renderer)
2404                 return parentRect;
2405
2406             IntRect rect = parentView->convertToRenderer(renderer, parentRect);
2407             // Subtract borders and padding
2408             rect.move(-renderer->borderLeft() - renderer->paddingLeft(),
2409                       -renderer->borderTop() - renderer->paddingTop());
2410             return rect;
2411         }
2412         
2413         return Widget::convertFromContainingView(parentRect);
2414     }
2415     
2416     return parentRect;
2417 }
2418
2419 IntPoint FrameView::convertToContainingView(const IntPoint& localPoint) const
2420 {
2421     if (const ScrollView* parentScrollView = parent()) {
2422         if (parentScrollView->isFrameView()) {
2423             const FrameView* parentView = static_cast<const FrameView*>(parentScrollView);
2424
2425             // Get our renderer in the parent view
2426             RenderPart* renderer = m_frame->ownerRenderer();
2427             if (!renderer)
2428                 return localPoint;
2429                 
2430             IntPoint point(localPoint);
2431
2432             // Add borders and padding
2433             point.move(renderer->borderLeft() + renderer->paddingLeft(),
2434                        renderer->borderTop() + renderer->paddingTop());
2435             return parentView->convertFromRenderer(renderer, point);
2436         }
2437         
2438         return Widget::convertToContainingView(localPoint);
2439     }
2440     
2441     return localPoint;
2442 }
2443
2444 IntPoint FrameView::convertFromContainingView(const IntPoint& parentPoint) const
2445 {
2446     if (const ScrollView* parentScrollView = parent()) {
2447         if (parentScrollView->isFrameView()) {
2448             const FrameView* parentView = static_cast<const FrameView*>(parentScrollView);
2449
2450             // Get our renderer in the parent view
2451             RenderPart* renderer = m_frame->ownerRenderer();
2452             if (!renderer)
2453                 return parentPoint;
2454
2455             IntPoint point = parentView->convertToRenderer(renderer, parentPoint);
2456             // Subtract borders and padding
2457             point.move(-renderer->borderLeft() - renderer->paddingLeft(),
2458                        -renderer->borderTop() - renderer->paddingTop());
2459             return point;
2460         }
2461         
2462         return Widget::convertFromContainingView(parentPoint);
2463     }
2464     
2465     return parentPoint;
2466 }
2467
2468 // Normal delay
2469 void FrameView::setRepaintThrottlingDeferredRepaintDelay(double p)
2470 {
2471     s_deferredRepaintDelay = p;
2472 }
2473
2474 // Negative value would mean that first few repaints happen without a delay
2475 void FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double p)
2476 {
2477     s_initialDeferredRepaintDelayDuringLoading = p;
2478 }
2479
2480 // The delay grows on each repaint to this maximum value
2481 void FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double p)
2482 {
2483     s_maxDeferredRepaintDelayDuringLoading = p;
2484 }
2485
2486 // On each repaint the delay increases by this amount
2487 void FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double p)
2488 {
2489     s_deferredRepaintDelayIncrementDuringLoading = p;
2490 }
2491
2492 bool FrameView::isVerticalDocument() const
2493 {
2494     if (!m_frame)
2495         return true;
2496     Document* doc = m_frame->document();
2497     if (!doc)
2498         return true;
2499     RenderObject* renderView = doc->renderer();
2500     if (!renderView)
2501         return true;
2502     return renderView->style()->isHorizontalWritingMode();
2503 }
2504
2505 bool FrameView::isFlippedDocument() const
2506 {
2507     if (!m_frame)
2508         return false;
2509     Document* doc = m_frame->document();
2510     if (!doc)
2511         return false;
2512     RenderObject* renderView = doc->renderer();
2513     if (!renderView)
2514         return false;
2515     return renderView->style()->isFlippedBlocksWritingMode();
2516 }
2517
2518 void FrameView::notifyWidgetsInAllFrames(WidgetNotification notification)
2519 {
2520     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
2521         if (RenderView* root = frame->contentRenderer())
2522             root->notifyWidgets(notification);
2523     }
2524 }
2525     
2526 AXObjectCache* FrameView::axObjectCache() const
2527 {
2528     if (frame() && frame()->document() && frame()->document()->axObjectCacheExists())
2529         return frame()->document()->axObjectCache();
2530     return 0;
2531 }
2532     
2533 } // namespace WebCore