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