Redo spellchecking of a field if the layout has changed
[WebKit-https.git] / Source / WebKit / blackberry / Api / WebPage.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2011, 2012, 2013 Research In Motion Limited. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18
19 #include "config.h"
20 #include "WebPage.h"
21
22 #include "APIShims.h"
23 #include "ApplicationCacheStorage.h"
24 #include "AuthenticationChallengeManager.h"
25 #include "AutofillManager.h"
26 #include "BackForwardController.h"
27 #include "BackForwardListBlackBerry.h"
28 #include "BackingStoreClient.h"
29 #include "BackingStore_p.h"
30 #if ENABLE(BATTERY_STATUS)
31 #include "BatteryClientBlackBerry.h"
32 #endif
33 #include "CachedImage.h"
34 #include "Chrome.h"
35 #include "ChromeClientBlackBerry.h"
36 #include "ContextMenuClientBlackBerry.h"
37 #include "CookieManager.h"
38 #include "CredentialManager.h"
39 #include "CredentialStorage.h"
40 #include "CredentialTransformData.h"
41 #include "DOMSupport.h"
42 #include "DatabaseManager.h"
43 #include "DefaultTapHighlight.h"
44 #include "DeviceMotionClientBlackBerry.h"
45 #include "DeviceOrientationClientBlackBerry.h"
46 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
47 #include "DeviceOrientationClientMock.h"
48 #endif
49 #include "DragClientBlackBerry.h"
50 // FIXME: We should be using DumpRenderTreeClient, but I'm not sure where we should
51 // create the DRT_BB object. See PR #120355.
52 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
53 #include "DumpRenderTreeBlackBerry.h"
54 #endif
55 #include "EditorClientBlackBerry.h"
56 #include "FocusController.h"
57 #include "Frame.h"
58 #include "FrameLoadRequest.h"
59 #include "FrameLoaderClientBlackBerry.h"
60 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
61 #include "GeolocationClientMock.h"
62 #endif
63 #include "GeolocationClientBlackBerry.h"
64 #include "GroupSettings.h"
65 #include "HTMLAreaElement.h"
66 #include "HTMLFrameOwnerElement.h"
67 #include "HTMLImageElement.h"
68 #include "HTMLInputElement.h"
69 #include "HTMLMediaElement.h"
70 #include "HTMLNames.h"
71 #include "HTMLParserIdioms.h"
72 #include "HTTPParsers.h"
73 #include "HistoryItem.h"
74 #include "IconDatabaseClientBlackBerry.h"
75 #include "ImageDocument.h"
76 #include "InPageSearchManager.h"
77 #include "InRegionScrollableArea.h"
78 #include "InRegionScroller_p.h"
79 #include "InputHandler.h"
80 #include "InspectorBackendDispatcher.h"
81 #include "InspectorClientBlackBerry.h"
82 #include "InspectorController.h"
83 #include "InspectorInstrumentation.h"
84 #include "InspectorOverlay.h"
85 #include "JavaScriptVariant_p.h"
86 #include "LayerWebKitThread.h"
87 #include "LocalFileSystem.h"
88 #if ENABLE(NETWORK_INFO)
89 #include "NetworkInfoClientBlackBerry.h"
90 #endif
91 #include "NetworkManager.h"
92 #include "NodeRenderStyle.h"
93 #include "NodeTraversal.h"
94 #if ENABLE(NAVIGATOR_CONTENT_UTILS)
95 #include "NavigatorContentUtilsClientBlackBerry.h"
96 #endif
97 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
98 #include "NotificationClientBlackBerry.h"
99 #endif
100 #include "Page.h"
101 #include "PageCache.h"
102 #include "PageGroup.h"
103 #include "PagePopupBlackBerry.h"
104 #include "PlatformTouchEvent.h"
105 #include "PlatformWheelEvent.h"
106 #include "PluginDatabase.h"
107 #include "PluginView.h"
108 #include "RenderLayerBacking.h"
109 #include "RenderLayerCompositor.h"
110 #if ENABLE(FULLSCREEN_API)
111 #include "RenderFullScreen.h"
112 #endif
113 #include "RenderText.h"
114 #include "RenderThemeBlackBerry.h"
115 #include "RenderTreeAsText.h"
116 #include "RenderView.h"
117 #include "RenderWidget.h"
118 #include "ScriptController.h"
119 #include "ScriptSourceCode.h"
120 #include "ScriptValue.h"
121 #include "ScrollTypes.h"
122 #include "SecurityPolicy.h"
123 #include "SelectionHandler.h"
124 #include "SelectionOverlay.h"
125 #include "Settings.h"
126 #include "Storage.h"
127 #include "StorageNamespace.h"
128 #include "SurfacePool.h"
129 #include "Text.h"
130 #include "ThreadCheck.h"
131 #include "TouchEventHandler.h"
132 #include "TransformationMatrix.h"
133 #if ENABLE(MEDIA_STREAM)
134 #include "UserMediaClientImpl.h"
135 #endif
136 #if ENABLE(VIBRATION)
137 #include "VibrationClientBlackBerry.h"
138 #endif
139 #include "VisiblePosition.h"
140 #include "WebCookieJar.h"
141 #if ENABLE(WEBDOM)
142 #include "WebDOMDocument.h"
143 #endif
144 #include "WebKitThreadViewportAccessor.h"
145 #include "WebKitVersion.h"
146 #include "WebOverlay.h"
147 #include "WebOverlay_p.h"
148 #include "WebPageClient.h"
149 #include "WebSocket.h"
150 #include "WebViewportArguments.h"
151 #include "npapi.h"
152 #include "runtime_root.h"
153
154 #if ENABLE(VIDEO)
155 #include "MediaPlayer.h"
156 #include "MediaPlayerPrivateBlackBerry.h"
157 #endif
158
159 #if USE(SKIA)
160 #include "PlatformContextSkia.h"
161 #endif
162
163 #if USE(ACCELERATED_COMPOSITING)
164 #include "FrameLayers.h"
165 #include "WebPageCompositorClient.h"
166 #include "WebPageCompositor_p.h"
167 #endif
168
169 #include <BlackBerryPlatformDeviceInfo.h>
170 #include <BlackBerryPlatformExecutableMessage.h>
171 #include <BlackBerryPlatformKeyboardEvent.h>
172 #include <BlackBerryPlatformMessageClient.h>
173 #include <BlackBerryPlatformMouseEvent.h>
174 #include <BlackBerryPlatformScreen.h>
175 #include <BlackBerryPlatformSettings.h>
176 #include <BlackBerryPlatformWebFileSystem.h>
177 #include <JavaScriptCore/APICast.h>
178 #include <JavaScriptCore/JSContextRef.h>
179 #include <JavaScriptCore/JSStringRef.h>
180 #include <SharedPointer.h>
181 #include <cmath>
182 #include <sys/keycodes.h>
183 #include <unicode/ustring.h> // platform ICU
184
185 #include <wtf/text/CString.h>
186
187 #ifndef USER_PROCESSES
188 #include <memalloc.h>
189 #endif
190
191 #if ENABLE(ACCELERATED_2D_CANVAS)
192 #include "GrContext.h"
193 #include "SharedGraphicsContext3D.h"
194 #endif
195
196 #if ENABLE(REQUEST_ANIMATION_FRAME)
197 #include "PlatformScreen.h"
198 #endif
199
200 #define DEBUG_TOUCH_EVENTS 0
201 #define DEBUG_WEBPAGE_LOAD 0
202 #define DEBUG_AC_COMMIT 0
203
204 using namespace std;
205 using namespace WebCore;
206
207 typedef const unsigned short* CUShortPtr;
208
209 namespace BlackBerry {
210 namespace WebKit {
211
212 static Vector<WebPage*>* visibleWebPages()
213 {
214     static Vector<WebPage*>* s_visibleWebPages = 0; // Initially, no web page is visible.
215     if (!s_visibleWebPages)
216         s_visibleWebPages = new Vector<WebPage*>;
217     return s_visibleWebPages;
218 }
219
220 const unsigned blockZoomMargin = 3; // Add 3 pixel margin on each side.
221 static int blockClickRadius = 0;
222 static double maximumBlockZoomScale = 3; // This scale can be clamped by the maximumScale set for the page.
223
224 const double manualScrollInterval = 0.1; // The time interval during which we associate user action with scrolling.
225
226 const IntSize minimumLayoutSize(10, 10); // Needs to be a small size, greater than 0, that we can grow the layout from.
227
228 const double minimumExpandingRatio = 0.15;
229
230 const double minimumZoomToFitScale = 0.25;
231 const double maximumImageDocumentZoomToFitScale = 2;
232
233 // Helper function to parse a URL and fill in missing parts.
234 static KURL parseUrl(const String& url)
235 {
236     String urlString(url);
237     KURL kurl = KURL(KURL(), urlString);
238     if (kurl.protocol().isEmpty()) {
239         urlString.insert("http://", 0);
240         kurl = KURL(KURL(), urlString);
241     }
242
243     return kurl;
244 }
245
246 // Helper functions to convert to and from WebCore types.
247 static inline WebCore::PlatformEvent::Type toWebCoreMouseEventType(const BlackBerry::Platform::MouseEvent::Type type)
248 {
249     switch (type) {
250     case BlackBerry::Platform::MouseEvent::MouseButtonDown:
251         return WebCore::PlatformEvent::MousePressed;
252     case Platform::MouseEvent::MouseButtonUp:
253         return WebCore::PlatformEvent::MouseReleased;
254     case Platform::MouseEvent::MouseMove:
255     default:
256         return WebCore::PlatformEvent::MouseMoved;
257     }
258 }
259
260 static inline ResourceRequestCachePolicy toWebCoreCachePolicy(Platform::NetworkRequest::CachePolicy policy)
261 {
262     switch (policy) {
263     case Platform::NetworkRequest::UseProtocolCachePolicy:
264         return UseProtocolCachePolicy;
265     case Platform::NetworkRequest::ReloadIgnoringCacheData:
266         return ReloadIgnoringCacheData;
267     case Platform::NetworkRequest::ReturnCacheDataElseLoad:
268         return ReturnCacheDataElseLoad;
269     case Platform::NetworkRequest::ReturnCacheDataDontLoad:
270         return ReturnCacheDataDontLoad;
271     default:
272         ASSERT_NOT_REACHED();
273         return UseProtocolCachePolicy;
274     }
275 }
276
277 #if ENABLE(EVENT_MODE_METATAGS)
278 static inline Platform::CursorEventMode toPlatformCursorEventMode(CursorEventMode mode)
279 {
280     switch (mode) {
281     case ProcessedCursorEvents:
282         return Platform::ProcessedCursorEvents;
283     case NativeCursorEvents:
284         return Platform::NativeCursorEvents;
285     default:
286         ASSERT_NOT_REACHED();
287         return Platform::ProcessedCursorEvents;
288     }
289 }
290
291 static inline Platform::TouchEventMode toPlatformTouchEventMode(TouchEventMode mode)
292 {
293     switch (mode) {
294     case ProcessedTouchEvents:
295         return Platform::ProcessedTouchEvents;
296     case NativeTouchEvents:
297         return Platform::NativeTouchEvents;
298     case PureTouchEventsWithMouseConversion:
299         return Platform::PureTouchEventsWithMouseConversion;
300     default:
301         ASSERT_NOT_REACHED();
302         return Platform::ProcessedTouchEvents;
303     }
304 }
305 #endif
306
307 static inline HistoryItem* historyItemFromBackForwardId(WebPage::BackForwardId id)
308 {
309     return reinterpret_cast<HistoryItem*>(id);
310 }
311
312 static inline WebPage::BackForwardId backForwardIdFromHistoryItem(HistoryItem* item)
313 {
314     return reinterpret_cast<WebPage::BackForwardId>(item);
315 }
316
317 void WebPage::setUserViewportArguments(const WebViewportArguments& viewportArguments)
318 {
319     d->m_userViewportArguments = *(viewportArguments.d);
320 }
321
322 void WebPage::resetUserViewportArguments()
323 {
324     d->m_userViewportArguments = ViewportArguments();
325 }
326
327 template <bool WebPagePrivate::* isActive>
328 class DeferredTask: public WebPagePrivate::DeferredTaskBase {
329 public:
330     static void finishOrCancel(WebPagePrivate* webPagePrivate)
331     {
332         webPagePrivate->*isActive = false;
333     }
334 protected:
335     DeferredTask(WebPagePrivate* webPagePrivate)
336         : DeferredTaskBase(webPagePrivate, isActive)
337     {
338     }
339     typedef DeferredTask<isActive> DeferredTaskType;
340 };
341
342 void WebPage::autofillTextField(const BlackBerry::Platform::String& item)
343 {
344     if (!d->m_webSettings->isFormAutofillEnabled())
345         return;
346
347     d->m_autofillManager->autofillTextField(item);
348 }
349
350 BlackBerry::Platform::String WebPage::renderTreeAsText()
351 {
352     return externalRepresentation(d->m_mainFrame);
353 }
354
355 WebPagePrivate::WebPagePrivate(WebPage* webPage, WebPageClient* client, const IntRect& rect)
356     : m_webPage(webPage)
357     , m_client(client)
358     , m_inspectorClient(0)
359     , m_page(0) // Initialized by init.
360     , m_mainFrame(0) // Initialized by init.
361     , m_currentContextNode(0)
362     , m_webSettings(0) // Initialized by init.
363     , m_cookieJar(0)
364     , m_visible(false)
365     , m_activationState(ActivationActive)
366     , m_shouldResetTilesWhenShown(false)
367     , m_shouldZoomToInitialScaleAfterLoadFinished(false)
368     , m_userScalable(true)
369     , m_userPerformedManualZoom(false)
370     , m_userPerformedManualScroll(false)
371     , m_contentsSizeChanged(false)
372     , m_overflowExceedsContentsSize(false)
373     , m_resetVirtualViewportOnCommitted(true)
374     , m_shouldUseFixedDesktopMode(false)
375     , m_inspectorEnabled(false)
376     , m_preventIdleDimmingCount(0)
377 #if ENABLE(TOUCH_EVENTS)
378     , m_preventDefaultOnTouchStart(false)
379 #endif
380     , m_nestedLayoutFinishedCount(0)
381     , m_actualVisibleWidth(rect.width())
382     , m_actualVisibleHeight(rect.height())
383     , m_defaultLayoutSize(minimumLayoutSize)
384     , m_didRestoreFromPageCache(false)
385     , m_viewMode(WebPagePrivate::Desktop) // Default to Desktop mode for PB.
386     , m_loadState(WebPagePrivate::None)
387     , m_transformationMatrix(new TransformationMatrix())
388     , m_backingStore(0) // Initialized by init.
389     , m_backingStoreClient(0) // Initialized by init.
390     , m_webkitThreadViewportAccessor(new WebKitThreadViewportAccessor(this))
391     , m_inPageSearchManager(new InPageSearchManager(this))
392     , m_inputHandler(new InputHandler(this))
393     , m_selectionHandler(new SelectionHandler(this))
394     , m_touchEventHandler(new TouchEventHandler(this))
395     , m_proximityDetector(new ProximityDetector(this))
396 #if ENABLE(EVENT_MODE_METATAGS)
397     , m_cursorEventMode(ProcessedCursorEvents)
398     , m_touchEventMode(ProcessedTouchEvents)
399 #endif
400 #if ENABLE(FULLSCREEN_API) && ENABLE(VIDEO)
401     , m_scaleBeforeFullScreen(-1.0)
402 #endif
403     , m_currentCursor(Platform::CursorNone)
404     , m_dumpRenderTree(0) // Lazy initialization.
405     , m_initialScale(-1.0)
406     , m_minimumScale(-1.0)
407     , m_maximumScale(-1.0)
408     , m_forceRespectViewportArguments(false)
409     , m_anchorInNodeRectRatio(-1, -1)
410     , m_currentBlockZoomNode(0)
411     , m_currentBlockZoomAdjustedNode(0)
412     , m_shouldReflowBlock(false)
413     , m_lastUserEventTimestamp(0.0)
414     , m_pluginMouseButtonPressed(false)
415     , m_pluginMayOpenNewTab(false)
416 #if USE(ACCELERATED_COMPOSITING)
417     , m_rootLayerCommitTimer(adoptPtr(new Timer<WebPagePrivate>(this, &WebPagePrivate::rootLayerCommitTimerFired)))
418     , m_needsOneShotDrawingSynchronization(false)
419     , m_needsCommit(false)
420     , m_suspendRootLayerCommit(false)
421 #endif
422     , m_pendingOrientation(-1)
423     , m_fullscreenNode(0)
424     , m_hasInRegionScrollableAreas(false)
425     , m_updateDelegatedOverlaysDispatched(false)
426     , m_deferredTasksTimer(this, &WebPagePrivate::deferredTasksTimerFired)
427     , m_selectPopup(0)
428     , m_autofillManager(AutofillManager::create(this))
429     , m_documentStyleRecalcPostponed(false)
430     , m_documentChildNeedsStyleRecalc(false)
431 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
432     , m_notificationManager(this)
433 #endif
434     , m_didStartAnimations(false)
435     , m_animationStartTime(0)
436 {
437     static bool isInitialized = false;
438     if (!isInitialized) {
439         isInitialized = true;
440         BlackBerry::Platform::DeviceInfo::instance();
441         defaultUserAgent();
442     }
443
444     AuthenticationChallengeManager::instance()->pageCreated(this);
445     clearCachedHitTestResult();
446 }
447
448 WebPage::WebPage(WebPageClient* client, const BlackBerry::Platform::String& pageGroupName, const Platform::IntRect& rect)
449 {
450     globalInitialize();
451     d = new WebPagePrivate(this, client, rect);
452     d->init(pageGroupName);
453 }
454
455 WebPagePrivate::~WebPagePrivate()
456 {
457     // Hand the backingstore back to another owner if necessary.
458     m_webPage->setVisible(false);
459     if (BackingStorePrivate::currentBackingStoreOwner() == m_webPage)
460         BackingStorePrivate::setCurrentBackingStoreOwner(0);
461
462     delete m_webSettings;
463     m_webSettings = 0;
464
465     delete m_cookieJar;
466     m_cookieJar = 0;
467
468     delete m_webkitThreadViewportAccessor;
469     m_webkitThreadViewportAccessor = 0;
470
471     delete m_backingStoreClient;
472     m_backingStoreClient = 0;
473     m_backingStore = 0;
474
475     delete m_page;
476     m_page = 0;
477
478     delete m_transformationMatrix;
479     m_transformationMatrix = 0;
480
481     delete m_inPageSearchManager;
482     m_inPageSearchManager = 0;
483
484     delete m_selectionHandler;
485     m_selectionHandler = 0;
486
487     delete m_inputHandler;
488     m_inputHandler = 0;
489
490     delete m_touchEventHandler;
491     m_touchEventHandler = 0;
492
493     delete m_proximityDetector;
494     m_proximityDetector = 0;
495
496 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
497     BlackBerry::Platform::deleteGuardedObject(static_cast<DumpRenderTree*>(m_dumpRenderTree));
498     m_dumpRenderTree = 0;
499 #endif
500
501     AuthenticationChallengeManager::instance()->pageDeleted(this);
502 }
503
504 WebPage::~WebPage()
505 {
506     deleteGuardedObject(d);
507     d = 0;
508 }
509
510 Page* WebPagePrivate::core(const WebPage* webPage)
511 {
512     return webPage->d->m_page;
513 }
514
515 void WebPagePrivate::init(const BlackBerry::Platform::String& pageGroupName)
516 {
517     m_webSettings = WebSettings::createFromStandardSettings();
518     m_webSettings->setUserAgentString(defaultUserAgent());
519
520     ChromeClientBlackBerry* chromeClient = new ChromeClientBlackBerry(this);
521 #if ENABLE(CONTEXT_MENUS)
522     ContextMenuClientBlackBerry* contextMenuClient = 0;
523     contextMenuClient = new ContextMenuClientBlackBerry();
524 #endif
525     EditorClientBlackBerry* editorClient = new EditorClientBlackBerry(this);
526     DragClientBlackBerry* dragClient = 0;
527 #if ENABLE(DRAG_SUPPORT)
528     dragClient = new DragClientBlackBerry();
529 #endif
530 #if ENABLE(INSPECTOR)
531     m_inspectorClient = new InspectorClientBlackBerry(this);
532 #endif
533
534     FrameLoaderClientBlackBerry* frameLoaderClient = new FrameLoaderClientBlackBerry();
535
536     Page::PageClients pageClients;
537     pageClients.chromeClient = chromeClient;
538 #if ENABLE(CONTEXT_MENUS)
539     pageClients.contextMenuClient = contextMenuClient;
540 #endif
541     pageClients.editorClient = editorClient;
542     pageClients.dragClient = dragClient;
543     pageClients.inspectorClient = m_inspectorClient;
544     pageClients.backForwardClient = BackForwardListBlackBerry::create(this);
545
546     m_page = new Page(pageClients);
547 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
548     if (isRunningDrt()) {
549         // In case running in DumpRenderTree mode set the controller to mock provider.
550         GeolocationClientMock* mock = new GeolocationClientMock();
551         WebCore::provideGeolocationTo(m_page, mock);
552         mock->setController(WebCore::GeolocationController::from(m_page));
553     } else
554 #endif
555         WebCore::provideGeolocationTo(m_page, new GeolocationClientBlackBerry(this));
556 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
557     if (getenv("drtRun"))
558         WebCore::provideDeviceOrientationTo(m_page, new DeviceOrientationClientMock);
559     else
560 #endif
561         WebCore::provideDeviceOrientationTo(m_page, new DeviceOrientationClientBlackBerry(this));
562
563     WebCore::provideDeviceMotionTo(m_page, new DeviceMotionClientBlackBerry(this));
564 #if ENABLE(VIBRATION)
565     WebCore::provideVibrationTo(m_page, new VibrationClientBlackBerry());
566 #endif
567
568 #if ENABLE(BATTERY_STATUS)
569     WebCore::provideBatteryTo(m_page, new WebCore::BatteryClientBlackBerry(this));
570 #endif
571
572 #if ENABLE(MEDIA_STREAM)
573     WebCore::provideUserMediaTo(m_page, new UserMediaClientImpl(m_webPage));
574 #endif
575
576 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
577     WebCore::provideNotification(m_page, new NotificationClientBlackBerry(this));
578 #endif
579
580 #if ENABLE(NAVIGATOR_CONTENT_UTILS)
581     m_navigatorContentUtilsClient = adoptPtr(new NavigatorContentUtilsClientBlackBerry(this));
582     WebCore::provideNavigatorContentUtilsTo(m_page, m_navigatorContentUtilsClient.get());
583 #endif
584
585 #if ENABLE(NETWORK_INFO)
586     WebCore::provideNetworkInfoTo(m_page, new WebCore::NetworkInfoClientBlackBerry(this));
587 #endif
588
589     m_page->setDeviceScaleFactor(m_webSettings->devicePixelRatio());
590
591     m_page->addLayoutMilestones(DidFirstVisuallyNonEmptyLayout);
592
593 #if USE(ACCELERATED_COMPOSITING)
594     m_tapHighlight = DefaultTapHighlight::create(this);
595     m_selectionHighlight = DefaultTapHighlight::create(this);
596     m_selectionOverlay = SelectionOverlay::create(this);
597     m_page->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
598 #endif
599
600     // FIXME: We explicitly call setDelegate() instead of passing ourself in createFromStandardSettings()
601     // so that we only get one didChangeSettings() callback when we set the page group name. This causes us
602     // to make a copy of the WebSettings since some WebSettings method make use of the page group name.
603     // Instead, we shouldn't be storing the page group name in WebSettings.
604     m_webSettings->setPageGroupName(pageGroupName);
605     m_webSettings->setDelegate(this);
606     didChangeSettings(m_webSettings);
607
608     RefPtr<Frame> newFrame = Frame::create(m_page, /* HTMLFrameOwnerElement* */ 0, frameLoaderClient);
609
610     m_mainFrame = newFrame.get();
611     frameLoaderClient->setFrame(m_mainFrame, this);
612     m_mainFrame->init();
613
614     m_inRegionScroller = adoptPtr(new InRegionScroller(this));
615
616 #if ENABLE(WEBGL)
617     m_page->settings()->setWebGLEnabled(true);
618 #endif
619 #if ENABLE(ACCELERATED_2D_CANVAS)
620     m_page->settings()->setCanvasUsesAcceleratedDrawing(true);
621     m_page->settings()->setAccelerated2dCanvasEnabled(true);
622 #endif
623
624     m_page->settings()->setInteractiveFormValidationEnabled(true);
625     m_page->settings()->setAllowUniversalAccessFromFileURLs(false);
626     m_page->settings()->setAllowFileAccessFromFileURLs(false);
627     m_page->settings()->setFixedPositionCreatesStackingContext(true);
628
629     m_backingStoreClient = BackingStoreClient::create(m_mainFrame, /* parent frame */ 0, m_webPage);
630     // The direct access to BackingStore is left here for convenience since it
631     // is owned by BackingStoreClient and then deleted by its destructor.
632     m_backingStore = m_backingStoreClient->backingStore();
633
634     blockClickRadius = int(roundf(0.35 * Platform::Graphics::Screen::primaryScreen()->pixelsPerInch(0).width())); // The clicked rectangle area should be a fixed unit of measurement.
635
636     m_page->settings()->setDelegateSelectionPaint(true);
637
638 #if ENABLE(REQUEST_ANIMATION_FRAME)
639     m_page->windowScreenDidChange((PlatformDisplayID)0);
640 #endif
641
642 #if ENABLE(WEB_TIMING)
643     m_page->settings()->setMemoryInfoEnabled(true);
644 #endif
645
646 #if ENABLE(FILE_SYSTEM)
647     static bool localFileSystemInitialized = false;
648     if (!localFileSystemInitialized) {
649         localFileSystemInitialized = true;
650         WebCore::LocalFileSystem::initializeLocalFileSystem("/");
651     }
652 #endif
653
654 #if USE(ACCELERATED_COMPOSITING)
655     // The compositor will be needed for overlay rendering, so create it
656     // unconditionally. It will allocate OpenGL objects lazily, so this incurs
657     // no overhead in the unlikely case where the compositor is not needed.
658     Platform::userInterfaceThreadMessageClient()->dispatchSyncMessage(
659             createMethodCallMessage(&WebPagePrivate::createCompositor, this));
660 #endif
661 }
662
663 class DeferredTaskLoadManualScript: public DeferredTask<&WebPagePrivate::m_wouldLoadManualScript> {
664 public:
665     explicit DeferredTaskLoadManualScript(WebPagePrivate* webPagePrivate, const KURL& url)
666         : DeferredTaskType(webPagePrivate)
667     {
668         webPagePrivate->m_cachedManualScript = url;
669     }
670 private:
671     virtual void performInternal(WebPagePrivate* webPagePrivate)
672     {
673         webPagePrivate->m_mainFrame->script()->executeIfJavaScriptURL(webPagePrivate->m_cachedManualScript, DoNotReplaceDocumentIfJavaScriptURL);
674     }
675 };
676
677 void WebPagePrivate::load(const BlackBerry::Platform::String& url, const BlackBerry::Platform::String& networkToken, const BlackBerry::Platform::String& method, Platform::NetworkRequest::CachePolicy cachePolicy, const char* data, size_t dataLength, const char* const* headers, size_t headersLength, bool isInitial, bool mustHandleInternally, bool needReferer, bool forceDownload, const BlackBerry::Platform::String& overrideContentType, const BlackBerry::Platform::String& suggestedSaveName)
678 {
679     stopCurrentLoad();
680     DeferredTaskLoadManualScript::finishOrCancel(this);
681
682     String urlString(url);
683     if (urlString.startsWith("vs:", false)) {
684         urlString = urlString.substring(3);
685         m_mainFrame->setInViewSourceMode(true);
686     } else
687         m_mainFrame->setInViewSourceMode(false);
688
689     KURL kurl = parseUrl(urlString);
690     if (protocolIs(kurl, "javascript")) {
691         // Never run javascript while loading is deferred.
692         if (m_page->defersLoading())
693             m_deferredTasks.append(adoptPtr(new DeferredTaskLoadManualScript(this, kurl)));
694         else
695             m_mainFrame->script()->executeIfJavaScriptURL(kurl, DoNotReplaceDocumentIfJavaScriptURL);
696         return;
697     }
698
699     if (isInitial)
700         NetworkManager::instance()->setInitialURL(kurl);
701
702     ResourceRequest request(kurl);
703     request.setToken(networkToken);
704     if (isInitial || mustHandleInternally)
705         request.setMustHandleInternally(true);
706     request.setHTTPMethod(method);
707     request.setCachePolicy(toWebCoreCachePolicy(cachePolicy));
708     if (!overrideContentType.empty())
709         request.setOverrideContentType(overrideContentType);
710
711     if (data)
712         request.setHTTPBody(FormData::create(data, dataLength));
713
714     for (unsigned i = 0; i + 1 < headersLength; i += 2)
715         request.addHTTPHeaderField(headers[i], headers[i + 1]);
716     if (needReferer && focusedOrMainFrame() && focusedOrMainFrame()->document())
717         request.addHTTPHeaderField("Referer", focusedOrMainFrame()->document()->url().string().utf8().data());
718
719     if (forceDownload)
720         request.setForceDownload(true);
721
722     request.setSuggestedSaveName(suggestedSaveName);
723
724     m_mainFrame->loader()->load(FrameLoadRequest(m_mainFrame, request));
725 }
726
727 void WebPage::load(const BlackBerry::Platform::String& url, const BlackBerry::Platform::String& networkToken, bool isInitial, bool needReferer, bool forceDownload)
728 {
729     d->load(url, networkToken, "GET", Platform::NetworkRequest::UseProtocolCachePolicy, 0, 0, 0, 0, isInitial, false, needReferer, forceDownload);
730 }
731
732 void WebPage::loadExtended(const char* url, const char* networkToken, const char* method, Platform::NetworkRequest::CachePolicy cachePolicy, const char* data, size_t dataLength, const char* const* headers, size_t headersLength, bool mustHandleInternally)
733 {
734     d->load(url, networkToken, method, cachePolicy, data, dataLength, headers, headersLength, false, mustHandleInternally, false, false, "");
735 }
736
737 void WebPage::loadFile(const BlackBerry::Platform::String& path, const BlackBerry::Platform::String& overrideContentType)
738 {
739     BlackBerry::Platform::String fileUrl(path);
740     if (fileUrl.startsWith("/"))
741         fileUrl = BlackBerry::Platform::String("file://", 7) + fileUrl;
742     else if (!fileUrl.startsWith("file:///"))
743         return;
744
745     d->load(fileUrl, BlackBerry::Platform::String::emptyString(), BlackBerry::Platform::String("GET", 3), Platform::NetworkRequest::UseProtocolCachePolicy, 0, 0, 0, 0, false, false, false, false, overrideContentType.c_str());
746 }
747
748 void WebPage::download(const Platform::NetworkRequest& request)
749 {
750     vector<const char*> headers;
751     Platform::NetworkRequest::HeaderList& list = request.getHeaderListRef();
752     for (unsigned i = 0; i < list.size(); i++) {
753         headers.push_back(list[i].first.c_str());
754         headers.push_back(list[i].second.c_str());
755     }
756     d->load(request.getUrlRef(), BlackBerry::Platform::String::emptyString(), "GET", Platform::NetworkRequest::UseProtocolCachePolicy, 0, 0, headers.empty() ? 0 : &headers[0], headers.size(), false, false, false, true, "", request.getSuggestedSaveName().c_str());
757 }
758
759 void WebPagePrivate::loadString(const BlackBerry::Platform::String& string, const BlackBerry::Platform::String& baseURL, const BlackBerry::Platform::String& contentType, const BlackBerry::Platform::String& failingURL)
760 {
761     KURL kurl = parseUrl(baseURL);
762     ResourceRequest request(kurl);
763     WTF::RefPtr<SharedBuffer> buffer
764         = SharedBuffer::create(string.c_str(), string.length());
765     SubstituteData substituteData(buffer,
766         extractMIMETypeFromMediaType(contentType),
767         extractCharsetFromMediaType(contentType),
768         !failingURL.empty() ? parseUrl(failingURL) : KURL());
769     m_mainFrame->loader()->load(FrameLoadRequest(m_mainFrame, request, substituteData));
770 }
771
772 void WebPage::loadString(const BlackBerry::Platform::String& string, const BlackBerry::Platform::String& baseURL, const BlackBerry::Platform::String& mimeType, const BlackBerry::Platform::String& failingURL)
773 {
774     d->loadString(string, baseURL, mimeType, failingURL);
775 }
776
777 bool WebPagePrivate::executeJavaScript(const BlackBerry::Platform::String& scriptUTF8, JavaScriptDataType& returnType, BlackBerry::Platform::String& returnValue)
778 {
779     BLACKBERRY_ASSERT(scriptUTF8.isUtf8());
780     String script = scriptUTF8;
781
782     if (script.isNull()) {
783         returnType = JSException;
784         return false;
785     }
786
787     if (script.isEmpty()) {
788         returnType = JSUndefined;
789         return true;
790     }
791
792     ScriptValue result = m_mainFrame->script()->executeScript(script, false);
793     JSC::JSValue value = result.jsValue();
794     if (!value) {
795         returnType = JSException;
796         return false;
797     }
798
799     if (value.isUndefined())
800         returnType = JSUndefined;
801     else if (value.isNull())
802         returnType = JSNull;
803     else if (value.isBoolean())
804         returnType = JSBoolean;
805     else if (value.isNumber())
806         returnType = JSNumber;
807     else if (value.isString())
808         returnType = JSString;
809     else if (value.isObject())
810         returnType = JSObject;
811     else
812         returnType = JSUndefined;
813
814     if (returnType == JSBoolean || returnType == JSNumber || returnType == JSString || returnType == JSObject) {
815         JSC::ExecState* exec = m_mainFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
816         returnValue = result.toString(exec);
817     }
818
819     return true;
820 }
821
822 bool WebPage::executeJavaScript(const BlackBerry::Platform::String& script, JavaScriptDataType& returnType, BlackBerry::Platform::String& returnValue)
823 {
824     return d->executeJavaScript(script, returnType, returnValue);
825 }
826
827 bool WebPagePrivate::executeJavaScriptInIsolatedWorld(const ScriptSourceCode& sourceCode, JavaScriptDataType& returnType, BlackBerry::Platform::String& returnValue)
828 {
829     if (!m_isolatedWorld)
830         m_isolatedWorld = m_mainFrame->script()->createWorld();
831
832     // Use evaluateInWorld to avoid canExecuteScripts check.
833     ScriptValue result = m_mainFrame->script()->evaluateInWorld(sourceCode, m_isolatedWorld.get());
834     JSC::JSValue value = result.jsValue();
835     if (!value) {
836         returnType = JSException;
837         return false;
838     }
839
840     if (value.isUndefined())
841         returnType = JSUndefined;
842     else if (value.isNull())
843         returnType = JSNull;
844     else if (value.isBoolean())
845         returnType = JSBoolean;
846     else if (value.isNumber())
847         returnType = JSNumber;
848     else if (value.isString())
849         returnType = JSString;
850     else if (value.isObject())
851         returnType = JSObject;
852     else
853         returnType = JSUndefined;
854
855     if (returnType == JSBoolean || returnType == JSNumber || returnType == JSString || returnType == JSObject) {
856         JSC::ExecState* exec = m_mainFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
857         returnValue = result.toString(exec);
858     }
859
860     return true;
861 }
862
863 bool WebPage::executeJavaScriptInIsolatedWorld(const std::wstring& script, JavaScriptDataType& returnType, BlackBerry::Platform::String& returnValue)
864 {
865     // On our platform wchar_t is unsigned int and UChar is unsigned short
866     // so we have to convert using ICU conversion function
867     int lengthCopied = 0;
868     UErrorCode error = U_ZERO_ERROR;
869     const int length = script.length() + 1 /*null termination char*/;
870     UChar data[length];
871
872     // FIXME: PR 138162 is giving U_INVALID_CHAR_FOUND error.
873     u_strFromUTF32(data, length, &lengthCopied, reinterpret_cast<const UChar32*>(script.c_str()), script.length(), &error);
874     BLACKBERRY_ASSERT(error == U_ZERO_ERROR);
875     if (error != U_ZERO_ERROR) {
876         Platform::logAlways(Platform::LogLevelCritical, "WebPage::executeJavaScriptInIsolatedWorld failed to convert UTF16 to JavaScript!");
877         return false;
878     }
879     String str = String(data, lengthCopied);
880     ScriptSourceCode sourceCode(str, KURL());
881     return d->executeJavaScriptInIsolatedWorld(sourceCode, returnType, returnValue);
882 }
883
884 bool WebPage::executeJavaScriptInIsolatedWorld(const BlackBerry::Platform::String& scriptUTF8, JavaScriptDataType& returnType, BlackBerry::Platform::String& returnValue)
885 {
886     BLACKBERRY_ASSERT(scriptUTF8.isUtf8());
887     ScriptSourceCode sourceCode(scriptUTF8, KURL());
888     return d->executeJavaScriptInIsolatedWorld(sourceCode, returnType, returnValue);
889 }
890
891 void WebPage::executeJavaScriptFunction(const std::vector<BlackBerry::Platform::String> &function, const std::vector<JavaScriptVariant> &args, JavaScriptVariant& returnValue)
892 {
893     if (!d->m_mainFrame) {
894         returnValue.setType(JavaScriptVariant::Exception);
895         return;
896     }
897
898     JSC::Bindings::RootObject* root = d->m_mainFrame->script()->bindingRootObject();
899     if (!root) {
900         returnValue.setType(JavaScriptVariant::Exception);
901         return;
902     }
903
904     JSC::ExecState* exec = root->globalObject()->globalExec();
905     JSGlobalContextRef ctx = toGlobalRef(exec);
906
907     JSC::APIEntryShim shim(exec);
908     WTF::Vector<JSValueRef> argListRef(args.size());
909     for (unsigned i = 0; i < args.size(); ++i)
910         argListRef[i] = BlackBerryJavaScriptVariantToJSValueRef(ctx, args[i]);
911
912     JSValueRef windowObjectValue = toRef(d->m_mainFrame->script()->globalObject(mainThreadNormalWorld()));
913     JSObjectRef obj = JSValueToObject(ctx, windowObjectValue, 0);
914     JSObjectRef thisObject = obj;
915     for (unsigned i = 0; i < function.size(); ++i) {
916         JSStringRef str = JSStringCreateWithUTF8CString(function[i].c_str());
917         thisObject = obj;
918         obj = JSValueToObject(ctx, JSObjectGetProperty(ctx, obj, str, 0), 0);
919         JSStringRelease(str);
920         if (!obj)
921             break;
922     }
923
924     JSObjectRef functionObject = obj;
925     JSValueRef result = 0;
926     if (functionObject && thisObject)
927         result = JSObjectCallAsFunction(ctx, functionObject, thisObject, args.size(), argListRef.data(), 0);
928
929     if (!result) {
930         returnValue.setType(JavaScriptVariant::Exception);
931         return;
932     }
933
934     returnValue = JSValueRefToBlackBerryJavaScriptVariant(ctx, result);
935 }
936
937 void WebPagePrivate::stopCurrentLoad()
938 {
939     // This function should contain all common code triggered by WebPage::load
940     // (which stops any load in progress before starting the new load) and
941     // WebPage::stoploading (the entry point for the client to stop the load
942     // explicitly). If it should only be done while stopping the load
943     // explicitly, it goes in WebPage::stopLoading, not here.
944     m_mainFrame->loader()->stopAllLoaders();
945
946     // Cancel any deferred script that hasn't been processed yet.
947     DeferredTaskLoadManualScript::finishOrCancel(this);
948 }
949
950 void WebPage::stopLoading()
951 {
952     d->stopCurrentLoad();
953 }
954
955 static void closeURLRecursively(Frame* frame)
956 {
957     // Do not create more frame please.
958     FrameLoaderClientBlackBerry* frameLoaderClient = static_cast<FrameLoaderClientBlackBerry*>(frame->loader()->client());
959     frameLoaderClient->suppressChildFrameCreation();
960
961     frame->loader()->closeURL();
962
963     Vector<RefPtr<Frame>, 10> childFrames;
964
965     for (RefPtr<Frame> childFrame = frame->tree()->firstChild(); childFrame; childFrame = childFrame->tree()->nextSibling())
966         childFrames.append(childFrame);
967
968     unsigned size = childFrames.size();
969     for (unsigned i = 0; i < size; i++)
970         closeURLRecursively(childFrames[i].get());
971 }
972
973 void WebPagePrivate::prepareToDestroy()
974 {
975     // Before the client starts tearing itself down, dispatch the unload event
976     // so it can take effect while all the client's state (e.g. scroll position)
977     // is still present.
978     closeURLRecursively(m_mainFrame);
979 }
980
981 void WebPage::prepareToDestroy()
982 {
983     d->prepareToDestroy();
984 }
985
986 bool WebPage::dispatchBeforeUnloadEvent()
987 {
988     return d->m_page->mainFrame()->loader()->shouldClose();
989 }
990
991 static void enableCrossSiteXHRRecursively(Frame* frame)
992 {
993     frame->document()->securityOrigin()->grantUniversalAccess();
994
995     Vector<RefPtr<Frame>, 10> childFrames;
996     for (RefPtr<Frame> childFrame = frame->tree()->firstChild(); childFrame; childFrame = childFrame->tree()->nextSibling())
997         childFrames.append(childFrame);
998
999     unsigned size = childFrames.size();
1000     for (unsigned i = 0; i < size; i++)
1001         enableCrossSiteXHRRecursively(childFrames[i].get());
1002 }
1003
1004 void WebPagePrivate::enableCrossSiteXHR()
1005 {
1006     enableCrossSiteXHRRecursively(m_mainFrame);
1007 }
1008
1009 void WebPage::enableCrossSiteXHR()
1010 {
1011     d->enableCrossSiteXHR();
1012 }
1013
1014 void WebPagePrivate::addOriginAccessWhitelistEntry(const BlackBerry::Platform::String& sourceOrigin, const BlackBerry::Platform::String& destinationOrigin, bool allowDestinationSubdomains)
1015 {
1016     RefPtr<SecurityOrigin> source = SecurityOrigin::createFromString(sourceOrigin);
1017     if (source->isUnique())
1018         return;
1019
1020     KURL destination(KURL(), destinationOrigin);
1021     SecurityPolicy::addOriginAccessWhitelistEntry(*source, destination.protocol(), destination.host(), allowDestinationSubdomains);
1022 }
1023
1024 void WebPage::addOriginAccessWhitelistEntry(const BlackBerry::Platform::String& sourceOrigin, const BlackBerry::Platform::String& destinationOrigin, bool allowDestinationSubdomains)
1025 {
1026     d->addOriginAccessWhitelistEntry(sourceOrigin, destinationOrigin, allowDestinationSubdomains);
1027 }
1028
1029 void WebPagePrivate::removeOriginAccessWhitelistEntry(const BlackBerry::Platform::String& sourceOrigin, const BlackBerry::Platform::String& destinationOrigin, bool allowDestinationSubdomains)
1030 {
1031     RefPtr<SecurityOrigin> source = SecurityOrigin::createFromString(sourceOrigin);
1032     if (source->isUnique())
1033         return;
1034
1035     KURL destination(KURL(), destinationOrigin);
1036     SecurityPolicy::removeOriginAccessWhitelistEntry(*source, destination.protocol(), destination.host(), allowDestinationSubdomains);
1037 }
1038
1039 void WebPage::removeOriginAccessWhitelistEntry(const BlackBerry::Platform::String& sourceOrigin, const BlackBerry::Platform::String& destinationOrigin, bool allowDestinationSubdomains)
1040 {
1041     d->removeOriginAccessWhitelistEntry(sourceOrigin, destinationOrigin, allowDestinationSubdomains);
1042 }
1043
1044 void WebPagePrivate::setLoadState(LoadState state)
1045 {
1046     if (m_loadState == state)
1047         return;
1048
1049     bool isFirstLoad = m_loadState == None;
1050
1051     // See RIM Bug #1068.
1052     if (state == Finished && m_mainFrame && m_mainFrame->document())
1053         m_mainFrame->document()->updateStyleIfNeeded();
1054
1055     // Dispatch the backingstore background color at important state changes.
1056     m_backingStore->d->setWebPageBackgroundColor(documentBackgroundColor());
1057
1058     m_loadState = state;
1059
1060 #if DEBUG_WEBPAGE_LOAD
1061     Platform::logAlways(Platform::LogLevelInfo, "WebPagePrivate::setLoadState %d", state);
1062 #endif
1063
1064     switch (m_loadState) {
1065     case Provisional:
1066         if (isFirstLoad) {
1067             // Paints the visible backingstore as settings()->backgroundColor()
1068             // to prevent initial checkerboard on the first blit.
1069             m_backingStore->d->renderAndBlitVisibleContentsImmediately();
1070         }
1071         break;
1072     case Committed:
1073         {
1074 #if ENABLE(ACCELERATED_2D_CANVAS)
1075             if (m_page->settings()->canvasUsesAcceleratedDrawing()) {
1076                 // Free GPU resources as we're on a new page.
1077                 // This will help us to free memory pressure.
1078                 SharedGraphicsContext3D::get()->makeContextCurrent();
1079                 GrContext* grContext = Platform::Graphics::getGrContext();
1080                 grContext->freeGpuResources();
1081             }
1082 #endif
1083
1084 #if USE(ACCELERATED_COMPOSITING)
1085             releaseLayerResources();
1086 #endif
1087
1088             // Suspend screen update to avoid ui thread blitting while resetting backingstore.
1089             // FIXME: Do we really need to suspend/resume both backingstore and screen here?
1090             m_backingStore->d->suspendBackingStoreUpdates();
1091             m_backingStore->d->suspendScreenUpdates();
1092
1093             m_previousContentsSize = IntSize();
1094             m_backingStore->d->resetRenderQueue();
1095             m_backingStore->d->resetTiles();
1096             m_backingStore->d->setScrollingOrZooming(false, false /* shouldBlit */);
1097             m_shouldZoomToInitialScaleAfterLoadFinished = false;
1098             m_userPerformedManualZoom = false;
1099             m_userPerformedManualScroll = false;
1100             m_shouldUseFixedDesktopMode = false;
1101             m_forceRespectViewportArguments = false;
1102             if (m_resetVirtualViewportOnCommitted) // For DRT.
1103                 m_virtualViewportSize = IntSize();
1104             if (m_webSettings->viewportWidth() > 0)
1105                 m_virtualViewportSize = IntSize(m_webSettings->viewportWidth(), m_defaultLayoutSize.height());
1106
1107             // Check if we have already process the meta viewport tag, this only happens on history navigation.
1108             // For back/forward history navigation, we should only keep these previous values if the document
1109             // has the meta viewport tag when the state is Committed in setLoadState.
1110             static ViewportArguments defaultViewportArguments;
1111             bool documentHasViewportArguments = false;
1112             if (m_mainFrame && m_mainFrame->document() && m_mainFrame->document()->viewportArguments() != defaultViewportArguments)
1113                 documentHasViewportArguments = true;
1114             if (!(m_didRestoreFromPageCache && documentHasViewportArguments)) {
1115                 m_viewportArguments = ViewportArguments();
1116                 m_userScalable = m_webSettings->isUserScalable();
1117                 resetScales();
1118
1119                 // At the moment we commit a new load, set the viewport arguments
1120                 // to any fallback values. If there is a meta viewport in the
1121                 // content it will overwrite the fallback arguments soon.
1122                 dispatchViewportPropertiesDidChange(m_userViewportArguments);
1123                 if (m_userViewportArguments != defaultViewportArguments)
1124                     m_forceRespectViewportArguments = true;
1125             } else {
1126                 Platform::IntSize virtualViewport = recomputeVirtualViewportFromViewportArguments();
1127                 m_webPage->setVirtualViewportSize(virtualViewport);
1128                 if (m_shouldUseFixedDesktopMode)
1129                     setViewMode(FixedDesktop);
1130                 else
1131                     setViewMode(Desktop);
1132             }
1133
1134 #if ENABLE(EVENT_MODE_METATAGS)
1135             didReceiveCursorEventMode(ProcessedCursorEvents);
1136             didReceiveTouchEventMode(ProcessedTouchEvents);
1137 #endif
1138
1139             // Reset block zoom and reflow.
1140             resetBlockZoom();
1141 #if ENABLE(VIEWPORT_REFLOW)
1142             toggleTextReflowIfEnabledForBlockZoomOnly();
1143 #endif
1144
1145             // Notify InputHandler of state change.
1146             m_inputHandler->setInputModeEnabled(false);
1147
1148             // Set the scroll to origin here and notify the client since we'll be
1149             // zooming below without any real contents yet thus the contents size
1150             // we report to the client could make our current scroll position invalid.
1151             setScrollPosition(IntPoint::zero());
1152             notifyTransformedScrollChanged();
1153
1154             // FIXME: Do we really need to suspend/resume both backingstore and screen here?
1155             m_backingStore->d->resumeBackingStoreUpdates();
1156             // Paints the visible backingstore as white. Note it is important we do
1157             // this strictly after re-setting the scroll position to origin and resetting
1158             // the scales otherwise the visible contents calculation is wrong and we
1159             // can end up blitting artifacts instead. See: RIM Bug #401.
1160             m_backingStore->d->resumeScreenUpdates(BackingStore::RenderAndBlit);
1161
1162             // Update cursor status.
1163             updateCursor();
1164
1165             break;
1166         }
1167     case Finished:
1168     case Failed:
1169         // Notify client of the initial zoom change.
1170         m_client->scaleChanged();
1171         m_backingStore->d->updateTiles(true /* updateVisible */, false /* immediate */);
1172         break;
1173     default:
1174         break;
1175     }
1176 }
1177
1178 double WebPagePrivate::clampedScale(double scale) const
1179 {
1180     if (scale < minimumScale())
1181         return minimumScale();
1182     if (scale > maximumScale())
1183         return maximumScale();
1184     return scale;
1185 }
1186
1187 bool WebPagePrivate::shouldZoomAboutPoint(double scale, const FloatPoint&, bool enforceScaleClamping, double* clampedScale)
1188 {
1189     if (!m_mainFrame || !m_mainFrame->view())
1190         return false;
1191
1192     if (enforceScaleClamping)
1193         scale = this->clampedScale(scale);
1194
1195     ASSERT(clampedScale);
1196     *clampedScale = scale;
1197
1198     if (currentScale() == scale)
1199         return false;
1200
1201     return true;
1202 }
1203
1204 bool WebPagePrivate::zoomAboutPoint(double unclampedScale, const FloatPoint& anchor, bool enforceScaleClamping, bool forceRendering, bool isRestoringZoomLevel)
1205 {
1206     if (!isRestoringZoomLevel) {
1207         // Clear any existing block zoom.  (If we are restoring a saved zoom level on page load,
1208         // there is guaranteed to be no existing block zoom and we don't want to clear m_shouldReflowBlock.)
1209         resetBlockZoom();
1210     }
1211
1212     // The reflow and block zoom stuff here needs to happen regardless of
1213     // whether we shouldZoomAboutPoint.
1214 #if ENABLE(VIEWPORT_REFLOW)
1215     toggleTextReflowIfEnabledForBlockZoomOnly(m_shouldReflowBlock);
1216     if (m_page->settings()->isTextReflowEnabled() && m_mainFrame->view())
1217         setNeedsLayout();
1218 #endif
1219
1220     double scale;
1221     if (!shouldZoomAboutPoint(unclampedScale, anchor, enforceScaleClamping, &scale)) {
1222         if (m_webPage->settings()->textReflowMode() == WebSettings::TextReflowEnabled) {
1223             m_currentPinchZoomNode = 0;
1224             m_anchorInNodeRectRatio = FloatPoint(-1, -1);
1225         }
1226         return false;
1227     }
1228     TransformationMatrix zoom;
1229     zoom.scale(scale);
1230
1231 #if DEBUG_WEBPAGE_LOAD
1232     if (loadState() < Finished) {
1233         Platform::logAlways(Platform::LogLevelInfo,
1234             "WebPagePrivate::zoomAboutPoint scale %f anchor %s",
1235             scale, Platform::FloatPoint(anchor).toString().c_str());
1236     }
1237 #endif
1238
1239     // Our current scroll position in float.
1240     FloatPoint scrollPosition = this->scrollPosition();
1241
1242     // Anchor offset from scroll position in float.
1243     FloatPoint anchorOffset(anchor.x() - scrollPosition.x(), anchor.y() - scrollPosition.y());
1244
1245     // The horizontal scaling factor and vertical scaling factor should be equal
1246     // to preserve aspect ratio of content.
1247     ASSERT(m_transformationMatrix->m11() == m_transformationMatrix->m22());
1248
1249     // Need to invert the previous transform to anchor the viewport.
1250     double inverseScale = scale / m_transformationMatrix->m11();
1251
1252     // Actual zoom.
1253     *m_transformationMatrix = zoom;
1254
1255     // Suspend all screen updates to the backingstore.
1256     // FIXME: Do we really need to suspend/resume both backingstore and screen here?
1257     m_backingStore->d->suspendBackingStoreUpdates();
1258     m_backingStore->d->suspendScreenUpdates();
1259
1260     updateViewportSize();
1261
1262     IntPoint newScrollPosition(IntPoint(max(0, static_cast<int>(roundf(anchor.x() - anchorOffset.x() / inverseScale))),
1263                                         max(0, static_cast<int>(roundf(anchor.y() - anchorOffset.y() / inverseScale)))));
1264
1265     if (m_webPage->settings()->textReflowMode() == WebSettings::TextReflowEnabled) {
1266         // This is a hack for email which has reflow always turned on.
1267         m_mainFrame->view()->setNeedsLayout();
1268         requestLayoutIfNeeded();
1269         if (m_currentPinchZoomNode)
1270             newScrollPosition = calculateReflowedScrollPosition(anchorOffset, scale == minimumScale() ? 1 : inverseScale);
1271          m_currentPinchZoomNode = 0;
1272          m_anchorInNodeRectRatio = FloatPoint(-1, -1);
1273     }
1274
1275     setScrollPosition(newScrollPosition);
1276
1277     notifyTransformChanged();
1278
1279     bool isLoading = this->isLoading();
1280
1281     // We need to invalidate all tiles both visible and non-visible if we're loading.
1282     m_backingStore->d->updateTiles(isLoading /* updateVisible */, false /* immediate */);
1283
1284     bool shouldRender = !isLoading || m_userPerformedManualZoom || forceRendering;
1285
1286     m_client->scaleChanged();
1287
1288     if (m_pendingOrientation != -1)
1289         m_client->updateInteractionViews();
1290
1291     // FIXME: Do we really need to suspend/resume both backingstore and screen here?
1292     m_backingStore->d->resumeBackingStoreUpdates();
1293
1294     // Clear window to make sure there are no artifacts.
1295     if (shouldRender) {
1296         // Resume all screen updates to the backingstore and render+blit visible contents to screen.
1297         m_backingStore->d->resumeScreenUpdates(BackingStore::RenderAndBlit);
1298     } else {
1299         // Resume all screen updates to the backingstore but do not blit to the screen because we not rendering.
1300         m_backingStore->d->resumeScreenUpdates(BackingStore::None);
1301     }
1302
1303     return true;
1304 }
1305
1306 IntPoint WebPagePrivate::calculateReflowedScrollPosition(const FloatPoint& anchorOffset, double inverseScale)
1307 {
1308     // Should only be invoked when text reflow is enabled.
1309     ASSERT(m_webPage->settings()->textReflowMode() == WebSettings::TextReflowEnabled);
1310
1311     int offsetY = 0;
1312     int offsetX = 0;
1313
1314     IntRect nodeRect = rectForNode(m_currentPinchZoomNode.get());
1315
1316     if (m_currentPinchZoomNode->renderer() && m_anchorInNodeRectRatio.y() >= 0) {
1317         offsetY = nodeRect.height() * m_anchorInNodeRectRatio.y();
1318         if (m_currentPinchZoomNode->renderer()->isImage() && m_anchorInNodeRectRatio.x() > 0)
1319             offsetX = nodeRect.width() * m_anchorInNodeRectRatio.x() - anchorOffset.x() / inverseScale;
1320     }
1321
1322     IntRect reflowedRect = adjustRectOffsetForFrameOffset(nodeRect, m_currentPinchZoomNode.get());
1323
1324     return IntPoint(max(0, static_cast<int>(roundf(reflowedRect.x() + offsetX))),
1325                     max(0, static_cast<int>(roundf(reflowedRect.y() + offsetY - anchorOffset.y() / inverseScale))));
1326 }
1327
1328 void WebPagePrivate::setNeedsLayout()
1329 {
1330     FrameView* view = m_mainFrame->view();
1331     ASSERT(view);
1332     view->setNeedsLayout();
1333 }
1334
1335 void WebPagePrivate::requestLayoutIfNeeded() const
1336 {
1337     FrameView* view = m_mainFrame->view();
1338     ASSERT(view);
1339     view->updateLayoutAndStyleIfNeededRecursive();
1340     ASSERT(!view->needsLayout());
1341 }
1342
1343 IntPoint WebPagePrivate::scrollPosition() const
1344 {
1345     if (!m_backingStoreClient)
1346         return IntPoint();
1347
1348     return m_backingStoreClient->scrollPosition();
1349 }
1350
1351 IntPoint WebPagePrivate::maximumScrollPosition() const
1352 {
1353     if (!m_backingStoreClient)
1354         return IntPoint();
1355
1356     return m_backingStoreClient->maximumScrollPosition();
1357 }
1358
1359 void WebPagePrivate::setScrollPosition(const IntPoint& pos)
1360 {
1361     ASSERT(m_backingStoreClient);
1362     m_backingStoreClient->setScrollPosition(pos);
1363 }
1364
1365 // Setting the scroll position is in transformed coordinates.
1366 void WebPage::setDocumentScrollPosition(const Platform::IntPoint& documentScrollPosition)
1367 {
1368     WebCore::IntPoint scrollPosition = documentScrollPosition;
1369     if (scrollPosition == d->scrollPosition())
1370         return;
1371
1372     // If the user recently performed an event, this new scroll position
1373     // could possibly be a result of that. Or not, this is just a heuristic.
1374     if (currentTime() - d->m_lastUserEventTimestamp < manualScrollInterval)
1375         d->m_userPerformedManualScroll = true;
1376
1377     d->m_backingStoreClient->setIsClientGeneratedScroll(true);
1378
1379     // UI thread can call BackingStorePrivate::setScrollingOrZooming(false) before WebKit thread calls WebPage::setScrollPosition(),
1380     // in which case it will set ScrollableArea::m_constrainsScrollingToContentEdge to true earlier.
1381     // We can cache ScrollableArea::m_constrainsScrollingToContentEdge and always set it to false before we set scroll position in
1382     // WebKit thread to avoid scroll position clamping during scrolling, and restore it to what it was after that.
1383     bool constrainsScrollingToContentEdge = d->m_mainFrame->view()->constrainsScrollingToContentEdge();
1384     d->m_mainFrame->view()->setConstrainsScrollingToContentEdge(false);
1385     d->setScrollPosition(scrollPosition);
1386     d->m_mainFrame->view()->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge);
1387
1388     d->m_backingStoreClient->setIsClientGeneratedScroll(false);
1389 }
1390
1391 bool WebPagePrivate::shouldSendResizeEvent()
1392 {
1393     if (!m_mainFrame || !m_mainFrame->document())
1394         return false;
1395
1396     // PR#96865 : Provide an option to always send resize events, regardless of the loading
1397     //            status. The scenario for this are Sapphire applications which tend to
1398     //            maintain an open GET request to the server. This open GET results in
1399     //            webkit thinking that content is still arriving when at the application
1400     //            level it is considered fully loaded.
1401     //
1402     //            NOTE: Care must be exercised in the use of this option, as it bypasses
1403     //                  the sanity provided in 'isLoadingInAPISense()' below.
1404     //
1405     static const bool unrestrictedResizeEvents = Platform::Settings::instance()->unrestrictedResizeEvents();
1406     if (unrestrictedResizeEvents)
1407         return true;
1408
1409     // Don't send the resize event if the document is loading. Some pages automatically reload
1410     // when the window is resized; Safari on iPhone often resizes the window while setting up its
1411     // viewport. This obviously can cause problems.
1412     DocumentLoader* documentLoader = m_mainFrame->loader()->documentLoader();
1413     if (documentLoader && documentLoader->isLoadingInAPISense())
1414         return false;
1415
1416     return true;
1417 }
1418
1419 void WebPagePrivate::willDeferLoading()
1420 {
1421     m_deferredTasksTimer.stop();
1422     m_client->willDeferLoading();
1423 }
1424
1425 void WebPagePrivate::didResumeLoading()
1426 {
1427     if (!m_deferredTasks.isEmpty())
1428         m_deferredTasksTimer.startOneShot(0);
1429     m_client->didResumeLoading();
1430 }
1431
1432 void WebPagePrivate::deferredTasksTimerFired(WebCore::Timer<WebPagePrivate>*)
1433 {
1434     ASSERT(!m_deferredTasks.isEmpty());
1435     if (m_deferredTasks.isEmpty())
1436         return;
1437
1438     OwnPtr<DeferredTaskBase> task = m_deferredTasks[0].release();
1439     m_deferredTasks.remove(0);
1440
1441     if (!m_deferredTasks.isEmpty())
1442         m_deferredTasksTimer.startOneShot(0);
1443
1444     task->perform(this);
1445 }
1446
1447 void WebPagePrivate::notifyInRegionScrollStopped()
1448 {
1449     if (m_inRegionScroller->d->isActive())
1450         m_inRegionScroller->d->reset();
1451 }
1452
1453 void WebPage::notifyInRegionScrollStopped()
1454 {
1455     d->notifyInRegionScrollStopped();
1456 }
1457
1458 void WebPagePrivate::setHasInRegionScrollableAreas(bool b)
1459 {
1460     if (b != m_hasInRegionScrollableAreas)
1461         m_hasInRegionScrollableAreas = b;
1462 }
1463
1464 IntSize WebPagePrivate::viewportSize() const
1465 {
1466     return m_webkitThreadViewportAccessor->roundToDocumentFromPixelContents(Platform::IntRect(Platform::IntPoint::zero(), transformedViewportSize())).size();
1467 }
1468
1469 IntSize WebPagePrivate::actualVisibleSize() const
1470 {
1471     return m_webkitThreadViewportAccessor->documentViewportSize();
1472 }
1473
1474 bool WebPagePrivate::hasVirtualViewport() const
1475 {
1476     return !m_virtualViewportSize.isEmpty();
1477 }
1478
1479 void WebPagePrivate::updateViewportSize(bool setFixedReportedSize, bool sendResizeEvent)
1480 {
1481     // This checks to make sure we're not calling updateViewportSize
1482     // during WebPagePrivate::init().
1483     if (!m_backingStore)
1484         return;
1485     ASSERT(m_mainFrame->view());
1486     IntSize visibleSize = actualVisibleSize();
1487     if (setFixedReportedSize)
1488         m_mainFrame->view()->setFixedReportedSize(visibleSize);
1489
1490     IntRect frameRect = IntRect(scrollPosition(), visibleSize);
1491     if (frameRect != m_mainFrame->view()->frameRect()) {
1492         m_mainFrame->view()->setFrameRect(frameRect);
1493         m_mainFrame->view()->adjustViewSize();
1494
1495 #if ENABLE(FULLSCREEN_API)
1496         adjustFullScreenElementDimensionsIfNeeded();
1497 #endif
1498     }
1499
1500     // We're going to need to send a resize event to JavaScript because
1501     // innerWidth and innerHeight depend on fixed reported size.
1502     // This is how we support mobile pages where JavaScript resizes
1503     // the page in order to get around the fixed layout size, e.g.
1504     // google maps when it detects a mobile user agent.
1505     if (sendResizeEvent && shouldSendResizeEvent())
1506         m_mainFrame->eventHandler()->sendResizeEvent();
1507
1508     // When the actual visible size changes, we also
1509     // need to reposition fixed elements.
1510     m_mainFrame->view()->repaintFixedElementsAfterScrolling();
1511 }
1512
1513 FloatPoint WebPagePrivate::centerOfVisibleContentsRect() const
1514 {
1515     // The visible contents rect in float.
1516     FloatRect visibleContentsRect = this->visibleContentsRect();
1517
1518     // The center of the visible contents rect in float.
1519     return FloatPoint(visibleContentsRect.x() + visibleContentsRect.width() / 2.0,
1520                       visibleContentsRect.y() + visibleContentsRect.height() / 2.0);
1521 }
1522
1523 IntRect WebPagePrivate::visibleContentsRect() const
1524 {
1525     return m_backingStoreClient->visibleContentsRect();
1526 }
1527
1528 IntSize WebPagePrivate::contentsSize() const
1529 {
1530     if (!m_mainFrame || !m_mainFrame->view())
1531         return IntSize();
1532
1533     return m_backingStoreClient->contentsSize();
1534 }
1535
1536 IntSize WebPagePrivate::absoluteVisibleOverflowSize() const
1537 {
1538     if (!m_mainFrame || !m_mainFrame->contentRenderer())
1539         return IntSize();
1540
1541     return IntSize(m_mainFrame->contentRenderer()->rightAbsoluteVisibleOverflow(), m_mainFrame->contentRenderer()->bottomAbsoluteVisibleOverflow());
1542 }
1543
1544 void WebPagePrivate::contentsSizeChanged(const IntSize& contentsSize)
1545 {
1546     if (m_previousContentsSize == contentsSize)
1547         return;
1548
1549     // This should only occur in the middle of layout so we set a flag here and
1550     // handle it at the end of the layout.
1551     m_contentsSizeChanged = true;
1552
1553 #if DEBUG_WEBPAGE_LOAD
1554     Platform::logAlways(Platform::LogLevelInfo, "WebPagePrivate::contentsSizeChanged %s", Platform::IntSize(contentsSize).toString().c_str());
1555 #endif
1556 }
1557
1558 void WebPagePrivate::overflowExceedsContentsSize()
1559 {
1560     m_overflowExceedsContentsSize = true;
1561     if (absoluteVisibleOverflowSize().width() < DEFAULT_MAX_LAYOUT_WIDTH && !hasVirtualViewport()) {
1562         if (setViewMode(viewMode())) {
1563             setNeedsLayout();
1564             requestLayoutIfNeeded();
1565         }
1566     }
1567 }
1568
1569 void WebPagePrivate::layoutFinished()
1570 {
1571     // If a layout change has occurred, we need to invalidate any current spellcheck requests and trigger a new run.
1572     m_inputHandler->stopPendingSpellCheckRequests();
1573     m_inputHandler->spellCheckTextBlock();
1574
1575     if (!m_contentsSizeChanged && !m_overflowExceedsContentsSize)
1576         return;
1577
1578     m_contentsSizeChanged = false; // Toggle to turn off notification again.
1579     m_overflowExceedsContentsSize = false;
1580
1581     if (contentsSize().isEmpty())
1582         return;
1583
1584     // The call to zoomToInitialScaleOnLoad can cause recursive layout when called from
1585     // the middle of a layout, but the recursion is limited by detection code in
1586     // setViewMode() and mitigation code in fixedLayoutSize().
1587     if (didLayoutExceedMaximumIterations()) {
1588         notifyTransformedContentsSizeChanged();
1589         return;
1590     }
1591
1592     // Temporarily save the m_previousContentsSize here before updating it (in
1593     // notifyTransformedContentsSizeChanged()) so we can compare if our contents
1594     // shrunk afterwards.
1595     IntSize previousContentsSize = m_previousContentsSize;
1596
1597     m_nestedLayoutFinishedCount++;
1598
1599     if (shouldZoomToInitialScaleOnLoad()) {
1600         zoomToInitialScaleOnLoad();
1601         m_shouldZoomToInitialScaleAfterLoadFinished = false;
1602     } else if (loadState() != None)
1603         notifyTransformedContentsSizeChanged();
1604
1605     m_nestedLayoutFinishedCount--;
1606
1607     if (!m_nestedLayoutFinishedCount) {
1608         // When the contents shrinks, there is a risk that we
1609         // will be left at a scroll position that lies outside of the
1610         // contents rect. Since we allow overscrolling and neglect
1611         // to clamp overscroll in order to retain input focus (RIM Bug #414)
1612         // we need to clamp somewhere, and this is where we know the
1613         // contents size has changed.
1614
1615         if (contentsSize() != previousContentsSize) {
1616
1617             IntPoint newScrollPosition = scrollPosition();
1618
1619             if (contentsSize().height() < previousContentsSize.height()) {
1620                 IntPoint scrollPositionWithHeightShrunk = IntPoint(newScrollPosition.x(), maximumScrollPosition().y());
1621                 newScrollPosition = newScrollPosition.shrunkTo(scrollPositionWithHeightShrunk);
1622             }
1623
1624             if (contentsSize().width() < previousContentsSize.width()) {
1625                 IntPoint scrollPositionWithWidthShrunk = IntPoint(maximumScrollPosition().x(), newScrollPosition.y());
1626                 newScrollPosition = newScrollPosition.shrunkTo(scrollPositionWithWidthShrunk);
1627             }
1628
1629             if (newScrollPosition != scrollPosition()) {
1630                 setScrollPosition(newScrollPosition);
1631                 notifyTransformedScrollChanged();
1632             }
1633
1634             const Platform::IntSize pixelContentsSize = m_webkitThreadViewportAccessor->pixelContentsSize();
1635
1636             // If the content size is too small, zoom it to fit the viewport.
1637             if ((loadState() == Finished || loadState() == Committed) && (pixelContentsSize.width() < m_actualVisibleWidth || pixelContentsSize.height() < m_actualVisibleHeight))
1638                 zoomAboutPoint(initialScale(), newScrollPosition);
1639         }
1640     }
1641 }
1642
1643 void WebPagePrivate::zoomToInitialScaleOnLoad()
1644 {
1645 #if DEBUG_WEBPAGE_LOAD
1646     Platform::logAlways(Platform::LogLevelInfo, "WebPagePrivate::zoomToInitialScaleOnLoad");
1647 #endif
1648
1649     bool needsLayout = false;
1650
1651     // If the contents width exceeds the viewport width set to desktop mode.
1652     if (m_shouldUseFixedDesktopMode)
1653         needsLayout = setViewMode(FixedDesktop);
1654     else
1655         needsLayout = setViewMode(Desktop);
1656
1657     if (needsLayout) {
1658         // This can cause recursive layout...
1659         setNeedsLayout();
1660     }
1661
1662     if (contentsSize().isEmpty()) {
1663 #if DEBUG_WEBPAGE_LOAD
1664         Platform::logAlways(Platform::LogLevelInfo, "WebPagePrivate::zoomToInitialScaleOnLoad content is empty!");
1665 #endif
1666         requestLayoutIfNeeded();
1667         notifyTransformedContentsSizeChanged();
1668         return;
1669     }
1670
1671     bool performedZoom = false;
1672     bool shouldZoom = !m_userPerformedManualZoom;
1673
1674     // If this is a back/forward type navigation, don't zoom to initial scale
1675     // but instead let the HistoryItem's saved viewport reign supreme.
1676     if (m_mainFrame && m_mainFrame->loader() && isBackForwardLoadType(m_mainFrame->loader()->loadType()))
1677         shouldZoom = false;
1678
1679     if (shouldZoom && shouldZoomToInitialScaleOnLoad()) {
1680         // Preserve at top and at left position, to avoid scrolling
1681         // to a non top-left position for web page with viewport meta tag
1682         // that specifies an initial-scale that is zoomed in.
1683         FloatPoint anchor = centerOfVisibleContentsRect();
1684         if (!scrollPosition().x())
1685             anchor.setX(0);
1686         if (!scrollPosition().y())
1687             anchor.setY(0);
1688         performedZoom = zoomAboutPoint(initialScale(), anchor);
1689     }
1690
1691     // zoomAboutPoint above can also toggle setNeedsLayout and cause recursive layout...
1692     requestLayoutIfNeeded();
1693
1694     if (!performedZoom) {
1695         // We only notify if we didn't perform zoom, because zoom will notify on
1696         // its own...
1697         notifyTransformedContentsSizeChanged();
1698     }
1699 }
1700
1701 double WebPagePrivate::zoomToFitScale() const
1702 {
1703     int contentWidth = contentsSize().width();
1704
1705     // For image document, zoom to fit the screen based on the actual image width
1706     // instead of the contents width within a maximum scale .
1707     Document* doc = m_page->mainFrame()->document();
1708     bool isImageDocument = doc && doc->isImageDocument();
1709     if (isImageDocument)
1710         contentWidth = static_cast<ImageDocument*>(doc)->imageSize().width();
1711
1712     double zoomToFitScale = contentWidth > 0.0 ? static_cast<double>(m_actualVisibleWidth) / contentWidth : 1.0;
1713     int contentHeight = contentsSize().height();
1714     if (contentHeight * zoomToFitScale < static_cast<double>(m_defaultLayoutSize.height()))
1715         zoomToFitScale = contentHeight > 0 ? static_cast<double>(m_defaultLayoutSize.height()) / contentHeight : 1.0;
1716     zoomToFitScale = std::max(zoomToFitScale, minimumZoomToFitScale);
1717
1718     if (!isImageDocument)
1719         return zoomToFitScale;
1720
1721     return std::min(zoomToFitScale, maximumImageDocumentZoomToFitScale);
1722 }
1723
1724 bool WebPagePrivate::respectViewport() const
1725 {
1726     return m_forceRespectViewportArguments || contentsSize().width() <= m_virtualViewportSize.width() + 1;
1727 }
1728
1729 double WebPagePrivate::initialScale() const
1730 {
1731
1732     if (m_initialScale > 0.0 && respectViewport())
1733         return m_initialScale;
1734
1735     if (m_webSettings->isZoomToFitOnLoad())
1736         return zoomToFitScale();
1737
1738     return 1.0;
1739 }
1740
1741 double WebPage::initialScale() const
1742 {
1743     return d->initialScale();
1744 }
1745
1746 void WebPage::initializeIconDataBase()
1747 {
1748     IconDatabaseClientBlackBerry::instance()->initIconDatabase(d->m_webSettings);
1749 }
1750
1751 bool WebPage::isUserScalable() const
1752 {
1753     return d->isUserScalable();
1754 }
1755
1756 void WebPage::setUserScalable(bool userScalable)
1757 {
1758     d->setUserScalable(userScalable);
1759 }
1760
1761 double WebPage::currentScale() const
1762 {
1763     return d->currentScale();
1764 }
1765
1766 void WebPage::setInitialScale(double initialScale)
1767 {
1768     d->setInitialScale(initialScale);
1769 }
1770
1771 double WebPage::minimumScale() const
1772 {
1773     return d->minimumScale();
1774 }
1775
1776 void WebPage::setMinimumScale(double minimumScale)
1777 {
1778     d->setMinimumScale(minimumScale);
1779 }
1780
1781 void WebPage::setMaximumScale(double maximumScale)
1782 {
1783     d->setMaximumScale(maximumScale);
1784 }
1785
1786 double WebPagePrivate::maximumScale() const
1787 {
1788     double zoomToFitScale = this->zoomToFitScale();
1789     if (m_maximumScale >= m_minimumScale && respectViewport())
1790         return std::max(zoomToFitScale, m_maximumScale);
1791
1792     return hasVirtualViewport() ? std::max<double>(zoomToFitScale, 4.0) : 4.0;
1793 }
1794
1795 double WebPage::maximumScale() const
1796 {
1797     return d->maximumScale();
1798 }
1799
1800 void WebPagePrivate::resetScales()
1801 {
1802     TransformationMatrix identity;
1803     *m_transformationMatrix = identity;
1804     m_initialScale = m_webSettings->initialScale() > 0 ? m_webSettings->initialScale() : -1.0;
1805     m_minimumScale = -1.0;
1806     m_maximumScale = -1.0;
1807     m_client->scaleChanged();
1808
1809     // We have to let WebCore know about updated framerect now that we've
1810     // reset our scales. See: RIM Bug #401.
1811     updateViewportSize();
1812 }
1813
1814 IntPoint WebPagePrivate::transformedScrollPosition() const
1815 {
1816     return m_backingStoreClient->transformedScrollPosition();
1817 }
1818
1819 IntPoint WebPagePrivate::transformedMaximumScrollPosition() const
1820 {
1821     return m_backingStoreClient->transformedMaximumScrollPosition();
1822 }
1823
1824 IntSize WebPagePrivate::transformedActualVisibleSize() const
1825 {
1826     return IntSize(m_actualVisibleWidth, m_actualVisibleHeight);
1827 }
1828
1829 Platform::ViewportAccessor* WebPage::webkitThreadViewportAccessor() const
1830 {
1831     return d->m_webkitThreadViewportAccessor;
1832 }
1833
1834 Platform::IntSize WebPage::viewportSize() const
1835 {
1836     return d->transformedActualVisibleSize();
1837 }
1838
1839 IntSize WebPagePrivate::transformedViewportSize() const
1840 {
1841     return BlackBerry::Platform::Settings::instance()->applicationSize();
1842 }
1843
1844 void WebPagePrivate::notifyTransformChanged()
1845 {
1846     notifyTransformedContentsSizeChanged();
1847     notifyTransformedScrollChanged();
1848
1849     m_backingStore->d->transformChanged();
1850 }
1851
1852 void WebPagePrivate::notifyTransformedContentsSizeChanged()
1853 {
1854     // We mark here as the last reported content size we sent to the client.
1855     m_previousContentsSize = contentsSize();
1856
1857     const IntSize size = m_webkitThreadViewportAccessor->pixelContentsSize();
1858     m_backingStore->d->contentsSizeChanged(size);
1859     m_client->contentsSizeChanged();
1860 }
1861
1862 void WebPagePrivate::notifyTransformedScrollChanged()
1863 {
1864     const IntPoint pos = transformedScrollPosition();
1865     m_backingStore->d->scrollChanged(pos);
1866     m_client->scrollChanged();
1867
1868 #if ENABLE(FULLSCREEN_API)
1869     adjustFullScreenElementDimensionsIfNeeded();
1870 #endif
1871 }
1872
1873 bool WebPagePrivate::setViewMode(ViewMode mode)
1874 {
1875     if (!m_mainFrame || !m_mainFrame->view())
1876         return false;
1877
1878     m_viewMode = mode;
1879
1880     // If we're in the middle of a nested layout with a recursion count above
1881     // some maximum threshold, then our algorithm for finding the minimum content
1882     // width of a given page has become dependent on the visible width.
1883     //
1884     // We need to find some method to ensure that we don't experience excessive
1885     // and even infinite recursion. This can even happen with valid html. The
1886     // former can happen when we run into inline text with few candidates for line
1887     // break. The latter can happen for instance if the page has a negative margin
1888     // set against the right border. Note: this is valid by spec and can lead to
1889     // a situation where there is no value for which the content width will ensure
1890     // no horizontal scrollbar.
1891     // Example: LayoutTests/css1/box_properties/margin.html
1892     //
1893     // In order to address such situations when we detect a recursion above some
1894     // maximum threshold we snap our fixed layout size to a defined quantum increment.
1895     // Eventually, either the content width will be satisfied to ensure no horizontal
1896     // scrollbar or this increment will run into the maximum layout size and the
1897     // recursion will necessarily end.
1898     bool snapToIncrement = didLayoutExceedMaximumIterations();
1899
1900     IntSize currentSize = m_mainFrame->view()->fixedLayoutSize();
1901     IntSize newSize = fixedLayoutSize(snapToIncrement);
1902     if (currentSize == newSize)
1903         return false;
1904
1905     // FIXME: Temp solution. We'll get back to this.
1906     if (m_nestedLayoutFinishedCount) {
1907         double widthChange = fabs(double(newSize.width() - currentSize.width()) / currentSize.width());
1908         double heightChange = fabs(double(newSize.height() - currentSize.height()) / currentSize.height());
1909         if (widthChange < 0.05 && heightChange < 0.05)
1910             return false;
1911     }
1912
1913     m_mainFrame->view()->setUseFixedLayout(useFixedLayout());
1914     m_mainFrame->view()->setFixedLayoutSize(newSize);
1915     return true; // Needs re-layout!
1916 }
1917
1918 int WebPagePrivate::playerID() const
1919 {
1920     return m_client ? m_client->getInstanceId() : 0;
1921 }
1922
1923 void WebPagePrivate::setCursor(PlatformCursor handle)
1924 {
1925     if (m_currentCursor.type() != handle.type()) {
1926         m_currentCursor = handle;
1927         m_client->cursorChanged(handle.type(), handle.url().c_str(), handle.hotspot());
1928     }
1929 }
1930
1931 Platform::NetworkStreamFactory* WebPagePrivate::networkStreamFactory()
1932 {
1933     return m_client->networkStreamFactory();
1934 }
1935
1936 Platform::Graphics::Window* WebPagePrivate::platformWindow() const
1937 {
1938     return m_client->window();
1939 }
1940
1941 void WebPagePrivate::setPreventsScreenDimming(bool keepAwake)
1942 {
1943     if (keepAwake) {
1944         if (!m_preventIdleDimmingCount)
1945             m_client->setPreventsScreenIdleDimming(true);
1946         m_preventIdleDimmingCount++;
1947     } else if (m_preventIdleDimmingCount > 0) {
1948         m_preventIdleDimmingCount--;
1949         if (!m_preventIdleDimmingCount)
1950             m_client->setPreventsScreenIdleDimming(false);
1951     } else
1952         ASSERT_NOT_REACHED(); // SetPreventsScreenIdleDimming(false) called too many times.
1953 }
1954
1955 void WebPagePrivate::showVirtualKeyboard(bool showKeyboard)
1956 {
1957     m_client->showVirtualKeyboard(showKeyboard);
1958 }
1959
1960 void WebPagePrivate::ensureContentVisible(bool centerInView)
1961 {
1962     m_inputHandler->ensureFocusElementVisible(centerInView);
1963 }
1964
1965 void WebPagePrivate::zoomToContentRect(const IntRect& rect)
1966 {
1967     // Don't scale if the user is not supposed to scale.
1968     if (!isUserScalable())
1969         return;
1970
1971     FloatPoint anchor = FloatPoint(rect.width() / 2.0 + rect.x(), rect.height() / 2.0 + rect.y());
1972     IntSize viewSize = viewportSize();
1973
1974     // Calculate the scale required to scale that dimension to fit.
1975     double scaleH = (double)viewSize.width() / (double)rect.width();
1976     double scaleV = (double)viewSize.height() / (double)rect.height();
1977
1978     // Choose the smaller scale factor so that all of the content is visible.
1979     zoomAboutPoint(min(scaleH, scaleV), anchor);
1980 }
1981
1982 void WebPagePrivate::registerPlugin(PluginView* plugin, bool shouldRegister)
1983 {
1984     if (shouldRegister)
1985         m_pluginViews.add(plugin);
1986     else
1987         m_pluginViews.remove(plugin);
1988 }
1989
1990 #define FOR_EACH_PLUGINVIEW(pluginViews) \
1991     HashSet<PluginView*>::const_iterator it = pluginViews.begin(); \
1992     HashSet<PluginView*>::const_iterator last = pluginViews.end(); \
1993     for (; it != last; ++it)
1994
1995 void WebPagePrivate::notifyPageOnLoad()
1996 {
1997     FOR_EACH_PLUGINVIEW(m_pluginViews)
1998         (*it)->handleOnLoadEvent();
1999 }
2000
2001 bool WebPagePrivate::shouldPluginEnterFullScreen(PluginView*, const char*)
2002 {
2003     return m_client->shouldPluginEnterFullScreen();
2004 }
2005
2006 void WebPagePrivate::didPluginEnterFullScreen(PluginView* plugin, const char* windowUniquePrefix)
2007 {
2008     m_fullScreenPluginView = plugin;
2009     m_client->didPluginEnterFullScreen();
2010
2011     if (!m_client->window())
2012         return;
2013
2014     Platform::Graphics::Window::setTransparencyDiscardFilter(windowUniquePrefix);
2015     m_client->window()->setSensitivityFullscreenOverride(true);
2016 }
2017
2018 void WebPagePrivate::didPluginExitFullScreen(PluginView*, const char*)
2019 {
2020     m_fullScreenPluginView = 0;
2021     m_client->didPluginExitFullScreen();
2022
2023     if (!m_client->window())
2024         return;
2025
2026     Platform::Graphics::Window::setTransparencyDiscardFilter(0);
2027     m_client->window()->setSensitivityFullscreenOverride(false);
2028 }
2029
2030 void WebPagePrivate::onPluginStartBackgroundPlay(PluginView*, const char*)
2031 {
2032     m_client->onPluginStartBackgroundPlay();
2033 }
2034
2035 void WebPagePrivate::onPluginStopBackgroundPlay(PluginView*, const char*)
2036 {
2037     m_client->onPluginStopBackgroundPlay();
2038 }
2039
2040 bool WebPagePrivate::lockOrientation(bool landscape)
2041 {
2042     return m_client->lockOrientation(landscape);
2043 }
2044
2045 void WebPagePrivate::unlockOrientation()
2046 {
2047     return m_client->unlockOrientation();
2048 }
2049
2050 int WebPagePrivate::orientation() const
2051 {
2052 #if ENABLE(ORIENTATION_EVENTS)
2053     return m_mainFrame->orientation();
2054 #else
2055 #error ORIENTATION_EVENTS must be defined.
2056 // Or a copy of the orientation value will have to be stored in these objects.
2057 #endif
2058 }
2059
2060 double WebPagePrivate::currentZoomFactor() const
2061 {
2062     return currentScale();
2063 }
2064
2065 int WebPagePrivate::showAlertDialog(WebPageClient::AlertType atype)
2066 {
2067     return m_client->showAlertDialog(atype);
2068 }
2069
2070 bool WebPagePrivate::isActive() const
2071 {
2072     return m_client->isActive();
2073 }
2074
2075 void WebPagePrivate::authenticationChallenge(const KURL& url, const ProtectionSpace& protectionSpace, const Credential& inputCredential)
2076 {
2077     AuthenticationChallengeManager* authmgr = AuthenticationChallengeManager::instance();
2078     BlackBerry::Platform::String username;
2079     BlackBerry::Platform::String password;
2080     BlackBerry::Platform::String requestURL(url.string());
2081
2082 #if !defined(PUBLIC_BUILD) || !PUBLIC_BUILD
2083     if (m_dumpRenderTree) {
2084         Credential credential(inputCredential, inputCredential.persistence());
2085         if (m_dumpRenderTree->didReceiveAuthenticationChallenge(credential))
2086             authmgr->notifyChallengeResult(url, protectionSpace, AuthenticationChallengeSuccess, credential);
2087         else
2088             authmgr->notifyChallengeResult(url, protectionSpace, AuthenticationChallengeCancelled, inputCredential);
2089         return;
2090     }
2091 #endif
2092
2093 #if ENABLE(BLACKBERRY_CREDENTIAL_PERSIST)
2094     if (m_webSettings->isCredentialAutofillEnabled() && !m_webSettings->isPrivateBrowsingEnabled())
2095         credentialManager().autofillAuthenticationChallenge(protectionSpace, username, password);
2096 #endif
2097
2098     bool isConfirmed = m_client->authenticationChallenge(protectionSpace.realm().characters(), protectionSpace.realm().length(), username, password, requestURL, protectionSpace.isProxy());
2099
2100 #if ENABLE(BLACKBERRY_CREDENTIAL_PERSIST)
2101     Credential credential(username, password, CredentialPersistencePermanent);
2102     if (m_webSettings->isCredentialAutofillEnabled() && !m_webSettings->isPrivateBrowsingEnabled() && isConfirmed)
2103         credentialManager().saveCredentialIfConfirmed(this, CredentialTransformData(protectionSpace, credential));
2104 #else
2105     Credential credential(username, password, CredentialPersistenceNone);
2106 #endif
2107
2108     if (isConfirmed)
2109         authmgr->notifyChallengeResult(url, protectionSpace, AuthenticationChallengeSuccess, credential);
2110     else
2111         authmgr->notifyChallengeResult(url, protectionSpace, AuthenticationChallengeCancelled, inputCredential);
2112 }
2113
2114 PageClientBlackBerry::SaveCredentialType WebPagePrivate::notifyShouldSaveCredential(bool isNew)
2115 {
2116     return static_cast<PageClientBlackBerry::SaveCredentialType>(m_client->notifyShouldSaveCredential(isNew));
2117 }
2118
2119 void WebPagePrivate::syncProxyCredential(const WebCore::Credential& credential)
2120 {
2121     m_client->syncProxyCredential(credential.user(), credential.password());
2122 }
2123
2124 void WebPagePrivate::notifyPopupAutofillDialog(const Vector<String>& candidates)
2125 {
2126     vector<BlackBerry::Platform::String> textItems;
2127     for (size_t i = 0; i < candidates.size(); i++)
2128         textItems.push_back(candidates[i]);
2129     m_client->notifyPopupAutofillDialog(textItems);
2130 }
2131
2132 void WebPagePrivate::notifyDismissAutofillDialog()
2133 {
2134     m_client->notifyDismissAutofillDialog();
2135 }
2136
2137 bool WebPagePrivate::useFixedLayout() const
2138 {
2139     return true;
2140 }
2141
2142 Platform::WebContext WebPagePrivate::webContext(TargetDetectionStrategy strategy)
2143 {
2144     Platform::WebContext context;
2145
2146     RefPtr<Node> node = contextNode(strategy);
2147     m_currentContextNode = node;
2148     if (!m_currentContextNode)
2149         return context;
2150
2151     // Send an onContextMenu event to the current context ndoe and get the result. Since we've already figured out
2152     // which node we want, we can send it directly to the node and not do a hit test. The onContextMenu event doesn't require
2153     // mouse positions so we just set the position at (0,0)
2154     PlatformMouseEvent mouseEvent(IntPoint(), IntPoint(), PlatformEvent::MouseMoved, 0, NoButton, false, false, false, TouchScreen);
2155     if (!m_currentContextNode->dispatchMouseEvent(mouseEvent, eventNames().contextmenuEvent, 0)) {
2156         context.setFlag(Platform::WebContext::IsOnContextMenuPrevented);
2157         return context;
2158     }
2159
2160     requestLayoutIfNeeded();
2161
2162     bool nodeAllowSelectionOverride = false;
2163     Node* linkNode = node->enclosingLinkEventParentOrSelf();
2164     if (node->isLink() || (node->isTextNode() && linkNode)) {
2165         KURL href;
2166         if (linkNode->isLink() && linkNode->hasAttributes()) {
2167             if (const Attribute* attribute = toElement(linkNode)->getAttributeItem(HTMLNames::hrefAttr))
2168                 href = linkNode->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(attribute->value()));
2169         }
2170
2171         String pattern = findPatternStringForUrl(href);
2172         if (!pattern.isEmpty())
2173             context.setPattern(pattern);
2174
2175         if (!href.string().isEmpty()) {
2176             context.setUrl(href.string());
2177
2178             // Links are non-selectable by default, but selection should be allowed
2179             // providing the page is selectable, use the parent to determine it.
2180             if (linkNode->parentNode() && linkNode->parentNode()->canStartSelection())
2181                 nodeAllowSelectionOverride = true;
2182         }
2183     }
2184
2185     if (node->isHTMLElement()) {
2186         HTMLImageElement* imageElement = 0;
2187         HTMLMediaElement* mediaElement = 0;
2188
2189         if (node->hasTagName(HTMLNames::imgTag))
2190             imageElement = static_cast<HTMLImageElement*>(node.get());
2191         else if (node->hasTagName(HTMLNames::areaTag))
2192             imageElement = static_cast<HTMLAreaElement*>(node.get())->imageElement();
2193
2194         if (static_cast<HTMLElement*>(node.get())->isMediaElement())
2195             mediaElement = static_cast<HTMLMediaElement*>(node.get());
2196
2197         if (imageElement && imageElement->renderer()) {
2198             context.setFlag(Platform::WebContext::IsImage);
2199             // FIXME: At the mean time, we only show "Save Image" when the image data is available.
2200             if (CachedImage* cachedImage = imageElement->cachedImage()) {
2201                 if (cachedImage->isLoaded() && cachedImage->resourceBuffer()) {
2202                     String url = stripLeadingAndTrailingHTMLSpaces(imageElement->getAttribute(HTMLNames::srcAttr).string());
2203                     context.setSrc(node->document()->completeURL(url).string());
2204
2205                     String mimeType = cachedImage->response().mimeType();
2206                     if (mimeType.isEmpty()) {
2207                         StringBuilder builder;
2208                         String extension = cachedImage->image()->filenameExtension();
2209                         builder.append("image/");
2210                         if (extension.isEmpty())
2211                             builder.append("unknown");
2212                         else if (extension == "jpg")
2213                             builder.append("jpeg");
2214                         else
2215                             builder.append(extension);
2216                         mimeType = builder.toString();
2217                     }
2218                     context.setMimeType(mimeType);
2219                 }
2220             }
2221             String alt = imageElement->altText();
2222             if (!alt.isNull())
2223                 context.setAlt(alt);
2224         }
2225
2226         if (mediaElement) {
2227             if (mediaElement->hasAudio())
2228                 context.setFlag(Platform::WebContext::IsAudio);
2229             if (mediaElement->hasVideo())
2230                 context.setFlag(Platform::WebContext::IsVideo);
2231
2232             String src = stripLeadingAndTrailingHTMLSpaces(mediaElement->getAttribute(HTMLNames::srcAttr).string());
2233             context.setSrc(node->document()->completeURL(src).string());
2234         }
2235     }
2236
2237     if (node->isTextNode()) {
2238         Text* curText = toText(node.get());
2239         if (!curText->wholeText().isEmpty())
2240             context.setText(curText->wholeText());
2241     }
2242
2243     bool canStartSelection = node->canStartSelection();
2244
2245     if (node->isElementNode()) {
2246         Element* element = toElement(node->deprecatedShadowAncestorNode());
2247
2248         if (DOMSupport::isTextBasedContentEditableElement(element)) {
2249             if (!canStartSelection) {
2250                 // Input fields host node is by spec non-editable unless the field itself has content editable enabled.
2251                 // Enable selection if the shadow tree for the input field is selectable.
2252                 Node* nodeUnderFinger = m_touchEventHandler->lastFatFingersResult().isValid() ? m_touchEventHandler->lastFatFingersResult().node(FatFingersResult::ShadowContentAllowed) : 0;
2253                 if (nodeUnderFinger)
2254                     canStartSelection = nodeUnderFinger->canStartSelection();
2255             }
2256             context.setFlag(Platform::WebContext::IsInput);
2257             if (element->hasTagName(HTMLNames::inputTag))
2258                 context.setFlag(Platform::WebContext::IsSingleLine);
2259             if (DOMSupport::isPasswordElement(element))
2260                 context.setFlag(Platform::WebContext::IsPassword);
2261
2262             String elementText(DOMSupport::inputElementText(element));
2263             if (!elementText.stripWhiteSpace().isEmpty())
2264                 context.setText(elementText);
2265             else if (!node->focused() && m_touchEventHandler->lastFatFingersResult().isValid() && strategy == RectBased) {
2266                 // If an input field is empty and not focused send a mouse click so that it gets a cursor and we can paste into it.
2267                 m_touchEventHandler->sendClickAtFatFingersPoint();
2268             }
2269         }
2270     }
2271
2272     if (!nodeAllowSelectionOverride && !canStartSelection)
2273         context.resetFlag(Platform::WebContext::IsSelectable);
2274
2275     if (node->isFocusable())
2276         context.setFlag(Platform::WebContext::IsFocusable);
2277
2278     // Walk up the node tree looking for our custom webworks context attribute.
2279     while (node) {
2280         if (node->isElementNode()) {
2281             Element* element = toElement(node->deprecatedShadowAncestorNode());
2282             String webWorksContext(DOMSupport::webWorksContext(element));
2283             if (!webWorksContext.stripWhiteSpace().isEmpty()) {
2284                 context.setFlag(Platform::WebContext::IsWebWorksContext);
2285                 context.setWebWorksContext(webWorksContext);
2286                 break;
2287             }
2288         }
2289         node = node->parentNode();
2290     }
2291
2292     return context;
2293 }
2294
2295 Platform::WebContext WebPage::webContext(TargetDetectionStrategy strategy) const
2296 {
2297     return d->webContext(strategy);
2298 }
2299
2300 void WebPagePrivate::updateCursor()
2301 {
2302     int buttonMask = 0;
2303     if (m_lastMouseEvent.button() == LeftButton)
2304         buttonMask = Platform::MouseEvent::ScreenLeftMouseButton;
2305     else if (m_lastMouseEvent.button() == MiddleButton)
2306         buttonMask = Platform::MouseEvent::ScreenMiddleMouseButton;
2307     else if (m_lastMouseEvent.button() == RightButton)
2308         buttonMask = Platform::MouseEvent::ScreenRightMouseButton;
2309
2310     unsigned modifiers = m_lastMouseEvent.shiftKey() ? 0 : KEYMOD_SHIFT |
2311         m_lastMouseEvent.ctrlKey() ? 0 : KEYMOD_CTRL |
2312         m_lastMouseEvent.altKey() ? 0 : KEYMOD_ALT;
2313
2314     const Platform::ViewportAccessor* viewportAccessor = m_webkitThreadViewportAccessor;
2315
2316     BlackBerry::Platform::MouseEvent event(buttonMask, buttonMask,
2317         viewportAccessor->roundToPixelFromDocumentContents(WebCore::FloatPoint(m_lastMouseEvent.position())),
2318         viewportAccessor->roundToPixelFromDocumentContents(WebCore::FloatPoint(m_lastMouseEvent.globalPosition())),
2319         0, modifiers, 0);
2320
2321     // We have added document viewport position and document content position as members of the mouse event. When we create the event, we should initialize them as well.
2322     event.populateDocumentPosition(m_lastMouseEvent.position(), viewportAccessor->documentContentsFromViewport(m_lastMouseEvent.position()));
2323
2324     m_webPage->mouseEvent(event);
2325 }
2326
2327 IntSize WebPagePrivate::fixedLayoutSize(bool snapToIncrement) const
2328 {
2329     if (hasVirtualViewport())
2330         return m_virtualViewportSize;
2331
2332     const int defaultLayoutWidth = m_defaultLayoutSize.width();
2333     const int defaultLayoutHeight = m_defaultLayoutSize.height();
2334
2335     int minWidth = defaultLayoutWidth;
2336     int maxWidth = DEFAULT_MAX_LAYOUT_WIDTH;
2337     int maxHeight = DEFAULT_MAX_LAYOUT_HEIGHT;
2338
2339     // If the load state is none then we haven't actually got anything yet, but we need to layout
2340     // the entire page so that the user sees the entire page (unrendered) instead of just part of it.
2341     // If the load state is Provisional, it is possible that absoluteVisibleOverflowSize() and
2342     // contentsSize() are based on the old page and cause inconsistent fixedLayoutSize, so layout the
2343     // new page based on the defaultLayoutSize as well.
2344     if (m_loadState == None || m_loadState == Provisional)
2345         return IntSize(defaultLayoutWidth, defaultLayoutHeight);
2346
2347     if (m_viewMode == FixedDesktop) {
2348         int width  = maxWidth;
2349         // if the defaultLayoutHeight is at minimum, it probably was set as 0
2350         // and clamped, meaning it's effectively not set.  (Even if it happened
2351         // to be set exactly to the minimum, it's too small to be useful.)  So
2352         // ignore it.
2353         int height;
2354         if (defaultLayoutHeight <= minimumLayoutSize.height())
2355             height = maxHeight;
2356         else
2357             height = ceilf(static_cast<float>(width) / static_cast<float>(defaultLayoutWidth) * static_cast<float>(defaultLayoutHeight));
2358         return IntSize(width, height);
2359     }
2360
2361     if (m_viewMode == Desktop) {
2362         // If we detect an overflow larger than the contents size then use that instead since
2363         // it'll still be clamped by the maxWidth below...
2364         int width = std::max(absoluteVisibleOverflowSize().width(), contentsSize().width());
2365         if (m_pendingOrientation != -1 && !m_nestedLayoutFinishedCount && !m_overflowExceedsContentsSize)
2366             width = 0;
2367
2368         if (snapToIncrement) {
2369             // Snap to increments of defaultLayoutWidth / 2.0.
2370             float factor = static_cast<float>(width) / (defaultLayoutWidth / 2.0);
2371             factor = ceilf(factor);
2372             width = (defaultLayoutWidth / 2.0) * factor;
2373         }
2374
2375         if (width < minWidth)
2376             width = minWidth;
2377         if (width > maxWidth)
2378             width = maxWidth;
2379         int height = ceilf(static_cast<float>(width) / static_cast<float>(defaultLayoutWidth) * static_cast<float>(defaultLayoutHeight));
2380         return IntSize(width, height);
2381     }
2382
2383     ASSERT_NOT_REACHED();
2384     return IntSize(defaultLayoutWidth, defaultLayoutHeight);
2385 }
2386
2387 BackingStoreClient* WebPagePrivate::backingStoreClient() const
2388 {
2389     return m_backingStoreClient;
2390 }
2391
2392 void WebPagePrivate::clearDocumentData(const Document* documentGoingAway)
2393 {
2394     ASSERT(documentGoingAway);
2395     if (m_currentContextNode && m_currentContextNode->document() == documentGoingAway)
2396         m_currentContextNode = 0;
2397
2398     if (m_currentPinchZoomNode && m_currentPinchZoomNode->document() == documentGoingAway)
2399         m_currentPinchZoomNode = 0;
2400
2401     if (m_currentBlockZoomAdjustedNode && m_currentBlockZoomAdjustedNode->document() == documentGoingAway)
2402         m_currentBlockZoomAdjustedNode = 0;
2403
2404     if (m_inRegionScroller->d->isActive())
2405         m_inRegionScroller->d->clearDocumentData(documentGoingAway);
2406
2407     if (documentGoingAway->frame())
2408         m_inputHandler->frameUnloaded(documentGoingAway->frame());
2409
2410     Node* nodeUnderFatFinger = m_touchEventHandler->lastFatFingersResult().node();
2411     if (nodeUnderFatFinger && nodeUnderFatFinger->document() == documentGoingAway)
2412         m_touchEventHandler->resetLastFatFingersResult();
2413
2414     // NOTE: m_fullscreenNode, m_fullScreenPluginView and m_pluginViews
2415     // are cleared in other methods already.
2416 }
2417
2418 typedef bool (*PredicateFunction)(RenderLayer*);
2419 static bool isPositionedContainer(RenderLayer* layer)
2420 {
2421     RenderObject* o = layer->renderer();
2422     return o->isRenderView() || o->isOutOfFlowPositioned() || o->isRelPositioned() || layer->hasTransform();
2423 }
2424
2425 static bool isFixedPositionedContainer(RenderLayer* layer)
2426 {
2427     RenderObject* o = layer->renderer();
2428     return o->isRenderView() || (o->isOutOfFlowPositioned() && o->style()->position() == FixedPosition);
2429 }
2430
2431 static RenderLayer* findAncestorOrSelfNotMatching(PredicateFunction predicate, RenderLayer* layer)
2432 {
2433     RenderLayer* curr = layer;
2434     while (curr && !predicate(curr))
2435         curr = curr->parent();
2436
2437     return curr;
2438 }
2439
2440 RenderLayer* WebPagePrivate::enclosingFixedPositionedAncestorOrSelfIfFixedPositioned(RenderLayer* layer)
2441 {
2442     return findAncestorOrSelfNotMatching(&isFixedPositionedContainer, layer);
2443 }
2444
2445 RenderLayer* WebPagePrivate::enclosingPositionedAncestorOrSelfIfPositioned(RenderLayer* layer)
2446 {
2447     return findAncestorOrSelfNotMatching(&isPositionedContainer, layer);
2448 }
2449
2450 static inline Frame* frameForNode(Node* node)
2451 {
2452     Node* origNode = node;
2453     for (; node; node = node->parentNode()) {
2454         if (RenderObject* renderer = node->renderer()) {
2455             if (renderer->isRenderView()) {
2456                 if (FrameView* view = toRenderView(renderer)->frameView()) {
2457                     if (Frame* frame = view->frame())
2458                         return frame;
2459                 }
2460             }
2461             if (renderer->isWidget()) {
2462                 Widget* widget = toRenderWidget(renderer)->widget();
2463                 if (widget && widget->isFrameView()) {
2464                     if (Frame* frame = toFrameView(widget)->frame())
2465                         return frame;
2466                 }
2467             }
2468         }
2469     }
2470
2471     for (node = origNode; node; node = node->parentNode()) {
2472         if (Document* doc = node->document()) {
2473             if (Frame* frame = doc->frame())
2474                 return frame;
2475         }
2476     }
2477
2478     return 0;
2479 }
2480
2481 static IntRect getNodeWindowRect(Node* node)
2482 {
2483     if (Frame* frame = frameForNode(node)) {
2484         if (FrameView* view = frame->view())
2485             return view->contentsToWindow(node->getRect());
2486     }
2487     ASSERT_NOT_REACHED();
2488     return IntRect();
2489 }
2490
2491 IntRect WebPagePrivate::getRecursiveVisibleWindowRect(ScrollView* view, bool noClipOfMainFrame)
2492 {
2493     ASSERT(m_mainFrame);
2494
2495     // Don't call this function asking to not clip the main frame providing only
2496     // the main frame. All that can be returned is the content rect which
2497     // isn't what this function is for.
2498     if (noClipOfMainFrame && view == m_mainFrame->view()) {
2499         ASSERT_NOT_REACHED();
2500         return IntRect(IntPoint::zero(), view->contentsSize());
2501     }
2502
2503     IntRect visibleWindowRect(view->contentsToWindow(view->visibleContentRect()));
2504     if (view->parent() && !(noClipOfMainFrame && view->parent() == m_mainFrame->view())) {
2505         // Intersect with parent visible rect.
2506         visibleWindowRect.intersect(getRecursiveVisibleWindowRect(view->parent(), noClipOfMainFrame));
2507     }
2508     return visibleWindowRect;
2509 }
2510
2511 void WebPagePrivate::assignFocus(Platform::FocusDirection direction)
2512 {
2513     ASSERT((int) Platform::FocusDirectionNone == (int) FocusDirectionNone);
2514     ASSERT((int) Platform::FocusDirectionForward == (int) FocusDirectionForward);
2515     ASSERT((int) Platform::FocusDirectionBackward == (int) FocusDirectionBackward);
2516
2517     // First we clear the focus, since we want to focus either initial or the last
2518     // focusable element in the webpage (according to the TABINDEX), or simply clear
2519     // the focus.
2520     clearFocusNode();
2521
2522     switch (direction) {
2523     case FocusDirectionForward:
2524     case FocusDirectionBackward:
2525         m_page->focusController()->setInitialFocus((FocusDirection) direction, 0);
2526         break;
2527     case FocusDirectionNone:
2528         break;
2529     default:
2530         ASSERT_NOT_REACHED();
2531     }
2532 }
2533
2534 void WebPage::assignFocus(Platform::FocusDirection direction)
2535 {
2536     if (d->m_page->defersLoading())
2537        return;
2538     d->assignFocus(direction);
2539 }
2540
2541 void WebPage::focusNextField()
2542 {
2543     d->m_inputHandler->focusNextField();
2544 }
2545
2546 void WebPage::focusPreviousField()
2547 {
2548     d->m_inputHandler->focusPreviousField();
2549 }
2550
2551 void WebPage::submitForm()
2552 {
2553     d->m_inputHandler->submitForm();
2554 }
2555
2556 Platform::IntRect WebPagePrivate::focusNodeRect()
2557 {
2558     Frame* frame = focusedOrMainFrame();
2559     if (!frame)
2560         return Platform::IntRect();
2561
2562     Document* doc = frame->document();
2563     FrameView* view = frame->view();
2564     if (!doc || !view || view->needsLayout())
2565         return Platform::IntRect();
2566
2567     const Platform::ViewportAccessor* viewportAccessor = m_webkitThreadViewportAccessor;
2568
2569     IntRect focusRect = rectForNode(doc->focusedNode());
2570     focusRect = adjustRectOffsetForFrameOffset(focusRect, doc->focusedNode());
2571     focusRect = viewportAccessor->roundToPixelFromDocumentContents(WebCore::FloatRect(focusRect));
2572     focusRect.intersect(viewportAccessor->pixelContentsRect());
2573     return focusRect;
2574 }
2575
2576 PassRefPtr<Node> WebPagePrivate::contextNode(TargetDetectionStrategy strategy)
2577 {
2578     EventHandler* eventHandler = focusedOrMainFrame()->eventHandler();
2579     const FatFingersResult lastFatFingersResult = m_touchEventHandler->lastFatFingersResult();
2580     bool isTouching = lastFatFingersResult.isValid() && strategy == RectBased;
2581
2582     // Check if we're using LinkToLink and the user is not touching the screen.
2583     if (m_webSettings->doesGetFocusNodeContext() && !isTouching) {
2584         RefPtr<Node> node;
2585         node = m_page->focusController()->focusedOrMainFrame()->document()->focusedNode();
2586         if (node) {
2587             IntRect visibleRect = IntRect(IntPoint(), actualVisibleSize());
2588             if (!visibleRect.intersects(getNodeWindowRect(node.get())))
2589                 return 0;
2590         }
2591         return node.release();
2592     }
2593
2594     // Check for text input.
2595     if (isTouching && lastFatFingersResult.isTextInput())
2596         return lastFatFingersResult.node(FatFingersResult::ShadowContentNotAllowed);
2597
2598     if (strategy == RectBased) {
2599         FatFingersResult result = FatFingers(this, lastFatFingersResult.adjustedPosition(), FatFingers::Text).findBestPoint();
2600         return result.node(FatFingersResult::ShadowContentNotAllowed);
2601     }
2602     if (strategy == FocusBased)
2603         return m_inputHandler->currentFocusElement();
2604
2605     IntPoint contentPos;
2606     if (isTouching)
2607         contentPos = lastFatFingersResult.adjustedPosition();
2608     else
2609         contentPos = m_webkitThreadViewportAccessor->documentContentsFromViewport(m_lastMouseEvent.position());
2610
2611     HitTestResult result = eventHandler->hitTestResultAtPoint(contentPos);
2612     return result.innerNode();
2613 }
2614
2615 static inline int distanceBetweenPoints(IntPoint p1, IntPoint p2)
2616 {
2617     // Change int to double, because (dy * dy) can cause int overflow in reality, e.g, (-46709 * -46709).
2618     double dx = static_cast<double>(p1.x() - p2.x());
2619     double dy = static_cast<double>(p1.y() - p2.y());
2620     return sqrt((dx * dx) + (dy * dy));
2621 }
2622
2623 Node* WebPagePrivate::bestNodeForZoomUnderPoint(const IntPoint& documentPoint)
2624 {
2625     IntRect clickRect(documentPoint.x() - blockClickRadius, documentPoint.y() - blockClickRadius, 2 * blockClickRadius, 2 * blockClickRadius);
2626     Node* originalNode = nodeForZoomUnderPoint(documentPoint);
2627     if (!originalNode)
2628         return 0;
2629     Node* node = bestChildNodeForClickRect(originalNode, clickRect);
2630     return node ? adjustedBlockZoomNodeForZoomAndExpandingRatioLimits(node) : adjustedBlockZoomNodeForZoomAndExpandingRatioLimits(originalNode);
2631 }
2632
2633 Node* WebPagePrivate::bestChildNodeForClickRect(Node* parentNode, const IntRect& clickRect)
2634 {
2635     if (!parentNode)
2636         return 0;
2637
2638     int bestDistance = std::numeric_limits<int>::max();
2639
2640     Node* node = parentNode->firstChild();
2641     Node* bestNode = 0;
2642     for (; node; node = node->nextSibling()) {
2643         IntRect rect = rectForNode(node);
2644         if (!clickRect.intersects(rect))
2645             continue;
2646
2647         int distance = distanceBetweenPoints(rect.center(), clickRect.center());
2648         Node* bestChildNode = bestChildNodeForClickRect(node, clickRect);
2649         if (bestChildNode) {
2650             IntRect bestChildRect = rectForNode(bestChildNode);
2651             int bestChildDistance = distanceBetweenPoints(bestChildRect.center(), clickRect.center());
2652             if (bestChildDistance < distance && bestChildDistance < bestDistance) {
2653                 bestNode = bestChildNode;
2654                 bestDistance = bestChildDistance;
2655             } else {
2656                 if (distance < bestDistance) {
2657                     bestNode = node;
2658                     bestDistance = distance;
2659                 }
2660             }
2661         } else {
2662             if (distance < bestDistance) {
2663                 bestNode = node;
2664                 bestDistance = distance;
2665             }
2666         }
2667     }
2668
2669     return bestNode;
2670 }
2671
2672 double WebPagePrivate::maxBlockZoomScale() const
2673 {
2674     return std::min(maximumBlockZoomScale, maximumScale());
2675 }
2676
2677 Node* WebPagePrivate::nodeForZoomUnderPoint(const IntPoint& documentPoint)
2678 {
2679     if (!m_mainFrame)
2680         return 0;
2681
2682     HitTestResult result = m_mainFrame->eventHandler()->hitTestResultAtPoint(documentPoint);
2683
2684     Node* node = result.innerNonSharedNode();
2685
2686     if (!node)
2687         return 0;
2688
2689     RenderObject* renderer = node->renderer();
2690     while (!renderer) {
2691         node = node->parentNode();
2692         renderer = node->renderer();
2693     }
2694
2695     return node;
2696 }
2697
2698 Node* WebPagePrivate::adjustedBlockZoomNodeForZoomAndExpandingRatioLimits(Node* node)
2699 {
2700     Node* initialNode = node;
2701     RenderObject* renderer = node->renderer();
2702     bool acceptableNodeSize = newScaleForBlockZoomRect(rectForNode(node), 1.0, 0) < maxBlockZoomScale();
2703     IntSize actualVisibleSize = this->actualVisibleSize();
2704
2705     while (!renderer || !acceptableNodeSize) {
2706         node = node->parentNode();
2707         IntRect nodeRect = rectForNode(node);
2708
2709         // Don't choose a node if the width of the node size is very close to the width of the actual visible size,
2710         // as block zoom can do nothing on such kind of node.
2711         if (!node || static_cast<double>(actualVisibleSize.width() - nodeRect.width()) / actualVisibleSize.width() < minimumExpandingRatio)
2712             return initialNode;
2713
2714         renderer = node->renderer();
2715         acceptableNodeSize = newScaleForBlockZoomRect(rectForNode(node), 1.0, 0) < maxBlockZoomScale();
2716     }
2717
2718     return node;
2719 }
2720
2721 bool WebPagePrivate::compareNodesForBlockZoom(Node* n1, Node* n2)
2722 {
2723     if (!n1 || !n2)
2724         return false;
2725
2726     return (n2 == n1) || n2->isDescendantOf(n1);
2727 }
2728
2729 double WebPagePrivate::newScaleForBlockZoomRect(const IntRect& rect, double oldScale, double margin)
2730 {
2731     if (rect.isEmpty())
2732         return std::numeric_limits<double>::max();
2733
2734     ASSERT(rect.width() + margin);
2735
2736     double newScale = oldScale * static_cast<double>(transformedActualVisibleSize().width()) / (rect.width() + margin);
2737
2738     return newScale;
2739 }
2740
2741 IntRect WebPagePrivate::rectForNode(Node* node)
2742 {
2743     if (!node)
2744         return IntRect();
2745
2746     RenderObject* renderer = node->renderer();
2747
2748     if (!renderer)
2749         return IntRect();
2750
2751     // Return rect in un-transformed content coordinates.
2752     IntRect blockRect;
2753
2754     // FIXME: Ensure this works with iframes.
2755     if (m_webPage->settings()->textReflowMode() == WebSettings::TextReflowEnabled && renderer->isText()) {
2756         RenderBlock* renderBlock = renderer->containingBlock();
2757         int xOffset = 0;
2758         int yOffset = 0;
2759         while (!renderBlock->isRoot()) {
2760             xOffset += renderBlock->x().toInt();
2761             yOffset += renderBlock->y().toInt();
2762             renderBlock = renderBlock->containingBlock();
2763         }
2764         const RenderText* renderText = toRenderText(renderer);
2765         IntRect linesBox = renderText->linesBoundingBox();
2766         blockRect = IntRect(xOffset + linesBox.x(), yOffset + linesBox.y(), linesBox.width(), linesBox.height());
2767     } else
2768         blockRect = IntRect(renderer->absoluteClippedOverflowRect());
2769
2770     if (renderer->isText()) {
2771         RenderBlock* rb = renderer->containingBlock();
2772
2773         // Inefficient? Way to find width when floats intersect a block.
2774         int blockWidth = 0;
2775         int lineCount = rb->lineCount();
2776         for (int i = 0; i < lineCount; i++)
2777             blockWidth = max(blockWidth, rb->availableLogicalWidthForLine(i, false).toInt());
2778
2779         blockRect.setWidth(blockWidth);
2780         blockRect.setX(blockRect.x() + rb->logicalLeftOffsetForLine(1, false));
2781     }
2782
2783     // Strip off padding.
2784     if (renderer->style()->hasPadding()) {
2785         blockRect.setX(blockRect.x() + renderer->style()->paddingLeft().value());
2786         blockRect.setY(blockRect.y() + renderer->style()->paddingTop().value());
2787         blockRect.setWidth(blockRect.width() - renderer->style()->paddingRight().value());
2788         blockRect.setHeight(blockRect.height() - renderer->style()->paddingBottom().value());
2789     }
2790
2791     return blockRect;
2792 }
2793
2794 IntPoint WebPagePrivate::frameOffset(const Frame* frame) const
2795 {
2796     ASSERT(frame);
2797
2798     // FIXME: This function can be called when page is being destroyed and JS triggers selection change.
2799     // We could break the call chain at upper levels, but I think it is better to check the frame pointer
2800     // here because the pointer is explicitly cleared in WebPage::destroy().
2801     if (!mainFrame())
2802         return IntPoint();
2803
2804     // Convert 0,0 in the frame's coordinate system to window coordinates to
2805     // get the frame's global position, and return this position in the main
2806     // frame's coordinates.  (So the main frame's coordinates will be 0,0.)
2807     return mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint::zero()));
2808 }
2809
2810 IntRect WebPagePrivate::adjustRectOffsetForFrameOffset(const IntRect& rect, const Node* node)
2811 {
2812     if (!node)
2813         return rect;
2814
2815     // Adjust the offset of the rect if it is in an iFrame/frame or set of iFrames/frames.
2816     // FIXME: can we just use frameOffset instead of this big routine?
2817     const Node* tnode = node;
2818     IntRect adjustedRect = rect;
2819     do {
2820         Frame* frame = tnode->document()->frame();
2821         if (!frame)
2822             continue;
2823
2824         Node* ownerNode = static_cast<Node*>(frame->ownerElement());
2825         tnode = ownerNode;
2826         if (ownerNode && (ownerNode->hasTagName(HTMLNames::iframeTag) || ownerNode->hasTagName(HTMLNames::frameTag))) {
2827             IntRect iFrameRect;
2828             do {
2829                 iFrameRect = rectForNode(ownerNode);
2830                 adjustedRect.move(iFrameRect.x(), iFrameRect.y());
2831                 adjustedRect.intersect(iFrameRect);
2832                 ownerNode = ownerNode->parentNode();
2833             } while (iFrameRect.isEmpty() && ownerNode);
2834         } else
2835             break;
2836     } while (tnode = tnode->parentNode());
2837
2838     return adjustedRect;
2839 }
2840
2841 IntRect WebPagePrivate::blockZoomRectForNode(Node* node)
2842 {
2843     if (!node || contentsSize().isEmpty())
2844         return IntRect();
2845
2846     Node* tnode = node;
2847     m_currentBlockZoomAdjustedNode = tnode;
2848
2849     IntRect blockRect = rectForNode(tnode);
2850     IntRect originalRect = blockRect;
2851
2852     int originalArea = originalRect.width() * originalRect.height();
2853     int pageArea = contentsSize().width() * contentsSize().height();
2854     double blockToPageRatio = static_cast<double>(pageArea - originalArea) / pageArea;
2855     double blockExpansionRatio = 5.0 * blockToPageRatio * blockToPageRatio;
2856
2857     if (!tnode->hasTagName(HTMLNames::imgTag) && !tnode->hasTagName(HTMLNames::inputTag) && !tnode->hasTagName(HTMLNames::textareaTag)) {
2858         while (tnode = tnode->parentNode()) {
2859             ASSERT(tnode);
2860             IntRect tRect = rectForNode(tnode);
2861             int tempBlockArea = tRect.width() * tRect.height();
2862             // Don't expand the block if it will be too large relative to the content.
2863             if (static_cast<double>(pageArea - tempBlockArea) / pageArea < minimumExpandingRatio)
2864                 break;
2865             if (tRect.isEmpty())
2866                 continue; // No renderer.
2867             if (tempBlockArea < 1.1 * originalArea)
2868                 continue; // The size of this parent is very close to the child, no need to go to this parent.
2869             // Don't expand the block if the parent node size is already almost the size of actual visible size.
2870             IntSize actualSize = actualVisibleSize();
2871             if (static_cast<double>(actualSize.width() - tRect.width()) / actualSize.width() < minimumExpandingRatio)
2872                 break;
2873             if (tempBlockArea < blockExpansionRatio * originalArea) {
2874                 blockRect = tRect;
2875                 m_currentBlockZoomAdjustedNode = tnode;
2876             } else
2877                 break;
2878         }
2879     }
2880
2881     const Platform::ViewportAccessor* viewportAccessor = m_webkitThreadViewportAccessor;
2882
2883     blockRect = adjustRectOffsetForFrameOffset(blockRect, node);
2884     blockRect = viewportAccessor->roundToPixelFromDocumentContents(WebCore::FloatRect(blockRect));
2885     blockRect.intersect(viewportAccessor->pixelContentsRect());
2886
2887     return blockRect;
2888 }
2889
2890 // This function should not be called directly.
2891 // It is called after the animation ends (see above).
2892 void WebPagePrivate::zoomAnimationFinished(double finalAnimationScale, const WebCore::FloatPoint& finalAnimationDocumentScrollPosition, bool shouldConstrainScrollingToContentEdge)
2893 {
2894     if (!m_mainFrame)
2895         return;
2896
2897     const Platform::ViewportAccessor* viewportAccessor = m_webkitThreadViewportAccessor;
2898
2899     IntPoint anchor(viewportAccessor->roundedDocumentContents(finalAnimationDocumentScrollPosition));
2900     bool willUseTextReflow = false;
2901
2902 #if ENABLE(VIEWPORT_REFLOW)
2903     willUseTextReflow = m_webPage->settings()->textReflowMode() != WebSettings::TextReflowDisabled;
2904     toggleTextReflowIfEnabledForBlockZoomOnly(m_shouldReflowBlock);
2905     setNeedsLayout();
2906 #endif
2907
2908     TransformationMatrix zoom;
2909     zoom.scale(finalAnimationScale);
2910     *m_transformationMatrix = zoom;
2911     // FIXME: Do we really need to suspend/resume both backingstore and screen here?
2912     m_backingStore->d->suspendBackingStoreUpdates();
2913     m_backingStore->d->suspendScreenUpdates();
2914     updateViewportSize();
2915
2916     FrameView* mainFrameView = m_mainFrame->view();
2917     bool constrainsScrollingToContentEdge = true;
2918     if (mainFrameView) {
2919         constrainsScrollingToContentEdge = mainFrameView->constrainsScrollingToContentEdge();
2920         mainFrameView->setConstrainsScrollingToContentEdge(shouldConstrainScrollingToContentEdge);
2921     }
2922
2923 #if ENABLE(VIEWPORT_REFLOW)
2924     requestLayoutIfNeeded();
2925     if (willUseTextReflow && m_shouldReflowBlock) {
2926         Platform::IntPoint roundedReflowOffset(
2927             std::floorf(m_finalAnimationDocumentScrollPositionReflowOffset.x()),
2928             std::floorf(m_finalAnimationDocumentScrollPositionReflowOffset.y()));
2929
2930         IntRect reflowedRect = rectForNode(m_currentBlockZoomAdjustedNode.get());
2931         reflowedRect = adjustRectOffsetForFrameOffset(reflowedRect, m_currentBlockZoomAdjustedNode.get());
2932         reflowedRect.move(roundedReflowOffset.x(), roundedReflowOffset.y());
2933
2934         RenderObject* renderer = m_currentBlockZoomAdjustedNode->renderer();
2935         IntPoint topLeftPoint(reflowedRect.location());
2936         if (renderer && renderer->isText()) {
2937             ETextAlign textAlign = renderer->style()->textAlign();
2938             IntPoint textAnchor;
2939             switch (textAlign) {
2940             case CENTER:
2941             case WEBKIT_CENTER:
2942                 textAnchor = IntPoint(reflowedRect.x() + (reflowedRect.width() - actualVisibleSize().width()) / 2, topLeftPoint.y());
2943                 break;
2944             case LEFT:
2945             case WEBKIT_LEFT:
2946                 textAnchor = topLeftPoint;
2947                 break;
2948             case RIGHT:
2949             case WEBKIT_RIGHT:
2950                 textAnchor = IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y());
2951                 break;
2952             case TASTART:
2953             case JUSTIFY:
2954             default:
2955                 if (renderer->style()->isLeftToRightDirection())
2956                     textAnchor = topLeftPoint;
2957                 else
2958                     textAnchor = IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y());
2959                 break;
2960             }
2961             setScrollPosition(textAnchor);
2962         } else {
2963             renderer->style()->isLeftToRightDirection()
2964                 ? setScrollPosition(topLeftPoint)
2965                 : setScrollPosition(IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y()));
2966         }
2967     } else if (willUseTextReflow) {
2968         IntRect finalRect = rectForNode(m_currentBlockZoomAdjustedNode.get());
2969         finalRect = adjustRectOffsetForFrameOffset(finalRect, m_currentBlockZoomAdjustedNode.get());
2970         setScrollPosition(IntPoint(0, finalRect.y() + m_finalAnimationDocumentScrollPositionReflowOffset.y()));
2971         resetBlockZoom();
2972     }
2973 #endif
2974     if (!willUseTextReflow) {
2975         setScrollPosition(anchor);
2976         if (!m_shouldReflowBlock)
2977             resetBlockZoom();
2978     }
2979
2980     notifyTransformChanged();
2981     m_client->scaleChanged();
2982
2983     if (mainFrameView)
2984         mainFrameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge);
2985
2986     // FIXME: Do we really need to suspend/resume both backingstore and screen here?
2987     m_backingStore->d->resumeBackingStoreUpdates();
2988     m_backingStore->d->resumeScreenUpdates(BackingStore::RenderAndBlit);
2989 }
2990
2991 void WebPage::zoomAnimationFinished(double finalScale, const Platform::FloatPoint& finalDocumentScrollPosition, bool shouldConstrainScrollingToContentEdge)
2992 {
2993     d->zoomAnimationFinished(finalScale, finalDocumentScrollPosition, shouldConstrainScrollingToContentEdge);
2994 }
2995
2996 void WebPage::resetBlockZoom()
2997 {
2998     d->resetBlockZoom();
2999 }
3000
3001 void WebPagePrivate::resetBlockZoom()
3002 {
3003     m_currentBlockZoomNode = 0;
3004     m_currentBlockZoomAdjustedNode = 0;
3005     m_shouldReflowBlock = false;
3006 }
3007
3008 void WebPage::destroyWebPageCompositor()
3009 {
3010 #if USE(ACCELERATED_COMPOSITING)
3011     // Destroy the layer renderer in a sync command before we destroy the backing store,
3012     // to flush any pending compositing messages on the compositing thread.
3013     // The backing store is indirectly deleted by the 'detachFromParent' call below.
3014     d->syncDestroyCompositorOnCompositingThread();
3015 #endif
3016 }
3017
3018 void WebPage::destroy()
3019 {
3020     // TODO: need to verify if this call needs to be made before calling
3021     // Close the Inspector to resume the JS engine if it's paused.
3022     disableWebInspector();
3023
3024     // WebPage::destroyWebPageCompositor()
3025     // FIXME: Do we really need to suspend/resume both backingstore and screen here?
3026     d->m_backingStore->d->suspendBackingStoreUpdates();
3027     d->m_backingStore->d->suspendScreenUpdates();
3028
3029     // Close the backforward list and release the cached pages.
3030     d->m_page->backForward()->close();
3031
3032     FrameLoader* loader = d->m_mainFrame->loader();
3033
3034     // Set m_mainFrame to 0 to avoid calls back in to the backingstore during webpage deletion.
3035     d->m_mainFrame = 0;
3036     if (loader)
3037         loader->detachFromParent();
3038
3039     deleteGuardedObject(this);
3040 }
3041
3042 WebPageClient* WebPage::client() const
3043 {
3044     return d->m_client;
3045 }
3046
3047 int WebPage::backForwardListLength() const
3048 {
3049     return d->m_page->getHistoryLength();
3050 }
3051
3052 bool WebPage::canGoBackOrForward(int delta) const
3053 {
3054     return d->m_page->canGoBackOrForward(delta);
3055 }
3056
3057 bool WebPage::goBackOrForward(int delta)
3058 {
3059     if (d->m_page->canGoBackOrForward(delta)) {
3060         d->m_userPerformedManualZoom = false;
3061         d->m_userPerformedManualScroll = false;
3062         d->m_backingStore->d->suspendScreenUpdates();
3063         d->m_page->goBackOrForward(delta);
3064         d->m_backingStore->d->resumeScreenUpdates(BackingStore::None);
3065         return true;
3066     }
3067     return false;
3068 }
3069
3070 void WebPage::goToBackForwardEntry(BackForwardId id)
3071 {
3072     HistoryItem* item = historyItemFromBackForwardId(id);
3073     ASSERT(item);
3074     d->m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
3075 }
3076
3077 void WebPage::reload()
3078 {
3079     d->m_mainFrame->loader()->reload(/* bypassCache */ true);
3080 }
3081
3082 void WebPage::reloadFromCache()
3083 {
3084     d->m_mainFrame->loader()->reload(/* bypassCache */ false);
3085 }
3086
3087 WebSettings* WebPage::settings() const
3088 {
3089     return d->m_webSettings;
3090 }
3091
3092 WebCookieJar* WebPage::cookieJar() const
3093 {
3094     if (!d->m_cookieJar)
3095         d->m_cookieJar = new WebCookieJar();
3096
3097     return d->m_cookieJar;
3098 }
3099
3100 bool WebPage::isLoading() const
3101 {
3102     return d->isLoading();
3103 }
3104
3105 bool WebPage::isVisible() const
3106 {
3107     return d->m_visible;
3108 }
3109
3110 #if ENABLE(PAGE_VISIBILITY_API)
3111 class DeferredTaskSetPageVisibilityState: public DeferredTask<&WebPagePrivate::m_wouldSetPageVisibilityState> {
3112 public:
3113     explicit DeferredTaskSetPageVisibilityState(WebPagePrivate* webPagePrivate)
3114         : DeferredTaskType(webPagePrivate)
3115     {
3116     }
3117 private:
3118     virtual void performInternal(WebPagePrivate* webPagePrivate)
3119     {
3120         webPagePrivate->setPageVisibilityState();
3121     }
3122 };
3123
3124 void WebPagePrivate::setPageVisibilityState()
3125 {
3126     if (m_page->defersLoading())
3127         m_deferredTasks.append(adoptPtr(new DeferredTaskSetPageVisibilityState(this)));
3128     else {
3129         DeferredTaskSetPageVisibilityState::finishOrCancel(this);
3130
3131         static bool s_initialVisibilityState = true;
3132
3133         m_page->setVisibilityState(m_visible && m_activationState == ActivationActive ? PageVisibilityStateVisible : PageVisibilityStateHidden, s_initialVisibilityState);
3134         s_initialVisibilityState = false;
3135     }
3136 }
3137 #endif
3138
3139 void WebPagePrivate::setVisible(bool visible)
3140 {
3141     if (visible != m_visible) {
3142         if (visible) {
3143             if (m_mainFrame)
3144                 m_mainFrame->animation()->resumeAnimations();
3145             if (m_page->scriptedAnimationsSuspended())
3146                 m_page->resumeScriptedAnimations();
3147         } else {
3148             if (m_mainFrame)
3149                 m_mainFrame->animation()->suspendAnimations();
3150             if (!m_page->scriptedAnimationsSuspended())
3151                 m_page->suspendScriptedAnimations();
3152
3153             if (m_webPage->hasOpenedPopup())
3154                 m_page->chrome()->client()->closePagePopup(0);
3155         }
3156
3157         m_visible = visible;
3158         m_backingStore->d->updateSuspendScreenUpdateState();
3159     }
3160
3161 #if ENABLE(PAGE_VISIBILITY_API)
3162     setPageVisibilityState();
3163 #endif
3164 }
3165
3166 void WebPage::setVisible(bool visible)
3167 {
3168     if (d->m_visible == visible)
3169         return;
3170
3171     d->setVisible(visible);
3172     AuthenticationChallengeManager::instance()->pageVisibilityChanged(d, visible);
3173
3174     if (!visible) {
3175         d->suspendBackingStore();
3176
3177         // Remove this WebPage from the visible pages list.
3178         size_t foundIndex = visibleWebPages()->find(this);
3179         if (foundIndex != WTF::notFound)
3180             visibleWebPages()->remove(foundIndex);
3181
3182         // Return the backing store to the last visible WebPage.
3183         if (BackingStorePrivate::currentBackingStoreOwner() == this && !visibleWebPages()->isEmpty())
3184             visibleWebPages()->last()->d->resumeBackingStore();
3185
3186 #if USE(ACCELERATED_COMPOSITING)
3187         // Root layer commit is not necessary for invisible tabs.
3188         // And release layer resources can reduce memory consumption.
3189         d->suspendRootLayerCommit();
3190 #endif
3191
3192         return;
3193     }
3194
3195 #if USE(ACCELERATED_COMPOSITING)
3196     d->resumeRootLayerCommit();
3197 #endif
3198
3199     // We want to become visible but not get backing store ownership.
3200     if (d->m_backingStore->d->isOpenGLCompositing() && !d->m_webSettings->isBackingStoreEnabled()) {
3201         d->setCompositorDrawsRootLayer(true);
3202 #if USE(ACCELERATED_COMPOSITING)
3203         d->setNeedsOneShotDrawingSynchronization();
3204 #endif
3205         d->setShouldResetTilesWhenShown(true);
3206         return;
3207     }
3208
3209     // Push this WebPage to the top of the visible pages list.
3210     if (!visibleWebPages()->isEmpty() && visibleWebPages()->last() != this) {
3211         size_t foundIndex = visibleWebPages()->find(this);
3212         if (foundIndex != WTF::notFound)
3213             visibleWebPages()->remove(foundIndex);
3214     }
3215     visibleWebPages()->append(this);
3216
3217     if (BackingStorePrivate::currentBackingStoreOwner()
3218         && BackingStorePrivate::currentBackingStoreOwner() != this)
3219         BackingStorePrivate::currentBackingStoreOwner()->d->suspendBackingStore();
3220
3221     // resumeBackingStore will set the current owner to this webpage.
3222     // If we set the owner prematurely, then the tiles will not be reset.
3223     d->resumeBackingStore();
3224 }
3225
3226 void WebPagePrivate::selectionChanged(Frame* frame)
3227 {
3228     m_inputHandler->selectionChanged();
3229
3230     // FIXME: This is a hack!
3231     // To ensure the selection being changed has its frame 'focused', lets
3232     // set it as focused ourselves (PR #104724).
3233     m_page->focusController()->setFocusedFrame(frame);
3234 }
3235
3236 void WebPagePrivate::updateSelectionScrollView(const Node* node)
3237 {
3238     m_inRegionScroller->d->updateSelectionScrollView(node);
3239 }
3240
3241 void WebPagePrivate::updateDelegatedOverlays(bool dispatched)
3242 {
3243     // Track a dispatched message, we don't want to flood the webkit thread.
3244     // There can be as many as one more message enqued as needed but never less.
3245     if (dispatched)
3246         m_updateDelegatedOverlaysDispatched = false;
3247     else if (m_updateDelegatedOverlaysDispatched) {
3248         // Early return if there is message already pending on the webkit thread.
3249         return;
3250     }
3251
3252     if (Platform::webKitThreadMessageClient()->isCurrentThread()) {
3253         // Must be called on the WebKit thread.
3254         if (m_selectionHandler->isSelectionActive())
3255             m_selectionHandler->selectionPositionChanged();
3256         if (m_inspectorOverlay)
3257             m_inspectorOverlay->update();
3258
3259     } else if (m_selectionHandler->isSelectionActive()) {
3260         // Don't bother dispatching to webkit thread if selection and tap highlight are not active.
3261         m_updateDelegatedOverlaysDispatched = true;
3262         Platform::webKitThreadMessageClient()->dispatchMessage(Platform::createMethodCallMessage(&WebPagePrivate::updateDelegatedOverlays, this, true /*dispatched*/));
3263     }
3264 }
3265
3266 void WebPage::setCaretHighlightStyle(Platform::CaretHighlightStyle style)
3267 {
3268 }
3269
3270 bool WebPage::setBatchEditingActive(bool active)
3271 {
3272     return d->m_inputHandler->setBatchEditingActive(active);
3273 }
3274
3275 bool WebPage::setInputSelection(unsigned start, unsigned end)
3276 {
3277     if (d->m_page->defersLoading())
3278         return false;
3279     return d->m_inputHandler->setSelection(start, end);
3280 }
3281
3282 int WebPage::inputCaretPosition() const
3283 {
3284     return d->m_inputHandler->caretPosition();
3285 }
3286
3287 class DeferredTaskPopupListSelectMultiple: public DeferredTask<&WebPagePrivate::m_wouldPopupListSelectMultiple> {
3288 public:
3289     DeferredTaskPopupListSelectMultiple(WebPagePrivate* webPagePrivate, int size, const bool* selecteds)
3290         : DeferredTaskType(webPagePrivate)
3291     {
3292         webPagePrivate->m_cachedPopupListSelecteds.append(selecteds, size);
3293     }
3294 private:
3295     virtual void performInternal(WebPagePrivate* webPagePrivate)
3296     {
3297         webPagePrivate->m_webPage->popupListClosed(webPagePrivate->m_cachedPopupListSelecteds.size(), webPagePrivate->m_cachedPopupListSelecteds.data());
3298     }
3299 };
3300
3301 class DeferredTaskPopupListSelectSingle: public DeferredTask<&WebPagePrivate::m_wouldPopupListSelectSingle> {
3302 public:
3303     explicit DeferredTaskPopupListSelectSingle(WebPagePrivate* webPagePrivate, int index)
3304         : DeferredTaskType(webPagePrivate)
3305     {
3306         webPagePrivate->m_cachedPopupListSelectedIndex = index;
3307     }
3308 private:
3309     virtual void performInternal(WebPagePrivate* webPagePrivate)
3310     {
3311         webPagePrivate->m_webPage->popupListClosed(webPagePrivate->m_cachedPopupListSelectedIndex);
3312     }
3313 };
3314
3315 void WebPage::popupListClosed(int size, const bool* selecteds)
3316 {
3317     DeferredTaskPopupListSelectSingle::finishOrCancel(d);
3318     if (d->m_page->defersLoading()) {
3319         d->m_deferredTasks.append(adoptPtr(new DeferredTaskPopupListSelectMultiple(d, size, selecteds)));
3320         return;
3321     }
3322     DeferredTaskPopupListSelectMultiple::finishOrCancel(d);
3323     d->m_inputHandler->setPopupListIndexes(size, selecteds);
3324 }
3325
3326 void WebPage::popupListClosed(int index)
3327 {
3328     DeferredTaskPopupListSelectMultiple::finishOrCancel(d);
3329     if (d->m_page->defersLoading()) {
3330         d->m_deferredTasks.append(adoptPtr(new DeferredTaskPopupListSelectSingle(d, index)));
3331         return;
3332     }
3333     DeferredTaskPopupListSelectSingle::finishOrCancel(d);
3334     d->m_inputHandler->setPopupListIndex(index);
3335 }
3336
3337 class DeferredTaskSetDateTimeInput: public DeferredTask<&WebPagePrivate::m_wouldSetDateTimeInput> {
3338 public:
3339     explicit DeferredTaskSetDateTimeInput(WebPagePrivate* webPagePrivate, BlackBerry::Platform::String value)
3340         : DeferredTaskType(webPagePrivate)
3341     {
3342         webPagePrivate->m_cachedDateTimeInput = value;
3343     }
3344 private:
3345     virtual void performInternal(WebPagePrivate* webPagePrivate)
3346     {
3347         webPagePrivate->m_webPage->setDateTimeInput(webPagePrivate->m_cachedDateTimeInput);
3348     }
3349 };
3350
3351 void WebPage::setDateTimeInput(const BlackBerry::Platform::String& value)
3352 {
3353     if (d->m_page->defersLoading()) {
3354         d->m_deferredTasks.append(adoptPtr(new DeferredTaskSetDateTimeInput(d, value)));
3355         return;
3356     }
3357     DeferredTaskSetDateTimeInput::finishOrCancel(d);
3358     d->m_inputHandler->setInputValue(value);
3359 }
3360
3361 class DeferredTaskSetColorInput: public DeferredTask<&WebPagePrivate::m_wouldSetColorInput> {
3362 public:
3363     explicit DeferredTaskSetColorInput(WebPagePrivate* webPagePrivate, BlackBerry::Platform::String value)
3364         : DeferredTaskType(webPagePrivate)
3365     {
3366         webPagePrivate->m_cachedColorInput = value;
3367     }
3368 private:
3369     virtual void performInternal(WebPagePrivate* webPagePrivate)
3370     {
3371         webPagePrivate->m_webPage->setColorInput(webPagePrivate->m_cachedColorInput);
3372     }
3373 };
3374
3375 void WebPage::setColorInput(const BlackBerry::Platform::String& value)
3376 {
3377     if (d->m_page->defersLoading()) {
3378         d->m_deferredTasks.append(adoptPtr(new DeferredTaskSetColorInput(d, value)));
3379         return;
3380     }
3381     DeferredTaskSetColorInput::finishOrCancel(d);
3382     d->m_inputHandler->setInputValue(value);
3383 }
3384
3385 void WebPage::setVirtualViewportSize(const Platform::IntSize& size)
3386 {
3387     d->m_virtualViewportSize = WebCore::IntSize(size);
3388 }
3389
3390 void WebPage::resetVirtualViewportOnCommitted(bool reset)
3391 {
3392     d->m_resetVirtualViewportOnCommitted = reset;
3393 }
3394
3395 Platform::IntSize WebPagePrivate::recomputeVirtualViewportFromViewportArguments()
3396 {
3397     static const ViewportArguments defaultViewportArguments;
3398     if (m_viewportArguments == defaultViewportArguments)
3399         return IntSize();
3400
3401     int desktopWidth = DEFAULT_MAX_LAYOUT_WIDTH;
3402     int deviceWidth = Platform::Graphics::Screen::primaryScreen()->width();
3403     int deviceHeight = Platform::Graphics::Screen::primaryScreen()->height();
3404     float devicePixelRatio = m_webSettings->devicePixelRatio();
3405     ViewportAttributes result = computeViewportAttributes(m_viewportArguments, desktopWidth, deviceWidth, deviceHeight, devicePixelRatio, m_defaultLayoutSize);
3406     m_page->setDeviceScaleFactor(devicePixelRatio);
3407
3408     setUserScalable(m_webSettings->isUserScalable() && result.userScalable);
3409     if (result.initialScale > 0)
3410         setInitialScale(result.initialScale * devicePixelRatio);
3411     if (result.minimumScale > 0)
3412         setMinimumScale(result.minimumScale * devicePixelRatio);
3413     if (result.maximumScale > 0)
3414         setMaximumScale(result.maximumScale * devicePixelRatio);
3415
3416     return Platform::IntSize(result.layoutSize.width(), result.layoutSize.height());
3417 }
3418
3419 #if ENABLE(EVENT_MODE_METATAGS)
3420 void WebPagePrivate::didReceiveCursorEventMode(CursorEventMode mode)
3421 {
3422     if (mode != m_cursorEventMode)
3423         m_client->cursorEventModeChanged(toPlatformCursorEventMode(mode));
3424     m_cursorEventMode = mode;
3425 }
3426
3427 void WebPagePrivate::didReceiveTouchEventMode(TouchEventMode mode)
3428 {
3429     if (mode != m_touchEventMode)
3430         m_client->touchEventModeChanged(toPlatformTouchEventMode(mode));
3431     m_touchEventMode = mode;
3432 }
3433 #endif
3434
3435 void WebPagePrivate::dispatchViewportPropertiesDidChange(const ViewportArguments& arguments)
3436 {
3437     if (arguments == m_viewportArguments)
3438         return;
3439
3440     // If the caller is trying to reset to default arguments, use the user supplied ones instead.
3441     static const ViewportArguments defaultViewportArguments;
3442     if (arguments == defaultViewportArguments) {
3443         m_viewportArguments = m_userViewportArguments;
3444         m_forceRespectViewportArguments = m_userViewportArguments != defaultViewportArguments;
3445     } else
3446         m_viewportArguments = arguments;
3447
3448     // 0 width or height in viewport arguments makes no sense, and results in a very large initial scale.
3449     // In real world, a 0 width or height is usually caused by a syntax error in "content" field of viewport
3450     // meta tag, for example, using semicolon instead of comma as separator ("width=device-width; initial-scale=1.0").
3451     // We don't have a plan to tolerate the semicolon separator, but we can avoid applying 0 width/height.
3452     // I default it to ValueDeviceWidth rather than ValueAuto because in more cases the web site wants "device-width"
3453     // when they specify the viewport width.
3454     if (!m_viewportArguments.width)
3455         m_viewportArguments.width = ViewportArguments::ValueDeviceWidth;
3456     if (!m_viewportArguments.height)
3457         m_viewportArguments.height = ViewportArguments::ValueDeviceHeight;
3458
3459     Platform::IntSize virtualViewport = recomputeVirtualViewportFromViewportArguments();
3460     m_webPage->setVirtualViewportSize(virtualViewport);
3461
3462     // Reset m_userPerformedManualZoom and enable m_shouldZoomToInitialScaleAfterLoadFinished so that we can relayout
3463     // the page and zoom it to fit the screen when we dynamically change the meta viewport after the load is finished.
3464     bool isLoadFinished = loadState() == Finished;
3465     if (isLoadFinished) {
3466         m_userPerformedManualZoom = false;
3467         setShouldZoomToInitialScaleAfterLoadFinished(true);
3468     }
3469     if (loadState() == Committed || isLoadFinished)
3470         zoomToInitialScaleOnLoad();
3471 }
3472
3473 void WebPagePrivate::suspendBackingStore()
3474 {
3475 #if USE(ACCELERATED_COMPOSITING)
3476     if (m_backingStore->d->isOpenGLCompositing()) {
3477         // A visible web page's backing store can be suspended when another web
3478         // page is taking over the backing store.
3479         if (m_visible)
3480             setCompositorDrawsRootLayer(true);
3481
3482         return;
3483     }
3484 #endif
3485 }
3486
3487 void WebPagePrivate::resumeBackingStore()
3488 {
3489     ASSERT(m_webPage->isVisible());
3490
3491     if (!m_backingStore->d->isActive() || shouldResetTilesWhenShown()) {
3492         BackingStorePrivate::setCurrentBackingStoreOwner(m_webPage);
3493
3494         // If we're OpenGL compositing, switching to accel comp drawing of the root layer
3495         // is a good substitute for backingstore blitting.
3496         if (m_backingStore->d->isOpenGLCompositing())
3497             setCompositorDrawsRootLayer(!m_backingStore->d->isActive());
3498
3499         m_backingStore->d->orientationChanged(); // Updates tile geometry and creates visible tile buffer.
3500         m_backingStore->d->resetTiles();
3501         m_backingStore->d->updateTiles(false /* updateVisible */, false /* immediate */);