Rename deviceDPI to devicePixelRatio https://bugs.webkit.org/show_bug.cgi?id=85049
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / WebPage.cpp
1 /*
2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "WebPage.h"
28
29 #include "Arguments.h"
30 #include "DataReference.h"
31 #include "DecoderAdapter.h"
32 #include "DrawingArea.h"
33 #include "InjectedBundle.h"
34 #include "InjectedBundleBackForwardList.h"
35 #include "LayerTreeHost.h"
36 #include "MessageID.h"
37 #include "NetscapePlugin.h"
38 #include "NotificationPermissionRequestManager.h"
39 #include "PageOverlay.h"
40 #include "PluginProxy.h"
41 #include "PluginView.h"
42 #include "PrintInfo.h"
43 #include "SessionState.h"
44 #include "ShareableBitmap.h"
45 #include "WebAlternativeTextClient.h"
46 #include "WebBackForwardList.h"
47 #include "WebBackForwardListItem.h"
48 #include "WebBackForwardListProxy.h"
49 #include "WebChromeClient.h"
50 #include "WebContextMenu.h"
51 #include "WebContextMenuClient.h"
52 #include "WebContextMessages.h"
53 #include "WebCoreArgumentCoders.h"
54 #include "WebDragClient.h"
55 #include "WebEditorClient.h"
56 #include "WebEvent.h"
57 #include "WebEventConversion.h"
58 #include "WebFrame.h"
59 #include "WebFullScreenManager.h"
60 #include "WebGeolocationClient.h"
61 #include "WebGeometry.h"
62 #include "WebImage.h"
63 #include "WebInspector.h"
64 #include "WebInspectorClient.h"
65 #include "WebNotificationClient.h"
66 #include "WebOpenPanelResultListener.h"
67 #include "WebPageCreationParameters.h"
68 #include "WebPageGroupProxy.h"
69 #include "WebPageProxyMessages.h"
70 #include "WebPopupMenu.h"
71 #include "WebPreferencesStore.h"
72 #include "WebProcess.h"
73 #include "WebProcessProxyMessages.h"
74 #include <JavaScriptCore/APICast.h>
75 #include <WebCore/AbstractDatabase.h>
76 #include <WebCore/ArchiveResource.h>
77 #include <WebCore/Chrome.h>
78 #include <WebCore/ContextMenuController.h>
79 #include <WebCore/DocumentFragment.h>
80 #include <WebCore/DocumentLoader.h>
81 #include <WebCore/DocumentMarkerController.h>
82 #include <WebCore/DragController.h>
83 #include <WebCore/DragData.h>
84 #include <WebCore/DragSession.h>
85 #include <WebCore/EventHandler.h>
86 #include <WebCore/FocusController.h>
87 #include <WebCore/FormState.h>
88 #include <WebCore/Frame.h>
89 #include <WebCore/FrameLoadRequest.h>
90 #include <WebCore/FrameLoaderTypes.h>
91 #include <WebCore/FrameView.h>
92 #include <WebCore/HTMLFormElement.h>
93 #include <WebCore/HTMLInputElement.h>
94 #include <WebCore/HistoryItem.h>
95 #include <WebCore/KeyboardEvent.h>
96 #include <WebCore/MouseEvent.h>
97 #include <WebCore/Page.h>
98 #include <WebCore/PlatformKeyboardEvent.h>
99 #include <WebCore/PluginDocument.h>
100 #include <WebCore/PrintContext.h>
101 #include <WebCore/RenderLayer.h>
102 #include <WebCore/RenderTreeAsText.h>
103 #include <WebCore/RenderView.h>
104 #include <WebCore/ResourceRequest.h>
105 #include <WebCore/RunLoop.h>
106 #include <WebCore/SchemeRegistry.h>
107 #include <WebCore/ScriptValue.h>
108 #include <WebCore/SerializedScriptValue.h>
109 #include <WebCore/Settings.h>
110 #include <WebCore/SharedBuffer.h>
111 #include <WebCore/SubstituteData.h>
112 #include <WebCore/TextIterator.h>
113 #include <WebCore/markup.h>
114 #include <runtime/JSLock.h>
115 #include <runtime/JSValue.h>
116
117 #include <WebCore/Range.h>
118 #include <WebCore/VisiblePosition.h>
119
120 #if ENABLE(PLUGIN_PROCESS)
121 #if PLATFORM(MAC)
122 #include "MachPort.h"
123 #endif
124 #endif
125
126 #if PLATFORM(MAC)
127 #include "BuiltInPDFView.h"
128 #endif
129
130 #if PLATFORM(QT)
131 #if ENABLE(DEVICE_ORIENTATION)
132 #include "DeviceMotionClientQt.h"
133 #include "DeviceOrientationClientQt.h"
134 #endif
135 #include "HitTestResult.h"
136 #include <QMimeData>
137 #endif
138
139 #if PLATFORM(GTK)
140 #include <gtk/gtk.h>
141 #include "DataObjectGtk.h"
142 #include "WebPrintOperationGtk.h"
143 #endif
144
145 #ifndef NDEBUG
146 #include <wtf/RefCountedLeakCounter.h>
147 #endif
148
149 using namespace JSC;
150 using namespace WebCore;
151 using namespace std;
152
153 namespace WebKit {
154
155 class SendStopResponsivenessTimer {
156 public:
157     SendStopResponsivenessTimer(WebPage* page)
158         : m_page(page)
159     {
160     }
161     
162     ~SendStopResponsivenessTimer()
163     {
164         m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
165     }
166
167 private:
168     WebPage* m_page;
169 };
170
171 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
172
173 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
174 {
175     RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
176
177     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
178         WebProcess::shared().injectedBundle()->didCreatePage(page.get());
179
180     return page.release();
181 }
182
183 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
184     : m_viewSize(parameters.viewSize)
185     , m_useFixedLayout(false)
186     , m_drawsBackground(true)
187     , m_drawsTransparentBackground(false)
188     , m_isInRedo(false)
189     , m_isClosed(false)
190     , m_tabToLinks(false)
191 #if PLATFORM(MAC)
192     , m_windowIsVisible(false)
193     , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
194     , m_layerHostingMode(LayerHostingModeDefault)
195     , m_keyboardEventBeingInterpreted(0)
196 #elif PLATFORM(WIN)
197     , m_nativeWindow(parameters.nativeWindow)
198 #elif PLATFORM(GTK)
199     , m_accessibilityObject(0)
200 #endif
201     , m_setCanStartMediaTimer(WebProcess::shared().runLoop(), this, &WebPage::setCanStartMediaTimerFired)
202     , m_findController(this)
203 #if ENABLE(TOUCH_EVENTS)
204 #if PLATFORM(QT)
205     , m_tapHighlightController(this)
206 #endif
207 #endif
208 #if ENABLE(GEOLOCATION)
209     , m_geolocationPermissionRequestManager(this)
210 #endif
211     , m_pageID(pageID)
212     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
213     , m_canRunModal(parameters.canRunModal)
214     , m_isRunningModal(false)
215     , m_cachedMainFrameIsPinnedToLeftSide(false)
216     , m_cachedMainFrameIsPinnedToRightSide(false)
217     , m_canShortCircuitHorizontalWheelEvents(false)
218     , m_numWheelEventHandlers(0)
219     , m_cachedPageCount(0)
220 #if ENABLE(CONTEXT_MENUS)
221     , m_isShowingContextMenu(false)
222 #endif
223     , m_willGoToBackForwardItemCallbackEnabled(true)
224 #if PLATFORM(WIN)
225     , m_gestureReachedScrollingLimit(false)
226 #endif
227 {
228     ASSERT(m_pageID);
229     // FIXME: This is a non-ideal location for this Setting and
230     // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
231     Settings::setDefaultMinDOMTimerInterval(0.004);
232
233     Page::PageClients pageClients;
234     pageClients.chromeClient = new WebChromeClient(this);
235 #if ENABLE(CONTEXT_MENUS)
236     pageClients.contextMenuClient = new WebContextMenuClient(this);
237 #endif
238     pageClients.editorClient = new WebEditorClient(this);
239     pageClients.dragClient = new WebDragClient(this);
240     pageClients.backForwardClient = WebBackForwardListProxy::create(this);
241 #if ENABLE(INSPECTOR)
242     pageClients.inspectorClient = new WebInspectorClient(this);
243 #endif
244 #if USE(AUTOCORRECTION_PANEL)
245     pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
246 #endif
247     
248     m_page = adoptPtr(new Page(pageClients));
249
250 #if ENABLE(GEOLOCATION)
251     WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
252 #endif
253 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(QT)
254     WebCore::provideDeviceMotionTo(m_page.get(), new DeviceMotionClientQt);
255     WebCore::provideDeviceOrientationTo(m_page.get(), new DeviceOrientationClientQt);
256 #endif
257 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
258     WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
259 #endif
260
261     // Qt does not yet call setIsInWindow. Until it does, just leave
262     // this line out so plug-ins and video will work. Eventually all platforms
263     // should call setIsInWindow and this comment and #if should be removed,
264     // leaving behind the setCanStartMedia call.
265 #if !PLATFORM(QT)
266     m_page->setCanStartMedia(false);
267 #endif
268
269     updatePreferences(parameters.store);
270
271     m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
272     m_page->setGroupName(m_pageGroup->identifier());
273
274     platformInitialize();
275
276     m_drawingArea = DrawingArea::create(this, parameters);
277     m_drawingArea->setPaintingEnabled(false);
278
279     m_mainFrame = WebFrame::createMainFrame(this);
280
281     setUseFixedLayout(parameters.useFixedLayout);
282
283     setDrawsBackground(parameters.drawsBackground);
284     setDrawsTransparentBackground(parameters.drawsTransparentBackground);
285
286     setPaginationMode(parameters.paginationMode);
287     setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
288     setPageLength(parameters.pageLength);
289     setGapBetweenPages(parameters.gapBetweenPages);
290
291     setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
292
293     setActive(parameters.isActive);
294     setFocused(parameters.isFocused);
295     setIsInWindow(parameters.isInWindow);
296
297     m_userAgent = parameters.userAgent;
298
299     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
300     
301     if (!parameters.sessionState.isEmpty())
302         restoreSession(parameters.sessionState);
303
304     m_drawingArea->setPaintingEnabled(true);
305     
306     setMediaVolume(parameters.mediaVolume);
307
308 #ifndef NDEBUG
309     webPageCounter.increment();
310 #endif
311 }
312
313 WebPage::~WebPage()
314 {
315     if (m_backForwardList)
316         m_backForwardList->detach();
317
318     ASSERT(!m_page);
319
320     m_sandboxExtensionTracker.invalidate();
321
322 #if PLATFORM(MAC)
323     ASSERT(m_pluginViews.isEmpty());
324 #endif
325
326 #ifndef NDEBUG
327     webPageCounter.decrement();
328 #endif
329 }
330
331 void WebPage::dummy(bool&)
332 {
333 }
334
335 CoreIPC::Connection* WebPage::connection() const
336 {
337     return WebProcess::shared().connection();
338 }
339
340 #if ENABLE(CONTEXT_MENUS)
341 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
342 {
343     m_contextMenuClient.initialize(client);
344 }
345 #endif
346
347 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
348 {
349     m_editorClient.initialize(client);
350 }
351
352 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
353 {
354     m_formClient.initialize(client);
355 }
356
357 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
358 {
359     m_loaderClient.initialize(client);
360 }
361
362 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
363 {
364     m_policyClient.initialize(client);
365 }
366
367 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
368 {
369     m_resourceLoadClient.initialize(client);
370 }
371
372 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
373 {
374     m_uiClient.initialize(client);
375 }
376
377 #if ENABLE(FULLSCREEN_API)
378 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
379 {
380     m_fullScreenClient.initialize(client);
381 }
382 #endif
383
384 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, const Plugin::Parameters& parameters)
385 {
386     String pluginPath;
387
388     if (!WebProcess::shared().connection()->sendSync(
389             Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()), 
390             Messages::WebContext::GetPluginPath::Reply(pluginPath), 0)) {
391         return 0;
392     }
393
394     if (pluginPath.isNull()) {
395 #if PLATFORM(MAC)
396         if (parameters.mimeType == "application/pdf"
397             || (parameters.mimeType.isEmpty() && parameters.url.path().lower().endsWith(".pdf")))
398             return BuiltInPDFView::create(frame);
399 #else
400         UNUSED_PARAM(frame);
401 #endif
402         return 0;
403     }
404
405 #if ENABLE(PLUGIN_PROCESS)
406     return PluginProxy::create(pluginPath);
407 #else
408     NetscapePlugin::setSetExceptionFunction(NPRuntimeObjectMap::setGlobalException);
409     return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
410 #endif
411 }
412
413 EditorState WebPage::editorState() const
414 {
415     Frame* frame = m_page->focusController()->focusedOrMainFrame();
416     ASSERT(frame);
417
418     EditorState result;
419     result.selectionIsNone = frame->selection()->isNone();
420     result.selectionIsRange = frame->selection()->isRange();
421     result.isContentEditable = frame->selection()->isContentEditable();
422     result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
423     result.isInPasswordField = frame->selection()->isInPasswordField();
424     result.hasComposition = frame->editor()->hasComposition();
425     result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
426
427 #if PLATFORM(QT)
428     size_t location = 0;
429     size_t length = 0;
430
431     Element* selectionRoot = frame->selection()->rootEditableElement();
432     Element* scope = selectionRoot ? selectionRoot : frame->document()->documentElement();
433
434     if (!scope)
435         return result;
436
437     if (scope->hasTagName(HTMLNames::inputTag)) {
438         HTMLInputElement* input = static_cast<HTMLInputElement*>(scope);
439         if (input->isTelephoneField())
440             result.inputMethodHints |= Qt::ImhDialableCharactersOnly;
441         else if (input->isNumberField())
442             result.inputMethodHints |= Qt::ImhDigitsOnly;
443         else if (input->isEmailField()) {
444             result.inputMethodHints |= Qt::ImhEmailCharactersOnly;
445             result.inputMethodHints |= Qt::ImhNoAutoUppercase;
446         } else if (input->isURLField()) {
447             result.inputMethodHints |= Qt::ImhUrlCharactersOnly;
448             result.inputMethodHints |= Qt::ImhNoAutoUppercase;
449         } else if (input->isPasswordField()) {
450             // Set ImhHiddenText flag for password fields. The Qt platform
451             // is responsible for determining which widget will receive input
452             // method events for password fields.
453             result.inputMethodHints |= Qt::ImhHiddenText;
454             result.inputMethodHints |= Qt::ImhNoAutoUppercase;
455             result.inputMethodHints |= Qt::ImhNoPredictiveText;
456             result.inputMethodHints |= Qt::ImhSensitiveData;
457         }
458     }
459
460     if (selectionRoot)
461         result.editorRect = frame->view()->contentsToWindow(selectionRoot->getPixelSnappedRect());
462
463     RefPtr<Range> range;
464     if (result.hasComposition && (range = frame->editor()->compositionRange())) {
465         frame->editor()->getCompositionSelection(result.anchorPosition, result.cursorPosition);
466
467         result.compositionRect = frame->view()->contentsToWindow(range->boundingBox());
468     }
469
470     if (!result.hasComposition && !result.selectionIsNone && (range = frame->selection()->selection().firstRange())) {
471         TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
472         bool baseIsFirst = frame->selection()->selection().isBaseFirst();
473
474         result.cursorPosition = (baseIsFirst) ? location + length : location;
475         result.anchorPosition = (baseIsFirst) ? location : location + length;
476         result.selectedText = range->text();
477     }
478
479     if (range)
480         result.cursorRect = frame->view()->contentsToWindow(frame->editor()->firstRectForRange(range.get()));
481
482     // FIXME: We should only transfer innerText when it changes and do this on the UI side.
483     if (result.isContentEditable && !result.isInPasswordField) {
484         result.surroundingText = scope->innerText();
485         if (result.hasComposition) {
486             // The anchor is always the left position when they represent a composition.
487             result.surroundingText.remove(result.anchorPosition, result.cursorPosition - result.anchorPosition);
488         }
489     }
490 #endif
491
492     return result;
493 }
494
495 String WebPage::renderTreeExternalRepresentation() const
496 {
497     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
498 }
499
500 uint64_t WebPage::renderTreeSize() const
501 {
502     if (!m_page)
503         return 0;
504     return m_page->renderTreeSize();
505 }
506
507 void WebPage::setPaintedObjectsCounterThreshold(uint64_t threshold)
508 {
509     if (!m_page)
510         return;
511     m_page->setRelevantRepaintedObjectsCounterThreshold(threshold);
512 }
513
514 void WebPage::setTracksRepaints(bool trackRepaints)
515 {
516     if (FrameView* view = mainFrameView())
517         view->setTracksRepaints(trackRepaints);
518 }
519
520 bool WebPage::isTrackingRepaints() const
521 {
522     if (FrameView* view = mainFrameView())
523         return view->isTrackingRepaints();
524
525     return false;
526 }
527
528 void WebPage::resetTrackedRepaints()
529 {
530     if (FrameView* view = mainFrameView())
531         view->resetTrackedRepaints();
532 }
533
534 PassRefPtr<ImmutableArray> WebPage::trackedRepaintRects()
535 {
536     FrameView* view = mainFrameView();
537     if (!view)
538         return ImmutableArray::create();
539
540     const Vector<IntRect>& rects = view->trackedRepaintRects();
541     size_t size = rects.size();
542     if (!size)
543         return ImmutableArray::create();
544
545     Vector<RefPtr<APIObject> > vector;
546     vector.reserveInitialCapacity(size);
547
548     for (size_t i = 0; i < size; ++i)
549         vector.uncheckedAppend(WebRect::create(toAPI(rects[i])));
550
551     return ImmutableArray::adopt(vector);
552 }
553
554 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
555 {
556     Frame* frame = m_page->focusController()->focusedOrMainFrame();
557     if (!frame)
558         return;
559     frame->editor()->command(commandName).execute(argument);
560 }
561
562 bool WebPage::isEditingCommandEnabled(const String& commandName)
563 {
564     Frame* frame = m_page->focusController()->focusedOrMainFrame();
565     if (!frame)
566         return false;
567     
568     Editor::Command command = frame->editor()->command(commandName);
569     return command.isSupported() && command.isEnabled();
570 }
571     
572 void WebPage::clearMainFrameName()
573 {
574     if (Frame* frame = mainFrame())
575         frame->tree()->clearName();
576 }
577
578 #if USE(ACCELERATED_COMPOSITING)
579 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
580 {
581     m_drawingArea->setRootCompositingLayer(layer);
582 }
583
584 void WebPage::exitAcceleratedCompositingMode()
585 {
586     m_drawingArea->setRootCompositingLayer(0);
587 }
588 #endif
589
590 void WebPage::close()
591 {
592     if (m_isClosed)
593         return;
594
595     m_isClosed = true;
596
597     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
598         WebProcess::shared().injectedBundle()->willDestroyPage(this);
599
600 #if ENABLE(INSPECTOR)
601     m_inspector = 0;
602 #endif
603 #if ENABLE(FULLSCREEN_API)
604     m_fullScreenManager = 0;
605 #endif
606
607     if (m_activePopupMenu) {
608         m_activePopupMenu->disconnectFromPage();
609         m_activePopupMenu = 0;
610     }
611
612     if (m_activeOpenPanelResultListener) {
613         m_activeOpenPanelResultListener->disconnectFromPage();
614         m_activeOpenPanelResultListener = 0;
615     }
616
617     m_sandboxExtensionTracker.invalidate();
618
619     m_underlayPage = nullptr;
620     m_printContext = nullptr;
621     m_mainFrame->coreFrame()->loader()->detachFromParent();
622     m_page = nullptr;
623     m_drawingArea = nullptr;
624
625     bool isRunningModal = m_isRunningModal;
626     m_isRunningModal = false;
627
628     // The WebPage can be destroyed by this call.
629     WebProcess::shared().removeWebPage(m_pageID);
630
631     if (isRunningModal)
632         WebProcess::shared().runLoop()->stop();
633 }
634
635 void WebPage::tryClose()
636 {
637     SendStopResponsivenessTimer stopper(this);
638
639     if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
640         send(Messages::WebPageProxy::StopResponsivenessTimer());
641         return;
642     }
643
644     send(Messages::WebPageProxy::ClosePage(true));
645 }
646
647 void WebPage::sendClose()
648 {
649     send(Messages::WebPageProxy::ClosePage(false));
650 }
651
652 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
653 {
654     loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
655 }
656
657 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
658 {
659     SendStopResponsivenessTimer stopper(this);
660
661     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
662     m_mainFrame->coreFrame()->loader()->load(request, false);
663 }
664
665 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
666 {
667     SendStopResponsivenessTimer stopper(this);
668
669     ResourceRequest request(baseURL);
670     SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
671     m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
672 }
673
674 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
675 {
676     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
677     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
678     loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
679 }
680
681 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
682 {
683     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
684     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
685     KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
686     loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
687 }
688
689 void WebPage::loadPlainTextString(const String& string)
690 {
691     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
692     loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
693 }
694
695 void WebPage::loadWebArchiveData(const CoreIPC::DataReference& webArchiveData)
696 {
697     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
698     loadData(sharedBuffer, "application/x-webarchive", "utf-16", blankURL(), KURL());
699 }
700
701 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
702 {
703     Frame* frame = m_page->mainFrame();
704     if (!frame)
705         return;
706
707     RefPtr<Event> coreEvent;
708     if (event.type() != WebEvent::NoType)
709         coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
710
711     frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)), 
712         false, false, coreEvent.get(), 0, MaybeSendReferrer);
713 }
714
715 void WebPage::stopLoadingFrame(uint64_t frameID)
716 {
717     WebFrame* frame = WebProcess::shared().webFrame(frameID);
718     if (!frame)
719         return;
720
721     frame->coreFrame()->loader()->stopForUserCancel();
722 }
723
724 void WebPage::stopLoading()
725 {
726     SendStopResponsivenessTimer stopper(this);
727
728     m_mainFrame->coreFrame()->loader()->stopForUserCancel();
729 }
730
731 void WebPage::setDefersLoading(bool defersLoading)
732 {
733     m_page->setDefersLoading(defersLoading);
734 }
735
736 void WebPage::reload(bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
737 {
738     SendStopResponsivenessTimer stopper(this);
739
740     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
741     m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
742 }
743
744 void WebPage::goForward(uint64_t backForwardItemID)
745 {
746     SendStopResponsivenessTimer stopper(this);
747
748     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
749     ASSERT(item);
750     if (!item)
751         return;
752
753     m_page->goToItem(item, FrameLoadTypeForward);
754 }
755
756 void WebPage::goBack(uint64_t backForwardItemID)
757 {
758     SendStopResponsivenessTimer stopper(this);
759
760     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
761     ASSERT(item);
762     if (!item)
763         return;
764
765     m_page->goToItem(item, FrameLoadTypeBack);
766 }
767
768 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
769 {
770     SendStopResponsivenessTimer stopper(this);
771
772     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
773     ASSERT(item);
774     if (!item)
775         return;
776
777     m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
778 }
779
780 void WebPage::tryRestoreScrollPosition()
781 {
782     m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
783 }
784
785 void WebPage::layoutIfNeeded()
786 {
787     if (m_mainFrame->coreFrame()->view())
788         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
789
790     if (m_underlayPage) {
791         if (FrameView *frameView = m_underlayPage->mainFrameView())
792             frameView->updateLayoutAndStyleIfNeededRecursive();
793     }
794 }
795
796 void WebPage::setSize(const WebCore::IntSize& viewSize)
797 {
798     FrameView* view = m_page->mainFrame()->view();
799
800 #if USE(TILED_BACKING_STORE)
801     // If we are resizing to content ignore external attempts.
802     if (view->useFixedLayout())
803         return;
804 #endif
805
806     if (m_viewSize == viewSize)
807         return;
808
809     view->resize(viewSize);
810     view->setNeedsLayout();
811     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
812     
813     m_viewSize = viewSize;
814 }
815
816 #if USE(TILED_BACKING_STORE)
817 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
818 {
819     ASSERT(m_useFixedLayout);
820
821     m_page->mainFrame()->view()->setFixedVisibleContentRect(rect);
822 }
823
824 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
825 {
826     ASSERT(m_useFixedLayout);
827     ASSERT(!targetLayoutSize.isEmpty());
828
829     FrameView* view = m_page->mainFrame()->view();
830
831     view->setDelegatesScrolling(true);
832     view->setUseFixedLayout(true);
833     view->setPaintsEntireContents(true);
834
835     if (view->fixedLayoutSize() == targetLayoutSize)
836         return;
837
838     // Always reset even when empty.
839     view->setFixedLayoutSize(targetLayoutSize);
840
841     m_page->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
842     m_page->settings()->setFixedElementsLayoutRelativeToFrame(true);
843
844     // Schedule a layout to use the new target size.
845     if (!view->layoutPending()) {
846         view->setNeedsLayout();
847         view->scheduleRelayout();
848     }
849 }
850
851 void WebPage::resizeToContentsIfNeeded()
852 {
853     ASSERT(m_useFixedLayout);
854
855     FrameView* view = m_page->mainFrame()->view();
856
857     if (!view->useFixedLayout())
858         return;
859
860     IntSize newSize = view->contentsSize().expandedTo(view->fixedLayoutSize());
861
862     if (newSize == m_viewSize)
863         return;
864
865     m_viewSize = newSize;
866     view->resize(newSize);
867     view->setNeedsLayout();
868 }
869
870 void WebPage::sendViewportAttributesChanged()
871 {
872     ASSERT(m_useFixedLayout);
873
874     // Viewport properties have no impact on zero sized fixed viewports.
875     if (m_viewportSize.isEmpty())
876         return;
877
878     // Recalculate the recommended layout size, when the available size (device pixel) changes.
879     Settings* settings = m_page->settings();
880
881     int minimumLayoutFallbackWidth = std::max(settings->layoutFallbackWidth(), m_viewportSize.width());
882
883     ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, settings->deviceWidth(), settings->deviceHeight(), static_cast<int>(160 * settings->devicePixelRatio()), m_viewportSize);
884
885     setResizesToContentsUsingLayoutSize(attr.layoutSize);
886     send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
887 }
888
889 void WebPage::setViewportSize(const IntSize& size)
890 {
891     ASSERT(m_useFixedLayout);
892
893     if (m_viewportSize == size)
894         return;
895
896      m_viewportSize = size;
897
898     sendViewportAttributesChanged();
899 }
900
901 #endif
902
903 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
904 {
905     Frame* frame = m_page->mainFrame();
906
907     IntPoint scrollPosition = frame->view()->scrollPosition();
908     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
909
910     // If the current scroll position in a direction is the max scroll position 
911     // we don't want to scroll at all.
912     IntSize newScrollOffset;
913     if (scrollPosition.x() < maximumScrollPosition.x())
914         newScrollOffset.setWidth(scrollOffset.width());
915     if (scrollPosition.y() < maximumScrollPosition.y())
916         newScrollOffset.setHeight(scrollOffset.height());
917
918     if (newScrollOffset.isZero())
919         return;
920
921     frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
922 }
923
924 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
925 {
926     GraphicsContextStateSaver stateSaver(graphicsContext);
927     graphicsContext.clip(rect);
928
929     if (m_underlayPage) {
930         m_underlayPage->drawRect(graphicsContext, rect);
931
932         graphicsContext.beginTransparencyLayer(1);
933         m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
934         graphicsContext.endTransparencyLayer();
935         return;
936     }
937
938     m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
939 }
940
941 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
942 {
943     ASSERT(m_pageOverlay);
944
945     GraphicsContextStateSaver stateSaver(graphicsContext);
946     graphicsContext.clip(rect);
947     m_pageOverlay->drawRect(graphicsContext, rect);
948 }
949
950 double WebPage::textZoomFactor() const
951 {
952     Frame* frame = m_mainFrame->coreFrame();
953     if (!frame)
954         return 1;
955     return frame->textZoomFactor();
956 }
957
958 void WebPage::setTextZoomFactor(double zoomFactor)
959 {
960     Frame* frame = m_mainFrame->coreFrame();
961     if (!frame)
962         return;
963     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
964 }
965
966 double WebPage::pageZoomFactor() const
967 {
968     Frame* frame = m_mainFrame->coreFrame();
969     if (!frame)
970         return 1;
971     return frame->pageZoomFactor();
972 }
973
974 void WebPage::setPageZoomFactor(double zoomFactor)
975 {
976     Frame* frame = m_mainFrame->coreFrame();
977     if (!frame)
978         return;
979     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
980 }
981
982 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
983 {
984     Frame* frame = m_mainFrame->coreFrame();
985     if (!frame)
986         return;
987     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
988 }
989
990 void WebPage::windowScreenDidChange(uint64_t displayID)
991 {
992     m_page->windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
993 }
994
995 void WebPage::scalePage(double scale, const IntPoint& origin)
996 {
997     m_page->setPageScaleFactor(scale, origin);
998
999     send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1000 }
1001
1002 double WebPage::pageScaleFactor() const
1003 {
1004     return m_page->pageScaleFactor();
1005 }
1006
1007 void WebPage::setDeviceScaleFactor(float scaleFactor)
1008 {
1009     if (scaleFactor == m_page->deviceScaleFactor())
1010         return;
1011
1012     m_page->setDeviceScaleFactor(scaleFactor);
1013
1014     // Tell all our plug-in views that the device scale factor changed.
1015 #if PLATFORM(MAC)
1016     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1017         (*it)->setDeviceScaleFactor(scaleFactor);
1018 #endif
1019
1020     if (m_findController.isShowingOverlay()) {
1021         // We must have updated layout to get the selection rects right.
1022         layoutIfNeeded();
1023         m_findController.deviceScaleFactorDidChange();
1024     }
1025 }
1026
1027 float WebPage::deviceScaleFactor() const
1028 {
1029     return m_page->deviceScaleFactor();
1030 }
1031
1032 void WebPage::setUseFixedLayout(bool fixed)
1033 {
1034     m_useFixedLayout = fixed;
1035
1036     FrameView* view = mainFrameView();
1037     if (!view)
1038         return;
1039
1040     view->setUseFixedLayout(fixed);
1041     if (!fixed)
1042         view->setFixedLayoutSize(IntSize());
1043 }
1044
1045 void WebPage::setFixedLayoutSize(const IntSize& size)
1046 {
1047     FrameView* view = mainFrameView();
1048     if (!view)
1049         return;
1050
1051     view->setFixedLayoutSize(size);
1052     view->forceLayout();
1053 }
1054
1055 void WebPage::setPaginationMode(uint32_t mode)
1056 {
1057     Page::Pagination pagination = m_page->pagination();
1058     pagination.mode = static_cast<Page::Pagination::Mode>(mode);
1059     m_page->setPagination(pagination);
1060 }
1061
1062 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1063 {
1064     Page::Pagination pagination = m_page->pagination();
1065     pagination.behavesLikeColumns = behavesLikeColumns;
1066     m_page->setPagination(pagination);
1067 }
1068
1069 void WebPage::setPageLength(double pageLength)
1070 {
1071     Page::Pagination pagination = m_page->pagination();
1072     pagination.pageLength = pageLength;
1073     m_page->setPagination(pagination);
1074 }
1075
1076 void WebPage::setGapBetweenPages(double gap)
1077 {
1078     Page::Pagination pagination = m_page->pagination();
1079     pagination.gap = gap;
1080     m_page->setPagination(pagination);
1081 }
1082
1083 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
1084 {
1085     bool shouldFadeIn = true;
1086     
1087     if (m_pageOverlay) {
1088         m_pageOverlay->setPage(0);
1089
1090         if (pageOverlay) {
1091             // We're installing a page overlay when a page overlay is already active.
1092             // In this case we don't want to fade in the new overlay.
1093             shouldFadeIn = false;
1094         }
1095     }
1096
1097     m_pageOverlay = pageOverlay;
1098     m_pageOverlay->setPage(this);
1099
1100     if (shouldFadeIn)
1101         m_pageOverlay->startFadeInAnimation();
1102
1103     m_drawingArea->didInstallPageOverlay();
1104 #if PLATFORM(WIN)
1105     send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
1106 #endif
1107
1108     m_pageOverlay->setNeedsDisplay();
1109 }
1110
1111 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
1112 {
1113     if (pageOverlay != m_pageOverlay)
1114         return;
1115
1116     if (fadeOut) {
1117         m_pageOverlay->startFadeOutAnimation();
1118         return;
1119     }
1120
1121     m_pageOverlay->setPage(0);
1122     m_pageOverlay = nullptr;
1123
1124     m_drawingArea->didUninstallPageOverlay();
1125 #if PLATFORM(WIN)
1126     send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
1127 #endif
1128 }
1129
1130 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1131 {
1132     FrameView* frameView = m_mainFrame->coreFrame()->view();
1133     if (!frameView)
1134         return 0;
1135
1136     IntSize bitmapSize = rect.size();
1137     float deviceScaleFactor = corePage()->deviceScaleFactor();
1138     bitmapSize.scale(deviceScaleFactor);
1139
1140     RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, options);
1141     if (!snapshot->bitmap())
1142         return 0;
1143     
1144     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1145     graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1146     graphicsContext->translate(-rect.x(), -rect.y());
1147
1148     frameView->updateLayoutAndStyleIfNeededRecursive();
1149
1150     PaintBehavior oldBehavior = frameView->paintBehavior();
1151     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1152     frameView->paint(graphicsContext.get(), rect);
1153     frameView->setPaintBehavior(oldBehavior);
1154
1155     return snapshot.release();
1156 }
1157
1158 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1159 {
1160     FrameView* frameView = m_mainFrame->coreFrame()->view();
1161     if (!frameView)
1162         return 0;
1163
1164     float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor();
1165     IntSize size(ceil(rect.width() * combinedScaleFactor), ceil(rect.height() * combinedScaleFactor));
1166     RefPtr<WebImage> snapshot = WebImage::create(size, options);
1167     if (!snapshot->bitmap())
1168         return 0;
1169
1170     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1171     graphicsContext->applyDeviceScaleFactor(combinedScaleFactor);
1172     graphicsContext->translate(-rect.x(), -rect.y());
1173
1174     frameView->updateLayoutAndStyleIfNeededRecursive();
1175
1176     PaintBehavior oldBehavior = frameView->paintBehavior();
1177     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1178     frameView->paintContents(graphicsContext.get(), rect);
1179     frameView->setPaintBehavior(oldBehavior);
1180
1181     return snapshot.release();
1182 }
1183
1184 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
1185 {
1186     return scaledSnapshotInDocumentCoordinates(rect, 1, options);
1187 }
1188
1189 void WebPage::pageDidScroll()
1190 {
1191     m_uiClient.pageDidScroll(this);
1192
1193     send(Messages::WebPageProxy::PageDidScroll());
1194 }
1195
1196 #if USE(TILED_BACKING_STORE)
1197 void WebPage::pageDidRequestScroll(const IntPoint& point)
1198 {
1199     send(Messages::WebPageProxy::PageDidRequestScroll(point));
1200 }
1201 #endif
1202
1203 #if ENABLE(CONTEXT_MENUS)
1204 WebContextMenu* WebPage::contextMenu()
1205 {
1206     if (!m_contextMenu)
1207         m_contextMenu = WebContextMenu::create(this);
1208     return m_contextMenu.get();
1209 }
1210 #endif
1211
1212 // Events 
1213
1214 static const WebEvent* g_currentEvent = 0;
1215
1216 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1217 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1218 // platform events passed to the event handler code.
1219 const WebEvent* WebPage::currentEvent()
1220 {
1221     return g_currentEvent;
1222 }
1223
1224 class CurrentEvent {
1225 public:
1226     explicit CurrentEvent(const WebEvent& event)
1227         : m_previousCurrentEvent(g_currentEvent)
1228     {
1229         g_currentEvent = &event;
1230     }
1231
1232     ~CurrentEvent()
1233     {
1234         g_currentEvent = m_previousCurrentEvent;
1235     }
1236
1237 private:
1238     const WebEvent* m_previousCurrentEvent;
1239 };
1240
1241 #if ENABLE(CONTEXT_MENUS)
1242 static bool isContextClick(const PlatformMouseEvent& event)
1243 {
1244     if (event.button() == WebCore::RightButton)
1245         return true;
1246
1247 #if PLATFORM(MAC)
1248     // FIXME: this really should be about OSX-style UI, not about the Mac port
1249     if (event.button() == WebCore::LeftButton && event.ctrlKey())
1250         return true;
1251 #endif
1252
1253     return false;
1254 }
1255
1256 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1257 {
1258     IntPoint point = page->corePage()->mainFrame()->view()->windowToContents(platformMouseEvent.position());
1259     HitTestResult result = page->corePage()->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1260
1261     Frame* frame = page->corePage()->mainFrame();
1262     if (result.innerNonSharedNode())
1263         frame = result.innerNonSharedNode()->document()->frame();
1264     
1265     bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1266     if (handled)
1267         page->contextMenu()->show();
1268
1269     return handled;
1270 }
1271 #endif
1272
1273 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1274 {
1275     Frame* frame = page->corePage()->mainFrame();
1276     if (!frame->view())
1277         return false;
1278
1279     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1280
1281     switch (platformMouseEvent.type()) {
1282         case PlatformEvent::MousePressed: {
1283 #if ENABLE(CONTEXT_MENUS)
1284             if (isContextClick(platformMouseEvent))
1285                 page->corePage()->contextMenuController()->clearContextMenu();
1286 #endif
1287
1288             bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1289 #if ENABLE(CONTEXT_MENUS)
1290             if (isContextClick(platformMouseEvent))
1291                 handled = handleContextMenuEvent(platformMouseEvent, page);
1292 #endif
1293
1294             return handled;
1295         }
1296         case PlatformEvent::MouseReleased:
1297             return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1298         case PlatformEvent::MouseMoved:
1299             if (onlyUpdateScrollbars)
1300                 return frame->eventHandler()->passMouseMovedEventToScrollbars(platformMouseEvent);
1301             return frame->eventHandler()->mouseMoved(platformMouseEvent);
1302         default:
1303             ASSERT_NOT_REACHED();
1304             return false;
1305     }
1306 }
1307
1308 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1309 {
1310 #if ENABLE(CONTEXT_MENUS)
1311     // Don't try to handle any pending mouse events if a context menu is showing.
1312     if (m_isShowingContextMenu) {
1313         send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1314         return;
1315     }
1316 #endif
1317     
1318     bool handled = false;
1319     
1320     if (m_pageOverlay) {
1321         // Let the page overlay handle the event.
1322         handled = m_pageOverlay->mouseEvent(mouseEvent);
1323     }
1324
1325     if (!handled) {
1326         CurrentEvent currentEvent(mouseEvent);
1327
1328         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1329         // button is currently pressed. It is possible that neither of those things will be true since on 
1330         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1331         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1332         // efficient scrollbars-only version of the event.
1333         bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1334         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1335     }
1336
1337     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1338 }
1339
1340 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1341 {
1342     handled = m_pageOverlay && m_pageOverlay->mouseEvent(mouseEvent);
1343
1344     if (!handled) {
1345         CurrentEvent currentEvent(mouseEvent);
1346
1347         // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1348         // button is currently pressed. It is possible that neither of those things will be true since on 
1349         // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one 
1350         // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1351         // efficient scrollbars-only version of the event.
1352         bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1353         handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1354     }
1355 }
1356
1357 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1358 {
1359     Frame* frame = page->mainFrame();
1360     if (!frame->view())
1361         return false;
1362
1363     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1364     return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1365 }
1366
1367 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1368 {
1369     CurrentEvent currentEvent(wheelEvent);
1370
1371     bool handled = handleWheelEvent(wheelEvent, m_page.get());
1372     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1373 }
1374
1375 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1376 {
1377     CurrentEvent currentEvent(wheelEvent);
1378
1379     handled = handleWheelEvent(wheelEvent, m_page.get());
1380 }
1381
1382 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1383 {
1384     if (!page->mainFrame()->view())
1385         return false;
1386
1387     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1388         return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1389     return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1390 }
1391
1392 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1393 {
1394     CurrentEvent currentEvent(keyboardEvent);
1395
1396     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1397     // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1398     if (!handled)
1399         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1400
1401     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1402 }
1403
1404 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1405 {
1406     CurrentEvent currentEvent(keyboardEvent);
1407
1408     handled = handleKeyEvent(keyboardEvent, m_page.get());
1409     if (!handled)
1410         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1411 }
1412
1413 #if ENABLE(GESTURE_EVENTS)
1414 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1415 {
1416     Frame* frame = page->mainFrame();
1417     if (!frame->view())
1418         return false;
1419
1420     PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1421     return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1422 }
1423
1424 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1425 {
1426     CurrentEvent currentEvent(gestureEvent);
1427
1428     bool handled = handleGestureEvent(gestureEvent, m_page.get());
1429     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1430 }
1431 #endif
1432
1433 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1434 {
1435     bool isEnabled = false;
1436     int32_t state = 0;
1437     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1438     if (frame) {
1439         Editor::Command command = frame->editor()->command(commandName);
1440         state = command.state();
1441         isEnabled = command.isSupported() && command.isEnabled();
1442     }
1443
1444     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1445 }
1446
1447 void WebPage::executeEditCommand(const String& commandName)
1448 {
1449     executeEditingCommand(commandName, String());
1450 }
1451
1452 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1453 {
1454     const BackForwardListItemVector& list = sessionState.list();
1455     size_t size = list.size();
1456     uint64_t currentItemID = 0;
1457     for (size_t i = 0; i < size; ++i) {
1458         WebBackForwardListItem* webItem = list[i].get();
1459         DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1460         
1461         RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1462         if (!item) {
1463             LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1464             return 0;
1465         }
1466         
1467         if (i == sessionState.currentIndex())
1468             currentItemID = webItem->itemID();
1469         
1470         WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1471     }    
1472     ASSERT(currentItemID);
1473     return currentItemID;
1474 }
1475
1476 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1477 {
1478     if (uint64_t currentItemID = restoreSession(sessionState))
1479         goToBackForwardItem(currentItemID);
1480 }
1481
1482 #if ENABLE(TOUCH_EVENTS)
1483 #if PLATFORM(QT)
1484 void WebPage::highlightPotentialActivation(const IntPoint& point, const IntSize& area)
1485 {
1486     if (point == IntPoint::zero()) {
1487         // An empty point deactivates the highlighting.
1488         tapHighlightController().hideHighlight();
1489     } else {
1490         Frame* mainframe = m_page->mainFrame();
1491         Node* activationNode = 0;
1492         Node* adjustedNode = 0;
1493         IntPoint adjustedPoint;
1494
1495 #if ENABLE(TOUCH_ADJUSTMENT)
1496         if (!mainframe->eventHandler()->bestClickableNodeForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), adjustedPoint, adjustedNode))
1497             return;
1498
1499 #else
1500         HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1501         adjustedNode = result.innerNode();
1502 #endif
1503         // Find the node to highlight. This is not the same as the node responding the tap gesture, because many
1504         // pages has a global click handler and we do not want to highlight the body.
1505         // Instead find the enclosing link or focusable element, or the last enclosing inline element.
1506         for (Node* node = adjustedNode; node; node = node->parentOrHostNode()) {
1507             if (node->isMouseFocusable() || node->isLink()) {
1508                 activationNode = node;
1509                 break;
1510             }
1511             if (node->renderer() && node->renderer()->isInline())
1512                 activationNode = node;
1513             else if (activationNode)
1514                 break;
1515         }
1516
1517         if (activationNode)
1518             tapHighlightController().highlight(activationNode);
1519     }
1520 }
1521 #endif
1522
1523 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1524 {
1525     Frame* frame = page->mainFrame();
1526     if (!frame->view())
1527         return false;
1528
1529     return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1530 }
1531
1532 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1533 {
1534     CurrentEvent currentEvent(touchEvent);
1535
1536     bool handled = handleTouchEvent(touchEvent, m_page.get());
1537
1538     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1539 }
1540
1541 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1542 {
1543     CurrentEvent currentEvent(touchEvent);
1544     handled = handleTouchEvent(touchEvent, m_page.get());
1545 }
1546 #endif
1547
1548 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1549 {
1550     page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1551 }
1552
1553 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1554 {
1555     page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1556 }
1557
1558 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1559 {
1560     scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1561 }
1562
1563 void WebPage::centerSelectionInVisibleArea()
1564 {
1565     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1566     if (!frame)
1567         return;
1568     
1569     frame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
1570     m_findController.showFindIndicatorInSelection();
1571 }
1572
1573 void WebPage::setActive(bool isActive)
1574 {
1575     m_page->focusController()->setActive(isActive);
1576
1577 #if PLATFORM(MAC)    
1578     // Tell all our plug-in views that the window focus changed.
1579     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1580         (*it)->setWindowIsFocused(isActive);
1581 #endif
1582 }
1583
1584 void WebPage::setDrawsBackground(bool drawsBackground)
1585 {
1586     if (m_drawsBackground == drawsBackground)
1587         return;
1588
1589     m_drawsBackground = drawsBackground;
1590
1591     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1592         if (FrameView* view = coreFrame->view())
1593             view->setTransparent(!drawsBackground);
1594     }
1595
1596     m_drawingArea->pageBackgroundTransparencyChanged();
1597     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1598 }
1599
1600 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1601 {
1602     if (m_drawsTransparentBackground == drawsTransparentBackground)
1603         return;
1604
1605     m_drawsTransparentBackground = drawsTransparentBackground;
1606
1607     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
1608     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1609         if (FrameView* view = coreFrame->view())
1610             view->setBaseBackgroundColor(backgroundColor);
1611     }
1612
1613     m_drawingArea->pageBackgroundTransparencyChanged();
1614     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1615 }
1616
1617 void WebPage::viewWillStartLiveResize()
1618 {
1619     if (!m_page)
1620         return;
1621
1622     // FIXME: This should propagate to all ScrollableAreas.
1623     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1624         if (FrameView* view = frame->view())
1625             view->willStartLiveResize();
1626     }
1627 }
1628
1629 void WebPage::viewWillEndLiveResize()
1630 {
1631     if (!m_page)
1632         return;
1633
1634     // FIXME: This should propagate to all ScrollableAreas.
1635     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1636         if (FrameView* view = frame->view())
1637             view->willEndLiveResize();
1638     }
1639 }
1640
1641 void WebPage::setFocused(bool isFocused)
1642 {
1643     m_page->focusController()->setFocused(isFocused);
1644 }
1645
1646 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
1647 {
1648     if (!m_page || !m_page->focusController())
1649         return;
1650
1651     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1652     frame->document()->setFocusedNode(0);
1653
1654     if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
1655         PlatformKeyboardEvent platformEvent(platform(event));
1656         platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
1657         m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame->document()->defaultView()).get());
1658         return;
1659     }
1660
1661     m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
1662 }
1663
1664 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
1665 {
1666     if (m_windowResizerSize == windowResizerSize)
1667         return;
1668
1669     m_windowResizerSize = windowResizerSize;
1670
1671     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1672         FrameView* view = coreFrame->view();
1673         if (view)
1674             view->windowResizerRectChanged();
1675     }
1676 }
1677
1678 void WebPage::setCanStartMediaTimerFired()
1679 {
1680     if (m_page)
1681         m_page->setCanStartMedia(true);
1682 }
1683
1684 void WebPage::setIsInWindow(bool isInWindow)
1685 {
1686     if (!isInWindow) {
1687         m_setCanStartMediaTimer.stop();
1688         m_page->setCanStartMedia(false);
1689         m_page->willMoveOffscreen();
1690     } else {
1691         // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
1692         // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
1693         // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
1694         m_setCanStartMediaTimer.startOneShot(0);
1695         m_page->didMoveOnscreen();
1696     }
1697 }
1698
1699 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
1700 {
1701     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1702     if (!frame)
1703         return;
1704     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
1705 }
1706
1707 void WebPage::show()
1708 {
1709     send(Messages::WebPageProxy::ShowPage());
1710 }
1711
1712 void WebPage::setUserAgent(const String& userAgent)
1713 {
1714     m_userAgent = userAgent;
1715 }
1716
1717 void WebPage::suspendActiveDOMObjectsAndAnimations()
1718 {
1719     m_page->suspendActiveDOMObjectsAndAnimations();
1720 }
1721
1722 void WebPage::resumeActiveDOMObjectsAndAnimations()
1723 {
1724     m_page->resumeActiveDOMObjectsAndAnimations();
1725
1726     // We need to repaint on resume to kickstart animated painting again.
1727     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1728 }
1729
1730 IntPoint WebPage::screenToWindow(const IntPoint& point)
1731 {
1732     IntPoint windowPoint;
1733     sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
1734     return windowPoint;
1735 }
1736     
1737 IntRect WebPage::windowToScreen(const IntRect& rect)
1738 {
1739     IntRect screenRect;
1740     sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
1741     return screenRect;
1742 }
1743
1744 IntRect WebPage::windowResizerRect() const
1745 {
1746     if (m_windowResizerSize.isEmpty())
1747         return IntRect();
1748
1749     IntSize frameViewSize;
1750     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
1751         if (FrameView* view = coreFrame->view())
1752             frameViewSize = view->size();
1753     }
1754
1755     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
1756                    m_windowResizerSize.width(), m_windowResizerSize.height());
1757 }
1758
1759 KeyboardUIMode WebPage::keyboardUIMode()
1760 {
1761     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
1762     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
1763 }
1764
1765 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
1766 {
1767     // NOTE: We need to be careful when running scripts that the objects we depend on don't
1768     // disappear during script execution.
1769
1770     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
1771     // long enough for the DataReference to be encoded by the sent message.
1772     RefPtr<SerializedScriptValue> serializedResultValue;
1773     CoreIPC::DataReference dataReference;
1774
1775     JSLock lock(SilenceAssertionsOnly);
1776     if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
1777         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
1778             dataReference = serializedResultValue->data();
1779     }
1780
1781     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
1782 }
1783
1784 void WebPage::getContentsAsString(uint64_t callbackID)
1785 {
1786     String resultString = m_mainFrame->contentsAsString();
1787     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1788 }
1789
1790 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
1791 {
1792     String resultString = renderTreeExternalRepresentation();
1793     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1794 }
1795
1796 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
1797 {
1798     String resultString = m_mainFrame->selectionAsString();
1799     if (resultString.isEmpty())
1800         resultString = m_mainFrame->contentsAsString();
1801     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1802 }
1803
1804 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
1805 {
1806     String resultString;
1807     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
1808        resultString = frame->source();
1809
1810     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1811 }
1812
1813 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
1814 {
1815     CoreIPC::DataReference dataReference;
1816
1817     RefPtr<SharedBuffer> buffer;
1818     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1819         if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1820             if ((buffer = loader->mainResourceData()))
1821                 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1822         }
1823     }
1824
1825     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1826 }
1827
1828 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
1829 {
1830     DocumentLoader* loader = frame->loader()->documentLoader();
1831     if (!loader)
1832         return 0;
1833
1834     RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
1835     if (!subresource)
1836         return 0;
1837
1838     return subresource->data();
1839 }
1840
1841 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
1842 {
1843     CoreIPC::DataReference dataReference;
1844     KURL resourceURL(KURL(), resourceURLString);
1845
1846     RefPtr<SharedBuffer> buffer;
1847     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1848         buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
1849         if (!buffer) {
1850             // Try to get the resource data from the cache.
1851             buffer = cachedResponseDataForURL(resourceURL);
1852         }
1853
1854         if (buffer)
1855             dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1856     }
1857
1858     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1859 }
1860
1861 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
1862 {
1863     CoreIPC::DataReference dataReference;
1864
1865 #if PLATFORM(MAC) || PLATFORM(WIN)
1866     RetainPtr<CFDataRef> data;
1867     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1868         if ((data = frame->webArchiveData(0, 0)))
1869             dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
1870     }
1871 #endif
1872
1873     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1874 }
1875
1876 void WebPage::forceRepaintWithoutCallback()
1877 {
1878     m_drawingArea->forceRepaint();
1879 }
1880
1881 void WebPage::forceRepaint(uint64_t callbackID)
1882 {
1883     if (m_drawingArea->forceRepaintAsync(callbackID))
1884         return;
1885
1886     forceRepaintWithoutCallback();
1887     send(Messages::WebPageProxy::VoidCallback(callbackID));
1888 }
1889
1890 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
1891 {
1892     WebPreferencesStore::removeTestRunnerOverrides();
1893     updatePreferences(store);
1894 }
1895
1896 void WebPage::updatePreferences(const WebPreferencesStore& store)
1897 {
1898     Settings* settings = m_page->settings();
1899
1900     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1901
1902     // FIXME: This should be generated from macro expansion for all preferences,
1903     // but we currently don't match the naming of WebCore exactly so we are
1904     // handrolling the boolean and integer preferences until that is fixed.
1905
1906 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1907
1908     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1909
1910 #undef INITIALIZE_SETTINGS
1911
1912     settings->setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1913     settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1914     settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
1915     settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1916     settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1917     settings->setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));    
1918     settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1919     settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1920     settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1921     settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1922     settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1923     settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1924     settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1925     settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1926     settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1927     settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1928     settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1929 #if ENABLE(WEB_ARCHIVE)
1930     settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1931 #endif
1932     settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1933     settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1934     settings->setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
1935     settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1936     settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1937     settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1938     settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
1939     settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1940     settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
1941     settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
1942     settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
1943
1944     settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1945     settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1946     settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1947     settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1948     settings->setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
1949     settings->setDevicePixelRatio(store.getDoubleValueForKey(WebPreferencesKey::devicePixelRatioKey()));
1950     settings->setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
1951     settings->setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
1952     settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
1953     settings->setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
1954
1955     settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1956     settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1957     settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1958     settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1959     settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1960     settings->setCSSCustomFilterEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCustomFilterEnabledKey()));
1961     settings->setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
1962     settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
1963     settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
1964     settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
1965     settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
1966     settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
1967     settings->setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
1968
1969     // <rdar://problem/10697417>: It is necessary to force compositing when accelerate drawing
1970     // is enabled on Mac so that scrollbars are always in their own layers.
1971 #if PLATFORM(MAC)
1972     if (settings->acceleratedDrawingEnabled())
1973         settings->setForceCompositingMode(LayerTreeHost::supportsAcceleratedCompositing());
1974     else
1975 #endif
1976         settings->setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1977
1978 #if ENABLE(SQL_DATABASE)
1979     AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1980 #endif
1981
1982 #if ENABLE(FULLSCREEN_API)
1983     settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
1984 #endif
1985
1986     settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
1987
1988 #if USE(AVFOUNDATION)
1989     settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
1990 #endif
1991
1992 #if ENABLE(WEB_SOCKETS)
1993     settings->setUseHixie76WebSocketProtocol(store.getBoolValueForKey(WebPreferencesKey::hixie76WebSocketProtocolEnabledKey()));
1994 #endif
1995
1996 #if ENABLE(WEB_AUDIO)
1997     settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
1998 #endif
1999
2000     settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2001     settings->setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2002     settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2003     settings->setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2004     settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2005
2006 #if ENABLE(VIDEO_TRACK)
2007     settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2008     settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2009     settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2010 #endif
2011
2012 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2013     settings->setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2014 #endif
2015
2016     settings->setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2017
2018     platformPreferencesDidChange(store);
2019
2020     if (m_drawingArea)
2021         m_drawingArea->updatePreferences();
2022 }
2023
2024 #if ENABLE(INSPECTOR)
2025 WebInspector* WebPage::inspector()
2026 {
2027     if (m_isClosed)
2028         return 0;
2029     if (!m_inspector)
2030         m_inspector = WebInspector::create(this);
2031     return m_inspector.get();
2032 }
2033 #endif
2034
2035 #if ENABLE(FULLSCREEN_API)
2036 WebFullScreenManager* WebPage::fullScreenManager()
2037 {
2038     if (!m_fullScreenManager)
2039         m_fullScreenManager = WebFullScreenManager::create(this);
2040     return m_fullScreenManager.get();
2041 }
2042 #endif
2043
2044 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2045 {
2046     if (m_notificationPermissionRequestManager)
2047         return m_notificationPermissionRequestManager.get();
2048
2049     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2050     return m_notificationPermissionRequestManager.get();
2051 }
2052
2053 #if !PLATFORM(GTK) && !PLATFORM(MAC)
2054 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2055 {
2056     Node* node = evt->target()->toNode();
2057     ASSERT(node);
2058     Frame* frame = node->document()->frame();
2059     ASSERT(frame);
2060
2061     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2062     if (!keyEvent)
2063         return false;
2064
2065     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
2066
2067     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2068         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2069         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2070         // (e.g. Tab that inserts a Tab character, or Enter).
2071         return !command.isTextInsertion() && command.execute(evt);
2072     }
2073
2074     if (command.execute(evt))
2075         return true;
2076
2077     // Don't insert null or control characters as they can result in unexpected behaviour
2078     if (evt->charCode() < ' ')
2079         return false;
2080
2081     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
2082 }
2083 #endif
2084
2085 #if PLATFORM(WIN)
2086 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
2087 {
2088     if (!m_page) {
2089         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2090         return;
2091     }
2092
2093     DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2094     switch (action) {
2095     case DragControllerActionEntered:
2096         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2097         break;
2098
2099     case DragControllerActionUpdated:
2100         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2101         break;
2102         
2103     case DragControllerActionExited:
2104         m_page->dragController()->dragExited(&dragData);
2105         break;
2106         
2107     case DragControllerActionPerformDrag:
2108         m_page->dragController()->performDrag(&dragData);
2109         break;
2110         
2111     default:
2112         ASSERT_NOT_REACHED();
2113     }
2114 }
2115
2116 #elif PLATFORM(QT) || PLATFORM(GTK)
2117 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2118 {
2119     if (!m_page) {
2120         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2121 #if PLATFORM(QT)
2122         QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2123 #elif PLATFORM(GTK)
2124         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2125 #endif
2126         delete data;
2127         return;
2128     }
2129
2130     switch (action) {
2131     case DragControllerActionEntered:
2132         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2133         break;
2134
2135     case DragControllerActionUpdated:
2136         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2137         break;
2138
2139     case DragControllerActionExited:
2140         m_page->dragController()->dragExited(&dragData);
2141         break;
2142
2143     case DragControllerActionPerformDrag: {
2144         m_page->dragController()->performDrag(&dragData);
2145         break;
2146     }
2147
2148     default:
2149         ASSERT_NOT_REACHED();
2150     }
2151     // DragData does not delete its platformData so we need to do that here.
2152 #if PLATFORM(QT)
2153     QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2154 #elif PLATFORM(GTK)
2155     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2156 #endif
2157     delete data;
2158 }
2159
2160 #else
2161 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsHandleArray)
2162 {
2163     if (!m_page) {
2164         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2165         return;
2166     }
2167
2168     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2169     switch (action) {
2170     case DragControllerActionEntered:
2171         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2172         break;
2173
2174     case DragControllerActionUpdated:
2175         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2176         break;
2177         
2178     case DragControllerActionExited:
2179         m_page->dragController()->dragExited(&dragData);
2180         break;
2181         
2182     case DragControllerActionPerformDrag: {
2183         ASSERT(!m_pendingDropSandboxExtension);
2184
2185         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2186         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++)
2187             m_pendingDropExtensionsForFileUpload.append(SandboxExtension::create(sandboxExtensionsHandleArray[i]));
2188
2189         m_page->dragController()->performDrag(&dragData);
2190
2191         // If we started loading a local file, the sandbox extension tracker would have adopted this
2192         // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2193         if (m_pendingDropSandboxExtension) {
2194             m_pendingDropSandboxExtension->invalidate();
2195             m_pendingDropSandboxExtension = nullptr;
2196         }
2197         for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2198             m_pendingDropExtensionsForFileUpload[i]->invalidate();
2199
2200         m_pendingDropExtensionsForFileUpload.clear();
2201         break;
2202     }
2203
2204     default:
2205         ASSERT_NOT_REACHED();
2206     }
2207 }
2208 #endif
2209
2210 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2211 {
2212     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2213     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2214
2215     m_page->dragController()->dragEnded();
2216     FrameView* view = m_page->mainFrame()->view();
2217     if (!view)
2218         return;
2219     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2220     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2221     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2222 }
2223
2224 void WebPage::willPerformLoadDragDestinationAction()
2225 {
2226     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2227 }
2228
2229 void WebPage::mayPerformUploadDragDestinationAction()
2230 {
2231     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2232         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2233     m_pendingDropExtensionsForFileUpload.clear();
2234 }
2235
2236 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2237 {
2238     return m_undoStepMap.get(stepID).get();
2239 }
2240
2241 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2242 {
2243     m_undoStepMap.set(stepID, entry);
2244 }
2245
2246 void WebPage::removeWebEditCommand(uint64_t stepID)
2247 {
2248     m_undoStepMap.remove(stepID);
2249 }
2250
2251 void WebPage::unapplyEditCommand(uint64_t stepID)
2252 {
2253     WebUndoStep* step = webUndoStep(stepID);
2254     if (!step)
2255         return;
2256
2257     step->step()->unapply();
2258 }
2259
2260 void WebPage::reapplyEditCommand(uint64_t stepID)
2261 {
2262     WebUndoStep* step = webUndoStep(stepID);
2263     if (!step)
2264         return;
2265
2266     m_isInRedo = true;
2267     step->step()->reapply();
2268     m_isInRedo = false;
2269 }
2270
2271 void WebPage::didRemoveEditCommand(uint64_t commandID)
2272 {
2273     removeWebEditCommand(commandID);
2274 }
2275
2276 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2277 {
2278     m_activePopupMenu = menu;
2279 }
2280
2281 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2282 {
2283     m_activeOpenPanelResultListener = openPanelResultListener;
2284 }
2285
2286 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2287 {
2288     return m_page->findString(target, options);
2289 }
2290
2291 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2292 {
2293     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2294 }
2295
2296 void WebPage::hideFindUI()
2297 {
2298     m_findController.hideFindUI();
2299 }
2300
2301 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2302 {
2303     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2304 }
2305
2306 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2307 {
2308     if (!m_activePopupMenu)
2309         return;
2310
2311     m_activePopupMenu->didChangeSelectedIndex(newIndex);
2312     m_activePopupMenu = 0;
2313 }
2314
2315 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2316 {
2317     if (!m_activeOpenPanelResultListener)
2318         return;
2319
2320     m_activeOpenPanelResultListener->didChooseFiles(files);
2321     m_activeOpenPanelResultListener = 0;
2322 }
2323
2324 void WebPage::didCancelForOpenPanel()
2325 {
2326     m_activeOpenPanelResultListener = 0;
2327 }
2328
2329 #if ENABLE(WEB_PROCESS_SANDBOX)
2330 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2331 {
2332     SandboxExtension::create(handle)->consumePermanently();
2333 }
2334 #endif
2335
2336 #if ENABLE(GEOLOCATION)
2337 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2338 {
2339     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2340 }
2341 #endif
2342
2343 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2344 {
2345     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2346 }
2347
2348 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2349 {
2350     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2351     frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2352 }
2353
2354 void WebPage::changeSpellingToWord(const String& word)
2355 {
2356     replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2357 }
2358
2359 void WebPage::unmarkAllMisspellings()
2360 {
2361     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2362         if (Document* document = frame->document())
2363             document->markers()->removeMarkers(DocumentMarker::Spelling);
2364     }
2365 }
2366
2367 void WebPage::unmarkAllBadGrammar()
2368 {
2369     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2370         if (Document* document = frame->document())
2371             document->markers()->removeMarkers(DocumentMarker::Grammar);
2372     }
2373 }
2374
2375 #if PLATFORM(MAC)
2376 void WebPage::uppercaseWord()
2377 {
2378     m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2379 }
2380
2381 void WebPage::lowercaseWord()
2382 {
2383     m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2384 }
2385
2386 void WebPage::capitalizeWord()
2387 {
2388     m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2389 }
2390 #endif
2391     
2392 void WebPage::setTextForActivePopupMenu(int32_t index)
2393 {
2394     if (!m_activePopupMenu)
2395         return;
2396
2397     m_activePopupMenu->setTextForIndex(index);
2398 }
2399
2400 #if PLATFORM(GTK)
2401 void WebPage::failedToShowPopupMenu()
2402 {
2403     if (!m_activePopupMenu)
2404         return;
2405
2406     m_activePopupMenu->client()->popupDidHide();
2407 }
2408 #endif
2409
2410 #if ENABLE(CONTEXT_MENUS)
2411 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2412 {
2413     if (!m_contextMenu)
2414         return;
2415
2416     m_contextMenu->itemSelected(item);
2417     m_contextMenu = 0;
2418 }
2419 #endif
2420
2421 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
2422 {
2423     bool selectReplacement = true;
2424     bool smartReplace = false;
2425     return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
2426 }
2427
2428 void WebPage::clearSelection()
2429 {
2430     m_page->focusController()->focusedOrMainFrame()->selection()->clear();
2431 }
2432
2433 bool WebPage::mainFrameHasCustomRepresentation() const
2434 {
2435     if (Frame* frame = mainFrame())
2436         return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
2437
2438     return false;
2439 }
2440
2441 void WebPage::didChangeScrollOffsetForMainFrame()
2442 {
2443     Frame* frame = m_page->mainFrame();
2444     IntPoint scrollPosition = frame->view()->scrollPosition();
2445     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
2446     IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
2447
2448     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
2449     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
2450
2451     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
2452         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
2453         
2454         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
2455         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
2456     }
2457 }
2458
2459 void WebPage::mainFrameDidLayout()
2460 {
2461     unsigned pageCount = m_page->pageCount();
2462     if (pageCount != m_cachedPageCount) {
2463         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
2464         m_cachedPageCount = pageCount;
2465     }
2466 }
2467
2468 #if PLATFORM(MAC)
2469
2470 void WebPage::addPluginView(PluginView* pluginView)
2471 {
2472     ASSERT(!m_pluginViews.contains(pluginView));
2473
2474     m_pluginViews.add(pluginView);
2475 }
2476
2477 void WebPage::removePluginView(PluginView* pluginView)
2478 {
2479     ASSERT(m_pluginViews.contains(pluginView));
2480
2481     m_pluginViews.remove(pluginView);
2482 }
2483
2484 void WebPage::setWindowIsVisible(bool windowIsVisible)
2485 {
2486     m_windowIsVisible = windowIsVisible;
2487
2488     corePage()->focusController()->setContainingWindowIsVisible(windowIsVisible);
2489
2490     // Tell all our plug-in views that the window visibility changed.
2491     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2492         (*it)->setWindowIsVisible(windowIsVisible);
2493 }
2494
2495 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
2496 {
2497     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
2498     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
2499     m_accessibilityPosition = accessibilityViewCoordinates;
2500     
2501     // Tell all our plug-in views that the window and view frames have changed.
2502     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2503         (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
2504 }
2505 #endif
2506
2507 bool WebPage::windowIsFocused() const
2508 {
2509     return m_page->focusController()->isActive();
2510 }
2511
2512 bool WebPage::windowAndWebPageAreFocused() const
2513 {
2514 #if PLATFORM(MAC)
2515     if (!m_windowIsVisible)
2516         return false;
2517 #endif
2518     return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
2519 }
2520
2521 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
2522 {
2523     if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
2524         if (m_drawingArea)
2525             m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
2526         return;
2527     }
2528
2529 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
2530     if (messageID.is<CoreIPC::MessageClassLayerTreeHost>()) {
2531         if (m_drawingArea)
2532             m_drawingArea->didReceiveLayerTreeHostMessage(connection, messageID, arguments);
2533         return;
2534     }
2535 #endif
2536     
2537 #if ENABLE(INSPECTOR)
2538     if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
2539         if (WebInspector* inspector = this->inspector())
2540             inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
2541         return;
2542     }
2543 #endif
2544
2545 #if ENABLE(FULLSCREEN_API)
2546     if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
2547         fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
2548         return;
2549     }
2550 #endif
2551
2552     didReceiveWebPageMessage(connection, messageID, arguments);
2553 }
2554
2555 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
2556 {   
2557     didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
2558 }
2559     
2560 InjectedBundleBackForwardList* WebPage::backForwardList()
2561 {
2562     if (!m_backForwardList)
2563         m_backForwardList = InjectedBundleBackForwardList::create(this);
2564     return m_backForwardList.get();
2565 }
2566
2567 #if PLATFORM(QT)
2568 #if ENABLE(TOUCH_ADJUSTMENT)
2569 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
2570 {
2571     Node* node = 0;
2572     IntRect zoomableArea;
2573     bool foundAreaForTouchPoint = m_mainFrame->coreFrame()->eventHandler()->bestZoomableAreaForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), zoomableArea, node);
2574     ASSERT(node);
2575
2576     if (!foundAreaForTouchPoint)
2577         return;
2578
2579     if (node->document() && node->document()->view())
2580         zoomableArea = node->document()->view()->contentsToWindow(zoomableArea);
2581
2582     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
2583 }
2584
2585 #else
2586 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
2587 {
2588     UNUSED_PARAM(area);
2589     Frame* mainframe = m_mainFrame->coreFrame();
2590     HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
2591
2592     Node* node = result.innerNode();
2593
2594     if (!node)
2595         return;
2596
2597     IntRect zoomableArea = node->getRect();
2598
2599     while (true) {
2600         bool found = !node->isTextNode() && !node->isShadowRoot();
2601
2602         // No candidate found, bail out.
2603         if (!found && !node->parentNode())
2604             return;
2605
2606         // Candidate found, and it is a better candidate than its parent.
2607         // NB: A parent is considered a better candidate iff the node is
2608         // contained by it and it is the only child.
2609         if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
2610             break;
2611
2612         node = node->parentNode();
2613         zoomableArea.unite(node->getRect());
2614     }
2615
2616     if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
2617         const ScrollView* view = node->document()->frame()->view();
2618         zoomableArea = view->contentsToWindow(zoomableArea);
2619     }
2620
2621     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
2622 }
2623 #endif
2624 #endif
2625
2626 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
2627 {
2628     invalidate();
2629 }
2630
2631 void WebPage::SandboxExtensionTracker::invalidate()
2632 {
2633     if (m_pendingProvisionalSandboxExtension) {
2634         m_pendingProvisionalSandboxExtension->invalidate();
2635         m_pendingProvisionalSandboxExtension = 0;
2636     }
2637
2638     if (m_provisionalSandboxExtension) {
2639         m_provisionalSandboxExtension->invalidate();
2640         m_provisionalSandboxExtension = 0;
2641     }
2642
2643     if (m_committedSandboxExtension) {
2644         m_committedSandboxExtension->invalidate();
2645         m_committedSandboxExtension = 0;
2646     }
2647 }
2648
2649 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
2650 {
2651     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
2652 }
2653
2654 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
2655 {
2656     ASSERT(frame->isMainFrame());
2657
2658     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
2659 }
2660
2661 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
2662 {
2663     // If we get two beginLoad calls in succession, without a provisional load starting, then
2664     // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
2665     if (m_pendingProvisionalSandboxExtension) {
2666         m_pendingProvisionalSandboxExtension->invalidate();
2667         m_pendingProvisionalSandboxExtension = nullptr;
2668     }
2669     
2670     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
2671 }
2672
2673 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
2674 {
2675     ASSERT(frame->isMainFrame());
2676
2677     FrameLoader* frameLoader = frame->coreFrame()->loader();
2678     FrameLoadType frameLoadType = frameLoader->loadType();
2679
2680     // If the page is being reloaded, it should reuse whatever extension is committed.
2681     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
2682         return true;
2683
2684     DocumentLoader* documentLoader = frameLoader->documentLoader();
2685     DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
2686     if (!documentLoader || !provisionalDocumentLoader)
2687         return false;
2688
2689     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
2690         return true;
2691
2692     return false;
2693 }
2694
2695 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
2696 {
2697     if (!frame->isMainFrame())
2698         return;
2699
2700     // We should only reuse the commited sandbox extension if it is not null. It can be
2701     // null if the last load was for an error page.
2702     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
2703         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
2704         ASSERT(!m_committedSandboxExtension);
2705     }
2706
2707     ASSERT(!m_provisionalSandboxExtension);
2708
2709     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
2710     if (!m_provisionalSandboxExtension)
2711         return;
2712
2713     m_provisionalSandboxExtension->consume();
2714 }
2715
2716 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
2717 {
2718     if (!frame->isMainFrame())
2719         return;
2720
2721     // Generally, there should be no pending extension at this stage, but we can have one if UI process
2722     // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
2723     if (m_pendingProvisionalSandboxExtension) {
2724         m_pendingProvisionalSandboxExtension->invalidate();
2725         m_pendingProvisionalSandboxExtension = nullptr;
2726     }
2727
2728     // The provisional load has been committed. Invalidate the currently committed sandbox
2729     // extension and make the provisional sandbox extension the committed sandbox extension.
2730     if (m_committedSandboxExtension)
2731         m_committedSandboxExtension->invalidate();
2732
2733     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
2734 }
2735
2736 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
2737 {
2738     if (!frame->isMainFrame())
2739         return;
2740
2741     // Generally, there should be no pending extension at this stage, but we can have one if UI process
2742     // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
2743     if (m_pendingProvisionalSandboxExtension) {
2744         m_pendingProvisionalSandboxExtension->invalidate();
2745         m_pendingProvisionalSandboxExtension = nullptr;
2746     }
2747
2748     if (!m_provisionalSandboxExtension)
2749         return;
2750
2751     m_provisionalSandboxExtension->invalidate();
2752     m_provisionalSandboxExtension = nullptr;
2753 }
2754
2755 bool WebPage::hasLocalDataForURL(const KURL& url)
2756 {
2757     if (url.isLocalFile())
2758         return true;
2759
2760     FrameLoader* frameLoader = m_page->mainFrame()->loader();
2761     DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
2762     if (documentLoader && documentLoader->subresource(url))
2763         return true;
2764
2765     return platformHasLocalDataForURL(url);
2766 }
2767
2768 void WebPage::setCustomTextEncodingName(const String& encoding)
2769 {
2770     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
2771 }
2772
2773 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
2774 {
2775     WebBackForwardListProxy::removeItem(itemID);
2776 }
2777
2778 #if PLATFORM(MAC)
2779
2780 bool WebPage::isSpeaking()
2781 {
2782     bool result;
2783     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
2784 }
2785
2786 void WebPage::speak(const String& string)
2787 {
2788     send(Messages::WebPageProxy::Speak(string));
2789 }
2790
2791 void WebPage::stopSpeaking()
2792 {
2793     send(Messages::WebPageProxy::StopSpeaking());
2794 }
2795
2796 #endif
2797
2798 #if PLATFORM(MAC)
2799 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
2800 {
2801     Document* document = coreFrame->document();
2802     if (!document)
2803         return 0;
2804
2805     if (!document->isPluginDocument())
2806         return 0;
2807
2808     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
2809     if (!pluginView)
2810         return 0;
2811
2812     return pluginView->pdfDocumentForPrinting();
2813 }
2814 #endif // PLATFORM(MAC)
2815
2816 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
2817 {
2818     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2819     if (!frame)
2820         return;
2821
2822     Frame* coreFrame = frame->coreFrame();
2823     if (!coreFrame)
2824         return;
2825
2826 #if PLATFORM(MAC)
2827     if (pdfDocumentForPrintingFrame(coreFrame))
2828         return;
2829 #endif // PLATFORM(MAC)
2830
2831     if (!m_printContext)
2832         m_printContext = adoptPtr(new PrintContext(coreFrame));
2833
2834     drawingArea()->setLayerTreeStateIsFrozen(true);
2835     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2836
2837     float fullPageHeight;
2838     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
2839
2840 #if PLATFORM(GTK)
2841     if (!m_printOperation)
2842         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
2843 #endif
2844 }
2845
2846 void WebPage::endPrinting()
2847 {
2848     drawingArea()->setLayerTreeStateIsFrozen(false);
2849 #if PLATFORM(GTK)
2850     m_printOperation = 0;
2851 #endif
2852     m_printContext = nullptr;
2853 }
2854
2855 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
2856 {
2857     Vector<IntRect> resultPageRects;
2858     double resultTotalScaleFactorForPrinting = 1;
2859
2860     beginPrinting(frameID, printInfo);
2861
2862     if (m_printContext) {
2863         resultPageRects = m_printContext->pageRects();
2864         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
2865     }
2866 #if PLATFORM(MAC)
2867     else
2868         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
2869 #endif // PLATFORM(MAC)
2870
2871     // If we're asked to print, we should actually print at least a blank page.
2872     if (resultPageRects.isEmpty())
2873         resultPageRects.append(IntRect(0, 0, 1, 1));
2874
2875     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
2876 }
2877
2878 #if PLATFORM(MAC) || PLATFORM(WIN)
2879 void WebPage::drawRectToPDF(uint64_t frameID, const PrintInfo& printInfo, const WebCore::IntRect& rect, uint64_t callbackID)
2880 {
2881     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2882     Frame* coreFrame = frame ? frame->coreFrame() : 0;
2883
2884     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2885
2886     if (coreFrame) {
2887 #if PLATFORM(MAC)
2888         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
2889 #else
2890         ASSERT(coreFrame->document()->printing());
2891 #endif
2892
2893         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2894         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2895
2896         CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
2897         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2898         RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2899         CGPDFContextBeginPage(context.get(), pageInfo.get());
2900
2901 #if PLATFORM(MAC)
2902         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
2903             ASSERT(!m_printContext);
2904             drawRectToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, rect);
2905         } else
2906 #endif
2907         {
2908             GraphicsContext ctx(context.get());
2909             ctx.scale(FloatSize(1, -1));
2910             ctx.translate(0, -rect.height());
2911             m_printContext->spoolRect(ctx, rect);
2912         }
2913
2914         CGPDFContextEndPage(context.get());
2915         CGPDFContextClose(context.get());
2916     }
2917
2918     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2919 }
2920
2921 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
2922 {
2923     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2924     Frame* coreFrame = frame ? frame->coreFrame() : 0;
2925
2926     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2927
2928     if (coreFrame) {
2929
2930 #if PLATFORM(MAC)
2931         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
2932 #else
2933         ASSERT(coreFrame->document()->printing());
2934 #endif
2935
2936         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2937         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2938
2939         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2940         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2941
2942 #if PLATFORM(MAC)
2943         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
2944             ASSERT(!m_printContext);
2945             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
2946         } else
2947 #endif
2948         {
2949             size_t pageCount = m_printContext->pageCount();
2950             for (uint32_t page = first; page < first + count; ++page) {
2951                 if (page >= pageCount)
2952                     break;
2953
2954                 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2955                 CGPDFContextBeginPage(context.get(), pageInfo.get());
2956
2957                 GraphicsContext ctx(context.get());
2958                 ctx.scale(FloatSize(1, -1));
2959                 ctx.translate(0, -m_printContext->pageRect(page).height());
2960                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
2961
2962                 CGPDFContextEndPage(context.get());
2963             }
2964         }
2965         CGPDFContextClose(context.get());
2966     }
2967
2968     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2969 }
2970
2971 #elif PLATFORM(GTK)
2972
2973 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
2974 {
2975     beginPrinting(frameID, printInfo);
2976     if (m_printContext && m_printOperation) {
2977         m_printOperation->startPrint(m_printContext.get(), callbackID);
2978         return;
2979     }
2980
2981     send(Messages::WebPageProxy::VoidCallback(callbackID));
2982 }
2983 #endif
2984
2985 void WebPage::setMediaVolume(float volume)
2986 {
2987     m_page->setMediaVolume(volume);
2988 }
2989
2990 void WebPage::runModal()
2991 {
2992     if (m_isClosed)
2993         return;
2994     if (m_isRunningModal)
2995         return;
2996
2997     m_isRunningModal = true;
2998     send(Messages::WebPageProxy::RunModal());
2999     RunLoop::run();
3000     ASSERT(!m_isRunningModal);
3001 }
3002
3003 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3004 {
3005     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3006 }
3007
3008 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3009 {
3010     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3011         return true;
3012     return platformCanHandleRequest(request);
3013 }
3014
3015 #if PLATFORM(MAC) && !defined(BUILDING_ON_SNOW_LEOPARD)
3016 void WebPage::handleAlternativeTextUIResult(const String& result)
3017 {
3018     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3019     if (!frame)
3020         return;
3021     frame->editor()->handleAlternativeTextUIResult(result);
3022 }
3023 #endif
3024
3025 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3026 {
3027     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3028 }
3029
3030 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3031 {
3032     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3033 }
3034
3035 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3036 {
3037     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3038 }
3039
3040 String WebPage::viewportConfigurationAsText(int deviceDPI, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
3041 {
3042     ViewportArguments arguments = mainFrame()->document()->viewportArguments();
3043     ViewportAttributes attrs = WebCore::computeViewportAttributes(arguments, /* default layout width for non-mobile pages */ 980, deviceWidth, deviceHeight, deviceDPI, IntSize(availableWidth, availableHeight));
3044     WebCore::restrictMinimumScaleFactorToViewportSize(attrs, IntSize(availableWidth, availableHeight));
3045     WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(attrs);
3046     return String::format("viewport size %dx%d scale %f with limits [%f, %f] and userScalable %f\n", attrs.layoutSize.width(), attrs.layoutSize.height(), attrs.initialScale, attrs.minimumScale, attrs.maximumScale, attrs.userScalable);
3047 }
3048
3049 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3050 {
3051     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3052     if (!frame || !frame->editor()->canEdit())
3053         return;
3054
3055     Vector<CompositionUnderline> underlines;
3056     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3057     frame->editor()->setComposition(compositionString, underlines, from, from + length);
3058 }
3059
3060 bool WebPage::hasCompositionForTesting()
3061 {
3062     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3063     return frame && frame->editor()->hasComposition();
3064 }
3065
3066 void WebPage::confirmCompositionForTesting(const String& compositionString)
3067 {
3068     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3069     if (!frame || !frame->editor()->canEdit())
3070         return;
3071
3072     if (compositionString.isNull())
3073         frame->editor()->confirmComposition();
3074     frame->editor()->confirmComposition(compositionString);
3075 }
3076
3077 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3078 {
3079     if (m_numWheelEventHandlers == numWheelEventHandlers)
3080         return;
3081
3082     m_numWheelEventHandlers = numWheelEventHandlers;
3083     recomputeShortCircuitHorizontalWheelEventsState();
3084 }
3085
3086 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3087 {
3088     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3089         return scrollbar->enabled();
3090
3091     return false;
3092 }
3093
3094 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3095 {
3096     if (FrameView* frameView = mainFrame->view()) {
3097         if (hasEnabledHorizontalScrollbar(frameView))
3098             return true;
3099     }
3100
3101     for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext()) {
3102         FrameView* frameView = frame->view();
3103         if (!frameView)
3104             continue;
3105
3106         const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3107         if (!scrollableAreas)
3108             continue;
3109
3110         for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3111             ScrollableArea* scrollableArea = *it;
3112             if (!scrollableArea->isOnActivePage())
3113                 continue;
3114
3115             if (hasEnabledHorizontalScrollbar(scrollableArea))
3116                 return true;
3117         }
3118     }
3119
3120     return false;
3121 }
3122
3123 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3124 {
3125     bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3126
3127     if (canShortCircuitHorizontalWheelEvents) {
3128         // Check if we have any horizontal scroll bars on the page.
3129         if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3130             canShortCircuitHorizontalWheelEvents = false;
3131     }
3132
3133     if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3134         return;
3135
3136     m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3137     send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3138 }
3139
3140 Frame* WebPage::mainFrame() const
3141 {
3142     return m_page ? m_page->mainFrame() : 0;
3143 }
3144
3145 FrameView* WebPage::mainFrameView() const
3146 {
3147     if (Frame* frame = mainFrame())
3148         return frame->view();
3149     
3150     return 0;
3151 }
3152
3153 #if ENABLE(PAGE_VISIBILITY_API)
3154 void WebPage::setVisibilityState(int visibilityState, bool isInitialState)
3155 {
3156     if (!m_page)
3157         return;
3158     m_page->setVisibilityState(static_cast<WebCore::PageVisibilityState>(visibilityState), isInitialState);
3159 }
3160 #endif
3161
3162 } // namespace WebKit