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_SYNC_REQUEST_ANIMATION_FRAME)
302 , m_suspendedAnimationController(false)
304 , m_inspectorClient(0)
307 // FIXME: This is a non-ideal location for this Setting and
308 // 4ms should be adopted project-wide now, https://bugs.webkit.org/show_bug.cgi?id=61214
309 #if ENABLE(TIZEN_DOM_TIMER_MIN_INTERVAL_SET)
310 Settings::setDefaultMinDOMTimerInterval(0.001);
312 Settings::setDefaultMinDOMTimerInterval(0.004);
315 Page::PageClients pageClients;
316 pageClients.chromeClient = new WebChromeClient(this);
317 #if ENABLE(CONTEXT_MENUS)
318 pageClients.contextMenuClient = new WebContextMenuClient(this);
320 pageClients.editorClient = new WebEditorClient(this);
321 #if ENABLE(DRAG_SUPPORT)
322 pageClients.dragClient = new WebDragClient(this);
324 pageClients.backForwardClient = WebBackForwardListProxy::create(this);
325 #if ENABLE(INSPECTOR)
326 m_inspectorClient = new WebInspectorClient(this);
327 pageClients.inspectorClient = m_inspectorClient;
329 #if USE(AUTOCORRECTION_PANEL)
330 pageClients.alternativeTextClient = new WebAlternativeTextClient(this);
333 m_page = adoptPtr(new Page(pageClients));
335 #if ENABLE(BATTERY_STATUS)
336 WebCore::provideBatteryTo(m_page.get(), new WebBatteryClient(this));
338 #if ENABLE(GEOLOCATION)
339 #if ENABLE(TIZEN_GEOLOCATION) && ENABLE(TIZEN_WEBKIT2_EFL_WTR)
340 if (WebProcess::shared().injectedBundle() && WebProcess::shared().injectedBundle()->testRunnerModeEnabled()) {
341 GeolocationClientMock* mock = new GeolocationClientMock();
342 WebCore::provideGeolocationTo(m_page.get(), mock);
343 mock->setController(WebCore::GeolocationController::from(m_page.get()));
345 #endif // ENABLE(TIZEN_GEOLOCATION) && ENABLE(TIZEN_WEBKIT2_EFL_WTR)
346 WebCore::provideGeolocationTo(m_page.get(), new WebGeolocationClient(this));
348 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(QT)
349 WebCore::provideDeviceMotionTo(m_page.get(), new DeviceMotionClientQt);
350 WebCore::provideDeviceOrientationTo(m_page.get(), new DeviceOrientationClientQt);
352 #if ENABLE(NETWORK_INFO)
353 WebCore::provideNetworkInfoTo(m_page.get(), new WebNetworkInfoClient(this));
355 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
356 WebCore::provideNotification(m_page.get(), new WebNotificationClient(this));
358 #if ENABLE(VIBRATION)
359 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
362 #if ENABLE(VIBRATION)
363 WebCore::provideVibrationTo(m_page.get(), new WebVibrationClient(this));
366 #if ENABLE(TIZEN_MEDIA_STREAM)
367 WebCore::provideUserMediaTo(m_page.get(), new WebUserMediaClient(this));
370 #if ENABLE(TIZEN_REGISTER_PROTOCOL_HANDLER) || ENABLE(TIZEN_CUSTOM_SCHEME_HANDLER)
371 WebCore::provideRegisterProtocolHandlerTo(m_page.get(), new WebRegisterProtocolHandlerClient(this));
374 #if ENABLE(TIZEN_REGISTER_CONTENT_HANDLER)
375 WebCore::provideRegisterContentHandlerTo(m_page.get(), new WebRegisterContentHandlerClient(this));
378 // Qt does not yet call setIsInWindow. Until it does, just leave
379 // this line out so plug-ins and video will work. Eventually all platforms
380 // should call setIsInWindow and this comment and #if should be removed,
381 // leaving behind the setCanStartMedia call.
383 m_page->setCanStartMedia(false);
386 updatePreferences(parameters.store);
388 m_pageGroup = WebProcess::shared().webPageGroup(parameters.pageGroupData);
389 m_page->setGroupName(m_pageGroup->identifier());
390 m_page->setDeviceScaleFactor(parameters.deviceScaleFactor);
392 platformInitialize();
394 m_drawingArea = DrawingArea::create(this, parameters);
395 m_drawingArea->setPaintingEnabled(false);
397 m_mainFrame = WebFrame::createMainFrame(this);
399 setUseFixedLayout(parameters.useFixedLayout);
401 setDrawsBackground(parameters.drawsBackground);
402 setDrawsTransparentBackground(parameters.drawsTransparentBackground);
404 setPaginationMode(parameters.paginationMode);
405 setPaginationBehavesLikeColumns(parameters.paginationBehavesLikeColumns);
406 setPageLength(parameters.pageLength);
407 setGapBetweenPages(parameters.gapBetweenPages);
409 setMemoryCacheMessagesEnabled(parameters.areMemoryCacheClientCallsEnabled);
411 setActive(parameters.isActive);
412 setFocused(parameters.isFocused);
413 setIsInWindow(parameters.isInWindow);
415 m_userAgent = parameters.userAgent;
417 WebBackForwardListProxy::setHighestItemIDFromUIProcess(parameters.highestUsedBackForwardItemID);
419 if (!parameters.sessionState.isEmpty())
420 restoreSession(parameters.sessionState);
422 m_drawingArea->setPaintingEnabled(true);
424 setMediaVolume(parameters.mediaVolume);
427 webPageCounter.increment();
433 if (m_backForwardList)
434 m_backForwardList->detach();
438 m_sandboxExtensionTracker.invalidate();
440 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
441 (*it)->webPageDestroyed();
444 webPageCounter.decrement();
448 void WebPage::dummy(bool&)
452 CoreIPC::Connection* WebPage::connection() const
454 return WebProcess::shared().connection();
457 #if ENABLE(CONTEXT_MENUS)
458 void WebPage::initializeInjectedBundleContextMenuClient(WKBundlePageContextMenuClient* client)
460 m_contextMenuClient.initialize(client);
464 void WebPage::initializeInjectedBundleEditorClient(WKBundlePageEditorClient* client)
466 m_editorClient.initialize(client);
469 void WebPage::initializeInjectedBundleFormClient(WKBundlePageFormClient* client)
471 m_formClient.initialize(client);
474 void WebPage::initializeInjectedBundleLoaderClient(WKBundlePageLoaderClient* client)
476 m_loaderClient.initialize(client);
479 void WebPage::initializeInjectedBundlePolicyClient(WKBundlePagePolicyClient* client)
481 m_policyClient.initialize(client);
484 void WebPage::initializeInjectedBundleResourceLoadClient(WKBundlePageResourceLoadClient* client)
486 m_resourceLoadClient.initialize(client);
489 void WebPage::initializeInjectedBundleUIClient(WKBundlePageUIClient* client)
491 m_uiClient.initialize(client);
494 #if ENABLE(FULLSCREEN_API)
495 void WebPage::initializeInjectedBundleFullScreenClient(WKBundlePageFullScreenClient* client)
497 m_fullScreenClient.initialize(client);
501 void WebPage::initializeInjectedBundleDiagnosticLoggingClient(WKBundlePageDiagnosticLoggingClient* client)
503 m_logDiagnosticMessageClient.initialize(client);
506 PassRefPtr<Plugin> WebPage::createPlugin(WebFrame* frame, HTMLPlugInElement* pluginElement, const Plugin::Parameters& parameters)
509 bool blocked = false;
511 if (!WebProcess::shared().connection()->sendSync(
512 Messages::WebContext::GetPluginPath(parameters.mimeType, parameters.url.string()),
513 Messages::WebContext::GetPluginPath::Reply(pluginPath, blocked), 0)) {
518 if (pluginElement->renderer()->isEmbeddedObject())
519 toRenderEmbeddedObject(pluginElement->renderer())->setPluginUnavailabilityReason(RenderEmbeddedObject::InsecurePluginVersion);
521 send(Messages::WebPageProxy::DidBlockInsecurePluginVersion(parameters.mimeType, parameters.url.string()));
525 if (pluginPath.isNull()) {
527 if (parameters.mimeType == "application/pdf"
528 || (parameters.mimeType.isEmpty() && parameters.url.path().lower().endsWith(".pdf")))
529 return BuiltInPDFView::create(frame);
536 #if ENABLE(PLUGIN_PROCESS)
537 return PluginProxy::create(pluginPath);
538 #elif ENABLE(NETSCAPE_PLUGIN_API)
539 NetscapePlugin::setSetExceptionFunction(NPRuntimeObjectMap::setGlobalException);
540 return NetscapePlugin::create(NetscapePluginModule::getOrCreate(pluginPath));
546 EditorState WebPage::editorState() const
548 Frame* frame = m_page->focusController()->focusedOrMainFrame();
552 result.selectionIsNone = frame->selection()->isNone();
553 result.selectionIsRange = frame->selection()->isRange();
554 result.isContentEditable = frame->selection()->isContentEditable();
555 result.isContentRichlyEditable = frame->selection()->isContentRichlyEditable();
556 result.isInPasswordField = frame->selection()->isInPasswordField();
557 result.hasComposition = frame->editor()->hasComposition();
558 result.shouldIgnoreCompositionSelectionChange = frame->editor()->ignoreCompositionSelectionChange();
560 #if ENABLE(TIZEN_WEBKIT2_GET_TEXT_STYLE_FOR_SELECTION)
561 if (!result.shouldIgnoreCompositionSelectionChange) {
562 result.underlineState = frame->editor()->selectionHasStyle(CSSPropertyWebkitTextDecorationsInEffect, "underline");
563 result.italicState = frame->editor()->selectionHasStyle(CSSPropertyFontStyle, "italic");
564 result.boldState = frame->editor()->selectionHasStyle(CSSPropertyFontWeight, "bold");
565 result.bgColor = frame->editor()->selectionStartCSSPropertyValue(CSSPropertyBackgroundColor);
566 result.color = frame->editor()->selectionStartCSSPropertyValue(CSSPropertyColor);
567 result.fontSize = frame->editor()->selectionStartCSSPropertyValue(CSSPropertyFontSize);
571 #if ENABLE(TIZEN_ISF_PORT) || ENABLE(TIZEN_WEBKIT2_TEXT_SELECTION)
572 Element* rootEditableElement = frame->selection()->rootEditableElement();
573 if (!rootEditableElement)
576 result.editorRect = nodeRect(rootEditableElement);
579 #if ENABLE(TIZEN_ISF_PORT)
580 result.isTapEventHandling = (currentEvent() && currentEvent()->type() == WebEvent::GestureSingleTap);
582 if (!result.shouldIgnoreCompositionSelectionChange && result.isContentEditable) {
583 result.inputMethodContextID = reinterpret_cast<uintptr_t>(rootEditableElement);
585 Node* hostNode = rootEditableElement->shadowHost();
587 hostNode = rootEditableElement;
589 HTMLTextFormControlElement* formControl = toTextFormControl(hostNode);
591 const AtomicString& type = formControl->type();
593 if (type == "number" && formControl->hasTagName(HTMLNames::inputTag)) {
594 StepRange stepRange = static_cast<HTMLInputElement*>(formControl)->createStepRange(RejectAny);
595 bool needsSigned = stepRange.minimum().isNegative();
596 bool needsDecimal = (stepRange.step().floor() != stepRange.step());
598 if (needsSigned && needsDecimal)
599 result.inputMethodHints = "signedDecimalNumber";
600 else if (needsSigned)
601 result.inputMethodHints = "signedNumber";
602 else if (needsDecimal)
603 result.inputMethodHints = "decimalNumber";
605 result.inputMethodHints = "number";
606 } else if (type == "text" && formControl->form() && equalIgnoringCase(formControl->form()->fastGetAttribute(HTMLNames::roleAttr), "search"))
607 result.inputMethodHints = "search";
609 result.inputMethodHints = type;
611 result.surroundingText = formControl->value();
614 Position base = frame->selection()->base();
615 Node* baseNode = base.containerNode();
617 result.cursorPosition = baseNode->isTextNode() ? base.offsetInContainerNode() : 0;
625 Element* selectionRoot = frame->selection()->rootEditableElement();
626 Element* scope = selectionRoot ? selectionRoot : frame->document()->documentElement();
631 if (scope->hasTagName(HTMLNames::inputTag)) {
632 HTMLInputElement* input = static_cast<HTMLInputElement*>(scope);
633 if (input->isTelephoneField())
634 result.inputMethodHints |= Qt::ImhDialableCharactersOnly;
635 else if (input->isNumberField())
636 result.inputMethodHints |= Qt::ImhDigitsOnly;
637 else if (input->isEmailField()) {
638 result.inputMethodHints |= Qt::ImhEmailCharactersOnly;
639 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
640 } else if (input->isURLField()) {
641 result.inputMethodHints |= Qt::ImhUrlCharactersOnly;
642 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
643 } else if (input->isPasswordField()) {
644 // Set ImhHiddenText flag for password fields. The Qt platform
645 // is responsible for determining which widget will receive input
646 // method events for password fields.
647 result.inputMethodHints |= Qt::ImhHiddenText;
648 result.inputMethodHints |= Qt::ImhNoAutoUppercase;
649 result.inputMethodHints |= Qt::ImhNoPredictiveText;
650 result.inputMethodHints |= Qt::ImhSensitiveData;
655 result.editorRect = frame->view()->contentsToWindow(selectionRoot->getPixelSnappedRect());
658 if (result.hasComposition && (range = frame->editor()->compositionRange())) {
659 frame->editor()->getCompositionSelection(result.anchorPosition, result.cursorPosition);
661 result.compositionRect = frame->view()->contentsToWindow(range->boundingBox());
664 if (!result.hasComposition && !result.selectionIsNone && (range = frame->selection()->selection().firstRange())) {
665 TextIterator::getLocationAndLengthFromRange(scope, range.get(), location, length);
666 bool baseIsFirst = frame->selection()->selection().isBaseFirst();
668 result.cursorPosition = (baseIsFirst) ? location + length : location;
669 result.anchorPosition = (baseIsFirst) ? location : location + length;
670 result.selectedText = range->text();
674 result.cursorRect = frame->view()->contentsToWindow(frame->editor()->firstRectForRange(range.get()));
676 // FIXME: We should only transfer innerText when it changes and do this on the UI side.
677 if (result.isContentEditable && !result.isInPasswordField) {
678 result.surroundingText = scope->innerText();
679 if (result.hasComposition) {
680 // The anchor is always the left position when they represent a composition.
681 result.surroundingText.remove(result.anchorPosition, result.cursorPosition - result.anchorPosition);
689 String WebPage::renderTreeExternalRepresentation() const
691 return externalRepresentation(m_mainFrame->coreFrame(), RenderAsTextBehaviorNormal);
694 uint64_t WebPage::renderTreeSize() const
698 return m_page->renderTreeSize().treeSize;
701 void WebPage::setPaintedObjectsCounterThreshold(uint64_t threshold)
705 m_page->setRelevantRepaintedObjectsCounterThreshold(threshold);
708 void WebPage::setTracksRepaints(bool trackRepaints)
710 if (FrameView* view = mainFrameView())
711 view->setTracksRepaints(trackRepaints);
714 bool WebPage::isTrackingRepaints() const
716 if (FrameView* view = mainFrameView())
717 return view->isTrackingRepaints();
722 void WebPage::resetTrackedRepaints()
724 if (FrameView* view = mainFrameView())
725 view->resetTrackedRepaints();
728 PassRefPtr<ImmutableArray> WebPage::trackedRepaintRects()
730 FrameView* view = mainFrameView();
732 return ImmutableArray::create();
734 const Vector<IntRect>& rects = view->trackedRepaintRects();
735 size_t size = rects.size();
737 return ImmutableArray::create();
739 Vector<RefPtr<APIObject> > vector;
740 vector.reserveInitialCapacity(size);
742 for (size_t i = 0; i < size; ++i)
743 vector.uncheckedAppend(WebRect::create(toAPI(rects[i])));
745 return ImmutableArray::adopt(vector);
748 void WebPage::executeEditingCommand(const String& commandName, const String& argument)
750 Frame* frame = m_page->focusController()->focusedOrMainFrame();
753 frame->editor()->command(commandName).execute(argument);
756 bool WebPage::isEditingCommandEnabled(const String& commandName)
758 Frame* frame = m_page->focusController()->focusedOrMainFrame();
762 Editor::Command command = frame->editor()->command(commandName);
763 return command.isSupported() && command.isEnabled();
766 void WebPage::clearMainFrameName()
768 if (Frame* frame = mainFrame())
769 frame->tree()->clearName();
772 #if USE(ACCELERATED_COMPOSITING)
773 void WebPage::enterAcceleratedCompositingMode(GraphicsLayer* layer)
775 m_drawingArea->setRootCompositingLayer(layer);
778 void WebPage::exitAcceleratedCompositingMode()
780 m_drawingArea->setRootCompositingLayer(0);
784 void WebPage::close()
791 if (pageGroup()->isVisibleToInjectedBundle() && WebProcess::shared().injectedBundle())
792 WebProcess::shared().injectedBundle()->willDestroyPage(this);
794 #if ENABLE(INSPECTOR)
797 #if ENABLE(FULLSCREEN_API)
798 m_fullScreenManager = 0;
801 if (m_activePopupMenu) {
802 m_activePopupMenu->disconnectFromPage();
803 m_activePopupMenu = 0;
806 if (m_activeOpenPanelResultListener) {
807 m_activeOpenPanelResultListener->disconnectFromPage();
808 m_activeOpenPanelResultListener = 0;
811 #if ENABLE(INPUT_TYPE_COLOR)
812 if (m_activeColorChooser) {
813 m_activeColorChooser->disconnectFromPage();
814 m_activeColorChooser = 0;
818 m_sandboxExtensionTracker.invalidate();
820 m_underlayPage = nullptr;
821 m_printContext = nullptr;
822 m_mainFrame->coreFrame()->loader()->detachFromParent();
824 m_drawingArea = nullptr;
826 bool isRunningModal = m_isRunningModal;
827 m_isRunningModal = false;
829 // The WebPage can be destroyed by this call.
830 WebProcess::shared().removeWebPage(m_pageID);
833 WebProcess::shared().runLoop()->stop();
836 void WebPage::tryClose()
838 SendStopResponsivenessTimer stopper(this);
840 if (!m_mainFrame->coreFrame()->loader()->shouldClose()) {
841 send(Messages::WebPageProxy::StopResponsivenessTimer());
845 send(Messages::WebPageProxy::ClosePage(true));
848 void WebPage::sendClose()
850 send(Messages::WebPageProxy::ClosePage(false));
853 void WebPage::loadURL(const String& url, const SandboxExtension::Handle& sandboxExtensionHandle)
855 loadURLRequest(ResourceRequest(KURL(KURL(), url)), sandboxExtensionHandle);
858 void WebPage::loadURLRequest(const ResourceRequest& request, const SandboxExtension::Handle& sandboxExtensionHandle)
860 SendStopResponsivenessTimer stopper(this);
862 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
863 m_mainFrame->coreFrame()->loader()->load(request, false);
866 void WebPage::loadData(PassRefPtr<SharedBuffer> sharedBuffer, const String& MIMEType, const String& encodingName, const KURL& baseURL, const KURL& unreachableURL)
868 SendStopResponsivenessTimer stopper(this);
870 ResourceRequest request(baseURL);
871 SubstituteData substituteData(sharedBuffer, MIMEType, encodingName, unreachableURL);
872 m_mainFrame->coreFrame()->loader()->load(request, substituteData, false);
875 void WebPage::loadHTMLString(const String& htmlString, const String& baseURLString)
877 #if ENABLE(TIZEN_LOAD_HTML_STRING_AS_UTF8)
878 CString html = htmlString.utf8();
879 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(html.data()), html.length());
880 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
881 loadData(sharedBuffer, "text/html", "utf-8", baseURL, KURL());
883 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
884 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
885 loadData(sharedBuffer, "text/html", "utf-16", baseURL, KURL());
889 void WebPage::loadAlternateHTMLString(const String& htmlString, const String& baseURLString, const String& unreachableURLString)
891 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(htmlString.characters()), htmlString.length() * sizeof(UChar));
892 KURL baseURL = baseURLString.isEmpty() ? blankURL() : KURL(KURL(), baseURLString);
893 KURL unreachableURL = unreachableURLString.isEmpty() ? KURL() : KURL(KURL(), unreachableURLString);
894 loadData(sharedBuffer, "text/html", "utf-16", baseURL, unreachableURL);
897 void WebPage::loadPlainTextString(const String& string)
899 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(string.characters()), string.length() * sizeof(UChar));
900 loadData(sharedBuffer, "text/plain", "utf-16", blankURL(), KURL());
903 void WebPage::loadWebArchiveData(const CoreIPC::DataReference& webArchiveData)
905 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(webArchiveData.data()), webArchiveData.size() * sizeof(uint8_t));
906 loadData(sharedBuffer, "application/x-webarchive", "utf-16", blankURL(), KURL());
910 void WebPage::loadContentsbyMimeType(const CoreIPC::DataReference& contents, const String& mimeType, const String& encoding, const String& baseURL)
912 RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(reinterpret_cast<const char*>(contents.data()), contents.size() * sizeof(uint8_t));
913 KURL baseKURL(WebCore::KURL(), baseURL);
914 loadData(sharedBuffer, mimeType, encoding, baseKURL, KURL());
918 void WebPage::linkClicked(const String& url, const WebMouseEvent& event)
920 Frame* frame = m_page->mainFrame();
924 RefPtr<Event> coreEvent;
925 if (event.type() != WebEvent::NoType)
926 coreEvent = MouseEvent::create(eventNames().clickEvent, frame->document()->defaultView(), platform(event), 0, 0);
928 frame->loader()->loadFrameRequest(FrameLoadRequest(frame->document()->securityOrigin(), ResourceRequest(url)),
929 false, false, coreEvent.get(), 0, MaybeSendReferrer);
932 void WebPage::stopLoadingFrame(uint64_t frameID)
934 WebFrame* frame = WebProcess::shared().webFrame(frameID);
938 frame->coreFrame()->loader()->stopForUserCancel();
941 void WebPage::stopLoading()
943 SendStopResponsivenessTimer stopper(this);
945 m_mainFrame->coreFrame()->loader()->stopForUserCancel();
948 void WebPage::setDefersLoading(bool defersLoading)
950 m_page->setDefersLoading(defersLoading);
953 void WebPage::reload(bool reloadFromOrigin, const SandboxExtension::Handle& sandboxExtensionHandle)
955 SendStopResponsivenessTimer stopper(this);
957 m_sandboxExtensionTracker.beginLoad(m_mainFrame.get(), sandboxExtensionHandle);
958 m_mainFrame->coreFrame()->loader()->reload(reloadFromOrigin);
961 void WebPage::goForward(uint64_t backForwardItemID)
963 SendStopResponsivenessTimer stopper(this);
965 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
970 m_page->goToItem(item, FrameLoadTypeForward);
973 void WebPage::goBack(uint64_t backForwardItemID)
975 SendStopResponsivenessTimer stopper(this);
977 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
982 m_page->goToItem(item, FrameLoadTypeBack);
985 void WebPage::goToBackForwardItem(uint64_t backForwardItemID)
987 SendStopResponsivenessTimer stopper(this);
989 HistoryItem* item = WebBackForwardListProxy::itemForID(backForwardItemID);
994 m_page->goToItem(item, FrameLoadTypeIndexedBackForward);
997 void WebPage::tryRestoreScrollPosition()
999 m_page->mainFrame()->loader()->history()->restoreScrollPositionAndViewState();
1002 void WebPage::layoutIfNeeded()
1004 if (m_mainFrame->coreFrame()->view())
1005 m_mainFrame->coreFrame()->view()->updateLayoutAndStyleIfNeededRecursive();
1007 if (m_underlayPage) {
1008 if (FrameView *frameView = m_underlayPage->mainFrameView())
1009 frameView->updateLayoutAndStyleIfNeededRecursive();
1013 void WebPage::setSize(const WebCore::IntSize& viewSize)
1015 FrameView* view = m_page->mainFrame()->view();
1017 #if USE(TILED_BACKING_STORE)
1018 // If we are resizing to content ignore external attempts.
1019 if (view->useFixedLayout())
1023 if (m_viewSize == viewSize)
1026 view->resize(viewSize);
1027 view->setNeedsLayout();
1028 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), viewSize));
1030 m_viewSize = viewSize;
1033 #if USE(TILED_BACKING_STORE)
1034 void WebPage::setFixedVisibleContentRect(const IntRect& rect)
1036 ASSERT(m_useFixedLayout);
1038 m_page->mainFrame()->view()->setFixedVisibleContentRect(rect);
1041 void WebPage::setResizesToContentsUsingLayoutSize(const IntSize& targetLayoutSize)
1043 ASSERT(m_useFixedLayout);
1044 ASSERT(!targetLayoutSize.isEmpty());
1046 FrameView* view = m_page->mainFrame()->view();
1048 view->setDelegatesScrolling(true);
1049 view->setUseFixedLayout(true);
1050 view->setPaintsEntireContents(true);
1052 if (view->fixedLayoutSize() == targetLayoutSize)
1055 m_page->settings()->setAcceleratedCompositingForFixedPositionEnabled(true);
1056 m_page->settings()->setFixedElementsLayoutRelativeToFrame(true);
1057 m_page->settings()->setFixedPositionCreatesStackingContext(true);
1059 // Always reset even when empty. This also takes care of the relayout.
1060 setFixedLayoutSize(targetLayoutSize);
1063 void WebPage::resizeToContentsIfNeeded()
1065 ASSERT(m_useFixedLayout);
1067 FrameView* view = m_page->mainFrame()->view();
1069 if (!view->useFixedLayout())
1072 IntSize newSize = view->contentsSize().expandedTo(view->fixedLayoutSize());
1074 if (newSize == m_viewSize)
1077 m_viewSize = newSize;
1078 view->resize(newSize);
1079 view->setNeedsLayout();
1082 void WebPage::sendViewportAttributesChanged()
1084 ASSERT(m_useFixedLayout);
1086 // Viewport properties have no impact on zero sized fixed viewports.
1087 if (m_viewportSize.isEmpty())
1090 // Recalculate the recommended layout size, when the available size (device pixel) changes.
1091 Settings* settings = m_page->settings();
1094 #if ENABLE(TIZEN_DLOG_SUPPORT)
1095 TIZEN_LOGI(" args type: [%d], scale: [%.1f, %.1f, %.1f], layout: [%.1f, %.1f], userScalable: [%.1f]"
1096 , static_cast<int>(m_page->viewportArguments().type), m_page->viewportArguments().initialScale
1097 , m_page->viewportArguments().minimumScale, m_page->viewportArguments().maximumScale
1098 , m_page->viewportArguments().width, m_page->viewportArguments().height, m_page->viewportArguments().userScalable);
1101 // As android and iphone does, we set layout width to 980 for desktop content
1102 int minimumLayoutFallbackWidth = settings->layoutFallbackWidth();
1104 int minimumLayoutFallbackWidth = std::max(settings->layoutFallbackWidth(), m_viewportSize.width());
1107 // If unset we use the viewport dimensions. This fits with the behavior of desktop browsers.
1108 int deviceWidth = (settings->deviceWidth() > 0) ? settings->deviceWidth() : m_viewportSize.width();
1109 int deviceHeight = (settings->deviceHeight() > 0) ? settings->deviceHeight() : m_viewportSize.height();
1111 ViewportAttributes attr = computeViewportAttributes(m_page->viewportArguments(), minimumLayoutFallbackWidth, deviceWidth, deviceHeight, m_page->deviceScaleFactor(), m_viewportSize);
1112 WebCore::restrictMinimumScaleFactorToViewportSize(attr, m_viewportSize);
1113 WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(attr);
1115 #if ENABLE(TIZEN_VIEWPORT_META_TAG)
1116 // On WebProcess, JS runs before visible content rect is updated by UIProcess
1117 // In this case, JS returns incorrect inner size value because scale factor is not updated yet
1118 // So, we update fixed visible content rect at here.
1119 // FIXME: scale factor needs to be calculated and set fixed visible content rect
1121 // if constrainsScrollingToContentEdge is true, scroll position will be adjusted with contents size.
1122 // disable this to avoid adjust scroll position on setFixedVisibleContentRect() because contents size is not fixed yet.
1123 bool constrainsScrollingToContentEdge = mainFrameView()->constrainsScrollingToContentEdge();
1124 mainFrameView()->setConstrainsScrollingToContentEdge(false);
1126 FloatSize contentFixedSize = m_viewportSize;
1127 contentFixedSize.scale(1 / (attr.initialScale * attr.devicePixelRatio));
1128 mainFrameView()->setFixedVisibleContentRect(IntRect(mainFrameView()->scrollPosition(), roundedIntSize(contentFixedSize)));
1130 // If viewport meta tag is not defined or initial scale factor is not defined,
1131 // initial scale factor can be defined by "Default View" setting of UIProcess.
1132 // Therefore we set initialScale as ValueAuto as WebKit opensource does, to handle it with setting on UIProcess.
1133 // You can find this implementation on WebKit bug.
1134 // https://bugs.webkit.org/show_bug.cgi?id=102392
1135 if (m_page->viewportArguments().type == ViewportArguments::Implicit
1136 || m_page->viewportArguments().initialScale == ViewportArguments::ValueAuto)
1137 attr.initialScale = ViewportArguments::ValueAuto;
1140 setResizesToContentsUsingLayoutSize(IntSize(static_cast<int>(attr.layoutSize.width()), static_cast<int>(attr.layoutSize.height())));
1142 #if ENABLE(TIZEN_VIEWPORT_META_TAG)
1143 // recover constrainsScrollingToContentEdge
1144 mainFrameView()->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge);
1147 send(Messages::WebPageProxy::DidChangeViewportProperties(attr));
1150 void WebPage::setViewportSize(const IntSize& size)
1152 ASSERT(m_useFixedLayout);
1154 if (m_viewportSize == size)
1157 #if ENABLE(TIZEN_DLOG_SUPPORT)
1158 TIZEN_LOGI(" viewportSize: [%d, %d]", size.width(), size.height());
1161 m_viewportSize = size;
1163 sendViewportAttributesChanged();
1168 void WebPage::scrollMainFrameIfNotAtMaxScrollPosition(const IntSize& scrollOffset)
1170 Frame* frame = m_page->mainFrame();
1172 IntPoint scrollPosition = frame->view()->scrollPosition();
1173 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
1175 // If the current scroll position in a direction is the max scroll position
1176 // we don't want to scroll at all.
1177 IntSize newScrollOffset;
1178 if (scrollPosition.x() < maximumScrollPosition.x())
1179 newScrollOffset.setWidth(scrollOffset.width());
1180 if (scrollPosition.y() < maximumScrollPosition.y())
1181 newScrollOffset.setHeight(scrollOffset.height());
1183 if (newScrollOffset.isZero())
1186 frame->view()->setScrollPosition(frame->view()->scrollPosition() + newScrollOffset);
1189 void WebPage::drawRect(GraphicsContext& graphicsContext, const IntRect& rect)
1191 GraphicsContextStateSaver stateSaver(graphicsContext);
1192 graphicsContext.clip(rect);
1194 if (m_underlayPage) {
1195 m_underlayPage->drawRect(graphicsContext, rect);
1197 graphicsContext.beginTransparencyLayer(1);
1198 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1199 graphicsContext.endTransparencyLayer();
1203 m_mainFrame->coreFrame()->view()->paint(&graphicsContext, rect);
1206 #if ENABLE(TIZEN_WEBKIT2_CONTEXT_MENU_TEXT_SELECTION_MODE)
1207 void WebPage::selectLink(WebCore::IntPoint positionForSelection, bool& result)
1210 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1214 FrameView* frameView = frame->view();
1218 HitTestResult hitTestResult = frame->eventHandler()->hitTestResultAtPoint(frameView->windowToContents(positionForSelection), false);
1220 RefPtr<Range> range;
1221 Element* URLElement = hitTestResult.URLElement();
1223 for (Node* childNode = URLElement->firstChild(); childNode; childNode = childNode->traverseNextNode(URLElement)) {
1224 RenderObject* r = childNode->renderer();
1225 if (r && (r->isText() || r->isImage())) {
1227 range = VisibleSelection::selectionFromContentsOfNode(childNode).toNormalizedRange();
1228 else if (!hitTestResult.image()) {
1229 RefPtr<Range> extendedRange = VisibleSelection::selectionFromContentsOfNode(childNode).toNormalizedRange();
1230 range->setEnd(childNode, extendedRange->endOffset());
1235 range = VisibleSelection::selectionFromContentsOfNode(URLElement).toNormalizedRange();
1237 range = VisibleSelection::selectionFromContentsOfNode(hitTestResult.innerNonSharedNode()).toNormalizedRange();
1239 WebCore::FrameSelection* frameSelection = frame->selection();
1240 if (!frameSelection)
1243 EAffinity affinity = frameSelection->affinity();
1244 frameSelection->setSelectedRange(range.get(), affinity, true);
1246 if (frameSelection->isRange())
1253 #if ENABLE(TIZEN_ORIENTATION_EVENTS)
1254 void WebPage::sendOrientationChangeEvent(int newOrientation)
1256 Frame* frame = m_mainFrame->coreFrame();
1257 if (!frame || frame->orientation() == newOrientation)
1260 frame->sendOrientationChangeEvent(newOrientation);
1261 for (WebCore::Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
1262 child->sendOrientationChangeEvent(newOrientation);
1266 void WebPage::drawPageOverlay(GraphicsContext& graphicsContext, const IntRect& rect)
1268 ASSERT(m_pageOverlay);
1270 GraphicsContextStateSaver stateSaver(graphicsContext);
1271 graphicsContext.clip(rect);
1272 m_pageOverlay->drawRect(graphicsContext, rect);
1275 double WebPage::textZoomFactor() const
1277 Frame* frame = m_mainFrame->coreFrame();
1280 return frame->textZoomFactor();
1283 void WebPage::setTextZoomFactor(double zoomFactor)
1285 Frame* frame = m_mainFrame->coreFrame();
1288 frame->setTextZoomFactor(static_cast<float>(zoomFactor));
1291 double WebPage::pageZoomFactor() const
1293 Frame* frame = m_mainFrame->coreFrame();
1296 return frame->pageZoomFactor();
1299 void WebPage::setPageZoomFactor(double zoomFactor)
1301 Frame* frame = m_mainFrame->coreFrame();
1304 frame->setPageZoomFactor(static_cast<float>(zoomFactor));
1307 void WebPage::setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor)
1309 Frame* frame = m_mainFrame->coreFrame();
1312 return frame->setPageAndTextZoomFactors(static_cast<float>(pageZoomFactor), static_cast<float>(textZoomFactor));
1315 void WebPage::windowScreenDidChange(uint64_t displayID)
1317 m_page->windowScreenDidChange(static_cast<PlatformDisplayID>(displayID));
1320 void WebPage::setViewMode(Page::ViewMode mode)
1322 m_page->setViewMode(mode);
1325 void WebPage::scalePage(double scale, const IntPoint& origin)
1327 m_page->setPageScaleFactor(scale, origin);
1329 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1330 (*it)->pageScaleFactorDidChange();
1332 send(Messages::WebPageProxy::PageScaleFactorDidChange(scale));
1335 double WebPage::pageScaleFactor() const
1337 return m_page->pageScaleFactor();
1340 void WebPage::setDeviceScaleFactor(float scaleFactor)
1342 if (scaleFactor == m_page->deviceScaleFactor())
1345 m_page->setDeviceScaleFactor(scaleFactor);
1347 // Tell all our plug-in views that the device scale factor changed.
1349 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
1350 (*it)->setDeviceScaleFactor(scaleFactor);
1353 if (m_findController.isShowingOverlay()) {
1354 // We must have updated layout to get the selection rects right.
1356 m_findController.deviceScaleFactorDidChange();
1360 float WebPage::deviceScaleFactor() const
1362 return m_page->deviceScaleFactor();
1365 void WebPage::setUseFixedLayout(bool fixed)
1367 m_useFixedLayout = fixed;
1369 FrameView* view = mainFrameView();
1373 view->setUseFixedLayout(fixed);
1375 setFixedLayoutSize(IntSize());
1378 void WebPage::setFixedLayoutSize(const IntSize& size)
1380 FrameView* view = mainFrameView();
1381 if (!view || view->fixedLayoutSize() == size)
1384 view->setFixedLayoutSize(size);
1385 // Do not force it until the first layout, this would then become our first layout prematurely.
1386 if (view->didFirstLayout())
1387 view->forceLayout();
1390 void WebPage::setPaginationMode(uint32_t mode)
1392 Page::Pagination pagination = m_page->pagination();
1393 pagination.mode = static_cast<Page::Pagination::Mode>(mode);
1394 m_page->setPagination(pagination);
1397 void WebPage::setPaginationBehavesLikeColumns(bool behavesLikeColumns)
1399 Page::Pagination pagination = m_page->pagination();
1400 pagination.behavesLikeColumns = behavesLikeColumns;
1401 m_page->setPagination(pagination);
1404 void WebPage::setPageLength(double pageLength)
1406 Page::Pagination pagination = m_page->pagination();
1407 pagination.pageLength = pageLength;
1408 m_page->setPagination(pagination);
1411 void WebPage::setGapBetweenPages(double gap)
1413 Page::Pagination pagination = m_page->pagination();
1414 pagination.gap = gap;
1415 m_page->setPagination(pagination);
1418 void WebPage::installPageOverlay(PassRefPtr<PageOverlay> pageOverlay)
1420 bool shouldFadeIn = true;
1422 if (m_pageOverlay) {
1423 m_pageOverlay->setPage(0);
1426 // We're installing a page overlay when a page overlay is already active.
1427 // In this case we don't want to fade in the new overlay.
1428 shouldFadeIn = false;
1432 m_pageOverlay = pageOverlay;
1433 m_pageOverlay->setPage(this);
1436 m_pageOverlay->startFadeInAnimation();
1438 m_drawingArea->didInstallPageOverlay();
1440 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(true));
1443 m_pageOverlay->setNeedsDisplay();
1446 void WebPage::uninstallPageOverlay(PageOverlay* pageOverlay, bool fadeOut)
1448 if (pageOverlay != m_pageOverlay)
1452 m_pageOverlay->startFadeOutAnimation();
1456 m_pageOverlay->setPage(0);
1457 m_pageOverlay = nullptr;
1459 m_drawingArea->didUninstallPageOverlay();
1461 send(Messages::WebPageProxy::DidInstallOrUninstallPageOverlay(false));
1465 #if PLATFORM(EFL) && OS(TIZEN)
1466 PassRefPtr<WebImage> WebPage::scaledSnapshotInViewCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1468 FrameView* frameView = m_mainFrame->coreFrame()->view();
1472 IntSize size(ceil(rect.width() * scaleFactor), ceil(rect.height() * scaleFactor));
1473 RefPtr<WebImage> snapshot = WebImage::create(size, options);
1474 if (!snapshot->bitmap())
1477 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1478 graphicsContext->scale(FloatSize(scaleFactor, scaleFactor));
1479 graphicsContext->translate(-rect.x(), -rect.y());
1481 frameView->updateLayoutAndStyleIfNeededRecursive();
1483 PaintBehavior oldBehavior = frameView->paintBehavior();
1484 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1485 frameView->paint(graphicsContext.get(), rect);
1486 frameView->setPaintBehavior(oldBehavior);
1488 return snapshot.release();
1491 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1493 return scaledSnapshotInViewCoordinates(rect, 1, options);
1496 PassRefPtr<WebImage> WebPage::snapshotInViewCoordinates(const IntRect& rect, ImageOptions options)
1498 FrameView* frameView = m_mainFrame->coreFrame()->view();
1502 IntSize bitmapSize = rect.size();
1503 float deviceScaleFactor = corePage()->deviceScaleFactor();
1504 bitmapSize.scale(deviceScaleFactor);
1506 RefPtr<WebImage> snapshot = WebImage::create(bitmapSize, options);
1507 if (!snapshot->bitmap())
1510 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1511 graphicsContext->applyDeviceScaleFactor(deviceScaleFactor);
1512 graphicsContext->translate(-rect.x(), -rect.y());
1514 frameView->updateLayoutAndStyleIfNeededRecursive();
1516 PaintBehavior oldBehavior = frameView->paintBehavior();
1517 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1518 frameView->paint(graphicsContext.get(), rect);
1519 frameView->setPaintBehavior(oldBehavior);
1521 return snapshot.release();
1525 PassRefPtr<WebImage> WebPage::scaledSnapshotInDocumentCoordinates(const IntRect& rect, double scaleFactor, ImageOptions options)
1527 FrameView* frameView = m_mainFrame->coreFrame()->view();
1531 float combinedScaleFactor = scaleFactor * corePage()->deviceScaleFactor();
1532 IntSize size(ceil(rect.width() * combinedScaleFactor), ceil(rect.height() * combinedScaleFactor));
1533 RefPtr<WebImage> snapshot = WebImage::create(size, options);
1534 if (!snapshot->bitmap())
1537 OwnPtr<WebCore::GraphicsContext> graphicsContext = snapshot->bitmap()->createGraphicsContext();
1538 graphicsContext->applyDeviceScaleFactor(combinedScaleFactor);
1539 graphicsContext->translate(-rect.x(), -rect.y());
1541 frameView->updateLayoutAndStyleIfNeededRecursive();
1543 PaintBehavior oldBehavior = frameView->paintBehavior();
1544 frameView->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
1545 frameView->paintContents(graphicsContext.get(), rect);
1546 frameView->setPaintBehavior(oldBehavior);
1548 return snapshot.release();
1551 PassRefPtr<WebImage> WebPage::snapshotInDocumentCoordinates(const IntRect& rect, ImageOptions options)
1553 return scaledSnapshotInDocumentCoordinates(rect, 1, options);
1556 void WebPage::pageDidScroll()
1558 m_uiClient.pageDidScroll(this);
1560 send(Messages::WebPageProxy::PageDidScroll());
1563 #if USE(TILED_BACKING_STORE)
1564 void WebPage::pageDidRequestScroll(const IntPoint& point)
1566 #if ENABLE(TIZEN_DLOG_SUPPORT)
1567 TIZEN_LOGI(" scroll position: [%d, %d]", point.x(), point.y());
1569 send(Messages::WebPageProxy::PageDidRequestScroll(point));
1573 #if ENABLE(TIZEN_WEBKIT2_HISTORICAL_RESTORE_VISIBLE_CONTENT_RECT)
1574 void WebPage::pageDidRequestRestoreVisibleContentRect(const IntPoint& point, float scale)
1576 #if ENABLE(TIZEN_DLOG_SUPPORT)
1577 TIZEN_LOGI(" scale factor: [%.2f], scroll position: [%d, %d]", scale, point.x(), point.y());
1579 send(Messages::WebPageProxy::pageDidRequestRestoreVisibleContentRect(point, scale));
1583 #if ENABLE(CONTEXT_MENUS)
1584 WebContextMenu* WebPage::contextMenu()
1587 m_contextMenu = WebContextMenu::create(this);
1588 return m_contextMenu.get();
1594 static const WebEvent* g_currentEvent = 0;
1596 // FIXME: WebPage::currentEvent is used by the plug-in code to avoid having to convert from DOM events back to
1597 // WebEvents. When we get the event handling sorted out, this should go away and the Widgets should get the correct
1598 // platform events passed to the event handler code.
1599 const WebEvent* WebPage::currentEvent()
1601 return g_currentEvent;
1604 class CurrentEvent {
1606 explicit CurrentEvent(const WebEvent& event)
1607 : m_previousCurrentEvent(g_currentEvent)
1609 g_currentEvent = &event;
1614 g_currentEvent = m_previousCurrentEvent;
1618 const WebEvent* m_previousCurrentEvent;
1621 #if ENABLE(CONTEXT_MENUS)
1622 static bool isContextClick(const PlatformMouseEvent& event)
1624 if (event.button() == WebCore::RightButton)
1628 // FIXME: this really should be about OSX-style UI, not about the Mac port
1629 if (event.button() == WebCore::LeftButton && event.ctrlKey())
1636 static bool handleContextMenuEvent(const PlatformMouseEvent& platformMouseEvent, WebPage* page)
1638 IntPoint point = page->corePage()->mainFrame()->view()->windowToContents(platformMouseEvent.position());
1639 HitTestResult result = page->corePage()->mainFrame()->eventHandler()->hitTestResultAtPoint(point, false);
1641 Frame* frame = page->corePage()->mainFrame();
1642 #if !ENABLE(TIZEN_CONTEXT_MENU_WEBKIT_2)
1643 if (result.innerNonSharedNode())
1644 frame = result.innerNonSharedNode()->document()->frame();
1647 bool handled = frame->eventHandler()->sendContextMenuEvent(platformMouseEvent);
1649 page->contextMenu()->show();
1651 #if ENABLE(TIZEN_DRAG_SUPPORT)
1652 if(result.isDragSupport()) {
1653 if (result.innerNonSharedNode())
1654 frame = result.innerNonSharedNode()->document()->frame();
1656 PlatformMouseEvent event(frame->view()->windowToContents(platformMouseEvent.position()), platformMouseEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1, false, false, false, false, currentTime());
1657 frame->page()->dragController()->setPosition(event);
1665 static bool handleMouseEvent(const WebMouseEvent& mouseEvent, WebPage* page, bool onlyUpdateScrollbars)
1667 Frame* frame = page->corePage()->mainFrame();
1671 PlatformMouseEvent platformMouseEvent = platform(mouseEvent);
1673 switch (platformMouseEvent.type()) {
1674 case PlatformEvent::MousePressed: {
1675 #if ENABLE(CONTEXT_MENUS)
1676 if (isContextClick(platformMouseEvent))
1677 page->corePage()->contextMenuController()->clearContextMenu();
1680 #if ENABLE(TIZEN_CONTEXT_MENU_WEBKIT_2)
1682 if (!isContextClick(platformMouseEvent))
1683 handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1685 bool handled = frame->eventHandler()->handleMousePressEvent(platformMouseEvent);
1687 #if ENABLE(CONTEXT_MENUS)
1688 if (isContextClick(platformMouseEvent))
1689 handled = handleContextMenuEvent(platformMouseEvent, page);
1692 bool gtkMouseButtonPressHandled = page->handleMousePressedEvent(platformMouseEvent);
1693 handled = handled || gtkMouseButtonPressHandled;
1698 case PlatformEvent::MouseReleased:
1699 return frame->eventHandler()->handleMouseReleaseEvent(platformMouseEvent);
1700 case PlatformEvent::MouseMoved:
1701 if (onlyUpdateScrollbars)
1702 return frame->eventHandler()->passMouseMovedEventToScrollbars(platformMouseEvent);
1703 return frame->eventHandler()->mouseMoved(platformMouseEvent);
1705 ASSERT_NOT_REACHED();
1710 void WebPage::mouseEvent(const WebMouseEvent& mouseEvent)
1712 #if ENABLE(CONTEXT_MENUS)
1713 // Don't try to handle any pending mouse events if a context menu is showing.
1714 if (m_isShowingContextMenu) {
1715 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), false));
1720 bool handled = false;
1722 if (m_pageOverlay) {
1723 // Let the page overlay handle the event.
1724 handled = m_pageOverlay->mouseEvent(mouseEvent);
1728 CurrentEvent currentEvent(mouseEvent);
1730 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1731 // button is currently pressed. It is possible that neither of those things will be true since on
1732 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1733 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1734 // efficient scrollbars-only version of the event.
1735 bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1736 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1739 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(mouseEvent.type()), handled));
1742 void WebPage::mouseEventSyncForTesting(const WebMouseEvent& mouseEvent, bool& handled)
1744 handled = m_pageOverlay && m_pageOverlay->mouseEvent(mouseEvent);
1747 CurrentEvent currentEvent(mouseEvent);
1749 // We need to do a full, normal hit test during this mouse event if the page is active or if a mouse
1750 // button is currently pressed. It is possible that neither of those things will be true since on
1751 // Lion when legacy scrollbars are enabled, WebKit receives mouse events all the time. If it is one
1752 // of those cases where the page is not active and the mouse is not pressed, then we can fire a more
1753 // efficient scrollbars-only version of the event.
1754 bool onlyUpdateScrollbars = !(m_page->focusController()->isActive() || (mouseEvent.button() != WebMouseEvent::NoButton));
1755 handled = handleMouseEvent(mouseEvent, this, onlyUpdateScrollbars);
1759 static bool handleWheelEvent(const WebWheelEvent& wheelEvent, Page* page)
1761 Frame* frame = page->mainFrame();
1765 PlatformWheelEvent platformWheelEvent = platform(wheelEvent);
1766 return frame->eventHandler()->handleWheelEvent(platformWheelEvent);
1769 void WebPage::wheelEvent(const WebWheelEvent& wheelEvent)
1771 CurrentEvent currentEvent(wheelEvent);
1773 bool handled = handleWheelEvent(wheelEvent, m_page.get());
1774 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(wheelEvent.type()), handled));
1777 void WebPage::wheelEventSyncForTesting(const WebWheelEvent& wheelEvent, bool& handled)
1779 CurrentEvent currentEvent(wheelEvent);
1781 handled = handleWheelEvent(wheelEvent, m_page.get());
1784 static bool handleKeyEvent(const WebKeyboardEvent& keyboardEvent, Page* page)
1786 if (!page->mainFrame()->view())
1789 if (keyboardEvent.type() == WebEvent::Char && keyboardEvent.isSystemKey())
1790 return page->focusController()->focusedOrMainFrame()->eventHandler()->handleAccessKey(platform(keyboardEvent));
1791 return page->focusController()->focusedOrMainFrame()->eventHandler()->keyEvent(platform(keyboardEvent));
1794 #if ENABLE(TIZEN_ISF_PORT)
1795 void WebPage::keyEvent(const NativeWebKeyboardEvent& keyboardEvent)
1797 void WebPage::keyEvent(const WebKeyboardEvent& keyboardEvent)
1800 CurrentEvent currentEvent(keyboardEvent);
1802 bool handled = handleKeyEvent(keyboardEvent, m_page.get());
1803 // FIXME: Platform default behaviors should be performed during normal DOM event dispatch (in most cases, in default keydown event handler).
1805 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1807 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(keyboardEvent.type()), handled));
1810 void WebPage::keyEventSyncForTesting(const WebKeyboardEvent& keyboardEvent, bool& handled)
1812 CurrentEvent currentEvent(keyboardEvent);
1814 handled = handleKeyEvent(keyboardEvent, m_page.get());
1816 handled = performDefaultBehaviorForKeyEvent(keyboardEvent);
1819 #if ENABLE(GESTURE_EVENTS)
1820 static bool handleGestureEvent(const WebGestureEvent& gestureEvent, Page* page)
1822 Frame* frame = page->mainFrame();
1826 PlatformGestureEvent platformGestureEvent = platform(gestureEvent);
1827 return frame->eventHandler()->handleGestureEvent(platformGestureEvent);
1830 void WebPage::gestureEvent(const WebGestureEvent& gestureEvent)
1832 CurrentEvent currentEvent(gestureEvent);
1834 bool handled = handleGestureEvent(gestureEvent, m_page.get());
1835 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(gestureEvent.type()), handled));
1839 void WebPage::validateCommand(const String& commandName, uint64_t callbackID)
1841 bool isEnabled = false;
1843 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1845 Editor::Command command = frame->editor()->command(commandName);
1846 state = command.state();
1847 isEnabled = command.isSupported() && command.isEnabled();
1850 send(Messages::WebPageProxy::ValidateCommandCallback(commandName, isEnabled, state, callbackID));
1853 void WebPage::executeEditCommand(const String& commandName)
1855 executeEditingCommand(commandName, String());
1858 uint64_t WebPage::restoreSession(const SessionState& sessionState)
1860 const BackForwardListItemVector& list = sessionState.list();
1861 size_t size = list.size();
1862 uint64_t currentItemID = 0;
1863 for (size_t i = 0; i < size; ++i) {
1864 WebBackForwardListItem* webItem = list[i].get();
1865 DecoderAdapter decoder(webItem->backForwardData().data(), webItem->backForwardData().size());
1867 RefPtr<HistoryItem> item = HistoryItem::decodeBackForwardTree(webItem->url(), webItem->title(), webItem->originalURL(), decoder);
1869 LOG_ERROR("Failed to decode a HistoryItem from session state data.");
1873 if (i == sessionState.currentIndex())
1874 currentItemID = webItem->itemID();
1876 WebBackForwardListProxy::addItemFromUIProcess(list[i]->itemID(), item.release());
1878 ASSERT(currentItemID);
1879 return currentItemID;
1882 void WebPage::restoreSessionAndNavigateToCurrentItem(const SessionState& sessionState)
1884 if (uint64_t currentItemID = restoreSession(sessionState))
1885 goToBackForwardItem(currentItemID);
1888 #if ENABLE(TOUCH_EVENTS)
1890 void WebPage::highlightPotentialActivation(const IntPoint& point, const IntSize& area)
1892 if (point == IntPoint::zero()) {
1893 // An empty point deactivates the highlighting.
1894 tapHighlightController().hideHighlight();
1896 Frame* mainframe = m_page->mainFrame();
1897 Node* activationNode = 0;
1898 Node* adjustedNode = 0;
1899 IntPoint adjustedPoint;
1901 #if ENABLE(TOUCH_ADJUSTMENT)
1902 if (!mainframe->eventHandler()->bestClickableNodeForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), adjustedPoint, adjustedNode))
1906 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
1907 adjustedNode = result.innerNode();
1909 // Find the node to highlight. This is not the same as the node responding the tap gesture, because many
1910 // pages has a global click handler and we do not want to highlight the body.
1911 // Instead find the enclosing link or focusable element, or the last enclosing inline element.
1912 for (Node* node = adjustedNode; node; node = node->parentOrHostNode()) {
1913 if (node->isMouseFocusable() || node->isLink()) {
1914 activationNode = node;
1917 if (node->renderer() && node->renderer()->isInline())
1918 activationNode = node;
1919 else if (activationNode)
1924 tapHighlightController().highlight(activationNode);
1929 static bool handleTouchEvent(const WebTouchEvent& touchEvent, Page* page)
1931 Frame* frame = page->mainFrame();
1935 return frame->eventHandler()->handleTouchEvent(platform(touchEvent));
1938 void WebPage::touchEvent(const WebTouchEvent& touchEvent)
1940 CurrentEvent currentEvent(touchEvent);
1942 bool handled = handleTouchEvent(touchEvent, m_page.get());
1944 #if ENABLE(TIZEN_CSS_OVERFLOW_SCROLL_ACCELERATION)
1945 static bool checkOverflow = false;
1946 if (touchEvent.type() == WebEvent::TouchStart && touchEvent.touchPoints().size() == 1) {
1947 checkOverflow = true;
1948 } else if (checkOverflow && touchEvent.type() == WebEvent::TouchMove && touchEvent.touchPoints().size() == 1) {
1949 bool pressed = false;
1951 #if ENABLE(TIZEN_CSS_OVERFLOW_SCROLL_ACCELERATION_ON_UI_SIDE)
1952 setPressedNodeAtPoint(touchEvent.touchPoints()[0].position(), true, pressed, id);
1954 setPressedNodeAtPoint(touchEvent.touchPoints()[0].position(), false, pressed, id);
1956 send(Messages::WebPageProxy::SetOverflowResult(pressed, id));
1957 checkOverflow = false;
1960 send(Messages::WebPageProxy::DidReceiveEvent(static_cast<uint32_t>(touchEvent.type()), handled));
1963 void WebPage::touchEventSyncForTesting(const WebTouchEvent& touchEvent, bool& handled)
1965 CurrentEvent currentEvent(touchEvent);
1966 handled = handleTouchEvent(touchEvent, m_page.get());
1970 void WebPage::scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
1972 page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
1975 void WebPage::logicalScroll(Page* page, ScrollLogicalDirection direction, ScrollGranularity granularity)
1977 page->focusController()->focusedOrMainFrame()->eventHandler()->logicalScrollRecursively(direction, granularity);
1980 void WebPage::scrollBy(uint32_t scrollDirection, uint32_t scrollGranularity)
1982 scroll(m_page.get(), static_cast<ScrollDirection>(scrollDirection), static_cast<ScrollGranularity>(scrollGranularity));
1985 void WebPage::centerSelectionInVisibleArea()
1987 Frame* frame = m_page->focusController()->focusedOrMainFrame();
1991 frame->selection()->revealSelection(ScrollAlignment::alignCenterAlways);
1992 m_findController.showFindIndicatorInSelection();
1995 void WebPage::setActive(bool isActive)
1997 m_page->focusController()->setActive(isActive);
2000 // Tell all our plug-in views that the window focus changed.
2001 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
2002 (*it)->setWindowIsFocused(isActive);
2006 void WebPage::setDrawsBackground(bool drawsBackground)
2008 if (m_drawsBackground == drawsBackground)
2011 m_drawsBackground = drawsBackground;
2013 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2014 if (FrameView* view = coreFrame->view())
2015 view->setTransparent(!drawsBackground);
2018 m_drawingArea->pageBackgroundTransparencyChanged();
2019 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2022 void WebPage::setDrawsTransparentBackground(bool drawsTransparentBackground)
2024 if (m_drawsTransparentBackground == drawsTransparentBackground)
2027 m_drawsTransparentBackground = drawsTransparentBackground;
2029 Color backgroundColor = drawsTransparentBackground ? Color::transparent : Color::white;
2030 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2031 if (FrameView* view = coreFrame->view())
2032 view->setBaseBackgroundColor(backgroundColor);
2035 m_drawingArea->pageBackgroundTransparencyChanged();
2036 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2039 void WebPage::viewWillStartLiveResize()
2044 // FIXME: This should propagate to all ScrollableAreas.
2045 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
2046 if (FrameView* view = frame->view())
2047 view->willStartLiveResize();
2051 void WebPage::viewWillEndLiveResize()
2056 // FIXME: This should propagate to all ScrollableAreas.
2057 if (Frame* frame = m_page->focusController()->focusedOrMainFrame()) {
2058 if (FrameView* view = frame->view())
2059 view->willEndLiveResize();
2063 void WebPage::setFocused(bool isFocused)
2065 m_page->focusController()->setFocused(isFocused);
2068 void WebPage::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event)
2070 if (!m_page || !m_page->focusController())
2073 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2074 frame->document()->setFocusedNode(0);
2076 if (isKeyboardEventValid && event.type() == WebEvent::KeyDown) {
2077 PlatformKeyboardEvent platformEvent(platform(event));
2078 platformEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
2079 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, KeyboardEvent::create(platformEvent, frame->document()->defaultView()).get());
2083 m_page->focusController()->setInitialFocus(forward ? FocusDirectionForward : FocusDirectionBackward, 0);
2086 void WebPage::setWindowResizerSize(const IntSize& windowResizerSize)
2088 if (m_windowResizerSize == windowResizerSize)
2091 m_windowResizerSize = windowResizerSize;
2093 for (Frame* coreFrame = m_mainFrame->coreFrame(); coreFrame; coreFrame = coreFrame->tree()->traverseNext()) {
2094 FrameView* view = coreFrame->view();
2096 view->windowResizerRectChanged();
2100 void WebPage::setCanStartMediaTimerFired()
2103 m_page->setCanStartMedia(true);
2106 void WebPage::setIsInWindow(bool isInWindow)
2109 m_setCanStartMediaTimer.stop();
2110 m_page->setCanStartMedia(false);
2111 m_page->willMoveOffscreen();
2113 // Defer the call to Page::setCanStartMedia() since it ends up sending a syncrhonous messages to the UI process
2114 // in order to get plug-in connections, and the UI process will be waiting for the Web process to update the backing
2115 // store after moving the view into a window, until it times out and paints white. See <rdar://problem/9242771>.
2116 m_setCanStartMediaTimer.startOneShot(0);
2117 m_page->didMoveOnscreen();
2121 void WebPage::didReceivePolicyDecision(uint64_t frameID, uint64_t listenerID, uint32_t policyAction, uint64_t downloadID)
2123 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2126 frame->didReceivePolicyDecision(listenerID, static_cast<PolicyAction>(policyAction), downloadID);
2129 void WebPage::show()
2131 send(Messages::WebPageProxy::ShowPage());
2134 void WebPage::setUserAgent(const String& userAgent)
2136 m_userAgent = userAgent;
2138 #if ENABLE(TIZEN_CUSTOM_HEADERS)
2139 void WebPage::addCustomHeader(const String& name, const String& value)
2141 m_customHeaders.add(name, value);
2144 void WebPage::removeCustomHeader(const String& name)
2146 m_customHeaders.remove(name);
2149 void WebPage::clearCustomHeaders()
2151 m_customHeaders.clear();
2154 WebCore::HTTPHeaderMap WebPage::customHeaders()
2156 return m_customHeaders;
2160 void WebPage::suspendActiveDOMObjectsAndAnimations()
2162 m_page->suspendActiveDOMObjectsAndAnimations();
2165 void WebPage::resumeActiveDOMObjectsAndAnimations()
2167 m_page->resumeActiveDOMObjectsAndAnimations();
2169 // We need to repaint on resume to kickstart animated painting again.
2170 m_drawingArea->setNeedsDisplay(IntRect(IntPoint(0, 0), m_viewSize));
2173 IntPoint WebPage::screenToWindow(const IntPoint& point)
2175 IntPoint windowPoint;
2176 sendSync(Messages::WebPageProxy::ScreenToWindow(point), Messages::WebPageProxy::ScreenToWindow::Reply(windowPoint));
2180 IntRect WebPage::windowToScreen(const IntRect& rect)
2183 sendSync(Messages::WebPageProxy::WindowToScreen(rect), Messages::WebPageProxy::WindowToScreen::Reply(screenRect));
2187 IntRect WebPage::windowResizerRect() const
2189 if (m_windowResizerSize.isEmpty())
2192 IntSize frameViewSize;
2193 if (Frame* coreFrame = m_mainFrame->coreFrame()) {
2194 if (FrameView* view = coreFrame->view())
2195 frameViewSize = view->size();
2198 return IntRect(frameViewSize.width() - m_windowResizerSize.width(), frameViewSize.height() - m_windowResizerSize.height(),
2199 m_windowResizerSize.width(), m_windowResizerSize.height());
2202 KeyboardUIMode WebPage::keyboardUIMode()
2204 bool fullKeyboardAccessEnabled = WebProcess::shared().fullKeyboardAccessEnabled();
2205 return static_cast<KeyboardUIMode>((fullKeyboardAccessEnabled ? KeyboardAccessFull : KeyboardAccessDefault) | (m_tabToLinks ? KeyboardAccessTabsToLinks : 0));
2208 void WebPage::runJavaScriptInMainFrame(const String& script, uint64_t callbackID)
2210 // NOTE: We need to be careful when running scripts that the objects we depend on don't
2211 // disappear during script execution.
2213 // Retain the SerializedScriptValue at this level so it (and the internal data) lives
2214 // long enough for the DataReference to be encoded by the sent message.
2215 RefPtr<SerializedScriptValue> serializedResultValue;
2216 CoreIPC::DataReference dataReference;
2218 JSLockHolder lock(JSDOMWindow::commonJSGlobalData());
2219 if (JSValue resultValue = m_mainFrame->coreFrame()->script()->executeScript(script, true).jsValue()) {
2220 if ((serializedResultValue = SerializedScriptValue::create(m_mainFrame->jsContext(), toRef(m_mainFrame->coreFrame()->script()->globalObject(mainThreadNormalWorld())->globalExec(), resultValue), 0)))
2221 dataReference = serializedResultValue->data();
2224 send(Messages::WebPageProxy::ScriptValueCallback(dataReference, callbackID));
2227 void WebPage::getContentsAsString(uint64_t callbackID)
2229 String resultString = m_mainFrame->contentsAsString();
2230 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2234 void WebPage::getContentsAsMHTMLData(uint64_t callbackID, bool useBinaryEncoding)
2236 CoreIPC::DataReference dataReference;
2238 RefPtr<SharedBuffer> buffer = useBinaryEncoding
2239 ? MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(m_page.get())
2240 : MHTMLArchive::generateMHTMLData(m_page.get());
2243 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2245 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2249 void WebPage::getRenderTreeExternalRepresentation(uint64_t callbackID)
2251 String resultString = renderTreeExternalRepresentation();
2252 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2255 void WebPage::getSelectionOrContentsAsString(uint64_t callbackID)
2257 String resultString = m_mainFrame->selectionAsString();
2258 if (resultString.isEmpty())
2259 resultString = m_mainFrame->contentsAsString();
2260 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2263 void WebPage::getSourceForFrame(uint64_t frameID, uint64_t callbackID)
2265 String resultString;
2266 if (WebFrame* frame = WebProcess::shared().webFrame(frameID))
2267 resultString = frame->source();
2269 send(Messages::WebPageProxy::StringCallback(resultString, callbackID));
2272 void WebPage::getMainResourceDataOfFrame(uint64_t frameID, uint64_t callbackID)
2274 CoreIPC::DataReference dataReference;
2276 RefPtr<SharedBuffer> buffer;
2277 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2278 if (DocumentLoader* loader = frame->coreFrame()->loader()->documentLoader()) {
2279 if ((buffer = loader->mainResourceData()))
2280 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2284 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2287 static PassRefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const KURL& resourceURL)
2289 DocumentLoader* loader = frame->loader()->documentLoader();
2293 RefPtr<ArchiveResource> subresource = loader->subresource(resourceURL);
2297 return subresource->data();
2300 void WebPage::getResourceDataFromFrame(uint64_t frameID, const String& resourceURLString, uint64_t callbackID)
2302 CoreIPC::DataReference dataReference;
2303 KURL resourceURL(KURL(), resourceURLString);
2305 RefPtr<SharedBuffer> buffer;
2306 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2307 buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
2309 // Try to get the resource data from the cache.
2310 buffer = cachedResponseDataForURL(resourceURL);
2314 dataReference = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>(buffer->data()), buffer->size());
2317 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2320 void WebPage::getWebArchiveOfFrame(uint64_t frameID, uint64_t callbackID)
2322 CoreIPC::DataReference dataReference;
2324 #if PLATFORM(MAC) || PLATFORM(WIN)
2325 RetainPtr<CFDataRef> data;
2326 if (WebFrame* frame = WebProcess::shared().webFrame(frameID)) {
2327 if ((data = frame->webArchiveData(0, 0)))
2328 dataReference = CoreIPC::DataReference(CFDataGetBytePtr(data.get()), CFDataGetLength(data.get()));
2332 send(Messages::WebPageProxy::DataCallback(dataReference, callbackID));
2335 void WebPage::forceRepaintWithoutCallback()
2337 m_drawingArea->forceRepaint();
2340 void WebPage::forceRepaint(uint64_t callbackID)
2342 if (m_drawingArea->forceRepaintAsync(callbackID))
2345 forceRepaintWithoutCallback();
2346 send(Messages::WebPageProxy::VoidCallback(callbackID));
2349 #if ENABLE(WEB_INTENTS)
2350 void WebPage::deliverIntentToFrame(uint64_t frameID, const IntentData& intentData)
2352 WebFrame* frame = WebProcess::shared().webFrame(frameID);
2356 frame->deliverIntent(intentData);
2360 void WebPage::preferencesDidChange(const WebPreferencesStore& store)
2362 WebPreferencesStore::removeTestRunnerOverrides();
2363 updatePreferences(store);
2366 void WebPage::updatePreferences(const WebPreferencesStore& store)
2368 Settings* settings = m_page->settings();
2370 m_tabToLinks = store.getBoolValueForKey(WebPreferencesKey::tabsToLinksKey());
2372 // FIXME: This should be generated from macro expansion for all preferences,
2373 // but we currently don't match the naming of WebCore exactly so we are
2374 // handrolling the boolean and integer preferences until that is fixed.
2376 #define INITIALIZE_SETTINGS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) settings->set##KeyUpper(store.get##TypeName##ValueForKey(WebPreferencesKey::KeyLower##Key()));
2378 FOR_EACH_WEBKIT_STRING_PREFERENCE(INITIALIZE_SETTINGS)
2380 #undef INITIALIZE_SETTINGS
2382 settings->setScriptEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptEnabledKey()));
2383 settings->setLoadsImagesAutomatically(store.getBoolValueForKey(WebPreferencesKey::loadsImagesAutomaticallyKey()));
2384 settings->setLoadsSiteIconsIgnoringImageLoadingSetting(store.getBoolValueForKey(WebPreferencesKey::loadsSiteIconsIgnoringImageLoadingPreferenceKey()));
2385 settings->setPluginsEnabled(store.getBoolValueForKey(WebPreferencesKey::pluginsEnabledKey()));
2386 settings->setJavaEnabled(store.getBoolValueForKey(WebPreferencesKey::javaEnabledKey()));
2387 settings->setJavaEnabledForLocalFiles(store.getBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey()));
2388 settings->setOfflineWebApplicationCacheEnabled(store.getBoolValueForKey(WebPreferencesKey::offlineWebApplicationCacheEnabledKey()));
2389 settings->setLocalStorageEnabled(store.getBoolValueForKey(WebPreferencesKey::localStorageEnabledKey()));
2390 settings->setXSSAuditorEnabled(store.getBoolValueForKey(WebPreferencesKey::xssAuditorEnabledKey()));
2391 settings->setFrameFlatteningEnabled(store.getBoolValueForKey(WebPreferencesKey::frameFlatteningEnabledKey()));
2392 settings->setPrivateBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey()));
2393 settings->setDeveloperExtrasEnabled(store.getBoolValueForKey(WebPreferencesKey::developerExtrasEnabledKey()));
2394 settings->setJavaScriptExperimentsEnabled(store.getBoolValueForKey(WebPreferencesKey::javaScriptExperimentsEnabledKey()));
2395 settings->setTextAreasAreResizable(store.getBoolValueForKey(WebPreferencesKey::textAreasAreResizableKey()));
2396 settings->setNeedsSiteSpecificQuirks(store.getBoolValueForKey(WebPreferencesKey::needsSiteSpecificQuirksKey()));
2397 settings->setJavaScriptCanOpenWindowsAutomatically(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanOpenWindowsAutomaticallyKey()));
2398 settings->setForceFTPDirectoryListings(store.getBoolValueForKey(WebPreferencesKey::forceFTPDirectoryListingsKey()));
2399 settings->setDNSPrefetchingEnabled(store.getBoolValueForKey(WebPreferencesKey::dnsPrefetchingEnabledKey()));
2400 #if ENABLE(WEB_ARCHIVE)
2401 settings->setWebArchiveDebugModeEnabled(store.getBoolValueForKey(WebPreferencesKey::webArchiveDebugModeEnabledKey()));
2403 settings->setLocalFileContentSniffingEnabled(store.getBoolValueForKey(WebPreferencesKey::localFileContentSniffingEnabledKey()));
2404 settings->setUsesPageCache(store.getBoolValueForKey(WebPreferencesKey::usesPageCacheKey()));
2405 settings->setPageCacheSupportsPlugins(store.getBoolValueForKey(WebPreferencesKey::pageCacheSupportsPluginsKey()));
2406 settings->setAuthorAndUserStylesEnabled(store.getBoolValueForKey(WebPreferencesKey::authorAndUserStylesEnabledKey()));
2407 settings->setPaginateDuringLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::paginateDuringLayoutEnabledKey()));
2408 settings->setDOMPasteAllowed(store.getBoolValueForKey(WebPreferencesKey::domPasteAllowedKey()));
2409 settings->setJavaScriptCanAccessClipboard(store.getBoolValueForKey(WebPreferencesKey::javaScriptCanAccessClipboardKey()));
2410 settings->setShouldPrintBackgrounds(store.getBoolValueForKey(WebPreferencesKey::shouldPrintBackgroundsKey()));
2411 settings->setWebSecurityEnabled(store.getBoolValueForKey(WebPreferencesKey::webSecurityEnabledKey()));
2412 settings->setAllowUniversalAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowUniversalAccessFromFileURLsKey()));
2413 settings->setAllowFileAccessFromFileURLs(store.getBoolValueForKey(WebPreferencesKey::allowFileAccessFromFileURLsKey()));
2415 settings->setMinimumFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumFontSizeKey()));
2416 settings->setMinimumLogicalFontSize(store.getUInt32ValueForKey(WebPreferencesKey::minimumLogicalFontSizeKey()));
2417 settings->setDefaultFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFontSizeKey()));
2418 settings->setDefaultFixedFontSize(store.getUInt32ValueForKey(WebPreferencesKey::defaultFixedFontSizeKey()));
2419 settings->setLayoutFallbackWidth(store.getUInt32ValueForKey(WebPreferencesKey::layoutFallbackWidthKey()));
2420 settings->setDeviceWidth(store.getUInt32ValueForKey(WebPreferencesKey::deviceWidthKey()));
2421 settings->setDeviceHeight(store.getUInt32ValueForKey(WebPreferencesKey::deviceHeightKey()));
2422 settings->setEditableLinkBehavior(static_cast<WebCore::EditableLinkBehavior>(store.getUInt32ValueForKey(WebPreferencesKey::editableLinkBehaviorKey())));
2423 settings->setShowsToolTipOverTruncatedText(store.getBoolValueForKey(WebPreferencesKey::showsToolTipOverTruncatedTextKey()));
2425 settings->setAcceleratedCompositingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedCompositingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2426 settings->setAcceleratedDrawingEnabled(store.getBoolValueForKey(WebPreferencesKey::acceleratedDrawingEnabledKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2427 settings->setCanvasUsesAcceleratedDrawing(store.getBoolValueForKey(WebPreferencesKey::canvasUsesAcceleratedDrawingKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2428 settings->setShowDebugBorders(store.getBoolValueForKey(WebPreferencesKey::compositingBordersVisibleKey()));
2429 settings->setShowRepaintCounter(store.getBoolValueForKey(WebPreferencesKey::compositingRepaintCountersVisibleKey()));
2430 settings->setCSSCustomFilterEnabled(store.getBoolValueForKey(WebPreferencesKey::cssCustomFilterEnabledKey()));
2431 settings->setCSSRegionsEnabled(store.getBoolValueForKey(WebPreferencesKey::cssRegionsEnabledKey()));
2432 settings->setCSSGridLayoutEnabled(store.getBoolValueForKey(WebPreferencesKey::cssGridLayoutEnabledKey()));
2433 settings->setRegionBasedColumnsEnabled(store.getBoolValueForKey(WebPreferencesKey::regionBasedColumnsEnabledKey()));
2434 settings->setWebGLEnabled(store.getBoolValueForKey(WebPreferencesKey::webGLEnabledKey()));
2435 settings->setMediaPlaybackRequiresUserGesture(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackRequiresUserGestureKey()));
2436 settings->setMediaPlaybackAllowsInline(store.getBoolValueForKey(WebPreferencesKey::mediaPlaybackAllowsInlineKey()));
2437 settings->setMockScrollbarsEnabled(store.getBoolValueForKey(WebPreferencesKey::mockScrollbarsEnabledKey()));
2438 settings->setHyperlinkAuditingEnabled(store.getBoolValueForKey(WebPreferencesKey::hyperlinkAuditingEnabledKey()));
2439 settings->setRequestAnimationFrameEnabled(store.getBoolValueForKey(WebPreferencesKey::requestAnimationFrameEnabledKey()));
2441 // <rdar://problem/10697417>: It is necessary to force compositing when accelerate drawing
2442 // is enabled on Mac so that scrollbars are always in their own layers.
2444 if (settings->acceleratedDrawingEnabled())
2445 settings->setForceCompositingMode(LayerTreeHost::supportsAcceleratedCompositing());
2448 settings->setForceCompositingMode(store.getBoolValueForKey(WebPreferencesKey::forceCompositingModeKey()) && LayerTreeHost::supportsAcceleratedCompositing());
2450 #if ENABLE(TIZEN_RUNTIME_BACKEND_SELECTION)
2451 if (!settings->acceleratedCompositingEnabled()) {
2452 settings->setAcceleratedCompositingFor3DTransformsEnabled(false);
2453 settings->setAcceleratedCompositingForVideoEnabled(false);
2454 settings->setAcceleratedCompositingForPluginsEnabled(false);
2455 settings->setAcceleratedCompositingForCanvasEnabled(false);
2456 settings->setAcceleratedCompositingForAnimationEnabled(false);
2459 #if ENABLE(TIZEN_WEBKIT2_MEMORY_SAVING_MODE)
2460 settings->setMemorySavingMode(WebProcess::shared().memorySavingModeEnabled());
2463 #if ENABLE(SQL_DATABASE)
2464 AbstractDatabase::setIsAvailable(store.getBoolValueForKey(WebPreferencesKey::databasesEnabledKey()));
2467 #if ENABLE(FULLSCREEN_API)
2468 settings->setFullScreenEnabled(store.getBoolValueForKey(WebPreferencesKey::fullScreenEnabledKey()));
2471 #if ENABLE(TIZEN_WEBKIT2_ASYNCHRONOUS_SPELLCHECKING)
2472 settings->setAsynchronousSpellCheckingEnabled(store.getBoolValueForKey(WebPreferencesKey::asynchronousSpellCheckingEnabledKey()));
2474 settings->setLocalStorageDatabasePath(WebProcess::shared().localStorageDirectory());
2476 #if USE(AVFOUNDATION)
2477 settings->setAVFoundationEnabled(store.getBoolValueForKey(WebPreferencesKey::isAVFoundationEnabledKey()));
2480 #if ENABLE(WEB_AUDIO)
2481 settings->setWebAudioEnabled(store.getBoolValueForKey(WebPreferencesKey::webAudioEnabledKey()));
2484 settings->setApplicationChromeMode(store.getBoolValueForKey(WebPreferencesKey::applicationChromeModeKey()));
2485 settings->setSuppressesIncrementalRendering(store.getBoolValueForKey(WebPreferencesKey::suppressesIncrementalRenderingKey()));
2486 settings->setBackspaceKeyNavigationEnabled(store.getBoolValueForKey(WebPreferencesKey::backspaceKeyNavigationEnabledKey()));
2487 settings->setWantsBalancedSetDefersLoadingBehavior(store.getBoolValueForKey(WebPreferencesKey::wantsBalancedSetDefersLoadingBehaviorKey()));
2488 settings->setCaretBrowsingEnabled(store.getBoolValueForKey(WebPreferencesKey::caretBrowsingEnabledKey()));
2490 #if ENABLE(VIDEO_TRACK)
2491 settings->setShouldDisplaySubtitles(store.getBoolValueForKey(WebPreferencesKey::shouldDisplaySubtitlesKey()));
2492 settings->setShouldDisplayCaptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayCaptionsKey()));
2493 settings->setShouldDisplayTextDescriptions(store.getBoolValueForKey(WebPreferencesKey::shouldDisplayTextDescriptionsKey()));
2496 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
2497 settings->setNotificationsEnabled(store.getBoolValueForKey(WebPreferencesKey::notificationsEnabledKey()));
2500 settings->setShouldRespectImageOrientation(store.getBoolValueForKey(WebPreferencesKey::shouldRespectImageOrientationKey()));
2502 #if ENABLE(TIZEN_INDEXED_DATABASE)
2503 m_page->group().groupSettings()->setIndexedDBDatabasePath(WebProcess::shared().indexedDatabaseDirectory());
2504 m_page->group().groupSettings()->setIndexedDBQuotaBytes(0x6400000); //100M
2507 settings->setDiagnosticLoggingEnabled(store.getBoolValueForKey(WebPreferencesKey::diagnosticLoggingEnabledKey()));
2509 #if ENABLE(TEXT_AUTOSIZING)
2510 settings->setTextAutosizingEnabled(store.getBoolValueForKey(WebPreferencesKey::textAutosizingEnabledKey()));
2513 #if ENABLE(TIZEN_FILE_SYSTEM)
2514 m_page->group().groupSettings()->setLocalFileSystemQuotaBytes(0x6400000); //100M
2517 #if ENABLE(TIZEN_WORKERS)
2518 m_page->group().groupSettings()->setAllowUniversalAccessFromFileURLs(settings->allowUniversalAccessFromFileURLs());
2521 platformPreferencesDidChange(store);
2524 m_drawingArea->updatePreferences();
2527 #if ENABLE(INSPECTOR)
2528 WebInspector* WebPage::inspector()
2533 m_inspector = WebInspector::create(this, m_inspectorClient);
2534 return m_inspector.get();
2538 #if ENABLE(FULLSCREEN_API)
2539 WebFullScreenManager* WebPage::fullScreenManager()
2541 if (!m_fullScreenManager)
2542 m_fullScreenManager = WebFullScreenManager::create(this);
2543 return m_fullScreenManager.get();
2547 NotificationPermissionRequestManager* WebPage::notificationPermissionRequestManager()
2549 if (m_notificationPermissionRequestManager)
2550 return m_notificationPermissionRequestManager.get();
2552 m_notificationPermissionRequestManager = NotificationPermissionRequestManager::create(this);
2553 return m_notificationPermissionRequestManager.get();
2556 #if ENABLE(TIZEN_MEDIA_STREAM)
2557 UserMediaPermissionRequestManager* WebPage::userMediaPermissionRequestManager()
2559 if (m_userMediaPermissionRequestManager)
2560 return m_userMediaPermissionRequestManager.get();
2562 m_userMediaPermissionRequestManager = UserMediaPermissionRequestManager::create(this);
2563 return m_userMediaPermissionRequestManager.get();
2567 #if !PLATFORM(GTK) && !PLATFORM(MAC)
2568 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* evt)
2570 Node* node = evt->target()->toNode();
2572 Frame* frame = node->document()->frame();
2575 const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
2579 Editor::Command command = frame->editor()->command(interpretKeyEvent(evt));
2581 if (keyEvent->type() == PlatformEvent::RawKeyDown) {
2582 // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
2583 // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
2584 // (e.g. Tab that inserts a Tab character, or Enter).
2585 return !command.isTextInsertion() && command.execute(evt);
2588 if (command.execute(evt))
2591 // Don't allow text insertion for nodes that cannot edit.
2592 if (!frame->editor()->canEdit())
2595 // Don't insert null or control characters as they can result in unexpected behaviour
2596 if (evt->charCode() < ' ')
2599 return frame->editor()->insertText(evt->keyEvent()->text(), evt);
2603 #if ENABLE(DRAG_SUPPORT)
2606 void WebPage::performDragControllerAction(uint64_t action, WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t draggingSourceOperationMask, const WebCore::DragDataMap& dataMap, uint32_t flags)
2609 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2613 DragData dragData(dataMap, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2615 case DragControllerActionEntered:
2616 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2619 case DragControllerActionUpdated:
2620 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2623 case DragControllerActionExited:
2624 m_page->dragController()->dragExited(&dragData);
2627 case DragControllerActionPerformDrag:
2628 m_page->dragController()->performDrag(&dragData);
2632 ASSERT_NOT_REACHED();
2636 #elif PLATFORM(QT) || PLATFORM(GTK) || ENABLE(TIZEN_DRAG_SUPPORT)
2637 void WebPage::performDragControllerAction(uint64_t action, WebCore::DragData dragData)
2640 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2642 QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2645 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2648 #if ENABLE(TIZEN_DRAG_SUPPORT)
2649 DataObjectTizen* data = const_cast<DataObjectTizen*>(dragData.platformData());
2656 case DragControllerActionEntered:
2657 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2660 case DragControllerActionUpdated:
2661 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2664 case DragControllerActionExited:
2665 m_page->dragController()->dragExited(&dragData);
2668 case DragControllerActionPerformDrag: {
2669 m_page->dragController()->performDrag(&dragData);
2674 ASSERT_NOT_REACHED();
2676 // DragData does not delete its platformData so we need to do that here.
2678 QMimeData* data = const_cast<QMimeData*>(dragData.platformData());
2681 DataObjectGtk* data = const_cast<DataObjectGtk*>(dragData.platformData());
2684 #if ENABLE(TIZEN_DRAG_SUPPORT)
2685 DataObjectTizen* data = const_cast<DataObjectTizen*>(dragData.platformData());
2691 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)
2694 send(Messages::WebPageProxy::DidPerformDragControllerAction(WebCore::DragSession()));
2698 DragData dragData(dragStorageName, clientPosition, globalPosition, static_cast<DragOperation>(draggingSourceOperationMask), static_cast<DragApplicationFlags>(flags));
2700 case DragControllerActionEntered:
2701 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragEntered(&dragData)));
2704 case DragControllerActionUpdated:
2705 send(Messages::WebPageProxy::DidPerformDragControllerAction(m_page->dragController()->dragUpdated(&dragData)));
2708 case DragControllerActionExited:
2709 m_page->dragController()->dragExited(&dragData);
2712 case DragControllerActionPerformDrag: {
2713 ASSERT(!m_pendingDropSandboxExtension);
2715 m_pendingDropSandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
2716 for (size_t i = 0; i < sandboxExtensionsHandleArray.size(); i++) {
2717 if (RefPtr<SandboxExtension> extension = SandboxExtension::create(sandboxExtensionsHandleArray[i]))
2718 m_pendingDropExtensionsForFileUpload.append(extension);
2721 m_page->dragController()->performDrag(&dragData);
2723 // If we started loading a local file, the sandbox extension tracker would have adopted this
2724 // pending drop sandbox extension. If not, we'll play it safe and invalidate it.
2725 if (m_pendingDropSandboxExtension) {
2726 m_pendingDropSandboxExtension->invalidate();
2727 m_pendingDropSandboxExtension = nullptr;
2729 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2730 m_pendingDropExtensionsForFileUpload[i]->invalidate();
2732 m_pendingDropExtensionsForFileUpload.clear();
2737 ASSERT_NOT_REACHED();
2742 void WebPage::dragEnded(WebCore::IntPoint clientPosition, WebCore::IntPoint globalPosition, uint64_t operation)
2744 IntPoint adjustedClientPosition(clientPosition.x() + m_page->dragController()->dragOffset().x(), clientPosition.y() + m_page->dragController()->dragOffset().y());
2745 IntPoint adjustedGlobalPosition(globalPosition.x() + m_page->dragController()->dragOffset().x(), globalPosition.y() + m_page->dragController()->dragOffset().y());
2747 m_page->dragController()->dragEnded();
2748 FrameView* view = m_page->mainFrame()->view();
2751 // FIXME: These are fake modifier keys here, but they should be real ones instead.
2752 PlatformMouseEvent event(adjustedClientPosition, adjustedGlobalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, currentTime());
2753 m_page->mainFrame()->eventHandler()->dragSourceEndedAt(event, (DragOperation)operation);
2756 void WebPage::willPerformLoadDragDestinationAction()
2758 m_sandboxExtensionTracker.willPerformLoadDragDestinationAction(m_pendingDropSandboxExtension.release());
2761 void WebPage::mayPerformUploadDragDestinationAction()
2763 for (size_t i = 0; i < m_pendingDropExtensionsForFileUpload.size(); i++)
2764 m_pendingDropExtensionsForFileUpload[i]->consumePermanently();
2765 m_pendingDropExtensionsForFileUpload.clear();
2768 #endif // ENABLE(DRAG_SUPPORT)
2770 WebUndoStep* WebPage::webUndoStep(uint64_t stepID)
2772 return m_undoStepMap.get(stepID).get();
2775 void WebPage::addWebUndoStep(uint64_t stepID, WebUndoStep* entry)
2777 m_undoStepMap.set(stepID, entry);
2780 void WebPage::removeWebEditCommand(uint64_t stepID)
2782 m_undoStepMap.remove(stepID);
2785 void WebPage::unapplyEditCommand(uint64_t stepID)
2787 WebUndoStep* step = webUndoStep(stepID);
2791 step->step()->unapply();
2794 void WebPage::reapplyEditCommand(uint64_t stepID)
2796 WebUndoStep* step = webUndoStep(stepID);
2801 step->step()->reapply();
2805 void WebPage::didRemoveEditCommand(uint64_t commandID)
2807 removeWebEditCommand(commandID);
2810 void WebPage::setActivePopupMenu(WebPopupMenu* menu)
2812 m_activePopupMenu = menu;
2815 #if ENABLE(INPUT_TYPE_COLOR)
2816 void WebPage::setActiveColorChooser(WebColorChooser* colorChooser)
2818 m_activeColorChooser = colorChooser;
2821 void WebPage::didEndColorChooser()
2823 m_activeColorChooser->didEndChooser();
2826 void WebPage::didChooseColor(const WebCore::Color& color)
2828 m_activeColorChooser->didChooseColor(color);
2832 void WebPage::setActiveOpenPanelResultListener(PassRefPtr<WebOpenPanelResultListener> openPanelResultListener)
2834 m_activeOpenPanelResultListener = openPanelResultListener;
2837 bool WebPage::findStringFromInjectedBundle(const String& target, FindOptions options)
2839 return m_page->findString(target, options);
2842 void WebPage::findString(const String& string, uint32_t options, uint32_t maxMatchCount)
2844 m_findController.findString(string, static_cast<FindOptions>(options), maxMatchCount);
2847 void WebPage::findStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2849 m_findController.findStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2852 void WebPage::getImageForFindMatch(uint32_t matchIndex)
2854 m_findController.getImageForFindMatch(matchIndex);
2857 void WebPage::selectFindMatch(uint32_t matchIndex)
2859 m_findController.selectFindMatch(matchIndex);
2862 void WebPage::hideFindUI()
2864 m_findController.hideFindUI();
2867 void WebPage::countStringMatches(const String& string, uint32_t options, uint32_t maxMatchCount)
2869 m_findController.countStringMatches(string, static_cast<FindOptions>(options), maxMatchCount);
2872 void WebPage::didChangeSelectedIndexForActivePopupMenu(int32_t newIndex)
2874 changeSelectedIndex(newIndex);
2876 // Since applictions on tizen may provide a way to select item more than one time,
2877 // we need to keep the active popup menu to allow repetitive selection.
2879 m_activePopupMenu = 0;
2883 void WebPage::changeSelectedIndex(int32_t index)
2885 if (!m_activePopupMenu)
2888 m_activePopupMenu->didChangeSelectedIndex(index);
2891 void WebPage::didChooseFilesForOpenPanel(const Vector<String>& files)
2893 if (!m_activeOpenPanelResultListener)
2896 m_activeOpenPanelResultListener->didChooseFiles(files);
2897 m_activeOpenPanelResultListener = 0;
2900 void WebPage::didCancelForOpenPanel()
2902 m_activeOpenPanelResultListener = 0;
2906 void WebPage::cancelForOpenPanel()
2908 if (m_activeOpenPanelResultListener) {
2909 m_activeOpenPanelResultListener->disconnectFromPage();
2910 m_activeOpenPanelResultListener = 0;
2915 #if ENABLE(WEB_PROCESS_SANDBOX)
2916 void WebPage::extendSandboxForFileFromOpenPanel(const SandboxExtension::Handle& handle)
2918 SandboxExtension::create(handle)->consumePermanently();
2922 #if ENABLE(GEOLOCATION)
2923 void WebPage::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed)
2925 m_geolocationPermissionRequestManager.didReceiveGeolocationPermissionDecision(geolocationID, allowed);
2929 void WebPage::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allowed)
2931 notificationPermissionRequestManager()->didReceiveNotificationPermissionDecision(notificationID, allowed);
2934 #if ENABLE(TIZEN_MEDIA_STREAM)
2935 void WebPage::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed)
2937 userMediaPermissionRequestManager()->didReceiveUserMediaPermissionDecision(userMediaID, allowed);
2941 void WebPage::advanceToNextMisspelling(bool startBeforeSelection)
2943 Frame* frame = m_page->focusController()->focusedOrMainFrame();
2944 frame->editor()->advanceToNextMisspelling(startBeforeSelection);
2947 void WebPage::changeSpellingToWord(const String& word)
2949 replaceSelectionWithText(m_page->focusController()->focusedOrMainFrame(), word);
2952 void WebPage::unmarkAllMisspellings()
2954 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2955 if (Document* document = frame->document())
2956 document->markers()->removeMarkers(DocumentMarker::Spelling);
2960 void WebPage::unmarkAllBadGrammar()
2962 for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
2963 if (Document* document = frame->document())
2964 document->markers()->removeMarkers(DocumentMarker::Grammar);
2969 void WebPage::uppercaseWord()
2971 m_page->focusController()->focusedOrMainFrame()->editor()->uppercaseWord();
2974 void WebPage::lowercaseWord()
2976 m_page->focusController()->focusedOrMainFrame()->editor()->lowercaseWord();
2979 void WebPage::capitalizeWord()
2981 m_page->focusController()->focusedOrMainFrame()->editor()->capitalizeWord();
2985 void WebPage::setTextForActivePopupMenu(int32_t index)
2987 if (!m_activePopupMenu)
2990 m_activePopupMenu->setTextForIndex(index);
2994 void WebPage::failedToShowPopupMenu()
2996 if (!m_activePopupMenu)
2999 m_activePopupMenu->client()->popupDidHide();
3003 #if ENABLE(CONTEXT_MENUS)
3004 void WebPage::didSelectItemFromActiveContextMenu(const WebContextMenuItemData& item)
3009 m_contextMenu->itemSelected(item);
3014 void WebPage::replaceSelectionWithText(Frame* frame, const String& text)
3016 bool selectReplacement = true;
3017 bool smartReplace = false;
3018 return frame->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
3021 void WebPage::clearSelection()
3023 m_page->focusController()->focusedOrMainFrame()->selection()->clear();
3026 bool WebPage::mainFrameHasCustomRepresentation() const
3028 if (Frame* frame = mainFrame())
3029 return static_cast<WebFrameLoaderClient*>(frame->loader()->client())->frameHasCustomRepresentation();
3034 void WebPage::didChangeScrollOffsetForMainFrame()
3036 Frame* frame = m_page->mainFrame();
3037 IntPoint scrollPosition = frame->view()->scrollPosition();
3038 IntPoint maximumScrollPosition = frame->view()->maximumScrollPosition();
3039 IntPoint minimumScrollPosition = frame->view()->minimumScrollPosition();
3041 #if PLATFORM(EFL) && OS(TIZEN)
3042 send(Messages::WebPageProxy::DidChangeScrollPositionForMainFrame(scrollPosition));
3045 bool isPinnedToLeftSide = (scrollPosition.x() <= minimumScrollPosition.x());
3046 bool isPinnedToRightSide = (scrollPosition.x() >= maximumScrollPosition.x());
3048 if (isPinnedToLeftSide != m_cachedMainFrameIsPinnedToLeftSide || isPinnedToRightSide != m_cachedMainFrameIsPinnedToRightSide) {
3049 send(Messages::WebPageProxy::DidChangeScrollOffsetPinningForMainFrame(isPinnedToLeftSide, isPinnedToRightSide));
3051 m_cachedMainFrameIsPinnedToLeftSide = isPinnedToLeftSide;
3052 m_cachedMainFrameIsPinnedToRightSide = isPinnedToRightSide;
3056 void WebPage::mainFrameDidLayout()
3058 unsigned pageCount = m_page->pageCount();
3059 if (pageCount != m_cachedPageCount) {
3060 send(Messages::WebPageProxy::DidChangePageCount(pageCount));
3061 m_cachedPageCount = pageCount;
3064 double red, green, blue, alpha;
3065 m_mainFrame->getDocumentBackgroundColor(&red, &green, &blue, &alpha);
3066 send(Messages::WebPageProxy::SetBackgroundColor(red, green, blue, alpha));
3069 void WebPage::addPluginView(PluginView* pluginView)
3071 ASSERT(!m_pluginViews.contains(pluginView));
3073 m_pluginViews.add(pluginView);
3076 void WebPage::removePluginView(PluginView* pluginView)
3078 ASSERT(m_pluginViews.contains(pluginView));
3080 m_pluginViews.remove(pluginView);
3084 void WebPage::setWindowIsVisible(bool windowIsVisible)
3086 m_windowIsVisible = windowIsVisible;
3088 corePage()->focusController()->setContainingWindowIsVisible(windowIsVisible);
3090 // Tell all our plug-in views that the window visibility changed.
3091 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
3092 (*it)->setWindowIsVisible(windowIsVisible);
3095 void WebPage::windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates)
3097 m_windowFrameInScreenCoordinates = windowFrameInScreenCoordinates;
3098 m_viewFrameInWindowCoordinates = viewFrameInWindowCoordinates;
3099 m_accessibilityPosition = accessibilityViewCoordinates;
3101 // Tell all our plug-in views that the window and view frames have changed.
3102 for (HashSet<PluginView*>::const_iterator it = m_pluginViews.begin(), end = m_pluginViews.end(); it != end; ++it)
3103 (*it)->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
3107 bool WebPage::windowIsFocused() const
3109 return m_page->focusController()->isActive();
3112 bool WebPage::windowAndWebPageAreFocused() const
3115 if (!m_windowIsVisible)
3118 return m_page->focusController()->isFocused() && m_page->focusController()->isActive();
3121 void WebPage::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
3123 if (messageID.is<CoreIPC::MessageClassDrawingArea>()) {
3125 m_drawingArea->didReceiveDrawingAreaMessage(connection, messageID, arguments);
3129 #if USE(TILED_BACKING_STORE) && USE(ACCELERATED_COMPOSITING)
3130 if (messageID.is<CoreIPC::MessageClassLayerTreeCoordinator>()) {
3132 m_drawingArea->didReceiveLayerTreeCoordinatorMessage(connection, messageID, arguments);
3137 #if ENABLE(INSPECTOR)
3138 if (messageID.is<CoreIPC::MessageClassWebInspector>()) {
3139 if (WebInspector* inspector = this->inspector())
3140 inspector->didReceiveWebInspectorMessage(connection, messageID, arguments);
3145 #if ENABLE(FULLSCREEN_API)
3146 if (messageID.is<CoreIPC::MessageClassWebFullScreenManager>()) {
3147 fullScreenManager()->didReceiveMessage(connection, messageID, arguments);
3152 didReceiveWebPageMessage(connection, messageID, arguments);
3155 void WebPage::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments, OwnPtr<CoreIPC::ArgumentEncoder>& reply)
3157 didReceiveSyncWebPageMessage(connection, messageID, arguments, reply);
3160 InjectedBundleBackForwardList* WebPage::backForwardList()
3162 if (!m_backForwardList)
3163 m_backForwardList = InjectedBundleBackForwardList::create(this);
3164 return m_backForwardList.get();
3167 #if PLATFORM(QT) || OS(TIZEN)
3168 #if ENABLE(TOUCH_ADJUSTMENT)
3169 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3172 IntRect zoomableArea;
3173 bool foundAreaForTouchPoint = m_mainFrame->coreFrame()->eventHandler()->bestZoomableAreaForTouchPoint(point, IntSize(area.width() / 2, area.height() / 2), zoomableArea, node);
3176 if (!foundAreaForTouchPoint)
3179 send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3183 void WebPage::findZoomableAreaForPoint(const WebCore::IntPoint& point, const WebCore::IntSize& area)
3186 Frame* mainframe = m_mainFrame->coreFrame();
3187 HitTestResult result = mainframe->eventHandler()->hitTestResultAtPoint(mainframe->view()->windowToContents(point), /*allowShadowContent*/ false, /*ignoreClipping*/ true);
3189 Node* node = result.innerNode();
3194 #if OS(TIZEN) // FIXME: This is to fix wrong codes of open source.
3195 IntRect zoomableArea = enclosingIntRect(node->getRect());
3197 IntRect zoomableArea = node->getRect();
3201 bool found = !node->isTextNode() && !node->isShadowRoot();
3203 // No candidate found, bail out.
3204 if (!found && !node->parentNode())
3207 // Candidate found, and it is a better candidate than its parent.
3208 // NB: A parent is considered a better candidate iff the node is
3209 // contained by it and it is the only child.
3210 if (found && (!node->parentNode() || node->parentNode()->childNodeCount() != 1))
3213 node = node->parentNode();
3214 #if OS(TIZEN) // FIXME: This is to fix wrong codes of open source.
3215 zoomableArea.unite(enclosingIntRect(node->getRect()));
3217 zoomableArea.unite(node->getRect());
3221 if (node->document() && node->document()->frame() && node->document()->frame()->view()) {
3222 const ScrollView* view = node->document()->frame()->view();
3223 zoomableArea = view->contentsToWindow(zoomableArea);
3226 send(Messages::WebPageProxy::DidFindZoomableArea(point, zoomableArea));
3231 WebPage::SandboxExtensionTracker::~SandboxExtensionTracker()
3236 void WebPage::SandboxExtensionTracker::invalidate()
3238 if (m_pendingProvisionalSandboxExtension) {
3239 m_pendingProvisionalSandboxExtension->invalidate();
3240 m_pendingProvisionalSandboxExtension = 0;
3243 if (m_provisionalSandboxExtension) {
3244 m_provisionalSandboxExtension->invalidate();
3245 m_provisionalSandboxExtension = 0;
3248 if (m_committedSandboxExtension) {
3249 m_committedSandboxExtension->invalidate();
3250 m_committedSandboxExtension = 0;
3254 void WebPage::SandboxExtensionTracker::willPerformLoadDragDestinationAction(PassRefPtr<SandboxExtension> pendingDropSandboxExtension)
3256 setPendingProvisionalSandboxExtension(pendingDropSandboxExtension);
3259 void WebPage::SandboxExtensionTracker::beginLoad(WebFrame* frame, const SandboxExtension::Handle& handle)
3261 ASSERT(frame->isMainFrame());
3263 setPendingProvisionalSandboxExtension(SandboxExtension::create(handle));
3266 void WebPage::SandboxExtensionTracker::setPendingProvisionalSandboxExtension(PassRefPtr<SandboxExtension> pendingProvisionalSandboxExtension)
3268 // If we get two beginLoad calls in succession, without a provisional load starting, then
3269 // m_pendingProvisionalSandboxExtension will be non-null. Invalidate and null out the extension if that is the case.
3270 if (m_pendingProvisionalSandboxExtension) {
3271 m_pendingProvisionalSandboxExtension->invalidate();
3272 m_pendingProvisionalSandboxExtension = nullptr;
3275 m_pendingProvisionalSandboxExtension = pendingProvisionalSandboxExtension;
3278 static bool shouldReuseCommittedSandboxExtension(WebFrame* frame)
3280 ASSERT(frame->isMainFrame());
3282 FrameLoader* frameLoader = frame->coreFrame()->loader();
3283 FrameLoadType frameLoadType = frameLoader->loadType();
3285 // If the page is being reloaded, it should reuse whatever extension is committed.
3286 if (frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin)
3289 DocumentLoader* documentLoader = frameLoader->documentLoader();
3290 DocumentLoader* provisionalDocumentLoader = frameLoader->provisionalDocumentLoader();
3291 if (!documentLoader || !provisionalDocumentLoader)
3294 if (documentLoader->url().isLocalFile() && provisionalDocumentLoader->url().isLocalFile())
3300 void WebPage::SandboxExtensionTracker::didStartProvisionalLoad(WebFrame* frame)
3302 if (!frame->isMainFrame())
3305 // We should only reuse the commited sandbox extension if it is not null. It can be
3306 // null if the last load was for an error page.
3307 if (m_committedSandboxExtension && shouldReuseCommittedSandboxExtension(frame)) {
3308 m_pendingProvisionalSandboxExtension = m_committedSandboxExtension.release();
3309 ASSERT(!m_committedSandboxExtension);
3312 ASSERT(!m_provisionalSandboxExtension);
3314 m_provisionalSandboxExtension = m_pendingProvisionalSandboxExtension.release();
3315 if (!m_provisionalSandboxExtension)
3318 m_provisionalSandboxExtension->consume();
3321 void WebPage::SandboxExtensionTracker::didCommitProvisionalLoad(WebFrame* frame)
3323 if (!frame->isMainFrame())
3326 // Generally, there should be no pending extension at this stage, but we can have one if UI process
3327 // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3328 if (m_pendingProvisionalSandboxExtension) {
3329 m_pendingProvisionalSandboxExtension->invalidate();
3330 m_pendingProvisionalSandboxExtension = nullptr;
3333 // The provisional load has been committed. Invalidate the currently committed sandbox
3334 // extension and make the provisional sandbox extension the committed sandbox extension.
3335 if (m_committedSandboxExtension)
3336 m_committedSandboxExtension->invalidate();
3338 m_committedSandboxExtension = m_provisionalSandboxExtension.release();
3341 void WebPage::SandboxExtensionTracker::didFailProvisionalLoad(WebFrame* frame)
3343 if (!frame->isMainFrame())
3346 // Generally, there should be no pending extension at this stage, but we can have one if UI process
3347 // has an out of date idea of WebProcess state, and initiates a load or reload without stopping an existing one.
3348 if (m_pendingProvisionalSandboxExtension) {
3349 m_pendingProvisionalSandboxExtension->invalidate();
3350 m_pendingProvisionalSandboxExtension = nullptr;
3353 if (!m_provisionalSandboxExtension)
3356 m_provisionalSandboxExtension->invalidate();
3357 m_provisionalSandboxExtension = nullptr;
3360 bool WebPage::hasLocalDataForURL(const KURL& url)
3362 if (url.isLocalFile())
3365 FrameLoader* frameLoader = m_page->mainFrame()->loader();
3366 DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
3367 if (documentLoader && documentLoader->subresource(url))
3370 return platformHasLocalDataForURL(url);
3373 void WebPage::setCustomTextEncodingName(const String& encoding)
3375 m_page->mainFrame()->loader()->reloadWithOverrideEncoding(encoding);
3378 void WebPage::didRemoveBackForwardItem(uint64_t itemID)
3380 WebBackForwardListProxy::removeItem(itemID);
3385 bool WebPage::isSpeaking()
3388 return sendSync(Messages::WebPageProxy::GetIsSpeaking(), Messages::WebPageProxy::GetIsSpeaking::Reply(result)) && result;
3391 void WebPage::speak(const String& string)
3393 send(Messages::WebPageProxy::Speak(string));
3396 void WebPage::stopSpeaking()
3398 send(Messages::WebPageProxy::StopSpeaking());
3404 RetainPtr<PDFDocument> WebPage::pdfDocumentForPrintingFrame(Frame* coreFrame)
3406 Document* document = coreFrame->document();
3410 if (!document->isPluginDocument())
3413 PluginView* pluginView = static_cast<PluginView*>(toPluginDocument(document)->pluginWidget());
3417 return pluginView->pdfDocumentForPrinting();
3419 #endif // PLATFORM(MAC)
3421 void WebPage::beginPrinting(uint64_t frameID, const PrintInfo& printInfo)
3423 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3427 Frame* coreFrame = frame->coreFrame();
3432 if (pdfDocumentForPrintingFrame(coreFrame))
3434 #endif // PLATFORM(MAC)
3436 if (!m_printContext)
3437 m_printContext = adoptPtr(new PrintContext(coreFrame));
3439 drawingArea()->setLayerTreeStateIsFrozen(true);
3440 m_printContext->begin(printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3442 float fullPageHeight;
3443 m_printContext->computePageRects(FloatRect(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight), 0, 0, printInfo.pageSetupScaleFactor, fullPageHeight, true);
3446 if (!m_printOperation)
3447 m_printOperation = WebPrintOperationGtk::create(this, printInfo);
3451 void WebPage::endPrinting()
3453 drawingArea()->setLayerTreeStateIsFrozen(false);
3455 m_printOperation = 0;
3457 m_printContext = nullptr;
3460 void WebPage::computePagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3462 Vector<IntRect> resultPageRects;
3463 double resultTotalScaleFactorForPrinting = 1;
3465 beginPrinting(frameID, printInfo);
3467 if (m_printContext) {
3468 resultPageRects = m_printContext->pageRects();
3469 resultTotalScaleFactorForPrinting = m_printContext->computeAutomaticScaleFactor(FloatSize(printInfo.availablePaperWidth, printInfo.availablePaperHeight)) * printInfo.pageSetupScaleFactor;
3473 computePagesForPrintingPDFDocument(frameID, printInfo, resultPageRects);
3474 #endif // PLATFORM(MAC)
3476 // If we're asked to print, we should actually print at least a blank page.
3477 if (resultPageRects.isEmpty())
3478 resultPageRects.append(IntRect(0, 0, 1, 1));
3480 send(Messages::WebPageProxy::ComputedPagesCallback(resultPageRects, resultTotalScaleFactorForPrinting, callbackID));
3483 #if PLATFORM(MAC) || PLATFORM(WIN)
3484 void WebPage::drawRectToPDF(uint64_t frameID, const PrintInfo& printInfo, const WebCore::IntRect& rect, uint64_t callbackID)
3486 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3487 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3489 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3494 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3496 ASSERT(coreFrame->document()->printing());
3499 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3500 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3502 CGRect mediaBox = CGRectMake(0, 0, rect.width(), rect.height());
3503 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3504 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3505 CGPDFContextBeginPage(context.get(), pageInfo.get());
3508 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3509 ASSERT(!m_printContext);
3510 drawRectToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, rect);
3514 GraphicsContext ctx(context.get());
3515 ctx.scale(FloatSize(1, -1));
3516 ctx.translate(0, -rect.height());
3517 m_printContext->spoolRect(ctx, rect);
3520 CGPDFContextEndPage(context.get());
3521 CGPDFContextClose(context.get());
3525 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3528 void WebPage::drawPagesToPDF(uint64_t frameID, const PrintInfo& printInfo, uint32_t first, uint32_t count, uint64_t callbackID)
3530 WebFrame* frame = WebProcess::shared().webFrame(frameID);
3531 Frame* coreFrame = frame ? frame->coreFrame() : 0;
3533 RetainPtr<CFMutableDataRef> pdfPageData(AdoptCF, CFDataCreateMutable(0, 0));
3539 ASSERT(coreFrame->document()->printing() || pdfDocumentForPrintingFrame(coreFrame));
3541 ASSERT(coreFrame->document()->printing());
3544 // FIXME: Use CGDataConsumerCreate with callbacks to avoid copying the data.
3545 RetainPtr<CGDataConsumerRef> pdfDataConsumer(AdoptCF, CGDataConsumerCreateWithCFData(pdfPageData.get()));
3547 CGRect mediaBox = (m_printContext && m_printContext->pageCount()) ? m_printContext->pageRect(0) : CGRectMake(0, 0, printInfo.availablePaperWidth, printInfo.availablePaperHeight);
3548 RetainPtr<CGContextRef> context(AdoptCF, CGPDFContextCreate(pdfDataConsumer.get(), &mediaBox, 0));
3551 if (RetainPtr<PDFDocument> pdfDocument = pdfDocumentForPrintingFrame(coreFrame)) {
3552 ASSERT(!m_printContext);
3553 drawPagesToPDFFromPDFDocument(context.get(), pdfDocument.get(), printInfo, first, count);
3557 size_t pageCount = m_printContext->pageCount();
3558 for (uint32_t page = first; page < first + count; ++page) {
3559 if (page >= pageCount)
3562 RetainPtr<CFDictionaryRef> pageInfo(AdoptCF, CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
3563 CGPDFContextBeginPage(context.get(), pageInfo.get());
3565 GraphicsContext ctx(context.get());
3566 ctx.scale(FloatSize(1, -1));
3567 ctx.translate(0, -m_printContext->pageRect(page).height());
3568 m_printContext->spoolPage(ctx, page, m_printContext->pageRect(page).width());
3570 CGPDFContextEndPage(context.get());
3573 CGPDFContextClose(context.get());
3577 send(Messages::WebPageProxy::DataCallback(CoreIPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3582 void WebPage::drawPagesForPrinting(uint64_t frameID, const PrintInfo& printInfo, uint64_t callbackID)
3584 beginPrinting(frameID, printInfo);
3585 if (m_printContext && m_printOperation) {
3586 m_printOperation->startPrint(m_printContext.get(), callbackID);
3590 send(Messages::WebPageProxy::VoidCallback(callbackID));
3594 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
3595 void WebPage::getWebAppCapable(uint64_t callbackID)
3597 RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("meta");
3598 bool capable = false;
3600 for (unsigned i = 0; i < nodeList->length(); i++) {
3601 WebCore::HTMLMetaElement* metaElement = static_cast<WebCore::HTMLMetaElement*>(nodeList->item(i));
3602 if (metaElement->name() == "apple-mobile-web-app-capable") {
3603 capable = metaElement->content() == "yes" ? true : false;
3608 send(Messages::WebPageProxy::DidGetWebAppCapable(capable, callbackID));
3611 void WebPage::getWebAppIconURL(uint64_t callbackID)
3613 RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("link");
3616 for (unsigned i = 0; i < nodeList->length(); i++) {
3617 WebCore::HTMLLinkElement* linkElement = static_cast<WebCore::HTMLLinkElement*>(nodeList->item(i));
3618 if (linkElement->rel() == "apple-touch-icon" || linkElement->rel() == "apple-touch-icon-precomposed")
3619 iconURL = linkElement->href().string();
3622 send(Messages::WebPageProxy::DidGetWebAppIconURL(iconURL, callbackID));
3625 void WebPage::getWebAppIconURLs(uint64_t callbackID)
3627 RefPtr<WebCore::NodeList> nodeList = mainFrame()->document()->getElementsByTagName("link");
3628 Vector<std::pair<String, String> > iconURLs;
3630 for (unsigned i = 0; i < nodeList->length(); i++) {
3631 WebCore::HTMLLinkElement* linkElement = static_cast<WebCore::HTMLLinkElement*>(nodeList->item(i));
3632 if (linkElement->rel() == "apple-touch-icon" || linkElement->rel() == "apple-touch-icon-precomposed")
3633 iconURLs.append(pair<String, String>(linkElement->href().string(), linkElement->iconSizes()));
3636 send(Messages::WebPageProxy::DidGetWebAppIconURLs(iconURLs, callbackID));
3640 void WebPage::setMediaVolume(float volume)
3642 m_page->setMediaVolume(volume);
3645 void WebPage::runModal()
3649 if (m_isRunningModal)
3652 m_isRunningModal = true;
3653 send(Messages::WebPageProxy::RunModal());
3655 ASSERT(!m_isRunningModal);
3658 void WebPage::setMemoryCacheMessagesEnabled(bool memoryCacheMessagesEnabled)
3660 m_page->setMemoryCacheClientCallsEnabled(memoryCacheMessagesEnabled);
3663 bool WebPage::canHandleRequest(const WebCore::ResourceRequest& request)
3665 if (SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(request.url().protocol()))
3667 return platformCanHandleRequest(request);
3670 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
3671 void WebPage::handleAlternativeTextUIResult(const String& result)
3673 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3676 frame->editor()->handleAlternativeTextUIResult(result);
3680 void WebPage::simulateMouseDown(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3682 mouseEvent(WebMouseEvent(WebMouseEvent::MouseDown, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3685 void WebPage::simulateMouseUp(int button, WebCore::IntPoint position, int clickCount, WKEventModifiers modifiers, double time)
3687 mouseEvent(WebMouseEvent(WebMouseEvent::MouseUp, static_cast<WebMouseEvent::Button>(button), position, position, 0, 0, 0, clickCount, static_cast<WebMouseEvent::Modifiers>(modifiers), time));
3690 void WebPage::simulateMouseMotion(WebCore::IntPoint position, double time)
3692 mouseEvent(WebMouseEvent(WebMouseEvent::MouseMove, WebMouseEvent::NoButton, position, position, 0, 0, 0, 0, WebMouseEvent::Modifiers(), time));
3695 void WebPage::setCompositionForTesting(const String& compositionString, uint64_t from, uint64_t length)
3697 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3698 if (!frame || !frame->editor()->canEdit())
3701 Vector<CompositionUnderline> underlines;
3702 underlines.append(CompositionUnderline(0, compositionString.length(), Color(Color::black), false));
3703 frame->editor()->setComposition(compositionString, underlines, from, from + length);
3706 bool WebPage::hasCompositionForTesting()
3708 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3709 return frame && frame->editor()->hasComposition();
3712 void WebPage::confirmCompositionForTesting(const String& compositionString)
3714 Frame* frame = m_page->focusController()->focusedOrMainFrame();
3715 if (!frame || !frame->editor()->canEdit())
3718 if (compositionString.isNull())
3719 frame->editor()->confirmComposition();
3720 frame->editor()->confirmComposition(compositionString);
3723 void WebPage::numWheelEventHandlersChanged(unsigned numWheelEventHandlers)
3725 if (m_numWheelEventHandlers == numWheelEventHandlers)
3728 m_numWheelEventHandlers = numWheelEventHandlers;
3729 recomputeShortCircuitHorizontalWheelEventsState();
3732 static bool hasEnabledHorizontalScrollbar(ScrollableArea* scrollableArea)
3734 if (Scrollbar* scrollbar = scrollableArea->horizontalScrollbar())
3735 return scrollbar->enabled();
3740 static bool pageContainsAnyHorizontalScrollbars(Frame* mainFrame)
3742 if (FrameView* frameView = mainFrame->view()) {
3743 if (hasEnabledHorizontalScrollbar(frameView))
3747 for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext()) {
3748 FrameView* frameView = frame->view();
3752 const HashSet<ScrollableArea*>* scrollableAreas = frameView->scrollableAreas();
3753 if (!scrollableAreas)
3756 for (HashSet<ScrollableArea*>::const_iterator it = scrollableAreas->begin(), end = scrollableAreas->end(); it != end; ++it) {
3757 ScrollableArea* scrollableArea = *it;
3758 if (!scrollableArea->isOnActivePage())
3761 if (hasEnabledHorizontalScrollbar(scrollableArea))
3769 void WebPage::recomputeShortCircuitHorizontalWheelEventsState()
3771 bool canShortCircuitHorizontalWheelEvents = !m_numWheelEventHandlers;
3773 if (canShortCircuitHorizontalWheelEvents) {
3774 // Check if we have any horizontal scroll bars on the page.
3775 if (pageContainsAnyHorizontalScrollbars(mainFrame()))
3776 canShortCircuitHorizontalWheelEvents = false;
3779 if (m_canShortCircuitHorizontalWheelEvents == canShortCircuitHorizontalWheelEvents)
3782 m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents;
3783 send(Messages::WebPageProxy::SetCanShortCircuitHorizontalWheelEvents(m_canShortCircuitHorizontalWheelEvents));
3786 Frame* WebPage::mainFrame() const
3788 return m_page ? m_page->mainFrame() : 0;
3791 FrameView* WebPage::mainFrameView() const
3793 if (Frame* frame = mainFrame())
3794 return frame->view();
3799 #if ENABLE(PAGE_VISIBILITY_API)
3800 void WebPage::setVisibilityState(int visibilityState, bool isInitialState)
3805 WebCore::PageVisibilityState state = static_cast<WebCore::PageVisibilityState>(visibilityState);
3807 if (m_visibilityState == state)
3810 FrameView* view = m_page->mainFrame() ? m_page->mainFrame()->view() : 0;
3812 if (state == WebCore::PageVisibilityStateVisible) {
3813 m_page->didMoveOnscreen();
3818 m_page->setVisibilityState(state, isInitialState);
3819 m_visibilityState = state;
3821 if (state == WebCore::PageVisibilityStateHidden) {
3822 m_page->willMoveOffscreen();
3829 #if ENABLE(TIZEN_NATIVE_MEMORY_SNAPSHOT)
3830 const char* dumpFileName = "/tmp/webkit_memory";
3833 void dumpMemorySnapshotForUrl(char* url)
3835 PrintFormat format = PRINT_FORMAT_JSON;
3837 fp = fopen(dumpFileName, "a");
3839 if (format == PRINT_FORMAT_JSON)
3842 fprintf(fp, "URL:%s\n", url);
3843 fprintf(fp, "%s", memoryPage(format).utf8().data());
3844 if (format == PRINT_FORMAT_JSON)
3845 fprintf(fp, "\"URL\":\"%s\"}\n", url);
3851 void dumpMemorySnapshot()
3853 dumpMemorySnapshotForUrl(lastUrl);
3856 void WebPage::dumpMemorySnapshot()
3858 char* url = strdup(mainWebFrame()->url().utf8().data());
3865 } // namespace WebKit