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