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 "NotificationPermissionRequestManager.h"
39 #include "PageOverlay.h"
40 #include "PluginProxy.h"
41 #include "PluginView.h"
42 #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"
60 #include "WebGeometry.h"
62 #include "WebInspector.h"
63 #include "WebInspectorClient.h"
64 #include "WebNotificationClient.h"
65 #include "WebOpenPanelResultListener.h"
66 #include "WebPageCreationParameters.h"
67 #include "WebPageGroupProxy.h"
68 #include "WebPageProxyMessages.h"
69 #include "WebPopupMenu.h"
70 #include "WebPreferencesStore.h"
71 #include "WebProcess.h"
72 #include "WebProcessProxyMessages.h"
73 #include <JavaScriptCore/APICast.h>
74 #include <WebCore/AbstractDatabase.h>
75 #include <WebCore/ArchiveResource.h>
76 #include <WebCore/Chrome.h>
77 #include <WebCore/ContextMenuController.h>
78 #include <WebCore/DocumentFragment.h>
79 #include <WebCore/DocumentLoader.h>
80 #include <WebCore/DocumentMarkerController.h>
81 #include <WebCore/DragController.h>
82 #include <WebCore/DragData.h>
83 #include <WebCore/DragSession.h>
84 #include <WebCore/EventHandler.h>
85 #include <WebCore/FocusController.h>
86 #include <WebCore/FormState.h>
87 #include <WebCore/Frame.h>
88 #include <WebCore/FrameLoadRequest.h>
89 #include <WebCore/FrameLoaderTypes.h>
90 #include <WebCore/FrameView.h>
91 #include <WebCore/HTMLFormElement.h>
92 #include <WebCore/HTMLInputElement.h>
93 #include <WebCore/HistoryItem.h>
94 #include <WebCore/KeyboardEvent.h>
95 #include <WebCore/MouseEvent.h>
96 #include <WebCore/Page.h>
97 #include <WebCore/PlatformKeyboardEvent.h>
98 #include <WebCore/PluginDocument.h>
99 #include <WebCore/PrintContext.h>
100 #include <WebCore/RenderArena.h>
101 #include <WebCore/RenderLayer.h>
102 #include <WebCore/RenderTreeAsText.h>
103 #include <WebCore/RenderView.h>
104 #include <WebCore/ReplaceSelectionCommand.h>
105 #include <WebCore/ResourceRequest.h>
106 #include <WebCore/RunLoop.h>
107 #include <WebCore/SchemeRegistry.h>
108 #include <WebCore/ScriptValue.h>
109 #include <WebCore/SerializedScriptValue.h>
110 #include <WebCore/Settings.h>
111 #include <WebCore/SharedBuffer.h>
112 #include <WebCore/SubstituteData.h>
113 #include <WebCore/TextIterator.h>
114 #include <WebCore/markup.h>
115 #include <runtime/JSLock.h>
116 #include <runtime/JSValue.h>
118 #include <WebCore/Range.h>
119 #include <WebCore/VisiblePosition.h>
121 #if ENABLE(PLUGIN_PROCESS)
123 #include "MachPort.h"
128 #include "BuiltInPDFView.h"
132 #include "HitTestResult.h"
138 #include "DataObjectGtk.h"
139 #include "WebPrintOperationGtk.h"
143 #include <wtf/RefCountedLeakCounter.h>
147 using namespace WebCore;
152 class SendStopResponsivenessTimer {
154 SendStopResponsivenessTimer(WebPage* page)
159 ~SendStopResponsivenessTimer()
161 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
168 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
170 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
172 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
174 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
175 WebProcess::shared().injectedBundle()->didCreatePage(page.get());
177 return page.release();
180 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
181 : m_viewSize(parameters.viewSize)
182 , m_useFixedLayout(false)
183 , m_drawsBackground(true)
184 , m_drawsTransparentBackground(false)
187 , m_tabToLinks(false)
189 , m_windowIsVisible(false)
190 , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
191 , m_keyboardEventBeingInterpreted(0)
193 , m_nativeWindow(parameters.nativeWindow)
195 , m_accessibilityObject(0)
197 , m_setCanStartMediaTimer(WebProcess::shared().runLoop(), this, &WebPage::setCanStartMediaTimerFired)
198 , m_findController(this)
199 #if ENABLE(TOUCH_EVENTS)
201 , m_tapHighlightController(this)
204 #if ENABLE(GEOLOCATION)
205 , m_geolocationPermissionRequestManager(this)
208 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
209 , m_canRunModal(parameters.canRunModal)
210 , m_isRunningModal(false)
211 , m_cachedMainFrameIsPinnedToLeftSide(false)
212 , m_cachedMainFrameIsPinnedToRightSide(false)
213 , m_canShortCircuitHorizontalWheelEvents(false)
214 , m_numWheelEventHandlers(0)
215 , m_cachedPageCount(0)
216 , m_isShowingContextMenu(false)
217 , m_willGoToBackForwardItemCallbackEnabled(true)
219 , m_gestureReachedScrollingLimit(false)
223 // FIXME: This is a non-ideal location for this Setting and
224 // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
225 Settings::setDefaultMinDOMTimerInterval(0.004);
227 Page::PageClients pageClients;
228 pageClients.chromeClient = new WebChromeClient(this);
229 pageClients.contextMenuClient = new WebContextMenuClient(this);
230 pageClients.editorClient = new WebEditorClient(this);
231 pageClients.dragClient = new WebDragClient(this);
232 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
233 #if ENABLE(GEOLOCATION)
234 pageClients.geolocationClient = new WebGeolocationClient(this);
236 #if ENABLE(INSPECTOR)
237 pageClients.inspectorClient = new WebInspectorClient(this);
240 m_page = adoptPtr(new Page(pageClients));
242 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
243 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
246 // Qt does not yet call setIsInWindow. Until it does, just leave
247 // this line out so plug-ins and video will work. Eventually all platforms
248 // should call setIsInWindow and this comment and #if should be removed,
249 // leaving behind the setCanStartMedia call.
251 m_page->setCanStartMedia(false);
254 updatePreferences(parameters.store);
256 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
257 m_page->setGroupName(m_pageGroup->identifier());
259 platformInitialize();
261 m_drawingArea = DrawingArea::create(this, parameters);
262 m_drawingArea->setPaintingEnabled(false);
264 m_mainFrame = WebFrame::createMainFrame(this);
266 setUseFixedLayout(parameters.useFixedLayout);
268 setDrawsBackground(parameters.drawsBackground);
269 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
271 setPaginationMode(parameters.paginationMode);
272 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
273 setPageLength(parameters.pageLength);
274 setGapBetweenPages(parameters.gapBetweenPages);
276 setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
278 setActive(parameters.isActive);
279 setFocused(parameters.isFocused);
280 setIsInWindow(parameters.isInWindow);
282 m_userAgent = parameters.userAgent;
284 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
286 if (!parameters.sessionState.isEmpty())
287 restoreSession(parameters.sessionState);
289 m_drawingArea->setPaintingEnabled(true);
291 setMediaVolume(parameters.mediaVolume);
294 webPageCounter.increment();
300 if (m_backForwardList)
301 m_backForwardList->detach();
305 m_sandboxExtensionTracker.invalidate();
308 ASSERT(m_pluginViews.isEmpty());
312 webPageCounter.decrement();
316 void WebPage::dummy(bool&)
320 CoreIPC::Connection* WebPage::connection() const
322 return WebProcess::shared().connection();
325 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
327 m_contextMenuClient.initialize(client);
330 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
332 m_editorClient.initialize(client);
335 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
337 m_formClient.initialize(client);
340 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
342 m_loaderClient.initialize(client);
345 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
347 m_policyClient.initialize(client);
350 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
352 m_resourceLoadClient.initialize(client);
355 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
357 m_uiClient.initialize(client);
360 #if ENABLE(FULLSCREEN_API)
361 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
363 m_fullScreenClient.initialize(client);
367 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, const Plugin::Parameters& parameters)
371 if (!WebProcess::shared().connection()->sendSync(
372 Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()),
373 Messages::WebContext::GetPluginPath::Reply(pluginPath), 0)) {
377 if (pluginPath.isNull()) {
379 if (parameters.mimeType == "application/pdf"
380 || (parameters.mimeType.isEmpty() && parameters.url.path().lower().endsWith(".pdf")))
381 return BuiltInPDFView::create(frame);
388 #if ENABLE(PLUGIN_PROCESS)
389 return PluginProxy::create(pluginPath);
391 NetscapePlugin::setSetExceptionFunction(NPRuntimeObjectMap::setGlobalException);
392 return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
396 EditorState WebPage::editorState() const
398 Frame* frame = m_page->focusController()->focusedOrMainFrame();
402 result.selectionIsNone = frame->selection()->isNone();
403 result.selectionIsRange = frame->selection()->isRange();
404 result.isContentEditable = frame->selection()->isContentEditable();
405 result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
406 result.isInPasswordField = frame->selection()->isInPasswordField();
407 result.hasComposition = frame->editor()->hasComposition();
408 result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
414 Element* selectionRoot = frame->selection()->rootEditableElement();
415 Element* scope = selectionRoot ? selectionRoot : frame->document()->documentElement();
420 if (scope->hasTagName(HTMLNames::inputTag)) {
421 HTMLInputElement* input = static_cast<HTMLInputElement*>(scope);
422 if (input->isTelephoneField())
423 result.inputMethodHints |= Qt::ImhDialableCharactersOnly;
424 else if (input->isNumberField())
425 result.inputMethodHints |= Qt::ImhDigitsOnly;
426 else if (input->isEmailField()) {
427 result.inputMethodHints |= Qt::ImhEmailCharactersOnly;
428 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
429 } else if (input->isURLField()) {
430 result.inputMethodHints |= Qt::ImhUrlCharactersOnly;
431 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
432 } else if (input->isPasswordField()) {
433 // Set ImhHiddenText flag for password fields. The Qt platform
434 // is responsible for determining which widget will receive input
435 // method events for password fields.
436 result.inputMethodHints |= Qt::ImhHiddenText;
437 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
438 result.inputMethodHints |= Qt::ImhNoPredictiveText;
439 result.inputMethodHints |= Qt::ImhSensitiveData;
444 result.editorRect = frame->view()->contentsToWindow(selectionRoot->getRect());
447 if (result.hasComposition && (range = frame->editor()->compositionRange())) {
448 frame->editor()->getCompositionSelection(result.anchorPosition, result.cursorPosition);
450 result.compositionRect = frame->view()->contentsToWindow(range->boundingBox());
453 if (!result.hasComposition && !result.selectionIsNone && (range = frame->selection()->selection().firstRange())) {
454 TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
455 bool baseIsFirst = frame->selection()->selection().isBaseFirst();
457 result.cursorPosition = (baseIsFirst) ? location + length : location;
458 result.anchorPosition = (baseIsFirst) ? location : location + length;
459 result.selectedText = range->text();
463 result.cursorRect = frame->view()->contentsToWindow(frame->editor()->firstRectForRange(range.get()));
465 // FIXME: We should only transfer innerText when it changes and do this on the UI side.
466 if (result.isContentEditable && !result.isInPasswordField) {
467 result.surroundingText = scope->innerText();
468 if (result.hasComposition) {
469 // The anchor is always the left position when they represent a composition.
470 result.surroundingText.remove(result.anchorPosition, result.cursorPosition - result.anchorPosition);
478 String WebPage::renderTreeExternalRepresentation() const
480 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
483 uint64_t WebPage::renderTreeSize() const
488 Frame* mainFrame = m_page->mainFrame();
493 for (Frame* coreFrame = mainFrame; coreFrame; coreFrame = coreFrame->tree()->traverseNext())
494 size += coreFrame->document()->renderArena()->totalRenderArenaSize();
499 void WebPage::setPaintedObjectsCounterThreshold(uint64_t threshold)
503 m_page->setRelevantRepaintedObjectsCounterThreshold(threshold);
506 void WebPage::setTracksRepaints(bool trackRepaints)
508 if (FrameView* view = mainFrameView())
509 view->setTracksRepaints(trackRepaints);
512 bool WebPage::isTrackingRepaints() const
514 if (FrameView* view = mainFrameView())
515 return view->isTrackingRepaints();
520 void WebPage::resetTrackedRepaints()
522 if (FrameView* view = mainFrameView())
523 view->resetTrackedRepaints();
526 PassRefPtr<ImmutableArray> WebPage::trackedRepaintRects()
528 FrameView* view = mainFrameView();
530 return ImmutableArray::create();
532 const Vector<IntRect>& rects = view->trackedRepaintRects();
533 size_t size = rects.size();
535 return ImmutableArray::create();
537 Vector<RefPtr<APIObject> > vector;
538 vector.reserveInitialCapacity(size);
540 for (size_t i = 0; i < size; ++i)
541 vector.uncheckedAppend(WebRect::create(toAPI(rects[i])));
543 return ImmutableArray::adopt(vector);
546 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
548 Frame* frame = m_page->focusController()->focusedOrMainFrame();
551 frame->editor()->command(commandName).execute(argument);
554 bool WebPage::isEditingCommandEnabled(const String& commandName)
556 Frame* frame = m_page->focusController()->focusedOrMainFrame();
560 Editor::Command command = frame->editor()->command(commandName);
561 return command.isSupported() && command.isEnabled();
564 void WebPage::clearMainFrameName()
566 if (Frame* frame = mainFrame())
567 frame->tree()->clearName();
570 #if USE(ACCELERATED_COMPOSITING)
571 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
573 m_drawingArea->setRootCompositingLayer(layer);
576 void WebPage::exitAcceleratedCompositingMode()
578 m_drawingArea->setRootCompositingLayer(0);
582 void WebPage::close()
589 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
590 WebProcess::shared().injectedBundle()->willDestroyPage(this);
592 #if ENABLE(INSPECTOR)
595 #if ENABLE(FULLSCREEN_API)
596 m_fullScreenManager = 0;
599 if (m_activePopupMenu) {
600 m_activePopupMenu->disconnectFromPage();
601 m_activePopupMenu = 0;
604 if (m_activeOpenPanelResultListener) {
605 m_activeOpenPanelResultListener->disconnectFromPage();
606 m_activeOpenPanelResultListener = 0;
609 m_sandboxExtensionTracker.invalidate();
611 m_underlayPage = nullptr;
612 m_printContext = nullptr;
613 m_mainFrame->coreFrame()->loader()->detachFromParent();
615 m_drawingArea = nullptr;
617 bool isRunningModal = m_isRunningModal;
618 m_isRunningModal = false;
620 // The WebPage can be destroyed by this call.
621 WebProcess::shared().removeWebPage(m_pageID);
624 WebProcess::shared().runLoop()->stop();
627 void WebPage::tryClose()
629 SendStopResponsivenessTimer stopper(this);
631 if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
632 send(Messages::WebPageProxy::StopResponsivenessTimer());
636 send(Messages::WebPageProxy::ClosePage(true));
639 void WebPage::sendClose()
641 send(Messages::WebPageProxy::ClosePage(false));
644 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
646 loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
649 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
651 SendStopResponsivenessTimer stopper(this);
653 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
654 m_mainFrame->coreFrame()->loader()->load(request, false);
657 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
659 SendStopResponsivenessTimer stopper(this);
661 ResourceRequest request(baseURL);
662 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
663 m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
666 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
668 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
669 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
670 loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
673 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
675 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
676 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
677 KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
678 loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
681 void WebPage::loadPlainTextString(const String& string)
683 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
684 loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
687 void WebPage::loadWebArchiveData(const CoreIPC::DataReference& webArchiveData)
689 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
690 loadData(sharedBuffer, "application/x-webarchive", "utf-16", blankURL(), KURL());
693 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
695 Frame* frame = m_page->mainFrame();
699 RefPtr<Event> coreEvent;
700 if (event.type() != WebEvent::NoType)
701 coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
703 frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)),
704 false, false, coreEvent.get(), 0, MaybeSendReferrer);
707 void WebPage::stopLoadingFrame(uint64_t frameID)
709 WebFrame* frame = WebProcess::shared().webFrame(frameID);
713 frame->coreFrame()->loader()->stopForUserCancel();
716 void WebPage::stopLoading()
718 SendStopResponsivenessTimer stopper(this);
720 m_mainFrame->coreFrame()->loader()->stopForUserCancel();
723 void WebPage::setDefersLoading(bool defersLoading)
725 m_page->setDefersLoading(defersLoading);
728 void WebPage::reload(bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
730 SendStopResponsivenessTimer stopper(this);
732 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
733 m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
736 void WebPage::goForward(uint64_t backForwardItemID)
738 SendStopResponsivenessTimer stopper(this);
740 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
745 m_page->goToItem(item, FrameLoadTypeForward);
748 void WebPage::goBack(uint64_t backForwardItemID)
750 SendStopResponsivenessTimer stopper(this);
752 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
757 m_page->goToItem(item, FrameLoadTypeBack);
760 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
762 SendStopResponsivenessTimer stopper(this);
764 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
769 m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
772 void WebPage::tryRestoreScrollPosition()
774 m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
777 void WebPage::layoutIfNeeded()
779 if (m_mainFrame->coreFrame()->view())
780 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
782 if (m_underlayPage) {
783 if (FrameView *frameView = m_underlayPage->mainFrameView())
784 frameView->updateLayoutAndStyleIfNeededRecursive();
788 void WebPage::setSize(const WebCore::IntSize& viewSize)
790 FrameView* view = m_page->mainFrame()->view();
792 #if USE(TILED_BACKING_STORE)
793 // If we are resizing to content ignore external attempts.
794 if (view->useFixedLayout())
798 if (m_viewSize == viewSize)
801 view->resize(viewSize);
802 view->setNeedsLayout();
803 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
805 m_viewSize = viewSize;
808 #if USE(TILED_BACKING_STORE)
809 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
811 ASSERT(m_useFixedLayout);
813 Frame* frame = m_page->mainFrame();
815 frame->view()->setFixedVisibleContentRect(rect);
818 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
820 ASSERT(m_useFixedLayout);
821 ASSERT(!targetLayoutSize.isEmpty());
823 FrameView* view = m_page->mainFrame()->view();
825 view->setDelegatesScrolling(true);
826 view->setUseFixedLayout(true);
827 view->setPaintsEntireContents(true);
829 if (view->fixedLayoutSize() == targetLayoutSize)
832 // Always reset even when empty.
833 view->setFixedLayoutSize(targetLayoutSize);
835 // Schedule a layout to use the new target size.
836 if (!view->layoutPending()) {
837 view->setNeedsLayout();
838 view->scheduleRelayout();
842 void WebPage::resizeToContentsIfNeeded()
844 ASSERT(m_useFixedLayout);
846 FrameView* view = m_page->mainFrame()->view();
848 if (!view->useFixedLayout())
851 IntSize contentSize = view->contentsSize();
852 if (contentSize == m_viewSize)
855 m_viewSize = contentSize;
856 view->resize(m_viewSize);
857 view->setNeedsLayout();
860 void WebPage::setViewportSize(const IntSize& size)
862 ASSERT(m_useFixedLayout);
864 if (m_viewportSize == size)
867 m_viewportSize = size;
869 // Recalculate the recommended layout size, when the available size (device pixel) changes.
870 Settings* settings = m_page->settings();
872 int minimumLayoutFallbackWidth = std::max(settings->layoutFallbackWidth(), size.width());
874 IntSize targetLayoutSize = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, settings->deviceWidth(), settings->deviceHeight(), settings->deviceDPI(), size).layoutSize;
875 setResizesToContentsUsingLayoutSize(targetLayoutSize);
880 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
882 Frame* frame = m_page->mainFrame();
884 IntPoint scrollPosition = frame->view()->scrollPosition();
885 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
887 // If the current scroll position in a direction is the max scroll position
888 // we don't want to scroll at all.
889 IntSize newScrollOffset;
890 if (scrollPosition.x() < maximumScrollPosition.x())
891 newScrollOffset.setWidth(scrollOffset.width());
892 if (scrollPosition.y() < maximumScrollPosition.y())
893 newScrollOffset.setHeight(scrollOffset.height());
895 if (newScrollOffset.isZero())
898 frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
901 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
903 GraphicsContextStateSaver stateSaver(graphicsContext);
904 graphicsContext.clip(rect);
906 if (m_underlayPage) {
907 m_underlayPage->drawRect(graphicsContext, rect);
909 graphicsContext.beginTransparencyLayer(1);
910 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
911 graphicsContext.endTransparencyLayer();
915 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
918 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
920 ASSERT(m_pageOverlay);
922 GraphicsContextStateSaver stateSaver(graphicsContext);
923 graphicsContext.clip(rect);
924 m_pageOverlay->drawRect(graphicsContext, rect);
927 double WebPage::textZoomFactor() const
929 Frame* frame = m_mainFrame->coreFrame();
932 return frame->textZoomFactor();
935 void WebPage::setTextZoomFactor(double zoomFactor)
937 Frame* frame = m_mainFrame->coreFrame();
940 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
943 double WebPage::pageZoomFactor() const
945 Frame* frame = m_mainFrame->coreFrame();
948 return frame->pageZoomFactor();
951 void WebPage::setPageZoomFactor(double zoomFactor)
953 Frame* frame = m_mainFrame->coreFrame();
956 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
959 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
961 Frame* frame = m_mainFrame->coreFrame();
964 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
967 void WebPage::windowScreenDidChange(uint64_t displayID)
969 m_page->windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
972 void WebPage::scalePage(double scale, const IntPoint& origin)
974 m_page->setPageScaleFactor(scale, origin);
976 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
979 double WebPage::pageScaleFactor() const
981 return m_page->pageScaleFactor();
984 void WebPage::setDeviceScaleFactor(float scaleFactor)
986 if (scaleFactor == m_page->deviceScaleFactor())
989 m_page->setDeviceScaleFactor(scaleFactor);
991 // Tell all our plug-in views that the device scale factor changed.
993 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
994 (*it)->setDeviceScaleFactor(scaleFactor);
997 if (m_findController.isShowingOverlay()) {
998 // We must have updated layout to get the selection rects right.
1000 m_findController.deviceScaleFactorDidChange();
1004 float WebPage::deviceScaleFactor() const
1006 return m_page->deviceScaleFactor();
1009 void WebPage::setUseFixedLayout(bool fixed)
1011 m_useFixedLayout = fixed;
1013 FrameView* view = mainFrameView();
1017 view->setUseFixedLayout(fixed);
1019 view->setFixedLayoutSize(IntSize());
1022 void WebPage::setFixedLayoutSize(const IntSize& size)
1024 FrameView* view = mainFrameView();
1028 view->setFixedLayoutSize(size);
1029 view->forceLayout();
1032 void WebPage::setPaginationMode(uint32_t mode)
1034 Page::Pagination pagination = m_page->pagination();
1035 pagination.mode = static_cast<Page::Pagination::Mode>(mode);
1036 m_page->setPagination(pagination);
1039 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1041 Page::Pagination pagination = m_page->pagination();
1042 pagination.behavesLikeColumns = behavesLikeColumns;
1043 m_page->setPagination(pagination);
1046 void WebPage::setPageLength(double pageLength)
1048 Page::Pagination pagination = m_page->pagination();
1049 pagination.pageLength = pageLength;
1050 m_page->setPagination(pagination);
1053 void WebPage::setGapBetweenPages(double gap)
1055 Page::Pagination pagination = m_page->pagination();
1056 pagination.gap = gap;
1057 m_page->setPagination(pagination);
1060 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
1062 bool shouldFadeIn = true;
1064 if (m_pageOverlay) {
1065 m_pageOverlay->setPage(0);
1068 // We're installing a page overlay when a page overlay is already active.
1069 // In this case we don't want to fade in the new overlay.
1070 shouldFadeIn = false;
1074 m_pageOverlay = pageOverlay;
1075 m_pageOverlay->setPage(this);
1078 m_pageOverlay->startFadeInAnimation();
1080 m_drawingArea->didInstallPageOverlay();
1082 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
1085 m_pageOverlay->setNeedsDisplay();
1088 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
1090 if (pageOverlay != m_pageOverlay)
1094 m_pageOverlay->startFadeOutAnimation();
1098 m_pageOverlay->setPage(0);
1099 m_pageOverlay = nullptr;
1101 m_drawingArea->didUninstallPageOverlay();
1103 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
1107 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1109 FrameView* frameView = m_mainFrame->coreFrame()->view();
1113 IntSize bitmapSize = rect.size();
1114 float deviceScaleFactor = corePage()->deviceScaleFactor();
1115 bitmapSize.scale(deviceScaleFactor);
1117 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, options);
1118 if (!snapshot->bitmap())
1121 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1122 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1123 graphicsContext->translate(-rect.x(), -rect.y());
1125 frameView->updateLayoutAndStyleIfNeededRecursive();
1127 PaintBehavior oldBehavior = frameView->paintBehavior();
1128 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1129 frameView->paint(graphicsContext.get(), rect);
1130 frameView->setPaintBehavior(oldBehavior);
1132 return snapshot.release();
1135 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1137 FrameView* frameView = m_mainFrame->coreFrame()->view();
1141 float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor();
1142 IntSize size(ceil(rect.width() * combinedScaleFactor), ceil(rect.height() * combinedScaleFactor));
1143 RefPtr<WebImage> snapshot = WebImage::create(size, options);
1144 if (!snapshot->bitmap())
1147 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1148 graphicsContext->applyDeviceScaleFactor(combinedScaleFactor);
1149 graphicsContext->translate(-rect.x(), -rect.y());
1151 frameView->updateLayoutAndStyleIfNeededRecursive();
1153 PaintBehavior oldBehavior = frameView->paintBehavior();
1154 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1155 frameView->paintContents(graphicsContext.get(), rect);
1156 frameView->setPaintBehavior(oldBehavior);
1158 return snapshot.release();
1161 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
1163 return scaledSnapshotInDocumentCoordinates(rect, 1, options);
1166 void WebPage::pageDidScroll()
1168 m_uiClient.pageDidScroll(this);
1170 send(Messages::WebPageProxy::PageDidScroll());
1173 #if USE(TILED_BACKING_STORE)
1174 void WebPage::pageDidRequestScroll(const IntPoint& point)
1176 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1180 WebContextMenu* WebPage::contextMenu()
1183 m_contextMenu = WebContextMenu::create(this);
1184 return m_contextMenu.get();
1189 static const WebEvent* g_currentEvent = 0;
1191 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1192 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1193 // platform events passed to the event handler code.
1194 const WebEvent* WebPage::currentEvent()
1196 return g_currentEvent;
1199 class CurrentEvent {
1201 explicit CurrentEvent(const WebEvent& event)
1202 : m_previousCurrentEvent(g_currentEvent)
1204 g_currentEvent = &event;
1209 g_currentEvent = m_previousCurrentEvent;
1213 const WebEvent* m_previousCurrentEvent;
1216 static bool isContextClick(const PlatformMouseEvent& event)
1218 if (event.button() == WebCore::RightButton)
1222 // FIXME: this really should be about OSX-style UI, not about the Mac port
1223 if (event.button() == WebCore::LeftButton && event.ctrlKey())
1230 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1232 IntPoint point = page->corePage()->mainFrame()->view()->windowToContents(platformMouseEvent.position());
1233 HitTestResult result = page->corePage()->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1235 Frame* frame = page->corePage()->mainFrame();
1236 if (result.innerNonSharedNode())
1237 frame = result.innerNonSharedNode()->document()->frame();
1239 bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1241 page->contextMenu()->show();
1246 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1248 Frame* frame = page->corePage()->mainFrame();
1252 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1254 switch (platformMouseEvent.type()) {
1255 case PlatformEvent::MousePressed: {
1256 if (isContextClick(platformMouseEvent))
1257 page->corePage()->contextMenuController()->clearContextMenu();
1259 bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1260 if (isContextClick(platformMouseEvent))
1261 handled = handleContextMenuEvent(platformMouseEvent, page);
1265 case PlatformEvent::MouseReleased:
1266 return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1267 case PlatformEvent::MouseMoved:
1268 if (onlyUpdateScrollbars)
1269 return frame->eventHandler()->passMouseMovedEventToScrollbars(platformMouseEvent);
1270 return frame->eventHandler()->mouseMoved(platformMouseEvent);
1272 ASSERT_NOT_REACHED();
1277 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1279 // Don't try to handle any pending mouse events if a context menu is showing.
1280 if (m_isShowingContextMenu) {
1281 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1285 bool handled = false;
1287 if (m_pageOverlay) {
1288 // Let the page overlay handle the event.
1289 handled = m_pageOverlay->mouseEvent(mouseEvent);
1293 CurrentEvent currentEvent(mouseEvent);
1295 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1296 // button is currently pressed. It is possible that neither of those things will be true since on
1297 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1298 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1299 // efficient scrollbars-only version of the event.
1300 bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1301 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1304 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1307 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1309 handled = m_pageOverlay && m_pageOverlay->mouseEvent(mouseEvent);
1312 CurrentEvent currentEvent(mouseEvent);
1314 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1315 // button is currently pressed. It is possible that neither of those things will be true since on
1316 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1317 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1318 // efficient scrollbars-only version of the event.
1319 bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1320 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1324 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1326 Frame* frame = page->mainFrame();
1330 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1331 return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1334 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1336 CurrentEvent currentEvent(wheelEvent);
1338 bool handled = handleWheelEvent(wheelEvent, m_page.get());
1339 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1342 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1344 CurrentEvent currentEvent(wheelEvent);
1346 handled = handleWheelEvent(wheelEvent, m_page.get());
1349 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1351 if (!page->mainFrame()->view())
1354 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1355 return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1356 return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1359 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1361 CurrentEvent currentEvent(keyboardEvent);
1363 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1364 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1366 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1368 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1371 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1373 CurrentEvent currentEvent(keyboardEvent);
1375 handled = handleKeyEvent(keyboardEvent, m_page.get());
1377 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1380 #if ENABLE(GESTURE_EVENTS)
1381 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1383 Frame* frame = page->mainFrame();
1387 PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1388 return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1391 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1393 CurrentEvent currentEvent(gestureEvent);
1395 bool handled = handleGestureEvent(gestureEvent, m_page.get());
1396 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1400 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1402 bool isEnabled = false;
1404 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1406 Editor::Command command = frame->editor()->command(commandName);
1407 state = command.state();
1408 isEnabled = command.isSupported() && command.isEnabled();
1411 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1414 void WebPage::executeEditCommand(const String& commandName)
1416 executeEditingCommand(commandName, String());
1419 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1421 const BackForwardListItemVector& list = sessionState.list();
1422 size_t size = list.size();
1423 uint64_t currentItemID = 0;
1424 for (size_t i = 0; i < size; ++i) {
1425 WebBackForwardListItem* webItem = list[i].get();
1426 DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1428 RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1430 LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1434 if (i == sessionState.currentIndex())
1435 currentItemID = webItem->itemID();
1437 WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1439 ASSERT(currentItemID);
1440 return currentItemID;
1443 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1445 if (uint64_t currentItemID = restoreSession(sessionState))
1446 goToBackForwardItem(currentItemID);
1449 #if ENABLE(TOUCH_EVENTS)
1451 void WebPage::highlightPotentialActivation(const IntPoint& point)
1453 Node* activationNode = 0;
1454 Frame* mainframe = m_page->mainFrame();
1456 if (point != IntPoint::zero()) {
1457 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1458 activationNode = result.innerNode();
1460 if (!activationNode->isFocusable())
1461 activationNode = activationNode->enclosingLinkEventParentOrSelf();
1465 tapHighlightController().highlight(activationNode);
1467 tapHighlightController().hideHighlight();
1471 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1473 Frame* frame = page->mainFrame();
1477 return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1480 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1482 CurrentEvent currentEvent(touchEvent);
1484 bool handled = handleTouchEvent(touchEvent, m_page.get());
1486 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1489 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1491 CurrentEvent currentEvent(touchEvent);
1492 handled = handleTouchEvent(touchEvent, m_page.get());
1496 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1498 page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1501 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1503 page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1506 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1508 scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1511 void WebPage::centerSelectionInVisibleArea()
1513 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1517 frame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
1518 m_findController.showFindIndicatorInSelection();
1521 void WebPage::setActive(bool isActive)
1523 m_page->focusController()->setActive(isActive);
1526 // Tell all our plug-in views that the window focus changed.
1527 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1528 (*it)->setWindowIsFocused(isActive);
1532 void WebPage::setDrawsBackground(bool drawsBackground)
1534 if (m_drawsBackground == drawsBackground)
1537 m_drawsBackground = drawsBackground;
1539 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1540 if (FrameView* view = coreFrame->view())
1541 view->setTransparent(!drawsBackground);
1544 m_drawingArea->pageBackgroundTransparencyChanged();
1545 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1548 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1550 if (m_drawsTransparentBackground == drawsTransparentBackground)
1553 m_drawsTransparentBackground = drawsTransparentBackground;
1555 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
1556 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1557 if (FrameView* view = coreFrame->view())
1558 view->setBaseBackgroundColor(backgroundColor);
1561 m_drawingArea->pageBackgroundTransparencyChanged();
1562 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1565 void WebPage::viewWillStartLiveResize()
1570 // FIXME: This should propagate to all ScrollableAreas.
1571 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1572 if (FrameView* view = frame->view())
1573 view->willStartLiveResize();
1577 void WebPage::viewWillEndLiveResize()
1582 // FIXME: This should propagate to all ScrollableAreas.
1583 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
1584 if (FrameView* view = frame->view())
1585 view->willEndLiveResize();
1589 void WebPage::setFocused(bool isFocused)
1591 m_page->focusController()->setFocused(isFocused);
1594 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
1596 if (!m_page || !m_page->focusController())
1599 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1600 frame->document()->setFocusedNode(0);
1602 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
1603 PlatformKeyboardEvent platformEvent(platform(event));
1604 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
1605 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame->document()->defaultView()).get());
1609 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
1612 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
1614 if (m_windowResizerSize == windowResizerSize)
1617 m_windowResizerSize = windowResizerSize;
1619 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1620 FrameView* view = coreFrame->view();
1622 view->windowResizerRectChanged();
1626 void WebPage::setCanStartMediaTimerFired()
1629 m_page->setCanStartMedia(true);
1632 void WebPage::setIsInWindow(bool isInWindow)
1635 m_setCanStartMediaTimer.stop();
1636 m_page->setCanStartMedia(false);
1637 m_page->willMoveOffscreen();
1639 // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
1640 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
1641 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
1642 m_setCanStartMediaTimer.startOneShot(0);
1643 m_page->didMoveOnscreen();
1647 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
1649 WebFrame* frame = WebProcess::shared().webFrame(frameID);
1652 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
1655 void WebPage::show()
1657 send(Messages::WebPageProxy::ShowPage());
1660 void WebPage::setUserAgent(const String& userAgent)
1662 m_userAgent = userAgent;
1665 void WebPage::suspendActiveDOMObjectsAndAnimations()
1667 m_page->suspendActiveDOMObjectsAndAnimations();
1670 void WebPage::resumeActiveDOMObjectsAndAnimations()
1672 m_page->resumeActiveDOMObjectsAndAnimations();
1674 // We need to repaint on resume to kickstart animated painting again.
1675 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1678 IntPoint WebPage::screenToWindow(const IntPoint& point)
1680 IntPoint windowPoint;
1681 sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
1685 IntRect WebPage::windowToScreen(const IntRect& rect)
1688 sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
1692 IntRect WebPage::windowResizerRect() const
1694 if (m_windowResizerSize.isEmpty())
1697 IntSize frameViewSize;
1698 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
1699 if (FrameView* view = coreFrame->view())
1700 frameViewSize = view->size();
1703 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
1704 m_windowResizerSize.width(), m_windowResizerSize.height());
1707 KeyboardUIMode WebPage::keyboardUIMode()
1709 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
1710 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
1713 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
1715 // NOTE: We need to be careful when running scripts that the objects we depend on don't
1716 // disappear during script execution.
1718 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
1719 // long enough for the DataReference to be encoded by the sent message.
1720 RefPtr<SerializedScriptValue> serializedResultValue;
1721 CoreIPC::DataReference dataReference;
1723 JSLock lock(SilenceAssertionsOnly);
1724 if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
1725 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
1726 dataReference = serializedResultValue->data();
1729 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
1732 void WebPage::getContentsAsString(uint64_t callbackID)
1734 String resultString = m_mainFrame->contentsAsString();
1735 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1738 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
1740 String resultString = renderTreeExternalRepresentation();
1741 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1744 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
1746 String resultString = m_mainFrame->selectionAsString();
1747 if (resultString.isEmpty())
1748 resultString = m_mainFrame->contentsAsString();
1749 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1752 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
1754 String resultString;
1755 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
1756 resultString = frame->source();
1758 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
1761 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
1763 CoreIPC::DataReference dataReference;
1765 RefPtr<SharedBuffer> buffer;
1766 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1767 if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
1768 if ((buffer = loader->mainResourceData()))
1769 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1773 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1776 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
1778 DocumentLoader* loader = frame->loader()->documentLoader();
1782 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
1786 return subresource->data();
1789 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
1791 CoreIPC::DataReference dataReference;
1792 KURL resourceURL(KURL(), resourceURLString);
1794 RefPtr<SharedBuffer> buffer;
1795 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1796 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
1798 // Try to get the resource data from the cache.
1799 buffer = cachedResponseDataForURL(resourceURL);
1803 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
1806 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1809 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
1811 CoreIPC::DataReference dataReference;
1813 #if PLATFORM(MAC) || PLATFORM(WIN)
1814 RetainPtr<CFDataRef> data;
1815 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
1816 if ((data = frame->webArchiveData(0, 0)))
1817 dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
1821 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
1824 void WebPage::forceRepaintWithoutCallback()
1826 m_drawingArea->forceRepaint();
1829 void WebPage::forceRepaint(uint64_t callbackID)
1831 if (m_drawingArea->forceRepaintAsync(callbackID))
1834 forceRepaintWithoutCallback();
1835 send(Messages::WebPageProxy::VoidCallback(callbackID));
1838 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
1840 WebPreferencesStore::removeTestRunnerOverrides();
1841 updatePreferences(store);
1844 void WebPage::updatePreferences(const WebPreferencesStore& store)
1846 Settings* settings = m_page->settings();
1848 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
1850 // FIXME: This should be generated from macro expansion for all preferences,
1851 // but we currently don't match the naming of WebCore exactly so we are
1852 // handrolling the boolean and integer preferences until that is fixed.
1854 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
1856 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
1858 #undef INITIALIZE_SETTINGS
1860 settings->setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
1861 settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
1862 settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
1863 settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
1864 settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
1865 settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
1866 settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
1867 settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
1868 settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
1869 settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
1870 settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
1871 settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
1872 settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
1873 settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
1874 settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
1875 settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
1876 #if ENABLE(WEB_ARCHIVE)
1877 settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
1879 settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
1880 settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
1881 settings->setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
1882 settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
1883 settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
1884 settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
1885 settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
1886 settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
1887 settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
1888 settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
1889 settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
1891 settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
1892 settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
1893 settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
1894 settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
1895 settings->setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
1896 settings->setDeviceDPI(store.getUInt32ValueForKey(WebPreferencesKey::deviceDPIKey()));
1897 settings->setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
1898 settings->setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
1899 settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
1900 settings->setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
1902 settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1903 settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1904 settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1905 settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
1906 settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
1907 settings->setCSSCustomFilterEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCustomFilterEnabledKey()));
1908 settings->setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
1909 settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
1910 settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
1911 settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
1912 settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
1913 settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
1914 settings->setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
1916 // <rdar://problem/10697417>: It is necessary to force compositing when accelerate drawing
1917 // is enabled on Mac so that scrollbars are always in their own layers.
1919 if (settings->acceleratedDrawingEnabled())
1920 settings->setForceCompositingMode(LayerTreeHost::supportsAcceleratedCompositing());
1923 settings->setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey()) && LayerTreeHost::supportsAcceleratedCompositing());
1925 #if ENABLE(SQL_DATABASE)
1926 AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
1929 #if ENABLE(FULLSCREEN_API)
1930 settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
1933 settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
1935 #if USE(AVFOUNDATION)
1936 settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
1939 #if ENABLE(WEB_SOCKETS)
1940 settings->setUseHixie76WebSocketProtocol(store.getBoolValueForKey(WebPreferencesKey::hixie76WebSocketProtocolEnabledKey()));
1943 #if ENABLE(WEB_AUDIO)
1944 settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
1947 settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
1948 settings->setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
1949 settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
1950 settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
1952 #if ENABLE(VIDEO_TRACK)
1953 settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
1954 settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
1955 settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
1958 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
1959 settings->setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
1962 platformPreferencesDidChange(store);
1965 #if ENABLE(INSPECTOR)
1966 WebInspector* WebPage::inspector()
1971 m_inspector = WebInspector::create(this);
1972 return m_inspector.get();
1976 #if ENABLE(FULLSCREEN_API)
1977 WebFullScreenManager* WebPage::fullScreenManager()
1979 if (!m_fullScreenManager)
1980 m_fullScreenManager = WebFullScreenManager::create(this);
1981 return m_fullScreenManager.get();
1985 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
1987 if (m_notificationPermissionRequestManager)
1988 return m_notificationPermissionRequestManager.get();
1990 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
1991 return m_notificationPermissionRequestManager.get();
1994 #if !PLATFORM(GTK) && !PLATFORM(MAC)
1995 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
1997 Node* node = evt->target()->toNode();
1999 Frame* frame = node->document()->frame();
2002 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2006 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
2008 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2009 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2010 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2011 // (e.g. Tab that inserts a Tab character, or Enter).
2012 return !command.isTextInsertion() && command.execute(evt);
2015 if (command.execute(evt))
2018 // Don't insert null or control characters as they can result in unexpected behaviour
2019 if (evt->charCode() < ' ')
2022 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
2027 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
2030 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2034 DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2036 case DragControllerActionEntered:
2037 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2040 case DragControllerActionUpdated:
2041 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2044 case DragControllerActionExited:
2045 m_page->dragController()->dragExited(&dragData);
2048 case DragControllerActionPerformDrag:
2049 m_page->dragController()->performDrag(&dragData);
2053 ASSERT_NOT_REACHED();
2057 #elif PLATFORM(QT) || PLATFORM(GTK)
2058 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2061 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2063 QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2065 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2072 case DragControllerActionEntered:
2073 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2076 case DragControllerActionUpdated:
2077 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2080 case DragControllerActionExited:
2081 m_page->dragController()->dragExited(&dragData);
2084 case DragControllerActionPerformDrag: {
2085 m_page->dragController()->performDrag(&dragData);
2090 ASSERT_NOT_REACHED();
2092 // DragData does not delete its platformData so we need to do that here.
2094 QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2096 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2102 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)
2105 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2109 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2111 case DragControllerActionEntered:
2112 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2115 case DragControllerActionUpdated:
2116 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2119 case DragControllerActionExited:
2120 m_page->dragController()->dragExited(&dragData);
2123 case DragControllerActionPerformDrag: {
2124 ASSERT(!m_pendingDropSandboxExtension);
2126 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2128 m_page->dragController()->performDrag(&dragData);
2130 // If we started loading a local file, the sandbox extension tracker would have adopted this
2131 // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2132 if (m_pendingDropSandboxExtension) {
2133 m_pendingDropSandboxExtension->invalidate();
2134 m_pendingDropSandboxExtension = nullptr;
2141 ASSERT_NOT_REACHED();
2146 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2148 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2149 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2151 m_page->dragController()->dragEnded();
2152 FrameView* view = m_page->mainFrame()->view();
2155 // FIXME: These are fake modifier keys here, but they should be real ones instead.
2156 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2157 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2160 void WebPage::willPerformLoadDragDestinationAction()
2162 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2165 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2167 return m_undoStepMap.get(stepID).get();
2170 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2172 m_undoStepMap.set(stepID, entry);
2175 void WebPage::removeWebEditCommand(uint64_t stepID)
2177 m_undoStepMap.remove(stepID);
2180 void WebPage::unapplyEditCommand(uint64_t stepID)
2182 WebUndoStep* step = webUndoStep(stepID);
2186 step->step()->unapply();
2189 void WebPage::reapplyEditCommand(uint64_t stepID)
2191 WebUndoStep* step = webUndoStep(stepID);
2196 step->step()->reapply();
2200 void WebPage::didRemoveEditCommand(uint64_t commandID)
2202 removeWebEditCommand(commandID);
2205 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2207 m_activePopupMenu = menu;
2210 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2212 m_activeOpenPanelResultListener = openPanelResultListener;
2215 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2217 return m_page->findString(target, options);
2220 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2222 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2225 void WebPage::hideFindUI()
2227 m_findController.hideFindUI();
2230 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2232 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2235 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2237 if (!m_activePopupMenu)
2240 m_activePopupMenu->didChangeSelectedIndex(newIndex);
2241 m_activePopupMenu = 0;
2244 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2246 if (!m_activeOpenPanelResultListener)
2249 m_activeOpenPanelResultListener->didChooseFiles(files);
2250 m_activeOpenPanelResultListener = 0;
2253 void WebPage::didCancelForOpenPanel()
2255 m_activeOpenPanelResultListener = 0;
2258 #if ENABLE(WEB_PROCESS_SANDBOX)
2259 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2261 SandboxExtension::create(handle)->consumePermanently();
2265 #if ENABLE(GEOLOCATION)
2266 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2268 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2272 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2274 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2277 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2279 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2280 frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2283 void WebPage::changeSpellingToWord(const String& word)
2285 replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2288 void WebPage::unmarkAllMisspellings()
2290 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2291 if (Document* document = frame->document())
2292 document->markers()->removeMarkers(DocumentMarker::Spelling);
2296 void WebPage::unmarkAllBadGrammar()
2298 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2299 if (Document* document = frame->document())
2300 document->markers()->removeMarkers(DocumentMarker::Grammar);
2305 void WebPage::uppercaseWord()
2307 m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2310 void WebPage::lowercaseWord()
2312 m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2315 void WebPage::capitalizeWord()
2317 m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2321 void WebPage::setTextForActivePopupMenu(int32_t index)
2323 if (!m_activePopupMenu)
2326 m_activePopupMenu->setTextForIndex(index);
2330 void WebPage::failedToShowPopupMenu()
2332 if (!m_activePopupMenu)
2335 m_activePopupMenu->client()->popupDidHide();
2339 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2344 m_contextMenu->itemSelected(item);
2348 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
2350 bool selectReplacement = true;
2351 bool smartReplace = false;
2352 return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
2355 void WebPage::clearSelection()
2357 m_page->focusController()->focusedOrMainFrame()->selection()->clear();
2360 bool WebPage::mainFrameHasCustomRepresentation() const
2362 if (Frame* frame = mainFrame())
2363 return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
2368 void WebPage::didChangeScrollOffsetForMainFrame()
2370 Frame* frame = m_page->mainFrame();
2371 IntPoint scrollPosition = frame->view()->scrollPosition();
2372 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
2373 IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
2375 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
2376 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
2378 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
2379 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
2381 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
2382 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
2386 void WebPage::mainFrameDidLayout()
2388 unsigned pageCount = m_page->pageCount();
2389 if (pageCount != m_cachedPageCount) {
2390 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
2391 m_cachedPageCount = pageCount;
2397 void WebPage::addPluginView(PluginView* pluginView)
2399 ASSERT(!m_pluginViews.contains(pluginView));
2401 m_pluginViews.add(pluginView);
2404 void WebPage::removePluginView(PluginView* pluginView)
2406 ASSERT(m_pluginViews.contains(pluginView));
2408 m_pluginViews.remove(pluginView);
2411 void WebPage::setWindowIsVisible(bool windowIsVisible)
2413 m_windowIsVisible = windowIsVisible;
2415 corePage()->focusController()->setContainingWindowIsVisible(windowIsVisible);
2417 // Tell all our plug-in views that the window visibility changed.
2418 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2419 (*it)->setWindowIsVisible(windowIsVisible);
2422 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
2424 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
2425 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
2426 m_accessibilityPosition = accessibilityViewCoordinates;
2428 // Tell all our plug-in views that the window and view frames have changed.
2429 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2430 (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
2435 bool WebPage::windowIsFocused() const
2438 if (!m_windowIsVisible)
2441 return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
2444 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
2446 if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
2448 m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
2452 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
2453 if (messageID.is<CoreIPC::MessageClassLayerTreeHost>()) {
2455 m_drawingArea->didReceiveLayerTreeHostMessage(connection, messageID, arguments);
2460 #if ENABLE(INSPECTOR)
2461 if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
2462 if (WebInspector* inspector = this->inspector())
2463 inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
2468 #if ENABLE(FULLSCREEN_API)
2469 if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
2470 fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
2475 didReceiveWebPageMessage(connection, messageID, arguments);
2478 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
2480 didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
2483 InjectedBundleBackForwardList* WebPage::backForwardList()
2485 if (!m_backForwardList)
2486 m_backForwardList = InjectedBundleBackForwardList::create(this);
2487 return m_backForwardList.get();
2491 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point)
2493 Frame* mainframe = m_mainFrame->coreFrame();
2494 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
2496 Node* node = result.innerNode();
2501 IntRect zoomableArea = node->getRect();
2504 bool found = !node->isTextNode() && !node->isShadowRoot();
2506 // No candidate found, bail out.
2507 if (!found && !node->parentNode())
2510 // Candidate found, and it is a better candidate than its parent.
2511 // NB: A parent is considered a better candidate iff the node is
2512 // contained by it and it is the only child.
2513 if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
2516 node = node->parentNode();
2517 zoomableArea.unite(node->getRect());
2520 if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
2521 const ScrollView* view = node->document()->frame()->view();
2522 zoomableArea = view->contentsToWindow(zoomableArea);
2525 send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
2529 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
2534 void WebPage::SandboxExtensionTracker::invalidate()
2536 if (m_pendingProvisionalSandboxExtension) {
2537 m_pendingProvisionalSandboxExtension->invalidate();
2538 m_pendingProvisionalSandboxExtension = 0;
2541 if (m_provisionalSandboxExtension) {
2542 m_provisionalSandboxExtension->invalidate();
2543 m_provisionalSandboxExtension = 0;
2546 if (m_committedSandboxExtension) {
2547 m_committedSandboxExtension->invalidate();
2548 m_committedSandboxExtension = 0;
2552 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
2554 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
2557 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
2559 ASSERT(frame->isMainFrame());
2561 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
2564 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
2566 // If we get two beginLoad calls in succession, without a provisional load starting, then
2567 // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
2568 if (m_pendingProvisionalSandboxExtension) {
2569 m_pendingProvisionalSandboxExtension->invalidate();
2570 m_pendingProvisionalSandboxExtension = nullptr;
2573 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
2576 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
2578 ASSERT(frame->isMainFrame());
2580 FrameLoader* frameLoader = frame->coreFrame()->loader();
2581 FrameLoadType frameLoadType = frameLoader->loadType();
2583 // If the page is being reloaded, it should reuse whatever extension is committed.
2584 if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
2587 DocumentLoader* documentLoader = frameLoader->documentLoader();
2588 DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
2589 if (!documentLoader || !provisionalDocumentLoader)
2592 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
2598 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
2600 if (!frame->isMainFrame())
2603 // We should only reuse the commited sandbox extension if it is not null. It can be
2604 // null if the last load was for an error page.
2605 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
2606 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
2607 ASSERT(!m_committedSandboxExtension);
2610 ASSERT(!m_provisionalSandboxExtension);
2612 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
2613 if (!m_provisionalSandboxExtension)
2616 m_provisionalSandboxExtension->consume();
2619 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
2621 if (!frame->isMainFrame())
2624 // Generally, there should be no pending extension at this stage, but we can have one if UI process
2625 // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
2626 if (m_pendingProvisionalSandboxExtension) {
2627 m_pendingProvisionalSandboxExtension->invalidate();
2628 m_pendingProvisionalSandboxExtension = nullptr;
2631 // The provisional load has been committed. Invalidate the currently committed sandbox
2632 // extension and make the provisional sandbox extension the committed sandbox extension.
2633 if (m_committedSandboxExtension)
2634 m_committedSandboxExtension->invalidate();
2636 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
2639 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
2641 if (!frame->isMainFrame())
2644 // Generally, there should be no pending extension at this stage, but we can have one if UI process
2645 // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
2646 if (m_pendingProvisionalSandboxExtension) {
2647 m_pendingProvisionalSandboxExtension->invalidate();
2648 m_pendingProvisionalSandboxExtension = nullptr;
2651 if (!m_provisionalSandboxExtension)
2654 m_provisionalSandboxExtension->invalidate();
2655 m_provisionalSandboxExtension = nullptr;
2658 bool WebPage::hasLocalDataForURL(const KURL& url)
2660 if (url.isLocalFile())
2663 FrameLoader* frameLoader = m_page->mainFrame()->loader();
2664 DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
2665 if (documentLoader && documentLoader->subresource(url))
2668 return platformHasLocalDataForURL(url);
2671 void WebPage::setCustomTextEncodingName(const String& encoding)
2673 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
2676 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
2678 WebBackForwardListProxy::removeItem(itemID);
2683 bool WebPage::isSpeaking()
2686 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
2689 void WebPage::speak(const String& string)
2691 send(Messages::WebPageProxy::Speak(string));
2694 void WebPage::stopSpeaking()
2696 send(Messages::WebPageProxy::StopSpeaking());
2702 static RetainPtr<CGPDFDocumentRef> pdfDocumentForPrintingFrame(Frame* coreFrame)
2704 Document* document = coreFrame->document();
2708 if (!document->isPluginDocument())
2711 PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
2715 return pluginView->pdfDocumentForPrinting();
2719 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
2721 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2725 Frame* coreFrame = frame->coreFrame();
2730 if (pdfDocumentForPrintingFrame(coreFrame))
2734 if (!m_printContext)
2735 m_printContext = adoptPtr(new PrintContext(coreFrame));
2737 drawingArea()->setLayerTreeStateIsFrozen(true);
2738 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2740 float fullPageHeight;
2741 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
2744 if (!m_printOperation)
2745 m_printOperation = WebPrintOperationGtk::create(this, printInfo);
2749 void WebPage::endPrinting()
2751 drawingArea()->setLayerTreeStateIsFrozen(false);
2753 m_printOperation = 0;
2755 m_printContext = nullptr;
2758 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
2760 Vector<IntRect> resultPageRects;
2761 double resultTotalScaleFactorForPrinting = 1;
2763 beginPrinting(frameID, printInfo);
2765 if (m_printContext) {
2766 resultPageRects = m_printContext->pageRects();
2767 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
2771 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2772 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2773 RetainPtr<CGPDFDocumentRef> pdfDocument = coreFrame ? pdfDocumentForPrintingFrame(coreFrame) : 0;
2774 if (pdfDocument && CGPDFDocumentAllowsPrinting(pdfDocument.get())) {
2775 CFIndex pageCount = CGPDFDocumentGetNumberOfPages(pdfDocument.get());
2776 IntRect pageRect(0, 0, ceilf(printInfo.availablePaperWidth), ceilf(printInfo.availablePaperHeight));
2777 for (CFIndex i = 1; i <= pageCount; ++i) {
2778 resultPageRects.append(pageRect);
2779 pageRect.move(0, pageRect.height());
2785 // If we're asked to print, we should actually print at least a blank page.
2786 if (resultPageRects.isEmpty())
2787 resultPageRects.append(IntRect(0, 0, 1, 1));
2789 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
2793 static inline CGFloat roundCGFloat(CGFloat f)
2795 if (sizeof(CGFloat) == sizeof(float))
2796 return roundf(static_cast<float>(f));
2797 return static_cast<CGFloat>(round(f));
2800 static void drawPDFPage(CGPDFDocumentRef pdfDocument, CFIndex pageIndex, CGContextRef context, CGFloat pageSetupScaleFactor, CGSize paperSize)
2802 CGContextSaveGState(context);
2804 CGContextScaleCTM(context, pageSetupScaleFactor, pageSetupScaleFactor);
2806 CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, pageIndex + 1);
2807 CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
2808 if (CGRectIsEmpty(cropBox))
2809 cropBox = CGRectIntersection(cropBox, CGPDFPageGetBoxRect(page, kCGPDFMediaBox));
2811 cropBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
2813 bool shouldRotate = (paperSize.width < paperSize.height) != (cropBox.size.width < cropBox.size.height);
2815 swap(cropBox.size.width, cropBox.size.height);
2818 CGFloat widthDifference = paperSize.width / pageSetupScaleFactor - cropBox.size.width;
2819 CGFloat heightDifference = paperSize.height / pageSetupScaleFactor - cropBox.size.height;
2820 if (widthDifference || heightDifference)
2821 CGContextTranslateCTM(context, roundCGFloat(widthDifference / 2), roundCGFloat(heightDifference / 2));
2824 CGContextRotateCTM(context, static_cast<CGFloat>(piOverTwoDouble));
2825 CGContextTranslateCTM(context, 0, -cropBox.size.width);
2828 CGContextDrawPDFPage(context, page);
2830 CGContextRestoreGState(context);
2834 #if PLATFORM(MAC) || PLATFORM(WIN)
2835 void WebPage::drawRectToPDF(uint64_t frameID, const PrintInfo& printInfo, const WebCore::IntRect& rect, uint64_t callbackID)
2837 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2838 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2840 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2844 UNUSED_PARAM(printInfo);
2846 ASSERT(coreFrame->document()->printing());
2848 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
2850 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2851 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2853 CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
2854 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2855 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2856 CGPDFContextBeginPage(context.get(), pageInfo.get());
2858 if (RetainPtr<CGPDFDocumentRef> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
2859 CFIndex pageCount = CGPDFDocumentGetNumberOfPages(pdfDocument.get());
2860 IntSize paperSize(ceilf(printInfo.availablePaperWidth), ceilf(printInfo.availablePaperHeight));
2861 IntRect pageRect(IntPoint(), paperSize);
2862 for (CFIndex i = 0; i < pageCount; ++i) {
2863 if (pageRect.intersects(rect)) {
2864 CGContextSaveGState(context.get());
2866 CGContextTranslateCTM(context.get(), pageRect.x() - rect.x(), pageRect.y() - rect.y());
2867 drawPDFPage(pdfDocument.get(), i, context.get(), printInfo.pageSetupScaleFactor, paperSize);
2869 CGContextRestoreGState(context.get());
2871 pageRect.move(0, pageRect.height());
2874 GraphicsContext ctx(context.get());
2875 ctx.scale(FloatSize(1, -1));
2876 ctx.translate(0, -rect.height());
2877 m_printContext->spoolRect(ctx, rect);
2880 CGPDFContextEndPage(context.get());
2881 CGPDFContextClose(context.get());
2885 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2888 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
2890 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2891 Frame* coreFrame = frame ? frame->coreFrame() : 0;
2893 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
2898 ASSERT(coreFrame->document()->printing());
2900 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
2902 RetainPtr<CGPDFDocumentRef> pdfDocument = pdfDocumentForPrintingFrame(coreFrame);
2904 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
2905 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
2907 CGRect mediaBox = m_printContext && m_printContext->pageCount() ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
2908 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
2909 size_t pageCount = m_printContext ? m_printContext->pageCount() : CGPDFDocumentGetNumberOfPages(pdfDocument.get());
2910 for (uint32_t page = first; page < first + count; ++page) {
2911 if (page >= pageCount)
2914 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2915 CGPDFContextBeginPage(context.get(), pageInfo.get());
2918 drawPDFPage(pdfDocument.get(), page, context.get(), printInfo.pageSetupScaleFactor, CGSizeMake(printInfo.availablePaperWidth, printInfo.availablePaperHeight));
2920 GraphicsContext ctx(context.get());
2921 ctx.scale(FloatSize(1, -1));
2922 ctx.translate(0, -m_printContext->pageRect(page).height());
2923 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
2926 CGPDFContextEndPage(context.get());
2928 CGPDFContextClose(context.get());
2932 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
2935 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
2937 beginPrinting(frameID, printInfo);
2938 if (m_printContext && m_printOperation) {
2939 m_printOperation->startPrint(m_printContext.get(), callbackID);
2943 send(Messages::WebPageProxy::VoidCallback(callbackID));
2947 void WebPage::setMediaVolume(float volume)
2949 m_page->setMediaVolume(volume);
2952 void WebPage::runModal()
2956 if (m_isRunningModal)
2959 m_isRunningModal = true;
2960 send(Messages::WebPageProxy::RunModal());
2962 ASSERT(!m_isRunningModal);
2965 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
2967 m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
2970 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
2972 if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
2974 return platformCanHandleRequest(request);
2977 #if PLATFORM(MAC) && !defined(BUILDING_ON_SNOW_LEOPARD)
2978 void WebPage::handleCorrectionPanelResult(const String& result)
2980 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2983 frame->editor()->handleCorrectionPanelResult(result);
2987 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
2989 mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
2992 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
2994 mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
2997 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
2999 mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3002 String WebPage::viewportConfigurationAsText(int deviceDPI, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
3004 ViewportArguments arguments = mainFrame()->document()->viewportArguments();
3005 ViewportAttributes attrs = WebCore::computeViewportAttributes(arguments, /* default layout width for non-mobile pages */ 980, deviceWidth, deviceHeight, deviceDPI, IntSize(availableWidth, availableHeight));
3006 WebCore::restrictMinimumScaleFactorToViewportSize(attrs, IntSize(availableWidth, availableHeight));
3007 WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(attrs);
3008 return String::format("viewport size %dx%d scale %f with limits [%f, %f] and userScalable %f\n", attrs.layoutSize.width(), attrs.layoutSize.height(), attrs.initialScale, attrs.minimumScale, attrs.maximumScale, attrs.userScalable);
3011 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3013 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3014 if (!frame || !frame->editor()->canEdit())
3017 Vector<CompositionUnderline> underlines;
3018 underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3019 frame->editor()->setComposition(compositionString, underlines, from, from + length);
3022 bool WebPage::hasCompositionForTesting()
3024 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3025 return frame && frame->editor()->hasComposition();
3028 void WebPage::confirmCompositionForTesting(const String& compositionString)
3030 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3031 if (!frame || !frame->editor()->canEdit())
3034 if (compositionString.isNull())
3035 frame->editor()->confirmComposition();
3036 frame->editor()->confirmComposition(compositionString);
3039 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3041 if (m_numWheelEventHandlers == numWheelEventHandlers)
3044 m_numWheelEventHandlers = numWheelEventHandlers;
3045 recomputeShortCircuitHorizontalWheelEventsState();
3048 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3050 if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3051 return scrollbar->enabled();
3056 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3058 if (FrameView* frameView = mainFrame->view()) {
3059 if (hasEnabledHorizontalScrollbar(frameView))
3063 for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext()) {
3064 FrameView* frameView = frame->view();
3068 const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3069 if (!scrollableAreas)
3072 for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3073 ScrollableArea* scrollableArea = *it;
3074 if (!scrollableArea->isOnActivePage())
3077 if (hasEnabledHorizontalScrollbar(scrollableArea))
3085 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3087 bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3089 if (canShortCircuitHorizontalWheelEvents) {
3090 // Check if we have any horizontal scroll bars on the page.
3091 if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3092 canShortCircuitHorizontalWheelEvents = false;
3095 if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3098 m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3099 send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3102 Frame* WebPage::mainFrame() const
3104 return m_page ? m_page->mainFrame() : 0;
3107 FrameView* WebPage::mainFrameView() const
3109 if (Frame* frame = mainFrame())
3110 return frame->view();
3115 } // namespace WebKit