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