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