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