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 "MessageID.h"
36 #include "NetscapePlugin.h"
37 #include "PageOverlay.h"
38 #include "PluginProxy.h"
39 #include "PluginView.h"
40 #include "PrintInfo.h"
42 #include "SessionState.h"
43 #include "ShareableBitmap.h"
44 #include "WebBackForwardList.h"
45 #include "WebBackForwardListItem.h"
46 #include "WebBackForwardListProxy.h"
47 #include "WebChromeClient.h"
48 #include "WebContextMenu.h"
49 #include "WebContextMenuClient.h"
50 #include "WebContextMessages.h"
51 #include "WebCoreArgumentCoders.h"
52 #include "WebDragClient.h"
53 #include "WebEditorClient.h"
55 #include "WebEventConversion.h"
57 #include "WebGeolocationClient.h"
59 #include "WebInspector.h"
60 #include "WebInspectorClient.h"
61 #include "WebOpenPanelResultListener.h"
62 #include "WebPageCreationParameters.h"
63 #include "WebPageGroupProxy.h"
64 #include "WebPageProxyMessages.h"
65 #include "WebPopupMenu.h"
66 #include "WebPreferencesStore.h"
67 #include "WebProcess.h"
68 #include "WebProcessProxyMessageKinds.h"
69 #include "WebProcessProxyMessages.h"
70 #include <WebCore/AbstractDatabase.h>
71 #include <WebCore/ArchiveResource.h>
72 #include <WebCore/Chrome.h>
73 #include <WebCore/ContextMenuController.h>
74 #include <WebCore/DocumentFragment.h>
75 #include <WebCore/DocumentLoader.h>
76 #include <WebCore/DocumentMarkerController.h>
77 #include <WebCore/DragController.h>
78 #include <WebCore/DragData.h>
79 #include <WebCore/EventHandler.h>
80 #include <WebCore/FocusController.h>
81 #include <WebCore/Frame.h>
82 #include <WebCore/FrameLoaderTypes.h>
83 #include <WebCore/FrameView.h>
84 #include <WebCore/HistoryItem.h>
85 #include <WebCore/KeyboardEvent.h>
86 #include <WebCore/Page.h>
87 #include <WebCore/PlatformKeyboardEvent.h>
88 #include <WebCore/PrintContext.h>
89 #include <WebCore/RenderTreeAsText.h>
90 #include <WebCore/RenderLayer.h>
91 #include <WebCore/RenderView.h>
92 #include <WebCore/ReplaceSelectionCommand.h>
93 #include <WebCore/ResourceRequest.h>
94 #include <WebCore/SerializedScriptValue.h>
95 #include <WebCore/Settings.h>
96 #include <WebCore/SharedBuffer.h>
97 #include <WebCore/SubstituteData.h>
98 #include <WebCore/TextIterator.h>
99 #include <WebCore/markup.h>
100 #include <runtime/JSLock.h>
101 #include <runtime/JSValue.h>
103 #include <WebCore/Range.h>
104 #include <WebCore/VisiblePosition.h>
106 #if PLATFORM(MAC) || PLATFORM(WIN)
107 #include <WebCore/LegacyWebArchive.h>
110 #if ENABLE(PLUGIN_PROCESS)
111 // FIXME: This is currently Mac-specific!
112 #include "MachPort.h"
116 #include "HitTestResult.h"
120 #include <wtf/RefCountedLeakCounter.h>
124 using namespace WebCore;
129 static WTF::RefCountedLeakCounter webPageCounter("WebPage");
132 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
134 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
136 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
137 WebProcess::shared().injectedBundle()->didCreatePage(page.get());
139 return page.release();
142 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
143 : m_viewSize(parameters.viewSize)
144 , m_drawsBackground(true)
145 , m_drawsTransparentBackground(false)
148 , m_tabToLinks(false)
150 , m_windowIsVisible(false)
151 , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
153 , m_nativeWindow(parameters.nativeWindow)
155 , m_findController(this)
156 , m_geolocationPermissionRequestManager(this)
158 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
159 , m_canRunModal(parameters.canRunModal)
160 , m_isRunningModal(false)
161 , m_cachedMainFrameIsPinnedToLeftSide(false)
162 , m_cachedMainFrameIsPinnedToRightSide(false)
166 Page::PageClients pageClients;
167 pageClients.chromeClient = new WebChromeClient(this);
168 pageClients.contextMenuClient = new WebContextMenuClient(this);
169 pageClients.editorClient = new WebEditorClient(this);
170 pageClients.dragClient = new WebDragClient(this);
171 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
172 #if ENABLE(CLIENT_BASED_GEOLOCATION)
173 pageClients.geolocationClient = new WebGeolocationClient(this);
175 #if ENABLE(INSPECTOR)
176 pageClients.inspectorClient = new WebInspectorClient(this);
178 m_page = adoptPtr(new Page(pageClients));
180 // Qt does not yet call setIsInWindow. Until it does, just leave
181 // this line out so plug-ins and video will work. Eventually all platforms
182 // should call setIsInWindow and this comment and #if should be removed,
183 // leaving behind the setCanStartMedia call.
185 m_page->setCanStartMedia(false);
188 updatePreferences(parameters.store);
190 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
191 m_page->setGroupName(m_pageGroup->identifier());
193 platformInitialize();
194 Settings::setDefaultMinDOMTimerInterval(0.004);
196 m_drawingArea = DrawingArea::create(this, parameters);
197 m_mainFrame = WebFrame::createMainFrame(this);
199 setDrawsBackground(parameters.drawsBackground);
200 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
202 setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
204 setActive(parameters.isActive);
205 setFocused(parameters.isFocused);
206 setIsInWindow(parameters.isInWindow);
208 m_userAgent = parameters.userAgent;
210 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
212 if (!parameters.sessionState.isEmpty())
213 restoreSession(parameters.sessionState);
216 webPageCounter.increment();
222 if (m_backForwardList)
223 m_backForwardList->detach();
227 m_sandboxExtensionTracker.invalidate();
230 ASSERT(m_pluginViews.isEmpty());
234 webPageCounter.decrement();
238 void WebPage::dummy(bool&)
242 CoreIPC::Connection* WebPage::connection() const
244 return WebProcess::shared().connection();
247 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
249 m_contextMenuClient.initialize(client);
252 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
254 m_editorClient.initialize(client);
257 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
259 m_formClient.initialize(client);
262 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
264 m_loaderClient.initialize(client);
267 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
269 m_policyClient.initialize(client);
272 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
274 m_resourceLoadClient.initialize(client);
277 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
279 m_uiClient.initialize(client);
282 PassRefPtr<Plugin> WebPage::createPlugin(const Plugin::Parameters& parameters)
286 if (!WebProcess::shared().connection()->sendSync(
287 Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()),
288 Messages::WebContext::GetPluginPath::Reply(pluginPath), 0)) {
292 if (pluginPath.isNull())
295 #if ENABLE(PLUGIN_PROCESS)
296 return PluginProxy::create(pluginPath);
298 return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
302 String WebPage::renderTreeExternalRepresentation() const
304 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
307 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
309 Frame* frame = m_page->focusController()->focusedOrMainFrame();
312 frame->editor()->command(commandName).execute(argument);
315 bool WebPage::isEditingCommandEnabled(const String& commandName)
317 Frame* frame = m_page->focusController()->focusedOrMainFrame();
321 Editor::Command command = frame->editor()->command(commandName);
322 return command.isSupported() && command.isEnabled();
325 void WebPage::clearMainFrameName()
327 mainFrame()->coreFrame()->tree()->clearName();
330 #if USE(ACCELERATED_COMPOSITING)
331 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
333 m_drawingArea->setRootCompositingLayer(layer);
336 void WebPage::exitAcceleratedCompositingMode()
338 m_drawingArea->setRootCompositingLayer(0);
342 void WebPage::close()
349 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
350 WebProcess::shared().injectedBundle()->willDestroyPage(this);
352 #if ENABLE(INSPECTOR)
356 if (m_activePopupMenu) {
357 m_activePopupMenu->disconnectFromPage();
358 m_activePopupMenu = 0;
361 if (m_activeOpenPanelResultListener) {
362 m_activeOpenPanelResultListener->disconnectFromPage();
363 m_activeOpenPanelResultListener = 0;
366 m_sandboxExtensionTracker.invalidate();
368 m_printContext = nullptr;
370 m_mainFrame->coreFrame()->loader()->detachFromParent();
373 m_drawingArea.clear();
375 bool isRunningModal = m_isRunningModal;
376 m_isRunningModal = false;
378 // The WebPage can be destroyed by this call.
379 WebProcess::shared().removeWebPage(m_pageID);
382 WebProcess::shared().runLoop()->stop();
385 void WebPage::tryClose()
387 if (!m_mainFrame->coreFrame()->loader()->shouldClose())
393 void WebPage::sendClose()
395 send(Messages::WebPageProxy::ClosePage());
398 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
400 loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
403 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
405 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
406 m_mainFrame->coreFrame()->loader()->load(request, false);
409 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
411 ResourceRequest request(baseURL);
412 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
413 m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
416 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
418 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
419 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
420 loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
423 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
425 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
426 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
427 KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString) ;
428 loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
431 void WebPage::loadPlainTextString(const String& string)
433 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
434 loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
437 void WebPage::stopLoadingFrame(uint64_t frameID)
439 WebFrame* frame = WebProcess::shared().webFrame(frameID);
443 frame->coreFrame()->loader()->stopForUserCancel();
446 void WebPage::stopLoading()
448 m_mainFrame->coreFrame()->loader()->stopForUserCancel();
451 void WebPage::setDefersLoading(bool defersLoading)
453 m_page->setDefersLoading(defersLoading);
456 void WebPage::reload(bool reloadFromOrigin)
458 m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
461 void WebPage::goForward(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
463 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
468 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
469 m_page->goToItem(item, FrameLoadTypeForward);
472 void WebPage::goBack(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
474 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
479 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
480 m_page->goToItem(item, FrameLoadTypeBack);
483 void WebPage::goToBackForwardItem(uint64_t backForwardItemID, const SandboxExtension::Handle& sandboxExtensionHandle)
485 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
490 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
491 m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
494 void WebPage::layoutIfNeeded()
496 if (m_mainFrame->coreFrame()->view())
497 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
500 void WebPage::setSize(const WebCore::IntSize& viewSize)
502 #if ENABLE(TILED_BACKING_STORE)
503 // If we are resizing to content ignore external attempts.
504 if (!m_resizesToContentsLayoutSize.isEmpty())
508 if (m_viewSize == viewSize)
511 Frame* frame = m_page->mainFrame();
513 frame->view()->resize(viewSize);
514 frame->view()->setNeedsLayout();
515 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
517 m_viewSize = viewSize;
520 #if ENABLE(TILED_BACKING_STORE)
521 void WebPage::setActualVisibleContentRect(const IntRect& rect)
523 Frame* frame = m_page->mainFrame();
525 frame->view()->setActualVisibleContentRect(rect);
528 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
530 if (m_resizesToContentsLayoutSize == targetLayoutSize)
533 m_resizesToContentsLayoutSize = targetLayoutSize;
535 Frame* frame = m_page->mainFrame();
536 if (m_resizesToContentsLayoutSize.isEmpty()) {
537 frame->view()->setDelegatesScrolling(false);
538 frame->view()->setUseFixedLayout(false);
539 frame->view()->setPaintsEntireContents(false);
541 frame->view()->setDelegatesScrolling(true);
542 frame->view()->setUseFixedLayout(true);
543 frame->view()->setPaintsEntireContents(true);
544 frame->view()->setFixedLayoutSize(m_resizesToContentsLayoutSize);
546 frame->view()->forceLayout();
549 void WebPage::resizeToContentsIfNeeded()
551 if (m_resizesToContentsLayoutSize.isEmpty())
554 Frame* frame = m_page->mainFrame();
556 IntSize contentSize = frame->view()->contentsSize();
557 if (contentSize == m_viewSize)
560 m_viewSize = contentSize;
561 frame->view()->resize(m_viewSize);
562 frame->view()->setNeedsLayout();
566 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
568 Frame* frame = m_page->mainFrame();
570 IntPoint scrollPosition = frame->view()->scrollPosition();
571 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
573 // If the current scroll position in a direction is the max scroll position
574 // we don't want to scroll at all.
575 IntSize newScrollOffset;
576 if (scrollPosition.x() < maximumScrollPosition.x())
577 newScrollOffset.setWidth(scrollOffset.width());
578 if (scrollPosition.y() < maximumScrollPosition.y())
579 newScrollOffset.setHeight(scrollOffset.height());
581 if (newScrollOffset.isZero())
584 frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
587 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
589 graphicsContext.save();
590 graphicsContext.clip(rect);
591 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
592 graphicsContext.restore();
595 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
597 ASSERT(m_pageOverlay);
599 graphicsContext.save();
600 graphicsContext.clip(rect);
601 m_pageOverlay->drawRect(graphicsContext, rect);
602 graphicsContext.restore();
605 double WebPage::textZoomFactor() const
607 Frame* frame = m_mainFrame->coreFrame();
610 return frame->textZoomFactor();
613 void WebPage::setTextZoomFactor(double zoomFactor)
615 Frame* frame = m_mainFrame->coreFrame();
618 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
621 double WebPage::pageZoomFactor() const
623 Frame* frame = m_mainFrame->coreFrame();
626 return frame->pageZoomFactor();
629 void WebPage::setPageZoomFactor(double zoomFactor)
631 Frame* frame = m_mainFrame->coreFrame();
634 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
637 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
639 Frame* frame = m_mainFrame->coreFrame();
642 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
645 void WebPage::scaleWebView(double scale, const IntPoint& origin)
647 Frame* frame = m_mainFrame->coreFrame();
650 frame->scalePage(scale, origin);
652 send(Messages::WebPageProxy::ViewScaleFactorDidChange(scale));
655 double WebPage::viewScaleFactor() const
657 Frame* frame = m_mainFrame->coreFrame();
660 return frame->pageScaleFactor();
663 void WebPage::setUseFixedLayout(bool fixed)
665 Frame* frame = m_mainFrame->coreFrame();
669 FrameView* view = frame->view();
673 view->setUseFixedLayout(fixed);
675 view->setFixedLayoutSize(IntSize());
678 void WebPage::setFixedLayoutSize(const IntSize& size)
680 Frame* frame = m_mainFrame->coreFrame();
684 FrameView* view = frame->view();
688 view->setFixedLayoutSize(size);
692 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
695 pageOverlay->setPage(0);
697 m_pageOverlay = pageOverlay;
698 m_pageOverlay->setPage(this);
700 m_drawingArea->didInstallPageOverlay();
702 m_pageOverlay->setNeedsDisplay();
705 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay)
707 if (pageOverlay != m_pageOverlay)
710 m_pageOverlay->setPage(0);
711 m_pageOverlay = nullptr;
713 m_drawingArea->didUninstallPageOverlay();
716 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
718 FrameView* frameView = m_mainFrame->coreFrame()->view();
722 frameView->updateLayoutAndStyleIfNeededRecursive();
724 PaintBehavior oldBehavior = frameView->paintBehavior();
725 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
727 RefPtr<WebImage> snapshot = WebImage::create(rect.size(), options);
728 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
730 graphicsContext->save();
731 graphicsContext->translate(-rect.x(), -rect.y());
732 frameView->paint(graphicsContext.get(), rect);
733 graphicsContext->restore();
735 frameView->setPaintBehavior(oldBehavior);
737 return snapshot.release();
740 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
742 FrameView* frameView = m_mainFrame->coreFrame()->view();
746 frameView->updateLayoutAndStyleIfNeededRecursive();
748 PaintBehavior oldBehavior = frameView->paintBehavior();
749 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
751 bool scale = scaleFactor != 1;
752 IntSize size = rect.size();
754 size = IntSize(ceil(rect.width() * scaleFactor), ceil(rect.height() * scaleFactor));
756 RefPtr<WebImage> snapshot = WebImage::create(size, options);
757 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
758 graphicsContext->save();
761 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
763 graphicsContext->translate(-rect.x(), -rect.y());
764 frameView->paintContents(graphicsContext.get(), rect);
765 graphicsContext->restore();
767 frameView->setPaintBehavior(oldBehavior);
769 return snapshot.release();
772 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
774 return scaledSnapshotInDocumentCoordinates(rect, 1, options);
777 void WebPage::pageDidScroll()
779 // Hide the find indicator.
780 m_findController.hideFindIndicator();
782 m_uiClient.pageDidScroll(this);
784 send(Messages::WebPageProxy::PageDidScroll());
787 #if ENABLE(TILED_BACKING_STORE)
788 void WebPage::pageDidRequestScroll(const IntSize& delta)
790 send(Messages::WebPageProxy::PageDidRequestScroll(delta));
794 WebContextMenu* WebPage::contextMenu()
797 m_contextMenu = WebContextMenu::create(this);
798 return m_contextMenu.get();
801 void WebPage::getLocationAndLengthFromRange(Range* range, uint64_t& location, uint64_t& length)
806 if (!range || !range->startContainer())
809 Element* selectionRoot = range->ownerDocument()->frame()->selection()->rootEditableElement();
810 Element* scope = selectionRoot ? selectionRoot : range->ownerDocument()->documentElement();
812 // Mouse events may cause TSM to attempt to create an NSRange for a portion of the view
813 // that is not inside the current editable region. These checks ensure we don't produce
814 // potentially invalid data when responding to such requests.
815 if (range->startContainer() != scope && !range->startContainer()->isDescendantOf(scope))
817 if (range->endContainer() != scope && !range->endContainer()->isDescendantOf(scope))
820 RefPtr<Range> testRange = Range::create(scope->document(), scope, 0, range->startContainer(), range->startOffset());
821 ASSERT(testRange->startContainer() == scope);
822 location = TextIterator::rangeLength(testRange.get());
825 testRange->setEnd(range->endContainer(), range->endOffset(), ec);
826 ASSERT(testRange->startContainer() == scope);
827 length = TextIterator::rangeLength(testRange.get()) - location;
832 static const WebEvent* g_currentEvent = 0;
834 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
835 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
836 // platform events passed to the event handler code.
837 const WebEvent* WebPage::currentEvent()
839 return g_currentEvent;
844 explicit CurrentEvent(const WebEvent& event)
845 : m_previousCurrentEvent(g_currentEvent)
847 g_currentEvent = &event;
852 g_currentEvent = m_previousCurrentEvent;
856 const WebEvent* m_previousCurrentEvent;
859 static bool isContextClick(const PlatformMouseEvent& event)
861 if (event.button() == WebCore::RightButton)
865 // FIXME: this really should be about OSX-style UI, not about the Mac port
866 if (event.button() == WebCore::LeftButton && event.ctrlKey())
873 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, Page* page)
875 Frame* frame = page->mainFrame();
879 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
881 switch (platformMouseEvent.eventType()) {
882 case WebCore::MouseEventPressed:
884 if (isContextClick(platformMouseEvent))
885 page->contextMenuController()->clearContextMenu();
887 bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
889 if (isContextClick(platformMouseEvent)) {
890 handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
892 page->chrome()->showContextMenu();
897 case WebCore::MouseEventReleased:
898 return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
899 case WebCore::MouseEventMoved:
900 return frame->eventHandler()->mouseMoved(platformMouseEvent);
903 ASSERT_NOT_REACHED();
908 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
910 bool handled = false;
913 // Let the page overlay handle the event.
914 handled = m_pageOverlay->mouseEvent(mouseEvent);
918 CurrentEvent currentEvent(mouseEvent);
920 handled = handleMouseEvent(mouseEvent, m_page.get());
923 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
926 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
928 Frame* frame = page->mainFrame();
932 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
933 return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
936 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
938 CurrentEvent currentEvent(wheelEvent);
940 bool handled = handleWheelEvent(wheelEvent, m_page.get());
941 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
944 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
946 if (!page->mainFrame()->view())
949 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
950 return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
951 return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
954 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
956 CurrentEvent currentEvent(keyboardEvent);
958 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
960 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
962 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
965 #if ENABLE(GESTURE_EVENTS)
966 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
968 Frame* frame = page->mainFrame();
972 PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
973 return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
976 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
978 CurrentEvent currentEvent(gestureEvent);
980 bool handled = handleGestureEvent(gestureEvent, m_page.get());
981 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
985 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
987 bool isEnabled = false;
989 Frame* frame = m_page->focusController()->focusedOrMainFrame();
991 Editor::Command command = frame->editor()->command(commandName);
992 state = command.state();
993 isEnabled = command.isSupported() && command.isEnabled();
996 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
999 void WebPage::executeEditCommand(const String& commandName)
1001 executeEditingCommand(commandName, String());
1004 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1006 const BackForwardListItemVector& list = sessionState.list();
1007 size_t size = list.size();
1008 uint64_t currentItemID = 0;
1009 for (size_t i = 0; i < size; ++i) {
1010 WebBackForwardListItem* webItem = list[i].get();
1011 DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1013 RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1015 LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1019 if (i == sessionState.currentIndex())
1020 currentItemID = webItem->itemID();
1022 WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1024 ASSERT(currentItemID);
1025 return currentItemID;
1028 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState, const SandboxExtension::Handle& sandboxExtensionHandle)
1030 if (uint64_t currentItemID = restoreSession(sessionState))
1031 goToBackForwardItem(currentItemID, sandboxExtensionHandle);
1034 #if ENABLE(TOUCH_EVENTS)
1035 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1037 Frame* frame = page->mainFrame();
1041 return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1044 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1046 CurrentEvent currentEvent(touchEvent);
1048 bool handled = handleTouchEvent(touchEvent, m_page.get());
1050 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1054 void WebPage::setActive(bool isActive)
1056 m_page->focusController()->setActive(isActive);
1059 // Tell all our plug-in views that the window focus changed.
1060 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1061 (*it)->setWindowIsFocused(isActive);
1065 void WebPage::setDrawsBackground(bool drawsBackground)
1067 if (m_drawsBackground == drawsBackground)
1070 m_drawsBackground = drawsBackground;
1072 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1073 if (FrameView* view = coreFrame->view())
1074 view->setTransparent(!drawsBackground);
1077 m_drawingArea->pageBackgroundTransparencyChanged();
1078 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1081 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1083 if (m_drawsTransparentBackground == drawsTransparentBackground)
1086 m_drawsTransparentBackground = drawsTransparentBackground;
1088 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
1089 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1090 if (FrameView* view = coreFrame->view())
1091 view->setBaseBackgroundColor(backgroundColor);
1094 m_drawingArea->pageBackgroundTransparencyChanged();
1095 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1098 void WebPage::viewWillStartLiveResize()
1103 // FIXME: This should propagate to all ScrollableAreas.
1104 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1105 if (FrameView* view = frame->view())
1106 view->willStartLiveResize();
1110 void WebPage::viewWillEndLiveResize()
1115 // FIXME: This should propagate to all ScrollableAreas.
1116 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1117 if (FrameView* view = frame->view())
1118 view->willEndLiveResize();
1122 void WebPage::setFocused(bool isFocused)
1124 m_page->focusController()->setFocused(isFocused);
1127 void WebPage::setInitialFocus(bool forward)
1129 if (!m_page || !m_page->focusController())
1132 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1133 frame->document()->setFocusedNode(0);
1134 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
1137 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
1139 if (m_windowResizerSize == windowResizerSize)
1142 m_windowResizerSize = windowResizerSize;
1144 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1145 FrameView* view = coreFrame->view();
1147 view->windowResizerRectChanged();
1151 void WebPage::setIsInWindow(bool isInWindow)
1154 m_page->setCanStartMedia(false);
1155 m_page->willMoveOffscreen();
1157 m_page->setCanStartMedia(true);
1158 m_page->didMoveOnscreen();
1162 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
1164 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1167 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
1170 void WebPage::show()
1172 send(Messages::WebPageProxy::ShowPage());
1175 void WebPage::setUserAgent(const String& userAgent)
1177 m_userAgent = userAgent;
1180 IntRect WebPage::windowToScreen(const IntRect& rect)
1183 sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
1187 IntRect WebPage::windowResizerRect() const
1189 if (m_windowResizerSize.isEmpty())
1192 IntSize frameViewSize;
1193 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
1194 if (FrameView* view = coreFrame->view())
1195 frameViewSize = view->size();
1198 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
1199 m_windowResizerSize.width(), m_windowResizerSize.height());
1202 KeyboardUIMode WebPage::keyboardUIMode()
1204 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
1205 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
1208 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
1210 // NOTE: We need to be careful when running scripts that the objects we depend on don't
1211 // disappear during script execution.
1213 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
1214 // long enough for the DataReference to be encoded by the sent message.
1215 RefPtr<SerializedScriptValue> serializedResultValue;
1216 CoreIPC::DataReference dataReference;
1218 JSLock lock(SilenceAssertionsOnly);
1219 if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
1220 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue)))
1221 dataReference = CoreIPC::DataReference(serializedResultValue->data().data(), serializedResultValue->data().size());
1224 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
1227 void WebPage::getContentsAsString(uint64_t callbackID)
1229 String resultString = m_mainFrame->contentsAsString();
1230 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1233 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
1235 String resultString = renderTreeExternalRepresentation();
1236 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1239 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
1241 String resultString = m_mainFrame->selectionAsString();
1242 if (resultString.isEmpty())
1243 resultString = m_mainFrame->contentsAsString();
1244 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1247 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
1249 String resultString;
1250 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
1251 resultString = frame->source();
1253 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1256 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
1258 CoreIPC::DataReference dataReference;
1260 RefPtr<SharedBuffer> buffer;
1261 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1262 if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1263 if ((buffer = loader->mainResourceData()))
1264 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1268 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1271 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURL, uint64_t callbackID)
1273 CoreIPC::DataReference dataReference;
1275 RefPtr<SharedBuffer> buffer;
1276 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1277 if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1278 if (RefPtr<ArchiveResource> subresource = loader->subresource(KURL(KURL(), resourceURL))) {
1279 if ((buffer = subresource->data()))
1280 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1285 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1288 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
1290 CoreIPC::DataReference dataReference;
1292 #if PLATFORM(MAC) || PLATFORM(WIN)
1293 RetainPtr<CFDataRef> data;
1294 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1295 if (RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(frame->coreFrame()->document())) {
1296 if ((data = archive->rawDataRepresentation()))
1297 dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
1302 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1305 void WebPage::forceRepaintWithoutCallback()
1307 m_drawingArea->forceRepaint();
1310 void WebPage::forceRepaint(uint64_t callbackID)
1312 forceRepaintWithoutCallback();
1313 send(Messages::WebPageProxy::VoidCallback(callbackID));
1316 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
1318 WebPreferencesStore::removeTestRunnerOverrides();
1319 updatePreferences(store);
1322 void WebPage::updatePreferences(const WebPreferencesStore& store)
1324 Settings* settings = m_page->settings();
1326 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1328 // FIXME: This should be generated from macro expansion for all preferences,
1329 // but we currently don't match the naming of WebCore exactly so we are
1330 // handrolling the boolean and integer preferences until that is fixed.
1332 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1334 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1336 #undef INITIALIZE_SETTINGS
1338 settings->setJavaScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1339 settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1340 settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1341 settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1342 settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1343 settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1344 settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1345 settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1346 settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1347 settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1348 settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1349 settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1350 settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1351 settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1352 settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1353 #if ENABLE(WEB_ARCHIVE)
1354 settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1356 settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1357 settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1358 settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1359 settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1360 settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1361 settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
1362 settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1364 settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1365 settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1366 settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1367 settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1370 // Temporarily turn off accelerated compositing until we have a good solution for rendering it.
1371 settings->setAcceleratedCompositingEnabled(false);
1372 settings->setAcceleratedDrawingEnabled(false);
1374 settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()));
1375 settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()));
1377 settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1378 settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1379 settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
1381 #if ENABLE(DATABASE)
1382 AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1385 platformPreferencesDidChange(store);
1388 #if ENABLE(INSPECTOR)
1389 WebInspector* WebPage::inspector()
1394 m_inspector = WebInspector::create(this);
1395 return m_inspector.get();
1400 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
1402 Node* node = evt->target()->toNode();
1404 Frame* frame = node->document()->frame();
1407 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
1411 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
1413 if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
1414 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
1415 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
1416 // (e.g. Tab that inserts a Tab character, or Enter).
1417 return !command.isTextInsertion() && command.execute(evt);
1420 if (command.execute(evt))
1423 // Don't insert null or control characters as they can result in unexpected behaviour
1424 if (evt->charCode() < ' ')
1427 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
1432 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
1435 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1439 DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1441 case DragControllerActionEntered:
1442 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1445 case DragControllerActionUpdated:
1446 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1449 case DragControllerActionExited:
1450 m_page->dragController()->dragExited(&dragData);
1453 case DragControllerActionPerformDrag:
1454 m_page->dragController()->performDrag(&dragData);
1458 ASSERT_NOT_REACHED();
1462 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const String& dragStorageName, uint32_t flags)
1465 send(Messages::WebPageProxy::DidPerformDragControllerAction(DragOperationNone));
1469 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
1471 case DragControllerActionEntered:
1472 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
1475 case DragControllerActionUpdated:
1476 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
1479 case DragControllerActionExited:
1480 m_page->dragController()->dragExited(&dragData);
1483 case DragControllerActionPerformDrag:
1484 m_page->dragController()->performDrag(&dragData);
1488 ASSERT_NOT_REACHED();
1493 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
1495 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
1496 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
1498 m_page->dragController()->dragEnded();
1499 FrameView* view = m_page->mainFrame()->view();
1502 // FIXME: These are fake modifier keys here, but they should be real ones instead.
1503 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, MouseEventMoved, 0, false, false, false, false, currentTime());
1504 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
1507 WebEditCommand* WebPage::webEditCommand(uint64_t commandID)
1509 return m_editCommandMap.get(commandID).get();
1512 void WebPage::addWebEditCommand(uint64_t commandID, WebEditCommand* command)
1514 m_editCommandMap.set(commandID, command);
1517 void WebPage::removeWebEditCommand(uint64_t commandID)
1519 m_editCommandMap.remove(commandID);
1522 void WebPage::unapplyEditCommand(uint64_t commandID)
1524 WebEditCommand* command = webEditCommand(commandID);
1528 command->command()->unapply();
1531 void WebPage::reapplyEditCommand(uint64_t commandID)
1533 WebEditCommand* command = webEditCommand(commandID);
1538 command->command()->reapply();
1542 void WebPage::didRemoveEditCommand(uint64_t commandID)
1544 removeWebEditCommand(commandID);
1547 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
1549 m_activePopupMenu = menu;
1552 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
1554 m_activeOpenPanelResultListener = openPanelResultListener;
1557 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
1559 return m_page->findString(target, options);
1562 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
1564 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
1567 void WebPage::hideFindUI()
1569 m_findController.hideFindUI();
1572 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
1574 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
1577 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
1579 if (!m_activePopupMenu)
1582 m_activePopupMenu->didChangeSelectedIndex(newIndex);
1583 m_activePopupMenu = 0;
1586 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
1588 if (!m_activeOpenPanelResultListener)
1591 m_activeOpenPanelResultListener->didChooseFiles(files);
1592 m_activeOpenPanelResultListener = 0;
1595 void WebPage::didCancelForOpenPanel()
1597 m_activeOpenPanelResultListener = 0;
1600 #if ENABLE(WEB_PROCESS_SANDBOX)
1601 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
1603 SandboxExtension::create(handle)->consumePermanently();
1607 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
1609 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
1612 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
1614 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1615 frame->editor()->advanceToNextMisspelling(startBeforeSelection);
1618 void WebPage::changeSpellingToWord(const String& word)
1620 replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
1623 void WebPage::unmarkAllMisspellings()
1625 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1626 if (Document* document = frame->document())
1627 document->markers()->removeMarkers(DocumentMarker::Spelling);
1631 void WebPage::unmarkAllBadGrammar()
1633 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
1634 if (Document* document = frame->document())
1635 document->markers()->removeMarkers(DocumentMarker::Grammar);
1640 void WebPage::uppercaseWord()
1642 m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
1645 void WebPage::lowercaseWord()
1647 m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
1650 void WebPage::capitalizeWord()
1652 m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
1656 void WebPage::setTextForActivePopupMenu(int32_t index)
1658 if (!m_activePopupMenu)
1661 m_activePopupMenu->setTextForIndex(index);
1664 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
1666 ASSERT(m_contextMenu);
1667 m_contextMenu->itemSelected(item);
1671 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
1673 if (frame->selection()->isNone())
1676 RefPtr<DocumentFragment> textFragment = createFragmentFromText(frame->selection()->toNormalizedRange().get(), text);
1677 applyCommand(ReplaceSelectionCommand::create(frame->document(), textFragment.release(), ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
1678 frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
1681 bool WebPage::mainFrameHasCustomRepresentation() const
1683 return static_cast<WebFrameLoaderClient*>(mainFrame()->coreFrame()->loader()->client())->frameHasCustomRepresentation();
1686 void WebPage::didChangeScrollOffsetForMainFrame()
1688 Frame* frame = m_page->mainFrame();
1689 IntPoint scrollPosition = frame->view()->scrollPosition();
1690 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
1692 bool isPinnedToLeftSide = (scrollPosition.x() <= 0);
1693 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
1695 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
1696 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
1698 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
1699 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
1705 void WebPage::addPluginView(PluginView* pluginView)
1707 ASSERT(!m_pluginViews.contains(pluginView));
1709 m_pluginViews.add(pluginView);
1712 void WebPage::removePluginView(PluginView* pluginView)
1714 ASSERT(m_pluginViews.contains(pluginView));
1716 m_pluginViews.remove(pluginView);
1719 void WebPage::setWindowIsVisible(bool windowIsVisible)
1721 m_windowIsVisible = windowIsVisible;
1723 // Tell all our plug-in views that the window visibility changed.
1724 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1725 (*it)->setWindowIsVisible(windowIsVisible);
1728 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
1730 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
1731 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
1732 m_accessibilityPosition = accessibilityViewCoordinates;
1734 // Tell all our plug-in views that the window and view frames have changed.
1735 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1736 (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
1739 bool WebPage::windowIsFocused() const
1741 return m_page->focusController()->isActive();
1746 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
1748 if (messageID.is<CoreIPC::MessageClassDrawingAreaLegacy>()) {
1750 m_drawingArea->didReceiveMessage(connection, messageID, arguments);
1754 #if PLATFORM(MAC) || PLATFORM(WIN)
1755 if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
1757 m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
1762 #if ENABLE(INSPECTOR)
1763 if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
1764 if (WebInspector* inspector = this->inspector())
1765 inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
1770 didReceiveWebPageMessage(connection, messageID, arguments);
1773 CoreIPC::SyncReplyMode WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, CoreIPC::ArgumentEncoder* reply)
1775 return didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
1778 InjectedBundleBackForwardList* WebPage::backForwardList()
1780 if (!m_backForwardList)
1781 m_backForwardList = InjectedBundleBackForwardList::create(this);
1782 return m_backForwardList.get();
1786 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point)
1788 const int minimumZoomTargetWidth = 100;
1790 Frame* mainframe = m_mainFrame->coreFrame();
1791 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1793 Node* node = result.innerNode();
1794 while (node && node->getRect().width() < minimumZoomTargetWidth)
1795 node = node->parentNode();
1797 IntRect zoomableArea;
1799 zoomableArea = node->getRect();
1800 send(Messages::WebPageProxy::DidFindZoomableArea(zoomableArea));
1804 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
1809 void WebPage::SandboxExtensionTracker::invalidate()
1811 if (m_pendingProvisionalSandboxExtension) {
1812 m_pendingProvisionalSandboxExtension->invalidate();
1813 m_pendingProvisionalSandboxExtension = 0;
1816 if (m_provisionalSandboxExtension) {
1817 m_provisionalSandboxExtension->invalidate();
1818 m_provisionalSandboxExtension = 0;
1821 if (m_committedSandboxExtension) {
1822 m_committedSandboxExtension->invalidate();
1823 m_committedSandboxExtension = 0;
1827 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
1829 ASSERT(frame->isMainFrame());
1831 // If we get two beginLoad calls in succession, without a provisional load starting, then
1832 // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
1833 if (m_pendingProvisionalSandboxExtension) {
1834 m_pendingProvisionalSandboxExtension->invalidate();
1835 m_pendingProvisionalSandboxExtension = nullptr;
1838 m_pendingProvisionalSandboxExtension = SandboxExtension::create(handle);
1841 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
1843 ASSERT(frame->isMainFrame());
1845 FrameLoader* frameLoader = frame->coreFrame()->loader();
1846 FrameLoadType frameLoadType = frameLoader->loadType();
1848 // If the page is being reloaded, it should reuse whatever extension is committed.
1849 if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
1852 DocumentLoader* documentLoader = frameLoader->documentLoader();
1853 DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
1854 if (!documentLoader || !provisionalDocumentLoader)
1857 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile()
1858 && provisionalDocumentLoader->triggeringAction().type() == NavigationTypeLinkClicked)
1864 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
1866 if (!frame->isMainFrame())
1869 if (shouldReuseCommittedSandboxExtension(frame)) {
1870 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
1871 ASSERT(!m_committedSandboxExtension);
1874 ASSERT(!m_provisionalSandboxExtension);
1876 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
1877 if (!m_provisionalSandboxExtension)
1880 m_provisionalSandboxExtension->consume();
1883 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
1885 if (!frame->isMainFrame())
1888 ASSERT(!m_pendingProvisionalSandboxExtension);
1890 // The provisional load has been committed. Invalidate the currently committed sandbox
1891 // extension and make the provisional sandbox extension the committed sandbox extension.
1892 if (m_committedSandboxExtension)
1893 m_committedSandboxExtension->invalidate();
1895 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
1898 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
1900 if (!frame->isMainFrame())
1903 ASSERT(!m_pendingProvisionalSandboxExtension);
1904 if (!m_provisionalSandboxExtension)
1907 m_provisionalSandboxExtension->invalidate();
1908 m_provisionalSandboxExtension = nullptr;
1911 bool WebPage::hasLocalDataForURL(const KURL& url)
1913 if (url.isLocalFile())
1916 FrameLoader* frameLoader = m_page->mainFrame()->loader();
1917 DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
1918 if (documentLoader && documentLoader->subresource(url))
1921 return platformHasLocalDataForURL(url);
1924 void WebPage::setCustomTextEncodingName(const String& encoding)
1926 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
1929 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
1931 WebBackForwardListProxy::removeItem(itemID);
1936 bool WebPage::isSpeaking()
1939 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
1942 void WebPage::speak(const String& string)
1944 send(Messages::WebPageProxy::Speak(string));
1947 void WebPage::stopSpeaking()
1949 send(Messages::WebPageProxy::StopSpeaking());
1954 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
1956 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1960 Frame* coreFrame = frame->coreFrame();
1964 if (!m_printContext)
1965 m_printContext = adoptPtr(new PrintContext(coreFrame));
1967 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
1969 float fullPageHeight;
1970 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
1973 void WebPage::endPrinting()
1975 m_printContext = nullptr;
1978 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
1980 Vector<IntRect> resultPageRects;
1981 double resultTotalScaleFactorForPrinting = 1;
1983 beginPrinting(frameID, printInfo);
1985 if (m_printContext) {
1986 resultPageRects = m_printContext->pageRects();
1987 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
1990 // If we're asked to print, we should actually print at least a blank page.
1991 if (resultPageRects.isEmpty())
1992 resultPageRects.append(IntRect(0, 0, 1, 1));
1994 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
1997 #if PLATFORM(MAC) || PLATFORM(WIN)
1998 void WebPage::drawRectToPDF(uint64_t frameID, const WebCore::IntRect& rect, uint64_t callbackID)
2000 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2001 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2003 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2006 ASSERT(coreFrame->document()->printing());
2008 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2009 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2011 CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
2012 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2013 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2014 CGPDFContextBeginPage(context.get(), pageInfo.get());
2016 GraphicsContext ctx(context.get());
2017 ctx.scale(FloatSize(1, -1));
2018 ctx.translate(0, -rect.height());
2019 m_printContext->spoolRect(ctx, rect);
2021 CGPDFContextEndPage(context.get());
2022 CGPDFContextClose(context.get());
2025 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2028 void WebPage::drawPagesToPDF(uint64_t frameID, uint32_t first, uint32_t count, uint64_t callbackID)
2030 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2031 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2033 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2036 ASSERT(coreFrame->document()->printing());
2038 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2039 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2041 CGRect mediaBox = m_printContext->pageCount() ? m_printContext->pageRect(0) : CGRectMake(0, 0, 1, 1);
2042 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2043 for (uint32_t page = first; page < first + count; ++page) {
2044 if (page >= m_printContext->pageCount())
2047 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2048 CGPDFContextBeginPage(context.get(), pageInfo.get());
2050 GraphicsContext ctx(context.get());
2051 ctx.scale(FloatSize(1, -1));
2052 ctx.translate(0, -m_printContext->pageRect(page).height());
2053 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
2055 CGPDFContextEndPage(context.get());
2057 CGPDFContextClose(context.get());
2060 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2064 void WebPage::runModal()
2068 if (m_isRunningModal)
2071 m_isRunningModal = true;
2072 send(Messages::WebPageProxy::RunModal());
2074 ASSERT(!m_isRunningModal);
2077 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
2079 m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
2082 } // namespace WebKit