WebKit2: Need API to stop loading a WKFrame
[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::preferencesDidChange(const WebPreferencesStore& store)
1191 {
1192     WebPreferencesStore::removeTestRunnerOverrides();
1193     updatePreferences(store);
1194 }
1195
1196 void WebPage::updatePreferences(const WebPreferencesStore& store)
1197 {
1198     Settings* settings = m_page->settings();
1199
1200     m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1201
1202     // FIXME: This should be generated from macro expansion for all preferences,
1203     // but we currently don't match the naming of WebCore exactly so we are
1204     // handrolling the boolean and integer preferences until that is fixed.
1205
1206 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1207
1208     FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1209
1210 #undef INITIALIZE_SETTINGS
1211
1212     settings->setJavaScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1213     settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1214     settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1215     settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1216     settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1217     settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1218     settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1219     settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1220     settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1221     settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1222     settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1223     settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1224     settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1225     settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1226     settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1227     settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1228     settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1229     settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1230     settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1231     settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1232     settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1233     settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1234
1235     settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1236     settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1237     settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1238     settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1239
1240 #if PLATFORM(WIN)
1241     // Temporarily turn off accelerated compositing until we have a good solution for rendering it.
1242     settings->setAcceleratedCompositingEnabled(false);
1243 #else
1244     settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
1245 #endif
1246     settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1247     settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1248
1249 #if ENABLE(DATABASE)
1250     AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1251 #endif
1252
1253     platformPreferencesDidChange(store);
1254 }
1255
1256 #if ENABLE(INSPECTOR)
1257 WebInspector* WebPage::inspector()
1258 {
1259     if (m_isClosed)
1260         return 0;
1261     if (!m_inspector)
1262         m_inspector = adoptPtr(new WebInspector(this));
1263     return m_inspector.get();
1264 }
1265 #endif
1266
1267 #if !PLATFORM(MAC)
1268 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
1269 {
1270     Node* node = evt->target()->toNode();
1271     ASSERT(node);
1272     Frame* frame = node->document()->frame();
1273     ASSERT(frame);
1274
1275     const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1276     if (!keyEvent)
1277         return false;
1278
1279     Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1280
1281     if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1282         // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1283         // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1284         // (e.g. Tab that inserts a Tab character, or Enter).
1285         return !command.isTextInsertion() && command.execute(evt);
1286     }
1287
1288     if (command.execute(evt))
1289         return true;
1290
1291     // Don't insert null or control characters as they can result in unexpected behaviour
1292     if (evt->charCode() < ' ')
1293         return false;
1294
1295     return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1296 }
1297 #endif
1298
1299 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags)
1300 {
1301     if (!m_page) {
1302         send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1303         return;
1304     }
1305
1306     DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1307     switch (action) {
1308     case DragControllerActionEntered:
1309         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1310         break;
1311
1312     case DragControllerActionUpdated:
1313         send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1314         break;
1315         
1316     case DragControllerActionExited:
1317         m_page->dragController()->dragExited(&dragData);
1318         break;
1319         
1320     case DragControllerActionPerformDrag:
1321         m_page->dragController()->performDrag(&dragData);
1322         break;
1323         
1324     default:
1325         ASSERT_NOT_REACHED();
1326     }
1327 }
1328
1329 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
1330 {
1331     IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
1332     IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
1333     
1334     m_page->dragController()->dragEnded();
1335     FrameView* view = m_page->mainFrame()->view();
1336     if (!view)
1337         return;
1338     // FIXME: These are fake modifier keys here, but they should be real ones instead.
1339     PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, MouseEventMoved, 0, false, false, false, false, currentTime());
1340     m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
1341 }
1342
1343 WebEditCommand* WebPage::webEditCommand(uint64_t commandID)
1344 {
1345     return m_editCommandMap.get(commandID).get();
1346 }
1347
1348 void WebPage::addWebEditCommand(uint64_t commandID, WebEditCommand* command)
1349 {
1350     m_editCommandMap.set(commandID, command);
1351 }
1352
1353 void WebPage::removeWebEditCommand(uint64_t commandID)
1354 {
1355     m_editCommandMap.remove(commandID);
1356 }
1357
1358 void WebPage::unapplyEditCommand(uint64_t commandID)
1359 {
1360     WebEditCommand* command = webEditCommand(commandID);
1361     if (!command)
1362         return;
1363
1364     command->command()->unapply();
1365 }
1366
1367 void WebPage::reapplyEditCommand(uint64_t commandID)
1368 {
1369     WebEditCommand* command = webEditCommand(commandID);
1370     if (!command)
1371         return;
1372
1373     m_isInRedo = true;
1374     command->command()->reapply();
1375     m_isInRedo = false;
1376 }
1377
1378 void WebPage::didRemoveEditCommand(uint64_t commandID)
1379 {
1380     removeWebEditCommand(commandID);
1381 }
1382
1383 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
1384 {
1385     m_activePopupMenu = menu;
1386 }
1387
1388 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
1389 {
1390     m_activeOpenPanelResultListener = openPanelResultListener;
1391 }
1392
1393 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
1394 {
1395     return m_page->findString(target, options);
1396 }
1397
1398 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
1399 {
1400     m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
1401 }
1402
1403 void WebPage::hideFindUI()
1404 {
1405     m_findController.hideFindUI();
1406 }
1407
1408 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
1409 {
1410     m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
1411 }
1412
1413 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
1414 {
1415     if (!m_activePopupMenu)
1416         return;
1417
1418     m_activePopupMenu->didChangeSelectedIndex(newIndex);
1419     m_activePopupMenu = 0;
1420 }
1421
1422 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
1423 {
1424     if (!m_activeOpenPanelResultListener)
1425         return;
1426
1427     m_activeOpenPanelResultListener->didChooseFiles(files);
1428     m_activeOpenPanelResultListener = 0;
1429 }
1430
1431 void WebPage::didCancelForOpenPanel()
1432 {
1433     m_activeOpenPanelResultListener = 0;
1434 }
1435
1436 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
1437 {
1438     m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
1439 }
1440
1441 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
1442 {
1443     Frame* frame = m_page->focusController()->focusedOrMainFrame();
1444     frame->editor()->advanceToNextMisspelling(startBeforeSelection);
1445 }
1446
1447 void WebPage::changeSpellingToWord(const String& word)
1448 {
1449     replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
1450 }
1451
1452 void WebPage::unmarkAllMisspellings()
1453 {
1454     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1455         if (Document* document = frame->document())
1456             document->markers()->removeMarkers(DocumentMarker::Spelling);
1457     }
1458 }
1459
1460 void WebPage::unmarkAllBadGrammar()
1461 {
1462     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1463         if (Document* document = frame->document())
1464             document->markers()->removeMarkers(DocumentMarker::Grammar);
1465     }
1466 }
1467
1468 #if PLATFORM(MAC)
1469 void WebPage::uppercaseWord()
1470 {
1471     m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
1472 }
1473
1474 void WebPage::lowercaseWord()
1475 {
1476     m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
1477 }
1478
1479 void WebPage::capitalizeWord()
1480 {
1481     m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
1482 }
1483 #endif
1484     
1485 void WebPage::setTextForActivePopupMenu(int32_t index)
1486 {
1487     if (!m_activePopupMenu)
1488         return;
1489
1490     m_activePopupMenu->setTextForIndex(index);
1491 }
1492
1493 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
1494 {
1495     ASSERT(m_contextMenu);
1496     m_contextMenu->itemSelected(item);
1497     m_contextMenu = 0;
1498 }
1499
1500 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
1501 {
1502     if (frame->selection()->isNone())
1503         return;
1504     
1505     RefPtr<DocumentFragment> textFragment = createFragmentFromText(frame->selection()->toNormalizedRange().get(), text);
1506     applyCommand(ReplaceSelectionCommand::create(frame->document(), textFragment.release(), true, false, true));
1507     frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
1508 }
1509
1510 bool WebPage::mainFrameHasCustomRepresentation() const
1511 {
1512     return static_cast<WebFrameLoaderClient*>(mainFrame()->coreFrame()->loader()->client())->frameHasCustomRepresentation();
1513 }
1514
1515 #if PLATFORM(MAC)
1516
1517 void WebPage::addPluginView(PluginView* pluginView)
1518 {
1519     ASSERT(!m_pluginViews.contains(pluginView));
1520
1521     m_pluginViews.add(pluginView);
1522 }
1523
1524 void WebPage::removePluginView(PluginView* pluginView)
1525 {
1526     ASSERT(m_pluginViews.contains(pluginView));
1527
1528     m_pluginViews.remove(pluginView);
1529 }
1530
1531 void WebPage::setWindowIsVisible(bool windowIsVisible)
1532 {
1533     m_windowIsVisible = windowIsVisible;
1534
1535     // Tell all our plug-in views that the window visibility changed.
1536     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1537         (*it)->setWindowIsVisible(windowIsVisible);
1538 }
1539
1540 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
1541 {
1542     m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
1543     m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
1544     m_accessibilityPosition = accessibilityViewCoordinates;
1545     
1546     // Tell all our plug-in views that the window and view frames have changed.
1547     for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1548         (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
1549 }
1550
1551 bool WebPage::windowIsFocused() const
1552 {
1553     return m_page->focusController()->isActive();
1554 }
1555
1556 #endif
1557
1558 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
1559 {
1560     if (messageID.is<CoreIPC::MessageClassDrawingAreaLegacy>()) {
1561         if (m_drawingArea)
1562             m_drawingArea->didReceiveMessage(connection, messageID, arguments);
1563         return;
1564     }
1565
1566 #ifdef __APPLE__
1567     if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
1568         if (m_drawingArea)
1569             m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
1570         return;
1571     }
1572 #endif
1573     
1574 #if ENABLE(INSPECTOR)
1575     if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
1576         if (WebInspector* inspector = this->inspector())
1577             inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
1578         return;
1579     }
1580 #endif
1581
1582     didReceiveWebPageMessage(connection, messageID, arguments);
1583 }
1584
1585 CoreIPC::SyncReplyMode WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, CoreIPC::ArgumentEncoder* reply)
1586 {   
1587     return didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
1588 }
1589     
1590 InjectedBundleBackForwardList* WebPage::backForwardList()
1591 {
1592     if (!m_backForwardList)
1593         m_backForwardList = InjectedBundleBackForwardList::create(this);
1594     return m_backForwardList.get();
1595 }
1596
1597 #if PLATFORM(QT)
1598 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point)
1599 {
1600     const int minimumZoomTargetWidth = 100;
1601
1602     Frame* mainframe = m_mainFrame->coreFrame();
1603     HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1604
1605     Node* node = result.innerNode();
1606     while (node && node->getRect().width() < minimumZoomTargetWidth)
1607         node = node->parentNode();
1608
1609     IntRect zoomableArea;
1610     if (node)
1611         zoomableArea = node->getRect();
1612     send(Messages::WebPageProxy::DidFindZoomableArea(zoomableArea));
1613 }
1614 #endif
1615
1616 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
1617 {
1618     invalidate();
1619 }
1620
1621 void WebPage::SandboxExtensionTracker::invalidate()
1622 {
1623     if (m_pendingProvisionalSandboxExtension) {
1624         m_pendingProvisionalSandboxExtension->invalidate();
1625         m_pendingProvisionalSandboxExtension = 0;
1626     }
1627
1628     if (m_provisionalSandboxExtension) {
1629         m_provisionalSandboxExtension->invalidate();
1630         m_provisionalSandboxExtension = 0;
1631     }
1632
1633     if (m_committedSandboxExtension) {
1634         m_committedSandboxExtension->invalidate();
1635         m_committedSandboxExtension = 0;
1636     }
1637 }
1638
1639 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
1640 {
1641     ASSERT(frame->isMainFrame());
1642
1643     // If we get two beginLoad calls in succession, without a provisional load starting, then
1644     // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
1645     if (m_pendingProvisionalSandboxExtension) {
1646         m_pendingProvisionalSandboxExtension->invalidate();
1647         m_pendingProvisionalSandboxExtension = nullptr;
1648     }
1649         
1650     m_pendingProvisionalSandboxExtension = SandboxExtension::create(handle);
1651 }
1652
1653 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
1654 {
1655     if (!frame->isMainFrame())
1656         return;
1657
1658     ASSERT(!m_provisionalSandboxExtension);
1659
1660     m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
1661     if (!m_provisionalSandboxExtension)
1662         return;
1663
1664     m_provisionalSandboxExtension->consume();
1665 }
1666
1667 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
1668 {
1669     if (!frame->isMainFrame())
1670         return;
1671     
1672     ASSERT(!m_pendingProvisionalSandboxExtension);
1673
1674     // The provisional load has been committed. Invalidate the currently committed sandbox
1675     // extension and make the provisional sandbox extension the committed sandbox extension.
1676     if (m_committedSandboxExtension)
1677         m_committedSandboxExtension->invalidate();
1678
1679     m_committedSandboxExtension = m_provisionalSandboxExtension.release();
1680 }
1681
1682 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
1683 {
1684     if (!frame->isMainFrame())
1685         return;
1686
1687     ASSERT(!m_pendingProvisionalSandboxExtension);
1688     if (!m_provisionalSandboxExtension)
1689         return;
1690
1691     m_provisionalSandboxExtension->invalidate();
1692     m_provisionalSandboxExtension = nullptr;
1693 }
1694
1695 bool WebPage::hasLocalDataForURL(const KURL& url)
1696 {
1697     if (url.isLocalFile())
1698         return true;
1699
1700     FrameLoader* frameLoader = m_page->mainFrame()->loader();
1701     DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
1702     if (documentLoader && documentLoader->subresource(url))
1703         return true;
1704
1705     return platformHasLocalDataForURL(url);
1706 }
1707
1708 void WebPage::setCustomTextEncodingName(const String& encoding)
1709 {
1710     m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
1711 }
1712
1713 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
1714 {
1715     WebBackForwardListProxy::removeItem(itemID);
1716 }
1717
1718 #if PLATFORM(MAC)
1719
1720 bool WebPage::isSpeaking()
1721 {
1722     bool result;
1723     return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
1724 }
1725
1726 void WebPage::speak(const String& string)
1727 {
1728     send(Messages::WebPageProxy::Speak(string));
1729 }
1730
1731 void WebPage::stopSpeaking()
1732 {
1733     send(Messages::WebPageProxy::StopSpeaking());
1734 }
1735
1736 #endif
1737
1738 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
1739 {
1740     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1741     if (!frame)
1742         return;
1743
1744     Frame* coreFrame = frame->coreFrame();
1745     if (!coreFrame)
1746         return;
1747
1748     if (!m_printContext)
1749         m_printContext = adoptPtr(new PrintContext(coreFrame));
1750
1751     m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
1752 }
1753
1754 void WebPage::endPrinting()
1755 {
1756     m_printContext = nullptr;
1757 }
1758
1759 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, Vector<IntRect>& resultPageRects, double& resultTotalScaleFactorForPrinting)
1760 {
1761     beginPrinting(frameID, printInfo);
1762
1763     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1764     if (!frame)
1765         return;
1766
1767     float fullPageHeight;
1768     m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
1769
1770     resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(printInfo.availablePaperWidth) * printInfo.pageSetupScaleFactor;
1771     resultPageRects = m_printContext->pageRects();
1772
1773     // If we're asked to print, we should actually print at least a blank page.
1774     if (resultPageRects.isEmpty())
1775         resultPageRects.append(IntRect(0, 0, 1, 1));
1776 }
1777
1778 #if PLATFORM(MAC)
1779 // FIXME: Find a better place for Mac specific code.
1780 void WebPage::drawRectToPDF(uint64_t frameID, const WebCore::IntRect& rect, Vector<uint8_t>& pdfData)
1781 {
1782     WebFrame* frame = WebProcess::shared().webFrame(frameID);
1783     if (!frame)
1784         return;
1785
1786     Frame* coreFrame = frame->coreFrame();
1787     if (!coreFrame)
1788         return;
1789
1790     ASSERT(coreFrame->document()->printing());
1791
1792     RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
1793
1794     // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
1795     RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
1796
1797     CGRect mediaBox = CGRectMake(0, 0, frame->size().width(), frame->size().height());
1798     RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
1799     CFDictionaryRef pageInfo = CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1800     CGPDFContextBeginPage(context.get(), pageInfo);
1801
1802     GraphicsContext ctx(context.get());
1803     m_printContext->spoolRect(ctx, rect);
1804
1805     CGPDFContextEndPage(context.get());
1806     CGPDFContextClose(context.get());
1807
1808     pdfData.resize(CFDataGetLength(pdfPageData.get()));
1809     CFDataGetBytes(pdfPageData.get(), CFRangeMake(0, pdfData.size()), pdfData.data());
1810 }
1811 #endif
1812
1813 void WebPage::runModal()
1814 {
1815     if (m_isClosed)
1816         return;
1817     if (m_isRunningModal)
1818         return;
1819
1820     m_isRunningModal = true;
1821     send(Messages::WebPageProxy::RunModal());
1822     RunLoop::run();
1823     ASSERT(!m_isRunningModal);
1824 }
1825
1826 } // namespace WebKit