2 * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
29 #include "Arguments.h"
30 #include "DataReference.h"
31 #include "DecoderAdapter.h"
32 #include "DrawingArea.h"
33 #include "InjectedBundle.h"
34 #include "InjectedBundleBackForwardList.h"
35 #include "LayerTreeHost.h"
36 #include "MessageID.h"
37 #include "NetscapePlugin.h"
38 #include "PageOverlay.h"
39 #include "PluginProxy.h"
40 #include "PluginView.h"
41 #include "PrintInfo.h"
43 #include "SessionState.h"
44 #include "ShareableBitmap.h"
45 #include "WebBackForwardList.h"
46 #include "WebBackForwardListItem.h"
47 #include "WebBackForwardListProxy.h"
48 #include "WebChromeClient.h"
49 #include "WebContextMenu.h"
50 #include "WebContextMenuClient.h"
51 #include "WebContextMessages.h"
52 #include "WebCoreArgumentCoders.h"
53 #include "WebDragClient.h"
54 #include "WebEditorClient.h"
56 #include "WebEventConversion.h"
58 #include "WebFullScreenManager.h"
59 #include "WebGeolocationClient.h"
61 #include "WebInspector.h"
62 #include "WebInspectorClient.h"
63 #include "WebOpenPanelResultListener.h"
64 #include "WebPageCreationParameters.h"
65 #include "WebPageGroupProxy.h"
66 #include "WebPageProxyMessages.h"
67 #include "WebPopupMenu.h"
68 #include "WebPreferencesStore.h"
69 #include "WebProcess.h"
70 #include "WebProcessProxyMessages.h"
71 #include <JavaScriptCore/APICast.h>
72 #include <WebCore/AbstractDatabase.h>
73 #include <WebCore/ArchiveResource.h>
74 #include <WebCore/Chrome.h>
75 #include <WebCore/ContextMenuController.h>
76 #include <WebCore/DocumentFragment.h>
77 #include <WebCore/DocumentLoader.h>
78 #include <WebCore/DocumentMarkerController.h>
79 #include <WebCore/DragController.h>
80 #include <WebCore/DragData.h>
81 #include <WebCore/EventHandler.h>
82 #include <WebCore/FocusController.h>
83 #include <WebCore/FormState.h>
84 #include <WebCore/Frame.h>
85 #include <WebCore/FrameLoadRequest.h>
86 #include <WebCore/FrameLoaderTypes.h>
87 #include <WebCore/FrameView.h>
88 #include <WebCore/HTMLFormElement.h>
89 #include <WebCore/HistoryItem.h>
90 #include <WebCore/KeyboardEvent.h>
91 #include <WebCore/MouseEvent.h>
92 #include <WebCore/Page.h>
93 #include <WebCore/PlatformKeyboardEvent.h>
94 #include <WebCore/PrintContext.h>
95 #include <WebCore/RenderArena.h>
96 #include <WebCore/RenderLayer.h>
97 #include <WebCore/RenderTreeAsText.h>
98 #include <WebCore/RenderView.h>
99 #include <WebCore/ReplaceSelectionCommand.h>
100 #include <WebCore/ResourceRequest.h>
101 #include <WebCore/SchemeRegistry.h>
102 #include <WebCore/ScriptValue.h>
103 #include <WebCore/SerializedScriptValue.h>
104 #include <WebCore/Settings.h>
105 #include <WebCore/SharedBuffer.h>
106 #include <WebCore/SubstituteData.h>
107 #include <WebCore/TextIterator.h>
108 #include <WebCore/markup.h>
109 #include <runtime/JSLock.h>
110 #include <runtime/JSValue.h>
112 #include <WebCore/Range.h>
113 #include <WebCore/VisiblePosition.h>
115 #if PLATFORM(MAC) || PLATFORM(WIN)
116 #include <WebCore/LegacyWebArchive.h>
119 #if ENABLE(PLUGIN_PROCESS)
121 #include "MachPort.h"
126 #include "HitTestResult.h"
130 #include <wtf/RefCountedLeakCounter.h>
134 using namespace WebCore;
138 class SendStopResponsivenessTimer {
140 SendStopResponsivenessTimer(WebPage* page)
145 ~SendStopResponsivenessTimer()
147 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
155 static WTF::RefCountedLeakCounter webPageCounter("WebPage");
158 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
160 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
162 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
163 WebProcess::shared().injectedBundle()->didCreatePage(page.get());
165 return page.release();
168 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
169 : m_viewSize(parameters.viewSize)
170 , m_drawsBackground(true)
171 , m_drawsTransparentBackground(false)
174 , m_tabToLinks(false)
176 , m_windowIsVisible(false)
177 , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
178 , m_keyboardEventBeingInterpreted(0)
180 , m_nativeWindow(parameters.nativeWindow)
182 , m_setCanStartMediaTimer(WebProcess::shared().runLoop(), this, &WebPage::setCanStartMediaTimerFired)
183 , m_findController(this)
184 , m_geolocationPermissionRequestManager(this)
186 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
187 , m_canRunModal(parameters.canRunModal)
188 , m_isRunningModal(false)
189 , m_userSpaceScaleFactor(parameters.userSpaceScaleFactor)
190 , m_cachedMainFrameIsPinnedToLeftSide(false)
191 , m_cachedMainFrameIsPinnedToRightSide(false)
192 , m_isShowingContextMenu(false)
194 , m_gestureReachedScrollingLimit(false)
198 // FIXME: This is a non-ideal location for this Setting and
199 // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
200 Settings::setDefaultMinDOMTimerInterval(0.004);
202 Page::PageClients pageClients;
203 pageClients.chromeClient = new WebChromeClient(this);
204 pageClients.contextMenuClient = new WebContextMenuClient(this);
205 pageClients.editorClient = new WebEditorClient(this);
206 pageClients.dragClient = new WebDragClient(this);
207 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
208 #if ENABLE(CLIENT_BASED_GEOLOCATION)
209 pageClients.geolocationClient = new WebGeolocationClient(this);
211 #if ENABLE(INSPECTOR)
212 pageClients.inspectorClient = new WebInspectorClient(this);
214 m_page = adoptPtr(new Page(pageClients));
216 // Qt does not yet call setIsInWindow. Until it does, just leave
217 // this line out so plug-ins and video will work. Eventually all platforms
218 // should call setIsInWindow and this comment and #if should be removed,
219 // leaving behind the setCanStartMedia call.
221 m_page->setCanStartMedia(false);
224 updatePreferences(parameters.store);
226 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
227 m_page->setGroupName(m_pageGroup->identifier());
229 platformInitialize();
231 m_drawingArea = DrawingArea::create(this, parameters);
232 m_mainFrame = WebFrame::createMainFrame(this);
234 setDrawsBackground(parameters.drawsBackground);
235 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
237 setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
239 setActive(parameters.isActive);
240 setFocused(parameters.isFocused);
241 setIsInWindow(parameters.isInWindow);
243 m_userAgent = parameters.userAgent;
245 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
247 if (!parameters.sessionState.isEmpty())
248 restoreSession(parameters.sessionState);
251 webPageCounter.increment();
257 if (m_backForwardList)
258 m_backForwardList->detach();
262 m_sandboxExtensionTracker.invalidate();
265 ASSERT(m_pluginViews.isEmpty());
269 webPageCounter.decrement();
273 void WebPage::dummy(bool&)
277 CoreIPC::Connection* WebPage::connection() const
279 return WebProcess::shared().connection();
282 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
284 m_contextMenuClient.initialize(client);
287 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
289 m_editorClient.initialize(client);
292 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
294 m_formClient.initialize(client);
297 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
299 m_loaderClient.initialize(client);
302 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
304 m_policyClient.initialize(client);
307 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
309 m_resourceLoadClient.initialize(client);
312 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
314 m_uiClient.initialize(client);
317 #if ENABLE(FULLSCREEN_API)
318 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
320 m_fullScreenClient.initialize(client);
324 PassRefPtr<Plugin> WebPage::createPlugin(const Plugin::Parameters& parameters)
328 if (!WebProcess::shared().connection()->sendSync(
329 Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()),
330 Messages::WebContext::GetPluginPath::Reply(pluginPath), 0)) {
334 if (pluginPath.isNull())
337 #if ENABLE(PLUGIN_PROCESS)
338 return PluginProxy::create(pluginPath);
340 return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
344 EditorState WebPage::editorState() const
346 Frame* frame = m_page->focusController()->focusedOrMainFrame();
350 result.selectionIsNone = frame->selection()->isNone();
351 result.selectionIsRange = frame->selection()->isRange();
352 result.isContentEditable = frame->selection()->isContentEditable();
353 result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
354 result.isInPasswordField = frame->selection()->isInPasswordField();
355 result.hasComposition = frame->editor()->hasComposition();
356 result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
361 String WebPage::renderTreeExternalRepresentation() const
363 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
366 uint64_t WebPage::renderTreeSize() const
371 Frame* mainFrame = m_page->mainFrame();
376 for (Frame* coreFrame = mainFrame; coreFrame; coreFrame = coreFrame->tree()->traverseNext())
377 size += coreFrame->document()->renderArena()->totalRenderArenaSize();
382 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
384 Frame* frame = m_page->focusController()->focusedOrMainFrame();
387 frame->editor()->command(commandName).execute(argument);
390 bool WebPage::isEditingCommandEnabled(const String& commandName)
392 Frame* frame = m_page->focusController()->focusedOrMainFrame();
396 Editor::Command command = frame->editor()->command(commandName);
397 return command.isSupported() && command.isEnabled();
400 void WebPage::clearMainFrameName()
402 mainFrame()->coreFrame()->tree()->clearName();
405 #if USE(ACCELERATED_COMPOSITING)
406 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
408 m_drawingArea->setRootCompositingLayer(layer);
411 void WebPage::exitAcceleratedCompositingMode()
413 m_drawingArea->setRootCompositingLayer(0);
417 void WebPage::close()
424 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
425 WebProcess::shared().injectedBundle()->willDestroyPage(this);
427 #if ENABLE(INSPECTOR)
430 #if ENABLE(FULLSCREEN_API)
431 m_fullScreenManager = 0;
434 if (m_activePopupMenu) {
435 m_activePopupMenu->disconnectFromPage();
436 m_activePopupMenu = 0;
439 if (m_activeOpenPanelResultListener) {
440 m_activeOpenPanelResultListener->disconnectFromPage();
441 m_activeOpenPanelResultListener = 0;
444 m_sandboxExtensionTracker.invalidate();
446 m_underlayPage = nullptr;
447 m_printContext = nullptr;
448 m_mainFrame->coreFrame()->loader()->detachFromParent();
450 m_drawingArea = nullptr;
452 bool isRunningModal = m_isRunningModal;
453 m_isRunningModal = false;
455 // The WebPage can be destroyed by this call.
456 WebProcess::shared().removeWebPage(m_pageID);
459 WebProcess::shared().runLoop()->stop();
462 void WebPage::tryClose()
464 SendStopResponsivenessTimer stopper(this);
466 if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
467 send(Messages::WebPageProxy::StopResponsivenessTimer());
471 send(Messages::WebPageProxy::ClosePage(true));
474 void WebPage::sendClose()
476 send(Messages::WebPageProxy::ClosePage(false));
479 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
481 loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
484 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
486 SendStopResponsivenessTimer stopper(this);
488 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
489 m_mainFrame->coreFrame()->loader()->load(request, false);
492 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
494 SendStopResponsivenessTimer stopper(this);
496 ResourceRequest request(baseURL);
497 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
498 m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
501 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
503 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
504 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
505 loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
508 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
510 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
511 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
512 KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
513 loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
516 void WebPage::loadPlainTextString(const String& string)
518 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
519 loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
522 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
524 Frame* frame = m_page->mainFrame();
528 RefPtr<Event> coreEvent;
529 if (event.type() != WebEvent::NoType)
530 coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
532 frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)),
533 false, false, coreEvent.get(), 0, SendReferrer);
536 void WebPage::stopLoadingFrame(uint64_t frameID)
538 WebFrame* frame = WebProcess::shared().webFrame(frameID);
542 frame->coreFrame()->loader()->stopForUserCancel();
545 void WebPage::stopLoading()
547 SendStopResponsivenessTimer stopper(this);
549 m_mainFrame->coreFrame()->loader()->stopForUserCancel();
552 void WebPage::setDefersLoading(bool defersLoading)
554 m_page->setDefersLoading(defersLoading);
557 void WebPage::reload(bool reloadFromOrigin)
559 SendStopResponsivenessTimer stopper(this);
561 m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
564 void WebPage::goForward(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
566 SendStopResponsivenessTimer stopper(this);
568 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
573 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
574 m_page->goToItem(item, FrameLoadTypeForward);
577 void WebPage::goBack(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
579 SendStopResponsivenessTimer stopper(this);
581 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
586 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
587 m_page->goToItem(item, FrameLoadTypeBack);
590 void WebPage::goToBackForwardItem(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
592 SendStopResponsivenessTimer stopper(this);
594 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
599 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
600 m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
603 void WebPage::tryRestoreScrollPosition()
605 m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
608 void WebPage::layoutIfNeeded()
610 if (m_mainFrame->coreFrame()->view())
611 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
613 if (m_underlayPage) {
614 if (FrameView *frameView = m_underlayPage->mainFrame()->coreFrame()->view())
615 frameView->updateLayoutAndStyleIfNeededRecursive();
619 void WebPage::setSize(const WebCore::IntSize& viewSize)
621 #if ENABLE(TILED_BACKING_STORE)
622 // If we are resizing to content ignore external attempts.
623 if (!m_resizesToContentsLayoutSize.isEmpty())
627 if (m_viewSize == viewSize)
630 Frame* frame = m_page->mainFrame();
632 frame->view()->resize(viewSize);
633 frame->view()->setNeedsLayout();
634 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
636 m_viewSize = viewSize;
639 #if ENABLE(TILED_BACKING_STORE)
640 void WebPage::setActualVisibleContentRect(const IntRect& rect)
642 Frame* frame = m_page->mainFrame();
644 frame->view()->setActualVisibleContentRect(rect);
647 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
649 if (m_resizesToContentsLayoutSize == targetLayoutSize)
652 m_resizesToContentsLayoutSize = targetLayoutSize;
654 Frame* frame = m_page->mainFrame();
655 if (m_resizesToContentsLayoutSize.isEmpty()) {
656 frame->view()->setDelegatesScrolling(false);
657 frame->view()->setUseFixedLayout(false);
658 frame->view()->setPaintsEntireContents(false);
660 frame->view()->setDelegatesScrolling(true);
661 frame->view()->setUseFixedLayout(true);
662 frame->view()->setPaintsEntireContents(true);
663 frame->view()->setFixedLayoutSize(m_resizesToContentsLayoutSize);
665 frame->view()->forceLayout();
668 void WebPage::resizeToContentsIfNeeded()
670 if (m_resizesToContentsLayoutSize.isEmpty())
673 Frame* frame = m_page->mainFrame();
675 IntSize contentSize = frame->view()->contentsSize();
676 if (contentSize == m_viewSize)
679 m_viewSize = contentSize;
680 frame->view()->resize(m_viewSize);
681 frame->view()->setNeedsLayout();
685 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
687 Frame* frame = m_page->mainFrame();
689 IntPoint scrollPosition = frame->view()->scrollPosition();
690 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
692 // If the current scroll position in a direction is the max scroll position
693 // we don't want to scroll at all.
694 IntSize newScrollOffset;
695 if (scrollPosition.x() < maximumScrollPosition.x())
696 newScrollOffset.setWidth(scrollOffset.width());
697 if (scrollPosition.y() < maximumScrollPosition.y())
698 newScrollOffset.setHeight(scrollOffset.height());
700 if (newScrollOffset.isZero())
703 frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
706 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
708 GraphicsContextStateSaver stateSaver(graphicsContext);
709 graphicsContext.clip(rect);
711 if (m_underlayPage) {
712 m_underlayPage->drawRect(graphicsContext, rect);
714 graphicsContext.beginTransparencyLayer(1);
715 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
716 graphicsContext.endTransparencyLayer();
720 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
723 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
725 ASSERT(m_pageOverlay);
727 GraphicsContextStateSaver stateSaver(graphicsContext);
728 graphicsContext.clip(rect);
729 m_pageOverlay->drawRect(graphicsContext, rect);
732 double WebPage::textZoomFactor() const
734 Frame* frame = m_mainFrame->coreFrame();
737 return frame->textZoomFactor();
740 void WebPage::setTextZoomFactor(double zoomFactor)
742 Frame* frame = m_mainFrame->coreFrame();
745 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
748 double WebPage::pageZoomFactor() const
750 Frame* frame = m_mainFrame->coreFrame();
753 return frame->pageZoomFactor();
756 void WebPage::setPageZoomFactor(double zoomFactor)
758 Frame* frame = m_mainFrame->coreFrame();
761 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
764 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
766 Frame* frame = m_mainFrame->coreFrame();
769 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
772 void WebPage::scaleWebView(double scale, const IntPoint& origin)
774 Frame* frame = m_mainFrame->coreFrame();
777 frame->scalePage(scale, origin);
779 send(Messages::WebPageProxy::ViewScaleFactorDidChange(scale));
782 double WebPage::viewScaleFactor() const
784 Frame* frame = m_mainFrame->coreFrame();
787 return frame->pageScaleFactor();
790 void WebPage::setUseFixedLayout(bool fixed)
792 Frame* frame = m_mainFrame->coreFrame();
796 FrameView* view = frame->view();
800 view->setUseFixedLayout(fixed);
802 view->setFixedLayoutSize(IntSize());
805 void WebPage::setFixedLayoutSize(const IntSize& size)
807 Frame* frame = m_mainFrame->coreFrame();
811 FrameView* view = frame->view();
815 view->setFixedLayoutSize(size);
819 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
821 bool shouldFadeIn = true;
824 m_pageOverlay->setPage(0);
827 // We're installing a page overlay when a page overlay is already active.
828 // In this case we don't want to fade in the new overlay.
829 shouldFadeIn = false;
833 m_pageOverlay = pageOverlay;
834 m_pageOverlay->setPage(this);
837 m_pageOverlay->startFadeInAnimation();
839 m_drawingArea->didInstallPageOverlay();
841 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
844 m_pageOverlay->setNeedsDisplay();
847 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
849 if (pageOverlay != m_pageOverlay)
853 m_pageOverlay->startFadeOutAnimation();
857 m_pageOverlay->setPage(0);
858 m_pageOverlay = nullptr;
860 m_drawingArea->didUninstallPageOverlay();
862 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
866 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
868 FrameView* frameView = m_mainFrame->coreFrame()->view();
872 frameView->updateLayoutAndStyleIfNeededRecursive();
874 PaintBehavior oldBehavior = frameView->paintBehavior();
875 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
877 RefPtr<WebImage> snapshot = WebImage::create(rect.size(), options);
878 if (!snapshot->bitmap())
881 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
883 graphicsContext->save();
884 graphicsContext->translate(-rect.x(), -rect.y());
885 frameView->paint(graphicsContext.get(), rect);
886 graphicsContext->restore();
888 frameView->setPaintBehavior(oldBehavior);
890 return snapshot.release();
893 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
895 FrameView* frameView = m_mainFrame->coreFrame()->view();
899 frameView->updateLayoutAndStyleIfNeededRecursive();
901 PaintBehavior oldBehavior = frameView->paintBehavior();
902 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
904 bool scale = scaleFactor != 1;
905 IntSize size = rect.size();
907 size = IntSize(ceil(rect.width() * scaleFactor), ceil(rect.height() * scaleFactor));
909 RefPtr<WebImage> snapshot = WebImage::create(size, options);
910 if (!snapshot->bitmap())
913 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
914 graphicsContext->save();
917 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
919 graphicsContext->translate(-rect.x(), -rect.y());
920 frameView->paintContents(graphicsContext.get(), rect);
921 graphicsContext->restore();
923 frameView->setPaintBehavior(oldBehavior);
925 return snapshot.release();
928 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
930 return scaledSnapshotInDocumentCoordinates(rect, 1, options);
933 void WebPage::createSnapshotOfVisibleContent(ShareableBitmap::Handle& snapshotHandle)
935 FrameView* frameView = m_mainFrame->coreFrame()->view();
939 IntRect contentRect = frameView->visibleContentRect(false);
940 RefPtr<WebImage> snapshotImage = scaledSnapshotInDocumentCoordinates(contentRect, 1, ImageOptionsShareable);
941 if (!snapshotImage->bitmap())
944 snapshotImage->bitmap()->createHandle(snapshotHandle);
947 void WebPage::pageDidScroll()
949 // Hide the find indicator.
950 m_findController.hideFindIndicator();
952 m_uiClient.pageDidScroll(this);
954 send(Messages::WebPageProxy::PageDidScroll());
957 #if ENABLE(TILED_BACKING_STORE)
958 void WebPage::pageDidRequestScroll(const IntPoint& point)
960 send(Messages::WebPageProxy::PageDidRequestScroll(point));
964 WebContextMenu* WebPage::contextMenu()
967 m_contextMenu = WebContextMenu::create(this);
968 return m_contextMenu.get();
973 static const WebEvent* g_currentEvent = 0;
975 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
976 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
977 // platform events passed to the event handler code.
978 const WebEvent* WebPage::currentEvent()
980 return g_currentEvent;
985 explicit CurrentEvent(const WebEvent& event)
986 : m_previousCurrentEvent(g_currentEvent)
988 g_currentEvent = &event;
993 g_currentEvent = m_previousCurrentEvent;
997 const WebEvent* m_previousCurrentEvent;
1000 static bool isContextClick(const PlatformMouseEvent& event)
1002 if (event.button() == WebCore::RightButton)
1006 // FIXME: this really should be about OSX-style UI, not about the Mac port
1007 if (event.button() == WebCore::LeftButton && event.ctrlKey())
1014 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, Page* page)
1016 IntPoint point = page->mainFrame()->view()->windowToContents(platformMouseEvent.pos());
1017 HitTestResult result = page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1019 Frame* frame = page->mainFrame();
1020 if (result.innerNonSharedNode())
1021 frame = result.innerNonSharedNode()->document()->frame();
1023 bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1025 page->chrome()->showContextMenu();
1030 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, Page* page)
1032 Frame* frame = page->mainFrame();
1036 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1038 switch (platformMouseEvent.eventType()) {
1039 case WebCore::MouseEventPressed:
1041 if (isContextClick(platformMouseEvent))
1042 page->contextMenuController()->clearContextMenu();
1044 bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1045 if (isContextClick(platformMouseEvent))
1046 handled = handleContextMenuEvent(platformMouseEvent, page);
1050 case WebCore::MouseEventReleased:
1051 return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1052 case WebCore::MouseEventMoved:
1053 return frame->eventHandler()->mouseMoved(platformMouseEvent);
1056 ASSERT_NOT_REACHED();
1061 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1063 // Don't try to handle any pending mouse events if a context menu is showing.
1064 if (m_isShowingContextMenu) {
1065 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1069 bool handled = false;
1071 if (m_pageOverlay) {
1072 // Let the page overlay handle the event.
1073 handled = m_pageOverlay->mouseEvent(mouseEvent);
1077 CurrentEvent currentEvent(mouseEvent);
1079 handled = handleMouseEvent(mouseEvent, m_page.get());
1082 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1085 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1087 Frame* frame = page->mainFrame();
1091 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1092 return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1095 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1097 CurrentEvent currentEvent(wheelEvent);
1100 if (wheelEvent.momentumPhase() == WebWheelEvent::PhaseBegan || wheelEvent.phase() == WebWheelEvent::PhaseBegan)
1101 m_drawingArea->disableDisplayThrottling();
1102 else if (wheelEvent.momentumPhase() == WebWheelEvent::PhaseEnded || wheelEvent.phase() == WebWheelEvent::PhaseEnded)
1103 m_drawingArea->enableDisplayThrottling();
1106 bool handled = handleWheelEvent(wheelEvent, m_page.get());
1107 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1110 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1112 if (!page->mainFrame()->view())
1115 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1116 return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1117 return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1120 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1122 CurrentEvent currentEvent(keyboardEvent);
1124 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1125 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1127 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1129 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1132 #if ENABLE(GESTURE_EVENTS)
1133 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1135 Frame* frame = page->mainFrame();
1139 PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1140 return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1143 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1145 CurrentEvent currentEvent(gestureEvent);
1147 bool handled = handleGestureEvent(gestureEvent, m_page.get());
1148 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1152 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1154 bool isEnabled = false;
1156 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1158 Editor::Command command = frame->editor()->command(commandName);
1159 state = command.state();
1160 isEnabled = command.isSupported() && command.isEnabled();
1163 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1166 void WebPage::executeEditCommand(const String& commandName)
1168 executeEditingCommand(commandName, String());
1171 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1173 const BackForwardListItemVector& list = sessionState.list();
1174 size_t size = list.size();
1175 uint64_t currentItemID = 0;
1176 for (size_t i = 0; i < size; ++i) {
1177 WebBackForwardListItem* webItem = list[i].get();
1178 DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1180 RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1182 LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1186 if (i == sessionState.currentIndex())
1187 currentItemID = webItem->itemID();
1189 WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1191 ASSERT(currentItemID);
1192 return currentItemID;
1195 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState, const SandboxExtension::Handle& sandboxExtensionHandle)
1197 if (uint64_t currentItemID = restoreSession(sessionState))
1198 goToBackForwardItem(currentItemID, sandboxExtensionHandle);
1201 #if ENABLE(TOUCH_EVENTS)
1202 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1204 Frame* frame = page->mainFrame();
1208 return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1211 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1213 CurrentEvent currentEvent(touchEvent);
1215 bool handled = handleTouchEvent(touchEvent, m_page.get());
1217 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1221 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1223 page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1226 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1228 page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1231 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1233 scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1236 void WebPage::setActive(bool isActive)
1238 m_page->focusController()->setActive(isActive);
1241 // Tell all our plug-in views that the window focus changed.
1242 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1243 (*it)->setWindowIsFocused(isActive);
1247 void WebPage::setDrawsBackground(bool drawsBackground)
1249 if (m_drawsBackground == drawsBackground)
1252 m_drawsBackground = drawsBackground;
1254 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1255 if (FrameView* view = coreFrame->view())
1256 view->setTransparent(!drawsBackground);
1259 m_drawingArea->pageBackgroundTransparencyChanged();
1260 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1263 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1265 if (m_drawsTransparentBackground == drawsTransparentBackground)
1268 m_drawsTransparentBackground = drawsTransparentBackground;
1270 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
1271 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1272 if (FrameView* view = coreFrame->view())
1273 view->setBaseBackgroundColor(backgroundColor);
1276 m_drawingArea->pageBackgroundTransparencyChanged();
1277 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1280 void WebPage::viewWillStartLiveResize()
1285 // FIXME: This should propagate to all ScrollableAreas.
1286 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1287 if (FrameView* view = frame->view())
1288 view->willStartLiveResize();
1292 void WebPage::viewWillEndLiveResize()
1297 // FIXME: This should propagate to all ScrollableAreas.
1298 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1299 if (FrameView* view = frame->view())
1300 view->willEndLiveResize();
1304 void WebPage::setFocused(bool isFocused)
1306 m_page->focusController()->setFocused(isFocused);
1309 void WebPage::setInitialFocus(bool forward)
1311 if (!m_page || !m_page->focusController())
1314 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1315 frame->document()->setFocusedNode(0);
1316 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
1319 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
1321 if (m_windowResizerSize == windowResizerSize)
1324 m_windowResizerSize = windowResizerSize;
1326 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1327 FrameView* view = coreFrame->view();
1329 view->windowResizerRectChanged();
1333 void WebPage::setCanStartMediaTimerFired()
1336 m_page->setCanStartMedia(true);
1339 void WebPage::setIsInWindow(bool isInWindow)
1342 m_setCanStartMediaTimer.stop();
1343 m_page->setCanStartMedia(false);
1344 m_page->willMoveOffscreen();
1346 // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
1347 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
1348 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
1349 m_setCanStartMediaTimer.startOneShot(0);
1350 m_page->didMoveOnscreen();
1354 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
1356 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1359 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
1362 void WebPage::show()
1364 send(Messages::WebPageProxy::ShowPage());
1367 void WebPage::setUserAgent(const String& userAgent)
1369 m_userAgent = userAgent;
1372 IntPoint WebPage::screenToWindow(const IntPoint& point)
1374 IntPoint windowPoint;
1375 sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
1379 IntRect WebPage::windowToScreen(const IntRect& rect)
1382 sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
1386 IntRect WebPage::windowResizerRect() const
1388 if (m_windowResizerSize.isEmpty())
1391 IntSize frameViewSize;
1392 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
1393 if (FrameView* view = coreFrame->view())
1394 frameViewSize = view->size();
1397 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
1398 m_windowResizerSize.width(), m_windowResizerSize.height());
1401 KeyboardUIMode WebPage::keyboardUIMode()
1403 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
1404 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
1407 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
1409 // NOTE: We need to be careful when running scripts that the objects we depend on don't
1410 // disappear during script execution.
1412 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
1413 // long enough for the DataReference to be encoded by the sent message.
1414 RefPtr<SerializedScriptValue> serializedResultValue;
1415 CoreIPC::DataReference dataReference;
1417 JSLock lock(SilenceAssertionsOnly);
1418 if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
1419 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(),
1420 toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
1421 dataReference = CoreIPC::DataReference(serializedResultValue->data().data(), serializedResultValue->data().size());
1424 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
1427 void WebPage::getContentsAsString(uint64_t callbackID)
1429 String resultString = m_mainFrame->contentsAsString();
1430 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1433 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
1435 String resultString = renderTreeExternalRepresentation();
1436 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1439 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
1441 String resultString = m_mainFrame->selectionAsString();
1442 if (resultString.isEmpty())
1443 resultString = m_mainFrame->contentsAsString();
1444 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1447 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
1449 String resultString;
1450 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
1451 resultString = frame->source();
1453 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1456 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
1458 CoreIPC::DataReference dataReference;
1460 RefPtr<SharedBuffer> buffer;
1461 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1462 if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1463 if ((buffer = loader->mainResourceData()))
1464 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1468 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1471 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
1473 DocumentLoader* loader = frame->loader()->documentLoader();
1477 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
1481 return subresource->data();
1484 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
1486 CoreIPC::DataReference dataReference;
1487 KURL resourceURL(KURL(), resourceURLString);
1489 RefPtr<SharedBuffer> buffer;
1490 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1491 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
1493 // Try to get the resource data from the cache.
1494 buffer = cachedResponseDataForURL(resourceURL);
1498 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1501 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1504 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
1506 CoreIPC::DataReference dataReference;
1508 #if PLATFORM(MAC) || PLATFORM(WIN)
1509 RetainPtr<CFDataRef> data;
1510 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1511 if (RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(frame->coreFrame()->document())) {
1512 if ((data = archive->rawDataRepresentation()))
1513 dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
1518 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1521 void WebPage::forceRepaintWithoutCallback()
1523 m_drawingArea->forceRepaint();
1526 void WebPage::forceRepaint(uint64_t callbackID)
1528 forceRepaintWithoutCallback();
1529 send(Messages::WebPageProxy::VoidCallback(callbackID));
1532 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
1534 WebPreferencesStore::removeTestRunnerOverrides();
1535 updatePreferences(store);
1538 void WebPage::updatePreferences(const WebPreferencesStore& store)
1540 Settings* settings = m_page->settings();
1542 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1544 // FIXME: This should be generated from macro expansion for all preferences,
1545 // but we currently don't match the naming of WebCore exactly so we are
1546 // handrolling the boolean and integer preferences until that is fixed.
1548 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1550 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1552 #undef INITIALIZE_SETTINGS
1554 settings->setJavaScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1555 settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1556 settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
1557 settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1558 settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1559 settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1560 settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1561 settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1562 settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1563 settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1564 settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1565 settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1566 settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1567 settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1568 settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1569 settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1570 #if ENABLE(WEB_ARCHIVE)
1571 settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1573 settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1574 settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1575 settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1576 settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1577 settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1578 settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
1579 settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1580 settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
1581 settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
1582 settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
1584 settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1585 settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1586 settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1587 settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1588 settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
1590 settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1591 settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1592 settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1593 settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1594 settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1595 settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
1597 #if ENABLE(DATABASE)
1598 AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1601 #if ENABLE(FULLSCREEN_API)
1602 settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
1605 #if ENABLE(DOM_STORAGE)
1606 settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
1609 #if USE(AVFOUNDATION)
1610 settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
1613 platformPreferencesDidChange(store);
1616 #if ENABLE(INSPECTOR)
1617 WebInspector* WebPage::inspector()
1622 m_inspector = WebInspector::create(this);
1623 return m_inspector.get();
1627 #if ENABLE(FULLSCREEN_API)
1628 WebFullScreenManager* WebPage::fullScreenManager()
1630 if (!m_fullScreenManager)
1631 m_fullScreenManager = WebFullScreenManager::create(this);
1632 return m_fullScreenManager.get();
1636 #if !PLATFORM(GTK) && !PLATFORM(MAC)
1637 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
1639 Node* node = evt->target()->toNode();
1641 Frame* frame = node->document()->frame();
1644 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1648 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1650 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1651 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1652 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1653 // (e.g. Tab that inserts a Tab character, or Enter).
1654 return !command.isTextInsertion() && command.execute(evt);
1657 if (command.execute(evt))
1660 // Don't insert null or control characters as they can result in unexpected behaviour
1661 if (evt->charCode() < ' ')
1664 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1669 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
1672 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1676 DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1678 case DragControllerActionEntered:
1679 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1682 case DragControllerActionUpdated:
1683 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1686 case DragControllerActionExited:
1687 m_page->dragController()->dragExited(&dragData);
1690 case DragControllerActionPerformDrag:
1691 m_page->dragController()->performDrag(&dragData);
1695 ASSERT_NOT_REACHED();
1699 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags, const SandboxExtension::Handle& sandboxExtensionHandle)
1702 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1706 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1708 case DragControllerActionEntered:
1709 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1712 case DragControllerActionUpdated:
1713 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1716 case DragControllerActionExited:
1717 m_page->dragController()->dragExited(&dragData);
1720 case DragControllerActionPerformDrag: {
1721 ASSERT(!m_pendingDropSandboxExtension);
1723 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
1725 m_page->dragController()->performDrag(&dragData);
1727 // If we started loading a local file, the sandbox extension tracker would have adopted this
1728 // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
1729 if (m_pendingDropSandboxExtension) {
1730 m_pendingDropSandboxExtension->invalidate();
1731 m_pendingDropSandboxExtension = nullptr;
1738 ASSERT_NOT_REACHED();
1743 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
1745 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
1746 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
1748 platformDragEnded();
1749 m_page->dragController()->dragEnded();
1750 FrameView* view = m_page->mainFrame()->view();
1753 // FIXME: These are fake modifier keys here, but they should be real ones instead.
1754 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, MouseEventMoved, 0, false, false, false, false, currentTime());
1755 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
1758 void WebPage::willPerformLoadDragDestinationAction()
1760 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
1763 WebEditCommand* WebPage::webEditCommand(uint64_t commandID)
1765 return m_editCommandMap.get(commandID).get();
1768 void WebPage::addWebEditCommand(uint64_t commandID, WebEditCommand* command)
1770 m_editCommandMap.set(commandID, command);
1773 void WebPage::removeWebEditCommand(uint64_t commandID)
1775 m_editCommandMap.remove(commandID);
1778 void WebPage::unapplyEditCommand(uint64_t commandID)
1780 WebEditCommand* command = webEditCommand(commandID);
1784 command->command()->unapply();
1787 void WebPage::reapplyEditCommand(uint64_t commandID)
1789 WebEditCommand* command = webEditCommand(commandID);
1794 command->command()->reapply();
1798 void WebPage::didRemoveEditCommand(uint64_t commandID)
1800 removeWebEditCommand(commandID);
1803 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
1805 m_activePopupMenu = menu;
1808 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
1810 m_activeOpenPanelResultListener = openPanelResultListener;
1813 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
1815 return m_page->findString(target, options);
1818 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
1820 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
1823 void WebPage::hideFindUI()
1825 m_findController.hideFindUI();
1828 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
1830 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
1833 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
1835 if (!m_activePopupMenu)
1838 m_activePopupMenu->didChangeSelectedIndex(newIndex);
1839 m_activePopupMenu = 0;
1842 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
1844 if (!m_activeOpenPanelResultListener)
1847 m_activeOpenPanelResultListener->didChooseFiles(files);
1848 m_activeOpenPanelResultListener = 0;
1851 void WebPage::didCancelForOpenPanel()
1853 m_activeOpenPanelResultListener = 0;
1856 #if ENABLE(WEB_PROCESS_SANDBOX)
1857 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
1859 SandboxExtension::create(handle)->consumePermanently();
1863 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
1865 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
1868 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
1870 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1871 frame->editor()->advanceToNextMisspelling(startBeforeSelection);
1874 void WebPage::changeSpellingToWord(const String& word)
1876 replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
1879 void WebPage::unmarkAllMisspellings()
1881 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1882 if (Document* document = frame->document())
1883 document->markers()->removeMarkers(DocumentMarker::Spelling);
1887 void WebPage::unmarkAllBadGrammar()
1889 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1890 if (Document* document = frame->document())
1891 document->markers()->removeMarkers(DocumentMarker::Grammar);
1896 void WebPage::uppercaseWord()
1898 m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
1901 void WebPage::lowercaseWord()
1903 m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
1906 void WebPage::capitalizeWord()
1908 m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
1912 void WebPage::setTextForActivePopupMenu(int32_t index)
1914 if (!m_activePopupMenu)
1917 m_activePopupMenu->setTextForIndex(index);
1920 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
1922 ASSERT(m_contextMenu);
1923 m_contextMenu->itemSelected(item);
1927 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
1929 if (frame->selection()->isNone())
1932 RefPtr<DocumentFragment> textFragment = createFragmentFromText(frame->selection()->toNormalizedRange().get(), text);
1933 applyCommand(ReplaceSelectionCommand::create(frame->document(), textFragment.release(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
1934 frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
1937 void WebPage::clearSelection()
1939 m_page->focusController()->focusedOrMainFrame()->selection()->clear();
1942 bool WebPage::mainFrameHasCustomRepresentation() const
1944 return static_cast<WebFrameLoaderClient*>(mainFrame()->coreFrame()->loader()->client())->frameHasCustomRepresentation();
1947 void WebPage::didChangeScrollOffsetForMainFrame()
1949 Frame* frame = m_page->mainFrame();
1950 IntPoint scrollPosition = frame->view()->scrollPosition();
1951 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
1952 IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
1954 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
1955 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
1957 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
1958 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
1960 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
1961 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
1967 void WebPage::addPluginView(PluginView* pluginView)
1969 ASSERT(!m_pluginViews.contains(pluginView));
1971 m_pluginViews.add(pluginView);
1974 void WebPage::removePluginView(PluginView* pluginView)
1976 ASSERT(m_pluginViews.contains(pluginView));
1978 m_pluginViews.remove(pluginView);
1981 void WebPage::setWindowIsVisible(bool windowIsVisible)
1983 m_windowIsVisible = windowIsVisible;
1985 // Tell all our plug-in views that the window visibility changed.
1986 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1987 (*it)->setWindowIsVisible(windowIsVisible);
1990 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
1992 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
1993 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
1994 m_accessibilityPosition = accessibilityViewCoordinates;
1996 // Tell all our plug-in views that the window and view frames have changed.
1997 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1998 (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
2003 bool WebPage::windowIsFocused() const
2006 if (!m_windowIsVisible)
2009 return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
2012 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
2014 if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
2016 m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
2020 #if ENABLE(INSPECTOR)
2021 if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
2022 if (WebInspector* inspector = this->inspector())
2023 inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
2028 #if ENABLE(FULLSCREEN_API)
2029 if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
2030 fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
2035 didReceiveWebPageMessage(connection, messageID, arguments);
2038 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
2040 didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
2043 InjectedBundleBackForwardList* WebPage::backForwardList()
2045 if (!m_backForwardList)
2046 m_backForwardList = InjectedBundleBackForwardList::create(this);
2047 return m_backForwardList.get();
2051 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point)
2053 const int minimumZoomTargetWidth = 100;
2055 Frame* mainframe = m_mainFrame->coreFrame();
2056 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
2058 Node* node = result.innerNode();
2059 while (node && node->getRect().width() < minimumZoomTargetWidth)
2060 node = node->parentNode();
2062 IntRect zoomableArea;
2064 zoomableArea = node->getRect();
2065 send(Messages::WebPageProxy::DidFindZoomableArea(zoomableArea));
2069 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
2074 void WebPage::SandboxExtensionTracker::invalidate()
2076 if (m_pendingProvisionalSandboxExtension) {
2077 m_pendingProvisionalSandboxExtension->invalidate();
2078 m_pendingProvisionalSandboxExtension = 0;
2081 if (m_provisionalSandboxExtension) {
2082 m_provisionalSandboxExtension->invalidate();
2083 m_provisionalSandboxExtension = 0;
2086 if (m_committedSandboxExtension) {
2087 m_committedSandboxExtension->invalidate();
2088 m_committedSandboxExtension = 0;
2092 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
2094 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
2097 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
2099 ASSERT(frame->isMainFrame());
2101 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
2104 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
2106 // If we get two beginLoad calls in succession, without a provisional load starting, then
2107 // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
2108 if (m_pendingProvisionalSandboxExtension) {
2109 m_pendingProvisionalSandboxExtension->invalidate();
2110 m_pendingProvisionalSandboxExtension = nullptr;
2113 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
2116 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
2118 ASSERT(frame->isMainFrame());
2120 FrameLoader* frameLoader = frame->coreFrame()->loader();
2121 FrameLoadType frameLoadType = frameLoader->loadType();
2123 // If the page is being reloaded, it should reuse whatever extension is committed.
2124 if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
2127 DocumentLoader* documentLoader = frameLoader->documentLoader();
2128 DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
2129 if (!documentLoader || !provisionalDocumentLoader)
2132 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
2138 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
2140 if (!frame->isMainFrame())
2143 // We should only reuse the commited sandbox extension if it is not null. It can be
2144 // null if the last load was for an error page.
2145 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
2146 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
2147 ASSERT(!m_committedSandboxExtension);
2150 ASSERT(!m_provisionalSandboxExtension);
2152 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
2153 if (!m_provisionalSandboxExtension)
2156 m_provisionalSandboxExtension->consume();
2159 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
2161 if (!frame->isMainFrame())
2164 ASSERT(!m_pendingProvisionalSandboxExtension);
2166 // The provisional load has been committed. Invalidate the currently committed sandbox
2167 // extension and make the provisional sandbox extension the committed sandbox extension.
2168 if (m_committedSandboxExtension)
2169 m_committedSandboxExtension->invalidate();
2171 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
2174 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
2176 if (!frame->isMainFrame())
2179 if (!m_provisionalSandboxExtension)
2182 m_provisionalSandboxExtension->invalidate();
2183 m_provisionalSandboxExtension = nullptr;
2186 bool WebPage::hasLocalDataForURL(const KURL& url)
2188 if (url.isLocalFile())
2191 FrameLoader* frameLoader = m_page->mainFrame()->loader();
2192 DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
2193 if (documentLoader && documentLoader->subresource(url))
2196 return platformHasLocalDataForURL(url);
2199 void WebPage::setCustomTextEncodingName(const String& encoding)
2201 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
2204 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
2206 WebBackForwardListProxy::removeItem(itemID);
2211 bool WebPage::isSpeaking()
2214 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
2217 void WebPage::speak(const String& string)
2219 send(Messages::WebPageProxy::Speak(string));
2222 void WebPage::stopSpeaking()
2224 send(Messages::WebPageProxy::StopSpeaking());
2229 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
2231 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2235 Frame* coreFrame = frame->coreFrame();
2239 if (!m_printContext)
2240 m_printContext = adoptPtr(new PrintContext(coreFrame));
2242 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2244 float fullPageHeight;
2245 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
2248 void WebPage::endPrinting()
2250 m_printContext = nullptr;
2253 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
2255 Vector<IntRect> resultPageRects;
2256 double resultTotalScaleFactorForPrinting = 1;
2258 beginPrinting(frameID, printInfo);
2260 if (m_printContext) {
2261 resultPageRects = m_printContext->pageRects();
2262 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
2265 // If we're asked to print, we should actually print at least a blank page.
2266 if (resultPageRects.isEmpty())
2267 resultPageRects.append(IntRect(0, 0, 1, 1));
2269 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
2272 #if PLATFORM(MAC) || PLATFORM(WIN)
2273 void WebPage::drawRectToPDF(uint64_t frameID, const WebCore::IntRect& rect, uint64_t callbackID)
2275 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2276 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2278 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2281 ASSERT(coreFrame->document()->printing());
2284 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2285 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2287 CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
2288 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2289 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2290 CGPDFContextBeginPage(context.get(), pageInfo.get());
2292 GraphicsContext ctx(context.get());
2293 ctx.scale(FloatSize(1, -1));
2294 ctx.translate(0, -rect.height());
2295 m_printContext->spoolRect(ctx, rect);
2297 CGPDFContextEndPage(context.get());
2298 CGPDFContextClose(context.get());
2302 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2305 void WebPage::drawPagesToPDF(uint64_t frameID, uint32_t first, uint32_t count, uint64_t callbackID)
2307 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2308 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2310 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2313 ASSERT(coreFrame->document()->printing());
2316 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2317 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2319 CGRect mediaBox = m_printContext->pageCount() ? m_printContext->pageRect(0) : CGRectMake(0, 0, 1, 1);
2320 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2321 for (uint32_t page = first; page < first + count; ++page) {
2322 if (page >= m_printContext->pageCount())
2325 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2326 CGPDFContextBeginPage(context.get(), pageInfo.get());
2328 GraphicsContext ctx(context.get());
2329 ctx.scale(FloatSize(1, -1));
2330 ctx.translate(0, -m_printContext->pageRect(page).height());
2331 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
2333 CGPDFContextEndPage(context.get());
2335 CGPDFContextClose(context.get());
2339 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2343 void WebPage::runModal()
2347 if (m_isRunningModal)
2350 m_isRunningModal = true;
2351 send(Messages::WebPageProxy::RunModal());
2353 ASSERT(!m_isRunningModal);
2356 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
2358 m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
2362 void WebPage::platformDragEnded()
2367 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
2369 if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
2371 return platformCanHandleRequest(request);
2374 #if PLATFORM(MAC) && !defined(BUILDING_ON_SNOW_LEOPARD)
2375 void WebPage::handleCorrectionPanelResult(const String& result)
2377 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2380 frame->editor()->handleCorrectionPanelResult(result);
2384 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
2386 mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
2389 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
2391 mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
2394 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
2396 mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
2399 } // namespace WebKit