AX: Webkit2 not sending UAZoomFocusChanged notifications
[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 "MessageID.h"
36 #include "NetscapePlugin.h"
37 #include "PageOverlay.h"
38 #include "PluginProxy.h"
39 #include "PluginView.h"
40 #include "PrintInfo.h"
41 #include "RunLoop.h"
42 #include "SessionState.h"
43 #include "ShareableBitmap.h"
44 #include "WebBackForwardList.h"
45 #include "WebBackForwardListItem.h"
46 #include "WebBackForwardListProxy.h"
47 #include "WebChromeClient.h"
48 #include "WebContextMenu.h"
49 #include "WebContextMenuClient.h"
50 #include "WebContextMessages.h"
51 #include "WebCoreArgumentCoders.h"
52 #include "WebDragClient.h"
53 #include "WebEditorClient.h"
54 #include "WebEvent.h"
55 #include "WebEventConversion.h"
56 #include "WebFrame.h"
57 #include "WebGeolocationClient.h"
58 #include "WebImage.h"
59 #include "WebInspector.h"
60 #include "WebInspectorClient.h"
61 #include "WebOpenPanelResultListener.h"
62 #include "WebPageCreationParameters.h"
63 #include "WebPageGroupProxy.h"
64 #include "WebPageProxyMessages.h"
65 #include "WebPopupMenu.h"
66 #include "WebPreferencesStore.h"
67 #include "WebProcess.h"
68 #include "WebProcessProxyMessageKinds.h"
69 #include "WebProcessProxyMessages.h"
70 #include <WebCore/AbstractDatabase.h>
71 #include <WebCore/ArchiveResource.h>
72 #include <WebCore/Chrome.h>
73 #include <WebCore/ContextMenuController.h>
74 #include <WebCore/DocumentFragment.h>
75 #include <WebCore/DocumentLoader.h>
76 #include <WebCore/DocumentMarkerController.h>
77 #include <WebCore/DragController.h>
78 #include <WebCore/DragData.h>
79 #include <WebCore/EventHandler.h>
80 #include <WebCore/FocusController.h>
81 #include <WebCore/Frame.h>
82 #include <WebCore/FrameLoaderTypes.h>
83 #include <WebCore/FrameView.h>
84 #include <WebCore/HistoryItem.h>
85 #include <WebCore/KeyboardEvent.h>
86 #include <WebCore/Page.h>
87 #include <WebCore/PlatformKeyboardEvent.h>
88 #include <WebCore/PrintContext.h>
89 #include <WebCore/RenderTreeAsText.h>
90 #include <WebCore/RenderLayer.h>
91 #include <WebCore/RenderView.h>
92 #include <WebCore/ReplaceSelectionCommand.h>
93 #include <WebCore/ResourceRequest.h>
94 #include <WebCore/SerializedScriptValue.h>
95 #include <WebCore/Settings.h>
96 #include <WebCore/SharedBuffer.h>
97 #include <WebCore/SubstituteData.h>
98 #include <WebCore/TextIterator.h>
99 #include <WebCore/markup.h>
100 #include <runtime/JSLock.h>
101 #include <runtime/JSValue.h>
102
103 #include <WebCore/Range.h>
104 #include <WebCore/VisiblePosition.h>
105
106 #if PLATFORM(MAC) || PLATFORM(WIN)
107 #include <WebCore/LegacyWebArchive.h>
108 #endif
109
110 #if ENABLE(PLUGIN_PROCESS)
111 // FIXME: This is currently Mac-specific!
112 #include "MachPort.h"
113 #endif
114
115 #if PLATFORM(QT)
116 #include "HitTestResult.h"
117 #endif
118
119 #ifndef NDEBUG
120 #include <wtf/RefCountedLeakCounter.h>
121 #endif
122
123 using namespace JSC;
124 using namespace WebCore;
125
126 namespace WebKit {
127
128 #ifndef NDEBUG
129 static WTF::RefCountedLeakCounter webPageCounter("WebPage");
130 #endif
131
132 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
133 {
134     RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
135
136     if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
137         WebProcess::shared().injectedBundle()->didCreatePage(page.get());
138
139     return page.release();
140 }
141
142 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
143     : m_viewSize(parameters.viewSize)
144     , m_drawsBackground(true)
145     , m_drawsTransparentBackground(false)
146     , m_isInRedo(false)
147     , m_isClosed(false)
148     , m_tabToLinks(false)
149 #if PLATFORM(MAC)
150     , m_windowIsVisible(false)
151     , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
152 #elif PLATFORM(WIN)
153     , m_nativeWindow(parameters.nativeWindow)
154 #endif
155     , m_findController(this)
156     , m_geolocationPermissionRequestManager(this)
157     , m_pageID(pageID)
158     , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
159     , m_canRunModal(parameters.canRunModal)
160     , m_isRunningModal(false)
161     , m_cachedMainFrameIsPinnedToLeftSide(false)
162     , m_cachedMainFrameIsPinnedToRightSide(false)
163 {
164     ASSERT(m_pageID);
165
166     Page::PageClients pageClients;
167     pageClients.chromeClient = new WebChromeClient(this);
168     pageClients.contextMenuClient = new WebContextMenuClient(this);
169     pageClients.editorClient = new WebEditorClient(this);
170     pageClients.dragClient = new WebDragClient(this);
171     pageClients.backForwardClient = WebBackForwardListProxy::create(this);
172 #if ENABLE(CLIENT_BASED_GEOLOCATION)
173     pageClients.geolocationClient = new WebGeolocationClient(this);
174 #endif
175 #if ENABLE(INSPECTOR)
176     pageClients.inspectorClient = new WebInspectorClient(this);
177 #endif
178     m_page = adoptPtr(new Page(pageClients));
179
180     // Qt does not yet call setIsInWindow. Until it does, just leave
181     // this line out so plug-ins and video will work. Eventually all platforms
182     // should call setIsInWindow and this comment and #if should be removed,
183     // leaving behind the setCanStartMedia call.
184 #if !PLATFORM(QT)
185     m_page->setCanStartMedia(false);
186 #endif
187
188     updatePreferences(parameters.store);
189
190     m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
191     m_page->setGroupName(m_pageGroup->identifier());
192
193     platformInitialize();
194     Settings::setDefaultMinDOMTimerInterval(0.004);
195
196     m_drawingArea = DrawingArea::create(this, parameters);
197     m_mainFrame = WebFrame::createMainFrame(this);
198
199     setDrawsBackground(parameters.drawsBackground);
200     setDrawsTransparentBackground(parameters.drawsTransparentBackground);
201
202     setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
203
204     setActive(parameters.isActive);
205     setFocused(parameters.isFocused);
206     setIsInWindow(parameters.isInWindow);
207
208     m_userAgent = parameters.userAgent;
209
210     WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
211     
212     if (!parameters.sessionState.isEmpty())
213         restoreSession(parameters.sessionState);
214
215 #ifndef NDEBUG
216     webPageCounter.increment();
217 #endif
218 }
219
220 WebPage::~WebPage()
221 {
222     if (m_backForwardList)
223         m_backForwardList->detach();
224
225     ASSERT(!m_page);
226
227     m_sandboxExtensionTracker.invalidate();
228
229 #if PLATFORM(MAC)
230     ASSERT(m_pluginViews.isEmpty());
231 #endif
232
233 #ifndef NDEBUG
234     webPageCounter.decrement();
235 #endif
236 }
237
238 void WebPage::dummy(bool&)
239 {
240 }
241
242 CoreIPC::Connection* WebPage::connection() const
243 {
244     return WebProcess::shared().connection();
245 }
246
247 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
248 {
249     m_contextMenuClient.initialize(client);
250 }
251
252 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
253 {
254     m_editorClient.initialize(client);
255 }
256
257 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
258 {
259     m_formClient.initialize(client);
260 }
261
262 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
263 {
264     m_loaderClient.initialize(client);
265 }
266
267 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
268 {
269     m_policyClient.initialize(client);
270 }
271
272 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
273 {
274     m_resourceLoadClient.initialize(client);
275 }
276
277 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
278 {
279     m_uiClient.initialize(client);
280 }
281
282 PassRefPtr<Plugin> WebPage::createPlugin(const Plugin::Parameters& parameters)
283 {
284     String pluginPath;
285
286     if (!WebProcess::shared().connection()->sendSync(
287             Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()), 
288             Messages::WebContext::GetPluginPath::Reply(pluginPath), 0)) {
289         return 0;
290     }
291
292     if (pluginPath.isNull())
293         return 0;
294
295 #if ENABLE(PLUGIN_PROCESS)
296     return PluginProxy::create(pluginPath);
297 #else
298     return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
299 #endif
300 }
301
302 String WebPage::renderTreeExternalRepresentation() const
303 {
304     return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
305 }
306
307 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
308 {
309     Frame* frame = m_page->focusController()->focusedOrMainFrame();
310     if (!frame)
311         return;
312     frame->editor()->command(commandName).execute(argument);
313 }
314
315 bool WebPage::isEditingCommandEnabled(const String& commandName)
316 {
317     Frame* frame = m_page->focusController()->focusedOrMainFrame();
318     if (!frame)
319         return false;
320     
321     Editor::Command command = frame->editor()->command(commandName);
322     return command.isSupported() && command.isEnabled();
323 }
324     
325 void WebPage::clearMainFrameName()
326 {
327     mainFrame()->coreFrame()->tree()->clearName();
328 }
329
330 #if USE(ACCELERATED_COMPOSITING)
331 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
332 {
333     m_drawingArea->setRootCompositingLayer(layer);
334 }
335
336 void WebPage::exitAcceleratedCompositingMode()
337 {
338     m_drawingArea->setRootCompositingLayer(0);
339 }
340 #endif
341
342 void WebPage::close()
343 {
344     if (m_isClosed)
345         return;
346
347     m_isClosed = true;
348
349     if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
350         WebProcess::shared().injectedBundle()->willDestroyPage(this);
351
352 #if ENABLE(INSPECTOR)
353     m_inspector = 0;
354 #endif
355
356     if (m_activePopupMenu) {
357         m_activePopupMenu->disconnectFromPage();
358         m_activePopupMenu = 0;
359     }
360
361     if (m_activeOpenPanelResultListener) {
362         m_activeOpenPanelResultListener->disconnectFromPage();
363         m_activeOpenPanelResultListener = 0;
364     }
365
366     m_sandboxExtensionTracker.invalidate();
367
368     m_printContext = nullptr;
369
370     m_mainFrame->coreFrame()->loader()->detachFromParent();
371     m_page.clear();
372
373     m_drawingArea.clear();
374
375     bool isRunningModal = m_isRunningModal;
376     m_isRunningModal = false;
377
378     // The WebPage can be destroyed by this call.
379     WebProcess::shared().removeWebPage(m_pageID);
380
381     if (isRunningModal)
382         WebProcess::shared().runLoop()->stop();
383 }
384
385 void WebPage::tryClose()
386 {
387     if (!m_mainFrame->coreFrame()->loader()->shouldClose())
388         return;
389
390     sendClose();
391 }
392
393 void WebPage::sendClose()
394 {
395     send(Messages::WebPageProxy::ClosePage());
396 }
397
398 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
399 {
400     loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
401 }
402
403 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
404 {
405     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
406     m_mainFrame->coreFrame()->loader()->load(request, false);
407 }
408
409 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
410 {
411     ResourceRequest request(baseURL);
412     SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
413     m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
414 }
415
416 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
417 {
418     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
419     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
420     loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
421 }
422
423 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
424 {
425     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
426     KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
427     KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString)  ;
428     loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
429 }
430
431 void WebPage::loadPlainTextString(const String& string)
432 {
433     RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
434     loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
435 }
436
437 void WebPage::stopLoadingFrame(uint64_t frameID)
438 {
439     WebFrame* frame = WebProcess::shared().webFrame(frameID);
440     if (!frame)
441         return;
442
443     frame->coreFrame()->loader()->stopForUserCancel();
444 }
445
446 void WebPage::stopLoading()
447 {
448     m_mainFrame->coreFrame()->loader()->stopForUserCancel();
449 }
450
451 void WebPage::setDefersLoading(bool defersLoading)
452 {
453     m_page->setDefersLoading(defersLoading);
454 }
455
456 void WebPage::reload(bool reloadFromOrigin)
457 {
458     m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
459 }
460
461 void WebPage::goForward(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
462 {
463     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
464     ASSERT(item);
465     if (!item)
466         return;
467
468     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
469     m_page->goToItem(item, FrameLoadTypeForward);
470 }
471
472 void WebPage::goBack(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
473 {
474     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
475     ASSERT(item);
476     if (!item)
477         return;
478
479     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
480     m_page->goToItem(item, FrameLoadTypeBack);
481 }
482
483 void WebPage::goToBackForwardItem(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
484 {
485     HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
486     ASSERT(item);
487     if (!item)
488         return;
489
490     m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
491     m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
492 }
493
494 void WebPage::layoutIfNeeded()
495 {
496     if (m_mainFrame->coreFrame()->view())
497         m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
498 }
499
500 void WebPage::setSize(const WebCore::IntSize& viewSize)
501 {
502 #if ENABLE(TILED_BACKING_STORE)
503     // If we are resizing to content ignore external attempts.
504     if (!m_resizesToContentsLayoutSize.isEmpty())
505         return;
506 #endif
507
508     if (m_viewSize == viewSize)
509         return;
510
511     Frame* frame = m_page->mainFrame();
512     
513     frame->view()->resize(viewSize);
514     frame->view()->setNeedsLayout();
515     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
516     
517     m_viewSize = viewSize;
518 }
519
520 #if ENABLE(TILED_BACKING_STORE)
521 void WebPage::setActualVisibleContentRect(const IntRect& rect)
522 {
523     Frame* frame = m_page->mainFrame();
524
525     frame->view()->setActualVisibleContentRect(rect);
526 }
527
528 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
529 {
530     if (m_resizesToContentsLayoutSize == targetLayoutSize)
531         return;
532
533     m_resizesToContentsLayoutSize = targetLayoutSize;
534
535     Frame* frame = m_page->mainFrame();
536     if (m_resizesToContentsLayoutSize.isEmpty()) {
537         frame->view()->setDelegatesScrolling(false);
538         frame->view()->setUseFixedLayout(false);
539         frame->view()->setPaintsEntireContents(false);
540     } else {
541         frame->view()->setDelegatesScrolling(true);
542         frame->view()->setUseFixedLayout(true);
543         frame->view()->setPaintsEntireContents(true);
544         frame->view()->setFixedLayoutSize(m_resizesToContentsLayoutSize);
545     }
546     frame->view()->forceLayout();
547 }
548
549 void WebPage::resizeToContentsIfNeeded()
550 {
551     if (m_resizesToContentsLayoutSize.isEmpty())
552         return;
553
554     Frame* frame = m_page->mainFrame();
555
556     IntSize contentSize = frame->view()->contentsSize();
557     if (contentSize == m_viewSize)
558         return;
559
560     m_viewSize = contentSize;
561     frame->view()->resize(m_viewSize);
562     frame->view()->setNeedsLayout();
563 }
564 #endif
565
566 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
567 {
568     Frame* frame = m_page->mainFrame();
569
570     IntPoint scrollPosition = frame->view()->scrollPosition();
571     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
572
573     // If the current scroll position in a direction is the max scroll position 
574     // we don't want to scroll at all.
575     IntSize newScrollOffset;
576     if (scrollPosition.x() < maximumScrollPosition.x())
577         newScrollOffset.setWidth(scrollOffset.width());
578     if (scrollPosition.y() < maximumScrollPosition.y())
579         newScrollOffset.setHeight(scrollOffset.height());
580
581     if (newScrollOffset.isZero())
582         return;
583
584     frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
585 }
586
587 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
588 {
589     graphicsContext.save();
590     graphicsContext.clip(rect);
591     m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
592     graphicsContext.restore();
593 }
594
595 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
596 {
597     ASSERT(m_pageOverlay);
598
599     graphicsContext.save();
600     graphicsContext.clip(rect);
601     m_pageOverlay->drawRect(graphicsContext, rect);
602     graphicsContext.restore();
603 }
604
605 double WebPage::textZoomFactor() const
606 {
607     Frame* frame = m_mainFrame->coreFrame();
608     if (!frame)
609         return 1;
610     return frame->textZoomFactor();
611 }
612
613 void WebPage::setTextZoomFactor(double zoomFactor)
614 {
615     Frame* frame = m_mainFrame->coreFrame();
616     if (!frame)
617         return;
618     frame->setTextZoomFactor(static_cast<float>(zoomFactor));
619 }
620
621 double WebPage::pageZoomFactor() const
622 {
623     Frame* frame = m_mainFrame->coreFrame();
624     if (!frame)
625         return 1;
626     return frame->pageZoomFactor();
627 }
628
629 void WebPage::setPageZoomFactor(double zoomFactor)
630 {
631     Frame* frame = m_mainFrame->coreFrame();
632     if (!frame)
633         return;
634     frame->setPageZoomFactor(static_cast<float>(zoomFactor));
635 }
636
637 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
638 {
639     Frame* frame = m_mainFrame->coreFrame();
640     if (!frame)
641         return;
642     return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
643 }
644
645 void WebPage::scaleWebView(double scale, const IntPoint& origin)
646 {
647     Frame* frame = m_mainFrame->coreFrame();
648     if (!frame)
649         return;
650     frame->scalePage(scale, origin);
651
652     send(Messages::WebPageProxy::ViewScaleFactorDidChange(scale));
653 }
654
655 double WebPage::viewScaleFactor() const
656 {
657     Frame* frame = m_mainFrame->coreFrame();
658     if (!frame)
659         return 1;
660     return frame->pageScaleFactor();
661 }
662
663 void WebPage::setUseFixedLayout(bool fixed)
664 {
665     Frame* frame = m_mainFrame->coreFrame();
666     if (!frame)
667         return;
668
669     FrameView* view = frame->view();
670     if (!view)
671         return;
672
673     view->setUseFixedLayout(fixed);
674     if (!fixed)
675         view->setFixedLayoutSize(IntSize());
676 }
677
678 void WebPage::setFixedLayoutSize(const IntSize& size)
679 {
680     Frame* frame = m_mainFrame->coreFrame();
681     if (!frame)
682         return;
683     
684     FrameView* view = frame->view();
685     if (!view)
686         return;
687
688     view->setFixedLayoutSize(size);
689     view->forceLayout();
690 }
691
692 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
693 {
694     if (m_pageOverlay)
695         pageOverlay->setPage(0);
696
697     m_pageOverlay = pageOverlay;
698     m_pageOverlay->setPage(this);
699
700     m_drawingArea->didInstallPageOverlay();
701
702     m_pageOverlay->setNeedsDisplay();
703 }
704
705 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay)
706 {
707     if (pageOverlay != m_pageOverlay)
708         return;
709
710     m_pageOverlay->setPage(0);
711     m_pageOverlay = nullptr;
712
713     m_drawingArea->didUninstallPageOverlay();
714 }
715
716 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
717 {
718     FrameView* frameView = m_mainFrame->coreFrame()->view();
719     if (!frameView)
720         return 0;
721
722     frameView->updateLayoutAndStyleIfNeededRecursive();
723
724     PaintBehavior oldBehavior = frameView->paintBehavior();
725     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
726
727     RefPtr<WebImage> snapshot = WebImage::create(rect.size(), options);
728     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
729
730     graphicsContext->save();
731     graphicsContext->translate(-rect.x(), -rect.y());
732     frameView->paint(graphicsContext.get(), rect);
733     graphicsContext->restore();
734
735     frameView->setPaintBehavior(oldBehavior);
736
737     return snapshot.release();
738 }
739
740 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
741 {
742     FrameView* frameView = m_mainFrame->coreFrame()->view();
743     if (!frameView)
744         return 0;
745
746     frameView->updateLayoutAndStyleIfNeededRecursive();
747
748     PaintBehavior oldBehavior = frameView->paintBehavior();
749     frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
750
751     bool scale = scaleFactor != 1;
752     IntSize size = rect.size();
753     if (scale) 
754         size = IntSize(ceil(rect.width() * scaleFactor), ceil(rect.height() * scaleFactor));
755
756     RefPtr<WebImage> snapshot = WebImage::create(size, options);
757     OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
758     graphicsContext->save();
759     
760     if (scale)
761         graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
762     
763     graphicsContext->translate(-rect.x(), -rect.y());
764     frameView->paintContents(graphicsContext.get(), rect);
765     graphicsContext->restore();
766
767     frameView->setPaintBehavior(oldBehavior);
768
769     return snapshot.release();
770 }
771
772 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
773 {
774     return scaledSnapshotInDocumentCoordinates(rect, 1, options);
775 }
776
777 void WebPage::pageDidScroll()
778 {
779     // Hide the find indicator.
780     m_findController.hideFindIndicator();
781
782     m_uiClient.pageDidScroll(this);
783
784     send(Messages::WebPageProxy::PageDidScroll());
785 }
786
787 #if ENABLE(TILED_BACKING_STORE)
788 void WebPage::pageDidRequestScroll(const IntSize& delta)
789 {
790     send(Messages::WebPageProxy::PageDidRequestScroll(delta));
791 }
792 #endif
793
794 WebContextMenu* WebPage::contextMenu()
795 {
796     if (!m_contextMenu)
797         m_contextMenu = WebContextMenu::create(this);
798     return m_contextMenu.get();
799 }
800
801 void WebPage::getLocationAndLengthFromRange(Range* range, uint64_t& location, uint64_t& length)
802 {
803     location = notFound;
804     length = 0;
805
806     if (!range || !range->startContainer())
807         return;
808
809     Element* selectionRoot = range->ownerDocument()->frame()->selection()->rootEditableElement();
810     Element* scope = selectionRoot ? selectionRoot : range->ownerDocument()->documentElement();
811     
812     // Mouse events may cause TSM to attempt to create an NSRange for a portion of the view
813     // that is not inside the current editable region.  These checks ensure we don't produce
814     // potentially invalid data when responding to such requests.
815     if (range->startContainer() != scope && !range->startContainer()->isDescendantOf(scope))
816         return;
817     if (range->endContainer() != scope && !range->endContainer()->isDescendantOf(scope))
818         return;
819
820     RefPtr<Range> testRange = Range::create(scope->document(), scope, 0, range->startContainer(), range->startOffset());
821     ASSERT(testRange->startContainer() == scope);
822     location = TextIterator::rangeLength(testRange.get());
823     
824     ExceptionCode ec;
825     testRange->setEnd(range->endContainer(), range->endOffset(), ec);
826     ASSERT(testRange->startContainer() == scope);
827     length = TextIterator::rangeLength(testRange.get()) - location;
828 }
829
830 // Events 
831
832 static const WebEvent* g_currentEvent = 0;
833
834 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
835 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
836 // platform events passed to the event handler code.
837 const WebEvent* WebPage::currentEvent()
838 {
839     return g_currentEvent;
840 }
841
842 class CurrentEvent {
843 public:
844     explicit CurrentEvent(const WebEvent& event)
845         : m_previousCurrentEvent(g_currentEvent)
846     {
847         g_currentEvent = &event;
848     }
849
850     ~CurrentEvent()
851     {
852         g_currentEvent = m_previousCurrentEvent;
853     }
854
855 private:
856     const WebEvent* m_previousCurrentEvent;
857 };
858
859 static bool isContextClick(const PlatformMouseEvent& event)
860 {
861     if (event.button() == WebCore::RightButton)
862         return true;
863
864 #if PLATFORM(MAC)
865     // FIXME: this really should be about OSX-style UI, not about the Mac port
866     if (event.button() == WebCore::LeftButton && event.ctrlKey())
867         return true;
868 #endif
869
870     return false;
871 }
872
873 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, Page* page)
874 {
875     Frame* frame = page->mainFrame();
876     if (!frame->view())
877         return false;
878
879     PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
880
881     switch (platformMouseEvent.eventType()) {
882         case WebCore::MouseEventPressed:
883         {
884             if (isContextClick(platformMouseEvent))
885                 page->contextMenuController()->clearContextMenu();
886             
887             bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
888             
889             if (isContextClick(platformMouseEvent)) {
890                 handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
891                 if (handled)
892                     page->chrome()->showContextMenu();
893             }
894
895             return handled;
896         }
897         case WebCore::MouseEventReleased:
898             return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
899         case WebCore::MouseEventMoved:
900             return frame->eventHandler()->mouseMoved(platformMouseEvent);
901
902         default:
903             ASSERT_NOT_REACHED();
904             return false;
905     }
906 }
907
908 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
909 {
910     bool handled = false;
911     
912     if (m_pageOverlay) {
913         // Let the page overlay handle the event.
914         handled = m_pageOverlay->mouseEvent(mouseEvent);
915     }
916
917     if (!handled) {
918         CurrentEvent currentEvent(mouseEvent);
919
920         handled = handleMouseEvent(mouseEvent, m_page.get());
921     }
922
923     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
924 }
925
926 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
927 {
928     Frame* frame = page->mainFrame();
929     if (!frame->view())
930         return false;
931
932     PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
933     return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
934 }
935
936 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
937 {
938     CurrentEvent currentEvent(wheelEvent);
939
940     bool handled = handleWheelEvent(wheelEvent, m_page.get());
941     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
942 }
943
944 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
945 {
946     if (!page->mainFrame()->view())
947         return false;
948
949     if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
950         return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
951     return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
952 }
953
954 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
955 {
956     CurrentEvent currentEvent(keyboardEvent);
957
958     bool handled = handleKeyEvent(keyboardEvent, m_page.get());
959     if (!handled)
960         handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
961
962     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
963 }
964
965 #if ENABLE(GESTURE_EVENTS)
966 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
967 {
968     Frame* frame = page->mainFrame();
969     if (!frame->view())
970         return false;
971
972     PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
973     return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
974 }
975
976 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
977 {
978     CurrentEvent currentEvent(gestureEvent);
979
980     bool handled = handleGestureEvent(gestureEvent, m_page.get());
981     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
982 }
983 #endif
984
985 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
986 {
987     bool isEnabled = false;
988     int32_t state = 0;
989     Frame* frame = m_page->focusController()->focusedOrMainFrame();
990     if (frame) {
991         Editor::Command command = frame->editor()->command(commandName);
992         state = command.state();
993         isEnabled = command.isSupported() && command.isEnabled();
994     }
995
996     send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
997 }
998
999 void WebPage::executeEditCommand(const String& commandName)
1000 {
1001     executeEditingCommand(commandName, String());
1002 }
1003
1004 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1005 {
1006     const BackForwardListItemVector& list = sessionState.list();
1007     size_t size = list.size();
1008     uint64_t currentItemID = 0;
1009     for (size_t i = 0; i < size; ++i) {
1010         WebBackForwardListItem* webItem = list[i].get();
1011         DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1012         
1013         RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1014         if (!item) {
1015             LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1016             return 0;
1017         }
1018         
1019         if (i == sessionState.currentIndex())
1020             currentItemID = webItem->itemID();
1021         
1022         WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1023     }    
1024     ASSERT(currentItemID);
1025     return currentItemID;
1026 }
1027
1028 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState, const SandboxExtension::Handle& sandboxExtensionHandle)
1029 {
1030     if (uint64_t currentItemID = restoreSession(sessionState))
1031         goToBackForwardItem(currentItemID, sandboxExtensionHandle);
1032 }
1033
1034 #if ENABLE(TOUCH_EVENTS)
1035 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1036 {
1037     Frame* frame = page->mainFrame();
1038     if (!frame->view())
1039         return false;
1040
1041     return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1042 }
1043
1044 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1045 {
1046     CurrentEvent currentEvent(touchEvent);
1047
1048     bool handled = handleTouchEvent(touchEvent, m_page.get());
1049
1050     send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1051 }
1052 #endif
1053
1054 void WebPage::setActive(bool isActive)
1055 {
1056     m_page->focusController()->setActive(isActive);
1057
1058 #if PLATFORM(MAC)    
1059     // Tell all our plug-in views that the window focus changed.
1060     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1061         (*it)->setWindowIsFocused(isActive);
1062 #endif
1063 }
1064
1065 void WebPage::setDrawsBackground(bool drawsBackground)
1066 {
1067     if (m_drawsBackground == drawsBackground)
1068         return;
1069
1070     m_drawsBackground = drawsBackground;
1071
1072     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1073         if (FrameView* view = coreFrame->view())
1074             view->setTransparent(!drawsBackground);
1075     }
1076
1077     m_drawingArea->pageBackgroundTransparencyChanged();
1078     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1079 }
1080
1081 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1082 {
1083     if (m_drawsTransparentBackground == drawsTransparentBackground)
1084         return;
1085
1086     m_drawsTransparentBackground = drawsTransparentBackground;
1087
1088     Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
1089     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1090         if (FrameView* view = coreFrame->view())
1091             view->setBaseBackgroundColor(backgroundColor);
1092     }
1093
1094     m_drawingArea->pageBackgroundTransparencyChanged();
1095     m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1096 }
1097
1098 void WebPage::viewWillStartLiveResize()
1099 {
1100     if (!m_page)
1101         return;
1102
1103     // FIXME: This should propagate to all ScrollableAreas.
1104     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1105         if (FrameView* view = frame->view())
1106             view->willStartLiveResize();
1107     }
1108 }
1109
1110 void WebPage::viewWillEndLiveResize()
1111 {
1112     if (!m_page)
1113         return;
1114
1115     // FIXME: This should propagate to all ScrollableAreas.
1116     if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1117         if (FrameView* view = frame->view())
1118             view->willEndLiveResize();
1119     }
1120 }
1121
1122 void WebPage::setFocused(bool isFocused)
1123 {
1124     m_page->focusController()->setFocused(isFocused);
1125 }
1126
1127 void WebPage::setInitialFocus(bool forward)
1128 {
1129     if (!m_page || !m_page->focusController())
1130         return;
1131
1132     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1133     frame->document()->setFocusedNode(0);
1134     m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
1135 }
1136
1137 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
1138 {
1139     if (m_windowResizerSize == windowResizerSize)
1140         return;
1141
1142     m_windowResizerSize = windowResizerSize;
1143
1144     for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1145         FrameView* view = coreFrame->view();
1146         if (view)
1147             view->windowResizerRectChanged();
1148     }
1149 }
1150
1151 void WebPage::setIsInWindow(bool isInWindow)
1152 {
1153     if (!isInWindow) {
1154         m_page->setCanStartMedia(false);
1155         m_page->willMoveOffscreen();
1156     } else {
1157         m_page->setCanStartMedia(true);
1158         m_page->didMoveOnscreen();
1159     }
1160 }
1161
1162 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
1163 {
1164     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1165     if (!frame)
1166         return;
1167     frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
1168 }
1169
1170 void WebPage::show()
1171 {
1172     send(Messages::WebPageProxy::ShowPage());
1173 }
1174
1175 void WebPage::setUserAgent(const String& userAgent)
1176 {
1177     m_userAgent = userAgent;
1178 }
1179     
1180 IntRect WebPage::windowToScreen(const IntRect& rect)
1181 {
1182     IntRect screenRect;
1183     sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
1184     return screenRect;
1185 }
1186
1187 IntRect WebPage::windowResizerRect() const
1188 {
1189     if (m_windowResizerSize.isEmpty())
1190         return IntRect();
1191
1192     IntSize frameViewSize;
1193     if (Frame* coreFrame = m_mainFrame->coreFrame()) {
1194         if (FrameView* view = coreFrame->view())
1195             frameViewSize = view->size();
1196     }
1197
1198     return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(), 
1199                    m_windowResizerSize.width(), m_windowResizerSize.height());
1200 }
1201
1202 KeyboardUIMode WebPage::keyboardUIMode()
1203 {
1204     bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
1205     return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
1206 }
1207
1208 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
1209 {
1210     // NOTE: We need to be careful when running scripts that the objects we depend on don't
1211     // disappear during script execution.
1212
1213     // Retain the SerializedScriptValue at this level so it (and the internal data) lives
1214     // long enough for the DataReference to be encoded by the sent message.
1215     RefPtr<SerializedScriptValue> serializedResultValue;
1216     CoreIPC::DataReference dataReference;
1217
1218     JSLock lock(SilenceAssertionsOnly);
1219     if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
1220         if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue)))
1221             dataReference = CoreIPC::DataReference(serializedResultValue->data().data(), serializedResultValue->data().size());
1222     }
1223
1224     send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
1225 }
1226
1227 void WebPage::getContentsAsString(uint64_t callbackID)
1228 {
1229     String resultString = m_mainFrame->contentsAsString();
1230     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1231 }
1232
1233 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
1234 {
1235     String resultString = renderTreeExternalRepresentation();
1236     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1237 }
1238
1239 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
1240 {
1241     String resultString = m_mainFrame->selectionAsString();
1242     if (resultString.isEmpty())
1243         resultString = m_mainFrame->contentsAsString();
1244     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1245 }
1246
1247 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
1248 {
1249     String resultString;
1250     if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
1251        resultString = frame->source();
1252
1253     send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1254 }
1255
1256 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
1257 {
1258     CoreIPC::DataReference dataReference;
1259
1260     RefPtr<SharedBuffer> buffer;
1261     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1262         if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1263             if ((buffer = loader->mainResourceData()))
1264                 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1265         }
1266     }
1267
1268     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1269 }
1270
1271 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURL, uint64_t callbackID)
1272 {
1273     CoreIPC::DataReference dataReference;
1274
1275     RefPtr<SharedBuffer> buffer;
1276     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1277         if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1278             if (RefPtr<ArchiveResource> subresource = loader->subresource(KURL(KURL(), resourceURL))) {
1279                 if ((buffer = subresource->data()))
1280                     dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1281             }
1282         }
1283     }
1284
1285     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1286 }
1287
1288 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
1289 {
1290     CoreIPC::DataReference dataReference;
1291
1292 #if PLATFORM(MAC) || PLATFORM(WIN)
1293     RetainPtr<CFDataRef> data;
1294     if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1295         if (RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(frame->coreFrame()->document())) {
1296             if ((data = archive->rawDataRepresentation()))
1297                 dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
1298         }
1299     }
1300 #endif
1301
1302     send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1303 }
1304
1305 void WebPage::forceRepaintWithoutCallback()
1306 {
1307     m_drawingArea->forceRepaint();
1308 }
1309
1310 void WebPage::forceRepaint(uint64_t callbackID)
1311 {
1312     forceRepaintWithoutCallback();
1313     send(Messages::WebPageProxy::VoidCallback(callbackID));
1314 }
1315
1316 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
1317 {
1318     WebPreferencesStore::removeTestRunnerOverrides();
1319     updatePreferences(store);
1320 }
1321
1322 void WebPage::updatePreferences(const WebPreferencesStore& store)
1323 {
1324     Settings* settings = m_page->settings();
1325
1326     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1327
1328     // FIXME: This should be generated from macro expansion for all preferences,
1329     // but we currently don't match the naming of WebCore exactly so we are
1330     // handrolling the boolean and integer preferences until that is fixed.
1331
1332 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1333
1334     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1335
1336 #undef INITIALIZE_SETTINGS
1337
1338     settings->setJavaScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1339     settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1340     settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1341     settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1342     settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1343     settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1344     settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1345     settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1346     settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1347     settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1348     settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1349     settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1350     settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1351     settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1352     settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1353 #if ENABLE(WEB_ARCHIVE)
1354     settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1355 #endif
1356     settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1357     settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1358     settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1359     settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1360     settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1361     settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
1362     settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1363
1364     settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1365     settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1366     settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1367     settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1368
1369 #if PLATFORM(WIN)
1370     // Temporarily turn off accelerated compositing until we have a good solution for rendering it.
1371     settings->setAcceleratedCompositingEnabled(false);
1372     settings->setAcceleratedDrawingEnabled(false);
1373 #else
1374     settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
1375     settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
1376 #endif
1377     settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1378     settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1379     settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
1380
1381 #if ENABLE(DATABASE)
1382     AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1383 #endif
1384
1385     platformPreferencesDidChange(store);
1386 }
1387
1388 #if ENABLE(INSPECTOR)
1389 WebInspector* WebPage::inspector()
1390 {
1391     if (m_isClosed)
1392         return 0;
1393     if (!m_inspector)
1394         m_inspector = WebInspector::create(this);
1395     return m_inspector.get();
1396 }
1397 #endif
1398
1399 #if !PLATFORM(MAC)
1400 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
1401 {
1402     Node* node = evt->target()->toNode();
1403     ASSERT(node);
1404     Frame* frame = node->document()->frame();
1405     ASSERT(frame);
1406
1407     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1408     if (!keyEvent)
1409         return false;
1410
1411     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1412
1413     if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1414         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1415         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1416         // (e.g. Tab that inserts a Tab character, or Enter).
1417         return !command.isTextInsertion() && command.execute(evt);
1418     }
1419
1420     if (command.execute(evt))
1421         return true;
1422
1423     // Don't insert null or control characters as they can result in unexpected behaviour
1424     if (evt->charCode() < ' ')
1425         return false;
1426
1427     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1428 }
1429 #endif
1430
1431 #if PLATFORM(WIN)
1432 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
1433 {
1434     if (!m_page) {
1435         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1436         return;
1437     }
1438
1439     DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1440     switch (action) {
1441     case DragControllerActionEntered:
1442         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1443         break;
1444
1445     case DragControllerActionUpdated:
1446         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1447         break;
1448         
1449     case DragControllerActionExited:
1450         m_page->dragController()->dragExited(&dragData);
1451         break;
1452         
1453     case DragControllerActionPerformDrag:
1454         m_page->dragController()->performDrag(&dragData);
1455         break;
1456         
1457     default:
1458         ASSERT_NOT_REACHED();
1459     }
1460 }
1461 #else
1462 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags)
1463 {
1464     if (!m_page) {
1465         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1466         return;
1467     }
1468
1469     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1470     switch (action) {
1471     case DragControllerActionEntered:
1472         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1473         break;
1474
1475     case DragControllerActionUpdated:
1476         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1477         break;
1478         
1479     case DragControllerActionExited:
1480         m_page->dragController()->dragExited(&dragData);
1481         break;
1482         
1483     case DragControllerActionPerformDrag:
1484         m_page->dragController()->performDrag(&dragData);
1485         break;
1486         
1487     default:
1488         ASSERT_NOT_REACHED();
1489     }
1490 }
1491 #endif
1492
1493 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
1494 {
1495     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
1496     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
1497     
1498     m_page->dragController()->dragEnded();
1499     FrameView* view = m_page->mainFrame()->view();
1500     if (!view)
1501         return;
1502     // FIXME: These are fake modifier keys here, but they should be real ones instead.
1503     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, MouseEventMoved, 0, false, false, false, false, currentTime());
1504     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
1505 }
1506
1507 WebEditCommand* WebPage::webEditCommand(uint64_t commandID)
1508 {
1509     return m_editCommandMap.get(commandID).get();
1510 }
1511
1512 void WebPage::addWebEditCommand(uint64_t commandID, WebEditCommand* command)
1513 {
1514     m_editCommandMap.set(commandID, command);
1515 }
1516
1517 void WebPage::removeWebEditCommand(uint64_t commandID)
1518 {
1519     m_editCommandMap.remove(commandID);
1520 }
1521
1522 void WebPage::unapplyEditCommand(uint64_t commandID)
1523 {
1524     WebEditCommand* command = webEditCommand(commandID);
1525     if (!command)
1526         return;
1527
1528     command->command()->unapply();
1529 }
1530
1531 void WebPage::reapplyEditCommand(uint64_t commandID)
1532 {
1533     WebEditCommand* command = webEditCommand(commandID);
1534     if (!command)
1535         return;
1536
1537     m_isInRedo = true;
1538     command->command()->reapply();
1539     m_isInRedo = false;
1540 }
1541
1542 void WebPage::didRemoveEditCommand(uint64_t commandID)
1543 {
1544     removeWebEditCommand(commandID);
1545 }
1546
1547 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
1548 {
1549     m_activePopupMenu = menu;
1550 }
1551
1552 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
1553 {
1554     m_activeOpenPanelResultListener = openPanelResultListener;
1555 }
1556
1557 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
1558 {
1559     return m_page->findString(target, options);
1560 }
1561
1562 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
1563 {
1564     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
1565 }
1566
1567 void WebPage::hideFindUI()
1568 {
1569     m_findController.hideFindUI();
1570 }
1571
1572 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
1573 {
1574     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
1575 }
1576
1577 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
1578 {
1579     if (!m_activePopupMenu)
1580         return;
1581
1582     m_activePopupMenu->didChangeSelectedIndex(newIndex);
1583     m_activePopupMenu = 0;
1584 }
1585
1586 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
1587 {
1588     if (!m_activeOpenPanelResultListener)
1589         return;
1590
1591     m_activeOpenPanelResultListener->didChooseFiles(files);
1592     m_activeOpenPanelResultListener = 0;
1593 }
1594
1595 void WebPage::didCancelForOpenPanel()
1596 {
1597     m_activeOpenPanelResultListener = 0;
1598 }
1599
1600 #if ENABLE(WEB_PROCESS_SANDBOX)
1601 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
1602 {
1603     SandboxExtension::create(handle)->consumePermanently();
1604 }
1605 #endif
1606
1607 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
1608 {
1609     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
1610 }
1611
1612 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
1613 {
1614     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1615     frame->editor()->advanceToNextMisspelling(startBeforeSelection);
1616 }
1617
1618 void WebPage::changeSpellingToWord(const String& word)
1619 {
1620     replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
1621 }
1622
1623 void WebPage::unmarkAllMisspellings()
1624 {
1625     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1626         if (Document* document = frame->document())
1627             document->markers()->removeMarkers(DocumentMarker::Spelling);
1628     }
1629 }
1630
1631 void WebPage::unmarkAllBadGrammar()
1632 {
1633     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1634         if (Document* document = frame->document())
1635             document->markers()->removeMarkers(DocumentMarker::Grammar);
1636     }
1637 }
1638
1639 #if PLATFORM(MAC)
1640 void WebPage::uppercaseWord()
1641 {
1642     m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
1643 }
1644
1645 void WebPage::lowercaseWord()
1646 {
1647     m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
1648 }
1649
1650 void WebPage::capitalizeWord()
1651 {
1652     m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
1653 }
1654 #endif
1655     
1656 void WebPage::setTextForActivePopupMenu(int32_t index)
1657 {
1658     if (!m_activePopupMenu)
1659         return;
1660
1661     m_activePopupMenu->setTextForIndex(index);
1662 }
1663
1664 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
1665 {
1666     ASSERT(m_contextMenu);
1667     m_contextMenu->itemSelected(item);
1668     m_contextMenu = 0;
1669 }
1670
1671 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
1672 {
1673     if (frame->selection()->isNone())
1674         return;
1675
1676     RefPtr<DocumentFragment> textFragment = createFragmentFromText(frame->selection()->toNormalizedRange().get(), text);
1677     applyCommand(ReplaceSelectionCommand::create(frame->document(), textFragment.release(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
1678     frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
1679 }
1680
1681 bool WebPage::mainFrameHasCustomRepresentation() const
1682 {
1683     return static_cast<WebFrameLoaderClient*>(mainFrame()->coreFrame()->loader()->client())->frameHasCustomRepresentation();
1684 }
1685
1686 void WebPage::didChangeScrollOffsetForMainFrame()
1687 {
1688     Frame* frame = m_page->mainFrame();
1689     IntPoint scrollPosition = frame->view()->scrollPosition();
1690     IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
1691
1692     bool isPinnedToLeftSide = (scrollPosition.x() <= 0);
1693     bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
1694
1695     if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
1696         send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
1697         
1698         m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
1699         m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
1700     }
1701 }
1702
1703 #if PLATFORM(MAC)
1704
1705 void WebPage::addPluginView(PluginView* pluginView)
1706 {
1707     ASSERT(!m_pluginViews.contains(pluginView));
1708
1709     m_pluginViews.add(pluginView);
1710 }
1711
1712 void WebPage::removePluginView(PluginView* pluginView)
1713 {
1714     ASSERT(m_pluginViews.contains(pluginView));
1715
1716     m_pluginViews.remove(pluginView);
1717 }
1718
1719 void WebPage::setWindowIsVisible(bool windowIsVisible)
1720 {
1721     m_windowIsVisible = windowIsVisible;
1722
1723     // Tell all our plug-in views that the window visibility changed.
1724     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1725         (*it)->setWindowIsVisible(windowIsVisible);
1726 }
1727
1728 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
1729 {
1730     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
1731     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
1732     m_accessibilityPosition = accessibilityViewCoordinates;
1733     
1734     // Tell all our plug-in views that the window and view frames have changed.
1735     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1736         (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
1737 }
1738
1739 bool WebPage::windowIsFocused() const
1740 {
1741     return m_page->focusController()->isActive();
1742 }
1743
1744 #endif
1745
1746 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
1747 {
1748     if (messageID.is<CoreIPC::MessageClassDrawingAreaLegacy>()) {
1749         if (m_drawingArea)
1750             m_drawingArea->didReceiveMessage(connection, messageID, arguments);
1751         return;
1752     }
1753
1754 #if PLATFORM(MAC) || PLATFORM(WIN)
1755     if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
1756         if (m_drawingArea)
1757             m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
1758         return;
1759     }
1760 #endif
1761     
1762 #if ENABLE(INSPECTOR)
1763     if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
1764         if (WebInspector* inspector = this->inspector())
1765             inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
1766         return;
1767     }
1768 #endif
1769
1770     didReceiveWebPageMessage(connection, messageID, arguments);
1771 }
1772
1773 CoreIPC::SyncReplyMode WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, CoreIPC::ArgumentEncoder* reply)
1774 {   
1775     return didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
1776 }
1777     
1778 InjectedBundleBackForwardList* WebPage::backForwardList()
1779 {
1780     if (!m_backForwardList)
1781         m_backForwardList = InjectedBundleBackForwardList::create(this);
1782     return m_backForwardList.get();
1783 }
1784
1785 #if PLATFORM(QT)
1786 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point)
1787 {
1788     const int minimumZoomTargetWidth = 100;
1789
1790     Frame* mainframe = m_mainFrame->coreFrame();
1791     HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1792
1793     Node* node = result.innerNode();
1794     while (node && node->getRect().width() < minimumZoomTargetWidth)
1795         node = node->parentNode();
1796
1797     IntRect zoomableArea;
1798     if (node)
1799         zoomableArea = node->getRect();
1800     send(Messages::WebPageProxy::DidFindZoomableArea(zoomableArea));
1801 }
1802 #endif
1803
1804 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
1805 {
1806     invalidate();
1807 }
1808
1809 void WebPage::SandboxExtensionTracker::invalidate()
1810 {
1811     if (m_pendingProvisionalSandboxExtension) {
1812         m_pendingProvisionalSandboxExtension->invalidate();
1813         m_pendingProvisionalSandboxExtension = 0;
1814     }
1815
1816     if (m_provisionalSandboxExtension) {
1817         m_provisionalSandboxExtension->invalidate();
1818         m_provisionalSandboxExtension = 0;
1819     }
1820
1821     if (m_committedSandboxExtension) {
1822         m_committedSandboxExtension->invalidate();
1823         m_committedSandboxExtension = 0;
1824     }
1825 }
1826
1827 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
1828 {
1829     ASSERT(frame->isMainFrame());
1830
1831     // If we get two beginLoad calls in succession, without a provisional load starting, then
1832     // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
1833     if (m_pendingProvisionalSandboxExtension) {
1834         m_pendingProvisionalSandboxExtension->invalidate();
1835         m_pendingProvisionalSandboxExtension = nullptr;
1836     }
1837         
1838     m_pendingProvisionalSandboxExtension = SandboxExtension::create(handle);
1839 }
1840
1841 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
1842 {
1843     ASSERT(frame->isMainFrame());
1844
1845     FrameLoader* frameLoader = frame->coreFrame()->loader();
1846     FrameLoadType frameLoadType = frameLoader->loadType();
1847
1848     // If the page is being reloaded, it should reuse whatever extension is committed.
1849     if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
1850         return true;
1851
1852     DocumentLoader* documentLoader = frameLoader->documentLoader();
1853     DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
1854     if (!documentLoader || !provisionalDocumentLoader)
1855         return false;
1856
1857     if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile() 
1858         && provisionalDocumentLoader->triggeringAction().type() == NavigationTypeLinkClicked)
1859         return true;
1860
1861     return false;
1862 }
1863
1864 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
1865 {
1866     if (!frame->isMainFrame())
1867         return;
1868
1869     if (shouldReuseCommittedSandboxExtension(frame)) {
1870         m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
1871         ASSERT(!m_committedSandboxExtension);
1872     }
1873
1874     ASSERT(!m_provisionalSandboxExtension);
1875
1876     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
1877     if (!m_provisionalSandboxExtension)
1878         return;
1879
1880     m_provisionalSandboxExtension->consume();
1881 }
1882
1883 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
1884 {
1885     if (!frame->isMainFrame())
1886         return;
1887     
1888     ASSERT(!m_pendingProvisionalSandboxExtension);
1889
1890     // The provisional load has been committed. Invalidate the currently committed sandbox
1891     // extension and make the provisional sandbox extension the committed sandbox extension.
1892     if (m_committedSandboxExtension)
1893         m_committedSandboxExtension->invalidate();
1894
1895     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
1896 }
1897
1898 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
1899 {
1900     if (!frame->isMainFrame())
1901         return;
1902
1903     ASSERT(!m_pendingProvisionalSandboxExtension);
1904     if (!m_provisionalSandboxExtension)
1905         return;
1906
1907     m_provisionalSandboxExtension->invalidate();
1908     m_provisionalSandboxExtension = nullptr;
1909 }
1910
1911 bool WebPage::hasLocalDataForURL(const KURL& url)
1912 {
1913     if (url.isLocalFile())
1914         return true;
1915
1916     FrameLoader* frameLoader = m_page->mainFrame()->loader();
1917     DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
1918     if (documentLoader && documentLoader->subresource(url))
1919         return true;
1920
1921     return platformHasLocalDataForURL(url);
1922 }
1923
1924 void WebPage::setCustomTextEncodingName(const String& encoding)
1925 {
1926     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
1927 }
1928
1929 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
1930 {
1931     WebBackForwardListProxy::removeItem(itemID);
1932 }
1933
1934 #if PLATFORM(MAC)
1935
1936 bool WebPage::isSpeaking()
1937 {
1938     bool result;
1939     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
1940 }
1941
1942 void WebPage::speak(const String& string)
1943 {
1944     send(Messages::WebPageProxy::Speak(string));
1945 }
1946
1947 void WebPage::stopSpeaking()
1948 {
1949     send(Messages::WebPageProxy::StopSpeaking());
1950 }
1951
1952 #endif
1953
1954 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
1955 {
1956     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1957     if (!frame)
1958         return;
1959
1960     Frame* coreFrame = frame->coreFrame();
1961     if (!coreFrame)
1962         return;
1963
1964     if (!m_printContext)
1965         m_printContext = adoptPtr(new PrintContext(coreFrame));
1966
1967     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
1968
1969     float fullPageHeight;
1970     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
1971 }
1972
1973 void WebPage::endPrinting()
1974 {
1975     m_printContext = nullptr;
1976 }
1977
1978 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
1979 {
1980     Vector<IntRect> resultPageRects;
1981     double resultTotalScaleFactorForPrinting = 1;
1982
1983     beginPrinting(frameID, printInfo);
1984
1985     if (m_printContext) {
1986         resultPageRects = m_printContext->pageRects();
1987         resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
1988     }
1989
1990     // If we're asked to print, we should actually print at least a blank page.
1991     if (resultPageRects.isEmpty())
1992         resultPageRects.append(IntRect(0, 0, 1, 1));
1993
1994     send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
1995 }
1996
1997 #if PLATFORM(MAC) || PLATFORM(WIN)
1998 void WebPage::drawRectToPDF(uint64_t frameID, const WebCore::IntRect& rect, uint64_t callbackID)
1999 {
2000     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2001     Frame* coreFrame = frame ? frame->coreFrame() : 0;
2002
2003     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2004
2005     if (coreFrame) {
2006         ASSERT(coreFrame->document()->printing());
2007
2008         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2009         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2010
2011         CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
2012         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2013         RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2014         CGPDFContextBeginPage(context.get(), pageInfo.get());
2015
2016         GraphicsContext ctx(context.get());
2017         ctx.scale(FloatSize(1, -1));
2018         ctx.translate(0, -rect.height());
2019         m_printContext->spoolRect(ctx, rect);
2020
2021         CGPDFContextEndPage(context.get());
2022         CGPDFContextClose(context.get());
2023     }
2024
2025     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2026 }
2027
2028 void WebPage::drawPagesToPDF(uint64_t frameID, uint32_t first, uint32_t count, uint64_t callbackID)
2029 {
2030     WebFrame* frame = WebProcess::shared().webFrame(frameID);
2031     Frame* coreFrame = frame ? frame->coreFrame() : 0;
2032
2033     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2034
2035     if (coreFrame) {
2036         ASSERT(coreFrame->document()->printing());
2037
2038         // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2039         RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2040
2041         CGRect mediaBox = m_printContext->pageCount() ? m_printContext->pageRect(0) : CGRectMake(0, 0, 1, 1);
2042         RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2043         for (uint32_t page = first; page < first + count; ++page) {
2044             if (page >= m_printContext->pageCount())
2045                 break;
2046
2047             RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2048             CGPDFContextBeginPage(context.get(), pageInfo.get());
2049
2050             GraphicsContext ctx(context.get());
2051             ctx.scale(FloatSize(1, -1));
2052             ctx.translate(0, -m_printContext->pageRect(page).height());
2053             m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
2054
2055             CGPDFContextEndPage(context.get());
2056         }
2057         CGPDFContextClose(context.get());
2058     }
2059
2060     send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2061 }
2062 #endif
2063
2064 void WebPage::runModal()
2065 {
2066     if (m_isClosed)
2067         return;
2068     if (m_isRunningModal)
2069         return;
2070
2071     m_isRunningModal = true;
2072     send(Messages::WebPageProxy::RunModal());
2073     RunLoop::run();
2074     ASSERT(!m_isRunningModal);
2075 }
2076
2077 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
2078 {
2079     m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
2080 }
2081
2082 } // namespace WebKit