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