2 * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2012 Intel Corporation. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24 * THE POSSIBILITY OF SUCH DAMAGE.
30 #include "Arguments.h"
31 #include "DataReference.h"
32 #include "DecoderAdapter.h"
33 #include "DrawingArea.h"
34 #include "InjectedBundle.h"
35 #include "InjectedBundleBackForwardList.h"
36 #include "LayerTreeHost.h"
37 #include "MessageID.h"
38 #include "NetscapePlugin.h"
39 #include "NotificationPermissionRequestManager.h"
40 #include "PageOverlay.h"
41 #include "PluginProxy.h"
42 #include "PluginView.h"
43 #include "PrintInfo.h"
44 #include "SessionState.h"
45 #include "ShareableBitmap.h"
46 #include "WebAlternativeTextClient.h"
47 #include "WebBackForwardList.h"
48 #include "WebBackForwardListItem.h"
49 #include "WebBackForwardListProxy.h"
50 #include "WebChromeClient.h"
51 #include "WebColorChooser.h"
52 #include "WebContextMenu.h"
53 #include "WebContextMenuClient.h"
54 #include "WebContextMessages.h"
55 #include "WebCoreArgumentCoders.h"
56 #include "WebDragClient.h"
57 #include "WebEditorClient.h"
59 #include "WebEventConversion.h"
61 #include "WebFullScreenManager.h"
62 #include "WebGeolocationClient.h"
63 #include "WebGeometry.h"
65 #include "WebInspector.h"
66 #include "WebInspectorClient.h"
67 #include "WebNotificationClient.h"
68 #include "WebOpenPanelResultListener.h"
69 #include "WebPageCreationParameters.h"
70 #include "WebPageGroupProxy.h"
71 #include "WebPageProxyMessages.h"
72 #include "WebPopupMenu.h"
73 #include "WebPreferencesStore.h"
74 #include "WebProcess.h"
75 #include "WebProcessProxyMessages.h"
76 #include <JavaScriptCore/APICast.h>
77 #include <WebCore/AbstractDatabase.h>
78 #include <WebCore/ArchiveResource.h>
79 #include <WebCore/Chrome.h>
80 #include <WebCore/ContextMenuController.h>
81 #include <WebCore/DocumentFragment.h>
82 #include <WebCore/DocumentLoader.h>
83 #include <WebCore/DocumentMarkerController.h>
84 #include <WebCore/DragController.h>
85 #include <WebCore/DragData.h>
86 #include <WebCore/DragSession.h>
87 #include <WebCore/EventHandler.h>
88 #include <WebCore/FocusController.h>
89 #include <WebCore/FormState.h>
90 #include <WebCore/Frame.h>
91 #include <WebCore/FrameLoadRequest.h>
92 #include <WebCore/FrameLoaderTypes.h>
93 #include <WebCore/FrameView.h>
94 #include <WebCore/HTMLFormElement.h>
95 #include <WebCore/HTMLInputElement.h>
96 #include <WebCore/HTMLPlugInElement.h>
97 #include <WebCore/HistoryItem.h>
98 #include <WebCore/KeyboardEvent.h>
99 #include <WebCore/MouseEvent.h>
100 #include <WebCore/Page.h>
101 #include <WebCore/PlatformKeyboardEvent.h>
102 #include <WebCore/PluginDocument.h>
103 #include <WebCore/PrintContext.h>
104 #include <WebCore/RenderLayer.h>
105 #include <WebCore/RenderTreeAsText.h>
106 #include <WebCore/RenderView.h>
107 #include <WebCore/ResourceRequest.h>
108 #include <WebCore/RunLoop.h>
109 #include <WebCore/SchemeRegistry.h>
110 #include <WebCore/ScriptValue.h>
111 #include <WebCore/SerializedScriptValue.h>
112 #include <WebCore/Settings.h>
113 #include <WebCore/SharedBuffer.h>
114 #include <WebCore/SubstituteData.h>
115 #include <WebCore/TextIterator.h>
116 #include <WebCore/markup.h>
117 #include <runtime/JSLock.h>
118 #include <runtime/JSValue.h>
120 #include <WebCore/Range.h>
121 #include <WebCore/VisiblePosition.h>
124 #include <WebCore/MHTMLArchive.h>
127 #if ENABLE(PLUGIN_PROCESS)
129 #include "MachPort.h"
133 #if ENABLE(BATTERY_STATUS)
134 #include "WebBatteryClient.h"
137 #if ENABLE(NETWORK_INFO)
138 #include "WebNetworkInfoClient.h"
141 #if ENABLE(WEB_INTENTS)
142 #include "IntentData.h"
145 #if ENABLE(VIBRATION)
146 #include "WebVibrationClient.h"
149 #if ENABLE(TIZEN_REGISTER_PROTOCOL_HANDLER) || ENABLE(TIZEN_CUSTOM_SCHEME_HANDLER)
150 #include "WebRegisterProtocolHandlerClient.h"
153 #if ENABLE(TIZEN_REGISTER_CONTENT_HANDLER)
154 #include "WebRegisterContentHandlerClient.h"
158 #include "BuiltInPDFView.h"
162 #if ENABLE(DEVICE_ORIENTATION)
163 #include "DeviceMotionClientQt.h"
164 #include "DeviceOrientationClientQt.h"
166 #include "HitTestResult.h"
172 #include "DataObjectGtk.h"
173 #include "WebPrintOperationGtk.h"
176 #if ENABLE(TIZEN_MEDIA_STREAM)
177 #include "WebUserMediaClient.h"
178 #include "UserMediaPermissionRequestManager.h"
181 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
182 #include <WebCore/NodeList.h>
183 #include "HTMLLinkElement.h"
184 #include "HTMLMetaElement.h"
187 #if ENABLE(TIZEN_GEOLOCATION)
188 #include <WebCore/GeolocationClientMock.h>
189 #include <WebCore/GeolocationController.h>
193 #include <wtf/RefCountedLeakCounter.h>
196 #if ENABLE(TIZEN_INDEXED_DATABASE)
197 #include <WebCore/PageGroup.h>
198 #include <WebCore/GroupSettings.h>
201 #if ENABLE(TIZEN_ISF_PORT)
202 #include "NativeWebKeyboardEvent.h"
205 #if ENABLE(TIZEN_NATIVE_MEMORY_SNAPSHOT)
206 #include "AboutDataTizen.h"
209 #if ENABLE(TIZEN_DRAG_SUPPORT)
210 #include "DataObjectTizen.h"
213 #if ENABLE(TIZEN_WEBKIT2_CONTEXT_MENU_TEXT_SELECTION_MODE)
214 #include "HTMLImageElement.h"
218 using namespace WebCore;
223 class SendStopResponsivenessTimer {
225 SendStopResponsivenessTimer(WebPage* page)
230 ~SendStopResponsivenessTimer()
232 m_page->send(Messages::WebPageProxy::StopResponsivenessTimer());
239 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageCounter, ("WebPage"));
241 PassRefPtr<WebPage> WebPage::create(uint64_t pageID, const WebPageCreationParameters& parameters)
243 RefPtr<WebPage> page = adoptRef(new WebPage(pageID, parameters));
245 if (page->pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
246 WebProcess::shared().injectedBundle()->didCreatePage(page.get());
248 return page.release();
251 WebPage::WebPage(uint64_t pageID, const WebPageCreationParameters& parameters)
252 : m_viewSize(parameters.viewSize)
253 , m_useFixedLayout(false)
254 , m_drawsBackground(true)
255 , m_drawsTransparentBackground(false)
258 , m_tabToLinks(false)
260 , m_windowIsVisible(false)
261 , m_isSmartInsertDeleteEnabled(parameters.isSmartInsertDeleteEnabled)
262 , m_layerHostingMode(parameters.layerHostingMode)
263 , m_keyboardEventBeingInterpreted(0)
265 , m_nativeWindow(parameters.nativeWindow)
267 , m_accessibilityObject(0)
269 , m_setCanStartMediaTimer(WebProcess::shared().runLoop(), this, &WebPage::setCanStartMediaTimerFired)
270 , m_findController(this)
271 #if ENABLE(TOUCH_EVENTS)
273 , m_tapHighlightController(this)
276 #if ENABLE(INPUT_TYPE_COLOR)
277 , m_activeColorChooser(0)
279 #if ENABLE(GEOLOCATION)
280 , m_geolocationPermissionRequestManager(this)
283 , m_canRunBeforeUnloadConfirmPanel(parameters.canRunBeforeUnloadConfirmPanel)
284 , m_canRunModal(parameters.canRunModal)
285 , m_isRunningModal(false)
286 , m_cachedMainFrameIsPinnedToLeftSide(false)
287 , m_cachedMainFrameIsPinnedToRightSide(false)
288 , m_canShortCircuitHorizontalWheelEvents(false)
289 , m_numWheelEventHandlers(0)
290 , m_cachedPageCount(0)
291 #if ENABLE(CONTEXT_MENUS)
292 , m_isShowingContextMenu(false)
294 , m_willGoToBackForwardItemCallbackEnabled(true)
296 , m_gestureReachedScrollingLimit(false)
298 #if ENABLE(PAGE_VISIBILITY_API)
299 , m_visibilityState(WebCore::PageVisibilityStateVisible)
301 #if ENABLE(TIZEN_RECORDING_SURFACE_SET)
302 , m_recordingSurfaceSetEnable(false)
303 , m_recordingSurfaceSetLoadStart(false)
304 , m_recordingSurfaceSetLoadFinished(false)
305 , m_recordingSurfaceSetSettings(false)
307 #if ENABLE(TIZEN_SYNC_REQUEST_ANIMATION_FRAME)
308 , m_suspendedAnimationController(false)
310 , m_inspectorClient(0)
313 // FIXME: This is a non-ideal location for this Setting and
314 // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
315 #if ENABLE(TIZEN_DOM_TIMER_MIN_INTERVAL_SET)
316 Settings::setDefaultMinDOMTimerInterval(0.001);
318 Settings::setDefaultMinDOMTimerInterval(0.004);
321 Page::PageClients pageClients;
322 pageClients.chromeClient = new WebChromeClient(this);
323 #if ENABLE(CONTEXT_MENUS)
324 pageClients.contextMenuClient = new WebContextMenuClient(this);
326 pageClients.editorClient = new WebEditorClient(this);
327 #if ENABLE(DRAG_SUPPORT)
328 pageClients.dragClient = new WebDragClient(this);
330 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
331 #if ENABLE(INSPECTOR)
332 m_inspectorClient = new WebInspectorClient(this);
333 pageClients.inspectorClient = m_inspectorClient;
335 #if USE(AUTOCORRECTION_PANEL)
336 pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
339 m_page = adoptPtr(new Page(pageClients));
341 #if ENABLE(BATTERY_STATUS)
342 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
344 #if ENABLE(GEOLOCATION)
345 #if ENABLE(TIZEN_GEOLOCATION) && ENABLE(TIZEN_WEBKIT2_EFL_WTR)
346 if (WebProcess::shared().injectedBundle() && WebProcess::shared().injectedBundle()->testRunnerModeEnabled()) {
347 GeolocationClientMock* mock = new GeolocationClientMock();
348 WebCore::provideGeolocationTo(m_page.get(), mock);
349 mock->setController(WebCore::GeolocationController::from(m_page.get()));
351 #endif // ENABLE(TIZEN_GEOLOCATION) && ENABLE(TIZEN_WEBKIT2_EFL_WTR)
352 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
354 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(QT)
355 WebCore::provideDeviceMotionTo(m_page.get(), new DeviceMotionClientQt);
356 WebCore::provideDeviceOrientationTo(m_page.get(), new DeviceOrientationClientQt);
358 #if ENABLE(NETWORK_INFO)
359 WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this));
361 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
362 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
364 #if ENABLE(VIBRATION)
365 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
368 #if ENABLE(VIBRATION)
369 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
372 #if ENABLE(TIZEN_MEDIA_STREAM)
373 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(this));
376 #if ENABLE(TIZEN_REGISTER_PROTOCOL_HANDLER) || ENABLE(TIZEN_CUSTOM_SCHEME_HANDLER)
377 WebCore::provideRegisterProtocolHandlerTo(m_page.get(), new WebRegisterProtocolHandlerClient(this));
380 #if ENABLE(TIZEN_REGISTER_CONTENT_HANDLER)
381 WebCore::provideRegisterContentHandlerTo(m_page.get(), new WebRegisterContentHandlerClient(this));
384 // Qt does not yet call setIsInWindow. Until it does, just leave
385 // this line out so plug-ins and video will work. Eventually all platforms
386 // should call setIsInWindow and this comment and #if should be removed,
387 // leaving behind the setCanStartMedia call.
389 m_page->setCanStartMedia(false);
392 updatePreferences(parameters.store);
394 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
395 m_page->setGroupName(m_pageGroup->identifier());
396 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
398 platformInitialize();
400 m_drawingArea = DrawingArea::create(this, parameters);
401 m_drawingArea->setPaintingEnabled(false);
403 m_mainFrame = WebFrame::createMainFrame(this);
405 setUseFixedLayout(parameters.useFixedLayout);
407 setDrawsBackground(parameters.drawsBackground);
408 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
410 setPaginationMode(parameters.paginationMode);
411 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
412 setPageLength(parameters.pageLength);
413 setGapBetweenPages(parameters.gapBetweenPages);
415 setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
417 setActive(parameters.isActive);
418 setFocused(parameters.isFocused);
419 setIsInWindow(parameters.isInWindow);
421 m_userAgent = parameters.userAgent;
423 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
425 if (!parameters.sessionState.isEmpty())
426 restoreSession(parameters.sessionState);
428 m_drawingArea->setPaintingEnabled(true);
430 setMediaVolume(parameters.mediaVolume);
433 webPageCounter.increment();
439 if (m_backForwardList)
440 m_backForwardList->detach();
444 m_sandboxExtensionTracker.invalidate();
446 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
447 (*it)->webPageDestroyed();
450 webPageCounter.decrement();
454 void WebPage::dummy(bool&)
458 CoreIPC::Connection* WebPage::connection() const
460 return WebProcess::shared().connection();
463 #if ENABLE(CONTEXT_MENUS)
464 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
466 m_contextMenuClient.initialize(client);
470 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
472 m_editorClient.initialize(client);
475 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
477 m_formClient.initialize(client);
480 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
482 m_loaderClient.initialize(client);
485 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
487 m_policyClient.initialize(client);
490 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
492 m_resourceLoadClient.initialize(client);
495 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
497 m_uiClient.initialize(client);
500 #if ENABLE(FULLSCREEN_API)
501 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
503 m_fullScreenClient.initialize(client);
507 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClient* client)
509 m_logDiagnosticMessageClient.initialize(client);
512 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters)
515 bool blocked = false;
517 if (!WebProcess::shared().connection()->sendSync(
518 Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()),
519 Messages::WebContext::GetPluginPath::Reply(pluginPath, blocked), 0)) {
524 if (pluginElement->renderer()->isEmbeddedObject())
525 toRenderEmbeddedObject(pluginElement->renderer())->setPluginUnavailabilityReason(RenderEmbeddedObject::InsecurePluginVersion);
527 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string()));
531 if (pluginPath.isNull()) {
533 if (parameters.mimeType == "application/pdf"
534 || (parameters.mimeType.isEmpty() && parameters.url.path().lower().endsWith(".pdf")))
535 return BuiltInPDFView::create(frame);
542 #if ENABLE(PLUGIN_PROCESS)
543 return PluginProxy::create(pluginPath);
544 #elif ENABLE(NETSCAPE_PLUGIN_API)
545 NetscapePlugin::setSetExceptionFunction(NPRuntimeObjectMap::setGlobalException);
546 return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
552 EditorState WebPage::editorState() const
554 Frame* frame = m_page->focusController()->focusedOrMainFrame();
558 result.selectionIsNone = frame->selection()->isNone();
559 result.selectionIsRange = frame->selection()->isRange();
560 result.isContentEditable = frame->selection()->isContentEditable();
561 result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
562 result.isInPasswordField = frame->selection()->isInPasswordField();
563 result.hasComposition = frame->editor()->hasComposition();
564 result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
566 #if ENABLE(TIZEN_WEBKIT2_TEXT_SELECTION) || ENABLE(TIZEN_ISF_PORT)
567 Element* selectionRoot = frame->selection()->rootEditableElementOrDocumentElement();
571 result.editorRect = frame->view()->contentsToWindow(selectionRoot->getPixelSnappedRect());
572 if (result.editorRect.maxX() <= 0 || result.editorRect.maxY() <= 0)
573 result.isContentEditable = false;
576 #if ENABLE(TIZEN_ISF_PORT)
577 Node* hostNode = selectionRoot->shadowAncestorNode();
578 if (result.isContentEditable) {
579 HTMLTextFormControlElement* formControl = toTextFormControl(hostNode);
581 result.inputMethodHints = formControl->type();
582 result.surroundingText = formControl->value();
585 Position base = frame->selection()->base();
586 Node* baseNode = base.containerNode();
588 result.cursorPosition = baseNode->isTextNode() ? base.offsetInContainerNode() : 0;
596 Element* selectionRoot = frame->selection()->rootEditableElement();
597 Element* scope = selectionRoot ? selectionRoot : frame->document()->documentElement();
602 if (scope->hasTagName(HTMLNames::inputTag)) {
603 HTMLInputElement* input = static_cast<HTMLInputElement*>(scope);
604 if (input->isTelephoneField())
605 result.inputMethodHints |= Qt::ImhDialableCharactersOnly;
606 else if (input->isNumberField())
607 result.inputMethodHints |= Qt::ImhDigitsOnly;
608 else if (input->isEmailField()) {
609 result.inputMethodHints |= Qt::ImhEmailCharactersOnly;
610 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
611 } else if (input->isURLField()) {
612 result.inputMethodHints |= Qt::ImhUrlCharactersOnly;
613 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
614 } else if (input->isPasswordField()) {
615 // Set ImhHiddenText flag for password fields. The Qt platform
616 // is responsible for determining which widget will receive input
617 // method events for password fields.
618 result.inputMethodHints |= Qt::ImhHiddenText;
619 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
620 result.inputMethodHints |= Qt::ImhNoPredictiveText;
621 result.inputMethodHints |= Qt::ImhSensitiveData;
626 result.editorRect = frame->view()->contentsToWindow(selectionRoot->getPixelSnappedRect());
629 if (result.hasComposition && (range = frame->editor()->compositionRange())) {
630 frame->editor()->getCompositionSelection(result.anchorPosition, result.cursorPosition);
632 result.compositionRect = frame->view()->contentsToWindow(range->boundingBox());
635 if (!result.hasComposition && !result.selectionIsNone && (range = frame->selection()->selection().firstRange())) {
636 TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
637 bool baseIsFirst = frame->selection()->selection().isBaseFirst();
639 result.cursorPosition = (baseIsFirst) ? location + length : location;
640 result.anchorPosition = (baseIsFirst) ? location : location + length;
641 result.selectedText = range->text();
645 result.cursorRect = frame->view()->contentsToWindow(frame->editor()->firstRectForRange(range.get()));
647 // FIXME: We should only transfer innerText when it changes and do this on the UI side.
648 if (result.isContentEditable && !result.isInPasswordField) {
649 result.surroundingText = scope->innerText();
650 if (result.hasComposition) {
651 // The anchor is always the left position when they represent a composition.
652 result.surroundingText.remove(result.anchorPosition, result.cursorPosition - result.anchorPosition);
660 String WebPage::renderTreeExternalRepresentation() const
662 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
665 uint64_t WebPage::renderTreeSize() const
669 return m_page->renderTreeSize().treeSize;
672 void WebPage::setPaintedObjectsCounterThreshold(uint64_t threshold)
676 m_page->setRelevantRepaintedObjectsCounterThreshold(threshold);
679 void WebPage::setTracksRepaints(bool trackRepaints)
681 if (FrameView* view = mainFrameView())
682 view->setTracksRepaints(trackRepaints);
685 bool WebPage::isTrackingRepaints() const
687 if (FrameView* view = mainFrameView())
688 return view->isTrackingRepaints();
693 void WebPage::resetTrackedRepaints()
695 if (FrameView* view = mainFrameView())
696 view->resetTrackedRepaints();
699 PassRefPtr<ImmutableArray> WebPage::trackedRepaintRects()
701 FrameView* view = mainFrameView();
703 return ImmutableArray::create();
705 const Vector<IntRect>& rects = view->trackedRepaintRects();
706 size_t size = rects.size();
708 return ImmutableArray::create();
710 Vector<RefPtr<APIObject> > vector;
711 vector.reserveInitialCapacity(size);
713 for (size_t i = 0; i < size; ++i)
714 vector.uncheckedAppend(WebRect::create(toAPI(rects[i])));
716 return ImmutableArray::adopt(vector);
719 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
721 Frame* frame = m_page->focusController()->focusedOrMainFrame();
724 frame->editor()->command(commandName).execute(argument);
727 bool WebPage::isEditingCommandEnabled(const String& commandName)
729 Frame* frame = m_page->focusController()->focusedOrMainFrame();
733 Editor::Command command = frame->editor()->command(commandName);
734 return command.isSupported() && command.isEnabled();
737 void WebPage::clearMainFrameName()
739 if (Frame* frame = mainFrame())
740 frame->tree()->clearName();
743 #if USE(ACCELERATED_COMPOSITING)
744 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
746 m_drawingArea->setRootCompositingLayer(layer);
749 void WebPage::exitAcceleratedCompositingMode()
751 m_drawingArea->setRootCompositingLayer(0);
755 void WebPage::close()
762 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
763 WebProcess::shared().injectedBundle()->willDestroyPage(this);
765 #if ENABLE(INSPECTOR)
768 #if ENABLE(FULLSCREEN_API)
769 m_fullScreenManager = 0;
772 if (m_activePopupMenu) {
773 m_activePopupMenu->disconnectFromPage();
774 m_activePopupMenu = 0;
777 if (m_activeOpenPanelResultListener) {
778 m_activeOpenPanelResultListener->disconnectFromPage();
779 m_activeOpenPanelResultListener = 0;
782 #if ENABLE(INPUT_TYPE_COLOR)
783 if (m_activeColorChooser) {
784 m_activeColorChooser->disconnectFromPage();
785 m_activeColorChooser = 0;
789 m_sandboxExtensionTracker.invalidate();
791 m_underlayPage = nullptr;
792 m_printContext = nullptr;
793 m_mainFrame->coreFrame()->loader()->detachFromParent();
795 m_drawingArea = nullptr;
797 bool isRunningModal = m_isRunningModal;
798 m_isRunningModal = false;
800 // The WebPage can be destroyed by this call.
801 WebProcess::shared().removeWebPage(m_pageID);
804 WebProcess::shared().runLoop()->stop();
807 void WebPage::tryClose()
809 SendStopResponsivenessTimer stopper(this);
811 if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
812 send(Messages::WebPageProxy::StopResponsivenessTimer());
816 send(Messages::WebPageProxy::ClosePage(true));
819 void WebPage::sendClose()
821 send(Messages::WebPageProxy::ClosePage(false));
824 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
826 #if ENABLE(TIZEN_RECORDING_SURFACE_SET)
827 recordingSurfaceSetEnableURL(url);
829 loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
832 #if ENABLE(TIZEN_RECORDING_SURFACE_SET)
833 void WebPage::recordingSurfaceSetEnableURL(const String& url)
835 if (m_recordingSurfaceSetSettings && strstr(url.utf8().data(), "bubblemark.com")) {
836 m_recordingSurfaceSetEnable = true;
837 m_page->m_recordingSurfaceSetEnable = true;
839 m_recordingSurfaceSetEnable = false;
840 m_page->m_recordingSurfaceSetEnable = false;
845 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
847 SendStopResponsivenessTimer stopper(this);
849 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
850 m_mainFrame->coreFrame()->loader()->load(request, false);
853 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
855 SendStopResponsivenessTimer stopper(this);
857 ResourceRequest request(baseURL);
858 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
859 m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
862 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
864 #if ENABLE(TIZEN_LOAD_HTML_STRING_AS_UTF8)
865 CString html = htmlString.utf8();
866 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(html.data()), html.length());
867 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
868 loadData(sharedBuffer, "text/html", "utf-8", baseURL, KURL());
870 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
871 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
872 loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
876 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
878 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
879 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
880 KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
881 loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
884 void WebPage::loadPlainTextString(const String& string)
886 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
887 loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
890 void WebPage::loadWebArchiveData(const CoreIPC::DataReference& webArchiveData)
892 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
893 loadData(sharedBuffer, "application/x-webarchive", "utf-16", blankURL(), KURL());
897 void WebPage::loadContentsbyMimeType(const CoreIPC::DataReference& contents, const String& mimeType, const String& encoding, const String& baseURL)
899 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(contents.data()), contents.size() * sizeof(uint8_t));
900 KURL baseKURL(WebCore::KURL(), baseURL);
901 loadData(sharedBuffer, mimeType, encoding, baseKURL, KURL());
905 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
907 Frame* frame = m_page->mainFrame();
911 RefPtr<Event> coreEvent;
912 if (event.type() != WebEvent::NoType)
913 coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
915 frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)),
916 false, false, coreEvent.get(), 0, MaybeSendReferrer);
919 void WebPage::stopLoadingFrame(uint64_t frameID)
921 WebFrame* frame = WebProcess::shared().webFrame(frameID);
925 frame->coreFrame()->loader()->stopForUserCancel();
928 void WebPage::stopLoading()
930 SendStopResponsivenessTimer stopper(this);
932 m_mainFrame->coreFrame()->loader()->stopForUserCancel();
935 void WebPage::setDefersLoading(bool defersLoading)
937 m_page->setDefersLoading(defersLoading);
940 void WebPage::reload(bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
942 SendStopResponsivenessTimer stopper(this);
944 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
945 m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
948 void WebPage::goForward(uint64_t backForwardItemID)
950 SendStopResponsivenessTimer stopper(this);
952 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
957 m_page->goToItem(item, FrameLoadTypeForward);
960 void WebPage::goBack(uint64_t backForwardItemID)
962 SendStopResponsivenessTimer stopper(this);
964 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
969 m_page->goToItem(item, FrameLoadTypeBack);
972 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
974 SendStopResponsivenessTimer stopper(this);
976 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
981 m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
984 void WebPage::tryRestoreScrollPosition()
986 m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
989 void WebPage::layoutIfNeeded()
991 if (m_mainFrame->coreFrame()->view())
992 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
994 if (m_underlayPage) {
995 if (FrameView *frameView = m_underlayPage->mainFrameView())
996 frameView->updateLayoutAndStyleIfNeededRecursive();
1000 void WebPage::setSize(const WebCore::IntSize& viewSize)
1002 FrameView* view = m_page->mainFrame()->view();
1004 #if USE(TILED_BACKING_STORE)
1005 // If we are resizing to content ignore external attempts.
1006 if (view->useFixedLayout())
1010 if (m_viewSize == viewSize)
1013 view->resize(viewSize);
1014 view->setNeedsLayout();
1015 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
1017 m_viewSize = viewSize;
1020 #if USE(TILED_BACKING_STORE)
1021 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1023 ASSERT(m_useFixedLayout);
1025 m_page->mainFrame()->view()->setFixedVisibleContentRect(rect);
1028 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
1030 ASSERT(m_useFixedLayout);
1031 ASSERT(!targetLayoutSize.isEmpty());
1033 FrameView* view = m_page->mainFrame()->view();
1035 view->setDelegatesScrolling(true);
1036 view->setUseFixedLayout(true);
1037 view->setPaintsEntireContents(true);
1039 if (view->fixedLayoutSize() == targetLayoutSize)
1042 m_page->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
1043 m_page->settings()->setFixedElementsLayoutRelativeToFrame(true);
1044 m_page->settings()->setFixedPositionCreatesStackingContext(true);
1046 // Always reset even when empty. This also takes care of the relayout.
1047 setFixedLayoutSize(targetLayoutSize);
1050 void WebPage::resizeToContentsIfNeeded()
1052 ASSERT(m_useFixedLayout);
1054 FrameView* view = m_page->mainFrame()->view();
1056 if (!view->useFixedLayout())
1059 IntSize newSize = view->contentsSize().expandedTo(view->fixedLayoutSize());
1061 if (newSize == m_viewSize)
1064 m_viewSize = newSize;
1065 view->resize(newSize);
1066 view->setNeedsLayout();
1069 void WebPage::sendViewportAttributesChanged()
1071 ASSERT(m_useFixedLayout);
1073 // Viewport properties have no impact on zero sized fixed viewports.
1074 if (m_viewportSize.isEmpty())
1077 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1078 Settings* settings = m_page->settings();
1081 // As android and iphone does, we set layout width to 980 for desktop content
1082 int minimumLayoutFallbackWidth = settings->layoutFallbackWidth();
1084 int minimumLayoutFallbackWidth = std::max(settings->layoutFallbackWidth(), m_viewportSize.width());
1087 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1088 int deviceWidth = (settings->deviceWidth() > 0) ? settings->deviceWidth() : m_viewportSize.width();
1089 int deviceHeight = (settings->deviceHeight() > 0) ? settings->deviceHeight() : m_viewportSize.height();
1091 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, m_page->deviceScaleFactor(), m_viewportSize);
1092 WebCore::restrictMinimumScaleFactorToViewportSize(attr, m_viewportSize);
1093 WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(attr);
1095 #if ENABLE(TIZEN_VIEWPORT_META_TAG)
1096 // On WebProcess, JS runs before visible content rect is updated by UIProcess
1097 // In this case, JS returns incorrect inner size value because scale factor is not updated yet
1098 // So, we update fixed visible content rect at here.
1099 // FIXME: scale factor needs to be calculated and set fixed visible content rect
1101 // if constrainsScrollingToContentEdge is true, scroll position will be adjusted with contents size.
1102 // disable this to avoid adjust scroll position on setFixedVisibleContentRect() because contents size is not fixed yet.
1103 bool constrainsScrollingToContentEdge = mainFrameView()->constrainsScrollingToContentEdge();
1104 mainFrameView()->setConstrainsScrollingToContentEdge(false);
1106 FloatSize contentFixedSize = m_viewportSize;
1107 contentFixedSize.scale(1 / (attr.initialScale * attr.devicePixelRatio));
1108 mainFrameView()->setFixedVisibleContentRect(IntRect(mainFrameView()->scrollPosition(), roundedIntSize(contentFixedSize)));
1110 // If viewport meta tag is not defined or initial scale factor is not defined,
1111 // initial scale factor can be defined by "Default View" setting of UIProcess.
1112 // Therefore we set initialScale as ValueAuto as WebKit opensource does, to handle it with setting on UIProcess.
1113 // You can find this implementation on WebKit bug.
1114 // https://bugs.webkit.org/show_bug.cgi?id=102392
1115 if (m_page->viewportArguments().type == ViewportArguments::Implicit
1116 || m_page->viewportArguments().initialScale == ViewportArguments::ValueAuto)
1117 attr.initialScale = ViewportArguments::ValueAuto;
1120 #if ENABLE(TIZEN_FULLSCREEN_API)
1121 if (fullScreenManager()->isMediaControlFullScreen())
1122 setResizesToContentsUsingLayoutSize(IntSize(deviceWidth, deviceHeight));
1125 setResizesToContentsUsingLayoutSize(IntSize(static_cast<int>(attr.layoutSize.width()), static_cast<int>(attr.layoutSize.height())));
1127 #if ENABLE(TIZEN_VIEWPORT_META_TAG)
1128 // recover constrainsScrollingToContentEdge
1129 mainFrameView()->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge);
1132 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1135 void WebPage::setViewportSize(const IntSize& size)
1137 ASSERT(m_useFixedLayout);
1139 if (m_viewportSize == size)
1142 m_viewportSize = size;
1144 sendViewportAttributesChanged();
1149 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1151 Frame* frame = m_page->mainFrame();
1153 IntPoint scrollPosition = frame->view()->scrollPosition();
1154 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
1156 // If the current scroll position in a direction is the max scroll position
1157 // we don't want to scroll at all.
1158 IntSize newScrollOffset;
1159 if (scrollPosition.x() < maximumScrollPosition.x())
1160 newScrollOffset.setWidth(scrollOffset.width());
1161 if (scrollPosition.y() < maximumScrollPosition.y())
1162 newScrollOffset.setHeight(scrollOffset.height());
1164 if (newScrollOffset.isZero())
1167 frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
1170 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1172 GraphicsContextStateSaver stateSaver(graphicsContext);
1173 graphicsContext.clip(rect);
1175 if (m_underlayPage) {
1176 m_underlayPage->drawRect(graphicsContext, rect);
1178 graphicsContext.beginTransparencyLayer(1);
1179 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1180 graphicsContext.endTransparencyLayer();
1184 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1187 #if ENABLE(TIZEN_WEBKIT2_CONTEXT_MENU_TEXT_SELECTION_MODE)
1188 void WebPage::selectLink(WebCore::IntPoint positionForSelection, bool& result)
1191 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1195 FrameView* frameView = frame->view();
1199 HitTestResult hitTestResult = frame->eventHandler()->hitTestResultAtPoint(frameView->windowToContents(positionForSelection), false);
1201 RefPtr<Range> range;
1202 Element* URLElement = hitTestResult.URLElement();
1204 for (Node* childNode = URLElement->firstChild(); childNode; childNode = childNode->traverseNextNode(URLElement)) {
1205 RenderObject* r = childNode->renderer();
1206 if (r && (r->isText() || r->isImage())) {
1208 range = VisibleSelection::selectionFromContentsOfNode(childNode).toNormalizedRange();
1209 else if (!hitTestResult.image()) {
1210 RefPtr<Range> extendedRange = VisibleSelection::selectionFromContentsOfNode(childNode).toNormalizedRange();
1211 range->setEnd(childNode, extendedRange->endOffset());
1216 range = VisibleSelection::selectionFromContentsOfNode(URLElement).toNormalizedRange();
1218 range = VisibleSelection::selectionFromContentsOfNode(hitTestResult.innerNonSharedNode()).toNormalizedRange();
1220 WebCore::FrameSelection* frameSelection = frame->selection();
1221 if (!frameSelection)
1224 EAffinity affinity = frameSelection->affinity();
1225 frameSelection->setSelectedRange(range.get(), affinity, true);
1227 if (frameSelection->isRange())
1234 #if ENABLE(TIZEN_ORIENTATION_EVENTS)
1235 void WebPage::sendOrientationChangeEvent(int newOrientation)
1237 Frame* frame = m_mainFrame->coreFrame();
1238 if (!frame || frame->orientation() == newOrientation)
1241 frame->sendOrientationChangeEvent(newOrientation);
1242 for (WebCore::Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1243 child->sendOrientationChangeEvent(newOrientation);
1247 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
1249 ASSERT(m_pageOverlay);
1251 GraphicsContextStateSaver stateSaver(graphicsContext);
1252 graphicsContext.clip(rect);
1253 m_pageOverlay->drawRect(graphicsContext, rect);
1256 double WebPage::textZoomFactor() const
1258 Frame* frame = m_mainFrame->coreFrame();
1261 return frame->textZoomFactor();
1264 void WebPage::setTextZoomFactor(double zoomFactor)
1266 Frame* frame = m_mainFrame->coreFrame();
1269 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1272 double WebPage::pageZoomFactor() const
1274 Frame* frame = m_mainFrame->coreFrame();
1277 return frame->pageZoomFactor();
1280 void WebPage::setPageZoomFactor(double zoomFactor)
1282 Frame* frame = m_mainFrame->coreFrame();
1285 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1288 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1290 Frame* frame = m_mainFrame->coreFrame();
1293 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1296 void WebPage::windowScreenDidChange(uint64_t displayID)
1298 m_page->windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1301 void WebPage::setViewMode(Page::ViewMode mode)
1303 m_page->setViewMode(mode);
1306 void WebPage::scalePage(double scale, const IntPoint& origin)
1308 m_page->setPageScaleFactor(scale, origin);
1310 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1311 (*it)->pageScaleFactorDidChange();
1313 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1316 double WebPage::pageScaleFactor() const
1318 return m_page->pageScaleFactor();
1321 void WebPage::setDeviceScaleFactor(float scaleFactor)
1323 if (scaleFactor == m_page->deviceScaleFactor())
1326 m_page->setDeviceScaleFactor(scaleFactor);
1328 // Tell all our plug-in views that the device scale factor changed.
1330 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1331 (*it)->setDeviceScaleFactor(scaleFactor);
1334 if (m_findController.isShowingOverlay()) {
1335 // We must have updated layout to get the selection rects right.
1337 m_findController.deviceScaleFactorDidChange();
1341 float WebPage::deviceScaleFactor() const
1343 return m_page->deviceScaleFactor();
1346 void WebPage::setUseFixedLayout(bool fixed)
1348 m_useFixedLayout = fixed;
1350 FrameView* view = mainFrameView();
1354 view->setUseFixedLayout(fixed);
1356 setFixedLayoutSize(IntSize());
1359 void WebPage::setFixedLayoutSize(const IntSize& size)
1361 FrameView* view = mainFrameView();
1362 if (!view || view->fixedLayoutSize() == size)
1365 view->setFixedLayoutSize(size);
1366 // Do not force it until the first layout, this would then become our first layout prematurely.
1367 if (view->didFirstLayout())
1368 view->forceLayout();
1371 void WebPage::setPaginationMode(uint32_t mode)
1373 Page::Pagination pagination = m_page->pagination();
1374 pagination.mode = static_cast<Page::Pagination::Mode>(mode);
1375 m_page->setPagination(pagination);
1378 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1380 Page::Pagination pagination = m_page->pagination();
1381 pagination.behavesLikeColumns = behavesLikeColumns;
1382 m_page->setPagination(pagination);
1385 void WebPage::setPageLength(double pageLength)
1387 Page::Pagination pagination = m_page->pagination();
1388 pagination.pageLength = pageLength;
1389 m_page->setPagination(pagination);
1392 void WebPage::setGapBetweenPages(double gap)
1394 Page::Pagination pagination = m_page->pagination();
1395 pagination.gap = gap;
1396 m_page->setPagination(pagination);
1399 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
1401 bool shouldFadeIn = true;
1403 if (m_pageOverlay) {
1404 m_pageOverlay->setPage(0);
1407 // We're installing a page overlay when a page overlay is already active.
1408 // In this case we don't want to fade in the new overlay.
1409 shouldFadeIn = false;
1413 m_pageOverlay = pageOverlay;
1414 m_pageOverlay->setPage(this);
1417 m_pageOverlay->startFadeInAnimation();
1419 m_drawingArea->didInstallPageOverlay();
1421 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
1424 m_pageOverlay->setNeedsDisplay();
1427 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
1429 if (pageOverlay != m_pageOverlay)
1433 m_pageOverlay->startFadeOutAnimation();
1437 m_pageOverlay->setPage(0);
1438 m_pageOverlay = nullptr;
1440 m_drawingArea->didUninstallPageOverlay();
1442 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
1446 #if PLATFORM(EFL) && OS(TIZEN)
1447 PassRefPtr<WebImage> WebPage::scaledSnapshotInViewCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1449 FrameView* frameView = m_mainFrame->coreFrame()->view();
1453 IntSize size(ceil(rect.width() * scaleFactor), ceil(rect.height() * scaleFactor));
1454 RefPtr<WebImage> snapshot = WebImage::create(size, options);
1455 if (!snapshot->bitmap())
1458 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1459 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1460 graphicsContext->translate(-rect.x(), -rect.y());
1462 frameView->updateLayoutAndStyleIfNeededRecursive();
1464 PaintBehavior oldBehavior = frameView->paintBehavior();
1465 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1466 frameView->paint(graphicsContext.get(), rect);
1467 frameView->setPaintBehavior(oldBehavior);
1469 return snapshot.release();
1472 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1474 return scaledSnapshotInViewCoordinates(rect, 1, options);
1477 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1479 FrameView* frameView = m_mainFrame->coreFrame()->view();
1483 IntSize bitmapSize = rect.size();
1484 float deviceScaleFactor = corePage()->deviceScaleFactor();
1485 bitmapSize.scale(deviceScaleFactor);
1487 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, options);
1488 if (!snapshot->bitmap())
1491 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1492 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1493 graphicsContext->translate(-rect.x(), -rect.y());
1495 frameView->updateLayoutAndStyleIfNeededRecursive();
1497 PaintBehavior oldBehavior = frameView->paintBehavior();
1498 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1499 frameView->paint(graphicsContext.get(), rect);
1500 frameView->setPaintBehavior(oldBehavior);
1502 return snapshot.release();
1506 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1508 FrameView* frameView = m_mainFrame->coreFrame()->view();
1512 float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor();
1513 IntSize size(ceil(rect.width() * combinedScaleFactor), ceil(rect.height() * combinedScaleFactor));
1514 RefPtr<WebImage> snapshot = WebImage::create(size, options);
1515 if (!snapshot->bitmap())
1518 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1519 graphicsContext->applyDeviceScaleFactor(combinedScaleFactor);
1520 graphicsContext->translate(-rect.x(), -rect.y());
1522 frameView->updateLayoutAndStyleIfNeededRecursive();
1524 PaintBehavior oldBehavior = frameView->paintBehavior();
1525 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1526 frameView->paintContents(graphicsContext.get(), rect);
1527 frameView->setPaintBehavior(oldBehavior);
1529 return snapshot.release();
1532 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
1534 return scaledSnapshotInDocumentCoordinates(rect, 1, options);
1537 void WebPage::pageDidScroll()
1539 m_uiClient.pageDidScroll(this);
1541 send(Messages::WebPageProxy::PageDidScroll());
1544 #if USE(TILED_BACKING_STORE)
1545 void WebPage::pageDidRequestScroll(const IntPoint& point)
1547 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1551 #if ENABLE(TIZEN_WEBKIT2_HISTORICAL_RESTORE_VISIBLE_CONTENT_RECT)
1552 void WebPage::pageDidRequestRestoreVisibleContentRect(const IntPoint& point, float scale)
1554 send(Messages::WebPageProxy::pageDidRequestRestoreVisibleContentRect(point, scale));
1558 #if ENABLE(CONTEXT_MENUS)
1559 WebContextMenu* WebPage::contextMenu()
1562 m_contextMenu = WebContextMenu::create(this);
1563 return m_contextMenu.get();
1569 static const WebEvent* g_currentEvent = 0;
1571 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1572 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1573 // platform events passed to the event handler code.
1574 const WebEvent* WebPage::currentEvent()
1576 return g_currentEvent;
1579 class CurrentEvent {
1581 explicit CurrentEvent(const WebEvent& event)
1582 : m_previousCurrentEvent(g_currentEvent)
1584 g_currentEvent = &event;
1589 g_currentEvent = m_previousCurrentEvent;
1593 const WebEvent* m_previousCurrentEvent;
1596 #if ENABLE(CONTEXT_MENUS)
1597 static bool isContextClick(const PlatformMouseEvent& event)
1599 if (event.button() == WebCore::RightButton)
1603 // FIXME: this really should be about OSX-style UI, not about the Mac port
1604 if (event.button() == WebCore::LeftButton && event.ctrlKey())
1611 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1613 IntPoint point = page->corePage()->mainFrame()->view()->windowToContents(platformMouseEvent.position());
1614 HitTestResult result = page->corePage()->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1616 Frame* frame = page->corePage()->mainFrame();
1617 #if !ENABLE(TIZEN_CONTEXT_MENU_WEBKIT_2)
1618 if (result.innerNonSharedNode())
1619 frame = result.innerNonSharedNode()->document()->frame();
1622 bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1624 page->contextMenu()->show();
1626 #if ENABLE(TIZEN_DRAG_SUPPORT)
1627 if(result.isDragSupport()) {
1628 if (result.innerNonSharedNode())
1629 frame = result.innerNonSharedNode()->document()->frame();
1631 PlatformMouseEvent event(frame->view()->windowToContents(platformMouseEvent.position()), platformMouseEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1632 frame->page()->dragController()->setPosition(event);
1640 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1642 Frame* frame = page->corePage()->mainFrame();
1646 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1648 switch (platformMouseEvent.type()) {
1649 case PlatformEvent::MousePressed: {
1650 #if ENABLE(CONTEXT_MENUS)
1651 if (isContextClick(platformMouseEvent))
1652 page->corePage()->contextMenuController()->clearContextMenu();
1655 #if ENABLE(TIZEN_CONTEXT_MENU_WEBKIT_2)
1657 if (!isContextClick(platformMouseEvent))
1658 handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1660 bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1662 #if ENABLE(CONTEXT_MENUS)
1663 if (isContextClick(platformMouseEvent))
1664 handled = handleContextMenuEvent(platformMouseEvent, page);
1667 bool gtkMouseButtonPressHandled = page->handleMousePressedEvent(platformMouseEvent);
1668 handled = handled || gtkMouseButtonPressHandled;
1673 case PlatformEvent::MouseReleased:
1674 return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1675 case PlatformEvent::MouseMoved:
1676 if (onlyUpdateScrollbars)
1677 return frame->eventHandler()->passMouseMovedEventToScrollbars(platformMouseEvent);
1678 return frame->eventHandler()->mouseMoved(platformMouseEvent);
1680 ASSERT_NOT_REACHED();
1685 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1687 #if ENABLE(CONTEXT_MENUS)
1688 // Don't try to handle any pending mouse events if a context menu is showing.
1689 if (m_isShowingContextMenu) {
1690 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1695 bool handled = false;
1697 if (m_pageOverlay) {
1698 // Let the page overlay handle the event.
1699 handled = m_pageOverlay->mouseEvent(mouseEvent);
1703 CurrentEvent currentEvent(mouseEvent);
1705 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1706 // button is currently pressed. It is possible that neither of those things will be true since on
1707 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1708 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1709 // efficient scrollbars-only version of the event.
1710 bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1711 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1714 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1717 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1719 handled = m_pageOverlay && m_pageOverlay->mouseEvent(mouseEvent);
1722 CurrentEvent currentEvent(mouseEvent);
1724 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1725 // button is currently pressed. It is possible that neither of those things will be true since on
1726 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1727 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1728 // efficient scrollbars-only version of the event.
1729 bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1730 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1734 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1736 Frame* frame = page->mainFrame();
1740 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1741 return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1744 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1746 CurrentEvent currentEvent(wheelEvent);
1748 bool handled = handleWheelEvent(wheelEvent, m_page.get());
1749 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1752 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1754 CurrentEvent currentEvent(wheelEvent);
1756 handled = handleWheelEvent(wheelEvent, m_page.get());
1759 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1761 if (!page->mainFrame()->view())
1764 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1765 return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1766 return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1769 #if ENABLE(TIZEN_ISF_PORT)
1770 void WebPage::keyEvent(const NativeWebKeyboardEvent& keyboardEvent)
1772 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1775 CurrentEvent currentEvent(keyboardEvent);
1777 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1778 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1780 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1782 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1785 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1787 CurrentEvent currentEvent(keyboardEvent);
1789 handled = handleKeyEvent(keyboardEvent, m_page.get());
1791 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1794 #if ENABLE(GESTURE_EVENTS)
1795 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1797 Frame* frame = page->mainFrame();
1801 PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1802 return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1805 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1807 CurrentEvent currentEvent(gestureEvent);
1809 bool handled = handleGestureEvent(gestureEvent, m_page.get());
1810 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1814 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1816 bool isEnabled = false;
1818 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1820 Editor::Command command = frame->editor()->command(commandName);
1821 state = command.state();
1822 isEnabled = command.isSupported() && command.isEnabled();
1825 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1828 void WebPage::executeEditCommand(const String& commandName)
1830 executeEditingCommand(commandName, String());
1833 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1835 const BackForwardListItemVector& list = sessionState.list();
1836 size_t size = list.size();
1837 uint64_t currentItemID = 0;
1838 for (size_t i = 0; i < size; ++i) {
1839 WebBackForwardListItem* webItem = list[i].get();
1840 DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1842 RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1844 LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1848 if (i == sessionState.currentIndex())
1849 currentItemID = webItem->itemID();
1851 WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1853 ASSERT(currentItemID);
1854 return currentItemID;
1857 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1859 if (uint64_t currentItemID = restoreSession(sessionState))
1860 goToBackForwardItem(currentItemID);
1863 #if ENABLE(TOUCH_EVENTS)
1865 void WebPage::highlightPotentialActivation(const IntPoint& point, const IntSize& area)
1867 if (point == IntPoint::zero()) {
1868 // An empty point deactivates the highlighting.
1869 tapHighlightController().hideHighlight();
1871 Frame* mainframe = m_page->mainFrame();
1872 Node* activationNode = 0;
1873 Node* adjustedNode = 0;
1874 IntPoint adjustedPoint;
1876 #if ENABLE(TOUCH_ADJUSTMENT)
1877 if (!mainframe->eventHandler()->bestClickableNodeForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), adjustedPoint, adjustedNode))
1881 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1882 adjustedNode = result.innerNode();
1884 // Find the node to highlight. This is not the same as the node responding the tap gesture, because many
1885 // pages has a global click handler and we do not want to highlight the body.
1886 // Instead find the enclosing link or focusable element, or the last enclosing inline element.
1887 for (Node* node = adjustedNode; node; node = node->parentOrHostNode()) {
1888 if (node->isMouseFocusable() || node->isLink()) {
1889 activationNode = node;
1892 if (node->renderer() && node->renderer()->isInline())
1893 activationNode = node;
1894 else if (activationNode)
1899 tapHighlightController().highlight(activationNode);
1904 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1906 Frame* frame = page->mainFrame();
1910 return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1913 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1915 CurrentEvent currentEvent(touchEvent);
1917 bool handled = handleTouchEvent(touchEvent, m_page.get());
1919 #if ENABLE(TIZEN_CSS_OVERFLOW_SCROLL_ACCELERATION)
1920 static bool checkOverflow = false;
1921 if (touchEvent.type() == WebEvent::TouchStart && touchEvent.touchPoints().size() == 1) {
1922 checkOverflow = true;
1923 } else if (checkOverflow && touchEvent.type() == WebEvent::TouchMove && touchEvent.touchPoints().size() == 1) {
1924 bool pressed = false;
1926 #if ENABLE(TIZEN_CSS_OVERFLOW_SCROLL_ACCELERATION_ON_UI_SIDE)
1927 setPressedNodeAtPoint(touchEvent.touchPoints()[0].position(), true, pressed, id);
1929 setPressedNodeAtPoint(touchEvent.touchPoints()[0].position(), false, pressed, id);
1931 send(Messages::WebPageProxy::SetOverflowResult(pressed, id));
1932 checkOverflow = false;
1935 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1938 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1940 CurrentEvent currentEvent(touchEvent);
1941 handled = handleTouchEvent(touchEvent, m_page.get());
1945 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1947 page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1950 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1952 page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1955 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1957 scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1960 void WebPage::centerSelectionInVisibleArea()
1962 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1966 frame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
1967 m_findController.showFindIndicatorInSelection();
1970 void WebPage::setActive(bool isActive)
1972 m_page->focusController()->setActive(isActive);
1975 // Tell all our plug-in views that the window focus changed.
1976 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1977 (*it)->setWindowIsFocused(isActive);
1981 void WebPage::setDrawsBackground(bool drawsBackground)
1983 if (m_drawsBackground == drawsBackground)
1986 m_drawsBackground = drawsBackground;
1988 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
1989 if (FrameView* view = coreFrame->view())
1990 view->setTransparent(!drawsBackground);
1993 m_drawingArea->pageBackgroundTransparencyChanged();
1994 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
1997 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
1999 if (m_drawsTransparentBackground == drawsTransparentBackground)
2002 m_drawsTransparentBackground = drawsTransparentBackground;
2004 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2005 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2006 if (FrameView* view = coreFrame->view())
2007 view->setBaseBackgroundColor(backgroundColor);
2010 m_drawingArea->pageBackgroundTransparencyChanged();
2011 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2014 void WebPage::viewWillStartLiveResize()
2019 // FIXME: This should propagate to all ScrollableAreas.
2020 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
2021 if (FrameView* view = frame->view())
2022 view->willStartLiveResize();
2026 void WebPage::viewWillEndLiveResize()
2031 // FIXME: This should propagate to all ScrollableAreas.
2032 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
2033 if (FrameView* view = frame->view())
2034 view->willEndLiveResize();
2038 void WebPage::setFocused(bool isFocused)
2040 m_page->focusController()->setFocused(isFocused);
2043 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2045 if (!m_page || !m_page->focusController())
2048 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2049 frame->document()->setFocusedNode(0);
2051 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2052 PlatformKeyboardEvent platformEvent(platform(event));
2053 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2054 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame->document()->defaultView()).get());
2058 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2061 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2063 if (m_windowResizerSize == windowResizerSize)
2066 m_windowResizerSize = windowResizerSize;
2068 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2069 FrameView* view = coreFrame->view();
2071 view->windowResizerRectChanged();
2075 void WebPage::setCanStartMediaTimerFired()
2078 m_page->setCanStartMedia(true);
2081 void WebPage::setIsInWindow(bool isInWindow)
2084 m_setCanStartMediaTimer.stop();
2085 m_page->setCanStartMedia(false);
2086 m_page->willMoveOffscreen();
2088 // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
2089 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2090 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2091 m_setCanStartMediaTimer.startOneShot(0);
2092 m_page->didMoveOnscreen();
2096 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2098 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2101 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2104 void WebPage::show()
2106 send(Messages::WebPageProxy::ShowPage());
2109 void WebPage::setUserAgent(const String& userAgent)
2111 m_userAgent = userAgent;
2113 #if ENABLE(TIZEN_CUSTOM_HEADERS)
2114 void WebPage::addCustomHeader(const String& name, const String& value)
2116 m_customHeaders.add(name, value);
2119 void WebPage::removeCustomHeader(const String& name)
2121 m_customHeaders.remove(name);
2124 void WebPage::clearCustomHeaders()
2126 m_customHeaders.clear();
2129 WebCore::HTTPHeaderMap WebPage::customHeaders()
2131 return m_customHeaders;
2135 void WebPage::suspendActiveDOMObjectsAndAnimations()
2137 m_page->suspendActiveDOMObjectsAndAnimations();
2140 void WebPage::resumeActiveDOMObjectsAndAnimations()
2142 m_page->resumeActiveDOMObjectsAndAnimations();
2144 // We need to repaint on resume to kickstart animated painting again.
2145 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2148 IntPoint WebPage::screenToWindow(const IntPoint& point)
2150 IntPoint windowPoint;
2151 sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
2155 IntRect WebPage::windowToScreen(const IntRect& rect)
2158 sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
2162 IntRect WebPage::windowResizerRect() const
2164 if (m_windowResizerSize.isEmpty())
2167 IntSize frameViewSize;
2168 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2169 if (FrameView* view = coreFrame->view())
2170 frameViewSize = view->size();
2173 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
2174 m_windowResizerSize.width(), m_windowResizerSize.height());
2177 KeyboardUIMode WebPage::keyboardUIMode()
2179 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2180 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2183 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2185 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2186 // disappear during script execution.
2188 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2189 // long enough for the DataReference to be encoded by the sent message.
2190 RefPtr<SerializedScriptValue> serializedResultValue;
2191 CoreIPC::DataReference dataReference;
2193 JSLockHolder lock(JSDOMWindow::commonJSGlobalData());
2194 if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
2195 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2196 dataReference = serializedResultValue->data();
2199 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2202 void WebPage::getContentsAsString(uint64_t callbackID)
2204 String resultString = m_mainFrame->contentsAsString();
2205 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2209 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2211 CoreIPC::DataReference dataReference;
2213 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2214 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2215 : MHTMLArchive::generateMHTMLData(m_page.get());
2218 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2220 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2224 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2226 String resultString = renderTreeExternalRepresentation();
2227 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2230 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2232 String resultString = m_mainFrame->selectionAsString();
2233 if (resultString.isEmpty())
2234 resultString = m_mainFrame->contentsAsString();
2235 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2238 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2240 String resultString;
2241 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2242 resultString = frame->source();
2244 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2247 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2249 CoreIPC::DataReference dataReference;
2251 RefPtr<SharedBuffer> buffer;
2252 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2253 if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
2254 if ((buffer = loader->mainResourceData()))
2255 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2259 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2262 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
2264 DocumentLoader* loader = frame->loader()->documentLoader();
2268 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2272 return subresource->data();
2275 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2277 CoreIPC::DataReference dataReference;
2278 KURL resourceURL(KURL(), resourceURLString);
2280 RefPtr<SharedBuffer> buffer;
2281 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2282 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2284 // Try to get the resource data from the cache.
2285 buffer = cachedResponseDataForURL(resourceURL);
2289 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2292 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2295 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2297 CoreIPC::DataReference dataReference;
2299 #if PLATFORM(MAC) || PLATFORM(WIN)
2300 RetainPtr<CFDataRef> data;
2301 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2302 if ((data = frame->webArchiveData(0, 0)))
2303 dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2307 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2310 void WebPage::forceRepaintWithoutCallback()
2312 m_drawingArea->forceRepaint();
2315 void WebPage::forceRepaint(uint64_t callbackID)
2317 if (m_drawingArea->forceRepaintAsync(callbackID))
2320 forceRepaintWithoutCallback();
2321 send(Messages::WebPageProxy::VoidCallback(callbackID));
2324 #if ENABLE(WEB_INTENTS)
2325 void WebPage::deliverIntentToFrame(uint64_t frameID, const IntentData& intentData)
2327 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2331 frame->deliverIntent(intentData);
2335 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2337 WebPreferencesStore::removeTestRunnerOverrides();
2338 updatePreferences(store);
2341 void WebPage::updatePreferences(const WebPreferencesStore& store)
2343 Settings* settings = m_page->settings();
2345 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2347 // FIXME: This should be generated from macro expansion for all preferences,
2348 // but we currently don't match the naming of WebCore exactly so we are
2349 // handrolling the boolean and integer preferences until that is fixed.
2351 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2353 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2355 #undef INITIALIZE_SETTINGS
2357 settings->setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2358 settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2359 settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2360 settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2361 settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2362 settings->setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2363 settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2364 settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2365 settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2366 settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2367 settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2368 settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2369 settings->setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2370 settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2371 settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2372 settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2373 settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2374 settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2375 #if ENABLE(WEB_ARCHIVE)
2376 settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2378 settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2379 settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2380 settings->setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2381 settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2382 settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2383 settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2384 settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2385 settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2386 settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2387 settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2388 settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2390 settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2391 settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2392 settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2393 settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2394 settings->setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2395 settings->setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2396 settings->setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2397 settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2398 settings->setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2400 settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2401 settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2402 settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2403 settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2404 settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2405 settings->setCSSCustomFilterEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCustomFilterEnabledKey()));
2406 settings->setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2407 settings->setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2408 settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2409 settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2410 settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2411 settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2412 settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2413 settings->setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2414 settings->setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2416 // <rdar://problem/10697417>: It is necessary to force compositing when accelerate drawing
2417 // is enabled on Mac so that scrollbars are always in their own layers.
2419 if (settings->acceleratedDrawingEnabled())
2420 settings->setForceCompositingMode(LayerTreeHost::supportsAcceleratedCompositing());
2423 settings->setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2425 #if ENABLE(TIZEN_RUNTIME_BACKEND_SELECTION)
2426 if (!settings->acceleratedCompositingEnabled()) {
2427 settings->setAcceleratedCompositingFor3DTransformsEnabled(false);
2428 settings->setAcceleratedCompositingForVideoEnabled(false);
2429 settings->setAcceleratedCompositingForPluginsEnabled(false);
2430 settings->setAcceleratedCompositingForCanvasEnabled(false);
2431 settings->setAcceleratedCompositingForAnimationEnabled(false);
2434 #if ENABLE(TIZEN_WEBKIT2_MEMORY_SAVING_MODE)
2435 settings->setMemorySavingMode(WebProcess::shared().memorySavingModeEnabled());
2438 #if ENABLE(SQL_DATABASE)
2439 AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2442 #if ENABLE(FULLSCREEN_API)
2443 settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2446 #if ENABLE(TIZEN_WEBKIT2_ASYNCHRONOUS_SPELLCHECKING)
2447 settings->setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2449 settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
2451 #if USE(AVFOUNDATION)
2452 settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2455 #if ENABLE(WEB_AUDIO)
2456 settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2459 settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2460 settings->setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2461 settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2462 settings->setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2463 settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2465 #if ENABLE(VIDEO_TRACK)
2466 settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2467 settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2468 settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2471 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2472 settings->setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2475 settings->setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2477 #if ENABLE(TIZEN_INDEXED_DATABASE)
2478 m_page->group().groupSettings()->setIndexedDBDatabasePath(WebProcess::shared().indexedDatabaseDirectory());
2479 m_page->group().groupSettings()->setIndexedDBQuotaBytes(0x6400000); //100M
2482 settings->setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2484 #if ENABLE(TEXT_AUTOSIZING)
2485 settings->setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2488 #if ENABLE(TIZEN_FILE_SYSTEM)
2489 m_page->group().groupSettings()->setLocalFileSystemQuotaBytes(0x6400000); //100M
2492 platformPreferencesDidChange(store);
2495 m_drawingArea->updatePreferences();
2498 #if ENABLE(INSPECTOR)
2499 WebInspector* WebPage::inspector()
2504 m_inspector = WebInspector::create(this, m_inspectorClient);
2505 return m_inspector.get();
2509 #if ENABLE(FULLSCREEN_API)
2510 WebFullScreenManager* WebPage::fullScreenManager()
2512 if (!m_fullScreenManager)
2513 m_fullScreenManager = WebFullScreenManager::create(this);
2514 return m_fullScreenManager.get();
2518 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2520 if (m_notificationPermissionRequestManager)
2521 return m_notificationPermissionRequestManager.get();
2523 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2524 return m_notificationPermissionRequestManager.get();
2527 #if ENABLE(TIZEN_MEDIA_STREAM)
2528 UserMediaPermissionRequestManager* WebPage::userMediaPermissionRequestManager()
2530 if (m_userMediaPermissionRequestManager)
2531 return m_userMediaPermissionRequestManager.get();
2533 m_userMediaPermissionRequestManager = UserMediaPermissionRequestManager::create(this);
2534 return m_userMediaPermissionRequestManager.get();
2538 #if !PLATFORM(GTK) && !PLATFORM(MAC)
2539 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2541 Node* node = evt->target()->toNode();
2543 Frame* frame = node->document()->frame();
2546 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2550 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
2552 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2553 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2554 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2555 // (e.g. Tab that inserts a Tab character, or Enter).
2556 return !command.isTextInsertion() && command.execute(evt);
2559 if (command.execute(evt))
2562 // Don't allow text insertion for nodes that cannot edit.
2563 if (!frame->editor()->canEdit())
2566 // Don't insert null or control characters as they can result in unexpected behaviour
2567 if (evt->charCode() < ' ')
2570 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
2574 #if ENABLE(DRAG_SUPPORT)
2577 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
2580 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2584 DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2586 case DragControllerActionEntered:
2587 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2590 case DragControllerActionUpdated:
2591 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2594 case DragControllerActionExited:
2595 m_page->dragController()->dragExited(&dragData);
2598 case DragControllerActionPerformDrag:
2599 m_page->dragController()->performDrag(&dragData);
2603 ASSERT_NOT_REACHED();
2607 #elif PLATFORM(QT) || PLATFORM(GTK) || ENABLE(TIZEN_DRAG_SUPPORT)
2608 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2611 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2613 QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2616 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2619 #if ENABLE(TIZEN_DRAG_SUPPORT)
2620 DataObjectTizen* data = const_cast<DataObjectTizen*>(dragData.platformData());
2627 case DragControllerActionEntered:
2628 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2631 case DragControllerActionUpdated:
2632 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2635 case DragControllerActionExited:
2636 m_page->dragController()->dragExited(&dragData);
2639 case DragControllerActionPerformDrag: {
2640 m_page->dragController()->performDrag(&dragData);
2645 ASSERT_NOT_REACHED();
2647 // DragData does not delete its platformData so we need to do that here.
2649 QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2652 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2655 #if ENABLE(TIZEN_DRAG_SUPPORT)
2656 DataObjectTizen* data = const_cast<DataObjectTizen*>(dragData.platformData());
2662 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, const SandboxExtension::HandleArray& sandboxExtensionsHandleArray)
2665 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2669 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2671 case DragControllerActionEntered:
2672 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2675 case DragControllerActionUpdated:
2676 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2679 case DragControllerActionExited:
2680 m_page->dragController()->dragExited(&dragData);
2683 case DragControllerActionPerformDrag: {
2684 ASSERT(!m_pendingDropSandboxExtension);
2686 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2687 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2688 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2689 m_pendingDropExtensionsForFileUpload.append(extension);
2692 m_page->dragController()->performDrag(&dragData);
2694 // If we started loading a local file, the sandbox extension tracker would have adopted this
2695 // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2696 if (m_pendingDropSandboxExtension) {
2697 m_pendingDropSandboxExtension->invalidate();
2698 m_pendingDropSandboxExtension = nullptr;
2700 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2701 m_pendingDropExtensionsForFileUpload[i]->invalidate();
2703 m_pendingDropExtensionsForFileUpload.clear();
2708 ASSERT_NOT_REACHED();
2713 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2715 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2716 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2718 m_page->dragController()->dragEnded();
2719 FrameView* view = m_page->mainFrame()->view();
2722 // FIXME: These are fake modifier keys here, but they should be real ones instead.
2723 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2724 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2727 void WebPage::willPerformLoadDragDestinationAction()
2729 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2732 void WebPage::mayPerformUploadDragDestinationAction()
2734 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2735 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2736 m_pendingDropExtensionsForFileUpload.clear();
2739 #endif // ENABLE(DRAG_SUPPORT)
2741 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2743 return m_undoStepMap.get(stepID).get();
2746 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2748 m_undoStepMap.set(stepID, entry);
2751 void WebPage::removeWebEditCommand(uint64_t stepID)
2753 m_undoStepMap.remove(stepID);
2756 void WebPage::unapplyEditCommand(uint64_t stepID)
2758 WebUndoStep* step = webUndoStep(stepID);
2762 step->step()->unapply();
2765 void WebPage::reapplyEditCommand(uint64_t stepID)
2767 WebUndoStep* step = webUndoStep(stepID);
2772 step->step()->reapply();
2776 void WebPage::didRemoveEditCommand(uint64_t commandID)
2778 removeWebEditCommand(commandID);
2781 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2783 m_activePopupMenu = menu;
2786 #if ENABLE(INPUT_TYPE_COLOR)
2787 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2789 m_activeColorChooser = colorChooser;
2792 void WebPage::didEndColorChooser()
2794 m_activeColorChooser->didEndChooser();
2797 void WebPage::didChooseColor(const WebCore::Color& color)
2799 m_activeColorChooser->didChooseColor(color);
2803 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2805 m_activeOpenPanelResultListener = openPanelResultListener;
2808 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2810 return m_page->findString(target, options);
2813 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2815 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2818 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2820 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2823 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2825 m_findController.getImageForFindMatch(matchIndex);
2828 void WebPage::selectFindMatch(uint32_t matchIndex)
2830 m_findController.selectFindMatch(matchIndex);
2833 void WebPage::hideFindUI()
2835 m_findController.hideFindUI();
2838 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2840 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2843 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2845 changeSelectedIndex(newIndex);
2847 // Since applictions on tizen may provide a way to select item more than one time,
2848 // we need to keep the active popup menu to allow repetitive selection.
2850 m_activePopupMenu = 0;
2854 void WebPage::changeSelectedIndex(int32_t index)
2856 if (!m_activePopupMenu)
2859 m_activePopupMenu->didChangeSelectedIndex(index);
2862 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2864 if (!m_activeOpenPanelResultListener)
2867 m_activeOpenPanelResultListener->didChooseFiles(files);
2868 m_activeOpenPanelResultListener = 0;
2871 void WebPage::didCancelForOpenPanel()
2873 m_activeOpenPanelResultListener = 0;
2876 #if ENABLE(WEB_PROCESS_SANDBOX)
2877 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2879 SandboxExtension::create(handle)->consumePermanently();
2883 #if ENABLE(GEOLOCATION)
2884 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2886 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2890 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2892 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2895 #if ENABLE(TIZEN_MEDIA_STREAM)
2896 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed)
2898 userMediaPermissionRequestManager()->didReceiveUserMediaPermissionDecision(userMediaID, allowed);
2902 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2904 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2905 frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2908 void WebPage::changeSpellingToWord(const String& word)
2910 replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2913 void WebPage::unmarkAllMisspellings()
2915 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2916 if (Document* document = frame->document())
2917 document->markers()->removeMarkers(DocumentMarker::Spelling);
2921 void WebPage::unmarkAllBadGrammar()
2923 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2924 if (Document* document = frame->document())
2925 document->markers()->removeMarkers(DocumentMarker::Grammar);
2930 void WebPage::uppercaseWord()
2932 m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2935 void WebPage::lowercaseWord()
2937 m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2940 void WebPage::capitalizeWord()
2942 m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2946 void WebPage::setTextForActivePopupMenu(int32_t index)
2948 if (!m_activePopupMenu)
2951 m_activePopupMenu->setTextForIndex(index);
2955 void WebPage::failedToShowPopupMenu()
2957 if (!m_activePopupMenu)
2960 m_activePopupMenu->client()->popupDidHide();
2964 #if ENABLE(CONTEXT_MENUS)
2965 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
2970 m_contextMenu->itemSelected(item);
2975 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
2977 bool selectReplacement = true;
2978 bool smartReplace = false;
2979 return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
2982 void WebPage::clearSelection()
2984 m_page->focusController()->focusedOrMainFrame()->selection()->clear();
2987 bool WebPage::mainFrameHasCustomRepresentation() const
2989 if (Frame* frame = mainFrame())
2990 return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
2995 void WebPage::didChangeScrollOffsetForMainFrame()
2997 Frame* frame = m_page->mainFrame();
2998 IntPoint scrollPosition = frame->view()->scrollPosition();
2999 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
3000 IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
3002 #if PLATFORM(EFL) && OS(TIZEN)
3003 send(Messages::WebPageProxy::DidChangeScrollPositionForMainFrame(scrollPosition));
3006 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3007 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3009 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
3010 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
3012 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3013 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3017 void WebPage::mainFrameDidLayout()
3019 unsigned pageCount = m_page->pageCount();
3020 if (pageCount != m_cachedPageCount) {
3021 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3022 m_cachedPageCount = pageCount;
3025 double red, green, blue, alpha;
3026 m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3027 send(Messages::WebPageProxy::SetBackgroundColor(red, green, blue, alpha));
3030 void WebPage::addPluginView(PluginView* pluginView)
3032 ASSERT(!m_pluginViews.contains(pluginView));
3034 m_pluginViews.add(pluginView);
3037 void WebPage::removePluginView(PluginView* pluginView)
3039 ASSERT(m_pluginViews.contains(pluginView));
3041 m_pluginViews.remove(pluginView);
3045 void WebPage::setWindowIsVisible(bool windowIsVisible)
3047 m_windowIsVisible = windowIsVisible;
3049 corePage()->focusController()->setContainingWindowIsVisible(windowIsVisible);
3051 // Tell all our plug-in views that the window visibility changed.
3052 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
3053 (*it)->setWindowIsVisible(windowIsVisible);
3056 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
3058 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3059 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3060 m_accessibilityPosition = accessibilityViewCoordinates;
3062 // Tell all our plug-in views that the window and view frames have changed.
3063 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
3064 (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
3068 bool WebPage::windowIsFocused() const
3070 return m_page->focusController()->isActive();
3073 bool WebPage::windowAndWebPageAreFocused() const
3076 if (!m_windowIsVisible)
3079 return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
3082 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
3084 if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
3086 m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
3090 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
3091 if (messageID.is<CoreIPC::MessageClassLayerTreeCoordinator>()) {
3093 m_drawingArea->didReceiveLayerTreeCoordinatorMessage(connection, messageID, arguments);
3098 #if ENABLE(INSPECTOR)
3099 if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
3100 if (WebInspector* inspector = this->inspector())
3101 inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
3106 #if ENABLE(FULLSCREEN_API)
3107 if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
3108 fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
3113 didReceiveWebPageMessage(connection, messageID, arguments);
3116 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
3118 didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
3121 InjectedBundleBackForwardList* WebPage::backForwardList()
3123 if (!m_backForwardList)
3124 m_backForwardList = InjectedBundleBackForwardList::create(this);
3125 return m_backForwardList.get();
3128 #if PLATFORM(QT) || OS(TIZEN)
3129 #if ENABLE(TOUCH_ADJUSTMENT)
3130 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3133 IntRect zoomableArea;
3134 bool foundAreaForTouchPoint = m_mainFrame->coreFrame()->eventHandler()->bestZoomableAreaForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), zoomableArea, node);
3137 if (!foundAreaForTouchPoint)
3140 send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3144 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3147 Frame* mainframe = m_mainFrame->coreFrame();
3148 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
3150 Node* node = result.innerNode();
3155 #if OS(TIZEN) // FIXME: This is to fix wrong codes of open source.
3156 IntRect zoomableArea = enclosingIntRect(node->getRect());
3158 IntRect zoomableArea = node->getRect();
3162 bool found = !node->isTextNode() && !node->isShadowRoot();
3164 // No candidate found, bail out.
3165 if (!found && !node->parentNode())
3168 // Candidate found, and it is a better candidate than its parent.
3169 // NB: A parent is considered a better candidate iff the node is
3170 // contained by it and it is the only child.
3171 if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
3174 node = node->parentNode();
3175 #if OS(TIZEN) // FIXME: This is to fix wrong codes of open source.
3176 zoomableArea.unite(enclosingIntRect(node->getRect()));
3178 zoomableArea.unite(node->getRect());
3182 if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
3183 const ScrollView* view = node->document()->frame()->view();
3184 zoomableArea = view->contentsToWindow(zoomableArea);
3187 send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3192 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3197 void WebPage::SandboxExtensionTracker::invalidate()
3199 if (m_pendingProvisionalSandboxExtension) {
3200 m_pendingProvisionalSandboxExtension->invalidate();
3201 m_pendingProvisionalSandboxExtension = 0;
3204 if (m_provisionalSandboxExtension) {
3205 m_provisionalSandboxExtension->invalidate();
3206 m_provisionalSandboxExtension = 0;
3209 if (m_committedSandboxExtension) {
3210 m_committedSandboxExtension->invalidate();
3211 m_committedSandboxExtension = 0;
3215 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3217 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3220 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3222 ASSERT(frame->isMainFrame());
3224 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3227 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3229 // If we get two beginLoad calls in succession, without a provisional load starting, then
3230 // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
3231 if (m_pendingProvisionalSandboxExtension) {
3232 m_pendingProvisionalSandboxExtension->invalidate();
3233 m_pendingProvisionalSandboxExtension = nullptr;
3236 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
3239 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3241 ASSERT(frame->isMainFrame());
3243 FrameLoader* frameLoader = frame->coreFrame()->loader();
3244 FrameLoadType frameLoadType = frameLoader->loadType();
3246 // If the page is being reloaded, it should reuse whatever extension is committed.
3247 if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3250 DocumentLoader* documentLoader = frameLoader->documentLoader();
3251 DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
3252 if (!documentLoader || !provisionalDocumentLoader)
3255 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3261 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3263 if (!frame->isMainFrame())
3266 // We should only reuse the commited sandbox extension if it is not null. It can be
3267 // null if the last load was for an error page.
3268 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
3269 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
3270 ASSERT(!m_committedSandboxExtension);
3273 ASSERT(!m_provisionalSandboxExtension);
3275 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3276 if (!m_provisionalSandboxExtension)
3279 m_provisionalSandboxExtension->consume();
3282 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3284 if (!frame->isMainFrame())
3287 // Generally, there should be no pending extension at this stage, but we can have one if UI process
3288 // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3289 if (m_pendingProvisionalSandboxExtension) {
3290 m_pendingProvisionalSandboxExtension->invalidate();
3291 m_pendingProvisionalSandboxExtension = nullptr;
3294 // The provisional load has been committed. Invalidate the currently committed sandbox
3295 // extension and make the provisional sandbox extension the committed sandbox extension.
3296 if (m_committedSandboxExtension)
3297 m_committedSandboxExtension->invalidate();
3299 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3302 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3304 if (!frame->isMainFrame())
3307 // Generally, there should be no pending extension at this stage, but we can have one if UI process
3308 // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3309 if (m_pendingProvisionalSandboxExtension) {
3310 m_pendingProvisionalSandboxExtension->invalidate();
3311 m_pendingProvisionalSandboxExtension = nullptr;
3314 if (!m_provisionalSandboxExtension)
3317 m_provisionalSandboxExtension->invalidate();
3318 m_provisionalSandboxExtension = nullptr;
3321 bool WebPage::hasLocalDataForURL(const KURL& url)
3323 if (url.isLocalFile())
3326 FrameLoader* frameLoader = m_page->mainFrame()->loader();
3327 DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
3328 if (documentLoader && documentLoader->subresource(url))
3331 return platformHasLocalDataForURL(url);
3334 void WebPage::setCustomTextEncodingName(const String& encoding)
3336 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
3339 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3341 WebBackForwardListProxy::removeItem(itemID);
3346 bool WebPage::isSpeaking()
3349 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3352 void WebPage::speak(const String& string)
3354 send(Messages::WebPageProxy::Speak(string));
3357 void WebPage::stopSpeaking()
3359 send(Messages::WebPageProxy::StopSpeaking());
3365 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3367 Document* document = coreFrame->document();
3371 if (!document->isPluginDocument())
3374 PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3378 return pluginView->pdfDocumentForPrinting();
3380 #endif // PLATFORM(MAC)
3382 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3384 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3388 Frame* coreFrame = frame->coreFrame();
3393 if (pdfDocumentForPrintingFrame(coreFrame))
3395 #endif // PLATFORM(MAC)
3397 if (!m_printContext)
3398 m_printContext = adoptPtr(new PrintContext(coreFrame));
3400 drawingArea()->setLayerTreeStateIsFrozen(true);
3401 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3403 float fullPageHeight;
3404 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3407 if (!m_printOperation)
3408 m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3412 void WebPage::endPrinting()
3414 drawingArea()->setLayerTreeStateIsFrozen(false);
3416 m_printOperation = 0;
3418 m_printContext = nullptr;
3421 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3423 Vector<IntRect> resultPageRects;
3424 double resultTotalScaleFactorForPrinting = 1;
3426 beginPrinting(frameID, printInfo);
3428 if (m_printContext) {
3429 resultPageRects = m_printContext->pageRects();
3430 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3434 computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3435 #endif // PLATFORM(MAC)
3437 // If we're asked to print, we should actually print at least a blank page.
3438 if (resultPageRects.isEmpty())
3439 resultPageRects.append(IntRect(0, 0, 1, 1));
3441 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3444 #if PLATFORM(MAC) || PLATFORM(WIN)
3445 void WebPage::drawRectToPDF(uint64_t frameID, const PrintInfo& printInfo, const WebCore::IntRect& rect, uint64_t callbackID)
3447 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3448 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3450 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3455 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3457 ASSERT(coreFrame->document()->printing());
3460 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3461 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3463 CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
3464 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3465 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3466 CGPDFContextBeginPage(context.get(), pageInfo.get());
3469 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3470 ASSERT(!m_printContext);
3471 drawRectToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, rect);
3475 GraphicsContext ctx(context.get());
3476 ctx.scale(FloatSize(1, -1));
3477 ctx.translate(0, -rect.height());
3478 m_printContext->spoolRect(ctx, rect);
3481 CGPDFContextEndPage(context.get());
3482 CGPDFContextClose(context.get());
3486 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3489 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3491 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3492 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3494 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3500 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3502 ASSERT(coreFrame->document()->printing());
3505 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3506 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3508 CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3509 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3512 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3513 ASSERT(!m_printContext);
3514 drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3518 size_t pageCount = m_printContext->pageCount();
3519 for (uint32_t page = first; page < first + count; ++page) {
3520 if (page >= pageCount)
3523 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3524 CGPDFContextBeginPage(context.get(), pageInfo.get());
3526 GraphicsContext ctx(context.get());
3527 ctx.scale(FloatSize(1, -1));
3528 ctx.translate(0, -m_printContext->pageRect(page).height());
3529 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3531 CGPDFContextEndPage(context.get());
3534 CGPDFContextClose(context.get());
3538 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3543 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3545 beginPrinting(frameID, printInfo);
3546 if (m_printContext && m_printOperation) {
3547 m_printOperation->startPrint(m_printContext.get(), callbackID);
3551 send(Messages::WebPageProxy::VoidCallback(callbackID));
3555 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
3556 void WebPage::getWebAppCapable(uint64_t callbackID)
3558 RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("meta");
3559 bool capable = false;
3561 for (unsigned i = 0; i < nodeList->length(); i++) {
3562 WebCore::HTMLMetaElement* metaElement = static_cast<WebCore::HTMLMetaElement*>(nodeList->item(i));
3563 if (metaElement->name() == "apple-mobile-web-app-capable") {
3564 capable = metaElement->content() == "yes" ? true : false;
3569 send(Messages::WebPageProxy::DidGetWebAppCapable(capable, callbackID));
3572 void WebPage::getWebAppIconURL(uint64_t callbackID)
3574 RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("link");
3577 for (unsigned i = 0; i < nodeList->length(); i++) {
3578 WebCore::HTMLLinkElement* linkElement = static_cast<WebCore::HTMLLinkElement*>(nodeList->item(i));
3579 if (linkElement->rel() == "apple-touch-icon" || linkElement->rel() == "apple-touch-icon-precomposed")
3580 iconURL = linkElement->href().string();
3583 send(Messages::WebPageProxy::DidGetWebAppIconURL(iconURL, callbackID));
3586 void WebPage::getWebAppIconURLs(uint64_t callbackID)
3588 RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("link");
3589 Vector<std::pair<String, String> > iconURLs;
3591 for (unsigned i = 0; i < nodeList->length(); i++) {
3592 WebCore::HTMLLinkElement* linkElement = static_cast<WebCore::HTMLLinkElement*>(nodeList->item(i));
3593 if (linkElement->rel() == "apple-touch-icon" || linkElement->rel() == "apple-touch-icon-precomposed")
3594 iconURLs.append(pair<String, String>(linkElement->href().string(), linkElement->iconSizes()));
3597 send(Messages::WebPageProxy::DidGetWebAppIconURLs(iconURLs, callbackID));
3601 void WebPage::setMediaVolume(float volume)
3603 m_page->setMediaVolume(volume);
3606 void WebPage::runModal()
3610 if (m_isRunningModal)
3613 m_isRunningModal = true;
3614 send(Messages::WebPageProxy::RunModal());
3616 ASSERT(!m_isRunningModal);
3619 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3621 m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3624 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3626 if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3628 return platformCanHandleRequest(request);
3631 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
3632 void WebPage::handleAlternativeTextUIResult(const String& result)
3634 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3637 frame->editor()->handleAlternativeTextUIResult(result);
3641 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3643 mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3646 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3648 mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3651 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3653 mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3656 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3658 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3659 if (!frame || !frame->editor()->canEdit())
3662 Vector<CompositionUnderline> underlines;
3663 underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3664 frame->editor()->setComposition(compositionString, underlines, from, from + length);
3667 bool WebPage::hasCompositionForTesting()
3669 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3670 return frame && frame->editor()->hasComposition();
3673 void WebPage::confirmCompositionForTesting(const String& compositionString)
3675 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3676 if (!frame || !frame->editor()->canEdit())
3679 if (compositionString.isNull())
3680 frame->editor()->confirmComposition();
3681 frame->editor()->confirmComposition(compositionString);
3684 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3686 if (m_numWheelEventHandlers == numWheelEventHandlers)
3689 m_numWheelEventHandlers = numWheelEventHandlers;
3690 recomputeShortCircuitHorizontalWheelEventsState();
3693 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3695 if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3696 return scrollbar->enabled();
3701 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3703 if (FrameView* frameView = mainFrame->view()) {
3704 if (hasEnabledHorizontalScrollbar(frameView))
3708 for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext()) {
3709 FrameView* frameView = frame->view();
3713 const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3714 if (!scrollableAreas)
3717 for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3718 ScrollableArea* scrollableArea = *it;
3719 if (!scrollableArea->isOnActivePage())
3722 if (hasEnabledHorizontalScrollbar(scrollableArea))
3730 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3732 bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3734 if (canShortCircuitHorizontalWheelEvents) {
3735 // Check if we have any horizontal scroll bars on the page.
3736 if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3737 canShortCircuitHorizontalWheelEvents = false;
3740 if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3743 m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3744 send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3747 Frame* WebPage::mainFrame() const
3749 return m_page ? m_page->mainFrame() : 0;
3752 FrameView* WebPage::mainFrameView() const
3754 if (Frame* frame = mainFrame())
3755 return frame->view();
3760 #if ENABLE(PAGE_VISIBILITY_API)
3761 void WebPage::setVisibilityState(int visibilityState, bool isInitialState)
3766 WebCore::PageVisibilityState state = static_cast<WebCore::PageVisibilityState>(visibilityState);
3768 if (m_visibilityState == state)
3771 FrameView* view = m_page->mainFrame() ? m_page->mainFrame()->view() : 0;
3773 if (state == WebCore::PageVisibilityStateVisible) {
3774 m_page->didMoveOnscreen();
3779 m_page->setVisibilityState(state, isInitialState);
3780 m_visibilityState = state;
3782 if (state == WebCore::PageVisibilityStateHidden) {
3783 m_page->willMoveOffscreen();
3790 #if ENABLE(TIZEN_NATIVE_MEMORY_SNAPSHOT)
3791 const char* dumpFileName = "/tmp/webkit_memory";
3794 void dumpMemorySnapshotForUrl(char* url)
3796 PrintFormat format = PRINT_FORMAT_JSON;
3798 fp = fopen(dumpFileName, "a");
3800 if (format == PRINT_FORMAT_JSON)
3803 fprintf(fp, "URL:%s\n", url);
3804 fprintf(fp, "%s", memoryPage(format).utf8().data());
3805 if (format == PRINT_FORMAT_JSON)
3806 fprintf(fp, "\"URL\":\"%s\"}\n", url);
3812 void dumpMemorySnapshot()
3814 dumpMemorySnapshotForUrl(lastUrl);
3817 void WebPage::dumpMemorySnapshot()
3819 char* url = strdup(mainWebFrame()->url().utf8().data());
3826 } // namespace WebKit