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