925206cf455e0543fb7eb7d7d8626e9030efc84c
[WebKit-https.git] / Source / WebKit2 / UIProcess / WebPageProxy.cpp
1 /*
2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2012 Intel Corporation. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "WebPageProxy.h"
29
30 #include "AuthenticationChallengeProxy.h"
31 #include "AuthenticationDecisionListener.h"
32 #include "DataReference.h"
33 #include "DownloadProxy.h"
34 #include "DrawingAreaProxy.h"
35 #include "DrawingAreaProxyMessages.h"
36 #include "EventDispatcherMessages.h"
37 #include "FindIndicator.h"
38 #include "ImmutableArray.h"
39 #include "Logging.h"
40 #include "NativeWebKeyboardEvent.h"
41 #include "NativeWebMouseEvent.h"
42 #include "NativeWebWheelEvent.h"
43 #include "NotificationPermissionRequest.h"
44 #include "NotificationPermissionRequestManager.h"
45 #include "PageClient.h"
46 #include "PluginInformation.h"
47 #include "PrintInfo.h"
48 #include "SessionState.h"
49 #include "TextChecker.h"
50 #include "TextCheckerState.h"
51 #include "WKContextPrivate.h"
52 #include "WebBackForwardList.h"
53 #include "WebBackForwardListItem.h"
54 #include "WebCertificateInfo.h"
55 #include "WebColorPickerResultListenerProxy.h"
56 #include "WebContext.h"
57 #include "WebContextMenuProxy.h"
58 #include "WebContextUserMessageCoders.h"
59 #include "WebCoreArgumentCoders.h"
60 #include "WebData.h"
61 #include "WebEditCommandProxy.h"
62 #include "WebEvent.h"
63 #include "WebFormSubmissionListenerProxy.h"
64 #include "WebFramePolicyListenerProxy.h"
65 #include "WebFullScreenManagerProxy.h"
66 #include "WebFullScreenManagerProxyMessages.h"
67 #include "WebInspectorProxy.h"
68 #include "WebInspectorProxyMessages.h"
69 #include "WebNotificationManagerProxy.h"
70 #include "WebOpenPanelResultListenerProxy.h"
71 #include "WebPageCreationParameters.h"
72 #include "WebPageGroup.h"
73 #include "WebPageGroupData.h"
74 #include "WebPageMessages.h"
75 #include "WebPageProxyMessages.h"
76 #include "WebPopupItem.h"
77 #include "WebPopupMenuProxy.h"
78 #include "WebPreferences.h"
79 #include "WebProcessMessages.h"
80 #include "WebProcessProxy.h"
81 #include "WebProtectionSpace.h"
82 #include "WebSecurityOrigin.h"
83 #include "WebURLRequest.h"
84 #include <WebCore/DragController.h>
85 #include <WebCore/DragData.h>
86 #include <WebCore/DragSession.h>
87 #include <WebCore/FloatRect.h>
88 #include <WebCore/FocusDirection.h>
89 #include <WebCore/MIMETypeRegistry.h>
90 #include <WebCore/RenderEmbeddedObject.h>
91 #include <WebCore/TextCheckerClient.h>
92 #include <WebCore/WindowFeatures.h>
93 #include <stdio.h>
94
95 #if USE(COORDINATED_GRAPHICS)
96 #include "CoordinatedLayerTreeHostProxyMessages.h"
97 #endif
98
99 #if PLATFORM(QT)
100 #include "ArgumentCodersQt.h"
101 #endif
102
103 #if PLATFORM(GTK)
104 #include "ArgumentCodersGtk.h"
105 #endif
106
107 #if USE(SOUP)
108 #include "WebSoupRequestManagerProxy.h"
109 #endif
110
111 #if ENABLE(VIBRATION)
112 #include "WebVibrationProxy.h"
113 #endif
114
115 #ifndef NDEBUG
116 #include <wtf/RefCountedLeakCounter.h>
117 #endif
118
119 // This controls what strategy we use for mouse wheel coalescing.
120 #define MERGE_WHEEL_EVENTS 1
121
122 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, m_process->connection())
123 #define MESSAGE_CHECK_URL(url) MESSAGE_CHECK_BASE(m_process->checkURLReceivedFromWebProcess(url), m_process->connection())
124
125 using namespace WebCore;
126
127 // Represents the number of wheel events we can hold in the queue before we start pushing them preemptively.
128 static const unsigned wheelEventQueueSizeThreshold = 10;
129
130 namespace WebKit {
131
132 WKPageDebugPaintFlags WebPageProxy::s_debugPaintFlags = 0;
133
134 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageProxyCounter, ("WebPageProxy"));
135
136 class ExceededDatabaseQuotaRecords {
137     WTF_MAKE_NONCOPYABLE(ExceededDatabaseQuotaRecords); WTF_MAKE_FAST_ALLOCATED;
138 public:
139     struct Record {
140         uint64_t frameID;
141         String originIdentifier;
142         String databaseName;
143         String displayName;
144         uint64_t currentQuota;
145         uint64_t currentOriginUsage;
146         uint64_t currentDatabaseUsage;
147         uint64_t expectedUsage;
148         RefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply;
149     };
150
151     static ExceededDatabaseQuotaRecords& shared();
152
153     PassOwnPtr<Record> createRecord(uint64_t frameID, String originIdentifier,
154         String databaseName, String displayName, uint64_t currentQuota,
155         uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, 
156         PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply>);
157
158     void add(PassOwnPtr<Record>);
159     bool areBeingProcessed() const { return m_currentRecord; }
160     Record* next();
161
162 private:
163     ExceededDatabaseQuotaRecords() { }
164     ~ExceededDatabaseQuotaRecords() { }
165
166     Deque<OwnPtr<Record>> m_records;
167     OwnPtr<Record> m_currentRecord;
168 };
169
170 ExceededDatabaseQuotaRecords& ExceededDatabaseQuotaRecords::shared()
171 {
172     DEFINE_STATIC_LOCAL(ExceededDatabaseQuotaRecords, records, ());
173     return records;
174 }
175
176 PassOwnPtr<ExceededDatabaseQuotaRecords::Record> ExceededDatabaseQuotaRecords::createRecord(
177     uint64_t frameID, String originIdentifier, String databaseName, String displayName,
178     uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage,
179     uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply)
180 {
181     OwnPtr<Record> record = adoptPtr(new Record);
182     record->frameID = frameID;
183     record->originIdentifier = originIdentifier;
184     record->databaseName = databaseName;
185     record->displayName = displayName;
186     record->currentQuota = currentQuota;
187     record->currentOriginUsage = currentOriginUsage;
188     record->currentDatabaseUsage = currentDatabaseUsage;
189     record->expectedUsage = expectedUsage;
190     record->reply = reply;
191     return record.release();
192 }
193
194 void ExceededDatabaseQuotaRecords::add(PassOwnPtr<ExceededDatabaseQuotaRecords::Record> record)
195 {
196     m_records.append(record);
197 }
198
199 ExceededDatabaseQuotaRecords::Record* ExceededDatabaseQuotaRecords::next()
200 {
201     m_currentRecord.clear();
202     if (!m_records.isEmpty())
203         m_currentRecord = m_records.takeFirst();
204     return m_currentRecord.get();
205 }
206
207 #if !LOG_DISABLED
208 static const char* webKeyboardEventTypeString(WebEvent::Type type)
209 {
210     switch (type) {
211     case WebEvent::KeyDown:
212         return "KeyDown";
213     
214     case WebEvent::KeyUp:
215         return "KeyUp";
216     
217     case WebEvent::RawKeyDown:
218         return "RawKeyDown";
219     
220     case WebEvent::Char:
221         return "Char";
222     
223     default:
224         ASSERT_NOT_REACHED();
225         return "<unknown>";
226     }
227 }
228 #endif // !LOG_DISABLED
229
230 PassRefPtr<WebPageProxy> WebPageProxy::create(PageClient* pageClient, PassRefPtr<WebProcessProxy> process, WebPageGroup* pageGroup, uint64_t pageID)
231 {
232     return adoptRef(new WebPageProxy(pageClient, process, pageGroup, pageID));
233 }
234
235 WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> process, WebPageGroup* pageGroup, uint64_t pageID)
236     : m_pageClient(pageClient)
237     , m_process(process)
238     , m_pageGroup(pageGroup)
239     , m_mainFrame(0)
240     , m_userAgent(standardUserAgent())
241     , m_geolocationPermissionRequestManager(this)
242     , m_notificationPermissionRequestManager(this)
243     , m_estimatedProgress(0)
244     , m_isInWindow(m_pageClient->isViewInWindow())
245     , m_isVisible(m_pageClient->isViewVisible())
246     , m_backForwardList(WebBackForwardList::create(this))
247     , m_loadStateAtProcessExit(WebFrameProxy::LoadStateFinished)
248     , m_textZoomFactor(1)
249     , m_pageZoomFactor(1)
250     , m_pageScaleFactor(1)
251     , m_intrinsicDeviceScaleFactor(1)
252     , m_customDeviceScaleFactor(0)
253 #if HAVE(LAYER_HOSTING_IN_WINDOW_SERVER)
254     , m_layerHostingMode(LayerHostingModeInWindowServer)
255 #else
256     , m_layerHostingMode(LayerHostingModeDefault)
257 #endif
258     , m_drawsBackground(true)
259     , m_drawsTransparentBackground(false)
260     , m_areMemoryCacheClientCallsEnabled(true)
261     , m_useFixedLayout(false)
262     , m_suppressScrollbarAnimations(false)
263     , m_paginationMode(Pagination::Unpaginated)
264     , m_paginationBehavesLikeColumns(false)
265     , m_pageLength(0)
266     , m_gapBetweenPages(0)
267     , m_isValid(true)
268     , m_isClosed(false)
269     , m_canRunModal(false)
270     , m_isInPrintingMode(false)
271     , m_isPerformingDOMPrintOperation(false)
272     , m_inDecidePolicyForResponseSync(false)
273     , m_decidePolicyForResponseRequest(0)
274     , m_syncMimeTypePolicyActionIsValid(false)
275     , m_syncMimeTypePolicyAction(PolicyUse)
276     , m_syncMimeTypePolicyDownloadID(0)
277     , m_inDecidePolicyForNavigationAction(false)
278     , m_syncNavigationActionPolicyActionIsValid(false)
279     , m_syncNavigationActionPolicyAction(PolicyUse)
280     , m_syncNavigationActionPolicyDownloadID(0)
281     , m_processingMouseMoveEvent(false)
282 #if ENABLE(TOUCH_EVENTS)
283     , m_needTouchEvents(false)
284 #endif
285     , m_pageID(pageID)
286     , m_isPageSuspended(false)
287 #if PLATFORM(MAC)
288     , m_isSmartInsertDeleteEnabled(TextChecker::isSmartInsertDeleteEnabled())
289 #endif
290     , m_spellDocumentTag(0)
291     , m_hasSpellDocumentTag(false)
292     , m_pendingLearnOrIgnoreWordMessageCount(0)
293     , m_mainFrameHasCustomRepresentation(false)
294     , m_mainFrameHasHorizontalScrollbar(false)
295     , m_mainFrameHasVerticalScrollbar(false)
296     , m_canShortCircuitHorizontalWheelEvents(true)
297     , m_mainFrameIsPinnedToLeftSide(false)
298     , m_mainFrameIsPinnedToRightSide(false)
299     , m_mainFrameIsPinnedToTopSide(false)
300     , m_mainFrameIsPinnedToBottomSide(false)
301     , m_rubberBandsAtBottom(false)
302     , m_rubberBandsAtTop(false)
303     , m_mainFrameInViewSourceMode(false)
304     , m_overridePrivateBrowsingEnabled(false)
305     , m_pageCount(0)
306     , m_renderTreeSize(0)
307     , m_shouldSendEventsSynchronously(false)
308     , m_suppressVisibilityUpdates(false)
309     , m_minimumLayoutWidth(0)
310     , m_mediaVolume(1)
311     , m_mayStartMediaWhenInWindow(true)
312     , m_waitingForDidUpdateInWindowState(false)
313 #if PLATFORM(MAC)
314     , m_exposedRectChangedTimer(this, &WebPageProxy::exposedRectChangedTimerFired)
315 #endif
316 #if ENABLE(PAGE_VISIBILITY_API)
317     , m_visibilityState(PageVisibilityStateVisible)
318 #endif
319 {
320 #if ENABLE(PAGE_VISIBILITY_API)
321     if (!m_isVisible)
322         m_visibilityState = PageVisibilityStateHidden;
323 #endif
324 #ifndef NDEBUG
325     webPageProxyCounter.increment();
326 #endif
327
328     WebContext::statistics().wkPageCount++;
329
330     m_pageGroup->addPage(this);
331
332 #if ENABLE(INSPECTOR)
333     m_inspector = WebInspectorProxy::create(this);
334 #endif
335 #if ENABLE(FULLSCREEN_API)
336     m_fullScreenManager = WebFullScreenManagerProxy::create(this);
337 #endif
338 #if ENABLE(VIBRATION)
339     m_vibration = WebVibrationProxy::create(this);
340 #endif
341 #if ENABLE(THREADED_SCROLLING)
342     m_rubberBandsAtBottom = true;
343     m_rubberBandsAtTop = true;
344 #endif
345
346     m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, this);
347
348     // FIXME: If we ever expose the session storage size as a preference, we need to pass it here.
349     m_process->context()->storageManager().createSessionStorageNamespace(m_pageID, m_process->isValid() ? m_process->connection() : 0, std::numeric_limits<unsigned>::max());
350 }
351
352 WebPageProxy::~WebPageProxy()
353 {
354     if (!m_isClosed)
355         close();
356
357     WebContext::statistics().wkPageCount--;
358
359     if (m_hasSpellDocumentTag)
360         TextChecker::closeSpellDocumentWithTag(m_spellDocumentTag);
361
362     m_pageGroup->removePage(this);
363
364 #ifndef NDEBUG
365     webPageProxyCounter.decrement();
366 #endif
367 }
368
369 WebProcessProxy* WebPageProxy::process() const
370 {
371     return m_process.get();
372 }
373
374 PlatformProcessIdentifier WebPageProxy::processIdentifier() const
375 {
376     if (!m_process)
377         return 0;
378
379     return m_process->processIdentifier();
380 }
381
382 bool WebPageProxy::isValid()
383 {
384     // A page that has been explicitly closed is never valid.
385     if (m_isClosed)
386         return false;
387
388     return m_isValid;
389 }
390
391 PassRefPtr<ImmutableArray> WebPageProxy::relatedPages() const
392 {
393     // pages() returns a list of pages in WebProcess, so this page may or may not be among them - a client can use a reference to WebPageProxy after the page has closed.
394     Vector<WebPageProxy*> pages = m_process->pages();
395
396     Vector<RefPtr<APIObject>> result;
397     result.reserveCapacity(pages.size());
398     for (size_t i = 0; i < pages.size(); ++i) {
399         if (pages[i] != this)
400             result.append(pages[i]);
401     }
402
403     return ImmutableArray::adopt(result);
404 }
405
406 void WebPageProxy::initializeLoaderClient(const WKPageLoaderClient* loadClient)
407 {
408     m_loaderClient.initialize(loadClient);
409     
410     if (!loadClient)
411         return;
412
413     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
414     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
415     // for backwards compatibility.
416     WebCore::LayoutMilestones milestones = 0;
417     if (loadClient->didFirstLayoutForFrame)
418         milestones |= WebCore::DidFirstLayout;
419     if (loadClient->didFirstVisuallyNonEmptyLayoutForFrame)
420         milestones |= WebCore::DidFirstVisuallyNonEmptyLayout;
421     if (loadClient->didNewFirstVisuallyNonEmptyLayout)
422         milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold;
423
424     if (milestones)
425         m_process->send(Messages::WebPage::ListenForLayoutMilestones(milestones), m_pageID);
426
427     m_process->send(Messages::WebPage::SetWillGoToBackForwardItemCallbackEnabled(loadClient->version > 0), m_pageID);
428 }
429
430 void WebPageProxy::initializePolicyClient(const WKPagePolicyClient* policyClient)
431 {
432     m_policyClient.initialize(policyClient);
433 }
434
435 void WebPageProxy::initializeFormClient(const WKPageFormClient* formClient)
436 {
437     m_formClient.initialize(formClient);
438 }
439
440 void WebPageProxy::initializeUIClient(const WKPageUIClient* client)
441 {
442     if (!isValid())
443         return;
444
445     m_uiClient.initialize(client);
446
447     m_process->send(Messages::WebPage::SetCanRunBeforeUnloadConfirmPanel(m_uiClient.canRunBeforeUnloadConfirmPanel()), m_pageID);
448     setCanRunModal(m_uiClient.canRunModal());
449 }
450
451 void WebPageProxy::initializeFindClient(const WKPageFindClient* client)
452 {
453     m_findClient.initialize(client);
454 }
455
456 void WebPageProxy::initializeFindMatchesClient(const WKPageFindMatchesClient* client)
457 {
458     m_findMatchesClient.initialize(client);
459 }
460
461 #if ENABLE(CONTEXT_MENUS)
462 void WebPageProxy::initializeContextMenuClient(const WKPageContextMenuClient* client)
463 {
464     m_contextMenuClient.initialize(client);
465 }
466 #endif
467
468 void WebPageProxy::reattachToWebProcess()
469 {
470     ASSERT(!isValid());
471     ASSERT(m_process);
472     ASSERT(!m_process->isValid());
473     ASSERT(!m_process->isLaunching());
474
475     m_isValid = true;
476
477     if (m_process->context()->processModel() == ProcessModelSharedSecondaryProcess)
478         m_process = m_process->context()->ensureSharedWebProcess();
479     else
480         m_process = m_process->context()->createNewWebProcessRespectingProcessCountLimit();
481     m_process->addExistingWebPage(this, m_pageID);
482     m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, this);
483
484 #if ENABLE(INSPECTOR)
485     m_inspector = WebInspectorProxy::create(this);
486 #endif
487 #if ENABLE(FULLSCREEN_API)
488     m_fullScreenManager = WebFullScreenManagerProxy::create(this);
489 #endif
490
491     initializeWebPage();
492
493     m_pageClient->didRelaunchProcess();
494     m_drawingArea->waitForBackingStoreUpdateOnNextPaint();
495 }
496
497 void WebPageProxy::reattachToWebProcessWithItem(WebBackForwardListItem* item)
498 {
499     if (item && item != m_backForwardList->currentItem())
500         m_backForwardList->goToItem(item);
501     
502     reattachToWebProcess();
503
504     if (!item)
505         return;
506
507     m_process->send(Messages::WebPage::GoToBackForwardItem(item->itemID()), m_pageID);
508     m_process->responsivenessTimer()->start();
509 }
510
511 void WebPageProxy::initializeWebPage()
512 {
513     ASSERT(isValid());
514
515     BackForwardListItemVector items = m_backForwardList->entries();
516     for (size_t i = 0; i < items.size(); ++i)
517         m_process->registerNewWebBackForwardListItem(items[i].get());
518
519     m_drawingArea = m_pageClient->createDrawingAreaProxy();
520     ASSERT(m_drawingArea);
521
522 #if ENABLE(INSPECTOR_SERVER)
523     if (m_pageGroup->preferences()->developerExtrasEnabled())
524         inspector()->enableRemoteInspection();
525 #endif
526
527     m_process->send(Messages::WebProcess::CreateWebPage(m_pageID, creationParameters()), 0);
528
529 #if ENABLE(PAGE_VISIBILITY_API)
530     m_process->send(Messages::WebPage::SetVisibilityState(m_visibilityState, /* isInitialState */ true), m_pageID);
531 #elif ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
532     m_process->send(Messages::WebPage::SetVisibilityState(m_isVisible ? PageVisibilityStateVisible : PageVisibilityStateHidden, /* isInitialState */ true), m_pageID);
533 #endif
534
535 #if PLATFORM(MAC)
536     m_process->send(Messages::WebPage::SetSmartInsertDeleteEnabled(m_isSmartInsertDeleteEnabled), m_pageID);
537 #endif
538 }
539
540 void WebPageProxy::close()
541 {
542     if (!isValid())
543         return;
544
545     m_isClosed = true;
546
547     m_backForwardList->pageClosed();
548     m_pageClient->pageClosed();
549
550     m_process->disconnectFramesFromPage(this);
551     m_mainFrame = 0;
552
553 #if ENABLE(INSPECTOR)
554     if (m_inspector) {
555         m_inspector->invalidate();
556         m_inspector = 0;
557     }
558 #endif
559
560 #if ENABLE(FULLSCREEN_API)
561     if (m_fullScreenManager) {
562         m_fullScreenManager->invalidate();
563         m_fullScreenManager = 0;
564     }
565 #endif
566
567 #if ENABLE(VIBRATION)
568     m_vibration->invalidate();
569 #endif
570
571     if (m_openPanelResultListener) {
572         m_openPanelResultListener->invalidate();
573         m_openPanelResultListener = 0;
574     }
575
576 #if ENABLE(INPUT_TYPE_COLOR)
577     if (m_colorChooser) {
578         m_colorChooser->invalidate();
579         m_colorChooser = nullptr;
580     }
581
582     if (m_colorPickerResultListener) {
583         m_colorPickerResultListener->invalidate();
584         m_colorPickerResultListener = nullptr;
585     }
586 #endif
587
588 #if ENABLE(GEOLOCATION)
589     m_geolocationPermissionRequestManager.invalidateRequests();
590 #endif
591
592     m_notificationPermissionRequestManager.invalidateRequests();
593
594     m_toolTip = String();
595
596     m_mainFrameHasHorizontalScrollbar = false;
597     m_mainFrameHasVerticalScrollbar = false;
598
599     m_mainFrameIsPinnedToLeftSide = false;
600     m_mainFrameIsPinnedToRightSide = false;
601     m_mainFrameIsPinnedToTopSide = false;
602     m_mainFrameIsPinnedToBottomSide = false;
603
604     m_visibleScrollerThumbRect = IntRect();
605
606     invalidateCallbackMap(m_voidCallbacks);
607     invalidateCallbackMap(m_dataCallbacks);
608     invalidateCallbackMap(m_imageCallbacks);
609     invalidateCallbackMap(m_stringCallbacks);
610     m_loadDependentStringCallbackIDs.clear();
611     invalidateCallbackMap(m_scriptValueCallbacks);
612     invalidateCallbackMap(m_computedPagesCallbacks);
613 #if PLATFORM(GTK)
614     invalidateCallbackMap(m_printFinishedCallbacks);
615 #endif
616
617     Vector<WebEditCommandProxy*> editCommandVector;
618     copyToVector(m_editCommandSet, editCommandVector);
619     m_editCommandSet.clear();
620     for (size_t i = 0, size = editCommandVector.size(); i < size; ++i)
621         editCommandVector[i]->invalidate();
622
623     m_activePopupMenu = 0;
624
625     m_estimatedProgress = 0.0;
626     
627     m_loaderClient.initialize(0);
628     m_policyClient.initialize(0);
629     m_uiClient.initialize(0);
630 #if PLATFORM(EFL)
631     m_uiPopupMenuClient.initialize(0);
632 #endif
633
634     m_drawingArea = nullptr;
635
636 #if PLATFORM(MAC)
637     m_exposedRectChangedTimer.stop();
638 #endif
639
640     m_process->send(Messages::WebPage::Close(), m_pageID);
641     m_process->removeWebPage(m_pageID);
642     m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID);
643     m_process->context()->storageManager().destroySessionStorageNamespace(m_pageID);
644 }
645
646 bool WebPageProxy::tryClose()
647 {
648     if (!isValid())
649         return true;
650
651     m_process->send(Messages::WebPage::TryClose(), m_pageID);
652     m_process->responsivenessTimer()->start();
653     return false;
654 }
655
656 bool WebPageProxy::maybeInitializeSandboxExtensionHandle(const KURL& url, SandboxExtension::Handle& sandboxExtensionHandle)
657 {
658     if (!url.isLocalFile())
659         return false;
660
661 #if ENABLE(INSPECTOR)
662     // Don't give the inspector full access to the file system.
663     if (WebInspectorProxy::isInspectorPage(this))
664         return false;
665 #endif
666
667     SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle);
668     return true;
669 }
670
671 void WebPageProxy::loadURL(const String& url, APIObject* userData)
672 {
673     setPendingAPIRequestURL(url);
674
675     if (!isValid())
676         reattachToWebProcess();
677
678     SandboxExtension::Handle sandboxExtensionHandle;
679     bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), url), sandboxExtensionHandle);
680     if (createdExtension)
681         m_process->willAcquireUniversalFileReadSandboxExtension();
682     m_process->send(Messages::WebPage::LoadURL(url, sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID);
683     m_process->responsivenessTimer()->start();
684 }
685
686 void WebPageProxy::loadURLRequest(WebURLRequest* urlRequest, APIObject* userData)
687 {
688     setPendingAPIRequestURL(urlRequest->resourceRequest().url());
689
690     if (!isValid())
691         reattachToWebProcess();
692
693     SandboxExtension::Handle sandboxExtensionHandle;
694     bool createdExtension = maybeInitializeSandboxExtensionHandle(urlRequest->resourceRequest().url(), sandboxExtensionHandle);
695     if (createdExtension)
696         m_process->willAcquireUniversalFileReadSandboxExtension();
697     m_process->send(Messages::WebPage::LoadURLRequest(urlRequest->resourceRequest(), sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID);
698     m_process->responsivenessTimer()->start();
699 }
700
701 void WebPageProxy::loadFile(const String& fileURLString, const String& resourceDirectoryURLString, APIObject* userData)
702 {
703     if (!isValid())
704         reattachToWebProcess();
705
706     KURL fileURL = KURL(KURL(), fileURLString);
707     if (!fileURL.isLocalFile())
708         return;
709
710     KURL resourceDirectoryURL;
711     if (resourceDirectoryURLString.isNull())
712         resourceDirectoryURL = KURL(ParsedURLString, ASCIILiteral("file:///"));
713     else {
714         resourceDirectoryURL = KURL(KURL(), resourceDirectoryURLString);
715         if (!resourceDirectoryURL.isLocalFile())
716             return;
717     }
718
719     String resourceDirectoryPath = resourceDirectoryURL.fileSystemPath();
720
721     SandboxExtension::Handle sandboxExtensionHandle;
722     SandboxExtension::createHandle(resourceDirectoryPath, SandboxExtension::ReadOnly, sandboxExtensionHandle);
723     m_process->assumeReadAccessToBaseURL(resourceDirectoryURL);
724     m_process->send(Messages::WebPage::LoadURL(fileURL, sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID);
725     m_process->responsivenessTimer()->start();
726 }
727
728 void WebPageProxy::loadData(WebData* data, const String& MIMEType, const String& encoding, const String& baseURL, APIObject* userData)
729 {
730     if (!isValid())
731         reattachToWebProcess();
732
733     m_process->assumeReadAccessToBaseURL(baseURL);
734     m_process->send(Messages::WebPage::LoadData(data->dataReference(), MIMEType, encoding, baseURL, WebContextUserMessageEncoder(userData)), m_pageID);
735     m_process->responsivenessTimer()->start();
736 }
737
738 void WebPageProxy::loadHTMLString(const String& htmlString, const String& baseURL, APIObject* userData)
739 {
740     if (!isValid())
741         reattachToWebProcess();
742
743     m_process->assumeReadAccessToBaseURL(baseURL);
744     m_process->send(Messages::WebPage::LoadHTMLString(htmlString, baseURL, WebContextUserMessageEncoder(userData)), m_pageID);
745     m_process->responsivenessTimer()->start();
746 }
747
748 void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, APIObject* userData)
749 {
750     if (!isValid())
751         reattachToWebProcess();
752
753     if (m_mainFrame)
754         m_mainFrame->setUnreachableURL(unreachableURL);
755
756     m_process->assumeReadAccessToBaseURL(baseURL);
757     m_process->send(Messages::WebPage::LoadAlternateHTMLString(htmlString, baseURL, unreachableURL, WebContextUserMessageEncoder(userData)), m_pageID);
758     m_process->responsivenessTimer()->start();
759 }
760
761 void WebPageProxy::loadPlainTextString(const String& string, APIObject* userData)
762 {
763     if (!isValid())
764         reattachToWebProcess();
765
766     m_process->send(Messages::WebPage::LoadPlainTextString(string, WebContextUserMessageEncoder(userData)), m_pageID);
767     m_process->responsivenessTimer()->start();
768 }
769
770 void WebPageProxy::loadWebArchiveData(const WebData* webArchiveData, APIObject* userData)
771 {
772     if (!isValid())
773         reattachToWebProcess();
774
775     m_process->send(Messages::WebPage::LoadWebArchiveData(webArchiveData->dataReference(), WebContextUserMessageEncoder(userData)), m_pageID);
776     m_process->responsivenessTimer()->start();
777 }
778
779 void WebPageProxy::stopLoading()
780 {
781     if (!isValid())
782         return;
783
784     m_process->send(Messages::WebPage::StopLoading(), m_pageID);
785     m_process->responsivenessTimer()->start();
786 }
787
788 void WebPageProxy::reload(bool reloadFromOrigin)
789 {
790     SandboxExtension::Handle sandboxExtensionHandle;
791
792     if (m_backForwardList->currentItem()) {
793         String url = m_backForwardList->currentItem()->url();
794         setPendingAPIRequestURL(url);
795
796         // We may not have an extension yet if back/forward list was reinstated after a WebProcess crash or a browser relaunch
797         bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), url), sandboxExtensionHandle);
798         if (createdExtension)
799             m_process->willAcquireUniversalFileReadSandboxExtension();
800     }
801
802     if (!isValid()) {
803         reattachToWebProcessWithItem(m_backForwardList->currentItem());
804         return;
805     }
806
807     m_process->send(Messages::WebPage::Reload(reloadFromOrigin, sandboxExtensionHandle), m_pageID);
808     m_process->responsivenessTimer()->start();
809 }
810
811 void WebPageProxy::goForward()
812 {
813     if (isValid() && !canGoForward())
814         return;
815
816     WebBackForwardListItem* forwardItem = m_backForwardList->forwardItem();
817     if (!forwardItem)
818         return;
819
820     setPendingAPIRequestURL(forwardItem->url());
821
822     if (!isValid()) {
823         reattachToWebProcessWithItem(forwardItem);
824         return;
825     }
826
827     m_process->send(Messages::WebPage::GoForward(forwardItem->itemID()), m_pageID);
828     m_process->responsivenessTimer()->start();
829 }
830
831 bool WebPageProxy::canGoForward() const
832 {
833     return m_backForwardList->forwardItem();
834 }
835
836 void WebPageProxy::goBack()
837 {
838     if (isValid() && !canGoBack())
839         return;
840
841     WebBackForwardListItem* backItem = m_backForwardList->backItem();
842     if (!backItem)
843         return;
844
845     setPendingAPIRequestURL(backItem->url());
846
847     if (!isValid()) {
848         reattachToWebProcessWithItem(backItem);
849         return;
850     }
851
852     m_process->send(Messages::WebPage::GoBack(backItem->itemID()), m_pageID);
853     m_process->responsivenessTimer()->start();
854 }
855
856 bool WebPageProxy::canGoBack() const
857 {
858     return m_backForwardList->backItem();
859 }
860
861 void WebPageProxy::goToBackForwardItem(WebBackForwardListItem* item)
862 {
863     if (!isValid()) {
864         reattachToWebProcessWithItem(item);
865         return;
866     }
867     
868     setPendingAPIRequestURL(item->url());
869
870     m_process->send(Messages::WebPage::GoToBackForwardItem(item->itemID()), m_pageID);
871     m_process->responsivenessTimer()->start();
872 }
873
874 void WebPageProxy::tryRestoreScrollPosition()
875 {
876     if (!isValid())
877         return;
878
879     m_process->send(Messages::WebPage::TryRestoreScrollPosition(), m_pageID);
880 }
881
882 void WebPageProxy::didChangeBackForwardList(WebBackForwardListItem* added, Vector<RefPtr<APIObject>>* removed)
883 {
884     m_loaderClient.didChangeBackForwardList(this, added, removed);
885 }
886
887 void WebPageProxy::shouldGoToBackForwardListItem(uint64_t itemID, bool& shouldGoToBackForwardItem)
888 {
889     WebBackForwardListItem* item = m_process->webBackForwardItem(itemID);
890     shouldGoToBackForwardItem = item && m_loaderClient.shouldGoToBackForwardListItem(this, item);
891 }
892
893 void WebPageProxy::willGoToBackForwardListItem(uint64_t itemID, CoreIPC::MessageDecoder& decoder)
894 {
895     RefPtr<APIObject> userData;
896     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
897     if (!decoder.decode(messageDecoder))
898         return;
899
900     if (WebBackForwardListItem* item = m_process->webBackForwardItem(itemID))
901         m_loaderClient.willGoToBackForwardListItem(this, item, userData.get());
902 }
903
904 String WebPageProxy::activeURL() const
905 {
906     // If there is a currently pending url, it is the active URL,
907     // even when there's no main frame yet, as it might be the
908     // first API request.
909     if (!m_pendingAPIRequestURL.isNull())
910         return m_pendingAPIRequestURL;
911
912     if (!m_mainFrame)
913         return String();
914
915     if (!m_mainFrame->unreachableURL().isEmpty())
916         return m_mainFrame->unreachableURL();
917
918     switch (m_mainFrame->loadState()) {
919     case WebFrameProxy::LoadStateProvisional:
920         return m_mainFrame->provisionalURL();
921     case WebFrameProxy::LoadStateCommitted:
922     case WebFrameProxy::LoadStateFinished:
923         return m_mainFrame->url();
924     }
925
926     ASSERT_NOT_REACHED();
927     return String();
928 }
929
930 String WebPageProxy::provisionalURL() const
931 {
932     if (!m_mainFrame)
933         return String();
934     return m_mainFrame->provisionalURL();
935 }
936
937 String WebPageProxy::committedURL() const
938 {
939     if (!m_mainFrame)
940         return String();
941
942     return m_mainFrame->url();
943 }
944
945 bool WebPageProxy::canShowMIMEType(const String& mimeType) const
946 {
947     if (MIMETypeRegistry::canShowMIMEType(mimeType))
948         return true;
949
950 #if ENABLE(NETSCAPE_PLUGIN_API)
951     String newMimeType = mimeType;
952     PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL());
953     if (!plugin.path.isNull() && m_pageGroup->preferences()->pluginsEnabled())
954         return true;
955 #endif // ENABLE(NETSCAPE_PLUGIN_API)
956
957 #if PLATFORM(MAC)
958     // On Mac, we can show PDFs.
959     if (MIMETypeRegistry::isPDFOrPostScriptMIMEType(mimeType) && !WebContext::omitPDFSupport())
960         return true;
961 #endif // PLATFORM(MAC)
962
963     return false;
964 }
965
966 void WebPageProxy::setDrawsBackground(bool drawsBackground)
967 {
968     if (m_drawsBackground == drawsBackground)
969         return;
970
971     m_drawsBackground = drawsBackground;
972
973     if (isValid())
974         m_process->send(Messages::WebPage::SetDrawsBackground(drawsBackground), m_pageID);
975 }
976
977 void WebPageProxy::setDrawsTransparentBackground(bool drawsTransparentBackground)
978 {
979     if (m_drawsTransparentBackground == drawsTransparentBackground)
980         return;
981
982     m_drawsTransparentBackground = drawsTransparentBackground;
983
984     if (isValid())
985         m_process->send(Messages::WebPage::SetDrawsTransparentBackground(drawsTransparentBackground), m_pageID);
986 }
987
988 void WebPageProxy::setUnderlayColor(const Color& color)
989 {
990     if (m_underlayColor == color)
991         return;
992
993     m_underlayColor = color;
994
995     if (isValid())
996         m_process->send(Messages::WebPage::SetUnderlayColor(color), m_pageID);
997 }
998
999 void WebPageProxy::viewWillStartLiveResize()
1000 {
1001     if (!isValid())
1002         return;
1003     m_process->send(Messages::WebPage::ViewWillStartLiveResize(), m_pageID);
1004 }
1005
1006 void WebPageProxy::viewWillEndLiveResize()
1007 {
1008     if (!isValid())
1009         return;
1010     m_process->send(Messages::WebPage::ViewWillEndLiveResize(), m_pageID);
1011 }
1012
1013 void WebPageProxy::setViewNeedsDisplay(const IntRect& rect)
1014 {
1015     m_pageClient->setViewNeedsDisplay(rect);
1016 }
1017
1018 void WebPageProxy::displayView()
1019 {
1020     m_pageClient->displayView();
1021 }
1022
1023 bool WebPageProxy::canScrollView()
1024 {
1025     return m_pageClient->canScrollView();
1026 }
1027
1028 void WebPageProxy::scrollView(const IntRect& scrollRect, const IntSize& scrollOffset)
1029 {
1030     m_pageClient->scrollView(scrollRect, scrollOffset);
1031 }
1032
1033 void WebPageProxy::viewStateDidChange(ViewStateFlags flags)
1034 {
1035     if (!isValid())
1036         return;
1037
1038     if (flags & ViewIsFocused)
1039         m_process->send(Messages::WebPage::SetFocused(m_pageClient->isViewFocused()), m_pageID);
1040
1041     if (flags & ViewWindowIsActive)
1042         m_process->send(Messages::WebPage::SetActive(m_pageClient->isViewWindowActive()), m_pageID);
1043
1044     if (flags & ViewIsVisible) {
1045         bool isVisible = m_pageClient->isViewVisible();
1046         if (isVisible != m_isVisible) {
1047             m_isVisible = isVisible;
1048             m_process->pageVisibilityChanged(this);
1049             m_drawingArea->visibilityDidChange();
1050
1051             if (!m_isVisible) {
1052                 // If we've started the responsiveness timer as part of telling the web process to update the backing store
1053                 // state, it might not send back a reply (since it won't paint anything if the web page is hidden) so we
1054                 // stop the unresponsiveness timer here.
1055                 m_process->responsivenessTimer()->stop();
1056             }
1057
1058 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING) && !ENABLE(PAGE_VISIBILITY_API)
1059             PageVisibilityState visibilityState = m_isVisible ? PageVisibilityStateVisible : PageVisibilityStateHidden;
1060             m_process->send(Messages::WebPage::SetVisibilityState(visibilityState, false), m_pageID);
1061 #endif
1062         }
1063     }
1064
1065     if (flags & ViewIsInWindow) {
1066         bool isInWindow = m_pageClient->isViewInWindow();
1067         if (m_isInWindow != isInWindow) {
1068             m_isInWindow = isInWindow;
1069             m_process->send(Messages::WebPage::SetIsInWindow(isInWindow), m_pageID);
1070         }
1071
1072         if (isInWindow) {
1073             LayerHostingMode layerHostingMode = m_pageClient->viewLayerHostingMode();
1074             if (m_layerHostingMode != layerHostingMode) {
1075                 m_layerHostingMode = layerHostingMode;
1076                 m_drawingArea->layerHostingModeDidChange();
1077             }
1078         }
1079     }
1080
1081 #if ENABLE(PAGE_VISIBILITY_API)
1082     PageVisibilityState visibilityState = PageVisibilityStateHidden;
1083
1084     if (m_isVisible)
1085         visibilityState = PageVisibilityStateVisible;
1086
1087     if (visibilityState != m_visibilityState) {
1088         m_visibilityState = visibilityState;
1089         m_process->send(Messages::WebPage::SetVisibilityState(visibilityState, false), m_pageID);
1090     }
1091 #endif
1092
1093     updateBackingStoreDiscardableState();
1094 }
1095
1096 void WebPageProxy::waitForDidUpdateInWindowState()
1097 {
1098     // If we have previously timed out with no response from the WebProcess, don't block the UIProcess again until it starts responding.
1099     if (m_waitingForDidUpdateInWindowState)
1100         return;
1101
1102     m_waitingForDidUpdateInWindowState = true;
1103
1104     if (!m_process->isLaunching()) {
1105         const double inWindowStateUpdateTimeout = 0.25;
1106         m_process->connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidUpdateInWindowState>(m_pageID, inWindowStateUpdateTimeout);
1107     }
1108 }
1109
1110 IntSize WebPageProxy::viewSize() const
1111 {
1112     return m_pageClient->viewSize();
1113 }
1114
1115 void WebPageProxy::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& keyboardEvent)
1116 {
1117     if (!isValid())
1118         return;
1119     m_process->send(Messages::WebPage::SetInitialFocus(forward, isKeyboardEventValid, keyboardEvent), m_pageID);
1120 }
1121
1122 void WebPageProxy::setWindowResizerSize(const IntSize& windowResizerSize)
1123 {
1124     if (!isValid())
1125         return;
1126     m_process->send(Messages::WebPage::SetWindowResizerSize(windowResizerSize), m_pageID);
1127 }
1128     
1129 void WebPageProxy::clearSelection()
1130 {
1131     if (!isValid())
1132         return;
1133     m_process->send(Messages::WebPage::ClearSelection(), m_pageID);
1134 }
1135
1136 void WebPageProxy::validateCommand(const String& commandName, PassRefPtr<ValidateCommandCallback> callback)
1137 {
1138     if (!isValid()) {
1139         callback->invalidate();
1140         return;
1141     }
1142
1143     uint64_t callbackID = callback->callbackID();
1144     m_validateCommandCallbacks.set(callbackID, callback.get());
1145     m_process->send(Messages::WebPage::ValidateCommand(commandName, callbackID), m_pageID);
1146 }
1147
1148 void WebPageProxy::setMaintainsInactiveSelection(bool newValue)
1149 {
1150     m_maintainsInactiveSelection = newValue;
1151 }
1152     
1153 void WebPageProxy::executeEditCommand(const String& commandName)
1154 {
1155     if (!isValid())
1156         return;
1157
1158     DEFINE_STATIC_LOCAL(String, ignoreSpellingCommandName, (ASCIILiteral("ignoreSpelling")));
1159     if (commandName == ignoreSpellingCommandName)
1160         ++m_pendingLearnOrIgnoreWordMessageCount;
1161
1162     m_process->send(Messages::WebPage::ExecuteEditCommand(commandName), m_pageID);
1163 }
1164     
1165 #if USE(TILED_BACKING_STORE)
1166 void WebPageProxy::commitPageTransitionViewport()
1167 {
1168     if (!isValid())
1169         return;
1170
1171     process()->send(Messages::WebPage::CommitPageTransitionViewport(), m_pageID);
1172 }
1173 #endif
1174
1175 #if ENABLE(DRAG_SUPPORT)
1176 void WebPageProxy::dragEntered(DragData* dragData, const String& dragStorageName)
1177 {
1178     SandboxExtension::Handle sandboxExtensionHandle;
1179     SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray;
1180     performDragControllerAction(DragControllerActionEntered, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray);
1181 }
1182
1183 void WebPageProxy::dragUpdated(DragData* dragData, const String& dragStorageName)
1184 {
1185     SandboxExtension::Handle sandboxExtensionHandle;
1186     SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray;
1187     performDragControllerAction(DragControllerActionUpdated, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray);
1188 }
1189
1190 void WebPageProxy::dragExited(DragData* dragData, const String& dragStorageName)
1191 {
1192     SandboxExtension::Handle sandboxExtensionHandle;
1193     SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray;
1194     performDragControllerAction(DragControllerActionExited, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray);
1195 }
1196
1197 void WebPageProxy::performDrag(DragData* dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload)
1198 {
1199     performDragControllerAction(DragControllerActionPerformDrag, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionsForUpload);
1200 }
1201
1202 void WebPageProxy::performDragControllerAction(DragControllerAction action, DragData* dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload)
1203 {
1204     if (!isValid())
1205         return;
1206 #if PLATFORM(QT) || PLATFORM(GTK)
1207     m_process->send(Messages::WebPage::PerformDragControllerAction(action, *dragData), m_pageID);
1208 #else
1209     m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData->clientPosition(), dragData->globalPosition(), dragData->draggingSourceOperationMask(), dragStorageName, dragData->flags(), sandboxExtensionHandle, sandboxExtensionsForUpload), m_pageID);
1210 #endif
1211 }
1212
1213 void WebPageProxy::didPerformDragControllerAction(WebCore::DragSession dragSession)
1214 {
1215     m_currentDragSession = dragSession;
1216 }
1217
1218 #if PLATFORM(QT) || PLATFORM(GTK)
1219 void WebPageProxy::startDrag(const DragData& dragData, const ShareableBitmap::Handle& dragImageHandle)
1220 {
1221     RefPtr<ShareableBitmap> dragImage = 0;
1222     if (!dragImageHandle.isNull()) {
1223         dragImage = ShareableBitmap::create(dragImageHandle);
1224         if (!dragImage)
1225             return;
1226     }
1227
1228     m_pageClient->startDrag(dragData, dragImage.release());
1229 }
1230 #endif
1231
1232 void WebPageProxy::dragEnded(const IntPoint& clientPosition, const IntPoint& globalPosition, uint64_t operation)
1233 {
1234     if (!isValid())
1235         return;
1236     m_process->send(Messages::WebPage::DragEnded(clientPosition, globalPosition, operation), m_pageID);
1237 }
1238 #endif // ENABLE(DRAG_SUPPORT)
1239
1240 void WebPageProxy::handleMouseEvent(const NativeWebMouseEvent& event)
1241 {
1242     if (!isValid())
1243         return;
1244
1245     // NOTE: This does not start the responsiveness timer because mouse move should not indicate interaction.
1246     if (event.type() != WebEvent::MouseMove)
1247         m_process->responsivenessTimer()->start();
1248     else {
1249         if (m_processingMouseMoveEvent) {
1250             m_nextMouseMoveEvent = adoptPtr(new NativeWebMouseEvent(event));
1251             return;
1252         }
1253
1254         m_processingMouseMoveEvent = true;
1255     }
1256
1257     // <https://bugs.webkit.org/show_bug.cgi?id=57904> We need to keep track of the mouse down event in the case where we
1258     // display a popup menu for select elements. When the user changes the selected item,
1259     // we fake a mouse up event by using this stored down event. This event gets cleared
1260     // when the mouse up message is received from WebProcess.
1261     if (event.type() == WebEvent::MouseDown)
1262         m_currentlyProcessedMouseDownEvent = adoptPtr(new NativeWebMouseEvent(event));
1263
1264     if (m_shouldSendEventsSynchronously) {
1265         bool handled = false;
1266         m_process->sendSync(Messages::WebPage::MouseEventSyncForTesting(event), Messages::WebPage::MouseEventSyncForTesting::Reply(handled), m_pageID);
1267         didReceiveEvent(event.type(), handled);
1268     } else
1269         m_process->send(Messages::WebPage::MouseEvent(event), m_pageID);
1270 }
1271
1272 #if MERGE_WHEEL_EVENTS
1273 static bool canCoalesce(const WebWheelEvent& a, const WebWheelEvent& b)
1274 {
1275     if (a.position() != b.position())
1276         return false;
1277     if (a.globalPosition() != b.globalPosition())
1278         return false;
1279     if (a.modifiers() != b.modifiers())
1280         return false;
1281     if (a.granularity() != b.granularity())
1282         return false;
1283 #if PLATFORM(MAC)
1284     if (a.phase() != b.phase())
1285         return false;
1286     if (a.momentumPhase() != b.momentumPhase())
1287         return false;
1288     if (a.hasPreciseScrollingDeltas() != b.hasPreciseScrollingDeltas())
1289         return false;
1290 #endif
1291
1292     return true;
1293 }
1294
1295 static WebWheelEvent coalesce(const WebWheelEvent& a, const WebWheelEvent& b)
1296 {
1297     ASSERT(canCoalesce(a, b));
1298
1299     FloatSize mergedDelta = a.delta() + b.delta();
1300     FloatSize mergedWheelTicks = a.wheelTicks() + b.wheelTicks();
1301
1302 #if PLATFORM(MAC)
1303     FloatSize mergedUnacceleratedScrollingDelta = a.unacceleratedScrollingDelta() + b.unacceleratedScrollingDelta();
1304
1305     return WebWheelEvent(WebEvent::Wheel, b.position(), b.globalPosition(), mergedDelta, mergedWheelTicks, b.granularity(), b.directionInvertedFromDevice(), b.phase(), b.momentumPhase(), b.hasPreciseScrollingDeltas(), b.scrollCount(), mergedUnacceleratedScrollingDelta, b.modifiers(), b.timestamp());
1306 #else
1307     return WebWheelEvent(WebEvent::Wheel, b.position(), b.globalPosition(), mergedDelta, mergedWheelTicks, b.granularity(), b.modifiers(), b.timestamp());
1308 #endif
1309 }
1310 #endif // MERGE_WHEEL_EVENTS
1311
1312 static WebWheelEvent coalescedWheelEvent(Deque<NativeWebWheelEvent>& queue, Vector<NativeWebWheelEvent>& coalescedEvents)
1313 {
1314     ASSERT(!queue.isEmpty());
1315     ASSERT(coalescedEvents.isEmpty());
1316
1317 #if MERGE_WHEEL_EVENTS
1318     NativeWebWheelEvent firstEvent = queue.takeFirst();
1319     coalescedEvents.append(firstEvent);
1320
1321     WebWheelEvent event = firstEvent;
1322     while (!queue.isEmpty() && canCoalesce(event, queue.first())) {
1323         NativeWebWheelEvent firstEvent = queue.takeFirst();
1324         coalescedEvents.append(firstEvent);
1325         event = coalesce(event, firstEvent);
1326     }
1327
1328     return event;
1329 #else
1330     while (!queue.isEmpty())
1331         coalescedEvents.append(queue.takeFirst());
1332     return coalescedEvents.last();
1333 #endif
1334 }
1335
1336 void WebPageProxy::handleWheelEvent(const NativeWebWheelEvent& event)
1337 {
1338     if (!isValid())
1339         return;
1340
1341     if (!m_currentlyProcessedWheelEvents.isEmpty()) {
1342         m_wheelEventQueue.append(event);
1343         if (m_wheelEventQueue.size() < wheelEventQueueSizeThreshold)
1344             return;
1345         // The queue has too many wheel events, so push a new event.
1346     }
1347
1348     if (!m_wheelEventQueue.isEmpty()) {
1349         processNextQueuedWheelEvent();
1350         return;
1351     }
1352
1353     OwnPtr<Vector<NativeWebWheelEvent>> coalescedWheelEvent = adoptPtr(new Vector<NativeWebWheelEvent>);
1354     coalescedWheelEvent->append(event);
1355     m_currentlyProcessedWheelEvents.append(coalescedWheelEvent.release());
1356     sendWheelEvent(event);
1357 }
1358
1359 void WebPageProxy::processNextQueuedWheelEvent()
1360 {
1361     OwnPtr<Vector<NativeWebWheelEvent>> nextCoalescedEvent = adoptPtr(new Vector<NativeWebWheelEvent>);
1362     WebWheelEvent nextWheelEvent = coalescedWheelEvent(m_wheelEventQueue, *nextCoalescedEvent.get());
1363     m_currentlyProcessedWheelEvents.append(nextCoalescedEvent.release());
1364     sendWheelEvent(nextWheelEvent);
1365 }
1366
1367 void WebPageProxy::sendWheelEvent(const WebWheelEvent& event)
1368 {
1369     m_process->responsivenessTimer()->start();
1370
1371     if (m_shouldSendEventsSynchronously) {
1372         bool handled = false;
1373         m_process->sendSync(Messages::WebPage::WheelEventSyncForTesting(event), Messages::WebPage::WheelEventSyncForTesting::Reply(handled), m_pageID);
1374         didReceiveEvent(event.type(), handled);
1375         return;
1376     }
1377
1378     m_process->send(Messages::EventDispatcher::WheelEvent(m_pageID, event, canGoBack(), canGoForward()), 0);
1379 }
1380
1381 void WebPageProxy::handleKeyboardEvent(const NativeWebKeyboardEvent& event)
1382 {
1383     if (!isValid())
1384         return;
1385     
1386     LOG(KeyHandling, "WebPageProxy::handleKeyboardEvent: %s", webKeyboardEventTypeString(event.type()));
1387
1388     m_keyEventQueue.append(event);
1389
1390     m_process->responsivenessTimer()->start();
1391     if (m_shouldSendEventsSynchronously) {
1392         bool handled = false;
1393         m_process->sendSync(Messages::WebPage::KeyEventSyncForTesting(event), Messages::WebPage::KeyEventSyncForTesting::Reply(handled), m_pageID);
1394         didReceiveEvent(event.type(), handled);
1395     } else if (m_keyEventQueue.size() == 1) // Otherwise, sent from DidReceiveEvent message handler.
1396         m_process->send(Messages::WebPage::KeyEvent(event), m_pageID);
1397 }
1398
1399 #if ENABLE(NETSCAPE_PLUGIN_API)
1400 void WebPageProxy::findPlugin(const String& mimeType, const String& urlString, const String& frameURLString, const String& pageURLString, const bool allowOnlyApplicationPlugins, String& pluginPath, String& newMimeType, uint32_t& pluginLoadPolicy)
1401 {
1402     MESSAGE_CHECK_URL(urlString);
1403
1404     newMimeType = mimeType.lower();
1405     pluginLoadPolicy = PluginModuleLoadNormally;
1406
1407     PluginData::AllowedPluginTypes allowedPluginTypes = allowOnlyApplicationPlugins ? PluginData::OnlyApplicationPlugins : PluginData::AllPlugins;
1408     PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString), allowedPluginTypes);
1409     if (!plugin.path)
1410         return;
1411
1412     pluginLoadPolicy = PluginInfoStore::policyForPlugin(plugin);
1413
1414 #if PLATFORM(MAC)
1415     RefPtr<ImmutableDictionary> pluginInformation = createPluginInformationDictionary(plugin, frameURLString, String(), pageURLString, String(), String());
1416     pluginLoadPolicy = m_loaderClient.pluginLoadPolicy(this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get());
1417 #else
1418     UNUSED_PARAM(frameURLString);
1419     UNUSED_PARAM(pageURLString);
1420 #endif
1421
1422     if (pluginLoadPolicy != PluginModuleLoadNormally)
1423         return;
1424
1425     pluginPath = plugin.path;
1426 }
1427 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1428
1429 #if ENABLE(GESTURE_EVENTS)
1430 void WebPageProxy::handleGestureEvent(const WebGestureEvent& event)
1431 {
1432     if (!isValid())
1433         return;
1434
1435     m_gestureEventQueue.append(event);
1436
1437     m_process->responsivenessTimer()->start();
1438     m_process->send(Messages::EventDispatcher::GestureEvent(m_pageID, event), 0);
1439 }
1440 #endif
1441
1442 #if ENABLE(TOUCH_EVENTS)
1443 #if PLATFORM(QT)
1444 void WebPageProxy::handlePotentialActivation(const IntPoint& touchPoint, const IntSize& touchArea)
1445 {
1446     m_process->send(Messages::WebPage::HighlightPotentialActivation(touchPoint, touchArea), m_pageID);
1447 }
1448 #endif
1449
1450 void WebPageProxy::handleTouchEvent(const NativeWebTouchEvent& event)
1451 {
1452     if (!isValid())
1453         return;
1454
1455     // If the page is suspended, which should be the case during panning, pinching
1456     // and animation on the page itself (kinetic scrolling, tap to zoom) etc, then
1457     // we do not send any of the events to the page even if is has listeners.
1458     if (m_needTouchEvents && !m_isPageSuspended) {
1459         m_touchEventQueue.append(event);
1460         m_process->responsivenessTimer()->start();
1461         if (m_shouldSendEventsSynchronously) {
1462             bool handled = false;
1463             m_process->sendSync(Messages::WebPage::TouchEventSyncForTesting(event), Messages::WebPage::TouchEventSyncForTesting::Reply(handled), m_pageID);
1464             didReceiveEvent(event.type(), handled);
1465         } else
1466             m_process->send(Messages::WebPage::TouchEvent(event), m_pageID);
1467     } else {
1468         if (m_touchEventQueue.isEmpty()) {
1469             bool isEventHandled = false;
1470             m_pageClient->doneWithTouchEvent(event, isEventHandled);
1471         } else {
1472             // We attach the incoming events to the newest queued event so that all
1473             // the events are delivered in the correct order when the event is dequed.
1474             QueuedTouchEvents& lastEvent = m_touchEventQueue.last();
1475             lastEvent.deferredTouchEvents.append(event);
1476         }
1477     }
1478 }
1479 #endif
1480
1481 void WebPageProxy::scrollBy(ScrollDirection direction, ScrollGranularity granularity)
1482 {
1483     if (!isValid())
1484         return;
1485
1486     m_process->send(Messages::WebPage::ScrollBy(direction, granularity), m_pageID);
1487 }
1488
1489 void WebPageProxy::centerSelectionInVisibleArea()
1490 {
1491     if (!isValid())
1492         return;
1493
1494     m_process->send(Messages::WebPage::CenterSelectionInVisibleArea(), m_pageID);
1495 }
1496
1497 void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy* frame, uint64_t listenerID)
1498 {
1499     if (!isValid())
1500         return;
1501
1502     if (action == PolicyIgnore)
1503         clearPendingAPIRequestURL();
1504
1505     uint64_t downloadID = 0;
1506     if (action == PolicyDownload) {
1507         // Create a download proxy.
1508         DownloadProxy* download = m_process->context()->createDownloadProxy();
1509         downloadID = download->downloadID();
1510 #if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK)
1511         // Our design does not suppport downloads without a WebPage.
1512         handleDownloadRequest(download);
1513 #endif
1514     }
1515
1516     // If we received a policy decision while in decidePolicyForResponse the decision will
1517     // be sent back to the web process by decidePolicyForResponse.
1518     if (m_inDecidePolicyForResponseSync) {
1519         m_syncMimeTypePolicyActionIsValid = true;
1520         m_syncMimeTypePolicyAction = action;
1521         m_syncMimeTypePolicyDownloadID = downloadID;
1522         return;
1523     }
1524
1525     // If we received a policy decision while in decidePolicyForNavigationAction the decision will 
1526     // be sent back to the web process by decidePolicyForNavigationAction. 
1527     if (m_inDecidePolicyForNavigationAction) {
1528         m_syncNavigationActionPolicyActionIsValid = true;
1529         m_syncNavigationActionPolicyAction = action;
1530         m_syncNavigationActionPolicyDownloadID = downloadID;
1531         return;
1532     }
1533     
1534     m_process->send(Messages::WebPage::DidReceivePolicyDecision(frame->frameID(), listenerID, action, downloadID), m_pageID);
1535 }
1536
1537 String WebPageProxy::pageTitle() const
1538 {
1539     // Return the null string if there is no main frame (e.g. nothing has been loaded in the page yet, WebProcess has
1540     // crashed, page has been closed).
1541     if (!m_mainFrame)
1542         return String();
1543
1544     return m_mainFrame->title();
1545 }
1546
1547 void WebPageProxy::setUserAgent(const String& userAgent)
1548 {
1549     if (m_userAgent == userAgent)
1550         return;
1551     m_userAgent = userAgent;
1552
1553     if (!isValid())
1554         return;
1555     m_process->send(Messages::WebPage::SetUserAgent(m_userAgent), m_pageID);
1556 }
1557
1558 void WebPageProxy::setApplicationNameForUserAgent(const String& applicationName)
1559 {
1560     if (m_applicationNameForUserAgent == applicationName)
1561         return;
1562
1563     m_applicationNameForUserAgent = applicationName;
1564     if (!m_customUserAgent.isEmpty())
1565         return;
1566
1567     setUserAgent(standardUserAgent(m_applicationNameForUserAgent));
1568 }
1569
1570 void WebPageProxy::setCustomUserAgent(const String& customUserAgent)
1571 {
1572     if (m_customUserAgent == customUserAgent)
1573         return;
1574
1575     m_customUserAgent = customUserAgent;
1576
1577     if (m_customUserAgent.isEmpty()) {
1578         setUserAgent(standardUserAgent(m_applicationNameForUserAgent));
1579         return;
1580     }
1581
1582     setUserAgent(m_customUserAgent);
1583 }
1584
1585 void WebPageProxy::resumeActiveDOMObjectsAndAnimations()
1586 {
1587     if (!isValid() || !m_isPageSuspended)
1588         return;
1589
1590     m_isPageSuspended = false;
1591
1592     m_process->send(Messages::WebPage::ResumeActiveDOMObjectsAndAnimations(), m_pageID);
1593 }
1594
1595 void WebPageProxy::suspendActiveDOMObjectsAndAnimations()
1596 {
1597     if (!isValid() || m_isPageSuspended)
1598         return;
1599
1600     m_isPageSuspended = true;
1601
1602     m_process->send(Messages::WebPage::SuspendActiveDOMObjectsAndAnimations(), m_pageID);
1603 }
1604
1605 bool WebPageProxy::supportsTextEncoding() const
1606 {
1607     return !m_mainFrameHasCustomRepresentation && m_mainFrame && !m_mainFrame->isDisplayingStandaloneImageDocument();
1608 }
1609
1610 void WebPageProxy::setCustomTextEncodingName(const String& encodingName)
1611 {
1612     if (m_customTextEncodingName == encodingName)
1613         return;
1614     m_customTextEncodingName = encodingName;
1615
1616     if (!isValid())
1617         return;
1618     m_process->send(Messages::WebPage::SetCustomTextEncodingName(encodingName), m_pageID);
1619 }
1620
1621 void WebPageProxy::terminateProcess()
1622 {
1623     // NOTE: This uses a check of m_isValid rather than calling isValid() since
1624     // we want this to run even for pages being closed or that already closed.
1625     if (!m_isValid)
1626         return;
1627
1628     m_process->requestTermination();
1629     resetStateAfterProcessExited();
1630 }
1631
1632 #if !USE(CF) || defined(BUILDING_QT__)
1633 PassRefPtr<WebData> WebPageProxy::sessionStateData(WebPageProxySessionStateFilterCallback, void* /*context*/) const
1634 {
1635     // FIXME: Return session state data for saving Page state.
1636     return 0;
1637 }
1638
1639 void WebPageProxy::restoreFromSessionStateData(WebData*)
1640 {
1641     // FIXME: Restore the Page from the passed in session state data.
1642 }
1643 #endif
1644
1645 bool WebPageProxy::supportsTextZoom() const
1646 {
1647     if (m_mainFrameHasCustomRepresentation)
1648         return false;
1649
1650     // FIXME: This should also return false for standalone media and plug-in documents.
1651     if (!m_mainFrame || m_mainFrame->isDisplayingStandaloneImageDocument())
1652         return false;
1653
1654     return true;
1655 }
1656  
1657 void WebPageProxy::setTextZoomFactor(double zoomFactor)
1658 {
1659     if (!isValid())
1660         return;
1661
1662     if (m_mainFrameHasCustomRepresentation)
1663         return;
1664
1665     if (m_textZoomFactor == zoomFactor)
1666         return;
1667
1668     m_textZoomFactor = zoomFactor;
1669     m_process->send(Messages::WebPage::SetTextZoomFactor(m_textZoomFactor), m_pageID); 
1670 }
1671
1672 double WebPageProxy::pageZoomFactor() const
1673 {
1674     return m_mainFrameHasCustomRepresentation ? m_pageClient->customRepresentationZoomFactor() : m_pageZoomFactor;
1675 }
1676
1677 void WebPageProxy::setPageZoomFactor(double zoomFactor)
1678 {
1679     if (!isValid())
1680         return;
1681
1682     if (m_mainFrameHasCustomRepresentation) {
1683         m_pageClient->setCustomRepresentationZoomFactor(zoomFactor);
1684         return;
1685     }
1686
1687     if (m_pageZoomFactor == zoomFactor)
1688         return;
1689
1690     m_pageZoomFactor = zoomFactor;
1691     m_process->send(Messages::WebPage::SetPageZoomFactor(m_pageZoomFactor), m_pageID); 
1692 }
1693
1694 void WebPageProxy::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1695 {
1696     if (!isValid())
1697         return;
1698
1699     if (m_mainFrameHasCustomRepresentation) {
1700         m_pageClient->setCustomRepresentationZoomFactor(pageZoomFactor);
1701         return;
1702     }
1703
1704     if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor)
1705         return;
1706
1707     m_pageZoomFactor = pageZoomFactor;
1708     m_textZoomFactor = textZoomFactor;
1709     m_process->send(Messages::WebPage::SetPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor), m_pageID); 
1710 }
1711
1712 void WebPageProxy::scalePage(double scale, const IntPoint& origin)
1713 {
1714     if (!isValid())
1715         return;
1716
1717     m_process->send(Messages::WebPage::ScalePage(scale, origin), m_pageID);
1718 }
1719
1720 void WebPageProxy::setIntrinsicDeviceScaleFactor(float scaleFactor)
1721 {
1722     if (m_intrinsicDeviceScaleFactor == scaleFactor)
1723         return;
1724
1725     m_intrinsicDeviceScaleFactor = scaleFactor;
1726
1727     if (m_drawingArea)
1728         m_drawingArea->deviceScaleFactorDidChange();
1729 }
1730
1731 void WebPageProxy::windowScreenDidChange(PlatformDisplayID displayID)
1732 {
1733     if (!isValid())
1734         return;
1735
1736     m_process->send(Messages::WebPage::WindowScreenDidChange(displayID), m_pageID);
1737 }
1738
1739 float WebPageProxy::deviceScaleFactor() const
1740 {
1741     if (m_customDeviceScaleFactor)
1742         return m_customDeviceScaleFactor;
1743     return m_intrinsicDeviceScaleFactor;
1744 }
1745
1746 void WebPageProxy::setCustomDeviceScaleFactor(float customScaleFactor)
1747 {
1748     if (!isValid())
1749         return;
1750
1751     if (m_customDeviceScaleFactor == customScaleFactor)
1752         return;
1753
1754     float oldScaleFactor = deviceScaleFactor();
1755
1756     m_customDeviceScaleFactor = customScaleFactor;
1757
1758     if (deviceScaleFactor() != oldScaleFactor)
1759         m_drawingArea->deviceScaleFactorDidChange();
1760 }
1761
1762 void WebPageProxy::setUseFixedLayout(bool fixed)
1763 {
1764     if (!isValid())
1765         return;
1766
1767     // This check is fine as the value is initialized in the web
1768     // process as part of the creation parameters.
1769     if (fixed == m_useFixedLayout)
1770         return;
1771
1772     m_useFixedLayout = fixed;
1773     if (!fixed)
1774         m_fixedLayoutSize = IntSize();
1775     m_process->send(Messages::WebPage::SetUseFixedLayout(fixed), m_pageID);
1776 }
1777
1778 void WebPageProxy::setFixedLayoutSize(const IntSize& size)
1779 {
1780     if (!isValid())
1781         return;
1782
1783     if (size == m_fixedLayoutSize)
1784         return;
1785
1786     m_fixedLayoutSize = size;
1787     m_process->send(Messages::WebPage::SetFixedLayoutSize(size), m_pageID);
1788 }
1789
1790 void WebPageProxy::listenForLayoutMilestones(WebCore::LayoutMilestones milestones)
1791 {
1792     if (!isValid())
1793         return;
1794
1795     m_process->send(Messages::WebPage::ListenForLayoutMilestones(milestones), m_pageID);
1796 }
1797
1798 void WebPageProxy::setVisibilityState(WebCore::PageVisibilityState visibilityState, bool isInitialState)
1799 {
1800     if (!isValid())
1801         return;
1802
1803 #if ENABLE(PAGE_VISIBILITY_API)
1804     if (visibilityState != m_visibilityState || isInitialState) {
1805         m_visibilityState = visibilityState;
1806         m_process->send(Messages::WebPage::SetVisibilityState(visibilityState, isInitialState), m_pageID);
1807     }
1808 #endif
1809 }
1810
1811 void WebPageProxy::setSuppressScrollbarAnimations(bool suppressAnimations)
1812 {
1813     if (!isValid())
1814         return;
1815
1816     if (suppressAnimations == m_suppressScrollbarAnimations)
1817         return;
1818
1819     m_suppressScrollbarAnimations = suppressAnimations;
1820     m_process->send(Messages::WebPage::SetSuppressScrollbarAnimations(suppressAnimations), m_pageID);
1821 }
1822
1823 void WebPageProxy::setRubberBandsAtBottom(bool rubberBandsAtBottom)
1824 {
1825     if (rubberBandsAtBottom == m_rubberBandsAtBottom)
1826         return;
1827
1828     m_rubberBandsAtBottom = rubberBandsAtBottom;
1829
1830     if (!isValid())
1831         return;
1832
1833     m_process->send(Messages::WebPage::SetRubberBandsAtBottom(rubberBandsAtBottom), m_pageID);
1834 }
1835
1836 void WebPageProxy::setRubberBandsAtTop(bool rubberBandsAtTop)
1837 {
1838     if (rubberBandsAtTop == m_rubberBandsAtTop)
1839         return;
1840
1841     m_rubberBandsAtTop = rubberBandsAtTop;
1842
1843     if (!isValid())
1844         return;
1845
1846     m_process->send(Messages::WebPage::SetRubberBandsAtTop(rubberBandsAtTop), m_pageID);
1847 }
1848
1849 void WebPageProxy::setPaginationMode(WebCore::Pagination::Mode mode)
1850 {
1851     if (mode == m_paginationMode)
1852         return;
1853
1854     m_paginationMode = mode;
1855
1856     if (!isValid())
1857         return;
1858     m_process->send(Messages::WebPage::SetPaginationMode(mode), m_pageID);
1859 }
1860
1861 void WebPageProxy::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1862 {
1863     if (behavesLikeColumns == m_paginationBehavesLikeColumns)
1864         return;
1865
1866     m_paginationBehavesLikeColumns = behavesLikeColumns;
1867
1868     if (!isValid())
1869         return;
1870     m_process->send(Messages::WebPage::SetPaginationBehavesLikeColumns(behavesLikeColumns), m_pageID);
1871 }
1872
1873 void WebPageProxy::setPageLength(double pageLength)
1874 {
1875     if (pageLength == m_pageLength)
1876         return;
1877
1878     m_pageLength = pageLength;
1879
1880     if (!isValid())
1881         return;
1882     m_process->send(Messages::WebPage::SetPageLength(pageLength), m_pageID);
1883 }
1884
1885 void WebPageProxy::setGapBetweenPages(double gap)
1886 {
1887     if (gap == m_gapBetweenPages)
1888         return;
1889
1890     m_gapBetweenPages = gap;
1891
1892     if (!isValid())
1893         return;
1894     m_process->send(Messages::WebPage::SetGapBetweenPages(gap), m_pageID);
1895 }
1896
1897 void WebPageProxy::pageScaleFactorDidChange(double scaleFactor)
1898 {
1899     m_pageScaleFactor = scaleFactor;
1900 }
1901
1902 void WebPageProxy::pageZoomFactorDidChange(double zoomFactor)
1903 {
1904     m_pageZoomFactor = zoomFactor;
1905 }
1906
1907 void WebPageProxy::setMemoryCacheClientCallsEnabled(bool memoryCacheClientCallsEnabled)
1908 {
1909     if (!isValid())
1910         return;
1911
1912     if (m_areMemoryCacheClientCallsEnabled == memoryCacheClientCallsEnabled)
1913         return;
1914
1915     m_areMemoryCacheClientCallsEnabled = memoryCacheClientCallsEnabled;
1916     m_process->send(Messages::WebPage::SetMemoryCacheMessagesEnabled(memoryCacheClientCallsEnabled), m_pageID);
1917 }
1918
1919 void WebPageProxy::findStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
1920 {
1921     if (string.isEmpty()) {
1922         didFindStringMatches(string, Vector<Vector<WebCore::IntRect>> (), 0);
1923         return;
1924     }
1925
1926     m_process->send(Messages::WebPage::FindStringMatches(string, options, maxMatchCount), m_pageID);
1927 }
1928
1929 void WebPageProxy::findString(const String& string, FindOptions options, unsigned maxMatchCount)
1930 {
1931     if (m_mainFrameHasCustomRepresentation)
1932         m_pageClient->findStringInCustomRepresentation(string, options, maxMatchCount);
1933     else
1934         m_process->send(Messages::WebPage::FindString(string, options, maxMatchCount), m_pageID);
1935 }
1936
1937 void WebPageProxy::getImageForFindMatch(int32_t matchIndex)
1938 {
1939     m_process->send(Messages::WebPage::GetImageForFindMatch(matchIndex), m_pageID);
1940 }
1941
1942 void WebPageProxy::selectFindMatch(int32_t matchIndex)
1943 {
1944     m_process->send(Messages::WebPage::SelectFindMatch(matchIndex), m_pageID);
1945 }
1946
1947 void WebPageProxy::hideFindUI()
1948 {
1949     m_process->send(Messages::WebPage::HideFindUI(), m_pageID);
1950 }
1951
1952 void WebPageProxy::countStringMatches(const String& string, FindOptions options, unsigned maxMatchCount)
1953 {
1954     if (m_mainFrameHasCustomRepresentation) {
1955         m_pageClient->countStringMatchesInCustomRepresentation(string, options, maxMatchCount);
1956         return;
1957     }
1958
1959     if (!isValid())
1960         return;
1961
1962     m_process->send(Messages::WebPage::CountStringMatches(string, options, maxMatchCount), m_pageID);
1963 }
1964
1965 void WebPageProxy::runJavaScriptInMainFrame(const String& script, PassRefPtr<ScriptValueCallback> prpCallback)
1966 {
1967     RefPtr<ScriptValueCallback> callback = prpCallback;
1968     if (!isValid()) {
1969         callback->invalidate();
1970         return;
1971     }
1972
1973     uint64_t callbackID = callback->callbackID();
1974     m_scriptValueCallbacks.set(callbackID, callback.get());
1975     m_process->send(Messages::WebPage::RunJavaScriptInMainFrame(script, callbackID), m_pageID);
1976 }
1977
1978 void WebPageProxy::getRenderTreeExternalRepresentation(PassRefPtr<StringCallback> prpCallback)
1979 {
1980     RefPtr<StringCallback> callback = prpCallback;
1981     if (!isValid()) {
1982         callback->invalidate();
1983         return;
1984     }
1985     
1986     uint64_t callbackID = callback->callbackID();
1987     m_stringCallbacks.set(callbackID, callback.get());
1988     m_process->send(Messages::WebPage::GetRenderTreeExternalRepresentation(callbackID), m_pageID);
1989 }
1990
1991 void WebPageProxy::getSourceForFrame(WebFrameProxy* frame, PassRefPtr<StringCallback> prpCallback)
1992 {
1993     RefPtr<StringCallback> callback = prpCallback;
1994     if (!isValid()) {
1995         callback->invalidate();
1996         return;
1997     }
1998     
1999     uint64_t callbackID = callback->callbackID();
2000     m_loadDependentStringCallbackIDs.add(callbackID);
2001     m_stringCallbacks.set(callbackID, callback.get());
2002     m_process->send(Messages::WebPage::GetSourceForFrame(frame->frameID(), callbackID), m_pageID);
2003 }
2004
2005 void WebPageProxy::getContentsAsString(PassRefPtr<StringCallback> prpCallback)
2006 {
2007     RefPtr<StringCallback> callback = prpCallback;
2008     if (!isValid()) {
2009         callback->invalidate();
2010         return;
2011     }
2012     
2013     uint64_t callbackID = callback->callbackID();
2014     m_loadDependentStringCallbackIDs.add(callbackID);
2015     m_stringCallbacks.set(callbackID, callback.get());
2016     m_process->send(Messages::WebPage::GetContentsAsString(callbackID), m_pageID);
2017 }
2018
2019 #if ENABLE(MHTML)
2020 void WebPageProxy::getContentsAsMHTMLData(PassRefPtr<DataCallback> prpCallback, bool useBinaryEncoding)
2021 {
2022     RefPtr<DataCallback> callback = prpCallback;
2023     if (!isValid()) {
2024         callback->invalidate();
2025         return;
2026     }
2027
2028     uint64_t callbackID = callback->callbackID();
2029     m_dataCallbacks.set(callbackID, callback.get());
2030     m_process->send(Messages::WebPage::GetContentsAsMHTMLData(callbackID, useBinaryEncoding), m_pageID);
2031 }
2032 #endif
2033
2034 void WebPageProxy::getSelectionOrContentsAsString(PassRefPtr<StringCallback> prpCallback)
2035 {
2036     RefPtr<StringCallback> callback = prpCallback;
2037     if (!isValid()) {
2038         callback->invalidate();
2039         return;
2040     }
2041     
2042     uint64_t callbackID = callback->callbackID();
2043     m_stringCallbacks.set(callbackID, callback.get());
2044     m_process->send(Messages::WebPage::GetSelectionOrContentsAsString(callbackID), m_pageID);
2045 }
2046
2047 void WebPageProxy::getSelectionAsWebArchiveData(PassRefPtr<DataCallback> prpCallback)
2048 {
2049     RefPtr<DataCallback> callback = prpCallback;
2050     if (!isValid()) {
2051         callback->invalidate();
2052         return;
2053     }
2054     
2055     uint64_t callbackID = callback->callbackID();
2056     m_dataCallbacks.set(callbackID, callback.get());
2057     m_process->send(Messages::WebPage::GetSelectionAsWebArchiveData(callbackID), m_pageID);
2058 }
2059
2060 void WebPageProxy::getMainResourceDataOfFrame(WebFrameProxy* frame, PassRefPtr<DataCallback> prpCallback)
2061 {
2062     RefPtr<DataCallback> callback = prpCallback;
2063     if (!isValid()) {
2064         callback->invalidate();
2065         return;
2066     }
2067     
2068     uint64_t callbackID = callback->callbackID();
2069     m_dataCallbacks.set(callbackID, callback.get());
2070     m_process->send(Messages::WebPage::GetMainResourceDataOfFrame(frame->frameID(), callbackID), m_pageID);
2071 }
2072
2073 void WebPageProxy::getResourceDataFromFrame(WebFrameProxy* frame, WebURL* resourceURL, PassRefPtr<DataCallback> prpCallback)
2074 {
2075     RefPtr<DataCallback> callback = prpCallback;
2076     if (!isValid()) {
2077         callback->invalidate();
2078         return;
2079     }
2080     
2081     uint64_t callbackID = callback->callbackID();
2082     m_dataCallbacks.set(callbackID, callback.get());
2083     m_process->send(Messages::WebPage::GetResourceDataFromFrame(frame->frameID(), resourceURL->string(), callbackID), m_pageID);
2084 }
2085
2086 void WebPageProxy::getWebArchiveOfFrame(WebFrameProxy* frame, PassRefPtr<DataCallback> prpCallback)
2087 {
2088     RefPtr<DataCallback> callback = prpCallback;
2089     if (!isValid()) {
2090         callback->invalidate();
2091         return;
2092     }
2093     
2094     uint64_t callbackID = callback->callbackID();
2095     m_dataCallbacks.set(callbackID, callback.get());
2096     m_process->send(Messages::WebPage::GetWebArchiveOfFrame(frame->frameID(), callbackID), m_pageID);
2097 }
2098
2099 void WebPageProxy::forceRepaint(PassRefPtr<VoidCallback> prpCallback)
2100 {
2101     RefPtr<VoidCallback> callback = prpCallback;
2102     if (!isValid()) {
2103         callback->invalidate();
2104         return;
2105     }
2106
2107     uint64_t callbackID = callback->callbackID();
2108     m_voidCallbacks.set(callbackID, callback.get());
2109     m_drawingArea->waitForBackingStoreUpdateOnNextPaint();
2110     m_process->send(Messages::WebPage::ForceRepaint(callbackID), m_pageID); 
2111 }
2112
2113 void WebPageProxy::preferencesDidChange()
2114 {
2115     if (!isValid())
2116         return;
2117
2118 #if ENABLE(INSPECTOR_SERVER)
2119     if (m_pageGroup->preferences()->developerExtrasEnabled())
2120         inspector()->enableRemoteInspection();
2121 #endif
2122
2123     m_process->pagePreferencesChanged(this);
2124
2125     // FIXME: It probably makes more sense to send individual preference changes.
2126     // However, WebKitTestRunner depends on getting a preference change notification
2127     // even if nothing changed in UI process, so that overrides get removed.
2128
2129     // Preferences need to be updated during synchronous printing to make "print backgrounds" preference work when toggled from a print dialog checkbox.
2130     m_process->send(Messages::WebPage::PreferencesDidChange(pageGroup()->preferences()->store()), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0);
2131 }
2132
2133 void WebPageProxy::didCreateMainFrame(uint64_t frameID)
2134 {
2135     MESSAGE_CHECK(!m_mainFrame);
2136     MESSAGE_CHECK(m_process->canCreateFrame(frameID));
2137
2138     m_mainFrame = WebFrameProxy::create(this, frameID);
2139
2140     // Add the frame to the process wide map.
2141     m_process->frameCreated(frameID, m_mainFrame.get());
2142 }
2143
2144 void WebPageProxy::didCreateSubframe(uint64_t frameID)
2145 {
2146     MESSAGE_CHECK(m_mainFrame);
2147     MESSAGE_CHECK(m_process->canCreateFrame(frameID));
2148     
2149     RefPtr<WebFrameProxy> subFrame = WebFrameProxy::create(this, frameID);
2150
2151     // Add the frame to the process wide map.
2152     m_process->frameCreated(frameID, subFrame.get());
2153 }
2154
2155 // Always start progress at initialProgressValue. This helps provide feedback as
2156 // soon as a load starts.
2157
2158 static const double initialProgressValue = 0.1;
2159
2160 double WebPageProxy::estimatedProgress() const
2161 {
2162     if (!pendingAPIRequestURL().isNull())
2163         return initialProgressValue;
2164     return m_estimatedProgress; 
2165 }
2166
2167 void WebPageProxy::didStartProgress()
2168 {
2169     m_estimatedProgress = initialProgressValue;
2170
2171     m_loaderClient.didStartProgress(this);
2172 }
2173
2174 void WebPageProxy::didChangeProgress(double value)
2175 {
2176     m_estimatedProgress = value;
2177
2178     m_loaderClient.didChangeProgress(this);
2179 }
2180
2181 void WebPageProxy::didFinishProgress()
2182 {
2183     m_estimatedProgress = 1.0;
2184
2185     m_loaderClient.didFinishProgress(this);
2186 }
2187
2188 void WebPageProxy::didStartProvisionalLoadForFrame(uint64_t frameID, const String& url, const String& unreachableURL, CoreIPC::MessageDecoder& decoder)
2189 {
2190     clearPendingAPIRequestURL();
2191
2192     RefPtr<APIObject> userData;
2193     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2194     if (!decoder.decode(messageDecoder))
2195         return;
2196
2197     WebFrameProxy* frame = m_process->webFrame(frameID);
2198     MESSAGE_CHECK(frame);
2199     MESSAGE_CHECK_URL(url);
2200
2201     frame->setUnreachableURL(unreachableURL);
2202
2203     frame->didStartProvisionalLoad(url);
2204     m_loaderClient.didStartProvisionalLoadForFrame(this, frame, userData.get());
2205 }
2206
2207 void WebPageProxy::didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, const String& url, CoreIPC::MessageDecoder& decoder)
2208 {
2209     RefPtr<APIObject> userData;
2210     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2211     if (!decoder.decode(messageDecoder))
2212         return;
2213
2214     WebFrameProxy* frame = m_process->webFrame(frameID);
2215     MESSAGE_CHECK(frame);
2216     MESSAGE_CHECK_URL(url);
2217
2218     frame->didReceiveServerRedirectForProvisionalLoad(url);
2219
2220     m_loaderClient.didReceiveServerRedirectForProvisionalLoadForFrame(this, frame, userData.get());
2221 }
2222
2223 void WebPageProxy::didFailProvisionalLoadForFrame(uint64_t frameID, const ResourceError& error, CoreIPC::MessageDecoder& decoder)
2224 {
2225     RefPtr<APIObject> userData;
2226     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2227     if (!decoder.decode(messageDecoder))
2228         return;
2229
2230     WebFrameProxy* frame = m_process->webFrame(frameID);
2231     MESSAGE_CHECK(frame);
2232
2233     frame->didFailProvisionalLoad();
2234
2235     m_loaderClient.didFailProvisionalLoadWithErrorForFrame(this, frame, error, userData.get());
2236 }
2237
2238 void WebPageProxy::clearLoadDependentCallbacks()
2239 {
2240     Vector<uint64_t> callbackIDsCopy;
2241     copyToVector(m_loadDependentStringCallbackIDs, callbackIDsCopy);
2242     m_loadDependentStringCallbackIDs.clear();
2243
2244     for (size_t i = 0; i < callbackIDsCopy.size(); ++i) {
2245         RefPtr<StringCallback> callback = m_stringCallbacks.take(callbackIDsCopy[i]);
2246         if (callback)
2247             callback->invalidate();
2248     }
2249 }
2250
2251 void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, const String& mimeType, bool frameHasCustomRepresentation, uint32_t opaqueFrameLoadType, const PlatformCertificateInfo& certificateInfo, CoreIPC::MessageDecoder& decoder)
2252 {
2253     RefPtr<APIObject> userData;
2254     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2255     if (!decoder.decode(messageDecoder))
2256         return;
2257
2258     WebFrameProxy* frame = m_process->webFrame(frameID);
2259     MESSAGE_CHECK(frame);
2260
2261 #if PLATFORM(MAC)
2262     // FIXME (bug 59111): didCommitLoadForFrame comes too late when restoring a page from b/f cache, making us disable secure event mode in password fields.
2263     // FIXME (bug 59121): A load going on in one frame shouldn't affect typing in sibling frames.
2264     m_pageClient->notifyInputContextAboutDiscardedComposition();
2265     m_pageClient->resetSecureInputState();
2266     dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored);
2267     m_pageClient->dismissDictionaryLookupPanel();
2268 #endif
2269
2270     clearLoadDependentCallbacks();
2271
2272     frame->didCommitLoad(mimeType, certificateInfo);
2273
2274     if (frame->isMainFrame()) {
2275         m_mainFrameHasCustomRepresentation = frameHasCustomRepresentation;
2276
2277         if (m_mainFrameHasCustomRepresentation) {
2278             // Always assume that the main frame is pinned here, since the custom representation view will handle
2279             // any wheel events and dispatch them to the WKView when necessary.
2280             m_mainFrameIsPinnedToLeftSide = true;
2281             m_mainFrameIsPinnedToRightSide = true;
2282             m_mainFrameIsPinnedToTopSide = true;
2283             m_mainFrameIsPinnedToBottomSide = true;
2284         }
2285         m_pageClient->didCommitLoadForMainFrame(frameHasCustomRepresentation);
2286     }
2287
2288     // Even if WebPage has the default pageScaleFactor (and therefore doesn't reset it),
2289     // WebPageProxy's cache of the value can get out of sync (e.g. in the case where a
2290     // plugin is handling page scaling itself) so we should reset it to the default
2291     // for standard main frame loads.
2292     if (frame->isMainFrame() && static_cast<FrameLoadType>(opaqueFrameLoadType) == FrameLoadTypeStandard)
2293         m_pageScaleFactor = 1;
2294
2295     m_loaderClient.didCommitLoadForFrame(this, frame, userData.get());
2296 }
2297
2298 void WebPageProxy::didFinishDocumentLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2299 {
2300     RefPtr<APIObject> userData;
2301     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2302     if (!decoder.decode(messageDecoder))
2303         return;
2304
2305     WebFrameProxy* frame = m_process->webFrame(frameID);
2306     MESSAGE_CHECK(frame);
2307
2308     m_loaderClient.didFinishDocumentLoadForFrame(this, frame, userData.get());
2309 }
2310
2311 void WebPageProxy::didFinishLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2312 {
2313     RefPtr<APIObject> userData;
2314     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2315     if (!decoder.decode(messageDecoder))
2316         return;
2317
2318     WebFrameProxy* frame = m_process->webFrame(frameID);
2319     MESSAGE_CHECK(frame);
2320
2321     frame->didFinishLoad();
2322
2323     m_loaderClient.didFinishLoadForFrame(this, frame, userData.get());
2324 }
2325
2326 void WebPageProxy::didFailLoadForFrame(uint64_t frameID, const ResourceError& error, CoreIPC::MessageDecoder& decoder)
2327 {
2328     RefPtr<APIObject> userData;
2329     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2330     if (!decoder.decode(messageDecoder))
2331         return;
2332
2333     WebFrameProxy* frame = m_process->webFrame(frameID);
2334     MESSAGE_CHECK(frame);
2335
2336     clearLoadDependentCallbacks();
2337
2338     frame->didFailLoad();
2339
2340     m_loaderClient.didFailLoadWithErrorForFrame(this, frame, error, userData.get());
2341 }
2342
2343 void WebPageProxy::didSameDocumentNavigationForFrame(uint64_t frameID, uint32_t opaqueSameDocumentNavigationType, const String& url, CoreIPC::MessageDecoder& decoder)
2344 {
2345     RefPtr<APIObject> userData;
2346     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2347     if (!decoder.decode(messageDecoder))
2348         return;
2349
2350     WebFrameProxy* frame = m_process->webFrame(frameID);
2351     MESSAGE_CHECK(frame);
2352     MESSAGE_CHECK_URL(url);
2353
2354     clearPendingAPIRequestURL();
2355     frame->didSameDocumentNavigation(url);
2356
2357     m_loaderClient.didSameDocumentNavigationForFrame(this, frame, static_cast<SameDocumentNavigationType>(opaqueSameDocumentNavigationType), userData.get());
2358 }
2359
2360 void WebPageProxy::didReceiveTitleForFrame(uint64_t frameID, const String& title, CoreIPC::MessageDecoder& decoder)
2361 {
2362     RefPtr<APIObject> userData;
2363     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2364     if (!decoder.decode(messageDecoder))
2365         return;
2366
2367     WebFrameProxy* frame = m_process->webFrame(frameID);
2368     MESSAGE_CHECK(frame);
2369
2370     frame->didChangeTitle(title);
2371     
2372     m_loaderClient.didReceiveTitleForFrame(this, title, frame, userData.get());
2373 }
2374
2375 void WebPageProxy::didFirstLayoutForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2376 {
2377     RefPtr<APIObject> userData;
2378     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2379     if (!decoder.decode(messageDecoder))
2380         return;
2381
2382     WebFrameProxy* frame = m_process->webFrame(frameID);
2383     MESSAGE_CHECK(frame);
2384
2385     m_loaderClient.didFirstLayoutForFrame(this, frame, userData.get());
2386 }
2387
2388 void WebPageProxy::didFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2389 {
2390     RefPtr<APIObject> userData;
2391     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2392     if (!decoder.decode(messageDecoder))
2393         return;
2394
2395     WebFrameProxy* frame = m_process->webFrame(frameID);
2396     MESSAGE_CHECK(frame);
2397
2398     m_loaderClient.didFirstVisuallyNonEmptyLayoutForFrame(this, frame, userData.get());
2399 }
2400
2401 void WebPageProxy::didNewFirstVisuallyNonEmptyLayout(CoreIPC::MessageDecoder& decoder)
2402 {
2403     RefPtr<APIObject> userData;
2404     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2405     if (!decoder.decode(messageDecoder))
2406         return;
2407
2408     m_loaderClient.didNewFirstVisuallyNonEmptyLayout(this, userData.get());
2409 }
2410
2411 void WebPageProxy::didLayout(uint32_t layoutMilestones, CoreIPC::MessageDecoder& decoder)
2412 {
2413     RefPtr<APIObject> userData;
2414     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2415     if (!decoder.decode(messageDecoder))
2416         return;
2417
2418     m_loaderClient.didLayout(this, static_cast<LayoutMilestones>(layoutMilestones), userData.get());
2419 }
2420
2421 void WebPageProxy::didRemoveFrameFromHierarchy(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2422 {
2423     RefPtr<APIObject> userData;
2424     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2425     if (!decoder.decode(messageDecoder))
2426         return;
2427
2428     WebFrameProxy* frame = m_process->webFrame(frameID);
2429     MESSAGE_CHECK(frame);
2430
2431     m_loaderClient.didRemoveFrameFromHierarchy(this, frame, userData.get());
2432 }
2433
2434 void WebPageProxy::didDisplayInsecureContentForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2435 {
2436     RefPtr<APIObject> userData;
2437     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2438     if (!decoder.decode(messageDecoder))
2439         return;
2440
2441     WebFrameProxy* frame = m_process->webFrame(frameID);
2442     MESSAGE_CHECK(frame);
2443
2444     m_loaderClient.didDisplayInsecureContentForFrame(this, frame, userData.get());
2445 }
2446
2447 void WebPageProxy::didRunInsecureContentForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2448 {
2449     RefPtr<APIObject> userData;
2450     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2451     if (!decoder.decode(messageDecoder))
2452         return;
2453
2454     WebFrameProxy* frame = m_process->webFrame(frameID);
2455     MESSAGE_CHECK(frame);
2456
2457     m_loaderClient.didRunInsecureContentForFrame(this, frame, userData.get());
2458 }
2459
2460 void WebPageProxy::didDetectXSSForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder)
2461 {
2462     RefPtr<APIObject> userData;
2463     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2464     if (!decoder.decode(messageDecoder))
2465         return;
2466
2467     WebFrameProxy* frame = m_process->webFrame(frameID);
2468     MESSAGE_CHECK(frame);
2469
2470     m_loaderClient.didDetectXSSForFrame(this, frame, userData.get());
2471 }
2472
2473 void WebPageProxy::frameDidBecomeFrameSet(uint64_t frameID, bool value)
2474 {
2475     WebFrameProxy* frame = m_process->webFrame(frameID);
2476     MESSAGE_CHECK(frame);
2477
2478     frame->setIsFrameSet(value);
2479     if (frame->isMainFrame())
2480         m_frameSetLargestFrame = value ? m_mainFrame : 0;
2481 }
2482
2483 // PolicyClient
2484 void WebPageProxy::decidePolicyForNavigationAction(uint64_t frameID, uint32_t opaqueNavigationType, uint32_t opaqueModifiers, int32_t opaqueMouseButton, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID)
2485 {
2486     RefPtr<APIObject> userData;
2487     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2488     if (!decoder.decode(messageDecoder))
2489         return;
2490
2491     if (request.url() != pendingAPIRequestURL())
2492         clearPendingAPIRequestURL();
2493
2494     WebFrameProxy* frame = m_process->webFrame(frameID);
2495     MESSAGE_CHECK(frame);
2496     MESSAGE_CHECK_URL(request.url());
2497
2498     NavigationType navigationType = static_cast<NavigationType>(opaqueNavigationType);
2499     WebEvent::Modifiers modifiers = static_cast<WebEvent::Modifiers>(opaqueModifiers);
2500     WebMouseEvent::Button mouseButton = static_cast<WebMouseEvent::Button>(opaqueMouseButton);
2501     
2502     RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID);
2503
2504     ASSERT(!m_inDecidePolicyForNavigationAction);
2505
2506     m_inDecidePolicyForNavigationAction = true;
2507     m_syncNavigationActionPolicyActionIsValid = false;
2508     
2509     if (!m_policyClient.decidePolicyForNavigationAction(this, frame, navigationType, modifiers, mouseButton, request, listener.get(), userData.get()))
2510         listener->use();
2511
2512     m_inDecidePolicyForNavigationAction = false;
2513
2514     // Check if we received a policy decision already. If we did, we can just pass it back.
2515     receivedPolicyAction = m_syncNavigationActionPolicyActionIsValid;
2516     if (m_syncNavigationActionPolicyActionIsValid) {
2517         policyAction = m_syncNavigationActionPolicyAction;
2518         downloadID = m_syncNavigationActionPolicyDownloadID;
2519     }
2520 }
2521
2522 void WebPageProxy::decidePolicyForNewWindowAction(uint64_t frameID, uint32_t opaqueNavigationType, uint32_t opaqueModifiers, int32_t opaqueMouseButton, const ResourceRequest& request, const String& frameName, uint64_t listenerID, CoreIPC::MessageDecoder& decoder)
2523 {
2524     RefPtr<APIObject> userData;
2525     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2526     if (!decoder.decode(messageDecoder))
2527         return;
2528
2529     WebFrameProxy* frame = m_process->webFrame(frameID);
2530     MESSAGE_CHECK(frame);
2531     MESSAGE_CHECK_URL(request.url());
2532
2533     NavigationType navigationType = static_cast<NavigationType>(opaqueNavigationType);
2534     WebEvent::Modifiers modifiers = static_cast<WebEvent::Modifiers>(opaqueModifiers);
2535     WebMouseEvent::Button mouseButton = static_cast<WebMouseEvent::Button>(opaqueMouseButton);
2536
2537     RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID);
2538     if (!m_policyClient.decidePolicyForNewWindowAction(this, frame, navigationType, modifiers, mouseButton, request, frameName, listener.get(), userData.get()))
2539         listener->use();
2540 }
2541
2542 void WebPageProxy::decidePolicyForResponse(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder)
2543 {
2544     RefPtr<APIObject> userData;
2545     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2546     if (!decoder.decode(messageDecoder))
2547         return;
2548
2549     WebFrameProxy* frame = m_process->webFrame(frameID);
2550     MESSAGE_CHECK(frame);
2551     MESSAGE_CHECK_URL(request.url());
2552     MESSAGE_CHECK_URL(response.url());
2553
2554     RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID);
2555
2556     if (!m_policyClient.decidePolicyForResponse(this, frame, response, request, listener.get(), userData.get()))
2557         listener->use();
2558 }
2559
2560 void WebPageProxy::decidePolicyForResponseSync(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID)
2561 {
2562     ASSERT(!m_inDecidePolicyForResponseSync);
2563
2564     m_inDecidePolicyForResponseSync = true;
2565     m_decidePolicyForResponseRequest = &request;
2566     m_syncMimeTypePolicyActionIsValid = false;
2567
2568     decidePolicyForResponse(frameID, response, request, listenerID, decoder);
2569
2570     m_inDecidePolicyForResponseSync = false;
2571     m_decidePolicyForResponseRequest = 0;
2572
2573     // Check if we received a policy decision already. If we did, we can just pass it back.
2574     receivedPolicyAction = m_syncMimeTypePolicyActionIsValid;
2575     if (m_syncMimeTypePolicyActionIsValid) {
2576         policyAction = m_syncMimeTypePolicyAction;
2577         downloadID = m_syncMimeTypePolicyDownloadID;
2578     }
2579 }
2580
2581 void WebPageProxy::unableToImplementPolicy(uint64_t frameID, const ResourceError& error, CoreIPC::MessageDecoder& decoder)
2582 {
2583     RefPtr<APIObject> userData;
2584     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2585     if (!decoder.decode(messageDecoder))
2586         return;
2587     
2588     WebFrameProxy* frame = m_process->webFrame(frameID);
2589     MESSAGE_CHECK(frame);
2590
2591     m_policyClient.unableToImplementPolicy(this, frame, error, userData.get());
2592 }
2593
2594 // FormClient
2595
2596 void WebPageProxy::willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String>>& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder& decoder)
2597 {
2598     RefPtr<APIObject> userData;
2599     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2600     if (!decoder.decode(messageDecoder))
2601         return;
2602
2603     WebFrameProxy* frame = m_process->webFrame(frameID);
2604     MESSAGE_CHECK(frame);
2605
2606     WebFrameProxy* sourceFrame = m_process->webFrame(sourceFrameID);
2607     MESSAGE_CHECK(sourceFrame);
2608
2609     RefPtr<WebFormSubmissionListenerProxy> listener = frame->setUpFormSubmissionListenerProxy(listenerID);
2610     if (!m_formClient.willSubmitForm(this, frame, sourceFrame, textFieldValues, userData.get(), listener.get()))
2611         listener->continueSubmission();
2612 }
2613
2614 // UIClient
2615
2616 void WebPageProxy::createNewPage(const ResourceRequest& request, const WindowFeatures& windowFeatures, uint32_t opaqueModifiers, int32_t opaqueMouseButton, uint64_t& newPageID, WebPageCreationParameters& newPageParameters)
2617 {
2618     RefPtr<WebPageProxy> newPage = m_uiClient.createNewPage(this, request, windowFeatures, static_cast<WebEvent::Modifiers>(opaqueModifiers), static_cast<WebMouseEvent::Button>(opaqueMouseButton));
2619     if (!newPage) {
2620         newPageID = 0;
2621         return;
2622     }
2623
2624     newPageID = newPage->pageID();
2625     newPageParameters = newPage->creationParameters();
2626     process()->context()->storageManager().cloneSessionStorageNamespace(m_pageID, newPage->pageID());
2627 }
2628     
2629 void WebPageProxy::showPage()
2630 {
2631     m_uiClient.showPage(this);
2632 }
2633
2634 void WebPageProxy::closePage(bool stopResponsivenessTimer)
2635 {
2636     if (stopResponsivenessTimer)
2637         m_process->responsivenessTimer()->stop();
2638
2639     m_pageClient->clearAllEditCommands();
2640     m_uiClient.close(this);
2641 }
2642
2643 void WebPageProxy::runJavaScriptAlert(uint64_t frameID, const String& message)
2644 {
2645     WebFrameProxy* frame = m_process->webFrame(frameID);
2646     MESSAGE_CHECK(frame);
2647
2648     // Since runJavaScriptAlert() can spin a nested run loop we need to turn off the responsiveness timer.
2649     m_process->responsivenessTimer()->stop();
2650
2651     m_uiClient.runJavaScriptAlert(this, message, frame);
2652 }
2653
2654 void WebPageProxy::runJavaScriptConfirm(uint64_t frameID, const String& message, bool& result)
2655 {
2656     WebFrameProxy* frame = m_process->webFrame(frameID);
2657     MESSAGE_CHECK(frame);
2658
2659     // Since runJavaScriptConfirm() can spin a nested run loop we need to turn off the responsiveness timer.
2660     m_process->responsivenessTimer()->stop();
2661
2662     result = m_uiClient.runJavaScriptConfirm(this, message, frame);
2663 }
2664
2665 void WebPageProxy::runJavaScriptPrompt(uint64_t frameID, const String& message, const String& defaultValue, String& result)
2666 {
2667     WebFrameProxy* frame = m_process->webFrame(frameID);
2668     MESSAGE_CHECK(frame);
2669
2670     // Since runJavaScriptPrompt() can spin a nested run loop we need to turn off the responsiveness timer.
2671     m_process->responsivenessTimer()->stop();
2672
2673     result = m_uiClient.runJavaScriptPrompt(this, message, defaultValue, frame);
2674 }
2675
2676 void WebPageProxy::shouldInterruptJavaScript(bool& result)
2677 {
2678     // Since shouldInterruptJavaScript() can spin a nested run loop we need to turn off the responsiveness timer.
2679     m_process->responsivenessTimer()->stop();
2680
2681     result = m_uiClient.shouldInterruptJavaScript(this);
2682 }
2683
2684 void WebPageProxy::setStatusText(const String& text)
2685 {
2686     m_uiClient.setStatusText(this, text);
2687 }
2688
2689 void WebPageProxy::mouseDidMoveOverElement(const WebHitTestResult::Data& hitTestResultData, uint32_t opaqueModifiers, CoreIPC::MessageDecoder& decoder)
2690 {
2691     RefPtr<APIObject> userData;
2692     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
2693     if (!decoder.decode(messageDecoder))
2694         return;
2695
2696     WebEvent::Modifiers modifiers = static_cast<WebEvent::Modifiers>(opaqueModifiers);
2697
2698     m_uiClient.mouseDidMoveOverElement(this, hitTestResultData, modifiers, userData.get());
2699 }
2700
2701 void WebPageProxy::connectionWillOpen(CoreIPC::Connection* connection)
2702 {
2703     ASSERT(connection == m_process->connection());
2704
2705     m_process->context()->storageManager().setAllowedSessionStorageNamespaceConnection(m_pageID, connection);
2706 }
2707
2708 void WebPageProxy::connectionWillClose(CoreIPC::Connection* connection)
2709 {
2710     ASSERT_UNUSED(connection, connection == m_process->connection());
2711
2712     m_process->context()->storageManager().setAllowedSessionStorageNamespaceConnection(m_pageID, 0);
2713 }
2714
2715 void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& pluginURLString, const String& pluginspageAttributeURLString, const String& frameURLString, const String& pageURLString)
2716 {
2717     MESSAGE_CHECK_URL(pluginURLString);
2718     MESSAGE_CHECK_URL(pluginspageAttributeURLString);
2719     MESSAGE_CHECK_URL(frameURLString);
2720     MESSAGE_CHECK_URL(pageURLString);
2721
2722     RefPtr<ImmutableDictionary> pluginInformation;
2723 #if ENABLE(NETSCAPE_PLUGIN_API)
2724     String newMimeType = mimeType;
2725     PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), pluginURLString));
2726     pluginInformation = createPluginInformationDictionary(plugin, frameURLString, mimeType, pageURLString, pluginspageAttributeURLString, pluginURLString);
2727 #endif
2728
2729     WKPluginUnavailabilityReason pluginUnavailabilityReason = kWKPluginUnavailabilityReasonPluginMissing;
2730     switch (static_cast<RenderEmbeddedObject::PluginUnavailabilityReason>(opaquePluginUnavailabilityReason)) {
2731     case RenderEmbeddedObject::PluginMissing:
2732         pluginUnavailabilityReason = kWKPluginUnavailabilityReasonPluginMissing;
2733         break;
2734     case RenderEmbeddedObject::InsecurePluginVersion:
2735         pluginUnavailabilityReason = kWKPluginUnavailabilityReasonInsecurePluginVersion;
2736         break;
2737     case RenderEmbeddedObject::PluginCrashed:
2738         pluginUnavailabilityReason = kWKPluginUnavailabilityReasonPluginCrashed;
2739         break;
2740
2741     case RenderEmbeddedObject::PluginInactive: {
2742 #if ENABLE(NETSCAPE_PLUGIN_API)
2743         if (!plugin.path.isEmpty() && PluginInfoStore::reactivateInactivePlugin(plugin)) {
2744             // The plug-in has been reactivated now; reload the page so it'll be instantiated.
2745             reload(false);
2746         }
2747         return;
2748 #endif
2749     }
2750
2751     case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy:
2752         ASSERT_NOT_REACHED();
2753     }
2754
2755     m_uiClient.unavailablePluginButtonClicked(this, pluginUnavailabilityReason, pluginInformation.get());
2756 }
2757
2758 void WebPageProxy::setToolbarsAreVisible(bool toolbarsAreVisible)
2759 {
2760     m_uiClient.setToolbarsAreVisible(this, toolbarsAreVisible);
2761 }
2762
2763 void WebPageProxy::getToolbarsAreVisible(bool& toolbarsAreVisible)
2764 {
2765     toolbarsAreVisible = m_uiClient.toolbarsAreVisible(this);
2766 }
2767
2768 void WebPageProxy::setMenuBarIsVisible(bool menuBarIsVisible)
2769 {
2770     m_uiClient.setMenuBarIsVisible(this, menuBarIsVisible);
2771 }
2772
2773 void WebPageProxy::getMenuBarIsVisible(bool& menuBarIsVisible)
2774 {
2775     menuBarIsVisible = m_uiClient.menuBarIsVisible(this);
2776 }
2777
2778 void WebPageProxy::setStatusBarIsVisible(bool statusBarIsVisible)
2779 {
2780     m_uiClient.setStatusBarIsVisible(this, statusBarIsVisible);
2781 }
2782
2783 void WebPageProxy::getStatusBarIsVisible(bool& statusBarIsVisible)
2784 {
2785     statusBarIsVisible = m_uiClient.statusBarIsVisible(this);
2786 }
2787
2788 void WebPageProxy::setIsResizable(bool isResizable)
2789 {
2790     m_uiClient.setIsResizable(this, isResizable);
2791 }
2792
2793 void WebPageProxy::getIsResizable(bool& isResizable)
2794 {
2795     isResizable = m_uiClient.isResizable(this);
2796 }
2797
2798 void WebPageProxy::setWindowFrame(const FloatRect& newWindowFrame)
2799 {
2800     m_uiClient.setWindowFrame(this, m_pageClient->convertToDeviceSpace(newWindowFrame));
2801 }
2802
2803 void WebPageProxy::getWindowFrame(FloatRect& newWindowFrame)
2804 {
2805     newWindowFrame = m_pageClient->convertToUserSpace(m_uiClient.windowFrame(this));
2806 }
2807     
2808 void WebPageProxy::screenToWindow(const IntPoint& screenPoint, IntPoint& windowPoint)
2809 {
2810     windowPoint = m_pageClient->screenToWindow(screenPoint);
2811 }
2812     
2813 void WebPageProxy::windowToScreen(const IntRect& viewRect, IntRect& result)
2814 {
2815     result = m_pageClient->windowToScreen(viewRect);
2816 }
2817     
2818 void WebPageProxy::runBeforeUnloadConfirmPanel(const String& message, uint64_t frameID, bool& shouldClose)
2819 {
2820     WebFrameProxy* frame = m_process->webFrame(frameID);
2821     MESSAGE_CHECK(frame);
2822
2823     // Since runBeforeUnloadConfirmPanel() can spin a nested run loop we need to turn off the responsiveness timer.
2824     m_process->responsivenessTimer()->stop();
2825
2826     shouldClose = m_uiClient.runBeforeUnloadConfirmPanel(this, message, frame);
2827 }
2828
2829 #if USE(TILED_BACKING_STORE)
2830 void WebPageProxy::pageDidRequestScroll(const IntPoint& point)
2831 {
2832     m_pageClient->pageDidRequestScroll(point);
2833 }
2834
2835 void WebPageProxy::pageTransitionViewportReady()
2836 {
2837     m_pageClient->pageTransitionViewportReady();
2838 }
2839
2840 void WebPageProxy::didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect)
2841 {
2842     m_pageClient->didRenderFrame(contentsSize, coveredRect);
2843 }
2844
2845 #endif
2846
2847 void WebPageProxy::didChangeViewportProperties(const ViewportAttributes& attr)
2848 {
2849     m_pageClient->didChangeViewportProperties(attr);
2850 }
2851
2852 void WebPageProxy::pageDidScroll()
2853 {
2854     m_uiClient.pageDidScroll(this);
2855 #if PLATFORM(MAC)
2856     dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored);
2857 #endif
2858 }
2859
2860 void WebPageProxy::runOpenPanel(uint64_t frameID, const FileChooserSettings& settings)
2861 {
2862     if (m_openPanelResultListener) {
2863         m_openPanelResultListener->invalidate();
2864         m_openPanelResultListener = 0;
2865     }
2866
2867     WebFrameProxy* frame = m_process->webFrame(frameID);
2868     MESSAGE_CHECK(frame);
2869
2870     RefPtr<WebOpenPanelParameters> parameters = WebOpenPanelParameters::create(settings);
2871     m_openPanelResultListener = WebOpenPanelResultListenerProxy::create(this);
2872
2873     // Since runOpenPanel() can spin a nested run loop we need to turn off the responsiveness timer.
2874     m_process->responsivenessTimer()->stop();
2875
2876     if (!m_uiClient.runOpenPanel(this, frame, parameters.get(), m_openPanelResultListener.get()))
2877         didCancelForOpenPanel();
2878 }
2879
2880 void WebPageProxy::printFrame(uint64_t frameID)
2881 {
2882     ASSERT(!m_isPerformingDOMPrintOperation);
2883     m_isPerformingDOMPrintOperation = true;
2884
2885     WebFrameProxy* frame = m_process->webFrame(frameID);
2886     MESSAGE_CHECK(frame);
2887
2888     m_uiClient.printFrame(this, frame);
2889
2890     endPrinting(); // Send a message synchronously while m_isPerformingDOMPrintOperation is still true.
2891     m_isPerformingDOMPrintOperation = false;
2892 }
2893
2894 void WebPageProxy::printMainFrame()
2895 {
2896     printFrame(m_mainFrame->frameID());
2897 }
2898
2899 void WebPageProxy::setMediaVolume(float volume)
2900 {
2901     if (volume == m_mediaVolume)
2902         return;
2903     
2904     m_mediaVolume = volume;
2905     
2906     if (!isValid())
2907         return;
2908     
2909     m_process->send(Messages::WebPage::SetMediaVolume(volume), m_pageID);    
2910 }
2911
2912 void WebPageProxy::setMayStartMediaWhenInWindow(bool mayStartMedia)
2913 {
2914     if (mayStartMedia == m_mayStartMediaWhenInWindow)
2915         return;
2916
2917     m_mayStartMediaWhenInWindow = mayStartMedia;
2918
2919     if (!isValid())
2920         return;
2921
2922     process()->send(Messages::WebPage::SetMayStartMediaWhenInWindow(mayStartMedia), m_pageID);
2923 }
2924
2925 #if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK)
2926 void WebPageProxy::handleDownloadRequest(DownloadProxy* download)
2927 {
2928     m_pageClient->handleDownloadRequest(download);
2929 }
2930 #endif // PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK)
2931
2932 #if PLATFORM(QT) || PLATFORM(EFL)
2933 void WebPageProxy::didChangeContentsSize(const IntSize& size)
2934 {
2935     m_pageClient->didChangeContentsSize(size);
2936 }
2937 #endif
2938
2939 #if ENABLE(TOUCH_EVENTS)
2940 void WebPageProxy::needTouchEvents(bool needTouchEvents)
2941 {
2942     m_needTouchEvents = needTouchEvents;
2943 }
2944 #endif
2945
2946 #if ENABLE(INPUT_TYPE_COLOR)
2947 void WebPageProxy::showColorChooser(const WebCore::Color& initialColor, const IntRect& elementRect)
2948 {
2949     ASSERT(!m_colorChooser);
2950
2951     if (m_colorPickerResultListener) {
2952         m_colorPickerResultListener->invalidate();
2953         m_colorPickerResultListener = nullptr;
2954     }
2955
2956     m_colorPickerResultListener = WebColorPickerResultListenerProxy::create(this);
2957     m_colorChooser = WebColorChooserProxy::create(this);
2958
2959     if (m_uiClient.showColorPicker(this, initialColor.serialized(), m_colorPickerResultListener.get()))
2960         return;
2961
2962     m_colorChooser = m_pageClient->createColorChooserProxy(this, initialColor, elementRect);
2963     if (!m_colorChooser)
2964         didEndColorChooser();
2965 }
2966
2967 void WebPageProxy::setColorChooserColor(const WebCore::Color& color)
2968 {
2969     ASSERT(m_colorChooser);
2970
2971     m_colorChooser->setSelectedColor(color);
2972 }
2973
2974 void WebPageProxy::endColorChooser()
2975 {
2976     ASSERT(m_colorChooser);
2977
2978     m_colorChooser->endChooser();
2979 }
2980
2981 void WebPageProxy::didChooseColor(const WebCore::Color& color)
2982 {
2983     if (!isValid())
2984         return;
2985
2986     m_process->send(Messages::WebPage::DidChooseColor(color), m_pageID);
2987 }
2988
2989 void WebPageProxy::didEndColorChooser()
2990 {
2991     if (!isValid())
2992         return;
2993
2994     if (m_colorChooser) {
2995         m_colorChooser->invalidate();
2996         m_colorChooser = nullptr;
2997     }
2998
2999     m_process->send(Messages::WebPage::DidEndColorChooser(), m_pageID);
3000
3001     m_colorPickerResultListener->invalidate();
3002     m_colorPickerResultListener = nullptr;
3003
3004     m_uiClient.hideColorPicker(this);
3005 }
3006 #endif
3007
3008 void WebPageProxy::didDraw()
3009 {
3010     m_uiClient.didDraw(this);
3011 }
3012
3013 // Inspector
3014
3015 #if ENABLE(INSPECTOR)
3016
3017 WebInspectorProxy* WebPageProxy::inspector()
3018 {
3019     if (isClosed() || !isValid())
3020         return 0;
3021     return m_inspector.get();
3022 }
3023
3024 #endif
3025
3026 #if ENABLE(FULLSCREEN_API)
3027 WebFullScreenManagerProxy* WebPageProxy::fullScreenManager()
3028 {
3029     return m_fullScreenManager.get();
3030 }
3031 #endif
3032
3033 // BackForwardList
3034
3035 void WebPageProxy::backForwardAddItem(uint64_t itemID)
3036 {
3037     m_backForwardList->addItem(m_process->webBackForwardItem(itemID));
3038 }
3039
3040 void WebPageProxy::backForwardGoToItem(uint64_t itemID, SandboxExtension::Handle& sandboxExtensionHandle)
3041 {
3042     WebBackForwardListItem* item = m_process->webBackForwardItem(itemID);
3043     if (!item)
3044         return;
3045
3046     bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), item->url()), sandboxExtensionHandle);
3047     if (createdExtension)
3048         m_process->willAcquireUniversalFileReadSandboxExtension();
3049     m_backForwardList->goToItem(item);
3050 }
3051
3052 void WebPageProxy::backForwardItemAtIndex(int32_t index, uint64_t& itemID)
3053 {
3054     WebBackForwardListItem* item = m_backForwardList->itemAtIndex(index);
3055     itemID = item ? item->itemID() : 0;
3056 }
3057
3058 void WebPageProxy::backForwardBackListCount(int32_t& count)
3059 {
3060     count = m_backForwardList->backListCount();
3061 }
3062
3063 void WebPageProxy::backForwardForwardListCount(int32_t& count)
3064 {
3065     count = m_backForwardList->forwardListCount();
3066 }
3067
3068 void WebPageProxy::editorStateChanged(const EditorState& editorState)
3069 {
3070 #if PLATFORM(MAC)
3071     bool couldChangeSecureInputState = m_editorState.isInPasswordField != editorState.isInPasswordField || m_editorState.selectionIsNone;
3072 #endif
3073
3074     m_editorState = editorState;
3075
3076 #if PLATFORM(MAC)
3077     m_pageClient->updateTextInputState(couldChangeSecureInputState);
3078 #elif PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK)
3079     m_pageClient->updateTextInputState();
3080 #endif
3081 }
3082
3083 // Undo management
3084
3085 void WebPageProxy::registerEditCommandForUndo(uint64_t commandID, uint32_t editAction)
3086 {
3087     registerEditCommand(WebEditCommandProxy::create(commandID, static_cast<EditAction>(editAction), this), Undo);
3088 }
3089
3090 void WebPageProxy::canUndoRedo(uint32_t action, bool& result)
3091 {
3092     result = m_pageClient->canUndoRedo(static_cast<UndoOrRedo>(action));
3093 }
3094
3095 void WebPageProxy::executeUndoRedo(uint32_t action, bool& result)
3096 {
3097     m_pageClient->executeUndoRedo(static_cast<UndoOrRedo>(action));
3098     result = true;
3099 }
3100
3101 void WebPageProxy::clearAllEditCommands()
3102 {
3103     m_pageClient->clearAllEditCommands();
3104 }
3105
3106 void WebPageProxy::didCountStringMatches(const String& string, uint32_t matchCount)
3107 {
3108     m_findClient.didCountStringMatches(this, string, matchCount);
3109 }
3110
3111 void WebPageProxy::didGetImageForFindMatch(const ShareableBitmap::Handle& contentImageHandle, uint32_t matchIndex)
3112 {
3113     m_findMatchesClient.didGetImageForMatchResult(this, WebImage::create(ShareableBitmap::create(contentImageHandle)).get(), matchIndex);
3114 }
3115
3116 void WebPageProxy::setFindIndicator(const FloatRect& selectionRectInWindowCoordinates, const Vector<FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle, bool fadeOut, bool animate)
3117 {
3118     RefPtr<FindIndicator> findIndicator = FindIndicator::create(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, contentImageScaleFactor, contentImageHandle);
3119     m_pageClient->setFindIndicator(findIndicator.release(), fadeOut, animate);
3120 }
3121
3122 void WebPageProxy::didFindString(const String& string, uint32_t matchCount)
3123 {
3124     m_findClient.didFindString(this, string, matchCount);
3125 }
3126
3127 void WebPageProxy::didFindStringMatches(const String& string, Vector<Vector<WebCore::IntRect>> matchRects, int32_t firstIndexAfterSelection)
3128 {
3129     Vector<RefPtr<APIObject>> matches;
3130     matches.reserveInitialCapacity(matchRects.size());
3131
3132     for (size_t i = 0; i < matchRects.size(); ++i) {
3133         const Vector<WebCore::IntRect>& rects = matchRects[i];
3134         size_t numRects = matchRects[i].size();
3135         Vector<RefPtr<APIObject>> apiRects;
3136         apiRects.reserveInitialCapacity(numRects);
3137
3138         for (size_t i = 0; i < numRects; ++i)
3139             apiRects.uncheckedAppend(WebRect::create(toAPI(rects[i])));
3140         matches.uncheckedAppend(ImmutableArray::adopt(apiRects));
3141     }
3142     m_findMatchesClient.didFindStringMatches(this, string, ImmutableArray::adopt(matches).get(), firstIndexAfterSelection);
3143 }
3144
3145 void WebPageProxy::didFailToFindString(const String& string)
3146 {
3147     m_findClient.didFailToFindString(this, string);
3148 }
3149
3150 void WebPageProxy::valueChangedForPopupMenu(WebPopupMenuProxy*, int32_t newSelectedIndex)
3151 {
3152     m_process->send(Messages::WebPage::DidChangeSelectedIndexForActivePopupMenu(newSelectedIndex), m_pageID);
3153 }
3154
3155 void WebPageProxy::setTextFromItemForPopupMenu(WebPopupMenuProxy*, int32_t index)
3156 {
3157     m_process->send(Messages::WebPage::SetTextForActivePopupMenu(index), m_pageID);
3158 }
3159
3160 NativeWebMouseEvent* WebPageProxy::currentlyProcessedMouseDownEvent()
3161 {
3162     return m_currentlyProcessedMouseDownEvent.get();
3163 }
3164
3165 void WebPageProxy::postMessageToInjectedBundle(const String& messageName, APIObject* messageBody)
3166 {
3167     process()->send(Messages::WebPage::PostInjectedBundleMessage(messageName, WebContextUserMessageEncoder(messageBody)), m_pageID);
3168 }
3169
3170 #if PLATFORM(GTK)
3171 void WebPageProxy::failedToShowPopupMenu()
3172 {
3173     m_process->send(Messages::WebPage::FailedToShowPopupMenu(), m_pageID);
3174 }
3175 #endif
3176
3177 void WebPageProxy::showPopupMenu(const IntRect& rect, uint64_t textDirection, const Vector<WebPopupItem>& items, int32_t selectedIndex, const PlatformPopupMenuData& data)
3178 {
3179     if (m_activePopupMenu) {
3180 #if PLATFORM(EFL)
3181         m_uiPopupMenuClient.hidePopupMenu(this);
3182 #else
3183         m_activePopupMenu->hidePopupMenu();
3184 #endif
3185         m_activePopupMenu->invalidate();
3186         m_activePopupMenu = 0;
3187     }
3188
3189     m_activePopupMenu = m_pageClient->createPopupMenuProxy(this);
3190
3191     if (!m_activePopupMenu)
3192         return;
3193
3194     // Since showPopupMenu() can spin a nested run loop we need to turn off the responsiveness timer.
3195     m_process->responsivenessTimer()->stop();
3196
3197 #if PLATFORM(EFL)
3198     UNUSED_PARAM(data);
3199     m_uiPopupMenuClient.showPopupMenu(this, m_activePopupMenu.get(), rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, selectedIndex);
3200 #else
3201     RefPtr<WebPopupMenuProxy> protectedActivePopupMenu = m_activePopupMenu;
3202
3203     protectedActivePopupMenu->showPopupMenu(rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, data, selectedIndex);
3204
3205     // Since Qt and Efl doesn't use a nested mainloop to show the popup and get the answer, we need to keep the client pointer valid.
3206 #if !PLATFORM(QT)
3207     protectedActivePopupMenu->invalidate();
3208 #endif
3209     protectedActivePopupMenu = 0;
3210 #endif
3211 }
3212
3213 void WebPageProxy::hidePopupMenu()
3214 {
3215     if (!m_activePopupMenu)
3216         return;
3217
3218 #if PLATFORM(EFL)
3219     m_uiPopupMenuClient.hidePopupMenu(this);
3220 #else
3221     m_activePopupMenu->hidePopupMenu();
3222 #endif
3223     m_activePopupMenu->invalidate();
3224     m_activePopupMenu = 0;
3225 }
3226
3227 #if ENABLE(CONTEXT_MENUS)
3228 void WebPageProxy::showContextMenu(const IntPoint& menuLocation, const WebHitTestResult::Data& hitTestResultData, const Vector<WebContextMenuItemData>& proposedItems, CoreIPC::MessageDecoder& decoder)
3229 {
3230     internalShowContextMenu(menuLocation, hitTestResultData, proposedItems, decoder);
3231     
3232     // No matter the result of internalShowContextMenu, always notify the WebProcess that the menu is hidden so it starts handling mouse events again.
3233     m_process->send(Messages::WebPage::ContextMenuHidden(), m_pageID);
3234 }
3235
3236 void WebPageProxy::internalShowContextMenu(const IntPoint& menuLocation, const WebHitTestResult::Data& hitTestResultData, const Vector<WebContextMenuItemData>& proposedItems, CoreIPC::MessageDecoder& decoder)
3237 {
3238     RefPtr<APIObject> userData;
3239     WebContextUserMessageDecoder messageDecoder(userData, m_process.get());
3240     if (!decoder.decode(messageDecoder))
3241         return;
3242
3243     m_activeContextMenuHitTestResultData = hitTestResultData;
3244
3245     if (!m_contextMenuClient.hideContextMenu(this) && m_activeContextMenu) {
3246         m_activeContextMenu->hideContextMenu();
3247         m_activeContextMenu = 0;
3248     }
3249
3250     m_activeContextMenu = m_pageClient->createContextMenuProxy(this);
3251     if (!m_activeContextMenu)
3252         return;
3253
3254     // Since showContextMenu() can spin a nested run loop we need to turn off the responsiveness timer.
3255     m_process->responsivenessTimer()->stop();
3256
3257     // Give the PageContextMenuClient one last swipe at changing the menu.
3258     Vector<WebContextMenuItemData> items;
3259     if (!m_contextMenuClient.getContextMenuFromProposedMenu(this, proposedItems, items, hitTestResultData, userData.get())) {
3260         if (!m_contextMenuClient.showContextMenu(this, menuLocation, proposedItems))
3261             m_activeContextMenu->showContextMenu(menuLocation, proposedItems);
3262     } else if (!m_contextMenuClient.showContextMenu(this, menuLocation, items))
3263         m_activeContextMenu->showContextMenu(menuLocation, items);
3264     
3265     m_contextMenuClient.contextMenuDismissed(this);
3266 }
3267
3268 void WebPageProxy::contextMenuItemSelected(const WebContextMenuItemData& item)
3269 {
3270     // Application custom items don't need to round-trip through to WebCore in the WebProcess.
3271     if (item.action() >= ContextMenuItemBaseApplicationTag) {
3272         m_contextMenuClient.customContextMenuItemSelected(this, item);
3273         return;
3274     }
3275
3276 #if PLATFORM(MAC)
3277     if (item.action() == ContextMenuItemTagSmartCopyPaste) {
3278         setSmartInsertDeleteEnabled(!isSmartInsertDeleteEnabled());
3279         return;
3280     }
3281     if (item.action() == ContextMenuItemTagSmartQuotes) {
3282         TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled);
3283         m_process->updateTextCheckerState();
3284         return;
3285     }
3286     if (item.action() == ContextMenuItemTagSmartDashes) {
3287         TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled);
3288         m_process->updateTextCheckerState();
3289         return;
3290     }
3291     if (item.action() == ContextMenuItemTagSmartLinks) {
3292         TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled);
3293         m_process->updateTextCheckerState();
3294         return;
3295     }
3296     if (item.action() == ContextMenuItemTagTextReplacement) {
3297         TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled);
3298         m_process->updateTextCheckerState();
3299         return;
3300     }
3301     if (item.action() == ContextMenuItemTagCorrectSpellingAutomatically) {
3302         TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled);
3303         m_process->updateTextCheckerState();
3304         return;        
3305     }
3306     if (item.action() == ContextMenuItemTagShowSubstitutions) {
3307         TextChecker::toggleSubstitutionsPanelIsShowing();
3308         return;
3309     }
3310 #endif
3311     if (item.action() == ContextMenuItemTagDownloadImageToDisk) {
3312         m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteImageURL));
3313         return;    
3314     }
3315     if (item.action() == ContextMenuItemTagDownloadLinkToDisk) {
3316         m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteLinkURL));
3317         return;
3318     }
3319     if (item.action() == ContextMenuItemTagCheckSpellingWhileTyping) {
3320         TextChecker::setContinuousSpellCheckingEnabled(!TextChecker::state().isContinuousSpellCheckingEnabled);
3321         m_process->updateTextCheckerState();
3322         return;
3323     }
3324     if (item.action() == ContextMenuItemTagCheckGrammarWithSpelling) {
3325         TextChecker::setGrammarCheckingEnabled(!TextChecker::state().isGrammarCheckingEnabled);
3326         m_process->updateTextCheckerState();
3327         return;
3328     }
3329     if (item.action() == ContextMenuItemTagShowSpellingPanel) {
3330         if (!TextChecker::spellingUIIsShowing())
3331             advanceToNextMisspelling(true);
3332         TextChecker::toggleSpellingUIIsShowing();
3333         return;
3334     }
3335     if (item.action() == ContextMenuItemTagLearnSpelling || item.action() == ContextMenuItemTagIgnoreSpelling)
3336         ++m_pendingLearnOrIgnoreWordMessageCount;
3337
3338     m_process->send(Messages::WebPage::DidSelectItemFromActiveContextMenu(item), m_pageID);
3339 }
3340 #endif // ENABLE(CONTEXT_MENUS)
3341
3342 void WebPageProxy::didChooseFilesForOpenPanel(const Vector<String>& fileURLs)
3343 {
3344     if (!isValid())
3345         return;
3346
3347 #if ENABLE(WEB_PROCESS_SANDBOX)
3348     // FIXME: The sandbox extensions should be sent with the DidChooseFilesForOpenPanel message. This
3349     // is gated on a way of passing SandboxExtension::Handles in a Vector.
3350     for (size_t i = 0; i < fileURLs.size(); ++i) {
3351         SandboxExtension::Handle sandboxExtensionHandle;
3352         SandboxExtension::createHandle(fileURLs[i], SandboxExtension::ReadOnly, sandboxExtensionHandle);
3353         m_process->send(Messages::WebPage::ExtendSandboxForFileFromOpenPanel(sandboxExtensionHandle), m_pageID);
3354     }
3355 #endif
3356
3357     m_process->send(Messages::WebPage::DidChooseFilesForOpenPanel(fileURLs), m_pageID);
3358
3359     m_openPanelResultListener->invalidate();
3360     m_openPanelResultListener = 0;
3361 }
3362
3363 void WebPageProxy::didCancelForOpenPanel()
3364 {
3365     if (!isValid())
3366         return;
3367
3368     m_process->send(Messages::WebPage::DidCancelForOpenPanel(), m_pageID);
3369     
3370     m_openPanelResultListener->invalidate();
3371     m_openPanelResultListener = 0;
3372 }
3373
3374 void WebPageProxy::advanceToNextMisspelling(bool startBeforeSelection) const
3375 {
3376     m_process->send(Messages::WebPage::AdvanceToNextMisspelling(startBeforeSelection), m_pageID);
3377 }
3378
3379 void WebPageProxy::changeSpellingToWord(const String& word) const
3380 {
3381     if (word.isEmpty())
3382         return;
3383
3384     m_process->send(Messages::WebPage::ChangeSpellingToWord(word), m_pageID);
3385 }
3386
3387 void WebPageProxy::registerEditCommand(PassRefPtr<WebEditCommandProxy> commandProxy, UndoOrRedo undoOrRedo)
3388 {
3389     m_pageClient->registerEditCommand(commandProxy, undoOrRedo);
3390 }
3391
3392 void WebPageProxy::addEditCommand(WebEditCommandProxy* command)
3393 {
3394     m_editCommandSet.add(command);
3395 }
3396
3397 void WebPageProxy::removeEditCommand(WebEditCommandProxy* command)
3398 {
3399     m_editCommandSet.remove(command);
3400
3401     if (!isValid())
3402         return;
3403     m_process->send(Messages::WebPage::DidRemoveEditCommand(command->commandID()), m_pageID);
3404 }
3405
3406 bool WebPageProxy::isValidEditCommand(WebEditCommandProxy* command)
3407 {
3408     return m_editCommandSet.find(command) != m_editCommandSet.end();
3409 }
3410
3411 int64_t WebPageProxy::spellDocumentTag()
3412 {
3413     if (!m_hasSpellDocumentTag) {
3414         m_spellDocumentTag = TextChecker::uniqueSpellDocumentTag(this);
3415         m_hasSpellDocumentTag = true;
3416     }
3417
3418     return m_spellDocumentTag;
3419 }
3420
3421 #if USE(UNIFIED_TEXT_CHECKING)
3422 void WebPageProxy::checkTextOfParagraph(const String& text, uint64_t checkingTypes, Vector<TextCheckingResult>& results)
3423 {
3424     results = TextChecker::checkTextOfParagraph(spellDocumentTag(), text.characters(), text.length(), checkingTypes);
3425 }
3426 #endif
3427
3428 void WebPageProxy::checkSpellingOfString(const String& text, int32_t& misspellingLocation, int32_t& misspellingLength)
3429 {
3430     TextChecker::checkSpellingOfString(spellDocumentTag(), text.characters(), text.length(), misspellingLocation, misspellingLength);
3431 }
3432
3433 void WebPageProxy::checkGrammarOfString(const String& text, Vector<GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength)
3434 {
3435     TextChecker::checkGrammarOfString(spellDocumentTag(), text.characters(), text.length(), grammarDetails, badGrammarLocation, badGrammarLength);
3436 }
3437
3438 void WebPageProxy::spellingUIIsShowing(bool& isShowing)
3439 {
3440     isShowing = TextChecker::spellingUIIsShowing();
3441 }
3442
3443 void WebPageProxy::updateSpellingUIWithMisspelledWord(const String& misspelledWord)
3444 {
3445     TextChecker::updateSpellingUIWithMisspelledWord(spellDocumentTag(), misspelledWord);
3446 }
3447
3448 void WebPageProxy::updateSpellingUIWithGrammarString(const String& badGrammarPhrase, const GrammarDetail& grammarDetail)
3449 {
3450     TextChecker::updateSpellingUIWithGrammarString(spellDocumentTag(), badGrammarPhrase, grammarDetail);
3451 }
3452
3453 void WebPageProxy::getGuessesForWord(const String& word, const String& context, Vector<String>& guesses)
3454 {
3455     TextChecker::getGuessesForWord(spellDocumentTag(), word, context, guesses);
3456 }
3457
3458 void WebPageProxy::learnWord(const String& word)
3459 {
3460     MESSAGE_CHECK(m_pendingLearnOrIgnoreWordMessageCount);
3461     --m_pendingLearnOrIgnoreWordMessageCount;
3462
3463     TextChecker::learnWord(spellDocumentTag(), word);
3464 }
3465
3466 void WebPageProxy::ignoreWord(const String& word)
3467 {
3468     MESSAGE_CHECK(m_pendingLearnOrIgnoreWordMessageCount);
3469     --m_pendingLearnOrIgnoreWordMessageCount;
3470
3471     TextChecker::ignoreWord(spellDocumentTag(), word);
3472 }
3473
3474 void WebPageProxy::requestCheckingOfString(uint64_t requestID, const TextCheckingRequestData& request)
3475 {
3476     TextChecker::requestCheckingOfString(TextCheckerCompletion::create(requestID, request, this));
3477 }
3478
3479 void WebPageProxy::didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>& result) const
3480 {
3481     m_process->send(Messages::WebPage::DidFinishCheckingText(requestID, result), m_pageID);
3482 }
3483
3484 void WebPageProxy::didCancelCheckingText(uint64_t requestID) const
3485 {
3486     m_process->send(Messages::WebPage::DidCancelCheckingText(requestID), m_pageID);
3487 }
3488 // Other
3489
3490 void WebPageProxy::setFocus(bool focused)
3491 {
3492     if (focused)
3493         m_uiClient.focus(this);
3494     else
3495         m_uiClient.unfocus(this);
3496 }
3497
3498 void WebPageProxy::takeFocus(uint32_t direction)
3499 {
3500     m_uiClient.takeFocus(this, (static_cast<FocusDirection>(direction) == FocusDirectionForward) ? kWKFocusDirectionForward : kWKFocusDirectionBackward);
3501 }
3502
3503 void WebPageProxy::setToolTip(const String& toolTip)
3504 {
3505     String oldToolTip = m_toolTip;
3506     m_toolTip = toolTip;
3507     m_pageClient->toolTipChanged(oldToolTip, m_toolTip);
3508 }
3509
3510 void WebPageProxy::setCursor(const WebCore::Cursor& cursor)
3511 {
3512     // The Web process may have asked to change the cursor when the view was in an active window, but
3513     // if it is no longer in a window or the window is not active, then the cursor should not change.
3514     if (m_pageClient->isViewWindowActive())
3515         m_pageClient->setCursor(cursor);
3516 }
3517
3518 void WebPageProxy::setCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves)
3519 {
3520     m_pageClient->setCursorHiddenUntilMouseMoves(hiddenUntilMouseMoves);
3521 }
3522
3523 void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled)
3524 {
3525     WebEvent::Type type = static_cast<WebEvent::Type>(opaqueType);
3526
3527     switch (type) {
3528     case WebEvent::NoType:
3529     case WebEvent::MouseMove:
3530         break;
3531
3532     case WebEvent::MouseDown:
3533     case WebEvent::MouseUp:
3534     case WebEvent::Wheel:
3535     case WebEvent::KeyDown:
3536     case WebEvent::KeyUp:
3537     case WebEvent::RawKeyDown:
3538     case WebEvent::Char:
3539 #if ENABLE(GESTURE_EVENTS)
3540     case WebEvent::GestureScrollBegin:
3541     case WebEvent::GestureScrollEnd:
3542     case WebEvent::GestureSingleTap:
3543 #endif
3544 #if ENABLE(TOUCH_EVENTS)
3545     case WebEvent::TouchStart:
3546     case WebEvent::TouchMove:
3547     case WebEvent::TouchEnd:
3548     case WebEvent::TouchCancel:
3549 #endif
3550         m_process->responsivenessTimer()->stop();
3551         break;
3552     }
3553
3554     switch (type) {
3555     case WebEvent::NoType:
3556         break;
3557     case WebEvent::MouseMove:
3558         m_processingMouseMoveEvent = false;
3559         if (m_nextMouseMoveEvent) {
3560             handleMouseEvent(*m_nextMouseMoveEvent);
3561             m_nextMouseMoveEvent = nullptr;
3562         }
3563         break;
3564     case WebEvent::MouseDown:
3565         break;
3566 #if ENABLE(GESTURE_EVENTS)
3567     case WebEvent::GestureScrollBegin:
3568     case WebEvent::GestureScrollEnd:
3569     case WebEvent::GestureSingleTap: {
3570         WebGestureEvent event = m_gestureEventQueue.first();
3571         MESSAGE_CHECK(type == event.type());
3572
3573         m_gestureEventQueue.removeFirst();
3574         m_pageClient->doneWithGestureEvent(event, handled);
3575         break;
3576     }
3577 #endif
3578     case WebEvent::MouseUp:
3579         m_currentlyProcessedMouseDownEvent = nullptr;
3580         break;
3581
3582     case WebEvent::Wheel: {
3583         ASSERT(!m_currentlyProcessedWheelEvents.isEmpty());
3584
3585         OwnPtr<Vector<NativeWebWheelEvent>> oldestCoalescedEvent = m_currentlyProcessedWheelEvents.takeFirst();
3586
3587         // FIXME: Dispatch additional events to the didNotHandleWheelEvent client function.
3588         if (!handled && m_uiClient.implementsDidNotHandleWheelEvent())
3589             m_uiClient.didNotHandleWheelEvent(this, oldestCoalescedEvent->last());
3590
3591         if (!m_wheelEventQueue.isEmpty())
3592             processNextQueuedWheelEvent();
3593         break;
3594     }
3595
3596     case WebEvent::KeyDown:
3597     case WebEvent::KeyUp:
3598     case WebEvent::RawKeyDown:
3599     case WebEvent::Char: {
3600         LOG(KeyHandling, "WebPageProxy::didReceiveEvent: %s", webKeyboardEventTypeString(type));
3601
3602         NativeWebKeyboardEvent event = m_keyEventQueue.first();
3603         MESSAGE_CHECK(type == event.type());
3604
3605         m_keyEventQueue.removeFirst();
3606
3607         if (!m_keyEventQueue.isEmpty())
3608             m_process->send(Messages::WebPage::KeyEvent(m_keyEventQueue.first()), m_pageID);
3609
3610         m_pageClient->doneWithKeyEvent(event, handled);
3611         if (handled)
3612             break;
3613
3614         if (m_uiClient.implementsDidNotHandleKeyEvent())
3615             m_uiClient.didNotHandleKeyEvent(this, event);
3616         break;
3617     }
3618 #if ENABLE(TOUCH_EVENTS)
3619     case WebEvent::TouchStart:
3620     case WebEvent::TouchMove:
3621     case WebEvent::TouchEnd:
3622     case WebEvent::TouchCancel: {
3623         QueuedTouchEvents queuedEvents = m_touchEventQueue.first();
3624         MESSAGE_CHECK(type == queuedEvents.forwardedEvent.type());
3625         m_touchEventQueue.removeFirst();
3626
3627         m_pageClient->doneWithTouchEvent(queuedEvents.forwardedEvent, handled);
3628         for (size_t i = 0; i < queuedEvents.deferredTouchEvents.size(); ++i) {
3629             bool isEventHandled = false;
3630             m_pageClient->doneWithTouchEvent(queuedEvents.deferredTouchEvents.at(i), isEventHandled);
3631         }
3632         break;
3633     }
3634 #endif
3635     }
3636 }
3637
3638 void WebPageProxy::stopResponsivenessTimer()
3639 {
3640     m_process->responsivenessTimer()->stop();
3641 }
3642
3643 void WebPageProxy::voidCallback(uint64_t callbackID)