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