20e8e926a5f7af4c06fd7bda67bb4798a8e986b0
[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->setAcceleratedCompositingForOverflowScrollEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingForOverflowScrollEnabledKey()));
2328     settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2329     settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2330     settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2331     settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2332     settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2333     settings->setShowTiledScrollingIndicator(store.getBoolValueForKey(WebPreferencesKey::tiledScrollingIndicatorVisibleKey()));
2334     settings->setAggressiveTileRetentionEnabled(store.getBoolValueForKey(WebPreferencesKey::aggressiveTileRetentionEnabledKey()));
2335     settings->setCSSCustomFilterEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCustomFilterEnabledKey()));
2336     RuntimeEnabledFeatures::setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2337     settings->setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2338     settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2339     settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2340     settings->setAccelerated2dCanvasEnabled(store.getBoolValueForKey(WebPreferencesKey::accelerated2dCanvasEnabledKey()));
2341     settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2342     settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2343     settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2344     settings->setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2345     settings->setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2346 #if ENABLE(SMOOTH_SCROLLING)
2347     settings->setEnableScrollAnimator(store.getBoolValueForKey(WebPreferencesKey::scrollAnimatorEnabledKey()));
2348 #endif
2349     settings->setInteractiveFormValidationEnabled(store.getBoolValueForKey(WebPreferencesKey::interactiveFormValidationEnabledKey()));
2350
2351 #if ENABLE(SQL_DATABASE)
2352     DatabaseManager::manager().setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2353 #endif
2354
2355 #if ENABLE(FULLSCREEN_API)
2356     settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2357 #endif
2358
2359     settings->setLocalStorageDatabasePath(WebProcess::shared().supplement<WebKeyValueStorageManager>()->localStorageDirectory());
2360
2361 #if USE(AVFOUNDATION)
2362     settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2363 #endif
2364
2365 #if PLATFORM(MAC) || (PLATFORM(QT) && USE(QTKIT))
2366     settings->setQTKitEnabled(store.getBoolValueForKey(WebPreferencesKey::isQTKitEnabledKey()));
2367 #endif
2368
2369 #if ENABLE(WEB_AUDIO)
2370     settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2371 #endif
2372
2373     settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2374     settings->setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2375     settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2376     settings->setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2377     settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2378
2379 #if ENABLE(VIDEO_TRACK)
2380     settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2381     settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2382     settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2383 #endif
2384
2385 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2386     settings->setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2387 #endif
2388
2389     settings->setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2390     settings->setStorageBlockingPolicy(static_cast<SecurityOrigin::StorageBlockingPolicy>(store.getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
2391     settings->setCookieEnabled(store.getBoolValueForKey(WebPreferencesKey::cookieEnabledKey()));
2392
2393     settings->setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2394
2395     settings->setScrollingPerformanceLoggingEnabled(m_scrollingPerformanceLoggingEnabled);
2396
2397     settings->setPlugInSnapshottingEnabled(store.getBoolValueForKey(WebPreferencesKey::plugInSnapshottingEnabledKey()));
2398     settings->setUsesEncodingDetector(store.getBoolValueForKey(WebPreferencesKey::usesEncodingDetectorKey()));
2399
2400 #if ENABLE(TEXT_AUTOSIZING)
2401     settings->setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2402 #endif
2403
2404     settings->setLogsPageMessagesToSystemConsoleEnabled(store.getBoolValueForKey(WebPreferencesKey::logsPageMessagesToSystemConsoleEnabledKey()));
2405     settings->setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2406
2407     settings->setSmartInsertDeleteEnabled(store.getBoolValueForKey(WebPreferencesKey::smartInsertDeleteEnabledKey()));
2408     settings->setShowsURLsInToolTips(store.getBoolValueForKey(WebPreferencesKey::showsURLsInToolTipsEnabledKey()));
2409
2410     platformPreferencesDidChange(store);
2411
2412     if (m_drawingArea)
2413         m_drawingArea->updatePreferences(store);
2414 }
2415
2416 #if ENABLE(INSPECTOR)
2417 WebInspector* WebPage::inspector()
2418 {
2419     if (m_isClosed)
2420         return 0;
2421     if (!m_inspector)
2422         m_inspector = WebInspector::create(this, m_inspectorClient);
2423     return m_inspector.get();
2424 }
2425 #endif
2426
2427 #if ENABLE(FULLSCREEN_API)
2428 WebFullScreenManager* WebPage::fullScreenManager()
2429 {
2430     if (!m_fullScreenManager)
2431         m_fullScreenManager = WebFullScreenManager::create(this);
2432     return m_fullScreenManager.get();
2433 }
2434 #endif
2435
2436 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2437 {
2438     if (m_notificationPermissionRequestManager)
2439         return m_notificationPermissionRequestManager.get();
2440
2441     m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2442     return m_notificationPermissionRequestManager.get();
2443 }
2444
2445 #if !PLATFORM(GTK) && !PLATFORM(MAC)
2446 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2447 {
2448     Node* node = evt->target()->toNode();
2449     ASSERT(node);
2450     Frame* frame = node->document()->frame();
2451     ASSERT(frame);
2452
2453     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2454     if (!keyEvent)
2455         return false;
2456
2457     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
2458
2459     if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2460         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2461         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2462         // (e.g. Tab that inserts a Tab character, or Enter).
2463         return !command.isTextInsertion() && command.execute(evt);
2464     }
2465
2466     if (command.execute(evt))
2467         return true;
2468
2469     // Don't allow text insertion for nodes that cannot edit.
2470     if (!frame->editor()->canEdit())
2471         return false;
2472
2473     // Don't insert null or control characters as they can result in unexpected behaviour
2474     if (evt->charCode() < ' ')
2475         return false;
2476
2477     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
2478 }
2479 #endif
2480
2481 #if ENABLE(DRAG_SUPPORT)
2482
2483 #if PLATFORM(QT) || PLATFORM(GTK)
2484 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2485 {
2486     if (!m_page) {
2487         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2488 #if PLATFORM(QT)
2489         QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2490         delete data;
2491 #elif PLATFORM(GTK)
2492         DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2493         data->deref();
2494 #endif
2495         return;
2496     }
2497
2498     switch (action) {
2499     case DragControllerActionEntered:
2500         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2501         break;
2502
2503     case DragControllerActionUpdated:
2504         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2505         break;
2506
2507     case DragControllerActionExited:
2508         m_page->dragController()->dragExited(&dragData);
2509         break;
2510
2511     case DragControllerActionPerformDrag: {
2512         m_page->dragController()->performDrag(&dragData);
2513         break;
2514     }
2515
2516     default:
2517         ASSERT_NOT_REACHED();
2518     }
2519     // DragData does not delete its platformData so we need to do that here.
2520 #if PLATFORM(QT)
2521     QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2522     delete data;
2523 #elif PLATFORM(GTK)
2524     DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2525     data->deref();
2526 #endif
2527 }
2528
2529 #else
2530 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)
2531 {
2532     if (!m_page) {
2533         send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2534         return;
2535     }
2536
2537     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2538     switch (action) {
2539     case DragControllerActionEntered:
2540         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2541         break;
2542
2543     case DragControllerActionUpdated:
2544         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2545         break;
2546         
2547     case DragControllerActionExited:
2548         m_page->dragController()->dragExited(&dragData);
2549         break;
2550         
2551     case DragControllerActionPerformDrag: {
2552         ASSERT(!m_pendingDropSandboxExtension);
2553
2554         m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2555         for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2556             if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2557                 m_pendingDropExtensionsForFileUpload.append(extension);
2558         }
2559
2560         m_page->dragController()->performDrag(&dragData);
2561
2562         // If we started loading a local file, the sandbox extension tracker would have adopted this
2563         // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2564         if (m_pendingDropSandboxExtension) {
2565             m_pendingDropSandboxExtension->invalidate();
2566             m_pendingDropSandboxExtension = nullptr;
2567         }
2568         for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2569             m_pendingDropExtensionsForFileUpload[i]->invalidate();
2570
2571         m_pendingDropExtensionsForFileUpload.clear();
2572         break;
2573     }
2574
2575     default:
2576         ASSERT_NOT_REACHED();
2577     }
2578 }
2579 #endif
2580
2581 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2582 {
2583     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2584     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2585
2586     m_page->dragController()->dragEnded();
2587     FrameView* view = m_page->mainFrame()->view();
2588     if (!view)
2589         return;
2590     // FIXME: These are fake modifier keys here, but they should be real ones instead.
2591     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2592     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2593 }
2594
2595 void WebPage::willPerformLoadDragDestinationAction()
2596 {
2597     m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2598 }
2599
2600 void WebPage::mayPerformUploadDragDestinationAction()
2601 {
2602     for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2603         m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2604     m_pendingDropExtensionsForFileUpload.clear();
2605 }
2606     
2607 #endif // ENABLE(DRAG_SUPPORT)
2608
2609 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2610 {
2611     return m_undoStepMap.get(stepID).get();
2612 }
2613
2614 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2615 {
2616     m_undoStepMap.set(stepID, entry);
2617 }
2618
2619 void WebPage::removeWebEditCommand(uint64_t stepID)
2620 {
2621     m_undoStepMap.remove(stepID);
2622 }
2623
2624 void WebPage::unapplyEditCommand(uint64_t stepID)
2625 {
2626     WebUndoStep* step = webUndoStep(stepID);
2627     if (!step)
2628         return;
2629
2630     step->step()->unapply();
2631 }
2632
2633 void WebPage::reapplyEditCommand(uint64_t stepID)
2634 {
2635     WebUndoStep* step = webUndoStep(stepID);
2636     if (!step)
2637         return;
2638
2639     m_isInRedo = true;
2640     step->step()->reapply();
2641     m_isInRedo = false;
2642 }
2643
2644 void WebPage::didRemoveEditCommand(uint64_t commandID)
2645 {
2646     removeWebEditCommand(commandID);
2647 }
2648
2649 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2650 {
2651     m_activePopupMenu = menu;
2652 }
2653
2654 #if ENABLE(INPUT_TYPE_COLOR)
2655 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2656 {
2657     m_activeColorChooser = colorChooser;
2658 }
2659
2660 void WebPage::didEndColorChooser()
2661 {
2662     m_activeColorChooser->didEndChooser();
2663 }
2664
2665 void WebPage::didChooseColor(const WebCore::Color& color)
2666 {
2667     m_activeColorChooser->didChooseColor(color);
2668 }
2669 #endif
2670
2671 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2672 {
2673     m_activeOpenPanelResultListener = openPanelResultListener;
2674 }
2675
2676 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2677 {
2678     return m_page->findString(target, options);
2679 }
2680
2681 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2682 {
2683     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2684 }
2685
2686 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2687 {
2688     m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2689 }
2690
2691 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2692 {
2693     m_findController.getImageForFindMatch(matchIndex);
2694 }
2695
2696 void WebPage::selectFindMatch(uint32_t matchIndex)
2697 {
2698     m_findController.selectFindMatch(matchIndex);
2699 }
2700
2701 void WebPage::hideFindUI()
2702 {
2703     m_findController.hideFindUI();
2704 }
2705
2706 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2707 {
2708     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2709 }
2710
2711 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2712 {
2713     changeSelectedIndex(newIndex);
2714     m_activePopupMenu = 0;
2715 }
2716
2717 void WebPage::changeSelectedIndex(int32_t index)
2718 {
2719     if (!m_activePopupMenu)
2720         return;
2721
2722     m_activePopupMenu->didChangeSelectedIndex(index);
2723 }
2724
2725 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2726 {
2727     if (!m_activeOpenPanelResultListener)
2728         return;
2729
2730     m_activeOpenPanelResultListener->didChooseFiles(files);
2731     m_activeOpenPanelResultListener = 0;
2732 }
2733
2734 void WebPage::didCancelForOpenPanel()
2735 {
2736     m_activeOpenPanelResultListener = 0;
2737 }
2738
2739 #if ENABLE(WEB_PROCESS_SANDBOX)
2740 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2741 {
2742     SandboxExtension::create(handle)->consumePermanently();
2743 }
2744 #endif
2745
2746 #if ENABLE(GEOLOCATION)
2747 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2748 {
2749     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2750 }
2751 #endif
2752
2753 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2754 {
2755     notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2756 }
2757
2758 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2759 {
2760     Frame* frame = m_page->focusController()->focusedOrMainFrame();
2761     frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2762 }
2763
2764 void WebPage::changeSpellingToWord(const String& word)
2765 {
2766     replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2767 }
2768
2769 void WebPage::unmarkAllMisspellings()
2770 {
2771     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2772         if (Document* document = frame->document())
2773             document->markers()->removeMarkers(DocumentMarker::Spelling);
2774     }
2775 }
2776
2777 void WebPage::unmarkAllBadGrammar()
2778 {
2779     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2780         if (Document* document = frame->document())
2781             document->markers()->removeMarkers(DocumentMarker::Grammar);
2782     }
2783 }
2784
2785 #if USE(APPKIT)
2786 void WebPage::uppercaseWord()
2787 {
2788     m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2789 }
2790
2791 void WebPage::lowercaseWord()
2792 {
2793     m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2794 }
2795
2796 void WebPage::capitalizeWord()
2797 {
2798     m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2799 }
2800 #endif
2801     
2802 void WebPage::setTextForActivePopupMenu(int32_t index)
2803 {
2804     if (!m_activePopupMenu)
2805         return;
2806
2807     m_activePopupMenu->setTextForIndex(index);
2808 }
2809
2810 #if PLATFORM(GTK)
2811 void WebPage::failedToShowPopupMenu()
2812 {
2813     if (!m_activePopupMenu)
2814         return;
2815
2816     m_activePopupMenu->client()->popupDidHide();
2817 }
2818 #endif
2819
2820 #if ENABLE(CONTEXT_MENUS)
2821 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2822 {
2823     if (!m_contextMenu)
2824         return;
2825
2826     m_contextMenu->itemSelected(item);
2827     m_contextMenu = 0;
2828 }
2829 #endif
2830
2831 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
2832 {
2833     bool selectReplacement = true;
2834     bool smartReplace = false;
2835     return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
2836 }
2837
2838 void WebPage::clearSelection()
2839 {
2840     m_page->focusController()->focusedOrMainFrame()->selection()->clear();
2841 }
2842
2843 bool WebPage::mainFrameHasCustomRepresentation() const
2844 {
2845     if (Frame* frame = mainFrame())
2846         return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
2847
2848     return false;
2849 }
2850
2851 void WebPage::didChangeScrollOffsetForMainFrame()
2852 {
2853     Frame* frame = m_page->mainFrame();
2854     IntPoint scrollPosition = frame->view()->scrollPosition();
2855     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
2856     IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
2857
2858     bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
2859     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
2860     bool isPinnedToTopSide = (scrollPosition.y() <= minimumScrollPosition.y());
2861     bool isPinnedToBottomSide = (scrollPosition.y() >= maximumScrollPosition.y());
2862
2863     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide || isPinnedToTopSide != m_cachedMainFrameIsPinnedToTopSide || isPinnedToBottomSide != m_cachedMainFrameIsPinnedToBottomSide) {
2864         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide, isPinnedToTopSide, isPinnedToBottomSide));
2865         
2866         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
2867         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
2868         m_cachedMainFrameIsPinnedToTopSide = isPinnedToTopSide;
2869         m_cachedMainFrameIsPinnedToBottomSide = isPinnedToBottomSide;
2870     }
2871 }
2872
2873 void WebPage::mainFrameDidLayout()
2874 {
2875     unsigned pageCount = m_page->pageCount();
2876     if (pageCount != m_cachedPageCount) {
2877         send(Messages::WebPageProxy::DidChangePageCount(pageCount));
2878         m_cachedPageCount = pageCount;
2879     }
2880
2881 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
2882     if (m_drawingArea && m_drawingArea->layerTreeHost()) {
2883         double red, green, blue, alpha;
2884         m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
2885         RGBA32 rgba = makeRGBA32FromFloats(red, green, blue, alpha);
2886         if (m_backgroundColor.rgb() != rgba) {
2887             m_backgroundColor.setRGB(rgba);
2888             m_drawingArea->layerTreeHost()->setBackgroundColor(m_backgroundColor);
2889         }
2890     }
2891 #endif
2892 }
2893
2894 void WebPage::addPluginView(PluginView* pluginView)
2895 {
2896     ASSERT(!m_pluginViews.contains(pluginView));
2897
2898     m_pluginViews.add(pluginView);
2899 }
2900
2901 void WebPage::removePluginView(PluginView* pluginView)
2902 {
2903     ASSERT(m_pluginViews.contains(pluginView));
2904
2905     m_pluginViews.remove(pluginView);
2906 }
2907
2908 #if PLATFORM(MAC)
2909 void WebPage::setWindowIsVisible(bool windowIsVisible)
2910 {
2911     m_windowIsVisible = windowIsVisible;
2912
2913     corePage()->focusController()->setContainingWindowIsVisible(windowIsVisible);
2914
2915     // Tell all our plug-in views that the window visibility changed.
2916     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2917         (*it)->setWindowIsVisible(windowIsVisible);
2918 }
2919
2920 void WebPage::windowAndViewFramesChanged(const IntRect& windowFrameInScreenCoordinates, const IntRect& viewFrameInWindowCoordinates, const IntPoint& accessibilityViewCoordinates)
2921 {
2922     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
2923     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
2924     m_accessibilityPosition = accessibilityViewCoordinates;
2925     
2926     // Tell all our plug-in views that the window and view frames have changed.
2927     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2928         (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
2929 }
2930 #endif
2931
2932 void WebPage::viewExposedRectChanged(const FloatRect& exposedRect)
2933 {
2934     m_drawingArea->setExposedRect(exposedRect);
2935 }
2936
2937 void WebPage::setMainFrameIsScrollable(bool isScrollable)
2938 {
2939     m_mainFrameIsScrollable = isScrollable;
2940     m_drawingArea->mainFrameScrollabilityChanged(isScrollable);
2941
2942     if (FrameView* frameView = m_mainFrame->coreFrame()->view()) {
2943         frameView->setCanHaveScrollbars(isScrollable);
2944         frameView->setProhibitsScrolling(!isScrollable);
2945     }
2946 }
2947
2948 bool WebPage::windowIsFocused() const
2949 {
2950     return m_page->focusController()->isActive();
2951 }
2952
2953 bool WebPage::windowAndWebPageAreFocused() const
2954 {
2955 #if PLATFORM(MAC)
2956     if (!m_windowIsVisible)
2957         return false;
2958 #endif
2959     return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
2960 }
2961
2962 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder)
2963 {
2964     if (decoder.messageReceiverName() == Messages::DrawingArea::messageReceiverName()) {
2965         if (m_drawingArea)
2966             m_drawingArea->didReceiveDrawingAreaMessage(connection, decoder);
2967         return;
2968     }
2969
2970 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
2971     if (decoder.messageReceiverName() == Messages::CoordinatedLayerTreeHost::messageReceiverName()) {
2972         if (m_drawingArea)
2973             m_drawingArea->didReceiveCoordinatedLayerTreeHostMessage(connection, decoder);
2974         return;
2975     }
2976 #endif
2977     
2978 #if ENABLE(INSPECTOR)
2979     if (decoder.messageReceiverName() == Messages::WebInspector::messageReceiverName()) {
2980         if (WebInspector* inspector = this->inspector())
2981             inspector->didReceiveWebInspectorMessage(connection, decoder);
2982         return;
2983     }
2984 #endif
2985
2986 #if ENABLE(FULLSCREEN_API)
2987     if (decoder.messageReceiverName() == Messages::WebFullScreenManager::messageReceiverName()) {
2988         fullScreenManager()->didReceiveMessage(connection, decoder);
2989         return;
2990     }
2991 #endif
2992
2993     didReceiveWebPageMessage(connection, decoder);
2994 }
2995
2996 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder)
2997 {   
2998     didReceiveSyncWebPageMessage(connection, decoder, replyEncoder);
2999 }
3000     
3001 InjectedBundleBackForwardList* WebPage::backForwardList()
3002 {
3003     if (!m_backForwardList)
3004         m_backForwardList = InjectedBundleBackForwardList::create(this);
3005     return m_backForwardList.get();
3006 }
3007
3008 #if PLATFORM(QT)
3009 #if ENABLE(TOUCH_ADJUSTMENT)
3010 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3011 {
3012     Node* node = 0;
3013     IntRect zoomableArea;
3014     bool foundAreaForTouchPoint = m_mainFrame->coreFrame()->eventHandler()->bestZoomableAreaForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), zoomableArea, node);
3015
3016     if (!foundAreaForTouchPoint)
3017         return;
3018
3019     ASSERT(node);
3020
3021     if (node->document() && node->document()->view())
3022         zoomableArea = node->document()->view()->contentsToWindow(zoomableArea);
3023
3024     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3025 }
3026
3027 #else
3028 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3029 {
3030     UNUSED_PARAM(area);
3031     Frame* mainframe = m_mainFrame->coreFrame();
3032     HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping);
3033
3034     Node* node = result.innerNode();
3035
3036     if (!node)
3037         return;
3038
3039     IntRect zoomableArea = node->getRect();
3040
3041     while (true) {
3042         bool found = !node->isTextNode() && !node->isShadowRoot();
3043
3044         // No candidate found, bail out.
3045         if (!found && !node->parentNode())
3046             return;
3047
3048         // Candidate found, and it is a better candidate than its parent.
3049         // NB: A parent is considered a better candidate iff the node is
3050         // contained by it and it is the only child.
3051         if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
3052             break;
3053
3054         node = node->parentNode();
3055         zoomableArea.unite(node->getRect());
3056     }
3057
3058     if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
3059         const ScrollView* view = node->document()->frame()->view();
3060         zoomableArea = view->contentsToWindow(zoomableArea);
3061     }
3062
3063     send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3064 }
3065 #endif
3066 #endif
3067
3068 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3069 {
3070     invalidate();
3071 }
3072
3073 void WebPage::SandboxExtensionTracker::invalidate()
3074 {
3075     if (m_pendingProvisionalSandboxExtension) {
3076         m_pendingProvisionalSandboxExtension->invalidate();
3077         m_pendingProvisionalSandboxExtension = 0;
3078     }
3079
3080     if (m_provisionalSandboxExtension) {
3081         m_provisionalSandboxExtension->invalidate();
3082         m_provisionalSandboxExtension = 0;
3083     }
3084
3085     if (m_committedSandboxExtension) {
3086         m_committedSandboxExtension->invalidate();
3087         m_committedSandboxExtension = 0;
3088     }
3089 }
3090
3091 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3092 {
3093     setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3094 }
3095
3096 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3097 {
3098     ASSERT_UNUSED(frame, frame->isMainFrame());
3099
3100     setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3101 }
3102
3103 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3104 {
3105     // If we get two beginLoad calls in succession, without a provisional load starting, then
3106     // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
3107     if (m_pendingProvisionalSandboxExtension) {
3108         m_pendingProvisionalSandboxExtension->invalidate();
3109         m_pendingProvisionalSandboxExtension = nullptr;
3110     }
3111     
3112     m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;    
3113 }
3114
3115 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3116 {
3117     ASSERT(frame->isMainFrame());
3118
3119     FrameLoader* frameLoader = frame->coreFrame()->loader();
3120     FrameLoadType frameLoadType = frameLoader->loadType();
3121
3122     // If the page is being reloaded, it should reuse whatever extension is committed.
3123     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3124         return true;
3125
3126     DocumentLoader* documentLoader = frameLoader->documentLoader();
3127     DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
3128     if (!documentLoader || !provisionalDocumentLoader)
3129         return false;
3130
3131     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3132         return true;
3133
3134     return false;
3135 }
3136
3137 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3138 {
3139     if (!frame->isMainFrame())
3140         return;
3141
3142     // We should only reuse the commited sandbox extension if it is not null. It can be
3143     // null if the last load was for an error page.
3144     if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
3145         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
3146         ASSERT(!m_committedSandboxExtension);
3147     }
3148
3149     ASSERT(!m_provisionalSandboxExtension);
3150
3151     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3152     if (!m_provisionalSandboxExtension)
3153         return;
3154
3155     m_provisionalSandboxExtension->consume();
3156 }
3157
3158 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3159 {
3160     if (!frame->isMainFrame())
3161         return;
3162
3163     // Generally, there should be no pending extension at this stage, but we can have one if UI process
3164     // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3165     if (m_pendingProvisionalSandboxExtension) {
3166         m_pendingProvisionalSandboxExtension->invalidate();
3167         m_pendingProvisionalSandboxExtension = nullptr;
3168     }
3169
3170     // The provisional load has been committed. Invalidate the currently committed sandbox
3171     // extension and make the provisional sandbox extension the committed sandbox extension.
3172     if (m_committedSandboxExtension)
3173         m_committedSandboxExtension->invalidate();
3174
3175     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3176 }
3177
3178 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3179 {
3180     if (!frame->isMainFrame())
3181         return;
3182
3183     // Generally, there should be no pending extension at this stage, but we can have one if UI process
3184     // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3185     if (m_pendingProvisionalSandboxExtension) {
3186         m_pendingProvisionalSandboxExtension->invalidate();
3187         m_pendingProvisionalSandboxExtension = nullptr;
3188     }
3189
3190     if (!m_provisionalSandboxExtension)
3191         return;
3192
3193     m_provisionalSandboxExtension->invalidate();
3194     m_provisionalSandboxExtension = nullptr;
3195 }
3196
3197 bool WebPage::hasLocalDataForURL(const KURL& url)
3198 {
3199     if (url.isLocalFile())
3200         return true;
3201
3202     FrameLoader* frameLoader = m_page->mainFrame()->loader();
3203     DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
3204     if (documentLoader && documentLoader->subresource(url))
3205         return true;
3206
3207     return platformHasLocalDataForURL(url);
3208 }
3209
3210 void WebPage::setCustomTextEncodingName(const String& encoding)
3211 {
3212     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
3213 }
3214
3215 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3216 {
3217     WebBackForwardListProxy::removeItem(itemID);
3218 }
3219
3220 #if PLATFORM(MAC)
3221
3222 bool WebPage::isSpeaking()
3223 {
3224     bool result;
3225     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3226 }
3227
3228 void WebPage::speak(const String& string)
3229 {
3230     send(Messages::WebPageProxy::Speak(string));
3231 }
3232
3233 void WebPage::stopSpeaking()
3234 {
3235     send(Messages::WebPageProxy::StopSpeaking());
3236 }
3237
3238 #endif
3239
3240 #if PLATFORM(MAC)
3241 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3242 {
3243     Document* document = coreFrame->document();
3244     if (!document)
3245         return 0;
3246
3247     if (!document->isPluginDocument())
3248         return 0;
3249
3250     PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3251     if (!pluginView)
3252         return 0;
3253
3254     return pluginView->pdfDocumentForPrinting();
3255 }
3256 #endif // PLATFORM(MAC)
3257
3258 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3259 {
3260     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3261     if (!frame)
3262         return;
3263
3264     Frame* coreFrame = frame->coreFrame();
3265     if (!coreFrame)
3266         return;
3267
3268 #if PLATFORM(MAC)
3269     if (pdfDocumentForPrintingFrame(coreFrame))
3270         return;
3271 #endif // PLATFORM(MAC)
3272
3273     if (!m_printContext)
3274         m_printContext = adoptPtr(new PrintContext(coreFrame));
3275
3276     drawingArea()->setLayerTreeStateIsFrozen(true);
3277     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3278
3279     float fullPageHeight;
3280     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3281
3282 #if PLATFORM(GTK)
3283     if (!m_printOperation)
3284         m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3285 #endif
3286 }
3287
3288 void WebPage::endPrinting()
3289 {
3290     drawingArea()->setLayerTreeStateIsFrozen(false);
3291 #if PLATFORM(GTK)
3292     m_printOperation = 0;
3293 #endif
3294     m_printContext = nullptr;
3295 }
3296
3297 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3298 {
3299     Vector<IntRect> resultPageRects;
3300     double resultTotalScaleFactorForPrinting = 1;
3301
3302     beginPrinting(frameID, printInfo);
3303
3304     if (m_printContext) {
3305         resultPageRects = m_printContext->pageRects();
3306         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3307     }
3308 #if PLATFORM(MAC)
3309     else
3310         computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3311 #endif // PLATFORM(MAC)
3312
3313     // If we're asked to print, we should actually print at least a blank page.
3314     if (resultPageRects.isEmpty())
3315         resultPageRects.append(IntRect(0, 0, 1, 1));
3316
3317     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3318 }
3319
3320 #if PLATFORM(MAC)
3321 void WebPage::drawRectToImage(uint64_t frameID, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, uint64_t callbackID)
3322 {
3323     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3324     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3325
3326     RefPtr<WebImage> image;
3327
3328 #if USE(CG)
3329     if (coreFrame) {
3330 #if PLATFORM(MAC)
3331         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3332 #else
3333         ASSERT(coreFrame->document()->printing());
3334 #endif
3335
3336         RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(imageSize, ShareableBitmap::SupportsAlpha);
3337         OwnPtr<GraphicsContext> graphicsContext = bitmap->createGraphicsContext();
3338
3339         float printingScale = static_cast<float>(imageSize.width()) / rect.width();
3340         graphicsContext->scale(FloatSize(printingScale, printingScale));
3341
3342 #if PLATFORM(MAC)
3343         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3344             ASSERT(!m_printContext);
3345             graphicsContext->scale(FloatSize(1, -1));
3346             graphicsContext->translate(0, -rect.height());
3347             drawPDFDocument(graphicsContext->platformContext(), pdfDocument.get(), printInfo, rect);
3348         } else
3349 #endif
3350         {
3351             m_printContext->spoolRect(*graphicsContext, rect);
3352         }
3353
3354         image = WebImage::create(bitmap.release());
3355     }
3356 #endif
3357
3358     ShareableBitmap::Handle handle;
3359
3360     if (image)
3361         image->bitmap()->createHandle(handle, SharedMemory::ReadOnly);
3362
3363     send(Messages::WebPageProxy::ImageCallback(handle, callbackID));
3364 }
3365
3366 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3367 {
3368     WebFrame* frame = WebProcess::shared().webFrame(frameID);
3369     Frame* coreFrame = frame ? frame->coreFrame() : 0;
3370
3371     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3372
3373 #if USE(CG)
3374     if (coreFrame) {
3375
3376 #if PLATFORM(MAC)
3377         ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3378 #else
3379         ASSERT(coreFrame->document()->printing());
3380 #endif
3381
3382         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3383         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3384
3385         CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3386         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3387
3388 #if PLATFORM(MAC)
3389         if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3390             ASSERT(!m_printContext);
3391             drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3392         } else
3393 #endif
3394         {
3395             size_t pageCount = m_printContext->pageCount();
3396             for (uint32_t page = first; page < first + count; ++page) {
3397                 if (page >= pageCount)
3398                     break;
3399
3400                 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3401                 CGPDFContextBeginPage(context.get(), pageInfo.get());
3402
3403                 GraphicsContext ctx(context.get());
3404                 ctx.scale(FloatSize(1, -1));
3405                 ctx.translate(0, -m_printContext->pageRect(page).height());
3406                 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3407
3408                 CGPDFContextEndPage(context.get());
3409             }
3410         }
3411         CGPDFContextClose(context.get());
3412     }
3413 #endif
3414
3415     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3416 }
3417
3418 #elif PLATFORM(GTK)
3419
3420 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3421 {
3422     beginPrinting(frameID, printInfo);
3423     if (m_printContext && m_printOperation) {
3424         m_printOperation->startPrint(m_printContext.get(), callbackID);
3425         return;
3426     }
3427
3428     send(Messages::WebPageProxy::VoidCallback(callbackID));
3429 }
3430 #endif
3431
3432 void WebPage::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size)
3433 {
3434     send(Messages::WebPageProxy::SavePDFToFileInDownloadsFolder(suggestedFilename, originatingURLString, CoreIPC::DataReference(data, size)));
3435 }
3436
3437 #if PLATFORM(MAC)
3438 void WebPage::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID)
3439 {
3440     send(Messages::WebPageProxy::SavePDFToTemporaryFolderAndOpenWithNativeApplication(suggestedFilename, originatingURLString, CoreIPC::DataReference(data, size), pdfUUID));
3441 }
3442 #endif
3443
3444 void WebPage::setMediaVolume(float volume)
3445 {
3446     m_page->setMediaVolume(volume);
3447 }
3448
3449 void WebPage::setMayStartMediaWhenInWindow(bool mayStartMedia)
3450 {
3451     if (mayStartMedia == m_mayStartMediaWhenInWindow)
3452         return;
3453
3454     m_mayStartMediaWhenInWindow = mayStartMedia;
3455     if (m_mayStartMediaWhenInWindow && m_page->isOnscreen())
3456         m_setCanStartMediaTimer.startOneShot(0);
3457 }
3458
3459 void WebPage::runModal()
3460 {
3461     if (m_isClosed)
3462         return;
3463     if (m_isRunningModal)
3464         return;
3465
3466     m_isRunningModal = true;
3467     send(Messages::WebPageProxy::RunModal());
3468     RunLoop::run();
3469     ASSERT(!m_isRunningModal);
3470 }
3471
3472 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3473 {
3474     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3475 }
3476
3477 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3478 {
3479     if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3480         return true;
3481
3482 #if ENABLE(BLOB)
3483     if (request.url().protocolIs("blob"))
3484         return true;
3485 #endif
3486
3487     return platformCanHandleRequest(request);
3488 }
3489
3490 #if USE(TILED_BACKING_STORE)
3491 void WebPage::commitPageTransitionViewport()
3492 {
3493     m_drawingArea->setLayerTreeStateIsFrozen(false);
3494 }
3495 #endif
3496
3497 #if PLATFORM(MAC)
3498 void WebPage::handleAlternativeTextUIResult(const String& result)
3499 {
3500     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3501     if (!frame)
3502         return;
3503     frame->editor()->handleAlternativeTextUIResult(result);
3504 }
3505 #endif
3506
3507 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3508 {
3509     mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3510 }
3511
3512 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3513 {
3514     mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3515 }
3516
3517 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3518 {
3519     mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3520 }
3521
3522 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3523 {
3524     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3525     if (!frame || !frame->editor()->canEdit())
3526         return;
3527
3528     Vector<CompositionUnderline> underlines;
3529     underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3530     frame->editor()->setComposition(compositionString, underlines, from, from + length);
3531 }
3532
3533 bool WebPage::hasCompositionForTesting()
3534 {
3535     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3536     return frame && frame->editor()->hasComposition();
3537 }
3538
3539 void WebPage::confirmCompositionForTesting(const String& compositionString)
3540 {
3541     Frame* frame = m_page->focusController()->focusedOrMainFrame();
3542     if (!frame || !frame->editor()->canEdit())
3543         return;
3544
3545     if (compositionString.isNull())
3546         frame->editor()->confirmComposition();
3547     frame->editor()->confirmComposition(compositionString);
3548 }
3549
3550 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3551 {
3552     if (m_numWheelEventHandlers == numWheelEventHandlers)
3553         return;
3554
3555     m_numWheelEventHandlers = numWheelEventHandlers;
3556     recomputeShortCircuitHorizontalWheelEventsState();
3557 }
3558
3559 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3560 {
3561     if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3562         return scrollbar->enabled();
3563
3564     return false;
3565 }
3566
3567 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3568 {
3569     if (FrameView* frameView = mainFrame->view()) {
3570         if (hasEnabledHorizontalScrollbar(frameView))
3571             return true;
3572     }
3573
3574     for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext()) {
3575         FrameView* frameView = frame->view();
3576         if (!frameView)
3577             continue;
3578
3579         const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3580         if (!scrollableAreas)
3581             continue;
3582
3583         for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3584             ScrollableArea* scrollableArea = *it;
3585             if (!scrollableArea->scrollbarsCanBeActive())
3586                 continue;
3587
3588             if (hasEnabledHorizontalScrollbar(scrollableArea))
3589                 return true;
3590         }
3591     }
3592
3593     return false;
3594 }
3595
3596 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3597 {
3598     bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3599
3600     if (canShortCircuitHorizontalWheelEvents) {
3601         // Check if we have any horizontal scroll bars on the page.
3602         if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3603             canShortCircuitHorizontalWheelEvents = false;
3604     }
3605
3606     if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3607         return;
3608
3609     m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3610     send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3611 }
3612
3613 Frame* WebPage::mainFrame() const
3614 {
3615     return m_page ? m_page->mainFrame() : 0;
3616 }
3617
3618 FrameView* WebPage::mainFrameView() const
3619 {
3620     if (Frame* frame = mainFrame())
3621         return frame->view();
3622     
3623     return 0;
3624 }
3625
3626 #if ENABLE(PAGE_VISIBILITY_API) || ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
3627 void WebPage::setVisibilityState(uint32_t visibilityState, bool isInitialState)
3628 {
3629     if (!m_page)
3630         return;
3631
3632     WebCore::PageVisibilityState state = static_cast<WebCore::PageVisibilityState>(visibilityState);
3633
3634 #if ENABLE(PAGE_VISIBILITY_API)
3635     if (m_visibilityState == state)
3636         return;
3637
3638     FrameView* view = m_page->mainFrame() ? m_page->mainFrame()->view() : 0;
3639
3640     if (state == WebCore::PageVisibilityStateVisible) {
3641         m_page->didMoveOnscreen();
3642         if (view)
3643             view->show();
3644     }
3645
3646     m_page->setVisibilityState(state, isInitialState);
3647     m_visibilityState = state;
3648
3649     if (state == WebCore::PageVisibilityStateHidden) {
3650         m_page->willMoveOffscreen();
3651         if (view)
3652             view->hide();
3653     }
3654 #endif
3655
3656 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING) && !ENABLE(PAGE_VISIBILITY_API)
3657     m_page->setVisibilityState(state, isInitialState);
3658 #endif
3659 }
3660 #endif
3661
3662 void WebPage::setScrollingPerformanceLoggingEnabled(bool enabled)
3663 {
3664     m_scrollingPerformanceLoggingEnabled = enabled;
3665
3666     FrameView* frameView = m_mainFrame->coreFrame()->view();
3667     if (!frameView)
3668         return;
3669
3670     frameView->setScrollingPerformanceLoggingEnabled(enabled);
3671 }
3672
3673 bool WebPage::canPluginHandleResponse(const ResourceResponse& response)
3674 {
3675 #if ENABLE(NETSCAPE_PLUGIN_API)
3676     String pluginPath;
3677     uint32_t pluginLoadPolicy;
3678     
3679     if (!sendSync(Messages::WebPageProxy::GetPluginPath(response.mimeType(), response.url().string(), response.url().string(), response.url().string()), Messages::WebPageProxy::GetPluginPath::Reply(pluginPath, pluginLoadPolicy)))
3680         return false;
3681
3682     return pluginLoadPolicy != PluginModuleBlocked && !pluginPath.isEmpty();
3683 #else
3684     return false;
3685 #endif
3686 }
3687
3688 bool WebPage::shouldUseCustomRepresentationForResponse(const ResourceResponse& response)
3689 {
3690     if (!m_mimeTypesWithCustomRepresentations.contains(response.mimeType()))
3691         return false;
3692
3693     // If a plug-in exists that claims to support this response, it should take precedence over the custom representation.
3694     return !canPluginHandleResponse(response);
3695 }
3696
3697 #if PLATFORM(QT) || PLATFORM(GTK)
3698 static Frame* targetFrameForEditing(WebPage* page)
3699 {
3700     Frame* targetFrame = page->corePage()->focusController()->focusedOrMainFrame();
3701
3702     if (!targetFrame || !targetFrame->editor())
3703         return 0;
3704
3705     Editor* editor = targetFrame->editor();
3706     if (!editor->canEdit())
3707         return 0;
3708
3709     if (editor->hasComposition()) {
3710         // We should verify the parent node of this IME composition node are
3711         // editable because JavaScript may delete a parent node of the composition
3712         // node. In this case, WebKit crashes while deleting texts from the parent
3713         // node, which doesn't exist any longer.
3714         if (PassRefPtr<Range> range = editor->compositionRange()) {
3715             Node* node = range->startContainer();
3716             if (!node || !node->isContentEditable())
3717                 return 0;
3718         }
3719     }
3720     return targetFrame;
3721 }
3722
3723 void WebPage::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength)
3724 {
3725     Frame* targetFrame = targetFrameForEditing(this);
3726     if (!targetFrame) {
3727         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3728         return;
3729     }
3730
3731     Editor* editor = targetFrame->editor();
3732     editor->confirmComposition(compositionString);
3733
3734     if (selectionStart == -1) {
3735         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3736         return;
3737     }
3738
3739     Element* scope = targetFrame->selection()->rootEditableElement();
3740     RefPtr<Range> selectionRange = TextIterator::rangeFromLocationAndLength(scope, selectionStart, selectionLength);
3741     ASSERT_WITH_MESSAGE(selectionRange, "Invalid selection: [%lld:%lld] in text of length %d", static_cast<long long>(selectionStart), static_cast<long long>(selectionLength), scope->innerText().length());
3742
3743     if (selectionRange) {
3744         VisibleSelection selection(selectionRange.get(), SEL_DEFAULT_AFFINITY);
3745         targetFrame->selection()->setSelection(selection);
3746     }
3747     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3748 }
3749
3750 void WebPage::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementStart, uint64_t replacementLength)
3751 {
3752     Frame* targetFrame = targetFrameForEditing(this);
3753     if (!targetFrame || !targetFrame->selection()->isContentEditable()) {
3754         send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3755         return;
3756     }
3757
3758     if (replacementLength > 0) {
3759         // The layout needs to be uptodate before setting a selection
3760         targetFrame->document()->updateLayout();
3761
3762         Element* scope = targetFrame->selection()->rootEditableElement();
3763         RefPtr<Range> replacementRange = TextIterator::rangeFromLocationAndLength(scope, replacementStart, replacementLength);
3764         targetFrame->editor()->setIgnoreCompositionSelectionChange(true);
3765         targetFrame->selection()->setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
3766         targetFrame->editor()->setIgnoreCompositionSelectionChange(false);
3767     }
3768
3769     targetFrame->editor()->setComposition(text, underlines, selectionStart, selectionEnd);
3770     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3771 }
3772
3773 void WebPage::cancelComposition()
3774 {
3775     if (Frame* targetFrame = targetFrameForEditing(this))
3776         targetFrame->editor()->cancelComposition();
3777     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3778 }
3779 #endif
3780
3781 void WebPage::didChangeSelection()
3782 {
3783     send(Messages::WebPageProxy::EditorStateChanged(editorState()));
3784 }
3785
3786 void WebPage::setMainFrameInViewSourceMode(bool inViewSourceMode)
3787 {
3788     m_mainFrame->coreFrame()->setInViewSourceMode(inViewSourceMode);
3789 }
3790
3791 void WebPage::setMinimumLayoutWidth(double minimumLayoutWidth)
3792 {
3793     if (m_minimumLayoutWidth == minimumLayoutWidth)
3794         return;
3795
3796     m_minimumLayoutWidth = minimumLayoutWidth;
3797
3798     int maximumSize = std::numeric_limits<int>::max();
3799
3800     if (minimumLayoutWidth > 0)
3801         corePage()->mainFrame()->view()->enableAutoSizeMode(true, IntSize(minimumLayoutWidth, 1), IntSize(maximumSize, maximumSize));
3802     else
3803         corePage()->mainFrame()->view()->enableAutoSizeMode(false, IntSize(), IntSize());
3804 }
3805
3806 bool WebPage::isSmartInsertDeleteEnabled()
3807 {
3808     return m_page->settings()->smartInsertDeleteEnabled();
3809 }
3810
3811 void WebPage::setSmartInsertDeleteEnabled(bool enabled)
3812 {
3813     m_page->settings()->setSmartInsertDeleteEnabled(enabled);
3814 }
3815
3816 bool WebPage::canShowMIMEType(const String& MIMEType) const
3817 {
3818     if (MIMETypeRegistry::canShowMIMEType(MIMEType))
3819         return true;
3820
3821     if (PluginData* pluginData = m_page->pluginData()) {
3822         if (pluginData->supportsMimeType(MIMEType) && m_page->settings()->arePluginsEnabled())
3823             return true;
3824     }
3825
3826     return false;
3827 }
3828
3829 void WebPage::addTextCheckingRequest(uint64_t requestID, PassRefPtr<TextCheckingRequest> request)
3830 {
3831     m_pendingTextCheckingRequestMap.add(requestID, request);
3832 }
3833
3834 void WebPage::didFinishCheckingText(uint64_t requestID, const Vector<TextCheckingResult>& result)
3835 {
3836     TextCheckingRequest* request = m_pendingTextCheckingRequestMap.get(requestID).get();
3837     if (!request)
3838         return;
3839
3840     request->didSucceed(result);
3841     m_pendingTextCheckingRequestMap.remove(requestID);
3842 }
3843
3844 void WebPage::didCancelCheckingText(uint64_t requestID)
3845 {
3846     TextCheckingRequest* request = m_pendingTextCheckingRequestMap.get(requestID).get();
3847     if (!request)
3848         return;
3849
3850     request->didCancel();
3851     m_pendingTextCheckingRequestMap.remove(requestID);
3852 }
3853
3854 } // namespace WebKit