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