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