diff options
Diffstat (limited to 'Source/WebKit2/UIProcess')
640 files changed, 25851 insertions, 20547 deletions
diff --git a/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp new file mode 100644 index 000000000..2ed74d376 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this program; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#if USE(COORDINATED_GRAPHICS) + +#include "WKView.h" + +#include "WKAPICast.h" +#include "WebView.h" + +using namespace WebCore; +using namespace WebKit; + +WKViewRef WKViewCreate(WKContextRef contextRef, WKPageGroupRef pageGroupRef) +{ + RefPtr<WebView> webView = WebView::create(toImpl(contextRef), toImpl(pageGroupRef)); + return toAPI(webView.release().leakRef()); +} + +void WKViewInitialize(WKViewRef viewRef) +{ + toImpl(viewRef)->initialize(); +} + +WKSize WKViewGetSize(WKViewRef viewRef) +{ + return toAPI(toImpl(viewRef)->size()); +} + +void WKViewSetSize(WKViewRef viewRef, WKSize size) +{ + toImpl(viewRef)->setSize(toIntSize(size)); +} + +void WKViewSetViewClient(WKViewRef viewRef, const WKViewClient* client) +{ + toImpl(viewRef)->initializeClient(client); +} + +bool WKViewIsFocused(WKViewRef viewRef) +{ + return toImpl(viewRef)->isFocused(); +} + +void WKViewSetIsFocused(WKViewRef viewRef, bool isFocused) +{ + toImpl(viewRef)->setFocused(isFocused); +} + +bool WKViewIsVisible(WKViewRef viewRef) +{ + return toImpl(viewRef)->isVisible(); +} + +void WKViewSetIsVisible(WKViewRef viewRef, bool isVisible) +{ + toImpl(viewRef)->setVisible(isVisible); +} + +float WKViewGetContentScaleFactor(WKViewRef viewRef) +{ + return toImpl(viewRef)->contentScaleFactor(); +} + +void WKViewSetContentScaleFactor(WKViewRef viewRef, float scale) +{ + toImpl(viewRef)->setContentScaleFactor(scale); +} + +WKPoint WKViewGetContentPosition(WKViewRef viewRef) +{ + const WebCore::FloatPoint& result = toImpl(viewRef)->contentPosition(); + return WKPointMake(result.x(), result.y()); +} + +void WKViewSetContentPosition(WKViewRef viewRef, WKPoint position) +{ + toImpl(viewRef)->setContentPosition(WebCore::FloatPoint(position.x, position.y)); +} + +void WKViewSetUserViewportTranslation(WKViewRef viewRef, double tx, double ty) +{ + toImpl(viewRef)->setUserViewportTranslation(tx, ty); +} + +WKPoint WKViewUserViewportToContents(WKViewRef viewRef, WKPoint point) +{ + const WebCore::IntPoint& result = toImpl(viewRef)->userViewportToContents(toIntPoint(point)); + return WKPointMake(result.x(), result.y()); +} + +WKPoint WKViewUserViewportToScene(WKViewRef viewRef, WKPoint point) +{ + WebCore::IntPoint result = toImpl(viewRef)->userViewportToScene(toIntPoint(point)); + return WKPointMake(result.x(), result.y()); +} + +WKPoint WKViewContentsToUserViewport(WKViewRef viewRef, WKPoint point) +{ + WebCore::IntPoint result = toImpl(viewRef)->contentsToUserViewport(toIntPoint(point)); + return WKPointMake(result.x(), result.y()); +} + +void WKViewPaintToCurrentGLContext(WKViewRef viewRef) +{ + toImpl(viewRef)->paintToCurrentGLContext(); +} + +WKPageRef WKViewGetPage(WKViewRef viewRef) +{ + return toImpl(viewRef)->pageRef(); +} + +void WKViewSetDrawsBackground(WKViewRef viewRef, bool flag) +{ + toImpl(viewRef)->setDrawsBackground(flag); +} + +bool WKViewGetDrawsBackground(WKViewRef viewRef) +{ + return toImpl(viewRef)->drawsBackground(); +} + +void WKViewSetDrawsTransparentBackground(WKViewRef viewRef, bool flag) +{ + toImpl(viewRef)->setDrawsTransparentBackground(flag); +} + +bool WKViewGetDrawsTransparentBackground(WKViewRef viewRef) +{ + return toImpl(viewRef)->drawsTransparentBackground(); +} + +void WKViewSuspendActiveDOMObjectsAndAnimations(WKViewRef viewRef) +{ + toImpl(viewRef)->suspendActiveDOMObjectsAndAnimations(); +} + +void WKViewResumeActiveDOMObjectsAndAnimations(WKViewRef viewRef) +{ + toImpl(viewRef)->resumeActiveDOMObjectsAndAnimations(); +} + +void WKViewSetShowsAsSource(WKViewRef viewRef, bool flag) +{ + toImpl(viewRef)->setShowsAsSource(flag); +} + +bool WKViewGetShowsAsSource(WKViewRef viewRef) +{ + return toImpl(viewRef)->showsAsSource(); +} + +bool WKViewExitFullScreen(WKViewRef viewRef) +{ +#if ENABLE(FULLSCREEN_API) + return toImpl(viewRef)->exitFullScreen(); +#else + UNUSED_PARAM(viewRef); + return false; +#endif +} + +void WKViewSetOpacity(WKViewRef view, double opacity) +{ + toImpl(view)->setOpacity(opacity); +} + +double WKViewOpacity(WKViewRef view) +{ + return toImpl(view)->opacity(); +} + +void WKViewFindZoomableAreaForRect(WKViewRef viewRef, WKRect wkRect) +{ + IntRect rect = toIntRect(wkRect); + toImpl(viewRef)->findZoomableAreaForPoint(rect.center(), rect.size()); +} + +#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h new file mode 100644 index 000000000..1ee55ea34 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this program; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifndef WKView_h +#define WKView_h + +#include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> + +#ifndef __cplusplus +#include <stdbool.h> +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*WKViewCallback)(WKViewRef view, const void* clientInfo); +typedef void (*WKViewViewNeedsDisplayCallback)(WKViewRef view, WKRect area, const void* clientInfo); +typedef void (*WKViewPageDidChangeContentsSizeCallback)(WKViewRef view, WKSize size, const void* clientInfo); +typedef void (*WKViewWebProcessCrashedCallback)(WKViewRef view, WKURLRef url, const void* clientInfo); +typedef void (*WKViewPageDidChangeContentsPositionCallback)(WKViewRef view, WKPoint position, const void* clientInfo); +typedef void (*WKViewPageDidRenderFrameCallback)(WKViewRef view, WKSize contentsSize, WKRect coveredRect, const void* clientInfo); +typedef void (*WKViewPageDidChangeViewportAttributesCallback)(WKViewRef view, WKViewportAttributesRef, const void* clientInfo); +typedef void (*WKViewPageDidChangeTooltipCallback)(WKViewRef view, WKStringRef newTooltip, const void* clientInfo); +typedef void (*WKViewDidFindZoomableAreaCallback)(WKViewRef view, WKPoint point, WKRect area, const void* clientInfo); +typedef void (*WKViewDoneWithTouchEventCallback)(WKViewRef view, WKTouchEventRef touchEvent, bool wasEventHandled, const void* clientInfo); + +struct WKViewClient { + int version; + const void* clientInfo; + + // Version 0 + WKViewViewNeedsDisplayCallback viewNeedsDisplay; + WKViewPageDidChangeContentsSizeCallback didChangeContentsSize; + WKViewWebProcessCrashedCallback webProcessCrashed; + WKViewCallback webProcessDidRelaunch; + WKViewPageDidChangeContentsPositionCallback didChangeContentsPosition; + WKViewPageDidRenderFrameCallback didRenderFrame; + WKViewCallback didCompletePageTransition; + WKViewPageDidChangeViewportAttributesCallback didChangeViewportAttributes; + WKViewPageDidChangeTooltipCallback didChangeTooltip; + WKViewDidFindZoomableAreaCallback didFindZoomableArea; + WKViewDoneWithTouchEventCallback doneWithTouchEvent; +}; +typedef struct WKViewClient WKViewClient; + +enum { kWKViewClientCurrentVersion = 0 }; + +WK_EXPORT WKViewRef WKViewCreate(WKContextRef context, WKPageGroupRef pageGroup); + +WK_EXPORT void WKViewInitialize(WKViewRef); + +WK_EXPORT WKSize WKViewGetSize(WKViewRef); +WK_EXPORT void WKViewSetSize(WKViewRef, WKSize size); + +WK_EXPORT void WKViewSetViewClient(WKViewRef, const WKViewClient*); + +WK_EXPORT bool WKViewIsFocused(WKViewRef); +WK_EXPORT void WKViewSetIsFocused(WKViewRef, bool); + +WK_EXPORT bool WKViewIsVisible(WKViewRef); +WK_EXPORT void WKViewSetIsVisible(WKViewRef, bool); + +WK_EXPORT float WKViewGetContentScaleFactor(WKViewRef); +WK_EXPORT void WKViewSetContentScaleFactor(WKViewRef, float); + +WK_EXPORT WKPoint WKViewGetContentPosition(WKViewRef); +WK_EXPORT void WKViewSetContentPosition(WKViewRef, WKPoint); + +WK_EXPORT void WKViewSetUserViewportTranslation(WKViewRef, double tx, double ty); +WK_EXPORT WKPoint WKViewUserViewportToContents(WKViewRef, WKPoint); +WK_EXPORT WKPoint WKViewUserViewportToScene(WKViewRef, WKPoint); +WK_EXPORT WKPoint WKViewContentsToUserViewport(WKViewRef, WKPoint); + +WK_EXPORT void WKViewPaintToCurrentGLContext(WKViewRef); + +WK_EXPORT WKPageRef WKViewGetPage(WKViewRef); + +WK_EXPORT void WKViewSetDrawsBackground(WKViewRef, bool); +WK_EXPORT bool WKViewGetDrawsBackground(WKViewRef); + +WK_EXPORT void WKViewSetDrawsTransparentBackground(WKViewRef, bool); +WK_EXPORT bool WKViewGetDrawsTransparentBackground(WKViewRef); + +WK_EXPORT void WKViewSuspendActiveDOMObjectsAndAnimations(WKViewRef); +WK_EXPORT void WKViewResumeActiveDOMObjectsAndAnimations(WKViewRef); + +WK_EXPORT void WKViewSetShowsAsSource(WKViewRef, bool); +WK_EXPORT bool WKViewGetShowsAsSource(WKViewRef); + +WK_EXPORT bool WKViewExitFullScreen(WKViewRef); + +WK_EXPORT void WKViewSetOpacity(WKViewRef view, double opacity); +WK_EXPORT double WKViewOpacity(WKViewRef view); + +WK_EXPORT void WKViewFindZoomableAreaForRect(WKViewRef, WKRect); + +#ifdef __cplusplus +} +#endif + +#endif /* WKView_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKAPICast.h b/Source/WebKit2/UIProcess/API/C/WKAPICast.h index 3c0584c06..64c8d1abf 100644 --- a/Source/WebKit2/UIProcess/API/C/WKAPICast.h +++ b/Source/WebKit2/UIProcess/API/C/WKAPICast.h @@ -30,9 +30,11 @@ #include "CacheModel.h" #include "FontSmoothingLevel.h" #include "HTTPCookieAcceptPolicy.h" +#include "InjectedBundleHitTestResultMediaType.h" +#include "PluginModuleInfo.h" #include "ProcessModel.h" #include "ResourceCachesToClear.h" -#include "WebGrammarDetail.h" +#include "WKBundleHitTestResult.h" #include "WKContext.h" #include "WKCookieManager.h" #include "WKCredentialTypes.h" @@ -42,6 +44,7 @@ #include "WKProtectionSpaceTypes.h" #include "WKResourceCacheManager.h" #include "WKSharedAPICast.h" +#include "WebGrammarDetail.h" #include <WebCore/Credential.h> #include <WebCore/FrameLoaderTypes.h> #include <WebCore/ProtectionSpace.h> @@ -74,9 +77,7 @@ class WebGrammarDetail; class WebHitTestResult; class WebIconDatabase; class WebInspectorProxy; -class WebIntentData; -class WebIntentServiceInfo; -class WebKeyValueStorageManagerProxy; +class WebKeyValueStorageManager; class WebMediaCacheManagerProxy; class WebNavigationData; class WebNetworkInfoManagerProxy; @@ -95,6 +96,7 @@ class WebRenderLayer; class WebRenderObject; class WebTextChecker; class WebVibrationProxy; +class WebViewportAttributes; WK_ADD_API_MAPPING(WKApplicationCacheManagerRef, WebApplicationCacheManagerProxy) WK_ADD_API_MAPPING(WKAuthenticationChallengeRef, AuthenticationChallengeProxy) @@ -103,6 +105,7 @@ WK_ADD_API_MAPPING(WKBackForwardListItemRef, WebBackForwardListItem) WK_ADD_API_MAPPING(WKBackForwardListRef, WebBackForwardList) WK_ADD_API_MAPPING(WKBatteryManagerRef, WebBatteryManagerProxy) WK_ADD_API_MAPPING(WKBatteryStatusRef, WebBatteryStatus) +WK_ADD_API_MAPPING(WKBundleHitTestResultMediaType, BundleHitTestResultMediaType) WK_ADD_API_MAPPING(WKResourceCacheManagerRef, WebResourceCacheManagerProxy) WK_ADD_API_MAPPING(WKColorPickerResultListenerRef, WebColorPickerResultListenerProxy) WK_ADD_API_MAPPING(WKContextRef, WebContext) @@ -119,9 +122,7 @@ WK_ADD_API_MAPPING(WKGeolocationPositionRef, WebGeolocationPosition) WK_ADD_API_MAPPING(WKGrammarDetailRef, WebGrammarDetail) WK_ADD_API_MAPPING(WKHitTestResultRef, WebHitTestResult) WK_ADD_API_MAPPING(WKIconDatabaseRef, WebIconDatabase) -WK_ADD_API_MAPPING(WKIntentDataRef, WebIntentData) -WK_ADD_API_MAPPING(WKIntentServiceInfoRef, WebIntentServiceInfo) -WK_ADD_API_MAPPING(WKKeyValueStorageManagerRef, WebKeyValueStorageManagerProxy) +WK_ADD_API_MAPPING(WKKeyValueStorageManagerRef, WebKeyValueStorageManager) WK_ADD_API_MAPPING(WKMediaCacheManagerRef, WebMediaCacheManagerProxy) WK_ADD_API_MAPPING(WKNavigationDataRef, WebNavigationData) WK_ADD_API_MAPPING(WKNetworkInfoManagerRef, WebNetworkInfoManagerProxy) @@ -141,10 +142,41 @@ WK_ADD_API_MAPPING(WKRenderLayerRef, WebRenderLayer) WK_ADD_API_MAPPING(WKRenderObjectRef, WebRenderObject) WK_ADD_API_MAPPING(WKTextCheckerRef, WebTextChecker) WK_ADD_API_MAPPING(WKVibrationRef, WebVibrationProxy) +WK_ADD_API_MAPPING(WKViewportAttributesRef, WebViewportAttributes) WK_ADD_API_MAPPING(WKInspectorRef, WebInspectorProxy) /* Enum conversions */ +inline BundleHitTestResultMediaType toBundleHitTestResultMediaType(WKBundleHitTestResultMediaType wkMediaType) +{ + switch (wkMediaType) { + case kWKBundleHitTestResultMediaTypeNone: + return BundleHitTestResultMediaTypeNone; + case kWKBundleHitTestResultMediaTypeAudio: + return BundleHitTestResultMediaTypeAudio; + case kWKBundleHitTestResultMediaTypeVideo: + return BundleHitTestResultMediaTypeVideo; + } + + ASSERT_NOT_REACHED(); + return BundleHitTestResultMediaTypeNone; +} + +inline WKBundleHitTestResultMediaType toAPI(BundleHitTestResultMediaType mediaType) +{ + switch (mediaType) { + case BundleHitTestResultMediaTypeNone: + return kWKBundleHitTestResultMediaTypeNone; + case BundleHitTestResultMediaTypeAudio: + return kWKBundleHitTestResultMediaTypeAudio; + case BundleHitTestResultMediaTypeVideo: + return kWKBundleHitTestResultMediaTypeVideo; + } + + ASSERT_NOT_REACHED(); + return kWKBundleHitTestResultMediaTypeNone; +} + inline CacheModel toCacheModel(WKCacheModel wkCacheModel) { switch (wkCacheModel) { @@ -210,10 +242,6 @@ inline FontSmoothingLevel toFontSmoothingLevel(WKFontSmoothingLevel wkLevel) return FontSmoothingLevelMedium; case kWKFontSmoothingLevelStrong: return FontSmoothingLevelStrong; -#if PLATFORM(WIN) - case kWKFontSmoothingLevelWindows: - return FontSmoothingLevelWindows; -#endif } ASSERT_NOT_REACHED(); @@ -232,10 +260,6 @@ inline WKFontSmoothingLevel toAPI(FontSmoothingLevel level) return kWKFontSmoothingLevelMedium; case FontSmoothingLevelStrong: return kWKFontSmoothingLevelStrong; -#if PLATFORM(WIN) - case FontSmoothingLevelWindows: - return kWKFontSmoothingLevelWindows; -#endif } ASSERT_NOT_REACHED(); @@ -414,6 +438,36 @@ inline WKStorageBlockingPolicy toAPI(WebCore::SecurityOrigin::StorageBlockingPol return kWKAllowAllStorage; } +inline WKPluginLoadPolicy toWKPluginLoadPolicy(PluginModuleLoadPolicy pluginModuleLoadPolicy) +{ + switch (pluginModuleLoadPolicy) { + case PluginModuleLoadNormally: + return kWKPluginLoadPolicyLoadNormally; + case PluginModuleLoadUnsandboxed: + return kWKPluginLoadPolicyLoadUnsandboxed; + case PluginModuleBlocked: + return kWKPluginLoadPolicyBlocked; + } + + ASSERT_NOT_REACHED(); + return kWKPluginLoadPolicyBlocked; +} + +inline PluginModuleLoadPolicy toPluginModuleLoadPolicy(WKPluginLoadPolicy pluginLoadPolicy) +{ + switch (pluginLoadPolicy) { + case kWKPluginLoadPolicyLoadNormally: + return PluginModuleLoadNormally; + case kWKPluginLoadPolicyBlocked: + return PluginModuleBlocked; + case kWKPluginLoadPolicyLoadUnsandboxed: + return PluginModuleLoadUnsandboxed; + } + + ASSERT_NOT_REACHED(); + return PluginModuleBlocked; +} + inline ProxyingRefPtr<WebGrammarDetail> toAPI(const WebCore::GrammarDetail& grammarDetail) { return ProxyingRefPtr<WebGrammarDetail>(WebGrammarDetail::create(grammarDetail)); @@ -421,10 +475,6 @@ inline ProxyingRefPtr<WebGrammarDetail> toAPI(const WebCore::GrammarDetail& gram } // namespace WebKit -#if (defined(WIN32) || defined(_WIN32)) && !defined(BUILDING_QT__) -#include "WKAPICastWin.h" -#endif - #if defined(BUILDING_GTK__) #include "WKAPICastGtk.h" #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKContext.cpp b/Source/WebKit2/UIProcess/API/C/WKContext.cpp index ac461157f..1629a5627 100644 --- a/Source/WebKit2/UIProcess/API/C/WKContext.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKContext.cpp @@ -32,9 +32,26 @@ #include "WebURLRequest.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> -#include <wtf/UnusedParam.h> #include <wtf/text/WTFString.h> +// Supplements +#include "WebApplicationCacheManagerProxy.h" +#include "WebCookieManagerProxy.h" +#include "WebGeolocationManagerProxy.h" +#include "WebKeyValueStorageManager.h" +#include "WebMediaCacheManagerProxy.h" +#include "WebNotificationManagerProxy.h" +#include "WebResourceCacheManagerProxy.h" +#if ENABLE(SQL_DATABASE) +#include "WebDatabaseManagerProxy.h" +#endif +#if ENABLE(BATTERY_STATUS) +#include "WebBatteryManagerProxy.h" +#endif +#if ENABLE(NETWORK_INFO) +#include "WebNetworkInfoManagerProxy.h" +#endif + using namespace WebKit; extern "C" { @@ -62,6 +79,11 @@ WKContextRef WKContextCreateWithInjectedBundlePath(WKStringRef pathRef) return toAPI(context.release().leakRef()); } +void WKContextSetClient(WKContextRef contextRef, const WKContextClient* wkClient) +{ + toImpl(contextRef)->initializeClient(wkClient); +} + void WKContextSetInjectedBundleClient(WKContextRef contextRef, const WKContextInjectedBundleClient* wkClient) { toImpl(contextRef)->initializeInjectedBundleClient(wkClient); @@ -131,6 +153,16 @@ WKProcessModel WKContextGetProcessModel(WKContextRef contextRef) return toAPI(toImpl(contextRef)->processModel()); } +void WKContextSetMaximumNumberOfProcesses(WKContextRef contextRef, unsigned numberOfProcesses) +{ + toImpl(contextRef)->setMaximumNumberOfProcesses(numberOfProcesses); +} + +unsigned WKContextGetMaximumNumberOfProcesses(WKContextRef contextRef) +{ + return toImpl(contextRef)->maximumNumberOfProcesses(); +} + void WKContextSetAlwaysUsesComplexTextCodePath(WKContextRef contextRef, bool alwaysUseComplexTextCodePath) { toImpl(contextRef)->setAlwaysUsesComplexTextCodePath(alwaysUseComplexTextCodePath); @@ -168,18 +200,18 @@ void WKContextSetDomainRelaxationForbiddenForURLScheme(WKContextRef contextRef, WKCookieManagerRef WKContextGetCookieManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->cookieManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebCookieManagerProxy>()); } WKApplicationCacheManagerRef WKContextGetApplicationCacheManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->applicationCacheManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebApplicationCacheManagerProxy>()); } WKBatteryManagerRef WKContextGetBatteryManager(WKContextRef contextRef) { #if ENABLE(BATTERY_STATUS) - return toAPI(toImpl(contextRef)->batteryManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebBatteryManagerProxy>()); #else return 0; #endif @@ -188,7 +220,7 @@ WKBatteryManagerRef WKContextGetBatteryManager(WKContextRef contextRef) WKDatabaseManagerRef WKContextGetDatabaseManager(WKContextRef contextRef) { #if ENABLE(SQL_DATABASE) - return toAPI(toImpl(contextRef)->databaseManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebDatabaseManagerProxy>()); #else return 0; #endif @@ -196,13 +228,13 @@ WKDatabaseManagerRef WKContextGetDatabaseManager(WKContextRef contextRef) WKGeolocationManagerRef WKContextGetGeolocationManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->geolocationManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebGeolocationManagerProxy>()); } WKNetworkInfoManagerRef WKContextGetNetworkInfoManager(WKContextRef contextRef) { #if ENABLE(NETWORK_INFO) - return toAPI(toImpl(contextRef)->networkInfoManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebNetworkInfoManagerProxy>()); #else return 0; #endif @@ -215,17 +247,17 @@ WKIconDatabaseRef WKContextGetIconDatabase(WKContextRef contextRef) WKKeyValueStorageManagerRef WKContextGetKeyValueStorageManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->keyValueStorageManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebKeyValueStorageManager>()); } WKMediaCacheManagerRef WKContextGetMediaCacheManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->mediaCacheManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebMediaCacheManagerProxy>()); } WKNotificationManagerRef WKContextGetNotificationManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->notificationManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebNotificationManagerProxy>()); } WKPluginSiteDataManagerRef WKContextGetPluginSiteDataManager(WKContextRef contextRef) @@ -239,7 +271,7 @@ WKPluginSiteDataManagerRef WKContextGetPluginSiteDataManager(WKContextRef contex WKResourceCacheManagerRef WKContextGetResourceCacheManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->resourceCacheManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebResourceCacheManagerProxy>()); } void WKContextStartMemorySampler(WKContextRef contextRef, WKDoubleRef interval) @@ -257,6 +289,16 @@ void WKContextSetIconDatabasePath(WKContextRef contextRef, WKStringRef iconDatab toImpl(contextRef)->setIconDatabasePath(toImpl(iconDatabasePath)->string()); } +void WKContextAllowSpecificHTTPSCertificateForHost(WKContextRef contextRef, WKCertificateInfoRef certificateRef, WKStringRef hostRef) +{ + toImpl(contextRef)->allowSpecificHTTPSCertificateForHost(toImpl(certificateRef), toImpl(hostRef)->string()); +} + +WK_EXPORT void WKContextSetApplicationCacheDirectory(WKContextRef contextRef, WKStringRef applicationCacheDirectory) +{ + toImpl(contextRef)->setApplicationCacheDirectory(toImpl(applicationCacheDirectory)->string()); +} + void WKContextSetDatabaseDirectory(WKContextRef contextRef, WKStringRef databaseDirectory) { toImpl(contextRef)->setDatabaseDirectory(toImpl(databaseDirectory)->string()); @@ -299,7 +341,12 @@ void WKContextWarmInitialProcess(WKContextRef contextRef) void WKContextGetStatistics(WKContextRef contextRef, void* context, WKContextGetStatisticsFunction callback) { - toImpl(contextRef)->getWebCoreStatistics(DictionaryCallback::create(context, callback)); + toImpl(contextRef)->getStatistics(0xFFFFFFFF, DictionaryCallback::create(context, callback)); +} + +void WKContextGetStatisticsWithOptions(WKContextRef contextRef, WKStatisticsOptions optionsMask, void* context, WKContextGetStatisticsFunction callback) +{ + toImpl(contextRef)->getStatistics(optionsMask, DictionaryCallback::create(context, callback)); } void WKContextGarbageCollectJavaScriptObjects(WKContextRef contextRef) @@ -317,6 +364,30 @@ void WKContextSetUsesNetworkProcess(WKContextRef contextRef, bool usesNetworkPro toImpl(contextRef)->setUsesNetworkProcess(usesNetworkProcess); } +WKDictionaryRef WKContextCopyPlugInAutoStartOriginHashes(WKContextRef contextRef) +{ + return toAPI(toImpl(contextRef)->plugInAutoStartOriginHashes().leakRef()); +} + +void WKContextSetPlugInAutoStartOriginHashes(WKContextRef contextRef, WKDictionaryRef dictionaryRef) +{ + if (!dictionaryRef) + return; + toImpl(contextRef)->setPlugInAutoStartOriginHashes(*toImpl(dictionaryRef)); +} + +void WKContextSetPlugInAutoStartOrigins(WKContextRef contextRef, WKArrayRef arrayRef) +{ + if (!arrayRef) + return; + toImpl(contextRef)->setPlugInAutoStartOrigins(*toImpl(arrayRef)); +} + +void WKContextSetInvalidMessageFunction(WKContextInvalidMessageFunction invalidMessageFunction) +{ + WebContext::setInvalidMessageCallback(invalidMessageFunction); +} + // Deprecated functions. void _WKContextSetAdditionalPluginsDirectory(WKContextRef context, WKStringRef pluginsDirectory) { diff --git a/Source/WebKit2/UIProcess/API/C/WKContext.h b/Source/WebKit2/UIProcess/API/C/WKContext.h index 8f77cbd8f..3ce731e78 100644 --- a/Source/WebKit2/UIProcess/API/C/WKContext.h +++ b/Source/WebKit2/UIProcess/API/C/WKContext.h @@ -39,6 +39,24 @@ enum { }; typedef uint32_t WKCacheModel; +// Context Client +typedef void (*WKContextPlugInAutoStartOriginHashesChangedCallback)(WKContextRef context, const void *clientInfo); +typedef void (*WKContextNetworkProcessDidCrashCallback)(WKContextRef context, const void *clientInfo); +typedef void (*WKContextPlugInInformationBecameAvailableCallback)(WKContextRef context, WKArrayRef plugIn, const void *clientInfo); + +struct WKContextClient { + int version; + const void * clientInfo; + + // Version 0. + WKContextPlugInAutoStartOriginHashesChangedCallback plugInAutoStartOriginHashesChanged; + WKContextNetworkProcessDidCrashCallback networkProcessDidCrash; + WKContextPlugInInformationBecameAvailableCallback plugInInformationBecameAvailable; +}; +typedef struct WKContextClient WKContextClient; + +enum { kWKContextClientCurrentVersion = 0 }; + // Injected Bundle Client typedef void (*WKContextDidReceiveMessageFromInjectedBundleCallback)(WKContextRef page, WKStringRef messageName, WKTypeRef messageBody, const void *clientInfo); typedef void (*WKContextDidReceiveSynchronousMessageFromInjectedBundleCallback)(WKContextRef page, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void *clientInfo); @@ -129,11 +147,18 @@ enum { }; typedef uint32_t WKProcessModel; +enum { + kWKStatisticsOptionsWebContent = 1 << 0, + kWKStatisticsOptionsNetworking = 1 << 1 +}; +typedef uint32_t WKStatisticsOptions; + WK_EXPORT WKTypeID WKContextGetTypeID(); WK_EXPORT WKContextRef WKContextCreate(); WK_EXPORT WKContextRef WKContextCreateWithInjectedBundlePath(WKStringRef path); +WK_EXPORT void WKContextSetClient(WKContextRef context, const WKContextClient* client); WK_EXPORT void WKContextSetInjectedBundleClient(WKContextRef context, const WKContextInjectedBundleClient* client); WK_EXPORT void WKContextSetHistoryClient(WKContextRef context, const WKContextHistoryClient* client); WK_EXPORT void WKContextSetDownloadClient(WKContextRef context, const WKContextDownloadClient* client); @@ -152,6 +177,9 @@ WK_EXPORT WKCacheModel WKContextGetCacheModel(WKContextRef context); WK_EXPORT void WKContextSetProcessModel(WKContextRef context, WKProcessModel processModel); WK_EXPORT WKProcessModel WKContextGetProcessModel(WKContextRef context); +WK_EXPORT void WKContextSetMaximumNumberOfProcesses(WKContextRef context, unsigned numberOfProcesses); +WK_EXPORT unsigned WKContextGetMaximumNumberOfProcesses(WKContextRef context); + WK_EXPORT void WKContextStartMemorySampler(WKContextRef context, WKDoubleRef interval); WK_EXPORT void WKContextStopMemorySampler(WKContextRef context); @@ -170,10 +198,15 @@ WK_EXPORT WKResourceCacheManagerRef WKContextGetResourceCacheManager(WKContextRe typedef void (*WKContextGetStatisticsFunction)(WKDictionaryRef statistics, WKErrorRef error, void* functionContext); WK_EXPORT void WKContextGetStatistics(WKContextRef context, void* functionContext, WKContextGetStatisticsFunction function); - +WK_EXPORT void WKContextGetStatisticsWithOptions(WKContextRef context, WKStatisticsOptions statisticsMask, void* functionContext, WKContextGetStatisticsFunction function); + WK_EXPORT void WKContextGarbageCollectJavaScriptObjects(WKContextRef context); WK_EXPORT void WKContextSetJavaScriptGarbageCollectorTimerEnabled(WKContextRef context, bool enable); +WK_EXPORT WKDictionaryRef WKContextCopyPlugInAutoStartOriginHashes(WKContextRef context); +WK_EXPORT void WKContextSetPlugInAutoStartOriginHashes(WKContextRef context, WKDictionaryRef dictionary); +WK_EXPORT void WKContextSetPlugInAutoStartOrigins(WKContextRef contextRef, WKArrayRef arrayRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h b/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h index 79c2ef50f..79e7f7f25 100644 --- a/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h @@ -56,8 +56,11 @@ WK_EXPORT void WKContextSetDomainRelaxationForbiddenForURLScheme(WKContextRef co WK_EXPORT void WKContextSetIconDatabasePath(WKContextRef context, WKStringRef iconDatabasePath); +WK_EXPORT void WKContextAllowSpecificHTTPSCertificateForHost(WKContextRef context, WKCertificateInfoRef certificate, WKStringRef host); + // FIXME: These functions are only effective if called before the Web process is launched. But // we should really change these settings to be on WebPreferences and changeable at runtime. +WK_EXPORT void WKContextSetApplicationCacheDirectory(WKContextRef context, WKStringRef applicationCacheDirectory); WK_EXPORT void WKContextSetDatabaseDirectory(WKContextRef context, WKStringRef databaseDirectory); WK_EXPORT void WKContextSetLocalStorageDirectory(WKContextRef context, WKStringRef localStorageDirectory); WK_EXPORT void WKContextSetDiskCacheDirectory(WKContextRef context, WKStringRef diskCacheDirectory); @@ -76,6 +79,9 @@ WK_EXPORT void WKContextWarmInitialProcess(WKContextRef context); // At some point it should be removed. WK_EXPORT void WKContextSetUsesNetworkProcess(WKContextRef context, bool usesNetworkProcess); +typedef void (*WKContextInvalidMessageFunction)(WKStringRef messageName); +WK_EXPORT void WKContextSetInvalidMessageFunction(WKContextInvalidMessageFunction invalidMessageFunction); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKDownload.cpp b/Source/WebKit2/UIProcess/API/C/WKDownload.cpp index 45dea68ec..3588fd563 100644 --- a/Source/WebKit2/UIProcess/API/C/WKDownload.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKDownload.cpp @@ -37,6 +37,11 @@ WKTypeID WKDownloadGetTypeID() return toAPI(DownloadProxy::APIType); } +uint64_t WKDownloadGetID(WKDownloadRef download) +{ + return toImpl(download)->downloadID(); +} + WKURLRequestRef WKDownloadCopyRequest(WKDownloadRef download) { return toAPI(WebURLRequest::create(toImpl(download)->request()).leakRef()); diff --git a/Source/WebKit2/UIProcess/API/C/WKDownload.h b/Source/WebKit2/UIProcess/API/C/WKDownload.h index b81268156..8acc9106d 100644 --- a/Source/WebKit2/UIProcess/API/C/WKDownload.h +++ b/Source/WebKit2/UIProcess/API/C/WKDownload.h @@ -38,6 +38,7 @@ extern "C" { WK_EXPORT WKTypeID WKDownloadGetTypeID(); +WK_EXPORT uint64_t WKDownloadGetID(WKDownloadRef download); WK_EXPORT WKURLRequestRef WKDownloadCopyRequest(WKDownloadRef download); WK_EXPORT WKDataRef WKDownloadGetResumeData(WKDownloadRef download); WK_EXPORT void WKDownloadCancel(WKDownloadRef download); diff --git a/Source/WebKit2/UIProcess/API/C/WKFrame.cpp b/Source/WebKit2/UIProcess/API/C/WKFrame.cpp index 067c090c7..3bb375f7d 100644 --- a/Source/WebKit2/UIProcess/API/C/WKFrame.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKFrame.cpp @@ -96,16 +96,6 @@ WKPageRef WKFrameGetPage(WKFrameRef frameRef) return toAPI(toImpl(frameRef)->page()); } -WKArrayRef WKFrameCopyChildFrames(WKFrameRef frameRef) -{ - return toAPI(toImpl(frameRef)->childFrames().leakRef()); -} - -WKFrameRef WKFrameGetParentFrame(WKFrameRef frameRef) -{ - return toAPI(toImpl(frameRef)->parentFrame()); -} - WKCertificateInfoRef WKFrameGetCertificateInfo(WKFrameRef frameRef) { return toAPI(toImpl(frameRef)->certificateInfo()); @@ -183,3 +173,16 @@ void WKFrameGetWebArchive_b(WKFrameRef frameRef, WKFrameGetWebArchiveBlock block WKFrameGetWebArchive(frameRef, callGetWebArchiveBlockAndDispose, Block_copy(block)); } #endif + + +// NOTE: These are deprecated and should be removed. They currently do nothing. + +WKArrayRef WKFrameCopyChildFrames(WKFrameRef) +{ + return 0; +} + +WKFrameRef WKFrameGetParentFrame(WKFrameRef) +{ + return 0; +} diff --git a/Source/WebKit2/UIProcess/API/C/WKFrame.h b/Source/WebKit2/UIProcess/API/C/WKFrame.h index eec939e6c..d8221cc0c 100644 --- a/Source/WebKit2/UIProcess/API/C/WKFrame.h +++ b/Source/WebKit2/UIProcess/API/C/WKFrame.h @@ -58,10 +58,6 @@ WK_EXPORT WKStringRef WKFrameCopyTitle(WKFrameRef frame); WK_EXPORT WKPageRef WKFrameGetPage(WKFrameRef frame); -WK_EXPORT WKArrayRef WKFrameCopyChildFrames(WKFrameRef frame); - -WK_EXPORT WKFrameRef WKFrameGetParentFrame(WKFrameRef frame); - WK_EXPORT WKCertificateInfoRef WKFrameGetCertificateInfo(WKFrameRef frame); WK_EXPORT bool WKFrameCanProvideSource(WKFrameRef frame); @@ -88,6 +84,12 @@ typedef void (^WKFrameGetWebArchiveBlock)(WKDataRef archiveData, WKErrorRef erro WK_EXPORT void WKFrameGetWebArchive_b(WKFrameRef frame, WKFrameGetWebArchiveBlock block); #endif + +// NOTE: These are deprecated and should be removed. They currently do nothing. + +WK_EXPORT WKArrayRef WKFrameCopyChildFrames(WKFrameRef frame); +WK_EXPORT WKFrameRef WKFrameGetParentFrame(WKFrameRef frame); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKInspector.cpp b/Source/WebKit2/UIProcess/API/C/WKInspector.cpp index 891388c9a..e638609bb 100644 --- a/Source/WebKit2/UIProcess/API/C/WKInspector.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKInspector.cpp @@ -45,15 +45,27 @@ WKPageRef WKInspectorGetPage(WKInspectorRef inspectorRef) #if ENABLE(INSPECTOR) return toAPI(toImpl(inspectorRef)->page()); #else + UNUSED_PARAM(inspectorRef); return 0; #endif } +bool WKInspectorIsConnected(WKInspectorRef inspectorRef) +{ +#if ENABLE(INSPECTOR) + return toImpl(inspectorRef)->isConnected(); +#else + UNUSED_PARAM(inspectorRef); + return false; +#endif +} + bool WKInspectorIsVisible(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isVisible(); #else + UNUSED_PARAM(inspectorRef); return false; #endif } @@ -63,14 +75,35 @@ bool WKInspectorIsFront(WKInspectorRef inspectorRef) #if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isFront(); #else + UNUSED_PARAM(inspectorRef); return false; #endif } +void WKInspectorConnect(WKInspectorRef inspectorRef) +{ +#if ENABLE(INSPECTOR) + toImpl(inspectorRef)->connect(); +#else + UNUSED_PARAM(inspectorRef); +#endif +} + void WKInspectorShow(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->show(); +#else + UNUSED_PARAM(inspectorRef); +#endif +} + +void WKInspectorHide(WKInspectorRef inspectorRef) +{ +#if ENABLE(INSPECTOR) + toImpl(inspectorRef)->hide(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -78,6 +111,8 @@ void WKInspectorClose(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->close(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -85,6 +120,8 @@ void WKInspectorShowConsole(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->showConsole(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -92,6 +129,8 @@ void WKInspectorShowResources(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->showResources(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -99,6 +138,9 @@ void WKInspectorShowMainResourceForFrame(WKInspectorRef inspectorRef, WKFrameRef { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->showMainResourceForFrame(toImpl(frameRef)); +#else + UNUSED_PARAM(inspectorRef); + UNUSED_PARAM(frameRef); #endif } @@ -107,6 +149,7 @@ bool WKInspectorIsAttached(WKInspectorRef inspectorRef) #if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isAttached(); #else + UNUSED_PARAM(inspectorRef); return false; #endif } @@ -115,6 +158,8 @@ void WKInspectorAttach(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->attach(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -122,6 +167,8 @@ void WKInspectorDetach(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->detach(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -130,6 +177,7 @@ bool WKInspectorIsDebuggingJavaScript(WKInspectorRef inspectorRef) #if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isDebuggingJavaScript(); #else + UNUSED_PARAM(inspectorRef); return false; #endif } @@ -138,6 +186,8 @@ void WKInspectorToggleJavaScriptDebugging(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->toggleJavaScriptDebugging(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -146,6 +196,7 @@ bool WKInspectorIsProfilingJavaScript(WKInspectorRef inspectorRef) #if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isProfilingJavaScript(); #else + UNUSED_PARAM(inspectorRef); return false; #endif } @@ -154,6 +205,8 @@ void WKInspectorToggleJavaScriptProfiling(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->toggleJavaScriptProfiling(); +#else + UNUSED_PARAM(inspectorRef); #endif } @@ -162,6 +215,7 @@ bool WKInspectorIsProfilingPage(WKInspectorRef inspectorRef) #if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isProfilingPage(); #else + UNUSED_PARAM(inspectorRef); return false; #endif } @@ -170,5 +224,7 @@ void WKInspectorTogglePageProfiling(WKInspectorRef inspectorRef) { #if ENABLE(INSPECTOR) toImpl(inspectorRef)->togglePageProfiling(); +#else + UNUSED_PARAM(inspectorRef); #endif } diff --git a/Source/WebKit2/UIProcess/API/C/WKInspector.h b/Source/WebKit2/UIProcess/API/C/WKInspector.h index fd3438afa..203e1b3cf 100644 --- a/Source/WebKit2/UIProcess/API/C/WKInspector.h +++ b/Source/WebKit2/UIProcess/API/C/WKInspector.h @@ -40,9 +40,14 @@ WK_EXPORT WKTypeID WKInspectorGetTypeID(); WK_EXPORT WKPageRef WKInspectorGetPage(WKInspectorRef inspector); +WK_EXPORT bool WKInspectorIsConnected(WKInspectorRef inspector); WK_EXPORT bool WKInspectorIsVisible(WKInspectorRef inspector); WK_EXPORT bool WKInspectorIsFront(WKInspectorRef inspector); + +WK_EXPORT void WKInspectorConnect(WKInspectorRef inspector); + WK_EXPORT void WKInspectorShow(WKInspectorRef inspector); +WK_EXPORT void WKInspectorHide(WKInspectorRef inspector); WK_EXPORT void WKInspectorClose(WKInspectorRef inspector); WK_EXPORT void WKInspectorShowConsole(WKInspectorRef inspector); diff --git a/Source/WebKit2/UIProcess/API/C/WKIntentData.cpp b/Source/WebKit2/UIProcess/API/C/WKIntentData.cpp deleted file mode 100644 index 92e61871c..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKIntentData.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WKIntentData.h" - -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "WKAPICast.h" -#include "WKDictionary.h" -#include "WKString.h" -#include "WebSerializedScriptValue.h" - -#if ENABLE(WEB_INTENTS) -#include "WebIntentData.h" -#endif - -using namespace WebKit; - -WKTypeID WKIntentDataGetTypeID() -{ -#if ENABLE(WEB_INTENTS) - return toAPI(WebIntentData::APIType); -#else - return 0; -#endif -} - -WKStringRef WKIntentDataCopyAction(WKIntentDataRef intentRef) -{ -#if ENABLE(WEB_INTENTS) - return toCopiedAPI(toImpl(intentRef)->action()); -#else - return 0; -#endif -} - -WKStringRef WKIntentDataCopyType(WKIntentDataRef intentRef) -{ -#if ENABLE(WEB_INTENTS) - return toCopiedAPI(toImpl(intentRef)->payloadType()); -#else - return 0; -#endif -} - -WKURLRef WKIntentDataCopyService(WKIntentDataRef intentRef) -{ -#if ENABLE(WEB_INTENTS) - return toCopiedURLAPI(toImpl(intentRef)->service()); -#else - return 0; -#endif -} - -WKArrayRef WKIntentDataCopySuggestions(WKIntentDataRef intentRef) -{ -#if ENABLE(WEB_INTENTS) - return toAPI(toImpl(intentRef)->suggestions().leakRef()); -#else - return 0; -#endif -} - -WKStringRef WKIntentDataCopyExtraValue(WKIntentDataRef intentRef, WKStringRef key) -{ -#if ENABLE(WEB_INTENTS) - return toCopiedAPI(toImpl(intentRef)->extra(toWTFString(key))); -#else - return 0; -#endif -} - -WKDictionaryRef WKIntentDataCopyExtras(WKIntentDataRef intentRef) -{ -#if ENABLE(WEB_INTENTS) - return toAPI(toImpl(intentRef)->extras().leakRef()); -#else - return 0; -#endif -} diff --git a/Source/WebKit2/UIProcess/API/C/WKIntentServiceInfo.cpp b/Source/WebKit2/UIProcess/API/C/WKIntentServiceInfo.cpp deleted file mode 100644 index 5a30fb71a..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKIntentServiceInfo.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WKIntentServiceInfo.h" - -#include "WKAPICast.h" - -#if ENABLE(WEB_INTENTS_TAG) -#include "WebIntentServiceInfo.h" -#endif - -using namespace WebKit; - -WKTypeID WKIntentServiceInfoGetTypeID() -{ -#if ENABLE(WEB_INTENTS_TAG) - return toAPI(WebIntentServiceInfo::APIType); -#else - return 0; -#endif -} - -WKStringRef WKIntentServiceInfoCopyAction(WKIntentServiceInfoRef serviceRef) -{ -#if ENABLE(WEB_INTENTS_TAG) - return toCopiedAPI(toImpl(serviceRef)->action()); -#else - return 0; -#endif -} - -WKStringRef WKIntentServiceInfoCopyType(WKIntentServiceInfoRef serviceRef) -{ -#if ENABLE(WEB_INTENTS_TAG) - return toCopiedAPI(toImpl(serviceRef)->payloadType()); -#else - return 0; -#endif -} - -WKURLRef WKIntentServiceInfoCopyHref(WKIntentServiceInfoRef serviceRef) -{ -#if ENABLE(WEB_INTENTS_TAG) - return toCopiedURLAPI(toImpl(serviceRef)->href()); -#else - return 0; -#endif -} - -WKStringRef WKIntentServiceInfoCopyTitle(WKIntentServiceInfoRef serviceRef) -{ -#if ENABLE(WEB_INTENTS_TAG) - return toCopiedAPI(toImpl(serviceRef)->title()); -#else - return 0; -#endif -} - -WKStringRef WKIntentServiceInfoCopyDisposition(WKIntentServiceInfoRef serviceRef) -{ -#if ENABLE(WEB_INTENTS_TAG) - return toCopiedAPI(toImpl(serviceRef)->disposition()); -#else - return 0; -#endif -} diff --git a/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp b/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp index f050692b4..d33c056bf 100644 --- a/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp @@ -27,13 +27,13 @@ #include "WKKeyValueStorageManager.h" #include "WKAPICast.h" -#include "WebKeyValueStorageManagerProxy.h" +#include "WebKeyValueStorageManager.h" using namespace WebKit; WKTypeID WKKeyValueStorageManagerGetTypeID() { - return toAPI(WebKeyValueStorageManagerProxy::APIType); + return toAPI(WebKeyValueStorageManager::APIType); } void WKKeyValueStorageManagerGetKeyValueStorageOrigins(WKKeyValueStorageManagerRef keyValueStorageManagerRef, void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) diff --git a/Source/WebKit2/UIProcess/API/C/WKNavigationData.cpp b/Source/WebKit2/UIProcess/API/C/WKNavigationData.cpp index ba09d4d81..e0100bed8 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNavigationData.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationData.cpp @@ -44,6 +44,12 @@ WKStringRef WKNavigationDataCopyTitle(WKNavigationDataRef navigationDataRef) WKURLRef WKNavigationDataCopyURL(WKNavigationDataRef navigationDataRef) { + // This returns the URL of the original request for backwards-compatibility purposes. + return toCopiedURLAPI(toImpl(navigationDataRef)->originalRequest().url()); +} + +WKURLRef WKNavigationDataCopyNavigationDestinationURL(WKNavigationDataRef navigationDataRef) +{ return toCopiedURLAPI(toImpl(navigationDataRef)->url()); } diff --git a/Source/WebKit2/UIProcess/API/C/WKNavigationData.h b/Source/WebKit2/UIProcess/API/C/WKNavigationData.h index cf5d1e53a..e5d3a15f8 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNavigationData.h +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationData.h @@ -35,8 +35,11 @@ extern "C" { WK_EXPORT WKTypeID WKNavigationDataGetTypeID(); WK_EXPORT WKStringRef WKNavigationDataCopyTitle(WKNavigationDataRef navigationData); -WK_EXPORT WKURLRef WKNavigationDataCopyURL(WKNavigationDataRef navigationData); WK_EXPORT WKURLRequestRef WKNavigationDataCopyOriginalRequest(WKNavigationDataRef navigationData); +WK_EXPORT WKURLRef WKNavigationDataCopyNavigationDestinationURL(WKNavigationDataRef navigationDataRef); + +// This returns the URL of the original request for backwards-compatibility purposes. +WK_EXPORT WKURLRef WKNavigationDataCopyURL(WKNavigationDataRef navigationData); #ifdef __cplusplus } diff --git a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp index 6a7c53e8f..29ecf543b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp @@ -56,3 +56,8 @@ WKStringRef WKOpenPanelParametersCopyCapture(WKOpenPanelParametersRef parameters return 0; #endif } + +WKArrayRef WKOpenPanelParametersCopySelectedFileNames(WKOpenPanelParametersRef parametersRef) +{ + return toAPI(toImpl(parametersRef)->selectedFileNames().leakRef()); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.h b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.h index ddcaae265..3801c2f7b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.h +++ b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.h @@ -45,6 +45,8 @@ WK_EXPORT WKArrayRef WKOpenPanelParametersCopyAcceptedMIMETypes(WKOpenPanelParam WK_EXPORT WKStringRef WKOpenPanelParametersCopyCapture(WKOpenPanelParametersRef parameters); +WK_EXPORT WKArrayRef WKOpenPanelParametersCopySelectedFileNames(WKOpenPanelParametersRef parametersRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKPage.cpp b/Source/WebKit2/UIProcess/API/C/WKPage.cpp index c0e17c429..611186f5a 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPage.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPage.cpp @@ -29,6 +29,7 @@ #include "PrintInfo.h" #include "WKAPICast.h" +#include "WKPluginInformation.h" #include "WebBackForwardList.h" #include "WebData.h" #include "WebPageProxy.h" @@ -39,6 +40,10 @@ #include <Block.h> #endif +#if ENABLE(CONTEXT_MENUS) +#include "WebContextMenuItem.h" +#endif + using namespace WebCore; using namespace WebKit; @@ -62,31 +67,81 @@ void WKPageLoadURL(WKPageRef pageRef, WKURLRef URLRef) toImpl(pageRef)->loadURL(toWTFString(URLRef)); } +void WKPageLoadURLWithUserData(WKPageRef pageRef, WKURLRef URLRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadURL(toWTFString(URLRef), toImpl(userDataRef)); +} + void WKPageLoadURLRequest(WKPageRef pageRef, WKURLRequestRef urlRequestRef) { toImpl(pageRef)->loadURLRequest(toImpl(urlRequestRef)); } +void WKPageLoadURLRequestWithUserData(WKPageRef pageRef, WKURLRequestRef urlRequestRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadURLRequest(toImpl(urlRequestRef), toImpl(userDataRef)); +} + +void WKPageLoadFile(WKPageRef pageRef, WKURLRef fileURL, WKURLRef resourceDirectoryURL) +{ + toImpl(pageRef)->loadFile(toWTFString(fileURL), toWTFString(resourceDirectoryURL)); +} + +void WKPageLoadFileWithUserData(WKPageRef pageRef, WKURLRef fileURL, WKURLRef resourceDirectoryURL, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadFile(toWTFString(fileURL), toWTFString(resourceDirectoryURL), toImpl(userDataRef)); +} + +void WKPageLoadData(WKPageRef pageRef, WKDataRef dataRef, WKStringRef MIMETypeRef, WKStringRef encodingRef, WKURLRef baseURLRef) +{ + toImpl(pageRef)->loadData(toImpl(dataRef), toWTFString(MIMETypeRef), toWTFString(encodingRef), toWTFString(baseURLRef)); +} + +void WKPageLoadDataWithUserData(WKPageRef pageRef, WKDataRef dataRef, WKStringRef MIMETypeRef, WKStringRef encodingRef, WKURLRef baseURLRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadData(toImpl(dataRef), toWTFString(MIMETypeRef), toWTFString(encodingRef), toWTFString(baseURLRef), toImpl(userDataRef)); +} + void WKPageLoadHTMLString(WKPageRef pageRef, WKStringRef htmlStringRef, WKURLRef baseURLRef) { toImpl(pageRef)->loadHTMLString(toWTFString(htmlStringRef), toWTFString(baseURLRef)); } +void WKPageLoadHTMLStringWithUserData(WKPageRef pageRef, WKStringRef htmlStringRef, WKURLRef baseURLRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadHTMLString(toWTFString(htmlStringRef), toWTFString(baseURLRef), toImpl(userDataRef)); +} + void WKPageLoadAlternateHTMLString(WKPageRef pageRef, WKStringRef htmlStringRef, WKURLRef baseURLRef, WKURLRef unreachableURLRef) { toImpl(pageRef)->loadAlternateHTMLString(toWTFString(htmlStringRef), toWTFString(baseURLRef), toWTFString(unreachableURLRef)); } +void WKPageLoadAlternateHTMLStringWithUserData(WKPageRef pageRef, WKStringRef htmlStringRef, WKURLRef baseURLRef, WKURLRef unreachableURLRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadAlternateHTMLString(toWTFString(htmlStringRef), toWTFString(baseURLRef), toWTFString(unreachableURLRef), toImpl(userDataRef)); +} + void WKPageLoadPlainTextString(WKPageRef pageRef, WKStringRef plainTextStringRef) { toImpl(pageRef)->loadPlainTextString(toWTFString(plainTextStringRef)); } +void WKPageLoadPlainTextStringWithUserData(WKPageRef pageRef, WKStringRef plainTextStringRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadPlainTextString(toWTFString(plainTextStringRef), toImpl(userDataRef)); +} + void WKPageLoadWebArchiveData(WKPageRef pageRef, WKDataRef webArchiveDataRef) { toImpl(pageRef)->loadWebArchiveData(toImpl(webArchiveDataRef)); } +void WKPageLoadWebArchiveDataWithUserData(WKPageRef pageRef, WKDataRef webArchiveDataRef, WKTypeRef userDataRef) +{ + toImpl(pageRef)->loadWebArchiveData(toImpl(webArchiveDataRef), toImpl(userDataRef)); +} + void WKPageStopLoading(WKPageRef pageRef) { toImpl(pageRef)->stopLoading(); @@ -187,6 +242,7 @@ WKInspectorRef WKPageGetInspector(WKPageRef pageRef) #if defined(ENABLE_INSPECTOR) && ENABLE_INSPECTOR return toAPI(toImpl(pageRef)->inspector()); #else + UNUSED_PARAM(pageRef); return 0; #endif } @@ -262,6 +318,12 @@ WKStringRef WKPageGetSessionHistoryURLValueType() return toAPI(sessionHistoryURLValueType); } +WKStringRef WKPageGetSessionBackForwardListItemValueType() +{ + static WebString* sessionBackForwardListValueType = WebString::create("SessionBackForwardListItem").leakRef(); + return toAPI(sessionBackForwardListValueType); +} + WKDataRef WKPageCopySessionState(WKPageRef pageRef, void *context, WKPageSessionStateFilterCallback filter) { return toAPI(toImpl(pageRef)->sessionStateData(filter, context).leakRef()); @@ -392,6 +454,27 @@ bool WKPageIsPinnedToBottomSide(WKPageRef pageRef) return toImpl(pageRef)->isPinnedToBottomSide(); } + +bool WKPageRubberBandsAtBottom(WKPageRef pageRef) +{ + return toImpl(pageRef)->rubberBandsAtBottom(); +} + +void WKPageSetRubberBandsAtBottom(WKPageRef pageRef, bool rubberBandsAtBottom) +{ + toImpl(pageRef)->setRubberBandsAtBottom(rubberBandsAtBottom); +} + +bool WKPageRubberBandsAtTop(WKPageRef pageRef) +{ + return toImpl(pageRef)->rubberBandsAtTop(); +} + +void WKPageSetRubberBandsAtTop(WKPageRef pageRef, bool rubberBandsAtTop) +{ + toImpl(pageRef)->setRubberBandsAtTop(rubberBandsAtTop); +} + void WKPageSetPaginationMode(WKPageRef pageRef, WKPaginationMode paginationMode) { Pagination::Mode mode; @@ -496,6 +579,21 @@ void WKPageCenterSelectionInVisibleArea(WKPageRef pageRef) return toImpl(pageRef)->centerSelectionInVisibleArea(); } +void WKPageFindStringMatches(WKPageRef pageRef, WKStringRef string, WKFindOptions options, unsigned maxMatchCount) +{ + toImpl(pageRef)->findStringMatches(toImpl(string)->string(), toFindOptions(options), maxMatchCount); +} + +void WKPageGetImageForFindMatch(WKPageRef pageRef, int32_t matchIndex) +{ + toImpl(pageRef)->getImageForFindMatch(matchIndex); +} + +void WKPageSelectFindMatch(WKPageRef pageRef, int32_t matchIndex) +{ + toImpl(pageRef)->selectFindMatch(matchIndex); +} + void WKPageFindString(WKPageRef pageRef, WKStringRef string, WKFindOptions options, unsigned maxMatchCount) { toImpl(pageRef)->findString(toImpl(string)->string(), toFindOptions(options), maxMatchCount); @@ -523,6 +621,11 @@ void WKPageSetPageFindClient(WKPageRef pageRef, const WKPageFindClient* wkClient toImpl(pageRef)->initializeFindClient(wkClient); } +void WKPageSetPageFindMatchesClient(WKPageRef pageRef, const WKPageFindMatchesClient* wkClient) +{ + toImpl(pageRef)->initializeFindMatchesClient(wkClient); +} + void WKPageSetPageFormClient(WKPageRef pageRef, const WKPageFormClient* wkClient) { toImpl(pageRef)->initializeFormClient(wkClient); @@ -538,11 +641,6 @@ void WKPageSetPagePolicyClient(WKPageRef pageRef, const WKPagePolicyClient* wkCl toImpl(pageRef)->initializePolicyClient(wkClient); } -void WKPageSetPageResourceLoadClient(WKPageRef pageRef, const WKPageResourceLoadClient* wkClient) -{ - toImpl(pageRef)->initializeResourceLoadClient(wkClient); -} - void WKPageSetPageUIClient(WKPageRef pageRef, const WKPageUIClient* wkClient) { toImpl(pageRef)->initializeUIClient(wkClient); @@ -624,6 +722,11 @@ void WKPageGetContentsAsString_b(WKPageRef pageRef, WKPageGetSourceForFrameBlock } #endif +void WKPageGetSelectionAsWebArchiveData(WKPageRef pageRef, void* context, WKPageGetSelectionAsWebArchiveDataFunction callback) +{ + toImpl(pageRef)->getSelectionAsWebArchiveData(DataCallback::create(context, callback)); +} + void WKPageGetContentsAsMHTMLData(WKPageRef pageRef, bool useBinaryEncoding, void* context, WKPageGetContentsAsMHTMLDataFunction callback) { #if ENABLE(MHTML) @@ -688,7 +791,7 @@ void WKPageExecuteCommand(WKPageRef pageRef, WKStringRef command) toImpl(pageRef)->executeEditCommand(toImpl(command)->string()); } -#if PLATFORM(MAC) || PLATFORM(WIN) +#if PLATFORM(MAC) struct ComputedPagesContext { ComputedPagesContext(WKPageComputePagesForPrintingFunction callback, void* context) : callback(callback) @@ -738,13 +841,6 @@ void WKPageEndPrinting(WKPageRef page) } #endif -void WKPageDeliverIntentToFrame(WKPageRef page, WKFrameRef frame, WKIntentDataRef intent) -{ -#if ENABLE(WEB_INTENTS) - toImpl(page)->deliverIntentToFrame(toImpl(frame), toImpl(intent)); -#endif -} - WKImageRef WKPageCreateSnapshotOfVisibleContent(WKPageRef) { return 0; @@ -774,3 +870,101 @@ void WKPageSetMayStartMediaWhenInWindow(WKPageRef pageRef, bool mayStartMedia) { toImpl(pageRef)->setMayStartMediaWhenInWindow(mayStartMedia); } + + +void WKPageSelectContextMenuItem(WKPageRef page, WKContextMenuItemRef item) +{ +#if ENABLE(CONTEXT_MENUS) + toImpl(page)->contextMenuItemSelected(*(toImpl(item)->data())); +#endif +} + +WKScrollPinningBehavior WKPageGetScrollPinningBehavior(WKPageRef page) +{ + ScrollPinningBehavior pinning = toImpl(page)->scrollPinningBehavior(); + + switch (pinning) { + case WebCore::ScrollPinningBehavior::DoNotPin: + return kWKScrollPinningBehaviorDoNotPin; + case WebCore::ScrollPinningBehavior::PinToTop: + return kWKScrollPinningBehaviorPinToTop; + case WebCore::ScrollPinningBehavior::PinToBottom: + return kWKScrollPinningBehaviorPinToBottom; + } + + ASSERT_NOT_REACHED(); + return kWKScrollPinningBehaviorDoNotPin; +} + +void WKPageSetScrollPinningBehavior(WKPageRef page, WKScrollPinningBehavior pinning) +{ + ScrollPinningBehavior corePinning = ScrollPinningBehavior::DoNotPin; + + switch (pinning) { + case kWKScrollPinningBehaviorDoNotPin: + corePinning = ScrollPinningBehavior::DoNotPin; + break; + case kWKScrollPinningBehaviorPinToTop: + corePinning = ScrollPinningBehavior::PinToTop; + break; + case kWKScrollPinningBehaviorPinToBottom: + corePinning = ScrollPinningBehavior::PinToBottom; + break; + default: + ASSERT_NOT_REACHED(); + } + + toImpl(page)->setScrollPinningBehavior(corePinning); +} + + + +// -- DEPRECATED -- + +void WKPageSetInvalidMessageFunction(WKPageInvalidMessageFunction) +{ + // FIXME: Remove this function when doing so won't break WebKit nightlies. +} + +WKStringRef WKPageGetPluginInformationBundleIdentifierKey() +{ + return WKPluginInformationBundleIdentifierKey(); +} + +WKStringRef WKPageGetPluginInformationBundleVersionKey() +{ + return WKPluginInformationBundleVersionKey(); +} + +WKStringRef WKPageGetPluginInformationDisplayNameKey() +{ + return WKPluginInformationDisplayNameKey(); +} + +WKStringRef WKPageGetPluginInformationFrameURLKey() +{ + return WKPluginInformationFrameURLKey(); +} + +WKStringRef WKPageGetPluginInformationMIMETypeKey() +{ + return WKPluginInformationMIMETypeKey(); +} + +WKStringRef WKPageGetPluginInformationPageURLKey() +{ + return WKPluginInformationPageURLKey(); +} + +WKStringRef WKPageGetPluginInformationPluginspageAttributeURLKey() +{ + return WKPluginInformationPluginspageAttributeURLKey(); +} + +WKStringRef WKPageGetPluginInformationPluginURLKey() +{ + return WKPluginInformationPluginURLKey(); +} + +// -- DEPRECATED -- + diff --git a/Source/WebKit2/UIProcess/API/C/WKPage.h b/Source/WebKit2/UIProcess/API/C/WKPage.h index b002eef0f..dc57c523d 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPage.h +++ b/Source/WebKit2/UIProcess/API/C/WKPage.h @@ -49,6 +49,14 @@ enum { }; typedef uint32_t WKFocusDirection; +enum { + kWKPluginLoadPolicyLoadNormally = 0, + kWKPluginLoadPolicyBlocked, + kWKPluginLoadPolicyInactive, + kWKPluginLoadPolicyLoadUnsandboxed, +}; +typedef uint32_t WKPluginLoadPolicy; + typedef void (*WKPageCallback)(WKPageRef page, const void* clientInfo); // FrameLoad Client @@ -73,13 +81,14 @@ typedef void (*WKPageDidChangeBackForwardListCallback)(WKPageRef page, WKBackFor typedef bool (*WKPageShouldGoToBackForwardListItemCallback)(WKPageRef page, WKBackForwardListItemRef item, const void *clientInfo); typedef void (*WKPageDidNewFirstVisuallyNonEmptyLayoutCallback)(WKPageRef page, WKTypeRef userData, const void *clientInfo); typedef void (*WKPageWillGoToBackForwardListItemCallback)(WKPageRef page, WKBackForwardListItemRef item, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPagePluginDidFailCallback)(WKPageRef page, WKErrorCode errorCode, WKStringRef mimeType, WKStringRef pluginIdentifier, WKStringRef pluginVersion, const void* clientInfo); -typedef void (*WKPageDidReceiveIntentForFrameCallback)(WKPageRef page, WKFrameRef frame, WKIntentDataRef intent, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageRegisterIntentServiceForFrameCallback)(WKPageRef page, WKFrameRef frame, WKIntentServiceInfoRef serviceInfo, WKTypeRef userData, const void *clientInfo); typedef void (*WKPageDidLayoutCallback)(WKPageRef page, WKLayoutMilestones milestones, WKTypeRef userData, const void *clientInfo); +typedef WKPluginLoadPolicy (*WKPagePluginLoadPolicyCallback)(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInfoDictionary, WKStringRef* unavailabilityDescription, const void* clientInfo); +typedef void (*WKPagePluginDidFailCallback)(WKPageRef page, WKErrorCode errorCode, WKDictionaryRef pluginInfoDictionary, const void* clientInfo); // Deprecated typedef void (*WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0)(WKPageRef page, WKStringRef mimeType, const void* clientInfo); +typedef void (*WKPagePluginDidFailCallback_deprecatedForUseWithV1)(WKPageRef page, WKErrorCode errorCode, WKStringRef mimeType, WKStringRef pluginIdentifier, WKStringRef pluginVersion, const void* clientInfo); +typedef WKPluginLoadPolicy (*WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2)(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInfoDictionary, const void* clientInfo); struct WKPageLoaderClient { int version; @@ -124,17 +133,22 @@ struct WKPageLoaderClient { WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; WKPageCallback interactionOccurredWhileProcessUnresponsive; - WKPagePluginDidFailCallback pluginDidFail; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; // Version 2 - WKPageDidReceiveIntentForFrameCallback didReceiveIntentForFrame; - WKPageRegisterIntentServiceForFrameCallback registerIntentServiceForFrame; + void (*didReceiveIntentForFrame_unavailable)(void); + void (*registerIntentServiceForFrame_unavailable)(void); WKPageDidLayoutCallback didLayout; + WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2 pluginLoadPolicy_deprecatedForUseWithV2; + WKPagePluginDidFailCallback pluginDidFail; + + // Version 3 + WKPagePluginLoadPolicyCallback pluginLoadPolicy; }; typedef struct WKPageLoaderClient WKPageLoaderClient; -enum { kWKPageLoaderClientCurrentVersion = 2 }; +enum { kWKPageLoaderClientCurrentVersion = 3 }; // Policy Client. typedef void (*WKPageDecidePolicyForNavigationActionCallback)(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); @@ -166,28 +180,6 @@ typedef struct WKPageFormClient WKPageFormClient; enum { kWKPageFormClientCurrentVersion = 0 }; -// Resource Load Client. -typedef void (*WKPageDidInitiateLoadForResourceCallback)(WKPageRef page, WKFrameRef frame, uint64_t resourceIdentifier, WKURLRequestRef request, bool pageIsProvisionallyLoading, const void* clientInfo); -typedef void (*WKPageDidSendRequestForResourceCallback)(WKPageRef page, WKFrameRef frame, uint64_t resourceIdentifier, WKURLRequestRef request, WKURLResponseRef redirectResponse, const void* clientInfo); -typedef void (*WKPageDidReceiveResponseForResourceCallback)(WKPageRef page, WKFrameRef frame, uint64_t resourceIdentifier, WKURLResponseRef response, const void* clientInfo); -typedef void (*WKPageDidReceiveContentLengthForResourceCallback)(WKPageRef page, WKFrameRef frame, uint64_t resourceIdentifier, uint64_t contentLength, const void* clientInfo); -typedef void (*WKPageDidFinishLoadForResourceCallback)(WKPageRef page, WKFrameRef frame, uint64_t resourceIdentifier, const void* clientInfo); -typedef void (*WKPageDidFailLoadForResourceCallback)(WKPageRef page, WKFrameRef frame, uint64_t resourceIdentifier, WKErrorRef error, const void* clientInfo); - -struct WKPageResourceLoadClient { - int version; - const void * clientInfo; - WKPageDidInitiateLoadForResourceCallback didInitiateLoadForResource; - WKPageDidSendRequestForResourceCallback didSendRequestForResource; - WKPageDidReceiveResponseForResourceCallback didReceiveResponseForResource; - WKPageDidReceiveContentLengthForResourceCallback didReceiveContentLengthForResource; - WKPageDidFinishLoadForResourceCallback didFinishLoadForResource; - WKPageDidFailLoadForResourceCallback didFailLoadForResource; -}; -typedef struct WKPageResourceLoadClient WKPageResourceLoadClient; - -enum { kWKPageResourceLoadClientCurrentVersion = 0 }; - enum { kWKPluginUnavailabilityReasonPluginMissing, kWKPluginUnavailabilityReasonPluginCrashed, @@ -229,14 +221,15 @@ typedef void (*WKPagePrintFrameCallback)(WKPageRef page, WKFrameRef frame, const typedef void (*WKPageSaveDataToFileInDownloadsFolderCallback)(WKPageRef page, WKStringRef suggestedFilename, WKStringRef mimeType, WKURLRef originatingURL, WKDataRef data, const void* clientInfo); typedef bool (*WKPageShouldInterruptJavaScriptCallback)(WKPageRef page, const void *clientInfo); typedef void (*WKPageDecidePolicyForNotificationPermissionRequestCallback)(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef permissionRequest, const void *clientInfo); -typedef void (*WKPageUnavailablePluginButtonClickedCallback)(WKPageRef page, WKPluginUnavailabilityReason pluginUnavailabilityReason, WKStringRef mimeType, WKStringRef url, WKStringRef pluginsPageURL, const void* clientInfo); typedef void (*WKPageShowColorPickerCallback)(WKPageRef page, WKStringRef initialColor, WKColorPickerResultListenerRef listener, const void* clientInfo); typedef void (*WKPageHideColorPickerCallback)(WKPageRef page, const void* clientInfo); +typedef void (*WKPageUnavailablePluginButtonClickedCallback)(WKPageRef page, WKPluginUnavailabilityReason pluginUnavailabilityReason, WKDictionaryRef pluginInfoDictionary, const void* clientInfo); // Deprecated typedef WKPageRef (*WKPageCreateNewPageCallback_deprecatedForUseWithV0)(WKPageRef page, WKDictionaryRef features, WKEventModifiers modifiers, WKEventMouseButton mouseButton, const void *clientInfo); typedef void (*WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0)(WKPageRef page, WKEventModifiers modifiers, WKTypeRef userData, const void *clientInfo); typedef void (*WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0)(WKPageRef page, WKStringRef mimeType, WKStringRef url, WKStringRef pluginsPageURL, const void* clientInfo); +typedef void (*WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1)(WKPageRef page, WKPluginUnavailabilityReason pluginUnavailabilityReason, WKStringRef mimeType, WKStringRef url, WKStringRef pluginsPageURL, const void* clientInfo); struct WKPageUIClient { int version; @@ -287,11 +280,12 @@ struct WKPageUIClient { WKPageCreateNewPageCallback createNewPage; WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; - WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; // Version 2 WKPageShowColorPickerCallback showColorPicker; WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; }; typedef struct WKPageUIClient WKPageUIClient; @@ -317,10 +311,26 @@ enum { kWKMoreThanMaximumMatchCount = -1 }; +// Find match client. +typedef void (*WKPageDidFindStringMatchesCallback)(WKPageRef page, WKStringRef string, WKArrayRef matches, int firstIndex, const void* clientInfo); +typedef void (*WKPageDidGetImageForMatchResultCallback)(WKPageRef page, WKImageRef image, uint32_t index, const void* clientInfo); + +struct WKPageFindMatchesClient { + int version; + const void * clientInfo; + WKPageDidFindStringMatchesCallback didFindStringMatches; + WKPageDidGetImageForMatchResultCallback didGetImageForMatchResult; +}; +typedef struct WKPageFindMatchesClient WKPageFindMatchesClient; + +enum { kWKPageFindMatchesClientCurrentVersion = 0 }; + // ContextMenu client typedef void (*WKPageGetContextMenuFromProposedContextMenuCallback)(WKPageRef page, WKArrayRef proposedMenu, WKArrayRef* newMenu, WKHitTestResultRef hitTestResult, WKTypeRef userData, const void* clientInfo); typedef void (*WKPageCustomContextMenuItemSelectedCallback)(WKPageRef page, WKContextMenuItemRef contextMenuItem, const void* clientInfo); typedef void (*WKPageContextMenuDismissedCallback)(WKPageRef page, const void* clientInfo); +typedef void (*WKPageShowContextMenuCallback)(WKPageRef page, WKPoint menuLocation, WKArrayRef menuItems, const void* clientInfo); +typedef void (*WKPageHideContextMenuCallback)(WKPageRef page, const void* clientInfo); // Deprecated typedef void (*WKPageGetContextMenuFromProposedContextMenuCallback_deprecatedForUseWithV0)(WKPageRef page, WKArrayRef proposedMenu, WKArrayRef* newMenu, WKTypeRef userData, const void* clientInfo); @@ -337,22 +347,39 @@ struct WKPageContextMenuClient { // Version 2 WKPageGetContextMenuFromProposedContextMenuCallback getContextMenuFromProposedMenu; + + // Version 3 + WKPageShowContextMenuCallback showContextMenu; + WKPageHideContextMenuCallback hideContextMenu; }; typedef struct WKPageContextMenuClient WKPageContextMenuClient; -enum { kWKPageContextMenuClientCurrentVersion = 2 }; +enum { kWKPageContextMenuClientCurrentVersion = 3 }; WK_EXPORT WKTypeID WKPageGetTypeID(); WK_EXPORT WKContextRef WKPageGetContext(WKPageRef page); WK_EXPORT WKPageGroupRef WKPageGetPageGroup(WKPageRef page); +// URL Requests WK_EXPORT void WKPageLoadURL(WKPageRef page, WKURLRef url); +WK_EXPORT void WKPageLoadURLWithUserData(WKPageRef page, WKURLRef url, WKTypeRef userData); WK_EXPORT void WKPageLoadURLRequest(WKPageRef page, WKURLRequestRef urlRequest); +WK_EXPORT void WKPageLoadURLRequestWithUserData(WKPageRef page, WKURLRequestRef urlRequest, WKTypeRef userData); +WK_EXPORT void WKPageLoadFile(WKPageRef page, WKURLRef fileURL, WKURLRef resourceDirectoryURL); +WK_EXPORT void WKPageLoadFileWithUserData(WKPageRef page, WKURLRef fileURL, WKURLRef resourceDirectoryURL, WKTypeRef userData); + +// Data Requests +WK_EXPORT void WKPageLoadData(WKPageRef page, WKDataRef data, WKStringRef MIMEType, WKStringRef encoding, WKURLRef baseURL); +WK_EXPORT void WKPageLoadDataWithUserData(WKPageRef page, WKDataRef data, WKStringRef MIMEType, WKStringRef encoding, WKURLRef baseURL, WKTypeRef userData); WK_EXPORT void WKPageLoadHTMLString(WKPageRef page, WKStringRef htmlString, WKURLRef baseURL); +WK_EXPORT void WKPageLoadHTMLStringWithUserData(WKPageRef page, WKStringRef htmlString, WKURLRef baseURL, WKTypeRef userData); WK_EXPORT void WKPageLoadAlternateHTMLString(WKPageRef page, WKStringRef htmlString, WKURLRef baseURL, WKURLRef unreachableURL); +WK_EXPORT void WKPageLoadAlternateHTMLStringWithUserData(WKPageRef page, WKStringRef htmlString, WKURLRef baseURL, WKURLRef unreachableURL, WKTypeRef userData); WK_EXPORT void WKPageLoadPlainTextString(WKPageRef page, WKStringRef plainTextString); +WK_EXPORT void WKPageLoadPlainTextStringWithUserData(WKPageRef page, WKStringRef plainTextString, WKTypeRef userData); WK_EXPORT void WKPageLoadWebArchiveData(WKPageRef page, WKDataRef webArchiveData); +WK_EXPORT void WKPageLoadWebArchiveDataWithUserData(WKPageRef page, WKDataRef webArchiveData, WKTypeRef userData); WK_EXPORT void WKPageStopLoading(WKPageRef page); WK_EXPORT void WKPageReload(WKPageRef page); @@ -407,6 +434,7 @@ WK_EXPORT void WKPageSetCustomTextEncodingName(WKPageRef page, WKStringRef encod WK_EXPORT void WKPageTerminate(WKPageRef page); WK_EXPORT WKStringRef WKPageGetSessionHistoryURLValueType(void); +WK_EXPORT WKStringRef WKPageGetSessionBackForwardListItemValueType(void); typedef bool (*WKPageSessionStateFilterCallback)(WKPageRef page, WKStringRef valueType, WKTypeRef value, void* context); WK_EXPORT WKDataRef WKPageCopySessionState(WKPageRef page, void* context, WKPageSessionStateFilterCallback urlAllowedCallback); @@ -445,6 +473,11 @@ WK_EXPORT bool WKPageIsPinnedToRightSide(WKPageRef page); WK_EXPORT bool WKPageIsPinnedToTopSide(WKPageRef page); WK_EXPORT bool WKPageIsPinnedToBottomSide(WKPageRef page); +WK_EXPORT bool WKPageRubberBandsAtBottom(WKPageRef); +WK_EXPORT void WKPageSetRubberBandsAtBottom(WKPageRef, bool rubberBandsAtBottom); +WK_EXPORT bool WKPageRubberBandsAtTop(WKPageRef); +WK_EXPORT void WKPageSetRubberBandsAtTop(WKPageRef, bool rubberBandsAtTop); + WK_EXPORT bool WKPageCanDelete(WKPageRef page); WK_EXPORT bool WKPageHasSelectedRange(WKPageRef page); WK_EXPORT bool WKPageIsContentEditable(WKPageRef page); @@ -455,13 +488,16 @@ WK_EXPORT void WKPageCenterSelectionInVisibleArea(WKPageRef page); WK_EXPORT void WKPageFindString(WKPageRef page, WKStringRef string, WKFindOptions findOptions, unsigned maxMatchCount); WK_EXPORT void WKPageHideFindUI(WKPageRef page); WK_EXPORT void WKPageCountStringMatches(WKPageRef page, WKStringRef string, WKFindOptions findOptions, unsigned maxMatchCount); +WK_EXPORT void WKPageFindStringMatches(WKPageRef page, WKStringRef string, WKFindOptions findOptions, unsigned maxMatchCount); +WK_EXPORT void WKPageGetImageForFindMatch(WKPageRef page, int32_t matchIndex); +WK_EXPORT void WKPageSelectFindMatch(WKPageRef page, int32_t matchIndex); WK_EXPORT void WKPageSetPageContextMenuClient(WKPageRef page, const WKPageContextMenuClient* client); WK_EXPORT void WKPageSetPageFindClient(WKPageRef page, const WKPageFindClient* client); +WK_EXPORT void WKPageSetPageFindMatchesClient(WKPageRef page, const WKPageFindMatchesClient* client); WK_EXPORT void WKPageSetPageFormClient(WKPageRef page, const WKPageFormClient* client); WK_EXPORT void WKPageSetPageLoaderClient(WKPageRef page, const WKPageLoaderClient* client); WK_EXPORT void WKPageSetPagePolicyClient(WKPageRef page, const WKPagePolicyClient* client); -WK_EXPORT void WKPageSetPageResourceLoadClient(WKPageRef page, const WKPageResourceLoadClient* client); WK_EXPORT void WKPageSetPageUIClient(WKPageRef page, const WKPageUIClient* client); typedef void (*WKPageRunJavaScriptFunction)(WKSerializedScriptValueRef, WKErrorRef, void*); @@ -488,11 +524,12 @@ WK_EXPORT void WKPageGetContentsAsString_b(WKPageRef page, WKPageGetContentsAsSt typedef void (*WKPageGetContentsAsMHTMLDataFunction)(WKDataRef, WKErrorRef, void*); WK_EXPORT void WKPageGetContentsAsMHTMLData(WKPageRef page, bool useBinaryEncoding, void* context, WKPageGetContentsAsMHTMLDataFunction function); +typedef void (*WKPageGetSelectionAsWebArchiveDataFunction)(WKDataRef, WKErrorRef, void*); +WK_EXPORT void WKPageGetSelectionAsWebArchiveData(WKPageRef page, void* context, WKPageGetSelectionAsWebArchiveDataFunction function); + typedef void (*WKPageForceRepaintFunction)(WKErrorRef, void*); WK_EXPORT void WKPageForceRepaint(WKPageRef page, void* context, WKPageForceRepaintFunction function); -WK_EXPORT void WKPageDeliverIntentToFrame(WKPageRef page, WKFrameRef frame, WKIntentDataRef intent); - /* Some of the more common command name strings include the following, although any WebCore EditorCommand string is supported: @@ -511,6 +548,36 @@ WK_EXPORT void WKPageExecuteCommand(WKPageRef page, WKStringRef command); WK_EXPORT void WKPagePostMessageToInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody); +WK_EXPORT void WKPageSelectContextMenuItem(WKPageRef page, WKContextMenuItemRef item); + + + +/* DEPRECATED - Please use constants from WKPluginInformation instead. */ + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationBundleIdentifierKey(); + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationBundleVersionKey(); + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationDisplayNameKey(); + +/* Value type: WKURLRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationFrameURLKey(); + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationMIMETypeKey(); + +/* Value type: WKURLRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationPageURLKey(); + +/* Value type: WKURLRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationPluginspageAttributeURLKey(); + +/* Value type: WKURLRef */ +WK_EXPORT WKStringRef WKPageGetPluginInformationPluginURLKey(); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h b/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h index 4f0e85ba5..114990aa3 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h @@ -97,6 +97,19 @@ WK_EXPORT void WKPageSetMayStartMediaWhenInWindow(WKPageRef page, bool mayStartM WK_EXPORT WKArrayRef WKPageCopyRelatedPages(WKPageRef page); +typedef void (*WKPageInvalidMessageFunction)(uint32_t messageID); +WK_EXPORT void WKPageSetInvalidMessageFunction(WKPageInvalidMessageFunction function); + +enum { + kWKScrollPinningBehaviorDoNotPin, + kWKScrollPinningBehaviorPinToTop, + kWKScrollPinningBehaviorPinToBottom +}; +typedef uint32_t WKScrollPinningBehavior; + +WK_EXPORT WKScrollPinningBehavior WKPageGetScrollPinningBehavior(WKPageRef page); +WK_EXPORT void WKPageSetScrollPinningBehavior(WKPageRef page, WKScrollPinningBehavior pinning); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp b/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp index 39539f449..1105ca27a 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp @@ -35,7 +35,6 @@ #endif using namespace WebKit; -using namespace std; WKTypeID WKPluginSiteDataManagerGetTypeID() { @@ -87,7 +86,7 @@ void WKPluginSiteDataManagerClearSiteData(WKPluginSiteDataManagerRef managerRef, void WKPluginSiteDataManagerClearAllSiteData(WKPluginSiteDataManagerRef managerRef, void* context, WKPluginSiteDataManagerClearSiteDataFunction function) { #if ENABLE(NETSCAPE_PLUGIN_API) - toImpl(managerRef)->clearSiteData(0, NP_CLEAR_ALL, numeric_limits<uint64_t>::max(), VoidCallback::create(context, function)); + toImpl(managerRef)->clearSiteData(0, NP_CLEAR_ALL, std::numeric_limits<uint64_t>::max(), VoidCallback::create(context, function)); #else UNUSED_PARAM(managerRef); UNUSED_PARAM(context); diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp b/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp index cb4cff018..86af62ea6 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp @@ -28,6 +28,7 @@ #include "WKPreferencesPrivate.h" #include "WKAPICast.h" +#include "WebContext.h" #include "WebPreferences.h" #include <WebCore/Settings.h> #include <wtf/PassRefPtr.h> @@ -68,6 +69,16 @@ bool WKPreferencesGetJavaScriptEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->javaScriptEnabled(); } +void WKPreferencesSetJavaScriptMarkupEnabled(WKPreferencesRef preferencesRef, bool javaScriptMarkupEnabled) +{ + toImpl(preferencesRef)->setJavaScriptMarkupEnabled(javaScriptMarkupEnabled); +} + +bool WKPreferencesGetJavaScriptMarkupEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->javaScriptMarkupEnabled(); +} + void WKPreferencesSetLoadsImagesAutomatically(WKPreferencesRef preferencesRef, bool loadsImagesAutomatically) { toImpl(preferencesRef)->setLoadsImagesAutomatically(loadsImagesAutomatically); @@ -408,6 +419,16 @@ bool WKPreferencesGetAcceleratedCompositingEnabled(WKPreferencesRef preferencesR return toImpl(preferencesRef)->acceleratedCompositingEnabled(); } +void WKPreferencesSetAcceleratedCompositingForOverflowScrollEnabled(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setAcceleratedCompositingForOverflowScrollEnabled(flag); +} + +bool WKPreferencesGetAcceleratedCompositingForOverflowScrollEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->acceleratedCompositingForOverflowScrollEnabled(); +} + void WKPreferencesSetCompositingBordersVisible(WKPreferencesRef preferencesRef, bool flag) { toImpl(preferencesRef)->setCompositingBordersVisible(flag); @@ -428,6 +449,16 @@ bool WKPreferencesGetCompositingRepaintCountersVisible(WKPreferencesRef preferen return toImpl(preferencesRef)->compositingRepaintCountersVisible(); } +void WKPreferencesSetTiledScrollingIndicatorVisible(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setTiledScrollingIndicatorVisible(flag); +} + +bool WKPreferencesGetTiledScrollingIndicatorVisible(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->tiledScrollingIndicatorVisible(); +} + void WKPreferencesSetCSSCustomFilterEnabled(WKPreferencesRef preferencesRef, bool flag) { toImpl(preferencesRef)->setCSSCustomFilterEnabled(flag); @@ -638,6 +669,16 @@ bool WKPreferencesGetFullScreenEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->fullScreenEnabled(); } +void WKPreferencesSetAsynchronousSpellCheckingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setAsynchronousSpellCheckingEnabled(enabled); +} + +bool WKPreferencesGetAsynchronousSpellCheckingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->asynchronousSpellCheckingEnabled(); +} + void WKPreferencesSetAVFoundationEnabled(WKPreferencesRef preferencesRef, bool enabled) { toImpl(preferencesRef)->setAVFoundationEnabled(enabled); @@ -944,6 +985,36 @@ bool WKPreferencesGetPlugInSnapshottingEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->plugInSnapshottingEnabled(); } +void WKPreferencesSetSnapshotAllPlugIns(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setSnapshotAllPlugIns(enabled); +} + +bool WKPreferencesGetSnapshotAllPlugIns(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->snapshotAllPlugIns(); +} + +void WKPreferencesSetAutostartOriginPlugInSnapshottingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setAutostartOriginPlugInSnapshottingEnabled(enabled); +} + +bool WKPreferencesGetAutostartOriginPlugInSnapshottingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->autostartOriginPlugInSnapshottingEnabled(); +} + +void WKPreferencesSetPrimaryPlugInSnapshotDetectionEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setPrimaryPlugInSnapshotDetectionEnabled(enabled); +} + +bool WKPreferencesGetPrimaryPlugInSnapshotDetectionEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->primaryPlugInSnapshotDetectionEnabled(); +} + void WKPreferencesSetPDFPluginEnabled(WKPreferencesRef preferencesRef, bool enabled) { toImpl(preferencesRef)->setPDFPluginEnabled(enabled); @@ -974,3 +1045,102 @@ bool WKPreferencesGetTextAutosizingEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->textAutosizingEnabled(); } +void WKPreferencesSetAggressiveTileRetentionEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setAggressiveTileRetentionEnabled(enabled); +} + +bool WKPreferencesGetAggressiveTileRetentionEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->aggressiveTileRetentionEnabled(); +} + +void WKPreferencesSetQTKitEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setQTKitEnabled(enabled); +} + +bool WKPreferencesGetQTKitEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->isQTKitEnabled(); +} + +void WKPreferencesSetLogsPageMessagesToSystemConsoleEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setLogsPageMessagesToSystemConsoleEnabled(enabled); +} + +bool WKPreferencesGetLogsPageMessagesToSystemConsoleEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->logsPageMessagesToSystemConsoleEnabled(); +} + +void WKPreferencesSetPageVisibilityBasedProcessSuppressionEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setPageVisibilityBasedProcessSuppressionEnabled(enabled); +} + +bool WKPreferencesGetPageVisibilityBasedProcessSuppressionEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->pageVisibilityBasedProcessSuppressionEnabled(); +} + +void WKPreferencesSetSmartInsertDeleteEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setSmartInsertDeleteEnabled(enabled); +} + +bool WKPreferencesGetSmartInsertDeleteEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->smartInsertDeleteEnabled(); +} + +void WKPreferencesSetSelectTrailingWhitespaceEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setSelectTrailingWhitespaceEnabled(enabled); +} + +bool WKPreferencesGetSelectTrailingWhitespaceEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->selectTrailingWhitespaceEnabled(); +} + +void WKPreferencesSetShowsURLsInToolTipsEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setShowsURLsInToolTipsEnabled(enabled); +} + +bool WKPreferencesGetShowsURLsInToolTipsEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->showsURLsInToolTipsEnabled(); +} + +void WKPreferencesSetHiddenPageDOMTimerThrottlingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setHiddenPageDOMTimerThrottlingEnabled(enabled); +} + +bool WKPreferencesGetHiddenPageDOMTimerThrottlingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->hiddenPageDOMTimerThrottlingEnabled(); +} + +void WKPreferencesSetHiddenPageCSSAnimationSuspensionEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setHiddenPageCSSAnimationSuspensionEnabled(enabled); +} + +bool WKPreferencesGetHiddenPageCSSAnimationSuspensionEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->hiddenPageCSSAnimationSuspensionEnabled(); +} + +void WKPreferencesSetIncrementalRenderingSuppressionTimeout(WKPreferencesRef preferencesRef, double timeout) +{ + toImpl(preferencesRef)->setIncrementalRenderingSuppressionTimeout(timeout); +} + +double WKPreferencesGetIncrementalRenderingSuppressionTimeout(WKPreferencesRef preferencesRef) +{ + return toAPI(toImpl(preferencesRef)->incrementalRenderingSuppressionTimeout()); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferences.h b/Source/WebKit2/UIProcess/API/C/WKPreferences.h index 4033d8cf1..bf36bb60e 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferences.h +++ b/Source/WebKit2/UIProcess/API/C/WKPreferences.h @@ -53,6 +53,10 @@ WK_EXPORT void WKPreferencesSetJavaScriptEnabled(WKPreferencesRef preferences, b WK_EXPORT bool WKPreferencesGetJavaScriptEnabled(WKPreferencesRef preferences); // Defaults to true. +WK_EXPORT void WKPreferencesSetJavaScriptMarkupEnabled(WKPreferencesRef preferences, bool javaScriptEnabled); +WK_EXPORT bool WKPreferencesGetJavaScriptMarkupEnabled(WKPreferencesRef preferences); + +// Defaults to true. WK_EXPORT void WKPreferencesSetLoadsImagesAutomatically(WKPreferencesRef preferences, bool loadsImagesAutomatically); WK_EXPORT bool WKPreferencesGetLoadsImagesAutomatically(WKPreferencesRef preferences); @@ -228,6 +232,14 @@ WK_EXPORT bool WKPreferencesGetEncodingDetectorEnabled(WKPreferencesRef preferen WK_EXPORT void WKPreferencesSetTextAutosizingEnabled(WKPreferencesRef preferences, bool textAutosizingEnabled); WK_EXPORT bool WKPreferencesGetTextAutosizingEnabled(WKPreferencesRef preferences); +// Defaults to true. +WK_EXPORT void WKPreferencesSetQTKitEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetQTKitEnabled(WKPreferencesRef preferencesRef); + +// Defaults to false +WK_EXPORT void WKPreferencesSetAsynchronousSpellCheckingEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetAsynchronousSpellCheckingEnabled(WKPreferencesRef preferencesRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h b/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h index a796bcb43..1c957563f 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h @@ -76,6 +76,10 @@ WK_EXPORT void WKPreferencesSetAcceleratedCompositingEnabled(WKPreferencesRef, b WK_EXPORT bool WKPreferencesGetAcceleratedCompositingEnabled(WKPreferencesRef); // Defaults to false. +WK_EXPORT void WKPreferencesSetAcceleratedCompositingForOverflowScrollEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetAcceleratedCompositingForOverflowScrollEnabled(WKPreferencesRef); + +// Defaults to false. WK_EXPORT void WKPreferencesSetCompositingBordersVisible(WKPreferencesRef, bool); WK_EXPORT bool WKPreferencesGetCompositingBordersVisible(WKPreferencesRef); @@ -83,6 +87,10 @@ WK_EXPORT bool WKPreferencesGetCompositingBordersVisible(WKPreferencesRef); WK_EXPORT void WKPreferencesSetCompositingRepaintCountersVisible(WKPreferencesRef, bool); WK_EXPORT bool WKPreferencesGetCompositingRepaintCountersVisible(WKPreferencesRef); +// Defaults to false. +WK_EXPORT void WKPreferencesSetTiledScrollingIndicatorVisible(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetTiledScrollingIndicatorVisible(WKPreferencesRef); + // Defaults to true. WK_EXPORT void WKPreferencesSetCSSCustomFilterEnabled(WKPreferencesRef, bool flag); WK_EXPORT bool WKPreferencesGetCSSCustomFilterEnabled(WKPreferencesRef); @@ -231,6 +239,54 @@ WK_EXPORT bool WKPreferencesGetCookieEnabled(WKPreferencesRef preferences); WK_EXPORT void WKPreferencesSetPDFPluginEnabled(WKPreferencesRef preferences, bool enabled); WK_EXPORT bool WKPreferencesGetPDFPluginEnabled(WKPreferencesRef preferences); +// Defaults to false +WK_EXPORT void WKPreferencesSetAggressiveTileRetentionEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetAggressiveTileRetentionEnabled(WKPreferencesRef preferences); + +// Defaults to false +WK_EXPORT void WKPreferencesSetLogsPageMessagesToSystemConsoleEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetLogsPageMessagesToSystemConsoleEnabled(WKPreferencesRef preferences); + +// Defaults to false +WK_EXPORT void WKPreferencesSetPageVisibilityBasedProcessSuppressionEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetPageVisibilityBasedProcessSuppressionEnabled(WKPreferencesRef); + +// Defaults to true +WK_EXPORT void WKPreferencesSetSmartInsertDeleteEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetSmartInsertDeleteEnabled(WKPreferencesRef preferences); + +// Defaults to false +WK_EXPORT void WKPreferencesSetSelectTrailingWhitespaceEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetSelectTrailingWhitespaceEnabled(WKPreferencesRef preferences); + +// Defaults to false +WK_EXPORT void WKPreferencesSetShowsURLsInToolTipsEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetShowsURLsInToolTipsEnabled(WKPreferencesRef preferences); + +// Defaults to true on Mac, false on other platforms. +WK_EXPORT void WKPreferencesSetHiddenPageDOMTimerThrottlingEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetHiddenPageDOMTimerThrottlingEnabled(WKPreferencesRef preferences); + +// Defaults to true on Mac, false on other platforms. +WK_EXPORT void WKPreferencesSetHiddenPageCSSAnimationSuspensionEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetHiddenPageCSSAnimationSuspensionEnabled(WKPreferencesRef preferences); + +// Defaults to false +WK_EXPORT void WKPreferencesSetSnapshotAllPlugIns(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetSnapshotAllPlugIns(WKPreferencesRef preferencesRef); + +// Defaults to true +WK_EXPORT void WKPreferencesSetAutostartOriginPlugInSnapshottingEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetAutostartOriginPlugInSnapshottingEnabled(WKPreferencesRef preferencesRef); + +// Defaults to true +WK_EXPORT void WKPreferencesSetPrimaryPlugInSnapshotDetectionEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetPrimaryPlugInSnapshotDetectionEnabled(WKPreferencesRef preferencesRef); + +// Defaults to 5 seconds. +WK_EXPORT void WKPreferencesSetIncrementalRenderingSuppressionTimeout(WKPreferencesRef preferencesRef, double timeout); +WK_EXPORT double WKPreferencesGetIncrementalRenderingSuppressionTimeout(WKPreferencesRef preferencesRef); + WK_EXPORT void WKPreferencesResetTestRunnerOverrides(WKPreferencesRef preferencesRef); #ifdef __cplusplus diff --git a/Source/WebKit2/UIProcess/API/C/WKVibration.h b/Source/WebKit2/UIProcess/API/C/WKVibration.h index f300b46e8..4884ecd85 100644 --- a/Source/WebKit2/UIProcess/API/C/WKVibration.h +++ b/Source/WebKit2/UIProcess/API/C/WKVibration.h @@ -33,7 +33,7 @@ extern "C" { #endif // Provider. -typedef void (*WKVibrationProviderVibrateCallback)(WKVibrationRef vibrationRef, uint64_t vibrationTime, const void* clientInfo); +typedef void (*WKVibrationProviderVibrateCallback)(WKVibrationRef vibrationRef, uint32_t vibrationTime, const void* clientInfo); typedef void (*WKVibrationProviderCancelVibrationCallback)(WKVibrationRef vibrationRef, const void* clientInfo); struct WKVibrationProvider { diff --git a/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.cpp b/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.cpp new file mode 100644 index 000000000..e30af5666 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the followlayoutSizeing disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list Viewof conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKViewportAttributes.h" + +#include "WKAPICast.h" +#include "WebViewportAttributes.h" + +using namespace WebKit; + +WKTypeID WKViewportAttributesGetTypeID() +{ + return toAPI(WebViewportAttributes::APIType); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h b/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h new file mode 100644 index 000000000..125b09cc4 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list Viewof conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKViewportAttributes_h +#define WKViewportAttributes_h + +#include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT WKTypeID WKViewportAttributesGetTypeID(); + +#ifdef __cplusplus +} +#endif + +#endif /* WKViewportAttributes_h */ diff --git a/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.cpp b/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.cpp new file mode 100644 index 000000000..118c4d8cb --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKIconDatabaseCairo.h" + +#include "WKAPICast.h" +#include "WebIconDatabase.h" + +using namespace WebCore; +using namespace WebKit; + +cairo_surface_t* WKIconDatabaseTryGetCairoSurfaceForURL(WKIconDatabaseRef iconDatabase, WKURLRef url) +{ + return toImpl(iconDatabase)->nativeImageForPageURL(toWTFString(url)).get(); +} diff --git a/Source/WebKit2/UIProcess/API/C/win/WKViewPrivate.h b/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.h index 5f89fd4e1..ea6231148 100644 --- a/Source/WebKit2/UIProcess/API/C/win/WKViewPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2013 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,20 +23,16 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKViewPrivate_h -#define WKViewPrivate_h - #include <WebKit2/WKBase.h> -#include <windows.h> + +typedef struct _cairo_surface cairo_surface_t; #ifdef __cplusplus extern "C" { #endif -WK_EXPORT void WKViewSetOverrideCursor(WKViewRef viewRef, HCURSOR overrideCursor); +WK_EXPORT cairo_surface_t* WKIconDatabaseTryGetCairoSurfaceForURL(WKIconDatabaseRef iconDatabase, WKURLRef url); #ifdef __cplusplus } #endif - -#endif /* WKViewPrivate_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h b/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h index 5a068ef36..87c5f5efb 100644 --- a/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h +++ b/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h @@ -24,11 +24,85 @@ #error "Please #include \"WKAPICast.h\" instead of this file directly." #endif -typedef struct _Evas_Object Evas_Object; +#include <WebCore/TextDirection.h> +#include <WebKit2/WKPopupItem.h> + +#if ENABLE(TOUCH_EVENTS) +#include "WebEvent.h" +#include <WebKit2/WKEventEfl.h> +#endif namespace WebKit { -WK_ADD_API_MAPPING(WKViewRef, Evas_Object) +class WebView; +class WebPopupItemEfl; +class WebPopupMenuListenerEfl; + +WK_ADD_API_MAPPING(WKViewRef, WebView) +WK_ADD_API_MAPPING(WKPopupItemRef, WebPopupItemEfl) +WK_ADD_API_MAPPING(WKPopupMenuListenerRef, WebPopupMenuListenerEfl) + +#if ENABLE(TOUCH_EVENTS) +class EwkTouchEvent; +class EwkTouchPoint; + +WK_ADD_API_MAPPING(WKTouchEventRef, EwkTouchEvent) +WK_ADD_API_MAPPING(WKTouchPointRef, EwkTouchPoint) +#endif + +// Enum conversions. +inline WKPopupItemTextDirection toAPI(WebCore::TextDirection direction) +{ + WKPopupItemTextDirection wkDirection = kWKPopupItemTextDirectionLTR; + + switch (direction) { + case WebCore::RTL: + wkDirection = kWKPopupItemTextDirectionRTL; + break; + case WebCore::LTR: + wkDirection = kWKPopupItemTextDirectionLTR; + break; + } + + return wkDirection; +} + +#if ENABLE(TOUCH_EVENTS) +inline WKEventType toAPI(WebEvent::Type type) +{ + switch (type) { + case WebEvent::TouchStart: + return kWKEventTypeTouchStart; + case WebEvent::TouchMove: + return kWKEventTypeTouchMove; + case WebEvent::TouchEnd: + return kWKEventTypeTouchEnd; + case WebEvent::TouchCancel: + return kWKEventTypeTouchCancel; + default: + return kWKEventTypeNoType; + } +} + +inline WKTouchPointState toAPI(WebPlatformTouchPoint::TouchPointState state) +{ + switch (state) { + case WebPlatformTouchPoint::TouchReleased: + return kWKTouchPointStateTouchReleased; + case WebPlatformTouchPoint::TouchPressed: + return kWKTouchPointStateTouchPressed; + case WebPlatformTouchPoint::TouchMoved: + return kWKTouchPointStateTouchMoved; + case WebPlatformTouchPoint::TouchStationary: + return kWKTouchPointStateTouchStationary; + case WebPlatformTouchPoint::TouchCancelled: + return kWKTouchPointStateTouchCancelled; + } + + ASSERT_NOT_REACHED(); + return kWKTouchPointStateTouchCancelled; +} +#endif } diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.cpp new file mode 100644 index 000000000..843aeb0dd --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.cpp @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKEventEfl.h" + +#include "EwkTouchEvent.h" +#include "EwkTouchPoint.h" +#include "ImmutableArray.h" +#include "WKAPICast.h" +#include "WebEvent.h" + +using namespace WebKit; + +WKTouchPointRef WKTouchPointCreate(int id, WKPoint position, WKPoint screenPosition, WKTouchPointState state, WKSize radius, float rotationAngle, float forceFactor) +{ +#if ENABLE(TOUCH_EVENTS) + return toAPI(EwkTouchPoint::create(id, state, screenPosition, position, radius, rotationAngle, forceFactor).leakRef()); +#else + UNUSED_PARAM(id); + UNUSED_PARAM(position); + UNUSED_PARAM(screenPosition); + UNUSED_PARAM(state); + UNUSED_PARAM(radius); + UNUSED_PARAM(rotationAngle); + UNUSED_PARAM(forceFactor); + return 0; +#endif +} + +WKTouchEventRef WKTouchEventCreate(WKEventType type, WKArrayRef wkTouchPoints, WKEventModifiers modifiers, double timestamp) +{ +#if ENABLE(TOUCH_EVENTS) + return toAPI(EwkTouchEvent::create(type, wkTouchPoints, modifiers, timestamp).leakRef()); +#else + UNUSED_PARAM(type); + UNUSED_PARAM(wkTouchPoints); + UNUSED_PARAM(modifiers); + UNUSED_PARAM(timestamp); + return 0; +#endif +} + +WKEventType WKTouchEventGetType(WKTouchEventRef event) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(event)->eventType(); +#else + UNUSED_PARAM(event); + return kWKEventTypeNoType; +#endif +} + +WKArrayRef WKTouchEventGetTouchPoints(WKTouchEventRef event) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(event)->touchPoints(); +#else + UNUSED_PARAM(event); + return 0; +#endif +} + +WKEventModifiers WKTouchEventGetModifiers(WKTouchEventRef event) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(event)->modifiers(); +#else + UNUSED_PARAM(event); + return 0; +#endif +} + +double WKTouchEventGetTimestamp(WKTouchEventRef event) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(event)->timestamp(); +#else + UNUSED_PARAM(event); + return 0; +#endif +} + +uint32_t WKTouchPointGetID(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->id(); +#else + UNUSED_PARAM(point); + return 0; +#endif +} + +WKTouchPointState WKTouchPointGetState(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->state(); +#else + UNUSED_PARAM(point); + return kWKTouchPointStateTouchCancelled; +#endif +} + +WKPoint WKTouchPointGetScreenPosition(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->screenPosition(); +#else + UNUSED_PARAM(point); + return WKPointMake(0, 0); +#endif +} + +WKPoint WKTouchPointGetPosition(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->position(); +#else + UNUSED_PARAM(point); + return WKPointMake(0, 0); +#endif +} + +WKSize WKTouchPointGetRadius(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->radius(); +#else + UNUSED_PARAM(point); + return WKSizeMake(0, 0); +#endif +} + +float WKTouchPointGetRotationAngle(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->rotationAngle(); +#else + UNUSED_PARAM(point); + return 0; +#endif +} + +float WKTouchPointGetForceFactor(WKTouchPointRef point) +{ +#if ENABLE(TOUCH_EVENTS) + return toImpl(point)->forceFactor(); +#else + UNUSED_PARAM(point); + return 0; +#endif +} diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.h b/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.h new file mode 100644 index 000000000..b5439219e --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.h @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * Copyright (C) 2012-2013 Nokia Corporation and/or its subsidiary(-ies). + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKEventEfl_h +#define WKEventEfl_h + +#include <WebKit2/WKEvent.h> +#include <WebKit2/WKGeometry.h> + +#ifdef __cplusplus +extern "C" { +#endif + +enum WKEventType { + kWKEventTypeNoType = -1, + kWKEventTypeTouchStart, + kWKEventTypeTouchMove, + kWKEventTypeTouchEnd, + kWKEventTypeTouchCancel +}; +typedef enum WKEventType WKEventType; + +enum WKTouchPointState { + kWKTouchPointStateTouchReleased, + kWKTouchPointStateTouchPressed, + kWKTouchPointStateTouchMoved, + kWKTouchPointStateTouchStationary, + kWKTouchPointStateTouchCancelled +}; +typedef enum WKTouchPointState WKTouchPointState; + +WK_EXPORT WKTouchPointRef WKTouchPointCreate(int id, WKPoint position, WKPoint screenPosition, WKTouchPointState, WKSize radius, float rotationAngle, float forceFactor); +WK_EXPORT WKTouchEventRef WKTouchEventCreate(WKEventType, WKArrayRef, WKEventModifiers, double timestamp); + +WK_EXPORT WKEventType WKTouchEventGetType(WKTouchEventRef); +WK_EXPORT WKArrayRef WKTouchEventGetTouchPoints(WKTouchEventRef); +WK_EXPORT WKEventModifiers WKTouchEventGetModifiers(WKTouchEventRef); +WK_EXPORT double WKTouchEventGetTimestamp(WKTouchEventRef); + +WK_EXPORT uint32_t WKTouchPointGetID(WKTouchPointRef); +WK_EXPORT WKTouchPointState WKTouchPointGetState(WKTouchPointRef); +WK_EXPORT WKPoint WKTouchPointGetScreenPosition(WKTouchPointRef); +WK_EXPORT WKPoint WKTouchPointGetPosition(WKTouchPointRef); +WK_EXPORT WKSize WKTouchPointGetRadius(WKTouchPointRef); +WK_EXPORT float WKTouchPointGetRotationAngle(WKTouchPointRef); +WK_EXPORT float WKTouchPointGetForceFactor(WKTouchPointRef); + +#ifdef __cplusplus +} +#endif + +#endif /* WKEventEfl_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.cpp new file mode 100644 index 000000000..2d5ec91b5 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKPageEfl.h" + +#include "WKAPICast.h" +#include "WebPageProxy.h" + +using namespace WebKit; + +void WKPageSetUIPopupMenuClient(WKPageRef pageRef, const WKPageUIPopupMenuClient* wkClient) +{ + toImpl(pageRef)->initializeUIPopupMenuClient(wkClient); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKIntentServiceInfo.h b/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.h index 121cffde8..77b9d140b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKIntentServiceInfo.h +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -12,7 +12,7 @@ * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF @@ -23,24 +23,34 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKIntentServiceInfo_h -#define WKIntentServiceInfo_h +#ifndef WKPageEfl_h +#define WKPageEfl_h #include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> +#include <WebKit2/WKPopupItem.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT WKTypeID WKIntentServiceInfoGetTypeID(); -WK_EXPORT WKStringRef WKIntentServiceInfoCopyAction(WKIntentServiceInfoRef serviceRef); -WK_EXPORT WKStringRef WKIntentServiceInfoCopyType(WKIntentServiceInfoRef serviceRef); -WK_EXPORT WKURLRef WKIntentServiceInfoCopyHref(WKIntentServiceInfoRef serviceRef); -WK_EXPORT WKStringRef WKIntentServiceInfoCopyTitle(WKIntentServiceInfoRef serviceRef); -WK_EXPORT WKStringRef WKIntentServiceInfoCopyDisposition(WKIntentServiceInfoRef serviceRef); +typedef void (*WKPageShowPopupMenuCallback)(WKPageRef page, WKPopupMenuListenerRef menuListenerRef, WKRect rect, WKPopupItemTextDirection textDirection, double pageScaleFactor, WKArrayRef itemsRef, int32_t selectedIndex, const void* clientInfo); +typedef void (*WKPageHidePopupMenuCallback)(WKPageRef page, const void* clientInfo); + +struct WKPageUIPopupMenuClient { + int version; + const void* clientInfo; + WKPageShowPopupMenuCallback showPopupMenu; + WKPageHidePopupMenuCallback hidePopupMenu; +}; +typedef struct WKPageUIPopupMenuClient WKPageUIPopupMenuClient; + +enum { kWKPageUIPopupMenuClientCurrentVersion = 0 }; + +WK_EXPORT void WKPageSetUIPopupMenuClient(WKPageRef page, const WKPageUIPopupMenuClient* client); #ifdef __cplusplus } #endif -#endif // WKIntentServiceInfo_h +#endif /* WKPageEfl_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.cpp new file mode 100644 index 000000000..7b0ea45ec --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKPopupItem.h" + +#include "WKAPICast.h" +#include "WebPopupItemEfl.h" + +using namespace WebKit; +using namespace WebCore; + +WKPopupItemType WKPopupItemGetType(WKPopupItemRef itemRef) +{ + switch (toImpl(itemRef)->itemType()) { + case WebPopupItem::Separator: + return kWKPopupItemTypeSeparator; + case WebPopupItem::Item: + return kWKPopupItemTypeItem; + default: + ASSERT_NOT_REACHED(); + return kWKPopupItemTypeItem; + } +} + +WKPopupItemTextDirection WKPopupItemGetTextDirection(WKPopupItemRef itemRef) +{ + switch (toImpl(itemRef)->textDirection()) { + case RTL: + return kWKPopupItemTextDirectionRTL; + case LTR: + return kWKPopupItemTextDirectionLTR; + default: + ASSERT_NOT_REACHED(); + return kWKPopupItemTextDirectionLTR; + } +} + +bool WKPopupItemHasTextDirectionOverride(WKPopupItemRef itemRef) +{ + return toImpl(itemRef)->hasTextDirectionOverride(); +} + +WKStringRef WKPopupItemCopyText(WKPopupItemRef itemRef) +{ + return toCopiedAPI(toImpl(itemRef)->text()); +} + +WKStringRef WKPopupItemCopyToolTipText(WKPopupItemRef itemRef) +{ + return toCopiedAPI(toImpl(itemRef)->toolTipText()); +} + +WKStringRef WKPopupItemCopyAccessibilityText(WKPopupItemRef itemRef) +{ + return toCopiedAPI(toImpl(itemRef)->accessibilityText()); +} + +bool WKPopupItemIsEnabled(WKPopupItemRef itemRef) +{ + return toImpl(itemRef)->isEnabled(); +} + +bool WKPopupItemIsLabel(WKPopupItemRef itemRef) +{ + return toImpl(itemRef)->isLabel(); +} + +bool WKPopupItemIsSelected(WKPopupItemRef itemRef) +{ + return toImpl(itemRef)->isSelected(); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKIntentData.h b/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.h index caf1b459f..b418ed526 100644 --- a/Source/WebKit2/UIProcess/API/C/WKIntentData.h +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -12,7 +12,7 @@ * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF @@ -23,8 +23,8 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKIntentData_h -#define WKIntentData_h +#ifndef WKPopupItem_h +#define WKPopupItem_h #include <WebKit2/WKBase.h> @@ -32,17 +32,33 @@ extern "C" { #endif -WK_EXPORT WKTypeID WKIntentDataGetTypeID(); +enum { + kWKPopupItemTypeSeparator, + kWKPopupItemTypeItem +}; +typedef uint32_t WKPopupItemType; -WK_EXPORT WKStringRef WKIntentDataCopyAction(WKIntentDataRef intentRef); -WK_EXPORT WKStringRef WKIntentDataCopyType(WKIntentDataRef intentRef); -WK_EXPORT WKURLRef WKIntentDataCopyService(WKIntentDataRef intentRef); -WK_EXPORT WKArrayRef WKIntentDataCopySuggestions(WKIntentDataRef intentRef); -WK_EXPORT WKStringRef WKIntentDataCopyExtraValue(WKIntentDataRef intentRef, WKStringRef key); -WK_EXPORT WKDictionaryRef WKIntentDataCopyExtras(WKIntentDataRef intentRef); +enum { + kWKPopupItemTextDirectionRTL, + kWKPopupItemTextDirectionLTR +}; +typedef uint32_t WKPopupItemTextDirection; + +WK_EXPORT WKPopupItemType WKPopupItemGetType(WKPopupItemRef item); + +WK_EXPORT WKPopupItemTextDirection WKPopupItemGetTextDirection(WKPopupItemRef item); +WK_EXPORT bool WKPopupItemHasTextDirectionOverride(WKPopupItemRef item); + +WK_EXPORT WKStringRef WKPopupItemCopyText(WKPopupItemRef item); +WK_EXPORT WKStringRef WKPopupItemCopyToolTipText(WKPopupItemRef item); +WK_EXPORT WKStringRef WKPopupItemCopyAccessibilityText(WKPopupItemRef item); + +WK_EXPORT bool WKPopupItemIsEnabled(WKPopupItemRef item); +WK_EXPORT bool WKPopupItemIsLabel(WKPopupItemRef item); +WK_EXPORT bool WKPopupItemIsSelected(WKPopupItemRef item); #ifdef __cplusplus } #endif -#endif // WKIntentData_h +#endif /* WKPopupItem_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.cpp new file mode 100644 index 000000000..34f82b455 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKPopupMenuListener.h" + +#include "WKAPICast.h" +#include "WebPopupMenuListenerEfl.h" + +using namespace WebKit; + +void WKPopupMenuListenerSetSelection(WKPopupMenuListenerRef listenerRef, int selectedIndex) +{ + toImpl(listenerRef)->valueChanged(selectedIndex); +} diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.h b/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.h new file mode 100644 index 000000000..854991679 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKPopupMenuListener_h +#define WKPopupMenuListener_h + +#include <WebKit2/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT void WKPopupMenuListenerSetSelection(WKPopupMenuListenerRef listener, int selectedIndex); + +#ifdef __cplusplus +} +#endif + +#endif /* WKPopupMenuListener_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp deleted file mode 100644 index f4436aedd..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKView.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "WKView.h" - -#include "EwkViewImpl.h" -#include "WKAPICast.h" -#include "ewk_view_private.h" - -using namespace WebKit; - -WKViewRef WKViewCreate(Evas* canvas, WKContextRef contextRef, WKPageGroupRef pageGroupRef) -{ - return toAPI(ewk_view_base_add(canvas, contextRef, pageGroupRef, EwkViewImpl::LegacyBehavior)); -} - -WKViewRef WKViewCreateWithFixedLayout(Evas* canvas, WKContextRef contextRef, WKPageGroupRef pageGroupRef) -{ - return toAPI(ewk_view_base_add(canvas, contextRef, pageGroupRef, EwkViewImpl::DefaultBehavior)); -} - -WKPageRef WKViewGetPage(WKViewRef viewRef) -{ - EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(toImpl(viewRef)); - - return viewImpl->wkPage(); -} - -WKImageRef WKViewGetSnapshot(WKViewRef viewRef) -{ - EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(toImpl(viewRef)); - - return viewImpl->takeSnapshot(); -} diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKView.h b/Source/WebKit2/UIProcess/API/C/efl/WKView.h deleted file mode 100644 index ca17a9945..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKView.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef WKView_h -#define WKView_h - -#include <WebKit2/WKBase.h> - -typedef struct _Evas Evas; - -#ifdef __cplusplus -extern "C" { -#endif - -WK_EXPORT WKViewRef WKViewCreate(Evas* canvas, WKContextRef context, WKPageGroupRef pageGroup); - -WK_EXPORT WKViewRef WKViewCreateWithFixedLayout(Evas* canvas, WKContextRef context, WKPageGroupRef pageGroup); - -WK_EXPORT WKPageRef WKViewGetPage(WKViewRef view); - -WK_EXPORT WKImageRef WKViewGetSnapshot(WKViewRef viewRef); - -#ifdef __cplusplus -} -#endif - -#endif /* WKView_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.cpp new file mode 100644 index 000000000..cefa2d358 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKViewEfl.h" + +#include "EwkView.h" +#include "WKAPICast.h" +#include "WebViewEfl.h" +#include <WebKit2/WKImageCairo.h> + +using namespace WebKit; + +void WKViewPaintToCairoSurface(WKViewRef viewRef, cairo_surface_t* surface) +{ + static_cast<WebViewEfl*>(toImpl(viewRef))->paintToCairoSurface(surface); +} + +WKImageRef WKViewCreateSnapshot(WKViewRef viewRef) +{ + EwkView* ewkView = static_cast<WebViewEfl*>(toImpl(viewRef))->ewkView(); + return WKImageCreateFromCairoSurface(ewkView->takeSnapshot().get(), 0 /* options */); +} + +void WKViewSetThemePath(WKViewRef viewRef, WKStringRef theme) +{ + static_cast<WebViewEfl*>(toImpl(viewRef))->setThemePath(toImpl(theme)->string()); +} + +void WKViewSendTouchEvent(WKViewRef viewRef, WKTouchEventRef touchEventRef) +{ +#if ENABLE(TOUCH_EVENTS) + static_cast<WebViewEfl*>(toImpl(viewRef))->sendTouchEvent(toImpl(touchEventRef)); +#else + UNUSED_PARAM(viewRef); + UNUSED_PARAM(touchEventRef); +#endif +} diff --git a/Source/WebKit2/UIProcess/API/C/win/WKContextPrivateWin.h b/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.h index 0d49ac99a..d8afdc432 100644 --- a/Source/WebKit2/UIProcess/API/C/win/WKContextPrivateWin.h +++ b/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2013 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,29 +23,27 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKContextPrivateWin_h -#define WKContextPrivateWin_h +#ifndef WKViewEfl_h +#define WKViewEfl_h #include <WebKit2/WKBase.h> -#include <WebKit2/WKContext.h> -#include <WebKit2/WKCookieManager.h> -#ifndef __cplusplus -#include <stdbool.h> -#endif +typedef struct _cairo_surface cairo_surface_t; #ifdef __cplusplus extern "C" { #endif -// Defaults to true. -WK_EXPORT void WKContextSetShouldPaintNativeControls(WKContextRef, bool); +WK_EXPORT void WKViewPaintToCairoSurface(WKViewRef, cairo_surface_t*); + +WK_EXPORT WKImageRef WKViewCreateSnapshot(WKViewRef); + +WK_EXPORT void WKViewSetThemePath(WKViewRef, WKStringRef); -// Defaults to WKHTTPCookieAcceptPolicyAlways. -WK_EXPORT void WKContextSetInitialHTTPCookieAcceptPolicy(WKContextRef, WKHTTPCookieAcceptPolicy); +WK_EXPORT void WKViewSendTouchEvent(WKViewRef, WKTouchEventRef); #ifdef __cplusplus } #endif -#endif /* WKContextPrivateWin_h */ +#endif /* WKViewEfl_h */ diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.h b/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.h new file mode 100644 index 000000000..937a4a604 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.h @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKContextPrivateMac_h +#define WKContextPrivateMac_h + +#include <WebKit2/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT bool WKContextGetProcessSuppressionEnabled(WKContextRef context); +WK_EXPORT void WKContextSetProcessSuppressionEnabled(WKContextRef context, bool enabled); + +WK_EXPORT bool WKContextIsPlugInUpdateAvailable(WKContextRef context, WKStringRef plugInBundleIdentifier); + +WK_EXPORT WKDictionaryRef WKContextCopyPlugInInfoForBundleIdentifier(WKContextRef context, WKStringRef plugInBundleIdentifier); + +typedef void (^WKContextGetInfoForInstalledPlugInsBlock)(WKArrayRef, WKErrorRef); +WK_EXPORT void WKContextGetInfoForInstalledPlugIns(WKContextRef context, WKContextGetInfoForInstalledPlugInsBlock block); + +WK_EXPORT void WKContextResetHSTSHosts(WKContextRef context); + +/* DEPRECATED - Please use constants from WKPluginInformation instead. */ + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPlugInInfoPathKey(); + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPlugInInfoBundleIdentifierKey(); + +/* Value type: WKStringRef */ +WK_EXPORT WKStringRef WKPlugInInfoVersionKey(); + +/* Value type: WKUInt64Ref */ +WK_EXPORT WKStringRef WKPlugInInfoLoadPolicyKey(); + +/* Value type: WKBooleanRef */ +WK_EXPORT WKStringRef WKPlugInInfoUpdatePastLastBlockedVersionIsKnownAvailableKey(); + +/* Value type: WKBooleanRef */ +WK_EXPORT WKStringRef WKPlugInInfoIsSandboxedKey(); + +#ifdef __cplusplus +} +#endif + +#endif /* WKContextPrivateMac_h */ diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.mm b/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.mm new file mode 100644 index 000000000..9fb8a2ad8 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.mm @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "WKContextPrivateMac.h" + +#import "ImmutableArray.h" +#import "ImmutableDictionary.h" +#import "PluginInfoStore.h" +#import "PluginInformation.h" +#import "PluginSandboxProfile.h" +#import "StringUtilities.h" +#import "WKAPICast.h" +#import "WKPluginInformation.h" +#import "WKSharedAPICast.h" +#import "WKStringCF.h" +#import "WebContext.h" +#import "WebNumber.h" +#import "WebString.h" +#import <WebKitSystemInterface.h> +#import <wtf/RetainPtr.h> + +using namespace WebKit; + +bool WKContextGetProcessSuppressionEnabled(WKContextRef contextRef) +{ + return toImpl(contextRef)->processSuppressionEnabled(); +} + +void WKContextSetProcessSuppressionEnabled(WKContextRef contextRef, bool enabled) +{ + toImpl(contextRef)->setProcessSuppressionEnabled(enabled); +} + +bool WKContextIsPlugInUpdateAvailable(WKContextRef contextRef, WKStringRef plugInBundleIdentifierRef) +{ + return WKIsPluginUpdateAvailable((NSString *)adoptCF(WKStringCopyCFString(kCFAllocatorDefault, plugInBundleIdentifierRef)).get()); +} + +WKDictionaryRef WKContextCopyPlugInInfoForBundleIdentifier(WKContextRef contextRef, WKStringRef plugInBundleIdentifierRef) +{ + PluginModuleInfo plugin = toImpl(contextRef)->pluginInfoStore().findPluginWithBundleIdentifier(toWTFString(plugInBundleIdentifierRef)); + if (plugin.path.isNull()) + return 0; + + RefPtr<ImmutableDictionary> dictionary = createPluginInformationDictionary(plugin); + return toAPI(dictionary.release().leakRef()); +} + +void WKContextGetInfoForInstalledPlugIns(WKContextRef contextRef, WKContextGetInfoForInstalledPlugInsBlock block) +{ + Vector<PluginModuleInfo> plugins = toImpl(contextRef)->pluginInfoStore().plugins(); + + Vector<RefPtr<APIObject>> pluginInfoDictionaries; + for (const auto& plugin: plugins) + pluginInfoDictionaries.append(createPluginInformationDictionary(plugin)); + + RefPtr<ImmutableArray> array = ImmutableArray::adopt(pluginInfoDictionaries); + + toImpl(contextRef)->ref(); + dispatch_async(dispatch_get_main_queue(), ^() { + block(toAPI(array.get()), 0); + + toImpl(contextRef)->deref(); + }); +} + +void WKContextResetHSTSHosts(WKContextRef context) +{ + return toImpl(context)->resetHSTSHosts(); +} + + +/* DEPRECATED - Please use constants from WKPluginInformation instead. */ + +WKStringRef WKPlugInInfoPathKey() +{ + return WKPluginInformationPathKey(); +} + +WKStringRef WKPlugInInfoBundleIdentifierKey() +{ + return WKPluginInformationBundleIdentifierKey(); +} + +WKStringRef WKPlugInInfoVersionKey() +{ + return WKPluginInformationBundleVersionKey(); +} + +WKStringRef WKPlugInInfoLoadPolicyKey() +{ + return WKPluginInformationDefaultLoadPolicyKey(); +} + +WKStringRef WKPlugInInfoUpdatePastLastBlockedVersionIsKnownAvailableKey() +{ + return WKPluginInformationUpdatePastLastBlockedVersionIsKnownAvailableKey(); +} + +WKStringRef WKPlugInInfoIsSandboxedKey() +{ + return WKPluginInformationHasSandboxProfileKey(); +} diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.cpp b/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.cpp index d881cdd32..5e45950cb 100644 --- a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.cpp +++ b/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.cpp @@ -27,7 +27,10 @@ #include "WKPagePrivateMac.h" #include "WKAPICast.h" +#include "WebContext.h" +#include "WebPageGroup.h" #include "WebPageProxy.h" +#include "WebPreferences.h" using namespace WebKit; @@ -35,3 +38,11 @@ pid_t WKPageGetProcessIdentifier(WKPageRef pageRef) { return toImpl(pageRef)->processIdentifier(); } + +bool WKPageIsURLKnownHSTSHost(WKPageRef page, WKURLRef url) +{ + WebPageProxy* webPageProxy = toImpl(page); + bool privateBrowsingEnabled = webPageProxy->pageGroup()->preferences()->privateBrowsingEnabled(); + + return webPageProxy->process()->context()->isURLKnownHSTSHost(toImpl(url)->string(), privateBrowsingEnabled); +} diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.h b/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.h index 1890da5ea..8357ba56a 100644 --- a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.h +++ b/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.h @@ -33,6 +33,7 @@ extern "C" { #endif WK_EXPORT pid_t WKPageGetProcessIdentifier(WKPageRef page); +WK_EXPORT bool WKPageIsURLKnownHSTSHost(WKPageRef page, WKURLRef url); #ifdef __cplusplus } diff --git a/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.cpp b/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.cpp new file mode 100644 index 000000000..eee5c6f6d --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WKIconDatabaseQt.h" + +#include "WKAPICast.h" +#include "WKSharedAPICast.h" +#include "WebIconDatabase.h" +#include <QPixmap> + +using namespace WebKit; +using namespace WebCore; + +QImage WKIconDatabaseTryGetQImageForURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef urlRef) +{ + QPixmap* pixmap = toImpl(iconDatabaseRef)->nativeImageForPageURL(toWTFString(urlRef)); + return pixmap ? pixmap->toImage() : QImage(); +} diff --git a/Source/WebKit2/UIProcess/win/WebProcessProxyWin.cpp b/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.h index fef2c68b3..b472dfb98 100644 --- a/Source/WebKit2/UIProcess/win/WebProcessProxyWin.cpp +++ b/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.h @@ -1,4 +1,5 @@ /* + * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -23,18 +24,16 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" -#include "WebProcessProxy.h" +#ifndef WKIconDatabaseQt_h +#define WKIconDatabaseQt_h -namespace WebKit { +#include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> -Vector<HWND> WebProcessProxy::windowsToReceiveSentMessagesWhileWaitingForSyncReply() -{ - return Vector<HWND>(); -} +QT_BEGIN_NAMESPACE +class QImage; +QT_END_NAMESPACE -void WebProcessProxy::platformConnect(ProcessLauncher::LaunchOptions&) -{ -} +WK_EXPORT QImage WKIconDatabaseTryGetQImageForURL(WKIconDatabaseRef iconDatabase, WKURLRef url); -} // namespace WebKit +#endif /* WKIconDatabaseQt_h */ diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp b/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp index e4e88d384..f7549f003 100644 --- a/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp +++ b/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp @@ -29,10 +29,13 @@ #include "WKAPICast.h" #include "WebContext.h" +// Supplements +#include "WebSoupRequestManagerProxy.h" + using namespace WebKit; WKSoupRequestManagerRef WKContextGetSoupRequestManager(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->soupRequestManagerProxy()); + return toAPI(toImpl(contextRef)->supplement<WebSoupRequestManagerProxy>()); } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_resource.cpp b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.cpp index 57c14aa20..86b31aa47 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_resource.cpp +++ b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.cpp @@ -24,36 +24,28 @@ */ #include "config.h" -#include "ewk_resource.h" +#include "WKCookieManagerSoup.h" -#include "ewk_resource_private.h" -#include <wtf/text/CString.h> +#include "SoupCookiePersistentStorageType.h" +#include "WKAPICast.h" +#include "WebCookieManagerProxy.h" -EwkResource::EwkResource(WKURLRef url, bool isMainResource) - : m_url(url) - , m_isMainResource(isMainResource) -{ } +using namespace WebKit; -const char* EwkResource::url() const +inline SoupCookiePersistentStorageType toSoupCookiePersistentStorageType(WKCookieStorageType wkCookieStorageType) { - return m_url; + switch (wkCookieStorageType) { + case kWKCookieStorageTypeText: + return SoupCookiePersistentStorageText; + case kWKCookieStorageTypeSQLite: + return SoupCookiePersistentStorageSQLite; + } + + ASSERT_NOT_REACHED(); + return SoupCookiePersistentStorageText; } -bool EwkResource::isMainResource() const +void WKCookieManagerSetCookiePersistentStorage(WKCookieManagerRef cookieManager, WKStringRef storagePath, WKCookieStorageType storageType) { - return m_isMainResource; -} - -const char* ewk_resource_url_get(const Ewk_Resource* resource) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkResource, resource, impl, 0); - - return impl->url(); -} - -Eina_Bool ewk_resource_main_resource_get(const Ewk_Resource* resource) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkResource, resource, impl, false); - - return impl->isMainResource(); + toImpl(cookieManager)->setCookiePersistentStorage(toWTFString(storagePath), storageType); } diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h new file mode 100644 index 000000000..0a7b4ff05 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2012 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKCookieManagerSoup_h +#define WKCookieManagerSoup_h + +#include <WebKit2/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + kWKCookieStorageTypeText = 0, + kWKCookieStorageTypeSQLite = 1 +}; +typedef uint32_t WKCookieStorageType; + +WK_EXPORT void WKCookieManagerSetCookiePersistentStorage(WKCookieManagerRef cookieManager, WKStringRef storagePath, WKCookieStorageType storageType); + +#ifdef __cplusplus +} +#endif + +#endif // WKCookieManagerSoup_h diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h b/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h index 4dba13908..6892de4bf 100644 --- a/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h +++ b/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h @@ -26,7 +26,6 @@ #ifndef WKSoupRequestManager_h #define WKSoupRequestManager_h -#include "WKAPICast.h" #include <WebKit2/WKBase.h> #ifdef __cplusplus diff --git a/Source/WebKit2/UIProcess/API/C/win/WKView.cpp b/Source/WebKit2/UIProcess/API/C/win/WKView.cpp deleted file mode 100644 index 16b1c1980..000000000 --- a/Source/WebKit2/UIProcess/API/C/win/WKView.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WKView.h" - -#include "WKAPICast.h" -#include "WebView.h" - -using namespace WebKit; - -WKTypeID WKViewGetTypeID() -{ - return toAPI(APIObject::TypeView); -} - -WKViewRef WKViewCreate(RECT rect, WKContextRef contextRef, WKPageGroupRef pageGroupRef, HWND parentWindow) -{ - RefPtr<WebView> view = WebView::create(rect, toImpl(contextRef), toImpl(pageGroupRef), parentWindow); - return toAPI(view.release().leakRef()); -} - -HWND WKViewGetWindow(WKViewRef viewRef) -{ - return toImpl(viewRef)->window(); -} - -WKPageRef WKViewGetPage(WKViewRef viewRef) -{ - return toAPI(toImpl(viewRef)->page()); -} - -void WKViewSetParentWindow(WKViewRef viewRef, HWND hostWindow) -{ - toImpl(viewRef)->setParentWindow(hostWindow); -} - -void WKViewWindowAncestryDidChange(WKViewRef viewRef) -{ - toImpl(viewRef)->windowAncestryDidChange(); -} - -void WKViewSetIsInWindow(WKViewRef viewRef, bool isInWindow) -{ - toImpl(viewRef)->setIsInWindow(isInWindow); -} - -void WKViewSetInitialFocus(WKViewRef viewRef, bool forward) -{ - bool isKeyboardEventValid = false; - toImpl(viewRef)->setInitialFocus(forward, isKeyboardEventValid, WebKeyboardEvent()); -} - -void WKViewSetScrollOffsetOnNextResize(WKViewRef viewRef, WKSize scrollOffset) -{ - toImpl(viewRef)->setScrollOffsetOnNextResize(toIntSize(scrollOffset)); -} - -void WKViewSetFindIndicatorCallback(WKViewRef viewRef, WKViewFindIndicatorCallback callback, void* context) -{ - toImpl(viewRef)->setFindIndicatorCallback(callback, context); -} - -WKViewFindIndicatorCallback WKViewGetFindIndicatorCallback(WKViewRef viewRef, void** context) -{ - return toImpl(viewRef)->getFindIndicatorCallback(context); -} - -bool WKViewIsPageOverlayInstalled(WKViewRef viewRef) -{ - return toImpl(viewRef)->pageOverlayInstalled(); -} - -void WKViewSetViewUndoClient(WKViewRef viewRef, const WKViewUndoClient* wkClient) -{ - if (wkClient && wkClient->version) - return; - toImpl(viewRef)->initializeUndoClient(wkClient); -} - -void WKViewReapplyEditCommand(WKViewRef viewRef, WKEditCommandRef command) -{ - toImpl(viewRef)->reapplyEditCommand(toImpl(command)); -} - -void WKViewUnapplyEditCommand(WKViewRef viewRef, WKEditCommandRef command) -{ - toImpl(viewRef)->unapplyEditCommand(toImpl(command)); -} - -void WKViewSetDrawsTransparentBackground(WKViewRef viewRef, bool drawsTransparentBackground) -{ - toImpl(viewRef)->page()->setDrawsTransparentBackground(drawsTransparentBackground); -} - -bool WKViewDrawsTransparentBackground(WKViewRef viewRef) -{ - return toImpl(viewRef)->page()->drawsTransparentBackground(); -} - -void WKViewSetCustomDropTarget(WKViewRef viewRef, IDropTarget* dropTarget) -{ - return toImpl(viewRef)->setCustomDropTarget(dropTarget); -} - diff --git a/Source/WebKit2/UIProcess/API/C/win/WKView.h b/Source/WebKit2/UIProcess/API/C/win/WKView.h deleted file mode 100644 index b54093f63..000000000 --- a/Source/WebKit2/UIProcess/API/C/win/WKView.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WKView_h -#define WKView_h - -#include <WebKit2/WKBase.h> -#include <WebKit2/WKGeometry.h> -#include <windows.h> - -struct IDropTarget; - -#ifdef __cplusplus -extern "C" { -#endif - -// Undo Client. -enum { - kWKViewUndo = 0, - kWKViewRedo = 1 -}; -typedef uint32_t WKViewUndoType; - -typedef void (*WKViewRegisterEditCommandCallback)(WKViewRef, WKEditCommandRef, WKViewUndoType undoOrRedo, const void *clientInfo); -typedef void (*WKViewClearAllEditCommandsCallback)(WKViewRef, const void *clientInfo); -typedef bool (*WKViewCanUndoRedoCallback)(WKViewRef, WKViewUndoType undoOrRedo, const void *clientInfo); -typedef void (*WKViewExecuteUndoRedoCallback)(WKViewRef, WKViewUndoType undoOrRedo, const void *clientInfo); - -struct WKViewUndoClient { - int version; - const void * clientInfo; - WKViewRegisterEditCommandCallback registerEditCommand; - WKViewClearAllEditCommandsCallback clearAllEditCommands; - WKViewCanUndoRedoCallback canUndoRedo; - WKViewExecuteUndoRedoCallback executeUndoRedo; -}; -typedef struct WKViewUndoClient WKViewUndoClient; - -enum { kWKViewUndoClientCurrentVersion = 0 }; - -WK_EXPORT WKTypeID WKViewGetTypeID(); - -WK_EXPORT WKViewRef WKViewCreate(RECT rect, WKContextRef context, WKPageGroupRef pageGroup, HWND parentWindow); - -WK_EXPORT HWND WKViewGetWindow(WKViewRef view); - -WK_EXPORT WKPageRef WKViewGetPage(WKViewRef view); - -WK_EXPORT void WKViewSetViewUndoClient(WKViewRef view, const WKViewUndoClient* client); -WK_EXPORT void WKViewReapplyEditCommand(WKViewRef view, WKEditCommandRef command); -WK_EXPORT void WKViewUnapplyEditCommand(WKViewRef view, WKEditCommandRef command); - -WK_EXPORT void WKViewSetParentWindow(WKViewRef view, HWND parentWindow); -WK_EXPORT void WKViewWindowAncestryDidChange(WKViewRef view); -WK_EXPORT void WKViewSetIsInWindow(WKViewRef view, bool isInWindow); -WK_EXPORT void WKViewSetInitialFocus(WKViewRef view, bool forward); -WK_EXPORT void WKViewSetScrollOffsetOnNextResize(WKViewRef view, WKSize scrollOffset); - -typedef void (*WKViewFindIndicatorCallback)(WKViewRef, HBITMAP selectionBitmap, RECT selectionRectInWindowCoordinates, bool fadeout, void*); -WK_EXPORT void WKViewSetFindIndicatorCallback(WKViewRef view, WKViewFindIndicatorCallback callback, void* context); -WK_EXPORT WKViewFindIndicatorCallback WKViewGetFindIndicatorCallback(WKViewRef view, void** context); - -WK_EXPORT bool WKViewIsPageOverlayInstalled(WKViewRef view); - -WK_EXPORT void WKViewSetDrawsTransparentBackground(WKViewRef view, bool drawsTransparentBackground); -WK_EXPORT bool WKViewDrawsTransparentBackground(WKViewRef view); - -WK_EXPORT void WKViewSetCustomDropTarget(WKViewRef view, IDropTarget*); - -#ifdef __cplusplus -} -#endif - -#endif /* WKView_h */ diff --git a/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp new file mode 100644 index 000000000..5d14f4369 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies) + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#if USE(COORDINATED_GRAPHICS) + +#include "WKCoordinatedScene.h" + +#include "WKCoordinatedSceneAPICast.h" + +#include <WebCore/CoordinatedGraphicsScene.h> +#include <WebCore/TextureMapperLayer.h> + +WK_EXPORT WKCoordinatedSceneLayer WKCoordinatedSceneFindScrollableContentsLayerAt(WKCoordinatedScene scene, WKPoint point) +{ + return toAPI(toImpl(scene)->findScrollableContentsLayerAt(WebCore::FloatPoint(point.x, point.y))); +} + +WK_EXPORT uint32_t WKCoordinatedSceneGetLayerID(WKCoordinatedSceneLayer layer) +{ + return toImpl(layer)->id(); +} + +WK_EXPORT void WKCoordinatedSceneScrollBy(WKCoordinatedSceneLayer layer, WKSize offset) +{ + toImpl(layer)->scrollBy(WebCore::FloatSize(offset.width, offset.height)); +} +#endif diff --git a/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h new file mode 100644 index 000000000..c4e88dcdf --- /dev/null +++ b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies) + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKCoordinatedScene_h +#define WKCoordinatedScene_h + +#include <WebKit2/WKGeometry.h> + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +typedef struct OpaqueCGScene* WKCoordinatedScene; +typedef struct OpaqueCGLayer* WKCoordinatedSceneLayer; + +WK_EXPORT WKCoordinatedSceneLayer WKCoordinatedSceneFindScrollableContentsLayerAt(WKCoordinatedScene, WKPoint); +WK_EXPORT uint32_t WKCoordinatedSceneGetLayerID(WKCoordinatedSceneLayer); +WK_EXPORT void WKCoordinatedSceneScrollBy(WKCoordinatedSceneLayer, WKSize); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // WKCoordinatedScene_h diff --git a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp b/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp index 21ff597d5..ecb7b5f79 100644 --- a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp +++ b/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp @@ -112,3 +112,11 @@ WKEinaSharedString WKEinaSharedString::adopt(Eina_Stringshare* string) sharedString.m_string = static_cast<const char*>(string); return sharedString; } + +Eina_Stringshare* WKEinaSharedString::leakString() +{ + Eina_Stringshare* sharedString = m_string; + m_string = 0; + + return sharedString; +} diff --git a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.h b/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.h index 52cfffa0e..dbb5f4788 100644 --- a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.h +++ b/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.h @@ -46,6 +46,8 @@ public: ~WKEinaSharedString(); + Eina_Stringshare* leakString(); + WKEinaSharedString& operator=(const WKEinaSharedString& other); WKEinaSharedString& operator=(const char* str); diff --git a/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.cpp b/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.cpp index f2f188354..4ae448e62 100644 --- a/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.cpp +++ b/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.cpp @@ -22,6 +22,7 @@ #include "WKStringQt.h" #include "WKAPICast.h" +#include "WKRetainPtr.h" #include <QString> #include <wtf/RefPtr.h> #include <wtf/text/WTFString.h> @@ -41,3 +42,10 @@ QString WKStringCopyQString(WKStringRef stringRef) const WTF::String& string = toImpl(stringRef)->string(); return QString(reinterpret_cast<const QChar*>(string.characters()), string.length()); } + +namespace WebKit { +QString adoptToQString(WKStringRef stringRef) +{ + return WKStringCopyQString(adoptWK(stringRef).get()); +} +} /* namespace WebKit */ diff --git a/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.h b/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.h index cc46e4250..ff2cfa837 100644 --- a/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.h +++ b/Source/WebKit2/UIProcess/API/cpp/qt/WKStringQt.h @@ -27,4 +27,9 @@ WK_EXPORT WKStringRef WKStringCreateWithQString(const QString& string); WK_EXPORT QString WKStringCopyQString(WKStringRef string); +namespace WebKit { +QString adoptToQString(WKStringRef); +} /* namespace WebKit */ + +using WebKit::adoptToQString; #endif /* WKStringQt_h */ diff --git a/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.cpp b/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.cpp index f9111f7ea..f9177fd59 100644 --- a/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.cpp +++ b/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.cpp @@ -22,22 +22,45 @@ #include "WKURLQt.h" #include "WKAPICast.h" +#include "WKRetainPtr.h" #include <QString> #include <wtf/RefPtr.h> #include <wtf/text/WTFString.h> using namespace WebKit; -WKURLRef WKURLCreateWithQUrl(const QUrl& qURL) +WKURLRef WKURLCreateWithQString(const QString& url) { - WTF::String urlString(qURL.toString()); - return toCopiedURLAPI(urlString); + return toCopiedURLAPI(url); +} + +QString WKURLCopyQString(WKURLRef urlRef) +{ + if (!urlRef) + return QString(); + return toImpl(urlRef)->string(); +} + +WKURLRef WKURLCreateWithQUrl(const QUrl& url) +{ + return WKURLCreateWithQString(url.toString(QUrl::FullyEncoded)); } QUrl WKURLCopyQUrl(WKURLRef urlRef) { if (!urlRef) return QUrl(); - const WTF::String& string = toImpl(urlRef)->string(); - return QUrl(QString(reinterpret_cast<const QChar*>(string.characters()), string.length())); + return QUrl(WKURLCopyQString(urlRef)); +} + +namespace WebKit { +QString adoptToQString(WKURLRef urlRef) +{ + return WKURLCopyQString(adoptWK(urlRef).get()); +} + +QUrl adoptToQUrl(WKURLRef urlRef) +{ + return WKURLCopyQUrl(adoptWK(urlRef).get()); } +} /* namespace WebKit */ diff --git a/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.h b/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.h index 2e4147330..b12f97459 100644 --- a/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.h +++ b/Source/WebKit2/UIProcess/API/cpp/qt/WKURLQt.h @@ -25,7 +25,18 @@ #include <WebKit2/WKBase.h> #include <WebKit2/WKURL.h> +WK_EXPORT WKURLRef WKURLCreateWithQString(const QString& url); +WK_EXPORT QString WKURLCopyQString(WKURLRef url); + WK_EXPORT WKURLRef WKURLCreateWithQUrl(const QUrl& url); -QUrl WKURLCopyQUrl(WKURLRef url); +WK_EXPORT QUrl WKURLCopyQUrl(WKURLRef url); + +namespace WebKit { +QString adoptToQString(WKURLRef); +QUrl adoptToQUrl(WKURLRef); +} /* namespace WebKit */ + +using WebKit::adoptToQString; +using WebKit::adoptToQUrl; #endif /* WKURLCF_h */ diff --git a/Source/WebKit2/UIProcess/API/efl/EWebKit2.h b/Source/WebKit2/UIProcess/API/efl/EWebKit2.h index b12211084..a9c8a14e7 100644 --- a/Source/WebKit2/UIProcess/API/efl/EWebKit2.h +++ b/Source/WebKit2/UIProcess/API/efl/EWebKit2.h @@ -42,15 +42,13 @@ #include "ewk_favicon_database.h" #include "ewk_file_chooser_request.h" #include "ewk_form_submission_request.h" -#include "ewk_intent.h" -#include "ewk_intent_service.h" #include "ewk_main.h" #include "ewk_navigation_data.h" #include "ewk_navigation_policy_decision.h" #include "ewk_object.h" +#include "ewk_page_group.h" #include "ewk_popup_menu.h" #include "ewk_popup_menu_item.h" -#include "ewk_resource.h" #include "ewk_security_origin.h" #include "ewk_settings.h" #include "ewk_storage_manager.h" diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.cpp b/Source/WebKit2/UIProcess/API/efl/EvasGLContext.cpp index 98a7e6a8e..862ddbb39 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.cpp +++ b/Source/WebKit2/UIProcess/API/efl/EvasGLContext.cpp @@ -24,10 +24,11 @@ */ #include "config.h" -#include "EvasGLContext.h" #if USE(ACCELERATED_COMPOSITING) +#include "EvasGLContext.h" + namespace WebKit { EvasGLContext::EvasGLContext(Evas_GL* evasGL, Evas_GL_Context* passContext) @@ -44,5 +45,4 @@ EvasGLContext::~EvasGLContext() } } // namespace WebKit - -#endif // USE(ACCELERATED_COMPOSITING) +#endif diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.h b/Source/WebKit2/UIProcess/API/efl/EvasGLContext.h index 9899a81f4..2ef7364dc 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.h +++ b/Source/WebKit2/UIProcess/API/efl/EvasGLContext.h @@ -25,8 +25,8 @@ #ifndef EvasGLContext_h #define EvasGLContext_h - #if USE(ACCELERATED_COMPOSITING) + #include <Evas_GL.h> #include <wtf/PassOwnPtr.h> @@ -46,7 +46,7 @@ public: } ~EvasGLContext(); - inline Evas_GL_Context* context() const { return m_context; } + Evas_GL_Context* context() { return m_context; } private: EvasGLContext(Evas_GL* evasGL, Evas_GL_Context* passContext); @@ -58,5 +58,4 @@ private: } // namespace WebKit #endif // USE(ACCELERATED_COMPOSITING) - #endif // EvasGLContext_h diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.cpp b/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.cpp index d5d138390..c7ec13c8e 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.cpp +++ b/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.cpp @@ -24,10 +24,10 @@ */ #include "config.h" -#include "EvasGLSurface.h" - #if USE(ACCELERATED_COMPOSITING) +#include "EvasGLSurface.h" + namespace WebKit { EvasGLSurface::EvasGLSurface(Evas_GL* evasGL, Evas_GL_Surface* passSurface) @@ -44,5 +44,4 @@ EvasGLSurface::~EvasGLSurface() } } // namespace WebKit - -#endif // USE(ACCELERATED_COMPOSITING) +#endif diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h b/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h index 9ab3062c4..f6fb2b5b0 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h +++ b/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h @@ -25,8 +25,8 @@ #ifndef EvasGLSurface_h #define EvasGLSurface_h - #if USE(ACCELERATED_COMPOSITING) + #include <Evas_GL.h> #include <WebCore/IntSize.h> #include <wtf/PassOwnPtr.h> @@ -39,7 +39,13 @@ public: { ASSERT(evasGL); ASSERT(cfg); - Evas_GL_Surface* surface = evas_gl_surface_create(evasGL, cfg, size.width(), size.height()); + + Evas_GL_Surface* surface = 0; + + // Ensure that the surface is created with valid size. + if (size.width() && size.height()) + surface = evas_gl_surface_create(evasGL, cfg, size.width(), size.height()); + if (!surface) return nullptr; @@ -48,7 +54,7 @@ public: } ~EvasGLSurface(); - inline Evas_GL_Surface* surface() const { return m_surface; } + Evas_GL_Surface* surface() { return m_surface; } private: EvasGLSurface(Evas_GL* evasGL, Evas_GL_Surface* passSurface); @@ -60,5 +66,4 @@ private: } // namespace WebKit #endif // USE(ACCELERATED_COMPOSITING) - #endif // EvasGLSurface_h diff --git a/Source/WebKit2/UIProcess/API/efl/EwkView.cpp b/Source/WebKit2/UIProcess/API/efl/EwkView.cpp new file mode 100644 index 000000000..457c86163 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/EwkView.cpp @@ -0,0 +1,1425 @@ +/* + Copyright (C) 2011 Samsung Electronics + Copyright (C) 2012 Intel Corporation. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "EwkView.h" + +#include "ContextMenuClientEfl.h" +#include "EflScreenUtilities.h" +#include "FindClientEfl.h" +#include "FormClientEfl.h" +#include "InputMethodContextEfl.h" +#include "NativeWebKeyboardEvent.h" +#include "NativeWebMouseEvent.h" +#include "NativeWebWheelEvent.h" +#include "NotImplemented.h" +#include "PageLoadClientEfl.h" +#include "PagePolicyClientEfl.h" +#include "PageUIClientEfl.h" +#include "PageViewportController.h" +#include "PageViewportControllerClientEfl.h" +#include "SnapshotImageGL.h" +#include "ViewClientEfl.h" +#include "WKArray.h" +#include "WKDictionary.h" +#include "WKEventEfl.h" +#include "WKGeometry.h" +#include "WKNumber.h" +#include "WKPageGroup.h" +#include "WKPopupItem.h" +#include "WKString.h" +#include "WKView.h" +#include "WKViewEfl.h" +#include "WebContext.h" +#include "WebImage.h" +#include "WebPageGroup.h" +#include "WebPageProxy.h" +#include "WebPreferences.h" +#include "ewk_back_forward_list_private.h" +#include "ewk_color_picker_private.h" +#include "ewk_context_menu_item_private.h" +#include "ewk_context_menu_private.h" +#include "ewk_context_private.h" +#include "ewk_favicon_database_private.h" +#include "ewk_page_group_private.h" +#include "ewk_popup_menu_item_private.h" +#include "ewk_popup_menu_private.h" +#include "ewk_private.h" +#include "ewk_security_origin_private.h" +#include "ewk_settings_private.h" +#include "ewk_view.h" +#include "ewk_window_features_private.h" +#include <Ecore_Evas.h> +#include <Ecore_X.h> +#include <Edje.h> +#if USE(ACCELERATED_COMPOSITING) +#include <Evas_GL.h> +#endif +#include <WebCore/CairoUtilitiesEfl.h> +#include <WebCore/Cursor.h> +#include <WebCore/NotImplemented.h> +#include <WebCore/PlatformContextCairo.h> +#include <WebKit2/WKImageCairo.h> +#include <wtf/MathExtras.h> + +#if ENABLE(VIBRATION) +#include "VibrationClientEfl.h" +#endif + +#if ENABLE(FULLSCREEN_API) +#include "WebFullScreenManagerProxy.h" +#endif + +using namespace EwkViewCallbacks; +using namespace WebCore; +using namespace WebKit; + +static const char smartClassName[] = "EWK2_View"; +static const int defaultCursorSize = 16; + +// Auxiliary functions. + +static inline void smartDataChanged(Ewk_View_Smart_Data* smartData) +{ + ASSERT(smartData); + + if (smartData->changed.any) + return; + + smartData->changed.any = true; + evas_object_smart_changed(smartData->self); +} + +static Evas_Smart* defaultSmartClassInstance() +{ + static Ewk_View_Smart_Class api = EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION(smartClassName); + static Evas_Smart* smart = 0; + + if (!smart) { + EwkView::initSmartClassInterface(api); + smart = evas_smart_class_new(&api.sc); + } + + return smart; +} + +static inline Ewk_View_Smart_Data* toSmartData(Evas_Object* evasObject) +{ + ASSERT(evasObject); + ASSERT(isEwkViewEvasObject(evasObject)); + + return static_cast<Ewk_View_Smart_Data*>(evas_object_smart_data_get(evasObject)); +} + +static inline EwkView* toEwkView(const Ewk_View_Smart_Data* smartData) +{ + ASSERT(smartData); + ASSERT(smartData->priv); + + return smartData->priv; +} + +static inline void showEvasObjectsIfNeeded(const Ewk_View_Smart_Data* smartData) +{ + ASSERT(smartData); + + if (evas_object_clipees_get(smartData->base.clipper)) + evas_object_show(smartData->base.clipper); + evas_object_show(smartData->image); +} + +// EwkViewEventHandler implementation. + +template <Evas_Callback_Type EventType> +class EwkViewEventHandler { +public: + static void subscribe(Evas_Object* evasObject) + { + evas_object_event_callback_add(evasObject, EventType, handleEvent, toSmartData(evasObject)); + } + + static void unsubscribe(Evas_Object* evasObject) + { + evas_object_event_callback_del(evasObject, EventType, handleEvent); + } + + static void handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo); +}; + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_MOUSE_DOWN>::handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->mouse_down) + smartData->api->mouse_down(smartData, static_cast<Evas_Event_Mouse_Down*>(eventInfo)); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_MOUSE_UP>::handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->mouse_up) + smartData->api->mouse_up(smartData, static_cast<Evas_Event_Mouse_Up*>(eventInfo)); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_MOUSE_MOVE>::handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->mouse_move) + smartData->api->mouse_move(smartData, static_cast<Evas_Event_Mouse_Move*>(eventInfo)); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_FOCUS_IN>::handleEvent(void* data, Evas*, Evas_Object*, void*) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->focus_in) + smartData->api->focus_in(smartData); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_FOCUS_OUT>::handleEvent(void* data, Evas*, Evas_Object*, void*) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->focus_out) + smartData->api->focus_out(smartData); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_MOUSE_WHEEL>::handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->mouse_wheel) + smartData->api->mouse_wheel(smartData, static_cast<Evas_Event_Mouse_Wheel*>(eventInfo)); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_KEY_DOWN>::handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->key_down) + smartData->api->key_down(smartData, static_cast<Evas_Event_Key_Down*>(eventInfo)); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_KEY_UP>::handleEvent(void* data, Evas*, Evas_Object*, void* eventInfo) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + if (smartData->api->key_up) + smartData->api->key_up(smartData, static_cast<Evas_Event_Key_Up*>(eventInfo)); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_SHOW>::handleEvent(void* data, Evas*, Evas_Object*, void*) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + WKViewSetIsVisible(toEwkView(smartData)->wkView(), true); +} + +template <> +void EwkViewEventHandler<EVAS_CALLBACK_HIDE>::handleEvent(void* data, Evas*, Evas_Object*, void*) +{ + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); + WKViewSetIsVisible(toEwkView(smartData)->wkView(), false); +} + +typedef HashMap<WKPageRef, Evas_Object*> WKPageToEvasObjectMap; + +static inline WKPageToEvasObjectMap& wkPageToEvasObjectMap() +{ + DEFINE_STATIC_LOCAL(WKPageToEvasObjectMap, map, ()); + return map; +} + +// EwkView implementation. + +EwkView::EwkView(WKViewRef view, Evas_Object* evasObject) + : m_webView(view) + , m_evasObject(evasObject) + , m_context(EwkContext::findOrCreateWrapper(WKPageGetContext(wkPage()))) + , m_pageGroup(EwkPageGroup::findOrCreateWrapper(WKPageGetPageGroup(wkPage()))) +#if USE(ACCELERATED_COMPOSITING) + , m_pendingSurfaceResize(false) +#endif + , m_pageLoadClient(PageLoadClientEfl::create(this)) + , m_pagePolicyClient(PagePolicyClientEfl::create(this)) + , m_pageUIClient(PageUIClientEfl::create(this)) + , m_contextMenuClient(ContextMenuClientEfl::create(this)) + , m_findClient(FindClientEfl::create(this)) + , m_formClient(FormClientEfl::create(this)) + , m_viewClient(ViewClientEfl::create(this)) +#if ENABLE(VIBRATION) + , m_vibrationClient(VibrationClientEfl::create(this)) +#endif + , m_backForwardList(EwkBackForwardList::create(WKPageGetBackForwardList(wkPage()))) + , m_settings(EwkSettings::create(this)) + , m_cursorIdentifier(0) + , m_userAgent(WKEinaSharedString(AdoptWK, WKPageCopyUserAgent(wkPage()))) + , m_mouseEventsEnabled(false) +#if ENABLE(TOUCH_EVENTS) + , m_touchEventsEnabled(false) +#endif + , m_displayTimer(this, &EwkView::displayTimerFired) + , m_inputMethodContext(InputMethodContextEfl::create(this, smartData()->base.evas)) +#if USE(ACCELERATED_COMPOSITING) + , m_pageViewportControllerClient(PageViewportControllerClientEfl::create(this)) + , m_pageViewportController(adoptPtr(new PageViewportController(page(), m_pageViewportControllerClient.get()))) +#endif + , m_isAccelerated(true) +{ + ASSERT(m_evasObject); + ASSERT(m_context); + + // FIXME: Remove when possible. + static_cast<WebViewEfl*>(webView())->setEwkView(this); +#if USE(ACCELERATED_COMPOSITING) + m_evasGL = adoptPtr(evas_gl_new(evas_object_evas_get(m_evasObject))); + if (m_evasGL) + m_evasGLContext = EvasGLContext::create(m_evasGL.get()); + + if (!m_evasGLContext) { + WARN("Failed to create Evas_GL, falling back to software mode."); + m_isAccelerated = false; + } +#endif + WKViewInitialize(wkView()); + + WKPageGroupRef wkPageGroup = WKPageGetPageGroup(wkPage()); + WKPreferencesRef wkPreferences = WKPageGroupGetPreferences(wkPageGroup); +#if USE(ACCELERATED_COMPOSITING) + WKPreferencesSetWebGLEnabled(wkPreferences, true); +#endif + WKPreferencesSetFullScreenEnabled(wkPreferences, true); + WKPreferencesSetWebAudioEnabled(wkPreferences, true); + WKPreferencesSetOfflineWebApplicationCacheEnabled(wkPreferences, true); +#if ENABLE(SPELLCHECK) + WKPreferencesSetAsynchronousSpellCheckingEnabled(wkPreferences, true); +#endif + WKPreferencesSetInteractiveFormValidationEnabled(wkPreferences, true); + + // Enable mouse events by default + setMouseEventsEnabled(true); + + // Listen for favicon changes. + EwkFaviconDatabase* iconDatabase = m_context->faviconDatabase(); + ASSERT(iconDatabase); + + iconDatabase->watchChanges(IconChangeCallbackData(EwkView::handleFaviconChanged, this)); + + WKPageToEvasObjectMap::AddResult result = wkPageToEvasObjectMap().add(wkPage(), m_evasObject); + ASSERT_UNUSED(result, result.isNewEntry); +} + +EwkView::~EwkView() +{ + // Unregister icon change callback. + EwkFaviconDatabase* iconDatabase = m_context->faviconDatabase(); + ASSERT(iconDatabase); + + iconDatabase->unwatchChanges(EwkView::handleFaviconChanged); + + ASSERT(wkPageToEvasObjectMap().get(wkPage()) == m_evasObject); + wkPageToEvasObjectMap().remove(wkPage()); +} + +EwkView* EwkView::create(WKViewRef webView, Evas* canvas, Evas_Smart* smart) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(canvas, 0); + + Evas_Object* evasObject = evas_object_smart_add(canvas, smart ? smart : defaultSmartClassInstance()); + EINA_SAFETY_ON_NULL_RETURN_VAL(evasObject, 0); + + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + if (!smartData) { + evas_object_del(evasObject); + return 0; + } + + ASSERT(!smartData->priv); + + smartData->priv = new EwkView(webView, evasObject); + + return smartData->priv; +} + +bool EwkView::initSmartClassInterface(Ewk_View_Smart_Class& api) +{ + if (api.version != EWK_VIEW_SMART_CLASS_VERSION) { + EINA_LOG_CRIT("Ewk_View_Smart_Class %p is version %lu while %lu was expected.", + &api, api.version, EWK_VIEW_SMART_CLASS_VERSION); + return false; + } + + if (!parentSmartClass.add) + evas_object_smart_clipped_smart_set(&parentSmartClass); + + evas_object_smart_clipped_smart_set(&api.sc); + + // Set Evas_Smart_Class callbacks. + api.sc.add = handleEvasObjectAdd; + api.sc.del = handleEvasObjectDelete; + api.sc.move = handleEvasObjectMove; + api.sc.resize = handleEvasObjectResize; + api.sc.show = handleEvasObjectShow; + api.sc.hide = handleEvasObjectHide; + api.sc.color_set = handleEvasObjectColorSet; + api.sc.calculate = handleEvasObjectCalculate; + api.sc.data = smartClassName; // It is used for type checking. + + // Set Ewk_View_Smart_Class callbacks. + api.focus_in = handleEwkViewFocusIn; + api.focus_out = handleEwkViewFocusOut; + api.mouse_wheel = handleEwkViewMouseWheel; + api.mouse_down = handleEwkViewMouseDown; + api.mouse_up = handleEwkViewMouseUp; + api.mouse_move = handleEwkViewMouseMove; + api.key_down = handleEwkViewKeyDown; + api.key_up = handleEwkViewKeyUp; + + return true; +} + +Evas_Object* EwkView::toEvasObject(WKPageRef page) +{ + ASSERT(page); + return wkPageToEvasObjectMap().get(page); +} + +WKPageRef EwkView::wkPage() const +{ + return WKViewGetPage(wkView()); +} + +void EwkView::setCursor(const Cursor& cursor) +{ + if (cursor.image()) { + // Custom cursor. + if (cursor.image() == m_cursorIdentifier) + return; + + m_cursorIdentifier = cursor.image(); + + Ewk_View_Smart_Data* sd = smartData(); + RefPtr<Evas_Object> cursorObject = adoptRef(cursor.image()->getEvasObject(sd->base.evas)); + if (!cursorObject) + return; + + // Resize cursor. + evas_object_resize(cursorObject.get(), cursor.image()->size().width(), cursor.image()->size().height()); + + // Get cursor hot spot. + IntPoint hotSpot; + cursor.image()->getHotSpot(hotSpot); + + Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); + // ecore_evas takes care of freeing the cursor object. + ecore_evas_object_cursor_set(ecoreEvas, cursorObject.release().leakRef(), EVAS_LAYER_MAX, hotSpot.x(), hotSpot.y()); + + return; + } + + // Standard cursor. + const char* group = cursor.platformCursor(); + if (!group || group == m_cursorIdentifier) + return; + + m_cursorIdentifier = group; + Ewk_View_Smart_Data* sd = smartData(); + RefPtr<Evas_Object> cursorObject = adoptRef(edje_object_add(sd->base.evas)); + + Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); + if (!m_theme || !edje_object_file_set(cursorObject.get(), m_theme, group)) { + ecore_evas_object_cursor_set(ecoreEvas, 0, 0, 0, 0); +#ifdef HAVE_ECORE_X + if (WebCore::isUsingEcoreX(sd->base.evas)) + WebCore::applyFallbackCursor(ecoreEvas, group); +#endif + return; + } + + // Set cursor size. + Evas_Coord width, height; + edje_object_size_min_get(cursorObject.get(), &width, &height); + if (width <= 0 || height <= 0) + edje_object_size_min_calc(cursorObject.get(), &width, &height); + if (width <= 0 || height <= 0) { + width = defaultCursorSize; + height = defaultCursorSize; + } + evas_object_resize(cursorObject.get(), width, height); + + // Get cursor hot spot. + const char* data; + int hotspotX = 0; + data = edje_object_data_get(cursorObject.get(), "hot.x"); + if (data) + hotspotX = atoi(data); + + int hotspotY = 0; + data = edje_object_data_get(cursorObject.get(), "hot.y"); + if (data) + hotspotY = atoi(data); + + // ecore_evas takes care of freeing the cursor object. + ecore_evas_object_cursor_set(ecoreEvas, cursorObject.release().leakRef(), EVAS_LAYER_MAX, hotspotX, hotspotY); +} + +void EwkView::setDeviceScaleFactor(float scale) +{ + const WKSize& deviceSize = WKViewGetSize(wkView()); + WKPageSetCustomBackingScaleFactor(wkPage(), scale); + + // Update internal viewport size after device-scale change. + WKViewSetSize(wkView(), deviceSize); +} + +float EwkView::deviceScaleFactor() const +{ + return WKPageGetBackingScaleFactor(wkPage()); +} + +AffineTransform EwkView::transformToScreen() const +{ + AffineTransform transform; + + int windowGlobalX = 0; + int windowGlobalY = 0; + + Ewk_View_Smart_Data* sd = smartData(); + +#ifdef HAVE_ECORE_X + Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); + + Ecore_X_Window window; + window = ecore_evas_gl_x11_window_get(ecoreEvas); + // Fallback to software mode if necessary. + if (!window) + window = ecore_evas_software_x11_window_get(ecoreEvas); // Returns 0 if none. + + int x, y; // x, y are relative to parent (in a reparenting window manager). + while (window) { + ecore_x_window_geometry_get(window, &x, &y, 0, 0); + windowGlobalX += x; + windowGlobalY += y; + window = ecore_x_window_parent_get(window); + } +#endif + + transform.translate(-sd->view.x, -sd->view.y); + transform.translate(windowGlobalX, windowGlobalY); + + return transform; +} + +inline Ewk_View_Smart_Data* EwkView::smartData() const +{ + return toSmartData(m_evasObject); +} + +inline IntSize EwkView::size() const +{ + // WebPage expects a size in UI units, and not raw device units. + FloatSize uiSize = deviceSize(); + uiSize.scale(1 / deviceScaleFactor()); + return roundedIntSize(uiSize); +} + +inline IntSize EwkView::deviceSize() const +{ + return toIntSize(WKViewGetSize(wkView())); +} + +void EwkView::displayTimerFired(Timer<EwkView>*) +{ + Ewk_View_Smart_Data* sd = smartData(); + +#if USE(ACCELERATED_COMPOSITING) + if (m_pendingSurfaceResize) { + // Create a GL surface here so that Evas has no chance of painting to an empty GL surface. + if (!createGLSurface()) + return; + // Make Evas objects visible here in order not to paint empty Evas objects with black color. + showEvasObjectsIfNeeded(sd); + + m_pendingSurfaceResize = false; + } +#endif + + if (!m_isAccelerated) { + RefPtr<cairo_surface_t> surface = createSurfaceForImage(sd->image); + if (!surface) + return; + + WKViewPaintToCairoSurface(wkView(), surface.get()); + evas_object_image_data_update_add(sd->image, 0, 0, sd->view.w, sd->view.h); + return; + } +#if USE(ACCELERATED_COMPOSITING) + evas_gl_make_current(m_evasGL.get(), m_evasGLSurface->surface(), m_evasGLContext->context()); + + WKViewPaintToCurrentGLContext(wkView()); +#endif + // sd->image is tied to a native surface, which is in the parent's coordinates. + evas_object_image_data_update_add(sd->image, sd->view.x, sd->view.y, sd->view.w, sd->view.h); +} + +void EwkView::scheduleUpdateDisplay() +{ + if (deviceSize().isEmpty()) + return; + + if (!m_displayTimer.isActive()) + m_displayTimer.startOneShot(0); +} + +#if ENABLE(FULLSCREEN_API) +/** + * @internal + * Calls fullscreen_enter callback or falls back to default behavior and enables fullscreen mode. + */ +void EwkView::enterFullScreen() +{ + Ewk_View_Smart_Data* sd = smartData(); + + RefPtr<EwkSecurityOrigin> origin = EwkSecurityOrigin::create(m_url); + + if (!sd->api->fullscreen_enter || !sd->api->fullscreen_enter(sd, origin.get())) { + Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); + ecore_evas_fullscreen_set(ecoreEvas, true); + } +} + +/** + * @internal + * Calls fullscreen_exit callback or falls back to default behavior and disables fullscreen mode. + */ +void EwkView::exitFullScreen() +{ + Ewk_View_Smart_Data* sd = smartData(); + + if (!sd->api->fullscreen_exit || !sd->api->fullscreen_exit(sd)) { + Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); + ecore_evas_fullscreen_set(ecoreEvas, false); + } +} +#endif + +WKRect EwkView::windowGeometry() const +{ + Evas_Coord x, y, width, height; + Ewk_View_Smart_Data* sd = smartData(); + + if (!sd->api->window_geometry_get || !sd->api->window_geometry_get(sd, &x, &y, &width, &height)) { + Ecore_Evas* ee = ecore_evas_ecore_evas_get(sd->base.evas); + ecore_evas_request_geometry_get(ee, &x, &y, &width, &height); + } + + return WKRectMake(x, y, width, height); +} + +void EwkView::setWindowGeometry(const WKRect& rect) +{ + Ewk_View_Smart_Data* sd = smartData(); + + if (!sd->api->window_geometry_set || !sd->api->window_geometry_set(sd, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)) { + Ecore_Evas* ee = ecore_evas_ecore_evas_get(sd->base.evas); + ecore_evas_move_resize(ee, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); + } +} + +const char* EwkView::title() const +{ + m_title = WKEinaSharedString(AdoptWK, WKPageCopyTitle(wkPage())); + + return m_title; +} + +/** + * @internal + * This function may return @c NULL. + */ +InputMethodContextEfl* EwkView::inputMethodContext() +{ + return m_inputMethodContext.get(); +} + +const char* EwkView::themePath() const +{ + return m_theme; +} + +void EwkView::setThemePath(const char* theme) +{ + if (m_theme != theme) { + m_theme = theme; + WKRetainPtr<WKStringRef> wkTheme = adoptWK(WKStringCreateWithUTF8CString(theme)); + WKViewSetThemePath(wkView(), wkTheme.get()); + } +} + +void EwkView::setCustomTextEncodingName(const char* customEncoding) +{ + if (m_customEncoding == customEncoding) + return; + + m_customEncoding = customEncoding; + WKRetainPtr<WKStringRef> wkCustomEncoding = adoptWK(WKStringCreateWithUTF8CString(customEncoding)); + WKPageSetCustomTextEncodingName(wkPage(), wkCustomEncoding.get()); +} + +void EwkView::setUserAgent(const char* userAgent) +{ + if (m_userAgent == userAgent) + return; + + WKRetainPtr<WKStringRef> wkUserAgent = adoptWK(WKStringCreateWithUTF8CString(userAgent)); + WKPageSetCustomUserAgent(wkPage(), wkUserAgent.get()); + + // When 'userAgent' is 0, user agent is set as a standard user agent by WKPageSetCustomUserAgent() + // so m_userAgent needs to be updated using WKPageCopyUserAgent(). + m_userAgent = WKEinaSharedString(AdoptWK, WKPageCopyUserAgent(wkPage())); +} + +void EwkView::setMouseEventsEnabled(bool enabled) +{ + if (m_mouseEventsEnabled == enabled) + return; + + m_mouseEventsEnabled = enabled; + if (enabled) { + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_DOWN>::subscribe(m_evasObject); + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_UP>::subscribe(m_evasObject); + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_MOVE>::subscribe(m_evasObject); + } else { + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_DOWN>::unsubscribe(m_evasObject); + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_UP>::unsubscribe(m_evasObject); + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_MOVE>::unsubscribe(m_evasObject); + } +} + +#if ENABLE(TOUCH_EVENTS) +static WKTouchPointState toWKTouchPointState(Evas_Touch_Point_State state) +{ + switch (state) { + case EVAS_TOUCH_POINT_UP: + return kWKTouchPointStateTouchReleased; + case EVAS_TOUCH_POINT_MOVE: + return kWKTouchPointStateTouchMoved; + case EVAS_TOUCH_POINT_DOWN: + return kWKTouchPointStateTouchPressed; + case EVAS_TOUCH_POINT_STILL: + return kWKTouchPointStateTouchStationary; + case EVAS_TOUCH_POINT_CANCEL: + default: + return kWKTouchPointStateTouchCancelled; + } +} + +static WKEventModifiers toWKEventModifiers(const Evas_Modifier* modifiers) +{ + WKEventModifiers wkModifiers = 0; + if (evas_key_modifier_is_set(modifiers, "Shift")) + wkModifiers |= kWKEventModifiersShiftKey; + if (evas_key_modifier_is_set(modifiers, "Control")) + wkModifiers |= kWKEventModifiersControlKey; + if (evas_key_modifier_is_set(modifiers, "Alt")) + wkModifiers |= kWKEventModifiersAltKey; + if (evas_key_modifier_is_set(modifiers, "Meta")) + wkModifiers |= kWKEventModifiersMetaKey; + + return wkModifiers; +} + +void EwkView::feedTouchEvent(Ewk_Touch_Event_Type type, const Eina_List* points, const Evas_Modifier* modifiers) +{ + unsigned length = eina_list_count(points); + OwnArrayPtr<WKTypeRef> touchPoints = adoptArrayPtr(new WKTypeRef[length]); + for (unsigned i = 0; i < length; ++i) { + Ewk_Touch_Point* point = static_cast<Ewk_Touch_Point*>(eina_list_nth(points, i)); + ASSERT(point); + IntPoint position(point->x, point->y); + touchPoints[i] = WKTouchPointCreate(point->id, toAPI(IntPoint(position)), toAPI(transformToScreen().mapPoint(position)), toWKTouchPointState(point->state), WKSizeMake(0, 0), 0, 1); + } + WKRetainPtr<WKArrayRef> wkTouchPoints(AdoptWK, WKArrayCreateAdoptingValues(touchPoints.get(), length)); + + WKViewSendTouchEvent(wkView(), adoptWK(WKTouchEventCreate(static_cast<WKEventType>(type), wkTouchPoints.get(), toWKEventModifiers(modifiers), ecore_time_get())).get()); +} + +void EwkView::setTouchEventsEnabled(bool enabled) +{ + if (m_touchEventsEnabled == enabled) + return; + + m_touchEventsEnabled = enabled; + + if (enabled) { + // FIXME: We have to connect touch callbacks with mouse and multi events + // because the Evas creates mouse events for first touch and multi events + // for second and third touches. Below codes should be fixed when the Evas + // supports the touch events. + // See https://bugs.webkit.org/show_bug.cgi?id=97785 for details. + Ewk_View_Smart_Data* sd = smartData(); + evas_object_event_callback_add(m_evasObject, EVAS_CALLBACK_MOUSE_DOWN, handleTouchDown, sd); + evas_object_event_callback_add(m_evasObject, EVAS_CALLBACK_MOUSE_UP, handleTouchUp, sd); + evas_object_event_callback_add(m_evasObject, EVAS_CALLBACK_MOUSE_MOVE, handleTouchMove, sd); + evas_object_event_callback_add(m_evasObject, EVAS_CALLBACK_MULTI_DOWN, handleTouchDown, sd); + evas_object_event_callback_add(m_evasObject, EVAS_CALLBACK_MULTI_UP, handleTouchUp, sd); + evas_object_event_callback_add(m_evasObject, EVAS_CALLBACK_MULTI_MOVE, handleTouchMove, sd); + } else { + evas_object_event_callback_del(m_evasObject, EVAS_CALLBACK_MOUSE_DOWN, handleTouchDown); + evas_object_event_callback_del(m_evasObject, EVAS_CALLBACK_MOUSE_UP, handleTouchUp); + evas_object_event_callback_del(m_evasObject, EVAS_CALLBACK_MOUSE_MOVE, handleTouchMove); + evas_object_event_callback_del(m_evasObject, EVAS_CALLBACK_MULTI_DOWN, handleTouchDown); + evas_object_event_callback_del(m_evasObject, EVAS_CALLBACK_MULTI_UP, handleTouchUp); + evas_object_event_callback_del(m_evasObject, EVAS_CALLBACK_MULTI_MOVE, handleTouchMove); + } +} + +void EwkView::doneWithTouchEvent(WKTouchEventRef, bool /* wasEventHandled */) +{ + notImplemented(); +} +#endif + +#if USE(ACCELERATED_COMPOSITING) +bool EwkView::createGLSurface() +{ + if (!m_isAccelerated) + return true; + + static Evas_GL_Config evasGLConfig = { + EVAS_GL_RGBA_8888, + EVAS_GL_DEPTH_BIT_8, + EVAS_GL_STENCIL_NONE, + EVAS_GL_OPTIONS_NONE, + EVAS_GL_MULTISAMPLE_NONE + }; + + // Recreate to current size: Replaces if non-null, and frees existing surface after (OwnPtr). + m_evasGLSurface = EvasGLSurface::create(m_evasGL.get(), &evasGLConfig, deviceSize()); + if (!m_evasGLSurface) + return false; + + Evas_Native_Surface nativeSurface; + evas_gl_native_surface_get(m_evasGL.get(), m_evasGLSurface->surface(), &nativeSurface); + evas_object_image_native_surface_set(smartData()->image, &nativeSurface); + + evas_gl_make_current(m_evasGL.get(), m_evasGLSurface->surface(), m_evasGLContext->context()); + + Evas_GL_API* gl = evas_gl_api_get(m_evasGL.get()); + + WKPoint boundsEnd = WKViewUserViewportToScene(wkView(), WKPointMake(deviceSize().width(), deviceSize().height())); + gl->glViewport(0, 0, boundsEnd.x, boundsEnd.y); + gl->glClearColor(1.0, 1.0, 1.0, 0); + gl->glClear(GL_COLOR_BUFFER_BIT); + + return true; +} +#endif + +#if ENABLE(INPUT_TYPE_COLOR) +/** + * @internal + * Requests to show external color picker. + */ +void EwkView::requestColorPicker(WKColorPickerResultListenerRef listener, const WebCore::Color& color) +{ + Ewk_View_Smart_Data* sd = smartData(); + EINA_SAFETY_ON_NULL_RETURN(sd->api->input_picker_color_request); + + if (!sd->api->input_picker_color_request) + return; + + if (m_colorPicker) + dismissColorPicker(); + + m_colorPicker = EwkColorPicker::create(listener, color); + + sd->api->input_picker_color_request(sd, m_colorPicker.get()); +} + +/** + * @internal + * Requests to hide external color picker. + */ +void EwkView::dismissColorPicker() +{ + if (!m_colorPicker) + return; + + Ewk_View_Smart_Data* sd = smartData(); + EINA_SAFETY_ON_NULL_RETURN(sd->api->input_picker_color_dismiss); + + if (sd->api->input_picker_color_dismiss) + sd->api->input_picker_color_dismiss(sd); + + m_colorPicker.clear(); +} +#endif + +COMPILE_ASSERT_MATCHING_ENUM(EWK_TEXT_DIRECTION_RIGHT_TO_LEFT, RTL); +COMPILE_ASSERT_MATCHING_ENUM(EWK_TEXT_DIRECTION_LEFT_TO_RIGHT, LTR); + +void EwkView::customContextMenuItemSelected(WKContextMenuItemRef contextMenuItem) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->custom_item_selected) + return; + + OwnPtr<EwkContextMenuItem> item = EwkContextMenuItem::create(contextMenuItem, 0); + + sd->api->custom_item_selected(sd, item.get()); +} + +void EwkView::showContextMenu(WKPoint position, WKArrayRef items) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->context_menu_show) + return; + + if (m_contextMenu) + hideContextMenu(); + + m_contextMenu = EwkContextMenu::create(this, items); + + position = WKViewContentsToUserViewport(wkView(), position); + + sd->api->context_menu_show(sd, position.x, position.y, m_contextMenu.get()); +} + +void EwkView::hideContextMenu() +{ + if (!m_contextMenu) + return; + + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (sd->api->context_menu_hide) + sd->api->context_menu_hide(sd); + + m_contextMenu.clear(); +} + +COMPILE_ASSERT_MATCHING_ENUM(EWK_TEXT_DIRECTION_RIGHT_TO_LEFT, kWKPopupItemTextDirectionRTL); +COMPILE_ASSERT_MATCHING_ENUM(EWK_TEXT_DIRECTION_LEFT_TO_RIGHT, kWKPopupItemTextDirectionLTR); + +void EwkView::requestPopupMenu(WKPopupMenuListenerRef popupMenuListener, const WKRect& rect, WKPopupItemTextDirection textDirection, double pageScaleFactor, WKArrayRef items, int32_t selectedIndex) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + ASSERT(popupMenuListener); + + if (!sd->api->popup_menu_show) + return; + + if (m_popupMenu) + closePopupMenu(); + + m_popupMenu = EwkPopupMenu::create(this, popupMenuListener, items, selectedIndex); + + WKPoint popupMenuPosition = WKViewContentsToUserViewport(wkView(), rect.origin); + + Eina_Rectangle einaRect; + EINA_RECTANGLE_SET(&einaRect, popupMenuPosition.x, popupMenuPosition.y, rect.size.width, rect.size.height); + + sd->api->popup_menu_show(sd, einaRect, static_cast<Ewk_Text_Direction>(textDirection), pageScaleFactor, m_popupMenu.get()); +} + +void EwkView::closePopupMenu() +{ + if (!m_popupMenu) + return; + + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (sd->api->popup_menu_hide) + sd->api->popup_menu_hide(sd); + + m_popupMenu.clear(); +} + +/** + * @internal + * Calls a smart member function for javascript alert(). + */ +void EwkView::requestJSAlertPopup(const WKEinaSharedString& message) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->run_javascript_alert) + return; + + sd->api->run_javascript_alert(sd, message); +} + +/** + * @internal + * Calls a smart member function for javascript confirm() and returns a value from the function. Returns false by default. + */ +bool EwkView::requestJSConfirmPopup(const WKEinaSharedString& message) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->run_javascript_confirm) + return false; + + return sd->api->run_javascript_confirm(sd, message); +} + +/** + * @internal + * Calls a smart member function for javascript prompt() and returns a value from the function. Returns null string by default. + */ +WKEinaSharedString EwkView::requestJSPromptPopup(const WKEinaSharedString& message, const WKEinaSharedString& defaultValue) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->run_javascript_prompt) + return WKEinaSharedString(); + + return WKEinaSharedString::adopt(sd->api->run_javascript_prompt(sd, message, defaultValue)); +} + +#if ENABLE(SQL_DATABASE) +/** + * @internal + * Calls exceeded_database_quota callback or falls back to default behavior returns default database quota. + */ +unsigned long long EwkView::informDatabaseQuotaReached(const String& databaseName, const String& displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + static const unsigned long long defaultQuota = 5 * 1024 * 1204; // 5 MB + if (sd->api->exceeded_database_quota) + return sd->api->exceeded_database_quota(sd, databaseName.utf8().data(), displayName.utf8().data(), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage); + + return defaultQuota; +} +#endif + +WebView* EwkView::webView() +{ + return toImpl(m_webView.get()); +} + +/** + * @internal + * The url of view was changed by the frame loader. + * + * Emits signal: "url,changed" with pointer to new url string. + */ +void EwkView::informURLChange() +{ + WKRetainPtr<WKURLRef> wkActiveURL = adoptWK(WKPageCopyActiveURL(wkPage())); + WKRetainPtr<WKStringRef> wkURLString = wkActiveURL ? adoptWK(WKURLCopyString(wkActiveURL.get())) : adoptWK(WKStringCreateWithUTF8CString("")); + + if (WKStringIsEqualToUTF8CString(wkURLString.get(), m_url)) + return; + + m_url = WKEinaSharedString(wkURLString.get()); + smartCallback<URLChanged>().call(m_url); + + // Update the view's favicon. + smartCallback<FaviconChanged>().call(); +} + +Evas_Object* EwkView::createFavicon() const +{ + EwkFaviconDatabase* iconDatabase = m_context->faviconDatabase(); + ASSERT(iconDatabase); + + return ewk_favicon_database_icon_get(iconDatabase, m_url, smartData()->base.evas); +} + +EwkWindowFeatures* EwkView::windowFeatures() +{ + if (!m_windowFeatures) + m_windowFeatures = EwkWindowFeatures::create(0, this); + + return m_windowFeatures.get(); +} + +WKPageRef EwkView::createNewPage(PassRefPtr<EwkUrlRequest> request, WKDictionaryRef windowFeatures) +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->window_create) + return 0; + + RefPtr<EwkWindowFeatures> ewkWindowFeatures = EwkWindowFeatures::create(windowFeatures, this); + + Evas_Object* newEwkView = sd->api->window_create(sd, request->url(), ewkWindowFeatures.get()); + if (!newEwkView) + return 0; + + EwkView* newViewImpl = toEwkView(newEwkView); + ASSERT(newViewImpl); + + newViewImpl->m_windowFeatures = ewkWindowFeatures; + + return static_cast<WKPageRef>(WKRetain(newViewImpl->page())); +} + +void EwkView::close() +{ + Ewk_View_Smart_Data* sd = smartData(); + ASSERT(sd->api); + + if (!sd->api->window_close) + return; + + sd->api->window_close(sd); +} + +void EwkView::handleEvasObjectAdd(Evas_Object* evasObject) +{ + const Evas_Smart* smart = evas_object_smart_smart_get(evasObject); + const Evas_Smart_Class* smartClass = evas_smart_class_get(smart); + const Ewk_View_Smart_Class* api = reinterpret_cast<const Ewk_View_Smart_Class*>(smartClass); + ASSERT(api); + + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + + if (!smartData) { + // Allocating with 'calloc' as the API contract is that it should be deleted with 'free()'. + smartData = static_cast<Ewk_View_Smart_Data*>(calloc(1, sizeof(Ewk_View_Smart_Data))); + evas_object_smart_data_set(evasObject, smartData); + } + + smartData->self = evasObject; + smartData->api = api; + + parentSmartClass.add(evasObject); + + smartData->priv = 0; // Will be initialized further. + + // Create evas_object_image to draw web contents. + smartData->image = evas_object_image_add(smartData->base.evas); + evas_object_image_alpha_set(smartData->image, false); + evas_object_image_filled_set(smartData->image, true); + evas_object_smart_member_add(smartData->image, evasObject); + evas_object_show(smartData->image); + + EwkViewEventHandler<EVAS_CALLBACK_FOCUS_IN>::subscribe(evasObject); + EwkViewEventHandler<EVAS_CALLBACK_FOCUS_OUT>::subscribe(evasObject); + EwkViewEventHandler<EVAS_CALLBACK_MOUSE_WHEEL>::subscribe(evasObject); + EwkViewEventHandler<EVAS_CALLBACK_KEY_DOWN>::subscribe(evasObject); + EwkViewEventHandler<EVAS_CALLBACK_KEY_UP>::subscribe(evasObject); + EwkViewEventHandler<EVAS_CALLBACK_SHOW>::subscribe(evasObject); + EwkViewEventHandler<EVAS_CALLBACK_HIDE>::subscribe(evasObject); +} + +void EwkView::handleEvasObjectDelete(Evas_Object* evasObject) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + if (smartData) { + ASSERT(smartData->priv); // smartData->priv is EwkView instance. + delete smartData->priv; + } + + parentSmartClass.del(evasObject); +} + +void EwkView::handleEvasObjectResize(Evas_Object* evasObject, Evas_Coord width, Evas_Coord height) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + ASSERT(smartData); + + evas_object_resize(smartData->image, width, height); + evas_object_image_size_set(smartData->image, width, height); + evas_object_image_fill_set(smartData->image, 0, 0, width, height); + + smartData->changed.size = true; + smartDataChanged(smartData); +} + +void EwkView::handleEvasObjectMove(Evas_Object* evasObject, Evas_Coord /*x*/, Evas_Coord /*y*/) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + ASSERT(smartData); + + smartData->changed.position = true; + smartDataChanged(smartData); +} + +void EwkView::handleEvasObjectCalculate(Evas_Object* evasObject) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + ASSERT(smartData); + + EwkView* self = toEwkView(smartData); + + smartData->changed.any = false; + + Evas_Coord x, y, width, height; + evas_object_geometry_get(evasObject, &x, &y, &width, &height); + + if (smartData->changed.position) { + smartData->changed.position = false; + smartData->view.x = x; + smartData->view.y = y; + evas_object_move(smartData->image, x, y); + WKViewSetUserViewportTranslation(self->wkView(), x, y); + } + + if (smartData->changed.size) { + smartData->changed.size = false; + smartData->view.w = width; + smartData->view.h = height; + + WKViewSetSize(self->wkView(), WKSizeMake(width, height)); +#if USE(ACCELERATED_COMPOSITING) + if (WKPageUseFixedLayout(self->wkPage())) + self->pageViewportController()->didChangeViewportSize(self->size()); + + self->setNeedsSurfaceResize(); +#endif + } +} + +void EwkView::handleEvasObjectShow(Evas_Object* evasObject) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + ASSERT(smartData); + + if (!toEwkView(smartData)->m_isAccelerated) + showEvasObjectsIfNeeded(smartData); +} + +void EwkView::handleEvasObjectHide(Evas_Object* evasObject) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + ASSERT(smartData); + + evas_object_hide(smartData->base.clipper); + evas_object_hide(smartData->image); +} + +void EwkView::handleEvasObjectColorSet(Evas_Object* evasObject, int red, int green, int blue, int alpha) +{ + Ewk_View_Smart_Data* smartData = toSmartData(evasObject); + ASSERT(smartData); + + EwkView* view = toEwkView(smartData); + ASSERT(view); + + alpha = clampTo(alpha, 0, 255); + red = clampTo(red, 0, alpha); + green = clampTo(green, 0, alpha); + blue = clampTo(blue, 0, alpha); + + evas_object_image_alpha_set(smartData->image, alpha < 255); + WKViewSetDrawsBackground(view->wkView(), red || green || blue); + WKViewSetDrawsTransparentBackground(view->wkView(), alpha < 255); + + parentSmartClass.color_set(evasObject, red, green, blue, alpha); +} + +Eina_Bool EwkView::handleEwkViewFocusIn(Ewk_View_Smart_Data* smartData) +{ + WKViewSetIsFocused(toEwkView(smartData)->wkView(), true); + return true; +} + +Eina_Bool EwkView::handleEwkViewFocusOut(Ewk_View_Smart_Data* smartData) +{ + WKViewSetIsFocused(toEwkView(smartData)->wkView(), false); + return true; +} + +Eina_Bool EwkView::handleEwkViewMouseWheel(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Wheel* wheelEvent) +{ + EwkView* self = toEwkView(smartData); + self->page()->handleWheelEvent(NativeWebWheelEvent(wheelEvent, self->webView()->transformFromScene(), self->transformToScreen())); + return true; +} + +Eina_Bool EwkView::handleEwkViewMouseDown(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Down* downEvent) +{ + EwkView* self = toEwkView(smartData); + self->page()->handleMouseEvent(NativeWebMouseEvent(downEvent, self->webView()->transformFromScene(), self->transformToScreen())); + return true; +} + +Eina_Bool EwkView::handleEwkViewMouseUp(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Up* upEvent) +{ + EwkView* self = toEwkView(smartData); + self->page()->handleMouseEvent(NativeWebMouseEvent(upEvent, self->webView()->transformFromScene(), self->transformToScreen())); + + if (InputMethodContextEfl* inputMethodContext = self->inputMethodContext()) + inputMethodContext->handleMouseUpEvent(upEvent); + + return true; +} + +Eina_Bool EwkView::handleEwkViewMouseMove(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Move* moveEvent) +{ + EwkView* self = toEwkView(smartData); + self->page()->handleMouseEvent(NativeWebMouseEvent(moveEvent, self->webView()->transformFromScene(), self->transformToScreen())); + return true; +} + +Eina_Bool EwkView::handleEwkViewKeyDown(Ewk_View_Smart_Data* smartData, const Evas_Event_Key_Down* downEvent) +{ + bool isFiltered = false; + EwkView* self = toEwkView(smartData); + if (InputMethodContextEfl* inputMethodContext = self->inputMethodContext()) + inputMethodContext->handleKeyDownEvent(downEvent, &isFiltered); + + self->page()->handleKeyboardEvent(NativeWebKeyboardEvent(downEvent, isFiltered)); + return true; +} + +Eina_Bool EwkView::handleEwkViewKeyUp(Ewk_View_Smart_Data* smartData, const Evas_Event_Key_Up* upEvent) +{ + toEwkView(smartData)->page()->handleKeyboardEvent(NativeWebKeyboardEvent(upEvent)); + return true; +} + +#if ENABLE(TOUCH_EVENTS) +void EwkView::feedTouchEvents(Ewk_Touch_Event_Type type) +{ + Ewk_View_Smart_Data* sd = smartData(); + + unsigned length = evas_touch_point_list_count(sd->base.evas); + if (!length) + return; + + OwnArrayPtr<WKTypeRef> touchPoints = adoptArrayPtr(new WKTypeRef[length]); + for (unsigned i = 0; i < length; ++i) { + int x, y; + evas_touch_point_list_nth_xy_get(sd->base.evas, i, &x, &y); + IntPoint position(x, y); + Evas_Touch_Point_State state = evas_touch_point_list_nth_state_get(sd->base.evas, i); + int id = evas_touch_point_list_nth_id_get(sd->base.evas, i); + touchPoints[i] = WKTouchPointCreate(id, toAPI(IntPoint(position)), toAPI(transformToScreen().mapPoint(position)), toWKTouchPointState(state), WKSizeMake(0, 0), 0, 1); + } + WKRetainPtr<WKArrayRef> wkTouchPoints(AdoptWK, WKArrayCreateAdoptingValues(touchPoints.get(), length)); + + WKViewSendTouchEvent(wkView(), adoptWK(WKTouchEventCreate(static_cast<WKEventType>(type), wkTouchPoints.get(), toWKEventModifiers(evas_key_modifier_get(sd->base.evas)), ecore_time_get())).get()); +} + +void EwkView::handleTouchDown(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */) +{ + toEwkView(ewkView)->feedTouchEvents(EWK_TOUCH_START); +} + +void EwkView::handleTouchUp(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */) +{ + toEwkView(ewkView)->feedTouchEvents(EWK_TOUCH_END); +} + +void EwkView::handleTouchMove(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */) +{ + toEwkView(ewkView)->feedTouchEvents(EWK_TOUCH_MOVE); +} +#endif + +void EwkView::handleFaviconChanged(const char* pageURL, void* eventInfo) +{ + EwkView* view = static_cast<EwkView*>(eventInfo); + + if (!view->url() || strcasecmp(view->url(), pageURL)) + return; + + view->smartCallback<FaviconChanged>().call(); +} + +PassRefPtr<cairo_surface_t> EwkView::takeSnapshot() +{ + // Suspend all animations before taking the snapshot. + WKViewSuspendActiveDOMObjectsAndAnimations(wkView()); + + // Wait for the pending repaint events to be processed. + while (m_displayTimer.isActive()) + ecore_main_loop_iterate(); + + Ewk_View_Smart_Data* sd = smartData(); +#if USE(ACCELERATED_COMPOSITING) + if (m_isAccelerated) { + RefPtr<cairo_surface_t> snapshot = getImageSurfaceFromFrameBuffer(0, 0, sd->view.w, sd->view.h); + // Resume all animations. + WKViewResumeActiveDOMObjectsAndAnimations(wkView()); + + return snapshot.release(); + } +#endif + RefPtr<cairo_surface_t> snapshot = createSurfaceForImage(sd->image); + // Resume all animations. + WKViewResumeActiveDOMObjectsAndAnimations(wkView()); + + return snapshot.release(); +} + +void EwkView::didFindZoomableArea(const WKPoint& point, const WKRect& area) +{ + notImplemented(); +} + +Evas_Smart_Class EwkView::parentSmartClass = EVAS_SMART_CLASS_INIT_NULL; + +// Free Ewk View functions. + +EwkView* toEwkView(const Evas_Object* evasObject) +{ + ASSERT(evasObject); + ASSERT(isEwkViewEvasObject(evasObject)); + + return toEwkView(static_cast<Ewk_View_Smart_Data*>(evas_object_smart_data_get(evasObject))); +} + +bool isEwkViewEvasObject(const Evas_Object* evasObject) +{ + ASSERT(evasObject); + + const char* evasObjectType = evas_object_type_get(evasObject); + const Evas_Smart* evasSmart = evas_object_smart_smart_get(evasObject); + if (!evasSmart) { + EINA_LOG_CRIT("%p (%s) is not a smart object!", evasObject, evasObjectType ? evasObjectType : "(null)"); + return false; + } + + const Evas_Smart_Class* smartClass = evas_smart_class_get(evasSmart); + if (!smartClass) { + EINA_LOG_CRIT("%p (%s) is not a smart class object!", evasObject, evasObjectType ? evasObjectType : "(null)"); + return false; + } + + if (smartClass->data != smartClassName) { + EINA_LOG_CRIT("%p (%s) is not of an ewk_view (need %p, got %p)!", evasObject, evasObjectType ? evasObjectType : "(null)", + smartClassName, smartClass->data); + return false; + } + + return true; +} diff --git a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.h b/Source/WebKit2/UIProcess/API/efl/EwkView.h index bb93fedb1..a9f011716 100644 --- a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.h +++ b/Source/WebKit2/UIProcess/API/efl/EwkView.h @@ -18,18 +18,22 @@ Boston, MA 02110-1301, USA. */ -#ifndef EwkViewImpl_h -#define EwkViewImpl_h +#ifndef EwkView_h +#define EwkView_h +#include "EvasGLContext.h" +#include "EvasGLSurface.h" #include "EwkViewCallbacks.h" #include "ImmutableDictionary.h" #include "RefPtrEfl.h" #include "WKEinaSharedString.h" -#include "WKGeometry.h" #include "WKRetainPtr.h" +#include "WebViewEfl.h" +#include "ewk_url_request_private.h" #include <Evas.h> #include <WebCore/FloatPoint.h> #include <WebCore/IntRect.h> +#include <WebCore/RefPtrCairo.h> #include <WebCore/TextDirection.h> #include <WebCore/Timer.h> #include <WebKit2/WKBase.h> @@ -42,48 +46,47 @@ #include "ewk_touch.h" #endif -#if USE(ACCELERATED_COMPOSITING) -#include "EvasGLContext.h" -#include "EvasGLSurface.h" -#endif +#include "WebContext.h" +#include "WebPageGroup.h" +#include "WebPreferences.h" + +typedef struct _cairo_surface cairo_surface_t; namespace WebKit { class ContextMenuClientEfl; class FindClientEfl; class FormClientEfl; class InputMethodContextEfl; -class PageClientBase; class PageLoadClientEfl; class PagePolicyClientEfl; class PageUIClientEfl; -class ResourceLoadClientEfl; -class WebContextMenuItemData; -class WebContextMenuProxyEfl; +class ViewClientEfl; +#if USE(ACCELERATED_COMPOSITING) +class PageViewportController; +class PageViewportControllerClientEfl; +#endif class WebPageGroup; class WebPageProxy; -class WebPopupItem; -class WebPopupMenuProxyEfl; #if ENABLE(VIBRATION) class VibrationClientEfl; #endif - -#if USE(COORDINATED_GRAPHICS) -class LayerTreeRenderer; -#endif } namespace WebCore { class AffineTransform; class Color; +class CoordinatedGraphicsScene; class Cursor; class IntSize; +class TransformationMatrix; } class EwkContext; class EwkBackForwardList; class EwkColorPicker; class EwkContextMenu; +class EwkPageGroup; class EwkPopupMenu; class EwkSettings; class EwkWindowFeatures; @@ -94,60 +97,61 @@ typedef struct _Evas_GL_Surface Evas_GL_Surface; #endif typedef struct Ewk_View_Smart_Data Ewk_View_Smart_Data; +typedef struct Ewk_View_Smart_Class Ewk_View_Smart_Class; -class EwkViewImpl { +class EwkView { public: + static EwkView* create(WKViewRef, Evas* canvas, Evas_Smart* smart = 0); + + static bool initSmartClassInterface(Ewk_View_Smart_Class&); + + static Evas_Object* toEvasObject(WKPageRef); - enum ViewBehavior { - LegacyBehavior, - DefaultBehavior - }; - EwkViewImpl(Evas_Object* view, PassRefPtr<EwkContext> context, PassRefPtr<WebKit::WebPageGroup> pageGroup, ViewBehavior); - ~EwkViewImpl(); + Evas_Object* evasObject() { return m_evasObject; } - static EwkViewImpl* fromEvasObject(const Evas_Object* view); + WKViewRef wkView() const { return m_webView.get(); } + WKPageRef wkPage() const; - Evas_Object* view() { return m_view; } - WKPageRef wkPage(); - WebKit::WebPageProxy* page() { return m_pageProxy.get(); } + WebKit::WebPageProxy* page() { return webView()->page(); } EwkContext* ewkContext() { return m_context.get(); } + EwkPageGroup* ewkPageGroup() { return m_pageGroup.get(); } EwkSettings* settings() { return m_settings.get(); } EwkBackForwardList* backForwardList() { return m_backForwardList.get(); } EwkWindowFeatures* windowFeatures(); - WebCore::IntSize size() const; - bool isFocused() const; - bool isVisible() const; +#if USE(ACCELERATED_COMPOSITING) + WebKit::PageViewportController* pageViewportController() { return m_pageViewportController.get(); } +#endif + + void setDeviceScaleFactor(float scale); + float deviceScaleFactor() const; - WebCore::AffineTransform transformToScene() const; - WebCore::AffineTransform transformFromScene() const; WebCore::AffineTransform transformToScreen() const; const char* url() const { return m_url; } - const char* faviconURL() const { return m_faviconURL; } + Evas_Object* createFavicon() const; const char* title() const; WebKit::InputMethodContextEfl* inputMethodContext(); const char* themePath() const; void setThemePath(const char* theme); - const char* customTextEncodingName() const; - void setCustomTextEncodingName(const String& encoding); + const char* customTextEncodingName() const { return m_customEncoding; } + void setCustomTextEncodingName(const char* customEncoding); + const char* userAgent() const { return m_userAgent; } + void setUserAgent(const char* userAgent); bool mouseEventsEnabled() const { return m_mouseEventsEnabled; } void setMouseEventsEnabled(bool enabled); #if ENABLE(TOUCH_EVENTS) + void feedTouchEvent(Ewk_Touch_Event_Type type, const Eina_List* points, const Evas_Modifier* modifiers); bool touchEventsEnabled() const { return m_touchEventsEnabled; } void setTouchEventsEnabled(bool enabled); + void doneWithTouchEvent(WKTouchEventRef, bool); #endif void setCursor(const WebCore::Cursor& cursor); - void setImageData(void* imageData, const WebCore::IntSize& size); - void update(const WebCore::IntRect& rect = WebCore::IntRect()); - - static void addToPageViewMap(EwkViewImpl* viewImpl); - static void removeFromPageViewMap(EwkViewImpl* viewImpl); - static const Evas_Object* viewFromPageViewMap(const WKPageRef); + void scheduleUpdateDisplay(); #if ENABLE(FULLSCREEN_API) void enterFullScreen(); @@ -156,11 +160,8 @@ public: WKRect windowGeometry() const; void setWindowGeometry(const WKRect&); - #if USE(ACCELERATED_COMPOSITING) - bool createGLSurface(const WebCore::IntSize& viewSize); - bool enterAcceleratedCompositingMode(); - bool exitAcceleratedCompositingMode(); + bool createGLSurface(); void setNeedsSurfaceResize() { m_pendingSurfaceResize = true; } #endif @@ -169,13 +170,14 @@ public: void dismissColorPicker(); #endif - WKPageRef createNewPage(WebKit::ImmutableDictionary* windowFeatures); - void closePage(); + WKPageRef createNewPage(PassRefPtr<EwkUrlRequest>, WKDictionaryRef windowFeatures); + void close(); - void requestPopupMenu(WebKit::WebPopupMenuProxyEfl*, const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebKit::WebPopupItem>& items, int32_t selectedIndex); + void requestPopupMenu(WKPopupMenuListenerRef, const WKRect&, WKPopupItemTextDirection, double pageScaleFactor, WKArrayRef items, int32_t selectedIndex); void closePopupMenu(); - - void showContextMenu(WebKit::WebContextMenuProxyEfl*, const WebCore::IntPoint& position, const Vector<WebKit::WebContextMenuItemData>& items); + + void customContextMenuItemSelected(WKContextMenuItemRef contextMenuItem); + void showContextMenu(WKPoint position, WKArrayRef items); void hideContextMenu(); void updateTextInputState(); @@ -187,104 +189,115 @@ public: template<EwkViewCallbacks::CallbackType callbackType> EwkViewCallbacks::CallBack<callbackType> smartCallback() const { - return EwkViewCallbacks::CallBack<callbackType>(m_view); + return EwkViewCallbacks::CallBack<callbackType>(m_evasObject); } -#if USE(TILED_BACKING_STORE) - void informLoadCommitted(); -#endif - void informContentsSizeChange(const WebCore::IntSize& size); unsigned long long informDatabaseQuotaReached(const String& databaseName, const String& displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage); -#if USE(TILED_BACKING_STORE) - WebKit::PageClientBase* pageClient() { return m_pageClient.get(); } - - void setScaleFactor(float scaleFactor) { m_scaleFactor = scaleFactor; } - float scaleFactor() const { return m_scaleFactor; } - - void setPagePosition(const WebCore::FloatPoint& position) { m_pagePosition = position; } - const WebCore::IntPoint discretePagePosition() const { return roundedIntPoint(m_pagePosition); } -#endif + // FIXME: Remove when possible. + WebKit::WebView* webView(); // FIXME: needs refactoring (split callback invoke) void informURLChange(); - bool isHardwareAccelerated() const { return m_isHardwareAccelerated; } - void setDrawsBackground(bool enable) { m_setDrawsBackground = enable; } + PassRefPtr<cairo_surface_t> takeSnapshot(); - WKImageRef takeSnapshot(); + void didFindZoomableArea(const WKPoint&, const WKRect&); private: -#if USE(ACCELERATED_COMPOSITING) - Evas_GL_Context* evasGLContext() { return m_evasGLContext ? m_evasGLContext->context() : 0; } - Evas_GL_Surface* evasGLSurface() { return m_evasGLSurface ? m_evasGLSurface->surface() : 0; } -#endif + EwkView(WKViewRef, Evas_Object*); + ~EwkView(); - inline Ewk_View_Smart_Data* smartData() const; - void displayTimerFired(WebCore::Timer<EwkViewImpl>*); + void setDeviceSize(const WebCore::IntSize&); + Ewk_View_Smart_Data* smartData() const; -#if USE(COORDINATED_GRAPHICS) - WebKit::LayerTreeRenderer* layerTreeRenderer(); -#endif - - void informIconChange(); + WebCore::IntSize size() const; + WebCore::IntSize deviceSize() const; + + void displayTimerFired(WebCore::Timer<EwkView>*); + + // Evas_Smart_Class callback interface: + static void handleEvasObjectAdd(Evas_Object*); + static void handleEvasObjectDelete(Evas_Object*); + static void handleEvasObjectMove(Evas_Object*, Evas_Coord x, Evas_Coord y); + static void handleEvasObjectResize(Evas_Object*, Evas_Coord width, Evas_Coord height); + static void handleEvasObjectShow(Evas_Object*); + static void handleEvasObjectHide(Evas_Object*); + static void handleEvasObjectColorSet(Evas_Object*, int red, int green, int blue, int alpha); + static void handleEvasObjectCalculate(Evas_Object*); + + // Ewk_View_Smart_Class callback interface: + static Eina_Bool handleEwkViewFocusIn(Ewk_View_Smart_Data* smartData); + static Eina_Bool handleEwkViewFocusOut(Ewk_View_Smart_Data* smartData); + static Eina_Bool handleEwkViewMouseWheel(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Wheel* wheelEvent); + static Eina_Bool handleEwkViewMouseDown(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Down* downEvent); + static Eina_Bool handleEwkViewMouseUp(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Up* upEvent); + static Eina_Bool handleEwkViewMouseMove(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Move* moveEvent); + static Eina_Bool handleEwkViewKeyDown(Ewk_View_Smart_Data* smartData, const Evas_Event_Key_Down* downEvent); + static Eina_Bool handleEwkViewKeyUp(Ewk_View_Smart_Data* smartData, const Evas_Event_Key_Up* upEvent); - static void onMouseDown(void* data, Evas*, Evas_Object*, void* eventInfo); - static void onMouseUp(void* data, Evas*, Evas_Object*, void* eventInfo); - static void onMouseMove(void* data, Evas*, Evas_Object*, void* eventInfo); #if ENABLE(TOUCH_EVENTS) void feedTouchEvents(Ewk_Touch_Event_Type type); - static void onTouchDown(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */); - static void onTouchUp(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */); - static void onTouchMove(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */); + static void handleTouchDown(void* data, Evas*, Evas_Object*, void* eventInfo); + static void handleTouchUp(void* data, Evas*, Evas_Object*, void* eventInfo); + static void handleTouchMove(void* data, Evas*, Evas_Object*, void* eventInfo); #endif - static void onFaviconChanged(const char* pageURL, void* eventInfo); + static void handleFaviconChanged(const char* pageURL, void* eventInfo); +private: // Note, initialization order matters. - Evas_Object* m_view; + WKRetainPtr<WKViewRef> m_webView; + Evas_Object* m_evasObject; RefPtr<EwkContext> m_context; + RefPtr<EwkPageGroup> m_pageGroup; #if USE(ACCELERATED_COMPOSITING) OwnPtr<Evas_GL> m_evasGL; OwnPtr<WebKit::EvasGLContext> m_evasGLContext; OwnPtr<WebKit::EvasGLSurface> m_evasGLSurface; bool m_pendingSurfaceResize; #endif - OwnPtr<WebKit::PageClientBase> m_pageClient; - RefPtr<WebKit::WebPageProxy> m_pageProxy; + WebCore::TransformationMatrix m_userViewportTransform; OwnPtr<WebKit::PageLoadClientEfl> m_pageLoadClient; OwnPtr<WebKit::PagePolicyClientEfl> m_pagePolicyClient; OwnPtr<WebKit::PageUIClientEfl> m_pageUIClient; - OwnPtr<WebKit::ResourceLoadClientEfl> m_resourceLoadClient; OwnPtr<WebKit::ContextMenuClientEfl> m_contextMenuClient; OwnPtr<WebKit::FindClientEfl> m_findClient; OwnPtr<WebKit::FormClientEfl> m_formClient; + OwnPtr<WebKit::ViewClientEfl> m_viewClient; #if ENABLE(VIBRATION) OwnPtr<WebKit::VibrationClientEfl> m_vibrationClient; #endif OwnPtr<EwkBackForwardList> m_backForwardList; -#if USE(TILED_BACKING_STORE) - float m_scaleFactor; - WebCore::FloatPoint m_pagePosition; -#endif OwnPtr<EwkSettings> m_settings; RefPtr<EwkWindowFeatures> m_windowFeatures; const void* m_cursorIdentifier; // This is an address, do not free it. - WKEinaSharedString m_faviconURL; WKEinaSharedString m_url; mutable WKEinaSharedString m_title; WKEinaSharedString m_theme; - mutable WKEinaSharedString m_customEncoding; + WKEinaSharedString m_customEncoding; + WKEinaSharedString m_userAgent; bool m_mouseEventsEnabled; #if ENABLE(TOUCH_EVENTS) bool m_touchEventsEnabled; #endif - WebCore::Timer<EwkViewImpl> m_displayTimer; - OwnPtr<EwkContextMenu> m_contextMenu; + WebCore::Timer<EwkView> m_displayTimer; + RefPtr<EwkContextMenu> m_contextMenu; OwnPtr<EwkPopupMenu> m_popupMenu; OwnPtr<WebKit::InputMethodContextEfl> m_inputMethodContext; +#if ENABLE(INPUT_TYPE_COLOR) OwnPtr<EwkColorPicker> m_colorPicker; - bool m_isHardwareAccelerated; - bool m_setDrawsBackground; +#endif +#if USE(ACCELERATED_COMPOSITING) + OwnPtr<WebKit::PageViewportControllerClientEfl> m_pageViewportControllerClient; + OwnPtr<WebKit::PageViewportController> m_pageViewportController; +#endif + bool m_isAccelerated; + + static Evas_Smart_Class parentSmartClass; }; -#endif // EwkViewImpl_h +EwkView* toEwkView(const Evas_Object*); + +bool isEwkViewEvasObject(const Evas_Object*); + +#endif // EwkView_h diff --git a/Source/WebKit2/UIProcess/API/efl/EwkViewCallbacks.h b/Source/WebKit2/UIProcess/API/efl/EwkViewCallbacks.h index cf822a2ed..78c304d3f 100644 --- a/Source/WebKit2/UIProcess/API/efl/EwkViewCallbacks.h +++ b/Source/WebKit2/UIProcess/API/efl/EwkViewCallbacks.h @@ -28,7 +28,9 @@ #include "WKEinaSharedString.h" #include "ewk_private.h" +#include "ewk_view.h" #include <Evas.h> +#include <WebKit2/WKGeometry.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> @@ -37,33 +39,22 @@ typedef struct EwkObject Ewk_Download_Job; typedef struct EwkObject Ewk_File_Chooser_Request; typedef struct EwkObject Ewk_Form_Submission_Request; typedef struct EwkObject Ewk_Navigation_Policy_Decision; -typedef struct EwkObject Ewk_Resource; -#if ENABLE(WEB_INTENTS) -typedef struct EwkObject Ewk_Intent; -#endif -#if ENABLE(WEB_INTENTS_TAG) -typedef struct EwkObject Ewk_Intent_Service; -#endif typedef struct EwkError Ewk_Error; -struct Ewk_Download_Job_Error; -struct Ewk_Resource_Request; -struct Ewk_Resource_Load_Response; -struct Ewk_Resource_Load_Error; - namespace EwkViewCallbacks { enum CallbackType { AuthenticationRequest, BackForwardListChange, CancelVibration, + ContentsSizeChanged, DownloadJobCancelled, DownloadJobFailed, DownloadJobFinished, DownloadJobRequested, FileChooserRequest, NewFormSubmissionRequest, - IconChanged, + FaviconChanged, LoadError, LoadFinished, LoadProgress, @@ -71,11 +62,6 @@ enum CallbackType { ProvisionalLoadFailed, ProvisionalLoadRedirect, ProvisionalLoadStarted, - ResourceLoadStarted, - ResourceLoadResponse, - ResourceLoadFailed, - ResourceLoadFinished, - ResourceRequestSent, StatusBarVisible, NavigationPolicyDecision, NewWindowPolicyDecision, @@ -87,13 +73,7 @@ enum CallbackType { URLChanged, Vibrate, WebProcessCrashed, - WindowResizable, -#if ENABLE(WEB_INTENTS) - IntentRequest, -#endif -#if ENABLE(WEB_INTENTS_TAG) - IntentServiceRegistration, -#endif + WindowResizable }; template <CallbackType> @@ -150,6 +130,22 @@ struct CallBack <callbackType, const char*> : public EvasObjectHolder { } }; +template <CallbackType callbackType> +struct CallBack <callbackType, Ewk_CSS_Size*> : public EvasObjectHolder { + explicit CallBack(Evas_Object* view) : EvasObjectHolder(view) { } + + void call(Ewk_CSS_Size* size) + { + evas_object_smart_callback_call(m_object, CallBackInfo<callbackType>::name(), size); + } + + void call(const WKSize& arg) + { + Ewk_CSS_Size size = { static_cast<Evas_Coord>(arg.width), static_cast<Evas_Coord>(arg.height) }; + call(&size); + } +}; + #define DECLARE_EWK_VIEW_CALLBACK(callbackType, string, type) \ template <> \ struct CallBackInfo<callbackType> { \ @@ -161,13 +157,14 @@ struct CallBackInfo<callbackType> { \ DECLARE_EWK_VIEW_CALLBACK(AuthenticationRequest, "authentication,request", Ewk_Auth_Request*); DECLARE_EWK_VIEW_CALLBACK(BackForwardListChange, "back,forward,list,changed", void); DECLARE_EWK_VIEW_CALLBACK(CancelVibration, "cancel,vibration", void); +DECLARE_EWK_VIEW_CALLBACK(ContentsSizeChanged, "contents,size,changed", Ewk_CSS_Size*); DECLARE_EWK_VIEW_CALLBACK(DownloadJobCancelled, "download,cancelled", Ewk_Download_Job*); DECLARE_EWK_VIEW_CALLBACK(DownloadJobFailed, "download,failed", Ewk_Download_Job_Error*); DECLARE_EWK_VIEW_CALLBACK(DownloadJobFinished, "download,finished", Ewk_Download_Job*); DECLARE_EWK_VIEW_CALLBACK(DownloadJobRequested, "download,request", Ewk_Download_Job*); DECLARE_EWK_VIEW_CALLBACK(FileChooserRequest, "file,chooser,request", Ewk_File_Chooser_Request*); DECLARE_EWK_VIEW_CALLBACK(NewFormSubmissionRequest, "form,submission,request", Ewk_Form_Submission_Request*); -DECLARE_EWK_VIEW_CALLBACK(IconChanged, "icon,changed", void); +DECLARE_EWK_VIEW_CALLBACK(FaviconChanged, "favicon,changed", void); DECLARE_EWK_VIEW_CALLBACK(LoadError, "load,error", Ewk_Error*); DECLARE_EWK_VIEW_CALLBACK(LoadFinished, "load,finished", void); DECLARE_EWK_VIEW_CALLBACK(LoadProgress, "load,progress", double*); @@ -177,11 +174,6 @@ DECLARE_EWK_VIEW_CALLBACK(ProvisionalLoadStarted, "load,provisional,started", vo DECLARE_EWK_VIEW_CALLBACK(MenuBarVisible, "menubar,visible", bool*); DECLARE_EWK_VIEW_CALLBACK(NavigationPolicyDecision, "policy,decision,navigation", Ewk_Navigation_Policy_Decision*); DECLARE_EWK_VIEW_CALLBACK(NewWindowPolicyDecision, "policy,decision,new,window", Ewk_Navigation_Policy_Decision*); -DECLARE_EWK_VIEW_CALLBACK(ResourceLoadStarted, "resource,request,new", Ewk_Resource_Request*); -DECLARE_EWK_VIEW_CALLBACK(ResourceLoadResponse, "resource,request,response", Ewk_Resource_Load_Response*); -DECLARE_EWK_VIEW_CALLBACK(ResourceLoadFailed, "resource,request,failed", Ewk_Resource_Load_Error*); -DECLARE_EWK_VIEW_CALLBACK(ResourceLoadFinished, "resource,request,finished", Ewk_Resource*); -DECLARE_EWK_VIEW_CALLBACK(ResourceRequestSent, "resource,request,sent", Ewk_Resource_Request*); DECLARE_EWK_VIEW_CALLBACK(StatusBarVisible, "statusbar,visible", bool*); DECLARE_EWK_VIEW_CALLBACK(TextFound, "text,found", unsigned*); DECLARE_EWK_VIEW_CALLBACK(TitleChange, "title,changed", const char*); @@ -189,15 +181,9 @@ DECLARE_EWK_VIEW_CALLBACK(ToolbarVisible, "toolbar,visible", bool*); DECLARE_EWK_VIEW_CALLBACK(TooltipTextUnset, "tooltip,text,unset", void); DECLARE_EWK_VIEW_CALLBACK(TooltipTextSet, "tooltip,text,set", const char*); DECLARE_EWK_VIEW_CALLBACK(URLChanged, "url,changed", const char*); -DECLARE_EWK_VIEW_CALLBACK(Vibrate, "vibrate", uint64_t*); +DECLARE_EWK_VIEW_CALLBACK(Vibrate, "vibrate", uint32_t*); DECLARE_EWK_VIEW_CALLBACK(WebProcessCrashed, "webprocess,crashed", bool*); DECLARE_EWK_VIEW_CALLBACK(WindowResizable, "window,resizable", bool*); -#if ENABLE(WEB_INTENTS) -DECLARE_EWK_VIEW_CALLBACK(IntentRequest, "intent,request,new", Ewk_Intent*); -#endif -#if ENABLE(WEB_INTENTS_TAG) -DECLARE_EWK_VIEW_CALLBACK(IntentServiceRegistration, "intent,service,register", Ewk_Intent_Service*); -#endif } diff --git a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp b/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp deleted file mode 100644 index 2f2629ce0..000000000 --- a/Source/WebKit2/UIProcess/API/efl/EwkViewImpl.cpp +++ /dev/null @@ -1,1046 +0,0 @@ -/* - Copyright (C) 2011 Samsung Electronics - Copyright (C) 2012 Intel Corporation. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" -#include "EwkViewImpl.h" - -#include "ContextMenuClientEfl.h" -#include "EflScreenUtilities.h" -#include "FindClientEfl.h" -#include "FormClientEfl.h" -#include "InputMethodContextEfl.h" -#include "LayerTreeCoordinatorProxy.h" -#include "LayerTreeRenderer.h" -#include "PageClientBase.h" -#include "PageClientDefaultImpl.h" -#include "PageClientLegacyImpl.h" -#include "PageLoadClientEfl.h" -#include "PagePolicyClientEfl.h" -#include "PageUIClientEfl.h" -#include "ResourceLoadClientEfl.h" -#include "SnapshotImageGL.h" -#include "WKDictionary.h" -#include "WKGeometry.h" -#include "WKNumber.h" -#include "WKString.h" -#include "WebContext.h" -#include "WebImage.h" -#include "WebPageGroup.h" -#include "WebPageProxy.h" -#include "WebPopupMenuProxyEfl.h" -#include "WebPreferences.h" -#include "ewk_back_forward_list_private.h" -#include "ewk_color_picker_private.h" -#include "ewk_context_menu_private.h" -#include "ewk_context_private.h" -#include "ewk_favicon_database_private.h" -#include "ewk_popup_menu_item_private.h" -#include "ewk_popup_menu_private.h" -#include "ewk_private.h" -#include "ewk_security_origin_private.h" -#include "ewk_settings_private.h" -#include "ewk_view.h" -#include "ewk_view_private.h" -#include "ewk_window_features_private.h" -#include <Ecore_Evas.h> -#include <Ecore_X.h> -#include <Edje.h> -#include <WebCore/CairoUtilitiesEfl.h> -#include <WebCore/Cursor.h> -#include <WebKit2/WKImageCairo.h> - -#if ENABLE(VIBRATION) -#include "VibrationClientEfl.h" -#endif - -#if ENABLE(FULLSCREEN_API) -#include "WebFullScreenManagerProxy.h" -#endif - -#if USE(ACCELERATED_COMPOSITING) -#include <Evas_GL.h> -#endif - -using namespace EwkViewCallbacks; -using namespace WebCore; -using namespace WebKit; - -static const int defaultCursorSize = 16; - -typedef HashMap<WKPageRef, Evas_Object*> PageViewMap; - -static inline PageViewMap& pageViewMap() -{ - DEFINE_STATIC_LOCAL(PageViewMap, map, ()); - return map; -} - -void EwkViewImpl::addToPageViewMap(EwkViewImpl* viewImpl) -{ - PageViewMap::AddResult result = pageViewMap().add(viewImpl->wkPage(), viewImpl->view()); - ASSERT_UNUSED(result, result.isNewEntry); -} - -void EwkViewImpl::removeFromPageViewMap(EwkViewImpl* viewImpl) -{ - ASSERT(pageViewMap().contains(viewImpl->wkPage())); - pageViewMap().remove(viewImpl->wkPage()); -} - -const Evas_Object* EwkViewImpl::viewFromPageViewMap(const WKPageRef page) -{ - ASSERT(page); - - return pageViewMap().get(page); -} - -EwkViewImpl::EwkViewImpl(Evas_Object* view, PassRefPtr<EwkContext> context, PassRefPtr<WebPageGroup> pageGroup, ViewBehavior behavior) - : m_view(view) - , m_context(context) -#if USE(ACCELERATED_COMPOSITING) - , m_pendingSurfaceResize(false) -#endif - , m_pageClient(behavior == DefaultBehavior ? PageClientDefaultImpl::create(this) : PageClientLegacyImpl::create(this)) - , m_pageProxy(m_context->webContext()->createWebPage(m_pageClient.get(), pageGroup.get())) - , m_pageLoadClient(PageLoadClientEfl::create(this)) - , m_pagePolicyClient(PagePolicyClientEfl::create(this)) - , m_pageUIClient(PageUIClientEfl::create(this)) - , m_resourceLoadClient(ResourceLoadClientEfl::create(this)) - , m_contextMenuClient(ContextMenuClientEfl::create(this)) - , m_findClient(FindClientEfl::create(this)) - , m_formClient(FormClientEfl::create(this)) -#if ENABLE(VIBRATION) - , m_vibrationClient(VibrationClientEfl::create(this)) -#endif - , m_backForwardList(Ewk_Back_Forward_List::create(toAPI(m_pageProxy->backForwardList()))) -#if USE(TILED_BACKING_STORE) - , m_scaleFactor(1) -#endif - , m_settings(Ewk_Settings::create(this)) - , m_cursorIdentifier(0) - , m_mouseEventsEnabled(false) -#if ENABLE(TOUCH_EVENTS) - , m_touchEventsEnabled(false) -#endif - , m_displayTimer(this, &EwkViewImpl::displayTimerFired) - , m_inputMethodContext(InputMethodContextEfl::create(this, smartData()->base.evas)) - , m_isHardwareAccelerated(true) - , m_setDrawsBackground(false) -{ - ASSERT(m_view); - ASSERT(m_context); - ASSERT(m_pageProxy); - -#if USE(COORDINATED_GRAPHICS) - m_pageProxy->pageGroup()->preferences()->setAcceleratedCompositingEnabled(true); - m_pageProxy->pageGroup()->preferences()->setForceCompositingMode(true); -#if ENABLE(WEBGL) - m_pageProxy->pageGroup()->preferences()->setWebGLEnabled(true); -#endif - if (behavior == DefaultBehavior) - m_pageProxy->setUseFixedLayout(true); -#endif - - m_pageProxy->initializeWebPage(); - -#if ENABLE(FULLSCREEN_API) - m_pageProxy->fullScreenManager()->setWebView(m_view); - m_pageProxy->pageGroup()->preferences()->setFullScreenEnabled(true); -#endif - - m_pageProxy->pageGroup()->preferences()->setOfflineWebApplicationCacheEnabled(true); - - // Enable mouse events by default - setMouseEventsEnabled(true); - - // Listen for favicon changes. - Ewk_Favicon_Database* iconDatabase = m_context->faviconDatabase(); - ASSERT(iconDatabase); - - iconDatabase->watchChanges(IconChangeCallbackData(EwkViewImpl::onFaviconChanged, this)); - - EwkViewImpl::addToPageViewMap(this); -} - -EwkViewImpl::~EwkViewImpl() -{ - m_pageProxy->close(); - - // Unregister icon change callback. - Ewk_Favicon_Database* iconDatabase = m_context->faviconDatabase(); - ASSERT(iconDatabase); - - iconDatabase->unwatchChanges(EwkViewImpl::onFaviconChanged); - - EwkViewImpl::removeFromPageViewMap(this); -} - -Ewk_View_Smart_Data* EwkViewImpl::smartData() const -{ - return static_cast<Ewk_View_Smart_Data*>(evas_object_smart_data_get(m_view)); -} - -EwkViewImpl* EwkViewImpl::fromEvasObject(const Evas_Object* view) -{ - ASSERT(view); - Ewk_View_Smart_Data* sd = static_cast<Ewk_View_Smart_Data*>(evas_object_smart_data_get(view)); - ASSERT(sd); - ASSERT(sd->priv); - return sd->priv; -} - -/** - * @internal - * Retrieves the internal WKPage for this view. - */ -WKPageRef EwkViewImpl::wkPage() -{ - return toAPI(m_pageProxy.get()); -} - -void EwkViewImpl::setCursor(const Cursor& cursor) -{ - if (cursor.image()) { - // Custom cursor. - if (cursor.image() == m_cursorIdentifier) - return; - - m_cursorIdentifier = cursor.image(); - - Ewk_View_Smart_Data* sd = smartData(); - RefPtr<Evas_Object> cursorObject = adoptRef(cursor.image()->getEvasObject(sd->base.evas)); - if (!cursorObject) - return; - - // Resize cursor. - evas_object_resize(cursorObject.get(), cursor.image()->size().width(), cursor.image()->size().height()); - - // Get cursor hot spot. - IntPoint hotSpot; - cursor.image()->getHotSpot(hotSpot); - - Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); - // ecore_evas takes care of freeing the cursor object. - ecore_evas_object_cursor_set(ecoreEvas, cursorObject.release().leakRef(), EVAS_LAYER_MAX, hotSpot.x(), hotSpot.y()); - - return; - } - - // Standard cursor. - const char* group = cursor.platformCursor(); - if (!group || group == m_cursorIdentifier) - return; - - m_cursorIdentifier = group; - Ewk_View_Smart_Data* sd = smartData(); - RefPtr<Evas_Object> cursorObject = adoptRef(edje_object_add(sd->base.evas)); - - Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); - if (!m_theme || !edje_object_file_set(cursorObject.get(), m_theme, group)) { - ecore_evas_object_cursor_set(ecoreEvas, 0, 0, 0, 0); -#ifdef HAVE_ECORE_X - if (WebCore::isUsingEcoreX(sd->base.evas)) - WebCore::applyFallbackCursor(ecoreEvas, group); -#endif - return; - } - - // Set cursor size. - Evas_Coord width, height; - edje_object_size_min_get(cursorObject.get(), &width, &height); - if (width <= 0 || height <= 0) - edje_object_size_min_calc(cursorObject.get(), &width, &height); - if (width <= 0 || height <= 0) { - width = defaultCursorSize; - height = defaultCursorSize; - } - evas_object_resize(cursorObject.get(), width, height); - - // Get cursor hot spot. - const char* data; - int hotspotX = 0; - data = edje_object_data_get(cursorObject.get(), "hot.x"); - if (data) - hotspotX = atoi(data); - - int hotspotY = 0; - data = edje_object_data_get(cursorObject.get(), "hot.y"); - if (data) - hotspotY = atoi(data); - - // ecore_evas takes care of freeing the cursor object. - ecore_evas_object_cursor_set(ecoreEvas, cursorObject.release().leakRef(), EVAS_LAYER_MAX, hotspotX, hotspotY); -} - -AffineTransform EwkViewImpl::transformFromScene() const -{ - AffineTransform transform; - -#if USE(TILED_BACKING_STORE) - transform.scale(1 / m_scaleFactor); - transform.translate(discretePagePosition().x(), discretePagePosition().y()); -#endif - - Ewk_View_Smart_Data* sd = smartData(); - transform.translate(-sd->view.x, -sd->view.y); - - return transform; -} - -AffineTransform EwkViewImpl::transformToScene() const -{ - return transformFromScene().inverse(); -} - -AffineTransform EwkViewImpl::transformToScreen() const -{ - AffineTransform transform; - - int windowGlobalX = 0; - int windowGlobalY = 0; - - Ewk_View_Smart_Data* sd = smartData(); - -#ifdef HAVE_ECORE_X - Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); - - Ecore_X_Window window; -#if USE(ACCELERATED_COMPOSITING) - window = ecore_evas_gl_x11_window_get(ecoreEvas); - // Fallback to software mode if necessary. - if (!window) -#endif - window = ecore_evas_software_x11_window_get(ecoreEvas); // Returns 0 if none. - - int x, y; // x, y are relative to parent (in a reparenting window manager). - while (window) { - ecore_x_window_geometry_get(window, &x, &y, 0, 0); - windowGlobalX += x; - windowGlobalY += y; - window = ecore_x_window_parent_get(window); - } -#endif - - transform.translate(-sd->view.x, -sd->view.y); - transform.translate(windowGlobalX, windowGlobalY); - - return transform; -} - -#if USE(COORDINATED_GRAPHICS) -LayerTreeRenderer* EwkViewImpl::layerTreeRenderer() -{ - DrawingAreaProxy* drawingArea = page()->drawingArea(); - if (!drawingArea) - return 0; - - WebKit::LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy = drawingArea->layerTreeCoordinatorProxy(); - if (!layerTreeCoordinatorProxy) - return 0; - - return layerTreeCoordinatorProxy->layerTreeRenderer(); -} -#endif - -void EwkViewImpl::displayTimerFired(Timer<EwkViewImpl>*) -{ -#if USE(COORDINATED_GRAPHICS) - Ewk_View_Smart_Data* sd = smartData(); - - if (m_pendingSurfaceResize) { - // Create a GL surface here so that Evas has no chance of painting to an empty GL surface. - createGLSurface(IntSize(sd->view.w, sd->view.h)); - m_pendingSurfaceResize = false; - } else - evas_gl_make_current(m_evasGL.get(), evasGLSurface(), evasGLContext()); - - // We are supposed to clip to the actual viewport, nothing less. - IntRect viewport(sd->view.x, sd->view.y, sd->view.w, sd->view.h); - - LayerTreeRenderer* renderer = layerTreeRenderer(); - if (!renderer) - return; - - renderer->setActive(true); - renderer->setDrawsBackground(m_setDrawsBackground); - if (m_isHardwareAccelerated) { - renderer->paintToCurrentGLContext(transformToScene().toTransformationMatrix(), /* opacity */ 1, viewport); - // sd->image is tied to a native surface. The native surface is in the parent's coordinates, - // so we need to account for the viewport position when calling evas_object_image_data_update_add. - evas_object_image_data_update_add(sd->image, viewport.x(), viewport.y(), viewport.width(), viewport.height()); - } else { - RefPtr<cairo_surface_t> surface = createSurfaceForImage(sd->image); - if (!surface) - return; - - RefPtr<cairo_t> graphicsContext = adoptRef(cairo_create(surface.get())); - cairo_translate(graphicsContext.get(), - discretePagePosition().x(), - discretePagePosition().y()); - cairo_scale(graphicsContext.get(), m_scaleFactor, m_scaleFactor); - renderer->paintToGraphicsContext(graphicsContext.get()); - evas_object_image_data_update_add(sd->image, 0, 0, viewport.width(), viewport.height()); - } -#endif -} - -void EwkViewImpl::update(const IntRect& rect) -{ - Ewk_View_Smart_Data* sd = smartData(); -#if USE(COORDINATED_GRAPHICS) - // Coordinated graphices needs to schedule an full update, not - // repainting of a region. Update in the event loop. - UNUSED_PARAM(rect); - - // Guard for zero sized viewport. - if (!(sd->view.w && sd->view.h)) - return; - - if (!m_displayTimer.isActive()) - m_displayTimer.startOneShot(0); -#else - if (!sd->image) - return; - - evas_object_image_data_update_add(sd->image, rect.x(), rect.y(), rect.width(), rect.height()); -#endif -} - -#if ENABLE(FULLSCREEN_API) -/** - * @internal - * Calls fullscreen_enter callback or falls back to default behavior and enables fullscreen mode. - */ -void EwkViewImpl::enterFullScreen() -{ - Ewk_View_Smart_Data* sd = smartData(); - - RefPtr<EwkSecurityOrigin> origin = EwkSecurityOrigin::create(KURL(ParsedURLString, String::fromUTF8(m_url))); - - if (!sd->api->fullscreen_enter || !sd->api->fullscreen_enter(sd, origin.get())) { - Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); - ecore_evas_fullscreen_set(ecoreEvas, true); - } -} - -/** - * @internal - * Calls fullscreen_exit callback or falls back to default behavior and disables fullscreen mode. - */ -void EwkViewImpl::exitFullScreen() -{ - Ewk_View_Smart_Data* sd = smartData(); - - if (!sd->api->fullscreen_exit || !sd->api->fullscreen_exit(sd)) { - Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(sd->base.evas); - ecore_evas_fullscreen_set(ecoreEvas, false); - } -} -#endif - -WKRect EwkViewImpl::windowGeometry() const -{ - Evas_Coord x, y, width, height; - Ewk_View_Smart_Data* sd = smartData(); - - if (!sd->api->window_geometry_get || !sd->api->window_geometry_get(sd, &x, &y, &width, &height)) { - Ecore_Evas* ee = ecore_evas_ecore_evas_get(sd->base.evas); - ecore_evas_request_geometry_get(ee, &x, &y, &width, &height); - } - - return WKRectMake(x, y, width, height); -} - -void EwkViewImpl::setWindowGeometry(const WKRect& rect) -{ - Ewk_View_Smart_Data* sd = smartData(); - - if (!sd->api->window_geometry_set || !sd->api->window_geometry_set(sd, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)) { - Ecore_Evas* ee = ecore_evas_ecore_evas_get(sd->base.evas); - ecore_evas_move_resize(ee, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); - } -} - -void EwkViewImpl::setImageData(void* imageData, const IntSize& size) -{ - Ewk_View_Smart_Data* sd = smartData(); - if (!imageData || !sd->image) - return; - - evas_object_resize(sd->image, size.width(), size.height()); - evas_object_image_size_set(sd->image, size.width(), size.height()); - evas_object_image_data_copy_set(sd->image, imageData); -} - -#if USE(TILED_BACKING_STORE) -void EwkViewImpl::informLoadCommitted() -{ - m_pageClient->didCommitLoad(); -} -#endif - -IntSize EwkViewImpl::size() const -{ - int width, height; - evas_object_geometry_get(m_view, 0, 0, &width, &height); - return IntSize(width, height); -} - -bool EwkViewImpl::isFocused() const -{ - return evas_object_focus_get(m_view); -} - -bool EwkViewImpl::isVisible() const -{ - return evas_object_visible_get(m_view); -} - -const char* EwkViewImpl::title() const -{ - m_title = m_pageProxy->pageTitle().utf8().data(); - - return m_title; -} - -/** - * @internal - * This function may return @c NULL. - */ -InputMethodContextEfl* EwkViewImpl::inputMethodContext() -{ - return m_inputMethodContext.get(); -} - -const char* EwkViewImpl::themePath() const -{ - return m_theme; -} - -void EwkViewImpl::setThemePath(const char* theme) -{ - if (m_theme != theme) { - m_theme = theme; - m_pageProxy->setThemePath(theme); - } -} - -const char* EwkViewImpl::customTextEncodingName() const -{ - String customEncoding = m_pageProxy->customTextEncodingName(); - if (customEncoding.isEmpty()) - return 0; - - m_customEncoding = customEncoding.utf8().data(); - - return m_customEncoding; -} - -void EwkViewImpl::setCustomTextEncodingName(const String& encoding) -{ - m_pageProxy->setCustomTextEncodingName(encoding); -} - -void EwkViewImpl::setMouseEventsEnabled(bool enabled) -{ - if (m_mouseEventsEnabled == enabled) - return; - - m_mouseEventsEnabled = enabled; - if (enabled) { - Ewk_View_Smart_Data* sd = smartData(); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MOUSE_DOWN, onMouseDown, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MOUSE_UP, onMouseUp, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MOUSE_MOVE, onMouseMove, sd); - } else { - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MOUSE_DOWN, onMouseDown); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MOUSE_UP, onMouseUp); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MOUSE_MOVE, onMouseMove); - } -} - -#if ENABLE(TOUCH_EVENTS) -void EwkViewImpl::setTouchEventsEnabled(bool enabled) -{ - if (m_touchEventsEnabled == enabled) - return; - - m_touchEventsEnabled = enabled; - - if (enabled) { - // FIXME: We have to connect touch callbacks with mouse and multi events - // because the Evas creates mouse events for first touch and multi events - // for second and third touches. Below codes should be fixed when the Evas - // supports the touch events. - // See https://bugs.webkit.org/show_bug.cgi?id=97785 for details. - Ewk_View_Smart_Data* sd = smartData(); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MOUSE_DOWN, onTouchDown, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MOUSE_UP, onTouchUp, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MOUSE_MOVE, onTouchMove, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MULTI_DOWN, onTouchDown, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MULTI_UP, onTouchUp, sd); - evas_object_event_callback_add(m_view, EVAS_CALLBACK_MULTI_MOVE, onTouchMove, sd); - } else { - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MOUSE_DOWN, onTouchDown); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MOUSE_UP, onTouchUp); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MOUSE_MOVE, onTouchMove); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MULTI_DOWN, onTouchDown); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MULTI_UP, onTouchUp); - evas_object_event_callback_del(m_view, EVAS_CALLBACK_MULTI_MOVE, onTouchMove); - } -} -#endif - -/** - * @internal - * Update the view's favicon and emits a "icon,changed" signal if it has - * changed. - * - * This function is called whenever the URL has changed or when the icon for - * the current page URL has changed. - */ -void EwkViewImpl::informIconChange() -{ - Ewk_Favicon_Database* iconDatabase = m_context->faviconDatabase(); - ASSERT(iconDatabase); - - m_faviconURL = ewk_favicon_database_icon_url_get(iconDatabase, m_url); - smartCallback<IconChanged>().call(); -} - -#if USE(ACCELERATED_COMPOSITING) -bool EwkViewImpl::createGLSurface(const IntSize& viewSize) -{ - if (!m_isHardwareAccelerated) - return true; - - if (!m_evasGL) { - Evas* evas = evas_object_evas_get(m_view); - m_evasGL = adoptPtr(evas_gl_new(evas)); - if (!m_evasGL) { - WARN("Failed to create Evas_GL, falling back to software mode."); - m_isHardwareAccelerated = false; -#if ENABLE(WEBGL) - m_pageProxy->pageGroup()->preferences()->setWebGLEnabled(false); -#endif - return false; - } - } - - if (!m_evasGLContext) { - m_evasGLContext = EvasGLContext::create(m_evasGL.get()); - if (!m_evasGLContext) { - WARN("Failed to create GLContext."); - return false; - } - } - - Ewk_View_Smart_Data* sd = smartData(); - - Evas_GL_Config evasGLConfig = { - EVAS_GL_RGBA_8888, - EVAS_GL_DEPTH_BIT_8, - EVAS_GL_STENCIL_NONE, - EVAS_GL_OPTIONS_NONE, - EVAS_GL_MULTISAMPLE_NONE - }; - - // Replaces if non-null, and frees existing surface after (OwnPtr). - m_evasGLSurface = EvasGLSurface::create(m_evasGL.get(), &evasGLConfig, viewSize); - if (!m_evasGLSurface) - return false; - - Evas_Native_Surface nativeSurface; - evas_gl_native_surface_get(m_evasGL.get(), evasGLSurface(), &nativeSurface); - evas_object_image_native_surface_set(sd->image, &nativeSurface); - - evas_gl_make_current(m_evasGL.get(), evasGLSurface(), evasGLContext()); - - Evas_GL_API* gl = evas_gl_api_get(m_evasGL.get()); - gl->glViewport(0, 0, viewSize.width() + sd->view.x, viewSize.height() + sd->view.y); - gl->glClearColor(1.0, 1.0, 1.0, 0); - gl->glClear(GL_COLOR_BUFFER_BIT); - - return true; -} - -bool EwkViewImpl::enterAcceleratedCompositingMode() -{ - layerTreeRenderer()->setActive(true); - - if (!m_isHardwareAccelerated) - return true; - - if (!m_evasGLSurface) { - if (!createGLSurface(size())) { - WARN("Failed to create GLSurface."); - return false; - } - } - - return true; -} - -bool EwkViewImpl::exitAcceleratedCompositingMode() -{ - return true; -} -#endif - -#if ENABLE(INPUT_TYPE_COLOR) -/** - * @internal - * Requests to show external color picker. - */ -void EwkViewImpl::requestColorPicker(WKColorPickerResultListenerRef listener, const WebCore::Color& color) -{ - Ewk_View_Smart_Data* sd = smartData(); - EINA_SAFETY_ON_NULL_RETURN(sd->api->input_picker_color_request); - - if (!sd->api->input_picker_color_request) - return; - - if (m_colorPicker) - dismissColorPicker(); - - m_colorPicker = Ewk_Color_Picker::create(listener, color); - - sd->api->input_picker_color_request(sd, m_colorPicker.get()); -} - -/** - * @internal - * Requests to hide external color picker. - */ -void EwkViewImpl::dismissColorPicker() -{ - if (!m_colorPicker) - return; - - Ewk_View_Smart_Data* sd = smartData(); - EINA_SAFETY_ON_NULL_RETURN(sd->api->input_picker_color_dismiss); - - if (sd->api->input_picker_color_dismiss) - sd->api->input_picker_color_dismiss(sd); - - m_colorPicker.clear(); -} -#endif - -void EwkViewImpl::informContentsSizeChange(const IntSize& size) -{ -#if USE(COORDINATED_GRAPHICS) - m_pageClient->didChangeContentsSize(size); -#else - UNUSED_PARAM(size); -#endif -} - -COMPILE_ASSERT_MATCHING_ENUM(EWK_TEXT_DIRECTION_RIGHT_TO_LEFT, RTL); -COMPILE_ASSERT_MATCHING_ENUM(EWK_TEXT_DIRECTION_LEFT_TO_RIGHT, LTR); - -void EwkViewImpl::showContextMenu(WebContextMenuProxyEfl* contextMenuProxy, const WebCore::IntPoint& position, const Vector<WebContextMenuItemData>& items) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - ASSERT(contextMenuProxy); - - if (!sd->api->context_menu_show) - return; - - if (m_contextMenu) - hideContextMenu(); - - m_contextMenu = Ewk_Context_Menu::create(this, contextMenuProxy, items); - - sd->api->context_menu_show(sd, position.x(), position.y(), m_contextMenu.get()); -} - -void EwkViewImpl::hideContextMenu() -{ - if (!m_contextMenu) - return; - - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (sd->api->context_menu_hide) - sd->api->context_menu_hide(sd); - - m_contextMenu.clear(); -} - -void EwkViewImpl::requestPopupMenu(WebPopupMenuProxyEfl* popupMenuProxy, const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, int32_t selectedIndex) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - ASSERT(popupMenuProxy); - - if (!sd->api->popup_menu_show) - return; - - if (m_popupMenu) - closePopupMenu(); - - m_popupMenu = Ewk_Popup_Menu::create(this, popupMenuProxy, items, selectedIndex); - - sd->api->popup_menu_show(sd, rect, static_cast<Ewk_Text_Direction>(textDirection), pageScaleFactor, m_popupMenu.get()); -} - -void EwkViewImpl::closePopupMenu() -{ - if (!m_popupMenu) - return; - - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (sd->api->popup_menu_hide) - sd->api->popup_menu_hide(sd); - - m_popupMenu.clear(); -} - -/** - * @internal - * Calls a smart member function for javascript alert(). - */ -void EwkViewImpl::requestJSAlertPopup(const WKEinaSharedString& message) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (!sd->api->run_javascript_alert) - return; - - sd->api->run_javascript_alert(sd, message); -} - -/** - * @internal - * Calls a smart member function for javascript confirm() and returns a value from the function. Returns false by default. - */ -bool EwkViewImpl::requestJSConfirmPopup(const WKEinaSharedString& message) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (!sd->api->run_javascript_confirm) - return false; - - return sd->api->run_javascript_confirm(sd, message); -} - -/** - * @internal - * Calls a smart member function for javascript prompt() and returns a value from the function. Returns null string by default. - */ -WKEinaSharedString EwkViewImpl::requestJSPromptPopup(const WKEinaSharedString& message, const WKEinaSharedString& defaultValue) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (!sd->api->run_javascript_prompt) - return WKEinaSharedString(); - - return WKEinaSharedString::adopt(sd->api->run_javascript_prompt(sd, message, defaultValue)); -} - -#if ENABLE(SQL_DATABASE) -/** - * @internal - * Calls exceeded_database_quota callback or falls back to default behavior returns default database quota. - */ -unsigned long long EwkViewImpl::informDatabaseQuotaReached(const String& databaseName, const String& displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - static const unsigned long long defaultQuota = 5 * 1024 * 1204; // 5 MB - if (sd->api->exceeded_database_quota) - return sd->api->exceeded_database_quota(sd, databaseName.utf8().data(), displayName.utf8().data(), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage); - - return defaultQuota; -} -#endif - -/** - * @internal - * The url of view was changed by the frame loader. - * - * Emits signal: "url,changed" with pointer to new url string. - */ -void EwkViewImpl::informURLChange() -{ - String activeURL = m_pageProxy->activeURL(); - if (activeURL.isEmpty()) - return; - - CString rawActiveURL = activeURL.utf8(); - if (m_url == rawActiveURL.data()) - return; - - m_url = rawActiveURL.data(); - smartCallback<URLChanged>().call(m_url); - - // Update the view's favicon. - informIconChange(); -} - -EwkWindowFeatures* EwkViewImpl::windowFeatures() -{ - if (!m_windowFeatures) - m_windowFeatures = EwkWindowFeatures::create(0, this); - - return m_windowFeatures.get(); -} - -WKPageRef EwkViewImpl::createNewPage(ImmutableDictionary* windowFeatures) -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (!sd->api->window_create) - return 0; - - RefPtr<EwkWindowFeatures> ewkWindowFeatures = EwkWindowFeatures::create(windowFeatures, this); - - Evas_Object* newEwkView = sd->api->window_create(sd, ewkWindowFeatures.get()); - if (!newEwkView) - return 0; - - EwkViewImpl* newViewImpl = EwkViewImpl::fromEvasObject(newEwkView); - ASSERT(newViewImpl); - - newViewImpl->m_windowFeatures = ewkWindowFeatures; - - return static_cast<WKPageRef>(WKRetain(newViewImpl->page())); -} - -void EwkViewImpl::closePage() -{ - Ewk_View_Smart_Data* sd = smartData(); - ASSERT(sd->api); - - if (!sd->api->window_close) - return; - - sd->api->window_close(sd); -} - -void EwkViewImpl::onMouseDown(void* data, Evas*, Evas_Object*, void* eventInfo) -{ - Evas_Event_Mouse_Down* downEvent = static_cast<Evas_Event_Mouse_Down*>(eventInfo); - Ewk_View_Smart_Data* sd = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(sd->api); - EINA_SAFETY_ON_NULL_RETURN(sd->api->mouse_down); - sd->api->mouse_down(sd, downEvent); -} - -void EwkViewImpl::onMouseUp(void* data, Evas*, Evas_Object*, void* eventInfo) -{ - Evas_Event_Mouse_Up* upEvent = static_cast<Evas_Event_Mouse_Up*>(eventInfo); - Ewk_View_Smart_Data* sd = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(sd->api); - EINA_SAFETY_ON_NULL_RETURN(sd->api->mouse_up); - sd->api->mouse_up(sd, upEvent); -} - -void EwkViewImpl::onMouseMove(void* data, Evas*, Evas_Object*, void* eventInfo) -{ - Evas_Event_Mouse_Move* moveEvent = static_cast<Evas_Event_Mouse_Move*>(eventInfo); - Ewk_View_Smart_Data* sd = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(sd->api); - EINA_SAFETY_ON_NULL_RETURN(sd->api->mouse_move); - sd->api->mouse_move(sd, moveEvent); -} - -#if ENABLE(TOUCH_EVENTS) -void EwkViewImpl::feedTouchEvents(Ewk_Touch_Event_Type type) -{ - Ewk_View_Smart_Data* sd = smartData(); - - unsigned count = evas_touch_point_list_count(sd->base.evas); - if (!count) - return; - - Eina_List* points = 0; - for (unsigned i = 0; i < count; ++i) { - Ewk_Touch_Point* point = new Ewk_Touch_Point; - point->id = evas_touch_point_list_nth_id_get(sd->base.evas, i); - evas_touch_point_list_nth_xy_get(sd->base.evas, i, &point->x, &point->y); - point->state = evas_touch_point_list_nth_state_get(sd->base.evas, i); - points = eina_list_append(points, point); - } - - ewk_view_feed_touch_event(m_view, type, points, evas_key_modifier_get(sd->base.evas)); - - void* data; - EINA_LIST_FREE(points, data) - delete static_cast<Ewk_Touch_Point*>(data); -} - -void EwkViewImpl::onTouchDown(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */) -{ - EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(ewkView); - viewImpl->feedTouchEvents(EWK_TOUCH_START); -} - -void EwkViewImpl::onTouchUp(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */) -{ - EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(ewkView); - viewImpl->feedTouchEvents(EWK_TOUCH_END); -} - -void EwkViewImpl::onTouchMove(void* /* data */, Evas* /* canvas */, Evas_Object* ewkView, void* /* eventInfo */) -{ - EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(ewkView); - viewImpl->feedTouchEvents(EWK_TOUCH_MOVE); -} -#endif - -void EwkViewImpl::onFaviconChanged(const char* pageURL, void* eventInfo) -{ - EwkViewImpl* viewImpl = static_cast<EwkViewImpl*>(eventInfo); - - if (!viewImpl->url() || strcasecmp(viewImpl->url(), pageURL)) - return; - - viewImpl->informIconChange(); -} - -WKImageRef EwkViewImpl::takeSnapshot() -{ - Ewk_View_Smart_Data* sd = smartData(); -#if USE(ACCELERATED_COMPOSITING) - if (!m_isHardwareAccelerated) -#endif - return WKImageCreateFromCairoSurface(createSurfaceForImage(sd->image).get(), 0); - -#if USE(ACCELERATED_COMPOSITING) - Evas_Native_Surface* nativeSurface = evas_object_image_native_surface_get(sd->image); - unsigned char* buffer = getImageFromCurrentTexture(sd->view.w, sd->view.h, nativeSurface->data.opengl.texture_id); - RefPtr<cairo_surface_t> surface = adoptRef(cairo_image_surface_create_for_data(buffer, CAIRO_FORMAT_ARGB32, sd->view.w, sd->view.h, sd->view.w * 4)); - WKImageRef image = WKImageCreateFromCairoSurface(surface.get(), 0); - delete[] buffer; - - return image; -#endif -} diff --git a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp index cd901efee..8e0b9d833 100644 --- a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp +++ b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp @@ -24,9 +24,11 @@ */ #include "config.h" -#include "SnapshotImageGL.h" #if USE(ACCELERATED_COMPOSITING) + +#include "SnapshotImageGL.h" + #if USE(OPENGL_ES_2) #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> @@ -34,25 +36,41 @@ #include "OpenGLShims.h" #endif -unsigned char* getImageFromCurrentTexture(int width, int height, int textureId) +#include <WebCore/CairoUtilitiesEfl.h> + +PassRefPtr<cairo_surface_t> getImageSurfaceFromFrameBuffer(int x, int y, int width, int height) { - glBindTexture(GL_TEXTURE_2D, textureId); - unsigned char* buffer = new unsigned char[width * height * 4]; - glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, buffer); + RefPtr<cairo_surface_t> newSurface = adoptRef(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height)); + unsigned char* data = cairo_image_surface_get_data(newSurface.get()); + +#if USE(OPENGL_ES_2) + GLenum format = GL_RGBA; +#else + GLenum format = GL_BGRA; +#endif + + glReadPixels(x, y, width, height, format, GL_UNSIGNED_BYTE, data); + +#if USE(OPENGL_ES_2) + // Convert to BGRA. + int totalBytes = width * height * 4; + + for (int i = 0; i < totalBytes; i += 4) + std::swap(data[i], data[i + 2]); +#endif // Textures are flipped on the Y axis, so we need to flip the image back. - unsigned tmp; - unsigned* buf = reinterpret_cast<unsigned*>(buffer); + unsigned* buf = reinterpret_cast<unsigned*>(data); for (int i = 0; i < height / 2; ++i) { for (int j = 0; j < width; ++j) { - tmp = buf[i * width + j]; + unsigned tmp = buf[i * width + j]; buf[i * width + j] = buf[(height - i - 1) * width + j]; buf[(height - i - 1) * width + j] = tmp; } } - return buffer; + cairo_surface_mark_dirty(newSurface.get()); + return newSurface; } - #endif diff --git a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h index 6c228b126..68c1428ae 100644 --- a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h +++ b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h @@ -27,7 +27,11 @@ #define SnapshotImageGL_h #if USE(ACCELERATED_COMPOSITING) -unsigned char* getImageFromCurrentTexture(int width, int height, int textureId); -#endif +#include <RefPtrCairo.h> +#include <wtf/OwnArrayPtr.h> + +PassRefPtr<cairo_surface_t> getImageSurfaceFromFrameBuffer(int x, int y, int width, int height); + +#endif // USE(ACCELERATED_COMPOSITING) #endif // SnapshotImageGL_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.cpp index 20279e3a6..b9ea77d5e 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.cpp @@ -26,18 +26,17 @@ #include "config.h" #include "ewk_auth_request.h" -#include "AuthenticationChallengeProxy.h" -#include "AuthenticationDecisionListener.h" -#include "WebCredential.h" -#include "WebProtectionSpace.h" -#include "WebString.h" +#include "WKAuthenticationChallenge.h" +#include "WKAuthenticationDecisionListener.h" +#include "WKCredential.h" +#include "WKProtectionSpace.h" +#include "WKString.h" #include "ewk_auth_request_private.h" #include <wtf/text/CString.h> using namespace WebKit; -using namespace WebCore; -EwkAuthRequest::EwkAuthRequest(AuthenticationChallengeProxy* authenticationChallenge) +EwkAuthRequest::EwkAuthRequest(WKAuthenticationChallengeRef authenticationChallenge) : m_authenticationChallenge(authenticationChallenge) , m_wasHandled(false) { @@ -53,14 +52,14 @@ EwkAuthRequest::~EwkAuthRequest() const char* EwkAuthRequest::suggestedUsername() const { if (!m_suggestedUsername) { - WebCredential* credential = m_authenticationChallenge->proposedCredential(); + WKRetainPtr<WKCredentialRef> credential = WKAuthenticationChallengeGetProposedCredential(m_authenticationChallenge.get()); ASSERT(credential); - const String& suggestedUsername = credential->user(); - if (suggestedUsername.isEmpty()) + WKRetainPtr<WKStringRef> suggestedUsername(AdoptWK, WKCredentialCopyUser(credential.get())); + if (!suggestedUsername || WKStringIsEmpty(suggestedUsername.get())) return 0; - m_suggestedUsername = suggestedUsername.utf8().data(); + m_suggestedUsername = suggestedUsername.get(); } return m_suggestedUsername; @@ -69,14 +68,14 @@ const char* EwkAuthRequest::suggestedUsername() const const char* EwkAuthRequest::realm() const { if (!m_realm) { - WebProtectionSpace* protectionSpace = m_authenticationChallenge->protectionSpace(); + WKRetainPtr<WKProtectionSpaceRef> protectionSpace = WKAuthenticationChallengeGetProtectionSpace(m_authenticationChallenge.get()); ASSERT(protectionSpace); - const String& realm = protectionSpace->realm(); - if (realm.isEmpty()) + WKRetainPtr<WKStringRef> realm(AdoptWK, WKProtectionSpaceCopyRealm(protectionSpace.get())); + if (!realm || WKStringIsEmpty(realm.get())) return 0; - m_realm = realm.utf8().data(); + m_realm = realm.get(); } return m_realm; @@ -85,14 +84,14 @@ const char* EwkAuthRequest::realm() const const char* EwkAuthRequest::host() const { if (!m_host) { - WebProtectionSpace* protectionSpace = m_authenticationChallenge->protectionSpace(); + WKRetainPtr<WKProtectionSpaceRef> protectionSpace = WKAuthenticationChallengeGetProtectionSpace(m_authenticationChallenge.get()); ASSERT(protectionSpace); - const String& host = protectionSpace->host(); - if (host.isEmpty()) + WKRetainPtr<WKStringRef> host(AdoptWK, WKProtectionSpaceCopyHost(protectionSpace.get())); + if (!host || WKStringIsEmpty(host.get())) return 0; - m_host = host.utf8().data(); + m_host = host.get(); } return m_host; @@ -104,26 +103,30 @@ bool EwkAuthRequest::continueWithoutCredential() return false; m_wasHandled = true; - m_authenticationChallenge->useCredential(0); + WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(m_authenticationChallenge.get()); + WKAuthenticationDecisionListenerUseCredential(decisionListener, 0); return true; } -bool EwkAuthRequest::authenticate(const String& username, const String& password) +bool EwkAuthRequest::authenticate(const char* username, const char* password) { if (m_wasHandled) return false; m_wasHandled = true; - RefPtr<WebCredential> credential = WebCredential::create(WebString::create(username).get(), WebString::create(password).get(), CredentialPersistenceForSession); - m_authenticationChallenge->useCredential(credential.get()); + WKRetainPtr<WKStringRef> wkUsername(AdoptWK, WKStringCreateWithUTF8CString(username)); + WKRetainPtr<WKStringRef> wkPassword(AdoptWK, WKStringCreateWithUTF8CString(password)); + WKRetainPtr<WKCredentialRef> credential(AdoptWK, WKCredentialCreate(wkUsername.get(), wkPassword.get(), kWKCredentialPersistenceForSession)); + WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(m_authenticationChallenge.get()); + WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get()); return true; } bool EwkAuthRequest::isRetrying() const { - return m_authenticationChallenge->previousFailureCount() > 0; + return WKAuthenticationChallengeGetPreviousFailureCount(m_authenticationChallenge.get()) > 0; } const char* ewk_auth_request_suggested_username_get(const Ewk_Auth_Request* request) @@ -146,7 +149,7 @@ Eina_Bool ewk_auth_request_authenticate(Ewk_Auth_Request* request, const char* u EINA_SAFETY_ON_NULL_RETURN_VAL(username, false); EINA_SAFETY_ON_NULL_RETURN_VAL(password, false); - return impl->authenticate(String::fromUTF8(username), String::fromUTF8(password)); + return impl->authenticate(username, password); } Eina_Bool ewk_auth_request_retrying_get(const Ewk_Auth_Request* request) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h index 9dbbd62e0..7ca9be309 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h @@ -27,19 +27,17 @@ #define ewk_auth_request_private_h #include "WKEinaSharedString.h" +#include "WKRetainPtr.h" #include "ewk_object_private.h" +#include <WebKit2/WKBase.h> #include <wtf/PassRefPtr.h> #include <wtf/text/WTFString.h> -namespace WebKit { -class AuthenticationChallengeProxy; -} - class EwkAuthRequest : public EwkObject { public: EWK_OBJECT_DECLARE(EwkAuthRequest) - static PassRefPtr<EwkAuthRequest> create(WebKit::AuthenticationChallengeProxy* authenticationChallenge) + static PassRefPtr<EwkAuthRequest> create(WKAuthenticationChallengeRef authenticationChallenge) { return adoptRef(new EwkAuthRequest(authenticationChallenge)); } @@ -51,12 +49,12 @@ public: bool isRetrying() const; bool continueWithoutCredential(); - bool authenticate(const String& username, const String& password); + bool authenticate(const char* username, const char* password); private: - explicit EwkAuthRequest(WebKit::AuthenticationChallengeProxy* authenticationChallenge); + explicit EwkAuthRequest(WKAuthenticationChallengeRef authenticationChallenge); - RefPtr<WebKit::AuthenticationChallengeProxy> m_authenticationChallenge; + WKRetainPtr<WKAuthenticationChallengeRef> m_authenticationChallenge; bool m_wasHandled; mutable WKEinaSharedString m_suggestedUsername; mutable WKEinaSharedString m_realm; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp index fb9d9b408..88634373d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp @@ -39,22 +39,22 @@ EwkBackForwardList::EwkBackForwardList(WKBackForwardListRef listRef) : m_wkList(listRef) { } -Ewk_Back_Forward_List_Item* EwkBackForwardList::nextItem() const +EwkBackForwardListItem* EwkBackForwardList::nextItem() const { return getFromCacheOrCreate(WKBackForwardListGetForwardItem(m_wkList.get())); } -Ewk_Back_Forward_List_Item* EwkBackForwardList::previousItem() const +EwkBackForwardListItem* EwkBackForwardList::previousItem() const { return getFromCacheOrCreate(WKBackForwardListGetBackItem(m_wkList.get())); } -Ewk_Back_Forward_List_Item* EwkBackForwardList::currentItem() const +EwkBackForwardListItem* EwkBackForwardList::currentItem() const { return getFromCacheOrCreate(WKBackForwardListGetCurrentItem(m_wkList.get())); } -Ewk_Back_Forward_List_Item* EwkBackForwardList::itemAt(int index) const +EwkBackForwardListItem* EwkBackForwardList::itemAt(int index) const { return getFromCacheOrCreate(WKBackForwardListGetItemAtIndex(m_wkList.get(), index)); } @@ -84,12 +84,12 @@ WKRetainPtr<WKArrayRef> EwkBackForwardList::forwardList(int limit) const return adoptWK(WKBackForwardListCopyForwardListWithLimit(m_wkList.get(), limit)); } -Ewk_Back_Forward_List_Item* EwkBackForwardList::getFromCacheOrCreate(WKBackForwardListItemRef wkItem) const +EwkBackForwardListItem* EwkBackForwardList::getFromCacheOrCreate(WKBackForwardListItemRef wkItem) const { if (!wkItem) return 0; - RefPtr<Ewk_Back_Forward_List_Item> item = m_wrapperCache.get(wkItem); + RefPtr<EwkBackForwardListItem> item = m_wrapperCache.get(wkItem); if (!item) { item = EwkBackForwardListItem::create(wkItem); m_wrapperCache.set(wkItem, item); @@ -108,7 +108,7 @@ Eina_List* EwkBackForwardList::createEinaList(WKArrayRef wkList) const const size_t count = WKArrayGetSize(wkList); for (size_t i = 0; i < count; ++i) { WKBackForwardListItemRef wkItem = static_cast<WKBackForwardListItemRef>(WKArrayGetItemAtIndex(wkList, i)); - Ewk_Back_Forward_List_Item* item = getFromCacheOrCreate(wkItem); + EwkBackForwardListItem* item = getFromCacheOrCreate(wkItem); result = eina_list_append(result, ewk_object_ref(item)); } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item_private.h index 8225532c7..7b6d20a48 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item_private.h @@ -48,6 +48,8 @@ public: const char* title() const; const char* originalURL() const; + WKBackForwardListItemRef wkItem() const { return m_wkItem.get(); } + private: explicit EwkBackForwardListItem(WKBackForwardListItemRef itemRef); diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_private.h index e676ccca6..e5c6f0e1d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_private.h @@ -27,13 +27,12 @@ #define ewk_back_forward_list_private_h #include "WKRetainPtr.h" -#include "ewk_back_forward_list_item.h" #include "ewk_back_forward_list_item_private.h" #include <WebKit2/WKBase.h> #include <wtf/HashMap.h> #include <wtf/PassOwnPtr.h> -typedef HashMap<WKBackForwardListItemRef, RefPtr<Ewk_Back_Forward_List_Item> > ItemsMap; +typedef HashMap<WKBackForwardListItemRef, RefPtr<EwkBackForwardListItem> > ItemsMap; class EwkBackForwardList { public: @@ -42,10 +41,10 @@ public: return adoptPtr(new EwkBackForwardList(listRef)); } - Ewk_Back_Forward_List_Item* previousItem() const; - Ewk_Back_Forward_List_Item* currentItem() const; - Ewk_Back_Forward_List_Item* nextItem() const; - Ewk_Back_Forward_List_Item* itemAt(int index) const; + EwkBackForwardListItem* previousItem() const; + EwkBackForwardListItem* currentItem() const; + EwkBackForwardListItem* nextItem() const; + EwkBackForwardListItem* itemAt(int index) const; WKRetainPtr<WKArrayRef> backList(int limit = -1) const; WKRetainPtr<WKArrayRef> forwardList(int limit = -1) const; @@ -57,7 +56,7 @@ public: private: explicit EwkBackForwardList(WKBackForwardListRef listRef); - Ewk_Back_Forward_List_Item* getFromCacheOrCreate(WKBackForwardListItemRef wkItem) const; + EwkBackForwardListItem* getFromCacheOrCreate(WKBackForwardListItemRef wkItem) const; WKRetainPtr<WKBackForwardListRef> m_wkList; mutable ItemsMap m_wrapperCache; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp index 4e6bde62c..1141394cb 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp @@ -24,7 +24,6 @@ #include "WKColorPickerResultListener.h" #include "WKString.h" #include "ewk_color_picker_private.h" -#include <WebCore/Color.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> @@ -58,6 +57,11 @@ Eina_Bool ewk_color_picker_color_set(Ewk_Color_Picker* colorPicker, int r, int g return true; #else + UNUSED_PARAM(colorPicker); + UNUSED_PARAM(r); + UNUSED_PARAM(g); + UNUSED_PARAM(b); + UNUSED_PARAM(a); return false; #endif } @@ -79,6 +83,11 @@ Eina_Bool ewk_color_picker_color_get(const Ewk_Color_Picker* colorPicker, int* r return true; #else + UNUSED_PARAM(colorPicker); + UNUSED_PARAM(r); + UNUSED_PARAM(g); + UNUSED_PARAM(b); + UNUSED_PARAM(a); return false; #endif } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp index 13534988a..7189f6d35 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp @@ -23,16 +23,15 @@ #include "BatteryProvider.h" #include "ContextHistoryClientEfl.h" +#include "DownloadManagerEfl.h" #include "NetworkInfoProvider.h" #include "RequestManagerClientEfl.h" #include "WKAPICast.h" #include "WKContextSoup.h" #include "WKNumber.h" -#include "WKRetainPtr.h" #include "WKString.h" #include "WebContext.h" #include "WebIconDatabase.h" -#include "WebSoupRequestManagerProxy.h" #include "ewk_context_private.h" #include "ewk_cookie_manager_private.h" #include "ewk_database_manager_private.h" @@ -46,14 +45,13 @@ #include <wtf/text/WTFString.h> #if ENABLE(SPELLCHECK) -#include "ewk_settings.h" -#include "ewk_text_checker_private.h" +#include "TextCheckerClientEfl.h" #endif using namespace WebCore; using namespace WebKit; -typedef HashMap<WebContext*, EwkContext*> ContextMap; +typedef HashMap<WKContextRef, EwkContext*> ContextMap; static inline ContextMap& contextMap() { @@ -61,21 +59,21 @@ static inline ContextMap& contextMap() return map; } -EwkContext::EwkContext(PassRefPtr<WebContext> context) +EwkContext::EwkContext(WKContextRef context) : m_context(context) - , m_databaseManager(Ewk_Database_Manager::create(m_context)) - , m_storageManager(Ewk_Storage_Manager::create(m_context)) + , m_databaseManager(EwkDatabaseManager::create(WKContextGetDatabaseManager(context))) + , m_storageManager(EwkStorageManager::create(WKContextGetKeyValueStorageManager(context))) #if ENABLE(BATTERY_STATUS) - , m_batteryProvider(BatteryProvider::create(m_context)) + , m_batteryProvider(BatteryProvider::create(context)) #endif #if ENABLE(NETWORK_INFO) - , m_networkInfoProvider(NetworkInfoProvider::create(m_context)) + , m_networkInfoProvider(NetworkInfoProvider::create(context)) #endif - , m_downloadManager(DownloadManagerEfl::create(this)) - , m_requestManagerClient(RequestManagerClientEfl::create(this)) - , m_historyClient(ContextHistoryClientEfl::create(m_context)) + , m_downloadManager(DownloadManagerEfl::create(context)) + , m_requestManagerClient(RequestManagerClientEfl::create(context)) + , m_historyClient(ContextHistoryClientEfl::create(context)) { - ContextMap::AddResult result = contextMap().add(m_context.get(), this); + ContextMap::AddResult result = contextMap().add(context, this); ASSERT_UNUSED(result, result.isNewEntry); #if ENABLE(MEMORY_SAMPLER) @@ -83,17 +81,15 @@ EwkContext::EwkContext(PassRefPtr<WebContext> context) static const char environmentVariable[] = "SAMPLE_MEMORY"; if (!initializeMemorySampler && getenv(environmentVariable)) { - m_context->startMemorySampler(0.0); + WKContextStartMemorySampler(context, adoptWK(WKDoubleCreate(0.0)).get()); initializeMemorySampler = true; } #endif #if ENABLE(SPELLCHECK) - Ewk_Text_Checker::initialize(); - if (ewk_settings_continuous_spell_checking_enabled_get()) { - // Load the default language. - ewk_settings_spell_checking_languages_set(0); - } + // Load the default dictionary to show context menu spellchecking items + // independently of checking spelling while typing setting. + TextCheckerClientEfl::instance().ensureSpellCheckingLanguage(); #endif } @@ -103,17 +99,17 @@ EwkContext::~EwkContext() contextMap().remove(m_context.get()); } -PassRefPtr<EwkContext> EwkContext::create(PassRefPtr<WebContext> context) +PassRefPtr<EwkContext> EwkContext::findOrCreateWrapper(WKContextRef context) { - if (contextMap().contains(context.get())) - return contextMap().get(context.get()); // Will be ref-ed automatically. + if (contextMap().contains(context)) + return contextMap().get(context); return adoptRef(new EwkContext(context)); } PassRefPtr<EwkContext> EwkContext::create() { - return create(WebContext::create(String())); + return adoptRef(new EwkContext(adoptWK(WKContextCreate()).get())); } PassRefPtr<EwkContext> EwkContext::create(const String& injectedBundlePath) @@ -121,25 +117,27 @@ PassRefPtr<EwkContext> EwkContext::create(const String& injectedBundlePath) if (!fileExists(injectedBundlePath)) return 0; - return create(WebContext::create(injectedBundlePath)); + WKRetainPtr<WKStringRef> path = adoptWK(toCopiedAPI(injectedBundlePath)); + + return adoptRef(new EwkContext(adoptWK(WKContextCreateWithInjectedBundlePath(path.get())).get())); } -PassRefPtr<EwkContext> EwkContext::defaultContext() +EwkContext* EwkContext::defaultContext() { - static RefPtr<EwkContext> defaultInstance = create(); + static EwkContext* defaultInstance = create().leakRef(); return defaultInstance; } -Ewk_Cookie_Manager* EwkContext::cookieManager() +EwkCookieManager* EwkContext::cookieManager() { if (!m_cookieManager) - m_cookieManager = Ewk_Cookie_Manager::create(WKContextGetCookieManager(toAPI(m_context.get()))); + m_cookieManager = EwkCookieManager::create(WKContextGetCookieManager(m_context.get())); return m_cookieManager.get(); } -Ewk_Database_Manager* EwkContext::databaseManager() +EwkDatabaseManager* EwkContext::databaseManager() { return m_databaseManager.get(); } @@ -149,26 +147,28 @@ void EwkContext::ensureFaviconDatabase() if (m_faviconDatabase) return; - m_faviconDatabase = Ewk_Favicon_Database::create(m_context.get()->iconDatabase()); + m_faviconDatabase = EwkFaviconDatabase::create(WKContextGetIconDatabase(m_context.get())); } bool EwkContext::setFaviconDatabaseDirectoryPath(const String& databaseDirectory) { ensureFaviconDatabase(); + // FIXME: Hole in WK2 API layering must be fixed when C API is available. + WebIconDatabase* iconDatabase = toImpl(WKContextGetIconDatabase(m_context.get())); // The database path is already open so its path was // already set. - if (m_context->iconDatabase()->isOpen()) + if (iconDatabase->isOpen()) return false; // If databaseDirectory is empty, we use the default database path for the platform. - String databasePath = databaseDirectory.isEmpty() ? m_context->iconDatabasePath() : pathByAppendingComponent(databaseDirectory, WebCore::IconDatabase::defaultDatabaseFilename()); - m_context->setIconDatabasePath(databasePath); + String databasePath = databaseDirectory.isEmpty() ? toImpl(m_context.get())->iconDatabasePath() : pathByAppendingComponent(databaseDirectory, WebCore::IconDatabase::defaultDatabaseFilename()); + toImpl(m_context.get())->setIconDatabasePath(databasePath); return true; } -Ewk_Favicon_Database* EwkContext::faviconDatabase() +EwkFaviconDatabase* EwkContext::faviconDatabase() { ensureFaviconDatabase(); ASSERT(m_faviconDatabase); @@ -176,7 +176,7 @@ Ewk_Favicon_Database* EwkContext::faviconDatabase() return m_faviconDatabase.get(); } -Ewk_Storage_Manager* EwkContext::storageManager() const +EwkStorageManager* EwkContext::storageManager() const { return m_storageManager.get(); } @@ -188,26 +188,32 @@ RequestManagerClientEfl* EwkContext::requestManager() void EwkContext::addVisitedLink(const String& visitedURL) { - m_context->addVisitedLink(visitedURL); + WKContextAddVisitedLink(m_context.get(), adoptWK(toCopiedAPI(visitedURL)).get()); } void EwkContext::setCacheModel(Ewk_Cache_Model cacheModel) { - m_context->setCacheModel(static_cast<WebKit::CacheModel>(cacheModel)); + WKContextSetCacheModel(m_context.get(), static_cast<WebKit::CacheModel>(cacheModel)); } Ewk_Cache_Model EwkContext::cacheModel() const { - return static_cast<Ewk_Cache_Model>(m_context->cacheModel()); + return static_cast<Ewk_Cache_Model>(WKContextGetCacheModel(m_context.get())); } #if ENABLE(NETSCAPE_PLUGIN_API) void EwkContext::setAdditionalPluginPath(const String& path) { - m_context->setAdditionalPluginsDirectory(path); + // FIXME: Hole in WK2 API layering must be fixed when C API is available. + toImpl(m_context.get())->setAdditionalPluginsDirectory(path); } #endif +void EwkContext::clearResourceCache() +{ + WKResourceCacheManagerClearCacheForAllOrigins(WKContextGetResourceCacheManager(m_context.get()), WKResourceCachesToClearAll); +} + Ewk_Cookie_Manager* ewk_context_cookie_manager_get(const Ewk_Context* ewkContext) { EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContext, ewkContext, impl, 0); @@ -255,7 +261,7 @@ ContextHistoryClientEfl* EwkContext::historyClient() Ewk_Context* ewk_context_default_get() { - return EwkContext::defaultContext().get(); + return EwkContext::defaultContext(); } Ewk_Context* ewk_context_new() @@ -319,13 +325,23 @@ Ewk_Cache_Model ewk_context_cache_model_get(const Ewk_Context* ewkContext) Eina_Bool ewk_context_additional_plugin_path_set(Ewk_Context* ewkContext, const char* path) { +#if ENABLE(NETSCAPE_PLUGIN_API) EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(path, false); -#if ENABLE(NETSCAPE_PLUGIN_API) impl->setAdditionalPluginPath(String::fromUTF8(path)); return true; #else + UNUSED_PARAM(ewkContext); + UNUSED_PARAM(path); return false; #endif } + +void ewk_context_resource_cache_clear(Ewk_Context* ewkContext) +{ + EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl); + + impl->clearResourceCache(); +} + diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context.h b/Source/WebKit2/UIProcess/API/efl/ewk_context.h index bfb7fd263..5d440aa94 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context.h @@ -128,7 +128,7 @@ EAPI Ewk_Context *ewk_context_default_get(void); * * @return Ewk_Context object on success or @c NULL on failure * - * @see ewk_context_unref + * @see ewk_object_unref * @see ewk_context_new_with_injected_bundle_path */ EAPI Ewk_Context *ewk_context_new(void); @@ -142,7 +142,7 @@ EAPI Ewk_Context *ewk_context_new(void); * * @return Ewk_Context object on success or @c NULL on failure * - * @see ewk_context_unref + * @see ewk_object_unref * @see ewk_context_new */ EAPI Ewk_Context *ewk_context_new_with_injected_bundle_path(const char *path); @@ -311,6 +311,14 @@ EAPI Ewk_Cache_Model ewk_context_cache_model_get(const Ewk_Context *context); */ EAPI Eina_Bool ewk_context_additional_plugin_path_set(Ewk_Context *context, const char *path); +/** + * Clears HTTP caches in local storage and all resources cached in memory + * such as images, CSS, JavaScript, XSL, and fonts for @a context. + * + * @param context context object to clear all resource caches + */ +EAPI void ewk_context_resource_cache_clear(Ewk_Context *context); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp index 0a4e54718..5a99e6bf7 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp @@ -27,41 +27,44 @@ #include "ewk_context_menu.h" #include "APIObject.h" -#include "EwkViewImpl.h" -#include "WebContextMenuItemData.h" -#include "WebContextMenuProxyEfl.h" +#include "EwkView.h" +#include "WKArray.h" +#include "WKString.h" #include "ewk_context_menu_item.h" #include "ewk_context_menu_item_private.h" #include "ewk_context_menu_private.h" using namespace WebKit; -EwkContextMenu::EwkContextMenu(EwkViewImpl* viewImpl, WebContextMenuProxyEfl* contextMenuProxy, const Vector<WebKit::WebContextMenuItemData>& items) - : m_viewImpl(viewImpl) - , m_contextMenuProxy(contextMenuProxy) +static WKContextMenuItemTag getWKTagFromEwkAction(Ewk_Context_Menu_Item_Action action); + +EwkContextMenu::EwkContextMenu(EwkView* view, WKArrayRef items) + : m_viewImpl(view) , m_contextMenuItems(0) { - const size_t size = items.size(); + size_t size = WKArrayGetSize(items); for (size_t i = 0; i < size; ++i) - m_contextMenuItems = eina_list_append(m_contextMenuItems, Ewk_Context_Menu_Item::create(items[i]).leakPtr()); + m_contextMenuItems = eina_list_append(m_contextMenuItems, Ewk_Context_Menu_Item::create(static_cast<WKContextMenuItemRef>(WKArrayGetItemAtIndex(items, i)), this).leakPtr()); } EwkContextMenu::EwkContextMenu() : m_viewImpl(0) - , m_contextMenuProxy(0) , m_contextMenuItems(0) { } EwkContextMenu::EwkContextMenu(Eina_List* items) : m_viewImpl(0) - , m_contextMenuProxy(0) , m_contextMenuItems(0) { Eina_List* l; void* data; - EINA_LIST_FOREACH(items, l, data) - m_contextMenuItems = eina_list_append(m_contextMenuItems, static_cast<EwkContextMenuItem*>(data)); + EINA_LIST_FOREACH(items, l, data) { + if (EwkContextMenuItem* item = static_cast<EwkContextMenuItem*>(data)) { + item->setParentMenu(this); + m_contextMenuItems = eina_list_append(m_contextMenuItems, item); + } + } } EwkContextMenu::~EwkContextMenu() @@ -73,77 +76,254 @@ EwkContextMenu::~EwkContextMenu() void EwkContextMenu::hide() { + if (!m_viewImpl) + return; + m_viewImpl->hideContextMenu(); } -void Ewk_Context_Menu::appendItem(EwkContextMenuItem* item) +void EwkContextMenu::appendItem(EwkContextMenuItem* item) { + item->setParentMenu(this); + + if (item->type() == EWK_SUBMENU_TYPE) + item->subMenu()->setEwkView(this->ewkView()); + m_contextMenuItems = eina_list_append(m_contextMenuItems, item); } -void Ewk_Context_Menu::removeItem(EwkContextMenuItem* item) +void EwkContextMenu::removeItem(EwkContextMenuItem* item) { m_contextMenuItems = eina_list_remove(m_contextMenuItems, item); } -void EwkContextMenu::contextMenuItemSelected(const WebKit::WebContextMenuItemData& item) +bool EwkContextMenu::contextMenuItemSelected(WKContextMenuItemRef item) { - m_contextMenuProxy->contextMenuItemSelected(item); + if (!m_viewImpl) + return false; + + WKPageSelectContextMenuItem(m_viewImpl->wkPage(), item); + + return true; } Ewk_Context_Menu* ewk_context_menu_new() { - return EwkContextMenu::create().leakPtr(); + return EwkContextMenu::create().leakRef(); } Ewk_Context_Menu* ewk_context_menu_new_with_items(Eina_List* items) { - return EwkContextMenu::create(items).leakPtr(); + return EwkContextMenu::create(items).leakRef(); } Eina_Bool ewk_context_menu_item_append(Ewk_Context_Menu* menu, Ewk_Context_Menu_Item* item) { - EINA_SAFETY_ON_NULL_RETURN_VAL(menu, false); + EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); + EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - menu->appendItem(item); + impl->appendItem(item); return true; } Eina_Bool ewk_context_menu_item_remove(Ewk_Context_Menu* menu, Ewk_Context_Menu_Item* item) { - EINA_SAFETY_ON_NULL_RETURN_VAL(menu, false); + EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); - menu->removeItem(item); + impl->removeItem(item); return true; } Eina_Bool ewk_context_menu_hide(Ewk_Context_Menu* menu) { - EINA_SAFETY_ON_NULL_RETURN_VAL(menu, false); + EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); - menu->hide(); + impl->hide(); return true; } const Eina_List* ewk_context_menu_items_get(const Ewk_Context_Menu* menu) { - EINA_SAFETY_ON_NULL_RETURN_VAL(menu, 0); + EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContextMenu, menu, impl, 0); - return menu->items(); + return impl->items(); } Eina_Bool ewk_context_menu_item_select(Ewk_Context_Menu* menu, Ewk_Context_Menu_Item* item) { - EINA_SAFETY_ON_NULL_RETURN_VAL(menu, false); + EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - WebCore::ContextMenuItemType type = static_cast<WebCore::ContextMenuItemType>(item->type()); - WebCore::ContextMenuAction action = static_cast<WebCore::ContextMenuAction>(item->action()); + WKContextMenuItemRef wkItem; - menu->contextMenuItemSelected(WebContextMenuItemData(type, action, item->title(), item->enabled(), item->checked())); + switch (item->type()) { + case EWK_ACTION_TYPE: + wkItem = WKContextMenuItemCreateAsAction(getWKTagFromEwkAction(item->action()), adoptWK(WKStringCreateWithUTF8CString(item->title())).get(), item->enabled()); + break; + case EWK_CHECKABLE_ACTION_TYPE: + wkItem = WKContextMenuItemCreateAsCheckableAction(getWKTagFromEwkAction(item->action()), adoptWK(WKStringCreateWithUTF8CString(item->title())).get(), item->enabled(), item->checked()); + break; + default: + ASSERT_NOT_REACHED(); + return false; + } - return true; + return impl->contextMenuItemSelected(wkItem); +} + +static WKContextMenuItemTag getWKTagFromEwkAction(Ewk_Context_Menu_Item_Action action) +{ + switch (action) { + case EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION: + return kWKContextMenuItemTagNoAction; + case EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK_IN_NEW_WINDOW: + return kWKContextMenuItemTagOpenLinkInNewWindow; + case EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_LINK_TO_DISK: + return kWKContextMenuItemTagDownloadLinkToDisk; + case EWK_CONTEXT_MENU_ITEM_TAG_COPY_LINK_TO_CLIPBOARD: + return kWKContextMenuItemTagCopyLinkToClipboard; + case EWK_CONTEXT_MENU_ITEM_TAG_OPEN_IMAGE_IN_NEW_WINDOW: + return kWKContextMenuItemTagOpenImageInNewWindow; + case EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_IMAGE_TO_DISK: + return kWKContextMenuItemTagDownloadImageToDisk; + case EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_TO_CLIPBOARD: + return kWKContextMenuItemTagCopyImageToClipboard; + case EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_URL_TO_CLIPBOARD: + return kWKContextMenuItemTagCopyImageUrlToClipboard; + case EWK_CONTEXT_MENU_ITEM_TAG_OPEN_FRAME_IN_NEW_WINDOW: + return kWKContextMenuItemTagOpenFrameInNewWindow; + case EWK_CONTEXT_MENU_ITEM_TAG_COPY: + return kWKContextMenuItemTagCopy; + case EWK_CONTEXT_MENU_ITEM_TAG_GO_BACK: + return kWKContextMenuItemTagGoBack; + case EWK_CONTEXT_MENU_ITEM_TAG_GO_FORWARD: + return kWKContextMenuItemTagGoForward; + case EWK_CONTEXT_MENU_ITEM_TAG_STOP: + return kWKContextMenuItemTagStop; + case EWK_CONTEXT_MENU_ITEM_TAG_RELOAD: + return kWKContextMenuItemTagReload; + case EWK_CONTEXT_MENU_ITEM_TAG_CUT: + return kWKContextMenuItemTagCut; + case EWK_CONTEXT_MENU_ITEM_TAG_PASTE: + return kWKContextMenuItemTagPaste; + case EWK_CONTEXT_MENU_ITEM_TAG_SELECT_ALL: + return kWKContextMenuItemTagSelectAll; + case EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_GUESS: + return kWKContextMenuItemTagSpellingGuess; + case EWK_CONTEXT_MENU_ITEM_TAG_NO_GUESSES_FOUND: + return kWKContextMenuItemTagNoGuessesFound; + case EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_SPELLING: + return kWKContextMenuItemTagIgnoreSpelling; + case EWK_CONTEXT_MENU_ITEM_TAG_LEARN_SPELLING: + return kWKContextMenuItemTagLearnSpelling; + case EWK_CONTEXT_MENU_ITEM_TAG_OTHER: + return kWKContextMenuItemTagOther; + case EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_IN_SPOTLIGHT: + return kWKContextMenuItemTagSearchInSpotlight; + case EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_WEB: + return kWKContextMenuItemTagSearchWeb; + case EWK_CONTEXT_MENU_ITEM_TAG_LOOK_UP_IN_DICTIONARY: + return kWKContextMenuItemTagLookUpInDictionary; + case EWK_CONTEXT_MENU_ITEM_TAG_OPEN_WITH_DEFAULT_APPLICATION: + return kWKContextMenuItemTagOpenWithDefaultApplication; + case EWK_CONTEXT_MENU_ITEM_PDFACTUAL_SIZE: + return kWKContextMenuItemTagPDFActualSize; + case EWK_CONTEXT_MENU_ITEM_PDFZOOM_IN: + return kWKContextMenuItemTagPDFZoomIn; + case EWK_CONTEXT_MENU_ITEM_PDFZOOM_OUT: + return kWKContextMenuItemTagPDFZoomOut; + case EWK_CONTEXT_MENU_ITEM_PDFAUTO_SIZE: + return kWKContextMenuItemTagPDFAutoSize; + case EWK_CONTEXT_MENU_ITEM_PDFSINGLE_PAGE: + return kWKContextMenuItemTagPDFSinglePage; + case EWK_CONTEXT_MENU_ITEM_PDFFACING_PAGES: + return kWKContextMenuItemTagPDFFacingPages; + case EWK_CONTEXT_MENU_ITEM_PDFCONTINUOUS: + return kWKContextMenuItemTagPDFContinuous; + case EWK_CONTEXT_MENU_ITEM_PDFNEXT_PAGE: + return kWKContextMenuItemTagPDFNextPage; + case EWK_CONTEXT_MENU_ITEM_PDFPREVIOUS_PAGE: + return kWKContextMenuItemTagPDFPreviousPage; + case EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK: + return kWKContextMenuItemTagOpenLink; + case EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_GRAMMAR: + return kWKContextMenuItemTagIgnoreGrammar; + case EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_MENU: + return kWKContextMenuItemTagSpellingMenu; + case EWK_CONTEXT_MENU_ITEM_TAG_SHOW_SPELLING_PANEL: + return kWKContextMenuItemTagShowSpellingPanel; + case EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING: + return kWKContextMenuItemTagCheckSpelling; + case EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING_WHILE_TYPING: + return kWKContextMenuItemTagCheckSpellingWhileTyping; + case EWK_CONTEXT_MENU_ITEM_TAG_CHECK_GRAMMAR_WITH_SPELLING: + return kWKContextMenuItemTagCheckGrammarWithSpelling; + case EWK_CONTEXT_MENU_ITEM_TAG_FONT_MENU: + return kWKContextMenuItemTagFontMenu; + case EWK_CONTEXT_MENU_ITEM_TAG_SHOW_FONTS: + return kWKContextMenuItemTagShowFonts; + case EWK_CONTEXT_MENU_ITEM_TAG_BOLD: + return kWKContextMenuItemTagBold; + case EWK_CONTEXT_MENU_ITEM_TAG_ITALIC: + return kWKContextMenuItemTagItalic; + case EWK_CONTEXT_MENU_ITEM_TAG_UNDERLINE: + return kWKContextMenuItemTagUnderline; + case EWK_CONTEXT_MENU_ITEM_TAG_OUTLINE: + return kWKContextMenuItemTagOutline; + case EWK_CONTEXT_MENU_ITEM_TAG_STYLES: + return kWKContextMenuItemTagStyles; + case EWK_CONTEXT_MENU_ITEM_TAG_SHOW_COLORS: + return kWKContextMenuItemTagShowColors; + case EWK_CONTEXT_MENU_ITEM_TAG_SPEECH_MENU: + return kWKContextMenuItemTagSpeechMenu; + case EWK_CONTEXT_MENU_ITEM_TAG_START_SPEAKING: + return kWKContextMenuItemTagStartSpeaking; + case EWK_CONTEXT_MENU_ITEM_TAG_STOP_SPEAKING: + return kWKContextMenuItemTagStopSpeaking; + case EWK_CONTEXT_MENU_ITEM_TAG_WRITING_DIRECTION_MENU: + return kWKContextMenuItemTagWritingDirectionMenu; + case EWK_CONTEXT_MENU_ITEM_TAG_DEFAULT_DIRECTION: + return kWKContextMenuItemTagDefaultDirection; + case EWK_CONTEXT_MENU_ITEM_TAG_LEFT_TO_RIGHT: + return kWKContextMenuItemTagLeftToRight; + case EWK_CONTEXT_MENU_ITEM_TAG_RIGHT_TO_LEFT: + return kWKContextMenuItemTagRightToLeft; + case EWK_CONTEXT_MENU_ITEM_TAG_PDFSINGLE_PAGE_SCROLLING: + return kWKContextMenuItemTagPDFSinglePageScrolling; + case EWK_CONTEXT_MENU_ITEM_TAG_PDFFACING_PAGES_SCROLLING: + return kWKContextMenuItemTagPDFFacingPagesScrolling; + case EWK_CONTEXT_MENU_ITEM_TAG_INSPECT_ELEMENT: + return kWKContextMenuItemTagInspectElement; + case EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_MENU: + return kWKContextMenuItemTagTextDirectionMenu; + case EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_DEFAULT: + return kWKContextMenuItemTagTextDirectionDefault; + case EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_LEFT_TO_RIGHT: + return kWKContextMenuItemTagTextDirectionLeftToRight; + case EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_RIGHT_TO_LEFT: + return kWKContextMenuItemTagTextDirectionRightToLeft; + case EWK_CONTEXT_MENU_ITEM_OPEN_MEDIA_IN_NEW_WINDOW: + return kWKContextMenuItemTagOpenMediaInNewWindow; + case EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_MEDIA_TO_DISK: + return kWKContextMenuItemTagDownloadMediaToDisk; + case EWK_CONTEXT_MENU_ITEM_TAG_COPY_MEDIA_LINK_TO_CLIPBOARD: + return kWKContextMenuItemTagCopyMediaLinkToClipboard; + case EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_CONTROLS: + return kWKContextMenuItemTagToggleMediaControls; + case EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_LOOP: + return kWKContextMenuItemTagToggleMediaLoop; + case EWK_CONTEXT_MENU_ITEM_TAG_ENTER_VIDEO_FULLSCREEN: + return kWKContextMenuItemTagEnterVideoFullscreen; + case EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_PLAY_PAUSE: + return kWKContextMenuItemTagMediaPlayPause; + case EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_MUTE: + return kWKContextMenuItemTagMediaMute; + case EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG: + return kWKContextMenuItemBaseApplicationTag; + default: + return static_cast<WKContextMenuItemTag>(action); + } } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp index d57dbf62a..33d11b469 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp @@ -27,42 +27,50 @@ #include "ewk_context_menu_item.h" #include "ewk_context_menu_item_private.h" +#include "ewk_context_menu_private.h" #include "ewk_private.h" +#include <WebKit2/WKContextMenuItemTypes.h> #include <wtf/text/CString.h> -using namespace WebCore; using namespace WebKit; -EwkContextMenuItem::EwkContextMenuItem(const WebContextMenuItemData& item) - : m_type(static_cast<Ewk_Context_Menu_Item_Type>(item.type())) - , m_action(static_cast<Ewk_Context_Menu_Item_Action>(item.action())) - , m_title(item.title().utf8().data()) - , m_isChecked(item.checked()) - , m_isEnabled(item.enabled()) - , m_parentMenu(0) - , m_subMenu(0) +static Ewk_Context_Menu_Item_Action getEwkActionFromWKTag(WKContextMenuItemTag action); + +EwkContextMenuItem::EwkContextMenuItem(WKContextMenuItemRef item, EwkContextMenu* parentMenu) + : m_type(static_cast<Ewk_Context_Menu_Item_Type>(WKContextMenuItemGetType(item))) + , m_action(getEwkActionFromWKTag((WKContextMenuItemGetTag(item)))) + , m_title(WKEinaSharedString(AdoptWK, WKContextMenuItemCopyTitle(item))) + , m_isChecked(WKContextMenuItemGetChecked(item)) + , m_isEnabled(WKContextMenuItemGetEnabled(item)) + , m_parentMenu(parentMenu) { + if (WKContextMenuItemGetType(item) == kWKContextMenuItemTypeSubmenu) { + WKRetainPtr<WKArrayRef> menuItems = adoptWK(WKContextMenuCopySubmenuItems(item)); + m_subMenu = EwkContextMenu::create(m_parentMenu->ewkView(), menuItems.get()); + } } -EwkContextMenuItem::EwkContextMenuItem(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, Ewk_Context_Menu* subMenu) +EwkContextMenuItem::EwkContextMenuItem(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, PassRefPtr<EwkContextMenu> subMenu, EwkContextMenu* parentMenu) : m_type(type) , m_action(action) , m_title(title) , m_isChecked(checked) , m_isEnabled(enabled) - , m_parentMenu(0) + , m_parentMenu(parentMenu) , m_subMenu(subMenu) { } Ewk_Context_Menu_Item* ewk_context_menu_item_new(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled) { - return Ewk_Context_Menu_Item::create(type, action, title, checked, enabled, 0).leakPtr(); + return Ewk_Context_Menu_Item::create(type, action, title, checked, enabled).leakPtr(); } -Ewk_Context_Menu_Item* ewk_context_menu_item_new_with_submenu(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, Ewk_Context_Menu* subMenu) +Ewk_Context_Menu_Item* ewk_context_menu_item_new_with_submenu(Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool enabled, Ewk_Context_Menu* subMenu) { - return Ewk_Context_Menu_Item::create(type, action, title, checked, enabled, subMenu).leakPtr(); + EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, subMenu, subMenuImpl, 0); + + return Ewk_Context_Menu_Item::create(EWK_SUBMENU_TYPE, action, title, false, enabled, subMenuImpl).leakPtr(); } Ewk_Context_Menu_Item_Type ewk_context_menu_item_type_get(const Ewk_Context_Menu_Item* item) @@ -145,78 +153,170 @@ Eina_Bool ewk_context_menu_item_enabled_set(Ewk_Context_Menu_Item* item, Eina_Bo return true; } -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION, WebCore::ContextMenuItemTagNoAction); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK_IN_NEW_WINDOW, WebCore::ContextMenuItemTagOpenLinkInNewWindow); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_LINK_TO_DISK, WebCore::ContextMenuItemTagDownloadLinkToDisk); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_COPY_LINK_TO_CLIPBOARD, WebCore::ContextMenuItemTagCopyLinkToClipboard); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OPEN_IMAGE_IN_NEW_WINDOW, WebCore::ContextMenuItemTagOpenImageInNewWindow); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_IMAGE_TO_DISK, WebCore::ContextMenuItemTagDownloadImageToDisk); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_TO_CLIPBOARD, WebCore::ContextMenuItemTagCopyImageToClipboard); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_URL_TO_CLIPBOARD, WebCore::ContextMenuItemTagCopyImageUrlToClipboard); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OPEN_FRAME_IN_NEW_WINDOW, WebCore::ContextMenuItemTagOpenFrameInNewWindow); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_COPY, WebCore::ContextMenuItemTagCopy); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_GO_BACK, WebCore::ContextMenuItemTagGoBack); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_GO_FORWARD, WebCore::ContextMenuItemTagGoForward); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_STOP, WebCore::ContextMenuItemTagStop); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_RELOAD, WebCore::ContextMenuItemTagReload); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_CUT, WebCore::ContextMenuItemTagCut); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_PASTE, WebCore::ContextMenuItemTagPaste); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SELECT_ALL, WebCore::ContextMenuItemTagSelectAll); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_GUESS, WebCore::ContextMenuItemTagSpellingGuess); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_NO_GUESSES_FOUND, WebCore::ContextMenuItemTagNoGuessesFound); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_SPELLING, WebCore::ContextMenuItemTagIgnoreSpelling); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_LEARN_SPELLING, WebCore::ContextMenuItemTagLearnSpelling); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OTHER, WebCore::ContextMenuItemTagOther); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_IN_SPOTLIGHT, WebCore::ContextMenuItemTagSearchInSpotlight); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_WEB, WebCore::ContextMenuItemTagSearchWeb); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_LOOK_UP_IN_DICTIONARY, WebCore::ContextMenuItemTagLookUpInDictionary); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OPEN_WITH_DEFAULT_APPLICATION, WebCore::ContextMenuItemTagOpenWithDefaultApplication); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFACTUAL_SIZE, WebCore::ContextMenuItemPDFActualSize); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFZOOM_IN, WebCore::ContextMenuItemPDFZoomIn); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFZOOM_OUT, WebCore::ContextMenuItemPDFZoomOut); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFAUTO_SIZE, WebCore::ContextMenuItemPDFAutoSize); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFSINGLE_PAGE, WebCore::ContextMenuItemPDFSinglePage); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFFACING_PAGES, WebCore::ContextMenuItemPDFFacingPages); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFCONTINUOUS, WebCore::ContextMenuItemPDFContinuous); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFNEXT_PAGE, WebCore::ContextMenuItemPDFNextPage); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_PDFPREVIOUS_PAGE, WebCore::ContextMenuItemPDFPreviousPage); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK, WebCore::ContextMenuItemTagOpenLink); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_GRAMMAR, WebCore::ContextMenuItemTagIgnoreGrammar); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_MENU, WebCore::ContextMenuItemTagSpellingMenu); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SHOW_SPELLING_PANEL, WebCore::ContextMenuItemTagShowSpellingPanel); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING, WebCore::ContextMenuItemTagCheckSpelling); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING_WHILE_TYPING, WebCore::ContextMenuItemTagCheckSpellingWhileTyping); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_CHECK_GRAMMAR_WITH_SPELLING, WebCore::ContextMenuItemTagCheckGrammarWithSpelling); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_FONT_MENU, WebCore::ContextMenuItemTagFontMenu); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SHOW_FONTS, WebCore::ContextMenuItemTagShowFonts); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_BOLD, WebCore::ContextMenuItemTagBold); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_ITALIC, WebCore::ContextMenuItemTagItalic); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_UNDERLINE, WebCore::ContextMenuItemTagUnderline); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_OUTLINE, WebCore::ContextMenuItemTagOutline); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_STYLES, WebCore::ContextMenuItemTagStyles); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SHOW_COLORS, WebCore::ContextMenuItemTagShowColors); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_SPEECH_MENU, WebCore::ContextMenuItemTagSpeechMenu); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_START_SPEAKING, WebCore::ContextMenuItemTagStartSpeaking); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_STOP_SPEAKING, WebCore::ContextMenuItemTagStopSpeaking); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_WRITING_DIRECTION_MENU, WebCore::ContextMenuItemTagWritingDirectionMenu); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_DEFAULT_DIRECTION, WebCore::ContextMenuItemTagDefaultDirection); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_LEFT_TO_RIGHT, WebCore::ContextMenuItemTagLeftToRight); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_RIGHT_TO_LEFT, WebCore::ContextMenuItemTagRightToLeft); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_PDFSINGLE_PAGE_SCROLLING, WebCore::ContextMenuItemTagPDFSinglePageScrolling); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_PDFFACING_PAGES_SCROLLING, WebCore::ContextMenuItemTagPDFFacingPagesScrolling); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_INSPECT_ELEMENT, WebCore::ContextMenuItemTagInspectElement); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_MENU, WebCore::ContextMenuItemTagTextDirectionMenu); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_DEFAULT, WebCore::ContextMenuItemTagTextDirectionDefault); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_LEFT_TO_RIGHT, WebCore::ContextMenuItemTagTextDirectionLeftToRight); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_RIGHT_TO_LEFT, WebCore::ContextMenuItemTagTextDirectionRightToLeft); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_OPEN_MEDIA_IN_NEW_WINDOW, WebCore::ContextMenuItemTagOpenMediaInNewWindow); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_COPY_MEDIA_LINK_TO_CLIPBOARD, WebCore::ContextMenuItemTagCopyMediaLinkToClipboard); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_CONTROLS, WebCore::ContextMenuItemTagToggleMediaControls); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_LOOP, WebCore::ContextMenuItemTagToggleMediaLoop); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_ENTER_VIDEO_FULLSCREEN, WebCore::ContextMenuItemTagEnterVideoFullscreen); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_PLAY_PAUSE, WebCore::ContextMenuItemTagMediaPlayPause); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_MUTE, WebCore::ContextMenuItemTagMediaMute); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_BASE_CUSTOM_TAG, WebCore::ContextMenuItemBaseCustomTag); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_CUSTOM_TAG_NO_ACTION, WebCore::ContextMenuItemCustomTagNoAction); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_LAST_CUSTOM_TAG, WebCore::ContextMenuItemLastCustomTag); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG, WebCore::ContextMenuItemBaseApplicationTag); +Ewk_Context_Menu* ewk_context_menu_item_parent_menu_get(const Ewk_Context_Menu_Item* item) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(item, 0); + + return item->parentMenu(); +} + +Ewk_Context_Menu* ewk_context_menu_item_submenu_get(const Ewk_Context_Menu_Item* item) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(item, 0); + + return item->subMenu(); +} + +static Ewk_Context_Menu_Item_Action getEwkActionFromWKTag(WKContextMenuItemTag action) +{ + switch (action) { + case kWKContextMenuItemTagNoAction: + return EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION; + case kWKContextMenuItemTagOpenLinkInNewWindow: + return EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK_IN_NEW_WINDOW; + case kWKContextMenuItemTagDownloadLinkToDisk: + return EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_LINK_TO_DISK; + case kWKContextMenuItemTagCopyLinkToClipboard: + return EWK_CONTEXT_MENU_ITEM_TAG_COPY_LINK_TO_CLIPBOARD; + case kWKContextMenuItemTagOpenImageInNewWindow: + return EWK_CONTEXT_MENU_ITEM_TAG_OPEN_IMAGE_IN_NEW_WINDOW; + case kWKContextMenuItemTagDownloadImageToDisk: + return EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_IMAGE_TO_DISK; + case kWKContextMenuItemTagCopyImageToClipboard: + return EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_TO_CLIPBOARD; + case kWKContextMenuItemTagCopyImageUrlToClipboard: + return EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_URL_TO_CLIPBOARD; + case kWKContextMenuItemTagOpenFrameInNewWindow: + return EWK_CONTEXT_MENU_ITEM_TAG_OPEN_FRAME_IN_NEW_WINDOW; + case kWKContextMenuItemTagCopy: + return EWK_CONTEXT_MENU_ITEM_TAG_COPY; + case kWKContextMenuItemTagGoBack: + return EWK_CONTEXT_MENU_ITEM_TAG_GO_BACK; + case kWKContextMenuItemTagGoForward: + return EWK_CONTEXT_MENU_ITEM_TAG_GO_FORWARD; + case kWKContextMenuItemTagStop: + return EWK_CONTEXT_MENU_ITEM_TAG_STOP; + case kWKContextMenuItemTagReload: + return EWK_CONTEXT_MENU_ITEM_TAG_RELOAD; + case kWKContextMenuItemTagCut: + return EWK_CONTEXT_MENU_ITEM_TAG_CUT; + case kWKContextMenuItemTagPaste: + return EWK_CONTEXT_MENU_ITEM_TAG_PASTE; + case kWKContextMenuItemTagSelectAll: + return EWK_CONTEXT_MENU_ITEM_TAG_SELECT_ALL; + case kWKContextMenuItemTagSpellingGuess: + return EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_GUESS; + case kWKContextMenuItemTagNoGuessesFound: + return EWK_CONTEXT_MENU_ITEM_TAG_NO_GUESSES_FOUND; + case kWKContextMenuItemTagIgnoreSpelling: + return EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_SPELLING; + case kWKContextMenuItemTagLearnSpelling: + return EWK_CONTEXT_MENU_ITEM_TAG_LEARN_SPELLING; + case kWKContextMenuItemTagOther: + return EWK_CONTEXT_MENU_ITEM_TAG_OTHER; + case kWKContextMenuItemTagSearchInSpotlight: + return EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_IN_SPOTLIGHT; + case kWKContextMenuItemTagSearchWeb: + return EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_WEB; + case kWKContextMenuItemTagLookUpInDictionary: + return EWK_CONTEXT_MENU_ITEM_TAG_LOOK_UP_IN_DICTIONARY; + case kWKContextMenuItemTagOpenWithDefaultApplication: + return EWK_CONTEXT_MENU_ITEM_TAG_OPEN_WITH_DEFAULT_APPLICATION; + case kWKContextMenuItemTagPDFActualSize: + return EWK_CONTEXT_MENU_ITEM_PDFACTUAL_SIZE; + case kWKContextMenuItemTagPDFZoomIn: + return EWK_CONTEXT_MENU_ITEM_PDFZOOM_IN; + case kWKContextMenuItemTagPDFZoomOut: + return EWK_CONTEXT_MENU_ITEM_PDFZOOM_OUT; + case kWKContextMenuItemTagPDFAutoSize: + return EWK_CONTEXT_MENU_ITEM_PDFAUTO_SIZE; + case kWKContextMenuItemTagPDFSinglePage: + return EWK_CONTEXT_MENU_ITEM_PDFSINGLE_PAGE; + case kWKContextMenuItemTagPDFFacingPages: + return EWK_CONTEXT_MENU_ITEM_PDFFACING_PAGES; + case kWKContextMenuItemTagPDFContinuous: + return EWK_CONTEXT_MENU_ITEM_PDFCONTINUOUS; + case kWKContextMenuItemTagPDFNextPage: + return EWK_CONTEXT_MENU_ITEM_PDFNEXT_PAGE; + case kWKContextMenuItemTagPDFPreviousPage: + return EWK_CONTEXT_MENU_ITEM_PDFPREVIOUS_PAGE; + case kWKContextMenuItemTagOpenLink: + return EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK; + case kWKContextMenuItemTagIgnoreGrammar: + return EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_GRAMMAR; + case kWKContextMenuItemTagSpellingMenu: + return EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_MENU; + case kWKContextMenuItemTagShowSpellingPanel: + return EWK_CONTEXT_MENU_ITEM_TAG_SHOW_SPELLING_PANEL; + case kWKContextMenuItemTagCheckSpelling: + return EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING; + case kWKContextMenuItemTagCheckSpellingWhileTyping: + return EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING_WHILE_TYPING; + case kWKContextMenuItemTagCheckGrammarWithSpelling: + return EWK_CONTEXT_MENU_ITEM_TAG_CHECK_GRAMMAR_WITH_SPELLING; + case kWKContextMenuItemTagFontMenu: + return EWK_CONTEXT_MENU_ITEM_TAG_FONT_MENU; + case kWKContextMenuItemTagShowFonts: + return EWK_CONTEXT_MENU_ITEM_TAG_SHOW_FONTS; + case kWKContextMenuItemTagBold: + return EWK_CONTEXT_MENU_ITEM_TAG_BOLD; + case kWKContextMenuItemTagItalic: + return EWK_CONTEXT_MENU_ITEM_TAG_ITALIC; + case kWKContextMenuItemTagUnderline: + return EWK_CONTEXT_MENU_ITEM_TAG_UNDERLINE; + case kWKContextMenuItemTagOutline: + return EWK_CONTEXT_MENU_ITEM_TAG_OUTLINE; + case kWKContextMenuItemTagStyles: + return EWK_CONTEXT_MENU_ITEM_TAG_STYLES; + case kWKContextMenuItemTagShowColors: + return EWK_CONTEXT_MENU_ITEM_TAG_SHOW_COLORS; + case kWKContextMenuItemTagSpeechMenu: + return EWK_CONTEXT_MENU_ITEM_TAG_SPEECH_MENU; + case kWKContextMenuItemTagStartSpeaking: + return EWK_CONTEXT_MENU_ITEM_TAG_START_SPEAKING; + case kWKContextMenuItemTagStopSpeaking: + return EWK_CONTEXT_MENU_ITEM_TAG_STOP_SPEAKING; + case kWKContextMenuItemTagWritingDirectionMenu: + return EWK_CONTEXT_MENU_ITEM_TAG_WRITING_DIRECTION_MENU; + case kWKContextMenuItemTagDefaultDirection: + return EWK_CONTEXT_MENU_ITEM_TAG_DEFAULT_DIRECTION; + case kWKContextMenuItemTagLeftToRight: + return EWK_CONTEXT_MENU_ITEM_TAG_LEFT_TO_RIGHT; + case kWKContextMenuItemTagRightToLeft: + return EWK_CONTEXT_MENU_ITEM_TAG_RIGHT_TO_LEFT; + case kWKContextMenuItemTagPDFSinglePageScrolling: + return EWK_CONTEXT_MENU_ITEM_TAG_PDFSINGLE_PAGE_SCROLLING; + case kWKContextMenuItemTagPDFFacingPagesScrolling: + return EWK_CONTEXT_MENU_ITEM_TAG_PDFFACING_PAGES_SCROLLING; + case kWKContextMenuItemTagInspectElement: + return EWK_CONTEXT_MENU_ITEM_TAG_INSPECT_ELEMENT; + case kWKContextMenuItemTagTextDirectionMenu: + return EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_MENU; + case kWKContextMenuItemTagTextDirectionDefault: + return EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_DEFAULT; + case kWKContextMenuItemTagTextDirectionLeftToRight: + return EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_LEFT_TO_RIGHT; + case kWKContextMenuItemTagTextDirectionRightToLeft: + return EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_RIGHT_TO_LEFT; + case kWKContextMenuItemTagOpenMediaInNewWindow: + return EWK_CONTEXT_MENU_ITEM_OPEN_MEDIA_IN_NEW_WINDOW; + case kWKContextMenuItemTagDownloadMediaToDisk: + return EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_MEDIA_TO_DISK; + case kWKContextMenuItemTagCopyMediaLinkToClipboard: + return EWK_CONTEXT_MENU_ITEM_TAG_COPY_MEDIA_LINK_TO_CLIPBOARD; + case kWKContextMenuItemTagToggleMediaControls: + return EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_CONTROLS; + case kWKContextMenuItemTagToggleMediaLoop: + return EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_LOOP; + case kWKContextMenuItemTagEnterVideoFullscreen: + return EWK_CONTEXT_MENU_ITEM_TAG_ENTER_VIDEO_FULLSCREEN; + case kWKContextMenuItemTagMediaPlayPause: + return EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_PLAY_PAUSE; + case kWKContextMenuItemTagMediaMute: + return EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_MUTE; + case kWKContextMenuItemBaseApplicationTag: + return EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG; + default: + return static_cast<Ewk_Context_Menu_Item_Action>(action); + } +} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.h b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.h index 9612a21f5..d9f74f9af 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.h @@ -41,7 +41,7 @@ extern "C" { /** * \enum Ewk_Context_Menu_Item_Type * @brief Defines the types of the items for the context menu. - * @info Keep this in sync with ContextMenuItem.h + * @info Keep this in sync with WKContextMenuItemTypes.h */ typedef enum { EWK_ACTION_TYPE, @@ -53,7 +53,6 @@ typedef enum { /** * \enum Ewk_Context_Menu_Action * @brief Provides the actions of items for the context menu. - * @info Keep this in sync with ContextMenuItem.h */ typedef enum { EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION, @@ -121,15 +120,13 @@ typedef enum { EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_LEFT_TO_RIGHT, EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_RIGHT_TO_LEFT, EWK_CONTEXT_MENU_ITEM_OPEN_MEDIA_IN_NEW_WINDOW, + EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_MEDIA_TO_DISK, EWK_CONTEXT_MENU_ITEM_TAG_COPY_MEDIA_LINK_TO_CLIPBOARD, EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_CONTROLS, EWK_CONTEXT_MENU_ITEM_TAG_TOGGLE_MEDIA_LOOP, EWK_CONTEXT_MENU_ITEM_TAG_ENTER_VIDEO_FULLSCREEN, EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_PLAY_PAUSE, EWK_CONTEXT_MENU_ITEM_TAG_MEDIA_MUTE, - EWK_CONTEXT_MENU_ITEM_BASE_CUSTOM_TAG = 5000, - EWK_CONTEXT_MENU_ITEM_CUSTOM_TAG_NO_ACTION = 5998, - EWK_CONTEXT_MENU_ITEM_LAST_CUSTOM_TAG = 5999, EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG = 10000 } Ewk_Context_Menu_Item_Action; @@ -148,19 +145,17 @@ typedef enum { EAPI Ewk_Context_Menu_Item *ewk_context_menu_item_new(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char *title, Eina_Bool checked, Eina_Bool enabled); /** - * Creates a new item of the context menu. + * Creates a new sub menu type item of the context menu. * - * @param type specifies a type of the item * @param action specifies a action of the item * @param title specifies a title of the item - * @param checked @c EINA_TRUE if the item should be toggled or @c EINA_FALSE if not * @param enabled @c EINA_TRUE to enable the item or @c EINA_FALSE to disable * @param submenu specifies a submenu of the item * @return the pointer to the new item * * @see ewk_context_menu_item_new */ -EAPI Ewk_Context_Menu_Item *ewk_context_menu_item_new_with_submenu(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char *title, Eina_Bool checked, Eina_Bool enabled, Ewk_Context_Menu *submenu); +EAPI Ewk_Context_Menu_Item *ewk_context_menu_item_new_with_submenu(Ewk_Context_Menu_Item_Action action, const char *title, Eina_Bool enabled, Ewk_Context_Menu *submenu); /** * Gets type of the item. @@ -263,6 +258,24 @@ EAPI Eina_Bool ewk_context_menu_item_enabled_get(const Ewk_Context_Menu_Item *o) */ EAPI Eina_Bool ewk_context_menu_item_enabled_set(Ewk_Context_Menu_Item *o, Eina_Bool enabled); +/** + * Gets the parent menu for the item. + * + * @param o item to get the parent + * + * @return the pointer to parent menu on success or @c NULL on failure + */ +EAPI Ewk_Context_Menu *ewk_context_menu_item_parent_menu_get(const Ewk_Context_Menu_Item *o); + +/** + * Gets the submenu for the item. + * + * @param o item to get the submenu + * + * @return the pointer to submenu on success or @c NULL on failure + */ +EAPI Ewk_Context_Menu *ewk_context_menu_item_submenu_get(const Ewk_Context_Menu_Item *o); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item_private.h index 62f2790b2..22158ec2f 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item_private.h @@ -26,11 +26,14 @@ #ifndef ewk_context_menu_item_private_h #define ewk_context_menu_item_private_h +#include "WKContextMenuItem.h" #include "WKEinaSharedString.h" -#include "WebContextMenuItemData.h" #include "ewk_context_menu.h" #include "ewk_context_menu_item.h" +#include "ewk_context_menu_private.h" #include <wtf/PassOwnPtr.h> +#include <wtf/PassRefPtr.h> +#include <wtf/RefPtr.h> /** * \struct Ewk_Context_Menu_Item @@ -38,14 +41,14 @@ */ class EwkContextMenuItem { public: - static PassOwnPtr<EwkContextMenuItem> create(const WebKit::WebContextMenuItemData& item) + static PassOwnPtr<EwkContextMenuItem> create(WKContextMenuItemRef item, EwkContextMenu* parentMenu) { - return adoptPtr(new EwkContextMenuItem(item)); + return adoptPtr(new EwkContextMenuItem(item, parentMenu)); } - static PassOwnPtr<EwkContextMenuItem> create(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, EwkContextMenu* subMenu) + static PassOwnPtr<EwkContextMenuItem> create(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, PassRefPtr<EwkContextMenu> subMenu = 0, EwkContextMenu* parentMenu = 0) { - return adoptPtr(new EwkContextMenuItem(type, action, title, checked, enabled, subMenu)); + return adoptPtr(new EwkContextMenuItem(type, action, title, checked, enabled, subMenu, parentMenu)); } Ewk_Context_Menu_Item_Action action() const { return m_action; } @@ -63,9 +66,14 @@ public: bool enabled() const { return m_isEnabled; } void setEnabled(bool enabled) { m_isEnabled = enabled; } + EwkContextMenu* parentMenu() const { return m_parentMenu; } + void setParentMenu(EwkContextMenu* parentMenu) { m_parentMenu = parentMenu; } + + EwkContextMenu* subMenu() const { return m_subMenu.get(); } + private: - explicit EwkContextMenuItem(const WebKit::WebContextMenuItemData&); - EwkContextMenuItem(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, EwkContextMenu* subMenu); + EwkContextMenuItem(WKContextMenuItemRef, EwkContextMenu* parentMenu); + EwkContextMenuItem(Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled, PassRefPtr<EwkContextMenu> subMenu, EwkContextMenu* parentMenu); Ewk_Context_Menu_Item_Type m_type; Ewk_Context_Menu_Item_Action m_action; @@ -75,8 +83,8 @@ private: bool m_isChecked; bool m_isEnabled; - Ewk_Context_Menu* m_parentMenu; - Ewk_Context_Menu* m_subMenu; + EwkContextMenu* m_parentMenu; + RefPtr<EwkContextMenu> m_subMenu; }; #endif // ewk_context_menu_item_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_private.h index 29f5c90ac..2a3c9a21d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_private.h @@ -26,34 +26,30 @@ #ifndef ewk_context_menu_private_h #define ewk_context_menu_private_h -#include "WebContextMenuItemData.h" #include "ewk_context_menu_item.h" +#include "ewk_object_private.h" #include <Eina.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> +#include <wtf/PassRefPtr.h> -namespace WebKit { -class WebContextMenuItemData; -class WebContextMenuProxyEfl; -} +class EwkView; -class EwkViewImpl; - -class EwkContextMenu { +class EwkContextMenu : public EwkObject { public: - static PassOwnPtr<EwkContextMenu> create(EwkViewImpl* viewImpl, WebKit::WebContextMenuProxyEfl* contextMenuProxy, const Vector<WebKit::WebContextMenuItemData>& items) + EWK_OBJECT_DECLARE(EwkContextMenu) + + static PassRefPtr<EwkContextMenu> create(EwkView* viewImpl, WKArrayRef items) { - return adoptPtr(new EwkContextMenu(viewImpl, contextMenuProxy, items)); + return adoptRef(new EwkContextMenu(viewImpl, items)); } - static PassOwnPtr<EwkContextMenu> create() + static PassRefPtr<EwkContextMenu> create() { - return adoptPtr(new EwkContextMenu()); + return adoptRef(new EwkContextMenu()); } - static PassOwnPtr<EwkContextMenu> create(Eina_List* items) + static PassRefPtr<EwkContextMenu> create(Eina_List* items) { - return adoptPtr(new EwkContextMenu(items)); + return adoptRef(new EwkContextMenu(items)); } ~EwkContextMenu(); @@ -63,15 +59,17 @@ public: void removeItem(EwkContextMenuItem*); const Eina_List* items() const { return m_contextMenuItems; } - void contextMenuItemSelected(const WebKit::WebContextMenuItemData& item); + bool contextMenuItemSelected(WKContextMenuItemRef item); + + EwkView* ewkView() const { return m_viewImpl; } + void setEwkView(EwkView* ewkView) { m_viewImpl = ewkView; } private: EwkContextMenu(); EwkContextMenu(Eina_List* items); - EwkContextMenu(EwkViewImpl* viewImpl, WebKit::WebContextMenuProxyEfl*, const Vector<WebKit::WebContextMenuItemData>& items); + EwkContextMenu(EwkView* viewImpl, WKArrayRef items); - EwkViewImpl* m_viewImpl; - WebKit::WebContextMenuProxyEfl* m_contextMenuProxy; + EwkView* m_viewImpl; Eina_List* m_contextMenuItems; }; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h index cb52a92b0..db1980957 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h @@ -20,12 +20,13 @@ #ifndef ewk_context_private_h #define ewk_context_private_h -#include "DownloadManagerEfl.h" -#include "WKAPICast.h" -#include "WKRetainPtr.h" -#include "WebContext.h" #include "ewk_context.h" #include "ewk_object_private.h" +#include <WebKit2/WKBase.h> +#include <WebKit2/WKRetainPtr.h> +#include <wtf/PassOwnPtr.h> +#include <wtf/RefPtr.h> +#include <wtf/text/WTFString.h> using namespace WebKit; @@ -34,6 +35,7 @@ class EwkFaviconDatabase; namespace WebKit { class ContextHistoryClientEfl; +class DownloadManagerEfl; class RequestManagerClientEfl; #if ENABLE(BATTERY_STATUS) class BatteryProvider; @@ -47,22 +49,22 @@ class EwkContext : public EwkObject { public: EWK_OBJECT_DECLARE(EwkContext) - static PassRefPtr<EwkContext> create(PassRefPtr<WebContext> context); + static PassRefPtr<EwkContext> findOrCreateWrapper(WKContextRef context); static PassRefPtr<EwkContext> create(); static PassRefPtr<EwkContext> create(const String& injectedBundlePath); - static PassRefPtr<EwkContext> defaultContext(); + static EwkContext* defaultContext(); ~EwkContext(); - Ewk_Cookie_Manager* cookieManager(); + EwkCookieManager* cookieManager(); - Ewk_Database_Manager* databaseManager(); + EwkDatabaseManager* databaseManager(); bool setFaviconDatabaseDirectoryPath(const String& databaseDirectory); - Ewk_Favicon_Database* faviconDatabase(); + EwkFaviconDatabase* faviconDatabase(); - Ewk_Storage_Manager* storageManager() const; + EwkStorageManager* storageManager() const; WebKit::RequestManagerClientEfl* requestManager(); @@ -72,7 +74,7 @@ public: Ewk_Cache_Model cacheModel() const; - PassRefPtr<WebContext> webContext() { return m_context; } + WKContextRef wkContext() const { return m_context.get(); } WebKit::DownloadManagerEfl* downloadManager() const; @@ -82,17 +84,19 @@ public: void setAdditionalPluginPath(const String&); #endif + void clearResourceCache(); + private: - explicit EwkContext(PassRefPtr<WebContext>); + explicit EwkContext(WKContextRef); void ensureFaviconDatabase(); - RefPtr<WebContext> m_context; + WKRetainPtr<WKContextRef> m_context; - OwnPtr<Ewk_Cookie_Manager> m_cookieManager; - OwnPtr<Ewk_Database_Manager> m_databaseManager; - OwnPtr<Ewk_Favicon_Database> m_faviconDatabase; - OwnPtr<Ewk_Storage_Manager> m_storageManager; + OwnPtr<EwkCookieManager> m_cookieManager; + OwnPtr<EwkDatabaseManager> m_databaseManager; + OwnPtr<EwkFaviconDatabase> m_faviconDatabase; + OwnPtr<EwkStorageManager> m_storageManager; #if ENABLE(BATTERY_STATUS) RefPtr<WebKit::BatteryProvider> m_batteryProvider; #endif diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp index 831d3bb01..475dca78e 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp @@ -28,59 +28,61 @@ #include "WKAPICast.h" #include "WKArray.h" +#include "WKCookieManagerSoup.h" #include "WKString.h" -#include "WebCookieManagerProxy.h" #include "ewk_cookie_manager_private.h" #include "ewk_error_private.h" #include "ewk_private.h" #include <wtf/OwnPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> using namespace WebKit; -EwkCookieManager::EwkCookieManager(WKCookieManagerRef cookieManagerRef) - : m_wkCookieManager(cookieManagerRef) +EwkCookieManager::EwkCookieManager(WKCookieManagerRef cookieManager) + : m_cookieManager(cookieManager) { + ASSERT(m_cookieManager); + WKCookieManagerClient wkCookieManagerClient = { kWKCookieManagerClientCurrentVersion, this, // clientInfo cookiesDidChange }; - WKCookieManagerSetClient(m_wkCookieManager.get(), &wkCookieManagerClient); + WKCookieManagerSetClient(m_cookieManager.get(), &wkCookieManagerClient); } EwkCookieManager::~EwkCookieManager() { if (isWatchingForChanges()) - WKCookieManagerStopObservingCookieChanges(m_wkCookieManager.get()); + WKCookieManagerStopObservingCookieChanges(m_cookieManager.get()); } -void EwkCookieManager::setPersistentStorage(const String& filename, SoupCookiePersistentStorageType storage) +void EwkCookieManager::setPersistentStorage(const char* filename, WKCookieStorageType storageType) { bool isWatchingChanges = isWatchingForChanges(); if (isWatchingChanges) - WKCookieManagerStopObservingCookieChanges(m_wkCookieManager.get()); + WKCookieManagerStopObservingCookieChanges(m_cookieManager.get()); - toImpl(m_wkCookieManager.get())->setCookiePersistentStorage(filename, storage); + WKRetainPtr<WKStringRef> wkFilename(AdoptWK, WKStringCreateWithUTF8CString(filename)); + WKCookieManagerSetCookiePersistentStorage(m_cookieManager.get(), wkFilename.get(), storageType); if (isWatchingChanges) - WKCookieManagerStartObservingCookieChanges(m_wkCookieManager.get()); + WKCookieManagerStartObservingCookieChanges(m_cookieManager.get()); } void EwkCookieManager::setHTTPAcceptPolicy(WKHTTPCookieAcceptPolicy policy) { - WKCookieManagerSetHTTPCookieAcceptPolicy(m_wkCookieManager.get(), policy); + WKCookieManagerSetHTTPCookieAcceptPolicy(m_cookieManager.get(), policy); } -void EwkCookieManager::clearHostnameCookies(const String& hostname) +void EwkCookieManager::clearHostnameCookies(const char* hostname) { - toImpl(m_wkCookieManager.get())->deleteCookiesForHostname(hostname); + WKRetainPtr<WKStringRef> wkHostname(AdoptWK, WKStringCreateWithUTF8CString(hostname)); + WKCookieManagerDeleteCookiesForHostname(m_cookieManager.get(), wkHostname.get()); } void EwkCookieManager::clearAllCookies() { - WKCookieManagerDeleteAllCookies(m_wkCookieManager.get()); + WKCookieManagerDeleteAllCookies(m_cookieManager.get()); } void EwkCookieManager::watchChanges(const Cookie_Change_Handler& changeHandler) @@ -88,9 +90,9 @@ void EwkCookieManager::watchChanges(const Cookie_Change_Handler& changeHandler) m_changeHandler = changeHandler; if (changeHandler.callback) - WKCookieManagerStartObservingCookieChanges(m_wkCookieManager.get()); + WKCookieManagerStartObservingCookieChanges(m_cookieManager.get()); else - WKCookieManagerStopObservingCookieChanges(m_wkCookieManager.get()); + WKCookieManagerStopObservingCookieChanges(m_cookieManager.get()); } bool EwkCookieManager::isWatchingForChanges() const @@ -100,17 +102,17 @@ bool EwkCookieManager::isWatchingForChanges() const void EwkCookieManager::getHostNamesWithCookies(WKCookieManagerGetCookieHostnamesFunction callback, void* userData) const { - WKCookieManagerGetHostnamesWithCookies(m_wkCookieManager.get(), userData, callback); + WKCookieManagerGetHostnamesWithCookies(m_cookieManager.get(), userData, callback); } void EwkCookieManager::getHTTPAcceptPolicy(WKCookieManagerGetHTTPCookieAcceptPolicyFunction callback, void* userData) const { - WKCookieManagerGetHTTPCookieAcceptPolicy(m_wkCookieManager.get(), userData, callback); + WKCookieManagerGetHTTPCookieAcceptPolicy(m_cookieManager.get(), userData, callback); } void EwkCookieManager::cookiesDidChange(WKCookieManagerRef, const void* clientInfo) { - Ewk_Cookie_Manager* manager = static_cast<Ewk_Cookie_Manager*>(const_cast<void*>(clientInfo)); + EwkCookieManager* manager = static_cast<EwkCookieManager*>(const_cast<void*>(clientInfo)); if (!manager->isWatchingForChanges()) return; @@ -119,15 +121,15 @@ void EwkCookieManager::cookiesDidChange(WKCookieManagerRef, const void* clientIn } // Ewk_Cookie_Persistent_Storage enum validation. -COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_PERSISTENT_STORAGE_TEXT, SoupCookiePersistentStorageText); -COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_PERSISTENT_STORAGE_SQLITE, SoupCookiePersistentStorageSQLite); +COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_PERSISTENT_STORAGE_TEXT, kWKCookieStorageTypeText); +COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_PERSISTENT_STORAGE_SQLITE, kWKCookieStorageTypeSQLite); void ewk_cookie_manager_persistent_storage_set(Ewk_Cookie_Manager* manager, const char* filename, Ewk_Cookie_Persistent_Storage storage) { EINA_SAFETY_ON_NULL_RETURN(manager); EINA_SAFETY_ON_NULL_RETURN(filename); - manager->setPersistentStorage(String::fromUTF8(filename), static_cast<SoupCookiePersistentStorageType>(storage)); + manager->setPersistentStorage(filename, static_cast<WKCookieStorageType>(storage)); } // Ewk_Cookie_Accept_Policy enum validation. @@ -155,7 +157,7 @@ struct Get_Policy_Async_Data { static void getAcceptPolicyCallback(WKHTTPCookieAcceptPolicy policy, WKErrorRef wkError, void* data) { Get_Policy_Async_Data* callbackData = static_cast<Get_Policy_Async_Data*>(data); - OwnPtr<Ewk_Error> ewkError = Ewk_Error::create(wkError); + OwnPtr<EwkError> ewkError = EwkError::create(wkError); callbackData->callback(static_cast<Ewk_Cookie_Accept_Policy>(policy), ewkError.get(), callbackData->userData); @@ -185,15 +187,14 @@ static void getHostnamesWithCookiesCallback(WKArrayRef wkHostnames, WKErrorRef w { Eina_List* hostnames = 0; Get_Hostnames_Async_Data* callbackData = static_cast<Get_Hostnames_Async_Data*>(context); - OwnPtr<Ewk_Error> ewkError = Ewk_Error::create(wkError); + OwnPtr<EwkError> ewkError = EwkError::create(wkError); const size_t hostnameCount = WKArrayGetSize(wkHostnames); for (size_t i = 0; i < hostnameCount; ++i) { WKStringRef wkHostname = static_cast<WKStringRef>(WKArrayGetItemAtIndex(wkHostnames, i)); - String hostname = toImpl(wkHostname)->string(); - if (hostname.isEmpty()) + if (WKStringIsEmpty(wkHostname)) continue; - hostnames = eina_list_append(hostnames, eina_stringshare_add(hostname.utf8().data())); + hostnames = eina_list_append(hostnames, WKEinaSharedString(wkHostname).leakString()); } callbackData->callback(hostnames, ewkError.get(), callbackData->userData); @@ -219,7 +220,7 @@ void ewk_cookie_manager_hostname_cookies_clear(Ewk_Cookie_Manager* manager, cons EINA_SAFETY_ON_NULL_RETURN(manager); EINA_SAFETY_ON_NULL_RETURN(hostname); - manager->clearHostnameCookies(String::fromUTF8(hostname)); + manager->clearHostnameCookies(hostname); } void ewk_cookie_manager_cookies_clear(Ewk_Cookie_Manager* manager) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h index 5de30606b..d478936df 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h @@ -26,8 +26,8 @@ #ifndef ewk_cookie_manager_private_h #define ewk_cookie_manager_private_h -#include "SoupCookiePersistentStorageType.h" #include "WKCookieManager.h" +#include "WKCookieManagerSoup.h" #include "WKRetainPtr.h" #include "ewk_cookie_manager.h" #include <WebKit2/WKBase.h> @@ -50,32 +50,32 @@ struct Cookie_Change_Handler { class EwkCookieManager { public: - static PassOwnPtr<EwkCookieManager> create(WKCookieManagerRef cookieManagerRef) + static PassOwnPtr<EwkCookieManager> create(WKCookieManagerRef cookieManager) { - return adoptPtr(new Ewk_Cookie_Manager(cookieManagerRef)); + return adoptPtr(new EwkCookieManager(cookieManager)); } ~EwkCookieManager(); - void setPersistentStorage(const String& filename, WebKit::SoupCookiePersistentStorageType storage); + void setPersistentStorage(const char* filename, WKCookieStorageType); void getHTTPAcceptPolicy(WKCookieManagerGetHTTPCookieAcceptPolicyFunction callback, void* userData) const; void setHTTPAcceptPolicy(WKHTTPCookieAcceptPolicy policy); - void clearHostnameCookies(const String& hostname); + void clearHostnameCookies(const char* hostname); void clearAllCookies(); void getHostNamesWithCookies(WKCookieManagerGetCookieHostnamesFunction callback, void* userData) const; void watchChanges(const Cookie_Change_Handler& changeHandler); private: - explicit EwkCookieManager(WKCookieManagerRef cookieManagerRef); + explicit EwkCookieManager(WKCookieManagerRef cookieManager); bool isWatchingForChanges() const; static void cookiesDidChange(WKCookieManagerRef, const void* clientInfo); - WKRetainPtr<WKCookieManagerRef> m_wkCookieManager; + WKRetainPtr<WKCookieManagerRef> m_cookieManager; Cookie_Change_Handler m_changeHandler; }; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp index 85ef90677..20155415e 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp @@ -28,22 +28,21 @@ #include "WKAPICast.h" #include "WKArray.h" -#include "WKDatabaseManager.h" -#include "WebDatabaseManagerProxy.h" #include "ewk_database_manager_private.h" #include "ewk_error_private.h" -#include "ewk_security_origin.h" #include "ewk_security_origin_private.h" using namespace WebKit; -EwkDatabaseManager::EwkDatabaseManager(WebDatabaseManagerProxy* databaseManager) +EwkDatabaseManager::EwkDatabaseManager(WKDatabaseManagerRef databaseManager) : m_databaseManager(databaseManager) -{ } +{ + ASSERT(databaseManager); +} void EwkDatabaseManager::getDatabaseOrigins(WKDatabaseManagerGetDatabaseOriginsFunction callback, void* context) const { - WKDatabaseManagerGetDatabaseOrigins(toAPI(m_databaseManager.get()), context, callback); + WKDatabaseManagerGetDatabaseOrigins(m_databaseManager.get(), context, callback); } Eina_List* EwkDatabaseManager::createOriginList(WKArrayRef origins) const @@ -53,7 +52,7 @@ Eina_List* EwkDatabaseManager::createOriginList(WKArrayRef origins) const for (size_t i = 0; i < length; ++i) { WKSecurityOriginRef wkOriginRef = static_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, i)); - RefPtr<Ewk_Security_Origin> origin = m_wrapperCache.get(wkOriginRef); + RefPtr<EwkSecurityOrigin> origin = m_wrapperCache.get(wkOriginRef); if (!origin) { origin = EwkSecurityOrigin::create(wkOriginRef); m_wrapperCache.set(wkOriginRef, origin); @@ -80,7 +79,7 @@ static void getDatabaseOriginsCallback(WKArrayRef origins, WKErrorRef wkError, v { OwnPtr<Ewk_Database_Origins_Async_Get_Context*> webDatabaseContext = adoptPtr(static_cast<Ewk_Database_Origins_Async_Get_Context*>(context)); Eina_List* originList = webDatabaseContext->manager->createOriginList(origins); - OwnPtr<Ewk_Error> ewkError = Ewk_Error::create(wkError); + OwnPtr<EwkError> ewkError = EwkError::create(wkError); webDatabaseContext->callback(originList, ewkError.get(), webDatabaseContext->userData); } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h index 7ce348daa..610a736eb 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h @@ -48,7 +48,7 @@ typedef struct EwkDatabaseManager Ewk_Database_Manager; * @brief Callback type for use with ewk_database_manager_origins_get() * * @param origins @c Eina_List containing @c Ewk_Security_Origin elements or @c NULL in case of error, - * the Eina_List and its items should be freed after use. Use ewk_security_origin_unref() + * the Eina_List and its items should be freed after use. Use ewk_object_unref() * to free the items */ typedef void (*Ewk_Database_Origins_Get_Cb)(Eina_List *origins, Ewk_Error *error, void *user_data); diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h index eee492412..b76918505 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h @@ -27,9 +27,8 @@ #define ewk_database_manager_private_h #include "WKDatabaseManager.h" -#include "WebContext.h" -#include "WebDatabaseManagerProxy.h" -#include "ewk_security_origin.h" +#include "WKRetainPtr.h" +#include "ewk_security_origin_private.h" #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> @@ -37,19 +36,19 @@ using namespace WebKit; class EwkDatabaseManager { public: - static PassOwnPtr<EwkDatabaseManager> create(PassRefPtr<WebContext> context) + static PassOwnPtr<EwkDatabaseManager> create(WKDatabaseManagerRef databaseManager) { - ASSERT(context); - return adoptPtr(new EwkDatabaseManager(context->databaseManagerProxy())); + ASSERT(databaseManager); + return adoptPtr(new EwkDatabaseManager(databaseManager)); } Eina_List* createOriginList(WKArrayRef wkList) const; void getDatabaseOrigins(WKDatabaseManagerGetDatabaseOriginsFunction callback, void* context) const; private: - explicit EwkDatabaseManager(WebDatabaseManagerProxy*); + explicit EwkDatabaseManager(WKDatabaseManagerRef); - RefPtr<WebDatabaseManagerProxy> m_databaseManager; - mutable HashMap<WKSecurityOriginRef, RefPtr<Ewk_Security_Origin> > m_wrapperCache; + WKRetainPtr<WKDatabaseManagerRef> m_databaseManager; + mutable HashMap<WKSecurityOriginRef, RefPtr<EwkSecurityOrigin> > m_wrapperCache; }; #endif // ewk_database_manager_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_defines.h b/Source/WebKit2/UIProcess/API/efl/ewk_defines.h index 97320fb37..bf0177f8b 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_defines.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_defines.h @@ -35,8 +35,12 @@ extern "C" { #endif -/** Creates a type name for Ewk_Context_Menu */ -typedef struct EwkContextMenu Ewk_Context_Menu; +/** + * Declare Ewk_Context_Menu as Ewk_Object. + * + * @see Ewk_Object + */ +typedef struct EwkObject Ewk_Context_Menu; /** Creates a type name for Ewk_Context_Menu_Item */ typedef struct EwkContextMenuItem Ewk_Context_Menu_Item; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp index 3ad7d4dbc..9ae97357c 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp @@ -26,18 +26,17 @@ #include "config.h" #include "ewk_download_job.h" -#include "DownloadProxy.h" #include "WKAPICast.h" #include "WKRetainPtr.h" -#include "WebURLRequest.h" +#include "WKURLRequest.h" #include "ewk_download_job_private.h" #include "ewk_url_response_private.h" #include <Ecore.h> using namespace WebKit; -EwkDownloadJob::EwkDownloadJob(WebKit::DownloadProxy* download, EwkViewImpl* viewImpl) - : m_downloadProxy(download) +EwkDownloadJob::EwkDownloadJob(WKDownloadRef download, EwkView* viewImpl) + : m_download(download) , m_viewImpl(viewImpl) , m_state(EWK_DOWNLOAD_JOB_STATE_NOT_STARTED) , m_startTime(-1) @@ -51,7 +50,7 @@ EwkDownloadJob::EwkDownloadJob(WebKit::DownloadProxy* download, EwkViewImpl* vie */ uint64_t EwkDownloadJob::id() const { - return m_downloadProxy->downloadID(); + return WKDownloadGetID(m_download.get()); } /** @@ -59,7 +58,7 @@ uint64_t EwkDownloadJob::id() const * Returns the view this download is attached to. * The view is needed to send notification signals. */ -EwkViewImpl* EwkDownloadJob::viewImpl() const +EwkView* EwkDownloadJob::view() const { return m_viewImpl; } @@ -86,7 +85,7 @@ Ewk_Url_Request* ewk_download_job_request_get(const Ewk_Download_Job* download) EwkUrlRequest* EwkDownloadJob::request() const { if (!m_request) { - WKRetainPtr<WKURLRequestRef> wkURLRequest(AdoptWK, toAPI(WebURLRequest::create(m_downloadProxy->request()).leakRef())); + WKRetainPtr<WKURLRequestRef> wkURLRequest(AdoptWK, WKDownloadCopyRequest(m_download.get())); m_request = EwkUrlRequest::create(wkURLRequest.get()); } @@ -157,7 +156,8 @@ bool EwkDownloadJob::cancel() return false; m_state = EWK_DOWNLOAD_JOB_STATE_CANCELLING; - m_downloadProxy->cancel(); + WKDownloadCancel(m_download.get()); + return true; } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h index 5b6a53f9a..3e516ef22 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h @@ -27,30 +27,28 @@ #define ewk_download_job_private_h #include "WKBase.h" +#include "WKDownload.h" #include "WKEinaSharedString.h" +#include "WKRetainPtr.h" #include "ewk_download_job.h" #include "ewk_url_request_private.h" #include "ewk_url_response_private.h" #include <Evas.h> #include <wtf/PassRefPtr.h> -namespace WebKit { -class DownloadProxy; -} - -class EwkViewImpl; +class EwkView; class EwkDownloadJob : public EwkObject { public: EWK_OBJECT_DECLARE(EwkDownloadJob) - static PassRefPtr<EwkDownloadJob> create(WebKit::DownloadProxy* download, EwkViewImpl* viewImpl) + static PassRefPtr<EwkDownloadJob> create(WKDownloadRef download, EwkView* viewImpl) { return adoptRef(new EwkDownloadJob(download, viewImpl)); } uint64_t id() const; - EwkViewImpl* viewImpl() const; + EwkView* view() const; Ewk_Download_Job_State state() const; void setState(Ewk_Download_Job_State); @@ -72,10 +70,10 @@ public: void incrementReceivedData(uint64_t length); private: - EwkDownloadJob(WebKit::DownloadProxy* download, EwkViewImpl* viewImpl); + EwkDownloadJob(WKDownloadRef download, EwkView* view); - WebKit::DownloadProxy* m_downloadProxy; - EwkViewImpl* m_viewImpl; + WKRetainPtr<WKDownloadRef> m_download; + EwkView* m_viewImpl; Ewk_Download_Job_State m_state; mutable RefPtr<EwkUrlRequest> m_request; RefPtr<EwkUrlResponse> m_response; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp index cb9d68e1c..29031fdf4 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp @@ -27,14 +27,12 @@ #include "ewk_error.h" #include "ErrorsEfl.h" +#include "WKError.h" #include "WKString.h" #include "WKURL.h" #include "ewk_error_private.h" -#include <WKAPICast.h> -#include <wtf/text/CString.h> using namespace WebCore; -using namespace WebKit; EwkError::EwkError(WKErrorRef errorRef) : m_wkError(errorRef) @@ -52,10 +50,9 @@ const char* EwkError::description() const return m_description; } -String EwkError::domain() const +WKRetainPtr<WKStringRef> EwkError::domain() const { - WKRetainPtr<WKStringRef> wkDomain(AdoptWK, WKErrorCopyDomain(m_wkError.get())); - return toWTFString(wkDomain.get()); + return adoptWK(WKErrorCopyDomain(m_wkError.get())); } int EwkError::errorCode() const @@ -65,25 +62,26 @@ int EwkError::errorCode() const bool EwkError::isCancellation() const { - return toImpl(m_wkError.get())->platformError().isCancellation(); + return WKStringIsEqualToUTF8CString(domain().get(), errorDomainNetwork) && errorCode() == NetworkErrorCancelled; } Ewk_Error_Type ewk_error_type_get(const Ewk_Error* error) { EINA_SAFETY_ON_NULL_RETURN_VAL(error, EWK_ERROR_TYPE_NONE); - String errorDomain = error->domain(); + WKRetainPtr<WKStringRef> wkErrorDomain = error->domain(); - if (errorDomain == errorDomainNetwork) + if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainNetwork)) return EWK_ERROR_TYPE_NETWORK; - if (errorDomain == errorDomainPolicy) + if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainPolicy)) return EWK_ERROR_TYPE_POLICY; - if (errorDomain == errorDomainPlugin) + if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainPlugin)) return EWK_ERROR_TYPE_PLUGIN; - if (errorDomain == errorDomainDownload) + if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainDownload)) return EWK_ERROR_TYPE_DOWNLOAD; - if (errorDomain == errorDomainPrint) + if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainPrint)) return EWK_ERROR_TYPE_PRINT; + return EWK_ERROR_TYPE_INTERNAL; } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h index 0a3873bb7..54682f076 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h @@ -27,10 +27,9 @@ #define ewk_error_private_h #include "WKEinaSharedString.h" -#include <WKError.h> #include <WKRetainPtr.h> +#include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -#include <wtf/text/WTFString.h> class EwkError { public: @@ -44,7 +43,7 @@ public: const char* url() const; const char* description() const; - String domain() const; + WKRetainPtr<WKStringRef> domain() const; int errorCode() const; bool isCancellation() const; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp index 7df4f3b75..6300ab390 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,9 +29,8 @@ #include "WKAPICast.h" #include "WKIconDatabase.h" +#include "WKIconDatabaseCairo.h" #include "WKURL.h" -#include "WebIconDatabase.h" -#include "WebURL.h" #include "ewk_favicon_database_private.h" #include <WebCore/CairoUtilitiesEfl.h> #include <WebCore/RefPtrCairo.h> @@ -39,28 +39,20 @@ using namespace WebKit; -EwkFaviconDatabase::EwkFaviconDatabase(WebIconDatabase* iconDatabase) +EwkFaviconDatabase::EwkFaviconDatabase(WKIconDatabaseRef iconDatabase) : m_iconDatabase(iconDatabase) { WKIconDatabaseClient iconDatabaseClient; memset(&iconDatabaseClient, 0, sizeof(WKIconDatabaseClient)); iconDatabaseClient.version = kWKIconDatabaseClientCurrentVersion; iconDatabaseClient.clientInfo = this; - iconDatabaseClient.didChangeIconForPageURL = didChangeIconForPageURL; iconDatabaseClient.iconDataReadyForPageURL = iconDataReadyForPageURL; - WKIconDatabaseSetIconDatabaseClient(toAPI(m_iconDatabase.get()), &iconDatabaseClient); + WKIconDatabaseSetIconDatabaseClient(m_iconDatabase.get(), &iconDatabaseClient); } EwkFaviconDatabase::~EwkFaviconDatabase() { -} - -String EwkFaviconDatabase::iconURLForPageURL(const String& pageURL) const -{ - String iconURL; - m_iconDatabase->synchronousIconURLForPageURL(pageURL, iconURL); - - return iconURL; + WKIconDatabaseSetIconDatabaseClient(m_iconDatabase.get(), 0); } void EwkFaviconDatabase::watchChanges(const IconChangeCallbackData& callbackData) @@ -78,61 +70,14 @@ void EwkFaviconDatabase::unwatchChanges(Ewk_Favicon_Database_Icon_Change_Cb call m_changeListeners.remove(callback); } -struct AsyncIconRequestResponse { - String pageURL; - RefPtr<cairo_surface_t> surface; - IconRequestCallbackData callbackData; - - AsyncIconRequestResponse(const String& pageURL, PassRefPtr<cairo_surface_t> surface, const IconRequestCallbackData& callbackData) - : pageURL(pageURL) - , surface(surface) - , callbackData(callbackData) - { } -}; - -static Eina_Bool respond_icon_request_idle(void* data) -{ - AsyncIconRequestResponse* response = static_cast<AsyncIconRequestResponse*>(data); - - RefPtr<Evas_Object> icon = response->surface ? WebCore::evasObjectFromCairoImageSurface(response->callbackData.evas, response->surface.get()) : 0; - response->callbackData.callback(response->pageURL.utf8().data(), icon.get(), response->callbackData.userData); - - delete response; - - return ECORE_CALLBACK_DONE; -} - -void EwkFaviconDatabase::iconForPageURL(const String& pageURL, const IconRequestCallbackData& callbackData) -{ - // We ask for the icon directly. If we don't get the icon data now, - // we'll be notified later (even if the database is still importing icons). - RefPtr<cairo_surface_t> surface = getIconSurfaceSynchronously(pageURL); - - // If there's no valid icon, but there's an iconURL registered, - // or it's still not registered but the import process hasn't - // finished yet, we need to wait for iconDataReadyForPageURL to be - // called before making and informed decision. - String iconURL = iconURLForPageURL(pageURL); - if (!surface && (!iconURL.isEmpty() || !m_iconDatabase->isUrlImportCompleted())) { - PendingIconRequestVector requests = m_iconRequests.get(pageURL); - requests.append(callbackData); - m_iconRequests.set(pageURL, requests); - return; - } - - // Respond when idle. - AsyncIconRequestResponse* response = new AsyncIconRequestResponse(pageURL, surface.release(), callbackData); - ecore_idler_add(respond_icon_request_idle, response); -} - void EwkFaviconDatabase::didChangeIconForPageURL(WKIconDatabaseRef, WKURLRef pageURLRef, const void* clientInfo) { - const Ewk_Favicon_Database* ewkIconDatabase = static_cast<const Ewk_Favicon_Database*>(clientInfo); + const EwkFaviconDatabase* ewkIconDatabase = static_cast<const EwkFaviconDatabase*>(clientInfo); if (ewkIconDatabase->m_changeListeners.isEmpty()) return; - CString pageURL = toImpl(pageURLRef)->string().utf8(); + CString pageURL = toWTFString(pageURLRef).utf8(); ChangeListenerMap::const_iterator it = ewkIconDatabase->m_changeListeners.begin(); ChangeListenerMap::const_iterator end = ewkIconDatabase->m_changeListeners.end(); @@ -140,60 +85,41 @@ void EwkFaviconDatabase::didChangeIconForPageURL(WKIconDatabaseRef, WKURLRef pag it->value.callback(pageURL.data(), it->value.userData); } -PassRefPtr<cairo_surface_t> EwkFaviconDatabase::getIconSurfaceSynchronously(const String& pageURL) const +PassRefPtr<cairo_surface_t> EwkFaviconDatabase::getIconSurfaceSynchronously(const char* pageURL) const { - m_iconDatabase->retainIconForPageURL(pageURL); + WKRetainPtr<WKURLRef> wkPageURL(AdoptWK, WKURLCreateWithUTF8CString(pageURL)); - WebCore::NativeImagePtr icon = m_iconDatabase->nativeImageForPageURL(pageURL); - if (!icon) { - m_iconDatabase->releaseIconForPageURL(pageURL); + RefPtr<cairo_surface_t> surface = WKIconDatabaseTryGetCairoSurfaceForURL(m_iconDatabase.get(), wkPageURL.get()); + if (!surface) return 0; - } - - RefPtr<cairo_surface_t> surface = icon->surface(); return surface.release(); } void EwkFaviconDatabase::iconDataReadyForPageURL(WKIconDatabaseRef, WKURLRef pageURL, const void* clientInfo) { - Ewk_Favicon_Database* ewkIconDatabase = const_cast<Ewk_Favicon_Database*>(static_cast<const Ewk_Favicon_Database*>(clientInfo)); + EwkFaviconDatabase* ewkIconDatabase = const_cast<EwkFaviconDatabase*>(static_cast<const EwkFaviconDatabase*>(clientInfo)); - String urlString = toImpl(pageURL)->string(); - if (!ewkIconDatabase->m_iconRequests.contains(urlString)) - return; + WKIconDatabaseRetainIconForURL(ewkIconDatabase->m_iconDatabase.get(), pageURL); - RefPtr<cairo_surface_t> surface = ewkIconDatabase->getIconSurfaceSynchronously(urlString); - - PendingIconRequestVector requestsForURL = ewkIconDatabase->m_iconRequests.take(urlString); - size_t requestCount = requestsForURL.size(); - for (size_t i = 0; i < requestCount; ++i) { - const IconRequestCallbackData& callbackData = requestsForURL[i]; - RefPtr<Evas_Object> icon = surface ? WebCore::evasObjectFromCairoImageSurface(callbackData.evas, surface.get()) : 0; - callbackData.callback(urlString.utf8().data(), icon.get(), callbackData.userData); - } + CString urlString = toWTFString(pageURL).utf8(); + ChangeListenerMap::const_iterator it = ewkIconDatabase->m_changeListeners.begin(); + ChangeListenerMap::const_iterator end = ewkIconDatabase->m_changeListeners.end(); + for (; it != end; ++it) + it->value.callback(urlString.data(), it->value.userData); } -const char* ewk_favicon_database_icon_url_get(Ewk_Favicon_Database* ewkIconDatabase, const char* pageURL) +Evas_Object* ewk_favicon_database_icon_get(Ewk_Favicon_Database* ewkIconDatabase, const char* pageURL, Evas* evas) { EINA_SAFETY_ON_NULL_RETURN_VAL(ewkIconDatabase, 0); EINA_SAFETY_ON_NULL_RETURN_VAL(pageURL, 0); + EINA_SAFETY_ON_NULL_RETURN_VAL(evas, 0); - String iconURL = ewkIconDatabase->iconURLForPageURL(String::fromUTF8(pageURL)); - - return eina_stringshare_add(iconURL.utf8().data()); -} - -Eina_Bool ewk_favicon_database_async_icon_get(Ewk_Favicon_Database* ewkIconDatabase, const char* page_url, Evas* evas, Ewk_Favicon_Database_Async_Icon_Get_Cb callback, void* userData) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(ewkIconDatabase, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(page_url, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(evas, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(callback, false); - - ewkIconDatabase->iconForPageURL(String::fromUTF8(page_url), IconRequestCallbackData(callback, userData, evas)); + RefPtr<cairo_surface_t> surface = ewkIconDatabase->getIconSurfaceSynchronously(pageURL); + if (!surface) + return 0; - return true; + return WebCore::evasObjectFromCairoImageSurface(evas, surface.get()).leakRef(); } void ewk_favicon_database_icon_change_callback_add(Ewk_Favicon_Database* ewkIconDatabase, Ewk_Favicon_Database_Icon_Change_Cb callback, void* userData) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h index b66a67b16..d5cefd2e4 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -47,40 +48,16 @@ typedef struct EwkFaviconDatabase Ewk_Favicon_Database; typedef void (*Ewk_Favicon_Database_Icon_Change_Cb)(const char *page_url, void *event_info); /** - * @typedef Ewk_Favicon_Database_Async_Icon_Get_Cb Ewk_Favicon_Database_Async_Icon_Get_Cb - * @brief Callback type for use with ewk_favicon_database_async_icon_get - * - * The @a icon may be NULL if there is no favicon associated to the given @a page_url. - * - * You need to call evas_object_ref() on the @a icon if you wish to keep it after the - * callback is executed. - */ -typedef void (*Ewk_Favicon_Database_Async_Icon_Get_Cb)(const char *page_url, Evas_Object *icon, void *event_info); - -/** - * Retrieves from the database the favicon URL for the given @a page_url - * - * @param database database object to query - * @param page_url URL of the page to get the favicon URL for - * - * @return a newly allocated string guaranteed to be eina_stringshare - * or @c NULL in case of error or if the key does not exist. - * You need to call eina_stringshare_del() after use. - */ -EAPI const char *ewk_favicon_database_icon_url_get(Ewk_Favicon_Database *database, const char *page_url); - -/** - * Retrieves asynchronously from the database the favicon for the given @a page_url + * Retrieves from the database the favicon for the given @a page_url * * @param database database object to query * @param page_url URL of the page to get the favicon for * @param evas The canvas to add the favicon to - * @param callback callback function to be called when the icon is retrieved - * @param data the data pointer that was to be passed to the callback * - * @return @c EINA_TRUE if the icon was successfuly requested, @c EINA_FALSE otherwise + * @return The favicon as an Evas_Object if successful, @c NULL otherwise. + * The returned Evas_Object needs to be freed after use. */ -EAPI Eina_Bool ewk_favicon_database_async_icon_get(Ewk_Favicon_Database *database, const char *page_url, Evas *evas, Ewk_Favicon_Database_Async_Icon_Get_Cb callback, void *data); +EAPI Evas_Object *ewk_favicon_database_icon_get(Ewk_Favicon_Database *database, const char *page_url, Evas *evas); /** * Add (register) a callback function to a icon change event diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h index 86a911263..1cc7722d8 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,14 +27,11 @@ #ifndef ewk_favicon_database_private_h #define ewk_favicon_database_private_h +#include "WKRetainPtr.h" #include "ewk_favicon_database.h" #include <WebKit2/WKBase.h> #include <wtf/HashMap.h> -namespace WebKit { -class WebIconDatabase; -} - struct IconChangeCallbackData { Ewk_Favicon_Database_Icon_Change_Cb callback; void* userData; @@ -49,53 +47,28 @@ struct IconChangeCallbackData { { } }; -struct IconRequestCallbackData { - Ewk_Favicon_Database_Async_Icon_Get_Cb callback; - void* userData; - Evas* evas; - - IconRequestCallbackData() - : callback(0) - , userData(0) - , evas(0) - { } - - IconRequestCallbackData(Ewk_Favicon_Database_Async_Icon_Get_Cb _callback, void* _userData, Evas* _evas) - : callback(_callback) - , userData(_userData) - , evas(_evas) - { } -}; - typedef HashMap<Ewk_Favicon_Database_Icon_Change_Cb, IconChangeCallbackData> ChangeListenerMap; -typedef Vector<IconRequestCallbackData> PendingIconRequestVector; -typedef HashMap<String /* pageURL */, PendingIconRequestVector> PendingIconRequestMap; class EwkFaviconDatabase { public: - static PassOwnPtr<EwkFaviconDatabase> create(WebKit::WebIconDatabase* iconDatabase) + static PassOwnPtr<EwkFaviconDatabase> create(WKIconDatabaseRef iconDatabase) { return adoptPtr(new EwkFaviconDatabase(iconDatabase)); } ~EwkFaviconDatabase(); - String iconURLForPageURL(const String& pageURL) const; - void iconForPageURL(const String& pageURL, const IconRequestCallbackData& callbackData); - + PassRefPtr<cairo_surface_t> getIconSurfaceSynchronously(const char* pageURL) const; void watchChanges(const IconChangeCallbackData& callbackData); void unwatchChanges(Ewk_Favicon_Database_Icon_Change_Cb callback); private: - explicit EwkFaviconDatabase(WebKit::WebIconDatabase* iconDatabase); - - PassRefPtr<cairo_surface_t> getIconSurfaceSynchronously(const String& pageURL) const; + explicit EwkFaviconDatabase(WKIconDatabaseRef iconDatabase); static void didChangeIconForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL, const void* clientInfo); static void iconDataReadyForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL, const void* clientInfo); - RefPtr<WebKit::WebIconDatabase> m_iconDatabase; + WKRetainPtr<WKIconDatabaseRef> m_iconDatabase; ChangeListenerMap m_changeListeners; - PendingIconRequestMap m_iconRequests; }; #endif // ewk_favicon_database_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.cpp index 37606c5dc..825fcffec 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.cpp @@ -26,18 +26,19 @@ #include "config.h" #include "ewk_file_chooser_request.h" -#include "ImmutableArray.h" -#include "MutableArray.h" -#include "WebOpenPanelParameters.h" -#include "WebOpenPanelResultListenerProxy.h" -#include "WebString.h" -#include "WebURL.h" +#include "WKArray.h" +#include "WKOpenPanelParameters.h" +#include "WKOpenPanelResultListener.h" +#include "WKSharedAPICast.h" +#include "WKString.h" +#include "WKURL.h" #include "ewk_file_chooser_request_private.h" +#include <wtf/OwnArrayPtr.h> #include <wtf/text/CString.h> using namespace WebKit; -EwkFileChooserRequest::EwkFileChooserRequest(WebOpenPanelParameters* parameters, WebOpenPanelResultListenerProxy* listener) +EwkFileChooserRequest::EwkFileChooserRequest(WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener) : m_parameters(parameters) , m_listener(listener) , m_wasRequestHandled(false) @@ -49,33 +50,30 @@ EwkFileChooserRequest::EwkFileChooserRequest(WebOpenPanelParameters* parameters, EwkFileChooserRequest::~EwkFileChooserRequest() { if (!m_wasRequestHandled) - m_listener->cancel(); + WKOpenPanelResultListenerCancel(m_listener.get()); } bool EwkFileChooserRequest::allowMultipleFiles() const { - return m_parameters->allowMultipleFiles(); + return WKOpenPanelParametersGetAllowsMultipleFiles(m_parameters.get()); } -PassRefPtr<ImmutableArray> EwkFileChooserRequest::acceptedMIMETypes() const +WKRetainPtr<WKArrayRef> EwkFileChooserRequest::acceptedMIMETypes() const { - return m_parameters->acceptMIMETypes(); + return adoptWK(WKOpenPanelParametersCopyAcceptedMIMETypes(m_parameters.get())); } void EwkFileChooserRequest::cancel() { m_wasRequestHandled = true; - return m_listener->cancel(); + return WKOpenPanelResultListenerCancel(m_listener.get()); } -void EwkFileChooserRequest::chooseFiles(Vector< RefPtr<APIObject> >& fileURLs) +void EwkFileChooserRequest::chooseFiles(WKArrayRef fileURLs) { - ASSERT(!fileURLs.isEmpty()); - ASSERT(fileURLs.size() == 1 || m_parameters->allowMultipleFiles()); - m_wasRequestHandled = true; - m_listener->chooseFiles(ImmutableArray::adopt(fileURLs).get()); + WKOpenPanelResultListenerChooseFiles(m_listener.get(), fileURLs); } Eina_Bool ewk_file_chooser_request_allow_multiple_files_get(const Ewk_File_Chooser_Request* request) @@ -90,14 +88,14 @@ Eina_List* ewk_file_chooser_request_accepted_mimetypes_get(const Ewk_File_Choose EWK_OBJ_GET_IMPL_OR_RETURN(const EwkFileChooserRequest, request, impl, 0); Eina_List* mimeTypeList = 0; - RefPtr<ImmutableArray> mimeTypes = impl->acceptedMIMETypes(); + WKRetainPtr<WKArrayRef> mimeTypes = impl->acceptedMIMETypes(); - const size_t size = mimeTypes->size(); + const size_t size = WKArrayGetSize(mimeTypes.get()); for (size_t i = 0; i < size; ++i) { - String mimeTypeString = static_cast<WebString*>(mimeTypes->at(i))->string(); - if (mimeTypeString.isEmpty()) + WKRetainPtr<WKStringRef> mimeType = static_cast<WKStringRef>(WKArrayGetItemAtIndex(mimeTypes.get(), i)); + if (!mimeType || WKStringIsEmpty(mimeType.get())) continue; - mimeTypeList = eina_list_append(mimeTypeList, eina_stringshare_add(mimeTypeString.utf8().data())); + mimeTypeList = eina_list_append(mimeTypeList, eina_stringshare_add(toWTFString(mimeType.get()).utf8().data())); } return mimeTypeList; @@ -117,20 +115,22 @@ Eina_Bool ewk_file_chooser_request_files_choose(Ewk_File_Chooser_Request* reques { EWK_OBJ_GET_IMPL_OR_RETURN(EwkFileChooserRequest, request, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(chosenFiles, false); - EINA_SAFETY_ON_FALSE_RETURN_VAL(eina_list_count(chosenFiles) == 1 || impl->allowMultipleFiles(), false); EINA_SAFETY_ON_TRUE_RETURN_VAL(impl->wasHandled(), false); - Vector< RefPtr<APIObject> > fileURLs; + const unsigned urlCount = eina_list_count(chosenFiles); + EINA_SAFETY_ON_FALSE_RETURN_VAL(urlCount == 1 || (urlCount > 1 && impl->allowMultipleFiles()), false); + + OwnArrayPtr<WKTypeRef> filesURLs = adoptArrayPtr(new WKTypeRef[urlCount]); - const Eina_List* l; - void* data; - EINA_LIST_FOREACH(chosenFiles, l, data) { - EINA_SAFETY_ON_NULL_RETURN_VAL(data, false); - String fileURL = "file://" + String::fromUTF8(static_cast<char*>(data)); - fileURLs.append(WebURL::create(fileURL)); + for (unsigned i = 0; i < urlCount; ++i) { + const char* url = static_cast<char*>(eina_list_nth(chosenFiles, i)); + EINA_SAFETY_ON_NULL_RETURN_VAL(url, false); + String fileURL = ASCIILiteral("file://") + String::fromUTF8(url); + filesURLs[i] = toCopiedURLAPI(fileURL); } - impl->chooseFiles(fileURLs); + WKRetainPtr<WKArrayRef> wkFileURLs(AdoptWK, WKArrayCreateAdoptingValues(filesURLs.get(), urlCount)); + impl->chooseFiles(wkFileURLs.get()); return true; } @@ -141,11 +141,12 @@ Eina_Bool ewk_file_chooser_request_file_choose(Ewk_File_Chooser_Request* request EINA_SAFETY_ON_NULL_RETURN_VAL(chosenFile, false); EINA_SAFETY_ON_TRUE_RETURN_VAL(impl->wasHandled(), false); - Vector< RefPtr<APIObject> > fileURLs; - String fileURL = "file://" + String::fromUTF8(chosenFile); - fileURLs.append(WebURL::create(fileURL)); + String fileURL = ASCIILiteral("file://") + String::fromUTF8(chosenFile); + WKRetainPtr<WKURLRef> wkURL(AdoptWK, toCopiedURLAPI(fileURL)); - impl->chooseFiles(fileURLs); + WKTypeRef wkURLPtr = wkURL.get(); + WKRetainPtr<WKArrayRef> wkFileURLs(AdoptWK, WKArrayCreate(&wkURLPtr, 1)); + impl->chooseFiles(wkFileURLs.get()); return true; } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request_private.h index 61778ff83..688a39176 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request_private.h @@ -27,22 +27,16 @@ #define ewk_file_chooser_request_private_h #include "APIObject.h" +#include "WKRetainPtr.h" #include "ewk_object_private.h" +#include <WebKit2/WKBase.h> #include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebKit { -class ImmutableArray; -class WebOpenPanelParameters; -class WebOpenPanelResultListenerProxy; -} class EwkFileChooserRequest : public EwkObject { public: EWK_OBJECT_DECLARE(EwkFileChooserRequest) - static PassRefPtr<EwkFileChooserRequest> create(WebKit::WebOpenPanelParameters* parameters, WebKit::WebOpenPanelResultListenerProxy* listener) + static PassRefPtr<EwkFileChooserRequest> create(WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener) { return adoptRef(new EwkFileChooserRequest(parameters, listener)); } @@ -50,16 +44,16 @@ public: ~EwkFileChooserRequest(); bool allowMultipleFiles() const; - PassRefPtr<WebKit::ImmutableArray> acceptedMIMETypes() const; + WKRetainPtr<WKArrayRef> acceptedMIMETypes() const; inline bool wasHandled() const { return m_wasRequestHandled; } void cancel(); - void chooseFiles(Vector< RefPtr<WebKit::APIObject> >& fileURLs); + void chooseFiles(WKArrayRef fileURLs); private: - EwkFileChooserRequest(WebKit::WebOpenPanelParameters* parameters, WebKit::WebOpenPanelResultListenerProxy* listener); + EwkFileChooserRequest(WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener); - RefPtr<WebKit::WebOpenPanelParameters> m_parameters; - RefPtr<WebKit::WebOpenPanelResultListenerProxy> m_listener; + WKRetainPtr<WKOpenPanelParametersRef> m_parameters; + WKRetainPtr<WKOpenPanelResultListenerRef> m_listener; bool m_wasRequestHandled; }; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp index e61a42f1f..60798eb43 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp @@ -31,7 +31,6 @@ #include "WKBase.h" #include "WKString.h" #include "ewk_form_submission_request_private.h" -#include <wtf/text/CString.h> using namespace WebKit; @@ -48,13 +47,13 @@ EwkFormSubmissionRequest::~EwkFormSubmissionRequest() WKFormSubmissionListenerContinue(m_wkListener.get()); } -String EwkFormSubmissionRequest::fieldValue(const String& fieldName) const +Eina_Stringshare* EwkFormSubmissionRequest::copyFieldValue(const char* fieldName) const { ASSERT(fieldName); - WKRetainPtr<WKStringRef> wkFieldName = adoptWK(toCopiedAPI(fieldName)); + WKRetainPtr<WKStringRef> wkFieldName = adoptWK(WKStringCreateWithUTF8CString(fieldName)); WKStringRef wkValue = static_cast<WKStringRef>(WKDictionaryGetItemForKey(m_wkValues.get(), wkFieldName.get())); - return wkValue ? toImpl(wkValue)->string() : String(); + return WKEinaSharedString(wkValue).leakString(); } WKRetainPtr<WKArrayRef> EwkFormSubmissionRequest::fieldNames() const @@ -72,16 +71,16 @@ Eina_List* ewk_form_submission_request_field_names_get(Ewk_Form_Submission_Reque { EWK_OBJ_GET_IMPL_OR_RETURN(EwkFormSubmissionRequest, request, impl, 0); - Eina_List* names = 0; + Eina_List* fieldNames = 0; - WKRetainPtr<WKArrayRef> wkKeys = impl->fieldNames(); - const size_t numKeys = WKArrayGetSize(wkKeys.get()); + WKRetainPtr<WKArrayRef> wkFieldNames = impl->fieldNames(); + const size_t numKeys = WKArrayGetSize(wkFieldNames.get()); for (size_t i = 0; i < numKeys; ++i) { - WKStringRef wkKey = static_cast<WKStringRef>(WKArrayGetItemAtIndex(wkKeys.get(), i)); - names = eina_list_append(names, eina_stringshare_add(toImpl(wkKey)->string().utf8().data())); + WKStringRef wkFieldName = static_cast<WKStringRef>(WKArrayGetItemAtIndex(wkFieldNames.get(), i)); + fieldNames = eina_list_append(fieldNames, WKEinaSharedString(wkFieldName).leakString()); } - return names; + return fieldNames; } const char* ewk_form_submission_request_field_value_get(Ewk_Form_Submission_Request* request, const char* name) @@ -89,9 +88,7 @@ const char* ewk_form_submission_request_field_value_get(Ewk_Form_Submission_Requ EWK_OBJ_GET_IMPL_OR_RETURN(EwkFormSubmissionRequest, request, impl, 0); EINA_SAFETY_ON_NULL_RETURN_VAL(name, 0); - String value = impl->fieldValue(String::fromUTF8(name)); - - return value.isNull() ? 0 : eina_stringshare_add(value.utf8().data()); + return impl->copyFieldValue(name); } Eina_Bool ewk_form_submission_request_submit(Ewk_Form_Submission_Request* request) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request_private.h index 26d324631..b2b8073aa 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request_private.h @@ -27,11 +27,11 @@ #define ewk_form_submission_request_private_h #include "WKDictionary.h" +#include "WKEinaSharedString.h" #include "WKFormSubmissionListener.h" #include "WKRetainPtr.h" #include "ewk_object_private.h" #include <wtf/PassRefPtr.h> -#include <wtf/text/WTFString.h> class EwkFormSubmissionRequest : public EwkObject { public: @@ -45,7 +45,7 @@ public: } WKRetainPtr<WKArrayRef> fieldNames() const; - String fieldValue(const String& fieldName) const; + Eina_Stringshare* copyFieldValue(const char* fieldName) const; void submit(); diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_intent.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_intent.cpp deleted file mode 100644 index 708660115..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_intent.h" - -#include "WKAPICast.h" -#include "WKArray.h" -#include "WKDictionary.h" -#include "WKString.h" -#include "WKURL.h" -#include "ewk_intent_private.h" -#include <wtf/text/CString.h> - -using namespace WebKit; - -#if ENABLE(WEB_INTENTS) -EwkIntent::EwkIntent(WKIntentDataRef intentRef) - : m_wkIntent(intentRef) - , m_action(AdoptWK, WKIntentDataCopyAction(intentRef)) - , m_type(AdoptWK, WKIntentDataCopyType(intentRef)) - , m_service(AdoptWK, WKIntentDataCopyService(intentRef)) -{ } - -WebIntentData* EwkIntent::webIntentData() const -{ - return toImpl(m_wkIntent.get()); -} - -const char* EwkIntent::action() const -{ - return m_action; -} - -const char* EwkIntent::type() const -{ - return m_type; -} - -const char* EwkIntent::service() const -{ - return m_service; -} - -WKRetainPtr<WKArrayRef> EwkIntent::suggestions() const -{ - return adoptWK(WKIntentDataCopySuggestions(m_wkIntent.get())); -} - -String EwkIntent::extra(const char* key) const -{ - WKRetainPtr<WKStringRef> keyRef = adoptWK(WKStringCreateWithUTF8CString(key)); - WKRetainPtr<WKStringRef> wkValue(AdoptWK, WKIntentDataCopyExtraValue(m_wkIntent.get(), keyRef.get())); - return toImpl(wkValue.get())->string(); -} - -WKRetainPtr<WKArrayRef> EwkIntent::extraKeys() const -{ - WKRetainPtr<WKDictionaryRef> wkExtras(AdoptWK, WKIntentDataCopyExtras(m_wkIntent.get())); - return adoptWK(WKDictionaryCopyKeys(wkExtras.get())); -} -#endif - -const char* ewk_intent_action_get(const Ewk_Intent* intent) -{ -#if ENABLE(WEB_INTENTS) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntent, intent, impl, 0); - return impl->action(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(intent, 0); - return 0; -#endif -} - -const char* ewk_intent_type_get(const Ewk_Intent* intent) -{ -#if ENABLE(WEB_INTENTS) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntent, intent, impl, 0); - return impl->type(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(intent, 0); - return 0; -#endif -} - -const char* ewk_intent_service_get(const Ewk_Intent* intent) -{ -#if ENABLE(WEB_INTENTS) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntent, intent, impl, 0); - return impl->service(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(intent, 0); - return 0; -#endif -} - -Eina_List* ewk_intent_suggestions_get(const Ewk_Intent* intent) -{ -#if ENABLE(WEB_INTENTS) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntent, intent, impl, 0); - Eina_List* listOfSuggestions = 0; - WKRetainPtr<WKArrayRef> wkSuggestions = impl->suggestions(); - const size_t numSuggestions = WKArrayGetSize(wkSuggestions.get()); - for (size_t i = 0; i < numSuggestions; ++i) { - WKURLRef wkSuggestion = static_cast<WKURLRef>(WKArrayGetItemAtIndex(wkSuggestions.get(), i)); - listOfSuggestions = eina_list_append(listOfSuggestions, eina_stringshare_add(toImpl(wkSuggestion)->string().utf8().data())); - } - - return listOfSuggestions; - -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(intent, 0); - return 0; -#endif -} - -const char* ewk_intent_extra_get(const Ewk_Intent* intent, const char* key) -{ -#if ENABLE(WEB_INTENTS) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntent, intent, impl, 0); - String value = impl->extra(key); - - if (value.isEmpty()) - return 0; - - return eina_stringshare_add(value.utf8().data()); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(intent, 0); - return 0; -#endif -} - -Eina_List* ewk_intent_extra_names_get(const Ewk_Intent* intent) -{ -#if ENABLE(WEB_INTENTS) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntent, intent, impl, 0); - Eina_List* listOfKeys = 0; - WKRetainPtr<WKArrayRef> wkKeys = impl->extraKeys(); - const size_t numKeys = WKArrayGetSize(wkKeys.get()); - for (size_t i = 0; i < numKeys; ++i) { - WKStringRef wkKey = static_cast<WKStringRef>(WKArrayGetItemAtIndex(wkKeys.get(), i)); - listOfKeys = eina_list_append(listOfKeys, eina_stringshare_add(toImpl(wkKey)->string().utf8().data())); - } - - return listOfKeys; -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(intent, 0); - return 0; -#endif -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_intent.h b/Source/WebKit2/UIProcess/API/efl/ewk_intent.h deleted file mode 100644 index 75448f212..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_intent.h - * @brief Describes the Ewk Intent API. - */ - -#ifndef ewk_intent_h -#define ewk_intent_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Intent as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Intent; - -/** - * Query action for this intent. - * - * @param intent intent item to query. - * - * @return the action pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_action_get(const Ewk_Intent *intent); - -/** - * Query type for this intent. - * - * @param intent intent item to query. - * - * @return the type pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_type_get(const Ewk_Intent *intent); - -/** - * Query service for this intent. - * - * @param intent intent item to query. - * - * @return the service pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_service_get(const Ewk_Intent *intent); - -/** - * Query suggestions for this intent. - * - * This function provides a list of (absolute) suggested Service URLs of which the Client - * is aware and which can handle the intent. - * - * @param intent intent item to query. - * - * @return @c Eina_List with suggested service URLs on success, or @c NULL on failure, - * the Eina_List and its items should be freed after use. Use eina_stringshare_del() - * to free the items. - */ -EAPI Eina_List *ewk_intent_suggestions_get(const Ewk_Intent *intent); - -/** - * Retrieves the value (if any) from the extra data dictionary this intent was constructed with. - * - * The returned string should be freed by eina_stringshare_del() after use. - * - * @param intent intent item to query. - * @param key key to query in the dictionary. - * - * @return a newly allocated string or @c NULL in case of error or if the key does not exist. - */ -EAPI const char *ewk_intent_extra_get(const Ewk_Intent *intent, const char *key); - -/** - * Retrieve a list of the names of extra metadata associated with the intent. - * - * The item of a returned list should be freed by eina_stringshare_del() after use. - * - * @param intent intent item to query. - * - * @return @c Eina_List with names of extra metadata on success, or @c NULL on failure, - * the Eina_List and its items should be freed after use. Use eina_stringshare_del() - * to free the items. - */ -EAPI Eina_List *ewk_intent_extra_names_get(const Ewk_Intent *intent); - -#ifdef __cplusplus -} -#endif -#endif // ewk_intent_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_intent_service.cpp deleted file mode 100644 index b86d46afd..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_intent_service.h" - -#include "IntentServiceInfo.h" -#include "WKAPICast.h" -#include "WKRetainPtr.h" -#include "WKURL.h" -#include "ewk_intent_service_private.h" -#include <wtf/text/CString.h> - -using namespace WebKit; - -#if ENABLE(WEB_INTENTS_TAG) -EwkIntentService::EwkIntentService(WKIntentServiceInfoRef serviceRef) - : m_action(AdoptWK, WKIntentServiceInfoCopyAction(serviceRef)) - , m_type(AdoptWK, WKIntentServiceInfoCopyType(serviceRef)) - , m_href(AdoptWK, WKIntentServiceInfoCopyHref(serviceRef)) - , m_title(AdoptWK, WKIntentServiceInfoCopyTitle(serviceRef)) - , m_disposition(AdoptWK, WKIntentServiceInfoCopyDisposition(serviceRef)) -{ } - -const char* EwkIntentService::action() const -{ - return m_action; -} - -const char* EwkIntentService::type() const -{ - return m_type; -} - -const char* EwkIntentService::href() const -{ - return m_href; -} - -const char* EwkIntentService::title() const -{ - return m_title; -} - -const char* EwkIntentService::disposition() const -{ - return m_disposition; -} -#endif - -const char* ewk_intent_service_action_get(const Ewk_Intent_Service* service) -{ -#if ENABLE(WEB_INTENTS_TAG) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntentService, service, impl, 0); - return impl->action(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(service, 0); - return 0; -#endif -} - -const char* ewk_intent_service_type_get(const Ewk_Intent_Service* service) -{ -#if ENABLE(WEB_INTENTS_TAG) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntentService, service, impl, 0); - return impl->type(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(service, 0); - return 0; -#endif -} - -const char* ewk_intent_service_href_get(const Ewk_Intent_Service* service) -{ -#if ENABLE(WEB_INTENTS_TAG) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntentService, service, impl, 0); - return impl->href(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(service, 0); - return 0; -#endif -} - -const char* ewk_intent_service_title_get(const Ewk_Intent_Service* service) -{ -#if ENABLE(WEB_INTENTS_TAG) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntentService, service, impl, 0); - return impl->title(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(service, 0); - return 0; -#endif -} - -const char* ewk_intent_service_disposition_get(const Ewk_Intent_Service* service) -{ -#if ENABLE(WEB_INTENTS_TAG) - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkIntentService, service, impl, 0); - return impl->disposition(); -#else - EINA_SAFETY_ON_NULL_RETURN_VAL(service, 0); - return 0; -#endif -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service.h b/Source/WebKit2/UIProcess/API/efl/ewk_intent_service.h deleted file mode 100644 index 12e580804..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_intent_service.h - * @brief Describes the Ewk Intent Service API. - */ - -#ifndef ewk_intent_service_h -#define ewk_intent_service_h - -#include <Evas.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Intent_Service as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Intent_Service; - -/** - * Query action for this intent service. - * - * @param service service item to query. - * - * @return the action pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_service_action_get(const Ewk_Intent_Service *service); - -/** - * Query type for this intent service. - * - * @param service service item to query. - * - * @return the type pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_service_type_get(const Ewk_Intent_Service *service); - -/** - * Query URL for this intent service. - * - * @param service service item to query. - * - * @return the URL pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_service_href_get(const Ewk_Intent_Service *service); - -/** - * Query title for this intent service. - * - * @param service service item to query. - * - * @return the title pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_service_title_get(const Ewk_Intent_Service *service); - -/** - * Query disposition for this intent service. - * - * @param service service item to query. - * - * @return the disposition pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_intent_service_disposition_get(const Ewk_Intent_Service *service); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_intent_service_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp index 890bc699a..7c1925cb8 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp @@ -85,7 +85,14 @@ int ewk_init(void) } #endif + if (!edje_init()) { + CRITICAL("Could not init edje."); + goto error_edje; + } + +#if !GLIB_CHECK_VERSION(2, 35, 0) g_type_init(); +#endif if (!ecore_main_loop_glib_integrate()) { WARN("Ecore was not compiled with GLib support, some plugins will not " @@ -94,8 +101,11 @@ int ewk_init(void) return ++_ewkInitCount; +error_edje: #ifdef HAVE_ECORE_X + ecore_x_shutdown(); error_ecore_x: +#else ecore_imf_shutdown(); #endif error_ecore_imf: @@ -118,6 +128,7 @@ int ewk_shutdown(void) if (--_ewkInitCount) return _ewkInitCount; + edje_shutdown(); #ifdef HAVE_ECORE_X ecore_x_shutdown(); #endif diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_page_group.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_page_group.cpp new file mode 100644 index 000000000..84cd5678c --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/ewk_page_group.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ewk_page_group.h" + +#include "WKAPICast.h" +#include "WKArray.h" +#include "WKArrayEfl.h" +#include "WKPageGroup.h" +#include "WKString.h" +#include "ewk_page_group_private.h" + +using namespace WebKit; + +const char EwkPageGroup::defaultIdentifier[] = "defaultPageGroupIdentifier"; + +typedef HashMap<WKPageGroupRef, EwkPageGroup*> PageGroupMap; + +static inline PageGroupMap& pageGroupMap() +{ + DEFINE_STATIC_LOCAL(PageGroupMap, map, ()); + return map; +} + +static WKTypeRef convertFromCharToWKString(void* data) +{ + return WKStringCreateWithUTF8CString(static_cast<char*>(data)); +} + +PassRefPtr<EwkPageGroup> EwkPageGroup::findOrCreateWrapper(WKPageGroupRef pageGroupRef) +{ + if (pageGroupMap().contains(pageGroupRef)) + return pageGroupMap().get(pageGroupRef); + + return adoptRef(new EwkPageGroup(pageGroupRef)); +} + +PassRefPtr<EwkPageGroup> EwkPageGroup::create(const String& identifier) +{ + WKRetainPtr<WKStringRef> identifierRef = adoptWK(toCopiedAPI(identifier.isEmpty() ? defaultIdentifier : identifier)); + WKRetainPtr<WKPageGroupRef> pageGroupRef = adoptWK(WKPageGroupCreateWithIdentifier(identifierRef.get())); + + return adoptRef(new EwkPageGroup(pageGroupRef.get())); +} + +EwkPageGroup::EwkPageGroup(WKPageGroupRef pageGroupRef) + : m_pageGroupRef(pageGroupRef) +{ + PageGroupMap::AddResult result = pageGroupMap().add(pageGroupRef, this); + ASSERT_UNUSED(result, result.isNewEntry); +} + +EwkPageGroup::~EwkPageGroup() +{ + ASSERT(pageGroupMap().get(m_pageGroupRef.get()) == this); + pageGroupMap().remove(m_pageGroupRef.get()); +} + +void EwkPageGroup::addUserStyleSheet(const String& source, const String& baseURL, Eina_List* whiteList, Eina_List* blackList, bool mainFrameOnly) +{ + ASSERT(source); + + WKRetainPtr<WKStringRef> wkSource = adoptWK(toCopiedAPI(source)); + WKRetainPtr<WKURLRef> wkBaseURL = adoptWK(toCopiedURLAPI(baseURL)); + WKRetainPtr<WKArrayRef> wkWhitelist = adoptWK(WKArrayCreateWithEinaList(whiteList, convertFromCharToWKString)); + WKRetainPtr<WKArrayRef> wkBlacklist = adoptWK(WKArrayCreateWithEinaList(blackList, convertFromCharToWKString)); + WKUserContentInjectedFrames injectedFrames = mainFrameOnly ? kWKInjectInTopFrameOnly : kWKInjectInAllFrames; + + WKPageGroupAddUserStyleSheet(m_pageGroupRef.get(), wkSource.get(), wkBaseURL.get(), wkWhitelist.get(), wkBlacklist.get(), injectedFrames); +} + +void EwkPageGroup::removeAllUserStyleSheets() +{ + WKPageGroupRemoveAllUserStyleSheets(m_pageGroupRef.get()); +} + +Ewk_Page_Group* ewk_page_group_create(const char* identifier) +{ + return EwkPageGroup::create(identifier).leakRef(); +} + +Eina_Bool ewk_page_group_user_style_sheet_add(Ewk_Page_Group* ewkPageGroup, const char* source, const char* baseURL, Eina_List* whiteList, Eina_List* blackList, Eina_Bool mainFrameOnly) +{ + EWK_OBJ_GET_IMPL_OR_RETURN(EwkPageGroup, ewkPageGroup, impl, false); + + impl->addUserStyleSheet(source, baseURL, whiteList, blackList, mainFrameOnly); + + return true; +} + +Eina_Bool ewk_page_group_user_style_sheets_remove_all(Ewk_Page_Group* ewkPageGroup) +{ + EWK_OBJ_GET_IMPL_OR_RETURN(EwkPageGroup, ewkPageGroup, impl, false); + + impl->removeAllUserStyleSheets(); + + return true; +} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_page_group.h b/Source/WebKit2/UIProcess/API/efl/ewk_page_group.h new file mode 100644 index 000000000..615edb039 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/ewk_page_group.h @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file ewk_page_group.h + * @brief Describes the Ewk Page Group API. + */ + +#ifndef ewk_page_group_h +#define ewk_page_group_h + +#include <Eina.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Declare Ewk_Page_Group as Ewk_Object. + * + * @see Ewk_Object + */ +typedef struct EwkObject Ewk_Page_Group; + +/** + * Creates a new Ewk_Page_Group. + * + * The returned Ewk_Page_Group object @b should be unref'ed after use. + * + * @return Ewk_Page_Group object on success or @c NULL on failure + * + * @see ewk_object_unref + */ +EAPI Ewk_Page_Group *ewk_page_group_create(const char *identifier); + +/** + * Adds the user style sheet to this page group. + * + * @param page_group ewk_page_gorup object to add the user style sheet + * @param source the user style sheet + * @param url baseURL + * @param white_list url list to allow adding the user style sheet + * @param black_list url list to disallow adding the user style sheet + * @param main_frame_only a state to apply the user style sheet only to the mainframe + * + * @return @c EINA_TRUE if the user style sheet is added to the page group, or + * @c EINA_FALSE otherwise + */ +EAPI Eina_Bool ewk_page_group_user_style_sheet_add(Ewk_Page_Group *page_group, const char *source, const char *base_url, Eina_List *white_list, Eina_List *black_list, Eina_Bool main_frame_only); + +/** + * Remove all the user style sheets from this page group. + * + * @param page_group page group object to remove all the user style sheets + * + * @return @c EINA_TRUE if all the user style sheet are removed from the page group, or + * @c EINA_FALSE otherwise + */ +EAPI Eina_Bool ewk_page_group_user_style_sheets_remove_all(Ewk_Page_Group *page_group); + +#ifdef __cplusplus +} +#endif + +#endif // ewk_page_group_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_page_group_private.h index 7a98a645d..3f922017d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_page_group_private.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,46 +23,39 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ewk_intent_service_private_h -#define ewk_intent_service_private_h +#ifndef ewk_page_group_private_h +#define ewk_page_group_private_h -#if ENABLE(WEB_INTENTS_TAG) - -#include "WKEinaSharedString.h" -#include "WKIntentServiceInfo.h" #include "ewk_object_private.h" +#include <Evas.h> #include <WebKit2/WKBase.h> -#include <wtf/PassRefPtr.h> +#include <WebKit2/WKRetainPtr.h> +#include <WebKit2/WKURL.h> +#include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> -/** - * \struct EwkIntentService - * @brief Contains the intent service data. - */ -class EwkIntentService : public EwkObject { +class EwkView; + +class EwkPageGroup : public EwkObject { public: - EWK_OBJECT_DECLARE(EwkIntentService) + EWK_OBJECT_DECLARE(EwkPageGroup) + + static PassRefPtr<EwkPageGroup> findOrCreateWrapper(WKPageGroupRef pageGroupRef); + static PassRefPtr<EwkPageGroup> create(const String& identifier = String()); - static PassRefPtr<EwkIntentService> create(WKIntentServiceInfoRef serviceRef) - { - return adoptRef(new EwkIntentService(serviceRef)); - } + ~EwkPageGroup(); - const char* action() const; - const char* type() const; - const char* href() const; - const char* title() const; - const char* disposition() const; + WKPageGroupRef wkPageGroup() const { return m_pageGroupRef.get(); } + + void addUserStyleSheet(const String& source, const String& baseURL, Eina_List* whitelist, Eina_List* blacklist, bool mainFrameOnly); + void removeAllUserStyleSheets(); private: - explicit EwkIntentService(WKIntentServiceInfoRef serviceRef); + explicit EwkPageGroup(WKPageGroupRef pageGroupRef); - WKEinaSharedString m_action; - WKEinaSharedString m_type; - WKEinaSharedString m_href; - WKEinaSharedString m_title; - WKEinaSharedString m_disposition; -}; + static const char defaultIdentifier[]; -#endif // ENABLE(WEB_INTENTS_TAG) + WKRetainPtr<WKPageGroupRef> m_pageGroupRef; +}; -#endif // ewk_intent_service_private_h +#endif // ewk_page_group_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.cpp index f1dad3ab7..1c8c33af1 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.cpp @@ -27,34 +27,37 @@ #include "config.h" #include "ewk_popup_menu.h" -#include "EwkViewImpl.h" -#include "WebPopupMenuProxyEfl.h" +#include "EwkView.h" +#include "WKAPICast.h" +#include "WKArray.h" +#include "WKPopupMenuListener.h" #include "ewk_popup_menu_item_private.h" #include "ewk_popup_menu_private.h" -using namespace WebKit; - -EwkPopupMenu::EwkPopupMenu(EwkViewImpl* viewImpl, WebPopupMenuProxyEfl* popupMenuProxy, const Vector<WebKit::WebPopupItem>& items, unsigned selectedIndex) - : m_viewImpl(viewImpl) - , m_popupMenuProxy(popupMenuProxy) +EwkPopupMenu::EwkPopupMenu(EwkView* view, WKPopupMenuListenerRef popupMenuListener, WKArrayRef items, unsigned selectedIndex) + : m_view(view) + , m_popupMenuListener(popupMenuListener) , m_popupMenuItems(0) , m_selectedIndex(selectedIndex) { - const size_t size = items.size(); - for (size_t i = 0; i < size; ++i) - m_popupMenuItems = eina_list_append(m_popupMenuItems, Ewk_Popup_Menu_Item::create(items[i]).leakPtr()); + size_t size = WKArrayGetSize(items); + for (size_t i = 0; i < size; ++i) { + WKPopupItemRef wkItem = static_cast<WKPopupItemRef>(WKArrayGetItemAtIndex(items, i)); + m_popupMenuItems = eina_list_append(m_popupMenuItems, EwkPopupMenuItem::create(wkItem).leakPtr()); + } } EwkPopupMenu::~EwkPopupMenu() { void* item; EINA_LIST_FREE(m_popupMenuItems, item) - delete static_cast<Ewk_Popup_Menu_Item*>(item); + delete static_cast<EwkPopupMenuItem*>(item); } void EwkPopupMenu::close() { - m_viewImpl->closePopupMenu(); + // Setting selected item will cause the popup menu to close. + WKPopupMenuListenerSetSelection(m_popupMenuListener.get(), m_selectedIndex); } const Eina_List* EwkPopupMenu::items() const @@ -69,7 +72,7 @@ unsigned EwkPopupMenu::selectedIndex() const bool EwkPopupMenu::setSelectedIndex(unsigned selectedIndex) { - if (!m_popupMenuProxy) + if (!m_popupMenuListener) return false; if (selectedIndex >= eina_list_count(m_popupMenuItems)) @@ -79,7 +82,7 @@ bool EwkPopupMenu::setSelectedIndex(unsigned selectedIndex) return true; m_selectedIndex = selectedIndex; - m_popupMenuProxy->valueChanged(selectedIndex); + WKPopupMenuListenerSetSelection(m_popupMenuListener.get(), selectedIndex); return true; } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp index 0a51d958a..9c428341d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp @@ -26,72 +26,71 @@ #include "config.h" #include "ewk_popup_menu_item.h" +#include "WKPopupItem.h" #include "ewk_popup_menu_item_private.h" #include "ewk_private.h" -#include <wtf/text/CString.h> - -using namespace WebKit; - -EwkPopupMenuItem::EwkPopupMenuItem(const WebKit::WebPopupItem& item) - : m_type(static_cast<Ewk_Popup_Menu_Item_Type>(item.m_type)) - , m_textDirection(static_cast<Ewk_Text_Direction>(item.m_textDirection)) - , m_hasTextDirectionOverride(item.m_hasTextDirectionOverride) - , m_isEnabled(item.m_isEnabled) - , m_isLabel(item.m_isLabel) - , m_isSelected(item.m_isSelected) - , m_text(item.m_text.utf8().data()) - , m_tooltipText(item.m_toolTip.utf8().data()) - , m_accessibilityText(item.m_accessibilityText.utf8().data()) + +EwkPopupMenuItem::EwkPopupMenuItem(WKPopupItemRef item) + : m_wkItem(item) { } +COMPILE_ASSERT_MATCHING_ENUM(EWK_POPUP_MENU_SEPARATOR, kWKPopupItemTypeSeparator); +COMPILE_ASSERT_MATCHING_ENUM(EWK_POPUP_MENU_ITEM, kWKPopupItemTypeItem); + Ewk_Popup_Menu_Item_Type EwkPopupMenuItem::type() const { - return m_type; + return static_cast<Ewk_Popup_Menu_Item_Type>(WKPopupItemGetType(m_wkItem.get())); } Ewk_Text_Direction EwkPopupMenuItem::textDirection() const { - return m_textDirection; + return static_cast<Ewk_Text_Direction>(WKPopupItemGetTextDirection(m_wkItem.get())); } const char* EwkPopupMenuItem::text() const { + if (!m_text) + m_text = WKEinaSharedString(AdoptWK, WKPopupItemCopyText(m_wkItem.get())); + return m_text; } const char* EwkPopupMenuItem::tooltipText() const { + if (!m_tooltipText) + m_tooltipText = WKEinaSharedString(AdoptWK, WKPopupItemCopyToolTipText(m_wkItem.get())); + return m_tooltipText; } const char* EwkPopupMenuItem::accessibilityText() const { + if (!m_accessibilityText) + m_accessibilityText = WKEinaSharedString(AdoptWK, WKPopupItemCopyAccessibilityText(m_wkItem.get())); + return m_accessibilityText; } bool EwkPopupMenuItem::hasTextDirectionOverride() const { - return m_hasTextDirectionOverride; + return WKPopupItemHasTextDirectionOverride(m_wkItem.get()); } bool EwkPopupMenuItem::isEnabled() const { - return m_isEnabled; + return WKPopupItemIsEnabled(m_wkItem.get()); } bool EwkPopupMenuItem::isLabel() const { - return m_isLabel; + return WKPopupItemIsLabel(m_wkItem.get()); } bool EwkPopupMenuItem::isSelected() const { - return m_isSelected; + return WKPopupItemIsSelected(m_wkItem.get()); } -COMPILE_ASSERT_MATCHING_ENUM(EWK_POPUP_MENU_SEPARATOR, WebPopupItem::Separator); -COMPILE_ASSERT_MATCHING_ENUM(EWK_POPUP_MENU_ITEM, WebPopupItem::Item); - Ewk_Popup_Menu_Item_Type ewk_popup_menu_item_type_get(const Ewk_Popup_Menu_Item* item) { EINA_SAFETY_ON_NULL_RETURN_VAL(item, EWK_POPUP_MENU_UNKNOWN); diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item_private.h index 680a391f1..d8d2b8cce 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item_private.h @@ -27,8 +27,9 @@ #define ewk_popup_menu_item_private_h #include "WKEinaSharedString.h" -#include "WebPopupItem.h" +#include "WKRetainPtr.h" #include "ewk_popup_menu_item.h" +#include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> /** @@ -37,7 +38,7 @@ */ class EwkPopupMenuItem { public: - static PassOwnPtr<EwkPopupMenuItem> create(const WebKit::WebPopupItem& item) + static PassOwnPtr<EwkPopupMenuItem> create(WKPopupItemRef item) { return adoptPtr(new EwkPopupMenuItem(item)); } @@ -55,19 +56,14 @@ public: const char* accessibilityText() const; private: - explicit EwkPopupMenuItem(const WebKit::WebPopupItem& item); + explicit EwkPopupMenuItem(WKPopupItemRef item); - Ewk_Popup_Menu_Item_Type m_type; - Ewk_Text_Direction m_textDirection; + WKRetainPtr<WKPopupItemRef> m_wkItem; - bool m_hasTextDirectionOverride; - bool m_isEnabled; - bool m_isLabel; - bool m_isSelected; - - WKEinaSharedString m_text; - WKEinaSharedString m_tooltipText; - WKEinaSharedString m_accessibilityText; + // Lazily initialized. + mutable WKEinaSharedString m_text; + mutable WKEinaSharedString m_tooltipText; + mutable WKEinaSharedString m_accessibilityText; }; #endif // ewk_popup_menu_item_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_private.h index 2b5de0684..5cd2e3aaf 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_private.h @@ -28,21 +28,16 @@ #define ewk_popup_menu_private_h #include <Eina.h> +#include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> -namespace WebKit { -class WebPopupItem; -class WebPopupMenuProxyEfl; -} - -class EwkViewImpl; +class EwkView; class EwkPopupMenu { public: - static PassOwnPtr<EwkPopupMenu> create(EwkViewImpl* viewImpl, WebKit::WebPopupMenuProxyEfl* popupMenuProxy, const Vector<WebKit::WebPopupItem>& items, unsigned selectedIndex) + static PassOwnPtr<EwkPopupMenu> create(EwkView* view, WKPopupMenuListenerRef popupMenuListener, WKArrayRef items, unsigned selectedIndex) { - return adoptPtr(new EwkPopupMenu(viewImpl, popupMenuProxy, items, selectedIndex)); + return adoptPtr(new EwkPopupMenu(view, popupMenuListener, items, selectedIndex)); } ~EwkPopupMenu(); @@ -54,10 +49,10 @@ public: unsigned selectedIndex() const; private: - EwkPopupMenu(EwkViewImpl* viewImpl, WebKit::WebPopupMenuProxyEfl*, const Vector<WebKit::WebPopupItem>& items, unsigned selectedIndex); + EwkPopupMenu(EwkView* viewImpl, WKPopupMenuListenerRef, WKArrayRef items, unsigned selectedIndex); - EwkViewImpl* m_viewImpl; - WebKit::WebPopupMenuProxyEfl* m_popupMenuProxy; + EwkView* m_view; + WKRetainPtr<WKPopupMenuListenerRef> m_popupMenuListener; Eina_List* m_popupMenuItems; unsigned m_selectedIndex; }; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_resource.h b/Source/WebKit2/UIProcess/API/efl/ewk_resource.h deleted file mode 100644 index ca36b6c54..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_resource.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_resource.h - * @brief Describes the Web Resource API. - */ - -#ifndef ewk_resource_h -#define ewk_resource_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Resource as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Resource; - -/** - * Query URL for this resource. - * - * @param resource resource object to query. - * - * @return the URL pointer, that may be @c NULL. This pointer is - * guaranteed to be eina_stringshare, so whenever possible - * save yourself some cpu cycles and use - * eina_stringshare_ref() instead of eina_stringshare_add() or - * strdup(). - */ -EAPI const char *ewk_resource_url_get(const Ewk_Resource *resource); - -/** - * Query if this is the main resource. - * - * @param resource resource object to query. - * - * @return @c EINA_TRUE if this is the main resource, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_resource_main_resource_get(const Ewk_Resource *resource); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_resource_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp index 60d8e39f8..b476f4444 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp @@ -28,11 +28,9 @@ #include "WKAPICast.h" #include "WKSecurityOrigin.h" -#include "WebSecurityOrigin.h" +#include "WKString.h" #include "ewk_security_origin_private.h" -#include <WebCore/SecurityOrigin.h> -using namespace WebCore; using namespace WebKit; EwkSecurityOrigin::EwkSecurityOrigin(WKSecurityOriginRef originRef) @@ -41,8 +39,8 @@ EwkSecurityOrigin::EwkSecurityOrigin(WKSecurityOriginRef originRef) , m_protocol(AdoptWK, WKSecurityOriginCopyProtocol(originRef)) { } -EwkSecurityOrigin::EwkSecurityOrigin(const KURL& url) - : m_wkOrigin(AdoptWK, toAPI(WebSecurityOrigin::create(SecurityOrigin::create(url)).leakRef())) +EwkSecurityOrigin::EwkSecurityOrigin(const char* url) + : m_wkOrigin(AdoptWK, WKSecurityOriginCreateFromString(adoptWK(WKStringCreateWithUTF8CString(url)).get())) , m_host(AdoptWK, WKSecurityOriginCopyHost(m_wkOrigin.get())) , m_protocol(AdoptWK, WKSecurityOriginCopyProtocol(m_wkOrigin.get())) { } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h index a2d3b317b..e787ce15d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h @@ -27,9 +27,7 @@ #define ewk_security_origin_private_h #include "WKEinaSharedString.h" -#include "WKSecurityOrigin.h" #include "ewk_object_private.h" -#include <WebCore/KURL.h> #include <WebKit2/WKBase.h> #include <wtf/PassRefPtr.h> @@ -42,7 +40,7 @@ public: return adoptRef(new EwkSecurityOrigin(originRef)); } - static PassRefPtr<EwkSecurityOrigin> create(const WebCore::KURL& url) + static PassRefPtr<EwkSecurityOrigin> create(const char* url) { return adoptRef(new EwkSecurityOrigin(url)); } @@ -53,7 +51,7 @@ public: private: explicit EwkSecurityOrigin(WKSecurityOriginRef originRef); - explicit EwkSecurityOrigin(const WebCore::KURL& url); + explicit EwkSecurityOrigin(const char* url); WKRetainPtr<WKSecurityOriginRef> m_wkOrigin; WKEinaSharedString m_host; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp index 7f7c49467..21b4bba09 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp @@ -27,61 +27,24 @@ #include "config.h" #include "ewk_settings.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "ewk_settings_private.h" #include <WebKit2/WebPageGroup.h> #include <WebKit2/WebPageProxy.h> #include <WebKit2/WebPreferences.h> -#if ENABLE(SPELLCHECK) -#include "WKTextChecker.h" -#include "ewk_text_checker_private.h" -#include <Ecore.h> -#include <wtf/Vector.h> -#include <wtf/text/CString.h> -#endif - using namespace WebKit; const WebKit::WebPreferences* EwkSettings::preferences() const { - return m_viewImpl->page()->pageGroup()->preferences(); + return m_view->page()->pageGroup()->preferences(); } WebKit::WebPreferences* EwkSettings::preferences() { - return m_viewImpl->page()->pageGroup()->preferences(); -} - -#if ENABLE(SPELLCHECK) -static struct { - bool isContinuousSpellCheckingEnabled : 1; - Vector<String> spellCheckingLanguages; - Ewk_Settings_Continuous_Spell_Checking_Change_Cb onContinuousSpellChecking; -} ewkTextCheckerSettings = { false, Vector<String>(), 0 }; - -static Eina_Bool onContinuousSpellCheckingIdler(void*) -{ - if (ewkTextCheckerSettings.onContinuousSpellChecking) - ewkTextCheckerSettings.onContinuousSpellChecking(ewkTextCheckerSettings.isContinuousSpellCheckingEnabled); - - return ECORE_CALLBACK_CANCEL; -} - -static Eina_Bool spellCheckingLanguagesSetUpdate(void*) -{ - // FIXME: Consider to delegate calling of this method in WebProcess to do not delay/block UIProcess. - Ewk_Text_Checker::updateSpellCheckingLanguages(ewkTextCheckerSettings.spellCheckingLanguages); - return ECORE_CALLBACK_CANCEL; + return m_view->page()->pageGroup()->preferences(); } -static void spellCheckingLanguagesSet(const Vector<String>& newLanguages) -{ - ewkTextCheckerSettings.spellCheckingLanguages = newLanguages; - ecore_idler_add(spellCheckingLanguagesSetUpdate, 0); -} -#endif // ENABLE(SPELLCHECK) - Eina_Bool ewk_settings_fullscreen_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { #if ENABLE(FULLSCREEN_API) @@ -89,6 +52,8 @@ Eina_Bool ewk_settings_fullscreen_enabled_set(Ewk_Settings* settings, Eina_Bool settings->preferences()->setFullScreenEnabled(enable); return true; #else + UNUSED_PARAM(settings); + UNUSED_PARAM(enable); return false; #endif } @@ -99,6 +64,7 @@ Eina_Bool ewk_settings_fullscreen_enabled_get(const Ewk_Settings* settings) EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); return settings->preferences()->fullScreenEnabled(); #else + UNUSED_PARAM(settings); return false; #endif } @@ -199,152 +165,156 @@ Eina_Bool ewk_settings_dns_prefetching_enabled_get(const Ewk_Settings* settings) return settings->preferences()->dnsPrefetchingEnabled(); } -void ewk_settings_continuous_spell_checking_change_cb_set(Ewk_Settings_Continuous_Spell_Checking_Change_Cb callback) +Eina_Bool ewk_settings_encoding_detector_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { -#if ENABLE(SPELLCHECK) - ewkTextCheckerSettings.onContinuousSpellChecking = callback; -#endif + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + + settings->preferences()->setUsesEncodingDetector(enable); + + return true; } -Eina_Bool ewk_settings_continuous_spell_checking_enabled_get() +Eina_Bool ewk_settings_encoding_detector_enabled_get(const Ewk_Settings* settings) { -#if ENABLE(SPELLCHECK) - return ewkTextCheckerSettings.isContinuousSpellCheckingEnabled; -#else - return false; -#endif + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + + return settings->preferences()->usesEncodingDetector(); } -void ewk_settings_continuous_spell_checking_enabled_set(Eina_Bool enable) +Eina_Bool ewk_settings_preferred_minimum_contents_width_set(Ewk_Settings *settings, unsigned width) { -#if ENABLE(SPELLCHECK) - enable = !!enable; - if (ewkTextCheckerSettings.isContinuousSpellCheckingEnabled != enable) { - ewkTextCheckerSettings.isContinuousSpellCheckingEnabled = enable; + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - WKTextCheckerContinuousSpellCheckingEnabledStateChanged(enable); + settings->preferences()->setLayoutFallbackWidth(width); - // Sets the default language if user didn't specify any. - if (enable && !Ewk_Text_Checker::hasDictionary()) - spellCheckingLanguagesSet(Vector<String>()); + return true; +} - if (ewkTextCheckerSettings.onContinuousSpellChecking) - ecore_idler_add(onContinuousSpellCheckingIdler, 0); - } -#endif +unsigned ewk_settings_preferred_minimum_contents_width_get(const Ewk_Settings *settings) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + + return settings->preferences()->layoutFallbackWidth(); } -Eina_List* ewk_settings_spell_checking_available_languages_get() +Eina_Bool ewk_settings_offline_web_application_cache_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { - Eina_List* listOflanguages = 0; -#if ENABLE(SPELLCHECK) - const Vector<String>& languages = Ewk_Text_Checker::availableSpellCheckingLanguages(); - size_t numberOfLanuages = languages.size(); + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + settings->preferences()->setOfflineWebApplicationCacheEnabled(enable); - for (size_t i = 0; i < numberOfLanuages; ++i) - listOflanguages = eina_list_append(listOflanguages, eina_stringshare_add(languages[i].utf8().data())); -#endif - return listOflanguages; + return true; } -void ewk_settings_spell_checking_languages_set(const char* languages) +Eina_Bool ewk_settings_offline_web_application_cache_enabled_get(const Ewk_Settings* settings) { -#if ENABLE(SPELLCHECK) - Vector<String> newLanguages; - String::fromUTF8(languages).split(',', newLanguages); + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - spellCheckingLanguagesSet(newLanguages); -#endif + return settings->preferences()->offlineWebApplicationCacheEnabled(); } -Eina_List* ewk_settings_spell_checking_languages_get() +Eina_Bool ewk_settings_scripts_can_open_windows_set(Ewk_Settings* settings, Eina_Bool enable) { - Eina_List* listOflanguages = 0; -#if ENABLE(SPELLCHECK) - Vector<String> languages = Ewk_Text_Checker::loadedSpellCheckingLanguages(); - size_t numberOfLanuages = languages.size(); + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + settings->preferences()->setJavaScriptCanOpenWindowsAutomatically(enable); + + return true; +} - for (size_t i = 0; i < numberOfLanuages; ++i) - listOflanguages = eina_list_append(listOflanguages, eina_stringshare_add(languages[i].utf8().data())); +Eina_Bool ewk_settings_scripts_can_open_windows_get(const Ewk_Settings* settings) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); -#endif - return listOflanguages; + return settings->preferences()->javaScriptCanOpenWindowsAutomatically(); } -Eina_Bool ewk_settings_encoding_detector_enabled_set(Ewk_Settings* settings, Eina_Bool enable) +Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setUsesEncodingDetector(enable); + settings->preferences()->setLocalStorageEnabled(enable); return true; } -Eina_Bool ewk_settings_encoding_detector_enabled_get(const Ewk_Settings* settings) +Eina_Bool ewk_settings_local_storage_enabled_get(const Ewk_Settings* settings) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - return settings->preferences()->usesEncodingDetector(); + return settings->preferences()->localStorageEnabled(); } -Eina_Bool ewk_settings_preferred_minimum_contents_width_set(Ewk_Settings *settings, unsigned width) +Eina_Bool ewk_settings_plugins_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setLayoutFallbackWidth(width); + settings->preferences()->setPluginsEnabled(enable); return true; } -unsigned ewk_settings_preferred_minimum_contents_width_get(const Ewk_Settings *settings) +Eina_Bool ewk_settings_plugins_enabled_get(const Ewk_Settings* settings) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - return settings->preferences()->layoutFallbackWidth(); + return settings->preferences()->pluginsEnabled(); } -Eina_Bool ewk_settings_offline_web_application_cache_enabled_set(Ewk_Settings* settings, Eina_Bool enable) +Eina_Bool ewk_settings_default_font_size_set(Ewk_Settings* settings, int size) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setOfflineWebApplicationCacheEnabled(enable); + + settings->preferences()->setDefaultFontSize(size); return true; } -Eina_Bool ewk_settings_offline_web_application_cache_enabled_get(const Ewk_Settings* settings) +int ewk_settings_default_font_size_get(const Ewk_Settings* settings) { - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); + EINA_SAFETY_ON_NULL_RETURN_VAL(settings, 0); - return settings->preferences()->offlineWebApplicationCacheEnabled(); + return settings->preferences()->defaultFontSize(); } -Eina_Bool ewk_settings_scripts_can_open_windows_set(Ewk_Settings* settings, Eina_Bool enable) +Eina_Bool ewk_settings_private_browsing_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setJavaScriptCanOpenWindowsAutomatically(enable); + + settings->preferences()->setPrivateBrowsingEnabled(enable); return true; } -Eina_Bool ewk_settings_scripts_can_open_windows_get(const Ewk_Settings* settings) +Eina_Bool ewk_settings_private_browsing_enabled_get(const Ewk_Settings* settings) { EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - return settings->preferences()->javaScriptCanOpenWindowsAutomatically(); + return settings->preferences()->privateBrowsingEnabled(); } -Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings* settings, Eina_Bool enable) +Eina_Bool ewk_settings_text_autosizing_enabled_set(Ewk_Settings* settings, Eina_Bool enable) { +#if ENABLE(TEXT_AUTOSIZING) EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setLocalStorageEnabled(enable); + settings->preferences()->setTextAutosizingEnabled(enable); return true; +#else + UNUSED_PARAM(settings); + UNUSED_PARAM(enable); + return false; +#endif } -Eina_Bool ewk_settings_local_storage_enabled_get(const Ewk_Settings* settings) +Eina_Bool ewk_settings_text_autosizing_enabled_get(const Ewk_Settings* settings) { +#if ENABLE(TEXT_AUTOSIZING) EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - return settings->preferences()->localStorageEnabled(); + return settings->preferences()->textAutosizingEnabled(); +#else + UNUSED_PARAM(settings); + return false; +#endif } + diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings.h b/Source/WebKit2/UIProcess/API/efl/ewk_settings.h index eb8cb1683..831c515f7 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_settings.h @@ -43,14 +43,6 @@ extern "C" { /** Creates a type name for Ewk_Settings */ typedef struct EwkSettings Ewk_Settings; -/** - * Creates a type name for the callback function used to notify the client when - * the continuous spell checking setting was changed by WebKit. - * - * @param enable @c EINA_TRUE if continuous spell checking is enabled or @c EINA_FALSE if it's disabled - */ -typedef void (*Ewk_Settings_Continuous_Spell_Checking_Change_Cb)(Eina_Bool enable); - /** * Enables/disables the Javascript Fullscreen API. The Javascript API allows @@ -229,76 +221,6 @@ EAPI Eina_Bool ewk_settings_dns_prefetching_enabled_set(Ewk_Settings *settings, EAPI Eina_Bool ewk_settings_dns_prefetching_enabled_get(const Ewk_Settings *settings); /** - * Sets a callback function used to notify the client when - * the continuous spell checking setting was changed by WebKit. - * - * Specifying of this callback is needed if the application wants to receive notifications - * once WebKit changes this setting. - * If the application is not interested, this callback is not set. - * Changing of this setting at the WebKit level can be made as a result of modifying - * options in a Context Menu by a user. - * - * @param cb a new callback function to set or @c NULL to invalidate the previous one - */ -EAPI void ewk_settings_continuous_spell_checking_change_cb_set(Ewk_Settings_Continuous_Spell_Checking_Change_Cb cb); - -/** - * Queries if continuous spell checking is enabled. - * - * @return @c EINA_TRUE if continuous spell checking is enabled or @c EINA_FALSE if it's disabled - */ -EAPI Eina_Bool ewk_settings_continuous_spell_checking_enabled_get(void); - -/** - * Enables/disables continuous spell checking. - * - * Additionally, this function calls a callback function (if defined) to notify - * the client about the change of the setting. - * This feature is disabled by default. - * - * @see ewk_settings_continuous_spell_checking_change_cb_set - * - * @param enable @c EINA_TRUE to enable continuous spell checking or @c EINA_FALSE to disable - */ -EAPI void ewk_settings_continuous_spell_checking_enabled_set(Eina_Bool enable); - -/** - * Gets the the list of all available the spell checking languages to use. - * - * @see ewk_settings_spell_checking_languages_set - * - * @return the list with available spell checking languages, or @c NULL on failure - * the Eina_List and its items should be freed after, use eina_stringshare_del() - */ -EAPI Eina_List *ewk_settings_spell_checking_available_languages_get(void); - -/** - * Sets @a languages as the list of languages to use by default WebKit - * implementation of spellchecker feature with Enchant library support. - * - * If @languages is @c NULL, the default language is used. - * If the default language can not be determined then any available dictionary will be used. - * - * @note This function invalidates the previously set languages. - * The dictionaries are requested asynchronously. - * - * @param languages a list of comma (',') separated language codes - * of the form 'en_US', ie, language_VARIANT, may be @c NULL. - */ -EAPI void ewk_settings_spell_checking_languages_set(const char *languages); - -/** - * Gets the the list of the spell checking languages in use. - * - * @see ewk_settings_spell_checking_available_languages_get - * @see ewk_settings_spell_checking_languages_set - * - * @return the list with the spell checking languages in use, - * the Eina_List and its items should be freed after, use eina_stringshare_del() - */ -EAPI Eina_List *ewk_settings_spell_checking_languages_get(void); - -/** * Enables/disables the encoding detector. * * By default, the encoding detector is disabled. @@ -424,6 +346,104 @@ EAPI Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings *settings, Ei */ EAPI Eina_Bool ewk_settings_local_storage_enabled_get(const Ewk_Settings *settings); +/** + * Toggles plug-ins support. + * + * By default, plug-ins support is enabled. + * + * @param settings settings object to set plug-ins support + * @param enable @c EINA_TRUE to enable plug-ins support + * @c EINA_FALSE to disable + * + * @return @c EINA_TRUE on success or @c EINA_FALSE on failure + */ +EAPI Eina_Bool ewk_settings_plugins_enabled_set(Ewk_Settings *settings, Eina_Bool enable); + +/** + * Returns whether plug-ins support is enabled or not. + * + * @param settings settings object to query whether plug-ins support is enabled + * + * @return @c EINA_TRUE if plug-ins support is enabled + * @c EINA_FALSE if not or on failure + */ +EAPI Eina_Bool ewk_settings_plugins_enabled_get(const Ewk_Settings *settings); + +/** + * Sets the default font size. + * + * By default, the default font size is @c 16. + * + * @param settings settings object to set the default font size + * @param size a new default font size to set + * + * @return @c EINA_TRUE on success or @c EINA_FALSE on failure + */ +EAPI Eina_Bool ewk_settings_default_font_size_set(Ewk_Settings *settings, int size); + +/** + * Returns the default font size. + * + * @param settings settings object to get the default font size + * + * @return @c the default font size or @c 0 on failure + */ +EAPI int ewk_settings_default_font_size_get(const Ewk_Settings *settings); + +/** + * Enables/disables private browsing. + * + * By default, private browsing is disabled. + * + * @param settings settings object to set private browsing + * @param enable @c EINA_TRUE to enable private browsing + * @c EINA_FALSE to disable + * + * @return @c EINA_TRUE on success or @c EINA_FALSE on failure + */ +EAPI Eina_Bool ewk_settings_private_browsing_enabled_set(Ewk_Settings *settings, Eina_Bool enable); + +/** + * Returns whether private browsing is enabled or not. + * + * Private Browsing allows a user to browse the Internet without saving any information + * about which sites and pages a user has visited. + * + * @param settings settings object to query whether private browsing is enabled + * + * @return @c EINA_TRUE if private browsing is enabled + * @c EINA_FALSE if not or on failure + */ +EAPI Eina_Bool ewk_settings_private_browsing_enabled_get(const Ewk_Settings *settings); + +/** + * Enables/disables text autosizing. + * + * By default, the text autosizing is disabled. + * + * @param settings settings object to set the text autosizing + * @param enable @c EINA_TRUE to enable the text autosizing + * @c EINA_FALSE to disable + * + * @return @c EINA_TRUE on success or @c EINA_FALSE on failure + * + * @see ewk_settings_text_autosizing_enabled_get() + */ +EAPI Eina_Bool ewk_settings_text_autosizing_enabled_set(Ewk_Settings *settings, Eina_Bool enable); + +/** + * Returns whether the text autosizing is enabled. + * + * The text autosizing is a feature which adjusts the font size of text in wide + * columns, and makes text more legible. + * + * @param settings settings object to query whether text autosizing is enabled + * + * @return @c EINA_TRUE if the text autosizing is enabled + * @c EINA_FALSE if not or on failure + */ +EAPI Eina_Bool ewk_settings_text_autosizing_enabled_get(const Ewk_Settings *settings); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_settings_private.h index 3335aad71..0b85d9b2f 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_settings_private.h @@ -32,14 +32,14 @@ namespace WebKit { class WebPreferences; } -class EwkViewImpl; +class EwkView; /** * \struct Ewk_Settings * @brief Contains the settings data. */ class EwkSettings { public: - static PassOwnPtr<EwkSettings> create(EwkViewImpl* viewImpl) + static PassOwnPtr<EwkSettings> create(EwkView* viewImpl) { return adoptPtr(new EwkSettings(viewImpl)); } @@ -48,13 +48,13 @@ public: WebKit::WebPreferences* preferences(); private: - explicit EwkSettings(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) + explicit EwkSettings(EwkView* viewImpl) + : m_view(viewImpl) { - ASSERT(m_viewImpl); + ASSERT(m_view); } - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; #endif // ewk_settings_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp index 282c7a017..fd0eaeb39 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp @@ -28,21 +28,21 @@ #include "WKAPICast.h" #include "WKArray.h" -#include "WebKeyValueStorageManagerProxy.h" #include "ewk_error_private.h" -#include "ewk_security_origin.h" #include "ewk_security_origin_private.h" #include "ewk_storage_manager_private.h" using namespace WebKit; -EwkStorageManager::EwkStorageManager(WebKeyValueStorageManagerProxy* storageManagerProxy) - : m_storageManager(storageManagerProxy) -{ } +EwkStorageManager::EwkStorageManager(WKKeyValueStorageManagerRef storageManager) + : m_storageManager(storageManager) +{ + ASSERT(storageManager); +} void EwkStorageManager::getStorageOrigins(void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) const { - WKKeyValueStorageManagerGetKeyValueStorageOrigins(toAPI(m_storageManager.get()), context, callback); + WKKeyValueStorageManagerGetKeyValueStorageOrigins(m_storageManager.get(), context, callback); } Eina_List* EwkStorageManager::createOriginList(WKArrayRef origins) const @@ -52,7 +52,7 @@ Eina_List* EwkStorageManager::createOriginList(WKArrayRef origins) const for (size_t i = 0; i < length; ++i) { WKSecurityOriginRef wkOriginRef = static_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, i)); - RefPtr<Ewk_Security_Origin> origin = m_wrapperCache.get(wkOriginRef); + RefPtr<EwkSecurityOrigin> origin = m_wrapperCache.get(wkOriginRef); if (!origin) { origin = EwkSecurityOrigin::create(wkOriginRef); m_wrapperCache.set(wkOriginRef, origin); @@ -82,7 +82,7 @@ static void getStorageOriginsCallback(WKArrayRef origins, WKErrorRef wkError, vo originList = webStorageContext->manager->createOriginList(origins); - OwnPtr<Ewk_Error> ewkError = Ewk_Error::create(wkError); + OwnPtr<EwkError> ewkError = EwkError::create(wkError); webStorageContext->callback(originList, ewkError.get(), webStorageContext->userData); } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h index f9d039bbd..4f5c8fb30 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h @@ -48,7 +48,7 @@ typedef struct EwkStorageManager Ewk_Storage_Manager; * @brief Callback type for use with ewk_storage_manager_origins_get(). * * @param origins @c Eina_List containing @c Ewk_Security_Origin elements or @c NULL in case of error, - * the Eina_List and its items should be freed after use. Use ewk_security_origin_unref() + * the Eina_List and its items should be freed after use. Use ewk_object_unref() * to free the items */ typedef void (*Ewk_Storage_Origins_Get_Cb)(Eina_List *origins, Ewk_Error *error, void *user_data); diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h index 5dd4b081e..550cff0f4 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h @@ -27,8 +27,7 @@ #define ewk_storage_manager_private_h #include "WKKeyValueStorageManager.h" -#include "WebContext.h" -#include "WebKeyValueStorageManagerProxy.h" +#include "WKRetainPtr.h" #include "ewk_security_origin_private.h" #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> @@ -37,20 +36,20 @@ using namespace WebKit; class EwkStorageManager { public: - static PassOwnPtr<EwkStorageManager> create(PassRefPtr<WebContext> context) + static PassOwnPtr<EwkStorageManager> create(WKKeyValueStorageManagerRef storageManager) { - ASSERT(context); - return adoptPtr(new EwkStorageManager(context->keyValueStorageManagerProxy())); + ASSERT(storageManager); + return adoptPtr(new EwkStorageManager(storageManager)); } Eina_List* createOriginList(WKArrayRef wkList) const; void getStorageOrigins(void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) const; private: - explicit EwkStorageManager(WebKeyValueStorageManagerProxy* storageManagerProxy); + explicit EwkStorageManager(WKKeyValueStorageManagerRef); - RefPtr<WebKeyValueStorageManagerProxy> m_storageManager; - mutable HashMap<WKSecurityOriginRef, RefPtr<Ewk_Security_Origin> > m_wrapperCache; + WKRetainPtr<WKKeyValueStorageManagerRef> m_storageManager; + mutable HashMap<WKSecurityOriginRef, RefPtr<EwkSecurityOrigin> > m_wrapperCache; }; #endif // ewk_storage_manager_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.cpp index ce546d56b..8f4994b0f 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2012-2013 Samsung Electronics * Copyright (C) 2012 Intel Corporation * * Redistribution and use in source and binary forms, with or without @@ -28,202 +28,88 @@ #include "ewk_text_checker.h" #if ENABLE(SPELLCHECK) +#include "TextCheckerClientEfl.h" -#include "TextCheckerEnchant.h" -#include "WKAPICast.h" -#include "WKMutableArray.h" -#include "WKRetainPtr.h" -#include "WKString.h" -#include "WKTextChecker.h" -#include "WebPageProxy.h" -#include "WebString.h" -#include "ewk_settings.h" -#include "ewk_text_checker_private.h" -#include <Eina.h> -#include <wtf/OwnPtr.h> -#include <wtf/text/CString.h> - -using namespace WebCore; using namespace WebKit; -/** - * @brief Structure to store client callback functions. - * - * @internal - */ -struct ClientCallbacks { - Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb unique_spell_document_tag_get; - Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb unique_spell_document_tag_close; - Ewk_Text_Checker_String_Spelling_Check_Cb string_spelling_check; - Ewk_Text_Checker_Word_Guesses_Get_Cb word_guesses_get; - Ewk_Text_Checker_Word_Learn_Cb word_learn; - Ewk_Text_Checker_Word_Ignore_Cb word_ignore; -}; - -static inline TextCheckerEnchant* textCheckerEnchant() -{ - static OwnPtr<TextCheckerEnchant> textCheckerEnchant = TextCheckerEnchant::create(); - return textCheckerEnchant.get(); -} - -static inline ClientCallbacks& clientCallbacks() -{ - DEFINE_STATIC_LOCAL(ClientCallbacks, clientCallbacks, ()); - return clientCallbacks; -} - -static bool isContinuousSpellCheckingEnabled(const void*) +static Eina_List* convertLanguagesToEinaList(const Vector<String>& languages) { - return ewk_settings_continuous_spell_checking_enabled_get(); -} + Eina_List* listOflanguages = 0; + size_t numberOfLanguages = languages.size(); -static void setContinuousSpellCheckingEnabled(bool enabled, const void*) -{ - ewk_settings_continuous_spell_checking_enabled_set(enabled); -} + for (size_t i = 0; i < numberOfLanguages; ++i) + listOflanguages = eina_list_append(listOflanguages, eina_stringshare_add(languages[i].utf8().data())); -static uint64_t uniqueSpellDocumentTag(WKPageRef page, const void*) -{ - if (clientCallbacks().unique_spell_document_tag_get) - return clientCallbacks().unique_spell_document_tag_get(toImpl(page)->viewWidget()); - - return 0; + return listOflanguages; } -static void closeSpellDocumentWithTag(uint64_t tag, const void*) -{ - if (clientCallbacks().unique_spell_document_tag_close) - clientCallbacks().unique_spell_document_tag_close(tag); +#define EWK_TEXT_CHECKER_CALLBACK_SET(TYPE_NAME, NAME) \ +void ewk_text_checker_##NAME##_cb_set(TYPE_NAME cb) \ +{ \ + TextCheckerClientEfl::instance().clientCallbacks().NAME = cb; \ } -static void checkSpellingOfString(uint64_t tag, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void*) -{ - if (clientCallbacks().string_spelling_check) - clientCallbacks().string_spelling_check(tag, toImpl(text)->string().utf8().data(), misspellingLocation, misspellingLength); - else - textCheckerEnchant()->checkSpellingOfString(toImpl(text)->string(), *misspellingLocation, *misspellingLength); -} - -static WKArrayRef guessesForWord(uint64_t tag, WKStringRef word, const void*) -{ - WKMutableArrayRef suggestionsForWord = WKMutableArrayCreate(); - - if (clientCallbacks().word_guesses_get) { - Eina_List* list = clientCallbacks().word_guesses_get(tag, toImpl(word)->string().utf8().data()); - void* item; - - EINA_LIST_FREE(list, item) { - WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(static_cast<const char*>(item))); - WKArrayAppendItem(suggestionsForWord, suggestion.get()); - free(item); - } - } else { - const Vector<String>& guesses = textCheckerEnchant()->getGuessesForWord(toImpl(word)->string()); - size_t numberOfGuesses = guesses.size(); - for (size_t i = 0; i < numberOfGuesses; ++i) { - WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(guesses[i].utf8().data())); - WKArrayAppendItem(suggestionsForWord, suggestion.get()); - } - } - - return suggestionsForWord; -} +#else -static void learnWord(uint64_t tag, WKStringRef word, const void*) -{ - if (clientCallbacks().word_learn) - clientCallbacks().word_learn(tag, toImpl(word)->string().utf8().data()); - else - textCheckerEnchant()->learnWord(toImpl(word)->string()); +// Defines an empty API to do not break build. +#define EWK_TEXT_CHECKER_CALLBACK_SET(TYPE_NAME, NAME) \ +void ewk_text_checker_##NAME##_cb_set(TYPE_NAME) \ +{ \ } +#endif // ENABLE(SPELLCHECK) -static void ignoreWord(uint64_t tag, WKStringRef word, const void*) +Eina_Bool ewk_text_checker_continuous_spell_checking_enabled_get() { - if (clientCallbacks().word_ignore) - clientCallbacks().word_ignore(tag, toImpl(word)->string().utf8().data()); - else - textCheckerEnchant()->ignoreWord(toImpl(word)->string()); +#if ENABLE(SPELLCHECK) + return TextCheckerClientEfl::instance().isContinuousSpellCheckingEnabled(); +#else + return false; +#endif } -namespace Ewk_Text_Checker { - -Vector<String> availableSpellCheckingLanguages() +void ewk_text_checker_continuous_spell_checking_enabled_set(Eina_Bool enable) { - return textCheckerEnchant()->availableSpellCheckingLanguages(); +#if ENABLE(SPELLCHECK) + WKTextCheckerContinuousSpellCheckingEnabledStateChanged(!!enable); +#else + UNUSED_PARAM(enable); +#endif } -void updateSpellCheckingLanguages(const Vector<String>& languages) +Eina_List* ewk_text_checker_spell_checking_available_languages_get() { - textCheckerEnchant()->updateSpellCheckingLanguages(languages); + Eina_List* listOflanguages = 0; +#if ENABLE(SPELLCHECK) + // FIXME: Expose WK2 C API to get available spell checking languages. + listOflanguages = convertLanguagesToEinaList(TextCheckerClientEfl::instance().availableSpellCheckingLanguages()); +#endif + return listOflanguages; } -Vector<String> loadedSpellCheckingLanguages() +void ewk_text_checker_spell_checking_languages_set(const char* languages) { - return textCheckerEnchant()->loadedSpellCheckingLanguages(); -} +#if ENABLE(SPELLCHECK) + Vector<String> newLanguages; + String::fromUTF8(languages).split(',', newLanguages); -bool hasDictionary() -{ - return textCheckerEnchant()->hasDictionary(); + // FIXME: Expose WK2 C API to set spell checking languages. + TextCheckerClientEfl::instance().updateSpellCheckingLanguages(newLanguages); +#else + UNUSED_PARAM(languages); +#endif } -/** - * Initializes spellcheck feature. - * - * @internal - * - * The default spellcheck feature is based on Enchant library. - * Client may use own spellcheck implementation previously set - * through the callback functions. - */ -void initialize() +Eina_List* ewk_text_checker_spell_checking_languages_get() { - static bool didInitializeTextCheckerClient = false; - if (didInitializeTextCheckerClient) - return; - - WKTextCheckerClient textCheckerClient = { - kWKTextCheckerClientCurrentVersion, - 0, // clientInfo - 0, // isContinuousSpellCheckingAllowed - isContinuousSpellCheckingEnabled, - setContinuousSpellCheckingEnabled, - 0, // isGrammarCheckingEnabled - 0, // setGrammarCheckingEnabled - uniqueSpellDocumentTag, - closeSpellDocumentWithTag, - checkSpellingOfString, - 0, // checkGrammarOfString - 0, // spellingUIIsShowing - 0, // toggleSpellingUIIsShowing - 0, // updateSpellingUIWithMisspelledWord - 0, // updateSpellingUIWithGrammarString - guessesForWord, - learnWord, - ignoreWord - }; - WKTextCheckerSetClient(&textCheckerClient); - - didInitializeTextCheckerClient = true; -} - -} // namespace Ewk_Text_Checker - -#define EWK_TEXT_CHECKER_CALLBACK_SET(TYPE_NAME, NAME) \ -void ewk_text_checker_##NAME##_cb_set(TYPE_NAME cb) \ -{ \ - clientCallbacks().NAME = cb; \ -} - -#else - -// Defines an empty API to do not break build. -#define EWK_TEXT_CHECKER_CALLBACK_SET(TYPE_NAME, NAME) \ -void ewk_text_checker_##NAME##_cb_set(TYPE_NAME) \ -{ \ + Eina_List* listOflanguages = 0; +#if ENABLE(SPELLCHECK) + // FIXME: Expose WK2 C API to get loaded spell checking languages. + listOflanguages = convertLanguagesToEinaList(TextCheckerClientEfl::instance().loadedSpellCheckingLanguages()); +#endif + return listOflanguages; } -#endif // ENABLE(SPELLCHECK) +EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_Continuous_Spell_Checking_Change_Cb, continuous_spell_checking_change) EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb, unique_spell_document_tag_get) EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb, unique_spell_document_tag_close) EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_String_Spelling_Check_Cb, string_spelling_check) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h index b7aea882f..b45322591 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2012-2013 Samsung Electronics * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -25,11 +25,14 @@ /** * @file ewk_text_checker.h - * @brief Provides API to overwrite the default WebKit spellchecker implementation. + * @brief Provides API to overwrite the default WebKit spellchecker implementation + * and contains API to manipulate spellchecker settings. * - * There is one spellchecker object per application and it's disabled by default. - * It allows to check spelling in the editable areas. - * If application wants to enable the feature, API from ewk_settings.h + * There is one spellchecker object per application. + * It allows to check spelling in the editable areas, get suggestions for the misspelled word, + * learn and ignore spelling. + * + * If application wants to check spelling while typing, ewk_text_checker_continuous_spell_checking_enabled_set API * should be used. * * The default WebKit spellchecker implementation is based on the Enchant library. @@ -48,6 +51,14 @@ extern "C" { #endif /** + * Creates a type name for the callback function used to notify the client when + * the continuous spell checking setting was changed by WebKit. + * + * @param enable @c EINA_TRUE if continuous spell checking is enabled or @c EINA_FALSE if it's disabled + */ +typedef void (*Ewk_Text_Checker_Continuous_Spell_Checking_Change_Cb)(Eina_Bool enable); + +/** * Defines a type name for the callback function to return a tag (identifier) which is guaranteed to be unique. * * Unique tags help to avoid collisions with other objects that are checked for spelling mistakes. @@ -85,8 +96,8 @@ typedef void (*Ewk_Text_Checker_String_Spelling_Check_Cb)(uint64_t tag, const ch * @param tag unique tag to notify the spell checker which document that @a text is associated, * @c 0 can be passed for text not associated with a particular document * @param word the word to get guesses - * @return a list of dynamically allocated strings (as char*) and - * caller is responsible for destroying them. + * @return a list of dynamically allocated strings (as char*), + * the list and its items will be freed by WebKit. */ typedef Eina_List *(*Ewk_Text_Checker_Word_Guesses_Get_Cb)(uint64_t tag, const char *word); @@ -108,6 +119,75 @@ typedef void (*Ewk_Text_Checker_Word_Learn_Cb)(uint64_t tag, const char *word); */ typedef void (*Ewk_Text_Checker_Word_Ignore_Cb)(uint64_t tag, const char *word); + +/** + * Queries if continuous spell checking is enabled. + * + * @return @c EINA_TRUE if continuous spell checking is enabled or @c EINA_FALSE if it's disabled + */ +EAPI Eina_Bool ewk_text_checker_continuous_spell_checking_enabled_get(void); + +/** + * Enables/disables continuous spell checking. + * + * This feature is disabled by default. + * + * @see ewk_text_checker_continuous_spell_checking_change_cb_set + * + * @param enable @c EINA_TRUE to enable continuous spell checking or @c EINA_FALSE to disable + */ +EAPI void ewk_text_checker_continuous_spell_checking_enabled_set(Eina_Bool enable); + +/** + * Gets the the list of all available the spell checking languages to use. + * + * @see ewk_settings_spell_checking_languages_set + * + * @return the list with available spell checking languages, or @c NULL on failure + * the Eina_List and its items should be freed after, use eina_stringshare_del() + */ +EAPI Eina_List *ewk_text_checker_spell_checking_available_languages_get(void); + +/** + * Sets @a languages as the list of languages to use by default WebKit + * implementation of spellchecker feature with Enchant library support. + * + * If @languages is @c NULL, the default language is used. + * If the default language can not be determined then any available dictionary will be used. + * + * @note This function invalidates the previously set languages. + * The dictionaries are requested asynchronously. + * + * @param languages a list of comma (',') separated language codes + * of the form 'en_US', ie, language_VARIANT, may be @c NULL. + */ +EAPI void ewk_text_checker_spell_checking_languages_set(const char *languages); + +/** + * Gets the the list of the spell checking languages in use. + * + * @see ewk_settings_spell_checking_available_languages_get + * @see ewk_settings_spell_checking_languages_set + * + * @return the list with the spell checking languages in use, + * the Eina_List and its items should be freed after, use eina_stringshare_del() + */ +EAPI Eina_List *ewk_text_checker_spell_checking_languages_get(void); + +/** + * Sets a callback function used to notify the client when + * the continuous spell checking setting was changed by WebKit. + * + * Specifying of this callback is needed if the application wants to receive notifications + * once WebKit changes this setting. + * If the application is not interested, this callback is not set. + * Changing of this setting at the WebKit level can be made as a result of modifying + * options in a Context Menu by a user. + * + * @param cb a new callback function to set or @c NULL to invalidate the previous one + */ +EAPI void ewk_text_checker_continuous_spell_checking_change_cb_set(Ewk_Text_Checker_Continuous_Spell_Checking_Change_Cb cb); + /** * Sets a callback function to get a unique spell document tag. * diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h index 6c4730e2e..f113cb3c0 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2012-2013 Samsung Electronics * Copyright (C) 2012 Intel Corporation * * Redistribution and use in source and binary forms, with or without @@ -31,17 +31,20 @@ #include "ewk_text_checker.h" -namespace Ewk_Text_Checker { - -void initialize(); - -// Enchant helpers. -Vector<String> availableSpellCheckingLanguages(); -void updateSpellCheckingLanguages(const Vector<String>& languages); -Vector<String> loadedSpellCheckingLanguages(); -bool hasDictionary(); - -} +/** + * @brief Structure to store client callback functions. + * + * @internal + */ +struct ClientCallbacks { + Ewk_Text_Checker_Continuous_Spell_Checking_Change_Cb continuous_spell_checking_change; + Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb unique_spell_document_tag_get; + Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb unique_spell_document_tag_close; + Ewk_Text_Checker_String_Spelling_Check_Cb string_spelling_check; + Ewk_Text_Checker_Word_Guesses_Get_Cb word_guesses_get; + Ewk_Text_Checker_Word_Learn_Cb word_learn; + Ewk_Text_Checker_Word_Ignore_Cb word_ignore; +}; #endif // ENABLE(SPELLCHECK) #endif // ewk_text_checker_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp index 6d5b87652..29244fa9f 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp @@ -31,15 +31,15 @@ using namespace WebKit; -EwkUrlResponse::EwkUrlResponse(const WebCore::ResourceResponse& coreResponse) - : m_coreResponse(coreResponse) - , m_url(AdoptWK, WKURLResponseCopyURL(WebKit::toAPI(coreResponse))) - , m_mimeType(AdoptWK, WKURLResponseCopyMIMEType(WebKit::toAPI(coreResponse))) +EwkUrlResponse::EwkUrlResponse(WKURLResponseRef response) + : m_response(response) + , m_url(AdoptWK, WKURLResponseCopyURL(response)) + , m_mimeType(AdoptWK, WKURLResponseCopyMIMEType(response)) { } int EwkUrlResponse::httpStatusCode() const { - return m_coreResponse.httpStatusCode(); + return WKURLResponseHTTPStatusCode(m_response.get()); } const char* EwkUrlResponse::url() const @@ -54,7 +54,7 @@ const char* EwkUrlResponse::mimeType() const unsigned long EwkUrlResponse::contentLength() const { - return m_coreResponse.expectedContentLength(); + return WKURLResponseGetExpectedContentLength(m_response.get()); } const char* ewk_url_response_url_get(const Ewk_Url_Response* response) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h index 02763c72f..4ea827498 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h @@ -30,7 +30,6 @@ #include "WKEinaSharedString.h" #include "WKURLResponse.h" #include "ewk_object_private.h" -#include <WebCore/ResourceResponse.h> #include <wtf/PassRefPtr.h> /** @@ -46,7 +45,7 @@ public: if (!wkResponse) return 0; - return adoptRef(new EwkUrlResponse(WebKit::toImpl(wkResponse)->resourceResponse())); + return adoptRef(new EwkUrlResponse(wkResponse)); } int httpStatusCode() const; @@ -55,9 +54,9 @@ public: unsigned long contentLength() const; private: - explicit EwkUrlResponse(const WebCore::ResourceResponse& coreResponse); + explicit EwkUrlResponse(WKURLResponseRef response); - WebCore::ResourceResponse m_coreResponse; + WKRetainPtr<WKURLResponseRef> m_response; WKEinaSharedString m_url; WKEinaSharedString m_mimeType; }; diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp index 889173088..728ee40fd 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp @@ -26,9 +26,9 @@ #include "config.h" #include "ewk_url_scheme_request.h" -#include "GOwnPtrSoup.h" #include "WKData.h" #include "WKString.h" +#include "WKURL.h" #include "ewk_url_scheme_request_private.h" using namespace WebKit; @@ -37,10 +37,9 @@ EwkUrlSchemeRequest::EwkUrlSchemeRequest(WKSoupRequestManagerRef manager, WKURLR : m_wkRequestManager(manager) , m_url(url) , m_requestID(requestID) + , m_scheme(AdoptWK, WKURLCopyScheme(url)) + , m_path(AdoptWK, WKURLCopyPath(url)) { - GOwnPtr<SoupURI> soupURI(soup_uri_new(m_url)); - m_scheme = soupURI->scheme; - m_path = soupURI->path; } uint64_t EwkUrlSchemeRequest::id() const diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp index 349b086e9..17c21d537 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp @@ -20,527 +20,129 @@ #include "config.h" #include "ewk_view.h" +#include "ewk_view_private.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "FindClientEfl.h" #include "FormClientEfl.h" #include "InputMethodContextEfl.h" -#include "NativeWebKeyboardEvent.h" -#include "NativeWebMouseEvent.h" -#include "NativeWebWheelEvent.h" -#include "PageClientBase.h" #include "PageLoadClientEfl.h" #include "PagePolicyClientEfl.h" #include "PageUIClientEfl.h" -#include "ResourceLoadClientEfl.h" -#include "WKAPICast.h" -#include "WKEinaSharedString.h" -#include "WKFindOptions.h" -#include "WKRetainPtr.h" -#include "WKString.h" -#include "WebContext.h" -#include "WebFullScreenManagerProxy.h" -#include "WebPageGroup.h" -#include "WebPreferences.h" +#include "PageViewportController.h" +#include "PageViewportControllerClientEfl.h" #include "ewk_back_forward_list_private.h" #include "ewk_context.h" #include "ewk_context_private.h" #include "ewk_favicon_database_private.h" -#include "ewk_intent_private.h" +#include "ewk_page_group.h" +#include "ewk_page_group_private.h" #include "ewk_private.h" #include "ewk_settings_private.h" -#include "ewk_view_private.h" #include <Ecore_Evas.h> +#include <WebKit2/WKAPICast.h> +#include <WebKit2/WKData.h> +#include <WebKit2/WKEinaSharedString.h> +#include <WebKit2/WKFindOptions.h> +#include <WebKit2/WKInspector.h> #include <WebKit2/WKPageGroup.h> +#include <WebKit2/WKRetainPtr.h> +#include <WebKit2/WKString.h> +#include <WebKit2/WKURL.h> +#include <WebKit2/WKView.h> #include <wtf/text/CString.h> #if ENABLE(INSPECTOR) #include "WebInspectorProxy.h" #endif -#if USE(TILED_BACKING_STORE) -#include "PageViewportController.h" -#include "PageViewportControllerClientEfl.h" -#endif - using namespace WebKit; -using namespace WebCore; - -static const char EWK_VIEW_TYPE_STR[] = "EWK2_View"; - -#define EWK_VIEW_TYPE_CHECK(ewkView, result) \ - bool result = true; \ - do { \ - if (!ewkView) { \ - EINA_LOG_CRIT("null is not a ewk_view"); \ - result = false; \ - break; \ - } \ - const char* _tmp_otype = evas_object_type_get(ewkView); \ - const Evas_Smart* _tmp_s = evas_object_smart_smart_get(ewkView); \ - if (EINA_UNLIKELY(!_tmp_s)) { \ - EINA_LOG_CRIT \ - ("%p (%s) is not a smart object!", \ - ewkView, _tmp_otype ? _tmp_otype : "(null)"); \ - result = false; \ - break; \ - } \ - const Evas_Smart_Class* _tmp_sc = evas_smart_class_get(_tmp_s); \ - if (EINA_UNLIKELY(!_tmp_sc)) { \ - EINA_LOG_CRIT \ - ("%p (%s) is not a smart object!", \ - ewkView, _tmp_otype ? _tmp_otype : "(null)"); \ - result = false; \ - break; \ - } \ - if (EINA_UNLIKELY(_tmp_sc->data != EWK_VIEW_TYPE_STR)) { \ - EINA_LOG_CRIT \ - ("%p (%s) is not of an ewk_view (need %p, got %p)!", \ - ewkView, _tmp_otype ? _tmp_otype : "(null)", \ - EWK_VIEW_TYPE_STR, _tmp_sc->data); \ - result = false; \ - } \ - } while (0) -#define EWK_VIEW_SD_GET(ewkView, smartData) \ - EWK_VIEW_TYPE_CHECK(ewkView, _tmp_result); \ - Ewk_View_Smart_Data* smartData = 0; \ - if (_tmp_result) \ - smartData = (Ewk_View_Smart_Data*)evas_object_smart_data_get(ewkView) +static inline EwkView* toEwkViewChecked(const Evas_Object* evasObject) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(evasObject, 0); + if (!isEwkViewEvasObject(evasObject)) + return 0; -#define EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData, ...) \ - EWK_VIEW_SD_GET(ewkView, smartData); \ - do { \ - if (!smartData) { \ - EINA_LOG_CRIT("no smart data for object %p (%s)", \ - ewkView, evas_object_type_get(ewkView)); \ - return __VA_ARGS__; \ - } \ - } while (0) + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(evas_object_smart_data_get(evasObject)); + EINA_SAFETY_ON_NULL_RETURN_VAL(smartData, 0); -#define EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, ...) \ - if (!smartData) { \ - EINA_LOG_CRIT("smart data is null"); \ - return __VA_ARGS__; \ - } \ - EwkViewImpl* impl = smartData->priv; \ - do { \ - if (!impl) { \ - EINA_LOG_CRIT("no private data for object %p (%s)", \ - smartData->self, evas_object_type_get(smartData->self)); \ - return __VA_ARGS__; \ - } \ - } while (0) + return smartData->priv; +} #define EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, ...) \ - EwkViewImpl* impl = 0; \ + EwkView* impl = toEwkViewChecked(ewkView); \ do { \ - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData, __VA_ARGS__); \ - impl = smartData->priv; \ if (!impl) { \ - EINA_LOG_CRIT("no private data for object %p (%s)", \ - smartData->self, evas_object_type_get(smartData->self)); \ + EINA_LOG_CRIT("no private data for object %p", ewkView); \ return __VA_ARGS__; \ } \ } while (0) -static void _ewk_view_smart_changed(Ewk_View_Smart_Data* smartData) -{ - if (smartData->changed.any) - return; - smartData->changed.any = true; - evas_object_smart_changed(smartData->self); -} - -// Default Event Handling. -static Eina_Bool _ewk_view_smart_focus_in(Ewk_View_Smart_Data* smartData) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->viewStateDidChange(WebPageProxy::ViewIsFocused | WebPageProxy::ViewWindowIsActive); - return true; -} - -static Eina_Bool _ewk_view_smart_focus_out(Ewk_View_Smart_Data* smartData) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->viewStateDidChange(WebPageProxy::ViewIsFocused | WebPageProxy::ViewWindowIsActive); - return true; -} - -static Eina_Bool _ewk_view_smart_mouse_wheel(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Wheel* wheelEvent) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->handleWheelEvent(NativeWebWheelEvent(wheelEvent, impl->transformFromScene(), impl->transformToScreen())); - return true; -} - -static Eina_Bool _ewk_view_smart_mouse_down(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Down* downEvent) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->handleMouseEvent(NativeWebMouseEvent(downEvent, impl->transformFromScene(), impl->transformToScreen())); - return true; -} - -static Eina_Bool _ewk_view_smart_mouse_up(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Up* upEvent) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->handleMouseEvent(NativeWebMouseEvent(upEvent, impl->transformFromScene(), impl->transformToScreen())); - - InputMethodContextEfl* inputMethodContext = impl->inputMethodContext(); - if (inputMethodContext) - inputMethodContext->handleMouseUpEvent(upEvent); - - return true; -} - -static Eina_Bool _ewk_view_smart_mouse_move(Ewk_View_Smart_Data* smartData, const Evas_Event_Mouse_Move* moveEvent) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->handleMouseEvent(NativeWebMouseEvent(moveEvent, impl->transformFromScene(), impl->transformToScreen())); - return true; -} - -static Eina_Bool _ewk_view_smart_key_down(Ewk_View_Smart_Data* smartData, const Evas_Event_Key_Down* downEvent) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - bool isFiltered = false; - InputMethodContextEfl* inputMethodContext = impl->inputMethodContext(); - if (inputMethodContext) - inputMethodContext->handleKeyDownEvent(downEvent, &isFiltered); - - impl->page()->handleKeyboardEvent(NativeWebKeyboardEvent(downEvent, isFiltered)); - return true; -} - -static Eina_Bool _ewk_view_smart_key_up(Ewk_View_Smart_Data* smartData, const Evas_Event_Key_Up* upEvent) -{ - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); - - impl->page()->handleKeyboardEvent(NativeWebKeyboardEvent(upEvent)); - return true; -} - -// Event Handling. -static void _ewk_view_on_focus_in(void* data, Evas*, Evas_Object*, void* /*eventInfo*/) -{ - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(smartData->api); - EINA_SAFETY_ON_NULL_RETURN(smartData->api->focus_in); - smartData->api->focus_in(smartData); -} - -static void _ewk_view_on_focus_out(void* data, Evas*, Evas_Object*, void* /*eventInfo*/) -{ - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(smartData->api); - EINA_SAFETY_ON_NULL_RETURN(smartData->api->focus_out); - smartData->api->focus_out(smartData); -} - -static void _ewk_view_on_mouse_wheel(void* data, Evas*, Evas_Object*, void* eventInfo) -{ - Evas_Event_Mouse_Wheel* wheelEvent = static_cast<Evas_Event_Mouse_Wheel*>(eventInfo); - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(smartData->api); - EINA_SAFETY_ON_NULL_RETURN(smartData->api->mouse_wheel); - smartData->api->mouse_wheel(smartData, wheelEvent); -} - -static void _ewk_view_on_key_down(void* data, Evas*, Evas_Object*, void* eventInfo) -{ - Evas_Event_Key_Down* downEvent = static_cast<Evas_Event_Key_Down*>(eventInfo); - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(smartData->api); - EINA_SAFETY_ON_NULL_RETURN(smartData->api->key_down); - smartData->api->key_down(smartData, downEvent); -} - -static void _ewk_view_on_key_up(void* data, Evas*, Evas_Object*, void* eventInfo) -{ - Evas_Event_Key_Up* upEvent = static_cast<Evas_Event_Key_Up*>(eventInfo); - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EINA_SAFETY_ON_NULL_RETURN(smartData->api); - EINA_SAFETY_ON_NULL_RETURN(smartData->api->key_up); - smartData->api->key_up(smartData, upEvent); -} - -static void _ewk_view_on_show(void* data, Evas*, Evas_Object*, void* /*eventInfo*/) -{ - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl); - impl->page()->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -static void _ewk_view_on_hide(void* data, Evas*, Evas_Object*, void* /*eventInfo*/) -{ - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl); - - // This call may look wrong, but we really need to pass ViewIsVisible here. - // viewStateDidChange() itself is responsible for actually setting the visibility to Visible or Hidden - // depending on what WebPageProxy::isViewVisible() returns, this simply triggers the process. - impl->page()->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -static Evas_Smart_Class g_parentSmartClass = EVAS_SMART_CLASS_INIT_NULL; - -static void _ewk_view_smart_add(Evas_Object* ewkView) -{ - const Evas_Smart* smart = evas_object_smart_smart_get(ewkView); - const Evas_Smart_Class* smartClass = evas_smart_class_get(smart); - const Ewk_View_Smart_Class* api = reinterpret_cast<const Ewk_View_Smart_Class*>(smartClass); - EWK_VIEW_SD_GET(ewkView, smartData); - - if (!smartData) { - smartData = static_cast<Ewk_View_Smart_Data*>(calloc(1, sizeof(Ewk_View_Smart_Data))); - if (!smartData) { - EINA_LOG_CRIT("could not allocate Ewk_View_Smart_Data"); - return; - } - evas_object_smart_data_set(ewkView, smartData); - } - - smartData->self = ewkView; - smartData->api = api; - - g_parentSmartClass.add(ewkView); - - smartData->priv = 0; - - // Create evas_object_image to draw web contents. - smartData->image = evas_object_image_add(smartData->base.evas); - evas_object_image_alpha_set(smartData->image, false); - evas_object_image_filled_set(smartData->image, true); - evas_object_smart_member_add(smartData->image, ewkView); - evas_object_show(smartData->image); - -#define CONNECT(s, c) evas_object_event_callback_add(ewkView, s, c, smartData) - CONNECT(EVAS_CALLBACK_FOCUS_IN, _ewk_view_on_focus_in); - CONNECT(EVAS_CALLBACK_FOCUS_OUT, _ewk_view_on_focus_out); - CONNECT(EVAS_CALLBACK_MOUSE_WHEEL, _ewk_view_on_mouse_wheel); - CONNECT(EVAS_CALLBACK_KEY_DOWN, _ewk_view_on_key_down); - CONNECT(EVAS_CALLBACK_KEY_UP, _ewk_view_on_key_up); - CONNECT(EVAS_CALLBACK_SHOW, _ewk_view_on_show); - CONNECT(EVAS_CALLBACK_HIDE, _ewk_view_on_hide); -#undef CONNECT -} - -static void _ewk_view_smart_del(Evas_Object* ewkView) -{ - EWK_VIEW_SD_GET(ewkView, smartData); - if (smartData) - delete smartData->priv; - - g_parentSmartClass.del(ewkView); -} - -static void _ewk_view_smart_resize(Evas_Object* ewkView, Evas_Coord width, Evas_Coord height) -{ - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData); - - evas_object_resize(smartData->image, width, height); - evas_object_image_size_set(smartData->image, width, height); - evas_object_image_fill_set(smartData->image, 0, 0, width, height); - - smartData->changed.size = true; - _ewk_view_smart_changed(smartData); -} - -static void _ewk_view_smart_move(Evas_Object* ewkView, Evas_Coord /*x*/, Evas_Coord /*y*/) -{ - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData); - - smartData->changed.position = true; - _ewk_view_smart_changed(smartData); -} - -static void _ewk_view_smart_calculate(Evas_Object* ewkView) -{ - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData); - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl); - - smartData->changed.any = false; - - Evas_Coord x, y, width, height; - evas_object_geometry_get(ewkView, &x, &y, &width, &height); - - if (smartData->changed.position) { - smartData->changed.position = false; - smartData->view.x = x; - smartData->view.y = y; - evas_object_move(smartData->image, x, y); - } - - if (smartData->changed.size) { - smartData->changed.size = false; - smartData->view.w = width; - smartData->view.h = height; - if (impl->page()->drawingArea()) - impl->page()->drawingArea()->setSize(IntSize(width, height), IntSize()); - -#if USE(ACCELERATED_COMPOSITING) - impl->setNeedsSurfaceResize(); -#endif -#if USE(TILED_BACKING_STORE) - impl->pageClient()->updateViewportSize(IntSize(width, height)); -#endif - } -} - -static void _ewk_view_smart_show(Evas_Object* ewkView) -{ - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData); - - if (evas_object_clipees_get(smartData->base.clipper)) - evas_object_show(smartData->base.clipper); - evas_object_show(smartData->image); -} - -static void _ewk_view_smart_hide(Evas_Object* ewkView) +Eina_Bool ewk_view_smart_class_set(Ewk_View_Smart_Class* api) { - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData); + EINA_SAFETY_ON_NULL_RETURN_VAL(api, false); - evas_object_hide(smartData->base.clipper); - evas_object_hide(smartData->image); + return EwkView::initSmartClassInterface(*api); } -static void _ewk_view_smart_color_set(Evas_Object* ewkView, int red, int green, int blue, int alpha) +Evas_Object* EWKViewCreate(WKContextRef context, WKPageGroupRef pageGroup, Evas* canvas, Evas_Smart* smart) { - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData); - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl); + WKRetainPtr<WKViewRef> wkView = adoptWK(WKViewCreate(context, pageGroup)); + WKPageSetUseFixedLayout(WKViewGetPage(wkView.get()), true); + if (EwkView* ewkView = EwkView::create(wkView.get(), canvas, smart)) + return ewkView->evasObject(); - if (alpha < 0) - alpha = 0; - else if (alpha > 255) - alpha = 255; - -#define CHECK_COLOR(color, alpha) \ - if (color < 0) \ - color = 0; \ - else if (color > alpha) \ - color = alpha; - CHECK_COLOR(red, alpha); - CHECK_COLOR(green, alpha); - CHECK_COLOR(blue, alpha); -#undef CHECK_COLOR - - evas_object_image_alpha_set(smartData->image, alpha < 255); - impl->page()->setDrawsBackground(red || green || blue); - impl->page()->setDrawsTransparentBackground(alpha < 255); - - g_parentSmartClass.color_set(ewkView, red, green, blue, alpha); + return 0; } -Eina_Bool ewk_view_smart_class_set(Ewk_View_Smart_Class* api) +WKViewRef EWKViewGetWKView(Evas_Object* ewkView) { - EINA_SAFETY_ON_NULL_RETURN_VAL(api, false); - - if (api->version != EWK_VIEW_SMART_CLASS_VERSION) { - EINA_LOG_CRIT("Ewk_View_Smart_Class %p is version %lu while %lu was expected.", - api, api->version, EWK_VIEW_SMART_CLASS_VERSION); - return false; - } - - if (EINA_UNLIKELY(!g_parentSmartClass.add)) - evas_object_smart_clipped_smart_set(&g_parentSmartClass); - - evas_object_smart_clipped_smart_set(&api->sc); - - // Set Evas_Smart_Class functions. - api->sc.add = _ewk_view_smart_add; - api->sc.del = _ewk_view_smart_del; - api->sc.move = _ewk_view_smart_move; - api->sc.resize = _ewk_view_smart_resize; - api->sc.show = _ewk_view_smart_show; - api->sc.hide = _ewk_view_smart_hide; - api->sc.color_set = _ewk_view_smart_color_set; - api->sc.calculate = _ewk_view_smart_calculate; - api->sc.data = EWK_VIEW_TYPE_STR; // It is used by type checking. - - // Set Ewk_View_Smart_Class functions. - api->focus_in = _ewk_view_smart_focus_in; - api->focus_out = _ewk_view_smart_focus_out; - api->mouse_wheel = _ewk_view_smart_mouse_wheel; - api->mouse_down = _ewk_view_smart_mouse_down; - api->mouse_up = _ewk_view_smart_mouse_up; - api->mouse_move = _ewk_view_smart_mouse_move; - api->key_down = _ewk_view_smart_key_down; - api->key_up = _ewk_view_smart_key_up; + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - return true; + return impl->wkView(); } -static inline Evas_Smart* createEwkViewSmartClass(void) +Evas_Object* ewk_view_smart_add(Evas* canvas, Evas_Smart* smart, Ewk_Context* context, Ewk_Page_Group* pageGroup) { - static Ewk_View_Smart_Class api = EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION("Ewk_View"); - static Evas_Smart* smart = 0; + EwkContext* ewkContext = ewk_object_cast<EwkContext*>(context); + EwkPageGroup* ewkPageGroup = ewk_object_cast<EwkPageGroup*>(pageGroup); - if (EINA_UNLIKELY(!smart)) { - ewk_view_smart_class_set(&api); - smart = evas_smart_class_new(&api.sc); - } + EINA_SAFETY_ON_NULL_RETURN_VAL(ewkContext, 0); + EINA_SAFETY_ON_NULL_RETURN_VAL(ewkContext->wkContext(), 0); + EINA_SAFETY_ON_NULL_RETURN_VAL(ewkPageGroup, 0); + EINA_SAFETY_ON_NULL_RETURN_VAL(ewkPageGroup->wkPageGroup(), 0); - return smart; + return EWKViewCreate(ewkContext->wkContext(), ewkPageGroup->wkPageGroup(), canvas, smart); } -static inline Evas_Object* createEwkView(Evas* canvas, Evas_Smart* smart, PassRefPtr<EwkContext> context, WKPageGroupRef pageGroupRef = 0, EwkViewImpl::ViewBehavior behavior = EwkViewImpl::DefaultBehavior) +Evas_Object* ewk_view_add(Evas* canvas) { - EINA_SAFETY_ON_NULL_RETURN_VAL(canvas, 0); - EINA_SAFETY_ON_NULL_RETURN_VAL(smart, 0); - EINA_SAFETY_ON_NULL_RETURN_VAL(context, 0); - - Evas_Object* ewkView = evas_object_smart_add(canvas, smart); - EINA_SAFETY_ON_NULL_RETURN_VAL(ewkView, 0); - - EWK_VIEW_SD_GET(ewkView, smartData); - if (!smartData) { - evas_object_del(ewkView); - return 0; - } - - ASSERT(!smartData->priv); - RefPtr<WebPageGroup> pageGroup = pageGroupRef ? toImpl(pageGroupRef) : WebPageGroup::create(); - smartData->priv = new EwkViewImpl(ewkView, context, pageGroup, behavior); - return ewkView; + return EWKViewCreate(adoptWK(WKContextCreate()).get(), 0, canvas, 0); } -/** - * @internal - * Constructs a ewk_view Evas_Object with WKType parameters. - */ -Evas_Object* ewk_view_base_add(Evas* canvas, WKContextRef contextRef, WKPageGroupRef pageGroupRef, EwkViewImpl::ViewBehavior behavior) +Evas_Object* ewk_view_add_with_context(Evas* canvas, Ewk_Context* context) { - return createEwkView(canvas, createEwkViewSmartClass(), EwkContext::create(toImpl(contextRef)), pageGroupRef, behavior); -} + EwkContext* ewkContext = ewk_object_cast<EwkContext*>(context); + EINA_SAFETY_ON_NULL_RETURN_VAL(ewkContext, 0); + EINA_SAFETY_ON_NULL_RETURN_VAL(ewkContext->wkContext(), 0); -Evas_Object* ewk_view_smart_add(Evas* canvas, Evas_Smart* smart, Ewk_Context* context) -{ - return createEwkView(canvas, smart, ewk_object_cast<EwkContext*>(context)); + return EWKViewCreate(ewkContext->wkContext(), 0, canvas, 0); } -Evas_Object* ewk_view_add_with_context(Evas* canvas, Ewk_Context* context) +Ewk_Context* ewk_view_context_get(const Evas_Object* ewkView) { - return ewk_view_smart_add(canvas, createEwkViewSmartClass(), ewk_object_cast<EwkContext*>(context)); -} + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); -Evas_Object* ewk_view_add(Evas* canvas) -{ - return ewk_view_add_with_context(canvas, ewk_context_default_get()); + return impl->ewkContext(); } -Ewk_Context* ewk_view_context_get(const Evas_Object* ewkView) +Ewk_Page_Group* ewk_view_page_group_get(const Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - return impl->ewkContext(); + return impl->ewkPageGroup(); } Eina_Bool ewk_view_url_set(Evas_Object* ewkView, const char* url) @@ -548,7 +150,8 @@ Eina_Bool ewk_view_url_set(Evas_Object* ewkView, const char* url) EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(url, false); - impl->page()->loadURL(url); + WKRetainPtr<WKURLRef> wkUrl = adoptWK(WKURLCreateWithUTF8CString(url)); + WKPageLoadURL(impl->wkPage(), wkUrl.get()); impl->informURLChange(); return true; @@ -561,18 +164,18 @@ const char* ewk_view_url_get(const Evas_Object* ewkView) return impl->url(); } -const char *ewk_view_icon_url_get(const Evas_Object *ewkView) +Evas_Object* ewk_view_favicon_get(const Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - return impl->faviconURL(); + return impl->createFavicon(); } Eina_Bool ewk_view_reload(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->reload(/*reloadFromOrigin*/ false); + WKPageReload(impl->wkPage()); impl->informURLChange(); return true; @@ -582,7 +185,7 @@ Eina_Bool ewk_view_reload_bypass_cache(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->reload(/*reloadFromOrigin*/ true); + WKPageReloadFromOrigin(impl->wkPage()); impl->informURLChange(); return true; @@ -592,7 +195,7 @@ Eina_Bool ewk_view_stop(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->stopLoading(); + WKPageStopLoading(impl->wkPage()); return true; } @@ -615,14 +218,14 @@ double ewk_view_load_progress_get(const Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, -1.0); - return impl->page()->estimatedProgress(); + return WKPageGetEstimatedProgress(impl->wkPage()); } Eina_Bool ewk_view_scale_set(Evas_Object* ewkView, double scaleFactor, int x, int y) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->scalePage(scaleFactor, IntPoint(x, y)); + WKPageSetScaleFactor(impl->wkPage(), scaleFactor, WKPointMake(x, y)); return true; } @@ -630,14 +233,14 @@ double ewk_view_scale_get(const Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, -1); - return impl->page()->pageScaleFactor(); + return WKPageGetScaleFactor(impl->wkPage()); } Eina_Bool ewk_view_device_pixel_ratio_set(Evas_Object* ewkView, float ratio) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->setCustomDeviceScaleFactor(ratio); + impl->setDeviceScaleFactor(ratio); return true; } @@ -646,7 +249,7 @@ float ewk_view_device_pixel_ratio_get(const Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, -1.0); - return impl->page()->deviceScaleFactor(); + return WKPageGetBackingScaleFactor(impl->wkPage()); } void ewk_view_theme_set(Evas_Object* ewkView, const char* path) @@ -667,9 +270,9 @@ Eina_Bool ewk_view_back(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - WebPageProxy* page = impl->page(); - if (page->canGoBack()) { - page->goBack(); + WKPageRef page = impl->wkPage(); + if (WKPageCanGoBack(page)) { + WKPageGoBack(page); return true; } @@ -680,43 +283,25 @@ Eina_Bool ewk_view_forward(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - WebPageProxy* page = impl->page(); - if (page->canGoForward()) { - page->goForward(); + WKPageRef page = impl->wkPage(); + if (WKPageCanGoForward(page)) { + WKPageGoForward(page); return true; } return false; } -Eina_Bool ewk_view_intent_deliver(Evas_Object* ewkView, Ewk_Intent* intent) -{ -#if ENABLE(WEB_INTENTS) - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - EwkIntent* intentImpl = ewk_object_cast<EwkIntent*>(intent); - EINA_SAFETY_ON_NULL_RETURN_VAL(intentImpl, false); - - WebPageProxy* page = impl->page(); - page->deliverIntentToFrame(page->mainFrame(), intentImpl->webIntentData()); - - return true; -#else - return false; -#endif -} - Eina_Bool ewk_view_back_possible(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - return impl->page()->canGoBack(); + return WKPageCanGoBack(impl->wkPage()); } Eina_Bool ewk_view_forward_possible(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - return impl->page()->canGoForward(); + return WKPageCanGoForward(impl->wkPage()); } Ewk_Back_Forward_List* ewk_view_back_forward_list_get(const Evas_Object* ewkView) @@ -726,15 +311,29 @@ Ewk_Back_Forward_List* ewk_view_back_forward_list_get(const Evas_Object* ewkView return impl->backForwardList(); } +Eina_Bool ewk_view_navigate_to(Evas_Object* ewkView, const Ewk_Back_Forward_List_Item* item) +{ + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); + EWK_OBJ_GET_IMPL_OR_RETURN(const EwkBackForwardListItem, item, itemImpl, false); + + WKPageGoToBackForwardListItem(impl->wkPage(), itemImpl->wkItem()); + + return true; +} + Eina_Bool ewk_view_html_string_load(Evas_Object* ewkView, const char* html, const char* baseUrl, const char* unreachableUrl) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(html, false); - if (unreachableUrl && *unreachableUrl) - impl->page()->loadAlternateHTMLString(String::fromUTF8(html), baseUrl ? String::fromUTF8(baseUrl) : "", String::fromUTF8(unreachableUrl)); - else - impl->page()->loadHTMLString(String::fromUTF8(html), baseUrl ? String::fromUTF8(baseUrl) : ""); + WKRetainPtr<WKStringRef> wkHTMLString = adoptWK(WKStringCreateWithUTF8CString(html)); + WKRetainPtr<WKURLRef> wkBaseURL = adoptWK(WKURLCreateWithUTF8CString(baseUrl)); + + if (unreachableUrl && *unreachableUrl) { + WKRetainPtr<WKURLRef> wkUnreachableURL = adoptWK(WKURLCreateWithUTF8CString(unreachableUrl)); + WKPageLoadAlternateHTMLString(impl->wkPage(), wkHTMLString.get(), wkBaseURL.get(), wkUnreachableURL.get()); + } else + WKPageLoadHTMLString(impl->wkPage(), wkHTMLString.get(), wkBaseURL.get()); impl->informURLChange(); @@ -752,7 +351,23 @@ Eina_Bool ewk_view_custom_encoding_set(Evas_Object* ewkView, const char* encodin { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->setCustomTextEncodingName(encoding ? encoding : String()); + impl->setCustomTextEncodingName(encoding); + + return true; +} + +const char* ewk_view_user_agent_get(const Evas_Object* ewkView) +{ + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); + + return impl->userAgent(); +} + +Eina_Bool ewk_view_user_agent_set(Evas_Object* ewkView, const char* userAgent) +{ + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); + + impl->setUserAgent(userAgent); return true; } @@ -772,7 +387,8 @@ Eina_Bool ewk_view_text_find(Evas_Object* ewkView, const char* text, Ewk_Find_Op EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(text, false); - impl->page()->findString(String::fromUTF8(text), static_cast<WebKit::FindOptions>(options), maxMatchCount); + WKRetainPtr<WKStringRef> wkText = adoptWK(WKStringCreateWithUTF8CString(text)); + WKPageFindString(impl->wkPage(), wkText.get(), static_cast<WebKit::FindOptions>(options), maxMatchCount); return true; } @@ -781,7 +397,7 @@ Eina_Bool ewk_view_text_find_highlight_clear(Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->hideFindUI(); + WKPageHideFindUI(impl->wkPage()); return true; } @@ -791,7 +407,8 @@ Eina_Bool ewk_view_text_matches_count(Evas_Object* ewkView, const char* text, Ew EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); EINA_SAFETY_ON_NULL_RETURN_VAL(text, false); - impl->page()->countStringMatches(String::fromUTF8(text), static_cast<WebKit::FindOptions>(options), maxMatchCount); + WKRetainPtr<WKStringRef> wkText = adoptWK(WKStringCreateWithUTF8CString(text)); + WKPageCountStringMatches(impl->wkPage(), wkText.get(), static_cast<WebKit::FindOptions>(options), maxMatchCount); return true; } @@ -816,13 +433,16 @@ Eina_Bool ewk_view_feed_touch_event(Evas_Object* ewkView, Ewk_Touch_Event_Type t { #if ENABLE(TOUCH_EVENTS) EINA_SAFETY_ON_NULL_RETURN_VAL(points, false); - EWK_VIEW_SD_GET_OR_RETURN(ewkView, smartData, false); - EWK_VIEW_IMPL_GET_BY_SD_OR_RETURN(smartData, impl, false); + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->handleTouchEvent(NativeWebTouchEvent(type, points, modifiers, impl->transformFromScene(), impl->transformToScreen(), ecore_time_get())); + impl->feedTouchEvent(type, points, modifiers); return true; #else + UNUSED_PARAM(ewkView); + UNUSED_PARAM(type); + UNUSED_PARAM(points); + UNUSED_PARAM(modifiers); return false; #endif } @@ -836,6 +456,8 @@ Eina_Bool ewk_view_touch_events_enabled_set(Evas_Object* ewkView, Eina_Bool enab return true; #else + UNUSED_PARAM(ewkView); + UNUSED_PARAM(enabled); return false; #endif } @@ -847,6 +469,7 @@ Eina_Bool ewk_view_touch_events_enabled_get(const Evas_Object* ewkView) return impl->touchEventsEnabled(); #else + UNUSED_PARAM(ewkView); return false; #endif } @@ -856,12 +479,13 @@ Eina_Bool ewk_view_inspector_show(Evas_Object* ewkView) #if ENABLE(INSPECTOR) EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - WebInspectorProxy* inspector = impl->page()->inspector(); - if (inspector) - inspector->show(); + WKInspectorRef wkInspector = WKPageGetInspector(impl->wkPage()); + if (wkInspector) + WKInspectorShow(wkInspector); return true; #else + UNUSED_PARAM(ewkView); return false; #endif } @@ -871,28 +495,29 @@ Eina_Bool ewk_view_inspector_close(Evas_Object* ewkView) #if ENABLE(INSPECTOR) EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - WebInspectorProxy* inspector = impl->page()->inspector(); - if (inspector) - inspector->close(); + WKInspectorRef wkInspector = WKPageGetInspector(impl->wkPage()); + if (wkInspector) + WKInspectorClose(wkInspector); return true; #else + UNUSED_PARAM(ewkView); return false; #endif } -// Ewk_Pagination_Mode should be matched up orders with WebCore::Pagination::Mode. -COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_UNPAGINATED, WebCore::Pagination::Unpaginated); -COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_LEFT_TO_RIGHT, WebCore::Pagination::LeftToRightPaginated); -COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_RIGHT_TO_LEFT, WebCore::Pagination::RightToLeftPaginated); -COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_TOP_TO_BOTTOM, WebCore::Pagination::TopToBottomPaginated); -COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_BOTTOM_TO_TOP, WebCore::Pagination::BottomToTopPaginated); +// Ewk_Pagination_Mode should be matched up orders with WKPaginationMode. +COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_UNPAGINATED, kWKPaginationModeUnpaginated); +COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_LEFT_TO_RIGHT, kWKPaginationModeLeftToRight); +COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_RIGHT_TO_LEFT, kWKPaginationModeRightToLeft); +COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_TOP_TO_BOTTOM, kWKPaginationModeTopToBottom); +COMPILE_ASSERT_MATCHING_ENUM(EWK_PAGINATION_MODE_BOTTOM_TO_TOP, kWKPaginationModeBottomToTop); Eina_Bool ewk_view_pagination_mode_set(Evas_Object* ewkView, Ewk_Pagination_Mode mode) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - impl->page()->setPaginationMode(static_cast<WebCore::Pagination::Mode>(mode)); + + WKPageSetPaginationMode(impl->wkPage(), static_cast<WKPaginationMode>(mode)); return true; } @@ -900,8 +525,8 @@ Eina_Bool ewk_view_pagination_mode_set(Evas_Object* ewkView, Ewk_Pagination_Mode Ewk_Pagination_Mode ewk_view_pagination_mode_get(const Evas_Object* ewkView) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, EWK_PAGINATION_MODE_INVALID); - - return static_cast<Ewk_Pagination_Mode>(impl->page()->paginationMode()); + + return static_cast<Ewk_Pagination_Mode>(WKPageGetPaginationMode(impl->wkPage())); } Eina_Bool ewk_view_fullscreen_exit(Evas_Object* ewkView) @@ -909,10 +534,9 @@ Eina_Bool ewk_view_fullscreen_exit(Evas_Object* ewkView) #if ENABLE(FULLSCREEN_API) EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - impl->page()->fullScreenManager()->requestExitFullScreen(); - - return true; + return WKViewExitFullScreen(impl->wkView()); #else + UNUSED_PARAM(ewkView); return false; #endif } @@ -921,5 +545,87 @@ void ewk_view_draws_page_background_set(Evas_Object *ewkView, Eina_Bool enabled) { EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl); - impl->setDrawsBackground(enabled); + WKViewSetDrawsBackground(impl->wkView(), enabled); +} + +/// Creates a type name for Ewk_Page_Contents_Context. +typedef struct Ewk_Page_Contents_Context Ewk_Page_Contents_Context; + +/* + * @brief Structure containing page contents context used for ewk_view_page_contents_get() API. + */ +struct Ewk_Page_Contents_Context { + Ewk_Page_Contents_Type type; + Ewk_Page_Contents_Cb callback; + void* userData; +}; + +/** + * @internal + * Callback function used for ewk_view_page_contents_get(). + */ +static void ewkViewPageContentsAsMHTMLCallback(WKDataRef wkData, WKErrorRef, void* context) +{ + EINA_SAFETY_ON_NULL_RETURN(context); + + Ewk_Page_Contents_Context* contentsContext = static_cast<Ewk_Page_Contents_Context*>(context); + contentsContext->callback(contentsContext->type, reinterpret_cast<const char*>(WKDataGetBytes(wkData)), contentsContext->userData); + + delete contentsContext; +} + +/** + * @internal + * Callback function used for ewk_view_page_contents_get(). + */ +static void ewkViewPageContentsAsStringCallback(WKStringRef wkString, WKErrorRef, void* context) +{ + EINA_SAFETY_ON_NULL_RETURN(context); + + Ewk_Page_Contents_Context* contentsContext = static_cast<Ewk_Page_Contents_Context*>(context); + contentsContext->callback(contentsContext->type, WKEinaSharedString(wkString), contentsContext->userData); + + delete contentsContext; +} + +Eina_Bool ewk_view_page_contents_get(const Evas_Object* ewkView, Ewk_Page_Contents_Type type, Ewk_Page_Contents_Cb callback, void* user_data) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(callback, false); + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); + + Ewk_Page_Contents_Context* context = new Ewk_Page_Contents_Context; + context->type = type; + context->callback = callback; + context->userData = user_data; + + switch (context->type) { + case EWK_PAGE_CONTENTS_TYPE_MHTML: + WKPageGetContentsAsMHTMLData(impl->wkPage(), false, context, ewkViewPageContentsAsMHTMLCallback); + break; + case EWK_PAGE_CONTENTS_TYPE_STRING: + WKPageGetContentsAsString(impl->wkPage(), context, ewkViewPageContentsAsStringCallback); + break; + default: + delete context; + ASSERT_NOT_REACHED(); + return false; + } + + return true; +} + +Eina_Bool ewk_view_source_mode_set(Evas_Object* ewkView, Eina_Bool enabled) +{ + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); + + WKViewSetShowsAsSource(impl->wkView(), enabled); + + return true; +} + +Eina_Bool ewk_view_source_mode_get(const Evas_Object* ewkView) +{ + EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); + + return WKViewGetShowsAsSource(impl->wkView()); } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_view.h b/Source/WebKit2/UIProcess/API/efl/ewk_view.h index 9a408ab5e..e99169233 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_view.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_view.h @@ -30,6 +30,7 @@ * ewk_auth_request_ref() on the request object to process the authentication asynchronously. * - "back,forward,list,changed", void: reports that the view's back / forward list had changed. * - "cancel,vibration", void: request to cancel the vibration. + * - "contents,size,changed", Ewk_CSS_Size*: reports that contents size was changed. * - "download,cancelled", Ewk_Download_Job*: reports that a download was effectively cancelled. * - "download,failed", Ewk_Download_Job_Error*: reports that a download failed with the given error. * - "download,finished", Ewk_Download_Job*: reports that a download completed successfully. @@ -47,9 +48,8 @@ * when done to continue with the form submission. If the last reference is removed on a * #Ewk_Form_Submission_Request and the form has not been submitted yet, * ewk_form_submission_request_submit() will be called automatically. - * - "icon,changed", void: reports that the view's favicon has changed. - * - "intent,request,new", Ewk_Intent*: reports new Web intent request. - * - "intent,service,register", Ewk_Intent_Service*: reports new Web intent service registration. + * - "favicon,changed", void: reports that the view's favicon has changed. + * The favicon can be queried using ewk_view_favicon_get(). * - "load,error", const Ewk_Error*: reports main frame load failed. * - "load,finished", void: reports load finished. * - "load,progress", double*: load progress has changed (value from 0.0 to 1.0). @@ -62,11 +62,6 @@ * - "policy,decision,new,window", Ewk_Navigation_Policy_Decision*: a new window policy decision should be taken. * To make a policy decision asynchronously, simply increment the reference count of the * #Ewk_Navigation_Policy_Decision object using ewk_navigation_policy_decision_ref(). - * - "resource,request,failed", const Ewk_Resource_Load_Error*: a resource failed loading. - * - "resource,request,finished", const Ewk_Resource*: a resource finished loading. - * - "resource,request,new", const Ewk_Resource_Request*: a resource request was initiated. - * - "resource,request,response", Ewk_Resource_Load_Response*: a response to a resource request was received. - * - "resource,request,sent", const Ewk_Resource_Request*: a resource request was sent. * - "text,found", unsigned int*: the requested text was found and it gives the number of matches. * - "title,changed", const char*: title of the main frame was changed. * - "tooltip,text,set", const char*: tooltip was set. @@ -85,9 +80,8 @@ #include "ewk_context_menu.h" #include "ewk_download_job.h" #include "ewk_error.h" -#include "ewk_intent.h" +#include "ewk_page_group.h" #include "ewk_popup_menu.h" -#include "ewk_resource.h" #include "ewk_security_origin.h" #include "ewk_settings.h" #include "ewk_touch.h" @@ -106,6 +100,12 @@ typedef enum { EWK_TEXT_DIRECTION_LEFT_TO_RIGHT } Ewk_Text_Direction; +/// Enum values containing page contents type values. +typedef enum { + EWK_PAGE_CONTENTS_TYPE_MHTML, + EWK_PAGE_CONTENTS_TYPE_STRING +} Ewk_Page_Contents_Type; + typedef struct Ewk_View_Smart_Data Ewk_View_Smart_Data; typedef struct Ewk_View_Smart_Class Ewk_View_Smart_Class; @@ -114,6 +114,7 @@ struct Ewk_View_Smart_Class { Evas_Smart_Class sc; /**< all but 'data' is free to be changed. */ unsigned long version; + Eina_Bool (*custom_item_selected)(Ewk_View_Smart_Data *sd, Ewk_Context_Menu_Item *item); Eina_Bool (*context_menu_show)(Ewk_View_Smart_Data *sd, Evas_Coord x, Evas_Coord y, Ewk_Context_Menu *menu); Eina_Bool (*context_menu_hide)(Ewk_View_Smart_Data *sd); @@ -153,7 +154,7 @@ struct Ewk_View_Smart_Class { // window creation and closing: // - Create a new window with specified features and close window. - Evas_Object *(*window_create)(Ewk_View_Smart_Data *sd, const Ewk_Window_Features *window_features); + Evas_Object *(*window_create)(Ewk_View_Smart_Data *sd, const char* url, const Ewk_Window_Features *window_features); void (*window_close)(Ewk_View_Smart_Data *sd); }; @@ -173,7 +174,7 @@ struct Ewk_View_Smart_Class { * @see EWK_VIEW_SMART_CLASS_INIT_VERSION * @see EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION */ -#define EWK_VIEW_SMART_CLASS_INIT(smart_class_init) {smart_class_init, EWK_VIEW_SMART_CLASS_VERSION, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define EWK_VIEW_SMART_CLASS_INIT(smart_class_init) {smart_class_init, EWK_VIEW_SMART_CLASS_VERSION, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} /** * Initializer to zero a whole Ewk_View_Smart_Class structure. @@ -202,7 +203,7 @@ struct Ewk_View_Smart_Class { */ #define EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION(name) EWK_VIEW_SMART_CLASS_INIT(EVAS_SMART_CLASS_INIT_NAME_VERSION(name)) -typedef struct EwkViewImpl EwkViewImpl; +typedef struct EwkView EwkView; /** * @brief Contains an internal View data. * @@ -214,7 +215,7 @@ struct Ewk_View_Smart_Data { const Ewk_View_Smart_Class* api; /**< reference to casted class instance */ Evas_Object* self; /**< reference to owner object */ Evas_Object* image; /**< reference to evas_object_image for drawing web contents */ - EwkViewImpl* priv; /**< should never be accessed, c++ stuff */ + EwkView* priv; /**< should never be accessed, c++ stuff */ struct { Evas_Coord x, y, w, h; /**< last used viewport */ } view; @@ -225,42 +226,6 @@ struct Ewk_View_Smart_Data { } changed; }; -/// Creates a type name for Ewk_Resource_Request. -typedef struct Ewk_Resource_Request Ewk_Resource_Request; - -/** - * @brief Structure containing details about a resource request. - */ -struct Ewk_Resource_Request { - Ewk_Resource *resource; /**< resource being requested */ - Ewk_Url_Request *request; /**< URL request for the resource */ - Ewk_Url_Response *redirect_response; /**< Possible redirect response for the resource or @c NULL */ -}; - -/// Creates a type name for Ewk_Resource_Load_Response. -typedef struct Ewk_Resource_Load_Response Ewk_Resource_Load_Response; - -/** - * @brief Structure containing details about a response to a resource request. - */ -struct Ewk_Resource_Load_Response { - Ewk_Resource *resource; /**< resource requested */ - Ewk_Url_Response *response; /**< resource load response */ -}; - -/// Creates a type name for Ewk_Resource_Load_Error. -typedef struct Ewk_Resource_Load_Error Ewk_Resource_Load_Error; - -/** - * @brief Structure containing details about a resource load error. - * - * Details given about a resource load failure. - */ -struct Ewk_Resource_Load_Error { - Ewk_Resource *resource; /**< resource that failed loading */ - Ewk_Error *error; /**< load error */ -}; - /// Creates a type name for Ewk_Download_Job_Error. typedef struct Ewk_Download_Job_Error Ewk_Download_Job_Error; @@ -272,6 +237,17 @@ struct Ewk_Download_Job_Error { Ewk_Error *error; /**< download error */ }; +/// Creates a type name for Ewk_CSS_Size. +typedef struct Ewk_CSS_Size Ewk_CSS_Size; + +/** + * @brief Structure representing size. + */ +struct Ewk_CSS_Size { + Evas_Coord w; /**< width */ + Evas_Coord h; /**< height */ +}; + /** * Enum values used to specify search options. * @brief Provides option to find text @@ -303,6 +279,15 @@ typedef enum { } Ewk_Pagination_Mode; /** + * Creates a type name for the callback function used to get the page contents. + * + * @param type type of the contents + * @param data string buffer of the contents + * @param user_data user data will be passed when ewk_view_page_contents_get is called + */ +typedef void (*Ewk_Page_Contents_Cb)(Ewk_Page_Contents_Type type, const char *data, void *user_data); + +/** * Sets the smart class APIs, enabling view to be inherited. * * @param api class definition to set, all members with the @@ -335,10 +320,11 @@ EAPI Eina_Bool ewk_view_smart_class_set(Ewk_View_Smart_Class *api); * @param e canvas object where to create the view object * @param smart Evas_Smart object. Its type should be EWK_VIEW_TYPE_STR * @param context Ewk_Context object which is used for initializing + * @param pageGroup Ewk_Page_Group object which is used for initializing * * @return view object on success or @c NULL on failure */ -EAPI Evas_Object *ewk_view_smart_add(Evas *e, Evas_Smart *smart, Ewk_Context *context); +EAPI Evas_Object *ewk_view_smart_add(Evas *e, Evas_Smart *smart, Ewk_Context *context, Ewk_Page_Group *pageGroup); /** * Creates a new EFL WebKit view object. @@ -369,6 +355,15 @@ EAPI Evas_Object *ewk_view_add_with_context(Evas *e, Ewk_Context *context); EAPI Ewk_Context *ewk_view_context_get(const Evas_Object *o); /** + * Gets the Ewk_Page_Group of this view. + * + * @param o the view object to get the Ewk_Page_Group + * + * @return the Ewk_Page_Group of this view or @c NULL on failure + */ +EAPI Ewk_Page_Group *ewk_view_page_group_get(const Evas_Object *o); + +/** * Asks the object to load the given URL. * * @param o view object to load @a URL @@ -392,16 +387,14 @@ EAPI Eina_Bool ewk_view_url_set(Evas_Object *o, const char *url); EAPI const char *ewk_view_url_get(const Evas_Object *o); /** - * Returns the current icon URL of view object. - * - * It returns an internal string and should not - * be modified. The string is guaranteed to be stringshared. + * Returns the current favicon of view object. * * @param o view object to get current icon URL * - * @return current icon URL on success or @c NULL if unavailable or on failure + * @return current favicon on success or @c NULL if unavailable or on failure. + * The returned Evas_Object needs to be freed after use. */ -EAPI const char *ewk_view_icon_url_get(const Evas_Object *o); +EAPI Evas_Object *ewk_view_favicon_get(const Evas_Object *o); /** * Asks the main frame to reload the current document. @@ -442,15 +435,6 @@ EAPI Eina_Bool ewk_view_stop(Evas_Object *o); EAPI Ewk_Settings *ewk_view_settings_get(const Evas_Object *o); /** - * Delivers a Web intent to the view's main frame. - * - * @param o view object to deliver the intent to - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_view_intent_deliver(Evas_Object *o, Ewk_Intent *intent); - -/** * Asks the main frame to navigate back in the history. * * @param o view object to navigate back @@ -506,6 +490,16 @@ EAPI Eina_Bool ewk_view_forward_possible(Evas_Object *o); EAPI Ewk_Back_Forward_List *ewk_view_back_forward_list_get(const Evas_Object *o); /** + * Navigates to specified back-forward list item. + * + * @param o view object to navigate in the history + * @param item the back-forward list item + * + * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise + */ +EAPI Eina_Bool ewk_view_navigate_to(Evas_Object *o, const Ewk_Back_Forward_List_Item *item); + +/** * Gets the current title of the main frame. * * It returns an internal string and should not @@ -649,10 +643,10 @@ EAPI const char *ewk_view_theme_get(const Evas_Object *o); * * @param o view object to get the current encoding * - * @return @c eina_strinshare containing the current encoding, or + * @return @c eina_stringshare containing the current encoding, or * @c NULL if it's not set */ -EAPI const char *ewk_view_custom_encoding_get(const Evas_Object *o); +EAPI const char *ewk_view_custom_encoding_get(const Evas_Object *o); /** * Sets the custom character encoding and reloads the page. @@ -662,7 +656,27 @@ EAPI const char *ewk_view_custom_encoding_get(const Evas_Object *o); * * @return @c EINA_TRUE on success @c EINA_FALSE otherwise */ -EAPI Eina_Bool ewk_view_custom_encoding_set(Evas_Object *o, const char *encoding); +EAPI Eina_Bool ewk_view_custom_encoding_set(Evas_Object *o, const char *encoding); + +/** + * Gets the current user agent string. + * + * @param o view object to get the current user agent + * + * @return @c eina_stringshare containing the current user agent, or + * @c default user agent if it's not set + */ +EAPI const char *ewk_view_user_agent_get(const Evas_Object *o); + +/** + * Sets the user agent string. + * + * @param o view to set the user agent + * @param user_agent the user agent string to set or @c NULL to restore the default one + * + * @return @c EINA_TRUE on success @c EINA_FALSE otherwise + */ +EAPI Eina_Bool ewk_view_user_agent_set(Evas_Object *o, const char *encoding); /** * Searches and hightlights the given string in the document. @@ -834,6 +848,42 @@ EAPI Eina_Bool ewk_view_fullscreen_exit(Evas_Object *o); */ EAPI void ewk_view_draws_page_background_set(Evas_Object *o, Eina_Bool enabled); +/** + * Get contents of the current web page. + * + * @param o view object to get the page contents + * @param type type of the page contents + * @param callback callback function to be called when the operation is finished + * @param user_data user data to be passed to the callback function + * + * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise + */ +EAPI Eina_Bool ewk_view_page_contents_get(const Evas_Object *o, Ewk_Page_Contents_Type type, Ewk_Page_Contents_Cb callback, void *user_data); + +/** + * Sets the source mode as EINA_TRUE to display the web source code + * or EINA_FALSE otherwise. The default value is EINA_FALSE. + * + * This method should be called before loading new contents on web view + * so that the new view mode will be applied to the new contents. + * + * @param o view object to set the view source mode + * @param enabled a state to set view source mode + * + * @return @c EINA_TRUE on success, or @c EINA_FALSE on failure + */ +EAPI Eina_Bool ewk_view_source_mode_set(Evas_Object *o, Eina_Bool enabled); + +/** + * Gets the view source mode of the current web page. + * + * @param o view object to get the view source mode + * + * @return @c EINA_TRUE if the view mode is set to load source code, or + * @c EINA_FALSE otherwise + */ +EAPI Eina_Bool ewk_view_source_mode_get(const Evas_Object *o); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h index 9a51ef244..6de35d91e 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h @@ -1,30 +1,42 @@ /* - * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2013 Intel Corporation. All rights reserved. * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ewk_view_private_h #define ewk_view_private_h -#include "EwkViewImpl.h" #include <Evas.h> #include <WebKit2/WKBase.h> -Evas_Object* ewk_view_base_add(Evas* canvas, WKContextRef, WKPageGroupRef, EwkViewImpl::ViewBehavior); +#ifdef __cplusplus +extern "C" { +#endif + +EAPI Evas_Object* EWKViewCreate(WKContextRef, WKPageGroupRef, Evas*, Evas_Smart*); +EAPI WKViewRef EWKViewGetWKView(Evas_Object*); +#ifdef __cplusplus +} +#endif #endif // ewk_view_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_window_features.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_window_features.cpp index 66a6c910f..8824cafbe 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_window_features.cpp +++ b/Source/WebKit2/UIProcess/API/efl/ewk_window_features.cpp @@ -26,72 +26,76 @@ #include "config.h" #include "ewk_window_features.h" -#include "WebNumber.h" +#include "EwkView.h" +#include "WKDictionary.h" +#include "WKNumber.h" +#include "WKString.h" #include "ewk_window_features_private.h" -#include <Eina.h> using namespace WebKit; -EwkWindowFeatures::EwkWindowFeatures(ImmutableDictionary* windowFeatures, EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) - , m_geometry(0, 0, 100, 100) - , m_toolbarVisible(true) - , m_statusBarVisible(true) - , m_scrollbarsVisible(true) - , m_menuBarVisible(true) - , m_locationBarVisible(true) - , m_resizable(true) - , m_fullScreen(false) +EwkWindowFeatures::EwkWindowFeatures(WKDictionaryRef windowFeatures, EwkView* view) + : m_view(view) + , m_toolbarVisible(getWindowFeatureBoolValue(windowFeatures, "toolBarVisible", true)) + , m_statusBarVisible(getWindowFeatureBoolValue(windowFeatures, "statusBarVisible", true)) + , m_scrollbarsVisible(getWindowFeatureBoolValue(windowFeatures, "scrollbarsVisible", true)) + , m_menuBarVisible(getWindowFeatureBoolValue(windowFeatures, "menuBarVisible", true)) + , m_locationBarVisible(getWindowFeatureBoolValue(windowFeatures, "locationBarVisible", true)) + , m_resizable(getWindowFeatureBoolValue(windowFeatures, "resizable", true)) + , m_fullScreen(getWindowFeatureBoolValue(windowFeatures, "fullscreen", false)) { - if (windowFeatures) { - m_geometry.setX(getWindowFeatureValue<double, WebDouble>(windowFeatures, ASCIILiteral("x"))); - m_geometry.setY(getWindowFeatureValue<double, WebDouble>(windowFeatures, ASCIILiteral("y"))); - m_geometry.setWidth(getWindowFeatureValue<double, WebDouble>(windowFeatures, ASCIILiteral("width"))); - m_geometry.setHeight(getWindowFeatureValue<double, WebDouble>(windowFeatures, ASCIILiteral("height"))); + m_geometry.x = getWindowFeatureDoubleValue(windowFeatures, "x", 0); + m_geometry.y = getWindowFeatureDoubleValue(windowFeatures, "y", 0); + m_geometry.w = getWindowFeatureDoubleValue(windowFeatures, "width", 0); + m_geometry.h = getWindowFeatureDoubleValue(windowFeatures, "height", 0); +} + +static inline WKTypeRef getWindowFeatureValue(WKDictionaryRef windowFeatures, const char* featureName) +{ + ASSERT(featureName); + if (!windowFeatures) + return 0; - m_toolbarVisible = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("toolBarVisible")); - m_statusBarVisible = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("statusBarVisible")); - m_scrollbarsVisible = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("scrollbarsVisible")); - m_menuBarVisible = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("menuBarVisible")); - m_locationBarVisible = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("locationBarVisible")); - m_resizable = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("resizable")); - m_fullScreen = getWindowFeatureValue<bool, WebBoolean>(windowFeatures, ASCIILiteral("fullscreen")); - } + WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString(featureName)); + return WKDictionaryGetItemForKey(windowFeatures, key.get()); } -template <typename T1, typename T2> -T1 EwkWindowFeatures::getWindowFeatureValue(ImmutableDictionary* windowFeatures, const String& featureName) +bool EwkWindowFeatures::getWindowFeatureBoolValue(WKDictionaryRef windowFeatures, const char* featureName, bool defaultValue) { - T2* featureValue = static_cast<T2*>(windowFeatures->get(featureName)); + WKBooleanRef value = static_cast<WKBooleanRef>(getWindowFeatureValue(windowFeatures, featureName)); - if (!featureValue) - return false; + return value ? WKBooleanGetValue(value) : defaultValue; +} + +double EwkWindowFeatures::getWindowFeatureDoubleValue(WKDictionaryRef windowFeatures, const char* featureName, double defaultValue) +{ + WKDoubleRef value = static_cast<WKDoubleRef>(getWindowFeatureValue(windowFeatures, featureName)); - return featureValue->value(); + return value ? WKDoubleGetValue(value) : defaultValue; } void EwkWindowFeatures::setToolbarVisible(bool toolbarVisible) { m_toolbarVisible = toolbarVisible; - m_viewImpl->smartCallback<EwkViewCallbacks::ToolbarVisible>().call(&toolbarVisible); + m_view->smartCallback<EwkViewCallbacks::ToolbarVisible>().call(&toolbarVisible); } void EwkWindowFeatures::setStatusBarVisible(bool statusBarVisible) { m_statusBarVisible = statusBarVisible; - m_viewImpl->smartCallback<EwkViewCallbacks::StatusBarVisible>().call(&statusBarVisible); + m_view->smartCallback<EwkViewCallbacks::StatusBarVisible>().call(&statusBarVisible); } void EwkWindowFeatures::setMenuBarVisible(bool menuBarVisible) { m_menuBarVisible = menuBarVisible; - m_viewImpl->smartCallback<EwkViewCallbacks::MenuBarVisible>().call(&menuBarVisible); + m_view->smartCallback<EwkViewCallbacks::MenuBarVisible>().call(&menuBarVisible); } void EwkWindowFeatures::setResizable(bool resizable) { m_resizable = resizable; - m_viewImpl->smartCallback<EwkViewCallbacks::WindowResizable>().call(&resizable); + m_view->smartCallback<EwkViewCallbacks::WindowResizable>().call(&resizable); } Eina_Bool ewk_window_features_toolbar_visible_get(const Ewk_Window_Features* window_features) @@ -147,15 +151,16 @@ void ewk_window_features_geometry_get(const Ewk_Window_Features* window_features { EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl); + const Evas_Coord_Rectangle& geometry = impl->geometry(); if (x) - *x = static_cast<Evas_Coord>(impl->geometry().x()); + *x = geometry.x; if (y) - *y = static_cast<Evas_Coord>(impl->geometry().y()); + *y = geometry.y; if (width) - *width = static_cast<Evas_Coord>(impl->geometry().width()); + *width = geometry.w; if (height) - *height = static_cast<Evas_Coord>(impl->geometry().height()); + *height = geometry.h; } diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_window_features_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_window_features_private.h index c6bf89232..8ae6c90c1 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_window_features_private.h +++ b/Source/WebKit2/UIProcess/API/efl/ewk_window_features_private.h @@ -26,26 +26,24 @@ #ifndef ewk_window_features_private_h #define ewk_window_features_private_h -#include "EwkViewImpl.h" -#include "ImmutableDictionary.h" -#include "WindowFeatures.h" #include "ewk_object_private.h" -#include <WebCore/FloatRect.h> +#include <Evas.h> +#include <WebKit2/WKBase.h> #include <wtf/RefCounted.h> -class EwkViewImpl; +class EwkView; class EwkWindowFeatures : public EwkObject { public: EWK_OBJECT_DECLARE(EwkWindowFeatures) - static PassRefPtr<EwkWindowFeatures> create(WebKit::ImmutableDictionary* windowFeatures, EwkViewImpl* viewImpl) + static PassRefPtr<EwkWindowFeatures> create(WKDictionaryRef windowFeatures, EwkView* viewImpl) { return adoptRef(new EwkWindowFeatures(windowFeatures, viewImpl)); } - WebCore::FloatRect geometry() const { return m_geometry; } - void setGeometry(WebCore::FloatRect& geometry) { m_geometry = geometry; } + const Evas_Coord_Rectangle& geometry() const { return m_geometry; } + void setGeometry(const Evas_Coord_Rectangle& geometry) { m_geometry = geometry; } bool toolbarVisible() const { return m_toolbarVisible; } void setToolbarVisible(bool toolbarVisible); @@ -69,13 +67,14 @@ public: void setFullScreen(bool fullScreen) { m_fullScreen = fullScreen; } private: - EwkWindowFeatures(WebKit::ImmutableDictionary* windowFeatures, EwkViewImpl* viewImpl); - template <typename T1, typename T2> - static T1 getWindowFeatureValue(WebKit::ImmutableDictionary* windowFeatures, const String& featureName); + EwkWindowFeatures(WKDictionaryRef windowFeatures, EwkView* viewImpl); - EwkViewImpl* m_viewImpl; + static bool getWindowFeatureBoolValue(WKDictionaryRef windowFeatures, const char* featureName, bool defaultValue); + static double getWindowFeatureDoubleValue(WKDictionaryRef windowFeatures, const char* featureName, double defaultValue); - WebCore::FloatRect m_geometry; + EwkView* m_view; + + Evas_Coord_Rectangle m_geometry; bool m_toolbarVisible; bool m_statusBarVisible; bool m_scrollbarsVisible; diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp index 6ce318f14..c671cb77c 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp @@ -23,7 +23,6 @@ #include "EWK2UnitTestEnvironment.h" #include <Ecore.h> #include <glib-object.h> -#include <wtf/UnusedParam.h> extern EWK2UnitTest::EWK2UnitTestEnvironment* environment; @@ -51,15 +50,26 @@ void EWK2UnitTestBase::SetUp() #if defined(WTF_USE_ACCELERATED_COMPOSITING) && defined(HAVE_ECORE_X) const char* engine = "opengl_x11"; m_ecoreEvas = ecore_evas_new(engine, 0, 0, width, height, 0); -#else - m_ecoreEvas = ecore_evas_new(0, 0, 0, width, height, 0); + // Graceful fallback to software rendering if evas_gl engine is not available. + if (!m_ecoreEvas) #endif + m_ecoreEvas = ecore_evas_new(0, 0, 0, width, height, 0); ecore_evas_show(m_ecoreEvas); Evas* evas = ecore_evas_get(m_ecoreEvas); Evas_Smart* smart = evas_smart_class_new(&m_ewkViewClass.sc); - m_webView = ewk_view_smart_add(evas, smart, ewk_context_default_get()); + + Ewk_Context* newContext = ewk_context_new(); + Ewk_Page_Group* newPageGroup = ewk_page_group_create("UnitTest"); + m_webView = ewk_view_smart_add(evas, smart, newContext, newPageGroup); + + // Clear HTTP cache files before running the unit tests, which prevents + // performance degradation due to so many cache files. + ewk_context_resource_cache_clear(newContext); + ewk_object_unref(newContext); + ewk_object_unref(newPageGroup); + ewk_view_theme_set(m_webView, environment->defaultTheme()); evas_object_resize(m_webView, width, height); @@ -96,7 +106,7 @@ public: bool isDone() const { return m_done; } - bool setDone() + void setDone() { if (m_timer) { ecore_timer_del(m_timer); @@ -215,6 +225,16 @@ bool EWK2UnitTestBase::waitUntilURLChangedTo(const char* expectedURL, double tim return !data.didTimeOut(); } +bool EWK2UnitTestBase::waitUntilTrue(bool &flag, double timeoutSeconds) +{ + CallbackDataExpectedValue<bool> data(true, timeoutSeconds); + + while (!data.isDone() && !flag) + ecore_main_loop_iterate(); + + return !data.didTimeOut(); +} + void EWK2UnitTestBase::mouseClick(int x, int y, int button) { Evas* evas = evas_object_evas_get(m_webView); @@ -223,6 +243,14 @@ void EWK2UnitTestBase::mouseClick(int x, int y, int button) evas_event_feed_mouse_up(evas, button, EVAS_BUTTON_NONE, 0, 0); } +void EWK2UnitTestBase::mouseDoubleClick(int x, int y, int button) +{ + Evas* evas = evas_object_evas_get(m_webView); + evas_event_feed_mouse_move(evas, x, y, 0, 0); + evas_event_feed_mouse_down(evas, button, EVAS_BUTTON_DOUBLE_CLICK, 0, 0); + evas_event_feed_mouse_up(evas, button, EVAS_BUTTON_NONE, 0, 0); +} + void EWK2UnitTestBase::mouseDown(int x, int y, int button) { Evas* evas = evas_object_evas_get(m_webView); diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h index bd5e4b995..13efa8bee 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h +++ b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h @@ -35,6 +35,7 @@ public: Ecore_Evas* backingStore() { return m_ecoreEvas; } Evas* canvas() { return ecore_evas_get(m_ecoreEvas); } Evas_Object* webView() { return m_webView; } + void setWebView(Evas_Object* webView) { m_webView = webView; } Ewk_View_Smart_Class* ewkViewClass() { return &m_ewkViewClass; } protected: @@ -49,8 +50,10 @@ protected: bool waitUntilLoadFinished(double timeoutSeconds = defaultTimeoutSeconds); bool waitUntilTitleChangedTo(const char* expectedTitle, double timeoutSeconds = defaultTimeoutSeconds); bool waitUntilURLChangedTo(const char* expectedURL, double timeoutSeconds = defaultTimeoutSeconds); + bool waitUntilTrue(bool &flag, double timeoutSeconds = defaultTimeoutSeconds); void mouseClick(int x, int y, int button = 1 /*Left*/); + void mouseDoubleClick(int x, int y, int button = 1 /*Left*/); void mouseDown(int x, int y, int button = 1 /*Left*/); void mouseUp(int x, int y, int button = 1 /*Left*/); void mouseMove(int x, int y); diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/intent-request.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/intent-request.html deleted file mode 100644 index 7b06cbec9..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/intent-request.html +++ /dev/null @@ -1,29 +0,0 @@ -<html> -<head> -<title>Web intent request test</title> -<script type="text/javascript"> -var clickCount = 0; - -function buttonClicked() { - if (clickCount == 0) { - var testIntent = new WebKitIntent( - {"action": "action1", - "type": "mime/type1", - "service": "http://service1.com/", - "extras": {"key1": "value1", "key2": "value2"}}); - navigator.webkitStartActivity(testIntent); - } else if (clickCount == 1) { - var testIntent = new WebKitIntent( - {"action": "action2", - "type": "mime/type2", - "suggestions": ["http://service1.com/", "http://service2.com/"]}); - navigator.webkitStartActivity(testIntent); - } - clickCount++; -} -</script> -</head> -<body> -<input type="button" id="button" value="Start Web Intent" onmouseup="buttonClicked()" style="position: absolute; top: 0px; left: 0px;"/> -</body> -</html> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/intent-service.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/intent-service.html deleted file mode 100644 index 1d9fa2a33..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/intent-service.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<head> -<title>Web Intent service registration test</title> -</head> - <body> - <intent action="action" type="type" title="Title" href="http://example.com/service" disposition="inline"></intent> - Registered Intent Service. - </body> -</html> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/spelling_selection_tests.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/spelling_selection_tests.html new file mode 100644 index 000000000..635eebd12 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/tests/resources/spelling_selection_tests.html @@ -0,0 +1,46 @@ +<!-- + The page contains elements used to check context menu spelling suggestions. + There are also available functions which select specific part of misspelled word/sentence. +--> +<html> +<head> + <title>Testing selection for Spelling</title> + <script> + // Select all text inside element. + function selectText(element) + { + var text = document.getElementById(element); + var selection = window.getSelection(); + var range = document.createRange(); + range.selectNodeContents(text); + selection.removeAllRanges(); + selection.addRange(range); + } + + // Select part of text inside element. + function selectSubText(element) + { + var text = document.getElementById(element); + var startNode = text.firstChild; + var endNode = text.firstChild; + var range = document.createRange(); + range.setStart(startNode, 2); + range.setEnd(endNode, 6); + // Select "llco" from Wellcome word. + var selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + } + </script> +</head> + +<body> + <!-- element used to count context menu items, without spellcheck suggestions --> + <div contenteditable="true" id="elementWithoutSpellcheck" spellcheck="false">Wellcome home</div> + <div contenteditable="true" id="elementWithSpellcheck" spellcheck="true">Wellcome home</div> + + <button onclick="selectText('elementWithSpellcheck')">Select all words</button> + <button onclick="selectSubText('elementWithSpellcheck')">Select sub word</button> + <button onclick="selectText('elementWithoutSpellcheck')">Select all words in field without spellcheck</button> +</body> +</html> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_auth_request.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_auth_request.cpp index cc3502177..0a7032d0d 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_auth_request.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_auth_request.cpp @@ -33,51 +33,63 @@ using namespace EWK2UnitTest; extern EWK2UnitTestEnvironment* environment; -static const char TEST_USERNAME[] = "username"; -static const char TEST_PASSWORD[] = "password"; -static const char EXPECTED_AUTHORIZATION[] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; // Base64 encoding of "username:password". -static const char INDEX_HTML_STRING[] = +static const char testUsername[] = "username"; +static const char testPassword[] = "password"; +static const char expectedSuccessTitle[] = "EFLWebKit2 Authentication test"; +static const char expectedAuthorization[] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; // Base64 encoding of "username:password". +static const char indexHTMLString[] = "<html>" "<head><title>EFLWebKit2 Authentication test</title></head>" "<body></body></html>"; -static void serverCallback(SoupServer*, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, void*) -{ - if (message->method != SOUP_METHOD_GET) { - soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); - return; +class EWK2AuthRequestTest : public EWK2UnitTestBase { +public: + static void serverCallback(SoupServer*, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, void*) + { + if (message->method != SOUP_METHOD_GET) { + soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); + return; + } + + if (!strcmp(path, "/index.html")) { + const char* authorization = soup_message_headers_get_one(message->request_headers, "Authorization"); + // Require authentication + if (authorization && !strcmp(authorization, expectedAuthorization)) { + // Successful authentication. + soup_message_set_status(message, SOUP_STATUS_OK); + soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, indexHTMLString, strlen(indexHTMLString)); + } else { + // No (valid) authorization header provided by the client, request authentication. + soup_message_set_status(message, SOUP_STATUS_UNAUTHORIZED); + soup_message_headers_append(message->response_headers, "WWW-Authenticate", "Basic realm=\"my realm\""); + } + } else + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + + soup_message_body_complete(message->response_body); } - if (!strcmp(path, "/index.html")) { - const char* authorization = soup_message_headers_get_one(message->request_headers, "Authorization"); - // Require authentication - if (authorization && !strcmp(authorization, EXPECTED_AUTHORIZATION)) { - // Successful authentication. - soup_message_set_status(message, SOUP_STATUS_OK); - soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, INDEX_HTML_STRING, strlen(INDEX_HTML_STRING)); - } else { - // No (valid) authorization header provided by the client, request authentication. - soup_message_set_status(message, SOUP_STATUS_UNAUTHORIZED); - soup_message_headers_append(message->response_headers, "WWW-Authenticate", "Basic realm=\"my realm\""); - } - } else - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + static void onAuthenticationRequest(void* userData, Evas_Object*, void* eventInfo) + { + Ewk_Auth_Request** returnRequest = static_cast<Ewk_Auth_Request**>(userData); + ASSERT_TRUE(returnRequest); - soup_message_body_complete(message->response_body); -} + Ewk_Auth_Request* request = static_cast<Ewk_Auth_Request*>(eventInfo); + ASSERT_TRUE(request); -static void onAuthenticationRequest(void* userData, Evas_Object*, void* eventInfo) -{ - Ewk_Auth_Request** returnRequest = static_cast<Ewk_Auth_Request**>(userData); - ASSERT_TRUE(returnRequest); + *returnRequest = ewk_object_ref(request); + } - Ewk_Auth_Request* request = static_cast<Ewk_Auth_Request*>(eventInfo); - ASSERT_TRUE(request); + static void onLoadFinished(void* userData, Evas_Object*, void*) + { + bool* isFinished = static_cast<bool*>(userData); + ASSERT_TRUE(isFinished); - *returnRequest = ewk_object_ref(request); -} + *isFinished = true; + } +}; -TEST_F(EWK2UnitTestBase, ewk_auth_request_success) +TEST_F(EWK2AuthRequestTest, ewk_auth_request_success) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -97,14 +109,14 @@ TEST_F(EWK2UnitTestBase, ewk_auth_request_success) EXPECT_STREQ("127.0.0.1", ewk_auth_request_host_get(authenticationRequest)); EXPECT_FALSE(ewk_auth_request_retrying_get(authenticationRequest)); - ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, TEST_USERNAME, TEST_PASSWORD)); + ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, testUsername, testPassword)); ewk_object_unref(authenticationRequest); - ASSERT_TRUE(waitUntilTitleChangedTo("EFLWebKit2 Authentication test")); + ASSERT_TRUE(waitUntilTitleChangedTo(expectedSuccessTitle)); } -TEST_F(EWK2UnitTestBase, ewk_auth_request_failure_then_success) +TEST_F(EWK2AuthRequestTest, ewk_auth_request_failure_then_success) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -123,7 +135,7 @@ TEST_F(EWK2UnitTestBase, ewk_auth_request_failure_then_success) EXPECT_STREQ("127.0.0.1", ewk_auth_request_host_get(authenticationRequest)); EXPECT_FALSE(ewk_auth_request_retrying_get(authenticationRequest)); - ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, TEST_USERNAME, "wrongpassword")); + ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, testUsername, "wrongpassword")); ewk_object_unref(authenticationRequest); authenticationRequest = 0; @@ -138,28 +150,14 @@ TEST_F(EWK2UnitTestBase, ewk_auth_request_failure_then_success) EXPECT_TRUE(ewk_auth_request_retrying_get(authenticationRequest)); // Now provide the right password. - ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, TEST_USERNAME, TEST_PASSWORD)); + ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, testUsername, testPassword)); ewk_object_unref(authenticationRequest); - ASSERT_TRUE(waitUntilTitleChangedTo("EFLWebKit2 Authentication test")); -} - -static void onResourceLoadResponse(void* userData, Evas_Object*, void* eventInfo) -{ - int* statusCode = static_cast<int*>(userData); - ASSERT_TRUE(statusCode); - - Ewk_Resource_Load_Response* response = static_cast<Ewk_Resource_Load_Response*>(eventInfo); - ASSERT_TRUE(response); - - if (!ewk_resource_main_resource_get(response->resource)) - return; - - *statusCode = ewk_url_response_status_code_get(response->response); + ASSERT_TRUE(waitUntilTitleChangedTo(expectedSuccessTitle)); } -TEST_F(EWK2UnitTestBase, ewk_auth_request_cancel) +TEST_F(EWK2AuthRequestTest, ewk_auth_request_cancel) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -179,17 +177,16 @@ TEST_F(EWK2UnitTestBase, ewk_auth_request_cancel) EXPECT_STREQ("127.0.0.1", ewk_auth_request_host_get(authenticationRequest)); EXPECT_FALSE(ewk_auth_request_retrying_get(authenticationRequest)); - int statusCode = 0; - evas_object_smart_callback_add(webView(), "resource,request,response", onResourceLoadResponse, &statusCode); + bool isFinished = false; + evas_object_smart_callback_add(webView(), "load,finished", onLoadFinished, &isFinished); // Will attempt to continue without authentication by default. ewk_object_unref(authenticationRequest); - while (!statusCode) + while (!isFinished) ecore_main_loop_iterate(); - // We should get a "402 Unauthorized" error. - EXPECT_EQ(SOUP_STATUS_UNAUTHORIZED, statusCode); + ASSERT_STRNE(expectedSuccessTitle, ewk_view_title_get(webView())); - evas_object_smart_callback_del(webView(), "resource,request,response", onResourceLoadResponse); + evas_object_smart_callback_del(webView(), "load,finished", onLoadFinished); } diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_back_forward_list.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_back_forward_list.cpp index c0510c594..400f5430d 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_back_forward_list.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_back_forward_list.cpp @@ -58,32 +58,35 @@ static void serverCallbackNavigation(SoupServer* server, SoupMessage* message, c soup_message_body_complete(message->response_body); } -static inline void checkItem(Ewk_Back_Forward_List_Item* item, const char* title, const char* url, const char* originalURL) -{ - ASSERT_TRUE(item); - EXPECT_STREQ(url, ewk_back_forward_list_item_url_get(item)); - EXPECT_STREQ(title, ewk_back_forward_list_item_title_get(item)); - EXPECT_STREQ(originalURL, ewk_back_forward_list_item_original_url_get(item)); -} +class EWK2BackForwardListTest : public EWK2UnitTestBase { +protected: + void checkItem(Ewk_Back_Forward_List_Item* item, const char* title, const char* url, const char* originalURL) + { + ASSERT_TRUE(item); + EXPECT_STREQ(url, ewk_back_forward_list_item_url_get(item)); + EXPECT_STREQ(title, ewk_back_forward_list_item_title_get(item)); + EXPECT_STREQ(originalURL, ewk_back_forward_list_item_original_url_get(item)); + } -static inline WKEinaSharedString urlFromTitle(EWK2UnitTestServer* httpServer, const char* title) -{ - Eina_Strbuf* path = eina_strbuf_new(); - eina_strbuf_append_printf(path, "/%s", title); - WKEinaSharedString res = httpServer->getURLForPath(eina_strbuf_string_get(path)).data(); - eina_strbuf_free(path); + WKEinaSharedString urlFromTitle(EWK2UnitTestServer* httpServer, const char* title) + { + Eina_Strbuf* path = eina_strbuf_new(); + eina_strbuf_append_printf(path, "/%s", title); + WKEinaSharedString res = httpServer->getURLForPath(eina_strbuf_string_get(path)).data(); + eina_strbuf_free(path); - return res; -} + return res; + } -static inline void freeEinaList(Eina_List* list) -{ - void* data = 0; - EINA_LIST_FREE(list, data) + void freeEinaList(Eina_List* list) + { + void* data = 0; + EINA_LIST_FREE(list, data) ewk_object_unref(static_cast<Ewk_Object*>(data)); -} + } +}; -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_current_item_get) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_current_item_get) { const char* url = environment->defaultTestPageUrl(); ASSERT_TRUE(loadUrlSync(url)); @@ -97,7 +100,7 @@ TEST_F(EWK2UnitTestBase, ewk_back_forward_list_current_item_get) ASSERT_EQ(currentItem, anotherCurrentItem); } -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_previous_item_get) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_previous_item_get) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); @@ -119,7 +122,7 @@ TEST_F(EWK2UnitTestBase, ewk_back_forward_list_previous_item_get) ASSERT_EQ(previousItem, anotherPreviousItem); } -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_next_item_get) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_next_item_get) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); @@ -145,7 +148,7 @@ TEST_F(EWK2UnitTestBase, ewk_back_forward_list_next_item_get) ASSERT_EQ(nextItem, anotherNextItem); } -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_item_at_index_get) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_item_at_index_get) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); @@ -170,7 +173,7 @@ TEST_F(EWK2UnitTestBase, ewk_back_forward_list_item_at_index_get) ASSERT_FALSE(nonExistingItem); } -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_count) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_count) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); @@ -187,7 +190,7 @@ TEST_F(EWK2UnitTestBase, ewk_back_forward_list_count) EXPECT_EQ(2, ewk_back_forward_list_count(backForwardList)); } -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_n_back_items_copy) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_n_back_items_copy) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); @@ -224,7 +227,7 @@ TEST_F(EWK2UnitTestBase, ewk_back_forward_list_n_back_items_copy) freeEinaList(backList); } -TEST_F(EWK2UnitTestBase, ewk_back_forward_list_n_forward_items_copy) +TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_n_forward_items_copy) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_color_picker.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_color_picker.cpp index c6d0b32af..f61631e97 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_color_picker.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_color_picker.cpp @@ -38,76 +38,93 @@ static const int changedAlpha = 0xff; static bool s_isColorPickerShown = false; static Ewk_Color_Picker* s_colorPicker = 0; +class EWK2ColorPickerTest : public EWK2UnitTestBase { +public: + static void onColorPickerDone(void* userData, Evas_Object*, void*) + { + bool* handled = static_cast<bool*>(userData); -static void onColorPickerDone(void* userData, Evas_Object*, void*) -{ - bool* handled = static_cast<bool*>(userData); - - *handled = true; -} - -static unsigned char setColorPickerColor(void* data) -{ - Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - - // 4. Change color to changed color. - EXPECT_TRUE(ewk_color_picker_color_set(s_colorPicker, changedRed, changedGreen, changedBlue, changedAlpha)); - - evas_object_smart_callback_call(smartData->self, "input,type,color,request", 0); - - return 0; -} - -static Eina_Bool showColorPicker(Ewk_View_Smart_Data* smartData, Ewk_Color_Picker* colorPicker) -{ - static bool isFirstRun = true; + *handled = true; + } - s_colorPicker = colorPicker; - s_isColorPickerShown = true; + static unsigned char setColorPickerColor(void* data) + { + Ewk_View_Smart_Data* smartData = static_cast<Ewk_View_Smart_Data*>(data); - int r, g, b, a; - EXPECT_TRUE(ewk_color_picker_color_get(colorPicker, &r, &g, &b, &a)); + // 4. Change color to changed color. + EXPECT_TRUE(ewk_color_picker_color_set(s_colorPicker, changedRed, changedGreen, changedBlue, changedAlpha)); - if (isFirstRun) { - // 2. Check initial value from html file. - EXPECT_EQ(initialRed, r); - EXPECT_EQ(initialGreen, g); - EXPECT_EQ(initialBlue, b); - EXPECT_EQ(initialAlpha, a); + evas_object_smart_callback_call(smartData->self, "input,type,color,request", 0); - isFirstRun = false; - } else { - // 7. Input values should be same as changed color. - EXPECT_EQ(changedRed, r); - EXPECT_EQ(changedGreen, g); - EXPECT_EQ(changedBlue, b); - EXPECT_EQ(changedAlpha, a); + return 0; + } - evas_object_smart_callback_call(smartData->self, "input,type,color,request", 0); + static Eina_Bool showColorPicker(Ewk_View_Smart_Data* smartData, Ewk_Color_Picker* colorPicker) + { + static bool isFirstRun = true; + + s_colorPicker = colorPicker; + s_isColorPickerShown = true; + + int r, g, b, a; + EXPECT_TRUE(ewk_color_picker_color_get(colorPicker, &r, &g, &b, &a)); + + if (isFirstRun) { + // 2. Check initial value from html file. + EXPECT_EQ(initialRed, r); + EXPECT_EQ(initialGreen, g); + EXPECT_EQ(initialBlue, b); + EXPECT_EQ(initialAlpha, a); + + isFirstRun = false; + } else { + // 7. Input values should be same as changed color. + EXPECT_EQ(changedRed, r); + EXPECT_EQ(changedGreen, g); + EXPECT_EQ(changedBlue, b); + EXPECT_EQ(changedAlpha, a); + + evas_object_smart_callback_call(smartData->self, "input,type,color,request", 0); + return true; + } + + // 3. Return after making a color picker. + ecore_timer_add(0.0, setColorPickerColor, smartData); return true; } - // 3. Return after making a color picker. - ecore_timer_add(0.0, setColorPickerColor, smartData); - return true; -} + static Eina_Bool hideColorPicker(Ewk_View_Smart_Data*) + { + // 5. Test color picker is shown. + EXPECT_TRUE(s_isColorPickerShown); + s_isColorPickerShown = false; + } -static Eina_Bool hideColorPicker(Ewk_View_Smart_Data*) -{ - // 5. Test color picker is shown. - EXPECT_TRUE(s_isColorPickerShown); - s_isColorPickerShown = false; -} + static Eina_Bool hideColorPickerByRemovingElement(Ewk_View_Smart_Data* smartData) + { + // 9. input_picker_color_dismiss() is called if the element is removed. + EXPECT_TRUE(s_isColorPickerShown); + s_isColorPickerShown = false; + evas_object_smart_callback_call(smartData->self, "input,type,color,request", 0); + } -static Eina_Bool hideColorPickerByRemovingElement(Ewk_View_Smart_Data* smartData) -{ - // 9. input_picker_color_dismiss() is called if the element is removed. - EXPECT_TRUE(s_isColorPickerShown); - s_isColorPickerShown = false; - evas_object_smart_callback_call(smartData->self, "input,type,color,request", 0); -} +protected: + enum Button { ShowColorPickerButton, HideColorPickerButton }; + + void clickButton(Button button) + { + switch (button) { + case ShowColorPickerButton: + mouseClick(30, 20); + break; + case HideColorPickerButton: + mouseClick(80, 20); + break; + } + } +}; -TEST_F(EWK2UnitTestBase, ewk_color_picker_color_set) +TEST_F(EWK2ColorPickerTest, ewk_color_picker_color_set) { Ewk_View_Smart_Class* api = ewkViewClass(); api->input_picker_color_request = showColorPicker; @@ -134,24 +151,21 @@ TEST_F(EWK2UnitTestBase, ewk_color_picker_color_set) ewk_view_html_string_load(webView(), colorPickerHTML, 0, 0); waitUntilLoadFinished(); - // 1. Click input element to show color picker. - mouseClick(30, 20); + clickButton(ShowColorPickerButton); bool handled = false; evas_object_smart_callback_add(webView(), "input,type,color,request", onColorPickerDone, &handled); while (!handled) ecore_main_loop_iterate(); - // 6. Click input element to show color picker again. - mouseClick(30, 20); + clickButton(ShowColorPickerButton); handled = false; while (!handled) ecore_main_loop_iterate(); - // 8. Click button to remove input element durlng color picker is shown. api->input_picker_color_dismiss = hideColorPickerByRemovingElement; - mouseClick(80, 20); + clickButton(HideColorPickerButton); handled = false; while (!handled) diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp index 9cd4e616d..f9db0ef26 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp @@ -34,14 +34,28 @@ extern EWK2UnitTestEnvironment* environment; static const char htmlReply[] = "<html><head><title>Foo</title></head><body>Bar</body></html>"; -TEST_F(EWK2UnitTestBase, ewk_context_default_get) +class EWK2ContextTest : public EWK2UnitTestBase { +public: + static void schemeRequestCallback(Ewk_Url_Scheme_Request* request, void* userData) + { + const char* scheme = ewk_url_scheme_request_scheme_get(request); + ASSERT_STREQ("fooscheme", scheme); + const char* url = ewk_url_scheme_request_url_get(request); + ASSERT_STREQ("fooscheme:MyPath", url); + const char* path = ewk_url_scheme_request_path_get(request); + ASSERT_STREQ("MyPath", path); + ASSERT_TRUE(ewk_url_scheme_request_finish(request, htmlReply, strlen(htmlReply), "text/html")); + } +}; + +TEST_F(EWK2ContextTest, ewk_context_default_get) { Ewk_Context* defaultContext = ewk_context_default_get(); ASSERT_TRUE(defaultContext); ASSERT_EQ(defaultContext, ewk_context_default_get()); } -TEST_F(EWK2UnitTestBase, ewk_context_cookie_manager_get) +TEST_F(EWK2ContextTest, ewk_context_cookie_manager_get) { Ewk_Context* context = ewk_view_context_get(webView()); Ewk_Cookie_Manager* cookieManager = ewk_context_cookie_manager_get(context); @@ -49,7 +63,7 @@ TEST_F(EWK2UnitTestBase, ewk_context_cookie_manager_get) ASSERT_EQ(cookieManager, ewk_context_cookie_manager_get(context)); } -TEST_F(EWK2UnitTestBase, ewk_context_database_manager_get) +TEST_F(EWK2ContextTest, ewk_context_database_manager_get) { Ewk_Context* context = ewk_view_context_get(webView()); Ewk_Database_Manager* databaseManager = ewk_context_database_manager_get(context); @@ -57,7 +71,7 @@ TEST_F(EWK2UnitTestBase, ewk_context_database_manager_get) ASSERT_EQ(databaseManager, ewk_context_database_manager_get(context)); } -TEST_F(EWK2UnitTestBase, ewk_context_favicon_database_get) +TEST_F(EWK2ContextTest, ewk_context_favicon_database_get) { Ewk_Context* context = ewk_view_context_get(webView()); Ewk_Favicon_Database* faviconDatabase = ewk_context_favicon_database_get(context); @@ -65,7 +79,7 @@ TEST_F(EWK2UnitTestBase, ewk_context_favicon_database_get) ASSERT_EQ(faviconDatabase, ewk_context_favicon_database_get(context)); } -TEST_F(EWK2UnitTestBase, ewk_context_storage_manager_get) +TEST_F(EWK2ContextTest, ewk_context_storage_manager_get) { Ewk_Context* context = ewk_view_context_get(webView()); Ewk_Storage_Manager* storageManager = ewk_context_storage_manager_get(context); @@ -73,25 +87,14 @@ TEST_F(EWK2UnitTestBase, ewk_context_storage_manager_get) ASSERT_EQ(storageManager, ewk_context_storage_manager_get(context)); } -static void schemeRequestCallback(Ewk_Url_Scheme_Request* request, void* userData) -{ - const char* scheme = ewk_url_scheme_request_scheme_get(request); - ASSERT_STREQ("fooscheme", scheme); - const char* url = ewk_url_scheme_request_url_get(request); - ASSERT_STREQ("fooscheme:MyPath", url); - const char* path = ewk_url_scheme_request_path_get(request); - ASSERT_STREQ("MyPath", path); - ASSERT_TRUE(ewk_url_scheme_request_finish(request, htmlReply, strlen(htmlReply), "text/html")); -} - -TEST_F(EWK2UnitTestBase, ewk_context_url_scheme_register) +TEST_F(EWK2ContextTest, ewk_context_url_scheme_register) { ewk_context_url_scheme_register(ewk_view_context_get(webView()), "fooscheme", schemeRequestCallback, 0); ASSERT_TRUE(loadUrlSync("fooscheme:MyPath")); ASSERT_STREQ("Foo", ewk_view_title_get(webView())); } -TEST_F(EWK2UnitTestBase, ewk_context_cache_model) +TEST_F(EWK2ContextTest, ewk_context_cache_model) { Ewk_Context* context = ewk_view_context_get(webView()); @@ -107,21 +110,21 @@ TEST_F(EWK2UnitTestBase, ewk_context_cache_model) ASSERT_EQ(EWK_CACHE_MODEL_DOCUMENT_VIEWER, ewk_context_cache_model_get(context)); } -TEST_F(EWK2UnitTestBase, ewk_context_new) +TEST_F(EWK2ContextTest, ewk_context_new) { Ewk_Context* context = ewk_context_new(); ASSERT_TRUE(context); ewk_object_unref(context); } -TEST_F(EWK2UnitTestBase, ewk_context_new_with_injected_bundle_path) +TEST_F(EWK2ContextTest, ewk_context_new_with_injected_bundle_path) { Ewk_Context* context = ewk_context_new_with_injected_bundle_path(environment->injectedBundleSample()); ASSERT_TRUE(context); ewk_object_unref(context); } -TEST_F(EWK2UnitTestBase, ewk_context_additional_plugin_path_set) +TEST_F(EWK2ContextTest, ewk_context_additional_plugin_path_set) { Ewk_Context* context = ewk_view_context_get(webView()); diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_menu.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_menu.cpp index 78858af1d..fba0ee790 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_menu.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_menu.cpp @@ -27,83 +27,201 @@ using namespace EWK2UnitTest; extern EWK2UnitTestEnvironment* environment; -static inline void checkBasicContextMenuItem(Ewk_Context_Menu_Item* item, Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled) -{ - ASSERT_TRUE(item); - - EXPECT_EQ(type, ewk_context_menu_item_type_get(item)); - EXPECT_EQ(action, ewk_context_menu_item_action_get(item)); - EXPECT_STREQ(title, ewk_context_menu_item_title_get(item)); +static bool testFinished = false; + +static const Ewk_Context_Menu_Item_Type customItemType = EWK_ACTION_TYPE; +static const Ewk_Context_Menu_Item_Action customItemTag = EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG; +static const char customItemTitle[] = "Custom Item"; +static const bool customItemChecked = false; +static const bool customItemEnabled = true; + +static const char webkitItemTitle1[] = "Open Link"; +static const char webkitItemTitle2[] = "Open Link in New Window"; +static const char webkitItemTitle3[] = "Download Linked File"; +static const char webkitItemTitle4[] = "Copy Link Location"; +static const char webkitItemNewTitle[] = "Copy Link"; + +class EWK2ContextMenuTest : public EWK2UnitTestBase { +public: + static void checkBasicContextMenuItem(Ewk_Context_Menu_Item* item, Ewk_Context_Menu_Item_Type type, Ewk_Context_Menu_Item_Action action, const char* title, Eina_Bool checked, Eina_Bool enabled) + { + ASSERT_TRUE(item); + + EXPECT_EQ(type, ewk_context_menu_item_type_get(item)); + EXPECT_EQ(action, ewk_context_menu_item_action_get(item)); + EXPECT_STREQ(title, ewk_context_menu_item_title_get(item)); EXPECT_EQ(checked, ewk_context_menu_item_checked_get(item)); EXPECT_EQ(enabled, ewk_context_menu_item_enabled_get(item)); -} + } + + static Eina_Bool customItemSelected(Ewk_View_Smart_Data*, Ewk_Context_Menu_Item* item) + { + checkBasicContextMenuItem(item, customItemType, static_cast<Ewk_Context_Menu_Item_Action>(customItemTag), customItemTitle, customItemChecked, customItemEnabled); + + return true; + } + + /** + * This callback receives context menu called upon link with items generated by WebKit2. + * Items have their properties modified, and one of items is selected. + */ + static Eina_Bool testContextMenu(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + const Eina_List* list = ewk_context_menu_items_get(contextMenu); + EXPECT_EQ(4, eina_list_count(list)); + + Ewk_Context_Menu_Item* item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 0)); + checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK, webkitItemTitle1, false, true); + + item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 1)); + checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK_IN_NEW_WINDOW, webkitItemTitle2, false, true); + ewk_context_menu_item_enabled_set(item, false); + EXPECT_FALSE(ewk_context_menu_item_enabled_get(item)); + + item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 2)); + checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_LINK_TO_DISK, webkitItemTitle3, false, true); + ewk_context_menu_item_checked_set(item, true); + EXPECT_TRUE(ewk_context_menu_item_checked_get(item)); + + item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 3)); + checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_COPY_LINK_TO_CLIPBOARD, webkitItemTitle4, false, true); + ewk_context_menu_item_title_set(item, webkitItemNewTitle); + EXPECT_STREQ(webkitItemNewTitle, ewk_context_menu_item_title_get(item)); + + // When context menu is created by WebKit, an item should have parent menu. + EXPECT_EQ(contextMenu, ewk_context_menu_item_parent_menu_get(item)); + + item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 0)); + + EXPECT_TRUE(ewk_context_menu_item_select(contextMenu, item)); + + return true; + } + + /** + * This callback receives context menu called upon link with items generated by WebKit2. + * Received items are removed, then custom item is created and selected. + */ + static Eina_Bool testContextMenuForRemoveAndAppend(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + const Eina_List* list = ewk_context_menu_items_get(contextMenu); + EXPECT_EQ(4, eina_list_count(list)); + + const Eina_List* listIterator; + void* data; + EINA_LIST_FOREACH(list, listIterator, data) + ewk_context_menu_item_remove(contextMenu, static_cast<Ewk_Context_Menu_Item*>(data)); + + list = ewk_context_menu_items_get(contextMenu); + EXPECT_EQ(0, eina_list_count(list)); + + Ewk_Context_Menu_Item* newItem = ewk_context_menu_item_new(customItemType, customItemTag, customItemTitle, customItemChecked, customItemEnabled); + + // When context menu item is created using ewk_context_menu_item_new, it should not have parent menu. + EXPECT_EQ(0, ewk_context_menu_item_parent_menu_get(newItem)); + ewk_context_menu_item_append(contextMenu, newItem); + + // When context menu item is added to menu using ewk_context_menu_item_append, it should have parent menu. + EXPECT_EQ(contextMenu, ewk_context_menu_item_parent_menu_get(newItem)); + + // When non submenu type context menu item was created using ewk_context_menu_item_new, submenu should be 0. + EXPECT_EQ(0, ewk_context_menu_item_submenu_get(newItem)); + + EXPECT_TRUE(ewk_context_menu_item_select(contextMenu, newItem)); + + ewk_context_menu_hide(contextMenu); + + return true; + } -static Eina_Bool showContextMenu(Ewk_View_Smart_Data* smartData, Evas_Coord x, Evas_Coord y, Ewk_Context_Menu* contextMenu) + /** + * This callback receives context menu called upon link with items generated by WebKit2. + * New submenus are created, one of submenu's item is selected. + */ + static Eina_Bool testContextMenuForSubmenu(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + Eina_List* subMenuItemList = 0; + Ewk_Context_Menu_Item* subMenuItem1 = ewk_context_menu_item_new(customItemType, customItemTag, customItemTitle, customItemChecked, customItemEnabled); + Ewk_Context_Menu_Item* subMenuItem2 = ewk_context_menu_item_new(EWK_ACTION_TYPE, static_cast<Ewk_Context_Menu_Item_Action>(customItemTag + 1), "New SubMenu Item 2", false, true); + Ewk_Context_Menu_Item* subMenuItem3 = ewk_context_menu_item_new(EWK_ACTION_TYPE, static_cast<Ewk_Context_Menu_Item_Action>(customItemTag + 2), "New SubMenu Item 3", false, true); + subMenuItemList = eina_list_append(subMenuItemList, subMenuItem1); + subMenuItemList = eina_list_append(subMenuItemList, subMenuItem2); + subMenuItemList = eina_list_append(subMenuItemList, subMenuItem3); + Ewk_Context_Menu* subMenu = ewk_context_menu_new_with_items(subMenuItemList); + + // When context menu is created using ewk_context_menu_new_with_items, items should have parent menu. + EXPECT_EQ(subMenu, ewk_context_menu_item_parent_menu_get(subMenuItem1)); + + Ewk_Context_Menu_Item* newItem = ewk_context_menu_item_new_with_submenu(EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG, "New Custom Item", true, subMenu); + // When context menu item is created using ewk_context_menu_item_new_with_submenu, it should not have parent menu. + EXPECT_EQ(0, ewk_context_menu_item_parent_menu_get(newItem)); + ewk_context_menu_item_append(contextMenu, newItem); + + // Context menu received from ewk_context_menu_item_submenu_get should be the same as one used to create sub menu. + EXPECT_EQ(subMenu, ewk_context_menu_item_submenu_get(newItem)); + + // When context menu item is created using ewk_context_menu_item_new_with_submenu and added using ewk_context_menu_item_append it should have parent menu. + EXPECT_EQ(contextMenu, ewk_context_menu_item_parent_menu_get(newItem)); + + Ewk_Context_Menu* subMenu2 = ewk_context_menu_new(); + Ewk_Context_Menu_Item* newItem2 = ewk_context_menu_item_new_with_submenu(EWK_CONTEXT_MENU_ITEM_BASE_APPLICATION_TAG, "New Custom Item 2", true, subMenu2); + ewk_context_menu_item_append(contextMenu, newItem2); + + EXPECT_TRUE(ewk_context_menu_item_select(ewk_context_menu_item_parent_menu_get(subMenuItem1), subMenuItem1)); + + ewk_context_menu_hide(ewk_context_menu_item_parent_menu_get(subMenuItem1)); + + return true; + } + + static Eina_Bool finishTest(Ewk_View_Smart_Data*) + { + testFinished = true; + + return true; + } + +protected: + void showContextMenu() + { + mouseClick(10, 20, /*Right*/ 3); + } +}; + +TEST_F(EWK2ContextMenuTest, ewk_context_menu_item_select) { - const Eina_List* list = ewk_context_menu_items_get(contextMenu); - EXPECT_EQ(4, eina_list_count(list)); - - Ewk_Context_Menu_Item* item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 0)); - checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_GO_BACK, "Go Back", false, true); - - item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 1)); - checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_GO_FORWARD, "Go Forward", false, true); - ewk_context_menu_item_enabled_set(item, false); - EXPECT_FALSE(ewk_context_menu_item_enabled_get(item)); - - item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 2)); - checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_STOP, "Stop", false, true); - ewk_context_menu_item_checked_set(item, true); - EXPECT_TRUE(ewk_context_menu_item_checked_get(item)); - - item = static_cast<Ewk_Context_Menu_Item*>(eina_list_nth(list, 3)); - checkBasicContextMenuItem(item, EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_RELOAD, "Reload", false, true); - ewk_context_menu_item_title_set(item, "Refresh"); - EXPECT_STREQ("Refresh", ewk_context_menu_item_title_get(item)); - - // Makes new context menu items. - Ewk_Context_Menu_Item* newItem = ewk_context_menu_item_new(EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OTHER, "New Custom Item", false, true); - ewk_context_menu_item_append(contextMenu, newItem); - - Eina_List* subMenuItemList = 0; - Ewk_Context_Menu_Item* subMenuItem1 = ewk_context_menu_item_new(EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OTHER, "New SubMenu Item 1", false, true); - Ewk_Context_Menu_Item* subMenuItem2 = ewk_context_menu_item_new(EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OTHER, "New SubMenu Item 2", false, true); - Ewk_Context_Menu_Item* subMenuItem3 = ewk_context_menu_item_new(EWK_ACTION_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OTHER, "New SubMenu Item 3", false, true); - subMenuItemList = eina_list_append(subMenuItemList, subMenuItem1); - subMenuItemList = eina_list_append(subMenuItemList, subMenuItem2); - subMenuItemList = eina_list_append(subMenuItemList, subMenuItem3); - Ewk_Context_Menu* subMenu = ewk_context_menu_new_with_items(subMenuItemList); - Ewk_Context_Menu_Item* newItem2 = ewk_context_menu_item_new_with_submenu(EWK_SUBMENU_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OTHER, "New Custom Item 2", false, true, subMenu); - ewk_context_menu_item_append(contextMenu, newItem2); - - Ewk_Context_Menu* subMenu2 = ewk_context_menu_new(); - Ewk_Context_Menu_Item* newItem3 = ewk_context_menu_item_new_with_submenu(EWK_SUBMENU_TYPE, EWK_CONTEXT_MENU_ITEM_TAG_OTHER, "New Custom Item 3", false, true, subMenu2); - ewk_context_menu_item_append(contextMenu, newItem3); - - list = ewk_context_menu_items_get(contextMenu); - EXPECT_EQ(7, eina_list_count(list)); - - ewk_context_menu_item_remove(contextMenu, newItem); - ewk_context_menu_item_remove(contextMenu, newItem2); - ewk_context_menu_item_remove(contextMenu, newItem3); - list = ewk_context_menu_items_get(contextMenu); - EXPECT_EQ(4, eina_list_count(list)); - - EXPECT_TRUE(ewk_context_menu_item_select(contextMenu, item)); - - return true; + const char* itemSelectHTML = + "<html>" + "<body><a href=http://www.google.com>Test Link</a></body>" + "</html>"; + + ewkViewClass()->context_menu_show = testContextMenu; + + ewk_view_html_string_load(webView(), itemSelectHTML, "file:///", 0); + ASSERT_TRUE(waitUntilLoadFinished()); + showContextMenu(); + ASSERT_TRUE(waitUntilLoadFinished()); } -TEST_F(EWK2UnitTestBase, ewk_context_menu_item_select) +TEST_F(EWK2ContextMenuTest, ewk_context_menu_custom_items) { const char* itemSelectHTML = "<html>" "<body><a href=http://www.google.com>Test Link</a></body>" - "</body></html>"; + "</html>"; - ewkViewClass()->context_menu_show = showContextMenu; + ewkViewClass()->custom_item_selected = customItemSelected; + ewkViewClass()->context_menu_show = testContextMenuForRemoveAndAppend; + ewkViewClass()->context_menu_hide = finishTest; ewk_view_html_string_load(webView(), itemSelectHTML, "file:///", 0); - mouseClick(20, 30, /*Right*/ 3); ASSERT_TRUE(waitUntilLoadFinished()); + showContextMenu(); + testFinished = false; + ASSERT_TRUE(waitUntilTrue(testFinished)); + + ewkViewClass()->context_menu_show = testContextMenuForSubmenu; + showContextMenu(); + testFinished = false; + ASSERT_TRUE(waitUntilTrue(testFinished)); } diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_cookie_manager.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_cookie_manager.cpp index 960675f79..881ce174b 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_cookie_manager.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_cookie_manager.cpp @@ -40,85 +40,95 @@ static const char INDEX_HTML_STRING[] = " <img src='http://localhost:%u/image.png' width=5 height=5></img>" "</body></html>"; -static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) -{ - if (message->method != SOUP_METHOD_GET) { - soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); - return; +class EWK2CookieManagerTest : public EWK2UnitTestBase { +public: + static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) + { + if (message->method != SOUP_METHOD_GET) { + soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); + return; + } + + soup_message_set_status(message, SOUP_STATUS_OK); + if (!strcmp(path, "/index.html")) { + Eina_Strbuf* buffer = eina_strbuf_new(); + eina_strbuf_append_printf(buffer, INDEX_HTML_STRING, soup_server_get_port(server)); + soup_message_headers_replace(message->response_headers, "Set-Cookie", "foo=bar; Max-Age=60"); + soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, eina_strbuf_string_steal(buffer), eina_strbuf_length_get(buffer)); + eina_strbuf_free(buffer); + } else if (!strcmp(path, "/image.png")) + soup_message_headers_replace(message->response_headers, "Set-Cookie", "baz=qux; Max-Age=60"); + else + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + + soup_message_body_complete(message->response_body); } - soup_message_set_status(message, SOUP_STATUS_OK); - if (!strcmp(path, "/index.html")) { - Eina_Strbuf* buffer = eina_strbuf_new(); - eina_strbuf_append_printf(buffer, INDEX_HTML_STRING, soup_server_get_port(server)); - soup_message_headers_replace(message->response_headers, "Set-Cookie", "foo=bar; Max-Age=60"); - soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, eina_strbuf_string_steal(buffer), eina_strbuf_length_get(buffer)); - eina_strbuf_free(buffer); - } else if (!strcmp(path, "/image.png")) - soup_message_headers_replace(message->response_headers, "Set-Cookie", "baz=qux; Max-Age=60"); - else - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); - - soup_message_body_complete(message->response_body); -} + static void getAcceptPolicyCallback(Ewk_Cookie_Accept_Policy policy, Ewk_Error* error, void* event_info) + { + ASSERT_FALSE(error); + Ewk_Cookie_Accept_Policy* ret = static_cast<Ewk_Cookie_Accept_Policy*>(event_info); + *ret = policy; + ecore_main_loop_quit(); + } -static void getAcceptPolicyCallback(Ewk_Cookie_Accept_Policy policy, Ewk_Error* error, void* event_info) -{ - ASSERT_FALSE(error); - Ewk_Cookie_Accept_Policy* ret = static_cast<Ewk_Cookie_Accept_Policy*>(event_info); - *ret = policy; - ecore_main_loop_quit(); -} + static void getHostnamesWithCookiesCallback(Eina_List* hostnames, Ewk_Error* error, void* event_info) + { + ASSERT_FALSE(error); -static Ewk_Cookie_Accept_Policy getAcceptPolicy(Ewk_Cookie_Manager* manager) -{ - Ewk_Cookie_Accept_Policy policy = EWK_COOKIE_ACCEPT_POLICY_ALWAYS; - ewk_cookie_manager_async_accept_policy_get(manager, getAcceptPolicyCallback, &policy); - ecore_main_loop_begin(); - return policy; -} + Eina_List** ret = static_cast<Eina_List**>(event_info); + Eina_List* l; + void* data; + EINA_LIST_FOREACH(hostnames, l, data) + *ret = eina_list_append(*ret, eina_stringshare_ref(static_cast<char*>(data))); + ecore_main_loop_quit(); + } -static void getHostnamesWithCookiesCallback(Eina_List* hostnames, Ewk_Error* error, void* event_info) -{ - ASSERT_FALSE(error); - - Eina_List** ret = static_cast<Eina_List**>(event_info); - Eina_List* l; - void* data; - EINA_LIST_FOREACH(hostnames, l, data) - *ret = eina_list_append(*ret, eina_stringshare_ref(static_cast<char*>(data))); - ecore_main_loop_quit(); -} + static int compareHostNames(const void* hostName1, const void* hostName2) + { + return strcmp(static_cast<const char*>(hostName1), static_cast<const char*>(hostName2)); + } -static Eina_List* getHostnamesWithCookies(Ewk_Cookie_Manager* manager) -{ - Eina_List* ret = 0; - ewk_cookie_manager_async_hostnames_with_cookies_get(manager, getHostnamesWithCookiesCallback, &ret); - ecore_main_loop_begin(); - return ret; -} + static void onCookiesChanged(void *eventInfo) + { + bool* cookiesChanged = static_cast<bool*>(eventInfo); + *cookiesChanged = true; + } -static void freeHostNames(Eina_List* hostnames) -{ - void* data; - EINA_LIST_FREE(hostnames, data) - eina_stringshare_del(static_cast<char*>(data)); -} +protected: + Ewk_Cookie_Accept_Policy getAcceptPolicy(Ewk_Cookie_Manager* manager) + { + Ewk_Cookie_Accept_Policy policy = EWK_COOKIE_ACCEPT_POLICY_ALWAYS; + ewk_cookie_manager_async_accept_policy_get(manager, getAcceptPolicyCallback, &policy); + ecore_main_loop_begin(); + return policy; + } -static int countHostnamesWithCookies(Ewk_Cookie_Manager* manager) -{ - Eina_List* hostnames = getHostnamesWithCookies(manager); - int count = eina_list_count(hostnames); - freeHostNames(hostnames); - return count; -} + Eina_List* getHostnamesWithCookies(Ewk_Cookie_Manager* manager) + { + Eina_List* ret = 0; + ewk_cookie_manager_async_hostnames_with_cookies_get(manager, getHostnamesWithCookiesCallback, &ret); + ecore_main_loop_begin(); + return ret; + } -static int compareHostNames(const void* hostName1, const void* hostName2) -{ - return strcmp(static_cast<const char*>(hostName1), static_cast<const char*>(hostName2)); -} + void freeHostNames(Eina_List* hostnames) + { + void* data; + EINA_LIST_FREE(hostnames, data) + eina_stringshare_del(static_cast<char*>(data)); + } + + int countHostnamesWithCookies(Ewk_Cookie_Manager* manager) + { + Eina_List* hostnames = getHostnamesWithCookies(manager); + int count = eina_list_count(hostnames); + freeHostNames(hostnames); + return count; + } +}; -TEST_F(EWK2UnitTestBase, ewk_cookie_manager_accept_policy) +TEST_F(EWK2CookieManagerTest, ewk_cookie_manager_accept_policy) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -156,13 +166,7 @@ TEST_F(EWK2UnitTestBase, ewk_cookie_manager_accept_policy) ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); } -void onCookiesChanged(void *eventInfo) -{ - bool* cookiesChanged = static_cast<bool*>(eventInfo); - *cookiesChanged = true; -} - -TEST_F(EWK2UnitTestBase, ewk_cookie_manager_changes_watch) +TEST_F(EWK2CookieManagerTest, ewk_cookie_manager_changes_watch) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -225,7 +229,7 @@ TEST_F(EWK2UnitTestBase, ewk_cookie_manager_changes_watch) unlink(textStorage2); } -TEST_F(EWK2UnitTestBase, ewk_cookie_manager_cookies_delete) +TEST_F(EWK2CookieManagerTest, ewk_cookie_manager_cookies_delete) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -261,7 +265,7 @@ TEST_F(EWK2UnitTestBase, ewk_cookie_manager_cookies_delete) ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); } -TEST_F(EWK2UnitTestBase, DISABLED_ewk_cookie_manager_permanent_storage) +TEST_F(EWK2CookieManagerTest, DISABLED_ewk_cookie_manager_permanent_storage) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -308,4 +312,3 @@ TEST_F(EWK2UnitTestBase, DISABLED_ewk_cookie_manager_permanent_storage) unlink(textStorage); unlink(sqliteStorage); } - diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_database_manager.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_database_manager.cpp index 8860edf42..513d7b3c3 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_database_manager.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_database_manager.cpp @@ -29,61 +29,64 @@ using namespace EWK2UnitTest; -struct OriginData { - Eina_List* originList; - Ewk_Database_Manager* manager; - bool didReceiveOriginsCallback; - bool isSynchronized; - unsigned timeoutSeconds; - - OriginData() - : originList(0) - , manager(0) - , didReceiveOriginsCallback(false) - , isSynchronized(false) - , timeoutSeconds(10) - { } -}; - -static void getDatabaseOriginsCallback(Eina_List* origins, Ewk_Error* error, void* userData) -{ - ASSERT_FALSE(error); - - OriginData* originData = static_cast<OriginData*>(userData); - originData->didReceiveOriginsCallback = true; - - Eina_List* l; - void* data; - EINA_LIST_FOREACH(origins, l, data) { - originData->originList = eina_list_append(originData->originList, data); - Ewk_Security_Origin* origin = static_cast<Ewk_Security_Origin*>(data); - if (!strcmp(ewk_security_origin_protocol_get(origin), "http") - && !strcmp(ewk_security_origin_host_get(origin), "www.databasetest.com") - && !ewk_security_origin_port_get(origin)) { - originData->isSynchronized = true; - ecore_main_loop_quit(); +class EWK2DatabaseManagerTest : public EWK2UnitTestBase { +public: + struct OriginData { + Eina_List* originList; + Ewk_Database_Manager* manager; + bool didReceiveOriginsCallback; + bool isSynchronized; + unsigned timeoutSeconds; + + OriginData() + : originList(0) + , manager(0) + , didReceiveOriginsCallback(false) + , isSynchronized(false) + , timeoutSeconds(10) + { } + }; + + static void databaseOriginsCallback(Eina_List* origins, Ewk_Error* error, void* userData) + { + ASSERT_FALSE(error); + + OriginData* originData = static_cast<OriginData*>(userData); + originData->didReceiveOriginsCallback = true; + + Eina_List* l; + void* data; + EINA_LIST_FOREACH(origins, l, data) { + originData->originList = eina_list_append(originData->originList, data); + Ewk_Security_Origin* origin = static_cast<Ewk_Security_Origin*>(data); + if (!strcmp(ewk_security_origin_protocol_get(origin), "http") + && !strcmp(ewk_security_origin_host_get(origin), "www.databasetest.com") + && !ewk_security_origin_port_get(origin)) { + originData->isSynchronized = true; + ecore_main_loop_quit(); + } } } -} -static bool timerCallback(void* userData) -{ - OriginData* originData = static_cast<OriginData*>(userData); + static Eina_Bool timerCallback(void* userData) + { + OriginData* originData = static_cast<OriginData*>(userData); - if (originData->isSynchronized || !--(originData->timeoutSeconds)) { - ecore_main_loop_quit(); - return ECORE_CALLBACK_CANCEL; - } + if (originData->isSynchronized || !--(originData->timeoutSeconds)) { + ecore_main_loop_quit(); + return ECORE_CALLBACK_CANCEL; + } - if (originData->didReceiveOriginsCallback) { - originData->didReceiveOriginsCallback = false; - ewk_database_manager_origins_get(originData->manager, getDatabaseOriginsCallback, originData); - } + if (originData->didReceiveOriginsCallback) { + originData->didReceiveOriginsCallback = false; + ewk_database_manager_origins_get(originData->manager, databaseOriginsCallback, originData); + } - return ECORE_CALLBACK_RENEW; -} + return ECORE_CALLBACK_RENEW; + } +}; -TEST_F(EWK2UnitTestBase, ewk_database_manager_origins_get) +TEST_F(EWK2DatabaseManagerTest, ewk_database_manager_origins_get) { Evas_Object* view = webView(); const char* databaseHTML = @@ -99,8 +102,8 @@ TEST_F(EWK2UnitTestBase, ewk_database_manager_origins_get) OriginData originData; originData.manager = ewk_context_database_manager_get(ewk_view_context_get(view)); - ASSERT_TRUE(ewk_database_manager_origins_get(originData.manager, getDatabaseOriginsCallback, &originData)); - Ecore_Timer* database_timer = ecore_timer_add(1, reinterpret_cast<Ecore_Task_Cb>(timerCallback), &originData); + ASSERT_TRUE(ewk_database_manager_origins_get(originData.manager, databaseOriginsCallback, &originData)); + Ecore_Timer* database_timer = ecore_timer_add(1, timerCallback, &originData); ecore_main_loop_begin(); if (database_timer) diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_download_job.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_download_job.cpp index f0e7d1b61..4303bed00 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_download_job.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_download_job.cpp @@ -41,112 +41,115 @@ extern EWK2UnitTestEnvironment* environment; static const char serverSuggestedFilename[] = "webkit-downloaded-file"; static const char testFilePath[] = "/test.pdf"; -struct DownloadTestData { - const char* fileUrl; - const char* destinationPath; -}; - -static inline bool fileExists(const char* path) -{ - struct stat buf; - return !stat(path, &buf); -} - -static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, void*) -{ - if (message->method != SOUP_METHOD_GET) { - soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); - return; +class EWK2DownloadJobTest : public EWK2UnitTestBase { +public: + struct DownloadTestData { + const char* fileUrl; + const char* destinationPath; + }; + + static bool fileExists(const char* path) + { + struct stat buf; + return !stat(path, &buf); } - Eina_Strbuf* filePath = eina_strbuf_new(); - eina_strbuf_append(filePath, TEST_RESOURCES_DIR); - eina_strbuf_append(filePath, path); - - Eina_File* f = eina_file_open(eina_strbuf_string_get(filePath), false); - eina_strbuf_free(filePath); - if (!f) { - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, void*) + { + if (message->method != SOUP_METHOD_GET) { + soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); + return; + } + + Eina_Strbuf* filePath = eina_strbuf_new(); + eina_strbuf_append(filePath, TEST_RESOURCES_DIR); + eina_strbuf_append(filePath, path); + + Eina_File* f = eina_file_open(eina_strbuf_string_get(filePath), false); + eina_strbuf_free(filePath); + if (!f) { + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + soup_message_body_complete(message->response_body); + return; + } + + size_t fileSize = eina_file_size_get(f); + + void* contents = eina_file_map_all(f, EINA_FILE_POPULATE); + if (!contents) { + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + soup_message_body_complete(message->response_body); + return; + } + + soup_message_set_status(message, SOUP_STATUS_OK); + + Eina_Strbuf* contentDisposition = eina_strbuf_new(); + eina_strbuf_append_printf(contentDisposition, "filename=%s", serverSuggestedFilename); + soup_message_headers_append(message->response_headers, "Content-Disposition", eina_strbuf_string_get(contentDisposition)); + eina_strbuf_free(contentDisposition); + + soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, fileSize); soup_message_body_complete(message->response_body); - return; - } - - size_t fileSize = eina_file_size_get(f); - void* contents = eina_file_map_all(f, EINA_FILE_POPULATE); - if (!contents) { - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); - soup_message_body_complete(message->response_body); - return; + eina_file_map_free(f, contents); + eina_file_close(f); } - soup_message_set_status(message, SOUP_STATUS_OK); - - Eina_Strbuf* contentDisposition = eina_strbuf_new(); - eina_strbuf_append_printf(contentDisposition, "filename=%s", serverSuggestedFilename); - soup_message_headers_append(message->response_headers, "Content-Disposition", eina_strbuf_string_get(contentDisposition)); - eina_strbuf_free(contentDisposition); - - soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, fileSize); - soup_message_body_complete(message->response_body); - - eina_file_map_free(f, contents); - eina_file_close(f); -} - -static void on_download_requested(void* userData, Evas_Object* webview, void* eventInfo) -{ - DownloadTestData* testData = static_cast<DownloadTestData*>(userData); - Ewk_Download_Job* download = static_cast<Ewk_Download_Job*>(eventInfo); - ASSERT_EQ(EWK_DOWNLOAD_JOB_STATE_NOT_STARTED, ewk_download_job_state_get(download)); - ASSERT_EQ(0, ewk_download_job_estimated_progress_get(download)); - ASSERT_EQ(0, ewk_download_job_elapsed_time_get(download)); + static void on_download_requested(void* userData, Evas_Object* webview, void* eventInfo) + { + DownloadTestData* testData = static_cast<DownloadTestData*>(userData); + Ewk_Download_Job* download = static_cast<Ewk_Download_Job*>(eventInfo); + ASSERT_EQ(EWK_DOWNLOAD_JOB_STATE_NOT_STARTED, ewk_download_job_state_get(download)); + ASSERT_EQ(0, ewk_download_job_estimated_progress_get(download)); + ASSERT_EQ(0, ewk_download_job_elapsed_time_get(download)); - Ewk_Url_Request* request = ewk_download_job_request_get(download); - ASSERT_TRUE(request); - EXPECT_STREQ(testData->fileUrl, ewk_url_request_url_get(request)); + Ewk_Url_Request* request = ewk_download_job_request_get(download); + ASSERT_TRUE(request); + EXPECT_STREQ(testData->fileUrl, ewk_url_request_url_get(request)); - Ewk_Url_Response* response = ewk_download_job_response_get(download); - ASSERT_TRUE(response); - EXPECT_STREQ("application/pdf", ewk_url_response_mime_type_get(response)); + Ewk_Url_Response* response = ewk_download_job_response_get(download); + ASSERT_TRUE(response); + EXPECT_STREQ("application/pdf", ewk_url_response_mime_type_get(response)); - EXPECT_STREQ(serverSuggestedFilename, ewk_download_job_suggested_filename_get(download)); + EXPECT_STREQ(serverSuggestedFilename, ewk_download_job_suggested_filename_get(download)); - ASSERT_FALSE(fileExists(testData->destinationPath)); - ewk_download_job_destination_set(download, testData->destinationPath); - EXPECT_STREQ(testData->destinationPath, ewk_download_job_destination_get(download)); -} + ASSERT_FALSE(fileExists(testData->destinationPath)); + ewk_download_job_destination_set(download, testData->destinationPath); + EXPECT_STREQ(testData->destinationPath, ewk_download_job_destination_get(download)); + } -static void on_download_cancelled(void* userData, Evas_Object* webview, void* eventInfo) -{ - fprintf(stderr, "Download was cancelled.\n"); - ecore_main_loop_quit(); - FAIL(); -} + static void on_download_cancelled(void* userData, Evas_Object* webview, void* eventInfo) + { + fprintf(stderr, "Download was cancelled.\n"); + ecore_main_loop_quit(); + FAIL(); + } -static void on_download_failed(void* userData, Evas_Object* webview, void* eventInfo) -{ - Ewk_Download_Job_Error* downloadError = static_cast<Ewk_Download_Job_Error*>(eventInfo); - fprintf(stderr, "Download error: %s\n", ewk_error_description_get(downloadError->error)); - ecore_main_loop_quit(); - FAIL(); -} + static void on_download_failed(void* userData, Evas_Object* webview, void* eventInfo) + { + Ewk_Download_Job_Error* downloadError = static_cast<Ewk_Download_Job_Error*>(eventInfo); + fprintf(stderr, "Download error: %s\n", ewk_error_description_get(downloadError->error)); + ecore_main_loop_quit(); + FAIL(); + } -static void on_download_finished(void* userData, Evas_Object* webview, void* eventInfo) -{ - DownloadTestData* testData = static_cast<DownloadTestData*>(userData); - Ewk_Download_Job* download = static_cast<Ewk_Download_Job*>(eventInfo); + static void on_download_finished(void* userData, Evas_Object* webview, void* eventInfo) + { + DownloadTestData* testData = static_cast<DownloadTestData*>(userData); + Ewk_Download_Job* download = static_cast<Ewk_Download_Job*>(eventInfo); - ASSERT_EQ(1, ewk_download_job_estimated_progress_get(download)); - ASSERT_EQ(EWK_DOWNLOAD_JOB_STATE_FINISHED, ewk_download_job_state_get(download)); - ASSERT_GT(ewk_download_job_elapsed_time_get(download), 0); + ASSERT_EQ(1, ewk_download_job_estimated_progress_get(download)); + ASSERT_EQ(EWK_DOWNLOAD_JOB_STATE_FINISHED, ewk_download_job_state_get(download)); + ASSERT_GT(ewk_download_job_elapsed_time_get(download), 0); - ASSERT_TRUE(fileExists(testData->destinationPath)); + ASSERT_TRUE(fileExists(testData->destinationPath)); - ecore_main_loop_quit(); -} + ecore_main_loop_quit(); + } +}; -TEST_F(EWK2UnitTestBase, ewk_download) +TEST_F(EWK2DownloadJobTest, ewk_download) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_eina_shared_string.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_eina_shared_string.cpp index 258249ccc..babc07e67 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_eina_shared_string.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_eina_shared_string.cpp @@ -39,39 +39,42 @@ extern EWK2UnitTestEnvironment* environment; #define anotherTestString "I'm another test string!" #define testUrl "file:///path/somewhere" -static inline void checkString(const WKEinaSharedString& string, const char* pattern) -{ - ASSERT_EQ(string.isNull(), pattern ? false : true); - ASSERT_EQ(string.length(), pattern ? strlen(pattern) : 0); // Compare length. - ASSERT_EQ(string, pattern); // Compare values. Check '==' operator with WKEinaSharedString and plain string. - ASSERT_STREQ(string, pattern); // Compare values. Check 'const char*' operator. -} - -TEST_F(EWK2UnitTestBase, constructEmpty) +class EWK2EinaSharedStringTest : public EWK2UnitTestBase { +protected: + void checkString(const WKEinaSharedString& string, const char* pattern) + { + ASSERT_EQ(string.isNull(), pattern ? false : true); + ASSERT_EQ(string.length(), pattern ? strlen(pattern) : 0); // Compare length. + ASSERT_EQ(string, pattern); // Compare values. Check '==' operator with WKEinaSharedString and plain string. + ASSERT_STREQ(string, pattern); // Compare values. Check 'const char*' operator. + } +}; + +TEST_F(EWK2EinaSharedStringTest, constructEmpty) { WKEinaSharedString emptyString; checkString(emptyString, 0); } -TEST_F(EWK2UnitTestBase, constructFromPlainString) +TEST_F(EWK2EinaSharedStringTest, constructFromPlainString) { WKEinaSharedString emptyString(testString); checkString(emptyString, testString); } -TEST_F(EWK2UnitTestBase, constructFromWKString) +TEST_F(EWK2EinaSharedStringTest, constructFromWKString) { WKEinaSharedString string(AdoptWK, WKStringCreateWithUTF8CString(testString)); checkString(string, testString); } -TEST_F(EWK2UnitTestBase, constructFromWKURL) +TEST_F(EWK2EinaSharedStringTest, constructFromWKURL) { WKEinaSharedString string(AdoptWK, WKURLCreateWithUTF8CString(testUrl)); checkString(string, testUrl); } -TEST_F(EWK2UnitTestBase, constructFromEinaStringShare) +TEST_F(EWK2EinaSharedStringTest, constructFromEinaStringShare) { WKEinaSharedString string(WKEinaSharedString::adopt(eina_stringshare_add(testString))); checkString(string, testString); @@ -83,7 +86,7 @@ TEST_F(EWK2UnitTestBase, constructFromEinaStringShare) checkString(string, anotherTestString); } -TEST_F(EWK2UnitTestBase, costructCopy) +TEST_F(EWK2EinaSharedStringTest, costructCopy) { WKEinaSharedString string(testString); WKEinaSharedString copyString(string); @@ -92,7 +95,7 @@ TEST_F(EWK2UnitTestBase, costructCopy) ASSERT_EQ(string, copyString); // Check '==' operator with two instances of WKEinaSharedString. } -TEST_F(EWK2UnitTestBase, comparisonOperators) +TEST_F(EWK2EinaSharedStringTest, comparisonOperators) { WKEinaSharedString string(testString); WKEinaSharedString sameString(testString); @@ -109,7 +112,7 @@ TEST_F(EWK2UnitTestBase, comparisonOperators) ASSERT_EQ(string, string); // Self-comparison. } -TEST_F(EWK2UnitTestBase, assignmentOperators) +TEST_F(EWK2EinaSharedStringTest, assignmentOperators) { WKEinaSharedString string; @@ -124,3 +127,17 @@ TEST_F(EWK2UnitTestBase, assignmentOperators) string = string; // Check that self-assignment does not break WKEinaSharedString internal data. checkString(string, anotherTestString); } + +TEST_F(EWK2EinaSharedStringTest, leakString) +{ + WKEinaSharedString string; + + string = testString; + checkString(string, testString); + + Eina_Stringshare* leakedString = string.leakString(); + checkString(string, 0); + ASSERT_STREQ(leakedString, testString); + + eina_stringshare_del(leakedString); +} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_favicon_database.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_favicon_database.cpp index 0ff1df077..d0d6cb1b0 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_favicon_database.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_favicon_database.cpp @@ -35,113 +35,68 @@ using namespace EWK2UnitTest; extern EWK2UnitTestEnvironment* environment; -static void serverCallback(SoupServer* httpServer, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) -{ - if (message->method != SOUP_METHOD_GET) { - soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); +class EWK2FaviconDatabaseTest : public EWK2UnitTestBase { +public: + struct IconRequestData { + Evas_Object* view; + Evas_Object* icon; + }; + + static void serverCallback(SoupServer* httpServer, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) + { + if (message->method != SOUP_METHOD_GET) { + soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); return; - } - - if (!strcmp(path, "/favicon.ico")) { - CString faviconPath = environment->pathForResource("blank.ico"); - Eina_File* f = eina_file_open(faviconPath.data(), false); - if (!f) { - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); - soup_message_body_complete(message->response_body); - return; } - size_t fileSize = eina_file_size_get(f); - - void* contents = eina_file_map_all(f, EINA_FILE_POPULATE); - if (!contents) { - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + if (!strcmp(path, "/favicon.ico")) { + CString faviconPath = environment->pathForResource("blank.ico"); + Eina_File* f = eina_file_open(faviconPath.data(), false); + if (!f) { + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + soup_message_body_complete(message->response_body); + return; + } + + size_t fileSize = eina_file_size_get(f); + + void* contents = eina_file_map_all(f, EINA_FILE_POPULATE); + if (!contents) { + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); + soup_message_body_complete(message->response_body); + return; + } + + soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, fileSize); + soup_message_set_status(message, SOUP_STATUS_OK); soup_message_body_complete(message->response_body); + + eina_file_map_free(f, contents); + eina_file_close(f); return; } - soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, fileSize); + const char contents[] = "<html><body>favicon test</body></html>"; soup_message_set_status(message, SOUP_STATUS_OK); + soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, strlen(contents)); soup_message_body_complete(message->response_body); - - eina_file_map_free(f, contents); - eina_file_close(f); - return; } - const char contents[] = "<html><body>favicon test</body></html>"; - soup_message_set_status(message, SOUP_STATUS_OK); - soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, contents, strlen(contents)); - soup_message_body_complete(message->response_body); -} + static void requestFaviconData(void* userData, Evas_Object*, void* eventInfo) + { + IconRequestData* data = static_cast<IconRequestData*>(userData); -static void onIconChanged(void* userData, Evas_Object*, void* eventInfo) -{ - bool* iconChanged = static_cast<bool*>(userData); - *iconChanged = true; -} + // Check the API retrieving a valid favicon from icon database. + Ewk_Context* context = ewk_view_context_get(data->view); + Ewk_Favicon_Database* faviconDatabase = ewk_context_favicon_database_get(context); + ASSERT_TRUE(faviconDatabase); -TEST_F(EWK2UnitTestBase, ewk_favicon_database_url_get) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - // Set favicon database path and enable functionality. - Ewk_Context* context = ewk_view_context_get(webView()); - ewk_context_favicon_database_directory_set(context, 0); - - bool iconChanged = false; - evas_object_smart_callback_add(webView(), "icon,changed", onIconChanged, &iconChanged); - - // We need to load the page first to ensure the icon data will be - // in the database in case there's an associated favicon. - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/").data())); - - while (!iconChanged) - ecore_main_loop_iterate(); - - ASSERT_TRUE(iconChanged); - evas_object_smart_callback_del(webView(), "icon,changed", onIconChanged); - - // Check the API retrieving a favicon URL. - Ewk_Favicon_Database* faviconDatabase = ewk_context_favicon_database_get(context); - ASSERT_TRUE(faviconDatabase); - - CString expectedFaviconURL = httpServer->getURLForPath("/favicon.ico"); - WKEinaSharedString iconURL = ewk_favicon_database_icon_url_get(faviconDatabase, ewk_view_url_get(webView())); - EXPECT_STREQ(expectedFaviconURL.data(), iconURL); - - const char* viewIconURL = ewk_view_icon_url_get(webView()); - EXPECT_STREQ(expectedFaviconURL.data(), viewIconURL); -} - -static void onIconDataReady(const char* page_url, Evas_Object* icon, void* event_info) -{ - Evas_Object** returnIcon = static_cast<Evas_Object**>(event_info); - if (icon) - evas_object_ref(icon); - *returnIcon = icon; -} - -struct IconRequestData { - Evas_Object* view; - Evas_Object* icon; + Evas* evas = evas_object_evas_get(data->view); + data->icon = ewk_favicon_database_icon_get(faviconDatabase, ewk_view_url_get(data->view), evas); + } }; -static void requestFaviconData(void* userData, Evas_Object*, void* eventInfo) -{ - IconRequestData* data = static_cast<IconRequestData*>(userData); - - // Check the API retrieving a valid favicon. - Ewk_Context* context = ewk_view_context_get(data->view); - Ewk_Favicon_Database* faviconDatabase = ewk_context_favicon_database_get(context); - ASSERT_TRUE(faviconDatabase); - - Evas* evas = evas_object_evas_get(data->view); - ASSERT_TRUE(ewk_favicon_database_async_icon_get(faviconDatabase, ewk_view_url_get(data->view), evas, onIconDataReady, &data->icon)); -} - -TEST_F(EWK2UnitTestBase, ewk_favicon_database_async_icon_get) +TEST_F(EWK2FaviconDatabaseTest, ewk_favicon_database_async_icon_get) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallback); @@ -151,7 +106,7 @@ TEST_F(EWK2UnitTestBase, ewk_favicon_database_async_icon_get) ewk_context_favicon_database_directory_set(context, 0); IconRequestData data = { webView(), 0 }; - evas_object_smart_callback_add(webView(), "icon,changed", requestFaviconData, &data); + evas_object_smart_callback_add(webView(), "favicon,changed", requestFaviconData, &data); // We need to load the page first to ensure the icon data will be // in the database in case there's an associated favicon. @@ -161,13 +116,20 @@ TEST_F(EWK2UnitTestBase, ewk_favicon_database_async_icon_get) ecore_main_loop_iterate(); ASSERT_TRUE(data.icon); - evas_object_smart_callback_del(webView(), "icon,changed", requestFaviconData); + evas_object_smart_callback_del(webView(), "favicon,changed", requestFaviconData); // It is a 16x16 favicon. int width, height; evas_object_image_size_get(data.icon, &width, &height); EXPECT_EQ(16, width); EXPECT_EQ(16, height); - evas_object_unref(data.icon); + + // Test API to request favicon from the view + Evas_Object* favicon = ewk_view_favicon_get(webView()); + ASSERT_TRUE(favicon); + evas_object_image_size_get(favicon, &width, &height); + EXPECT_EQ(16, width); + EXPECT_EQ(16, height); + evas_object_unref(favicon); } diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_file_chooser_request.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_file_chooser_request.cpp index a66520ba3..d79983679 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_file_chooser_request.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_file_chooser_request.cpp @@ -32,41 +32,49 @@ using namespace EWK2UnitTest; extern EWK2UnitTestEnvironment* environment; -static void onFileChooserRequest(void* userData, Evas_Object*, void* eventInfo) -{ - Ewk_File_Chooser_Request** returnRequest = static_cast<Ewk_File_Chooser_Request**>(userData); - ASSERT_TRUE(returnRequest); - Ewk_File_Chooser_Request* request = static_cast<Ewk_File_Chooser_Request*>(eventInfo); - ASSERT_TRUE(request); - - // Ref the request to process asynchronously. - *returnRequest = ewk_object_ref(request); -} +class EWK2FileChooserRequestTest : public EWK2UnitTestBase { +public: + static void onFileChooserRequest(void* userData, Evas_Object*, void* eventInfo) + { + Ewk_File_Chooser_Request** returnRequest = static_cast<Ewk_File_Chooser_Request**>(userData); + ASSERT_TRUE(returnRequest); + Ewk_File_Chooser_Request* request = static_cast<Ewk_File_Chooser_Request*>(eventInfo); + ASSERT_TRUE(request); + + // Ref the request to process asynchronously. + *returnRequest = ewk_object_ref(request); + } -static int compareStrings(const void* string1, const void* string2) -{ - ASSERT(string1); - ASSERT(string2); + static int compareStrings(const void* string1, const void* string2) + { + ASSERT(string1); + ASSERT(string2); - return strcmp(static_cast<const char*>(string1), static_cast<const char*>(string2)); -} + return strcmp(static_cast<const char*>(string1), static_cast<const char*>(string2)); + } -static void freeStringList(Eina_List** list) -{ - void* data; - EINA_LIST_FREE(*list, data) { +protected: + void freeStringList(Eina_List** list) + { + void* data; + EINA_LIST_FREE(*list, data) { eina_stringshare_del(static_cast<char*>(data)); + } } -} -TEST_F(EWK2UnitTestBase, ewk_file_chooser_request_files_choose) + void clickFileInput() + { + mouseClick(15, 15); + } +}; + +TEST_F(EWK2FileChooserRequestTest, ewk_file_chooser_request_files_choose) { Ewk_File_Chooser_Request* request = 0; evas_object_smart_callback_add(webView(), "file,chooser,request", onFileChooserRequest, &request); ASSERT_TRUE(loadUrlSync(environment->urlForResource("file_chooser.html").data())); - // Click on the file input. - mouseClick(15, 15); + clickFileInput(); // Wait for the file chooser request. while (!request) @@ -98,14 +106,13 @@ TEST_F(EWK2UnitTestBase, ewk_file_chooser_request_files_choose) EXPECT_TRUE(waitUntilTitleChangedTo("file1.png|file2.png")); } -TEST_F(EWK2UnitTestBase, ewk_file_chooser_request_file_choose) +TEST_F(EWK2FileChooserRequestTest, ewk_file_chooser_request_file_choose) { Ewk_File_Chooser_Request* request = 0; evas_object_smart_callback_add(webView(), "file,chooser,request", onFileChooserRequest, &request); ASSERT_TRUE(loadUrlSync(environment->urlForResource("file_chooser.html").data())); - // Click on the file input. - mouseClick(15, 15); + clickFileInput(); // Wait for the file chooser request. while (!request) @@ -124,14 +131,13 @@ TEST_F(EWK2UnitTestBase, ewk_file_chooser_request_file_choose) EXPECT_TRUE(waitUntilTitleChangedTo("file3.png")); } -TEST_F(EWK2UnitTestBase, ewk_file_chooser_request_file_cancel) +TEST_F(EWK2FileChooserRequestTest, ewk_file_chooser_request_file_cancel) { Ewk_File_Chooser_Request* request = 0; evas_object_smart_callback_add(webView(), "file,chooser,request", onFileChooserRequest, &request); ASSERT_TRUE(loadUrlSync(environment->urlForResource("file_chooser.html").data())); - // Click on the file input. - mouseClick(15, 15); + clickFileInput(); // Wait for the file chooser request. while (!request) @@ -151,8 +157,8 @@ TEST_F(EWK2UnitTestBase, ewk_file_chooser_request_file_cancel) // Default behavior is to cancel if the client does not act on the request. request = 0; evas_object_smart_callback_add(webView(), "file,chooser,request", onFileChooserRequest, &request); - // Click on the file input. - mouseClick(15, 15); + + clickFileInput(); // Wait for the file chooser request. while (!request) diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_intents.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_intents.cpp deleted file mode 100644 index d7d99eaf4..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_intents.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" -#include "UnitTestUtils/EWK2UnitTestServer.h" - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -static void onIntentServiceRegistration(void* userData, Evas_Object*, void* eventInfo) -{ - bool* intentRegistered = static_cast<bool*>(userData); - ASSERT_FALSE(*intentRegistered); - *intentRegistered = true; - - Ewk_Intent_Service* service = static_cast<Ewk_Intent_Service*>(eventInfo); - ASSERT_TRUE(service); - EXPECT_STREQ("action", ewk_intent_service_action_get(service)); - EXPECT_STREQ("type", ewk_intent_service_type_get(service)); - EXPECT_STREQ("Title", ewk_intent_service_title_get(service)); - EXPECT_STREQ("http://example.com/service", ewk_intent_service_href_get(service)); - EXPECT_STREQ("inline", ewk_intent_service_disposition_get(service)); -} - -TEST_F(EWK2UnitTestBase, ewk_intent_service_registration) -{ - bool intentRegistered = false; - evas_object_smart_callback_add(webView(), "intent,service,register", onIntentServiceRegistration, &intentRegistered); - ASSERT_TRUE(loadUrlSync(environment->urlForResource("intent-service.html").data())); - evas_object_smart_callback_del(webView(), "intent,service,register", onIntentServiceRegistration); - ASSERT_TRUE(intentRegistered); -} - -int stringSortCb(const void* d1, const void* d2) -{ - return strcmp(static_cast<const char*>(d1), static_cast<const char*>(d2)); -} - -static void onIntentReceived(void* userData, Evas_Object*, void* eventInfo) -{ - unsigned* intentReceivedCount = static_cast<unsigned*>(userData); - ASSERT_GE(*intentReceivedCount, 0); - ASSERT_LE(*intentReceivedCount, 1); - ++(*intentReceivedCount); - - Ewk_Intent* intent = static_cast<Ewk_Intent*>(eventInfo); - ASSERT_TRUE(intent); - - if (*intentReceivedCount == 1) { - // First intent. - EXPECT_STREQ("action1", ewk_intent_action_get(intent)); - EXPECT_STREQ("mime/type1", ewk_intent_type_get(intent)); - EXPECT_STREQ("http://service1.com/", ewk_intent_service_get(intent)); - EXPECT_STREQ("value1", ewk_intent_extra_get(intent, "key1")); - EXPECT_STREQ("value2", ewk_intent_extra_get(intent, "key2")); - } else { - // Second intent. - EXPECT_STREQ("action2", ewk_intent_action_get(intent)); - EXPECT_STREQ("mime/type2", ewk_intent_type_get(intent)); - Eina_List* suggestions = ewk_intent_suggestions_get(intent); - ASSERT_TRUE(suggestions); - ASSERT_EQ(2, eina_list_count(suggestions)); - // We need to sort the suggestions since Intent is using a HashSet internally. - suggestions = eina_list_sort(suggestions, 2, stringSortCb); - EXPECT_STREQ("http://service1.com/", static_cast<const char*>(eina_list_nth(suggestions, 0))); - EXPECT_STREQ("http://service2.com/", static_cast<const char*>(eina_list_nth(suggestions, 1))); - - void* listData = 0; - EINA_LIST_FREE(suggestions, listData) - eina_stringshare_del(static_cast<const char*>(listData)); - } -} - -TEST_F(EWK2UnitTestBase, ewk_intent_request) -{ - unsigned intentReceivedCount = 0; - evas_object_smart_callback_add(webView(), "intent,request,new", onIntentReceived, &intentReceivedCount); - ASSERT_TRUE(loadUrlSync(environment->urlForResource("intent-request.html").data())); - - // A user gesture is required for the intent to start. - mouseClick(5, 5); - while (intentReceivedCount != 1) - ecore_main_loop_iterate(); - ASSERT_EQ(1, intentReceivedCount); - - // Generate a second intent request. - mouseClick(5, 5); - while (intentReceivedCount != 2) - ecore_main_loop_iterate(); - ASSERT_EQ(2, intentReceivedCount); - evas_object_smart_callback_del(webView(), "intent,request,new", onIntentReceived); -} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_page_group.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_page_group.cpp new file mode 100644 index 000000000..b5ca59771 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_page_group.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include "UnitTestUtils/EWK2UnitTestBase.h" + +using namespace EWK2UnitTest; + +extern EWK2UnitTestEnvironment* environment; + +static const char htmlString[] = "<html><head><title>Foo</title></head><body style='background-color: red'><script>document.title=window.getComputedStyle(document.body, null).getPropertyValue('background-color')</script>HELLO</body></html>"; +static const char userStyleSheet[] = "body { background-color: green !important; }"; +static const char greenInRGB[] = "rgb(0, 128, 0)"; +static const char redInRGB[] = "rgb(255, 0, 0)"; + +TEST_F(EWK2UnitTestBase, ewk_page_group) +{ + Evas_Smart* smart = evas_smart_class_new(&(ewkViewClass()->sc)); + Ewk_Page_Group* pageGroup = ewk_page_group_create("test"); + ASSERT_TRUE(pageGroup); + + Evas_Object* newWebView = ewk_view_smart_add(canvas(), smart, ewk_context_default_get(), pageGroup); + setWebView(newWebView); + + ASSERT_EQ(pageGroup, ewk_view_page_group_get(newWebView)); + ewk_object_unref(pageGroup); +} + +TEST_F(EWK2UnitTestBase, ewk_page_group_user_style_sheet_add_before_creating_view) +{ + Evas_Smart* smart = evas_smart_class_new(&(ewkViewClass()->sc)); + Ewk_Page_Group* pageGroup = ewk_page_group_create("test"); + ASSERT_TRUE(pageGroup); + + // Add a user style sheet to the page group before creating a view. + ewk_page_group_user_style_sheet_add(pageGroup, userStyleSheet, 0, 0, 0, true); + + // Create a new web view with this page group. + Evas_Object* newWebView = ewk_view_smart_add(canvas(), smart, ewk_context_default_get(), pageGroup); + setWebView(newWebView); + + ewk_object_unref(pageGroup); + ewk_view_theme_set(webView(), environment->defaultTheme()); + evas_object_resize(webView(), environment->defaultWidth(), environment->defaultHeight()); + evas_object_show(webView()); + evas_object_focus_set(webView(), true); + + ewk_view_html_string_load(webView(), htmlString, 0, 0); + ASSERT_TRUE(waitUntilTitleChangedTo(greenInRGB)); +} + +TEST_F(EWK2UnitTestBase, ewk_page_group_user_style_sheet_add_after_creating_view) +{ + // Add a user style sheet to the page group after creating a view. + Ewk_Page_Group* pageGroup = ewk_view_page_group_get(webView()); + ASSERT_TRUE(pageGroup); + ewk_page_group_user_style_sheet_add(pageGroup, userStyleSheet, 0, 0, 0, true); + + ewk_view_html_string_load(webView(), htmlString, 0, 0); + ASSERT_TRUE(waitUntilTitleChangedTo(greenInRGB)); +} + +TEST_F(EWK2UnitTestBase, ewk_page_group_user_style_sheets_remove_all) +{ + Evas_Smart* smart = evas_smart_class_new(&(ewkViewClass()->sc)); + Ewk_Page_Group* pageGroup = ewk_page_group_create("test"); + ASSERT_TRUE(pageGroup); + + // Add a user style sheet to the page group before creating a view. + ewk_page_group_user_style_sheet_add(pageGroup, userStyleSheet, 0, 0, 0, true); + + // Create a new web view with this page group. + Evas_Object* newWebView = ewk_view_smart_add(canvas(), smart, ewk_context_default_get(), pageGroup); + setWebView(newWebView); + + ewk_object_unref(pageGroup); + ewk_view_theme_set(webView(), environment->defaultTheme()); + evas_object_resize(webView(), environment->defaultWidth(), environment->defaultHeight()); + evas_object_show(webView()); + evas_object_focus_set(webView(), true); + + ewk_view_html_string_load(webView(), htmlString, 0, 0); + + // Remove all user style sheets in the page group. + ewk_page_group_user_style_sheets_remove_all(ewk_view_page_group_get(webView())); + ASSERT_TRUE(waitUntilTitleChangedTo(redInRGB)); + + // Add a user style sheet to the page group after creating a view. + pageGroup = ewk_view_page_group_get(webView()); + ewk_page_group_user_style_sheet_add(pageGroup, userStyleSheet, 0, 0, 0, true); + ewk_view_html_string_load(webView(), htmlString, 0, 0); + + // Remove all user style sheets in the page group. + ewk_page_group_user_style_sheets_remove_all(ewk_view_page_group_get(webView())); + ASSERT_TRUE(waitUntilTitleChangedTo(redInRGB)); +} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_popup_menu.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_popup_menu.cpp index a2581320a..3ff5d105f 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_popup_menu.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_popup_menu.cpp @@ -27,62 +27,65 @@ extern EWK2UnitTestEnvironment* environment; static Ewk_Popup_Menu* s_popupMenu = 0; -static inline void checkBasicPopupMenuItem(Ewk_Popup_Menu_Item* item, const char* title, bool enabled) -{ - EXPECT_EQ(EWK_POPUP_MENU_ITEM, ewk_popup_menu_item_type_get(item)); - EXPECT_STREQ(title, ewk_popup_menu_item_text_get(item)); - EXPECT_EQ(enabled, ewk_popup_menu_item_enabled_get(item)); -} - -static Eina_Bool selectItemAfterDelayed(void* data) -{ - EXPECT_TRUE(ewk_popup_menu_selected_index_set(static_cast<Ewk_Popup_Menu*>(data), 0)); - return ECORE_CALLBACK_CANCEL; -} - -static Eina_Bool showPopupMenu(Ewk_View_Smart_Data* smartData, Eina_Rectangle, Ewk_Text_Direction, double, Ewk_Popup_Menu* popupMenu) -{ - s_popupMenu = popupMenu; - - EXPECT_EQ(2, ewk_popup_menu_selected_index_get(popupMenu)); - - const Eina_List* list = ewk_popup_menu_items_get(popupMenu); - - Ewk_Popup_Menu_Item* item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 0)); - checkBasicPopupMenuItem(item, "first", true); - EXPECT_EQ(EWK_TEXT_DIRECTION_LEFT_TO_RIGHT, ewk_popup_menu_item_text_direction_get(item)); - EXPECT_STREQ("", ewk_popup_menu_item_tooltip_get(item)); - EXPECT_STREQ("", ewk_popup_menu_item_accessibility_text_get(item)); - EXPECT_FALSE(ewk_popup_menu_item_is_label_get(item)); - EXPECT_FALSE(ewk_popup_menu_item_selected_get(item)); - - item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 1)); - checkBasicPopupMenuItem(item, "second", false); - EXPECT_FALSE(ewk_popup_menu_item_enabled_get(item)); - - item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 2)); - checkBasicPopupMenuItem(item, "third", true); - EXPECT_EQ(EWK_TEXT_DIRECTION_RIGHT_TO_LEFT, ewk_popup_menu_item_text_direction_get(item)); - EXPECT_STREQ("tooltip", ewk_popup_menu_item_tooltip_get(item)); - EXPECT_STREQ("aria", ewk_popup_menu_item_accessibility_text_get(item)); - EXPECT_TRUE(ewk_popup_menu_item_selected_get(item)); - - item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 3)); - checkBasicPopupMenuItem(item, "label", false); - EXPECT_TRUE(ewk_popup_menu_item_is_label_get(item)); - - item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 4)); - checkBasicPopupMenuItem(item, " forth", true); - - item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 5)); - EXPECT_EQ(EWK_POPUP_MENU_UNKNOWN, ewk_popup_menu_item_type_get(item)); - EXPECT_STREQ(0, ewk_popup_menu_item_text_get(item)); - - ecore_timer_add(0, selectItemAfterDelayed, popupMenu); - return true; -} - -TEST_F(EWK2UnitTestBase, ewk_popup_menu_select_item) +class EWK2PopupMenuTest : public EWK2UnitTestBase { +public: + static void checkBasicPopupMenuItem(Ewk_Popup_Menu_Item* item, const char* title, bool enabled) + { + EXPECT_EQ(EWK_POPUP_MENU_ITEM, ewk_popup_menu_item_type_get(item)); + EXPECT_STREQ(title, ewk_popup_menu_item_text_get(item)); + EXPECT_EQ(enabled, ewk_popup_menu_item_enabled_get(item)); + } + + static Eina_Bool selectItemAfterDelayed(void* data) + { + EXPECT_TRUE(ewk_popup_menu_selected_index_set(static_cast<Ewk_Popup_Menu*>(data), 0)); + return ECORE_CALLBACK_CANCEL; + } + + static Eina_Bool showPopupMenu(Ewk_View_Smart_Data* smartData, Eina_Rectangle, Ewk_Text_Direction, double, Ewk_Popup_Menu* popupMenu) + { + s_popupMenu = popupMenu; + + EXPECT_EQ(2, ewk_popup_menu_selected_index_get(popupMenu)); + + const Eina_List* list = ewk_popup_menu_items_get(popupMenu); + + Ewk_Popup_Menu_Item* item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 0)); + checkBasicPopupMenuItem(item, "first", true); + EXPECT_EQ(EWK_TEXT_DIRECTION_LEFT_TO_RIGHT, ewk_popup_menu_item_text_direction_get(item)); + EXPECT_STREQ("", ewk_popup_menu_item_tooltip_get(item)); + EXPECT_STREQ("", ewk_popup_menu_item_accessibility_text_get(item)); + EXPECT_FALSE(ewk_popup_menu_item_is_label_get(item)); + EXPECT_FALSE(ewk_popup_menu_item_selected_get(item)); + + item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 1)); + checkBasicPopupMenuItem(item, "second", false); + EXPECT_FALSE(ewk_popup_menu_item_enabled_get(item)); + + item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 2)); + checkBasicPopupMenuItem(item, "third", true); + EXPECT_EQ(EWK_TEXT_DIRECTION_RIGHT_TO_LEFT, ewk_popup_menu_item_text_direction_get(item)); + EXPECT_STREQ("tooltip", ewk_popup_menu_item_tooltip_get(item)); + EXPECT_STREQ("aria", ewk_popup_menu_item_accessibility_text_get(item)); + EXPECT_TRUE(ewk_popup_menu_item_selected_get(item)); + + item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 3)); + checkBasicPopupMenuItem(item, "label", false); + EXPECT_TRUE(ewk_popup_menu_item_is_label_get(item)); + + item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 4)); + checkBasicPopupMenuItem(item, " forth", true); + + item = static_cast<Ewk_Popup_Menu_Item*>(eina_list_nth(list, 5)); + EXPECT_EQ(EWK_POPUP_MENU_UNKNOWN, ewk_popup_menu_item_type_get(item)); + EXPECT_STREQ(0, ewk_popup_menu_item_text_get(item)); + + ecore_timer_add(0, selectItemAfterDelayed, popupMenu); + return true; + } +}; + +TEST_F(EWK2PopupMenuTest, ewk_popup_menu_select_item) { const char* selectHTML = "<!doctype html><body><select onchange=\"document.title=this.value;\">" diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp index 7b7247928..caf6af413 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp @@ -221,3 +221,69 @@ TEST_F(EWK2UnitTestBase, ewk_settings_local_storage_enabled) ASSERT_TRUE(ewk_settings_local_storage_enabled_set(settings, true)); ASSERT_TRUE(ewk_settings_local_storage_enabled_get(settings)); } + +TEST_F(EWK2UnitTestBase, ewk_settings_plugins_enabled) +{ + Ewk_Settings* settings = ewk_view_settings_get(webView()); + + // Plug-ins support is enabled by default. + ASSERT_TRUE(ewk_settings_plugins_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_plugins_enabled_set(settings, true)); + ASSERT_TRUE(ewk_settings_plugins_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_plugins_enabled_set(settings, false)); + ASSERT_FALSE(ewk_settings_plugins_enabled_get(settings)); +} + +TEST_F(EWK2UnitTestBase, ewk_settings_default_font_size) +{ + Ewk_Settings* settings = ewk_view_settings_get(webView()); + + // 16 by default. + ASSERT_EQ(16, ewk_settings_default_font_size_get(settings)); + + ASSERT_TRUE(ewk_settings_default_font_size_set(settings, 10)); + ASSERT_EQ(10, ewk_settings_default_font_size_get(settings)); + + ASSERT_TRUE(ewk_settings_default_font_size_set(settings, 20)); + ASSERT_EQ(20, ewk_settings_default_font_size_get(settings)); +} + +TEST_F(EWK2UnitTestBase, ewk_settings_private_browsing_enabled) +{ + Ewk_Settings* settings = ewk_view_settings_get(webView()); + + // Private browsing is disabled by default. + ASSERT_FALSE(ewk_settings_private_browsing_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_private_browsing_enabled_set(settings, true)); + ASSERT_TRUE(ewk_settings_private_browsing_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_private_browsing_enabled_set(settings, false)); + ASSERT_FALSE(ewk_settings_private_browsing_enabled_get(settings)); +} + +TEST_F(EWK2UnitTestBase, ewk_settings_text_autosizing_enabled) +{ + Ewk_Settings* settings = ewk_view_settings_get(webView()); + +#if ENABLE(TEXT_AUTOSIZING) + // Text autosizing should be disabled by default. + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_text_autosizing_enabled_set(settings, false)); + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_get(settings)); + + ASSERT_TRUE(ewk_settings_text_autosizing_enabled_set(settings, true)); + ASSERT_TRUE(ewk_settings_text_autosizing_enabled_get(settings)); +#else + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_get(settings)); + + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_set(settings, false)); + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_get(settings)); + + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_set(settings, true)); + ASSERT_FALSE(ewk_settings_text_autosizing_enabled_get(settings)); +#endif +} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_storage_manager.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_storage_manager.cpp index c3da4d6a7..0c6d336e0 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_storage_manager.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_storage_manager.cpp @@ -29,76 +29,80 @@ using namespace EWK2UnitTest; -struct OriginData { - Eina_List* originList; - Ewk_Storage_Manager* manager; - bool didReceiveOriginsCallback; - bool isSynchronized; - unsigned timeToCheck; - - OriginData() - : originList(0) - , manager(0) - , didReceiveOriginsCallback(false) - , isSynchronized(false) - , timeToCheck(10) - { } -}; - -static void getStorageOriginsCallback(Eina_List* origins, Ewk_Error* error, void* userData) -{ - ASSERT_FALSE(error); - - OriginData* originData = static_cast<OriginData*>(userData); - originData->didReceiveOriginsCallback = true; - - Eina_List* l; - void* data; - EINA_LIST_FOREACH(origins, l, data) { - originData->originList = eina_list_append(originData->originList, data); - Ewk_Security_Origin* origin = static_cast<Ewk_Security_Origin*>(data); - if (!strcmp(ewk_security_origin_protocol_get(origin), "http") - && !strcmp(ewk_security_origin_host_get(origin), "www.storagetest.com") - && !ewk_security_origin_port_get(origin)) { - originData->isSynchronized = true; - ecore_main_loop_quit(); +class EWK2StorageManagerTest : public EWK2UnitTestBase { +public: + struct OriginData { + Eina_List* originList; + Ewk_Storage_Manager* manager; + bool didReceiveOriginsCallback; + bool isSynchronized; + unsigned timeToCheck; + + OriginData() + : originList(0) + , manager(0) + , didReceiveOriginsCallback(false) + , isSynchronized(false) + , timeToCheck(10) + { } + }; + + static void getStorageOriginsCallback(Eina_List* origins, Ewk_Error* error, void* userData) + { + ASSERT_FALSE(error); + + OriginData* originData = static_cast<OriginData*>(userData); + originData->didReceiveOriginsCallback = true; + + Eina_List* l; + void* data; + EINA_LIST_FOREACH(origins, l, data) { + originData->originList = eina_list_append(originData->originList, data); + Ewk_Security_Origin* origin = static_cast<Ewk_Security_Origin*>(data); + if (!strcmp(ewk_security_origin_protocol_get(origin), "http") + && !strcmp(ewk_security_origin_host_get(origin), "www.storagetest.com") + && !ewk_security_origin_port_get(origin)) { + originData->isSynchronized = true; + ecore_main_loop_quit(); + } } } -} -static bool timerCallback(void* userData) -{ - OriginData* originData = static_cast<OriginData*>(userData); + static bool timerCallback(void* userData) + { + OriginData* originData = static_cast<OriginData*>(userData); - if (originData->isSynchronized || !--(originData->timeToCheck)) { - ecore_main_loop_quit(); - return ECORE_CALLBACK_CANCEL; - } + if (originData->isSynchronized || !--(originData->timeToCheck)) { + ecore_main_loop_quit(); + return ECORE_CALLBACK_CANCEL; + } - if (originData->didReceiveOriginsCallback) { - originData->didReceiveOriginsCallback = false; - ewk_storage_manager_origins_get(originData->manager, getStorageOriginsCallback, originData); + if (originData->didReceiveOriginsCallback) { + originData->didReceiveOriginsCallback = false; + ewk_storage_manager_origins_get(originData->manager, getStorageOriginsCallback, originData); + } + + return ECORE_CALLBACK_RENEW; } - return ECORE_CALLBACK_RENEW; -} +protected: + bool checkOrigin(Eina_List* origins, Ewk_Security_Origin** origin) + { + Eina_List* l; + void* data; + EINA_LIST_FOREACH(origins, l, data) { + *origin = static_cast<Ewk_Security_Origin*>(data); + if (!strcmp(ewk_security_origin_protocol_get(*origin), "http") + && !strcmp(ewk_security_origin_host_get(*origin), "www.storagetest.com") + && !ewk_security_origin_port_get(*origin)) + return true; + } -static bool checkOrigin(Eina_List* origins, Ewk_Security_Origin** origin) -{ - Eina_List* l; - void* data; - EINA_LIST_FOREACH(origins, l, data) { - *origin = static_cast<Ewk_Security_Origin*>(data); - if (!strcmp(ewk_security_origin_protocol_get(*origin), "http") - && !strcmp(ewk_security_origin_host_get(*origin), "www.storagetest.com") - && !ewk_security_origin_port_get(*origin)) - return true; + return false; } +}; - return false; -} - -TEST_F(EWK2UnitTestBase, ewk_storage_manager_origins_get) +TEST_F(EWK2StorageManagerTest, ewk_storage_manager_origins_get) { Evas_Object* view = webView(); const char* storageHTML = diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_text_checker.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_text_checker.cpp index 82da09a9e..6dcb870c8 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_text_checker.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_text_checker.cpp @@ -45,190 +45,479 @@ static bool isSettingEnabled = false; static Ecore_Timer* timeoutTimer = 0; static double defaultTimeoutInSeconds = 0.5; +static bool wasContextMenuShown = false; +static const char noGuessesString[] = "No Guesses Found"; +static const char ignoreSpellingString[] = "Ignore Spelling"; +static const char learnSpellingString[] = "Learn Spelling"; + +static const char* clientSuggestionsForWord[] = { "clientSuggestion1", "clientSuggestion2", "clientSuggestion3" }; +static unsigned contextMenuItemsNumber = 0; +static String knownWord; + /** * Structure keeps information which callbacks were called. * Its values are reset before each test. */ static struct { - bool spellDocumentTag : 1; - bool spellDocumentTagClose : 1; - bool spellingCheck : 1; - bool wordGuesses : 1; - bool wordLearn : 1; - bool wordIgnore : 1; + bool settingChange; + bool spellDocumentTag; + bool spellDocumentTagClose; + bool spellingCheck; + bool wordGuesses; + bool wordLearn; + bool wordIgnore; } callbacksExecutionStats; -static void resetCallbacksExecutionStats() -{ - callbacksExecutionStats.spellDocumentTag = false; - callbacksExecutionStats.spellDocumentTagClose = false; - callbacksExecutionStats.spellingCheck = false; - callbacksExecutionStats.wordGuesses = false; - callbacksExecutionStats.wordLearn = false; - callbacksExecutionStats.wordIgnore = false; -} +class EWK2TextCheckerTest : public EWK2UnitTestBase { +public: + static void resetCallbacksExecutionStats() + { + callbacksExecutionStats.settingChange = false; + callbacksExecutionStats.spellDocumentTag = false; + callbacksExecutionStats.spellDocumentTagClose = false; + callbacksExecutionStats.spellingCheck = false; + callbacksExecutionStats.wordGuesses = false; + callbacksExecutionStats.wordLearn = false; + callbacksExecutionStats.wordIgnore = false; + } -/** - * Handle the timeout, it may happen for the asynchronous tests. - * - * @internal - * - * @return the ECORE_CALLBACK_CANCEL flag to delete the timer automatically - */ -static Eina_Bool onTimeout(void*) -{ - ecore_main_loop_quit(); - return ECORE_CALLBACK_CANCEL; -} + /** + * Handle the timeout, it may happen for the asynchronous tests. + * + * @internal + * + * @return the ECORE_CALLBACK_CANCEL flag to delete the timer automatically + */ + static Eina_Bool onTimeout(void*) + { + ecore_main_loop_quit(); + return ECORE_CALLBACK_CANCEL; + } -/** - * This callback tests whether the client's callback is called when the spell checking setting was changed. - * - * @internal - * - * Verify the new setting value (passes in the @a flag parameter) if it equals to the previously set. - * - * @internal - * - * @param flag the new setting value - */ -static void onSettingChange(Eina_Bool flag) -{ - EXPECT_EQ(isSettingEnabled, flag); + /** + * This callback tests whether the client's callback is called when the spell checking setting was changed. + * + * @internal + * + * Verify the new setting value (passes in the @a flag parameter) if it equals to the previously set. + * + * @internal + * + * @param flag the new setting value + */ + static void onSettingChange(Eina_Bool flag) + { + EXPECT_EQ(isSettingEnabled, flag); + callbacksExecutionStats.settingChange = true; + } - ecore_timer_del(timeoutTimer); - timeoutTimer = 0; - ecore_main_loop_quit(); -} + /** + * Returns unique tag (an identifier). + * + * @internal + * + * It will be used for onSpellingCheck, onWordGuesses etc. to notify + * the client on which object (associated to the tag) the spelling is being invoked. + * + * @param ewkView the view object to get unique tag + * + * @return unique tag for the given @a ewkView object + */ + static uint64_t onSpellDocumentTag(const Evas_Object* ewkView) + { + EXPECT_EQ(defaultView, ewkView); + callbacksExecutionStats.spellDocumentTag = true; + + return defaultDocumentTag; + } -/** - * Returns unique tag (an identifier). - * - * @internal - * - * It will be used for onSpellingCheck, onWordGuesses etc. to notify - * the client on which object (associated to the tag) the spelling is being invoked. - * - * @param ewkView the view object to get unique tag - * - * @return unique tag for the given @a ewkView object - */ -static uint64_t onSpellDocumentTag(const Evas_Object* ewkView) -{ - EXPECT_EQ(defaultView, ewkView); - callbacksExecutionStats.spellDocumentTag = true; + /** + * The view which is associated to the @a tag has been destroyed. + * + * @internal + * + * @param tag the tag to be closed + */ + static void onSpellDocumentTagClose(uint64_t tag) + { + ASSERT_EQ(defaultDocumentTag, tag); + callbacksExecutionStats.spellDocumentTagClose = true; + } - return defaultDocumentTag; -} + /** + * Checks spelling for the given @a text. + * + * @internal + * + * @param tag unique tag to notify the client on which object the spelling is being performed + * @param text the text containing the words to spellcheck + * @param misspelling_location a pointer to store the beginning of the misspelled @a text, @c -1 if the @a text is correct + * @param misspelling_length a pointer to store the length of misspelled @a text, @c 0 if the @a text is correct + */ + static void onSpellingCheck(uint64_t tag, const char* text, int32_t* misspellingLocation, int32_t* misspellingLength) + { + ASSERT_EQ(defaultDocumentTag, tag); + ASSERT_STREQ(expectedMisspelledWord, text); + + ASSERT_TRUE(misspellingLocation); + ASSERT_TRUE(misspellingLength); + + // The client is able to show the misselled text through its location (the beginning of misspelling) + // and length (the end of misspelling). + *misspellingLocation = 0; + *misspellingLength = strlen(expectedMisspelledWord); + + callbacksExecutionStats.spellingCheck = true; + } -/** - * The view which is associated to the @a tag has been destroyed. - * - * @internal - * - * @param tag the tag to be closed - */ -static void onSpellDocumentTagClose(uint64_t tag) -{ - ASSERT_EQ(defaultDocumentTag, tag); - callbacksExecutionStats.spellDocumentTagClose = true; -} + /** + * Checks spelling for the given @a text and compares it with the knownWord. + * + * @internal + * + * @param text the text containing the words to spellcheck + * @param misspelling_location a pointer to store the beginning of the misspelled @a text, @c -1 if the @a text is correct + * @param misspelling_length a pointer to store the length of misspelled @a text, @c 0 if the @a text is correct + */ + static void onSpellingForKnownWord(uint64_t, const char* text, int32_t* misspellingLocation, int32_t* misspellingLength) + { + ASSERT_STREQ(knownWord.utf8().data(), text); + + ASSERT_TRUE(misspellingLocation); + ASSERT_TRUE(misspellingLength); + + *misspellingLocation = -1; + *misspellingLength = 0; + + callbacksExecutionStats.spellingCheck = true; + } + + /** + * Gets a list of suggested spellings for a misspelled @a word. + * + * @internal + * + * @param tag unique tag to notify the client on which object the spelling is being performed + * @param word the word to get guesses + * @return a list of dynamically allocated strings (as char*) and + * caller is responsible for destroying them. + */ + static Eina_List* onWordGuesses(uint64_t tag, const char* word) + { + EXPECT_EQ(defaultDocumentTag, tag); + EXPECT_STREQ(expectedMisspelledWord, word); + + Eina_List* suggestionsForWord = 0; + size_t numberOfSuggestions = WTF_ARRAY_LENGTH(clientSuggestionsForWord); + for (size_t i = 0; i < numberOfSuggestions; ++i) + suggestionsForWord = eina_list_append(suggestionsForWord, strdup(clientSuggestionsForWord[i])); + + callbacksExecutionStats.wordGuesses = true; + return suggestionsForWord; + } + + /** + * Adds the @a word to the spell checker dictionary. + * + * @internal + * + * @param tag unique tag to notify the client on which object the spelling is being performed + * @param word the word to add + */ + static void onWordLearn(uint64_t tag, const char* word) + { + ASSERT_EQ(defaultDocumentTag, tag); + ASSERT_STREQ(expectedMisspelledWord, word); + knownWord = word; + callbacksExecutionStats.wordLearn = true; + } + + /** + * Tells the spell checker to ignore a given @a word. + * + * @internal + * + * @param tag unique tag to notify the client on which object the spelling is being performed + * @param word the word to ignore + */ + static void onWordIgnore(uint64_t tag, const char* word) + { + ASSERT_EQ(defaultDocumentTag, tag); + ASSERT_STREQ(expectedMisspelledWord, word); + knownWord = word; + callbacksExecutionStats.wordIgnore = true; + } + + /** + * Helper, get required item from context menu. + * + * @param contextMenu the context menu object + * @param itemAction action of item to get + * @param itemType type of item to get + * + * @return required item + */ + static Ewk_Context_Menu_Item* findContextMenuItem(const Ewk_Context_Menu* contextMenu, Ewk_Context_Menu_Item_Action itemAction, Ewk_Context_Menu_Item_Type itemType) + { + const Eina_List* contextMenuItems = ewk_context_menu_items_get(contextMenu); + + void* itemData; + const Eina_List* listIterator; + EINA_LIST_FOREACH(contextMenuItems, listIterator, itemData) { + Ewk_Context_Menu_Item* item = static_cast<Ewk_Context_Menu_Item*>(itemData); + if (ewk_context_menu_item_action_get(item) == itemAction + && ewk_context_menu_item_type_get(item) == itemType) + return item; + } + + ADD_FAILURE(); + return 0; + } + + static Eina_Bool checkCorrectnessOfSpellingItems(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + const Eina_List* contextMenuItems = ewk_context_menu_items_get(contextMenu); + + bool noGuessesAvailable = false; + bool isIgnoreSpellingAvailable = false; + bool isLearnSpellingAvailable = false; + + const Eina_List* listIterator; + void* itemData; + EINA_LIST_FOREACH(contextMenuItems, listIterator, itemData) { + Ewk_Context_Menu_Item* item = static_cast<Ewk_Context_Menu_Item*>(itemData); + if (!strcmp(ewk_context_menu_item_title_get(item), noGuessesString)) + noGuessesAvailable = true; + else if (!strcmp(ewk_context_menu_item_title_get(item), ignoreSpellingString)) + isIgnoreSpellingAvailable = true; + else if (!strcmp(ewk_context_menu_item_title_get(item), learnSpellingString)) + isLearnSpellingAvailable = true; + } + + EXPECT_FALSE(noGuessesAvailable); + EXPECT_TRUE(isIgnoreSpellingAvailable); + EXPECT_TRUE(isLearnSpellingAvailable); + + wasContextMenuShown = true; + return true; + } + + static Eina_Bool toogleCheckSpellingWhileTyping(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + Ewk_Context_Menu_Item* spellingAndGrammarItem = findContextMenuItem(contextMenu, EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_MENU, EWK_SUBMENU_TYPE); + Ewk_Context_Menu* spellingAndGrammarSubmenu = ewk_context_menu_item_submenu_get(spellingAndGrammarItem); + Ewk_Context_Menu_Item* checkSpellingWhileTypingItem = findContextMenuItem(spellingAndGrammarSubmenu, EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING_WHILE_TYPING, EWK_CHECKABLE_ACTION_TYPE); + + return ewk_context_menu_item_select(spellingAndGrammarSubmenu, checkSpellingWhileTypingItem); + } + + static Eina_Bool checkClientSuggestionsForWord(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + const Eina_List* contextMenuItems = ewk_context_menu_items_get(contextMenu); + + size_t numberOfSuggestions = WTF_ARRAY_LENGTH(clientSuggestionsForWord); + // contextMenuItems should contain suggestions and another options. + if (numberOfSuggestions > eina_list_count(contextMenuItems)) { + ADD_FAILURE(); + return true; + } + // Verify suggestions from the top of context menu list. + for (size_t i = 0; i < numberOfSuggestions; ++i) { + Ewk_Context_Menu_Item* item = static_cast<Ewk_Context_Menu_Item*>(eina_list_data_get(contextMenuItems)); + EXPECT_STREQ(clientSuggestionsForWord[i], ewk_context_menu_item_title_get(item)); + contextMenuItems = eina_list_next(contextMenuItems); + } + + wasContextMenuShown = true; + return true; + } + + static Eina_Bool selectLearnSpelling(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + return ewk_context_menu_item_select(contextMenu, findContextMenuItem(contextMenu, EWK_CONTEXT_MENU_ITEM_TAG_LEARN_SPELLING, EWK_ACTION_TYPE)); + } + + static Eina_Bool selectIgnoreSpelling(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + return ewk_context_menu_item_select(contextMenu, findContextMenuItem(contextMenu, EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_SPELLING, EWK_ACTION_TYPE)); + } + + /** + * Count number of elements in context menu. + */ + static Eina_Bool countContextMenuItems(Ewk_View_Smart_Data*, Evas_Coord, Evas_Coord, Ewk_Context_Menu* contextMenu) + { + contextMenuItemsNumber = eina_list_count(ewk_context_menu_items_get(contextMenu)); + wasContextMenuShown = true; + return true; + } + +protected: + enum Line { FirstLine, SecondLine }; + enum Button { SelectAllWordsWithSpellcheckButton, SelectAllWordsWithoutSpellcheckButton, SelectSubWordWithSpellcheckButton }; + + void clickButton(Button button) + { + switch (button) { + case SelectAllWordsWithSpellcheckButton: + mouseClick(60, 60); + break; + case SelectAllWordsWithoutSpellcheckButton: + mouseClick(500, 60); + break; + case SelectSubWordWithSpellcheckButton : + mouseClick(200, 60); + break; + } + } + + void showContextMenu(Line line) + { + switch (line) { + case FirstLine: + mouseClick(10, 20, 3); + break; + case SecondLine: + mouseClick(35, 35, 3); + break; + } + } + + void selectFirstWord(Line line) + { + switch (line) { + case FirstLine: + mouseDoubleClick(10, 20); + break; + case SecondLine: + mouseDoubleClick(35, 35); + break; + } + } +}; /** - * Checks spelling for the given @a text. - * - * @internal - * - * @param tag unique tag to notify the client on which object the spelling is being performed - * @param text the text containing the words to spellcheck - * @param misspelling_location a pointer to store the beginning of the misspelled @a text, @c -1 if the @a text is correct - * @param misspelling_length a pointer to store the length of misspelled @a text, @c 0 if the @a text is correct + * Test whether there are spelling suggestions when misspelled word is directly context clicked. */ -static void onSpellingCheck(uint64_t tag, const char* text, int32_t* misspellingLocation, int32_t* misspellingLength) +TEST_F(EWK2TextCheckerTest, spelling_suggestion_for_context_click) { - ASSERT_EQ(defaultDocumentTag, tag); - ASSERT_STREQ(expectedMisspelledWord, text); + wasContextMenuShown = false; + + // Checking number of context menu items when element has no spellcheck suggestions. + ewkViewClass()->context_menu_show = countContextMenuItems; + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + showContextMenu(FirstLine); - ASSERT_TRUE(misspellingLocation); - ASSERT_TRUE(misspellingLength); + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + unsigned numberItemsWithoutSpellCheck = contextMenuItemsNumber; - // The client is able to show the misselled text through its location (the beginning of misspelling) - // and length (the end of misspelling). - *misspellingLocation = 0; - *misspellingLength = strlen(expectedMisspelledWord); + wasContextMenuShown = false; - callbacksExecutionStats.spellingCheck = true; + // Testing how many items are in context menu when spellcheck is enabled. + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + showContextMenu(SecondLine); + + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + + EXPECT_LT(numberItemsWithoutSpellCheck, contextMenuItemsNumber); } /** - * Gets a list of suggested spellings for a misspelled @a word. - * - * @internal - * - * @param tag unique tag to notify the client on which object the spelling is being performed - * @param word the word to get guesses - * @return a list of dynamically allocated strings (as char*) and - * caller is responsible for destroying them. + * Test whether there are no spelling suggestions when multiple words are selected (that are not a single misspelling). */ -static Eina_List* onWordGuesses(uint64_t tag, const char* word) +TEST_F(EWK2TextCheckerTest, no_spelling_suggestion_for_multiword_selection) { - EXPECT_EQ(defaultDocumentTag, tag); - EXPECT_STREQ(expectedMisspelledWord, word); + wasContextMenuShown = false; + + // Checking number of context menu items when element has no spellcheck suggestions. + ewkViewClass()->context_menu_show = countContextMenuItems; + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + clickButton(SelectAllWordsWithoutSpellcheckButton); + showContextMenu(FirstLine); - Eina_List* suggestionsForWord = 0; - // FIXME: Fill the Eina_List with suggestions for the misspelled word. - callbacksExecutionStats.wordGuesses = true; + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + unsigned numberItemsWithoutSpellCheck = contextMenuItemsNumber; - return suggestionsForWord; + wasContextMenuShown = false; + + // Testing how many items are in context menu when multiple words are selected. + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + clickButton(SelectAllWordsWithSpellcheckButton); + showContextMenu(SecondLine); + + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + + EXPECT_EQ(numberItemsWithoutSpellCheck, contextMenuItemsNumber); } /** - * Adds the @a word to the spell checker dictionary. - * - * @internal - * - * @param tag unique tag to notify the client on which object the spelling is being performed - * @param word the word to add + * Test whether there are no spelling suggestions when part of misspelled word are selected. */ -static void onWordLearn(uint64_t tag, const char* word) +TEST_F(EWK2TextCheckerTest, no_spelling_suggestion_for_subword_selection) { - ASSERT_EQ(defaultDocumentTag, tag); - ASSERT_STREQ(expectedMisspelledWord, word); - callbacksExecutionStats.wordLearn = true; + wasContextMenuShown = false; + + // Checking number of context menu items when element has no spellcheck suggestions. + ewkViewClass()->context_menu_show = countContextMenuItems; + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + clickButton(SelectAllWordsWithoutSpellcheckButton); + showContextMenu(FirstLine); + + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + unsigned numberItemsWithoutSpellCheck = contextMenuItemsNumber; + + wasContextMenuShown = false; + + // Testing how many items are in context menu when part of word is selected. + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + clickButton(SelectSubWordWithSpellcheckButton); + showContextMenu(SecondLine); + + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + + EXPECT_EQ(numberItemsWithoutSpellCheck, contextMenuItemsNumber); } /** - * Tells the spell checker to ignore a given @a word. - * - * @internal - * - * @param tag unique tag to notify the client on which object the spelling is being performed - * @param word the word to ignore + * Test whether context menu spelling items are available when misspelled word has selection as the double click. */ -static void onWordIgnore(uint64_t tag, const char* word) +TEST_F(EWK2TextCheckerTest, spelling_suggestion_for_double_clicked_word) { - ASSERT_EQ(defaultDocumentTag, tag); - ASSERT_STREQ(expectedMisspelledWord, word); - callbacksExecutionStats.wordIgnore = true; + wasContextMenuShown = false; + + // Checking number of context menu items when element has no spell check suggestions. + ewkViewClass()->context_menu_show = countContextMenuItems; + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + clickButton(SelectAllWordsWithoutSpellcheckButton); + showContextMenu(FirstLine); + + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + unsigned numberItemsWithoutSpellCheck = contextMenuItemsNumber; + + wasContextMenuShown = false; + + // Making double click on misspelled word to select it, and checking are there context menu spell check suggestions. + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_selection_tests.html").data())); + selectFirstWord(SecondLine); + showContextMenu(SecondLine); + + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + + EXPECT_LT(numberItemsWithoutSpellCheck, contextMenuItemsNumber); } /** - * Test setter/getter for the continous spell checking: - * - ewk_settings_continuous_spell_checking_enabled_get - * - ewk_settings_continuous_spell_checking_enabled_set + * Test whether the default language is loaded independently of + * continuous spell checking setting. */ -TEST_F(EWK2UnitTestBase, ewk_settings_continuous_spell_checking_enabled) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_spell_checking_languages_get) { - ewk_settings_continuous_spell_checking_enabled_set(true); -#if ENABLE(SPELLCHECK) - EXPECT_TRUE(ewk_settings_continuous_spell_checking_enabled_get()); - - // When the spell checking has been enabled, the default language is set (if the user - // didn't set any). The languages are being loaded on the idler, wait for them. + ewk_text_checker_continuous_spell_checking_enabled_set(false); + // The language is being loaded on the idler, wait for it. timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); ecore_main_loop_begin(); - Eina_List* loadedLanguages = ewk_settings_spell_checking_languages_get(); + Eina_List* loadedLanguages = ewk_text_checker_spell_checking_languages_get(); // No dictionary is available/installed. if (!loadedLanguages) return; @@ -237,60 +526,121 @@ TEST_F(EWK2UnitTestBase, ewk_settings_continuous_spell_checking_enabled) void* data; EINA_LIST_FREE(loadedLanguages, data) - eina_stringshare_del(static_cast<const char*>(data)); -#else - EXPECT_FALSE(ewk_settings_continuous_spell_checking_enabled_get()); -#endif + eina_stringshare_del(static_cast<Eina_Stringshare*>(data)); + + // Repeat the checking when continuous spell checking setting is on. + ewk_text_checker_continuous_spell_checking_enabled_set(true); + timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); + ecore_main_loop_begin(); + + loadedLanguages = ewk_text_checker_spell_checking_languages_get(); + if (!loadedLanguages) + return; + + EXPECT_EQ(1, eina_list_count(loadedLanguages)); - ewk_settings_continuous_spell_checking_enabled_set(false); - EXPECT_FALSE(ewk_settings_continuous_spell_checking_enabled_get()); + EINA_LIST_FREE(loadedLanguages, data) + eina_stringshare_del(static_cast<Eina_Stringshare*>(data)); } /** - * Test whether the callback is called when the spell checking setting has been changed. + * Test whether the context menu spelling items (suggestions, learn and ignore spelling) + * are available when continuous spell checking is off. */ -TEST_F(EWK2UnitTestBase, ewk_settings_continuous_spell_checking_change_cb_set) +TEST_F(EWK2TextCheckerTest, context_menu_spelling_items_availability) { - ewk_settings_continuous_spell_checking_change_cb_set(onSettingChange); - - isSettingEnabled = ewk_settings_continuous_spell_checking_enabled_get(); - isSettingEnabled = !isSettingEnabled; - ewk_settings_continuous_spell_checking_enabled_set(isSettingEnabled); + ewk_text_checker_continuous_spell_checking_enabled_set(false); + ewkViewClass()->context_menu_show = checkCorrectnessOfSpellingItems; - timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); + showContextMenu(FirstLine); - // Start proccesing Ecore events, the notification about the change of the spell - // checking setting is called on idler. - // We can't call ecore_main_loop_iterate because it doesn't process the idlers. - ecore_main_loop_begin(); + while (!wasContextMenuShown) + ecore_main_loop_iterate(); +} +/** + * Test setter/getter for the continuous spell checking: + * - ewk_text_checker_continuous_spell_checking_enabled_get + * - ewk_text_checker_continuous_spell_checking_enabled_set + */ +TEST_F(EWK2TextCheckerTest, ewk_text_checker_continuous_spell_checking_enabled) +{ + ewk_text_checker_continuous_spell_checking_enabled_set(true); #if ENABLE(SPELLCHECK) - EXPECT_FALSE(timeoutTimer); + EXPECT_TRUE(ewk_text_checker_continuous_spell_checking_enabled_get()); #else - EXPECT_TRUE(timeoutTimer); + EXPECT_FALSE(ewk_text_checker_continuous_spell_checking_enabled_get()); #endif - // The callback shouldn't be called if the setting option is already set. - isSettingEnabled = ewk_settings_continuous_spell_checking_enabled_get(); - ewk_settings_continuous_spell_checking_enabled_set(isSettingEnabled); + ewk_text_checker_continuous_spell_checking_enabled_set(false); + EXPECT_FALSE(ewk_text_checker_continuous_spell_checking_enabled_get()); +} - timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); - ecore_main_loop_begin(); +/** + * Test whether the onSettingChange callback is called when "Check Spelling While Typing" setting was changed in context menu. + * Two cases are tested: + * - "Check Spelling While Typing" is enabled, + * - "Check Spelling While Typing" is disabled. + */ +TEST_F(EWK2TextCheckerTest, ewk_text_checker_check_spelling_while_typing_toggle) +{ + resetCallbacksExecutionStats(); + ewkViewClass()->context_menu_show = toogleCheckSpellingWhileTyping; + + ewk_text_checker_continuous_spell_checking_change_cb_set(onSettingChange); + isSettingEnabled = !ewk_text_checker_continuous_spell_checking_enabled_get(); + + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); + + showContextMenu(FirstLine); + ASSERT_TRUE(waitUntilTrue(callbacksExecutionStats.settingChange)); - // When the SPELLCHECK macro is disabled the callback won't be called too. - EXPECT_TRUE(timeoutTimer); + resetCallbacksExecutionStats(); - // The callback shouldn't be called if the user has invalidated it. - ewk_settings_continuous_spell_checking_change_cb_set(0); - isSettingEnabled = ewk_settings_continuous_spell_checking_enabled_get(); + // Test case, when "Check Spelling While Typing" is in reverse to the previous one. isSettingEnabled = !isSettingEnabled; - ewk_settings_continuous_spell_checking_enabled_set(isSettingEnabled); - timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); - ecore_main_loop_begin(); + showContextMenu(FirstLine); + ASSERT_TRUE(waitUntilTrue(callbacksExecutionStats.settingChange)); + + ewk_text_checker_continuous_spell_checking_change_cb_set(0); +} + +/** + * Test whether the onSettingChange callback is not called when the spell checking setting was changed by client. + */ +TEST_F(EWK2TextCheckerTest, ewk_text_checker_continuous_spell_checking_change_cb_set) +{ + resetCallbacksExecutionStats(); + + ewk_text_checker_continuous_spell_checking_change_cb_set(onSettingChange); + + isSettingEnabled = ewk_text_checker_continuous_spell_checking_enabled_get(); + isSettingEnabled = !isSettingEnabled; + // The notifications about the setting change shouldn't be sent if the change was made + // on the client's request (public API). + ewk_text_checker_continuous_spell_checking_enabled_set(isSettingEnabled); + + // The notification about the change of the spell checking setting is called on idler. + ASSERT_FALSE(waitUntilTrue(callbacksExecutionStats.settingChange, /*Timeout*/ 0)); + + ewk_text_checker_continuous_spell_checking_change_cb_set(0); +} + +/** + * Test whether the onSettingChange callback is not called, if the client does not set it. + * "Check Spelling While Typing" option is toggled in context menu. + */ +TEST_F(EWK2TextCheckerTest, ewk_text_checker_continuous_spell_checking_change_cb_unset) +{ + resetCallbacksExecutionStats(); + ewkViewClass()->context_menu_show = toogleCheckSpellingWhileTyping; - // If the SPELLCHECK macro is disabled, the callback is not set. - EXPECT_TRUE(timeoutTimer); + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); + + showContextMenu(FirstLine); + ASSERT_FALSE(waitUntilTrue(callbacksExecutionStats.settingChange, /*Timeout*/ 0)); } /** @@ -298,9 +648,9 @@ TEST_F(EWK2UnitTestBase, ewk_settings_continuous_spell_checking_change_cb_set) * if they are in use. * All the dictionaries from the list can be set to perform spellchecking. */ -TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_available_languages_get) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_spell_checking_available_languages_get) { - Eina_List* availableLanguages = ewk_settings_spell_checking_available_languages_get(); + Eina_List* availableLanguages = ewk_text_checker_spell_checking_available_languages_get(); // No dictionary is available/installed or the SPELLCHECK macro is disabled. if (!availableLanguages) return; @@ -319,14 +669,14 @@ TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_available_languages_get) } // Set all available languages. - ewk_settings_spell_checking_languages_set(languages.toString().utf8().data()); + ewk_text_checker_spell_checking_languages_set(languages.toString().utf8().data()); // Languages are being loaded on the idler, wait for them. timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); ecore_main_loop_begin(); // Get the languages in use. - Eina_List* loadedLanguages = ewk_settings_spell_checking_languages_get(); + Eina_List* loadedLanguages = ewk_text_checker_spell_checking_languages_get(); ASSERT_EQ(eina_list_count(loadedLanguages), eina_list_count(availableLanguages)); i = 0; @@ -350,16 +700,16 @@ TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_available_languages_get) * - setting the default language, * - if two arbitrarily selected dictionaries are set correctly. */ -TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_languages) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_spell_checking_languages) { // Set the default language. - ewk_settings_spell_checking_languages_set(0); + ewk_text_checker_spell_checking_languages_set(0); // Languages are being loaded on the idler, wait for them. timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); ecore_main_loop_begin(); - Eina_List* loadedLanguages = ewk_settings_spell_checking_languages_get(); + Eina_List* loadedLanguages = ewk_text_checker_spell_checking_languages_get(); // No dictionary is available/installed or the SPELLCHECK macro is disabled. if (!loadedLanguages) return; @@ -372,7 +722,7 @@ TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_languages) eina_stringshare_del(static_cast<const char*>(actual)); // Get the first and last language from installed dictionaries. - Eina_List* availableLanguages = ewk_settings_spell_checking_available_languages_get(); + Eina_List* availableLanguages = ewk_text_checker_spell_checking_available_languages_get(); unsigned numberOfAvailableLanguages = eina_list_count(availableLanguages); // We assume that user has installed at lest two dictionaries. if (numberOfAvailableLanguages < 2) @@ -389,12 +739,12 @@ TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_languages) languages.append(String(lastExpected).lower()); // Set both languages (the first and the last) from the list. - ewk_settings_spell_checking_languages_set(languages.toString().utf8().data()); + ewk_text_checker_spell_checking_languages_set(languages.toString().utf8().data()); timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); ecore_main_loop_begin(); - loadedLanguages = ewk_settings_spell_checking_languages_get(); + loadedLanguages = ewk_text_checker_spell_checking_languages_get(); ASSERT_EQ(2, eina_list_count(loadedLanguages)); EXPECT_STREQ(firstExpected, static_cast<const char*>(eina_list_nth(loadedLanguages, 0))); @@ -411,10 +761,10 @@ TEST_F(EWK2UnitTestBase, ewk_settings_spell_checking_languages) /** * Test whether the client's callbacks aren't called (if not specified). */ -TEST_F(EWK2UnitTestBase, ewk_text_checker) +TEST_F(EWK2TextCheckerTest, ewk_text_checker) { resetCallbacksExecutionStats(); - ewk_settings_continuous_spell_checking_enabled_set(true); + ewk_text_checker_continuous_spell_checking_enabled_set(true); ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); @@ -432,11 +782,11 @@ TEST_F(EWK2UnitTestBase, ewk_text_checker) /** * Test whether the client's callbacks (onSpellDocumentTag, onSpellDocumentTagClose) are called. */ -TEST_F(EWK2UnitTestBase, ewk_text_checker_unique_spell_document_tag) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_unique_spell_document_tag) { resetCallbacksExecutionStats(); defaultView = webView(); - ewk_settings_continuous_spell_checking_enabled_set(true); + ewk_text_checker_continuous_spell_checking_enabled_set(true); ewk_text_checker_unique_spell_document_tag_get_cb_set(onSpellDocumentTag); ewk_text_checker_unique_spell_document_tag_close_cb_set(onSpellDocumentTagClose); @@ -454,11 +804,11 @@ TEST_F(EWK2UnitTestBase, ewk_text_checker_unique_spell_document_tag) * Test whether the client's callback (onSpellingCheck) is called when * the word to input field was put. */ -TEST_F(EWK2UnitTestBase, ewk_text_checker_string_spelling_check_cb_set) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_string_spelling_check_cb_set) { resetCallbacksExecutionStats(); defaultView = webView(); - ewk_settings_continuous_spell_checking_enabled_set(true); + ewk_text_checker_continuous_spell_checking_enabled_set(true); ewk_text_checker_string_spelling_check_cb_set(onSpellingCheck); @@ -472,60 +822,85 @@ TEST_F(EWK2UnitTestBase, ewk_text_checker_string_spelling_check_cb_set) * Test whether the client's callback (onWordGuesses) is called when * the context menu was shown on the misspelled word. */ -TEST_F(EWK2UnitTestBase, ewk_text_checker_word_guesses_get_cb_set) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_word_guesses_get_cb_set) { resetCallbacksExecutionStats(); + wasContextMenuShown = false; defaultView = webView(); - ewk_settings_continuous_spell_checking_enabled_set(true); - + ewkViewClass()->context_menu_show = checkClientSuggestionsForWord; ewk_text_checker_word_guesses_get_cb_set(onWordGuesses); ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - /* FIXME: - 1) Invoke the context menu on the misspelled word (not implemented for WK2), - the word has to be selected first. - 2) Fill the suggestion list in the onWordGuesses callback. - 3) Compare context menu suggestions to the suggestion list. - 4) Check whether the callback was called. */ + showContextMenu(FirstLine); + ASSERT_TRUE(waitUntilTrue(wasContextMenuShown)); + + // Check whether the callback is called. + ASSERT_TRUE(callbacksExecutionStats.wordGuesses); + + ewk_text_checker_word_guesses_get_cb_set(0); } /** * Test whether the client's callback (onWordLearn) is called when - * the context menu option "Learn spelling" was choosen. + * the context menu option "Learn spelling" was chosen. In the next step, + * check whether the learned word is treated as spelled correctly while spell checking. */ -TEST_F(EWK2UnitTestBase, ewk_text_checker_word_learn_cb_set) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_word_learn_cb_set) { resetCallbacksExecutionStats(); + knownWord = emptyString(); defaultView = webView(); - ewk_settings_continuous_spell_checking_enabled_set(true); - ewk_text_checker_word_learn_cb_set(onWordLearn); + ewkViewClass()->context_menu_show = selectLearnSpelling; + + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); + selectFirstWord(FirstLine); + showContextMenu(FirstLine); + + ASSERT_TRUE(waitUntilTrue(callbacksExecutionStats.wordLearn)); + + // Open html again and check whether the learned word + // is treated as spelled correctly while spell checking. + resetCallbacksExecutionStats(); + ewk_text_checker_string_spelling_check_cb_set(onSpellingForKnownWord); ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - /* FIXME: - 1) Invoke the context menu on the misspelled word (not implemented for WK2), - the word has to be selected first. - 2) Check whether the callback was called. */ + ASSERT_TRUE(callbacksExecutionStats.spellingCheck); + + ewk_text_checker_string_spelling_check_cb_set(0); + ewk_text_checker_word_learn_cb_set(0); } /** * Test whether the client's callback (onWordIgnore) is called when - * the context menu option "Ignore spelling" was choosen. + * the context menu option "Ignore spelling" was chosen. In the next step, + * check whether the ignored word is treated as spelled correctly while spell checking. */ -TEST_F(EWK2UnitTestBase, ewk_text_checker_word_ignore_cb_set) +TEST_F(EWK2TextCheckerTest, ewk_text_checker_word_ignore_cb_set) { resetCallbacksExecutionStats(); + knownWord = emptyString(); defaultView = webView(); - ewk_settings_continuous_spell_checking_enabled_set(true); - ewk_text_checker_word_ignore_cb_set(onWordIgnore); + ewkViewClass()->context_menu_show = selectIgnoreSpelling; + + ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); + selectFirstWord(FirstLine); + showContextMenu(FirstLine); + + ASSERT_TRUE(waitUntilTrue(callbacksExecutionStats.wordIgnore)); + + // Open html again and check whether the ignored word + // is treated as spelled correctly while spell checking. + resetCallbacksExecutionStats(); + ewk_text_checker_string_spelling_check_cb_set(onSpellingForKnownWord); ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - /* FIXME: - 1) Invoke the context menu on the misspelled word (not implemented for WK2), - the word has to be selected first. - 2) Check whether the callback was called. */ + ASSERT_TRUE(callbacksExecutionStats.spellingCheck); + + ewk_text_checker_string_spelling_check_cb_set(0); + ewk_text_checker_word_ignore_cb_set(0); } diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp index 922c3ec21..b65240007 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp @@ -23,16 +23,221 @@ #include "UnitTestUtils/EWK2UnitTestServer.h" #include <wtf/OwnPtr.h> #include <wtf/PassOwnPtr.h> -#include <wtf/UnusedParam.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> using namespace EWK2UnitTest; extern EWK2UnitTestEnvironment* environment; -bool fullScreenCallbackCalled; -TEST_F(EWK2UnitTestBase, ewk_view_type_check) +static bool fullScreenCallbackCalled; +static bool obtainedPageContents = false; + +static struct { + const char* expectedMessage; + bool called; +} alertCallbackData; + +static struct { + const char* expectedMessage; + bool result; + bool called; +} confirmCallbackData; + +static struct { + const char* expectedMessage; + const char* expectedDefaultValue; + const char* result; + bool called; +} promptCallbackData; + +class EWK2ViewTest : public EWK2UnitTestBase { +public: + struct VibrationCbData { + bool didReceiveVibrate; // Whether the vibration event received. + bool didReceiveCancelVibration; // Whether the cancel vibration event received. + unsigned vibrateCalledCount; // Vibrate callbacks count. + unsigned expectedVibrationTime; // Expected vibration time. + }; + + static void onLoadFinishedForRedirection(void* userData, Evas_Object*, void*) + { + int* countLoadFinished = static_cast<int*>(userData); + (*countLoadFinished)--; + } + + static void serverCallbackNavigation(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) + { + if (message->method != SOUP_METHOD_GET) { + soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); + return; + } + + soup_message_set_status(message, SOUP_STATUS_OK); + + Eina_Strbuf* body = eina_strbuf_new(); + eina_strbuf_append_printf(body, "<html><title>%s</title><body>%s</body></html>", path + 1, path + 1); + const size_t bodyLength = eina_strbuf_length_get(body); + soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, eina_strbuf_string_steal(body), bodyLength); + eina_strbuf_free(body); + + soup_message_body_complete(message->response_body); + } + + static void onFormAboutToBeSubmitted(void* userData, Evas_Object*, void* eventInfo) + { + Ewk_Form_Submission_Request* request = static_cast<Ewk_Form_Submission_Request*>(eventInfo); + bool* handled = static_cast<bool*>(userData); + + ASSERT_TRUE(request); + + Eina_List* fieldNames = ewk_form_submission_request_field_names_get(request); + ASSERT_TRUE(fieldNames); + ASSERT_EQ(3, eina_list_count(fieldNames)); + void* data; + EINA_LIST_FREE(fieldNames, data) + eina_stringshare_del(static_cast<char*>(data)); + + const char* value1 = ewk_form_submission_request_field_value_get(request, "text1"); + ASSERT_STREQ("value1", value1); + eina_stringshare_del(value1); + const char* value2 = ewk_form_submission_request_field_value_get(request, "text2"); + ASSERT_STREQ("value2", value2); + eina_stringshare_del(value2); + const char* password = ewk_form_submission_request_field_value_get(request, "password"); + ASSERT_STREQ("secret", password); + eina_stringshare_del(password); + + *handled = true; + } + + static Eina_Bool fullScreenCallback(Ewk_View_Smart_Data* smartData, Ewk_Security_Origin*) + { + fullScreenCallbackCalled = true; + return false; + } + + static Eina_Bool fullScreenExitCallback(Ewk_View_Smart_Data* smartData) + { + fullScreenCallbackCalled = true; + return false; + } + + static void checkAlert(Ewk_View_Smart_Data*, const char* message) + { + alertCallbackData.called = true; + EXPECT_STREQ(message, alertCallbackData.expectedMessage); + } + + static Eina_Bool checkConfirm(Ewk_View_Smart_Data*, const char* message) + { + confirmCallbackData.called = true; + EXPECT_STREQ(message, confirmCallbackData.expectedMessage); + return confirmCallbackData.result; + } + + static const char* checkPrompt(Ewk_View_Smart_Data*, const char* message, const char* defaultValue) + { + promptCallbackData.called = true; + EXPECT_STREQ(message, promptCallbackData.expectedMessage); + EXPECT_STREQ(defaultValue, promptCallbackData.expectedDefaultValue); + + if (!promptCallbackData.result) + return 0; + + return eina_stringshare_add(promptCallbackData.result); + } + + static void onTextFound(void* userData, Evas_Object*, void* eventInfo) + { + int* result = static_cast<int*>(userData); + unsigned* matchCount = static_cast<unsigned*>(eventInfo); + + *result = *matchCount; + } + + static void onVibrate(void* userData, Evas_Object*, void* eventInfo) + { + VibrationCbData* data = static_cast<VibrationCbData*>(userData); + unsigned* vibrationTime = static_cast<unsigned*>(eventInfo); + if (*vibrationTime == data->expectedVibrationTime) + data->didReceiveVibrate = true; + data->vibrateCalledCount++; + } + + static void onCancelVibration(void* userData, Evas_Object*, void*) + { + VibrationCbData* data = static_cast<VibrationCbData*>(userData); + data->didReceiveCancelVibration = true; + } + + static void loadVibrationHTMLString(Evas_Object* webView, const char* vibrationPattern, bool waitForVibrationEvent, VibrationCbData* data) + { + const char* content = + "<html><head><script type='text/javascript'>function vibrate() { navigator.vibrate(%s);" + " document.title = \"Loaded\"; }</script></head><body onload='vibrate()'></body></html>"; + + data->didReceiveVibrate = false; + data->didReceiveCancelVibration = false; + data->vibrateCalledCount = 0; + Eina_Strbuf* buffer = eina_strbuf_new(); + eina_strbuf_append_printf(buffer, content, vibrationPattern); + ewk_view_html_string_load(webView, eina_strbuf_string_get(buffer), 0, 0); + eina_strbuf_free(buffer); + + if (!waitForVibrationEvent) + return; + + while (!data->didReceiveVibrate && !data->didReceiveCancelVibration) + ecore_main_loop_iterate(); + } + + static void onContentsSizeChangedPortrait(void* userData, Evas_Object*, void* eventInfo) + { + bool* result = static_cast<bool*>(userData); + Ewk_CSS_Size* size = static_cast<Ewk_CSS_Size*>(eventInfo); + if (size->w == 2000 && size->h == 3000) + *result = true; + } + + static void onContentsSizeChangedLandscape(void* userData, Evas_Object*, void* eventInfo) + { + bool* result = static_cast<bool*>(userData); + Ewk_CSS_Size* size = static_cast<Ewk_CSS_Size*>(eventInfo); + if (size->w == 3000 && size->h == 2000) + *result = true; + } + + static void PageContentsAsMHTMLCallback(Ewk_Page_Contents_Type type, const char* data, void*) + { + // Check the type + ASSERT_EQ(EWK_PAGE_CONTENTS_TYPE_MHTML, type); + + // The variable data should have below text block. + const String expectedMHTML = "\r\n\r\n<=00h=00t=00m=00l=00>=00<=00h=00e=00a=00d=00>=00<=00m=00e=00t=00a=00 =00c=\r\n" + "=00h=00a=00r=00s=00e=00t=00=3D=00\"=00U=00T=00F=00-=001=006=00L=00E=00\"=00>=\r\n" + "=00<=00/=00h=00e=00a=00d=00>=00<=00b=00o=00d=00y=00>=00<=00p=00>=00S=00i=00=\r\n" + "m=00p=00l=00e=00 =00H=00T=00M=00L=00<=00/=00p=00>=00<=00/=00b=00o=00d=00y=\r\n" + "=00>=00<=00/=00h=00t=00m=00l=00>=00\r\n"; + + ASSERT_TRUE(String(data).contains(expectedMHTML)); + + obtainedPageContents = true; + } + + static void PageContentsAsStringCallback(Ewk_Page_Contents_Type type, const char* data, void*) + { + // Check the type. + ASSERT_EQ(EWK_PAGE_CONTENTS_TYPE_STRING, type); + + // The variable data should be "Simple HTML". + ASSERT_STREQ("Simple HTML", data); + + obtainedPageContents = true; + } +}; + +TEST_F(EWK2ViewTest, ewk_view_type_check) { ASSERT_FALSE(ewk_view_context_get(0)); @@ -40,13 +245,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_type_check) ASSERT_FALSE(ewk_view_url_set(rectangle, 0)); } -static void onLoadFinishedForRedirection(void* userData, Evas_Object*, void*) -{ - int* countLoadFinished = static_cast<int*>(userData); - (*countLoadFinished)--; -} - -TEST_F(EWK2UnitTestBase, ewk_view_url_get) +TEST_F(EWK2ViewTest, ewk_view_url_get) { ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); EXPECT_STREQ(environment->defaultTestPageUrl(), ewk_view_url_get(webView())); @@ -60,7 +259,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_url_get) EXPECT_STREQ(environment->defaultTestPageUrl(), ewk_view_url_get(webView())); } -TEST_F(EWK2UnitTestBase, ewk_view_device_pixel_ratio) +TEST_F(EWK2ViewTest, ewk_view_device_pixel_ratio) { ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); @@ -74,7 +273,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_device_pixel_ratio) ASSERT_FLOAT_EQ(1, ewk_view_device_pixel_ratio_get(webView())); } -TEST_F(EWK2UnitTestBase, ewk_view_html_string_load) +TEST_F(EWK2ViewTest, ewk_view_html_string_load) { ewk_view_html_string_load(webView(), "<html><head><title>Foo</title></head><body>Bar</body></html>", 0, 0); ASSERT_TRUE(waitUntilTitleChangedTo("Foo")); @@ -84,25 +283,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_html_string_load) ASSERT_STREQ("Bar", ewk_view_title_get(webView())); } -static void serverCallbackNavigation(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) -{ - if (message->method != SOUP_METHOD_GET) { - soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); - return; - } - - soup_message_set_status(message, SOUP_STATUS_OK); - - Eina_Strbuf* body = eina_strbuf_new(); - eina_strbuf_append_printf(body, "<html><title>%s</title><body>%s</body></html>", path + 1, path + 1); - const size_t bodyLength = eina_strbuf_length_get(body); - soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, eina_strbuf_string_steal(body), bodyLength); - eina_strbuf_free(body); - - soup_message_body_complete(message->response_body); -} - -TEST_F(EWK2UnitTestBase, ewk_view_navigation) +TEST_F(EWK2ViewTest, ewk_view_navigation) { OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); httpServer->run(serverCallbackNavigation); @@ -132,9 +313,29 @@ TEST_F(EWK2UnitTestBase, ewk_view_navigation) ASSERT_STREQ("Page2", ewk_view_title_get(webView())); ASSERT_TRUE(ewk_view_back_possible(webView())); ASSERT_FALSE(ewk_view_forward_possible(webView())); + + // Visit Page3 + ewk_view_url_set(webView(), httpServer->getURLForPath("/Page3").data()); + ASSERT_TRUE(waitUntilTitleChangedTo("Page3")); + ASSERT_STREQ("Page3", ewk_view_title_get(webView())); + ASSERT_TRUE(ewk_view_back_possible(webView())); + ASSERT_FALSE(ewk_view_forward_possible(webView())); + + Ewk_Back_Forward_List* list = ewk_view_back_forward_list_get(webView()); + ASSERT_EQ(3, ewk_back_forward_list_count(list)); + + // Navigate to Page1 + ewk_view_navigate_to(webView(), ewk_back_forward_list_item_at_index_get(list, -2)); + ASSERT_TRUE(waitUntilTitleChangedTo("Page1")); + ASSERT_STREQ("Page1", ewk_view_title_get(webView())); + + // Navigate to Page3 + ewk_view_navigate_to(webView(), ewk_back_forward_list_item_at_index_get(list, 2)); + ASSERT_TRUE(waitUntilTitleChangedTo("Page3")); + ASSERT_STREQ("Page3", ewk_view_title_get(webView())); } -TEST_F(EWK2UnitTestBase, DISABLED_ewk_view_setting_encoding_custom) +TEST_F(EWK2ViewTest, ewk_view_custom_encoding) { ASSERT_FALSE(ewk_view_custom_encoding_get(webView())); ASSERT_TRUE(ewk_view_custom_encoding_set(webView(), "UTF-8")); @@ -144,34 +345,7 @@ TEST_F(EWK2UnitTestBase, DISABLED_ewk_view_setting_encoding_custom) ASSERT_FALSE(ewk_view_custom_encoding_get(webView())); } -static void onFormAboutToBeSubmitted(void* userData, Evas_Object*, void* eventInfo) -{ - Ewk_Form_Submission_Request* request = static_cast<Ewk_Form_Submission_Request*>(eventInfo); - bool* handled = static_cast<bool*>(userData); - - ASSERT_TRUE(request); - - Eina_List* fieldNames = ewk_form_submission_request_field_names_get(request); - ASSERT_TRUE(fieldNames); - ASSERT_EQ(3, eina_list_count(fieldNames)); - void* data; - EINA_LIST_FREE(fieldNames, data) - eina_stringshare_del(static_cast<char*>(data)); - - const char* value1 = ewk_form_submission_request_field_value_get(request, "text1"); - ASSERT_STREQ("value1", value1); - eina_stringshare_del(value1); - const char* value2 = ewk_form_submission_request_field_value_get(request, "text2"); - ASSERT_STREQ("value2", value2); - eina_stringshare_del(value2); - const char* password = ewk_form_submission_request_field_value_get(request, "password"); - ASSERT_STREQ("secret", password); - eina_stringshare_del(password); - - *handled = true; -} - -TEST_F(EWK2UnitTestBase, ewk_view_form_submission_request) +TEST_F(EWK2ViewTest, ewk_view_form_submission_request) { const char* formHTML = "<html><head><script type='text/javascript'>function submitForm() { document.getElementById('myform').submit(); }</script></head>" @@ -195,14 +369,14 @@ TEST_F(EWK2UnitTestBase, ewk_view_form_submission_request) evas_object_smart_callback_del(webView(), "form,submission,request", onFormAboutToBeSubmitted); } -TEST_F(EWK2UnitTestBase, ewk_view_settings_get) +TEST_F(EWK2ViewTest, ewk_view_settings_get) { Ewk_Settings* settings = ewk_view_settings_get(webView()); ASSERT_TRUE(settings); ASSERT_EQ(settings, ewk_view_settings_get(webView())); } -TEST_F(EWK2UnitTestBase, ewk_view_theme_set) +TEST_F(EWK2ViewTest, ewk_view_theme_set) { const char* buttonHTML = "<html><body><input type='button' id='btn'>" "<script>document.title=document.getElementById('btn').clientWidth;</script>" @@ -224,7 +398,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_theme_set) EXPECT_TRUE(waitUntilTitleChangedTo("299")); // button of big button theme has 299px as padding (15 to -285) } -TEST_F(EWK2UnitTestBase, ewk_view_mouse_events_enabled) +TEST_F(EWK2ViewTest, ewk_view_mouse_events_enabled) { ASSERT_TRUE(ewk_view_mouse_events_enabled_set(webView(), EINA_TRUE)); ASSERT_TRUE(ewk_view_mouse_events_enabled_get(webView())); @@ -236,19 +410,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_mouse_events_enabled) ASSERT_FALSE(ewk_view_mouse_events_enabled_get(webView())); } -static Eina_Bool fullScreenCallback(Ewk_View_Smart_Data* smartData, Ewk_Security_Origin*) -{ - fullScreenCallbackCalled = true; - return false; -} - -static Eina_Bool fullScreenExitCallback(Ewk_View_Smart_Data* smartData) -{ - fullScreenCallbackCalled = true; - return false; -} - -TEST_F(EWK2UnitTestBase, ewk_view_full_screen_enter) +TEST_F(EWK2ViewTest, ewk_view_full_screen_enter) { const char fullscreenHTML[] = "<!doctype html><head><script>function makeFullScreen(){" @@ -267,7 +429,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_full_screen_enter) ASSERT_TRUE(fullScreenCallbackCalled); } -TEST_F(EWK2UnitTestBase, ewk_view_full_screen_exit) +TEST_F(EWK2ViewTest, ewk_view_full_screen_exit) { const char fullscreenHTML[] = "<!doctype html><head><script>function makeFullScreenAndExit(){" @@ -287,7 +449,14 @@ TEST_F(EWK2UnitTestBase, ewk_view_full_screen_exit) ASSERT_TRUE(fullScreenCallbackCalled); } -TEST_F(EWK2UnitTestBase, ewk_view_same_page_navigation) +TEST_F(EWK2ViewTest, ewk_view_cancel_full_screen_request) +{ + // FullScreenmanager should skip cancel fullscreen request if fullscreen + // mode was not set using FullScreen API. + ASSERT_FALSE(ewk_view_fullscreen_exit(webView())); +} + +TEST_F(EWK2ViewTest, ewk_view_same_page_navigation) { // Tests that same page navigation updates the page URL. String testUrl = environment->urlForResource("same_page_navigation.html").data(); @@ -298,7 +467,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_same_page_navigation) ASSERT_TRUE(waitUntilURLChangedTo(testUrl.utf8().data())); } -TEST_F(EWK2UnitTestBase, ewk_view_title_changed) +TEST_F(EWK2ViewTest, ewk_view_title_changed) { const char* titleChangedHTML = "<!doctype html><head><title>Title before changed</title></head>" @@ -322,31 +491,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_title_changed) EXPECT_STREQ("", ewk_view_title_get(webView())); } -static struct { - const char* expectedMessage; - bool called; -} alertCallbackData; - -static struct { - const char* expectedMessage; - bool result; - bool called; -} confirmCallbackData; - -static struct { - const char* expectedMessage; - const char* expectedDefaultValue; - const char* result; - bool called; -} promptCallbackData; - -static void checkAlert(Ewk_View_Smart_Data*, const char* message) -{ - alertCallbackData.called = true; - EXPECT_STREQ(message, alertCallbackData.expectedMessage); -} - -TEST_F(EWK2UnitTestBase, ewk_view_run_javascript_alert) +TEST_F(EWK2ViewTest, ewk_view_run_javascript_alert) { ewkViewClass()->run_javascript_alert = checkAlert; @@ -386,14 +531,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_run_javascript_alert) EXPECT_FALSE(alertCallbackData.called); } -static Eina_Bool checkConfirm(Ewk_View_Smart_Data*, const char* message) -{ - confirmCallbackData.called = true; - EXPECT_STREQ(message, confirmCallbackData.expectedMessage); - return confirmCallbackData.result; -} - -TEST_F(EWK2UnitTestBase, ewk_view_run_javascript_confirm) +TEST_F(EWK2ViewTest, ewk_view_run_javascript_confirm) { ewkViewClass()->run_javascript_confirm = checkConfirm; @@ -450,19 +588,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_run_javascript_confirm) EXPECT_FALSE(confirmCallbackData.called); } -static const char* checkPrompt(Ewk_View_Smart_Data*, const char* message, const char* defaultValue) -{ - promptCallbackData.called = true; - EXPECT_STREQ(message, promptCallbackData.expectedMessage); - EXPECT_STREQ(defaultValue, promptCallbackData.expectedDefaultValue); - - if (!promptCallbackData.result) - return 0; - - return eina_stringshare_add(promptCallbackData.result); -} - -TEST_F(EWK2UnitTestBase, ewk_view_run_javascript_prompt) +TEST_F(EWK2ViewTest, ewk_view_run_javascript_prompt) { static const char promptMessage[] = "Prompt message"; static const char promptResult[] = "Prompt result"; @@ -550,14 +676,21 @@ TEST_F(EWK2UnitTestBase, ewk_view_run_javascript_prompt) EXPECT_FALSE(promptCallbackData.called); } -TEST_F(EWK2UnitTestBase, ewk_view_context_get) +TEST_F(EWK2ViewTest, ewk_view_context_get) { Ewk_Context* context = ewk_view_context_get(webView()); ASSERT_TRUE(context); ASSERT_EQ(context, ewk_view_context_get(webView())); } -TEST_F(EWK2UnitTestBase, ewk_view_feed_touch_event) +TEST_F(EWK2ViewTest, ewk_view_page_group_get) +{ + Ewk_Page_Group* pageGroup = ewk_view_page_group_get(webView()); + ASSERT_TRUE(pageGroup); + ASSERT_EQ(pageGroup, ewk_view_page_group_get(webView())); +} + +TEST_F(EWK2ViewTest, ewk_view_feed_touch_event) { Eina_List* points = 0; Ewk_Touch_Point point1 = { 0, 0, 0, EVAS_TOUCH_POINT_DOWN }; @@ -583,15 +716,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_feed_touch_event) eina_list_free(points); } -static void onTextFound(void* userData, Evas_Object*, void* eventInfo) -{ - int* result = static_cast<int*>(userData); - unsigned* matchCount = static_cast<unsigned*>(eventInfo); - - *result = *matchCount; -} - -TEST_F(EWK2UnitTestBase, ewk_view_text_find) +TEST_F(EWK2ViewTest, ewk_view_text_find) { const char textFindHTML[] = "<!DOCTYPE html>" @@ -618,7 +743,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_text_find) evas_object_smart_callback_del(webView(), "text,found", onTextFound); } -TEST_F(EWK2UnitTestBase, ewk_view_text_matches_count) +TEST_F(EWK2ViewTest, ewk_view_text_matches_count) { const char textFindHTML[] = "<!DOCTYPE html>" @@ -670,7 +795,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_text_matches_count) evas_object_smart_callback_del(webView(), "text,found", onTextFound); } -TEST_F(EWK2UnitTestBase, ewk_view_touch_events_enabled) +TEST_F(EWK2ViewTest, ewk_view_touch_events_enabled) { ASSERT_FALSE(ewk_view_touch_events_enabled_get(webView())); @@ -712,12 +837,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_touch_events_enabled) ASSERT_FALSE(ewk_view_touch_events_enabled_get(webView())); } -Eina_Bool windowMoveResizeTimedOut(void* data) -{ - *static_cast<bool*>(data) = true; -} - -TEST_F(EWK2UnitTestBase, window_move_resize) +TEST_F(EWK2ViewTest, window_move_resize) { int x, y, width, height; Ecore_Evas* ee = ecore_evas_ecore_evas_get(evas_object_evas_get(webView())); @@ -737,7 +857,7 @@ TEST_F(EWK2UnitTestBase, window_move_resize) EXPECT_EQ(100, height); } -TEST_F(EWK2UnitTestBase, ewk_view_inspector) +TEST_F(EWK2ViewTest, ewk_view_inspector) { #if ENABLE(INSPECTOR) ASSERT_TRUE(ewk_view_inspector_show(webView())); @@ -748,7 +868,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_inspector) #endif } -TEST_F(EWK2UnitTestBase, ewk_view_scale) +TEST_F(EWK2ViewTest, DISABLED_ewk_view_scale) { ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); @@ -769,7 +889,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_scale) ASSERT_FLOAT_EQ(1, ewk_view_scale_get(webView())); } -TEST_F(EWK2UnitTestBase, ewk_view_pagination) +TEST_F(EWK2ViewTest, ewk_view_pagination) { ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); @@ -798,50 +918,7 @@ TEST_F(EWK2UnitTestBase, ewk_view_pagination) ASSERT_EQ(EWK_PAGINATION_MODE_UNPAGINATED, ewk_view_pagination_mode_get(webView())); } -struct VibrationCbData { - bool didReceiveVibrate; // Whether the vibration event received. - bool didReceiveCancelVibration; // Whether the cancel vibration event received. - unsigned vibrateCalledCount; // Vibrate callbacks count. - uint64_t expectedVibrationTime; // Expected vibration time. -}; - -static void onVibrate(void* userData, Evas_Object*, void* eventInfo) -{ - VibrationCbData* data = static_cast<VibrationCbData*>(userData); - uint64_t* vibrationTime = static_cast<uint64_t*>(eventInfo); - if (*vibrationTime == data->expectedVibrationTime) - data->didReceiveVibrate = true; - data->vibrateCalledCount++; -} - -static void onCancelVibration(void* userData, Evas_Object*, void*) -{ - VibrationCbData* data = static_cast<VibrationCbData*>(userData); - data->didReceiveCancelVibration = true; -} - -static void loadVibrationHTMLString(Evas_Object* webView, const char* vibrationPattern, bool waitForVibrationEvent, VibrationCbData* data) -{ - const char* content = - "<html><head><script type='text/javascript'>function vibrate() { navigator.vibrate(%s);" - " document.title = \"Loaded\"; }</script></head><body onload='vibrate()'></body></html>"; - - data->didReceiveVibrate = false; - data->didReceiveCancelVibration = false; - data->vibrateCalledCount = 0; - Eina_Strbuf* buffer = eina_strbuf_new(); - eina_strbuf_append_printf(buffer, content, vibrationPattern); - ewk_view_html_string_load(webView, eina_strbuf_string_get(buffer), 0, 0); - eina_strbuf_free(buffer); - - if (!waitForVibrationEvent) - return; - - while (!data->didReceiveVibrate && !data->didReceiveCancelVibration) - ecore_main_loop_iterate(); -} - -TEST_F(EWK2UnitTestBase, ewk_context_vibration_client_callbacks_set) +TEST_F(EWK2ViewTest, ewk_context_vibration_client_callbacks_set) { VibrationCbData data = { false, false, 0, 5000 }; evas_object_smart_callback_add(webView(), "vibrate", onVibrate, &data); @@ -881,3 +958,86 @@ TEST_F(EWK2UnitTestBase, ewk_context_vibration_client_callbacks_set) ASSERT_FALSE(data.didReceiveCancelVibration); } +TEST_F(EWK2ViewTest, ewk_view_contents_size_changed) +{ + const char contentsSizeHTMLPortrait[] = + "<!DOCTYPE html>" + "<body style=\"margin:0px;width:2000px;height:3000px\"></body>"; + const char contentsSizeHTMLLandscape[] = + "<!DOCTYPE html>" + "<body style=\"margin:0px;width:3000px;height:2000px\"></body>"; + + bool sizeChanged = false; + evas_object_smart_callback_add(webView(), "contents,size,changed", onContentsSizeChangedPortrait, &sizeChanged); + ewk_view_html_string_load(webView(), contentsSizeHTMLPortrait, 0, 0); + while (!sizeChanged) + ecore_main_loop_iterate(); + evas_object_smart_callback_del(webView(), "contents,size,changed", onContentsSizeChangedPortrait); + + evas_object_smart_callback_add(webView(), "contents,size,changed", onContentsSizeChangedLandscape, &sizeChanged); + ewk_view_device_pixel_ratio_set(webView(), 2); + ewk_view_html_string_load(webView(), contentsSizeHTMLLandscape, 0, 0); + sizeChanged = false; + while (!sizeChanged) + ecore_main_loop_iterate(); + evas_object_smart_callback_del(webView(), "contents,size,changed", onContentsSizeChangedLandscape); + + evas_object_smart_callback_add(webView(), "contents,size,changed", onContentsSizeChangedPortrait, &sizeChanged); + ewk_view_scale_set(webView(), 3, 0, 0); + ewk_view_html_string_load(webView(), contentsSizeHTMLPortrait, 0, 0); + sizeChanged = false; + while (!sizeChanged) + ecore_main_loop_iterate(); + evas_object_smart_callback_del(webView(), "contents,size,changed", onContentsSizeChangedPortrait); +} + +TEST_F(EWK2ViewTest, ewk_view_page_contents_get) +{ + const char content[] = "<p>Simple HTML</p>"; + ewk_view_html_string_load(webView(), content, 0, 0); + waitUntilLoadFinished(); + + ASSERT_TRUE(ewk_view_page_contents_get(webView(), EWK_PAGE_CONTENTS_TYPE_MHTML, PageContentsAsMHTMLCallback, 0)); + while (!obtainedPageContents) + ecore_main_loop_iterate(); + + obtainedPageContents = false; + ASSERT_TRUE(ewk_view_page_contents_get(webView(), EWK_PAGE_CONTENTS_TYPE_STRING, PageContentsAsStringCallback, 0)); + while (!obtainedPageContents) + ecore_main_loop_iterate(); +} + +TEST_F(EWK2ViewTest, ewk_view_source_mode) +{ + const char indexHTML[] = "<html><body>Test Web View Mode<script>document.title=window.document.body.innerText;</script></body></html>"; + const char contents[] = "Test Web View Mode"; + + // Default source mode is false. + EXPECT_FALSE(ewk_view_source_mode_get(webView())); + + // Load web contents of the web page. + ewk_view_html_string_load(webView(), indexHTML, 0, 0); + EXPECT_TRUE(waitUntilTitleChangedTo(contents)); + + EXPECT_TRUE(ewk_view_source_mode_set(webView(), true)); + EXPECT_TRUE(ewk_view_source_mode_get(webView())); + + // TODO: Add a test case when the source mode is true. + // But it needs a way to retrieve the body contents to compare the loaded contents + // such as excuting the JavaScript, 'window.document.body.innerText'. + // https://bugs.webkit.org/show_bug.cgi?id=101904. +} + +TEST_F(EWK2ViewTest, ewk_view_user_agent) +{ + const char* defaultUserAgent = eina_stringshare_add(ewk_view_user_agent_get(webView())); + const char customUserAgent[] = "Foo"; + + ASSERT_TRUE(ewk_view_user_agent_set(webView(), customUserAgent)); + ASSERT_STREQ(customUserAgent, ewk_view_user_agent_get(webView())); + + // Set the default user agent string. + ASSERT_TRUE(ewk_view_user_agent_set(webView(), 0)); + ASSERT_STREQ(defaultUserAgent, ewk_view_user_agent_get(webView())); + eina_stringshare_del(defaultUserAgent); +} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_window_features.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_window_features.cpp index 5fb0e5201..24ca9a4ae 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_window_features.cpp +++ b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_window_features.cpp @@ -33,38 +33,62 @@ using namespace EWK2UnitTest; using namespace WebCore; -static Evas_Object* createDefaultWindow(Ewk_View_Smart_Data* smartData, const Ewk_Window_Features* windowFeatures) -{ - // default values of WebCore:WindowFeatures() - // - menuBarVisible(true) - // - statusBarVisible(true) - // - toolBarVisible(true) - // - locationBarVisible(true) - // - scrollbarsVisible(true) - // - resizable(true) - // - fullscreen(false) - - EXPECT_TRUE(ewk_window_features_toolbar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_statusbar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_scrollbars_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_menubar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_locationbar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_resizable_get(windowFeatures)); - - EXPECT_FALSE(ewk_window_features_fullscreen_get(windowFeatures)); - - int x, y, width, height; - ewk_window_features_geometry_get(windowFeatures, &x, &y, &width, &height); - - EXPECT_EQ(0, x); - EXPECT_EQ(0, y); - EXPECT_EQ(0, width); - EXPECT_EQ(0, height); - - return 0; -} - -TEST_F(EWK2UnitTestBase, ewk_window_features_default_property_get) +class EWK2WindowFeaturesTest : public EWK2UnitTestBase { +public: + static Evas_Object* createDefaultWindow(Ewk_View_Smart_Data* smartData, const char*, const Ewk_Window_Features* windowFeatures) + { + // default values of WebCore:WindowFeatures() + // - menuBarVisible(true) + // - statusBarVisible(true) + // - toolBarVisible(true) + // - locationBarVisible(true) + // - scrollbarsVisible(true) + // - resizable(true) + // - fullscreen(false) + + EXPECT_TRUE(ewk_window_features_toolbar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_statusbar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_scrollbars_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_menubar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_locationbar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_resizable_get(windowFeatures)); + + EXPECT_FALSE(ewk_window_features_fullscreen_get(windowFeatures)); + + int x, y, width, height; + ewk_window_features_geometry_get(windowFeatures, &x, &y, &width, &height); + + EXPECT_EQ(0, x); + EXPECT_EQ(0, y); + EXPECT_EQ(0, width); + EXPECT_EQ(0, height); + + return 0; + } + + static Evas_Object* createWindow(Ewk_View_Smart_Data *smartData, const char*, const Ewk_Window_Features *windowFeatures) + { + EXPECT_FALSE(ewk_window_features_toolbar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_statusbar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_scrollbars_visible_get(windowFeatures)); + EXPECT_FALSE(ewk_window_features_menubar_visible_get(windowFeatures)); + EXPECT_FALSE(ewk_window_features_locationbar_visible_get(windowFeatures)); + EXPECT_TRUE(ewk_window_features_resizable_get(windowFeatures)); + EXPECT_FALSE(ewk_window_features_fullscreen_get(windowFeatures)); + + int x, y, width, height; + ewk_window_features_geometry_get(windowFeatures, &x, &y, &width, &height); + + EXPECT_EQ(100, x); + EXPECT_EQ(150, y); + EXPECT_EQ(400, width); + EXPECT_EQ(400, height); + + return 0; + } +}; + +TEST_F(EWK2WindowFeaturesTest, ewk_window_features_default_property_get) { Evas_Object* view = webView(); @@ -76,28 +100,7 @@ TEST_F(EWK2UnitTestBase, ewk_window_features_default_property_get) ASSERT_TRUE(waitUntilLoadFinished()); } -static Evas_Object* createWindow(Ewk_View_Smart_Data *smartData, const Ewk_Window_Features *windowFeatures) -{ - EXPECT_FALSE(ewk_window_features_toolbar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_statusbar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_scrollbars_visible_get(windowFeatures)); - EXPECT_FALSE(ewk_window_features_menubar_visible_get(windowFeatures)); - EXPECT_FALSE(ewk_window_features_locationbar_visible_get(windowFeatures)); - EXPECT_TRUE(ewk_window_features_resizable_get(windowFeatures)); - EXPECT_FALSE(ewk_window_features_fullscreen_get(windowFeatures)); - - int x, y, width, height; - ewk_window_features_geometry_get(windowFeatures, &x, &y, &width, &height); - - EXPECT_EQ(100, x); - EXPECT_EQ(150, y); - EXPECT_EQ(400, width); - EXPECT_EQ(400, height); - - return 0; -} - -TEST_F(EWK2UnitTestBase, ewk_window_features_property_get) +TEST_F(EWK2WindowFeaturesTest, ewk_window_features_property_get) { Evas_Object* view = webView(); diff --git a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp b/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp index 248d07284..bd214f3b6 100644 --- a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp @@ -212,6 +212,8 @@ void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool { if (wasEventHandled) return; + if (event.isFakeEventForComposition()) + return; WebKitWebViewBase* webkitWebViewBase = WEBKIT_WEB_VIEW_BASE(m_viewWidget); webkitWebViewBaseForwardNextKeyEvent(webkitWebViewBase); @@ -229,7 +231,7 @@ PassRefPtr<WebContextMenuProxy> PageClientImpl::createContextMenuProxy(WebPagePr } #if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorChooserProxy> PageClientImpl::createColorChooserProxy(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) +PassRefPtr<WebColorPicker> PageClientImpl::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) { notImplemented(); return 0; @@ -258,47 +260,24 @@ void PageClientImpl::updateAcceleratedCompositingMode(const LayerTreeContext&) } #endif // USE(ACCELERATED_COMPOSITING) -void PageClientImpl::didCommitLoadForMainFrame(bool useCustomRepresentation) -{ -} - -void PageClientImpl::didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&) -{ -} - -double PageClientImpl::customRepresentationZoomFactor() -{ - notImplemented(); - return 0; -} - -void PageClientImpl::setCustomRepresentationZoomFactor(double) -{ - notImplemented(); -} - void PageClientImpl::pageClosed() { notImplemented(); } -void PageClientImpl::didChangeScrollbarsForMainFrame() const -{ -} - -void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&) +void PageClientImpl::preferencesDidChange() { notImplemented(); } -void PageClientImpl::findStringInCustomRepresentation(const String&, FindOptions, unsigned) +void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&) { notImplemented(); } -void PageClientImpl::countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned) +void PageClientImpl::updateTextInputState() { - notImplemented(); + webkitWebViewBaseUpdateTextInputState(WEBKIT_WEB_VIEW_BASE(m_viewWidget)); } void PageClientImpl::startDrag(const WebCore::DragData& dragData, PassRefPtr<ShareableBitmap> dragImage) diff --git a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h b/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h index d9b34c52b..a7469cdbf 100644 --- a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h +++ b/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h @@ -56,6 +56,7 @@ private: virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy(); virtual void setViewNeedsDisplay(const WebCore::IntRect&); virtual void displayView(); + virtual bool canScrollView() { return false; } virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); virtual WebCore::IntSize viewSize(); virtual bool isViewWindowActive(); @@ -65,6 +66,7 @@ private: virtual void processDidCrash(); virtual void didRelaunchProcess(); virtual void pageClosed(); + virtual void preferencesDidChange(); virtual void takeFocus(bool direction); virtual void toolTipChanged(const WTF::String&, const WTF::String&); virtual void setCursor(const WebCore::Cursor&); @@ -82,14 +84,12 @@ private: virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*); virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); #if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorChooserProxy> createColorChooserProxy(WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&); + virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&); #endif virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate); - virtual void didChangeScrollbarsForMainFrame() const; virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); virtual void getEditorCommandsForKeyEvent(const NativeWebKeyboardEvent&, const AtomicString&, Vector<WTF::String>&); - virtual void findStringInCustomRepresentation(const String&, FindOptions, unsigned); - virtual void countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned); + virtual void updateTextInputState(); virtual void startDrag(const WebCore::DragData&, PassRefPtr<ShareableBitmap> dragImage); #if USE(ACCELERATED_COMPOSITING) @@ -98,11 +98,6 @@ private: virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); #endif - virtual void didCommitLoadForMainFrame(bool useCustomRepresentation); - virtual void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&); - virtual double customRepresentationZoomFactor(); - virtual void setCustomRepresentationZoomFactor(double); - virtual void handleDownloadRequest(DownloadProxy*); // Members of PageClientImpl class diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKit2GtkAuthenticationDialog.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKit2GtkAuthenticationDialog.cpp deleted file mode 100644 index 13efe8c68..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKit2GtkAuthenticationDialog.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2012 Igalia S.L. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "WebKit2GtkAuthenticationDialog.h" - -#include "AuthenticationChallengeProxy.h" -#include "AuthenticationDecisionListener.h" -#include "WebCredential.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" -#include <gtk/gtk.h> - -namespace WebKit { - -// This is necessary because GtkEventBox does not draw a background by default, -// but we want it to have a normal GtkWindow background. -static gboolean drawSignal(GtkWidget* widget, cairo_t* cr, GtkStyleContext* styleContext) -{ - gtk_render_background(styleContext, cr, 0, 0, - gtk_widget_get_allocated_width(widget), gtk_widget_get_allocated_height(widget)); - return FALSE; -} - -WebKit2GtkAuthenticationDialog::WebKit2GtkAuthenticationDialog(AuthenticationChallengeProxy* authenticationChallenge) - : GtkAuthenticationDialog(authenticationChallenge->core()) - , m_authenticationChallenge(authenticationChallenge) - , m_styleContext(adoptGRef(gtk_style_context_new())) -{ - m_dialog = gtk_event_box_new(); - - GtkWidget* frame = gtk_frame_new(0); - gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); - gtk_container_add(GTK_CONTAINER(m_dialog), frame); - createContentsInContainer(frame); - - gtk_style_context_add_class(m_styleContext.get(), GTK_STYLE_CLASS_BACKGROUND); - GtkWidgetPath* path = gtk_widget_path_new(); - gtk_widget_path_append_type(path, GTK_TYPE_WINDOW); - gtk_style_context_set_path(m_styleContext.get(), path); - gtk_widget_path_free(path); - - g_signal_connect(m_dialog, "draw", G_CALLBACK(drawSignal), m_styleContext.get()); -} - -void WebKit2GtkAuthenticationDialog::authenticate(const WebCore::Credential& credential) -{ - RefPtr<WebCredential> webCredential = WebCredential::create(credential); - m_authenticationChallenge->listener()->useCredential(webCredential.get()); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.cpp new file mode 100644 index 000000000..0699da7ee --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "WebKitAuthenticationDialog.h" + +#include "AuthenticationDecisionListener.h" +#include "WebCredential.h" +#include "WebKitPrivate.h" + +using namespace WebKit; + +struct _WebKitAuthenticationDialogPrivate { + RefPtr<AuthenticationChallengeProxy> authenticationChallenge; + + GtkWidget* authWidget; + GtkWidget* defaultButton; + GRefPtr<GtkStyleContext> styleContext; +}; + +WEBKIT_DEFINE_TYPE(WebKitAuthenticationDialog, webkit_authentication_dialog, GTK_TYPE_EVENT_BOX) + +static void webkitAuthenticationDialogAuthenticate(WebKitAuthenticationDialog* authDialog, WebCredential* credential) +{ + WebKitAuthenticationDialogPrivate* priv = authDialog->priv; + priv->authenticationChallenge->listener()->useCredential(credential); + gtk_widget_destroy(GTK_WIDGET(authDialog)); +} + +static void okButtonClicked(GtkButton*, WebKitAuthenticationDialog* authDialog) +{ + WebKitAuthenticationDialogPrivate* priv = authDialog->priv; + RefPtr<WebCredential> webCredential = WebCredential::create(webkitAuthenticationWidgetCreateCredential(WEBKIT_AUTHENTICATION_WIDGET(priv->authWidget))); + webkitAuthenticationDialogAuthenticate(authDialog, webCredential.get()); +} + +static void cancelButtonClicked(GtkButton*, WebKitAuthenticationDialog* authDialog) +{ + webkitAuthenticationDialogAuthenticate(authDialog, 0); +} + +static void webkitAuthenticationDialogInitialize(WebKitAuthenticationDialog* authDialog, CredentialStorageMode credentialStorageMode) +{ + GtkWidget* frame = gtk_frame_new(0); + gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN); + + GtkWidget* vBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_set_border_width(GTK_CONTAINER(vBox), 5); + + GtkWidget* buttonBox = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL); + gtk_button_box_set_layout(GTK_BUTTON_BOX(buttonBox), GTK_BUTTONBOX_END); + gtk_container_set_border_width(GTK_CONTAINER(buttonBox), 5); + gtk_box_set_spacing(GTK_BOX(buttonBox), 6); + + GtkWidget* button = gtk_button_new_from_stock(GTK_STOCK_CANCEL); + g_signal_connect(button, "clicked", G_CALLBACK(cancelButtonClicked), authDialog); + gtk_box_pack_end(GTK_BOX(buttonBox), button, FALSE, TRUE, 0); + gtk_widget_show(button); + + button = gtk_button_new_from_stock(GTK_STOCK_OK); + authDialog->priv->defaultButton = button; + g_signal_connect(button, "clicked", G_CALLBACK(okButtonClicked), authDialog); + gtk_widget_set_can_default(button, TRUE); + gtk_box_pack_end(GTK_BOX(buttonBox), button, FALSE, TRUE, 0); + gtk_widget_show(button); + + authDialog->priv->authWidget = webkitAuthenticationWidgetNew(authDialog->priv->authenticationChallenge->core(), credentialStorageMode); + gtk_box_pack_start(GTK_BOX(vBox), authDialog->priv->authWidget, TRUE, TRUE, 0); + gtk_widget_show(authDialog->priv->authWidget); + + gtk_box_pack_end(GTK_BOX(vBox), buttonBox, FALSE, TRUE, 0); + gtk_widget_show(buttonBox); + + gtk_container_add(GTK_CONTAINER(frame), vBox); + gtk_widget_show(vBox); + + gtk_container_add(GTK_CONTAINER(authDialog), frame); + gtk_widget_show(frame); +} + +static gboolean webkitAuthenticationDialogDraw(GtkWidget* widget, cairo_t* cr) +{ + WebKitAuthenticationDialogPrivate* priv = WEBKIT_AUTHENTICATION_DIALOG(widget)->priv; + + gtk_style_context_save(priv->styleContext.get()); + gtk_style_context_add_class(priv->styleContext.get(), GTK_STYLE_CLASS_BACKGROUND); + gtk_render_background(priv->styleContext.get(), cr, 0, 0, gtk_widget_get_allocated_width(widget), gtk_widget_get_allocated_height(widget)); + gtk_style_context_restore(priv->styleContext.get()); + + GTK_WIDGET_CLASS(webkit_authentication_dialog_parent_class)->draw(widget, cr); + + return FALSE; +} + +static void webkitAuthenticationDialogMap(GtkWidget* widget) +{ + WebKitAuthenticationDialogPrivate* priv = WEBKIT_AUTHENTICATION_DIALOG(widget)->priv; + gtk_widget_grab_default(priv->defaultButton); + + GTK_WIDGET_CLASS(webkit_authentication_dialog_parent_class)->map(widget); +} + +static void webkitAuthenticationDialogConstructed(GObject* object) +{ + G_OBJECT_CLASS(webkit_authentication_dialog_parent_class)->constructed(object); + + WebKitAuthenticationDialogPrivate* priv = WEBKIT_AUTHENTICATION_DIALOG(object)->priv; + priv->styleContext = adoptGRef(gtk_style_context_new()); + GtkWidgetPath* path = gtk_widget_path_new(); + gtk_widget_path_append_type(path, GTK_TYPE_WINDOW); + gtk_style_context_set_path(priv->styleContext.get(), path); + gtk_widget_path_free(path); +} + +static void webkit_authentication_dialog_class_init(WebKitAuthenticationDialogClass* klass) +{ + GObjectClass* objectClass = G_OBJECT_CLASS(klass); + objectClass->constructed = webkitAuthenticationDialogConstructed; + + GtkWidgetClass* widgetClass = GTK_WIDGET_CLASS(klass); + widgetClass->draw = webkitAuthenticationDialogDraw; + widgetClass->map = webkitAuthenticationDialogMap; +} + +GtkWidget* webkitAuthenticationDialogNew(AuthenticationChallengeProxy* authenticationChallenge, CredentialStorageMode mode) +{ + WebKitAuthenticationDialog* authDialog = WEBKIT_AUTHENTICATION_DIALOG(g_object_new(WEBKIT_TYPE_AUTHENTICATION_DIALOG, NULL)); + authDialog->priv->authenticationChallenge = authenticationChallenge; + webkitAuthenticationDialogInitialize(authDialog, mode); + return GTK_WIDGET(authDialog); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.h b/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.h new file mode 100644 index 000000000..7d4de2a6d --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifndef WebKitAuthenticationDialog_h +#define WebKitAuthenticationDialog_h + +#include "AuthenticationChallengeProxy.h" +#include "WebKitAuthenticationWidget.h" +#include <gtk/gtk.h> + +G_BEGIN_DECLS + +#define WEBKIT_TYPE_AUTHENTICATION_DIALOG (webkit_authentication_dialog_get_type()) +#define WEBKIT_AUTHENTICATION_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_AUTHENTICATION_DIALOG, WebKitAuthenticationDialog)) +#define WEBKIT_IS_AUTHENTICATION_DIALOG(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_AUTHENTICATION_DIALOG)) +#define WEBKIT_AUTHENTICATION_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_AUTHENTICATION_DIALOG, WebKitAuthenticationDialogClass)) +#define WEBKIT_IS_AUTHENTICATION_DIALOG_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_AUTHENTICATION_DIALOG)) +#define WEBKIT_AUTHENTICATION_DIALOG_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_AUTHENTICATION_DIALOG, WebKitAuthenticationDialogClass)) + +typedef struct _WebKitAuthenticationDialog WebKitAuthenticationDialog; +typedef struct _WebKitAuthenticationDialogClass WebKitAuthenticationDialogClass; +typedef struct _WebKitAuthenticationDialogPrivate WebKitAuthenticationDialogPrivate; + +struct _WebKitAuthenticationDialog { + GtkEventBox parent; + + WebKitAuthenticationDialogPrivate* priv; +}; + +struct _WebKitAuthenticationDialogClass { + GtkEventBoxClass parentClass; +}; + +GType webkit_authentication_dialog_get_type(); +GtkWidget* webkitAuthenticationDialogNew(WebKit::AuthenticationChallengeProxy*, CredentialStorageMode); + +G_END_DECLS + +#endif // WebKitAuthenticationDialog_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.cpp index fbf302aa8..47aaa4cc8 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.cpp @@ -252,7 +252,8 @@ GList* webkit_back_forward_list_get_back_list_with_limit(WebKitBackForwardList* g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); WebKitBackForwardListPrivate* priv = backForwardList->priv; - return webkitBackForwardListCreateList(backForwardList, priv->backForwardItems->backListAsImmutableArrayWithLimit(limit).leakRef()); + RefPtr<ImmutableArray> immutableArray = priv->backForwardItems->backListAsImmutableArrayWithLimit(limit); + return webkitBackForwardListCreateList(backForwardList, immutableArray.get()); } /** @@ -282,5 +283,6 @@ GList* webkit_back_forward_list_get_forward_list_with_limit(WebKitBackForwardLis g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); WebKitBackForwardListPrivate* priv = backForwardList->priv; - return webkitBackForwardListCreateList(backForwardList, priv->backForwardItems->forwardListAsImmutableArrayWithLimit(limit).leakRef()); + RefPtr<ImmutableArray> immutableArray = priv->backForwardItems->forwardListAsImmutableArrayWithLimit(limit); + return webkitBackForwardListCreateList(backForwardList, immutableArray.get()); } diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.h b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.h index 4cdb089e4..6fbd42ab0 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.h @@ -49,6 +49,11 @@ struct _WebKitBackForwardList { struct _WebKitBackForwardListClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp index 53fd1c8c2..ae18b05ec 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp @@ -28,6 +28,17 @@ using namespace WebKit; +/** + * SECTION: WebKitBackForwardListItem + * @Short_description: One item of the #WebKitBackForwardList + * @Title: WebKitBackForwardListItem + * @See_also: #WebKitBackForwardList + * + * A history item is part of the #WebKitBackForwardList and consists + * out of a title and a URI. + * + */ + struct _WebKitBackForwardListItemPrivate { RefPtr<WebBackForwardListItem> webListItem; CString uri; diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h index 43fcc7f8f..5090e516c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h @@ -48,6 +48,11 @@ struct _WebKitBackForwardListItem { struct _WebKitBackForwardListItemClass { GInitiallyUnownedClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp index 46ce958ee..0ab6edba6 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp @@ -28,6 +28,25 @@ using namespace WebKit; using namespace WebCore; +/** + * SECTION: WebKitContextMenu + * @Short_description: Represents the context menu in a #WebKitWebView + * @Title: WebKitContextMenu + * + * #WebKitContextMenu represents a context menu containing + * #WebKitContextMenuItem<!-- -->s in a #WebKitWebView. + * + * When a #WebKitWebView is about to display the context menu, it + * emits the #WebKitWebView::context-menu signal, which has the + * #WebKitContextMenu as an argument. You can modify it, adding new + * submenus that you can create with webkit_context_menu_new(), adding + * new #WebKitContextMenuItem<!-- -->s with + * webkit_context_menu_prepend(), webkit_context_menu_append() or + * webkit_context_menu_insert(), maybe after having removed the + * existing ones with webkit_context_menu_remove_all(). + * + */ + struct _WebKitContextMenuPrivate { GList* items; WebKitContextMenuItem* parentItem; diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h index 9df3f4c11..22f4bef29 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h @@ -27,6 +27,7 @@ #include <glib-object.h> #include <webkit2/WebKitContextMenuItem.h> #include <webkit2/WebKitDefines.h> +#include <webkit2/WebKitForwardDeclarations.h> G_BEGIN_DECLS @@ -48,6 +49,11 @@ struct _WebKitContextMenu { struct _WebKitContextMenuClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp index 42f90b871..f50c52aea 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp @@ -40,6 +40,8 @@ void attachContextMenuClientToView(WebKitWebView* webView) 0, // customContextMenuItemSelected 0, // contextMenuDismissed getContextMenuFromProposedMenu, + 0, // showContextMenu + 0, // hideContextMenu }; WKPageRef wkPage = toAPI(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView))); WKPageSetPageContextMenuClient(wkPage, &wkContextMenuClient); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp index aa89b990b..d98cc548e 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp @@ -37,6 +37,19 @@ using namespace WebKit; using namespace WebCore; +/** + * SECTION: WebKitContextMenuItem + * @Short_description: One item of the #WebKitContextMenu + * @Title: WebKitContextMenuItem + * + * The #WebKitContextMenu is composed of #WebKitContextMenuItem<!-- + * -->s. These items can be created from a #GtkAction, from a + * #WebKitContextMenuAction or from a #WebKitContextMenuAction and a + * label. These #WebKitContextMenuAction<!-- -->s denote stock actions + * for the items. You can also create separators and submenus. + * + */ + struct _WebKitContextMenuItemPrivate { ~_WebKitContextMenuItemPrivate() { diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h index 52d912843..75d60d7d6 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h @@ -28,6 +28,7 @@ #include <webkit2/WebKitDefines.h> #include <webkit2/WebKitContextMenu.h> #include <webkit2/WebKitContextMenuActions.h> +#include <webkit2/WebKitForwardDeclarations.h> G_BEGIN_DECLS @@ -49,6 +50,11 @@ struct _WebKitContextMenuItem { struct _WebKitContextMenuItemClass { GInitiallyUnownedClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp index 29a37ebd3..daf79fe3b 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp @@ -29,6 +29,22 @@ using namespace WebKit; +/** + * SECTION: WebKitCookieManager + * @Short_description: Defines how to handle cookies in a #WebKitWebContext + * @Title: WebKitCookieManager + * + * The #WebKitCookieManager defines how to handle cookies in a + * #WebKitWebContext. Get it from the context with + * webkit_web_context_get_cookie_manager(), and use it to set where to + * store cookies, with webkit_cookie_manager_set_persistent_storage(), + * to get the list of domains with cookies, with + * webkit_cookie_manager_get_domains_with_cookies(), or to set the + * acceptance policy, with webkit_cookie_manager_get_accept_policy() + * (among other actions). + * + */ + enum { CHANGED, @@ -133,22 +149,10 @@ void webkit_cookie_manager_set_accept_policy(WebKitCookieManager* manager, WebKi manager->priv->webCookieManager->setHTTPCookieAcceptPolicy(policy); } -struct GetAcceptPolicyAsyncData { - WKHTTPCookieAcceptPolicy policy; - GRefPtr<GCancellable> cancellable; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(GetAcceptPolicyAsyncData) - static void webkitCookieManagerGetAcceptPolicyCallback(WKHTTPCookieAcceptPolicy policy, WKErrorRef, void* context) { - GRefPtr<GSimpleAsyncResult> result = adoptGRef(G_SIMPLE_ASYNC_RESULT(context)); - GetAcceptPolicyAsyncData* data = static_cast<GetAcceptPolicyAsyncData*>(g_simple_async_result_get_op_res_gpointer(result.get())); - GError* error = 0; - if (g_cancellable_set_error_if_cancelled(data->cancellable.get(), &error)) - g_simple_async_result_take_error(result.get(), error); - else - data->policy = policy; - g_simple_async_result_complete(result.get()); + GRefPtr<GTask> task = adoptGRef(G_TASK(context)); + g_task_return_int(task.get(), policy); } /** @@ -167,13 +171,8 @@ void webkit_cookie_manager_get_accept_policy(WebKitCookieManager* manager, GCanc { g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(manager), callback, userData, - reinterpret_cast<gpointer>(webkit_cookie_manager_get_accept_policy)); - GetAcceptPolicyAsyncData* data = createGetAcceptPolicyAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyGetAcceptPolicyAsyncData)); - - manager->priv->webCookieManager->getHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyCallback::create(result, webkitCookieManagerGetAcceptPolicyCallback)); + GTask* task = g_task_new(manager, cancellable, callback, userData); + manager->priv->webCookieManager->getHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyCallback::create(task, webkitCookieManagerGetAcceptPolicyCallback)); } /** @@ -189,44 +188,29 @@ void webkit_cookie_manager_get_accept_policy(WebKitCookieManager* manager, GCanc WebKitCookieAcceptPolicy webkit_cookie_manager_get_accept_policy_finish(WebKitCookieManager* manager, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager), WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY); - - GSimpleAsyncResult* simpleResult = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simpleResult) == webkit_cookie_manager_get_accept_policy); + g_return_val_if_fail(g_task_is_valid(result, manager), WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY); - if (g_simple_async_result_propagate_error(simpleResult, error)) - return WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY; - - GetAcceptPolicyAsyncData* data = static_cast<GetAcceptPolicyAsyncData*>(g_simple_async_result_get_op_res_gpointer(simpleResult)); - return static_cast<WebKitCookieAcceptPolicy>(data->policy); + gssize returnValue = g_task_propagate_int(G_TASK(result), error); + return returnValue == -1 ? WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY : static_cast<WebKitCookieAcceptPolicy>(returnValue); } -struct GetDomainsWithCookiesAsyncData { - GRefPtr<GPtrArray> domains; - GRefPtr<GCancellable> cancellable; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(GetDomainsWithCookiesAsyncData) - static void webkitCookieManagerGetDomainsWithCookiesCallback(WKArrayRef wkDomains, WKErrorRef, void* context) { - GRefPtr<GSimpleAsyncResult> result = adoptGRef(G_SIMPLE_ASYNC_RESULT(context)); - GetDomainsWithCookiesAsyncData* data = static_cast<GetDomainsWithCookiesAsyncData*>(g_simple_async_result_get_op_res_gpointer(result.get())); - GError* error = 0; - if (g_cancellable_set_error_if_cancelled(data->cancellable.get(), &error)) - g_simple_async_result_take_error(result.get(), error); - else { - ImmutableArray* domains = toImpl(wkDomains); - data->domains = adoptGRef(g_ptr_array_new_with_free_func(g_free)); - for (size_t i = 0; i < domains->size(); ++i) { - WebString* domainString = static_cast<WebString*>(domains->at(i)); - String domain = domainString->string(); - if (domain.isEmpty()) - continue; - g_ptr_array_add(data->domains.get(), g_strdup(domain.utf8().data())); - } - g_ptr_array_add(data->domains.get(), 0); + GRefPtr<GTask> task = adoptGRef(G_TASK(context)); + if (g_task_return_error_if_cancelled(task.get())) + return; + + ImmutableArray* domains = toImpl(wkDomains); + GPtrArray* returnValue = g_ptr_array_sized_new(domains->size()); + for (size_t i = 0; i < domains->size(); ++i) { + WebString* domainString = static_cast<WebString*>(domains->at(i)); + String domain = domainString->string(); + if (domain.isEmpty()) + continue; + g_ptr_array_add(returnValue, g_strdup(domain.utf8().data())); } - g_simple_async_result_complete(result.get()); + g_ptr_array_add(returnValue, 0); + g_task_return_pointer(task.get(), g_ptr_array_free(returnValue, FALSE), reinterpret_cast<GDestroyNotify>(g_strfreev)); } /** @@ -245,12 +229,8 @@ void webkit_cookie_manager_get_domains_with_cookies(WebKitCookieManager* manager { g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(manager), callback, userData, - reinterpret_cast<gpointer>(webkit_cookie_manager_get_domains_with_cookies)); - GetDomainsWithCookiesAsyncData* data = createGetDomainsWithCookiesAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyGetDomainsWithCookiesAsyncData)); - manager->priv->webCookieManager->getHostnamesWithCookies(ArrayCallback::create(result, webkitCookieManagerGetDomainsWithCookiesCallback)); + GTask* task = g_task_new(manager, cancellable, callback, userData); + manager->priv->webCookieManager->getHostnamesWithCookies(ArrayCallback::create(task, webkitCookieManagerGetDomainsWithCookiesCallback)); } /** @@ -269,16 +249,9 @@ void webkit_cookie_manager_get_domains_with_cookies(WebKitCookieManager* manager gchar** webkit_cookie_manager_get_domains_with_cookies_finish(WebKitCookieManager* manager, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager), 0); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), 0); - - GSimpleAsyncResult* simpleResult = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simpleResult) == webkit_cookie_manager_get_domains_with_cookies); - - if (g_simple_async_result_propagate_error(simpleResult, error)) - return 0; + g_return_val_if_fail(g_task_is_valid(result, manager), 0); - GetDomainsWithCookiesAsyncData* data = static_cast<GetDomainsWithCookiesAsyncData*>(g_simple_async_result_get_op_res_gpointer(simpleResult)); - return reinterpret_cast<char**>(g_ptr_array_free(data->domains.leakRef(), FALSE)); + return reinterpret_cast<char**>(g_task_propagate_pointer(G_TASK(result), error)); } /** diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h index 28dfe28ef..f25f1a2b0 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h @@ -77,6 +77,11 @@ struct _WebKitCookieManager { struct _WebKitCookieManagerClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h b/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h index 733bf884c..8b637652b 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h @@ -23,7 +23,7 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) +#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) && !defined(__WEBKIT_WEB_EXTENSION_H_INSIDE__) #error "Only <webkit2/webkit2.h> can be included directly." #endif @@ -32,12 +32,6 @@ #include <glib.h> -typedef struct _WebKitPrintOperation WebKitPrintOperation; -typedef struct _WebKitFindController WebKitFindController; -typedef struct _WebKitWebView WebKitWebView; -typedef struct _WebKitContextMenu WebKitContextMenu; -typedef struct _WebKitContextMenuItem WebKitContextMenuItem; - #ifdef G_OS_WIN32 # ifdef BUILDING_WEBKIT # define WEBKIT_API __declspec(dllexport) diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp index 245f1a61b..e9524c209 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp @@ -34,6 +34,19 @@ using namespace WebKit; using namespace WebCore; +/** + * SECTION: WebKitDownload + * @Short_description: Object used to communicate with the application when downloading + * @Title: WebKitDownload + * + * #WebKitDownload carries information about a download request and + * response, including a #WebKitURIRequest and a #WebKitURIResponse + * objects. The application may use this object to control the + * download process, or to simply figure out what is to be downloaded, + * and handle the download process itself. + * + */ + enum { RECEIVED_DATA, FINISHED, @@ -101,7 +114,12 @@ static gboolean webkitDownloadDecideDestination(WebKitDownload* download, const return FALSE; GOwnPtr<char> filename(g_strdelimit(g_strdup(suggestedFilename), G_DIR_SEPARATOR_S, '_')); - GOwnPtr<char> destination(g_build_filename(g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD), filename.get(), NULL)); + const gchar *downloadsDir = g_get_user_special_dir(G_USER_DIRECTORY_DOWNLOAD); + if (!downloadsDir) { + // If we don't have XDG user dirs info, set just to HOME. + downloadsDir = g_get_home_dir(); + } + GOwnPtr<char> destination(g_build_filename(downloadsDir, filename.get(), NULL)); GOwnPtr<char> destinationURI(g_filename_to_uri(destination.get(), 0, 0)); download->priv->destinationURI = destinationURI.get(); g_object_notify(G_OBJECT(download), "destination"); @@ -263,6 +281,13 @@ WebKitDownload* webkitDownloadCreate(DownloadProxy* downloadProxy) return download; } +WebKitDownload* webkitDownloadCreateForRequest(DownloadProxy* downloadProxy, const ResourceRequest& request) +{ + WebKitDownload* download = webkitDownloadCreate(downloadProxy); + download->priv->request = adoptGRef(webkitURIRequestCreateForResourceRequest(request)); + return download; +} + void webkitDownloadSetResponse(WebKitDownload* download, WebKitURIResponse* response) { download->priv->response = response; diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h b/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h index 448bebf6b..493bfea40 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h @@ -26,6 +26,7 @@ #include <glib-object.h> #include <webkit2/WebKitDefines.h> +#include <webkit2/WebKitForwardDeclarations.h> #include <webkit2/WebKitURIRequest.h> #include <webkit2/WebKitURIResponse.h> @@ -53,6 +54,11 @@ struct _WebKitDownloadClass { gboolean (* decide_destination) (WebKitDownload *download, const gchar *suggested_filename); + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h index d7b43050c..980ad732b 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h @@ -23,9 +23,11 @@ #include "WebKitDownload.h" #include "WebKitPrivate.h" #include <WebCore/ResourceError.h> +#include <WebCore/ResourceRequest.h> #include <wtf/text/CString.h> WebKitDownload* webkitDownloadCreate(WebKit::DownloadProxy*); +WebKitDownload* webkitDownloadCreateForRequest(WebKit::DownloadProxy*, const WebCore::ResourceRequest&); bool webkitDownloadIsCancelled(WebKitDownload*); void webkitDownloadSetResponse(WebKitDownload*, WebKitURIResponse*); void webkitDownloadSetWebView(WebKitDownload*, WebKitWebView*); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.cpp.template b/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.cpp.template new file mode 100644 index 000000000..292e1e556 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.cpp.template @@ -0,0 +1,62 @@ +/*** BEGIN file-header ***/ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include <config.h> +#include "WebKitEnumTypes.h" + +#include <webkit2/webkit2.h> +extern "C" { +/*** END file-header ***/ + + +/*** BEGIN file-production ***/ +// Enumerations from @filename@. +/*** END file-production ***/ + + +/*** BEGIN value-header ***/ +GType @enum_name@_get_type() +{ + static const G@Type@Value values[] = { +/*** END value-header ***/ + + +/*** BEGIN value-production ***/ + { @VALUENAME@, "@VALUENAME@", "@valuenick@" }, +/*** END value-production ***/ + + +/*** BEGIN value-tail ***/ + { 0, NULL, NULL } + }; + + static GType type = 0; + if (G_UNLIKELY(!type)) + type = g_@type@_register_static("@EnumName@", values); + + return type; +} + +/*** END value-tail ***/ + + +/*** BEGIN file-tail ***/ +} +/*** END file-tail ***/ diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.h.template b/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.h.template new file mode 100644 index 000000000..1283e0bbd --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.h.template @@ -0,0 +1,54 @@ +/*** BEGIN file-header ***/ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) +#error "Only <webkit2/webkit2.h> can be included directly." +#endif + +#ifndef WEBKIT_ENUM_TYPES_H +#define WEBKIT_ENUM_TYPES_H + +#include <glib-object.h> +#include <webkit2/WebKitDefines.h> + +G_BEGIN_DECLS +/*** END file-header ***/ + + +/*** BEGIN file-production ***/ +/* Enumerations from @filename@. */ +/*** END file-production ***/ + + +/*** BEGIN enumeration-production ***/ +#define WEBKIT_TYPE_@ENUMSHORT@ @enum_name@_get_type () + +WEBKIT_API GType +@enum_name@_get_type (void); + +/*** END enumeration-production ***/ + + +/*** BEGIN file-tail ***/ +G_END_DECLS + +#endif +/*** END file-tail ***/ + diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitError.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitError.cpp index daf09ecc2..c06dc61a5 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitError.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitError.cpp @@ -26,6 +26,15 @@ using namespace WebCore; +/** + * SECTION: WebKitError + * @Short_description: Categorized WebKit errors + * @Title: WebKitError + * + * Categorized WebKit errors. + * + */ + GQuark webkit_network_error_quark() { return g_quark_from_static_string(WebCore::errorDomainNetwork); @@ -82,3 +91,8 @@ GQuark webkit_javascript_error_quark() { return g_quark_from_static_string("WebKitJavascriptError"); } + +GQuark webkit_snapshot_error_quark() +{ + return g_quark_from_static_string("WebKitSnapshotError"); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitError.h b/Source/WebKit2/UIProcess/API/gtk/WebKitError.h index c20581683..e7de93bc2 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitError.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitError.h @@ -35,6 +35,7 @@ G_BEGIN_DECLS #define WEBKIT_DOWNLOAD_ERROR webkit_download_error_quark () #define WEBKIT_PRINT_ERROR webkit_print_error_quark () #define WEBKIT_JAVASCRIPT_ERROR webkit_print_error_quark () +#define WEBKIT_SNAPSHOT_ERROR webkit_snapshot_error_quark () /** * WebKitNetworkError: @@ -130,6 +131,16 @@ typedef enum { WEBKIT_JAVASCRIPT_ERROR_SCRIPT_FAILED = 699 } WebKitJavascriptError; +/** + * WebKitSnapshotError: + * @WEBKIT_SNAPSHOT_ERROR_FAILED_TO_CREATE: An error occurred when creating a webpage snapshot. + * + * Enum values used to denote errors happending when creating snapshots of #WebKitWebView + */ +typedef enum { + WEBKIT_SNAPSHOT_ERROR_FAILED_TO_CREATE = 799 +} WebKitSnapshotError; + WEBKIT_API GQuark webkit_network_error_quark (void); @@ -148,6 +159,9 @@ webkit_print_error_quark (void); WEBKIT_API GQuark webkit_javascript_error_quark (void); +WEBKIT_API GQuark +webkit_snapshot_error_quark (void); + G_END_DECLS #endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.cpp index d50533b91..af274b97d 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.cpp @@ -35,6 +35,26 @@ using namespace WebKit; +/** + * SECTION: WebKitFaviconDatabase + * @Short_description: A WebKit favicon database + * @Title: WebKitFaviconDatabase + * + * #WebKitFaviconDatabase provides access to the icons associated with + * web sites. + * + * WebKit will automatically look for available icons in <link> + * elements on opened pages as well as an existing favicon.ico and + * load the images found into a memory cache if possible. That cache + * is frozen to an on-disk database for persistence. + * + * If #WebKitSettings:enable-private-browsing is %TRUE, new icons + * won't be added to the on-disk database and no existing icons will + * be deleted from it. Nevertheless, WebKit will still store them in + * the in-memory cache during the current execution. + * + */ + enum { FAVICON_CHANGED, @@ -43,7 +63,7 @@ enum { static guint signals[LAST_SIGNAL] = { 0, }; -typedef Vector<GRefPtr<GSimpleAsyncResult> > PendingIconRequestVector; +typedef Vector<GRefPtr<GTask> > PendingIconRequestVector; typedef HashMap<String, PendingIconRequestVector*> PendingIconRequestMap; struct _WebKitFaviconDatabasePrivate { @@ -110,7 +130,7 @@ struct GetFaviconSurfaceAsyncData { }; WEBKIT_DEFINE_ASYNC_DATA_STRUCT(GetFaviconSurfaceAsyncData) -static cairo_surface_t* getIconSurfaceSynchronously(WebKitFaviconDatabase* database, const String& pageURL, GError** error) +static PassRefPtr<cairo_surface_t> getIconSurfaceSynchronously(WebKitFaviconDatabase* database, const String& pageURL, GError** error) { ASSERT(isMainThread()); @@ -122,13 +142,13 @@ static cairo_surface_t* getIconSurfaceSynchronously(WebKitFaviconDatabase* datab return 0; } - WebCore::NativeImagePtr icon = iconImage->nativeImageForCurrentFrame(); - if (!icon) { + RefPtr<cairo_surface_t> surface = iconImage->nativeImageForCurrentFrame(); + if (!surface) { g_set_error(error, WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND, _("Page %s does not have a favicon"), pageURL.utf8().data()); return 0; } - return icon->surface(); + return surface.release(); } static void deletePendingIconRequests(WebKitFaviconDatabase* database, PendingIconRequestVector* requests, const String& pageURL) @@ -147,18 +167,15 @@ static void processPendingIconsForPageURL(WebKitFaviconDatabase* database, const RefPtr<cairo_surface_t> icon = getIconSurfaceSynchronously(database, pageURL, &error.outPtr()); for (size_t i = 0; i < pendingIconRequests->size(); ++i) { - GSimpleAsyncResult* result = pendingIconRequests->at(i).get(); - GetFaviconSurfaceAsyncData* data = static_cast<GetFaviconSurfaceAsyncData*>(g_simple_async_result_get_op_res_gpointer(result)); - if (!g_cancellable_is_cancelled(data->cancellable.get())) { - if (error) - g_simple_async_result_take_error(result, error.release()); - else { - data->icon = icon; - data->shouldReleaseIconForPageURL = false; - } + GTask* task = pendingIconRequests->at(i).get(); + if (error) + g_task_return_error(task, error.release()); + else { + GetFaviconSurfaceAsyncData* data = static_cast<GetFaviconSurfaceAsyncData*>(g_task_get_task_data(task)); + data->icon = icon; + data->shouldReleaseIconForPageURL = false; + g_task_return_boolean(task, TRUE); } - - g_simple_async_result_complete(result); } deletePendingIconRequests(database, pendingIconRequests, pageURL); } @@ -218,28 +235,6 @@ static PendingIconRequestVector* getOrCreatePendingIconRequests(WebKitFaviconDat return icons; } -static void setErrorForAsyncResult(GSimpleAsyncResult* result, WebKitFaviconDatabaseError error, const String& pageURL = String()) -{ - ASSERT(result); - - switch (error) { - case WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED: - g_simple_async_result_set_error(result, WEBKIT_FAVICON_DATABASE_ERROR, error, _("Favicons database not initialized yet")); - break; - - case WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND: - g_simple_async_result_set_error(result, WEBKIT_FAVICON_DATABASE_ERROR, error, _("Page %s does not have a favicon"), pageURL.utf8().data()); - break; - - case WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN: - g_simple_async_result_set_error(result, WEBKIT_FAVICON_DATABASE_ERROR, error, _("Unknown favicon for page %s"), pageURL.utf8().data()); - break; - - default: - ASSERT_NOT_REACHED(); - } -} - GQuark webkit_favicon_database_error_quark(void) { return g_quark_from_static_string("WebKitFaviconDatabaseError"); @@ -267,29 +262,27 @@ void webkit_favicon_database_get_favicon(WebKitFaviconDatabase* database, const g_return_if_fail(WEBKIT_IS_FAVICON_DATABASE(database)); g_return_if_fail(pageURI); - GRefPtr<GSimpleAsyncResult> result = adoptGRef(g_simple_async_result_new(G_OBJECT(database), callback, userData, reinterpret_cast<gpointer>(webkit_favicon_database_get_favicon))); - g_simple_async_result_set_check_cancellable(result.get(), cancellable); - - GetFaviconSurfaceAsyncData* data = createGetFaviconSurfaceAsyncData(); - g_simple_async_result_set_op_res_gpointer(result.get(), data, reinterpret_cast<GDestroyNotify>(destroyGetFaviconSurfaceAsyncData)); - data->faviconDatabase = database; - data->pageURL = String::fromUTF8(pageURI); - data->cancellable = cancellable; - WebKitFaviconDatabasePrivate* priv = database->priv; WebIconDatabase* iconDatabaseImpl = priv->iconDatabase.get(); if (!iconDatabaseImpl->isOpen()) { - setErrorForAsyncResult(result.get(), WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED); - g_simple_async_result_complete_in_idle(result.get()); + g_task_report_new_error(database, callback, userData, 0, + WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED, _("Favicons database not initialized yet")); return; } - if (data->pageURL.isEmpty() || data->pageURL.startsWith("about:")) { - setErrorForAsyncResult(result.get(), WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND, data->pageURL); - g_simple_async_result_complete_in_idle(result.get()); + if (g_str_has_prefix(pageURI, "about:")) { + g_task_report_new_error(database, callback, userData, 0, + WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND, _("Page %s does not have a favicon"), pageURI); return; } + GRefPtr<GTask> task = adoptGRef(g_task_new(database, cancellable, callback, userData)); + + GetFaviconSurfaceAsyncData* data = createGetFaviconSurfaceAsyncData(); + data->faviconDatabase = database; + data->pageURL = String::fromUTF8(pageURI); + g_task_set_task_data(task.get(), data, reinterpret_cast<GDestroyNotify>(destroyGetFaviconSurfaceAsyncData)); + priv->iconDatabase->retainIconForPageURL(data->pageURL); // We ask for the icon directly. If we don't get the icon data now, @@ -297,7 +290,7 @@ void webkit_favicon_database_get_favicon(WebKitFaviconDatabase* database, const GOwnPtr<GError> error; data->icon = getIconSurfaceSynchronously(database, data->pageURL, &error.outPtr()); if (data->icon) { - g_simple_async_result_complete_in_idle(result.get()); + g_task_return_boolean(task.get(), TRUE); return; } @@ -305,8 +298,7 @@ void webkit_favicon_database_get_favicon(WebKitFaviconDatabase* database, const data->shouldReleaseIconForPageURL = true; if (g_error_matches(error.get(), WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND)) { - g_simple_async_result_take_error(result.get(), error.release()); - g_simple_async_result_complete_in_idle(result.get()); + g_task_return_error(task.get(), error.release()); return; } @@ -317,14 +309,14 @@ void webkit_favicon_database_get_favicon(WebKitFaviconDatabase* database, const String iconURLForPageURL; iconDatabaseImpl->synchronousIconURLForPageURL(data->pageURL, iconURLForPageURL); if (!iconURLForPageURL.isEmpty() || !iconDatabaseImpl->isUrlImportCompleted()) { - PendingIconRequestVector* icons = getOrCreatePendingIconRequests(database, data->pageURL); - ASSERT(icons); - icons->append(result); + PendingIconRequestVector* iconRequests = getOrCreatePendingIconRequests(database, data->pageURL); + ASSERT(iconRequests); + iconRequests->append(task); return; } - setErrorForAsyncResult(result.get(), WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN, data->pageURL); - g_simple_async_result_complete_in_idle(result.get()); + g_task_return_new_error(task.get(), WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN, + _("Unknown favicon for page %s"), pageURI); } /** @@ -340,14 +332,14 @@ void webkit_favicon_database_get_favicon(WebKitFaviconDatabase* database, const */ cairo_surface_t* webkit_favicon_database_get_favicon_finish(WebKitFaviconDatabase* database, GAsyncResult* result, GError** error) { - GSimpleAsyncResult* simpleResult = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simpleResult) == webkit_favicon_database_get_favicon); + g_return_val_if_fail(WEBKIT_IS_FAVICON_DATABASE(database), 0); + g_return_val_if_fail(g_task_is_valid(result, database), 0); - if (g_simple_async_result_propagate_error(simpleResult, error)) + GTask* task = G_TASK(result); + if (!g_task_propagate_boolean(task, error)) return 0; - GetFaviconSurfaceAsyncData* data = static_cast<GetFaviconSurfaceAsyncData*>(g_simple_async_result_get_op_res_gpointer(simpleResult)); - ASSERT(data); + GetFaviconSurfaceAsyncData* data = static_cast<GetFaviconSurfaceAsyncData*>(g_task_get_task_data(task)); return cairo_surface_reference(data->icon.get()); } diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h index 811a8e6bb..45fbb5d88 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h @@ -51,6 +51,11 @@ struct _WebKitFaviconDatabase { struct _WebKitFaviconDatabaseClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; /** diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp index 85ae0efa0..217d06961 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp @@ -345,16 +345,17 @@ const gchar* const* webkit_file_chooser_request_get_selected_files(WebKitFileCho if (request->priv->selectedFiles) return reinterpret_cast<gchar**>(request->priv->selectedFiles->pdata); - const Vector<String> selectedFileNames = request->priv->parameters->selectedFileNames(); - size_t numOfFiles = selectedFileNames.size(); + RefPtr<ImmutableArray> selectedFileNames = request->priv->parameters->selectedFileNames(); + size_t numOfFiles = selectedFileNames->size(); if (!numOfFiles) return 0; request->priv->selectedFiles = adoptGRef(g_ptr_array_new_with_free_func(g_free)); for (size_t i = 0; i < numOfFiles; ++i) { - if (selectedFileNames[i].isEmpty()) + WebString* webFileName = static_cast<WebString*>(selectedFileNames->at(i)); + if (webFileName->isEmpty()) continue; - CString filename = fileSystemRepresentation(selectedFileNames[i]); + CString filename = fileSystemRepresentation(webFileName->string()); g_ptr_array_add(request->priv->selectedFiles.get(), g_strdup(filename.data())); } g_ptr_array_add(request->priv->selectedFiles.get(), 0); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h index 88eec9966..2b0069024 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h @@ -49,6 +49,11 @@ struct _WebKitFileChooserRequest { struct _WebKitFileChooserRequestClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp index 7e36a4ad5..516c58237 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp @@ -22,6 +22,7 @@ #include "WebKitEnumTypes.h" #include "WebKitPrivate.h" +#include "WebKitWebView.h" #include "WebKitWebViewBasePrivate.h" #include <glib/gi18n-lib.h> #include <wtf/gobject/GRefPtr.h> @@ -30,6 +31,23 @@ using namespace WebKit; using namespace WebCore; +/** + * SECTION: WebKitFindController + * @Short_description: Controls text search in a #WebKitWebView + * @Title: WebKitFindController + * + * A #WebKitFindController is used to search text in a #WebKitWebView. You + * can get a #WebKitWebView<!-- -->'s #WebKitFindController with + * webkit_web_view_get_find_controller(), and later use it to search + * for text using webkit_find_controller_search(), or get the + * number of matches using webkit_find_controller_count_matches(). The + * operations are asynchronous and trigger signals when ready, such as + * #WebKitFindController::found-text, + * #WebKitFindController::failed-to-find-text or + * #WebKitFindController::counted-matches<!-- -->. + * + */ + enum { FOUND_TEXT, FAILED_TO_FIND_TEXT, diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h index 3a47f99d4..7bad1d051 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h @@ -26,6 +26,7 @@ #include <glib-object.h> #include <webkit2/WebKitDefines.h> +#include <webkit2/WebKitForwardDeclarations.h> G_BEGIN_DECLS @@ -73,6 +74,11 @@ struct _WebKitFindController { struct _WebKitFindControllerClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp index 816cee3f6..92ee4586c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp @@ -28,6 +28,21 @@ using namespace WebKit; +/** + * SECTION: WebKitFormSubmissionRequest + * @Short_description: Represents a form submission request + * @Title: WebKitFormSubmissionRequest + * + * When a form is about to be submitted in a #WebKitWebView, the + * #WebKitWebView::submit-form signal is emitted. Its request argument + * contains information about the text fields of the form, that are + * typically used to store login information, returned in a + * #GHashTable by the webkit_form_submission_request_get_text_fields() + * method, and you can finally submit the form with + * webkit_form_submission_request_submit(). + * + */ + struct _WebKitFormSubmissionRequestPrivate { RefPtr<ImmutableDictionary> webValues; RefPtr<WebFormSubmissionListenerProxy> listener; diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h index 910a81c6d..e27779b34 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h @@ -49,6 +49,11 @@ struct _WebKitFormSubmissionRequest { struct _WebKitFormSubmissionRequestClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitForwardDeclarations.h b/Source/WebKit2/UIProcess/API/gtk/WebKitForwardDeclarations.h new file mode 100644 index 000000000..a9898de48 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitForwardDeclarations.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2013 Igalia S.L. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) +#error "Only <webkit2/webkit2.h> can be included directly." +#endif + +#ifndef WebKitForward_h +#define WebKitForward_h + +typedef struct _WebKitPrintOperation WebKitPrintOperation; +typedef struct _WebKitFindController WebKitFindController; +typedef struct _WebKitWebView WebKitWebView; +typedef struct _WebKitContextMenu WebKitContextMenu; +typedef struct _WebKitContextMenuItem WebKitContextMenuItem; + +#endif // WebKitForward_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h index 033b63f7e..4b44af09f 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h @@ -49,6 +49,11 @@ struct _WebKitGeolocationPermissionRequest { struct _WebKitGeolocationPermissionRequestClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp index 8df293cba..918d316c0 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp @@ -240,6 +240,9 @@ WebKitHitTestResult* webkitHitTestResultCreate(WebHitTestResult* hitTestResult) if (hitTestResult->isContentEditable()) context |= WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE; + if (hitTestResult->isScrollbar()) + context |= WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR; + const String& linkTitle = hitTestResult->linkTitle(); const String& linkLabel = hitTestResult->linkLabel(); @@ -262,6 +265,7 @@ bool webkitHitTestResultCompare(WebKitHitTestResult* hitTestResult, WebHitTestRe { WebKitHitTestResultPrivate* priv = hitTestResult->priv; return webHitTestResult->isContentEditable() == webkit_hit_test_result_context_is_editable(hitTestResult) + && webHitTestResult->isScrollbar() == webkit_hit_test_result_context_is_scrollbar(hitTestResult) && stringIsEqualToCString(webHitTestResult->absoluteLinkURL(), priv->linkURI) && stringIsEqualToCString(webHitTestResult->linkTitle(), priv->linkTitle) && stringIsEqualToCString(webHitTestResult->linkLabel(), priv->linkLabel) @@ -433,3 +437,20 @@ const gchar* webkit_hit_test_result_get_media_uri(WebKitHitTestResult* hitTestRe return hitTestResult->priv->mediaURI.data(); } + +/** + * webkit_hit_test_result_context_is_scrollbar: + * @hit_test_result: a #WebKitHitTestResult + * + * Gets whether %WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR flag is present in + * #WebKitHitTestResult:context. + * + * Returns: %TRUE if there's a scrollbar element at the coordinates of the @hit_test_result, + * or %FALSE otherwise + */ +gboolean webkit_hit_test_result_context_is_scrollbar(WebKitHitTestResult* hitTestResult) +{ + g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), FALSE); + + return hitTestResult->priv->context & WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR; +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.h b/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.h index 01e66c964..54611ba92 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.h @@ -47,16 +47,18 @@ typedef struct _WebKitHitTestResultPrivate WebKitHitTestResultPrivate; * @WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE: an image element. * @WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA: a video or audio element. * @WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE: an editable element + * @WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR: a scrollbar element. * * Enum values with flags representing the context of a #WebKitHitTestResult. */ typedef enum { - WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT = 1 << 1, - WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK = 1 << 2, - WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE = 1 << 3, - WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA = 1 << 4, - WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE = 1 << 5 + WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT = 1 << 1, + WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK = 1 << 2, + WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE = 1 << 3, + WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA = 1 << 4, + WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE = 1 << 5, + WEBKIT_HIT_TEST_RESULT_CONTEXT_SCROLLBAR = 1 << 6 } WebKitHitTestResultContext; struct _WebKitHitTestResult { @@ -67,6 +69,11 @@ struct _WebKitHitTestResult { struct _WebKitHitTestResultClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType @@ -102,6 +109,9 @@ webkit_hit_test_result_get_image_uri (WebKitHitTestResult *hit_test_resul WEBKIT_API const gchar * webkit_hit_test_result_get_media_uri (WebKitHitTestResult *hit_test_result); +WEBKIT_API gboolean +webkit_hit_test_result_context_is_scrollbar (WebKitHitTestResult *hit_test_result); + G_END_DECLS #endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.cpp new file mode 100644 index 000000000..26a6f8f10 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "WebKitInjectedBundleClient.h" + +#include "WebImage.h" +#include "WebKitURIRequestPrivate.h" +#include "WebKitURIResponsePrivate.h" +#include "WebKitWebContextPrivate.h" +#include "WebKitWebResourcePrivate.h" +#include "WebKitWebViewPrivate.h" +#include <wtf/gobject/GOwnPtr.h> + +using namespace WebKit; +using namespace WebCore; + +static void didReceiveWebViewMessageFromInjectedBundle(WebKitWebView* webView, const char* messageName, ImmutableDictionary& message) +{ + if (g_str_equal(messageName, "DidInitiateLoadForResource")) { + WebFrameProxy* frame = static_cast<WebFrameProxy*>(message.get(String::fromUTF8("Frame"))); + WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier"))); + WebURLRequest* webRequest = static_cast<WebURLRequest*>(message.get(String::fromUTF8("Request"))); + GRefPtr<WebKitURIRequest> request = adoptGRef(webkitURIRequestCreateForResourceRequest(webRequest->resourceRequest())); + + webkitWebViewResourceLoadStarted(webView, frame, resourceIdentifier->value(), request.get()); + } else if (g_str_equal(messageName, "DidSendRequestForResource")) { + WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier"))); + GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value()); + if (!resource) + return; + + WebURLRequest* webRequest = static_cast<WebURLRequest*>(message.get(String::fromUTF8("Request"))); + GRefPtr<WebKitURIRequest> request = adoptGRef(webkitURIRequestCreateForResourceRequest(webRequest->resourceRequest())); + WebURLResponse* webRedirectResponse = static_cast<WebURLResponse*>(message.get(String::fromUTF8("RedirectResponse"))); + GRefPtr<WebKitURIResponse> redirectResponse = webRedirectResponse ? adoptGRef(webkitURIResponseCreateForResourceResponse(webRedirectResponse->resourceResponse())) : 0; + + webkitWebResourceSentRequest(resource.get(), request.get(), redirectResponse.get()); + } else if (g_str_equal(messageName, "DidReceiveResponseForResource")) { + WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier"))); + GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value()); + if (!resource) + return; + + WebURLResponse* webResponse = static_cast<WebURLResponse*>(message.get(String::fromUTF8("Response"))); + GRefPtr<WebKitURIResponse> response = adoptGRef(webkitURIResponseCreateForResourceResponse(webResponse->resourceResponse())); + + webkitWebResourceSetResponse(resource.get(), response.get()); + } else if (g_str_equal(messageName, "DidReceiveContentLengthForResource")) { + WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier"))); + GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value()); + if (!resource) + return; + + WebUInt64* contentLength = static_cast<WebUInt64*>(message.get(String::fromUTF8("ContentLength"))); + webkitWebResourceNotifyProgress(resource.get(), contentLength->value()); + } else if (g_str_equal(messageName, "DidFinishLoadForResource")) { + WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier"))); + GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value()); + if (!resource) + return; + + webkitWebResourceFinished(resource.get()); + webkitWebViewRemoveLoadingWebResource(webView, resourceIdentifier->value()); + } else if (g_str_equal(messageName, "DidFailLoadForResource")) { + WebUInt64* resourceIdentifier = static_cast<WebUInt64*>(message.get(String::fromUTF8("Identifier"))); + GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier->value()); + if (!resource) + return; + + WebError* webError = static_cast<WebError*>(message.get(String::fromUTF8("Error"))); + const ResourceError& platformError = webError->platformError(); + GOwnPtr<GError> resourceError(g_error_new_literal(g_quark_from_string(platformError.domain().utf8().data()), + platformError.errorCode(), platformError.localizedDescription().utf8().data())); + + webkitWebResourceFailed(resource.get(), resourceError.get()); + webkitWebViewRemoveLoadingWebResource(webView, resourceIdentifier->value()); + } else if (g_str_equal(messageName, "DidGetSnapshot")) { + WebUInt64* callbackID = static_cast<WebUInt64*>(message.get("CallbackID")); + WebImage* image = static_cast<WebImage*>(message.get("Snapshot")); + webKitWebViewDidReceiveSnapshot(webView, callbackID->value(), image); + } else + ASSERT_NOT_REACHED(); +} + +static void didReceiveMessageFromInjectedBundle(WKContextRef, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo) +{ + ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID()); + ImmutableDictionary& message = *toImpl(static_cast<WKDictionaryRef>(messageBody)); + + CString messageNameCString = toImpl(messageName)->string().utf8(); + const char* messageNameUTF8 = messageNameCString.data(); + + if (g_str_has_prefix(messageNameUTF8, "WebPage.")) { + WebPageProxy* page = static_cast<WebPageProxy*>(message.get(String::fromUTF8("Page"))); + WebKitWebView* webView = webkitWebContextGetWebViewForPage(WEBKIT_WEB_CONTEXT(clientInfo), page); + if (!webView) + return; + + didReceiveWebViewMessageFromInjectedBundle(webView, messageNameUTF8 + strlen("WebPage."), message); + } else + ASSERT_NOT_REACHED(); +} + +void attachInjectedBundleClientToContext(WebKitWebContext* webContext) +{ + WKContextInjectedBundleClient wkInjectedBundleClient = { + kWKContextInjectedBundleClientCurrentVersion, + webContext, // clientInfo + didReceiveMessageFromInjectedBundle, + 0, // didReceiveSynchronousMessageFromInjectedBundle + 0 // getInjectedBundleInitializationUserData + }; + WKContextSetInjectedBundleClient(toAPI(webkitWebContextGetContext(webContext)), &wkInjectedBundleClient); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitResourceLoadClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.h index 0e6a3613c..7f7c79179 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitResourceLoadClient.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2013 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -17,11 +17,11 @@ * Boston, MA 02110-1301, USA. */ -#ifndef WebKitResourceLoadClient_h -#define WebKitResourceLoadClient_h +#ifndef WebKitInjectedBundleClient_h +#define WebKitInjectedBundleClient_h -#include "WebKitWebView.h" +#include "WebKitWebContext.h" -void attachResourceLoadClientToView(WebKitWebView*); +void attachInjectedBundleClientToContext(WebKitWebContext*); #endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp index 1eae26753..36cd6c0e6 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp @@ -21,7 +21,6 @@ #include "config.h" #include "WebKitLoaderClient.h" -#include "WebKit2GtkAuthenticationDialog.h" #include "WebKitBackForwardListPrivate.h" #include "WebKitURIResponsePrivate.h" #include "WebKitWebViewBasePrivate.h" @@ -57,8 +56,11 @@ static void didFailProvisionalLoadWithErrorForFrame(WKPageRef page, WKFrameRef f GOwnPtr<GError> webError(g_error_new_literal(g_quark_from_string(resourceError.domain().utf8().data()), resourceError.errorCode(), resourceError.localizedDescription().utf8().data())); - webkitWebViewLoadFailed(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_LOAD_STARTED, - resourceError.failingURL().utf8().data(), webError.get()); + if (resourceError.tlsErrors()) { + webkitWebViewLoadFailedWithTLSErrors(WEBKIT_WEB_VIEW(clientInfo), resourceError.failingURL().utf8().data(), webError.get(), + static_cast<GTlsCertificateFlags>(resourceError.tlsErrors()), resourceError.certificate()); + } else + webkitWebViewLoadFailed(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_LOAD_STARTED, resourceError.failingURL().utf8().data(), webError.get()); } static void didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) @@ -106,6 +108,16 @@ static void didReceiveTitleForFrame(WKPageRef page, WKStringRef titleRef, WKFram webkitWebViewSetTitle(WEBKIT_WEB_VIEW(clientInfo), toImpl(titleRef)->string().utf8()); } +static void didDisplayInsecureContentForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo) +{ + webkitWebViewInsecureContentDetected(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_INSECURE_CONTENT_DISPLAYED); +} + +static void didRunInsecureContentForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo) +{ + webkitWebViewInsecureContentDetected(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_INSECURE_CONTENT_RUN); +} + static void didChangeProgress(WKPageRef page, const void* clientInfo) { webkitWebViewSetEstimatedLoadProgress(WEBKIT_WEB_VIEW(clientInfo), WKPageGetEstimatedProgress(page)); @@ -121,6 +133,11 @@ static void didReceiveAuthenticationChallengeInFrame(WKPageRef page, WKFrameRef webkitWebViewHandleAuthenticationChallenge(WEBKIT_WEB_VIEW(clientInfo), toImpl(authenticationChallenge)); } +static void processDidCrash(WKPageRef page, const void* clientInfo) +{ + webkitWebViewWebProcessCrashed(WEBKIT_WEB_VIEW(clientInfo)); +} + void attachLoaderClientToView(WebKitWebView* webView) { WKPageLoaderClient wkLoaderClient = { @@ -138,8 +155,8 @@ void attachLoaderClientToView(WebKitWebView* webView) 0, // didFirstLayoutForFrame 0, // didFirstVisuallyNonEmptyLayoutForFrame 0, // didRemoveFrameFromHierarchy - 0, // didDisplayInsecureContentForFrame - 0, // didRunInsecureContentForFrame + didDisplayInsecureContentForFrame, + didRunInsecureContentForFrame, 0, // canAuthenticateAgainstProtectionSpaceInFrame didReceiveAuthenticationChallengeInFrame, didChangeProgress, // didStartProgress @@ -147,7 +164,7 @@ void attachLoaderClientToView(WebKitWebView* webView) didChangeProgress, // didFinishProgress 0, // didBecomeUnresponsive 0, // didBecomeResponsive - 0, // processDidCrash + processDidCrash, didChangeBackForwardList, 0, // shouldGoToBackForwardListItem 0, // didFailToInitializePlugin @@ -155,10 +172,12 @@ void attachLoaderClientToView(WebKitWebView* webView) 0, // didFirstVisuallyNonEmptyLayoutForFrame 0, // willGoToBackForwardListItem 0, // interactionOccurredWhileProcessUnresponsive - 0, // pluginDidFail + 0, // pluginDidFail_deprecatedForUseWithV1 0, // didReceiveIntentForFrame 0, // registerIntentServiceForFrame 0, // didLayout + 0, // pluginLoadPolicy + 0, // pluginDidFail }; WKPageRef wkPage = toAPI(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView))); WKPageSetPageLoaderClient(wkPage, &wkLoaderClient); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h b/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h index bbf241268..751397731 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h @@ -71,6 +71,11 @@ struct _WebKitNavigationPolicyDecision { struct _WebKitNavigationPolicyDecisionClass { WebKitPolicyDecisionClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp index 0dd1121cf..977afa450 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp @@ -26,6 +26,20 @@ using namespace WebKit; +/** + * SECTION: WebKitPlugin + * @Short_description: Represents a plugin, enabling fine-grained control + * @Title: WebKitPlugin + * + * This object represents a single plugin, found while scanning the + * various platform plugin directories. This object can be used to get + * more information about a plugin, and enable/disable it, allowing + * fine-grained control of plugins. The list of available plugins can + * be obtained from the #WebKitWebContext, with + * webkit_web_context_get_plugins(). + * + */ + struct _WebKitPluginPrivate { ~_WebKitPluginPrivate() { diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h index 8928348cc..d7533c920 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h @@ -48,6 +48,11 @@ struct _WebKitPlugin { struct _WebKitPluginClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h index ecca5f9c3..f192a1d37 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h @@ -49,6 +49,11 @@ struct _WebKitPolicyDecision { struct _WebKitPolicyDecisionClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp index 6b72d188d..068a28cdd 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp @@ -38,6 +38,18 @@ using namespace WebKit; +/** + * SECTION: WebKitPrintOperation + * @Short_description: Controls a print operation + * @Title: WebKitPrintOperation + * + * A #WebKitPrintOperation controls a print operation in WebKit. With + * a similar API to #GtkPrintOperation, it lets you set the print + * settings with webkit_print_operation_set_print_settings() or + * display the print dialog with webkit_print_operation_run_dialog(). + * + */ + enum { PROP_0, diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h index a02f4e809..b7159b8c6 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h @@ -26,6 +26,7 @@ #include <glib-object.h> #include <webkit2/WebKitDefines.h> +#include <webkit2/WebKitForwardDeclarations.h> #include <webkit2/WebKitWebView.h> G_BEGIN_DECLS @@ -61,6 +62,11 @@ struct _WebKitPrintOperation { struct _WebKitPrintOperationClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h index be39e802c..83904ad9a 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h @@ -120,4 +120,9 @@ GType type_name##_get_type(void) \ unsigned wkEventModifiersToGdkModifiers(WKEventModifiers); unsigned wkEventMouseButtonToWebKitMouseButton(WKEventMouseButton); +enum SnapshotRegion { + SnapshotRegionVisible, + SnapshotRegionFullDocument +}; + #endif // WebKitPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitResourceLoadClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitResourceLoadClient.cpp deleted file mode 100644 index 4444a1ee7..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitResourceLoadClient.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2012 Igalia S.L. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "WebKitResourceLoadClient.h" - -#include "WebContext.h" -#include "WebKitURIRequestPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include "WebKitWebResourcePrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" -#include "WebURLResponse.h" -#include <WebKit2/WKString.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -using namespace WebCore; -using namespace WebKit; - -static void didInitiateLoadForResource(WKPageRef, WKFrameRef wkFrame, uint64_t resourceIdentifier, WKURLRequestRef wkRequest, bool pageIsProvisionallyLoading, const void* clientInfo) -{ - GRefPtr<WebKitURIRequest> request = adoptGRef(webkitURIRequestCreateForResourceRequest(toImpl(wkRequest)->resourceRequest())); - webkitWebViewResourceLoadStarted(WEBKIT_WEB_VIEW(clientInfo), toImpl(wkFrame), resourceIdentifier, request.get()); -} - -static void didSendRequestForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLRequestRef wkRequest, WKURLResponseRef wkRedirectResponse, const void* clientInfo) -{ - GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(WEBKIT_WEB_VIEW(clientInfo), resourceIdentifier); - if (!resource) - return; - - GRefPtr<WebKitURIRequest> request = adoptGRef(webkitURIRequestCreateForResourceRequest(toImpl(wkRequest)->resourceRequest())); - GRefPtr<WebKitURIResponse> redirectResponse = wkRedirectResponse ? adoptGRef(webkitURIResponseCreateForResourceResponse(toImpl(wkRedirectResponse)->resourceResponse())) : 0; - webkitWebResourceSentRequest(resource.get(), request.get(), redirectResponse.get()); -} - -static void didReceiveResponseForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLResponseRef wkResponse, const void* clientInfo) -{ - GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(WEBKIT_WEB_VIEW(clientInfo), resourceIdentifier); - if (!resource) - return; - - GRefPtr<WebKitURIResponse> response = adoptGRef(webkitURIResponseCreateForResourceResponse(toImpl(wkResponse)->resourceResponse())); - webkitWebResourceSetResponse(resource.get(), response.get()); -} - -static void didReceiveContentLengthForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, uint64_t contentLength, const void* clientInfo) -{ - GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(WEBKIT_WEB_VIEW(clientInfo), resourceIdentifier); - if (!resource) - return; - - webkitWebResourceNotifyProgress(resource.get(), contentLength); -} - -static void didFinishLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, const void* clientInfo) -{ - GRefPtr<WebKitWebResource> resource = webkitWebViewResourceLoadFinished(WEBKIT_WEB_VIEW(clientInfo), resourceIdentifier); - if (!resource) - return; - - webkitWebResourceFinished(resource.get()); -} - -static void didFailLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKErrorRef wkError, const void* clientInfo) -{ - WebKitWebView* webView = WEBKIT_WEB_VIEW(clientInfo); - GRefPtr<WebKitWebResource> resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier); - if (!resource) - return; - - const ResourceError& resourceError = toImpl(wkError)->platformError(); - GOwnPtr<GError> webError(g_error_new_literal(g_quark_from_string(resourceError.domain().utf8().data()), - resourceError.errorCode(), - resourceError.localizedDescription().utf8().data())); - webkitWebResourceFailed(resource.get(), webError.get()); - webkitWebViewRemoveLoadingWebResource(webView, resourceIdentifier); -} - -void attachResourceLoadClientToView(WebKitWebView* webView) -{ - WKPageResourceLoadClient wkResourceLoadClient = { - kWKPageResourceLoadClientCurrentVersion, - webView, // ClientInfo - didInitiateLoadForResource, - didSendRequestForResource, - didReceiveResponseForResource, - didReceiveContentLengthForResource, - didFinishLoadForResource, - didFailLoadForResource, - }; - WKPageRef wkPage = toAPI(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView))); - WKPageSetPageResourceLoadClient(wkPage, &wkResourceLoadClient); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h b/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h index 7653fcc14..4a689fbc7 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h @@ -52,6 +52,11 @@ struct _WebKitResponsePolicyDecision { struct _WebKitResponsePolicyDecisionClass { WebKitPolicyDecisionClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp index cd8803749..e8c36d72c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp @@ -27,6 +27,19 @@ using namespace WebKit; +/** + * SECTION: WebKitSecurityManager + * @Short_description: Controls security settings in a #WebKitWebContext + * @Title: WebKitSecurityManager + * + * The #WebKitSecurityManager defines security settings for URI + * schemes in a #WebKitWebContext. Get it from the context with + * webkit_web_context_get_security_manager(), and use it to register a + * URI scheme with a certain security level, or to check if it already + * has it. + * + */ + typedef enum { SecurityPolicyLocal, SecurityPolicyNoAccess, diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h index fb8c36eda..e8cf9e7cd 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h @@ -48,6 +48,11 @@ struct _WebKitSecurityManager { struct _WebKitSecurityManagerClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp index bf1ede057..53a547a1f 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp @@ -31,11 +31,9 @@ #include "config.h" #include "WebKitSettings.h" +#include "ExperimentalFeatures.h" #include "WebKitPrivate.h" #include "WebKitSettingsPrivate.h" -#include "WebPageGroup.h" -#include "WebPageProxy.h" -#include "WebPreferences.h" #include <WebCore/UserAgentGtk.h> #include <glib/gi18n-lib.h> #include <wtf/text/CString.h> @@ -72,18 +70,19 @@ struct _WebKitSettingsPrivate { /** * SECTION:WebKitSettings - * @short_description: Control the behaviour of a #WebKitWebView + * @short_description: Control the behaviour of #WebKitWebView<!-- -->s + * @see_also: #WebKitWebViewGroup, #WebKitWebView * - * #WebKitSettings can be applied to a #WebKitWebView to control text charset, - * color, font sizes, printing mode, script support, loading of images and various other things. + * #WebKitSettings can be applied to a #WebKitWebViewGroup to control text charset, + * color, font sizes, printing mode, script support, loading of images and various + * other things on the #WebKitWebView<!-- -->s of the group. * After creation, a #WebKitSettings object contains default settings. * * <informalexample><programlisting> - * /<!-- -->* Create a new #WebKitSettings and disable JavaScript. *<!-- -->/ - * WebKitSettings *settings = webkit_settings_new (); - * g_object_set (G_OBJECT (settings), "enable-javascript", FALSE, NULL); + * /<!-- -->* Disable JavaScript. *<!-- -->/ + * WebKitSettings *settings = webkit_web_view_group_get_settings (my_view_group); + * webkit_settings_set_enable_javascript (settings, FALSE); * - * webkit_web_view_set_settings (WEBKIT_WEB_VIEW (my_webview), settings); * </programlisting></informalexample> */ @@ -134,9 +133,22 @@ enum { PROP_ENABLE_SITE_SPECIFIC_QUIRKS, PROP_ENABLE_PAGE_CACHE, PROP_USER_AGENT, - PROP_ENABLE_SMOOTH_SCROLLING + PROP_ENABLE_SMOOTH_SCROLLING, + PROP_ENABLE_ACCELERATED_2D_CANVAS, + PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT }; +static void webKitSettingsConstructed(GObject* object) +{ + G_OBJECT_CLASS(webkit_settings_parent_class)->constructed(object); + + WebPreferences* prefs = WEBKIT_SETTINGS(object)->priv->preferences.get(); + ExperimentalFeatures features; + bool regionBasedColumnsEnabled = features.isEnabled(ExperimentalFeatures::RegionBasedColumns); + if (prefs->regionBasedColumnsEnabled() != regionBasedColumnsEnabled) + prefs->setRegionBasedColumnsEnabled(regionBasedColumnsEnabled); +} + static void webKitSettingsSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) { WebKitSettings* settings = WEBKIT_SETTINGS(object); @@ -257,7 +269,13 @@ static void webKitSettingsSetProperty(GObject* object, guint propId, const GValu webkit_settings_set_media_playback_allows_inline(settings, g_value_get_boolean(value)); break; case PROP_DRAW_COMPOSITING_INDICATORS: - webkit_settings_set_draw_compositing_indicators(settings, g_value_get_boolean(value)); + if (g_value_get_boolean(value)) + webkit_settings_set_draw_compositing_indicators(settings, g_value_get_boolean(value)); + else { + char* debugVisualsEnvironment = getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS"); + bool showDebugVisuals = debugVisualsEnvironment && !strcmp(debugVisualsEnvironment, "1"); + webkit_settings_set_draw_compositing_indicators(settings, showDebugVisuals); + } break; case PROP_ENABLE_SITE_SPECIFIC_QUIRKS: webkit_settings_set_enable_site_specific_quirks(settings, g_value_get_boolean(value)); @@ -271,6 +289,12 @@ static void webKitSettingsSetProperty(GObject* object, guint propId, const GValu case PROP_ENABLE_SMOOTH_SCROLLING: webkit_settings_set_enable_smooth_scrolling(settings, g_value_get_boolean(value)); break; + case PROP_ENABLE_ACCELERATED_2D_CANVAS: + webkit_settings_set_enable_accelerated_2d_canvas(settings, g_value_get_boolean(value)); + break; + case PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT: + webkit_settings_set_enable_write_console_messages_to_stdout(settings, g_value_get_boolean(value)); + break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); break; @@ -411,6 +435,12 @@ static void webKitSettingsGetProperty(GObject* object, guint propId, GValue* val case PROP_ENABLE_SMOOTH_SCROLLING: g_value_set_boolean(value, webkit_settings_get_enable_smooth_scrolling(settings)); break; + case PROP_ENABLE_ACCELERATED_2D_CANVAS: + g_value_set_boolean(value, webkit_settings_get_enable_accelerated_2d_canvas(settings)); + break; + case PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT: + g_value_set_boolean(value, webkit_settings_get_enable_write_console_messages_to_stdout(settings)); + break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); break; @@ -420,6 +450,7 @@ static void webKitSettingsGetProperty(GObject* object, guint propId, GValue* val static void webkit_settings_class_init(WebKitSettingsClass* klass) { GObjectClass* gObjectClass = G_OBJECT_CLASS(klass); + gObjectClass->constructed = webKitSettingsConstructed; gObjectClass->set_property = webKitSettingsSetProperty; gObjectClass->get_property = webKitSettingsGetProperty; @@ -1067,20 +1098,53 @@ static void webkit_settings_class_init(WebKitSettingsClass* klass) _("Whether to enable smooth scrolling"), FALSE, readWriteConstructParamFlags)); + + /** + * WebKitSettings:enable-accelerated-2d-canvas: + * + * Enable or disable accelerated 2D canvas. Accelerated 2D canvas is only available + * if WebKitGTK+ was compiled with a version of Cairo including the unstable CairoGL API. + * When accelerated 2D canvas is enabled, WebKit may render some 2D canvas content + * using hardware accelerated drawing operations. + * + * Since: 2.2 + */ + g_object_class_install_property(gObjectClass, + PROP_ENABLE_ACCELERATED_2D_CANVAS, + g_param_spec_boolean("enable-accelerated-2d-canvas", + _("Enable accelerated 2D canvas"), + _("Whether to enable accelerated 2D canvas"), + FALSE, + readWriteConstructParamFlags)); + + /** + * WebKitSettings:enable-write-console-messages-to-stdout: + * + * Enable or disable writing console messages to stdout. These are messages + * sent to the console with console.log and related methods. + * + * Since: 2.2 + */ + g_object_class_install_property(gObjectClass, + PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT, + g_param_spec_boolean("enable-write-console-messages-to-stdout", + _("Write console messages on stdout"), + _("Whether to write console messages on stdout"), + FALSE, + readWriteConstructParamFlags)); + } -void webkitSettingsAttachSettingsToPage(WebKitSettings* settings, WebPageProxy* page) +WebPreferences* webkitSettingsGetPreferences(WebKitSettings* settings) { - page->pageGroup()->setPreferences(settings->priv->preferences.get()); - page->setCanRunModal(settings->priv->allowModalDialogs); - page->setCustomUserAgent(String::fromUTF8(settings->priv->userAgent.data())); + return settings->priv->preferences.get(); } /** * webkit_settings_new: * * Creates a new #WebKitSettings instance with default values. It must - * be manually attached to a #WebKitWebView. + * be manually attached to a #WebKitWebViewGroup. * See also webkit_settings_new_with_settings(). * * Returns: a new #WebKitSettings instance. @@ -1097,7 +1161,7 @@ WebKitSettings* webkit_settings_new() * %NULL-terminated * * Creates a new #WebKitSettings instance with the given settings. It must - * be manually attached to a #WebKitWebView. + * be manually attached to a #WebKitWebViewGroup. * * Returns: a new #WebKitSettings instance. */ @@ -2654,3 +2718,81 @@ void webkit_settings_set_enable_smooth_scrolling(WebKitSettings* settings, gbool priv->preferences->setScrollAnimatorEnabled(enabled); g_object_notify(G_OBJECT(settings), "enable-smooth-scrolling"); } + +/** + * webkit_settings_get_enable_accelerated_2d_canvas: + * @settings: a #WebKitSettings + * + * Get the #WebKitSettings:enable-accelerated-2d-canvas property. + * + * Returns: %TRUE if accelerated 2D canvas is enabled or %FALSE otherwise. + * + * Since: 2.2 + */ +gboolean webkit_settings_get_enable_accelerated_2d_canvas(WebKitSettings* settings) +{ + g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); + + return settings->priv->preferences->accelerated2dCanvasEnabled(); +} + +/** + * webkit_settings_set_enable_accelerated_2d_canvas: + * @settings: a #WebKitSettings + * @enabled: Value to be set + * + * Set the #WebKitSettings:enable-accelerated-2d-canvas property. + * + * Since: 2.2 + */ +void webkit_settings_set_enable_accelerated_2d_canvas(WebKitSettings* settings, gboolean enabled) +{ + g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); + + WebKitSettingsPrivate* priv = settings->priv; + if (priv->preferences->accelerated2dCanvasEnabled() == enabled) + return; + + priv->preferences->setAccelerated2dCanvasEnabled(enabled); + g_object_notify(G_OBJECT(settings), "enable-accelerated-2d-canvas"); +} + +/** + * webkit_settings_get_enable_write_console_messages_to_stdout: + * @settings: a #WebKitSettings + * + * Get the #WebKitSettings:enable-write-console-messages-to-stdout property. + * + * Returns: %TRUE if writing console messages to stdout is enabled or %FALSE + * otherwise. + * + * Since: 2.2 + */ +gboolean webkit_settings_get_enable_write_console_messages_to_stdout(WebKitSettings* settings) +{ + g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); + + return settings->priv->preferences->logsPageMessagesToSystemConsoleEnabled(); +} + +/** + * webkit_settings_set_enable_write_console_messages_to_stdout: + * @settings: a #WebKitSettings + * @enabled: Value to be set + * + * Set the #WebKitSettings:enable-write-console-messages-to-stdout property. + * + * Since: 2.2 + */ +void webkit_settings_set_enable_write_console_messages_to_stdout(WebKitSettings* settings, gboolean enabled) +{ + g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); + + WebKitSettingsPrivate* priv = settings->priv; + bool currentValue = priv->preferences->logsPageMessagesToSystemConsoleEnabled(); + if (currentValue == enabled) + return; + + priv->preferences->setLogsPageMessagesToSystemConsoleEnabled(enabled); + g_object_notify(G_OBJECT(settings), "enable-write-console-messages-to-stdout"); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.h b/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.h index a9fe86a30..a904d0eb6 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.h @@ -60,11 +60,10 @@ struct _WebKitSettings { struct _WebKitSettingsClass { GObjectClass parent_class; - /* Padding for future expansion */ + void (*_webkit_reserved0) (void); void (*_webkit_reserved1) (void); void (*_webkit_reserved2) (void); void (*_webkit_reserved3) (void); - void (*_webkit_reserved4) (void); }; WEBKIT_API GType @@ -380,6 +379,20 @@ WEBKIT_API void webkit_settings_set_enable_smooth_scrolling (WebKitSettings *settings, gboolean enabled); +WEBKIT_API gboolean +webkit_settings_get_enable_accelerated_2d_canvas (WebKitSettings *settings); + +WEBKIT_API void +webkit_settings_set_enable_accelerated_2d_canvas (WebKitSettings *settings, + gboolean enabled); + +WEBKIT_API gboolean +webkit_settings_get_enable_write_console_messages_to_stdout (WebKitSettings *settings); + +WEBKIT_API void +webkit_settings_set_enable_write_console_messages_to_stdout (WebKitSettings *settings, + gboolean enabled); + G_END_DECLS #endif /* WebKitSettings_h */ diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSettingsPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitSettingsPrivate.h index 1ec252bc2..c23a8cd1f 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSettingsPrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitSettingsPrivate.h @@ -27,7 +27,8 @@ #define WebKitSettingsPrivate_h #include "WebKitSettings.h" +#include "WebPreferences.h" -void webkitSettingsAttachSettingsToPage(WebKitSettings*, WebKit::WebPageProxy*); +WebKit::WebPreferences* webkitSettingsGetPreferences(WebKitSettings*); #endif // WebKitSettingsPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp index 00d65ed34..0899b8563 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp @@ -126,7 +126,8 @@ static WKRect getWindowFrame(WKPageRef page, const void* clientInfo) static void setWindowFrame(WKPageRef page, WKRect frame, const void* clientInfo) { WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - GdkRectangle geometry = { frame.origin.x, frame.origin.y, frame.size.width, frame.size.height }; + GdkRectangle geometry = { static_cast<int>(frame.origin.x), static_cast<int>(frame.origin.y), + static_cast<int>(frame.size.width), static_cast<int>(frame.size.height) }; webkitWindowPropertiesSetGeometry(windowProperties, &geometry); } @@ -207,6 +208,7 @@ void attachUIClientToView(WebKitWebView* webView) 0, // unavailablePluginButtonClicked 0, // showColorPicker 0, // hideColorPicker + 0, // pluginLoadPolicy }; WKPageRef wkPage = toAPI(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView))); WKPageSetPageUIClient(wkPage, &wkUIClient); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp index 147d17e1c..50c6eea5d 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp @@ -22,6 +22,7 @@ #include "WebKitPrivate.h" #include "WebKitURIRequestPrivate.h" +#include <WebCore/GOwnPtrSoup.h> #include <glib/gi18n-lib.h> #include <wtf/text/CString.h> @@ -33,9 +34,21 @@ enum { using namespace WebCore; +/** + * SECTION: WebKitURIRequest + * @Short_description: Represents a URI request + * @Title: WebKitURIRequest + * + * A #WebKitURIRequest can be created with a URI using the + * webkit_uri_request_new() method, and you can get the URI of an + * existing request with the webkit_uri_request_get_uri() one. + * + */ + struct _WebKitURIRequestPrivate { WebCore::ResourceRequest resourceRequest; CString uri; + GOwnPtr<SoupMessageHeaders> httpHeaders; }; WEBKIT_DEFINE_TYPE(WebKitURIRequest, webkit_uri_request, G_TYPE_OBJECT) @@ -59,7 +72,7 @@ static void webkitURIRequestSetProperty(GObject* object, guint propId, const GVa switch (propId) { case PROP_URI: - request->priv->resourceRequest.setURL(KURL(KURL(), g_value_get_string(value))); + webkit_uri_request_set_uri(request, g_value_get_string(value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); @@ -81,8 +94,8 @@ static void webkit_uri_request_class_init(WebKitURIRequestClass* requestClass) g_param_spec_string("uri", _("URI"), _("The URI to which the request will be made."), - 0, - static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); + "about:blank", + static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT))); } /** @@ -114,14 +127,60 @@ const gchar* webkit_uri_request_get_uri(WebKitURIRequest* request) return request->priv->uri.data(); } -WebKitURIRequest* webkitURIRequestCreateForResourceRequest(const WebCore::ResourceRequest& resourceRequest) +/** + * webkit_uri_request_set_uri: + * @request: a #WebKitURIRequest + * @uri: an URI + * + * Set the URI of @request + */ +void webkit_uri_request_set_uri(WebKitURIRequest* request, const char* uri) +{ + g_return_if_fail(WEBKIT_IS_URI_REQUEST(request)); + g_return_if_fail(uri); + + KURL url(KURL(), uri); + if (url == request->priv->resourceRequest.url()) + return; + + request->priv->resourceRequest.setURL(url); + g_object_notify(G_OBJECT(request), "uri"); +} + +/** + * webkit_uri_request_get_http_headers: + * @request: a #WebKitURIRequest + * + * Get the HTTP headers of a #WebKitURIRequest as a #SoupMessageHeaders. + * + * Returns: (transfer none): a #SoupMessageHeaders with the HTTP headers of @request + * or %NULL if @request is not an HTTP request. + */ +SoupMessageHeaders* webkit_uri_request_get_http_headers(WebKitURIRequest* request) +{ + g_return_val_if_fail(WEBKIT_IS_URI_REQUEST(request), 0); + + if (request->priv->httpHeaders) + return request->priv->httpHeaders.get(); + + if (!request->priv->resourceRequest.url().protocolIsInHTTPFamily()) + return 0; + + request->priv->httpHeaders.set(soup_message_headers_new(SOUP_MESSAGE_HEADERS_REQUEST)); + request->priv->resourceRequest.updateSoupMessageHeaders(request->priv->httpHeaders.get()); + return request->priv->httpHeaders.get(); +} + +WebKitURIRequest* webkitURIRequestCreateForResourceRequest(const ResourceRequest& resourceRequest) { WebKitURIRequest* uriRequest = WEBKIT_URI_REQUEST(g_object_new(WEBKIT_TYPE_URI_REQUEST, NULL)); uriRequest->priv->resourceRequest = resourceRequest; return uriRequest; } -const WebCore::ResourceRequest& webkitURIRequestGetResourceRequest(WebKitURIRequest* uriRequest) +void webkitURIRequestGetResourceRequest(WebKitURIRequest* request, ResourceRequest& resourceRequest) { - return uriRequest->priv->resourceRequest; + resourceRequest = request->priv->resourceRequest; + if (request->priv->httpHeaders) + resourceRequest.updateFromSoupMessageHeaders(request->priv->httpHeaders.get()); } diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.h index 5236069b3..cac3b332b 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.h @@ -17,7 +17,7 @@ * Boston, MA 02110-1301, USA. */ -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) +#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) && !defined(__WEBKIT_WEB_EXTENSION_H_INSIDE__) #error "Only <webkit2/webkit2.h> can be included directly." #endif @@ -25,6 +25,7 @@ #define WebKitURIRequest_h #include <glib-object.h> +#include <libsoup/soup.h> #include <webkit2/WebKitDefines.h> G_BEGIN_DECLS @@ -50,16 +51,27 @@ struct _WebKitURIRequest { struct _WebKitURIRequestClass { GObjectClass parent_class; + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType -webkit_uri_request_get_type (void); +webkit_uri_request_get_type (void); WEBKIT_API WebKitURIRequest * -webkit_uri_request_new (const gchar *uri); +webkit_uri_request_new (const gchar *uri); WEBKIT_API const gchar * -webkit_uri_request_get_uri (WebKitURIRequest *request); +webkit_uri_request_get_uri (WebKitURIRequest *request); + +WEBKIT_API void +webkit_uri_request_set_uri (WebKitURIRequest *request, + const gchar *uri); + +WEBKIT_API SoupMessageHeaders * +webkit_uri_request_get_http_headers (WebKitURIRequest *request); G_END_DECLS diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequestPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequestPrivate.h index 3af02a527..12586153b 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequestPrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequestPrivate.h @@ -30,6 +30,6 @@ #include <WebCore/ResourceRequest.h> WebKitURIRequest* webkitURIRequestCreateForResourceRequest(const WebCore::ResourceRequest&); -const WebCore::ResourceRequest& webkitURIRequestGetResourceRequest(WebKitURIRequest*); +void webkitURIRequestGetResourceRequest(WebKitURIRequest*, WebCore::ResourceRequest&); #endif // WebKitURIRequestPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp index 576ce953a..20ab248a5 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp @@ -20,8 +20,6 @@ #include "config.h" #include "WebKitURIResponse.h" -#include "PlatformCertificateInfo.h" -#include "WebCertificateInfo.h" #include "WebKitPrivate.h" #include "WebKitURIResponsePrivate.h" #include <glib/gi18n-lib.h> @@ -30,6 +28,17 @@ using namespace WebKit; using namespace WebCore; +/** + * SECTION: WebKitURIResponse + * @Short_description: Represents a URI response + * @Title: WebKitURIResponse + * + * A #WebKitURIResponse contains information such as the URI, the + * status code, the content length, the mime type, the HTTP status or + * the suggested filename. + * + */ + enum { PROP_0, @@ -207,31 +216,6 @@ const gchar* webkit_uri_response_get_mime_type(WebKitURIResponse* response) } /** - * webkit_uri_response_get_https_status: - * @response: a #WebKitURIResponse - * @certificate: (out) (transfer none): return location for a #GTlsCertificate - * @errors: (out): return location for a #GTlsCertificateFlags the verification status of @certificate - * - * Retrieves the #GTlsCertificate associated with the @response connection, - * and the #GTlsCertificateFlags showing what problems, if any, have been found - * with that certificate. - * If the response connection is not HTTPS, this function returns %FALSE. - * - * Returns: %TRUE if @response connection uses HTTPS or %FALSE otherwise. - */ -gboolean webkit_uri_response_get_https_status(WebKitURIResponse* response, GTlsCertificate** certificate, GTlsCertificateFlags* errors) -{ - g_return_val_if_fail(WEBKIT_IS_URI_RESPONSE(response), FALSE); - - if (certificate) - *certificate = response->priv->resourceResponse.soupMessageCertificate(); - if (errors) - *errors = response->priv->resourceResponse.soupMessageTLSErrors(); - - return !!response->priv->resourceResponse.soupMessageCertificate(); -} - -/** * webkit_uri_response_get_suggested_filename: * @response: a #WebKitURIResponse * @@ -265,9 +249,3 @@ const WebCore::ResourceResponse& webkitURIResponseGetResourceResponse(WebKitURIR return uriResponse->priv->resourceResponse; } -void webkitURIResponseSetCertificateInfo(WebKitURIResponse* response, WebCertificateInfo* certificate) -{ - const PlatformCertificateInfo& certificateInfo = certificate->platformCertificateInfo(); - response->priv->resourceResponse.setSoupMessageCertificate(certificateInfo.certificate()); - response->priv->resourceResponse.setSoupMessageTLSErrors(certificateInfo.tlsErrors()); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h index d90cf4132..d43eca13f 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h @@ -17,7 +17,7 @@ * Boston, MA 02110-1301, USA. */ -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) +#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) && !defined(__WEBKIT_WEB_EXTENSION_H_INSIDE__) #error "Only <webkit2/webkit2.h> can be included directly." #endif @@ -50,6 +50,10 @@ struct _WebKitURIResponse { struct _WebKitURIResponseClass { GObjectClass parent_class; + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType @@ -67,10 +71,6 @@ webkit_uri_response_get_content_length (WebKitURIResponse *response); WEBKIT_API const gchar * webkit_uri_response_get_mime_type (WebKitURIResponse *response); -WEBKIT_API gboolean -webkit_uri_response_get_https_status (WebKitURIResponse *response, - GTlsCertificate **certificate, - GTlsCertificateFlags *errors); WEBKIT_API const gchar * webkit_uri_response_get_suggested_filename (WebKitURIResponse *response); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h index b111b71fa..c2dc49c17 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h @@ -31,6 +31,5 @@ WebKitURIResponse* webkitURIResponseCreateForResourceResponse(const WebCore::ResourceResponse&); const WebCore::ResourceResponse& webkitURIResponseGetResourceResponse(WebKitURIResponse*); -void webkitURIResponseSetCertificateInfo(WebKitURIResponse*, WebKit::WebCertificateInfo*); #endif // WebKitURIResponsePrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp index f65789fce..0e5218129 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp @@ -27,12 +27,29 @@ #include "WebPageProxy.h" #include "WebSoupRequestManagerProxy.h" #include <WebCore/GOwnPtrSoup.h> +#include <WebCore/ResourceError.h> #include <libsoup/soup.h> #include <wtf/gobject/GRefPtr.h> #include <wtf/text/CString.h> using namespace WebKit; +/** + * SECTION: WebKitURISchemeRequest + * @Short_description: Represents a URI scheme request + * @Title: WebKitURISchemeRequest + * + * If you register a particular URI scheme in a #WebKitWebContext, + * using webkit_web_context_register_uri_scheme(), you have to provide + * a #WebKitURISchemeRequestCallback. After that, when a URI request + * is made with that particular scheme, your callback will be + * called. There you will be able to access properties such as the + * scheme, the URI and path, and the #WebKitWebView that initiated the + * request, and also finish the request with + * webkit_uri_scheme_request_finish(). + * + */ + static const unsigned int gReadBufferSize = 8192; struct _WebKitURISchemeRequestPrivate { @@ -146,10 +163,10 @@ WebKitWebView* webkit_uri_scheme_request_get_web_view(WebKitURISchemeRequest* re static void webkitURISchemeRequestReadCallback(GInputStream* inputStream, GAsyncResult* result, WebKitURISchemeRequest* schemeRequest) { GRefPtr<WebKitURISchemeRequest> request = adoptGRef(schemeRequest); - gssize bytesRead = g_input_stream_read_finish(inputStream, result, 0); - // FIXME: notify the WebProcess that we failed to read from the user stream. + GOwnPtr<GError> error; + gssize bytesRead = g_input_stream_read_finish(inputStream, result, &error.outPtr()); if (bytesRead == -1) { - webkitWebContextDidFinishURIRequest(request->priv->webContext, request->priv->requestID); + webkit_uri_scheme_request_finish_error(request.get(), error.get()); return; } @@ -197,3 +214,25 @@ void webkit_uri_scheme_request_finish(WebKitURISchemeRequest* request, GInputStr g_input_stream_read_async(inputStream, request->priv->readBuffer, gReadBufferSize, G_PRIORITY_DEFAULT, request->priv->cancellable.get(), reinterpret_cast<GAsyncReadyCallback>(webkitURISchemeRequestReadCallback), g_object_ref(request)); } + +/** + * webkit_uri_scheme_request_finish_error: + * @request: a #WebKitURISchemeRequest + * @error: a #GError that will be passed to the #WebKitWebView + * + * Finish a #WebKitURISchemeRequest with a #GError. + * + * Since: 2.2 + */ +void webkit_uri_scheme_request_finish_error(WebKitURISchemeRequest* request, GError* error) +{ + g_return_if_fail(WEBKIT_IS_URI_SCHEME_REQUEST(request)); + g_return_if_fail(error); + + WebKitURISchemeRequestPrivate* priv = request->priv; + + WebCore::ResourceError resourceError(g_quark_to_string(error->domain), error->code, priv->uri.data(), String::fromUTF8(error->message)); + priv->webRequestManager->didFailURIRequest(resourceError, priv->requestID); + + webkitWebContextDidFinishURIRequest(priv->webContext, priv->requestID); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.h index 9ead50709..71895da51 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.h @@ -26,6 +26,7 @@ #include <glib-object.h> #include <webkit2/WebKitDefines.h> +#include <webkit2/WebKitForwardDeclarations.h> G_BEGIN_DECLS @@ -48,6 +49,11 @@ struct _WebKitURISchemeRequest { struct _WebKitURISchemeRequestClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType @@ -71,6 +77,10 @@ webkit_uri_scheme_request_finish (WebKitURISchemeRequest *request, gint64 stream_length, const gchar *mime_type); +WEBKIT_API void +webkit_uri_scheme_request_finish_error (WebKitURISchemeRequest *request, + GError *error); + G_END_DECLS #endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp index 4ef62e372..54dacc4f7 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp @@ -21,6 +21,20 @@ #include "WebKitVersion.h" /** + * SECTION: WebKitVersion + * @Short_description: Provides the WebKit version + * @Title: WebKitVersion + * + * Provides convenience functions returning WebKit's major, minor and + * micro versions of the WebKit library your code is running + * against. This is not necessarily the same as the + * #WEBKIT_MAJOR_VERSION, #WEBKIT_MINOR_VERSION or + * #WEBKIT_MICRO_VERSION, which represent the version of the WebKit + * headers included when compiling the code. + * + */ + +/** * webkit_get_major_version: * * Returns the major version number of the WebKit library. diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp index 3dbcfe88f..d2c8bbdf9 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp @@ -20,11 +20,14 @@ #include "config.h" #include "WebKitWebContext.h" +#include "WebCookieManagerProxy.h" +#include "WebGeolocationManagerProxy.h" #include "WebKitCookieManagerPrivate.h" #include "WebKitDownloadClient.h" #include "WebKitDownloadPrivate.h" #include "WebKitFaviconDatabasePrivate.h" #include "WebKitGeolocationProvider.h" +#include "WebKitInjectedBundleClient.h" #include "WebKitPluginPrivate.h" #include "WebKitPrivate.h" #include "WebKitRequestManagerClient.h" @@ -32,6 +35,8 @@ #include "WebKitTextChecker.h" #include "WebKitURISchemeRequestPrivate.h" #include "WebKitWebContextPrivate.h" +#include "WebKitWebViewBasePrivate.h" +#include "WebKitWebViewGroupPrivate.h" #include "WebResourceCacheManagerProxy.h" #include <WebCore/FileSystem.h> #include <WebCore/IconDatabase.h> @@ -46,6 +51,32 @@ using namespace WebKit; +/** + * SECTION: WebKitWebContext + * @Short_description: Manages aspects common to all #WebKitWebView<!-- -->s + * @Title: WebKitWebContext + * + * The #WebKitWebContext manages all aspects common to all + * #WebKitWebView<!-- -->s. + * + * You can define the #WebKitCacheModel with + * webkit_web_context_set_cache_model(), depending on the needs of + * your application. You can access the #WebKitCookieManager or the + * #WebKitSecurityManager to specify the behaviour of your application + * regarding cookies and security, using + * webkit_web_context_get_cookie_manager() and + * webkit_web_context_get_security_manager() for that. + * + * It is also possible to change your preferred language or enable + * spell checking, using webkit_web_context_set_preferred_languages(), + * webkit_web_context_set_spell_checking_languages() and + * webkit_web_context_set_spell_checking_enabled(). + * + * You can use webkit_web_context_register_uri_scheme() to register + * custom URI schemes, and manage several other settings. + * + */ + enum { DOWNLOAD_STARTED, @@ -110,6 +141,10 @@ struct _WebKitWebContextPrivate { OwnPtr<WebKitTextChecker> textChecker; #endif CString faviconDatabaseDirectory; + WebKitTLSErrorsPolicy tlsErrorsPolicy; + + HashMap<uint64_t, WebKitWebView*> webViews; + GRefPtr<WebKitWebViewGroup> defaultWebViewGroup; }; static guint signals[LAST_SIGNAL] = { 0, }; @@ -137,20 +172,39 @@ static void webkit_web_context_class_init(WebKitWebContextClass* webContextClass WEBKIT_TYPE_DOWNLOAD); } +static CString injectedBundleDirectory() +{ + const char* bundleDirectory = g_getenv("WEBKIT_INJECTED_BUNDLE_PATH"); + if (bundleDirectory && g_file_test(bundleDirectory, G_FILE_TEST_IS_DIR)) + return bundleDirectory; + + static const char* injectedBundlePath = LIBDIR G_DIR_SEPARATOR_S "webkit2gtk-" WEBKITGTK_API_VERSION_STRING + G_DIR_SEPARATOR_S "injected-bundle" G_DIR_SEPARATOR_S; + return injectedBundlePath; +} + +static CString injectedBundleFilename() +{ + GOwnPtr<char> bundleFilename(g_build_filename(injectedBundleDirectory().data(), "libwebkit2gtkinjectedbundle.so", NULL)); + return bundleFilename.get(); +} + static gpointer createDefaultWebContext(gpointer) { static GRefPtr<WebKitWebContext> webContext = adoptGRef(WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, NULL))); WebKitWebContextPrivate* priv = webContext->priv; - priv->context = WebContext::create(String()); - priv->requestManager = webContext->priv->context->soupRequestManagerProxy(); + priv->context = WebContext::create(WebCore::filenameToString(injectedBundleFilename().data())); + priv->requestManager = webContext->priv->context->supplement<WebSoupRequestManagerProxy>(); priv->context->setCacheModel(CacheModelPrimaryWebBrowser); + priv->tlsErrorsPolicy = WEBKIT_TLS_ERRORS_POLICY_IGNORE; + attachInjectedBundleClientToContext(webContext.get()); attachDownloadClientToContext(webContext.get()); attachRequestManagerClientToContext(webContext.get()); #if ENABLE(GEOLOCATION) - priv->geolocationProvider = WebKitGeolocationProvider::create(priv->context->geolocationManagerProxy()); + priv->geolocationProvider = WebKitGeolocationProvider::create(priv->context->supplement<WebGeolocationManagerProxy>()); #endif #if ENABLE(SPELLCHECK) priv->textChecker = WebKitTextChecker::create(); @@ -258,7 +312,7 @@ void webkit_web_context_clear_cache(WebKitWebContext* context) { g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - context->priv->context->resourceCacheManagerProxy()->clearCacheForAllOrigins(AllResourceCaches); + context->priv->context->supplement<WebResourceCacheManagerProxy>()->clearCacheForAllOrigins(AllResourceCaches); } typedef HashMap<DownloadProxy*, GRefPtr<WebKitDownload> > DownloadsMap; @@ -304,7 +358,7 @@ WebKitCookieManager* webkit_web_context_get_cookie_manager(WebKitWebContext* con WebKitWebContextPrivate* priv = context->priv; if (!priv->cookieManager) - priv->cookieManager = adoptGRef(webkitCookieManagerCreate(priv->context->cookieManagerProxy())); + priv->cookieManager = adoptGRef(webkitCookieManagerCreate(priv->context->supplement<WebCookieManagerProxy>())); return priv->cookieManager.get(); } @@ -439,15 +493,18 @@ void webkit_web_context_set_additional_plugins_directory(WebKitWebContext* conte context->priv->context->setAdditionalPluginsDirectory(WebCore::filenameToString(directory)); } -struct GetPluginsAsyncData { - Vector<PluginModuleInfo> plugins; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(GetPluginsAsyncData) +static void destroyPluginList(GList* plugins) +{ + g_list_free_full(plugins, g_object_unref); +} -static void webkitWebContextGetPluginThread(GSimpleAsyncResult* result, GObject* object, GCancellable*) +static void webkitWebContextGetPluginThread(GTask* task, gpointer object, gpointer taskData, GCancellable*) { - GetPluginsAsyncData* data = static_cast<GetPluginsAsyncData*>(g_simple_async_result_get_op_res_gpointer(result)); - data->plugins = WEBKIT_WEB_CONTEXT(object)->priv->context->pluginInfoStore().plugins(); + Vector<PluginModuleInfo> plugins = WEBKIT_WEB_CONTEXT(object)->priv->context->pluginInfoStore().plugins(); + GList* returnValue = 0; + for (size_t i = 0; i < plugins.size(); ++i) + returnValue = g_list_prepend(returnValue, webkitPluginCreate(plugins[i])); + g_task_return_pointer(task, returnValue, reinterpret_cast<GDestroyNotify>(destroyPluginList)); } /** @@ -466,11 +523,8 @@ void webkit_web_context_get_plugins(WebKitWebContext* context, GCancellable* can { g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - GRefPtr<GSimpleAsyncResult> result = adoptGRef(g_simple_async_result_new(G_OBJECT(context), callback, userData, - reinterpret_cast<gpointer>(webkit_web_context_get_plugins))); - g_simple_async_result_set_op_res_gpointer(result.get(), createGetPluginsAsyncData(), - reinterpret_cast<GDestroyNotify>(destroyGetPluginsAsyncData)); - g_simple_async_result_run_in_thread(result.get(), webkitWebContextGetPluginThread, G_PRIORITY_DEFAULT, cancellable); + GRefPtr<GTask> task = adoptGRef(g_task_new(context, cancellable, callback, userData)); + g_task_run_in_thread(task.get(), webkitWebContextGetPluginThread); } /** @@ -487,20 +541,9 @@ void webkit_web_context_get_plugins(WebKitWebContext* context, GCancellable* can GList* webkit_web_context_get_plugins_finish(WebKitWebContext* context, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), 0); - - GSimpleAsyncResult* simpleResult = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simpleResult) == webkit_web_context_get_plugins); - - if (g_simple_async_result_propagate_error(simpleResult, error)) - return 0; - - GetPluginsAsyncData* data = static_cast<GetPluginsAsyncData*>(g_simple_async_result_get_op_res_gpointer(simpleResult)); - GList* plugins = 0; - for (size_t i = 0; i < data->plugins.size(); ++i) - plugins = g_list_prepend(plugins, webkitPluginCreate(data->plugins[i])); + g_return_val_if_fail(g_task_is_valid(result, context), 0); - return plugins; + return static_cast<GList*>(g_task_propagate_pointer(G_TASK(result), error)); } /** @@ -515,8 +558,9 @@ GList* webkit_web_context_get_plugins_finish(WebKitWebContext* context, GAsyncRe * #WebKitWebContext, the #WebKitURISchemeRequestCallback registered will be called with a * #WebKitURISchemeRequest. * It is possible to handle URI scheme requests asynchronously, by calling g_object_ref() on the - * #WebKitURISchemeRequest and calling webkit_uri_scheme_request_finish() later when the data of - * the request is available. + * #WebKitURISchemeRequest and calling webkit_uri_scheme_request_finish() later + * when the data of the request is available or + * webkit_uri_scheme_request_finish_error() in case of error. * * <informalexample><programlisting> * static void @@ -534,12 +578,19 @@ GList* webkit_web_context_get_plugins_finish(WebKitWebContext* context, GAsyncRe * /<!-- -->* Create a GInputStream with the contents of memory about page, and set its length to stream_length *<!-- -->/ * } else if (!g_strcmp0 (path, "applications")) { * /<!-- -->* Create a GInputStream with the contents of applications about page, and set its length to stream_length *<!-- -->/ - * } else { + * } else if (!g_strcmp0 (path, "example")) { * gchar *contents; * - * contents = g_strdup_printf ("<html><body><p>Invalid about:%s page</p></body></html>", path); + * contents = g_strdup_printf ("<html><body><p>Example about page</p></body></html>"); * stream_length = strlen (contents); * stream = g_memory_input_stream_new_from_data (contents, stream_length, g_free); + * } else { + * GError *error; + * + * error = g_error_new (ABOUT_HANDLER_ERROR, ABOUT_HANDLER_ERROR_INVALID, "Invalid about:%s page.", path); + * webkit_uri_scheme_request_finish_error (request, error); + * g_error_free (error); + * return; * } * webkit_uri_scheme_request_finish (request, stream, stream_length, "text/html"); * g_object_unref (stream); @@ -668,6 +719,94 @@ void webkit_web_context_set_preferred_languages(WebKitWebContext* context, const WebCore::languageDidChange(); } +/** + * webkit_web_context_set_tls_errors_policy: + * @context: a #WebKitWebContext + * @policy: a #WebKitTLSErrorsPolicy + * + * Set the TLS errors policy of @context as @policy + */ +void webkit_web_context_set_tls_errors_policy(WebKitWebContext* context, WebKitTLSErrorsPolicy policy) +{ + g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); + + if (context->priv->tlsErrorsPolicy == policy) + return; + + context->priv->tlsErrorsPolicy = policy; + bool ignoreTLSErrors = policy == WEBKIT_TLS_ERRORS_POLICY_IGNORE; + if (context->priv->context->ignoreTLSErrors() != ignoreTLSErrors) + context->priv->context->setIgnoreTLSErrors(ignoreTLSErrors); +} + +/** + * webkit_web_context_get_tls_errors_policy: + * @context: a #WebKitWebContext + * + * Get the TLS errors policy of @context + * + * Returns: a #WebKitTLSErrorsPolicy + */ +WebKitTLSErrorsPolicy webkit_web_context_get_tls_errors_policy(WebKitWebContext* context) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), WEBKIT_TLS_ERRORS_POLICY_IGNORE); + + return context->priv->tlsErrorsPolicy; +} + +/** + * webkit_web_context_set_web_extensions_directory: + * @context: a #WebKitWebContext + * @directory: the directory to add + * + * Set the directory where WebKit will look for Web Extensions. + * This method must be called before loading anything in this context, otherwise + * it will not have any effect. + */ +void webkit_web_context_set_web_extensions_directory(WebKitWebContext* context, const char* directory) +{ + g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); + g_return_if_fail(directory); + + // We pass the additional web extensions directory to the injected bundle as initialization user data. + context->priv->context->setInjectedBundleInitializationUserData(WebString::create(WebCore::filenameToString(directory))); +} + +/** + * webkit_web_context_set_disk_cache_directory: + * @context: a #WebKitWebContext + * @directory: the directory to set + * + * Set the directory where disk cache files will be stored + * This method must be called before loading anything in this context, otherwise + * it will not have any effect. + */ +void webkit_web_context_set_disk_cache_directory(WebKitWebContext* context, const char* directory) +{ + g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); + g_return_if_fail(directory); + + context->priv->context->setDiskCacheDirectory(WebCore::filenameToString(directory)); +} + +/** + * webkit_web_context_prefetch_dns: + * @context: a #WebKitWebContext + * @hostname: a hostname to be resolved + * + * Resolve the domain name of the given @hostname in advance, so that if a URI + * of @hostname is requested the load will be performed more quickly. + */ +void webkit_web_context_prefetch_dns(WebKitWebContext* context, const char* hostname) +{ + g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); + g_return_if_fail(hostname); + + ImmutableDictionary::MapType message; + message.set(String::fromUTF8("Hostname"), WebString::create(String::fromUTF8(hostname))); + context->priv->context->postMessageToInjectedBundle(String::fromUTF8("PrefetchDNS"), ImmutableDictionary::adopt(message).get()); +} + WebKitDownload* webkitWebContextGetOrCreateDownload(DownloadProxy* downloadProxy) { GRefPtr<WebKitDownload> download = downloadsMap().get(downloadProxy); @@ -681,8 +820,9 @@ WebKitDownload* webkitWebContextGetOrCreateDownload(DownloadProxy* downloadProxy WebKitDownload* webkitWebContextStartDownload(WebKitWebContext* context, const char* uri, WebPageProxy* initiatingPage) { - DownloadProxy* downloadProxy = context->priv->context->download(initiatingPage, WebCore::ResourceRequest(String::fromUTF8(uri))); - WebKitDownload* download = webkitDownloadCreate(downloadProxy); + WebCore::ResourceRequest request(String::fromUTF8(uri)); + DownloadProxy* downloadProxy = context->priv->context->download(initiatingPage, request); + WebKitDownload* download = webkitDownloadCreateForRequest(downloadProxy, request); downloadsMap().set(downloadProxy, download); return download; } @@ -733,3 +873,32 @@ void webkitWebContextDidFinishURIRequest(WebKitWebContext* context, uint64_t req { context->priv->uriSchemeRequests.remove(requestID); } + +void webkitWebContextCreatePageForWebView(WebKitWebContext* context, WebKitWebView* webView, WebKitWebViewGroup* webViewGroup) +{ + WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(webView); + WebPageGroup* pageGroup = webViewGroup ? webkitWebViewGroupGetPageGroup(webViewGroup) : 0; + webkitWebViewBaseCreateWebPage(webViewBase, context->priv->context.get(), pageGroup); + + WebPageProxy* page = webkitWebViewBaseGetPage(webViewBase); + context->priv->webViews.set(page->pageID(), webView); + + if (!pageGroup && !context->priv->defaultWebViewGroup) + context->priv->defaultWebViewGroup = adoptGRef(webkitWebViewGroupCreate(page->pageGroup())); +} + +void webkitWebContextWebViewDestroyed(WebKitWebContext* context, WebKitWebView* webView) +{ + WebPageProxy* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView)); + context->priv->webViews.remove(page->pageID()); +} + +WebKitWebView* webkitWebContextGetWebViewForPage(WebKitWebContext* context, WebPageProxy* page) +{ + return page ? context->priv->webViews.get(page->pageID()) : 0; +} + +WebKitWebViewGroup* webkitWebContextGetDefaultWebViewGroup(WebKitWebContext* context) +{ + return context->priv->defaultWebViewGroup.get(); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.h index ae79bec87..dd38c1d37 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.h @@ -62,6 +62,18 @@ typedef enum { } WebKitCacheModel; /** + * WebKitTLSErrorsPolicy: + * @WEBKIT_TLS_ERRORS_POLICY_IGNORE: Ignore TLS errors. + * @WEBKIT_TLS_ERRORS_POLICY_FAIL: TLS errors make the load to finish with an error. + * + * Enum values used to denote the TLS errors policy. + */ +typedef enum { + WEBKIT_TLS_ERRORS_POLICY_IGNORE, + WEBKIT_TLS_ERRORS_POLICY_FAIL +} WebKitTLSErrorsPolicy; + +/** * WebKitURISchemeRequestCallback: * @request: the #WebKitURISchemeRequest * @user_data: user data passed to the callback @@ -86,11 +98,14 @@ struct _WebKitWebContext { struct _WebKitWebContextClass { GObjectClass parent; - /* Padding for future expansion */ void (*_webkit_reserved0) (void); void (*_webkit_reserved1) (void); void (*_webkit_reserved2) (void); void (*_webkit_reserved3) (void); + void (*_webkit_reserved4) (void); + void (*_webkit_reserved5) (void); + void (*_webkit_reserved6) (void); + void (*_webkit_reserved7) (void); }; WEBKIT_API GType @@ -165,6 +180,25 @@ WEBKIT_API void webkit_web_context_set_preferred_languages (WebKitWebContext *context, const gchar * const *languages); +WEBKIT_API void +webkit_web_context_set_tls_errors_policy (WebKitWebContext *context, + WebKitTLSErrorsPolicy policy); + +WEBKIT_API WebKitTLSErrorsPolicy +webkit_web_context_get_tls_errors_policy (WebKitWebContext *context); + +WEBKIT_API void +webkit_web_context_set_web_extensions_directory (WebKitWebContext *context, + const gchar *directory); + +WEBKIT_API void +webkit_web_context_prefetch_dns (WebKitWebContext *context, + const gchar *hostname); + +WEBKIT_API void +webkit_web_context_set_disk_cache_directory (WebKitWebContext *context, + const gchar *directory); + G_END_DECLS #endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContextPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContextPrivate.h index f97e167ed..81c473c56 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContextPrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContextPrivate.h @@ -31,6 +31,7 @@ #include "WebKitPrivate.h" #include "WebKitURISchemeRequest.h" #include "WebKitWebContext.h" +#include "WebKitWebViewGroup.h" #include "WebSoupRequestManagerProxy.h" WebKit::WebContext* webkitWebContextGetContext(WebKitWebContext*); @@ -42,5 +43,9 @@ WebKit::WebSoupRequestManagerProxy* webkitWebContextGetRequestManager(WebKitWebC void webkitWebContextReceivedURIRequest(WebKitWebContext*, WebKitURISchemeRequest*); void webkitWebContextDidFailToLoadURIRequest(WebKitWebContext*, uint64_t requestID); void webkitWebContextDidFinishURIRequest(WebKitWebContext*, uint64_t requestID); +void webkitWebContextCreatePageForWebView(WebKitWebContext*, WebKitWebView*, WebKitWebViewGroup*); +void webkitWebContextWebViewDestroyed(WebKitWebContext*, WebKitWebView*); +WebKitWebView* webkitWebContextGetWebViewForPage(WebKitWebContext*, WebKit::WebPageProxy*); +WebKitWebViewGroup* webkitWebContextGetDefaultWebViewGroup(WebKitWebContext*); #endif // WebKitWebContextPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.cpp index 378a1f4c0..3839ad3e2 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.cpp @@ -29,6 +29,35 @@ using namespace WebKit; +/** + * SECTION: WebKitWebInspector + * @Short_description: Access to the WebKit inspector + * @Title: WebKitWebInspector + * + * The WebKit Inspector is a graphical tool to inspect and change the + * content of a #WebKitWebView. It also includes an interactive + * JavaScript debugger. Using this class one can get a #GtkWidget + * which can be embedded into an application to show the inspector. + * + * The inspector is available when the #WebKitSettings of the + * #WebKitWebView has set the #WebKitSettings:enable-developer-extras + * to true, otherwise no inspector is available. + * + * <informalexample><programlisting> + * /<!-- -->* Enable the developer extras *<!-- -->/ + * WebKitSettings *setting = webkit_web_view_get_settings (WEBKIT_WEB_VIEW(my_webview)); + * g_object_set (G_OBJECT(settings), "enable-developer-extras", TRUE, NULL); + * + * /<!-- -->* Load some data or reload to be able to inspect the page*<!-- -->/ + * webkit_web_load_uri (WEBKIT_WEB_VIEW(my_webview), "http://www.gnome.org"); + * + * /<!-- -->* Show the inspector *<!-- -->/ + * WebKitWebInspector *inspector = webkit_web_view_get_inspector (WEBKIT_WEB_VIEW(my_webview)); + * webkit_web_inspector_show (WEBKIT_WEB_INSPECTOR(inspector)); + * </programlisting></informalexample> + * + */ + enum { OPEN_WINDOW, BRING_TO_FRONT, diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h index 10c281094..67f0f4957 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h @@ -49,6 +49,11 @@ struct _WebKitWebInspector { struct _WebKitWebInspectorClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp index 7a540d353..f81cd2b17 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp @@ -31,6 +31,23 @@ using namespace WebKit; +/** + * SECTION: WebKitWebResource + * @Short_description: Represents a resource at the end of a URI + * @Title: WebKitWebResource + * + * A #WebKitWebResource encapsulates content for each resource at the + * end of a particular URI. For example, one #WebKitWebResource will + * be created for each separate image and stylesheet when a page is + * loaded. + * + * You can access the response and the URI for a given + * #WebKitWebResource, using webkit_web_resource_get_uri() and + * webkit_web_resource_get_response(), as well as the raw data, using + * webkit_web_resource_get_data(). + * + */ + enum { SENT_REQUEST, RECEIVED_DATA, @@ -90,7 +107,7 @@ static void webkit_web_resource_class_init(WebKitWebResourceClass* resourceClass PROP_URI, g_param_spec_string("uri", _("URI"), - _("The current active URI of the result"), + _("The current active URI of the resource"), 0, WEBKIT_PARAM_READABLE)); @@ -238,7 +255,7 @@ WebFrameProxy* webkitWebResourceGetFrame(WebKitWebResource* resource) * webkit_web_resource_get_uri: * @resource: a #WebKitWebResource * - * Returns the current active URI of @web_view. The active URI might change during + * Returns the current active URI of @resource. The active URI might change during * a load operation: * * <orderedlist> @@ -294,20 +311,15 @@ WebKitURIResponse* webkit_web_resource_get_response(WebKitWebResource* resource) struct ResourceGetDataAsyncData { RefPtr<WebData> webData; - GRefPtr<GCancellable> cancellable; }; WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ResourceGetDataAsyncData) static void resourceDataCallback(WKDataRef wkData, WKErrorRef, void* context) { - GRefPtr<GSimpleAsyncResult> result = adoptGRef(G_SIMPLE_ASYNC_RESULT(context)); - ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_simple_async_result_get_op_res_gpointer(result.get())); - GError* error = 0; - if (g_cancellable_set_error_if_cancelled(data->cancellable.get(), &error)) - g_simple_async_result_take_error(result.get(), error); - else - data->webData = toImpl(wkData); - g_simple_async_result_complete(result.get()); + GRefPtr<GTask> task = adoptGRef(G_TASK(context)); + ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task.get())); + data->webData = toImpl(wkData); + g_task_return_boolean(task.get(), TRUE); } /** @@ -326,16 +338,13 @@ void webkit_web_resource_get_data(WebKitWebResource* resource, GCancellable* can { g_return_if_fail(WEBKIT_IS_WEB_RESOURCE(resource)); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(resource), callback, userData, - reinterpret_cast<gpointer>(webkit_web_resource_get_data)); - ResourceGetDataAsyncData* data = createResourceGetDataAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyResourceGetDataAsyncData)); + GTask* task = g_task_new(resource, cancellable, callback, userData); + g_task_set_task_data(task, createResourceGetDataAsyncData(), reinterpret_cast<GDestroyNotify>(destroyResourceGetDataAsyncData)); if (resource->priv->isMainResource) - resource->priv->frame->getMainResourceData(DataCallback::create(result, resourceDataCallback)); + resource->priv->frame->getMainResourceData(DataCallback::create(task, resourceDataCallback)); else { String url = String::fromUTF8(resource->priv->uri.data()); - resource->priv->frame->getResourceData(WebURL::create(url).get(), DataCallback::create(result, resourceDataCallback)); + resource->priv->frame->getResourceData(WebURL::create(url).get(), DataCallback::create(task, resourceDataCallback)); } } @@ -354,15 +363,13 @@ void webkit_web_resource_get_data(WebKitWebResource* resource, GCancellable* can guchar* webkit_web_resource_get_data_finish(WebKitWebResource* resource, GAsyncResult* result, gsize* length, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), 0); - - GSimpleAsyncResult* simple = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simple) == webkit_web_resource_get_data); + g_return_val_if_fail(g_task_is_valid(result, resource), 0); - if (g_simple_async_result_propagate_error(simple, error)) + GTask* task = G_TASK(result); + if (!g_task_propagate_boolean(task, error)) return 0; - ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_simple_async_result_get_op_res_gpointer(simple)); + ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task)); if (length) *length = data->webData->size(); return static_cast<guchar*>(g_memdup(data->webData->bytes(), data->webData->size())); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.h index 1cfada0fb..7463686ab 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.h @@ -50,6 +50,11 @@ struct _WebKitWebResource { struct _WebKitWebResourceClass { GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp index fb0c5ed9a..29497090d 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp @@ -21,9 +21,13 @@ #include "config.h" #include "WebKitWebView.h" +#include "ImageOptions.h" +#include "PlatformCertificateInfo.h" +#include "WebCertificateInfo.h" #include "WebContextMenuItem.h" #include "WebContextMenuItemData.h" #include "WebData.h" +#include "WebKitAuthenticationDialog.h" #include "WebKitBackForwardListPrivate.h" #include "WebKitContextMenuClient.h" #include "WebKitContextMenuItemPrivate.h" @@ -41,10 +45,8 @@ #include "WebKitPolicyClient.h" #include "WebKitPrintOperationPrivate.h" #include "WebKitPrivate.h" -#include "WebKitResourceLoadClient.h" #include "WebKitResponsePolicyDecision.h" #include "WebKitScriptDialogPrivate.h" -#include "WebKitSettingsPrivate.h" #include "WebKitUIClient.h" #include "WebKitURIRequestPrivate.h" #include "WebKitURIResponsePrivate.h" @@ -52,6 +54,7 @@ #include "WebKitWebInspectorPrivate.h" #include "WebKitWebResourcePrivate.h" #include "WebKitWebViewBasePrivate.h" +#include "WebKitWebViewGroupPrivate.h" #include "WebKitWebViewPrivate.h" #include "WebKitWindowPropertiesPrivate.h" #include <JavaScriptCore/APICast.h> @@ -67,6 +70,21 @@ using namespace WebKit; using namespace WebCore; +/** + * SECTION: WebKitWebView + * @Short_description: The central class of the WebKit2GTK+ API + * @Title: WebKitWebView + * + * #WebKitWebView is the central class of the WebKit2GTK+ API. It is + * responsible for managing the drawing of the content and forwarding + * of events. You can load any URI into the #WebKitWebView or a data + * string. With #WebKitSettings you can control various aspects of the + * rendering and loading of the content. + * + * Note that #WebKitWebView is scrollable by itself, so you don't need + * to embed it in a #GtkScrolledWindow. + */ + enum { LOAD_CHANGED, LOAD_FAILED, @@ -97,6 +115,10 @@ enum { SUBMIT_FORM, + INSECURE_CONTENT_DETECTED, + + WEB_PROCESS_CRASHED, + LAST_SIGNAL }; @@ -104,16 +126,18 @@ enum { PROP_0, PROP_WEB_CONTEXT, + PROP_GROUP, PROP_TITLE, PROP_ESTIMATED_LOAD_PROGRESS, PROP_FAVICON, PROP_URI, PROP_ZOOM_LEVEL, - PROP_IS_LOADING + PROP_IS_LOADING, + PROP_VIEW_MODE }; typedef HashMap<uint64_t, GRefPtr<WebKitWebResource> > LoadingResourcesMap; -typedef HashMap<String, GRefPtr<WebKitWebResource> > ResourcesMap; +typedef HashMap<uint64_t, GRefPtr<GTask> > SnapshotResultsMap; struct _WebKitWebViewPrivate { ~_WebKitWebViewPrivate() @@ -132,6 +156,7 @@ struct _WebKitWebViewPrivate { double estimatedLoadProgress; CString activeURI; bool isLoading; + WebKitViewMode viewMode; bool waitingForMainResource; unsigned long mainResourceResponseHandlerID; @@ -139,6 +164,8 @@ struct _WebKitWebViewPrivate { GRefPtr<WebKitBackForwardList> backForwardList; GRefPtr<WebKitSettings> settings; + unsigned long settingsChangedHandlerID; + GRefPtr<WebKitWebViewGroup> group; GRefPtr<WebKitWindowProperties> windowProperties; GRefPtr<GMainLoop> modalLoop; @@ -151,7 +178,6 @@ struct _WebKitWebViewPrivate { GRefPtr<WebKitWebResource> mainResource; LoadingResourcesMap loadingResourcesMap; - ResourcesMap subresourcesMap; GRefPtr<WebKitWebInspector> inspector; @@ -159,6 +185,8 @@ struct _WebKitWebViewPrivate { GRefPtr<GCancellable> faviconCancellable; CString faviconURI; unsigned long faviconChangedHandlerID; + + SnapshotResultsMap snapshotResultsMap; }; static guint signals[LAST_SIGNAL] = { 0, }; @@ -338,10 +366,16 @@ static void faviconChangedCallback(WebKitFaviconDatabase* database, const char* webkitWebViewUpdateFaviconURI(webView, faviconURI); } -static void webkitWebViewSetSettings(WebKitWebView* webView, WebKitSettings* settings) +static void webkitWebViewUpdateSettings(WebKitWebView* webView) { - webView->priv->settings = settings; - webkitSettingsAttachSettingsToPage(webView->priv->settings.get(), getPage(webView)); + // We keep a ref of the current settings to disconnect the signals when settings change in the group. + webView->priv->settings = webkit_web_view_get_settings(webView); + + WebKitSettings* settings = webView->priv->settings.get(); + WebPageProxy* page = getPage(webView); + page->setCanRunModal(webkit_settings_get_allow_modal_dialogs(settings)); + page->setCustomUserAgent(String::fromUTF8(webkit_settings_get_user_agent(settings))); + g_signal_connect(settings, "notify::allow-modal-dialogs", G_CALLBACK(allowModalDialogsChanged), webView); g_signal_connect(settings, "notify::zoom-text-only", G_CALLBACK(zoomTextOnlyChanged), webView); g_signal_connect(settings, "notify::user-agent", G_CALLBACK(userAgentChanged), webView); @@ -355,6 +389,20 @@ static void webkitWebViewDisconnectSettingsSignalHandlers(WebKitWebView* webView g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(userAgentChanged), webView); } +static void webkitWebViewSettingsChanged(WebKitWebViewGroup* group, GParamSpec*, WebKitWebView* webView) +{ + webkitWebViewDisconnectSettingsSignalHandlers(webView); + webkitWebViewUpdateSettings(webView); +} + +static void webkitWebViewDisconnectSettingsChangedSignalHandler(WebKitWebView* webView) +{ + WebKitWebViewPrivate* priv = webView->priv; + if (priv->settingsChangedHandlerID) + g_signal_handler_disconnect(webkit_web_view_get_group(webView), priv->settingsChangedHandlerID); + priv->settingsChangedHandlerID = 0; +} + static void webkitWebViewDisconnectMainResourceResponseChangedSignalHandler(WebKitWebView* webView) { WebKitWebViewPrivate* priv = webView->priv; @@ -437,15 +485,13 @@ static void webkitWebViewConstructed(GObject* object) WebKitWebView* webView = WEBKIT_WEB_VIEW(object); WebKitWebViewPrivate* priv = webView->priv; - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(webView); + webkitWebContextCreatePageForWebView(priv->context, webView, priv->group.get()); - webkitWebViewBaseCreateWebPage(webViewBase, webkitWebContextGetContext(priv->context), 0); - webkitWebViewBaseSetDownloadRequestHandler(webViewBase, webkitWebViewHandleDownloadRequest); + webkitWebViewBaseSetDownloadRequestHandler(WEBKIT_WEB_VIEW_BASE(webView), webkitWebViewHandleDownloadRequest); attachLoaderClientToView(webView); attachUIClientToView(webView); attachPolicyClientToView(webView); - attachResourceLoadClientToView(webView); attachFullScreenClientToView(webView); attachContextMenuClientToView(webView); attachFormClientToView(webView); @@ -453,8 +499,9 @@ static void webkitWebViewConstructed(GObject* object) priv->backForwardList = adoptGRef(webkitBackForwardListCreate(getPage(webView)->backForwardList())); priv->windowProperties = adoptGRef(webkitWindowPropertiesCreate()); - GRefPtr<WebKitSettings> settings = adoptGRef(webkit_settings_new()); - webkitWebViewSetSettings(webView, settings.get()); + webkitWebViewUpdateSettings(webView); + priv->settingsChangedHandlerID = + g_signal_connect(webkit_web_view_get_group(webView), "notify::settings", G_CALLBACK(webkitWebViewSettingsChanged), webView); } static void webkitWebViewSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) @@ -467,9 +514,17 @@ static void webkitWebViewSetProperty(GObject* object, guint propId, const GValue webView->priv->context = webContext ? WEBKIT_WEB_CONTEXT(webContext) : webkit_web_context_get_default(); break; } + case PROP_GROUP: { + gpointer group = g_value_get_object(value); + webView->priv->group = group ? WEBKIT_WEB_VIEW_GROUP(group) : 0; + break; + } case PROP_ZOOM_LEVEL: webkit_web_view_set_zoom_level(webView, g_value_get_double(value)); break; + case PROP_VIEW_MODE: + webkit_web_view_set_view_mode(webView, static_cast<WebKitViewMode>(g_value_get_enum(value))); + break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); } @@ -483,6 +538,9 @@ static void webkitWebViewGetProperty(GObject* object, guint propId, GValue* valu case PROP_WEB_CONTEXT: g_value_take_object(value, webView->priv->context); break; + case PROP_GROUP: + g_value_set_object(value, webkit_web_view_get_group(webView)); + break; case PROP_TITLE: g_value_set_string(value, webView->priv->title.data()); break; @@ -501,6 +559,9 @@ static void webkitWebViewGetProperty(GObject* object, guint propId, GValue* valu case PROP_IS_LOADING: g_value_set_boolean(value, webkit_web_view_is_loading(webView)); break; + case PROP_VIEW_MODE: + g_value_set_enum(value, webkit_web_view_get_view_mode(webView)); + break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); } @@ -511,9 +572,12 @@ static void webkitWebViewDispose(GObject* object) WebKitWebView* webView = WEBKIT_WEB_VIEW(object); webkitWebViewCancelFaviconRequest(webView); webkitWebViewDisconnectMainResourceResponseChangedSignalHandler(webView); + webkitWebViewDisconnectSettingsChangedSignalHandler(webView); webkitWebViewDisconnectSettingsSignalHandlers(webView); webkitWebViewDisconnectFaviconDatabaseSignalHandlers(webView); + webkitWebContextWebViewDestroyed(webView->priv->context, webView); + G_OBJECT_CLASS(webkit_web_view_parent_class)->dispose(object); } @@ -554,6 +618,20 @@ static void webkit_web_view_class_init(WebKitWebViewClass* webViewClass) _("The web context for the view"), WEBKIT_TYPE_WEB_CONTEXT, static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); + /** + * WebKitWebView:group: + * + * The #WebKitWebViewGroup of the view. + */ + g_object_class_install_property( + gObjectClass, + PROP_GROUP, + g_param_spec_object( + "group", + _("WebView Group"), + _("The WebKitWebViewGroup of the view"), + WEBKIT_TYPE_WEB_VIEW_GROUP, + static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); /** * WebKitWebView:title: @@ -646,6 +724,21 @@ static void webkit_web_view_class_init(WebKitWebViewClass* webViewClass) WEBKIT_PARAM_READABLE)); /** + * WebKitWebView:view-mode: + * + * The #WebKitViewMode that is used to display the contents of a #WebKitWebView. + * See also webkit_web_view_set_view_mode(). + */ + g_object_class_install_property(gObjectClass, + PROP_VIEW_MODE, + g_param_spec_enum("view-mode", + "View Mode", + _("The view mode to display the web view contents"), + WEBKIT_TYPE_VIEW_MODE, + WEBKIT_VIEW_MODE_WEB, + WEBKIT_PARAM_READWRITE)); + + /** * WebKitWebView::load-changed: * @web_view: the #WebKitWebView on which the signal is emitted * @load_event: the #WebKitLoadEvent @@ -1230,6 +1323,49 @@ static void webkit_web_view_class_init(WebKitWebViewClass* webViewClass) g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, WEBKIT_TYPE_FORM_SUBMISSION_REQUEST); + + /** + * WebKitWebView::insecure-content-detected: + * @web_view: the #WebKitWebView on which the signal is emitted + * @event: the #WebKitInsecureContentEvent + * + * This signal is emitted when insecure content has been detected + * in a page loaded through a secure connection. This typically + * means that a external resource from an unstrusted source has + * been run or displayed, resulting in a mix of HTTPS and + * non-HTTPS content. + * + * You can check the @event parameter to know exactly which kind + * of event has been detected (see #WebKitInsecureContentEvent). + */ + signals[INSECURE_CONTENT_DETECTED] = + g_signal_new("insecure-content-detected", + G_TYPE_FROM_CLASS(webViewClass), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(WebKitWebViewClass, insecure_content_detected), + 0, 0, + g_cclosure_marshal_VOID__ENUM, + G_TYPE_NONE, 1, + WEBKIT_TYPE_INSECURE_CONTENT_EVENT); + + /** + * WebKitWebView::web-process-crashed: + * @web_view: the #WebKitWebView + * + * This signal is emitted when the web process crashes. + * + * Returns: %TRUE to stop other handlers from being invoked for the event. + * %FALSE to propagate the event further. + */ + signals[WEB_PROCESS_CRASHED] = g_signal_new( + "web-process-crashed", + G_TYPE_FROM_CLASS(webViewClass), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(WebKitWebViewClass, web_process_crashed), + g_signal_accumulator_true_handled, + 0, + webkit_marshal_BOOLEAN__VOID, + G_TYPE_BOOLEAN, 0); } static void webkitWebViewSetIsLoading(WebKitWebView* webView, bool isLoading) @@ -1247,15 +1383,6 @@ static void webkitWebViewSetIsLoading(WebKitWebView* webView, bool isLoading) g_object_thaw_notify(G_OBJECT(webView)); } -static void setCertificateToMainResource(WebKitWebView* webView) -{ - WebKitWebViewPrivate* priv = webView->priv; - ASSERT(priv->mainResource.get()); - - webkitURIResponseSetCertificateInfo(webkit_web_resource_get_response(priv->mainResource.get()), - webkitWebResourceGetFrame(priv->mainResource.get())->certificateInfo()); -} - static void webkitWebViewEmitLoadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent) { if (loadEvent == WEBKIT_LOAD_STARTED) { @@ -1300,15 +1427,13 @@ void webkitWebViewLoadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent) GOwnPtr<char> faviconURI(webkit_favicon_database_get_favicon_uri(database, priv->activeURI.data())); webkitWebViewUpdateFaviconURI(webView, faviconURI.get()); - priv->subresourcesMap.clear(); if (!priv->mainResource) { // When a page is loaded from the history cache, the main resource load callbacks // are called when the main frame load is finished. We want to make sure there's a // main resource available when load has been committed, so we delay the emission of // load-changed signal until main resource object has been created. priv->waitingForMainResource = true; - } else - setCertificateToMainResource(webView); + } } if (priv->waitingForMainResource) @@ -1325,6 +1450,19 @@ void webkitWebViewLoadFailed(WebKitWebView* webView, WebKitLoadEvent loadEvent, g_signal_emit(webView, signals[LOAD_CHANGED], 0, WEBKIT_LOAD_FINISHED); } +void webkitWebViewLoadFailedWithTLSErrors(WebKitWebView* webView, const char* failingURI, GError *error, GTlsCertificateFlags tlsErrors, GTlsCertificate* certificate) +{ + webkitWebViewSetIsLoading(webView, false); + + WebKitTLSErrorsPolicy tlsErrorsPolicy = webkit_web_context_get_tls_errors_policy(webView->priv->context); + if (tlsErrorsPolicy == WEBKIT_TLS_ERRORS_POLICY_FAIL) { + webkitWebViewLoadFailed(webView, WEBKIT_LOAD_STARTED, failingURI, error); + return; + } + + g_signal_emit(webView, signals[LOAD_CHANGED], 0, WEBKIT_LOAD_FINISHED); +} + void webkitWebViewSetTitle(WebKitWebView* webView, const CString& title) { WebKitWebViewPrivate* priv = webView->priv; @@ -1454,7 +1592,6 @@ void webkitWebViewPrintFrame(WebKitWebView* webView, WebFrameProxy* frame) static void mainResourceResponseChangedCallback(WebKitWebResource*, GParamSpec*, WebKitWebView* webView) { webkitWebViewDisconnectMainResourceResponseChangedSignalHandler(webView); - setCertificateToMainResource(webView); webkitWebViewEmitDelayedLoadEvents(webView); } @@ -1485,7 +1622,6 @@ void webkitWebViewResourceLoadStarted(WebKitWebView* webView, WebFrameProxy* fra WebKitWebResource* webkitWebViewGetLoadingWebResource(WebKitWebView* webView, uint64_t resourceIdentifier) { GRefPtr<WebKitWebResource> resource = webView->priv->loadingResourcesMap.get(resourceIdentifier); - ASSERT(resource.get()); return resource.get(); } @@ -1496,16 +1632,6 @@ void webkitWebViewRemoveLoadingWebResource(WebKitWebView* webView, uint64_t reso priv->loadingResourcesMap.remove(resourceIdentifier); } -WebKitWebResource* webkitWebViewResourceLoadFinished(WebKitWebView* webView, uint64_t resourceIdentifier) -{ - WebKitWebViewPrivate* priv = webView->priv; - WebKitWebResource* resource = webkitWebViewGetLoadingWebResource(webView, resourceIdentifier); - if (resource != priv->mainResource) - priv->subresourcesMap.set(String::fromUTF8(webkit_web_resource_get_uri(resource)), resource); - webkitWebViewRemoveLoadingWebResource(webView, resourceIdentifier); - return resource; -} - bool webkitWebViewEnterFullScreen(WebKitWebView* webView) { gboolean returnValue; @@ -1612,16 +1738,26 @@ void webkitWebViewSubmitFormRequest(WebKitWebView* webView, WebKitFormSubmission void webkitWebViewHandleAuthenticationChallenge(WebKitWebView* webView, AuthenticationChallengeProxy* authenticationChallenge) { - WebKit2GtkAuthenticationDialog* dialog = new WebKit2GtkAuthenticationDialog(authenticationChallenge); - webkitWebViewBaseAddAuthenticationDialog(WEBKIT_WEB_VIEW_BASE(webView), dialog); - dialog->show(); + CredentialStorageMode credentialStorageMode; + if (webkit_settings_get_enable_private_browsing(webkit_web_view_get_settings(webView))) + credentialStorageMode = DisallowPersistentStorage; + else + credentialStorageMode = AllowPersistentStorage; + + webkitWebViewBaseAddAuthenticationDialog(WEBKIT_WEB_VIEW_BASE(webView), webkitAuthenticationDialogNew(authenticationChallenge, credentialStorageMode)); +} + +void webkitWebViewInsecureContentDetected(WebKitWebView* webView, WebKitInsecureContentEvent type) +{ + g_signal_emit(webView, signals[INSECURE_CONTENT_DETECTED], 0, type); } /** * webkit_web_view_new: * - * Creates a new #WebKitWebView with the default #WebKitWebContext. - * See also webkit_web_view_new_with_context(). + * Creates a new #WebKitWebView with the default #WebKitWebContext and the + * default #WebKitWebViewGroup. + * See also webkit_web_view_new_with_context() and webkit_web_view_new_with_group(). * * Returns: The newly created #WebKitWebView widget */ @@ -1634,7 +1770,9 @@ GtkWidget* webkit_web_view_new() * webkit_web_view_new_with_context: * @context: the #WebKitWebContext to be used by the #WebKitWebView * - * Creates a new #WebKitWebView with the given #WebKitWebContext. + * Creates a new #WebKitWebView with the given #WebKitWebContext and the + * default #WebKitWebViewGroup. + * See also webkit_web_view_new_with_group(). * * Returns: The newly created #WebKitWebView widget */ @@ -1646,6 +1784,23 @@ GtkWidget* webkit_web_view_new_with_context(WebKitWebContext* context) } /** + * webkit_web_view_new_with_group: + * @group: a #WebKitWebViewGroup + * + * Creates a new #WebKitWebView with the given #WebKitWebViewGroup. + * The view will be part of @group and it will be affected by the + * group properties like the settings. + * + * Returns: The newly created #WebKitWebView widget + */ +GtkWidget* webkit_web_view_new_with_group(WebKitWebViewGroup* group) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW_GROUP(group), 0); + + return GTK_WIDGET(g_object_new(WEBKIT_TYPE_WEB_VIEW, "group", group, NULL)); +} + +/** * webkit_web_view_get_context: * @web_view: a #WebKitWebView * @@ -1661,6 +1816,24 @@ WebKitWebContext* webkit_web_view_get_context(WebKitWebView *webView) } /** + * webkit_web_view_get_group: + * @web_view: a #WebKitWebView + * + * Gets the group @web_view belongs to. + * + * Returns: (transfer none): the #WebKitWebViewGroup to which the view belongs + */ +WebKitWebViewGroup* webkit_web_view_get_group(WebKitWebView* webView) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); + + if (webView->priv->group) + return webView->priv->group.get(); + + return webkitWebContextGetDefaultWebViewGroup(webView->priv->context); +} + +/** * webkit_web_view_load_uri: * @web_view: a #WebKitWebView * @uri: an URI string @@ -1754,7 +1927,26 @@ void webkit_web_view_load_request(WebKitWebView* webView, WebKitURIRequest* requ g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); g_return_if_fail(WEBKIT_IS_URI_REQUEST(request)); - getPage(webView)->loadURLRequest(WebURLRequest::create(webkitURIRequestGetResourceRequest(request)).leakRef()); + ResourceRequest resourceRequest; + webkitURIRequestGetResourceRequest(request, resourceRequest); + RefPtr<WebURLRequest> urlRequest = WebURLRequest::create(resourceRequest); + getPage(webView)->loadURLRequest(urlRequest.get()); +} + +/** + * webkit_web_view_get_page_id: + * @web_view: a #WebKitWebView + * + * Get the identifier of the #WebKitWebPage corresponding to + * the #WebKitWebView + * + * Returns: the page ID of @web_view. + */ +guint64 webkit_web_view_get_page_id(WebKitWebView* webView) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); + + return getPage(webView)->pageID(); } /** @@ -2078,22 +2270,16 @@ void webkit_web_view_go_to_back_forward_list_item(WebKitWebView* webView, WebKit * @web_view: a #WebKitWebView * @settings: a #WebKitSettings * - * Sets the #WebKitSettings to be applied to @web_view. The - * existing #WebKitSettings of @web_view will be replaced by - * @settings. New settings are applied immediately on @web_view. - * The same #WebKitSettings object can be shared - * by multiple #WebKitWebView<!-- -->s. + * Sets the #WebKitSettings to be applied to @web_view. + * This is a convenient method to set new settings to the + * #WebKitWebViewGroup @web_view belongs to. + * New settings are applied immediately on all #WebKitWebView<!-- -->s + * in the @web_view group. + * See also webkit_web_view_group_set_settings(). */ void webkit_web_view_set_settings(WebKitWebView* webView, WebKitSettings* settings) { - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - if (webView->priv->settings == settings) - return; - - webkitWebViewDisconnectSettingsSignalHandlers(webView); - webkitWebViewSetSettings(webView, settings); + webkit_web_view_group_set_settings(webkit_web_view_get_group(webView), settings); } /** @@ -2101,26 +2287,19 @@ void webkit_web_view_set_settings(WebKitWebView* webView, WebKitSettings* settin * @web_view: a #WebKitWebView * * Gets the #WebKitSettings currently applied to @web_view. - * If no other #WebKitSettings have been explicitly applied to - * @web_view with webkit_web_view_set_settings(), the default - * #WebKitSettings will be returned. This method always returns - * a valid #WebKitSettings object. - * To modify any of the @web_view settings, you can either create - * a new #WebKitSettings object with webkit_settings_new(), setting - * the desired preferences, and then replace the existing @web_view - * settings with webkit_web_view_set_settings() or get the existing - * @web_view settings and update it directly. #WebKitSettings objects - * can be shared by multiple #WebKitWebView<!-- -->s, so modifying + * This is a convenient method to get the settings of the + * #WebKitWebViewGroup @web_view belongs to. + * #WebKitSettings objects are shared by all the #WebKitWebView<!-- -->s + * in the same #WebKitWebViewGroup, so modifying * the settings of a #WebKitWebView would affect other - * #WebKitWebView<!-- -->s using the same #WebKitSettings. + * #WebKitWebView<!-- -->s of the same group. + * See also webkit_web_view_group_get_settings(). * * Returns: (transfer none): the #WebKitSettings attached to @web_view */ WebKitSettings* webkit_web_view_get_settings(WebKitWebView* webView) { - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->settings.get(); + return webkit_web_view_group_get_settings(webkit_web_view_get_group(webView)); } /** @@ -2155,7 +2334,7 @@ void webkit_web_view_set_zoom_level(WebKitWebView* webView, gdouble zoomLevel) return; WebPageProxy* page = getPage(webView); - if (webkit_settings_get_zoom_text_only(webView->priv->settings.get())) + if (webkit_settings_get_zoom_text_only(webkit_web_view_get_settings(webView))) page->setTextZoomFactor(zoomLevel); else page->setPageZoomFactor(zoomLevel); @@ -2176,26 +2355,14 @@ gdouble webkit_web_view_get_zoom_level(WebKitWebView* webView) g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 1); WebPageProxy* page = getPage(webView); - gboolean zoomTextOnly = webkit_settings_get_zoom_text_only(webView->priv->settings.get()); + gboolean zoomTextOnly = webkit_settings_get_zoom_text_only(webkit_web_view_get_settings(webView)); return zoomTextOnly ? page->textZoomFactor() : page->pageZoomFactor(); } -struct ValidateEditingCommandAsyncData { - bool isEnabled; - GRefPtr<GCancellable> cancellable; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ValidateEditingCommandAsyncData) - static void didValidateCommand(WKStringRef command, bool isEnabled, int32_t state, WKErrorRef, void* context) { - GRefPtr<GSimpleAsyncResult> result = adoptGRef(G_SIMPLE_ASYNC_RESULT(context)); - ValidateEditingCommandAsyncData* data = static_cast<ValidateEditingCommandAsyncData*>(g_simple_async_result_get_op_res_gpointer(result.get())); - GError* error = 0; - if (g_cancellable_set_error_if_cancelled(data->cancellable.get(), &error)) - g_simple_async_result_take_error(result.get(), error); - else - data->isEnabled = isEnabled; - g_simple_async_result_complete(result.get()); + GRefPtr<GTask> task = adoptGRef(G_TASK(context)); + g_task_return_boolean(task.get(), isEnabled); } /** @@ -2216,13 +2383,8 @@ void webkit_web_view_can_execute_editing_command(WebKitWebView* webView, const c g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); g_return_if_fail(command); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(webView), callback, userData, - reinterpret_cast<gpointer>(webkit_web_view_can_execute_editing_command)); - ValidateEditingCommandAsyncData* data = createValidateEditingCommandAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyValidateEditingCommandAsyncData)); - - getPage(webView)->validateCommand(String::fromUTF8(command), ValidateCommandCallback::create(result, didValidateCommand)); + GTask* task = g_task_new(webView, cancellable, callback, userData); + getPage(webView)->validateCommand(String::fromUTF8(command), ValidateCommandCallback::create(task, didValidateCommand)); } /** @@ -2238,16 +2400,9 @@ void webkit_web_view_can_execute_editing_command(WebKitWebView* webView, const c gboolean webkit_web_view_can_execute_editing_command_finish(WebKitWebView* webView, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), FALSE); + g_return_val_if_fail(g_task_is_valid(result, webView), FALSE); - GSimpleAsyncResult* simple = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simple) == webkit_web_view_can_execute_editing_command); - - if (g_simple_async_result_propagate_error(simple, error)) - return FALSE; - - ValidateEditingCommandAsyncData* data = static_cast<ValidateEditingCommandAsyncData*>(g_simple_async_result_get_op_res_gpointer(simple)); - return data->isEnabled; + return g_task_propagate_boolean(G_TASK(result), error); } /** @@ -2306,33 +2461,21 @@ JSGlobalContextRef webkit_web_view_get_javascript_global_context(WebKitWebView* return webView->priv->javascriptGlobalContext; } -struct RunJavaScriptAsyncData { - ~RunJavaScriptAsyncData() - { - if (scriptResult) - webkit_javascript_result_unref(scriptResult); - } - - WebKitJavascriptResult* scriptResult; - GRefPtr<GCancellable> cancellable; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(RunJavaScriptAsyncData) - static void webkitWebViewRunJavaScriptCallback(WKSerializedScriptValueRef wkSerializedScriptValue, WKErrorRef, void* context) { - GRefPtr<GSimpleAsyncResult> result = adoptGRef(G_SIMPLE_ASYNC_RESULT(context)); - RunJavaScriptAsyncData* data = static_cast<RunJavaScriptAsyncData*>(g_simple_async_result_get_op_res_gpointer(result.get())); - GError* error = 0; - if (g_cancellable_set_error_if_cancelled(data->cancellable.get(), &error)) - g_simple_async_result_take_error(result.get(), error); - else if (wkSerializedScriptValue) { - GRefPtr<WebKitWebView> webView = adoptGRef(WEBKIT_WEB_VIEW(g_async_result_get_source_object(G_ASYNC_RESULT(result.get())))); - data->scriptResult = webkitJavascriptResultCreate(webView.get(), toImpl(wkSerializedScriptValue)); - } else { - g_set_error_literal(&error, WEBKIT_JAVASCRIPT_ERROR, WEBKIT_JAVASCRIPT_ERROR_SCRIPT_FAILED, _("An exception was raised in JavaScript")); - g_simple_async_result_take_error(result.get(), error); + GRefPtr<GTask> task = adoptGRef(G_TASK(context)); + if (g_task_return_error_if_cancelled(task.get())) + return; + + if (!wkSerializedScriptValue) { + g_task_return_new_error(task.get(), WEBKIT_JAVASCRIPT_ERROR, WEBKIT_JAVASCRIPT_ERROR_SCRIPT_FAILED, + _("An exception was raised in JavaScript")); + return; } - g_simple_async_result_complete(result.get()); + + WebKitWebView* webView = WEBKIT_WEB_VIEW(g_task_get_source_object(task.get())); + g_task_return_pointer(task.get(), webkitJavascriptResultCreate(webView, toImpl(wkSerializedScriptValue)), + reinterpret_cast<GDestroyNotify>(webkit_javascript_result_unref)); } /** @@ -2343,7 +2486,8 @@ static void webkitWebViewRunJavaScriptCallback(WKSerializedScriptValueRef wkSeri * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished * @user_data: (closure): the data to pass to callback function * - * Asynchronously run @script in the context of the current page in @web_view. + * Asynchronously run @script in the context of the current page in @web_view. If + * WebKitWebSettings:enable-javascript is FALSE, this method will do nothing. * * When the operation is finished, @callback will be called. You can then call * webkit_web_view_run_javascript_finish() to get the result of the operation. @@ -2353,14 +2497,8 @@ void webkit_web_view_run_javascript(WebKitWebView* webView, const gchar* script, g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); g_return_if_fail(script); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(webView), callback, userData, - reinterpret_cast<gpointer>(webkit_web_view_run_javascript)); - RunJavaScriptAsyncData* data = createRunJavaScriptAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyRunJavaScriptAsyncData)); - - getPage(webView)->runJavaScriptInMainFrame(String::fromUTF8(script), - ScriptValueCallback::create(result, webkitWebViewRunJavaScriptCallback)); + GTask* task = g_task_new(webView, cancellable, callback, userData); + getPage(webView)->runJavaScriptInMainFrame(String::fromUTF8(script), ScriptValueCallback::create(task, webkitWebViewRunJavaScriptCallback)); } /** @@ -2430,35 +2568,26 @@ void webkit_web_view_run_javascript(WebKitWebView* webView, const gchar* script, WebKitJavascriptResult* webkit_web_view_run_javascript_finish(WebKitWebView* webView, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), 0); - - GSimpleAsyncResult* simpleResult = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simpleResult) == webkit_web_view_run_javascript); + g_return_val_if_fail(g_task_is_valid(result, webView), 0); - if (g_simple_async_result_propagate_error(simpleResult, error)) - return 0; - - RunJavaScriptAsyncData* data = static_cast<RunJavaScriptAsyncData*>(g_simple_async_result_get_op_res_gpointer(simpleResult)); - return data->scriptResult ? webkit_javascript_result_ref(data->scriptResult) : 0; + return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error)); } static void resourcesStreamReadCallback(GObject* object, GAsyncResult* result, gpointer userData) { - GOutputStream* outputStream = G_OUTPUT_STREAM(object); - GRefPtr<GSimpleAsyncResult> runJavascriptResult = adoptGRef(G_SIMPLE_ASYNC_RESULT(userData)); + GRefPtr<GTask> task = adoptGRef(G_TASK(userData)); GError* error = 0; - g_output_stream_splice_finish(outputStream, result, &error); + g_output_stream_splice_finish(G_OUTPUT_STREAM(object), result, &error); if (error) { - g_simple_async_result_take_error(runJavascriptResult.get(), error); - g_simple_async_result_complete(runJavascriptResult.get()); + g_task_return_error(task.get(), error); return; } - GRefPtr<WebKitWebView> webView = adoptGRef(WEBKIT_WEB_VIEW(g_async_result_get_source_object(G_ASYNC_RESULT(runJavascriptResult.get())))); - gpointer outputStreamData = g_memory_output_stream_get_data(G_MEMORY_OUTPUT_STREAM(outputStream)); - getPage(webView.get())->runJavaScriptInMainFrame(String::fromUTF8(reinterpret_cast<const gchar*>(outputStreamData)), - ScriptValueCallback::create(runJavascriptResult.leakRef(), webkitWebViewRunJavaScriptCallback)); + WebKitWebView* webView = WEBKIT_WEB_VIEW(g_task_get_source_object(task.get())); + gpointer outputStreamData = g_memory_output_stream_get_data(G_MEMORY_OUTPUT_STREAM(object)); + getPage(webView)->runJavaScriptInMainFrame(String::fromUTF8(reinterpret_cast<const gchar*>(outputStreamData)), + ScriptValueCallback::create(task.leakRef(), webkitWebViewRunJavaScriptCallback)); } /** @@ -2481,25 +2610,18 @@ void webkit_web_view_run_javascript_from_gresource(WebKitWebView* webView, const g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); g_return_if_fail(resource); - GRefPtr<GSimpleAsyncResult> result = adoptGRef(g_simple_async_result_new(G_OBJECT(webView), callback, userData, - reinterpret_cast<gpointer>(webkit_web_view_run_javascript_from_gresource))); - RunJavaScriptAsyncData* data = createRunJavaScriptAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result.get(), data, reinterpret_cast<GDestroyNotify>(destroyRunJavaScriptAsyncData)); - GError* error = 0; GRefPtr<GInputStream> inputStream = adoptGRef(g_resources_open_stream(resource, G_RESOURCE_LOOKUP_FLAGS_NONE, &error)); if (error) { - g_simple_async_result_take_error(result.get(), error); - g_simple_async_result_complete_in_idle(result.get()); + g_task_report_error(webView, callback, userData, 0, error); return; } + GTask* task = g_task_new(webView, cancellable, callback, userData); GRefPtr<GOutputStream> outputStream = adoptGRef(g_memory_output_stream_new(0, 0, fastRealloc, fastFree)); g_output_stream_splice_async(outputStream.get(), inputStream.get(), - static_cast<GOutputStreamSpliceFlags>(G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET), - G_PRIORITY_DEFAULT, - cancellable, resourcesStreamReadCallback, result.leakRef()); + static_cast<GOutputStreamSpliceFlags>(G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET), + G_PRIORITY_DEFAULT, cancellable, resourcesStreamReadCallback, task); } /** @@ -2518,16 +2640,9 @@ void webkit_web_view_run_javascript_from_gresource(WebKitWebView* webView, const WebKitJavascriptResult* webkit_web_view_run_javascript_from_gresource_finish(WebKitWebView* webView, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), 0); - - GSimpleAsyncResult* simpleResult = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simpleResult) == webkit_web_view_run_javascript_from_gresource); + g_return_val_if_fail(g_task_is_valid(result, webView), 0); - if (g_simple_async_result_propagate_error(simpleResult, error)) - return 0; - - RunJavaScriptAsyncData* data = static_cast<RunJavaScriptAsyncData*>(g_simple_async_result_get_op_res_gpointer(simpleResult)); - return data->scriptResult ? webkit_javascript_result_ref(data->scriptResult) : 0; + return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error)); } /** @@ -2535,7 +2650,6 @@ WebKitJavascriptResult* webkit_web_view_run_javascript_from_gresource_finish(Web * @web_view: a #WebKitWebView * * Return the main resource of @web_view. - * See also webkit_web_view_get_subresources(): * * Returns: (transfer none): the main #WebKitWebResource of the view * or %NULL if nothing has been loaded. @@ -2548,28 +2662,6 @@ WebKitWebResource* webkit_web_view_get_main_resource(WebKitWebView* webView) } /** - * webkit_web_view_get_subresources: - * @web_view: a #WebKitWebView - * - * Return the list of subresources of @web_view. - * See also webkit_web_view_get_main_resource(). - * - * Returns: (element-type WebKitWebResource) (transfer container): a list of #WebKitWebResource. - */ -GList* webkit_web_view_get_subresources(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - GList* subresources = 0; - WebKitWebViewPrivate* priv = webView->priv; - ResourcesMap::const_iterator end = priv->subresourcesMap.end(); - for (ResourcesMap::const_iterator it = priv->subresourcesMap.begin(); it != end; ++it) - subresources = g_list_prepend(subresources, it->value.get()); - - return g_list_reverse(subresources); -} - -/** * webkit_web_view_get_inspector: * @web_view: a #WebKitWebView * @@ -2607,46 +2699,42 @@ gboolean webkit_web_view_can_show_mime_type(WebKitWebView* webView, const char* struct ViewSaveAsyncData { RefPtr<WebData> webData; GRefPtr<GFile> file; - GRefPtr<GCancellable> cancellable; }; WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ViewSaveAsyncData) static void fileReplaceContentsCallback(GObject* object, GAsyncResult* result, gpointer data) { - GFile* file = G_FILE(object); - GRefPtr<GSimpleAsyncResult> savedToFileResult = adoptGRef(G_SIMPLE_ASYNC_RESULT(data)); - + GRefPtr<GTask> task = adoptGRef(G_TASK(data)); GError* error = 0; - if (!g_file_replace_contents_finish(file, result, 0, &error)) - g_simple_async_result_take_error(savedToFileResult.get(), error); + if (!g_file_replace_contents_finish(G_FILE(object), result, 0, &error)) { + g_task_return_error(task.get(), error); + return; + } - g_simple_async_result_complete(savedToFileResult.get()); + g_task_return_boolean(task.get(), TRUE); } static void getContentsAsMHTMLDataCallback(WKDataRef wkData, WKErrorRef, void* context) { - GRefPtr<GSimpleAsyncResult> result = adoptGRef(G_SIMPLE_ASYNC_RESULT(context)); - ViewSaveAsyncData* data = static_cast<ViewSaveAsyncData*>(g_simple_async_result_get_op_res_gpointer(result.get())); - GError* error = 0; + GRefPtr<GTask> task = adoptGRef(G_TASK(context)); + if (g_task_return_error_if_cancelled(task.get())) + return; - if (g_cancellable_set_error_if_cancelled(data->cancellable.get(), &error)) - g_simple_async_result_take_error(result.get(), error); - else { - // We need to retain the data until the asyncronous process - // initiated by the user has finished completely. - data->webData = toImpl(wkData); - - // If we are saving to a file we need to write the data on disk before finishing. - if (g_simple_async_result_get_source_tag(result.get()) == webkit_web_view_save_to_file) { - ASSERT(G_IS_FILE(data->file.get())); - g_file_replace_contents_async(data->file.get(), reinterpret_cast<const gchar*>(data->webData->bytes()), data->webData->size(), - 0, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, data->cancellable.get(), fileReplaceContentsCallback, - g_object_ref(result.get())); - return; - } + ViewSaveAsyncData* data = static_cast<ViewSaveAsyncData*>(g_task_get_task_data(task.get())); + // We need to retain the data until the asyncronous process + // initiated by the user has finished completely. + data->webData = toImpl(wkData); + + // If we are saving to a file we need to write the data on disk before finishing. + if (g_task_get_source_tag(task.get()) == webkit_web_view_save_to_file) { + ASSERT(G_IS_FILE(data->file.get())); + GCancellable* cancellable = g_task_get_cancellable(task.get()); + g_file_replace_contents_async(data->file.get(), reinterpret_cast<const gchar*>(data->webData->bytes()), data->webData->size(), + 0, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, cancellable, fileReplaceContentsCallback, task.leakRef()); + return; } - g_simple_async_result_complete(result.get()); + g_task_return_boolean(task.get(), TRUE); } /** @@ -2672,13 +2760,10 @@ void webkit_web_view_save(WebKitWebView* webView, WebKitSaveMode saveMode, GCanc // We only support MHTML at the moment. g_return_if_fail(saveMode == WEBKIT_SAVE_MODE_MHTML); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(webView), callback, userData, - reinterpret_cast<gpointer>(webkit_web_view_save)); - ViewSaveAsyncData* data = createViewSaveAsyncData(); - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData)); - - getPage(webView)->getContentsAsMHTMLData(DataCallback::create(result, getContentsAsMHTMLDataCallback), false); + GTask* task = g_task_new(webView, cancellable, callback, userData); + g_task_set_source_tag(task, reinterpret_cast<gpointer>(webkit_web_view_save)); + g_task_set_task_data(task, createViewSaveAsyncData(), reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData)); + getPage(webView)->getContentsAsMHTMLData(DataCallback::create(task, getContentsAsMHTMLDataCallback), false); } /** @@ -2695,16 +2780,14 @@ void webkit_web_view_save(WebKitWebView* webView, WebKitSaveMode saveMode, GCanc GInputStream* webkit_web_view_save_finish(WebKitWebView* webView, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), 0); - - GSimpleAsyncResult* simple = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simple) == webkit_web_view_save); + g_return_val_if_fail(g_task_is_valid(result, webView), 0); - if (g_simple_async_result_propagate_error(simple, error)) + GTask* task = G_TASK(result); + if (!g_task_propagate_boolean(task, error)) return 0; GInputStream* dataStream = g_memory_input_stream_new(); - ViewSaveAsyncData* data = static_cast<ViewSaveAsyncData*>(g_simple_async_result_get_op_res_gpointer(simple)); + ViewSaveAsyncData* data = static_cast<ViewSaveAsyncData*>(g_task_get_task_data(task)); gsize length = data->webData->size(); if (length) g_memory_input_stream_add_data(G_MEMORY_INPUT_STREAM(dataStream), g_memdup(data->webData->bytes(), length), length, g_free); @@ -2737,14 +2820,13 @@ void webkit_web_view_save_to_file(WebKitWebView* webView, GFile* file, WebKitSav // We only support MHTML at the moment. g_return_if_fail(saveMode == WEBKIT_SAVE_MODE_MHTML); - GSimpleAsyncResult* result = g_simple_async_result_new(G_OBJECT(webView), callback, userData, - reinterpret_cast<gpointer>(webkit_web_view_save_to_file)); + GTask* task = g_task_new(webView, cancellable, callback, userData); + g_task_set_source_tag(task, reinterpret_cast<gpointer>(webkit_web_view_save_to_file)); ViewSaveAsyncData* data = createViewSaveAsyncData(); data->file = file; - data->cancellable = cancellable; - g_simple_async_result_set_op_res_gpointer(result, data, reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData)); + g_task_set_task_data(task, data, reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData)); - getPage(webView)->getContentsAsMHTMLData(DataCallback::create(result, getContentsAsMHTMLDataCallback), false); + getPage(webView)->getContentsAsMHTMLData(DataCallback::create(task, getContentsAsMHTMLDataCallback), false); } /** @@ -2760,15 +2842,9 @@ void webkit_web_view_save_to_file(WebKitWebView* webView, GFile* file, WebKitSav gboolean webkit_web_view_save_to_file_finish(WebKitWebView* webView, GAsyncResult* result, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); - g_return_val_if_fail(G_IS_ASYNC_RESULT(result), FALSE); + g_return_val_if_fail(g_task_is_valid(result, webView), FALSE); - GSimpleAsyncResult* simple = G_SIMPLE_ASYNC_RESULT(result); - g_warn_if_fail(g_simple_async_result_get_source_tag(simple) == webkit_web_view_save_to_file); - - if (g_simple_async_result_propagate_error(simple, error)) - return FALSE; - - return TRUE; + return g_task_propagate_boolean(G_TASK(result), error); } /** @@ -2791,3 +2867,166 @@ WebKitDownload* webkit_web_view_download_uri(WebKitWebView* webView, const char* return download; } + +/** + * webkit_web_view_set_view_mode: + * @web_view: a #WebKitWebView + * @view_mode: a #WebKitViewMode + * + * Set the view mode of @web_view to @view_mode. This method should be called + * before loading new contents on @web_view so that the new #WebKitViewMode will + * be applied to the new contents. + */ +void webkit_web_view_set_view_mode(WebKitWebView* webView, WebKitViewMode viewMode) +{ + g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); + + if (webView->priv->viewMode == viewMode) + return; + + getPage(webView)->setMainFrameInViewSourceMode(viewMode == WEBKIT_VIEW_MODE_SOURCE); + + webView->priv->viewMode = viewMode; + g_object_notify(G_OBJECT(webView), "view-mode"); +} + +/** + * webkit_web_view_get_view_mode: + * @web_view: a #WebKitWebView + * + * Get the view mode of @web_view. + * + * Returns: the #WebKitViewMode of @web_view. + */ +WebKitViewMode webkit_web_view_get_view_mode(WebKitWebView* webView) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), WEBKIT_VIEW_MODE_WEB); + + return webView->priv->viewMode; +} + +/** + * webkit_web_view_get_tls_info: + * @web_view: a #WebKitWebView + * @certificate: (out) (transfer none): return location for a #GTlsCertificate + * @errors: (out): return location for a #GTlsCertificateFlags the verification status of @certificate + * + * Retrieves the #GTlsCertificate associated with the @web_view connection, + * and the #GTlsCertificateFlags showing what problems, if any, have been found + * with that certificate. + * If the connection is not HTTPS, this function returns %FALSE. + * This function should be called after a response has been received from the + * server, so you can connect to #WebKitWebView::load-changed and call this function + * when it's emitted with %WEBKIT_LOAD_COMMITTED event. + * + * Returns: %TRUE if the @web_view connection uses HTTPS and a response has been received + * from the server, or %FALSE otherwise. + */ +gboolean webkit_web_view_get_tls_info(WebKitWebView* webView, GTlsCertificate** certificate, GTlsCertificateFlags* errors) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); + + WebFrameProxy* mainFrame = getPage(webView)->mainFrame(); + if (!mainFrame) + return FALSE; + + const PlatformCertificateInfo& certificateInfo = mainFrame->certificateInfo()->platformCertificateInfo(); + if (certificate) + *certificate = certificateInfo.certificate(); + if (errors) + *errors = certificateInfo.tlsErrors(); + + return !!certificateInfo.certificate(); +} + +void webKitWebViewDidReceiveSnapshot(WebKitWebView* webView, uint64_t callbackID, WebImage* webImage) +{ + GRefPtr<GTask> task = webView->priv->snapshotResultsMap.take(callbackID); + if (g_task_return_error_if_cancelled(task.get())) + return; + + if (!webImage) { + g_task_return_new_error(task.get(), WEBKIT_SNAPSHOT_ERROR, WEBKIT_SNAPSHOT_ERROR_FAILED_TO_CREATE, + _("There was an error creating the snapshot")); + return; + } + + if (RefPtr<ShareableBitmap> image = webImage->bitmap()) + g_task_return_pointer(task.get(), image->createCairoSurface().leakRef(), reinterpret_cast<GDestroyNotify>(cairo_surface_destroy)); + else + g_task_return_pointer(task.get(), 0, 0); +} + +COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_SNAPSHOT_REGION_VISIBLE, SnapshotRegionVisible); +COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, SnapshotRegionFullDocument); + +static inline unsigned webKitSnapshotOptionsToSnapshotOptions(WebKitSnapshotOptions options) +{ + SnapshotOptions snapshotOptions = 0; + + if (!(options & WEBKIT_SNAPSHOT_OPTIONS_INCLUDE_SELECTION_HIGHLIGHTING)) + snapshotOptions |= SnapshotOptionsExcludeSelectionHighlighting; + + return snapshotOptions; +} + +static inline uint64_t generateSnapshotCallbackID() +{ + static uint64_t uniqueCallbackID = 1; + return uniqueCallbackID++; +} + +/** + * webkit_web_view_get_snapshot: + * @web_view: a #WebKitWebView + * @options: #WebKitSnapshotOptions for the snapshot + * @region: the #WebKitSnapshotRegion for this snapshot + * @cancellable: (allow-none): a #GCancellable + * @callback: (scope async): a #GAsyncReadyCallback + * @user_data: (closure): user data + * + * Asynchronously retrieves a snapshot of @web_view for @region. + * @options specifies how the snapshot should be rendered. + * + * When the operation is finished, @callback will be called. You must + * call webkit_web_view_get_snapshot_finish() to get the result of the + * operation. + */ +void webkit_web_view_get_snapshot(WebKitWebView* webView, WebKitSnapshotRegion region, WebKitSnapshotOptions options, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) +{ + g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); + + ImmutableDictionary::MapType message; + uint64_t callbackID = generateSnapshotCallbackID(); + message.set(String::fromUTF8("SnapshotOptions"), WebUInt64::create(static_cast<uint64_t>(webKitSnapshotOptionsToSnapshotOptions(options)))); + message.set(String::fromUTF8("SnapshotRegion"), WebUInt64::create(static_cast<uint64_t>(region))); + message.set(String::fromUTF8("CallbackID"), WebUInt64::create(callbackID)); + + webView->priv->snapshotResultsMap.set(callbackID, adoptGRef(g_task_new(webView, cancellable, callback, userData))); + getPage(webView)->postMessageToInjectedBundle(String::fromUTF8("GetSnapshot"), ImmutableDictionary::adopt(message).get()); +} + +/** + * webkit_web_view_get_snapshot_finish: + * @web_view: a #WebKitWebView + * @result: a #GAsyncResult + * @error: return location for error or %NULL to ignore + * + * Finishes an asynchronous operation started with webkit_web_view_get_snapshot(). + * + * Returns: (transfer full): a #cairo_surface_t with the retrieved snapshot or %NULL in error. + */ +cairo_surface_t* webkit_web_view_get_snapshot_finish(WebKitWebView* webView, GAsyncResult* result, GError** error) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); + g_return_val_if_fail(g_task_is_valid(result, webView), 0); + + return static_cast<cairo_surface_t*>(g_task_propagate_pointer(G_TASK(result), error)); +} + +void webkitWebViewWebProcessCrashed(WebKitWebView* webView) +{ + gboolean returnValue; + g_signal_emit(webView, signals[WEB_PROCESS_CRASHED], 0, &returnValue); +} + diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.h index 7c8381329..b23d7ffb1 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.h @@ -34,6 +34,7 @@ #include <webkit2/WebKitFileChooserRequest.h> #include <webkit2/WebKitFindController.h> #include <webkit2/WebKitFormSubmissionRequest.h> +#include <webkit2/WebKitForwardDeclarations.h> #include <webkit2/WebKitHitTestResult.h> #include <webkit2/WebKitJavascriptResult.h> #include <webkit2/WebKitPermissionRequest.h> @@ -45,6 +46,7 @@ #include <webkit2/WebKitWebInspector.h> #include <webkit2/WebKitWebResource.h> #include <webkit2/WebKitWebViewBase.h> +#include <webkit2/WebKitWebViewGroup.h> #include <webkit2/WebKitWindowProperties.h> G_BEGIN_DECLS @@ -129,6 +131,64 @@ typedef enum { WEBKIT_SAVE_MODE_MHTML } WebKitSaveMode; +/** + * WebKitInsecureContentEvent: + * @WEBKIT_INSECURE_CONTENT_RUN: Insecure content has been detected by + * trying to execute any kind of logic (e.g. a script) from an + * untrusted source. + * @WEBKIT_INSECURE_CONTENT_DISPLAYED: Insecure content has been + * detected by trying to display any kind of resource (e.g. an image) + * from an untrusted source. + * + * Enum values used to denote the different events which can trigger + * the detection of insecure content. + */ +typedef enum { + WEBKIT_INSECURE_CONTENT_RUN, + WEBKIT_INSECURE_CONTENT_DISPLAYED +} WebKitInsecureContentEvent; + +/** + * WebKitViewMode: + * @WEBKIT_VIEW_MODE_WEB: The normal view mode to display web contents. + * @WEBKIT_VIEW_MODE_SOURCE: The source mode to display web source code. + * + * Enum values to specify the different ways in which a #WebKitWebView + * can display a web page. + */ +typedef enum { + WEBKIT_VIEW_MODE_WEB, + WEBKIT_VIEW_MODE_SOURCE +} WebKitViewMode; + +/** + * WebKitSnapshotOptions: + * @WEBKIT_SNAPSHOT_OPTIONS_NONE: Do not include any special options. + * @WEBKIT_SNAPSHOT_OPTIONS_INCLUDE_SELECTION_HIGHLIGHTING: Whether to include in the + * snapshot the highlight of the selected content. + * + * Enum values used to specify options when taking a snapshot + * from a #WebKitWebView. + */ +typedef enum { + WEBKIT_SNAPSHOT_OPTIONS_NONE = 0, + WEBKIT_SNAPSHOT_OPTIONS_INCLUDE_SELECTION_HIGHLIGHTING = 1 << 0, +} WebKitSnapshotOptions; + +/** + * WebKitSnapshotRegion: + * @WEBKIT_SNAPSHOT_REGION_VISIBLE: Specifies a snapshot only for the area that is + * visible in the webview + * @WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT: A snapshot of the entire document. + * + * Enum values used to specify the region from which to get a #WebKitWebView + * snapshot + */ +typedef enum { + WEBKIT_SNAPSHOT_REGION_VISIBLE = 0, + WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, +} WebKitSnapshotRegion; + struct _WebKitWebView { WebKitWebViewBase parent; @@ -139,47 +199,49 @@ struct _WebKitWebView { struct _WebKitWebViewClass { WebKitWebViewBaseClass parent; - void (* load_changed) (WebKitWebView *web_view, - WebKitLoadEvent load_event); - gboolean (* load_failed) (WebKitWebView *web_view, - WebKitLoadEvent load_event, - const gchar *failing_uri, - GError *error); - - GtkWidget *(* create) (WebKitWebView *web_view); - void (* ready_to_show) (WebKitWebView *web_view); - void (* run_as_modal) (WebKitWebView *web_view); - void (* close) (WebKitWebView *web_view); - - gboolean (* script_dialog) (WebKitWebView *web_view, - WebKitScriptDialog *dialog); - - gboolean (* decide_policy) (WebKitWebView *web_view, - WebKitPolicyDecision *decision, - WebKitPolicyDecisionType type); - gboolean (* permission_request) (WebKitWebView *web_view, - WebKitPermissionRequest *permission_request); - void (* mouse_target_changed) (WebKitWebView *web_view, - WebKitHitTestResult *hit_test_result, - guint modifiers); - gboolean (* print) (WebKitWebView *web_view, - WebKitPrintOperation *print_operation); - void (* resource_load_started) (WebKitWebView *web_view, - WebKitWebResource *resource, - WebKitURIRequest *request); - gboolean (* enter_fullscreen) (WebKitWebView *web_view); - gboolean (* leave_fullscreen) (WebKitWebView *web_view); - gboolean (* run_file_chooser) (WebKitWebView *web_view, - WebKitFileChooserRequest *request); - gboolean (* context_menu) (WebKitWebView *web_view, - WebKitContextMenu *context_menu, - GdkEvent *event, - WebKitHitTestResult *hit_test_result); - void (* context_menu_dismissed) (WebKitWebView *web_view); - void (* submit_form) (WebKitWebView *web_view, - WebKitFormSubmissionRequest *request); - - /* Padding for future expansion */ + void (* load_changed) (WebKitWebView *web_view, + WebKitLoadEvent load_event); + gboolean (* load_failed) (WebKitWebView *web_view, + WebKitLoadEvent load_event, + const gchar *failing_uri, + GError *error); + + GtkWidget *(* create) (WebKitWebView *web_view); + void (* ready_to_show) (WebKitWebView *web_view); + void (* run_as_modal) (WebKitWebView *web_view); + void (* close) (WebKitWebView *web_view); + + gboolean (* script_dialog) (WebKitWebView *web_view, + WebKitScriptDialog *dialog) ; + + gboolean (* decide_policy) (WebKitWebView *web_view, + WebKitPolicyDecision *decision, + WebKitPolicyDecisionType type); + gboolean (* permission_request) (WebKitWebView *web_view, + WebKitPermissionRequest *permission_request); + void (* mouse_target_changed) (WebKitWebView *web_view, + WebKitHitTestResult *hit_test_result, + guint modifiers); + gboolean (* print) (WebKitWebView *web_view, + WebKitPrintOperation *print_operation); + void (* resource_load_started) (WebKitWebView *web_view, + WebKitWebResource *resource, + WebKitURIRequest *request); + gboolean (* enter_fullscreen) (WebKitWebView *web_view); + gboolean (* leave_fullscreen) (WebKitWebView *web_view); + gboolean (* run_file_chooser) (WebKitWebView *web_view, + WebKitFileChooserRequest *request); + gboolean (* context_menu) (WebKitWebView *web_view, + WebKitContextMenu *context_menu, + GdkEvent *event, + WebKitHitTestResult *hit_test_result); + void (* context_menu_dismissed) (WebKitWebView *web_view); + void (* submit_form) (WebKitWebView *web_view, + WebKitFormSubmissionRequest *request); + void (* insecure_content_detected) (WebKitWebView *web_view, + WebKitInsecureContentEvent event); + gboolean (* web_process_crashed) (WebKitWebView *web_view); + void (*_webkit_reserved0) (void); void (*_webkit_reserved1) (void); void (*_webkit_reserved2) (void); @@ -199,9 +261,15 @@ webkit_web_view_new (void); WEBKIT_API GtkWidget * webkit_web_view_new_with_context (WebKitWebContext *context); +WEBKIT_API GtkWidget * +webkit_web_view_new_with_group (WebKitWebViewGroup *group); + WEBKIT_API WebKitWebContext * webkit_web_view_get_context (WebKitWebView *web_view); +WEBKIT_API WebKitWebViewGroup * +webkit_web_view_get_group (WebKitWebView *web_view); + WEBKIT_API void webkit_web_view_load_uri (WebKitWebView *web_view, const gchar *uri); @@ -229,6 +297,9 @@ webkit_web_view_stop_loading (WebKitWebView WEBKIT_API gboolean webkit_web_view_is_loading (WebKitWebView *web_view); +WEBKIT_API guint64 +webkit_web_view_get_page_id (WebKitWebView *web_view); + WEBKIT_API const gchar * webkit_web_view_get_title (WebKitWebView *web_view); @@ -336,9 +407,6 @@ webkit_web_view_run_javascript_from_gresource_finish (WebKitWebView WEBKIT_API WebKitWebResource * webkit_web_view_get_main_resource (WebKitWebView *web_view); -WEBKIT_API GList * -webkit_web_view_get_subresources (WebKitWebView *web_view); - WEBKIT_API WebKitWebInspector * webkit_web_view_get_inspector (WebKitWebView *web_view); @@ -375,6 +443,29 @@ WEBKIT_API WebKitDownload * webkit_web_view_download_uri (WebKitWebView *web_view, const char *uri); +WEBKIT_API void +webkit_web_view_set_view_mode (WebKitWebView *web_view, + WebKitViewMode view_mode); + +WEBKIT_API WebKitViewMode +webkit_web_view_get_view_mode (WebKitWebView *web_view); + +WEBKIT_API gboolean +webkit_web_view_get_tls_info (WebKitWebView *web_view, + GTlsCertificate **certificate, + GTlsCertificateFlags *errors); +WEBKIT_API void +webkit_web_view_get_snapshot (WebKitWebView *web_view, + WebKitSnapshotRegion region, + WebKitSnapshotOptions options, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +WEBKIT_API cairo_surface_t * +webkit_web_view_get_snapshot_finish (WebKitWebView *web_view, + GAsyncResult *result, + GError **error); G_END_DECLS #endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.cpp index c46deb27a..a414920b1 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.cpp @@ -29,7 +29,6 @@ #include "WebKitWebViewBase.h" #include "DrawingAreaProxyImpl.h" -#include "NativeWebKeyboardEvent.h" #include "NativeWebMouseEvent.h" #include "NativeWebWheelEvent.h" #include "PageClientImpl.h" @@ -37,11 +36,12 @@ #include "WebEventFactory.h" #include "WebFullScreenClientGtk.h" #include "WebInspectorProxy.h" +#include "WebKitAuthenticationDialog.h" #include "WebKitPrivate.h" #include "WebKitWebViewBaseAccessible.h" #include "WebKitWebViewBasePrivate.h" #include "WebPageProxy.h" -#include <WebCore/ClipboardGtk.h> +#include "WebViewBaseInputMethodFilter.h" #include <WebCore/ClipboardUtilitiesGtk.h> #include <WebCore/DataObjectGtk.h> #include <WebCore/DragData.h> @@ -81,9 +81,8 @@ void redirectedWindowDamagedCallback(void* data); struct _WebKitWebViewBasePrivate { _WebKitWebViewBasePrivate() - : imContext(adoptGRef(gtk_im_multicontext_new())) #if USE(TEXTURE_MAPPER_GL) - , redirectedWindow(RedirectedXCompositeWindow::create(IntSize(1, 1), RedirectedXCompositeWindow::DoNotCreateGLContext)) + : redirectedWindow(RedirectedXCompositeWindow::create(IntSize(1, 1), RedirectedXCompositeWindow::DoNotCreateGLContext)) #endif { } @@ -97,7 +96,6 @@ struct _WebKitWebViewBasePrivate { OwnPtr<PageClientImpl> pageClient; RefPtr<WebPageProxy> pageProxy; bool shouldForwardNextKeyEvent; - GRefPtr<GtkIMContext> imContext; GtkClickCounter clickCounter; CString tooltipText; IntRect tooltipArea; @@ -106,11 +104,12 @@ struct _WebKitWebViewBasePrivate { IntSize resizerSize; GRefPtr<AtkObject> accessible; bool needsResizeOnMap; - WebKit2GtkAuthenticationDialog* authenticationDialog; + GtkWidget* authenticationDialog; GtkWidget* inspectorView; unsigned inspectorViewHeight; GOwnPtr<GdkEvent> contextMenuEvent; WebContextMenuProxyGtk* activeContextMenuProxy; + WebViewBaseInputMethodFilter inputMethodFilter; GtkWindow* toplevelOnScreenWindow; unsigned long toplevelResizeGripVisibilityID; @@ -245,9 +244,7 @@ static void webkitWebViewBaseRealize(GtkWidget* widget) | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_SCROLL_MASK -#if GTK_CHECK_VERSION(3, 3, 18) | GDK_SMOOTH_SCROLL_MASK -#endif | GDK_POINTER_MOTION_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK @@ -265,9 +262,6 @@ static void webkitWebViewBaseRealize(GtkWidget* widget) gtk_style_context_set_background(gtk_widget_get_style_context(widget), window); WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webView->priv; - gtk_im_context_set_client_window(priv->imContext.get(), window); - GtkWidget* toplevel = gtk_widget_get_toplevel(widget); if (widgetIsOnscreenToplevelWindow(toplevel)) webkitWebViewBaseSetToplevelOnScreenWindow(webView, GTK_WINDOW(toplevel)); @@ -276,7 +270,7 @@ static void webkitWebViewBaseRealize(GtkWidget* widget) static bool webkitWebViewChildIsInternalWidget(WebKitWebViewBase* webViewBase, GtkWidget* widget) { WebKitWebViewBasePrivate* priv = webViewBase->priv; - return widget == priv->inspectorView || (priv->authenticationDialog && priv->authenticationDialog->widget() == widget); + return widget == priv->inspectorView || widget == priv->authenticationDialog; } static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget) @@ -295,18 +289,22 @@ static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* wi gtk_widget_set_parent(widget, GTK_WIDGET(container)); } -void webkitWebViewBaseAddAuthenticationDialog(WebKitWebViewBase* webViewBase, WebKit2GtkAuthenticationDialog* dialog) +void webkitWebViewBaseAddAuthenticationDialog(WebKitWebViewBase* webViewBase, GtkWidget* dialog) { - webViewBase->priv->authenticationDialog = dialog; - gtk_container_add(GTK_CONTAINER(webViewBase), dialog->widget()); - gtk_widget_queue_draw(GTK_WIDGET(webViewBase)); // We need to draw the shadow over the widget. + WebKitWebViewBasePrivate* priv = webViewBase->priv; + priv->authenticationDialog = dialog; + gtk_container_add(GTK_CONTAINER(webViewBase), dialog); + gtk_widget_show(dialog); + + // We need to draw the shadow over the widget. + gtk_widget_queue_draw(GTK_WIDGET(webViewBase)); } void webkitWebViewBaseCancelAuthenticationDialog(WebKitWebViewBase* webViewBase) { WebKitWebViewBasePrivate* priv = webViewBase->priv; if (priv->authenticationDialog) - priv->authenticationDialog->destroy(); + gtk_widget_destroy(priv->authenticationDialog); } void webkitWebViewBaseAddWebInspector(WebKitWebViewBase* webViewBase, GtkWidget* inspector) @@ -327,7 +325,7 @@ static void webkitWebViewBaseContainerRemove(GtkContainer* container, GtkWidget* if (priv->inspectorView == widget) { priv->inspectorView = 0; priv->inspectorViewHeight = 0; - } else if (priv->authenticationDialog && priv->authenticationDialog->widget() == widget) { + } else if (priv->authenticationDialog == widget) { priv->authenticationDialog = 0; } else { ASSERT(priv->children.contains(widget)); @@ -351,7 +349,7 @@ static void webkitWebViewBaseContainerForall(GtkContainer* container, gboolean i (*callback)(priv->inspectorView, callbackData); if (includeInternals && priv->authenticationDialog) - (*callback)(priv->authenticationDialog->widget(), callbackData); + (*callback)(priv->authenticationDialog, callbackData); } void webkitWebViewBaseChildMoveResize(WebKitWebViewBase* webView, GtkWidget* child, const IntRect& childRect) @@ -437,6 +435,8 @@ static gboolean webkitWebViewBaseDraw(GtkWidget* widget, cairo_t* cr) cairo_paint(cr); } + GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->draw(widget, cr); + return FALSE; } @@ -463,12 +463,13 @@ static void resizeWebKitWebViewBaseFromAllocation(WebKitWebViewBase* webViewBase IntRect viewRect(allocation->x, allocation->y, allocation->width, allocation->height); WebKitWebViewBasePrivate* priv = webViewBase->priv; if (priv->inspectorView) { + int inspectorViewHeight = std::min(static_cast<int>(priv->inspectorViewHeight), allocation->height); GtkAllocation childAllocation = viewRect; - childAllocation.y = allocation->height - priv->inspectorViewHeight; - childAllocation.height = priv->inspectorViewHeight; + childAllocation.y = allocation->height - inspectorViewHeight; + childAllocation.height = inspectorViewHeight; gtk_widget_size_allocate(priv->inspectorView, &childAllocation); - viewRect.setHeight(allocation->height - priv->inspectorViewHeight); + viewRect.setHeight(std::max(allocation->height - inspectorViewHeight, 1)); } // The authentication dialog is centered in the view rect, which means that it @@ -476,7 +477,7 @@ static void resizeWebKitWebViewBaseFromAllocation(WebKitWebViewBase* webViewBase // after calculating the inspector allocation. if (priv->authenticationDialog) { GtkRequisition naturalSize; - gtk_widget_get_preferred_size(priv->authenticationDialog->widget(), 0, &naturalSize); + gtk_widget_get_preferred_size(priv->authenticationDialog, 0, &naturalSize); GtkAllocation childAllocation = { (viewRect.width() - naturalSize.width) / 2, @@ -484,7 +485,7 @@ static void resizeWebKitWebViewBaseFromAllocation(WebKitWebViewBase* webViewBase naturalSize.width, naturalSize.height }; - gtk_widget_size_allocate(priv->authenticationDialog->widget(), &childAllocation); + gtk_widget_size_allocate(priv->authenticationDialog, &childAllocation); } #if USE(TEXTURE_MAPPER_GL) @@ -493,7 +494,7 @@ static void resizeWebKitWebViewBaseFromAllocation(WebKitWebViewBase* webViewBase #endif if (priv->pageProxy->drawingArea()) - priv->pageProxy->drawingArea()->setSize(viewRect.size(), IntSize()); + priv->pageProxy->drawingArea()->setSize(viewRect.size(), IntSize(), IntSize()); webkitWebViewBaseNotifyResizerSize(webViewBase); } @@ -506,7 +507,7 @@ static void webkitWebViewBaseSizeAllocate(GtkWidget* widget, GtkAllocation* allo GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->size_allocate(widget, allocation); WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - if (sizeChanged && !gtk_widget_get_mapped(widget) && !webViewBase->priv->pageProxy->drawingArea()->size().isEmpty()) { + if (sizeChanged && !gtk_widget_get_mapped(widget)) { webViewBase->priv->needsResizeOnMap = true; return; } @@ -549,7 +550,7 @@ static gboolean webkitWebViewBaseFocusInEvent(GtkWidget* widget, GdkEventFocus* { WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); webkitWebViewBaseSetFocus(webViewBase, true); - gtk_im_context_focus_in(webViewBase->priv->imContext.get()); + webViewBase->priv->inputMethodFilter.notifyFocusedIn(); return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus_in_event(widget, event); } @@ -558,7 +559,7 @@ static gboolean webkitWebViewBaseFocusOutEvent(GtkWidget* widget, GdkEventFocus* { WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); webkitWebViewBaseSetFocus(webViewBase, false); - gtk_im_context_focus_out(webViewBase->priv->imContext.get()); + webViewBase->priv->inputMethodFilter.notifyFocusedOut(); return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus_out_event(widget, event); } @@ -593,7 +594,7 @@ static gboolean webkitWebViewBaseKeyPressEvent(GtkWidget* widget, GdkEventKey* e priv->shouldForwardNextKeyEvent = FALSE; return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_press_event(widget, event); } - priv->pageProxy->handleKeyboardEvent(NativeWebKeyboardEvent(reinterpret_cast<GdkEvent*>(event))); + priv->inputMethodFilter.filterKeyEvent(event); return TRUE; } @@ -602,14 +603,11 @@ static gboolean webkitWebViewBaseKeyReleaseEvent(GtkWidget* widget, GdkEventKey* WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (gtk_im_context_filter_keypress(priv->imContext.get(), event)) - return TRUE; - if (priv->shouldForwardNextKeyEvent) { priv->shouldForwardNextKeyEvent = FALSE; return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_release_event(widget, event); } - priv->pageProxy->handleKeyboardEvent(NativeWebKeyboardEvent(reinterpret_cast<GdkEvent*>(event))); + priv->inputMethodFilter.filterKeyEvent(event); return TRUE; } @@ -623,6 +621,8 @@ static gboolean webkitWebViewBaseButtonPressEvent(GtkWidget* widget, GdkEventBut gtk_widget_grab_focus(widget); + priv->inputMethodFilter.notifyMouseButtonPress(); + if (!priv->clickCounter.shouldProcessButtonEvent(buttonEvent)) return TRUE; @@ -720,12 +720,14 @@ static void webkitWebViewBaseDragEnd(GtkWidget* widget, GdkDragContext* context) static void webkitWebViewBaseDragDataReceived(GtkWidget* widget, GdkDragContext* context, gint x, gint y, GtkSelectionData* selectionData, guint info, guint time) { WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - OwnPtr<DragData> dragData(webViewBase->priv->dragAndDropHelper.handleDragDataReceived(context, selectionData, info)); - if (!dragData) + IntPoint position; + DataObjectGtk* dataObject = webViewBase->priv->dragAndDropHelper.handleDragDataReceived(context, selectionData, info, position); + if (!dataObject) return; + DragData dragData(dataObject, position, convertWidgetPointToScreenPoint(widget, position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(context))); webViewBase->priv->pageProxy->resetDragOperation(); - webViewBase->priv->pageProxy->dragEntered(dragData.get()); + webViewBase->priv->pageProxy->dragEntered(&dragData); DragOperation operation = webViewBase->priv->pageProxy->dragSession().operation; gdk_drag_status(context, dragOperationToSingleGdkDragAction(operation), time); } @@ -761,11 +763,13 @@ static AtkObject* webkitWebViewBaseGetAccessible(GtkWidget* widget) static gboolean webkitWebViewBaseDragMotion(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time) { WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - OwnPtr<DragData> dragData(webViewBase->priv->dragAndDropHelper.handleDragMotion(context, IntPoint(x, y), time)); - if (!dragData) + IntPoint position(x, y); + DataObjectGtk* dataObject = webViewBase->priv->dragAndDropHelper.handleDragMotion(context, position, time); + if (!dataObject) return TRUE; - webViewBase->priv->pageProxy->dragUpdated(dragData.get()); + DragData dragData(dataObject, position, convertWidgetPointToScreenPoint(widget, position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(context))); + webViewBase->priv->pageProxy->dragUpdated(&dragData); DragOperation operation = webViewBase->priv->pageProxy->dragSession().operation; gdk_drag_status(context, dragOperationToSingleGdkDragAction(operation), time); return TRUE; @@ -791,13 +795,15 @@ static void webkitWebViewBaseDragLeave(GtkWidget* widget, GdkDragContext* contex static gboolean webkitWebViewBaseDragDrop(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time) { WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - OwnPtr<DragData> dragData(webViewBase->priv->dragAndDropHelper.handleDragDrop(context, IntPoint(x, y))); - if (!dragData) + DataObjectGtk* dataObject = webViewBase->priv->dragAndDropHelper.handleDragDrop(context); + if (!dataObject) return FALSE; + IntPoint position(x, y); + DragData dragData(dataObject, position, convertWidgetPointToScreenPoint(widget, position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(context))); SandboxExtension::Handle handle; SandboxExtension::HandleArray sandboxExtensionForUpload; - webViewBase->priv->pageProxy->performDrag(dragData.get(), String(), handle, sandboxExtensionForUpload); + webViewBase->priv->pageProxy->performDrag(&dragData, String(), handle, sandboxExtensionForUpload); gtk_drag_finish(context, TRUE, FALSE, time); return TRUE; } @@ -815,13 +821,22 @@ static gboolean webkitWebViewBaseFocus(GtkWidget* widget, GtkDirectionType direc WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv; if (priv->authenticationDialog) { gboolean returnValue; - g_signal_emit_by_name(priv->authenticationDialog->widget(), "focus", direction, &returnValue); + g_signal_emit_by_name(priv->authenticationDialog, "focus", direction, &returnValue); return returnValue; } return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus(widget, direction); } +static void webkitWebViewBaseDestroy(GtkWidget* widget) +{ + WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv; + if (priv->authenticationDialog) + gtk_widget_destroy(priv->authenticationDialog); + + GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->destroy(widget); +} + static void webkit_web_view_base_class_init(WebKitWebViewBaseClass* webkitWebViewBaseClass) { GtkWidgetClass* widgetClass = GTK_WIDGET_CLASS(webkitWebViewBaseClass); @@ -848,6 +863,7 @@ static void webkit_web_view_base_class_init(WebKitWebViewBaseClass* webkitWebVie widgetClass->drag_data_received = webkitWebViewBaseDragDataReceived; widgetClass->get_accessible = webkitWebViewBaseGetAccessible; widgetClass->parent_set = webkitWebViewBaseParentSet; + widgetClass->destroy = webkitWebViewBaseDestroy; GObjectClass* gobjectClass = G_OBJECT_CLASS(webkitWebViewBaseClass); gobjectClass->constructed = webkitWebViewBaseConstructed; @@ -868,7 +884,7 @@ WebKitWebViewBase* webkitWebViewBaseCreate(WebContext* context, WebPageGroup* pa GtkIMContext* webkitWebViewBaseGetIMContext(WebKitWebViewBase* webkitWebViewBase) { - return webkitWebViewBase->priv->imContext.get(); + return webkitWebViewBase->priv->inputMethodFilter.context(); } WebPageProxy* webkitWebViewBaseGetPage(WebKitWebViewBase* webkitWebViewBase) @@ -891,6 +907,10 @@ void webkitWebViewBaseCreateWebPage(WebKitWebViewBase* webkitWebViewBase, WebCon if (priv->redirectedWindow) priv->pageProxy->setAcceleratedCompositingWindowId(priv->redirectedWindow->windowId()); #endif + + // This must happen here instead of the instance initializer, because the input method + // filter must have access to the page. + priv->inputMethodFilter.setWebView(webkitWebViewBase); } void webkitWebViewBaseSetTooltipText(WebKitWebViewBase* webViewBase, const char* tooltip) @@ -1073,3 +1093,13 @@ void webkitWebViewBaseHandleDownloadRequest(WebKitWebViewBase* webViewBase, Down if (webViewBase->priv->downloadHandler) webViewBase->priv->downloadHandler(webViewBase, download); } + +void webkitWebViewBaseSetInputMethodState(WebKitWebViewBase* webkitWebViewBase, bool enabled) +{ + webkitWebViewBase->priv->inputMethodFilter.setEnabled(enabled); +} + +void webkitWebViewBaseUpdateTextInputState(WebKitWebViewBase* webkitWebViewBase) +{ + webkitWebViewBase->priv->inputMethodFilter.setCursorRect(webkitWebViewBase->priv->pageProxy->editorState().cursorRect); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.h index 99c4d30cf..f24457f57 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.h @@ -57,7 +57,6 @@ struct _WebKitWebViewBase { struct _WebKitWebViewBaseClass { GtkContainerClass parentClass; - /* Padding for future expansion */ void (*_webkit_reserved0) (void); void (*_webkit_reserved1) (void); void (*_webkit_reserved2) (void); @@ -65,7 +64,7 @@ struct _WebKitWebViewBaseClass { }; WEBKIT_API GType -webkit_web_view_base_get_type(); +webkit_web_view_base_get_type (void); G_END_DECLS diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h index 2bd0bc002..e30fd949e 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h @@ -29,7 +29,6 @@ #define WebKitWebViewBasePrivate_h #include "WebContextMenuProxyGtk.h" -#include "WebKit2GtkAuthenticationDialog.h" #include "WebKitPrivate.h" #include "WebKitWebViewBase.h" #include "WebPageProxy.h" @@ -50,6 +49,8 @@ void webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase*, unsigned height void webkitWebViewBaseSetActiveContextMenuProxy(WebKitWebViewBase*, WebKit::WebContextMenuProxyGtk*); WebKit::WebContextMenuProxyGtk* webkitWebViewBaseGetActiveContextMenuProxy(WebKitWebViewBase*); GdkEvent* webkitWebViewBaseTakeContextMenuEvent(WebKitWebViewBase*); +void webkitWebViewBaseSetInputMethodState(WebKitWebViewBase*, bool enabled); +void webkitWebViewBaseUpdateTextInputState(WebKitWebViewBase*); #if USE(TEXTURE_MAPPER_GL) void webkitWebViewBaseQueueDrawOfAcceleratedCompositingResults(WebKitWebViewBase*); @@ -65,7 +66,7 @@ typedef void (*WebKitWebViewBaseDownloadRequestHandler) (WebKitWebViewBase*, Web void webkitWebViewBaseSetDownloadRequestHandler(WebKitWebViewBase*, WebKitWebViewBaseDownloadRequestHandler); void webkitWebViewBaseHandleDownloadRequest(WebKitWebViewBase*, WebKit::DownloadProxy*); -void webkitWebViewBaseAddAuthenticationDialog(WebKitWebViewBase*, WebKit::WebKit2GtkAuthenticationDialog*); +void webkitWebViewBaseAddAuthenticationDialog(WebKitWebViewBase*, GtkWidget* authDialog); void webkitWebViewBaseCancelAuthenticationDialog(WebKitWebViewBase*); void webkitWebViewBaseAddWebInspector(WebKitWebViewBase*, GtkWidget* inspector); diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.cpp new file mode 100644 index 000000000..998c5c0c1 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.cpp @@ -0,0 +1,287 @@ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "WebKitWebViewGroup.h" + +#include "ImmutableArray.h" +#include "WebKitPrivate.h" +#include "WebKitSettingsPrivate.h" +#include "WebKitWebViewGroupPrivate.h" +#include <glib/gi18n-lib.h> +#include <wtf/gobject/GRefPtr.h> +#include <wtf/text/CString.h> + +using namespace WebKit; + +/** + * SECTION: WebKitWebViewGroup + * @Short_description: Group of web views + * @Title: WebKitWebViewGroup + * @See_also: #WebKitWebView, #WebKitSettings + * + * A WebKitWebViewGroup represents a group of #WebKitWebView<!-- -->s that + * share things like settings. There's a default WebKitWebViewGroup where + * all #WebKitWebView<!-- -->s of the same #WebKitWebContext are added by default. + * To create a #WebKitWebView in a different WebKitWebViewGroup you can use + * webkit_web_view_new_with_group(). + * + * WebKitWebViewGroups are identified by a unique name given when the group is + * created with webkit_web_view_group_new(). + * WebKitWebViewGroups have a #WebKitSettings to control the settings of all + * #WebKitWebView<!-- -->s of the group. You can get the settings with + * webkit_web_view_group_get_settings() to handle the settings, or you can set + * your own #WebKitSettings with webkit_web_view_group_set_settings(). When + * the #WebKitSettings of a WebKitWebViewGroup changes, the signal notify::settings + * is emitted on the group. + */ + +enum { + PROP_0, + + PROP_SETTINGS +}; + +struct _WebKitWebViewGroupPrivate { + RefPtr<WebPageGroup> pageGroup; + CString name; + GRefPtr<WebKitSettings> settings; +}; + +WEBKIT_DEFINE_TYPE(WebKitWebViewGroup, webkit_web_view_group, G_TYPE_OBJECT) + +static void webkitWebViewGroupSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) +{ + WebKitWebViewGroup* group = WEBKIT_WEB_VIEW_GROUP(object); + + switch (propId) { + case PROP_SETTINGS: + webkit_web_view_group_set_settings(group, WEBKIT_SETTINGS(g_value_get_object(value))); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); + } +} + +static void webkitWebViewGroupGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) +{ + WebKitWebViewGroup* group = WEBKIT_WEB_VIEW_GROUP(object); + + switch (propId) { + case PROP_SETTINGS: + g_value_set_object(value, webkit_web_view_group_get_settings(group)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); + } +} + +static void webkitWebViewGroupConstructed(GObject* object) +{ + G_OBJECT_CLASS(webkit_web_view_group_parent_class)->constructed(object); + + WebKitWebViewGroupPrivate* priv = WEBKIT_WEB_VIEW_GROUP(object)->priv; + priv->settings = adoptGRef(webkit_settings_new()); +} + +static void webkit_web_view_group_class_init(WebKitWebViewGroupClass* hitTestResultClass) +{ + GObjectClass* objectClass = G_OBJECT_CLASS(hitTestResultClass); + objectClass->set_property = webkitWebViewGroupSetProperty; + objectClass->get_property = webkitWebViewGroupGetProperty; + objectClass->constructed = webkitWebViewGroupConstructed; + + /** + * WebKitWebViewGroup:settings: + * + * The #WebKitSettings of the web view group. + */ + g_object_class_install_property( + objectClass, + PROP_SETTINGS, + g_param_spec_object( + "settings", + _("Settings"), + _("The settings of the web view group"), + WEBKIT_TYPE_SETTINGS, + WEBKIT_PARAM_READWRITE)); +} + +static void webkitWebViewGroupAttachSettingsToPageGroup(WebKitWebViewGroup* group) +{ + group->priv->pageGroup->setPreferences(webkitSettingsGetPreferences(group->priv->settings.get())); +} + +WebKitWebViewGroup* webkitWebViewGroupCreate(WebPageGroup* pageGroup) +{ + WebKitWebViewGroup* group = WEBKIT_WEB_VIEW_GROUP(g_object_new(WEBKIT_TYPE_WEB_VIEW_GROUP, NULL)); + group->priv->pageGroup = pageGroup; + webkitWebViewGroupAttachSettingsToPageGroup(group); + return group; +} + +WebPageGroup* webkitWebViewGroupGetPageGroup(WebKitWebViewGroup* group) +{ + return group->priv->pageGroup.get(); +} + +/** + * webkit_web_view_group_new: + * @name: (allow-none): the name of the group + * + * Creates a new #WebKitWebViewGroup with the given @name. + * If @name is %NULL a unique identifier name will be created + * automatically. + * The newly created #WebKitWebViewGroup doesn't contain any + * #WebKitWebView, web views are added to the new group when created + * with webkit_web_view_new_with_group() passing the group. + * + * Returns: (transfer full): a new #WebKitWebViewGroup + */ +WebKitWebViewGroup* webkit_web_view_group_new(const char* name) +{ + WebKitWebViewGroup* group = WEBKIT_WEB_VIEW_GROUP(g_object_new(WEBKIT_TYPE_WEB_VIEW_GROUP, NULL)); + group->priv->pageGroup = WebPageGroup::create(name ? String::fromUTF8(name) : String()); + webkitWebViewGroupAttachSettingsToPageGroup(group); + return group; +} + +/** + * webkit_web_view_group_get_name: + * @group: a #WebKitWebViewGroup + * + * Gets the name that uniquely identifies the #WebKitWebViewGroup. + * + * Returns: the name of @group + */ +const char* webkit_web_view_group_get_name(WebKitWebViewGroup* group) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW_GROUP(group), 0); + + WebKitWebViewGroupPrivate* priv = group->priv; + if (priv->name.isNull()) + priv->name = priv->pageGroup->identifier().utf8(); + + return priv->name.data(); +} + +/** + * webkit_web_view_group_get_settings: + * @group: a #WebKitWebViewGroup + * + * Gets the #WebKitSettings of the #WebKitWebViewGroup. + * + * Returns: (transfer none): the settings of @group + */ +WebKitSettings* webkit_web_view_group_get_settings(WebKitWebViewGroup* group) +{ + g_return_val_if_fail(WEBKIT_IS_WEB_VIEW_GROUP(group), 0); + + return group->priv->settings.get(); +} + +/** + * webkit_web_view_group_set_settings: + * @group: a #WebKitWebViewGroup + * @settings: a #WebKitSettings + * + * Sets a new #WebKitSettings for the #WebKitWebViewGroup. The settings will + * affect to all the #WebKitWebView<!-- -->s of the group. + * #WebKitWebViewGroup<!-- -->s always have a #WebKitSettings so if you just want to + * modify a setting you can use webkit_web_view_group_get_settings() and modify the + * returned #WebKitSettings instead. + * Setting the same #WebKitSettings multiple times doesn't have any effect. + * You can monitor the settings of a #WebKitWebViewGroup by connecting to the + * notify::settings signal of @group. + */ +void webkit_web_view_group_set_settings(WebKitWebViewGroup* group, WebKitSettings* settings) +{ + g_return_if_fail(WEBKIT_IS_WEB_VIEW_GROUP(group)); + g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); + + if (group->priv->settings == settings) + return; + + group->priv->settings = settings; + webkitWebViewGroupAttachSettingsToPageGroup(group); + g_object_notify(G_OBJECT(group), "settings"); +} + +COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_INJECTED_CONTENT_FRAMES_ALL, WebCore::InjectInAllFrames); +COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_INJECTED_CONTENT_FRAMES_TOP_ONLY, WebCore::InjectInTopFrameOnly); + +static PassRefPtr<ImmutableArray> toImmutableArray(const char* const* list) +{ + if (!list) + return 0; + + Vector<RefPtr<APIObject> > entries; + while (*list) { + entries.append(WebString::createFromUTF8String(*list)); + list++; + } + return ImmutableArray::adopt(entries); +} + +/** + * webkit_web_view_group_add_user_style_sheet: + * @group: a #WebKitWebViewGroup + * @source: the source of the style_sheet to inject + * @base_uri: (allow-none): the base URI to use when processing the style_sheet contents or %NULL for about:blank + * @whitelist: (array zero-terminated=1) (allow-none): a whitelist of URI patterns or %NULL + * @blacklist: (array zero-terminated=1) (allow-none): a blacklist of URI patterns or %NULL + * @injected_frames: a #WebKitInjectedContentFrames describing to which frames the style_sheet should apply + * + * Inject an external style sheet into pages. It is possible to only apply the style sheet + * to some URIs by passing non-null values for @whitelist or @blacklist. Passing a %NULL + * whitelist implies that all URIs are on the whitelist. The style sheet is applied if a URI matches + * the whitelist and not the blacklist. URI patterns must be of the form [protocol]://[host]/[path] + * where the host and path components can contain the wildcard character ('*') to represent zero + * or more other characters. + */ +void webkit_web_view_group_add_user_style_sheet(WebKitWebViewGroup* group, const char* source, const char* baseURI, const char* const* whitelist, const char* const* blacklist, WebKitInjectedContentFrames injectedFrames) +{ + g_return_if_fail(WEBKIT_IS_WEB_VIEW_GROUP(group)); + g_return_if_fail(source); + + RefPtr<ImmutableArray> webWhitelist = toImmutableArray(whitelist); + RefPtr<ImmutableArray> webBlacklist = toImmutableArray(blacklist); + + // We always use UserStyleUserLevel to match the behavior of WKPageGroupAddUserStyleSheet. + group->priv->pageGroup->addUserStyleSheet( + String::fromUTF8(source), + String::fromUTF8(baseURI), + webWhitelist.get(), + webBlacklist.get(), + static_cast<WebCore::UserContentInjectedFrames>(injectedFrames), + WebCore::UserStyleUserLevel); +} + +/** + * webkit_web_view_group_remove_all_user_style_sheets: + * @group: a #WebKitWebViewGroup + * + * Remove all style sheets previously injected into this #WebKitWebViewGroup + * via webkit_web_view_group_add_user_style_sheet(). + */ +void webkit_web_view_group_remove_all_user_style_sheets(WebKitWebViewGroup* group) +{ + g_return_if_fail(WEBKIT_IS_WEB_VIEW_GROUP(group)); + group->priv->pageGroup->removeAllUserStyleSheets(); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.h new file mode 100644 index 000000000..685f19904 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.h @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) +#error "Only <webkit2/webkit2.h> can be included directly." +#endif + +#ifndef WebKitWebViewGroup_h +#define WebKitWebViewGroup_h + +#include <glib-object.h> +#include <webkit2/WebKitDefines.h> +#include <webkit2/WebKitSettings.h> + +G_BEGIN_DECLS + +#define WEBKIT_TYPE_WEB_VIEW_GROUP (webkit_web_view_group_get_type()) +#define WEBKIT_WEB_VIEW_GROUP(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_WEB_VIEW_GROUP, WebKitWebViewGroup)) +#define WEBKIT_IS_WEB_VIEW_GROUP(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_WEB_VIEW_GROUP)) +#define WEBKIT_WEB_VIEW_GROUP_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_VIEW_GROUP, WebKitWebViewGroupClass)) +#define WEBKIT_IS_WEB_VIEW_GROUP_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_VIEW_GROUP)) +#define WEBKIT_WEB_VIEW_GROUP_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_WEB_VIEW_GROUP, WebKitWebViewGroupClass)) + +typedef struct _WebKitWebViewGroup WebKitWebViewGroup; +typedef struct _WebKitWebViewGroupClass WebKitWebViewGroupClass; +typedef struct _WebKitWebViewGroupPrivate WebKitWebViewGroupPrivate; + +struct _WebKitWebViewGroup { + GObject parent; + + WebKitWebViewGroupPrivate *priv; +}; + +struct _WebKitWebViewGroupClass { + GObjectClass parent_class; + + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); +}; + +/** + * WebKitInjectedContentFrames: + * @WEBKIT_INJECTED_CONTENT_FRAMES_ALL: Content will be injected into all frames. + * @WEBKIT_INJECTED_CONTENT_FRAMES_TOP_ONLY: Content will only be injected into the main frame. + * + * Enum values used for determining into which frames content is injected. + */ +typedef enum { + WEBKIT_INJECTED_CONTENT_FRAMES_ALL, + WEBKIT_INJECTED_CONTENT_FRAMES_TOP_ONLY, +} WebKitInjectedContentFrames; + +WEBKIT_API GType +webkit_web_view_group_get_type (void); + +WEBKIT_API WebKitWebViewGroup * +webkit_web_view_group_new (const gchar *name); + +WEBKIT_API const gchar * +webkit_web_view_group_get_name (WebKitWebViewGroup *group); + +WEBKIT_API WebKitSettings * +webkit_web_view_group_get_settings (WebKitWebViewGroup *group); + +WEBKIT_API void +webkit_web_view_group_set_settings (WebKitWebViewGroup *group, + WebKitSettings *settings); + +WEBKIT_API void +webkit_web_view_group_add_user_style_sheet (WebKitWebViewGroup *group, + const gchar *source, + const gchar *base_uri, + const gchar * const *whitelist, + const gchar * const *blacklist, + WebKitInjectedContentFrames injected_frames); + +WEBKIT_API void +webkit_web_view_group_remove_all_user_style_sheets (WebKitWebViewGroup *group); + +G_END_DECLS + +#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroupPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroupPrivate.h new file mode 100644 index 000000000..5fd865610 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroupPrivate.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifndef WebKitWebViewGroupPrivate_h +#define WebKitWebViewGroupPrivate_h + +#include "WebKitWebViewGroup.h" +#include "WebPageGroup.h" + +WebKitWebViewGroup* webkitWebViewGroupCreate(WebKit::WebPageGroup*); +WebKit::WebPageGroup* webkitWebViewGroupGetPageGroup(WebKitWebViewGroup*); + +#endif // WebKitWebViewGroupPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewPrivate.h index 66da58476..eb1f27db2 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewPrivate.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewPrivate.h @@ -27,11 +27,13 @@ #ifndef WebKitWebViewPrivate_h #define WebKitWebViewPrivate_h +#include "WebImage.h" #include "WebKitWebView.h" #include <wtf/text/CString.h> void webkitWebViewLoadChanged(WebKitWebView*, WebKitLoadEvent); void webkitWebViewLoadFailed(WebKitWebView*, WebKitLoadEvent, const char* failingURI, GError*); +void webkitWebViewLoadFailedWithTLSErrors(WebKitWebView*, const char* failingURI, GError *, GTlsCertificateFlags, GTlsCertificate*); void webkitWebViewSetEstimatedLoadProgress(WebKitWebView*, double estimatedLoadProgress); void webkitWebViewSetTitle(WebKitWebView*, const CString&); void webkitWebViewUpdateURI(WebKitWebView*); @@ -49,12 +51,14 @@ void webkitWebViewPrintFrame(WebKitWebView*, WebKit::WebFrameProxy*); void webkitWebViewResourceLoadStarted(WebKitWebView*, WebKit::WebFrameProxy*, uint64_t resourceIdentifier, WebKitURIRequest*); void webkitWebViewRunFileChooserRequest(WebKitWebView*, WebKitFileChooserRequest*); WebKitWebResource* webkitWebViewGetLoadingWebResource(WebKitWebView*, uint64_t resourceIdentifier); +void webKitWebViewDidReceiveSnapshot(WebKitWebView*, uint64_t callbackID, WebKit::WebImage*); void webkitWebViewRemoveLoadingWebResource(WebKitWebView*, uint64_t resourceIdentifier); -WebKitWebResource* webkitWebViewResourceLoadFinished(WebKitWebView*, uint64_t resourceIdentifier); bool webkitWebViewEnterFullScreen(WebKitWebView*); bool webkitWebViewLeaveFullScreen(WebKitWebView*); void webkitWebViewPopulateContextMenu(WebKitWebView*, WebKit::ImmutableArray* proposedMenu, WebKit::WebHitTestResult*); void webkitWebViewSubmitFormRequest(WebKitWebView*, WebKitFormSubmissionRequest*); void webkitWebViewHandleAuthenticationChallenge(WebKitWebView*, WebKit::AuthenticationChallengeProxy*); +void webkitWebViewInsecureContentDetected(WebKitWebView*, WebKitInsecureContentEvent); +void webkitWebViewWebProcessCrashed(WebKitWebView*); #endif // WebKitWebViewPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h index 11d71fb9a..edbcee98d 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h +++ b/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h @@ -51,6 +51,10 @@ struct _WebKitWindowProperties { struct _WebKitWindowPropertiesClass { GObjectClass parent_class; + void (*_webkit_reserved0) (void); + void (*_webkit_reserved1) (void); + void (*_webkit_reserved2) (void); + void (*_webkit_reserved3) (void); }; WEBKIT_API GType diff --git a/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.cpp b/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.cpp new file mode 100644 index 000000000..8b87c1522 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "WebViewBaseInputMethodFilter.h" + +#include "NativeWebKeyboardEvent.h" +#include "WebKitWebViewBasePrivate.h" +#include "WebPageProxy.h" +#include <WebCore/Color.h> +#include <WebCore/CompositionResults.h> +#include <WebCore/Editor.h> + +using namespace WebCore; + +namespace WebKit { + +void WebViewBaseInputMethodFilter::setWebView(WebKitWebViewBase* webView) +{ + GtkInputMethodFilter::setWidget(GTK_WIDGET(webView)); + + m_webPageProxy = webkitWebViewBaseGetPage(webView); + ASSERT(m_webPageProxy); +} + +bool WebViewBaseInputMethodFilter::canEdit() +{ + return true; +} + +bool WebViewBaseInputMethodFilter::sendSimpleKeyEvent(GdkEventKey* event, WTF::String simpleString, EventFakedForComposition faked) +{ + ASSERT(m_webPageProxy); + m_webPageProxy->handleKeyboardEvent(NativeWebKeyboardEvent(reinterpret_cast<GdkEvent*>(event), + CompositionResults(simpleString), faked)); + return true; +} + +bool WebViewBaseInputMethodFilter::sendKeyEventWithCompositionResults(GdkEventKey* event, ResultsToSend resultsToSend, EventFakedForComposition faked) +{ + ASSERT(m_webPageProxy); + m_webPageProxy->handleKeyboardEvent(NativeWebKeyboardEvent(reinterpret_cast<GdkEvent*>(event), + CompositionResults(CompositionResults::WillSendCompositionResultsSoon), + faked)); + + if (resultsToSend & Composition && !m_confirmedComposition.isNull()) + confirmCompositionText(m_confirmedComposition); + if (resultsToSend & Preedit && !m_preedit.isNull()) + setPreedit(m_preedit, m_cursorOffset); + return true; +} + +void WebViewBaseInputMethodFilter::confirmCompositionText(String text) +{ + ASSERT(m_webPageProxy); + m_webPageProxy->confirmComposition(text, -1, 0); +} + +void WebViewBaseInputMethodFilter::confirmCurrentComposition() +{ + ASSERT(m_webPageProxy); + m_webPageProxy->confirmComposition(String(), -1, 0); +} + +void WebViewBaseInputMethodFilter::cancelCurrentComposition() +{ + ASSERT(m_webPageProxy); + m_webPageProxy->cancelComposition(); +} + +void WebViewBaseInputMethodFilter::setPreedit(String newPreedit, int cursorOffset) +{ + // TODO: We should parse the PangoAttrList that we get from the IM context here. + Vector<CompositionUnderline> underlines; + underlines.append(CompositionUnderline(0, newPreedit.length(), Color(1, 1, 1), false)); + + ASSERT(m_webPageProxy); + m_webPageProxy->setComposition(newPreedit, underlines, + m_cursorOffset, m_cursorOffset, + 0 /* replacement start */, + 0 /* replacement end */); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.h b/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.h new file mode 100644 index 000000000..9cde8b12d --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifndef WebViewBaseInputMethodFilter_h +#define WebViewBaseInputMethodFilter_h + +#include "GtkInputMethodFilter.h" +#include "WebPageProxy.h" + +typedef struct _WebKitWebViewBase WebKitWebViewBase; + +namespace WebKit { + +class WebViewBaseInputMethodFilter : public WebCore::GtkInputMethodFilter { +public: + void setWebView(WebKitWebViewBase*); + +protected: + virtual bool sendSimpleKeyEvent(GdkEventKey*, WTF::String eventString, EventFakedForComposition); + virtual bool sendKeyEventWithCompositionResults(GdkEventKey*, ResultsToSend, EventFakedForComposition); + virtual bool canEdit(); + virtual void confirmCompositionText(String); + virtual void confirmCurrentComposition(); + virtual void cancelCurrentComposition(); + virtual void setPreedit(String, int cursorOffset); + +private: + WebPageProxy* m_webPageProxy; +}; + +} // namespace WebKit + +#endif // WebViewBaseInputMethodFilter_h diff --git a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-docs.sgml b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-docs.sgml index 8623af33e..2fa7ebacf 100644 --- a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-docs.sgml +++ b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-docs.sgml @@ -13,7 +13,6 @@ <title>Class Overview</title> <xi:include href="xml/WebKitWebContext.xml"/> <xi:include href="xml/WebKitWebView.xml"/> - <xi:include href="xml/WebKitWebViewBase.xml"/> <xi:include href="xml/WebKitBackForwardList.xml"/> <xi:include href="xml/WebKitBackForwardListItem.xml"/> <xi:include href="xml/WebKitSettings.xml"/> @@ -42,6 +41,13 @@ <xi:include href="xml/WebKitContextMenuItem.xml"/> <xi:include href="xml/WebKitFormSubmissionRequest.xml"/> <xi:include href="xml/WebKitSecurityManager.xml"/> + <xi:include href="xml/WebKitWebViewGroup.xml"/> + </chapter> + + <chapter> + <title>Web Extensions</title> + <xi:include href="xml/WebKitWebExtension.xml"/> + <xi:include href="xml/WebKitWebPage.xml"/> </chapter> <index id="index-all"> diff --git a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt index 2f6f54b0d..f280c62df 100644 --- a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt +++ b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt @@ -24,6 +24,7 @@ WEBKIT_OBSOLETE_API <TITLE>WebKitWebContext</TITLE> WebKitWebContext WebKitCacheModel +WebKitTLSErrorsPolicy webkit_web_context_get_default webkit_web_context_get_cache_model webkit_web_context_set_cache_model @@ -42,6 +43,11 @@ webkit_web_context_set_spell_checking_enabled webkit_web_context_get_spell_checking_languages webkit_web_context_set_spell_checking_languages webkit_web_context_set_preferred_languages +webkit_web_context_set_tls_errors_policy +webkit_web_context_get_tls_errors_policy +webkit_web_context_set_web_extensions_directory +webkit_web_context_prefetch_dns +webkit_web_context_set_disk_cache_directory <SUBSECTION URI Scheme> WebKitURISchemeRequestCallback @@ -68,6 +74,10 @@ WebKitWebView WebKitLoadEvent WebKitPolicyDecisionType WebKitSaveMode +WebKitViewMode +WebKitInsecureContentEvent +WebKitSnapshotOptions +WebKitSnapshotRegion <SUBSECTION Editing Commands> WEBKIT_EDITING_COMMAND_CUT @@ -80,7 +90,9 @@ WEBKIT_EDITING_COMMAND_REDO <SUBSECTION> webkit_web_view_new webkit_web_view_new_with_context +webkit_web_view_new_with_group webkit_web_view_get_context +webkit_web_view_get_group webkit_web_view_load_uri webkit_web_view_load_html webkit_web_view_load_alternate_html @@ -91,6 +103,7 @@ webkit_web_view_go_back webkit_web_view_can_go_forward webkit_web_view_go_forward webkit_web_view_get_title +webkit_web_view_get_page_id webkit_web_view_reload webkit_web_view_reload_bypass_cache webkit_web_view_stop_loading @@ -123,6 +136,11 @@ webkit_web_view_save_finish webkit_web_view_save_to_file webkit_web_view_save_to_file_finish webkit_web_view_download_uri +webkit_web_view_set_view_mode +webkit_web_view_get_view_mode +webkit_web_view_get_tls_info +webkit_web_view_get_snapshot +webkit_web_view_get_snapshot_finish <SUBSECTION WebKitJavascriptResult> WebKitJavascriptResult @@ -140,7 +158,6 @@ webkit_script_dialog_confirm_set_confirmed webkit_script_dialog_prompt_get_default_text webkit_script_dialog_prompt_set_text webkit_web_view_get_main_resource -webkit_web_view_get_subresources <SUBSECTION Standard> WebKitWebViewClass @@ -300,6 +317,10 @@ webkit_settings_set_user_agent webkit_settings_set_user_agent_with_application_details webkit_settings_get_enable_smooth_scrolling webkit_settings_set_enable_smooth_scrolling +webkit_settings_get_enable_accelerated_2d_canvas +webkit_settings_set_enable_accelerated_2d_canvas +webkit_settings_get_enable_write_console_messages_to_stdout +webkit_settings_set_enable_write_console_messages_to_stdout <SUBSECTION Standard> WebKitSettingsClass @@ -320,6 +341,8 @@ webkit_settings_get_type WebKitURIRequest webkit_uri_request_new webkit_uri_request_get_uri +webkit_uri_request_set_uri +webkit_uri_request_get_http_headers <SUBSECTION Standard> WebKitURIRequestClass @@ -342,7 +365,6 @@ webkit_uri_response_get_uri webkit_uri_response_get_status_code webkit_uri_response_get_content_length webkit_uri_response_get_mime_type -webkit_uri_response_get_https_status webkit_uri_response_get_suggested_filename <SUBSECTION Standard> @@ -526,6 +548,7 @@ webkit_hit_test_result_get_link_title webkit_hit_test_result_get_link_label webkit_hit_test_result_get_image_uri webkit_hit_test_result_get_media_uri +webkit_hit_test_result_context_is_scrollbar <SUBSECTION Standard> WebKitHitTestResultClass @@ -597,18 +620,21 @@ WEBKIT_POLICY_ERROR WEBKIT_DOWNLOAD_ERROR WEBKIT_PRINT_ERROR WEBKIT_JAVASCRIPT_ERROR +WEBKIT_SNAPSHOT_ERROR WebKitNetworkError WebKitPluginError WebKitPolicyError WebKitDownloadError WebKitPrintError WebKitJavascriptError +WebKitSnapshotError webkit_network_error_quark webkit_plugin_error_quark webkit_policy_error_quark webkit_download_error_quark webkit_print_error_quark webkit_javascript_error_quark +webkit_snapshot_error_quark </SECTION> <SECTION> @@ -782,6 +808,7 @@ webkit_uri_scheme_request_get_uri webkit_uri_scheme_request_get_path webkit_uri_scheme_request_get_web_view webkit_uri_scheme_request_finish +webkit_uri_scheme_request_finish_error <SUBSECTION Standard> WebKitURISchemeRequestClass @@ -919,3 +946,69 @@ WEBKIT_SECURITY_MANAGER_GET_CLASS WebKitSecurityManagerPrivate webkit_security_manager_get_type </SECTION> + +<SECTION> +<FILE>WebKitWebViewGroup</FILE> +WebKitWebViewGroup +WebKitInjectedContentFrames +webkit_web_view_group_new +webkit_web_view_group_get_name +webkit_web_view_group_get_settings +webkit_web_view_group_set_settings +webkit_web_view_group_add_user_style_sheet +webkit_web_view_group_remove_all_user_style_sheets + +<SUBSECTION Standard> +WebKitWebViewGroupClass +WEBKIT_TYPE_WEB_VIEW_GROUP +WEBKIT_WEB_VIEW_GROUP +WEBKIT_IS_WEB_VIEW_GROUP +WEBKIT_WEB_VIEW_GROUP_CLASS +WEBKIT_IS_WEB_VIEW_GROUP_CLASS +WEBKIT_WEB_VIEW_GROUP_GET_CLASS + +<SUBSECTION Private> +WebKitWebViewGroupPrivate +webkit_web_view_group_get_type +</SECTION> + +<SECTION> +<FILE>WebKitWebExtension</FILE> +WebKitWebExtension +WebKitWebExtensionInitializeFunction +webkit_web_extension_get_page + +<SUBSECTION Standard> +WebKitWebExtensionClass +WEBKIT_TYPE_WEB_EXTENSION +WEBKIT_WEB_EXTENSION +WEBKIT_IS_WEB_EXTENSION +WEBKIT_WEB_EXTENSION_CLASS +WEBKIT_IS_WEB_EXTENSION_CLASS +WEBKIT_WEB_EXTENSION_GET_CLASS + +<SUBSECTION Private> +WebKitWebExtensionPrivate +webkit_web_extension_get_type +</SECTION> + +<SECTION> +<FILE>WebKitWebPage</FILE> +WebKitWebPage +webkit_web_page_get_dom_document +webkit_web_page_get_id +webkit_web_page_get_uri + +<SUBSECTION Standard> +WebKitWebPageClass +WEBKIT_TYPE_WEB_PAGE +WEBKIT_WEB_PAGE +WEBKIT_IS_WEB_PAGE +WEBKIT_WEB_PAGE_CLASS +WEBKIT_IS_WEB_PAGE_CLASS +WEBKIT_WEB_PAGE_GET_CLASS + +<SUBSECTION Private> +WebKitWebPagePrivate +webkit_web_page_get_type +</SECTION> diff --git a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk.types b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk.types index 4d8843e9c..5d97f69be 100644 --- a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk.types +++ b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk.types @@ -21,3 +21,6 @@ webkit_web_inspector_get_type webkit_uri_scheme_request_get_type webkit_context_menu_get_type webkit_context_menu_item_get_type +webkit_web_view_group_get_type +webkit_web_extension_get_type +webkit_web_page_get_type diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am b/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am index a8f9976fd..7510b617c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am +++ b/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am @@ -12,6 +12,7 @@ TEST_PROGS += \ Programs/WebKit2APITests/TestPrinting \ Programs/WebKit2APITests/TestResources \ Programs/WebKit2APITests/TestSSL \ + Programs/WebKit2APITests/TestWebExtensions \ Programs/WebKit2APITests/TestWebKitVersion \ Programs/WebKit2APITests/TestWebKitFaviconDatabase \ Programs/WebKit2APITests/TestWebKitFindController \ @@ -19,6 +20,7 @@ TEST_PROGS += \ Programs/WebKit2APITests/TestWebKitSettings \ Programs/WebKit2APITests/TestWebKitWebContext \ Programs/WebKit2APITests/TestWebKitWebView \ + Programs/WebKit2APITests/TestWebKitWebViewGroup \ Programs/WebKit2APITests/TestWebViewEditor noinst_PROGRAMS += $(TEST_PROGS) @@ -34,6 +36,8 @@ webkit2_tests_cppflags = \ -DWEBKIT_SRC_DIR=\"${shell pwd}/${srcdir}\" \ -DWEBKIT_DERIVED_SRC_DIR=\"${shell pwd}/${top_builddir}/DerivedSources\" \ -DWEBKIT_TEST_PLUGIN_DIR=\"${shell pwd}/${top_builddir}/TestNetscapePlugin/.libs\" \ + -DWEBKIT_TEST_WEB_EXTENSIONS_DIR=\"${shell pwd}/${top_builddir}/Libraries/WebExtensions/.libs\" \ + -DWEBKIT_INJECTED_BUNDLE_PATH=\"${shell pwd}/$(top_builddir)/.libs\" \ $(javascriptcore_cppflags) \ -I$(srcdir)/Source/JavaScriptCore \ -I$(srcdir)/Source \ @@ -43,6 +47,7 @@ webkit2_tests_cppflags = \ -I$(top_builddir)/DerivedSources/WebKit2/webkit2gtk/include \ -I$(srcdir)/Source/WebKit2/UIProcess/API/gtk \ $(global_cppflags) \ + $(FREETYPE_CFLAGS) \ $(GLIB_CFLAGS) \ $(GTK_CFLAGS) \ $(LIBSOUP_CFLAGS) @@ -51,6 +56,7 @@ webkit2_tests_ldadd = \ Libraries/libWebKit2APITestCore.la \ libjavascriptcoregtk-@WEBKITGTK_API_MAJOR_VERSION@.@WEBKITGTK_API_MINOR_VERSION@.la \ libwebkit2gtk-@WEBKITGTK_API_MAJOR_VERSION@.@WEBKITGTK_API_MINOR_VERSION@.la \ + $(FREETYPE_LIBS) \ $(GEOCLUE_LIBS) \ $(GLIB_LIBS) \ $(GTK_LIBS) \ @@ -61,15 +67,27 @@ webkit2_tests_ldflags = \ -no-fast-install Programs/resources/webkit2gtk-tests-resources.gresource: Source/WebKit2/UIProcess/API/gtk/tests/resources/webkit2gtk-tests.gresource.xml $(shell $(GLIB_COMPILE_RESOURCES) --sourcedir=$(srcdir) --generate-dependencies $(srcdir)/Source/WebKit2/UIProcess/API/gtk/tests/resources/webkit2gtk-tests.gresource.xml) + $(AM_V_at)mkdir -p ${GENPROGRAMS}/resources $(AM_V_GEN) $(GLIB_COMPILE_RESOURCES) --target=$@ --sourcedir=$(srcdir) $< -DISTCLEANFILES += Programs/resources/webkit2gtk-tests-resources.gresource -noinst_DATA += Programs/resources/webkit2gtk-tests-resources.gresource +Programs/resources/inspector/inspectorPageIndex.html: Source/WebKit2/UIProcess/InspectorServer/front-end/inspectorPageIndex.html + $(AM_V_at)mkdir -p ${GENPROGRAMS}/resources/inspector + $(AM_V_GEN)cp $(srcdir)/Source/WebKit2/UIProcess/InspectorServer/front-end/inspectorPageIndex.html ${GENPROGRAMS}/resources/inspector + +DISTCLEANFILES += \ + Programs/resources/webkit2gtk-tests-resources.gresource \ + Programs/resources/inspector/inspectorPageIndex.html + +noinst_DATA += \ + Programs/resources/webkit2gtk-tests-resources.gresource \ + Programs/resources/inspector/inspectorPageIndex.html noinst_LTLIBRARIES += Libraries/libWebKit2APITestCore.la Libraries_libWebKit2APITestCore_la_SOURCES = \ Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp \ Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.h \ + Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.cpp \ + Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.h \ Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.cpp \ Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.h \ Source/WebKit2/UIProcess/API/gtk/tests/TestMain.cpp \ @@ -78,6 +96,30 @@ Libraries_libWebKit2APITestCore_la_SOURCES = \ Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h Libraries_libWebKit2APITestCore_la_CPPFLAGS = $(webkit2_tests_cppflags) +noinst_LTLIBRARIES += Libraries/WebExtensions/libWebExtensionTest.la +Libraries_WebExtensions_libWebExtensionTest_la_SOURCES = \ + Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp + +Libraries_WebExtensions_libWebExtensionTest_la_LDFLAGS = \ + -rpath ${shell pwd}/$(top_builddir)/Libraries/WebExtensions/.libs \ + $(no_undefined) \ + -avoid-version \ + -module + +Libraries_WebExtensions_libWebExtensionTest_la_CPPFLAGS = \ + -I$(srcdir)/Source/WebKit2/WebProcess/InjectedBundle/API/gtk \ + -I$(top_builddir)/DerivedSources \ + -I$(top_builddir)/DerivedSources/WebKit2/webkit2extension/include \ + -DWEBKIT2_COMPILATION \ + $(webkit2_tests_cppflags) + +Libraries_WebExtensions_libWebExtensionTest_la_CXXFLAGS = \ + $(global_cxxflags) + +Libraries_WebExtensions_libWebExtensionTest_la_CFLAGS = \ + $(global_cflags) + + EXTRA_DIST += \ Source/WebKit2/UIProcess/API/gtk/tests/resources/test-cert.pem \ Source/WebKit2/UIProcess/API/gtk/tests/resources/test-key.pem \ @@ -214,4 +256,16 @@ Programs_WebKit2APITests_TestSSL_CPPFLAGS = $(webkit2_tests_cppflags) Programs_WebKit2APITests_TestSSL_LDADD = $(webkit2_tests_ldadd) Programs_WebKit2APITests_TestSSL_LDFLAGS = $(webkit2_tests_ldflags) +Programs_WebKit2APITests_TestWebExtensions_SOURCES = \ + Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp +Programs_WebKit2APITests_TestWebExtensions_CPPFLAGS = $(webkit2_tests_cppflags) +Programs_WebKit2APITests_TestWebExtensions_LDADD = $(webkit2_tests_ldadd) +Programs_WebKit2APITests_TestWebExtensions_LDFLAGS = $(webkit2_tests_ldflags) + +Programs_WebKit2APITests_TestWebKitWebViewGroup_SOURCES = \ + Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebViewGroup.cpp +Programs_WebKit2APITests_TestWebKitWebViewGroup_CPPFLAGS = $(webkit2_tests_cppflags) +Programs_WebKit2APITests_TestWebKitWebViewGroup_LDADD = $(webkit2_tests_ldadd) +Programs_WebKit2APITests_TestWebKitWebViewGroup_LDFLAGS = $(webkit2_tests_ldflags) + endif # ENABLE_WEBKIT2 diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/InspectorTestServer.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/InspectorTestServer.cpp index f13b043df..7c9dc900c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/InspectorTestServer.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/InspectorTestServer.cpp @@ -40,6 +40,10 @@ int main(int argc, char** argv) // Overwrite WEBKIT_INSPECTOR_SERVER variable with default value. g_setenv("WEBKIT_INSPECTOR_SERVER", "127.0.0.1:2999", TRUE); + + // Overwrite WEBKIT_INSPECTOR_SERVER_PATH variable to point to inspector resources folder. + const gchar* inspectorResourcesPath = g_getenv("WEBKIT_INSPECTOR_PATH"); + g_setenv("WEBKIT_INSPECTOR_SERVER_PATH", inspectorResourcesPath, TRUE); WebKitWebView* webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(webView), TRUE); diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp index b904111f4..df3420492 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp @@ -63,6 +63,7 @@ static void loadChangedCallback(WebKitWebView* webView, WebKitLoadEvent loadEven static void loadFailedCallback(WebKitWebView* webView, WebKitLoadEvent loadEvent, const char* failingURI, GError* error, LoadTrackingTest* test) { test->m_loadFailed = true; + test->m_error.set(g_error_copy(error)); switch (loadEvent) { case WEBKIT_LOAD_STARTED: @@ -153,6 +154,7 @@ void LoadTrackingTest::loadURI(const char* uri) { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); WebViewTest::loadURI(uri); } @@ -160,6 +162,7 @@ void LoadTrackingTest::loadHtml(const char* html, const char* baseURI) { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); WebViewTest::loadHtml(html, baseURI); } @@ -167,6 +170,7 @@ void LoadTrackingTest::loadPlainText(const char* plainText) { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); WebViewTest::loadPlainText(plainText); } @@ -174,6 +178,7 @@ void LoadTrackingTest::loadRequest(WebKitURIRequest* request) { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); WebViewTest::loadRequest(request); } @@ -181,6 +186,7 @@ void LoadTrackingTest::reload() { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); webkit_web_view_reload(m_webView); } @@ -188,6 +194,7 @@ void LoadTrackingTest::goBack() { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); WebViewTest::goBack(); } @@ -195,5 +202,6 @@ void LoadTrackingTest::goForward() { m_loadEvents.clear(); m_estimatedProgress = 0; + m_error.clear(); WebViewTest::goForward(); } diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.h b/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.h index 562f7f038..a3cf7843d 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.h +++ b/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.h @@ -59,6 +59,7 @@ public: }; bool m_runLoadUntilCompletion; bool m_loadFailed; + GOwnPtr<GError> m_error; Vector<LoadEvents> m_loadEvents; float m_estimatedProgress; CString m_redirectURI; diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp index eff59862b..c361f8baf 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp @@ -354,8 +354,8 @@ static void testContextMenuDefaultMenu(ContextMenuDefaultTest* test, gconstpoint " <a style='position:absolute; left:1; top:1' href='http://www.webkitgtk.org' title='WebKitGTK+ Title'>WebKitGTK+ Website</a>" " <img style='position:absolute; left:1; top:10' src='0xdeadbeef' width=5 height=5></img>" " <a style='position:absolute; left:1; top:20' href='http://www.webkitgtk.org/logo' title='WebKitGTK+ Logo'><img src='0xdeadbeef' width=5 height=5></img></a>" - " <video style='position:absolute; left:1; top:30' width=10 height=10 controls='controls'><source src='movie.ogg' type='video/ogg' /></video>" - " <input style='position:absolute; left:1; top:50' size='10'></input>" + " <input style='position:absolute; left:1; top:30' size='10'></input>" + " <video style='position:absolute; left:1; top:50' width='300' height='300' controls='controls' preload='none'><source src='movie.ogg' type='video/ogg' /></video>" "</body></html>"; test->loadHtml(linksHTML, "file:///"); test->waitUntilLoadFinished(); @@ -382,11 +382,11 @@ static void testContextMenuDefaultMenu(ContextMenuDefaultTest* test, gconstpoint // Context menu for image video. test->m_expectedMenuType = ContextMenuDefaultTest::Video; - test->showContextMenuAtPositionAndWaitUntilFinished(1, 30); + test->showContextMenuAtPositionAndWaitUntilFinished(1, 50); // Context menu for editable. test->m_expectedMenuType = ContextMenuDefaultTest::Editable; - test->showContextMenuAtPositionAndWaitUntilFinished(5, 55); + test->showContextMenuAtPositionAndWaitUntilFinished(5, 35); } class ContextMenuCustomTest: public ContextMenuTest { diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp index 56a62cd09..ce159906c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp @@ -153,9 +153,18 @@ public: webkit_download_set_destination(download, destinationURI.get()); } - void waitUntilDownloadFinishes() + WebKitDownload* downloadURIAndWaitUntilFinishes(const CString& requestURI) { + WebKitDownload* download = webkit_web_context_download_uri(m_webContext, requestURI.data()); + assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download)); + + WebKitURIRequest* request = webkit_download_get_request(download); + g_assert(request); + ASSERT_CMP_CSTRING(webkit_uri_request_get_uri(request), ==, requestURI); + g_main_loop_run(m_mainLoop); + + return download; } void checkDestinationAndDeleteFile(WebKitDownload* download, const char* expectedName) @@ -181,9 +190,7 @@ static void testDownloadLocalFile(DownloadTest* test, gconstpointer) GRefPtr<GFile> source = adoptGRef(g_file_new_for_path(sourcePath.get())); GRefPtr<GFileInfo> sourceInfo = adoptGRef(g_file_query_info(source.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE, static_cast<GFileQueryInfoFlags>(0), 0, 0)); GOwnPtr<char> sourceURI(g_file_get_uri(source.get())); - GRefPtr<WebKitDownload> download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, sourceURI.get())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + GRefPtr<WebKitDownload> download = adoptGRef(test->downloadURIAndWaitUntilFinishes(sourceURI.get())); g_assert(!webkit_download_get_web_view(download.get())); Vector<DownloadTest::DownloadEvent>& events = test->m_downloadEvents; @@ -246,9 +253,7 @@ public: static void testDownloadLocalFileError(DownloadErrorTest* test, gconstpointer) { test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_NETWORK; - GRefPtr<WebKitDownload> download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, "file:///foo/bar")); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + GRefPtr<WebKitDownload> download = adoptGRef(test->downloadURIAndWaitUntilFinishes("file:///foo/bar")); g_assert(!webkit_download_get_web_view(download.get())); Vector<DownloadTest::DownloadEvent>& events = test->m_downloadEvents; @@ -263,12 +268,9 @@ static void testDownloadLocalFileError(DownloadErrorTest* test, gconstpointer) GOwnPtr<char> path(g_build_filename(Test::getWebKit1TestResoucesDir().data(), "test.pdf", NULL)); GRefPtr<GFile> file = adoptGRef(g_file_new_for_path(path.get())); GOwnPtr<char> uri(g_file_get_uri(file.get())); - download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, uri.get())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + download = adoptGRef(test->downloadURIAndWaitUntilFinishes(uri.get())); g_assert(!webkit_download_get_web_view(download.get())); - events = test->m_downloadEvents; g_assert_cmpint(events.size(), ==, 4); g_assert_cmpint(events[0], ==, DownloadTest::Started); g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); @@ -279,12 +281,9 @@ static void testDownloadLocalFileError(DownloadErrorTest* test, gconstpointer) test->checkDestinationAndDeleteFile(download.get(), "bar"); test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER; - download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, uri.get())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + download = adoptGRef(test->downloadURIAndWaitUntilFinishes(uri.get())); g_assert(!webkit_download_get_web_view(download.get())); - events = test->m_downloadEvents; g_assert_cmpint(events.size(), ==, 4); g_assert_cmpint(events[0], ==, DownloadTest::Started); g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); @@ -325,9 +324,7 @@ static void serverCallback(SoupServer* server, SoupMessage* message, const char* static void testDownloadRemoteFile(DownloadTest* test, gconstpointer) { - GRefPtr<WebKitDownload> download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, kServer->getURIForPath("/test.pdf").data())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + GRefPtr<WebKitDownload> download = adoptGRef(test->downloadURIAndWaitUntilFinishes(kServer->getURIForPath("/test.pdf"))); g_assert(!webkit_download_get_web_view(download.get())); Vector<DownloadTest::DownloadEvent>& events = test->m_downloadEvents; @@ -341,8 +338,7 @@ static void testDownloadRemoteFile(DownloadTest* test, gconstpointer) WebKitURIRequest* request = webkit_download_get_request(download.get()); g_assert(request); - CString requestURI = kServer->getURIForPath("/test.pdf"); - g_assert_cmpstr(webkit_uri_request_get_uri(request), ==, requestURI.data()); + ASSERT_CMP_CSTRING(webkit_uri_request_get_uri(request), ==, kServer->getURIForPath("/test.pdf")); g_assert(webkit_download_get_destination(download.get())); g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), ==, 1); @@ -352,10 +348,7 @@ static void testDownloadRemoteFile(DownloadTest* test, gconstpointer) static void testDownloadRemoteFileError(DownloadErrorTest* test, gconstpointer) { test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_NETWORK; - GRefPtr<WebKitDownload> download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, - kServer->getURIForPath("/foo").data())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + GRefPtr<WebKitDownload> download = adoptGRef(test->downloadURIAndWaitUntilFinishes(kServer->getURIForPath("/foo"))); g_assert(!webkit_download_get_web_view(download.get())); Vector<DownloadTest::DownloadEvent>& events = test->m_downloadEvents; @@ -370,12 +363,9 @@ static void testDownloadRemoteFileError(DownloadErrorTest* test, gconstpointer) g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_DESTINATION; - download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, kServer->getURIForPath("/test.pdf").data())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + download = adoptGRef(test->downloadURIAndWaitUntilFinishes(kServer->getURIForPath("/test.pdf"))); g_assert(!webkit_download_get_web_view(download.get())); - events = test->m_downloadEvents; g_assert_cmpint(events.size(), ==, 4); g_assert_cmpint(events[0], ==, DownloadTest::Started); g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); @@ -386,12 +376,9 @@ static void testDownloadRemoteFileError(DownloadErrorTest* test, gconstpointer) test->checkDestinationAndDeleteFile(download.get(), "bar"); test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER; - download = adoptGRef(webkit_web_context_download_uri(test->m_webContext, kServer->getURIForPath("/test.pdf").data())); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download.get())); - test->waitUntilDownloadFinishes(); + download = adoptGRef(test->downloadURIAndWaitUntilFinishes(kServer->getURIForPath("/test.pdf"))); g_assert(!webkit_download_get_web_view(download.get())); - events = test->m_downloadEvents; g_assert_cmpint(events.size(), ==, 4); g_assert_cmpint(events[0], ==, DownloadTest::Started); g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); @@ -500,8 +487,14 @@ public: static void testPolicyResponseDownload(PolicyResponseDownloadTest* test, gconstpointer) { // Test that a download started by the the policy checker contains the web view. - test->loadURI(kServer->getURIForPath("/test.pdf").data()); + CString requestURI = kServer->getURIForPath("/test.pdf").data(); + test->loadURI(requestURI.data()); test->waitUntilDownloadStarted(); + + WebKitURIRequest* request = webkit_download_get_request(test->m_download.get()); + g_assert(request); + ASSERT_CMP_CSTRING(webkit_uri_request_get_uri(request), ==, requestURI); + g_assert(test->m_webView == webkit_download_get_web_view(test->m_download.get())); test->cancelDownloadAndWaitUntilFinished(); } diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp index 673749411..aa80888b3 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp @@ -59,12 +59,12 @@ public: return test->detach(); } + static const unsigned gMinimumAttachedInspectorWidth = 750; static const unsigned gMinimumAttachedInspectorHeight = 250; InspectorTest() : WebViewTest() , m_inspector(webkit_web_view_get_inspector(m_webView)) - , m_quitOnBringToFront(false) { webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(m_webView), TRUE); assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_inspector)); @@ -90,15 +90,13 @@ public: virtual bool bringToFront() { m_events.append(BringToFront); - if (m_quitOnBringToFront) - g_main_loop_quit(m_mainLoop); + g_main_loop_quit(m_mainLoop); return FALSE; } virtual void closed() { m_events.append(Closed); - g_main_loop_quit(m_mainLoop); } virtual bool attach() @@ -113,18 +111,23 @@ public: return TRUE; } - void showAndWaitUntilFinished(bool quitOnBringToFront) + + static gboolean showIdle(InspectorTest* test) { - m_quitOnBringToFront = quitOnBringToFront; - webkit_web_inspector_show(m_inspector); + webkit_web_inspector_show(test->m_inspector); + return FALSE; + } + + void show() + { + g_idle_add(reinterpret_cast<GSourceFunc>(showIdle), this); g_main_loop_run(m_mainLoop); - m_quitOnBringToFront = false; } void resizeViewAndAttach() { // Resize the view to make room for the inspector. - resizeView(300, (gMinimumAttachedInspectorHeight + 1) * 4 / 3); + resizeView(gMinimumAttachedInspectorWidth, (gMinimumAttachedInspectorHeight + 1) * 4 / 3); webkit_web_inspector_attach(m_inspector); } @@ -140,14 +143,12 @@ public: g_main_loop_run(m_mainLoop); } - void closeAndWaitUntilClosed() + void close() { webkit_web_inspector_close(m_inspector); - g_main_loop_run(m_mainLoop); } WebKitWebInspector* m_inspector; - bool m_quitOnBringToFront; Vector<InspectorEvents> m_events; }; @@ -158,7 +159,7 @@ static void testInspectorDefault(InspectorTest* test, gconstpointer) test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); - test->showAndWaitUntilFinished(false); + test->show(); // We don't add the view to a container, so consume the weak ref with GRefPtr. GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); @@ -166,12 +167,11 @@ static void testInspectorDefault(InspectorTest* test, gconstpointer) g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; - g_assert_cmpint(events.size(), ==, 2); - g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); - g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); + g_assert_cmpint(events.size(), ==, 1); + g_assert_cmpint(events[0], ==, InspectorTest::OpenWindow); test->m_events.clear(); - test->showAndWaitUntilFinished(true); + test->show(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); @@ -193,7 +193,7 @@ static void testInspectorDefault(InspectorTest* test, gconstpointer) g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); - test->closeAndWaitUntilClosed(); + test->close(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); @@ -272,12 +272,11 @@ public: return InspectorTest::detach(); } - void destroyWindowAndWaitUntilClosed() + void destroyWindow() { g_assert(m_inspectorWindow); gtk_widget_destroy(m_inspectorWindow); m_inspectorWindow = 0; - g_main_loop_run(m_mainLoop); } GtkWidget* m_inspectorWindow; @@ -290,13 +289,12 @@ static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpoi test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); - test->showAndWaitUntilFinished(false); + test->show(); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webkit_web_inspector_get_web_view(test->m_inspector))); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); Vector<InspectorTest::InspectorEvents>& events = test->m_events; - g_assert_cmpint(events.size(), ==, 2); - g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); - g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); + g_assert_cmpint(events.size(), ==, 1); + g_assert_cmpint(events[0], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); @@ -318,7 +316,7 @@ static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpoi test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); test->m_events.clear(); - test->closeAndWaitUntilClosed(); + test->close(); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); @@ -333,12 +331,12 @@ static void testInspectorCustomContainerDestroyed(CustomInspectorTest* test, gco test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); - test->showAndWaitUntilFinished(false); + test->show(); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webkit_web_inspector_get_web_view(test->m_inspector))); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); test->m_events.clear(); - test->destroyWindowAndWaitUntilClosed(); + test->destroyWindow(); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp index 30d8fac0c..35fb3fcdc 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp @@ -73,12 +73,7 @@ static gpointer testServerMonitorThreadFunc(gpointer) static void startTestServerMonitor() { gChildIsReady = false; - -#if (!GLIB_CHECK_VERSION(2, 31, 0)) - g_thread_create(testServerMonitorThreadFunc, 0, FALSE, 0); -#else g_thread_new("TestServerMonitor", testServerMonitorThreadFunc, 0); -#endif } static void startTestServer() @@ -189,8 +184,8 @@ static void testInspectorServerPageList(InspectorServerTest* test, gconstpointer g_assert(javascriptResult); g_assert(!error.get()); valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); - String validInspectorURL = String("/webinspector/inspector.html?page=") + String::number(pageId); - g_assert_cmpstr(valueString.get(), ==, validInspectorURL.utf8().data()); + String validInspectorURL = String("/inspector.html?page=") + String::number(pageId); + ASSERT_CMP_CSTRING(valueString.get(), ==, validInspectorURL.utf8()); } // Test sending a raw remote debugging message through our web socket server. diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp index 8fcf33009..331915e00 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp @@ -22,13 +22,18 @@ #include "config.h" #include "LoadTrackingTest.h" +#include "WebKitTestBus.h" #include "WebKitTestServer.h" +#include "WebViewTest.h" #include <gtk/gtk.h> #include <libsoup/soup.h> #include <wtf/text/CString.h> +static WebKitTestBus* bus; static WebKitTestServer* kServer; +const char* kDNTHeaderNotPresent = "DNT header not present"; + static void testLoadingStatus(LoadTrackingTest* test, gconstpointer data) { test->setRedirectURI(kServer->getURIForPath("/normal").data()); @@ -214,9 +219,7 @@ public: private: void checkActiveURI(const char* uri) { - // g_assert_cmpstr is a macro, so we need to cache the temporary string. - CString serverURI = kServer->getURIForPath(uri); - g_assert_cmpstr(m_activeURI.data(), ==, serverURI.data()); + ASSERT_CMP_CSTRING(m_activeURI, ==, kServer->getURIForPath(uri)); } }; @@ -282,6 +285,105 @@ static void testWebViewIsLoading(ViewIsLoadingTest* test, gconstpointer) test->waitUntilLoadFinished(); } +class WebPageURITest: public WebViewTest { +public: + MAKE_GLIB_TEST_FIXTURE(WebPageURITest); + + static void webPageURIChangedCallback(GDBusConnection*, const char*, const char*, const char*, const char*, GVariant* result, WebPageURITest* test) + { + const char* uri; + g_variant_get(result, "(&s)", &uri); + test->m_webPageURIs.append(uri); + } + + static void webViewURIChanged(GObject*, GParamSpec*, WebPageURITest* test) + { + test->m_webViewURIs.append(webkit_web_view_get_uri(test->m_webView)); + } + + WebPageURITest() + { + GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest", + "/org/webkit/gtk/WebExtensionTest", "org.webkit.gtk.WebExtensionTest", m_mainLoop)); + m_uriChangedSignalID = g_dbus_connection_signal_subscribe( + g_dbus_proxy_get_connection(proxy.get()), + 0, + "org.webkit.gtk.WebExtensionTest", + "URIChanged", + "/org/webkit/gtk/WebExtensionTest", + 0, + G_DBUS_SIGNAL_FLAGS_NONE, + reinterpret_cast<GDBusSignalCallback>(webPageURIChangedCallback), + this, + 0); + g_assert(m_uriChangedSignalID); + + g_signal_connect(m_webView, "notify::uri", G_CALLBACK(webViewURIChanged), this); + } + + ~WebPageURITest() + { + g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); + g_dbus_connection_signal_unsubscribe(bus->connection(), m_uriChangedSignalID); + } + + unsigned m_uriChangedSignalID; + Vector<CString> m_webPageURIs; + Vector<CString> m_webViewURIs; +}; + +static void testWebPageURI(WebPageURITest* test, gconstpointer) +{ + test->loadURI(kServer->getURIForPath("/redirect").data()); + test->waitUntilLoadFinished(); + + g_assert_cmpint(test->m_webPageURIs.size(), ==, test->m_webViewURIs.size()); + for (size_t i = 0; i < test->m_webPageURIs.size(); ++i) + ASSERT_CMP_CSTRING(test->m_webPageURIs[i], ==, test->m_webViewURIs[i]); + + g_assert_cmpint(test->m_webPageURIs.size(), ==, 2); + ASSERT_CMP_CSTRING(test->m_webPageURIs[0], ==, kServer->getURIForPath("/redirect")); + ASSERT_CMP_CSTRING(test->m_webPageURIs[1], ==, kServer->getURIForPath("/normal")); + +} + +static void testURIRequestHTTPHeaders(WebViewTest* test, gconstpointer) +{ + GRefPtr<WebKitURIRequest> uriRequest = adoptGRef(webkit_uri_request_new("file:///foo/bar")); + g_assert(uriRequest.get()); + g_assert_cmpstr(webkit_uri_request_get_uri(uriRequest.get()), ==, "file:///foo/bar"); + g_assert(!webkit_uri_request_get_http_headers(uriRequest.get())); + + // Load a request with no Do Not Track header. + webkit_uri_request_set_uri(uriRequest.get(), kServer->getURIForPath("/do-not-track-header").data()); + test->loadRequest(uriRequest.get()); + test->waitUntilLoadFinished(); + + size_t mainResourceDataSize = 0; + const char* mainResourceData = test->mainResourceData(mainResourceDataSize); + g_assert_cmpint(mainResourceDataSize, ==, strlen(kDNTHeaderNotPresent)); + g_assert(!strncmp(mainResourceData, kDNTHeaderNotPresent, mainResourceDataSize)); + + // Add the Do Not Track header and load the request again. + SoupMessageHeaders* headers = webkit_uri_request_get_http_headers(uriRequest.get()); + g_assert(headers); + soup_message_headers_append(headers, "DNT", "1"); + test->loadRequest(uriRequest.get()); + test->waitUntilLoadFinished(); + + mainResourceData = test->mainResourceData(mainResourceDataSize); + g_assert_cmpint(mainResourceDataSize, ==, 1); + g_assert(!strncmp(mainResourceData, "1", mainResourceDataSize)); + + // Load a URI for which the web extension will add the Do Not Track header. + test->loadURI(kServer->getURIForPath("/add-do-not-track-header").data()); + test->waitUntilLoadFinished(); + + mainResourceData = test->mainResourceData(mainResourceDataSize); + g_assert_cmpint(mainResourceDataSize, ==, 1); + g_assert(!strncmp(mainResourceData, "1", mainResourceDataSize)); +} + static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) { static const char* responseString = "<html><body>Testing!Testing!Testing!Testing!Testing!Testing!Testing!" @@ -312,6 +414,13 @@ static void serverCallback(SoupServer* server, SoupMessage* message, const char* soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, responseString, strlen(responseString)); soup_server_unpause_message(server, message); return; + } else if (g_str_equal(path, "/do-not-track-header") || g_str_equal(path, "/add-do-not-track-header")) { + const char* doNotTrack = soup_message_headers_get_one(message->request_headers, "DNT"); + if (doNotTrack) + soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, doNotTrack, strlen(doNotTrack)); + else + soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, kDNTHeaderNotPresent, strlen(kDNTHeaderNotPresent)); + soup_message_set_status(message, SOUP_STATUS_OK); } else soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); @@ -320,6 +429,11 @@ static void serverCallback(SoupServer* server, SoupMessage* message, const char* void beforeAll() { + webkit_web_context_set_web_extensions_directory(webkit_web_context_get_default(), WEBKIT_TEST_WEB_EXTENSIONS_DIR); + bus = new WebKitTestBus(); + if (!bus->run()) + return; + kServer = new WebKitTestServer(); kServer->run(serverCallback); @@ -340,9 +454,12 @@ void beforeAll() ViewURITrackingTest::add("WebKitWebView", "active-uri", testWebViewActiveURI); ViewIsLoadingTest::add("WebKitWebView", "is-loading", testWebViewIsLoading); + WebPageURITest::add("WebKitWebPage", "get-uri", testWebPageURI); + WebViewTest::add("WebKitURIRequest", "http-headers", testURIRequestHTTPHeaders); } void afterAll() { + delete bus; delete kServer; } diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.cpp index 2044ab52e..6ac35f8ca 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.cpp @@ -20,7 +20,10 @@ #include "config.h" #include "TestMain.h" +#include <glib/gstdio.h> #include <gtk/gtk.h> +#include <webkit2/webkit2.h> +#include <wtf/gobject/GOwnPtr.h> void beforeAll(); void afterAll(); @@ -35,17 +38,38 @@ static void registerGResource(void) g_resource_unref(resource); } +static void removeNonEmptyDirectory(const char* directoryPath) +{ + GDir* directory = g_dir_open(directoryPath, 0, 0); + g_assert(directory); + const char* fileName; + while ((fileName = g_dir_read_name(directory))) { + GOwnPtr<char> filePath(g_build_filename(directoryPath, fileName, NULL)); + g_unlink(filePath.get()); + } + g_dir_close(directory); + g_rmdir(directoryPath); +} + int main(int argc, char** argv) { gtk_test_init(&argc, &argv, 0); g_setenv("WEBKIT_EXEC_PATH", WEBKIT_EXEC_PATH, FALSE); + g_setenv("WEBKIT_INJECTED_BUNDLE_PATH", WEBKIT_INJECTED_BUNDLE_PATH, FALSE); + g_setenv("LC_ALL", "C", TRUE); g_test_bug_base("https://bugs.webkit.org/"); registerGResource(); + GOwnPtr<char> diskCacheTempDirectory(g_dir_make_tmp("WebKit2TestsDiskCache-XXXXXX", 0)); + g_assert(diskCacheTempDirectory.get()); + webkit_web_context_set_disk_cache_directory(webkit_web_context_get_default(), diskCacheTempDirectory.get()); + beforeAll(); int returnValue = g_test_run(); afterAll(); + removeNonEmptyDirectory(diskCacheTempDirectory.get()); + return returnValue; } diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.h b/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.h index 6fe9de86d..02c90709c 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.h +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.h @@ -20,6 +20,7 @@ #ifndef TestMain_h #define TestMain_h +#include <cairo.h> #include <glib-object.h> #include <wtf/HashSet.h> #include <wtf/gobject/GOwnPtr.h> @@ -40,6 +41,12 @@ g_test_add(testPath.get(), ClassName, 0, ClassName::setUp, testFunc, ClassName::tearDown); \ } +#define ASSERT_CMP_CSTRING(s1, cmp, s2) \ + do { CString __s1 = (s1); CString __s2 = (s2); \ + if (g_strcmp0(__s1.data(), __s2.data()) cmp 0) ; else \ + g_assertion_message_cmpstr(G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \ + #s1 " " #cmp " " #s2, __s1.data(), #cmp, __s2.data()); } while (0) + class Test { public: MAKE_GLIB_TEST_FIXTURE(Test); @@ -95,6 +102,17 @@ public: g_log_set_always_fatal(static_cast<GLogLevelFlags>(fatalMask)); } + static bool cairoSurfacesEqual(cairo_surface_t* s1, cairo_surface_t* s2) + { + return (cairo_image_surface_get_format(s1) == cairo_image_surface_get_format(s2) + && cairo_image_surface_get_width(s1) == cairo_image_surface_get_width(s2) + && cairo_image_surface_get_height(s1) == cairo_image_surface_get_height(s2) + && cairo_image_surface_get_stride(s1) == cairo_image_surface_get_stride(s2) + && !memcmp(const_cast<const void*>(reinterpret_cast<void*>(cairo_image_surface_get_data(s1))), + const_cast<const void*>(reinterpret_cast<void*>(cairo_image_surface_get_data(s2))), + cairo_image_surface_get_height(s1)*cairo_image_surface_get_stride(s1))); + } + HashSet<GObject*> m_watchedObjects; }; diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp index 123831f76..72c2cfbbd 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp @@ -146,7 +146,7 @@ static void testPrintOperationPrint(PrintTest* test, gconstpointer) webkit_print_operation_print(test->m_printOperation.get()); test->waitUntilPrintFinished(); - GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(outputFile.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE","G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, + GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(outputFile.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE "," G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, static_cast<GFileQueryInfoFlags>(0), 0, 0)); g_assert(fileInfo.get()); g_assert_cmpint(g_file_info_get_size(fileInfo.get()), >, 0); diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp index 20b90b0b4..a24b6fdff 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp @@ -93,15 +93,27 @@ public: g_signal_connect(resource, "failed", G_CALLBACK(resourceFailedCallback), test); } + void clearSubresources() + { + g_list_free_full(m_subresources, reinterpret_cast<GDestroyNotify>(g_object_unref)); + m_subresources = 0; + } + ResourcesTest() : WebViewTest() , m_resourcesLoaded(0) , m_resourcesToLoad(0) , m_resourceDataSize(0) + , m_subresources(0) { g_signal_connect(m_webView, "resource-load-started", G_CALLBACK(resourceLoadStartedCallback), this); } + ~ResourcesTest() + { + clearSubresources(); + } + virtual void resourceLoadStarted(WebKitWebResource* resource, WebKitURIRequest* request) { } @@ -121,6 +133,8 @@ public: virtual void resourceFinished(WebKitWebResource* resource) { g_signal_handlers_disconnect_matched(resource, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); + if (webkit_web_view_get_main_resource(m_webView) != resource) + m_subresources = g_list_prepend(m_subresources, g_object_ref(resource)); if (++m_resourcesLoaded == m_resourcesToLoad) g_main_loop_quit(m_mainLoop); } @@ -134,9 +148,15 @@ public: { m_resourcesLoaded = 0; m_resourcesToLoad = resourcesCount; + clearSubresources(); g_main_loop_run(m_mainLoop); } + GList* subresources() + { + return m_subresources; + } + static void resourceGetDataCallback(GObject* object, GAsyncResult* result, gpointer userData) { size_t dataSize; @@ -177,13 +197,14 @@ public: size_t m_resourcesToLoad; GOwnPtr<char> m_resourceData; size_t m_resourceDataSize; + GList* m_subresources; }; static void testWebViewResources(ResourcesTest* test, gconstpointer) { // Nothing loaded yet, there shoulnd't be resources. g_assert(!webkit_web_view_get_main_resource(test->m_webView)); - g_assert(!webkit_web_view_get_subresources(test->m_webView)); + g_assert(!test->subresources()); // Load simple page without subresources. test->loadHtml("<html><body>Testing WebKitGTK+</body></html>", 0); @@ -191,7 +212,7 @@ static void testWebViewResources(ResourcesTest* test, gconstpointer) WebKitWebResource* resource = webkit_web_view_get_main_resource(test->m_webView); g_assert(resource); g_assert_cmpstr(webkit_web_view_get_uri(test->m_webView), ==, webkit_web_resource_get_uri(resource)); - g_assert(!webkit_web_view_get_subresources(test->m_webView)); + g_assert(!test->subresources()); // Load simple page with subresources. test->loadURI(kServer->getURIForPath("/").data()); @@ -200,9 +221,9 @@ static void testWebViewResources(ResourcesTest* test, gconstpointer) resource = webkit_web_view_get_main_resource(test->m_webView); g_assert(resource); g_assert_cmpstr(webkit_web_view_get_uri(test->m_webView), ==, webkit_web_resource_get_uri(resource)); - GOwnPtr<GList> subresources(webkit_web_view_get_subresources(test->m_webView)); + GList* subresources = test->subresources(); g_assert(subresources); - g_assert_cmpint(g_list_length(subresources.get()), ==, 3); + g_assert_cmpint(g_list_length(subresources), ==, 3); #if 0 // Load the same URI again. @@ -482,9 +503,7 @@ public: private: void checkActiveURI(const char* uri) { - // g_assert_cmpstr is a macro, so we need to cache the temporary string. - CString serverURI = kServer->getURIForPath(uri); - g_assert_cmpstr(m_activeURI.data(), ==, serverURI.data()); + ASSERT_CMP_CSTRING(m_activeURI, ==, kServer->getURIForPath(uri)); } }; @@ -505,8 +524,8 @@ static void testWebResourceGetData(ResourcesTest* test, gconstpointer) g_assert(resource); test->checkResourceData(resource); - GOwnPtr<GList> subresources(webkit_web_view_get_subresources(test->m_webView)); - for (GList* item = subresources.get(); item; item = g_list_next(item)) + GList* subresources = test->subresources(); + for (GList* item = subresources; item; item = g_list_next(item)) test->checkResourceData(WEBKIT_WEB_RESOURCE(item->data)); } @@ -539,6 +558,75 @@ static void testWebViewResourcesHistoryCache(SingleResourceLoadTest* test, gcons g_assert_cmpstr(webkit_web_resource_get_uri(resource), ==, simpleStyleCSSURI.data()); } +class SendRequestTest: public SingleResourceLoadTest { +public: + MAKE_GLIB_TEST_FIXTURE(SendRequestTest); + + void resourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) + { + if (resource != m_resource) + return; + + g_assert_cmpstr(webkit_uri_request_get_uri(request), ==, m_expectedNewResourceURI.data()); + g_assert_cmpstr(webkit_uri_request_get_uri(request), ==, webkit_web_resource_get_uri(resource)); + + SingleResourceLoadTest::resourceSentRequest(resource, request, redirectResponse); + } + + void resourceFailed(WebKitWebResource* resource, GError* error) + { + if (resource != m_resource) + return; + + g_assert_cmpstr(webkit_web_resource_get_uri(resource), ==, m_expectedCancelledResourceURI.data()); + g_assert_error(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED); + + SingleResourceLoadTest::resourceFailed(resource, error); + } + + void setExpectedNewResourceURI(const CString& uri) + { + m_expectedNewResourceURI = uri; + } + + void setExpectedCancelledResourceURI(const CString& uri) + { + m_expectedCancelledResourceURI = uri; + } + + CString m_expectedNewResourceURI; + CString m_expectedCancelledResourceURI; +}; + +static void testWebResourceSendRequest(SendRequestTest* test, gconstpointer) +{ + test->setExpectedNewResourceURI(kServer->getURIForPath("/javascript.js")); + test->loadURI(kServer->getURIForPath("relative-javascript.html").data()); + test->waitUntilResourceLoadFinished(); + g_assert(test->m_resource); + + Vector<SingleResourceLoadTest::LoadEvents>& events = test->m_loadEvents; + g_assert_cmpint(events.size(), ==, 5); + g_assert_cmpint(events[0], ==, SingleResourceLoadTest::Started); + g_assert_cmpint(events[1], ==, SingleResourceLoadTest::SentRequest); + g_assert_cmpint(events[2], ==, SingleResourceLoadTest::ReceivedResponse); + g_assert_cmpint(events[3], ==, SingleResourceLoadTest::ReceivedData); + g_assert_cmpint(events[4], ==, SingleResourceLoadTest::Finished); + events.clear(); + + // Cancel request. + test->setExpectedCancelledResourceURI(kServer->getURIForPath("/cancel-this.js")); + test->loadURI(kServer->getURIForPath("/resource-to-cancel.html").data()); + test->waitUntilResourceLoadFinished(); + g_assert(test->m_resource); + + g_assert_cmpint(events.size(), ==, 3); + g_assert_cmpint(events[0], ==, SingleResourceLoadTest::Started); + g_assert_cmpint(events[1], ==, SingleResourceLoadTest::Failed); + g_assert_cmpint(events[2], ==, SingleResourceLoadTest::Finished); + events.clear(); +} + static void addCacheHTTPHeadersToResponse(SoupMessage* message) { // The actual date doesn't really matter. @@ -592,6 +680,12 @@ static void serverCallback(SoupServer* server, SoupMessage* message, const char* soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, kJavascript, strlen(kJavascript)); soup_message_headers_append(message->response_headers, "Content-Type", "text/javascript"); soup_message_headers_append(message->response_headers, "Content-Disposition", "filename=JavaScript.js"); + } else if (g_str_equal(path, "/relative-javascript.html")) { + static const char* javascriptRelativeHTML = "<html><head><script language='javascript' src='remove-this/javascript.js'></script></head><body></body></html>"; + soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, javascriptRelativeHTML, strlen(javascriptRelativeHTML)); + } else if (g_str_equal(path, "/resource-to-cancel.html")) { + static const char* resourceToCancelHTML = "<html><head><script language='javascript' src='cancel-this.js'></script></head><body></body></html>"; + soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, resourceToCancelHTML, strlen(resourceToCancelHTML)); } else if (g_str_equal(path, "/blank.ico")) { GOwnPtr<char> filePath(g_build_filename(Test::getWebKit1TestResoucesDir().data(), path, NULL)); char* contents; @@ -622,6 +716,8 @@ void beforeAll() kServer = new WebKitTestServer(); kServer->run(serverCallback); + webkit_web_context_set_web_extensions_directory(webkit_web_context_get_default(), WEBKIT_TEST_WEB_EXTENSIONS_DIR); + ResourcesTest::add("WebKitWebView", "resources", testWebViewResources); SingleResourceLoadTest::add("WebKitWebResource", "loading", testWebResourceLoading); SingleResourceLoadTest::add("WebKitWebResource", "response", testWebResourceResponse); @@ -630,6 +726,7 @@ void beforeAll() ResourceURITrackingTest::add("WebKitWebResource", "active-uri", testWebResourceActiveURI); ResourcesTest::add("WebKitWebResource", "get-data", testWebResourceGetData); SingleResourceLoadTest::add("WebKitWebView", "history-cache", testWebViewResourcesHistoryCache); + SendRequestTest::add("WebKitWebPage", "send-request", testWebResourceSendRequest); } void afterAll() diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp index 8fa013dc4..db6ccc852 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp @@ -23,8 +23,11 @@ #include "WebKitTestServer.h" #include <gtk/gtk.h> -static WebKitTestServer* kServer; +static WebKitTestServer* kHttpsServer; +static WebKitTestServer* kHttpServer; + static const char* indexHTML = "<html><body>Testing WebKit2GTK+ SSL</body></htmll>"; +static const char* insecureContentHTML = "<html><script src=\"%s\"></script><body><p>Text + image <img src=\"%s\" align=\"right\"/></p></body></html>"; class SSLTest: public LoadTrackingTest { public: @@ -35,16 +38,18 @@ public: { } - virtual void loadCommitted() + virtual void provisionalLoadFailed(const gchar* failingURI, GError* error) { - WebKitWebResource* resource = webkit_web_view_get_main_resource(m_webView); - g_assert(resource); - WebKitURIResponse* response = webkit_web_resource_get_response(resource); - g_assert(response); + g_assert_error(error, SOUP_HTTP_ERROR, SOUP_STATUS_SSL_FAILED); + LoadTrackingTest::provisionalLoadFailed(failingURI, error); + } + virtual void loadCommitted() + { GTlsCertificate* certificate = 0; - webkit_uri_response_get_https_status(response, &certificate, &m_tlsErrors); + webkit_web_view_get_tls_info(m_webView, &certificate, &m_tlsErrors); m_certificate = certificate; + LoadTrackingTest::loadCommitted(); } void waitUntilLoadFinished() @@ -60,7 +65,7 @@ public: static void testSSL(SSLTest* test, gconstpointer) { - test->loadURI(kServer->getURIForPath("/").data()); + test->loadURI(kHttpsServer->getURIForPath("/").data()); test->waitUntilLoadFinished(); g_assert(test->m_certificate); // We always expect errors because we are using a self-signed certificate, @@ -75,7 +80,59 @@ static void testSSL(SSLTest* test, gconstpointer) g_assert(!test->m_tlsErrors); } -static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) +class InsecureContentTest: public WebViewTest { +public: + MAKE_GLIB_TEST_FIXTURE(InsecureContentTest); + + InsecureContentTest() + : m_insecureContentRun(false) + , m_insecureContentDisplayed(false) + { + g_signal_connect(m_webView, "insecure-content-detected", G_CALLBACK(insecureContentDetectedCallback), this); + } + + static void insecureContentDetectedCallback(WebKitWebView* webView, WebKitInsecureContentEvent event, InsecureContentTest* test) + { + g_assert(webView == test->m_webView); + + if (event == WEBKIT_INSECURE_CONTENT_RUN) + test->m_insecureContentRun = true; + + if (event == WEBKIT_INSECURE_CONTENT_DISPLAYED) + test->m_insecureContentDisplayed = true; + } + + bool m_insecureContentRun; + bool m_insecureContentDisplayed; +}; + +static void testInsecureContent(InsecureContentTest* test, gconstpointer) +{ + test->loadURI(kHttpsServer->getURIForPath("/insecure-content/").data()); + test->waitUntilLoadFinished(); + + g_assert(test->m_insecureContentRun); + g_assert(test->m_insecureContentDisplayed); +} + +static void testTLSErrorsPolicy(SSLTest* test, gconstpointer) +{ + WebKitWebContext* context = webkit_web_view_get_context(test->m_webView); + // TLS errors are ignored by default. + g_assert(webkit_web_context_get_tls_errors_policy(context) == WEBKIT_TLS_ERRORS_POLICY_IGNORE); + test->loadURI(kHttpsServer->getURIForPath("/").data()); + test->waitUntilLoadFinished(); + g_assert(!test->m_loadFailed); + + webkit_web_context_set_tls_errors_policy(context, WEBKIT_TLS_ERRORS_POLICY_FAIL); + test->loadURI(kHttpsServer->getURIForPath("/").data()); + test->waitUntilLoadFinished(); + g_assert(test->m_loadFailed); + g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed)); + g_assert(!test->m_loadEvents.contains(LoadTrackingTest::LoadCommitted)); +} + +static void httpsServerCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) { if (message->method != SOUP_METHOD_GET) { soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); @@ -86,19 +143,59 @@ static void serverCallback(SoupServer* server, SoupMessage* message, const char* soup_message_set_status(message, SOUP_STATUS_OK); soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, indexHTML, strlen(indexHTML)); soup_message_body_complete(message->response_body); + } else if (g_str_equal(path, "/insecure-content/")) { + GOwnPtr<char> responseHTML(g_strdup_printf(insecureContentHTML, kHttpServer->getURIForPath("/test-script").data(), kHttpServer->getURIForPath("/test-image").data())); + soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, responseHTML.get(), strlen(responseHTML.get())); + soup_message_set_status(message, SOUP_STATUS_OK); + soup_message_body_complete(message->response_body); + } else + soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); +} + +static void httpServerCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) +{ + if (message->method != SOUP_METHOD_GET) { + soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); + return; + } + + if (g_str_equal(path, "/test-script")) { + GOwnPtr<char> pathToFile(g_build_filename(Test::getResourcesDir().data(), "link-title.js", NULL)); + char* contents; + gsize length; + g_file_get_contents(pathToFile.get(), &contents, &length, 0); + + soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, contents, length); + soup_message_set_status(message, SOUP_STATUS_OK); + soup_message_body_complete(message->response_body); + } else if (g_str_equal(path, "/test-image")) { + GOwnPtr<char> pathToFile(g_build_filename(Test::getWebKit1TestResoucesDir().data(), "blank.ico", NULL)); + char* contents; + gsize length; + g_file_get_contents(pathToFile.get(), &contents, &length, 0); + + soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, contents, length); + soup_message_set_status(message, SOUP_STATUS_OK); + soup_message_body_complete(message->response_body); } else soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); } void beforeAll() { - kServer = new WebKitTestServer(WebKitTestServer::ServerHTTPS); - kServer->run(serverCallback); + kHttpsServer = new WebKitTestServer(WebKitTestServer::ServerHTTPS); + kHttpsServer->run(httpsServerCallback); + + kHttpServer = new WebKitTestServer(WebKitTestServer::ServerHTTP); + kHttpServer->run(httpServerCallback); SSLTest::add("WebKitWebView", "ssl", testSSL); + InsecureContentTest::add("WebKitWebView", "insecure-content", testInsecureContent); + SSLTest::add("WebKitWebContext", "tls-errors-policy", testTLSErrorsPolicy); } void afterAll() { - delete kServer; + delete kHttpsServer; + delete kHttpServer; } diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp new file mode 100644 index 000000000..527cc936c --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2,1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" + +#include "WebKitTestBus.h" +#include "WebViewTest.h" +#include <wtf/gobject/GRefPtr.h> + +static WebKitTestBus* bus; + +static void testWebExtensionGetTitle(WebViewTest* test, gconstpointer) +{ + test->loadHtml("<html><head><title>WebKitGTK+ Web Extensions Test</title></head><body></body></html>", 0); + test->waitUntilLoadFinished(); + + GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest", + "/org/webkit/gtk/WebExtensionTest" , "org.webkit.gtk.WebExtensionTest", test->m_mainLoop)); + GRefPtr<GVariant> result = adoptGRef(g_dbus_proxy_call_sync( + proxy.get(), + "GetTitle", + g_variant_new("(t)", webkit_web_view_get_page_id(test->m_webView)), + G_DBUS_CALL_FLAGS_NONE, + -1, 0, 0)); + g_assert(result); + + const char* title; + g_variant_get(result.get(), "(&s)", &title); + g_assert_cmpstr(title, ==, "WebKitGTK+ Web Extensions Test"); +} + +static void documentLoadedCallback(GDBusConnection*, const char*, const char*, const char*, const char*, GVariant*, WebViewTest* test) +{ + g_main_loop_quit(test->m_mainLoop); +} + +static void testDocumentLoadedSignal(WebViewTest* test, gconstpointer) +{ + GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest", + "/org/webkit/gtk/WebExtensionTest", "org.webkit.gtk.WebExtensionTest", test->m_mainLoop)); + GDBusConnection* connection = g_dbus_proxy_get_connection(proxy.get()); + guint id = g_dbus_connection_signal_subscribe(connection, + 0, + "org.webkit.gtk.WebExtensionTest", + "DocumentLoaded", + "/org/webkit/gtk/WebExtensionTest", + 0, + G_DBUS_SIGNAL_FLAGS_NONE, + reinterpret_cast<GDBusSignalCallback>(documentLoadedCallback), + test, + 0); + g_assert(id); + + test->loadHtml("<html><head><title>WebKitGTK+ Web Extensions Test</title></head><body></body></html>", 0); + g_main_loop_run(test->m_mainLoop); + g_dbus_connection_signal_unsubscribe(connection, id); +} + +static gboolean webProcessCrashedCallback(WebKitWebView*, WebViewTest* test) +{ + test->quitMainLoop(); + + return FALSE; +} + +static void testWebKitWebViewProcessCrashed(WebViewTest* test, gconstpointer) +{ + test->loadHtml("<html></html>", 0); + test->waitUntilLoadFinished(); + + g_signal_connect(test->m_webView, "web-process-crashed", + G_CALLBACK(webProcessCrashedCallback), test); + + GRefPtr<GDBusProxy> proxy = adoptGRef(bus->createProxy("org.webkit.gtk.WebExtensionTest", + "/org/webkit/gtk/WebExtensionTest", "org.webkit.gtk.WebExtensionTest", test->m_mainLoop)); + + GRefPtr<GVariant> result = adoptGRef(g_dbus_proxy_call_sync( + proxy.get(), + "AbortProcess", + 0, + G_DBUS_CALL_FLAGS_NONE, + -1, 0, 0)); + g_assert(!result); + g_main_loop_run(test->m_mainLoop); +} + +void beforeAll() +{ + webkit_web_context_set_web_extensions_directory(webkit_web_context_get_default(), WEBKIT_TEST_WEB_EXTENSIONS_DIR); + bus = new WebKitTestBus(); + if (!bus->run()) + return; + + WebViewTest::add("WebKitWebExtension", "dom-document-title", testWebExtensionGetTitle); + WebViewTest::add("WebKitWebExtension", "document-loaded-signal", testDocumentLoadedSignal); + WebViewTest::add("WebKitWebView", "web-process-crashed", testWebKitWebViewProcessCrashed); +} + +void afterAll() +{ + delete bus; +} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitAccessibility.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitAccessibility.cpp index 3db9094a5..d3750c005 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitAccessibility.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitAccessibility.cpp @@ -81,12 +81,7 @@ static gpointer testServerMonitorThreadFunc(gpointer) static void startTestServerMonitor() { kChildIsReady = false; - -#if (!GLIB_CHECK_VERSION(2, 31, 0)) - g_thread_create(testServerMonitorThreadFunc, 0, FALSE, 0); -#else g_thread_new("TestServerMonitor", testServerMonitorThreadFunc, 0); -#endif } static void startTestServer() diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp index ac13e4d07..1a06f7496 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp @@ -133,7 +133,7 @@ serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHash soup_message_body_complete(message->response_body); } -static void testNotInitialized(FaviconDatabaseTest* test, gconstpointer) +static void testNotInitialized(FaviconDatabaseTest* test) { // Try to retrieve a valid favicon from a not initialized database. test->getFaviconForPageURIAndWaitUntilReady(kServer->getURIForPath("/foo").data()); @@ -142,22 +142,22 @@ static void testNotInitialized(FaviconDatabaseTest* test, gconstpointer) g_assert_cmpint(test->m_error->code, ==, WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED); } -static void testSetDirectory(FaviconDatabaseTest* test, gconstpointer) +static void testSetDirectory(FaviconDatabaseTest* test) { webkit_web_context_set_favicon_database_directory(test->m_webContext, kTempDirectory); g_assert_cmpstr(kTempDirectory, ==, webkit_web_context_get_favicon_database_directory(test->m_webContext)); } -static void testClearDatabase(FaviconDatabaseTest* test, gconstpointer) +static void testClearDatabase(FaviconDatabaseTest* test) { WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(test->m_webContext); webkit_favicon_database_clear(database); - GOwnPtr<char> iconURI(webkit_favicon_database_get_favicon_uri(database, kServer->getURIForPath("/").data())); + GOwnPtr<char> iconURI(webkit_favicon_database_get_favicon_uri(database, kServer->getURIForPath("/foo").data())); g_assert(!iconURI); } -static void testGetFavicon(FaviconDatabaseTest* test, gconstpointer) +static void testGetFavicon(FaviconDatabaseTest* test) { // We need to load the page first to ensure the icon data will be // in the database in case there's an associated favicon. @@ -198,17 +198,19 @@ static void testGetFavicon(FaviconDatabaseTest* test, gconstpointer) g_assert(test->m_error); } -static void testGetFaviconURI(FaviconDatabaseTest* test, gconstpointer) +static void testGetFaviconURI(FaviconDatabaseTest* test) { WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(test->m_webContext); - const char* baseURI = kServer->getURIForPath("/foo").data(); - GOwnPtr<char> iconURI(webkit_favicon_database_get_favicon_uri(database, baseURI)); - g_assert_cmpstr(iconURI.get(), ==, kServer->getURIForPath("/icon/favicon.ico").data()); + CString baseURI = kServer->getURIForPath("/foo"); + GOwnPtr<char> iconURI(webkit_favicon_database_get_favicon_uri(database, baseURI.data())); + ASSERT_CMP_CSTRING(iconURI.get(), ==, kServer->getURIForPath("/icon/favicon.ico")); } -static void testWebViewFavicon(FaviconDatabaseTest* test, gconstpointer) +static void testWebViewFavicon(FaviconDatabaseTest* test) { + test->m_faviconURI = CString(); + cairo_surface_t* iconFromWebView = webkit_web_view_get_favicon(test->m_webView); g_assert(!iconFromWebView); @@ -225,6 +227,18 @@ static void testWebViewFavicon(FaviconDatabaseTest* test, gconstpointer) g_assert_cmpuint(cairo_image_surface_get_height(iconFromWebView), ==, 16); } +static void testFaviconDatabase(FaviconDatabaseTest* test, gconstpointer) +{ + // These tests depend on this order to run properly so we declare them in a single one. + // See https://bugs.webkit.org/show_bug.cgi?id=111434. + testNotInitialized(test); + testSetDirectory(test); + testGetFavicon(test); + testGetFaviconURI(test); + testWebViewFavicon(test); + testClearDatabase(test); +} + void beforeAll() { // Start a soup server for testing. @@ -235,12 +249,7 @@ void beforeAll() g_assert(kTempDirectory); // Add tests to the suite. - FaviconDatabaseTest::add("WebKitFaviconDatabase", "not-initialized", testNotInitialized); - FaviconDatabaseTest::add("WebKitFaviconDatabase", "set-directory", testSetDirectory); - FaviconDatabaseTest::add("WebKitFaviconDatabase", "get-favicon", testGetFavicon); - FaviconDatabaseTest::add("WebKitFaviconDatabase", "get-favicon-uri", testGetFaviconURI); - FaviconDatabaseTest::add("WebKitWebView", "favicon", testWebViewFavicon); - FaviconDatabaseTest::add("WebKitFaviconDatabase", "clear-database", testClearDatabase); + FaviconDatabaseTest::add("WebKitFaviconDatabase", "favicon-database-test", testFaviconDatabase); } static void webkitFaviconDatabaseFinalizedCallback(gpointer, GObject*) diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp index 90159b87f..d2eef4ca4 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp @@ -62,12 +62,6 @@ public: g_main_loop_run(m_mainLoop); } - void waitUntilWebViewDrawSignal() - { - g_signal_connect_after(m_webView, "draw", G_CALLBACK(webViewDraw), this); - g_main_loop_run(m_mainLoop); - } - GRefPtr<WebKitFindController> m_findController; bool m_textFound; unsigned m_matchCount; @@ -75,12 +69,6 @@ public: private: bool m_runFindUntilCompletion; - static void webViewDraw(GtkWidget *widget, cairo_t *cr, FindControllerTest* test) - { - g_main_loop_quit(test->m_mainLoop); - g_signal_handlers_disconnect_matched(widget, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, test); - } - static void foundTextCallback(WebKitFindController*, guint matchCount, FindControllerTest* test) { test->m_textFound = true; @@ -271,67 +259,38 @@ static void testFindControllerOptions(FindControllerTest* test, gconstpointer) g_assert(test->m_textFound); } -static gboolean gdkPixbufEqual(GdkPixbuf* firstPixbuf, GdkPixbuf* secondPixbuf) -{ - if (gdk_pixbuf_get_bits_per_sample(firstPixbuf) != gdk_pixbuf_get_bits_per_sample(secondPixbuf) - || gdk_pixbuf_get_has_alpha(firstPixbuf) != gdk_pixbuf_get_has_alpha(secondPixbuf) - || gdk_pixbuf_get_height(firstPixbuf) != gdk_pixbuf_get_height(secondPixbuf) - || gdk_pixbuf_get_n_channels(firstPixbuf) != gdk_pixbuf_get_n_channels(secondPixbuf) - || gdk_pixbuf_get_rowstride(firstPixbuf) != gdk_pixbuf_get_rowstride(secondPixbuf) - || gdk_pixbuf_get_width(firstPixbuf) != gdk_pixbuf_get_width(secondPixbuf)) - return FALSE; - - int pixbufRowstride = gdk_pixbuf_get_rowstride(firstPixbuf); - int pixbufHeight = gdk_pixbuf_get_height(firstPixbuf); - int pixbufWidth = gdk_pixbuf_get_width(firstPixbuf); - int numberOfChannels = gdk_pixbuf_get_n_channels(firstPixbuf); - int bitsPerSample = gdk_pixbuf_get_bits_per_sample(firstPixbuf); - - // Last row can be of different length. Taken from gdk-pixbuf documentation. - int totalLength = (pixbufHeight - 1) * pixbufRowstride \ - + pixbufWidth * ((numberOfChannels * bitsPerSample + 7) / 8); - - guchar* firstPixels = gdk_pixbuf_get_pixels(firstPixbuf); - guchar* secondPixels = gdk_pixbuf_get_pixels(secondPixbuf); - for (int i = 0; i < totalLength; i++) - if (firstPixels[i] != secondPixels[i]) - return FALSE; - - return TRUE; -} - static void testFindControllerHide(FindControllerTest* test, gconstpointer) { test->loadHtml(testString, 0); test->waitUntilLoadFinished(); test->showInWindowAndWaitUntilMapped(); - int allocatedHeight = gtk_widget_get_allocated_height(GTK_WIDGET(test->m_webView)); - int allocatedWidth = gtk_widget_get_allocated_width(GTK_WIDGET(test->m_webView)); - GdkWindow* webViewGdkWindow = gtk_widget_get_window(GTK_WIDGET(test->m_webView)); - g_assert(webViewGdkWindow); - test->waitUntilWebViewDrawSignal(); - GRefPtr<GdkPixbuf> originalPixbuf = adoptGRef(gdk_pixbuf_get_from_window(webViewGdkWindow, 0, 0, allocatedHeight, allocatedWidth)); - g_assert(originalPixbuf); + cairo_surface_t* originalSurface = cairo_surface_reference( + test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, WEBKIT_SNAPSHOT_OPTIONS_NONE)); + g_assert(originalSurface); test->find("testing", WEBKIT_FIND_OPTIONS_NONE, 1); test->waitUntilFindFinished(); g_assert(test->m_textFound); - test->waitUntilWebViewDrawSignal(); - GRefPtr<GdkPixbuf> highlightPixbuf = adoptGRef(gdk_pixbuf_get_from_window(webViewGdkWindow, 0, 0, allocatedHeight, allocatedWidth)); - g_assert(highlightPixbuf); - g_assert(!gdkPixbufEqual(originalPixbuf.get(), highlightPixbuf.get())); + cairo_surface_t* highlightSurface = cairo_surface_reference( + test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, WEBKIT_SNAPSHOT_OPTIONS_NONE)); + g_assert(highlightSurface); + g_assert(!Test::cairoSurfacesEqual(originalSurface, highlightSurface)); WebKitFindController* findController = webkit_web_view_get_find_controller(test->m_webView); webkit_find_controller_search_finish(findController); webkit_web_view_execute_editing_command(test->m_webView, "Unselect"); - test->waitUntilWebViewDrawSignal(); - GRefPtr<GdkPixbuf> unhighlightPixbuf = adoptGRef(gdk_pixbuf_get_from_window(webViewGdkWindow, 0, 0, allocatedHeight, allocatedWidth)); - g_assert(unhighlightPixbuf); - g_assert(gdkPixbufEqual(originalPixbuf.get(), unhighlightPixbuf.get())); + cairo_surface_t* unhighlightSurface = cairo_surface_reference( + test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, WEBKIT_SNAPSHOT_OPTIONS_NONE)); + g_assert(unhighlightSurface); + g_assert(Test::cairoSurfacesEqual(originalSurface, unhighlightSurface)); + + cairo_surface_destroy(originalSurface); + cairo_surface_destroy(highlightSurface); + cairo_surface_destroy(unhighlightSurface); } static void testFindControllerInstance(FindControllerTest* test, gconstpointer) diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp index c7a0dc259..1ee3843f9 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp @@ -248,6 +248,16 @@ static void testWebKitSettings(Test*, gconstpointer) webkit_settings_set_enable_smooth_scrolling(settings, TRUE); g_assert(webkit_settings_get_enable_smooth_scrolling(settings)); + // By default, accelerated 2D canvas is disabled. + g_assert(!webkit_settings_get_enable_accelerated_2d_canvas(settings)); + webkit_settings_set_enable_accelerated_2d_canvas(settings, TRUE); + g_assert(webkit_settings_get_enable_accelerated_2d_canvas(settings)); + + // By default, writing of console messages to stdout is disabled. + g_assert(!webkit_settings_get_enable_write_console_messages_to_stdout(settings)); + webkit_settings_set_enable_write_console_messages_to_stdout(settings, TRUE); + g_assert(webkit_settings_get_enable_write_console_messages_to_stdout(settings)); + g_object_unref(G_OBJECT(settings)); } @@ -274,7 +284,7 @@ static void assertThatUserAgentIsSentInHeaders(WebViewTest* test, const CString& { test->loadURI(gServer->getURIForPath("/").data()); test->waitUntilLoadFinished(); - g_assert_cmpstr(convertWebViewMainResourceDataToCString(test).data(), ==, userAgent.data()); + ASSERT_CMP_CSTRING(convertWebViewMainResourceDataToCString(test), ==, userAgent); } static void testWebKitSettingsUserAgent(WebViewTest* test, gconstpointer) @@ -300,12 +310,12 @@ static void testWebKitSettingsUserAgent(WebViewTest* test, gconstpointer) assertThatUserAgentIsSentInHeaders(test, funkyUserAgent); webkit_settings_set_user_agent_with_application_details(settings.get(), "WebKitGTK+", 0); - CString userAgentWithNullVersion = webkit_settings_get_user_agent(settings.get()); - g_assert_cmpstr(g_strstr_len(userAgentWithNullVersion.data(), -1, defaultUserAgent.data()), ==, userAgentWithNullVersion.data()); - g_assert(g_strstr_len(userAgentWithNullVersion.data(), -1, "WebKitGTK+")); + const char* userAgentWithNullVersion = webkit_settings_get_user_agent(settings.get()); + g_assert_cmpstr(g_strstr_len(userAgentWithNullVersion, -1, defaultUserAgent.data()), ==, userAgentWithNullVersion); + g_assert(g_strstr_len(userAgentWithNullVersion, -1, "WebKitGTK+")); webkit_settings_set_user_agent_with_application_details(settings.get(), "WebKitGTK+", ""); - g_assert_cmpstr(webkit_settings_get_user_agent(settings.get()), ==, userAgentWithNullVersion.data()); + g_assert_cmpstr(webkit_settings_get_user_agent(settings.get()), ==, userAgentWithNullVersion); webkit_settings_set_user_agent_with_application_details(settings.get(), "WebCatGTK+", "3.4.5"); const char* newUserAgent = webkit_settings_get_user_agent(settings.get()); diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp index 185c06cfe..54e44d682 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp @@ -114,6 +114,9 @@ static void testWebContextGetPlugins(PluginsTest* test, gconstpointer) static const char* kBarHTML = "<html><body>Bar</body></html>"; static const char* kEchoHTMLFormat = "<html><body>%s</body></html>"; +static const char* errorDomain = "test"; +static const int errorCode = 10; +static const char* errorMessage = "Error message."; class URISchemeTest: public LoadTrackingTest { public: @@ -122,22 +125,19 @@ public: struct URISchemeHandler { URISchemeHandler() : replyLength(0) - , replyWithPath(false) { } - URISchemeHandler(const char* reply, int replyLength, const char* mimeType, bool replyWithPath = false) + URISchemeHandler(const char* reply, int replyLength, const char* mimeType) : reply(reply) , replyLength(replyLength) , mimeType(mimeType) - , replyWithPath(replyWithPath) { } CString reply; int replyLength; CString mimeType; - bool replyWithPath; }; static void uriSchemeRequestCallback(WebKitURISchemeRequest* request, gpointer userData) @@ -151,22 +151,32 @@ public: GRefPtr<GInputStream> inputStream = adoptGRef(g_memory_input_stream_new()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inputStream.get())); - String scheme(String::fromUTF8(webkit_uri_scheme_request_get_scheme(request))); - g_assert(!scheme.isEmpty()); - g_assert(test->m_handlersMap.contains(scheme)); - const URISchemeHandler& handler = test->m_handlersMap.get(scheme); + const char* scheme = webkit_uri_scheme_request_get_scheme(request); + g_assert(scheme); + g_assert(test->m_handlersMap.contains(String::fromUTF8(scheme))); - if (handler.replyWithPath) { + if (!g_strcmp0(scheme, "error")) { + GOwnPtr<GError> error(g_error_new_literal(g_quark_from_string(errorDomain), errorCode, errorMessage)); + webkit_uri_scheme_request_finish_error(request, error.get()); + return; + } + + const URISchemeHandler& handler = test->m_handlersMap.get(String::fromUTF8(scheme)); + + if (!g_strcmp0(scheme, "echo")) { char* replyHTML = g_strdup_printf(handler.reply.data(), webkit_uri_scheme_request_get_path(request)); g_memory_input_stream_add_data(G_MEMORY_INPUT_STREAM(inputStream.get()), replyHTML, strlen(replyHTML), g_free); - } else if (!handler.reply.isNull()) + } else if (!g_strcmp0(scheme, "closed")) + g_input_stream_close(inputStream.get(), 0, 0); + else if (!handler.reply.isNull()) g_memory_input_stream_add_data(G_MEMORY_INPUT_STREAM(inputStream.get()), handler.reply.data(), handler.reply.length(), 0); + webkit_uri_scheme_request_finish(request, inputStream.get(), handler.replyLength, handler.mimeType.data()); } - void registerURISchemeHandler(const char* scheme, const char* reply, int replyLength, const char* mimeType, bool replyWithPath = false) + void registerURISchemeHandler(const char* scheme, const char* reply, int replyLength, const char* mimeType) { - m_handlersMap.set(String::fromUTF8(scheme), URISchemeHandler(reply, replyLength, mimeType, replyWithPath)); + m_handlersMap.set(String::fromUTF8(scheme), URISchemeHandler(reply, replyLength, mimeType)); webkit_web_context_register_uri_scheme(webkit_web_context_get_default(), scheme, uriSchemeRequestCallback, this, 0); } @@ -184,7 +194,7 @@ static void testWebContextURIScheme(URISchemeTest* test, gconstpointer) g_assert_cmpint(mainResourceDataSize, ==, strlen(kBarHTML)); g_assert(!strncmp(mainResourceData, kBarHTML, mainResourceDataSize)); - test->registerURISchemeHandler("echo", kEchoHTMLFormat, -1, "text/html", true); + test->registerURISchemeHandler("echo", kEchoHTMLFormat, -1, "text/html"); test->loadURI("echo:hello world"); test->waitUntilLoadFinished(); GOwnPtr<char> echoHTML(g_strdup_printf(kEchoHTMLFormat, webkit_uri_scheme_request_get_path(test->m_uriSchemeRequest.get()))); @@ -205,6 +215,23 @@ static void testWebContextURIScheme(URISchemeTest* test, gconstpointer) test->waitUntilLoadFinished(); g_assert(!test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed)); g_assert(!test->m_loadEvents.contains(LoadTrackingTest::LoadFailed)); + + test->registerURISchemeHandler("error", 0, 0, 0); + test->m_loadEvents.clear(); + test->loadURI("error:error"); + test->waitUntilLoadFinished(); + g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed)); + g_assert(test->m_loadFailed); + g_assert_error(test->m_error.get(), g_quark_from_string(errorDomain), errorCode); + g_assert_cmpstr(test->m_error->message, ==, errorMessage); + + test->registerURISchemeHandler("closed", 0, 0, 0); + test->m_loadEvents.clear(); + test->loadURI("closed:input-stream"); + test->waitUntilLoadFinished(); + g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed)); + g_assert(test->m_loadFailed); + g_assert_error(test->m_error.get(), G_IO_ERROR, G_IO_ERROR_CLOSED); } static void testWebContextSpellChecker(Test* test, gconstpointer) diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp index 08cdbe82a..88d77f286 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp @@ -48,12 +48,10 @@ static void testWebViewCustomCharset(WebViewTest* test, gconstpointer) static void testWebViewSettings(WebViewTest* test, gconstpointer) { WebKitSettings* defaultSettings = webkit_web_view_get_settings(test->m_webView); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(defaultSettings)); g_assert(defaultSettings); g_assert(webkit_settings_get_enable_javascript(defaultSettings)); GRefPtr<WebKitSettings> newSettings = adoptGRef(webkit_settings_new()); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(newSettings.get())); g_object_set(G_OBJECT(newSettings.get()), "enable-javascript", FALSE, NULL); webkit_web_view_set_settings(test->m_webView, newSettings.get()); @@ -67,7 +65,6 @@ static void testWebViewSettings(WebViewTest* test, gconstpointer) g_assert(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(webView2.get())) == settings); GRefPtr<WebKitSettings> newSettings2 = adoptGRef(webkit_settings_new()); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(newSettings2.get())); webkit_web_view_set_settings(WEBKIT_WEB_VIEW(webView2.get()), newSettings2.get()); settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(webView2.get())); g_assert(settings == newSettings2.get()); @@ -479,8 +476,9 @@ static void testWebViewMouseTarget(UIClientTest* test, gconstpointer) " <a style='position:absolute; left:1; top:1' href='http://www.webkitgtk.org' title='WebKitGTK+ Title'>WebKitGTK+ Website</a>" " <img style='position:absolute; left:1; top:10' src='0xdeadbeef' width=5 height=5></img>" " <a style='position:absolute; left:1; top:20' href='http://www.webkitgtk.org/logo' title='WebKitGTK+ Logo'><img src='0xdeadbeef' width=5 height=5></img></a>" - " <video style='position:absolute; left:1; top:30' width=10 height=10 controls='controls'><source src='movie.ogg' type='video/ogg' /></video>" - " <input style='position:absolute; left:1; top:50' size='10'></input>" + " <input style='position:absolute; left:1; top:30' size='10'></input>" + " <div style='position:absolute; left:1; top:50; width:30; height:30; overflow:scroll'> </div>" + " <video style='position:absolute; left:1; top:100' width='300' height='300' controls='controls' preload='none'><source src='movie.ogg' type='video/ogg' /></video>" "</body></html>"; test->loadHtml(linksHoveredHTML, "file:///"); @@ -511,6 +509,7 @@ static void testWebViewMouseTarget(UIClientTest* test, gconstpointer) g_assert(webkit_hit_test_result_context_is_image(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_media(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_editable(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_scrollbar(hitTestResult)); g_assert_cmpstr(webkit_hit_test_result_get_image_uri(hitTestResult), ==, "file:///0xdeadbeef"); g_assert(test->m_mouseTargetModifiers & GDK_CONTROL_MASK); @@ -520,6 +519,7 @@ static void testWebViewMouseTarget(UIClientTest* test, gconstpointer) g_assert(webkit_hit_test_result_context_is_image(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_media(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_editable(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_scrollbar(hitTestResult)); g_assert_cmpstr(webkit_hit_test_result_get_link_uri(hitTestResult), ==, "http://www.webkitgtk.org/logo"); g_assert_cmpstr(webkit_hit_test_result_get_image_uri(hitTestResult), ==, "file:///0xdeadbeef"); g_assert_cmpstr(webkit_hit_test_result_get_link_title(hitTestResult), ==, "WebKitGTK+ Logo"); @@ -527,21 +527,32 @@ static void testWebViewMouseTarget(UIClientTest* test, gconstpointer) g_assert(!test->m_mouseTargetModifiers); // Move over media. - hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(1, 30); + hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(1, 100); g_assert(!webkit_hit_test_result_context_is_link(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_image(hitTestResult)); g_assert(webkit_hit_test_result_context_is_media(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_editable(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_scrollbar(hitTestResult)); g_assert_cmpstr(webkit_hit_test_result_get_media_uri(hitTestResult), ==, "file:///movie.ogg"); g_assert(!test->m_mouseTargetModifiers); // Mover over input. - hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(5, 55); + hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(5, 35); g_assert(!webkit_hit_test_result_context_is_link(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_image(hitTestResult)); g_assert(!webkit_hit_test_result_context_is_media(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_scrollbar(hitTestResult)); g_assert(webkit_hit_test_result_context_is_editable(hitTestResult)); g_assert(!test->m_mouseTargetModifiers); + + // Move over scrollbar. + hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(5, 75); + g_assert(!webkit_hit_test_result_context_is_link(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_image(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_media(hitTestResult)); + g_assert(!webkit_hit_test_result_context_is_editable(hitTestResult)); + g_assert(webkit_hit_test_result_context_is_scrollbar(hitTestResult)); + g_assert(!test->m_mouseTargetModifiers); } static void testWebViewPermissionRequests(UIClientTest* test, gconstpointer) @@ -1050,6 +1061,174 @@ static void testWebViewSave(SaveWebViewTest* test, gconstpointer) g_assert_cmpint(g_file_info_get_size(fileInfo.get()), ==, totalBytesFromStream); } +static void testWebViewMode(WebViewTest* test, gconstpointer) +{ + static const char* indexHTML = "<html><body><p>Test Web View Mode</p></body></html>"; + + // Web mode. + g_assert_cmpuint(webkit_web_view_get_view_mode(test->m_webView), ==, WEBKIT_VIEW_MODE_WEB); + test->loadHtml(indexHTML, 0); + test->waitUntilLoadFinished(); + WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished("window.document.body.textContent;", 0); + GOwnPtr<char> valueString(WebViewTest::javascriptResultToCString(javascriptResult)); + g_assert_cmpstr(valueString.get(), ==, "Test Web View Mode"); + + // Source mode. + webkit_web_view_set_view_mode(test->m_webView, WEBKIT_VIEW_MODE_SOURCE); + test->loadHtml(indexHTML, 0); + test->waitUntilLoadFinished(); + javascriptResult = test->runJavaScriptAndWaitUntilFinished("window.document.body.textContent;", 0); + valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); + g_assert_cmpstr(valueString.get(), ==, indexHTML); +} + +// To test page visibility API. Currently only 'visible' and 'hidden' states are implemented fully in WebCore. +// See also http://www.w3.org/TR/2011/WD-page-visibility-20110602/ and https://developers.google.com/chrome/whitepapers/pagevisibility +static void testWebViewPageVisibility(WebViewTest* test, gconstpointer) +{ + test->loadHtml("<html><title></title>" + "<body><p>Test Web Page Visibility</p>" + "<script>" + "document.addEventListener(\"webkitvisibilitychange\", onVisibilityChange, false);" + "function onVisibilityChange() {" + " document.title = document.webkitVisibilityState;" + "}" + "</script>" + "</body></html>", + 0); + + // Wait untill the page is loaded. Initial visibility should be 'hidden'. + test->waitUntilLoadFinished(); + + GOwnPtr<GError> error; + WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished("document.webkitVisibilityState;", &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + GOwnPtr<char> valueString(WebViewTest::javascriptResultToCString(javascriptResult)); + g_assert_cmpstr(valueString.get(), ==, "hidden"); + + javascriptResult = test->runJavaScriptAndWaitUntilFinished("document.webkitHidden;", &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + g_assert(WebViewTest::javascriptResultToBoolean(javascriptResult)); + + // Show the page. The visibility should be updated to 'visible'. + test->showInWindow(); + test->waitUntilTitleChanged(); + + javascriptResult = test->runJavaScriptAndWaitUntilFinished("document.webkitVisibilityState;", &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); + g_assert_cmpstr(valueString.get(), ==, "visible"); + + javascriptResult = test->runJavaScriptAndWaitUntilFinished("document.webkitHidden;", &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + g_assert(!WebViewTest::javascriptResultToBoolean(javascriptResult)); + + // Hide the page. The visibility should be updated to 'hidden'. + gtk_widget_hide(GTK_WIDGET(test->m_webView)); + test->waitUntilTitleChanged(); + + javascriptResult = test->runJavaScriptAndWaitUntilFinished("document.webkitVisibilityState;", &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); + g_assert_cmpstr(valueString.get(), ==, "hidden"); + + javascriptResult = test->runJavaScriptAndWaitUntilFinished("document.webkitHidden;", &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + g_assert(WebViewTest::javascriptResultToBoolean(javascriptResult)); +} + +class SnapshotWebViewTest: public WebViewTest { +public: + MAKE_GLIB_TEST_FIXTURE(SnapshotWebViewTest); + + static void onSnapshotCancelledReady(WebKitWebView* web_view, GAsyncResult* res, SnapshotWebViewTest* test) + { + GOwnPtr<GError> error; + test->m_surface = webkit_web_view_get_snapshot_finish(web_view, res, &error.outPtr()); + g_assert(!test->m_surface); + g_assert_error(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED); + test->quitMainLoop(); + } + + gboolean getSnapshotAndCancel() + { + if (m_surface) + cairo_surface_destroy(m_surface); + m_surface = 0; + GRefPtr<GCancellable> cancellable = adoptGRef(g_cancellable_new()); + webkit_web_view_get_snapshot(m_webView, WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE, cancellable.get(), reinterpret_cast<GAsyncReadyCallback>(onSnapshotCancelledReady), this); + g_cancellable_cancel(cancellable.get()); + g_main_loop_run(m_mainLoop); + + return true; + } + +}; + +static void testWebViewSnapshot(SnapshotWebViewTest* test, gconstpointer) +{ + test->loadHtml("<html><body><p>Whatever</p></body></html>", 0); + test->waitUntilLoadFinished(); + + // WebView not visible. + cairo_surface_t* surface1 = test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE); + g_assert(!surface1); + + // Show surface, resize to 50x50, try again. + test->showInWindowAndWaitUntilMapped(); + test->resizeView(50, 50); + surface1 = test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE); + g_assert(surface1); + + // obtained surface should be at the most 50x50. Store the size + // for comparison later. + int width = cairo_image_surface_get_width(surface1); + int height = cairo_image_surface_get_height(surface1); + g_assert_cmpint(width, <=, 50); + g_assert_cmpint(height, <=, 50); + + // Select all text in the WebView, request a snapshot ignoring selection. + test->selectAll(); + surface1 = cairo_surface_reference(test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE)); + g_assert(surface1); + g_assert_cmpint(cairo_image_surface_get_width(surface1), ==, width); + g_assert_cmpint(cairo_image_surface_get_height(surface1), ==, height); + + // Create identical surface. + cairo_surface_t* surface2 = test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE); + g_assert(surface2); + + // Compare these two, they should be identical. + g_assert(Test::cairoSurfacesEqual(surface1, surface2)); + + // Request a new snapshot, including the selection this time. The + // size should be the same but the result must be different to the + // one previously obtained. + surface2 = test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_INCLUDE_SELECTION_HIGHLIGHTING); + g_assert(surface2); + g_assert_cmpint(cairo_image_surface_get_width(surface2), ==, width); + g_assert_cmpint(cairo_image_surface_get_height(surface2), ==, height); + g_assert(!Test::cairoSurfacesEqual(surface1, surface2)); + + // Request a snapshot of the whole document in the WebView. The + // result should be different from the size obtained previously. + surface2 = test->getSnapshotAndWaitUntilReady(WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, WEBKIT_SNAPSHOT_OPTIONS_NONE); + g_assert(surface2); + g_assert_cmpint(cairo_image_surface_get_width(surface2), >, width); + g_assert_cmpint(cairo_image_surface_get_height(surface2), >, height); + g_assert(!Test::cairoSurfacesEqual(surface1, surface2)); + + cairo_surface_destroy(surface1); + + g_assert(test->getSnapshotAndCancel()); +} + void beforeAll() { WebViewTest::add("WebKitWebView", "default-context", testWebViewDefaultContext); @@ -1069,6 +1248,9 @@ void beforeAll() WebViewTest::add("WebKitWebView", "can-show-mime-type", testWebViewCanShowMIMEType); FormClientTest::add("WebKitWebView", "submit-form", testWebViewSubmitForm); SaveWebViewTest::add("WebKitWebView", "save", testWebViewSave); + WebViewTest::add("WebKitWebView", "view-mode", testWebViewMode); + SnapshotWebViewTest::add("WebKitWebView", "snapshot", testWebViewSnapshot); + WebViewTest::add("WebKitWebView", "page-visibility", testWebViewPageVisibility); } void afterAll() diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebViewGroup.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebViewGroup.cpp new file mode 100644 index 000000000..026c5c5b9 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebViewGroup.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2013 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2,1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" + +#include "WebKitTestServer.h" +#include "WebViewTest.h" +#include <cstdarg> +#include <gtk/gtk.h> +#include <webkit2/webkit2.h> +#include <wtf/gobject/GRefPtr.h> + +static WebKitTestServer* kServer; + +// These are all here so that they can be changed easily, if necessary. +static const char* kStyleSheetHTML = "<html><div id=\"styledElement\">Sweet stylez!</div></html>"; +static const char* kInjectedStyleSheet = "#styledElement { font-weight: bold; }"; +static const char* kStyleSheetTestScript = "getComputedStyle(document.getElementById('styledElement'))['font-weight']"; +static const char* kStyleSheetTestScriptResult = "bold"; + +static void testWebViewGroupDefault(Test* test, gconstpointer) +{ + // Default group is shared by all WebViews by default. + GRefPtr<WebKitWebView> webView1 = WEBKIT_WEB_VIEW(webkit_web_view_new()); + GRefPtr<WebKitWebView> webView2 = WEBKIT_WEB_VIEW(webkit_web_view_new()); + g_assert(webkit_web_view_get_group(webView1.get()) == webkit_web_view_get_group(webView2.get())); + + // Settings are shared by all web view in the same group. + g_assert(webkit_web_view_get_settings(webView1.get()) == webkit_web_view_get_settings(webView2.get())); + g_assert(webkit_web_view_get_settings(webView1.get()) == webkit_web_view_group_get_settings(webkit_web_view_get_group(webView2.get()))); +} + +static void testWebViewGroupNewGroup(Test* test, gconstpointer) +{ + // Passing 0 as group name generates the name automatically. + GRefPtr<WebKitWebViewGroup> viewGroup1 = adoptGRef(webkit_web_view_group_new(0)); + test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(viewGroup1.get())); + g_assert(webkit_web_view_group_get_name(viewGroup1.get())); + + // New group with a given name. + GRefPtr<WebKitWebViewGroup> viewGroup2 = adoptGRef(webkit_web_view_group_new("TestGroup2")); + test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(viewGroup2.get())); + g_assert_cmpstr(webkit_web_view_group_get_name(viewGroup2.get()), ==, "TestGroup2"); + g_assert_cmpstr(webkit_web_view_group_get_name(viewGroup2.get()), !=, webkit_web_view_group_get_name(viewGroup1.get())); + + // Every group has its own settings. + g_assert(webkit_web_view_group_get_settings(viewGroup1.get()) != webkit_web_view_group_get_settings(viewGroup2.get())); +} + +static void testWebViewNewWithGroup(Test* test, gconstpointer) +{ + GRefPtr<WebKitWebViewGroup> viewGroup1 = adoptGRef(webkit_web_view_group_new("TestGroup1")); + test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(viewGroup1.get())); + GRefPtr<WebKitWebView> webView1 = WEBKIT_WEB_VIEW(webkit_web_view_new_with_group(viewGroup1.get())); + g_assert(webkit_web_view_get_group(webView1.get()) == viewGroup1.get()); + + GRefPtr<WebKitWebView> webView2 = WEBKIT_WEB_VIEW(webkit_web_view_new()); + g_assert(webkit_web_view_get_group(webView2.get()) != viewGroup1.get()); + + // Settings should be different for views in different groups. + g_assert(webkit_web_view_get_settings(webView1.get()) != webkit_web_view_get_settings(webView2.get())); +} + +static void testWebViewGroupSettings(Test* test, gconstpointer) +{ + GRefPtr<WebKitWebViewGroup> viewGroup1 = adoptGRef(webkit_web_view_group_new("TestGroup1")); + test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(viewGroup1.get())); + GRefPtr<WebKitSettings> newSettings = adoptGRef(webkit_settings_new_with_settings("enable-javascript", FALSE, NULL)); + test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(newSettings.get())); + webkit_web_view_group_set_settings(viewGroup1.get(), newSettings.get()); + g_assert(webkit_web_view_group_get_settings(viewGroup1.get()) == newSettings.get()); + + GRefPtr<WebKitWebView> webView1 = WEBKIT_WEB_VIEW(webkit_web_view_new_with_group(viewGroup1.get())); + GRefPtr<WebKitWebView> webView2 = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebKitSettings* webView1Settings = webkit_web_view_get_settings(webView1.get()); + WebKitSettings* webView2Settings = webkit_web_view_get_settings(webView2.get()); + g_assert(webView1Settings != webView2Settings); + g_assert(webkit_settings_get_enable_javascript(webView1Settings) != webkit_settings_get_enable_javascript(webView2Settings)); + + webkit_web_view_set_settings(webView1.get(), webView2Settings); + g_assert(webkit_web_view_get_settings(webView1.get()) == webView2Settings); + g_assert(webkit_web_view_group_get_settings(webkit_web_view_get_group(webView1.get())) == webView2Settings); +} + +static bool isStyleSheetInjectedForURLAtPath(WebViewTest* test, const char* path) +{ + test->loadURI(kServer->getURIForPath(path).data()); + test->waitUntilLoadFinished(); + + GOwnPtr<GError> error; + WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished(kStyleSheetTestScript, &error.outPtr()); + g_assert(javascriptResult); + g_assert(!error.get()); + + GOwnPtr<char> resultString(WebViewTest::javascriptResultToCString(javascriptResult)); + return !g_strcmp0(resultString.get(), kStyleSheetTestScriptResult); +} + +static void fillURLListFromPaths(char** list, const char* path, ...) +{ + va_list argumentList; + va_start(argumentList, path); + + int i = 0; + while (path) { + // FIXME: We must use a wildcard for the host here until http://wkbug.com/112476 is fixed. + // Until that time patterns with port numbers in them will not properly match URLs with port numbers. + list[i++] = g_strdup_printf("http://*/%s*", path); + path = va_arg(argumentList, const char*); + } +} + +static void removeOldInjectedStyleSheetsAndResetLists(WebKitWebViewGroup* group, char** whitelist, char** blacklist) +{ + webkit_web_view_group_remove_all_user_style_sheets(group); + + while (*whitelist) { + g_free(*whitelist); + *whitelist = 0; + whitelist++; + } + + while (*blacklist) { + g_free(*blacklist); + *blacklist = 0; + blacklist++; + } +} + +static void testWebViewGroupInjectedStyleSheet(WebViewTest* test, gconstpointer) +{ + WebKitWebViewGroup* group = webkit_web_view_get_group(test->m_webView); + char* whitelist[3] = { 0, 0, 0 }; + char* blacklist[3] = { 0, 0, 0 }; + + removeOldInjectedStyleSheetsAndResetLists(group, whitelist, blacklist); + + // Without a whitelist or a blacklist all URLs should have the injected style sheet. + static const char* randomPath = "somerandompath"; + g_assert(!isStyleSheetInjectedForURLAtPath(test, randomPath)); + webkit_web_view_group_add_user_style_sheet(group, kInjectedStyleSheet, 0, 0, 0, WEBKIT_INJECTED_CONTENT_FRAMES_ALL); + g_assert(isStyleSheetInjectedForURLAtPath(test, randomPath)); + + removeOldInjectedStyleSheetsAndResetLists(group, whitelist, blacklist); + + fillURLListFromPaths(blacklist, randomPath, 0); + webkit_web_view_group_add_user_style_sheet(group, kInjectedStyleSheet, 0, 0, blacklist, WEBKIT_INJECTED_CONTENT_FRAMES_ALL); + g_assert(!isStyleSheetInjectedForURLAtPath(test, randomPath)); + g_assert(isStyleSheetInjectedForURLAtPath(test, "someotherrandompath")); + + removeOldInjectedStyleSheetsAndResetLists(group, whitelist, blacklist); + + static const char* inTheWhiteList = "inthewhitelist"; + static const char* notInWhitelist = "notinthewhitelist"; + static const char* inTheWhiteListAndBlackList = "inthewhitelistandblacklist"; + + fillURLListFromPaths(whitelist, inTheWhiteList, inTheWhiteListAndBlackList, 0); + fillURLListFromPaths(blacklist, inTheWhiteListAndBlackList, 0); + webkit_web_view_group_add_user_style_sheet(group, kInjectedStyleSheet, 0, whitelist, blacklist, WEBKIT_INJECTED_CONTENT_FRAMES_ALL); + g_assert(isStyleSheetInjectedForURLAtPath(test, inTheWhiteList)); + g_assert(!isStyleSheetInjectedForURLAtPath(test, inTheWhiteListAndBlackList)); + g_assert(!isStyleSheetInjectedForURLAtPath(test, notInWhitelist)); + + // It's important to clean up the environment before other tests. + removeOldInjectedStyleSheetsAndResetLists(group, whitelist, blacklist); +} + +static void serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable*, SoupClientContext*, gpointer) +{ + soup_message_set_status(message, SOUP_STATUS_OK); + soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, kStyleSheetHTML, strlen(kStyleSheetHTML)); + soup_message_body_complete(message->response_body); +} + +void beforeAll() +{ + kServer = new WebKitTestServer(); + kServer->run(serverCallback); + + Test::add("WebKitWebViewGroup", "default-group", testWebViewGroupDefault); + Test::add("WebKitWebViewGroup", "new-group", testWebViewGroupNewGroup); + Test::add("WebKitWebView", "new-with-group", testWebViewNewWithGroup); + Test::add("WebKitWebViewGroup", "settings", testWebViewGroupSettings); + WebViewTest::add("WebKitWebViewGroup", "injected-style-sheet", testWebViewGroupInjectedStyleSheet); +} + +void afterAll() +{ + delete kServer; +} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp new file mode 100644 index 000000000..692663e33 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" + +#include <gio/gio.h> +#include <stdlib.h> +#include <string.h> + +#include <webkit2/webkit-web-extension.h> +#include <wtf/gobject/GOwnPtr.h> + +static const char introspectionXML[] = + "<node>" + " <interface name='org.webkit.gtk.WebExtensionTest'>" + " <method name='GetTitle'>" + " <arg type='t' name='pageID' direction='in'/>" + " <arg type='s' name='title' direction='out'/>" + " </method>" + " <method name='AbortProcess'>" + " </method>" + " <signal name='DocumentLoaded'/>" + " <signal name='URIChanged'>" + " <arg type='s' name='uri' direction='out'/>" + " </signal>" + " </interface>" + "</node>"; + +static void documentLoadedCallback(WebKitWebPage*, gpointer userData) +{ + bool ok = g_dbus_connection_emit_signal(G_DBUS_CONNECTION(userData), + 0, + "/org/webkit/gtk/WebExtensionTest", + "org.webkit.gtk.WebExtensionTest", + "DocumentLoaded", + 0, + 0); + g_assert(ok); +} + +static void uriChangedCallback(WebKitWebPage* webPage, GParamSpec* pspec, gpointer userData) +{ + bool ok = g_dbus_connection_emit_signal( + G_DBUS_CONNECTION(userData), + 0, + "/org/webkit/gtk/WebExtensionTest", + "org.webkit.gtk.WebExtensionTest", + "URIChanged", + g_variant_new("(s)", webkit_web_page_get_uri(webPage)), + 0); + g_assert(ok); +} + +static gboolean sendRequestCallback(WebKitWebPage*, WebKitURIRequest* request, WebKitURIResponse*, gpointer) +{ + const char* requestURI = webkit_uri_request_get_uri(request); + g_assert(requestURI); + + if (const char* suffix = g_strrstr(requestURI, "/remove-this/javascript.js")) { + GOwnPtr<char> prefix(g_strndup(requestURI, strlen(requestURI) - strlen(suffix))); + GOwnPtr<char> newURI(g_strdup_printf("%s/javascript.js", prefix.get())); + webkit_uri_request_set_uri(request, newURI.get()); + } else if (g_str_has_suffix(requestURI, "/add-do-not-track-header")) { + SoupMessageHeaders* headers = webkit_uri_request_get_http_headers(request); + g_assert(headers); + soup_message_headers_append(headers, "DNT", "1"); + } else if (g_str_has_suffix(requestURI, "/cancel-this.js")) + return TRUE; + + return FALSE; +} + +static void pageCreatedCallback(WebKitWebExtension*, WebKitWebPage* webPage, gpointer userData) +{ + g_signal_connect(webPage, "document-loaded", G_CALLBACK(documentLoadedCallback), userData); + g_signal_connect(webPage, "notify::uri", G_CALLBACK(uriChangedCallback), userData); + g_signal_connect(webPage, "send-request", G_CALLBACK(sendRequestCallback), 0); +} + +static void methodCallCallback(GDBusConnection* connection, const char* sender, const char* objectPath, const char* interfaceName, const char* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData) +{ + if (g_strcmp0(interfaceName, "org.webkit.gtk.WebExtensionTest")) + return; + + if (!g_strcmp0(methodName, "GetTitle")) { + uint64_t pageID; + g_variant_get(parameters, "(t)", &pageID); + + WebKitWebExtension* extension = WEBKIT_WEB_EXTENSION(userData); + WebKitWebPage* page = webkit_web_extension_get_page(extension, pageID); + if (!page) { + g_dbus_method_invocation_return_error( + invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, + "Invalid page ID: %" G_GUINT64_FORMAT, pageID); + return; + } + g_assert_cmpuint(webkit_web_page_get_id(page), ==, pageID); + + WebKitDOMDocument* document = webkit_web_page_get_dom_document(page); + GOwnPtr<char> title(webkit_dom_document_get_title(document)); + g_dbus_method_invocation_return_value(invocation, g_variant_new("(s)", title.get())); + } else if (!g_strcmp0(methodName, "AbortProcess")) { + abort(); + } +} + +static const GDBusInterfaceVTable interfaceVirtualTable = { + methodCallCallback, 0, 0, { 0, } +}; + +static void busAcquiredCallback(GDBusConnection* connection, const char* name, gpointer userData) +{ + static GDBusNodeInfo *introspectionData = 0; + if (!introspectionData) + introspectionData = g_dbus_node_info_new_for_xml(introspectionXML, 0); + + GOwnPtr<GError> error; + unsigned registrationID = g_dbus_connection_register_object( + connection, + "/org/webkit/gtk/WebExtensionTest", + introspectionData->interfaces[0], + &interfaceVirtualTable, + g_object_ref(userData), + static_cast<GDestroyNotify>(g_object_unref), + &error.outPtr()); + if (!registrationID) + g_warning("Failed to register object: %s\n", error->message); + + g_signal_connect(WEBKIT_WEB_EXTENSION(userData), "page-created", G_CALLBACK(pageCreatedCallback), connection); +} + +extern "C" void webkit_web_extension_initialize(WebKitWebExtension* extension) +{ + g_bus_own_name( + G_BUS_TYPE_SESSION, + "org.webkit.gtk.WebExtensionTest", + G_BUS_NAME_OWNER_FLAGS_NONE, + busAcquiredCallback, + 0, 0, + g_object_ref(extension), + static_cast<GDestroyNotify>(g_object_unref)); +} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.cpp new file mode 100644 index 000000000..8c2d3f638 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "WebKitTestBus.h" + +#include <wtf/gobject/GOwnPtr.h> +#include <wtf/text/WTFString.h> + +WebKitTestBus::WebKitTestBus() + : m_pid(-1) +{ +} + +bool WebKitTestBus::run() +{ + // FIXME: Use GTestDBus when we bump glib to 2.34. + GOwnPtr<char> dbusLaunch(g_find_program_in_path("dbus-launch")); + if (!dbusLaunch) { + g_warning("Error starting DBUS daemon: dbus-launch not found in path"); + return false; + } + + GOwnPtr<char> output; + GOwnPtr<GError> error; + if (!g_spawn_command_line_sync(dbusLaunch.get(), &output.outPtr(), 0, 0, &error.outPtr())) { + g_warning("Error starting DBUS daemon: %s", error->message); + return false; + } + + String outputString = String::fromUTF8(output.get()); + Vector<String> lines; + outputString.split(UChar('\n'), /* allowEmptyEntries */ false, lines); + for (size_t i = 0; i < lines.size(); ++i) { + char** keyValue = g_strsplit(lines[i].utf8().data(), "=", 2); + g_assert_cmpuint(g_strv_length(keyValue), ==, 2); + if (!g_strcmp0(keyValue[0], "DBUS_SESSION_BUS_ADDRESS")) { + m_address = keyValue[1]; + g_setenv("DBUS_SESSION_BUS_ADDRESS", keyValue[1], TRUE); + } else if (!g_strcmp0(keyValue[0], "DBUS_SESSION_BUS_PID")) + m_pid = g_ascii_strtoll(keyValue[1], 0, 10); + g_strfreev(keyValue); + } + + return m_pid > 0; +} + +WebKitTestBus::~WebKitTestBus() +{ + g_unsetenv("DBUS_SESSION_BUS_ADDRESS"); + + if (m_pid != -1) + kill(m_pid, SIGTERM); +} + +GDBusConnection* WebKitTestBus::getOrCreateConnection() +{ + if (m_connection) + return m_connection.get(); + + g_assert(!m_address.isNull()); + m_connection = adoptGRef(g_dbus_connection_new_for_address_sync(m_address.data(), + static_cast<GDBusConnectionFlags>(G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT | G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION), + 0, 0, 0)); + return m_connection.get(); +} + +static void onNameAppeared(GDBusConnection*, const char*, const char*, gpointer userData) +{ + g_main_loop_quit(static_cast<GMainLoop*>(userData)); +} + +GDBusProxy* WebKitTestBus::createProxy(const char* serviceName, const char* objectPath, const char* interfaceName, GMainLoop* mainLoop) +{ + unsigned watcherID = g_bus_watch_name_on_connection(getOrCreateConnection(), serviceName, G_BUS_NAME_WATCHER_FLAGS_NONE, onNameAppeared, 0, mainLoop, 0); + g_main_loop_run(mainLoop); + g_bus_unwatch_name(watcherID); + + GDBusProxy* proxy = g_dbus_proxy_new_sync( + connection(), + G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START, + 0, // GDBusInterfaceInfo + serviceName, + objectPath, + interfaceName, + 0, // GCancellable + 0); + g_assert(proxy); + return proxy; +} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKit2GtkAuthenticationDialog.h b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.h index 67064622c..b9f856b27 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKit2GtkAuthenticationDialog.h +++ b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.h @@ -17,32 +17,28 @@ * Boston, MA 02110-1301, USA. */ -#ifndef WebKit2GtkAuthenticationDialog_h -#define WebKit2GtkAuthenticationDialog_h +#ifndef WebKitTestBus_h +#define WebKitTestBus_h -#include "AuthenticationChallengeProxy.h" -#include "WKRetainPtr.h" -#include "WebKitWebViewBase.h" -#include <WebCore/Credential.h> -#include <WebCore/GtkAuthenticationDialog.h> +#include <gio/gio.h> #include <wtf/gobject/GRefPtr.h> +#include <wtf/text/CString.h> -namespace WebKit { - -class WebKit2GtkAuthenticationDialog : public WebCore::GtkAuthenticationDialog { +class WebKitTestBus { public: - WebKit2GtkAuthenticationDialog(AuthenticationChallengeProxy*); - virtual ~WebKit2GtkAuthenticationDialog() { } - GtkWidget* widget() { return m_dialog; } + WebKitTestBus(); + virtual ~WebKitTestBus(); -protected: - virtual void authenticate(const WebCore::Credential&); + bool run(); + GDBusProxy* createProxy(const char* serviceName, const char* objectPath, const char* interfaceName, GMainLoop*); + GDBusConnection* connection() const { return m_connection.get(); } private: - RefPtr<AuthenticationChallengeProxy> m_authenticationChallenge; - GRefPtr<GtkStyleContext> m_styleContext; -}; + GDBusConnection* getOrCreateConnection(); -} // namespace WebKit + pid_t m_pid; + CString m_address; + GRefPtr<GDBusConnection> m_connection; +}; -#endif // WebKit2GtkAuthenticationDialog_h +#endif // WebKitTestBus_h diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp index 7e7eb0167..e6c843456 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp +++ b/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp @@ -30,6 +30,7 @@ WebViewTest::WebViewTest() , m_parentWindow(0) , m_javascriptResult(0) , m_resourceDataSize(0) + , m_surface(0) { assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_webView)); } @@ -40,6 +41,8 @@ WebViewTest::~WebViewTest() gtk_widget_destroy(m_parentWindow); if (m_javascriptResult) webkit_javascript_result_unref(m_javascriptResult); + if (m_surface) + cairo_surface_destroy(m_surface); g_object_unref(m_webView); g_main_loop_unref(m_mainLoop); } @@ -175,6 +178,15 @@ static gboolean parentWindowMapped(GtkWidget* widget, GdkEvent*, WebViewTest* te return FALSE; } +void WebViewTest::showInWindow(GtkWindowType windowType) +{ + g_assert(!m_parentWindow); + m_parentWindow = gtk_window_new(windowType); + gtk_container_add(GTK_CONTAINER(m_parentWindow), GTK_WIDGET(m_webView)); + gtk_widget_show(GTK_WIDGET(m_webView)); + gtk_widget_show(m_parentWindow); +} + void WebViewTest::showInWindowAndWaitUntilMapped(GtkWindowType windowType) { g_assert(!m_parentWindow); @@ -198,6 +210,11 @@ void WebViewTest::resizeView(int width, int height) gtk_widget_size_allocate(GTK_WIDGET(m_webView), &allocation); } +void WebViewTest::selectAll() +{ + webkit_web_view_execute_editing_command(m_webView, "SelectAll"); +} + static void resourceGetDataCallback(GObject* object, GAsyncResult* result, gpointer userData) { size_t dataSize; @@ -406,3 +423,22 @@ bool WebViewTest::javascriptResultIsUndefined(WebKitJavascriptResult* javascript return JSValueIsUndefined(context, value); } +static void onSnapshotReady(WebKitWebView* web_view, GAsyncResult* res, WebViewTest* test) +{ + GOwnPtr<GError> error; + test->m_surface = webkit_web_view_get_snapshot_finish(web_view, res, &error.outPtr()); + g_assert(!test->m_surface || !error.get()); + if (error) + g_assert_error(error.get(), WEBKIT_SNAPSHOT_ERROR, WEBKIT_SNAPSHOT_ERROR_FAILED_TO_CREATE); + test->quitMainLoop(); +} + +cairo_surface_t* WebViewTest::getSnapshotAndWaitUntilReady(WebKitSnapshotRegion region, WebKitSnapshotOptions options) +{ + if (m_surface) + cairo_surface_destroy(m_surface); + m_surface = 0; + webkit_web_view_get_snapshot(m_webView, region, options, 0, reinterpret_cast<GAsyncReadyCallback>(onSnapshotReady), this); + g_main_loop_run(m_mainLoop); + return m_surface; +} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h b/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h index 06f398f96..a460e22b4 100644 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h +++ b/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h @@ -46,8 +46,10 @@ public: void waitUntilLoadFinished(); void waitUntilTitleChangedTo(const char* expectedTitle); void waitUntilTitleChanged(); + void showInWindow(GtkWindowType = GTK_WINDOW_POPUP); void showInWindowAndWaitUntilMapped(GtkWindowType = GTK_WINDOW_POPUP); void resizeView(int width, int height); + void selectAll(); const char* mainResourceData(size_t& mainResourceDataSize); void mouseMoveTo(int x, int y, unsigned int mouseModifiers = 0); @@ -64,6 +66,8 @@ public: static bool javascriptResultIsNull(WebKitJavascriptResult*); static bool javascriptResultIsUndefined(WebKitJavascriptResult*); + cairo_surface_t* getSnapshotAndWaitUntilReady(WebKitSnapshotRegion, WebKitSnapshotOptions); + WebKitWebView* m_webView; GMainLoop* m_mainLoop; CString m_activeURI; @@ -73,6 +77,7 @@ public: GError** m_javascriptError; GOwnPtr<char> m_resourceData; size_t m_resourceDataSize; + cairo_surface_t* m_surface; private: void doMouseButtonEvent(GdkEventType, int, int, unsigned int, unsigned int); diff --git a/Source/WebKit2/UIProcess/API/gtk/webkit2.h b/Source/WebKit2/UIProcess/API/gtk/webkit2.h index 1b4fa86a1..d18431528 100644 --- a/Source/WebKit2/UIProcess/API/gtk/webkit2.h +++ b/Source/WebKit2/UIProcess/API/gtk/webkit2.h @@ -59,6 +59,7 @@ #include <webkit2/WebKitWebResource.h> #include <webkit2/WebKitWebView.h> #include <webkit2/WebKitWebViewBase.h> +#include <webkit2/WebKitWebViewGroup.h> #include <webkit2/WebKitWindowProperties.h> #undef __WEBKIT2_H_INSIDE__ diff --git a/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list b/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list index efd9e0433..420766ea7 100644 --- a/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list +++ b/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list @@ -3,6 +3,7 @@ BOOLEAN:ENUM,STRING,POINTER BOOLEAN:OBJECT BOOLEAN:OBJECT,BOXED,OBJECT BOOLEAN:OBJECT,ENUM +BOOLEAN:OBJECT,OBJECT BOOLEAN:STRING BOOLEAN:VOID OBJECT:VOID diff --git a/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm b/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm index 0e6a6f130..19d696670 100644 --- a/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm +++ b/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm @@ -148,7 +148,7 @@ void FindIndicatorWindow::setFindIndicator(PassRefPtr<FindIndicator> findIndicat NSRect windowContentRect = [NSWindow contentRectForFrameRect:windowFrameRect styleMask:NSBorderlessWindowMask]; - m_findIndicatorWindow.adoptNS([[NSWindow alloc] initWithContentRect:windowContentRect + m_findIndicatorWindow = adoptNS([[NSWindow alloc] initWithContentRect:windowContentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]); @@ -157,7 +157,7 @@ void FindIndicatorWindow::setFindIndicator(PassRefPtr<FindIndicator> findIndicat [m_findIndicatorWindow.get() setOpaque:NO]; [m_findIndicatorWindow.get() setIgnoresMouseEvents:YES]; - RetainPtr<WKFindIndicatorView> findIndicatorView(AdoptNS, [[WKFindIndicatorView alloc] _initWithFindIndicator:m_findIndicator]); + RetainPtr<WKFindIndicatorView> findIndicatorView = adoptNS([[WKFindIndicatorView alloc] _initWithFindIndicator:m_findIndicator]); [m_findIndicatorWindow.get() setContentView:findIndicatorView.get()]; [[m_wkView window] addChildWindow:m_findIndicatorWindow.get() ordered:NSWindowAbove]; @@ -166,7 +166,7 @@ void FindIndicatorWindow::setFindIndicator(PassRefPtr<FindIndicator> findIndicat if (animate) { // Start the bounce animation. m_bounceAnimationContext = WKWindowBounceAnimationContextCreate(m_findIndicatorWindow.get()); - m_bounceAnimation.adoptNS([[WKFindIndicatorWindowAnimation alloc] _initWithFindIndicatorWindow:this + m_bounceAnimation = adoptNS([[WKFindIndicatorWindowAnimation alloc] _initWithFindIndicatorWindow:this animationDuration:bounceAnimationDuration animationProgressCallback:&FindIndicatorWindow::bounceAnimationCallback animationDidEndCallback:&FindIndicatorWindow::bounceAnimationDidEnd]); @@ -206,7 +206,7 @@ void FindIndicatorWindow::startFadeOutTimerFired() { ASSERT(!m_fadeOutAnimation); - m_fadeOutAnimation.adoptNS([[WKFindIndicatorWindowAnimation alloc] _initWithFindIndicatorWindow:this + m_fadeOutAnimation = adoptNS([[WKFindIndicatorWindowAnimation alloc] _initWithFindIndicatorWindow:this animationDuration:fadeOutAnimationDuration animationProgressCallback:&FindIndicatorWindow::fadeOutAnimationCallback animationDidEndCallback:&FindIndicatorWindow::fadeOutAnimationDidEnd]); diff --git a/Source/WebKit2/UIProcess/API/mac/PDFViewController.h b/Source/WebKit2/UIProcess/API/mac/PDFViewController.h index 46aaf8458..265d7d692 100644 --- a/Source/WebKit2/UIProcess/API/mac/PDFViewController.h +++ b/Source/WebKit2/UIProcess/API/mac/PDFViewController.h @@ -31,6 +31,7 @@ #include <wtf/Noncopyable.h> #include <wtf/PassOwnPtr.h> #include <wtf/RetainPtr.h> +#include <wtf/text/WTFString.h> @class PDFView; @class WKView; @@ -79,8 +80,6 @@ private: static Class pdfDocumentClass(); static NSBundle* pdfKitBundle(); - NSString *pathToPDFOnDisk(); - WKView* m_wkView; RetainPtr<WKPDFView> m_wkPDFView; @@ -89,8 +88,7 @@ private: RetainPtr<NSString> m_suggestedFilename; RetainPtr<CFDataRef> m_pdfData; - RetainPtr<NSString> m_pathToPDFOnDisk; - bool m_hasWrittenPDFToDisk; + String m_temporaryPDFUUID; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm b/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm index 7b03a5645..8436c5dc8 100644 --- a/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm +++ b/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm @@ -36,6 +36,7 @@ #import "WebPreferences.h" #import <PDFKit/PDFKit.h> #import <WebCore/LocalizedStrings.h> +#import <WebCore/UUID.h> #import <wtf/ObjcRuntimeExtras.h> #import <wtf/text/CString.h> #import <wtf/text/WTFString.h> @@ -45,6 +46,7 @@ #define _webkit_PDFViewScaleChangedNotification @"PDFViewScaleChanged" #define _webkit_PDFViewPageChangedNotification @"PDFViewChangedPage" +using namespace WebCore; using namespace WebKit; @class PDFDocument; @@ -132,7 +134,7 @@ static BOOL _PDFSelectionsAreEqual(PDFSelection *selectionA, PDFSelection *selec Class previewViewClass = PDFViewController::pdfPreviewViewClass(); ASSERT(previewViewClass); - _pdfPreviewView.adoptNS([[previewViewClass alloc] initWithFrame:frame]); + _pdfPreviewView = adoptNS([[previewViewClass alloc] initWithFrame:frame]); [_pdfPreviewView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [self addSubview:_pdfPreviewView.get()]; @@ -401,9 +403,8 @@ PassOwnPtr<PDFViewController> PDFViewController::create(WKView *wkView) PDFViewController::PDFViewController(WKView *wkView) : m_wkView(wkView) - , m_wkPDFView(AdoptNS, [[WKPDFView alloc] initWithFrame:[m_wkView bounds] PDFViewController:this]) + , m_wkPDFView(adoptNS([[WKPDFView alloc] initWithFrame:[m_wkView bounds] PDFViewController:this])) , m_pdfView([m_wkPDFView.get() pdfView]) - , m_hasWrittenPDFToDisk(false) { [m_wkView addSubview:m_wkPDFView.get()]; } @@ -431,18 +432,18 @@ static RetainPtr<CFDataRef> convertPostScriptDataSourceToPDF(const CoreIPC::Data // http://developer.apple.com/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_ps_convert/chapter_16_section_1.html CGPSConverterCallbacks callbacks = { 0, 0, 0, 0, 0, 0, 0, 0 }; - RetainPtr<CGPSConverterRef> converter(AdoptCF, CGPSConverterCreate(0, &callbacks, 0)); + RetainPtr<CGPSConverterRef> converter = adoptCF(CGPSConverterCreate(0, &callbacks, 0)); ASSERT(converter); - RetainPtr<NSData> nsData(AdoptNS, [[NSData alloc] initWithBytesNoCopy:const_cast<uint8_t*>(dataReference.data()) length:dataReference.size() freeWhenDone:NO]); + RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:const_cast<uint8_t*>(dataReference.data()) length:dataReference.size() freeWhenDone:NO]); - RetainPtr<CGDataProviderRef> provider(AdoptCF, CGDataProviderCreateWithCFData((CFDataRef)nsData.get())); + RetainPtr<CGDataProviderRef> provider = adoptCF(CGDataProviderCreateWithCFData((CFDataRef)nsData.get())); ASSERT(provider); - RetainPtr<CFMutableDataRef> result(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0)); + RetainPtr<CFMutableDataRef> result = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0)); ASSERT(result); - RetainPtr<CGDataConsumerRef> consumer(AdoptCF, CGDataConsumerCreateWithCFData(result.get())); + RetainPtr<CGDataConsumerRef> consumer = adoptCF(CGDataConsumerCreateWithCFData(result.get())); ASSERT(consumer); CGPSConverterConvert(converter.get(), provider.get(), consumer.get(), 0); @@ -462,11 +463,11 @@ void PDFViewController::setPDFDocumentData(const String& mimeType, const String& m_suggestedFilename = String(suggestedFilename + ".pdf"); } else { // Make sure to copy the data. - m_pdfData.adoptCF(CFDataCreate(0, dataReference.data(), dataReference.size())); + m_pdfData = adoptCF(CFDataCreate(0, dataReference.data(), dataReference.size())); m_suggestedFilename = suggestedFilename; } - RetainPtr<PDFDocument> pdfDocument(AdoptNS, [[pdfDocumentClass() alloc] initWithData:(NSData *)m_pdfData.get()]); + RetainPtr<PDFDocument> pdfDocument = adoptNS([[pdfDocumentClass() alloc] initWithData:(NSData *)m_pdfData.get()]); [m_wkPDFView.get() setDocument:pdfDocument.get()]; } @@ -504,7 +505,6 @@ bool PDFViewController::forwardScrollWheelEvent(NSEvent *wheelEvent) return true; } -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 static IMP oldPDFViewScrollView_scrollWheel; static WKPDFView *findEnclosingWKPDFView(NSView *view) @@ -539,7 +539,6 @@ static void PDFViewScrollView_scrollWheel(NSScrollView* self, SEL _cmd, NSEvent wtfCallIMP<void>(oldPDFViewScrollView_scrollWheel, self, _cmd, wheelEvent); } -#endif NSBundle* PDFViewController::pdfKitBundle() { @@ -557,12 +556,10 @@ NSBundle* PDFViewController::pdfKitBundle() if (![pdfKitBundle load]) LOG_ERROR("Couldn't load PDFKit.framework"); -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 if (Class pdfViewScrollViewClass = [pdfKitBundle classNamed:@"PDFViewScrollView"]) { if (Method scrollWheel = class_getInstanceMethod(pdfViewScrollViewClass, @selector(scrollWheel:))) oldPDFViewScrollView_scrollWheel = method_setImplementation(scrollWheel, reinterpret_cast<IMP>(PDFViewScrollView_scrollWheel)); } -#endif return pdfKitBundle; } @@ -580,22 +577,14 @@ void PDFViewController::openPDFInFinder() return; } - NSString *path = pathToPDFOnDisk(); - if (!path) + if (!m_temporaryPDFUUID) { + ASSERT(m_pdfData); + m_temporaryPDFUUID = createCanonicalUUIDString(); + page()->savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(m_suggestedFilename.get(), page()->mainFrame()->url(), CFDataGetBytePtr(m_pdfData.get()), CFDataGetLength(m_pdfData.get()), m_temporaryPDFUUID); return; - - if (!m_hasWrittenPDFToDisk) { - // Create a PDF file with the minimal permissions (only accessible to the current user, see 4145714). - RetainPtr<NSNumber> permissions(AdoptNS, [[NSNumber alloc] initWithInt:S_IRUSR]); - RetainPtr<NSDictionary> fileAttributes(AdoptNS, [[NSDictionary alloc] initWithObjectsAndKeys:permissions.get(), NSFilePosixPermissions, nil]); - - if (![[NSFileManager defaultManager] createFileAtPath:path contents:(NSData *)m_pdfData.get() attributes:fileAttributes.get()]) - return; - - m_hasWrittenPDFToDisk = true; } - [[NSWorkspace sharedWorkspace] openFile:path]; + page()->openPDFFromTemporaryFolderWithNativeApplication(m_temporaryPDFUUID); } static void releaseCFData(unsigned char*, const void* data) @@ -624,50 +613,6 @@ void PDFViewController::savePDFToDownloadsFolder() page()->saveDataToFileInDownloadsFolder(m_suggestedFilename.get(), page()->mainFrame()->mimeType(), page()->mainFrame()->url(), data.get()); } -static NSString *temporaryPDFDirectoryPath() -{ - static NSString *temporaryPDFDirectoryPath; - - if (!temporaryPDFDirectoryPath) { - NSString *temporaryDirectoryTemplate = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WebKitPDFs-XXXXXX"]; - CString templateRepresentation = [temporaryDirectoryTemplate fileSystemRepresentation]; - - if (mkdtemp(templateRepresentation.mutableData())) - temporaryPDFDirectoryPath = [[[NSFileManager defaultManager] stringWithFileSystemRepresentation:templateRepresentation.data() length:templateRepresentation.length()] copy]; - } - - return temporaryPDFDirectoryPath; -} - -NSString *PDFViewController::pathToPDFOnDisk() -{ - if (m_pathToPDFOnDisk) - return m_pathToPDFOnDisk.get(); - - NSString *pdfDirectoryPath = temporaryPDFDirectoryPath(); - if (!pdfDirectoryPath) - return nil; - - NSString *path = [pdfDirectoryPath stringByAppendingPathComponent:m_suggestedFilename.get()]; - - NSFileManager *fileManager = [NSFileManager defaultManager]; - if ([fileManager fileExistsAtPath:path]) { - NSString *pathTemplatePrefix = [pdfDirectoryPath stringByAppendingPathComponent:@"XXXXXX-"]; - NSString *pathTemplate = [pathTemplatePrefix stringByAppendingString:m_suggestedFilename.get()]; - CString pathTemplateRepresentation = [pathTemplate fileSystemRepresentation]; - - int fd = mkstemps(pathTemplateRepresentation.mutableData(), pathTemplateRepresentation.length() - strlen([pathTemplatePrefix fileSystemRepresentation]) + 1); - if (fd < 0) - return nil; - - close(fd); - path = [fileManager stringWithFileSystemRepresentation:pathTemplateRepresentation.data() length:pathTemplateRepresentation.length()]; - } - - m_pathToPDFOnDisk.adoptNS([path copy]); - return path; -} - void PDFViewController::linkClicked(const String& url) { NSEvent* nsEvent = [NSApp currentEvent]; diff --git a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h index 66b23e47c..5f747c0c5 100644 --- a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h +++ b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h @@ -40,7 +40,7 @@ class AlternativeTextUIController; namespace WebKit { class FindIndicatorWindow; -class PageClientImpl : public PageClient { +class PageClientImpl FINAL : public PageClient { public: static PassOwnPtr<PageClientImpl> create(WKView*); virtual ~PageClientImpl(); @@ -53,6 +53,7 @@ private: virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy(); virtual void setViewNeedsDisplay(const WebCore::IntRect&); virtual void displayView(); + virtual bool canScrollView(); virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); virtual WebCore::IntSize viewSize(); @@ -67,6 +68,7 @@ private: virtual void processDidCrash(); virtual void pageClosed(); virtual void didRelaunchProcess(); + virtual void preferencesDidChange() OVERRIDE; virtual void toolTipChanged(const String& oldToolTip, const String& newToolTip); virtual void setCursor(const WebCore::Cursor&); virtual void setCursorHiddenUntilMouseMoves(bool); @@ -81,8 +83,9 @@ private: virtual void setDragImage(const WebCore::IntPoint& clientPosition, PassRefPtr<ShareableBitmap> dragImage, bool isLinkDrag); virtual void setPromisedData(const String& pasteboardName, PassRefPtr<WebCore::SharedBuffer> imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleUrl, PassRefPtr<WebCore::SharedBuffer> archiveBuffer); - virtual void updateTextInputState(bool updateSecureInputState); - virtual void resetTextInputState(); + virtual void updateSecureInputState() OVERRIDE; + virtual void resetSecureInputState() OVERRIDE; + virtual void notifyInputContextAboutDiscardedComposition() OVERRIDE; virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&); virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&); @@ -98,7 +101,7 @@ private: virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); #if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorChooserProxy> createColorChooserProxy(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&); + virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&); #endif void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate); @@ -116,16 +119,6 @@ private: virtual CGContextRef containingWindowGraphicsContext(); - virtual void didChangeScrollbarsForMainFrame() const; - - virtual void didCommitLoadForMainFrame(bool useCustomRepresentation); - virtual void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&); - - virtual double customRepresentationZoomFactor(); - virtual void setCustomRepresentationZoomFactor(double); - virtual void findStringInCustomRepresentation(const String&, FindOptions, unsigned maxMatchCount); - virtual void countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned maxMatchCount); - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); virtual void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&); @@ -145,7 +138,6 @@ private: virtual uint64_t addDictationAlternatives(const RetainPtr<NSTextAlternatives>&); virtual void removeDictationAlternatives(uint64_t dictationContext); virtual void showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext); - virtual void dismissDictationAlternativeUI(); virtual Vector<String> dictationAlternatives(uint64_t dictationContext); #endif diff --git a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm index 0172cb077..3d93314e6 100644 --- a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm +++ b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm @@ -127,7 +127,7 @@ PassOwnPtr<PageClientImpl> PageClientImpl::create(WKView* wkView) PageClientImpl::PageClientImpl(WKView* wkView) : m_wkView(wkView) - , m_undoTarget(AdoptNS, [[WKEditorUndoTargetObjC alloc] init]) + , m_undoTarget(adoptNS([[WKEditorUndoTargetObjC alloc] init])) #if USE(DICTATION_ALTERNATIVES) , m_alternativeTextUIController(adoptPtr(new AlternativeTextUIController)) #endif @@ -153,6 +153,12 @@ void PageClientImpl::displayView() [m_wkView displayIfNeeded]; } +bool PageClientImpl::canScrollView() +{ + // -scrollRect:by: does nothing in layer-backed views <rdar://problem/12961719>. + return ![m_wkView layer]; +} + void PageClientImpl::scrollView(const IntRect& scrollRect, const IntSize& scrollOffset) { NSRect clippedScrollRect = NSIntersectionRect(scrollRect, NSOffsetRect(scrollRect, -scrollOffset.width(), -scrollOffset.height())); @@ -191,9 +197,19 @@ bool PageClientImpl::isViewVisible() if (![[m_wkView window] isVisible]) return false; +#if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 + // Mountain Lion and previous do not support occlusion notifications, and as such will + // continue to report as "visible" when not on the active space. + if (![[m_wkView window] isOnActiveSpace]) + return false; +#endif + if ([m_wkView isHiddenOrHasHiddenAncestor]) return false; + if ([m_wkView _isWindowOccluded]) + return false; + return true; } @@ -242,6 +258,11 @@ void PageClientImpl::didRelaunchProcess() [m_wkView _didRelaunchProcess]; } +void PageClientImpl::preferencesDidChange() +{ + [m_wkView _preferencesDidChange]; +} + void PageClientImpl::toolTipChanged(const String& oldToolTip, const String& newToolTip) { [m_wkView _toolTipChangedFrom:nsStringFromWebCoreString(oldToolTip) to:nsStringFromWebCoreString(newToolTip)]; @@ -266,7 +287,7 @@ void PageClientImpl::registerEditCommand(PassRefPtr<WebEditCommandProxy> prpComm { RefPtr<WebEditCommandProxy> command = prpCommand; - RetainPtr<WKEditCommandObjC> commandObjC(AdoptNS, [[WKEditCommandObjC alloc] initWithWebEditCommandProxy:command]); + RetainPtr<WKEditCommandObjC> commandObjC = adoptNS([[WKEditCommandObjC alloc] initWithWebEditCommandProxy:command]); String actionName = WebEditCommandProxy::nameForEditAction(command->editAction()); NSUndoManager *undoManager = [m_wkView undoManager]; @@ -298,7 +319,7 @@ bool PageClientImpl::interpretKeyEvent(const NativeWebKeyboardEvent& event, Vect void PageClientImpl::setDragImage(const IntPoint& clientPosition, PassRefPtr<ShareableBitmap> dragImage, bool isLinkDrag) { RetainPtr<CGImageRef> dragCGImage = dragImage->makeCGImage(); - RetainPtr<NSImage> dragNSImage(AdoptNS, [[NSImage alloc] initWithCGImage:dragCGImage.get() size:dragImage->size()]); + RetainPtr<NSImage> dragNSImage = adoptNS([[NSImage alloc] initWithCGImage:dragCGImage.get() size:dragImage->size()]); [m_wkView _setDragImage:dragNSImage.get() at:clientPosition linkDrag:isLinkDrag]; } @@ -310,14 +331,19 @@ void PageClientImpl::setPromisedData(const String& pasteboardName, PassRefPtr<Sh [m_wkView _setPromisedData:image.get() withFileName:filename withExtension:extension withTitle:title withURL:url withVisibleURL:visibleUrl withArchive:archiveBuffer.get() forPasteboard:pasteboardName]; } -void PageClientImpl::updateTextInputState(bool updateSecureInputState) +void PageClientImpl::updateSecureInputState() { - [m_wkView _updateTextInputStateIncludingSecureInputState:updateSecureInputState]; + [m_wkView _updateSecureInputState]; } -void PageClientImpl::resetTextInputState() +void PageClientImpl::resetSecureInputState() { - [m_wkView _resetTextInputState]; + [m_wkView _resetSecureInputState]; +} + +void PageClientImpl::notifyInputContextAboutDiscardedComposition() +{ + [m_wkView _notifyInputContextAboutDiscardedComposition]; } FloatRect PageClientImpl::convertToDeviceSpace(const FloatRect& rect) @@ -367,7 +393,7 @@ PassRefPtr<WebContextMenuProxy> PageClientImpl::createContextMenuProxy(WebPagePr } #if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorChooserProxy> PageClientImpl::createColorChooserProxy(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) +PassRefPtr<WebColorPicker> PageClientImpl::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) { notImplemented(); return 0; @@ -432,41 +458,6 @@ CGContextRef PageClientImpl::containingWindowGraphicsContext() return static_cast<CGContextRef>([[window graphicsContext] graphicsPort]); } -void PageClientImpl::didChangeScrollbarsForMainFrame() const -{ - [m_wkView _didChangeScrollbarsForMainFrame]; -} - -void PageClientImpl::didCommitLoadForMainFrame(bool useCustomRepresentation) -{ - [m_wkView _setPageHasCustomRepresentation:useCustomRepresentation]; -} - -void PageClientImpl::didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference& dataReference) -{ - [m_wkView _didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:suggestedFilename dataReference:dataReference]; -} - -double PageClientImpl::customRepresentationZoomFactor() -{ - return [m_wkView _customRepresentationZoomFactor]; -} - -void PageClientImpl::setCustomRepresentationZoomFactor(double zoomFactor) -{ - [m_wkView _setCustomRepresentationZoomFactor:zoomFactor]; -} - -void PageClientImpl::findStringInCustomRepresentation(const String& string, FindOptions options, unsigned maxMatchCount) -{ - [m_wkView _findStringInCustomRepresentation:string withFindOptions:options maxMatchCount:maxMatchCount]; -} - -void PageClientImpl::countStringMatchesInCustomRepresentation(const String& string, FindOptions options, unsigned maxMatchCount) -{ - [m_wkView _countStringMatchesInCustomRepresentation:string withFindOptions:options maxMatchCount:maxMatchCount]; -} - void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&) { notImplemented(); @@ -477,24 +468,17 @@ void PageClientImpl::didPerformDictionaryLookup(const AttributedString& text, co RetainPtr<NSAttributedString> attributedString = text.string; NSPoint textBaselineOrigin = dictionaryPopupInfo.origin; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 // Convert to screen coordinates. textBaselineOrigin = [m_wkView convertPoint:textBaselineOrigin toView:nil]; textBaselineOrigin = [m_wkView.window convertRectToScreen:NSMakeRect(textBaselineOrigin.x, textBaselineOrigin.y, 0, 0)].origin; WKShowWordDefinitionWindow(attributedString.get(), textBaselineOrigin, (NSDictionary *)dictionaryPopupInfo.options.get()); -#else - // If the dictionary lookup is being triggered by a hot key, force the overlay style. - NSDictionary *options = (dictionaryPopupInfo.type == DictionaryPopupInfo::HotKey) ? [NSDictionary dictionaryWithObject:NSDefinitionPresentationTypeOverlay forKey:NSDefinitionPresentationTypeKey] : 0; - [m_wkView showDefinitionForAttributedString:attributedString.get() range:NSMakeRange(0, [attributedString.get() length]) options:options baselineOriginProvider:^(NSRange adjustedRange) { return (NSPoint)textBaselineOrigin; }]; -#endif } void PageClientImpl::dismissDictionaryLookupPanel() { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 + // FIXME: We don't know which panel we are dismissing, it may not even be in the current page (see <rdar://problem/13875766>). WKHideWordDefinitionWindow(); -#endif } void PageClientImpl::showCorrectionPanel(AlternativeTextType type, const FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) @@ -524,15 +508,12 @@ String PageClientImpl::dismissCorrectionPanelSoon(WebCore::ReasonForDismissingAl void PageClientImpl::recordAutocorrectionResponse(AutocorrectionResponseType responseType, const String& replacedString, const String& replacementString) { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 NSCorrectionResponse response = responseType == AutocorrectionReverted ? NSCorrectionResponseReverted : NSCorrectionResponseEdited; CorrectionPanel::recordAutocorrectionResponse(m_wkView, response, replacedString, replacementString); -#endif } void PageClientImpl::recommendedScrollbarStyleDidChange(int32_t newStyle) { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 NSArray *trackingAreas = [m_wkView trackingAreas]; NSUInteger count = [trackingAreas count]; ASSERT(count == 1); @@ -553,9 +534,6 @@ void PageClientImpl::recommendedScrollbarStyleDidChange(int32_t newStyle) userInfo:nil]; [m_wkView addTrackingArea:trackingArea]; [trackingArea release]; -#else - UNUSED_PARAM(newStyle); -#endif } void PageClientImpl::intrinsicContentSizeDidChange(const IntSize& intrinsicContentSize) @@ -592,11 +570,6 @@ Vector<String> PageClientImpl::dictationAlternatives(uint64_t dictationContext) { return m_alternativeTextUIController->alternativesForContext(dictationContext); } - -void PageClientImpl::dismissDictationAlternativeUI() -{ - m_alternativeTextUIController->dismissAlternatives(); -} #endif } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h index 07bb9a8d2..6aa81c438 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h @@ -48,16 +48,23 @@ WK_EXPORT /* Load a request. This is only valid for requests of non-file: URLs. Passing a file: URL will throw an exception. */ - (void)loadRequest:(NSURLRequest *)request; +- (void)loadRequest:(NSURLRequest *)request userData:(id)userData; /* Load a file: URL. Opens the sandbox only for files within allowedDirectory. - - Passing a non-file: URL to either parameter will yeild an exception. + - Passing a non-file: URL to either parameter will yield an exception. - Passing nil as the allowedDirectory will open the entire file-system for - reading. + reading. */ - (void)loadFileURL:(NSURL *)URL restrictToFilesWithin:(NSURL *)allowedDirectory; +- (void)loadFileURL:(NSURL *)URL restrictToFilesWithin:(NSURL *)allowedDirectory userData:(id)userData; /* Load a page using the passed in string as its contents. */ - (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL; +- (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL userData:(id)userData; + +/* Load a page using the passed in data as its contents. */ +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL; +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL userData:(id)userData; /* Stops the load associated with the active URL. */ - (void)stopLoading; diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm index d91019f72..f7120af2e 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm @@ -28,6 +28,7 @@ #import "WKBrowsingContextControllerPrivate.h" #import "WKBrowsingContextControllerInternal.h" +#import "ObjCObjectGraph.h" #import "WKErrorCF.h" #import "WKFrame.h" #import "WKPagePrivate.h" @@ -37,11 +38,14 @@ #import "WKURLRequest.h" #import "WKURLRequestNS.h" #import "WebContext.h" +#import "WebData.h" #import "WebPageProxy.h" #import <wtf/RetainPtr.h> #import "WKBrowsingContextLoadDelegate.h" +using namespace WebKit; + static inline NSString *autoreleased(WKStringRef string) { WKRetainPtr<WKStringRef> wkString = adoptWK(string); @@ -99,37 +103,67 @@ static inline NSURL *autoreleased(WKURLRef url) + (void)registerSchemeForCustomProtocol:(NSString *)scheme { + if (!scheme) + return; + NSString *lowercaseScheme = [scheme lowercaseString]; [[WKBrowsingContextController customSchemes] addObject:lowercaseScheme]; - [[NSNotificationCenter defaultCenter] postNotificationName:WebKit::SchemeForCustomProtocolRegisteredNotificationName object:lowercaseScheme]; + [[NSNotificationCenter defaultCenter] postNotificationName:SchemeForCustomProtocolRegisteredNotificationName object:lowercaseScheme]; } + (void)unregisterSchemeForCustomProtocol:(NSString *)scheme { + if (!scheme) + return; + NSString *lowercaseScheme = [scheme lowercaseString]; [[WKBrowsingContextController customSchemes] removeObject:lowercaseScheme]; - [[NSNotificationCenter defaultCenter] postNotificationName:WebKit::SchemeForCustomProtocolUnregisteredNotificationName object:lowercaseScheme]; + [[NSNotificationCenter defaultCenter] postNotificationName:SchemeForCustomProtocolUnregisteredNotificationName object:lowercaseScheme]; } - (void)loadRequest:(NSURLRequest *)request { + [self loadRequest:request userData:nil]; +} + +- (void)loadRequest:(NSURLRequest *)request userData:(id)userData +{ WKRetainPtr<WKURLRequestRef> wkRequest = adoptWK(WKURLRequestCreateWithNSURLRequest(request)); - WKPageLoadURLRequest(self._pageRef, wkRequest.get()); + + RefPtr<ObjCObjectGraph> wkUserData; + if (userData) + wkUserData = ObjCObjectGraph::create(userData); + + WKPageLoadURLRequestWithUserData(self._pageRef, wkRequest.get(), (WKTypeRef)wkUserData.get()); } - (void)loadFileURL:(NSURL *)URL restrictToFilesWithin:(NSURL *)allowedDirectory { - if (![URL isFileURL]) - return; + [self loadFileURL:URL restrictToFilesWithin:allowedDirectory userData:nil]; +} - /* FIXME: Implement restrictions. */ +- (void)loadFileURL:(NSURL *)URL restrictToFilesWithin:(NSURL *)allowedDirectory userData:(id)userData +{ + if (![URL isFileURL] || (allowedDirectory && ![allowedDirectory isFileURL])) + [NSException raise:NSInvalidArgumentException format:@"Attempted to load a non-file URL"]; WKRetainPtr<WKURLRef> wkURL = adoptWK(WKURLCreateWithCFURL((CFURLRef)URL)); - WKPageLoadURL(self._pageRef, wkURL.get()); + WKRetainPtr<WKURLRef> wkAllowedDirectory = adoptWK(WKURLCreateWithCFURL((CFURLRef)allowedDirectory)); + + RefPtr<ObjCObjectGraph> wkUserData; + if (userData) + wkUserData = ObjCObjectGraph::create(userData); + + WKPageLoadFileWithUserData(self._pageRef, wkURL.get(), wkAllowedDirectory.get(), (WKTypeRef)wkUserData.get()); } - (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL { + [self loadHTMLString:HTMLString baseURL:baseURL userData:nil]; +} + +- (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL userData:(id)userData +{ WKRetainPtr<WKStringRef> wkHTMLString; if (HTMLString) wkHTMLString = adoptWK(WKStringCreateWithCFString((CFStringRef)HTMLString)); @@ -138,7 +172,48 @@ static inline NSURL *autoreleased(WKURLRef url) if (baseURL) wkBaseURL = adoptWK(WKURLCreateWithCFURL((CFURLRef)baseURL)); - WKPageLoadHTMLString(self._pageRef, wkHTMLString.get(), wkBaseURL.get()); + RefPtr<ObjCObjectGraph> wkUserData; + if (userData) + wkUserData = ObjCObjectGraph::create(userData); + + WKPageLoadHTMLStringWithUserData(self._pageRef, wkHTMLString.get(), wkBaseURL.get(), (WKTypeRef)wkUserData.get()); +} + +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL +{ + [self loadData:data MIMEType:MIMEType textEncodingName:encodingName baseURL:baseURL userData:nil]; +} + +static void releaseNSData(unsigned char*, const void* data) +{ + [(NSData *)data release]; +} + +- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL userData:(id)userData +{ + RefPtr<WebData> wkData; + if (data) { + [data retain]; + wkData = WebData::createWithoutCopying((const unsigned char*)[data bytes], [data length], releaseNSData, data); + } + + WKRetainPtr<WKStringRef> wkMIMEType; + if (MIMEType) + wkMIMEType = adoptWK(WKStringCreateWithCFString((CFStringRef)MIMEType)); + + WKRetainPtr<WKStringRef> wkEncodingName; + if (encodingName) + wkEncodingName = adoptWK(WKStringCreateWithCFString((CFStringRef)encodingName)); + + WKRetainPtr<WKURLRef> wkBaseURL; + if (baseURL) + wkBaseURL = adoptWK(WKURLCreateWithCFURL((CFURLRef)baseURL)); + + RefPtr<ObjCObjectGraph> wkUserData; + if (userData) + wkUserData = ObjCObjectGraph::create(userData); + + WKPageLoadDataWithUserData(self._pageRef, toAPI(wkData.get()), wkMIMEType.get(), wkEncodingName.get(), wkBaseURL.get(), (WKTypeRef)wkUserData.get()); } - (void)stopLoading @@ -340,7 +415,7 @@ static void didFailProvisionalLoadWithErrorForFrame(WKPageRef page, WKFrameRef f WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidFailProvisionalLoad:withError:)]) { - RetainPtr<CFErrorRef> cfError(AdoptCF, WKErrorCopyCFError(kCFAllocatorDefault, error)); + RetainPtr<CFErrorRef> cfError = adoptCF(WKErrorCopyCFError(kCFAllocatorDefault, error)); [browsingContext.loadDelegate browsingContextControllerDidFailProvisionalLoad:browsingContext withError:(NSError *)cfError.get()]; } } @@ -372,7 +447,7 @@ static void didFailLoadWithErrorForFrame(WKPageRef page, WKFrameRef frame, WKErr WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidFailLoad:withError:)]) { - RetainPtr<CFErrorRef> cfError(AdoptCF, WKErrorCopyCFError(kCFAllocatorDefault, error)); + RetainPtr<CFErrorRef> cfError = adoptCF(WKErrorCopyCFError(kCFAllocatorDefault, error)); [browsingContext.loadDelegate browsingContextControllerDidFailLoad:browsingContext withError:(NSError *)cfError.get()]; } } diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h index fe895c923..1ec4b515c 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h @@ -33,8 +33,6 @@ /* Returns a WKBrowsingContextController associated with the WKPageRef. */ + (WKBrowsingContextController *)_browsingContextControllerForPageRef:(WKPageRef)pageRef; -@property(readonly) WKPageRef _pageRef; - + (NSMutableSet *)customSchemes; @end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h index 48fcb12f0..6c8cb49b2 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h @@ -36,6 +36,8 @@ typedef NSUInteger WKBrowsingContextPaginationMode; @interface WKBrowsingContextController (Private) +@property(readonly) WKPageRef _pageRef; + @property WKBrowsingContextPaginationMode paginationMode; // Whether the column-break-{before,after} properties are respected instead of the // page-break-{before,after} properties. diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm index 5704dd72a..a24b015c9 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm @@ -25,7 +25,7 @@ #import "config.h" #import "WKBrowsingContextGroup.h" -#import "WKBrowsingContextGroupInternal.h" +#import "WKBrowsingContextGroupPrivate.h" #import "WKArray.h" #import "WKPageGroup.h" @@ -56,6 +56,12 @@ _data = [[WKBrowsingContextGroupData alloc] init]; _data->_pageGroupRef = adoptWK(WKPageGroupCreateWithIdentifier(adoptWK(WKStringCreateWithCFString((CFStringRef)identifier)).get())); + // Give the WKBrowsingContextGroup a identifier-less preferences, so that they + // don't get automatically written to the disk. The automatic writing has proven + // confusing to users of the API. + WKRetainPtr<WKPreferencesRef> preferences = adoptWK(WKPreferencesCreate()); + WKPageGroupSetPreferences(_data->_pageGroupRef.get(), preferences.get()); + return self; } @@ -75,6 +81,16 @@ WKPreferencesSetJavaScriptEnabled(WKPageGroupGetPreferences(self._pageGroupRef), allowsJavaScript); } +- (BOOL)allowsJavaScriptMarkup +{ + return WKPreferencesGetJavaScriptMarkupEnabled(WKPageGroupGetPreferences(self._pageGroupRef)); +} + +- (void)setAllowsJavaScriptMarkup:(BOOL)allowsJavaScriptMarkup +{ + WKPreferencesSetJavaScriptMarkupEnabled(WKPageGroupGetPreferences(self._pageGroupRef), allowsJavaScriptMarkup); +} + - (BOOL)allowsPlugIns { return WKPreferencesGetPluginsEnabled(WKPageGroupGetPreferences(self._pageGroupRef)); @@ -143,7 +159,7 @@ static WKArrayRef createWKArray(NSArray *array) @end -@implementation WKBrowsingContextGroup (Internal) +@implementation WKBrowsingContextGroup (Private) - (WKPageGroupRef)_pageGroupRef { diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroupInternal.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroupPrivate.h index 957c3b09b..d4f0fc416 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroupInternal.h +++ b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroupPrivate.h @@ -25,7 +25,7 @@ #import <WebKit2/WKBrowsingContextGroup.h> -@interface WKBrowsingContextGroup (Internal) +@interface WKBrowsingContextGroup (Private) @property(readonly) WKPageGroupRef _pageGroupRef; diff --git a/Source/WebKit2/UIProcess/API/mac/WKConnection.mm b/Source/WebKit2/UIProcess/API/mac/WKConnection.mm index 50efb79bc..3830e740f 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKConnection.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKConnection.mm @@ -88,10 +88,10 @@ static void didReceiveMessage(WKConnectionRef, WKStringRef messageName, WKTypeRe { WKConnection *connection = (WKConnection *)clientInfo; if ([connection.delegate respondsToSelector:@selector(connection:didReceiveMessageWithName:body:)]) { - RetainPtr<NSString> nsMessageName = adoptNS((NSString *)WKStringCopyCFString(kCFAllocatorDefault, messageName)); + RetainPtr<CFStringRef> nsMessageName = adoptCF(WKStringCopyCFString(kCFAllocatorDefault, messageName)); RetainPtr<id> nsMessageBody = ((ObjCObjectGraph*)messageBody)->rootObject(); - [connection.delegate connection:connection didReceiveMessageWithName:nsMessageName.get() body:nsMessageBody.get()]; + [connection.delegate connection:connection didReceiveMessageWithName:(NSString *)nsMessageName.get() body:nsMessageBody.get()]; } } diff --git a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h b/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h index 67bd4b1b9..b45f635b3 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h +++ b/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h @@ -42,7 +42,7 @@ namespace WebKit { RefPtr<WebKit::WebFrameProxy> _webFrame; Vector<WebCore::IntRect> _printingPageRects; double _totalScaleFactorForPrinting; - HashMap<WebCore::IntRect, RefPtr<WebKit::ShareableBitmap> > _pagePreviews; + HashMap<WebCore::IntRect, RefPtr<WebKit::ShareableBitmap>> _pagePreviews; Vector<uint8_t> _printedPagesData; RetainPtr<PDFDocument> _printedPagesPDFDocument; diff --git a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm b/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm index 0f53f99e9..350ad542e 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm @@ -472,13 +472,15 @@ static void prepareDataForPrintingOnSecondaryThread(void* untypedContext) { ASSERT(isMainThread()); - IntRect rect(nsRect); - rect.scale(1 / _totalScaleFactorForPrinting); - HashMap<WebCore::IntRect, RefPtr<ShareableBitmap> >::iterator pagePreviewIterator = _pagePreviews.find(rect); + IntRect scaledPrintingRect(nsRect); + scaledPrintingRect.scale(1 / _totalScaleFactorForPrinting); + IntSize imageSize(nsRect.size); + imageSize.scale(_webFrame->page()->deviceScaleFactor()); + HashMap<WebCore::IntRect, RefPtr<ShareableBitmap>>::iterator pagePreviewIterator = _pagePreviews.find(scaledPrintingRect); if (pagePreviewIterator == _pagePreviews.end()) { // It's too early to ask for page preview if we don't even know page size and scale. if ([self _hasPageRects]) { - if (uint64_t existingCallback = [self _expectedPreviewCallbackForRect:rect]) { + if (uint64_t existingCallback = [self _expectedPreviewCallbackForRect:scaledPrintingRect]) { // We've already asked for a preview of this page, and are waiting for response. // There is no need to ask again. _latestExpectedPreviewCallback = existingCallback; @@ -493,12 +495,12 @@ static void prepareDataForPrintingOnSecondaryThread(void* untypedContext) IPCCallbackContext* context = new IPCCallbackContext; RefPtr<ImageCallback> callback = ImageCallback::create(context, pageDidDrawToImage); _latestExpectedPreviewCallback = callback->callbackID(); - _expectedPreviewCallbacks.add(_latestExpectedPreviewCallback, rect); + _expectedPreviewCallbacks.add(_latestExpectedPreviewCallback, scaledPrintingRect); context->view = self; context->callbackID = callback->callbackID(); - _webFrame->page()->drawRectToImage(_webFrame.get(), PrintInfo([_printOperation printInfo]), rect, callback.get()); + _webFrame->page()->drawRectToImage(_webFrame.get(), PrintInfo([_printOperation printInfo]), scaledPrintingRect, imageSize, callback.get()); return; } } @@ -513,14 +515,7 @@ static void prepareDataForPrintingOnSecondaryThread(void* untypedContext) GraphicsContext context(cgContext); GraphicsContextStateSaver stateSaver(context); - context.translate(nsRect.origin.x, nsRect.origin.y); - context.scale(FloatSize(_totalScaleFactorForPrinting, _totalScaleFactorForPrinting)); - - // FIXME: Should we get the WebPage's deviceScaleFactor from here instead? - const IntRect& imageBounds = bitmap->bounds(); - float imageScaleFactor = imageBounds.width() / rect.width(); - - bitmap->paint(context, imageScaleFactor, IntPoint(), imageBounds); + bitmap->paint(context, _webFrame->page()->deviceScaleFactor(), IntPoint(nsRect.origin), bitmap->bounds()); } - (void)drawRect:(NSRect)nsRect @@ -541,8 +536,8 @@ static void prepareDataForPrintingOnSecondaryThread(void* untypedContext) ASSERT(!_printedPagesData.isEmpty()); // Prepared by knowsPageRange: if (!_printedPagesPDFDocument) { - RetainPtr<NSData> pdfData(AdoptNS, [[NSData alloc] initWithBytes:_printedPagesData.data() length:_printedPagesData.size()]); - _printedPagesPDFDocument.adoptNS([[pdfDocumentClass() alloc] initWithData:pdfData.get()]); + RetainPtr<NSData> pdfData = adoptNS([[NSData alloc] initWithBytes:_printedPagesData.data() length:_printedPagesData.size()]); + _printedPagesPDFDocument = adoptNS([[pdfDocumentClass() alloc] initWithData:pdfData.get()]); } unsigned printedPageNumber = [self _pageForRect:nsRect] - [self _firstPrintedPageNumber]; diff --git a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h b/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h index d315ad78c..95944814a 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h +++ b/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h @@ -29,6 +29,11 @@ @class WKProcessGroup, WKProcessGroupData, WKConnection; @protocol WKProcessGroupDelegate <NSObject> +@optional + +- (id)processGroupWillCreateConnectionToWebProcessPlugIn:(WKProcessGroup *)processGroup; + +@required - (void)processGroup:(WKProcessGroup *)processGroup didCreateConnectionToWebProcessPlugIn:(WKConnection *)connection; diff --git a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm b/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm index 8b4770046..044716b82 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm @@ -25,8 +25,9 @@ #import "config.h" #import "WKProcessGroup.h" -#import "WKProcessGroupInternal.h" +#import "WKProcessGroupPrivate.h" +#import "ObjCObjectGraph.h" #import "WKConnectionInternal.h" #import "WKContext.h" #import "WKRetainPtr.h" @@ -69,6 +70,30 @@ static void setUpConnectionClient(WKProcessGroup *processGroup, WKContextRef con WKContextSetConnectionClient(contextRef, &connectionClient); } +static WKTypeRef getInjectedBundleInitializationUserData(WKContextRef, const void* clientInfo) +{ + WKProcessGroup *processGroup = (WKProcessGroup *)clientInfo; + if ([processGroup.delegate respondsToSelector:@selector(processGroupWillCreateConnectionToWebProcessPlugIn:)]) { + RetainPtr<id> initializationUserData = [processGroup.delegate processGroupWillCreateConnectionToWebProcessPlugIn:processGroup]; + RefPtr<WebKit::ObjCObjectGraph> wkMessageBody = WebKit::ObjCObjectGraph::create(initializationUserData.get()); + return (WKTypeRef)wkMessageBody.release().leakRef(); + } + + return 0; +} + +static void setUpInectedBundleClient(WKProcessGroup *processGroup, WKContextRef contextRef) +{ + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + + injectedBundleClient.version = kWKContextInjectedBundleClientCurrentVersion; + injectedBundleClient.clientInfo = processGroup; + injectedBundleClient.getInjectedBundleInitializationUserData = getInjectedBundleInitializationUserData; + + WKContextSetInjectedBundleClient(contextRef, &injectedBundleClient); +} + - (id)init { return [self initWithInjectedBundleURL:nil]; @@ -88,6 +113,7 @@ static void setUpConnectionClient(WKProcessGroup *processGroup, WKContextRef con _data->_contextRef = adoptWK(WKContextCreate()); setUpConnectionClient(self, _data->_contextRef.get()); + setUpInectedBundleClient(self, _data->_contextRef.get()); return self; } @@ -95,6 +121,7 @@ static void setUpConnectionClient(WKProcessGroup *processGroup, WKContextRef con - (void)dealloc { WKContextSetConnectionClient(_data->_contextRef.get(), 0); + WKContextSetInjectedBundleClient(_data->_contextRef.get(), 0); [_data release]; [super dealloc]; @@ -112,7 +139,7 @@ static void setUpConnectionClient(WKProcessGroup *processGroup, WKContextRef con @end -@implementation WKProcessGroup (Internal) +@implementation WKProcessGroup (Private) - (WKContextRef)_contextRef { @@ -120,5 +147,3 @@ static void setUpConnectionClient(WKProcessGroup *processGroup, WKContextRef con } @end - - diff --git a/Source/WebKit2/UIProcess/API/mac/WKProcessGroupInternal.h b/Source/WebKit2/UIProcess/API/mac/WKProcessGroupPrivate.h index 1a8bc2ae2..7a9d2f9c0 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKProcessGroupInternal.h +++ b/Source/WebKit2/UIProcess/API/mac/WKProcessGroupPrivate.h @@ -25,7 +25,7 @@ #import <WebKit2/WKProcessGroup.h> -@interface WKProcessGroup (Internal) +@interface WKProcessGroup (Private) @property(readonly) WKContextRef _contextRef; diff --git a/Source/WebKit2/UIProcess/API/C/win/WKViewPrivate.cpp b/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.h index 7b3cf6e82..7b81e9a98 100644 --- a/Source/WebKit2/UIProcess/API/C/win/WKViewPrivate.cpp +++ b/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,15 +23,18 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" -#include "WKViewPrivate.h" +#if defined(__LP64__) && defined(__clang__) -#include "WKAPICast.h" -#include "WebView.h" +#import <Foundation/Foundation.h> +#import <WebKit2/WKBase.h> -using namespace WebKit; +WK_EXPORT +@interface WKTypeRefWrapper : NSObject -void WKViewSetOverrideCursor(WKViewRef viewRef, HCURSOR overrideCursor) -{ - toImpl(viewRef)->setOverrideCursor(overrideCursor); -} +- (id)initWithObject:(WKTypeRef)object; + +@property(readonly) WKTypeRef object; + +@end + +#endif diff --git a/Source/WebKit2/UIProcess/API/C/win/WKContextWin.cpp b/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.mm index 4971540e4..fd80ac248 100644 --- a/Source/WebKit2/UIProcess/API/C/win/WKContextWin.cpp +++ b/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.mm @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,21 +23,38 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" -#include "WKContext.h" -#include "WKContextPrivateWin.h" +#import "config.h" -#include "WKAPICast.h" -#include "WebContext.h" +#if defined(__LP64__) && defined(__clang__) -using namespace WebKit; +#import "WKTypeRefWrapper.h" -void WKContextSetShouldPaintNativeControls(WKContextRef contextRef, bool b) +#import "WKRetainPtr.h" + +@interface WKTypeRefWrapper () { + // Underlying WKTypeRef. + WKRetainPtr<WKTypeRef> _object; +} +@end + +@implementation WKTypeRefWrapper + +- (id)initWithObject:(WKTypeRef)object { - toImpl(contextRef)->setShouldPaintNativeControls(b); + self = [super init]; + if (!self) + return nil; + + _object = object; + + return self; } -void WKContextSetInitialHTTPCookieAcceptPolicy(WKContextRef contextRef, WKHTTPCookieAcceptPolicy policy) +- (WKTypeRef)object { - toImpl(contextRef)->setInitialHTTPCookieAcceptPolicy(toHTTPCookieAcceptPolicy(policy)); + return _object.get(); } + +@end + +#endif // defined(__LP64__) && defined(__clang__) diff --git a/Source/WebKit2/UIProcess/API/mac/WKView.mm b/Source/WebKit2/UIProcess/API/mac/WKView.mm index b1470fea9..1d8760988 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKView.mm +++ b/Source/WebKit2/UIProcess/API/mac/WKView.mm @@ -43,7 +43,6 @@ #import "NativeWebKeyboardEvent.h" #import "NativeWebMouseEvent.h" #import "NativeWebWheelEvent.h" -#import "PDFViewController.h" #import "PageClientImpl.h" #import "PasteboardTypes.h" #import "RemoteLayerTreeDrawingAreaProxy.h" @@ -62,10 +61,13 @@ #import "WebEventFactory.h" #import "WebFullScreenManagerProxy.h" #import "WebPage.h" +#import "WebPageGroup.h" #import "WebPageProxy.h" +#import "WebPreferences.h" #import "WebProcessProxy.h" #import "WebSystemInterface.h" #import <QuartzCore/QuartzCore.h> +#import <WebCore/AXObjectCache.h> #import <WebCore/ColorMac.h> #import <WebCore/DragController.h> #import <WebCore/DragData.h> @@ -82,6 +84,8 @@ #import <WebCore/SharedBuffer.h> #import <WebCore/TextAlternativeWithRange.h> #import <WebCore/WebCoreNSStringExtras.h> +#import <WebCore/WebCoreFullScreenPlaceholderView.h> +#import <WebCore/WebCoreFullScreenWindow.h> #import <WebCore/FileSystem.h> #import <WebKitSystemInterface.h> #import <sys/stat.h> @@ -90,9 +94,18 @@ /* API internals. */ #import "WKBrowsingContextControllerInternal.h" -#import "WKBrowsingContextGroupInternal.h" -#import "WKProcessGroupInternal.h" +#import "WKBrowsingContextGroupPrivate.h" +#import "WKProcessGroupPrivate.h" +inline bool isWKContentAnchorRight(WKContentAnchor x) +{ + return x == WKContentAnchorTopRight || x == WKContentAnchorBottomRight; +} + +inline bool isWKContentAnchorBottom(WKContentAnchor x) +{ + return x == WKContentAnchorBottomLeft || x == WKContentAnchorBottomRight; +} @interface NSApplication (WKNSApplicationDetails) - (void)speakString:(NSString *)string; @@ -105,13 +118,6 @@ @end @interface NSWindow (WKNSWindowDetails) -#if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060 -- (NSRect)_growBoxRect; -- (id)_growBoxOwner; -- (void)_setShowOpaqueGrowBoxForOwner:(id)owner; -- (BOOL)_updateGrowBoxForWindowFrameChange; -#endif - - (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect; - (void)_maskRoundedBottomCorners:(NSRect)clipRect; @end @@ -122,7 +128,7 @@ using namespace WebCore; namespace WebKit { typedef id <NSValidatedUserInterfaceItem> ValidationItem; -typedef Vector<RetainPtr<ValidationItem> > ValidationVector; +typedef Vector<RetainPtr<ValidationItem>> ValidationVector; typedef HashMap<String, ValidationVector> ValidationMap; } @@ -142,6 +148,10 @@ struct WKViewInterpretKeyEventsParameters { - (void)_setDrawingAreaSize:(NSSize)size; - (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState; - (BOOL)_shouldUseTiledDrawingArea; + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 +- (void)_setIsWindowOccluded:(BOOL)isWindowOccluded; +#endif @end @interface WKViewData : NSObject { @@ -164,8 +174,6 @@ struct WKViewInterpretKeyEventsParameters { // For asynchronous validation. ValidationMap _validationMap; - OwnPtr<PDFViewController> _pdfViewController; - OwnPtr<FindIndicatorWindow> _findIndicatorWindow; // We keep here the event when resending it to // the application to distinguish the case of a new event from one @@ -203,6 +211,12 @@ struct WKViewInterpretKeyEventsParameters { NSRect _windowBottomCornerIntersectionRect; unsigned _frameSizeUpdatesDisabledCount; + BOOL _shouldDeferViewInWindowChanges; + + BOOL _viewInWindowChangeWasDeferred; + + BOOL _needsViewFrameInWindowCoordinates; + BOOL _didScheduleWindowAndViewFrameUpdate; // Whether the containing window of the WKView has a valid backing store. // The window server invalidates the backing store whenever the window is resized or minimized. @@ -216,7 +230,22 @@ struct WKViewInterpretKeyEventsParameters { String _promisedFilename; String _promisedURL; + // The frame origin can be seen as a position within the layer of painted page content where the + // top left corner of the frame will be positioned. This is usually 0,0 - but if the content + // anchor is set to a corner other than the top left, the origin will implicitly move as the + // the frame size is modified. + NSPoint _frameOrigin; + WKContentAnchor _contentAnchor; + NSSize _intrinsicContentSize; + BOOL _clipsToVisibleRect; + NSRect _contentPreparationRect; + BOOL _useContentPreparationRectForVisibleRect; + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + BOOL _isWindowOccluded; + BOOL _windowOcclusionDetectionEnabled; +#endif } @end @@ -224,7 +253,6 @@ struct WKViewInterpretKeyEventsParameters { @implementation WKViewData @end - @interface WKResponderChainSink : NSResponder { NSResponder *_lastResponderInChain; bool _didReceiveUnhandledCommand; @@ -267,6 +295,9 @@ struct WKViewInterpretKeyEventsParameters { [_data release]; _data = nil; + NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter]; + [workspaceNotificationCenter removeObserver:self name:NSWorkspaceActiveSpaceDidChangeNotification object:nil]; + WebContext::statistics().wkViewCount--; [super dealloc]; @@ -275,7 +306,7 @@ struct WKViewInterpretKeyEventsParameters { - (WKBrowsingContextController *)browsingContextController { if (!_data->_browsingContextController) - _data->_browsingContextController.adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:[self pageRef]]); + _data->_browsingContextController = adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:[self pageRef]]); return _data->_browsingContextController.get(); } @@ -331,8 +362,11 @@ struct WKViewInterpretKeyEventsParameters { if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange) _data->_page->cancelComposition(); - [self _resetTextInputState]; - + + [self _notifyInputContextAboutDiscardedComposition]; + + [self _resetSecureInputState]; + if (!_data->_page->maintainsInactiveSelection()) _data->_page->clearSelection(); @@ -363,27 +397,91 @@ struct WKViewInterpretKeyEventsParameters { return _data->_intrinsicContentSize; } +- (void)prepareContentInRect:(NSRect)rect +{ + _data->_contentPreparationRect = rect; + _data->_useContentPreparationRectForVisibleRect = YES; + + [self _updateViewExposedRect]; +} + +- (void)_updateViewExposedRect +{ + NSRect exposedRect = [self visibleRect]; + + if (_data->_useContentPreparationRectForVisibleRect) + exposedRect = NSUnionRect(_data->_contentPreparationRect, exposedRect); + + _data->_page->viewExposedRectChanged(exposedRect, _data->_clipsToVisibleRect); +} + - (void)setFrameSize:(NSSize)size { if (!NSEqualSizes(size, [self frame].size)) _data->_windowHasValidBackingStore = NO; - [super setFrameSize:size]; + bool frameSizeUpdatesEnabled = ![self frameSizeUpdatesDisabled]; + NSPoint newFrameOrigin; + + // If frame updates are enabled we'll synchronously wait on the repaint, so we can reposition + // the layers back to the origin. If frame updates are disabled then shift the layer position + // so that the currently painted contents remain anchored appropriately. + if (frameSizeUpdatesEnabled) + newFrameOrigin = NSZeroPoint; + else { + newFrameOrigin = _data->_frameOrigin; + if (isWKContentAnchorRight(_data->_contentAnchor)) + newFrameOrigin.x += [self frame].size.width - size.width; + if (isWKContentAnchorBottom(_data->_contentAnchor)) + newFrameOrigin.y += [self frame].size.height - size.height; + } - if (![self frameSizeUpdatesDisabled]) + // If the frame origin has changed then update the layer position. + if (_data->_layerHostingView && !NSEqualPoints(_data->_frameOrigin, newFrameOrigin)) { + _data->_frameOrigin = newFrameOrigin; + CALayer *rootLayer = [[_data->_layerHostingView layer].sublayers objectAtIndex:0]; + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + rootLayer.position = CGPointMake(-newFrameOrigin.x, -newFrameOrigin.y); + [CATransaction commit]; + } + + [super setFrameSize:size]; + + if (frameSizeUpdatesEnabled) { + if (_data->_clipsToVisibleRect) + [self _updateViewExposedRect]; [self _setDrawingAreaSize:size]; + } } - (void)_updateWindowAndViewFrames { - NSWindow *window = [self window]; - ASSERT(window); - - NSRect windowFrameInScreenCoordinates = [window frame]; - NSRect viewFrameInWindowCoordinates = [self convertRect:[self frame] toView:nil]; - NSPoint accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue]; - - _data->_page->windowAndViewFramesChanged(enclosingIntRect(windowFrameInScreenCoordinates), enclosingIntRect(viewFrameInWindowCoordinates), IntPoint(accessibilityPosition)); + if (_data->_clipsToVisibleRect) + [self _updateViewExposedRect]; + + if (_data->_didScheduleWindowAndViewFrameUpdate) + return; + + _data->_didScheduleWindowAndViewFrameUpdate = YES; + + dispatch_async(dispatch_get_main_queue(), ^{ + _data->_didScheduleWindowAndViewFrameUpdate = NO; + + if (!_data->_needsViewFrameInWindowCoordinates && !WebCore::AXObjectCache::accessibilityEnabled()) + return; + + NSRect viewFrameInWindowCoordinates = NSZeroRect; + NSPoint accessibilityPosition = NSZeroPoint; + + if (_data->_needsViewFrameInWindowCoordinates) + viewFrameInWindowCoordinates = [self convertRect:self.frame toView:nil]; + + if (WebCore::AXObjectCache::accessibilityEnabled()) + accessibilityPosition = [[self accessibilityAttributeValue:NSAccessibilityPositionAttribute] pointValue]; + + _data->_page->windowAndViewFramesChanged(viewFrameInWindowCoordinates, accessibilityPosition); + }); } - (void)renewGState @@ -581,13 +679,22 @@ WEBCORE_COMMAND(yankAndSelect) - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType { - BOOL isValidSendType = !sendType || ([PasteboardTypes::forSelection() containsObject:sendType] && !_data->_page->editorState().selectionIsNone); + EditorState editorState = _data->_page->editorState(); + BOOL isValidSendType = NO; + + if (sendType && !editorState.selectionIsNone) { + if (editorState.isInPlugin) + isValidSendType = [sendType isEqualToString:NSStringPboardType]; + else + isValidSendType = [PasteboardTypes::forSelection() containsObject:sendType]; + } + BOOL isValidReturnType = NO; if (!returnType) isValidReturnType = YES; - else if ([PasteboardTypes::forEditing() containsObject:returnType] && _data->_page->editorState().isContentEditable) { + else if ([PasteboardTypes::forEditing() containsObject:returnType] && editorState.isContentEditable) { // We can insert strings in any editable context. We can insert other types, like images, only in rich edit contexts. - isValidReturnType = _data->_page->editorState().isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType]; + isValidReturnType = editorState.isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType]; } if (isValidSendType && isValidReturnType) return self; @@ -970,7 +1077,6 @@ static void speakString(WKStringRef string, WKErrorRef error, void*) - (void)displayIfNeeded { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. In the meantime, // it is necessary to disable scren updates so we get a chance to redraw the corners before this // display is visible. @@ -978,17 +1084,14 @@ static void speakString(WKStringRef string, WKErrorRef error, void*) BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect); if (shouldMaskWindow) NSDisableScreenUpdates(); -#endif [super displayIfNeeded]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 if (shouldMaskWindow) { [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect]; NSEnableScreenUpdates(); _data->_windowBottomCornerIntersectionRect = NSZeroRect; } -#endif } // Events @@ -1403,18 +1506,6 @@ static const short kIOHIDEventTypeScroll = 6; LOG(TextInput, "...done executing saved keypress commands."); } -- (void)_notifyInputContextAboutDiscardedComposition -{ - // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts. - // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key. - // This is not a problem when the window is key, because we discard marked text on resigning first responder. - if (![[self window] isKeyWindow] || self != [[self window] firstResponder]) - return; - - LOG(TextInput, "-> discardMarkedText"); - [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to. -} - - (NSTextInputContext *)inputContext { WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; @@ -1692,7 +1783,6 @@ static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnde _data->_page->dragUpdated(&dragData, [[draggingInfo draggingPasteboard] name]); WebCore::DragSession dragSession = _data->_page->dragSession(); -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 NSInteger numberOfValidItemsForDrop = dragSession.numberOfItemsToBeAccepted; NSDraggingFormation draggingFormation = NSDraggingFormationNone; if (dragSession.mouseIsOverFileInput && numberOfValidItemsForDrop > 0) @@ -1702,7 +1792,7 @@ static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnde [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop]; if ([draggingInfo draggingFormation] != draggingFormation) [draggingInfo setDraggingFormation:draggingFormation]; -#endif + return dragSession.operation; } @@ -1804,57 +1894,6 @@ static void createSandboxExtensionsForFileUpload(NSPasteboard *pasteboard, Sandb } -#if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060 -- (BOOL)_ownsWindowGrowBox -{ - NSWindow* window = [self window]; - if (!window) - return NO; - - NSView *superview = [self superview]; - if (!superview) - return NO; - - NSRect growBoxRect = [window _growBoxRect]; - if (NSIsEmptyRect(growBoxRect)) - return NO; - - NSRect visibleRect = [self visibleRect]; - if (NSIsEmptyRect(visibleRect)) - return NO; - - NSRect visibleRectInWindowCoords = [self convertRect:visibleRect toView:nil]; - if (!NSIntersectsRect(growBoxRect, visibleRectInWindowCoords)) - return NO; - - return YES; -} - -- (BOOL)_updateGrowBoxForWindowFrameChange -{ - // Temporarily enable the resize indicator to make a the _ownsWindowGrowBox calculation work. - BOOL wasShowingIndicator = [[self window] showsResizeIndicator]; - if (!wasShowingIndicator) - [[self window] setShowsResizeIndicator:YES]; - - BOOL ownsGrowBox = [self _ownsWindowGrowBox]; - _data->_page->setWindowResizerSize(ownsGrowBox ? enclosingIntRect([[self window] _growBoxRect]).size() : IntSize()); - - if (ownsGrowBox) - [[self window] _setShowOpaqueGrowBoxForOwner:(_data->_page->hasHorizontalScrollbar() || _data->_page->hasVerticalScrollbar() ? self : nil)]; - else - [[self window] _setShowOpaqueGrowBoxForOwner:nil]; - - // Once WebCore can draw the window resizer, this should read: - // if (wasShowingIndicator) - // [[self window] setShowsResizeIndicator:!ownsGrowBox]; - if (!wasShowingIndicator) - [[self window] setShowsResizeIndicator:NO]; - - return ownsGrowBox; -} -#endif - // FIXME: Use AppKit constants for these when they are available. static NSString * const windowDidChangeBackingPropertiesNotification = @"NSWindowDidChangeBackingPropertiesNotification"; static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOldScaleFactorKey"; @@ -1882,6 +1921,10 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl name:windowDidChangeBackingPropertiesNotification object:window]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeScreen:) name:NSWindowDidChangeScreenNotification object:window]; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeOcclusionState:) + name:NSWindowDidChangeOcclusionStateNotification object:window]; +#endif } } @@ -1897,10 +1940,14 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidDeminiaturizeNotification object:window]; [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMoveNotification object:window]; [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResizeNotification object:window]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowWillOrderOffScreenNotification" object:window]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidOrderOffScreenNotification" object:window]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"_NSWindowDidBecomeVisible" object:window]; [[NSNotificationCenter defaultCenter] removeObserver:self name:windowDidChangeBackingPropertiesNotification object:window]; [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeScreenNotification object:window]; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidChangeOcclusionStateNotification object:window]; +#endif } - (void)viewWillMoveToWindow:(NSWindow *)window @@ -1922,11 +1969,6 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl [self removeWindowObservers]; [self addWindowObserversForWindow:window]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060 - if ([currentWindow _growBoxOwner] == self) - [currentWindow _setShowOpaqueGrowBoxForOwner:nil]; -#endif } - (void)viewDidMoveToWindow @@ -1935,10 +1977,21 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl // update the active state first and then make it visible. If the view is about to be hidden, we hide it first and then // update the active state. if ([self window]) { +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + if (_data->_windowOcclusionDetectionEnabled) + [self _setIsWindowOccluded:([[self window] occlusionState] & NSWindowOcclusionStateVisible) != NSWindowOcclusionStateVisible]; +#endif _data->_windowHasValidBackingStore = NO; + [self doWindowDidChangeScreen]; [self _updateWindowVisibility]; _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow); + + if ([self isDeferringViewInWindowChanges]) { + _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); + _data->_viewInWindowChangeWasDeferred = YES; + } else + _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow); + [self _updateWindowAndViewFrames]; if (!_data->_flagsChangedEventMonitor) { @@ -1952,7 +2005,12 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl } else { [self _updateWindowVisibility]; _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); - _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow); + + if ([self isDeferringViewInWindowChanges]) { + _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); + _data->_viewInWindowChangeWasDeferred = YES; + } else + _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive | WebPageProxy::ViewIsInWindow); [NSEvent removeMonitor:_data->_flagsChangedEventMonitor]; _data->_flagsChangedEventMonitor = nil; @@ -1963,9 +2021,7 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl _data->_endGestureMonitor = nil; } #endif -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 WKHideWordDefinitionWindow(); -#endif } _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]); @@ -1983,9 +2039,6 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl [self _updateSecureInputState]; _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); } - - // Send a change screen to make sure the initial displayID is set - [self doWindowDidChangeScreen]; } - (void)_windowDidChangeScreen:(NSNotification *)notification @@ -2057,6 +2110,16 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl _data->_page->setIntrinsicDeviceScaleFactor(newBackingScaleFactor); } +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 +- (void)_windowDidChangeOcclusionState:(NSNotification *)notification +{ + if (!_data->_windowOcclusionDetectionEnabled) + return; + + [self _setIsWindowOccluded:([self.window occlusionState] & NSWindowOcclusionStateVisible) != NSWindowOcclusionStateVisible]; +} +#endif + static void drawPageBackground(CGContextRef context, WebPageProxy* page, const IntRect& rect) { if (!page->drawsBackground()) @@ -2099,7 +2162,7 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I // If the window doesn't have a valid backing store, we need to fill the parts of the page that we // didn't paint with the background color (white or clear), to avoid garbage in those areas. - if (!_data->_windowHasValidBackingStore) { + if (!_data->_windowHasValidBackingStore || !drawingArea->hasReceivedFirstUpdate()) { Vector<IntRect> unpaintedRects = unpaintedRegion.rects(); for (size_t i = 0; i < unpaintedRects.size(); ++i) drawPageBackground(context, _data->_page.get(), unpaintedRects[i]); @@ -2146,11 +2209,16 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I drawingArea->colorSpaceDidChange(); } +- (void)_activeSpaceDidChange:(NSNotification *)notification +{ + _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); +} + - (void)_accessibilityRegisterUIProcessTokens { // Initialize remote accessibility when the window connection has been established. NSData *remoteElementToken = WKAXRemoteTokenForElement(self); - NSData *remoteWindowToken = WKAXRemoteTokenForElement([self accessibilityAttributeValue:NSAccessibilityWindowAttribute]); + NSData *remoteWindowToken = WKAXRemoteTokenForElement([self window]); CoreIPC::DataReference elementToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteElementToken bytes]), [remoteElementToken length]); CoreIPC::DataReference windowToken = CoreIPC::DataReference(reinterpret_cast<const uint8_t*>([remoteWindowToken bytes]), [remoteWindowToken length]); _data->_page->registerUIProcessAccessibilityTokens(elementToken, windowToken); @@ -2172,11 +2240,20 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I WKAXRegisterRemoteProcess(registerProcess, pid); } -- (id)accessibilityFocusedUIElement +- (void)enableAccessibilityIfNecessary { - if (_data->_pdfViewController) - return NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView()); + if (WebCore::AXObjectCache::accessibilityEnabled()) + return; + + // After enabling accessibility update the window frame on the web process so that the + // correct accessibility position is transmitted (when AX is off, that position is not calculated). + WebCore::AXObjectCache::enableAccessibility(); + [self _updateWindowAndViewFrames]; +} +- (id)accessibilityFocusedUIElement +{ + [self enableAccessibilityIfNecessary]; return _data->_remoteAccessibilityChild.get(); } @@ -2187,20 +2264,18 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I - (id)accessibilityHitTest:(NSPoint)point { - if (_data->_pdfViewController) - return [_data->_pdfViewController->pdfView() accessibilityHitTest:point]; - + [self enableAccessibilityIfNecessary]; return _data->_remoteAccessibilityChild.get(); } - (id)accessibilityAttributeValue:(NSString*)attribute { + [self enableAccessibilityIfNecessary]; + if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) { id child = nil; - if (_data->_pdfViewController) - child = NSAccessibilityUnignoredDescendant(_data->_pdfViewController->pdfView()); - else if (_data->_remoteAccessibilityChild) + if (_data->_remoteAccessibilityChild) child = _data->_remoteAccessibilityChild.get(); if (!child) @@ -2245,15 +2320,9 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I - (float)_intrinsicDeviceScaleFactor { NSWindow *window = [self window]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 if (window) return [window backingScaleFactor]; return [[NSScreen mainScreen] backingScaleFactor]; -#else - if (window) - return [window userSpaceScaleFactor]; - return [[NSScreen mainScreen] userSpaceScaleFactor]; -#endif } - (void)_setDrawingAreaSize:(NSSize)size @@ -2261,7 +2330,13 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I if (!_data->_page->drawingArea()) return; - _data->_page->drawingArea()->setSize(IntSize(size), IntSize(_data->_resizeScrollOffset)); + NSSize layerOffset = NSMakeSize(_data->_frameOrigin.x, _data->_frameOrigin.y); + if (isWKContentAnchorRight(_data->_contentAnchor)) + layerOffset.width += [self frame].size.width - size.width; + if (isWKContentAnchorBottom(_data->_contentAnchor)) + layerOffset.height += [self frame].size.height - size.height; + + _data->_page->drawingArea()->setSize(IntSize(size), IntSize(layerOffset), IntSize(_data->_resizeScrollOffset)); _data->_resizeScrollOffset = NSZeroSize; } @@ -2278,6 +2353,17 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I } #endif +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 +- (void)_setIsWindowOccluded:(BOOL)isWindowOccluded +{ + if (_data->_isWindowOccluded == isWindowOccluded) + return; + + _data->_isWindowOccluded = isWindowOccluded; + _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); +} +#endif + @end @implementation WKView (Internal) @@ -2338,6 +2424,18 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I [self _accessibilityRegisterUIProcessTokens]; } +- (void)_preferencesDidChange +{ + BOOL needsViewFrameInWindowCoordinates = _data->_page->pageGroup()->preferences()->pluginsEnabled(); + + if (!!needsViewFrameInWindowCoordinates == !!_data->_needsViewFrameInWindowCoordinates) + return; + + _data->_needsViewFrameInWindowCoordinates = needsViewFrameInWindowCoordinates; + if ([self window]) + [self _updateWindowAndViewFrames]; +} + - (void)_setCursor:(NSCursor *)cursor { if ([NSCursor currentCursor] == cursor) @@ -2578,7 +2676,7 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I if (rootLayer) { if (!_data->_layerHostingView) { // Create an NSView that will host our layer tree. - _data->_layerHostingView.adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]); + _data->_layerHostingView = adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]); [_data->_layerHostingView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; @@ -2602,6 +2700,7 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I [_data->_layerHostingView setWantsLayer:NO]; _data->_layerHostingView = nullptr; + _data->_frameOrigin = NSZeroPoint; } } @@ -2652,57 +2751,6 @@ static void drawPageBackground(CGContextRef context, WebPageProxy* page, const I [self _setPluginComplexTextInputState:pluginComplexTextInputState]; } -- (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation -{ - bool hadPDFView = _data->_pdfViewController; - _data->_pdfViewController = nullptr; - - if (pageHasCustomRepresentation) - _data->_pdfViewController = PDFViewController::create(self); - - if (pageHasCustomRepresentation != hadPDFView) - _data->_page->drawingArea()->pageCustomRepresentationChanged(); -} - -- (void)_didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:(const String&)suggestedFilename dataReference:(const CoreIPC::DataReference&)dataReference -{ - ASSERT(_data->_pdfViewController); - - _data->_pdfViewController->setPDFDocumentData(_data->_page->mainFrame()->mimeType(), suggestedFilename, dataReference); -} - -- (double)_customRepresentationZoomFactor -{ - if (!_data->_pdfViewController) - return 1; - - return _data->_pdfViewController->zoomFactor(); -} - -- (void)_setCustomRepresentationZoomFactor:(double)zoomFactor -{ - if (!_data->_pdfViewController) - return; - - _data->_pdfViewController->setZoomFactor(zoomFactor); -} - -- (void)_findStringInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count -{ - if (!_data->_pdfViewController) - return; - - _data->_pdfViewController->findString(string, options, count); -} - -- (void)_countStringMatchesInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count -{ - if (!_data->_pdfViewController) - return; - - _data->_pdfViewController->countStringMatches(string, options, count); -} - - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag { IntSize size([image size]); @@ -2732,7 +2780,7 @@ static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension { NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName]; - RetainPtr<NSMutableArray> types(AdoptNS, [[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]); + RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]); [types.get() addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()]; [pasteboard declareTypes:types.get() owner:self]; @@ -2814,8 +2862,8 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) RetainPtr<NSData> data; if (_data->_promisedImage) { - data.adoptNS(_data->_promisedImage->data()->createNSData()); - wrapper.adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]); + data = adoptNS(_data->_promisedImage->data()->createNSData()); + wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]); [wrapper.get() setPreferredFilename:_data->_promisedFilename]; } @@ -2864,38 +2912,24 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) _data->_inSecureInputState = isInPasswordField; } -- (void)_updateTextInputStateIncludingSecureInputState:(BOOL)updateSecureInputState +- (void)_resetSecureInputState { - const EditorState& editorState = _data->_page->editorState(); - if (updateSecureInputState) { - // This is a temporary state when editing. Flipping secure input state too quickly can expose race conditions. - if (!editorState.selectionIsNone) - [self _updateSecureInputState]; - } - - if (!editorState.hasComposition || editorState.shouldIgnoreCompositionSelectionChange) - return; - - _data->_page->cancelComposition(); - - [self _notifyInputContextAboutDiscardedComposition]; -} - -- (void)_resetTextInputState -{ - [self _notifyInputContextAboutDiscardedComposition]; - if (_data->_inSecureInputState) { DisableSecureEventInput(); _data->_inSecureInputState = NO; } } -- (void)_didChangeScrollbarsForMainFrame +- (void)_notifyInputContextAboutDiscardedComposition { -#if __MAC_OS_X_VERSION_MIN_REQUIRED == 1060 - [self _updateGrowBoxForWindowFrameChange]; -#endif + // <rdar://problem/9359055>: -discardMarkedText can only be called for active contexts. + // FIXME: We fail to ever notify the input context if something (e.g. a navigation) happens while the window is not key. + // This is not a problem when the window is key, because we discard marked text on resigning first responder. + if (![[self window] isKeyWindow] || self != [[self window] firstResponder]) + return; + + LOG(TextInput, "-> discardMarkedText"); + [[super inputContext] discardMarkedText]; // Inform the input method that we won't have an inline input area despite having been asked to. } #if ENABLE(FULLSCREEN_API) @@ -2907,7 +2941,7 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) - (WKFullScreenWindowController*)fullScreenWindowController { if (!_data->_fullScreenWindowController) { - _data->_fullScreenWindowController.adoptNS([[WKFullScreenWindowController alloc] init]); + _data->_fullScreenWindowController = adoptNS([[WKFullScreenWindowController alloc] initWithWindow:[self createFullScreenWindow]]); [_data->_fullScreenWindowController.get() setWebView:self]; } return _data->_fullScreenWindowController.get(); @@ -2926,7 +2960,7 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) { // The sink does two things: 1) Tells us if the responder went unhandled, and // 2) prevents any NSBeep; we don't ever want to beep here. - RetainPtr<WKResponderChainSink> sink(AdoptNS, [[WKResponderChainSink alloc] initWithResponderChain:self]); + RetainPtr<WKResponderChainSink> sink = adoptNS([[WKResponderChainSink alloc] initWithResponderChain:self]); [super doCommandBySelector:selector]; [sink.get() detach]; return ![sink.get() didReceiveUnhandledCommand]; @@ -2934,14 +2968,21 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) - (void)_setIntrinsicContentSize:(NSSize)intrinsicContentSize { - _data->_intrinsicContentSize = intrinsicContentSize; + // If the intrinsic content size is less than the minimum layout width, the content flowed to fit, + // so we can report that that dimension is flexible. If not, we need to report our intrinsic width + // so that autolayout will know to provide space for us. + + NSSize intrinsicContentSizeAcknowledgingFlexibleWidth = intrinsicContentSize; + if (intrinsicContentSize.width < _data->_page->minimumLayoutSize().width()) + intrinsicContentSizeAcknowledgingFlexibleWidth.width = NSViewNoInstrinsicMetric; + + _data->_intrinsicContentSize = intrinsicContentSizeAcknowledgingFlexibleWidth; [self invalidateIntrinsicContentSize]; } - (void)_cacheWindowBottomCornerRect { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. + // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. NSWindow *window = [self window]; if (!window) return; @@ -2949,7 +2990,6 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]]; if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect)) [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]]; -#endif } - (NSInteger)spellCheckerDocumentTag @@ -2976,6 +3016,15 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) return _data->_page->suppressVisibilityUpdates(); } +- (BOOL)_isWindowOccluded +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + return _data->_isWindowOccluded; +#else + return NO; +#endif +} + @end @implementation WKView (Private) @@ -3006,14 +3055,10 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) // Legacy style scrollbars have design details that rely on tracking the mouse all the time. NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 if (WKRecommendedScrollerStyle() == NSScrollerStyleLegacy) options |= NSTrackingActiveAlways; else options |= NSTrackingActiveInKeyWindow; -#else - options |= NSTrackingActiveInKeyWindow; -#endif NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame options:options @@ -3033,9 +3078,20 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) #endif _data->_mouseDownEvent = nil; _data->_ignoringMouseDraggedEvents = NO; + _data->_clipsToVisibleRect = NO; + _data->_useContentPreparationRectForVisibleRect = NO; _data->_intrinsicContentSize = NSMakeSize(NSViewNoInstrinsicMetric, NSViewNoInstrinsicMetric); +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + _data->_isWindowOccluded = NO; + _data->_windowOcclusionDetectionEnabled = YES; +#endif + + _data->_needsViewFrameInWindowCoordinates = _data->_page->pageGroup()->preferences()->pluginsEnabled(); + _data->_frameOrigin = NSZeroPoint; + _data->_contentAnchor = WKContentAnchorTopLeft; + [self _registerDraggedTypes]; if ([self _shouldUseTiledDrawingArea]) { @@ -3047,6 +3103,9 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) WebContext::statistics().wkViewCount++; + NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter]; + [workspaceNotificationCenter addObserver:self selector:@selector(_activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil]; + return self; } @@ -3058,7 +3117,16 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) - (void)updateLayer { - self.layer.backgroundColor = CGColorGetConstantColor(kCGColorWhite); + if ([self drawsBackground] && ![self drawsTransparentBackground]) + self.layer.backgroundColor = CGColorGetConstantColor(kCGColorWhite); + else + self.layer.backgroundColor = CGColorGetConstantColor(kCGColorClear); + + // If asynchronous geometry updates have been sent by forceAsyncDrawingAreaSizeUpdate, + // then subsequent calls to setFrameSize should not result in us waiting for the did + // udpate response if setFrameSize is called. + if ([self frameSizeUpdatesDisabled]) + return; if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea()) drawingArea->waitForPossibleGeometryUpdate(); @@ -3080,22 +3148,15 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) { LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data()); - // Only the top frame can currently contain a PDF view. - if (_data->_pdfViewController) { - if (!toImpl(frameRef)->isMainFrame()) - return 0; - return _data->_pdfViewController->makePrintOperation(printInfo); - } else { - // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows - // printing), this function should return nil. - RetainPtr<WKPrintingView> printingView(AdoptNS, [[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]); - // NSPrintOperation takes ownership of the view. - NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get()]; - [printOperation setCanSpawnSeparateThread:YES]; - [printOperation setJobTitle:toImpl(frameRef)->title()]; - printingView->_printOperation = printOperation; - return printOperation; - } + // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows + // printing), this function should return nil. + RetainPtr<WKPrintingView> printingView = adoptNS([[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]); + // NSPrintOperation takes ownership of the view. + NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get() printInfo:printInfo]; + [printOperation setCanSpawnSeparateThread:YES]; + [printOperation setJobTitle:toImpl(frameRef)->title()]; + printingView->_printOperation = printOperation; + return printOperation; } - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset @@ -3116,8 +3177,11 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) if (!_data->_frameSizeUpdatesDisabledCount) return; - if (!(--_data->_frameSizeUpdatesDisabledCount)) + if (!(--_data->_frameSizeUpdatesDisabledCount)) { + if (_data->_clipsToVisibleRect) + [self _updateViewExposedRect]; [self _setDrawingAreaSize:[self frame].size]; + } } - (BOOL)frameSizeUpdatesDisabled @@ -3136,19 +3200,232 @@ static NSString *pathWithUniqueFilenameForPath(NSString *path) + (void)hideWordDefinitionWindow { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 WKHideWordDefinitionWindow(); -#endif } - (CGFloat)minimumLayoutWidth { - return _data->_page->minimumLayoutWidth(); + static BOOL loggedDeprecationWarning = NO; + + if (!loggedDeprecationWarning) { + NSLog(@"Please use minimumSizeForAutoLayout instead of minimumLayoutWidth."); + loggedDeprecationWarning = YES; + } + + return self.minimumSizeForAutoLayout.width; } - (void)setMinimumLayoutWidth:(CGFloat)minimumLayoutWidth { - _data->_page->setMinimumLayoutWidth(minimumLayoutWidth); + static BOOL loggedDeprecationWarning = NO; + + if (!loggedDeprecationWarning) { + NSLog(@"Please use setMinimumSizeForAutoLayout: instead of setMinimumLayoutWidth:."); + loggedDeprecationWarning = YES; + } + + [self setMinimumWidthForAutoLayout:minimumLayoutWidth]; +} + +- (CGFloat)minimumWidthForAutoLayout +{ + static BOOL loggedDeprecationWarning = NO; + + if (!loggedDeprecationWarning) { + NSLog(@"Please use minimumSizeForAutoLayout instead of minimumWidthForAutoLayout."); + loggedDeprecationWarning = YES; + } + + return self.minimumSizeForAutoLayout.width; +} + +- (void)setMinimumWidthForAutoLayout:(CGFloat)minimumLayoutWidth +{ + static BOOL loggedDeprecationWarning = NO; + + if (!loggedDeprecationWarning) { + NSLog(@"Please use setMinimumSizeForAutoLayout: instead of setMinimumWidthForAutoLayout:"); + loggedDeprecationWarning = YES; + } + + self.minimumSizeForAutoLayout = NSMakeSize(minimumLayoutWidth, self.minimumSizeForAutoLayout.height); +} + +- (NSSize)minimumSizeForAutoLayout +{ + return _data->_page->minimumLayoutSize(); +} + +- (void)setMinimumSizeForAutoLayout:(NSSize)minimumSizeForAutoLayout +{ + BOOL expandsToFit = minimumSizeForAutoLayout.width > 0; + + _data->_page->setMinimumLayoutSize(IntSize(minimumSizeForAutoLayout.width, minimumSizeForAutoLayout.height)); + _data->_page->setMainFrameIsScrollable(!expandsToFit); + + [self setShouldClipToVisibleRect:expandsToFit]; +} + +- (BOOL)shouldClipToVisibleRect +{ + return _data->_clipsToVisibleRect; +} + +- (void)setShouldClipToVisibleRect:(BOOL)clipsToVisibleRect +{ + _data->_clipsToVisibleRect = clipsToVisibleRect; + [self _updateViewExposedRect]; +} + +- (NSColor *)underlayColor +{ + Color webColor = _data->_page->underlayColor(); + if (!webColor.isValid()) + return nil; + + return nsColor(webColor); +} + +- (void)setUnderlayColor:(NSColor *)underlayColor +{ + _data->_page->setUnderlayColor(colorFromNSColor(underlayColor)); +} + +- (NSView*)fullScreenPlaceholderView +{ +#if ENABLE(FULLSCREEN_API) + if (_data->_fullScreenWindowController && [_data->_fullScreenWindowController isFullScreen]) + return [_data->_fullScreenWindowController webViewPlaceholder]; +#endif + return nil; +} + +- (void)beginDeferringViewInWindowChanges +{ + if (_data->_shouldDeferViewInWindowChanges) { + NSLog(@"beginDeferringViewInWindowChanges was called while already deferring view-in-window changes!"); + return; + } + + _data->_shouldDeferViewInWindowChanges = YES; +} + +- (void)endDeferringViewInWindowChanges +{ + if (!_data->_shouldDeferViewInWindowChanges) { + NSLog(@"endDeferringViewInWindowChanges was called without beginDeferringViewInWindowChanges!"); + return; + } + + _data->_shouldDeferViewInWindowChanges = NO; + + if (_data->_viewInWindowChangeWasDeferred) { + _data->_page->viewStateDidChange(WebPageProxy::ViewIsInWindow); + _data->_viewInWindowChangeWasDeferred = NO; + } +} + +- (void)endDeferringViewInWindowChangesSync +{ + if (!_data->_shouldDeferViewInWindowChanges) { + NSLog(@"endDeferringViewInWindowChangesSync was called without beginDeferringViewInWindowChanges!"); + return; + } + + PageClient* pageClient = _data->_pageClient.get(); + bool hasPendingViewInWindowChange = _data->_viewInWindowChangeWasDeferred && _data->_page->isInWindow() != pageClient->isViewInWindow(); + + [self endDeferringViewInWindowChanges]; + + if (hasPendingViewInWindowChange) + _data->_page->waitForDidUpdateInWindowState(); +} + +- (BOOL)isDeferringViewInWindowChanges +{ + return _data->_shouldDeferViewInWindowChanges; +} + +- (BOOL)windowOcclusionDetectionEnabled +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + return _data->_windowOcclusionDetectionEnabled; +#else + return NO; +#endif +} + +- (void)setWindowOcclusionDetectionEnabled:(BOOL)flag +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + if (_data->_windowOcclusionDetectionEnabled == flag) + return; + + _data->_windowOcclusionDetectionEnabled = flag; + + if (flag) { + // When enabling window occlusion detection, update the view's current occluded state + // immediately, as the notification only fires when it changes. + if (self.window) + [self _setIsWindowOccluded:([self.window occlusionState] & NSWindowOcclusionStateVisible) != NSWindowOcclusionStateVisible]; + } else { + // When disabling window occlusion detection, force the view to think it is not occluded, + // as it may already be occluded at the time of calling. + [self _setIsWindowOccluded:NO]; + } +#endif +} + +- (void)setContentAnchor:(WKContentAnchor)contentAnchor +{ + _data->_contentAnchor = contentAnchor; +} + +- (WKContentAnchor)contentAnchor +{ + return _data->_contentAnchor; +} + +// This method forces a drawing area geometry update, even if frame size updates are disabled. +// The updated is performed asynchronously; we don't wait for the geometry update before returning. +// The area drawn need not match the current frame size - if it differs it will be anchored to the +// frame according to the current contentAnchor. +- (void)forceAsyncDrawingAreaSizeUpdate:(NSSize)size +{ + if (_data->_clipsToVisibleRect) + [self _updateViewExposedRect]; + [self _setDrawingAreaSize:size]; + + // If a geometry update is pending the new update won't be sent. Poll without waiting for any + // pending did-update message now, such that the new update can be sent. We do so after setting + // the drawing area size such that the latest update is sent. + if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea()) + drawingArea->waitForPossibleGeometryUpdate(0); +} + +- (void)waitForAsyncDrawingAreaSizeUpdate +{ + if (DrawingAreaProxy* drawingArea = _data->_page->drawingArea()) { + // If a geometry update is still pending then the action of recieving the + // first geometry update may result in another update being scheduled - + // we should wait for this to complete too. + drawingArea->waitForPossibleGeometryUpdate(DrawingAreaProxy::didUpdateBackingStoreStateTimeout * 0.5); + drawingArea->waitForPossibleGeometryUpdate(DrawingAreaProxy::didUpdateBackingStoreStateTimeout * 0.5); + } +} + +- (NSWindow*)createFullScreenWindow +{ +#if ENABLE(FULLSCREEN_API) +#if __MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 + NSRect contentRect = NSZeroRect; +#else + NSRect contentRect = [[NSScreen mainScreen] frame]; +#endif + return [[[WebCoreFullScreenWindow alloc] initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO] autorelease]; +#else + return nil; +#endif } @end diff --git a/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h b/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h index 9b02947a3..8e62c576a 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h +++ b/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h @@ -55,6 +55,7 @@ namespace WebKit { - (void)_processDidCrash; - (void)_pageClosed; - (void)_didRelaunchProcess; +- (void)_preferencesDidChange; - (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip; - (void)_setCursor:(NSCursor *)cursor; - (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState; @@ -73,19 +74,11 @@ namespace WebKit { - (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier; - (void)_setPluginComplexTextInputState:(WebKit::PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier; -- (void)_setPageHasCustomRepresentation:(BOOL)pageHasCustomRepresentation; -- (void)_didFinishLoadingDataForCustomRepresentationWithSuggestedFilename:(const String&)suggestedFilename dataReference:(const CoreIPC::DataReference&)dataReference; -- (double)_customRepresentationZoomFactor; -- (void)_setCustomRepresentationZoomFactor:(double)zoomFactor; -- (void)_findStringInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count; -- (void)_countStringMatchesInCustomRepresentation:(NSString *)string withFindOptions:(WebKit::FindOptions)options maxMatchCount:(NSUInteger)count; - (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag; - (void)_setPromisedData:(WebCore::Image *)image withFileName:(NSString *)filename withExtension:(NSString *)extension withTitle:(NSString *)title withURL:(NSString *)url withVisibleURL:(NSString *)visibleUrl withArchive:(WebCore::SharedBuffer*) archiveBuffer forPasteboard:(NSString *)pasteboardName; - (void)_updateSecureInputState; -- (void)_updateTextInputStateIncludingSecureInputState:(BOOL)updateSecureInputState; -- (void)_resetTextInputState; - -- (void)_didChangeScrollbarsForMainFrame; +- (void)_resetSecureInputState; +- (void)_notifyInputContextAboutDiscardedComposition; - (WebKit::ColorSpaceData)_colorSpace; @@ -103,4 +96,6 @@ namespace WebKit { - (void)_setSuppressVisibilityUpdates:(BOOL)suppressVisibilityUpdates; - (BOOL)_suppressVisibilityUpdates; +- (BOOL)_isWindowOccluded; + @end diff --git a/Source/WebKit2/UIProcess/API/mac/WKViewPrivate.h b/Source/WebKit2/UIProcess/API/mac/WKViewPrivate.h index 2161eb786..a9ff9d30f 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKViewPrivate.h +++ b/Source/WebKit2/UIProcess/API/mac/WKViewPrivate.h @@ -25,11 +25,19 @@ #import <WebKit2/WKView.h> +typedef enum { + WKContentAnchorTopLeft, + WKContentAnchorTopRight, + WKContentAnchorBottomLeft, + WKContentAnchorBottomRight, +} WKContentAnchor; + @interface WKView (Private) /* C SPI support. */ @property(readonly) WKPageRef pageRef; +@property WKContentAnchor contentAnchor; - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef; - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef relatedToPage:(WKPageRef)relatedPage; @@ -51,5 +59,24 @@ + (void)hideWordDefinitionWindow; @property (readwrite) CGFloat minimumLayoutWidth; +@property (readwrite) CGFloat minimumWidthForAutoLayout; +@property (readwrite) NSSize minimumSizeForAutoLayout; +@property (readwrite) BOOL shouldClipToVisibleRect; + +@property(copy, nonatomic) NSColor *underlayColor; + +- (NSView*)fullScreenPlaceholderView; +- (NSWindow*)createFullScreenWindow; + +- (void)beginDeferringViewInWindowChanges; +- (void)endDeferringViewInWindowChanges; +- (void)endDeferringViewInWindowChangesSync; +- (BOOL)isDeferringViewInWindowChanges; + +- (BOOL)windowOcclusionDetectionEnabled; +- (void)setWindowOcclusionDetectionEnabled:(BOOL)flag; + +- (void)forceAsyncDrawingAreaSizeUpdate:(NSSize)size; +- (void)waitForAsyncDrawingAreaSizeUpdate; @end diff --git a/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate.cpp b/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate.cpp index 19f14d5c4..a10c89da4 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate.cpp @@ -27,6 +27,7 @@ #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QMimeDatabase> +#include <QtCore/QUrl> QQuickUrlSchemeDelegate::QQuickUrlSchemeDelegate(QObject* parent) : QObject(parent) diff --git a/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate_p.h b/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate_p.h index 596d3c266..087cb29b7 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickurlschemedelegate_p.h @@ -23,11 +23,11 @@ #include "qwebkitglobal.h" #include <QObject> -#include <QtCore/QUrl> #include <QtQuick/qquickitem.h> class QQuickNetworkRequest; class QQuickNetworkReply; +class QUrl; class QWEBKIT_EXPORT QQuickUrlSchemeDelegate : public QObject { Q_OBJECT diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebpage.cpp b/Source/WebKit2/UIProcess/API/qt/qquickwebpage.cpp index a7d74b2e2..e8e646a7f 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebpage.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebpage.cpp @@ -21,16 +21,16 @@ #include "config.h" #include "qquickwebpage_p.h" -#include "LayerTreeCoordinatorProxy.h" -#include "LayerTreeRenderer.h" #include "QtWebPageEventHandler.h" #include "QtWebPageSGNode.h" #include "TransformationMatrix.h" -#include "WebPageProxy.h" #include "qquickwebpage_p_p.h" #include "qquickwebview_p.h" +#include "qquickwebview_p_p.h" #include "qwebkittest_p.h" #include <QQuickWindow> +#include <WKPage.h> +#include <WebCore/CoordinatedGraphicsScene.h> using namespace WebKit; @@ -54,43 +54,34 @@ QQuickWebPage::~QQuickWebPage() QQuickWebPagePrivate::QQuickWebPagePrivate(QQuickWebPage* q, QQuickWebView* viewportItem) : q(q) , viewportItem(viewportItem) - , webPageProxy(0) , paintingIsInitialized(false) , contentsScale(1) { } -void QQuickWebPagePrivate::initialize(WebKit::WebPageProxy* webPageProxy) -{ - this->webPageProxy = webPageProxy; - eventHandler.reset(new QtWebPageEventHandler(toAPI(webPageProxy), q, viewportItem)); -} - void QQuickWebPagePrivate::paint(QPainter* painter) { - if (!webPageProxy->drawingArea()) - return; - - LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy = webPageProxy->drawingArea()->layerTreeCoordinatorProxy(); - if (layerTreeCoordinatorProxy->layerTreeRenderer()) - layerTreeCoordinatorProxy->layerTreeRenderer()->paintToGraphicsContext(painter); + if (WebCore::CoordinatedGraphicsScene* scene = QQuickWebViewPrivate::get(viewportItem)->coordinatedGraphicsScene()) + scene->paintToGraphicsContext(painter); } + QSGNode* QQuickWebPage::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*) { - if (!d->webPageProxy->drawingArea()) - return oldNode; + QQuickWebViewPrivate* webViewPrivate = QQuickWebViewPrivate::get(d->viewportItem); - LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy = d->webPageProxy->drawingArea()->layerTreeCoordinatorProxy(); - LayerTreeRenderer* renderer = layerTreeCoordinatorProxy->layerTreeRenderer(); + WebCore::CoordinatedGraphicsScene* scene = webViewPrivate->coordinatedGraphicsScene(); + if (!scene) + return oldNode; QtWebPageSGNode* node = static_cast<QtWebPageSGNode*>(oldNode); const QWindow* window = this->window(); ASSERT(window); - if (window && d->webPageProxy->deviceScaleFactor() != window->devicePixelRatio()) { - d->webPageProxy->setIntrinsicDeviceScaleFactor(window->devicePixelRatio()); + WKPageRef pageRef = webViewPrivate->webPage.get(); + if (window && WKPageGetBackingScaleFactor(pageRef) != window->devicePixelRatio()) { + WKPageSetCustomBackingScaleFactor(pageRef, window->devicePixelRatio()); // This signal is queued since if we are running a threaded renderer. This might cause failures // if tests are reading the new value between the property change and the signal emission. emit d->viewportItem->experimental()->test()->devicePixelRatioChanged(); @@ -99,22 +90,17 @@ QSGNode* QQuickWebPage::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*) if (!node) node = new QtWebPageSGNode; - node->setRenderer(renderer); + node->setCoordinatedGraphicsScene(scene); node->setScale(d->contentsScale); node->setDevicePixelRatio(window->devicePixelRatio()); - QColor backgroundColor = d->webPageProxy->drawsTransparentBackground() ? Qt::transparent : Qt::white; + QColor backgroundColor = webViewPrivate->transparentBackground() ? Qt::transparent : Qt::white; QRectF backgroundRect(QPointF(0, 0), d->contentsSize); node->setBackground(backgroundRect, backgroundColor); return node; } -QtWebPageEventHandler* QQuickWebPage::eventHandler() const -{ - return d->eventHandler.data(); -} - void QQuickWebPage::setContentsSize(const QSizeF& size) { if (size.isEmpty() || d->contentsSize == size) @@ -169,10 +155,6 @@ void QQuickWebPagePrivate::updateSize() { QSizeF scaledSize = contentsSize * contentsScale; - DrawingAreaProxy* drawingArea = webPageProxy->drawingArea(); - if (drawingArea && drawingArea->layerTreeCoordinatorProxy()) - drawingArea->layerTreeCoordinatorProxy()->setContentsSize(WebCore::FloatSize(contentsSize)); - q->setSize(scaledSize); if (viewportItem->experimental()->flickableViewportEnabled()) { diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p.h b/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p.h index 3a112d62b..e2aaa6c38 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p.h @@ -28,11 +28,6 @@ class QQuickWebPagePrivate; class QQuickWebView; -class QWebPreferences; - -namespace WebKit { -class QtWebPageEventHandler; -} class QWEBKIT_EXPORT QQuickWebPage : public QQuickItem { Q_OBJECT @@ -48,8 +43,6 @@ public: QTransform transformFromItem() const; QTransform transformToItem() const; - WebKit::QtWebPageEventHandler* eventHandler() const; - protected: virtual QSGNode* updatePaintNode(QSGNode*, UpdatePaintNodeData*); diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p_p.h b/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p_p.h index c7ac86c3d..9a04b3f03 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebpage_p_p.h @@ -24,27 +24,19 @@ #include "qquickwebpage_p.h" #include <QTransform> -namespace WebKit { -class WebPageProxy; -class QtWebPageEventHandler; -} +class QQuickWebViewPrivate; class QQuickWebPagePrivate { public: QQuickWebPagePrivate(QQuickWebPage* q, QQuickWebView* viewportItem); ~QQuickWebPagePrivate(); - void initialize(WebKit::WebPageProxy*); - void updateSize(); void paint(QPainter*); void resetPaintNode(); - - QScopedPointer<WebKit::QtWebPageEventHandler> eventHandler; QQuickWebPage* const q; QQuickWebView* const viewportItem; - WebKit::WebPageProxy* webPageProxy; bool paintingIsInitialized; QSizeF contentsSize; diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp b/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp index 2806ce5d5..ab3045834 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp @@ -1,5 +1,7 @@ /* * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) + * Copyright (c) 2012 Hewlett-Packard Development Company, L.P. + * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -21,6 +23,7 @@ #include "config.h" #include "qquickwebview_p.h" +#include "CoordinatedLayerTreeHostProxy.h" #include "DownloadProxy.h" #include "DrawingAreaProxyImpl.h" #include "PageViewportControllerClientQt.h" @@ -30,9 +33,10 @@ #include "QtWebError.h" #include "QtWebIconDatabaseClient.h" #include "QtWebPageEventHandler.h" -#include "QtWebPageLoadClient.h" #include "QtWebPagePolicyClient.h" #include "WebBackForwardList.h" +#include "WebContext.h" +#include "WebFindOptions.h" #if ENABLE(INSPECTOR_SERVER) #include "WebInspectorProxy.h" #include "WebInspectorServer.h" @@ -42,6 +46,7 @@ #endif #include "WebPageGroup.h" #include "WebPreferences.h" +#include "qglobal.h" #include "qquicknetworkreply_p.h" #include "qquicknetworkrequest_p.h" #include "qquickwebpage_p_p.h" @@ -58,13 +63,22 @@ #include <JavaScriptCore/JSBase.h> #include <JavaScriptCore/JSRetainPtr.h> #include <QDateTime> +#include <QMap> #include <QtCore/QFile> #include <QtQml/QJSValue> #include <QtQuick/QQuickView> +#include <WKNumber.h> #include <WKOpenPanelResultListener.h> +#include <WKPageGroup.h> +#include <WKPreferences.h> #include <WKSerializedScriptValue.h> +#include <WKString.h> +#include <WKStringQt.h> +#include <WKURLQt.h> +#include <WebCore/CoordinatedGraphicsScene.h> #include <WebCore/IntPoint.h> #include <WebCore/IntRect.h> +#include <limits> #include <wtf/Assertions.h> #include <wtf/MainThread.h> #include <wtf/Vector.h> @@ -78,6 +92,15 @@ static const int kAxisLockSampleCount = 5; static const qreal kAxisLockVelocityThreshold = 300; static const qreal kAxisLockVelocityDirectionThreshold = 50; +typedef QMap<WKPageRef, QQuickWebViewPrivate*> PageToViewMap; +Q_GLOBAL_STATIC(PageToViewMap, pageToView) + +static inline QQuickWebViewPrivate* toQQuickWebViewPrivate(const void* clientInfo) +{ + ASSERT(clientInfo); + return reinterpret_cast<QQuickWebViewPrivate*>(const_cast<void*>(clientInfo)); +} + struct JSCallbackClosure { QPointer<QObject> receiver; QByteArray method; @@ -184,6 +207,11 @@ static QQuickWebViewPrivate* createPrivateObject(QQuickWebView* publicObject) return new QQuickWebViewLegacyPrivate(publicObject); } +QQuickWebViewPrivate* QQuickWebViewPrivate::get(WKPageRef page) +{ + return pageToView()->value(page); +} + QQuickWebViewPrivate::FlickableAxisLocker::FlickableAxisLocker() : m_allowedDirection(QQuickFlickable::AutoFlickDirection) , m_time(0), m_sampleCount(0) @@ -259,6 +287,7 @@ QPointF QQuickWebViewPrivate::FlickableAxisLocker::adjust(const QPointF& positio QQuickWebViewPrivate::QQuickWebViewPrivate(QQuickWebView* viewport) : q_ptr(viewport) , experimental(new QQuickWebViewExperimental(viewport, this)) + , context(0) , alertDialog(0) , confirmDialog(0) , promptDialog(0) @@ -286,42 +315,78 @@ QQuickWebViewPrivate::QQuickWebViewPrivate(QQuickWebView* viewport) QQuickWebViewPrivate::~QQuickWebViewPrivate() { webPageProxy->close(); + pageToView()->remove(webPage.get()); } // Note: we delay this initialization to make sure that QQuickWebView has its d-ptr in-place. void QQuickWebViewPrivate::initialize(WKContextRef contextRef, WKPageGroupRef pageGroupRef) { - RefPtr<WebPageGroup> pageGroup; - if (pageGroupRef) - pageGroup = toImpl(pageGroupRef); - else - pageGroup = WebPageGroup::create(); + pageGroup = pageGroupRef; + if (!pageGroup) + pageGroup = adoptWK(WKPageGroupCreateWithIdentifier(0)); + + context = contextRef ? QtWebContext::create(contextRef) : QtWebContext::defaultContext(); + webPageProxy = toImpl(context->context())->createWebPage(&pageClient, toImpl(pageGroup.get())); + webPage = toAPI(webPageProxy.get()); + pageToView()->insert(webPage.get(), this); - context = contextRef ? QtWebContext::create(toImpl(contextRef)) : QtWebContext::defaultContext(); - webPageProxy = context->createWebPage(&pageClient, pageGroup.get()); webPageProxy->setUseFixedLayout(s_flickableViewportEnabled); #if ENABLE(FULLSCREEN_API) webPageProxy->fullScreenManager()->setWebView(q_ptr); #endif - QQuickWebPagePrivate* const pageViewPrivate = pageView.data()->d; - pageViewPrivate->initialize(webPageProxy.get()); + pageEventHandler.reset(new QtWebPageEventHandler(webPage.get(), pageView.data(), q_ptr)); + + { + WKPageFindClient findClient; + memset(&findClient, 0, sizeof(WKPageFindClient)); + findClient.version = kWKPageFindClientCurrentVersion; + findClient.clientInfo = this; + findClient.didFindString = didFindString; + findClient.didFailToFindString = didFailToFindString; + WKPageSetPageFindClient(webPage.get(), &findClient); + } + + { + WKPageLoaderClient loadClient; + memset(&loadClient, 0, sizeof(WKPageLoaderClient)); + loadClient.version = kWKPageLoaderClientCurrentVersion; + loadClient.clientInfo = this; + loadClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; + loadClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame; + loadClient.didFailProvisionalLoadWithErrorForFrame = didFailLoad; + loadClient.didCommitLoadForFrame = didCommitLoadForFrame; + loadClient.didFinishLoadForFrame = didFinishLoadForFrame; + loadClient.didFailLoadWithErrorForFrame = didFailLoad; + loadClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; + loadClient.didReceiveTitleForFrame = didReceiveTitleForFrame; + loadClient.didStartProgress = didStartProgress; + loadClient.didChangeProgress = didChangeProgress; + loadClient.didFinishProgress = didFinishProgress; + loadClient.didChangeBackForwardList = didChangeBackForwardList; + loadClient.processDidBecomeUnresponsive = processDidBecomeUnresponsive; + loadClient.processDidBecomeResponsive = processDidBecomeResponsive; + WKPageSetPageLoaderClient(webPage.get(), &loadClient); + } - pageLoadClient.reset(new QtWebPageLoadClient(toAPI(webPageProxy.get()), q_ptr)); - pagePolicyClient.reset(new QtWebPagePolicyClient(toAPI(webPageProxy.get()), q_ptr)); - pageUIClient.reset(new QtWebPageUIClient(toAPI(webPageProxy.get()), q_ptr)); - navigationHistory = adoptPtr(QWebNavigationHistoryPrivate::createHistory(toAPI(webPageProxy.get()))); + pagePolicyClient.reset(new QtWebPagePolicyClient(webPage.get(), q_ptr)); + pageUIClient.reset(new QtWebPageUIClient(webPage.get(), q_ptr)); + navigationHistory = adoptPtr(QWebNavigationHistoryPrivate::createHistory(webPage.get())); QtWebIconDatabaseClient* iconDatabase = context->iconDatabase(); QObject::connect(iconDatabase, SIGNAL(iconChangedForPageURL(QString)), q_ptr, SLOT(_q_onIconChangedForPageURL(QString))); // Any page setting should preferrable be set before creating the page. - webPageProxy->pageGroup()->preferences()->setAcceleratedCompositingEnabled(true); + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(pageGroup.get()); + WKPreferencesSetAcceleratedCompositingEnabled(preferencesRef, true); + bool showDebugVisuals = qgetenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS") == "1"; + WKPreferencesSetCompositingBordersVisible(preferencesRef, showDebugVisuals); + WKPreferencesSetCompositingRepaintCountersVisible(preferencesRef, showDebugVisuals); + WKPreferencesSetFrameFlatteningEnabled(preferencesRef, true); + WKPreferencesSetWebGLEnabled(preferencesRef, true); webPageProxy->pageGroup()->preferences()->setForceCompositingMode(true); - webPageProxy->pageGroup()->preferences()->setFrameFlatteningEnabled(true); - webPageProxy->pageGroup()->preferences()->setWebGLEnabled(true); - pageClient.initialize(q_ptr, pageViewPrivate->eventHandler.data(), &undoController); + pageClient.initialize(q_ptr, pageEventHandler.data(), &undoController); webPageProxy->initializeWebPage(); webPageProxy->registerApplicationScheme(ASCIILiteral("qrc")); @@ -330,109 +395,160 @@ void QQuickWebViewPrivate::initialize(WKContextRef contextRef, WKPageGroupRef pa q_ptr->setFlag(QQuickItem::ItemAcceptsDrops, true); } -void QQuickWebViewPrivate::loadDidStop() +void QQuickWebViewPrivate::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) { - Q_Q(QQuickWebView); - ASSERT(!q->loading()); - QWebLoadRequest loadRequest(q->url(), QQuickWebView::LoadStoppedStatus); + if (!WKFrameIsMainFrame(frame)) + return; + + WKRetainPtr<WKURLRef> url = adoptWK(WKFrameCopyProvisionalURL(frame)); + + QQuickWebView* const q = toQQuickWebViewPrivate(clientInfo)->q_func(); + + q->emitUrlChangeIfNeeded(); + QWebLoadRequest loadRequest(WKURLCopyQUrl(url.get()), QQuickWebView::LoadStartedStatus); emit q->loadingChanged(&loadRequest); } -void QQuickWebViewPrivate::setTransparentBackground(bool enable) +void QQuickWebViewPrivate::didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) { - webPageProxy->setDrawsTransparentBackground(enable); -} + if (!WKFrameIsMainFrame(frame)) + return; -bool QQuickWebViewPrivate::transparentBackground() const -{ - return webPageProxy->drawsTransparentBackground(); + toQQuickWebViewPrivate(clientInfo)->q_func()->emitUrlChangeIfNeeded(); } -void QQuickWebViewPrivate::provisionalLoadDidStart(const WTF::String& url) +void QQuickWebViewPrivate::didFailLoad(WKPageRef, WKFrameRef frame, WKErrorRef errorRef, WKTypeRef, const void* clientInfo) { - Q_Q(QQuickWebView); + if (!WKFrameIsMainFrame(frame)) + return; - q->emitUrlChangeIfNeeded(); + QQuickWebView* const q = toQQuickWebViewPrivate(clientInfo)->q_func(); + ASSERT(!q->loading()); - QWebLoadRequest loadRequest(QString(url), QQuickWebView::LoadStartedStatus); - emit q->loadingChanged(&loadRequest); -} + QtWebError error(errorRef); + if (error.isCancellation()) { + QWebLoadRequest loadRequest(q->url(), QQuickWebView::LoadStoppedStatus); + emit q->loadingChanged(&loadRequest); + return; + } -void QQuickWebViewPrivate::didReceiveServerRedirectForProvisionalLoad(const WTF::String&) -{ - Q_Q(QQuickWebView); + int errorCode = error.errorCode(); + if (errorCode == kWKErrorCodeFrameLoadInterruptedByPolicyChange && errorCode == kWKErrorCodePlugInWillHandleLoad) { + QWebLoadRequest loadRequest(q->url(), QQuickWebView::LoadSucceededStatus); + q->emitUrlChangeIfNeeded(); + emit q->loadingChanged(&loadRequest); + return; + } + // We set the unreachable url unconditionally so that the current + // active url of the webview when the loadingChanged signal is + // emitted reflects the failed url, not the previously committed + // url. This also ensures that if the user does not do a loadHtml + // with an error page and and unreachable url as a reponse to the + // failed load, we can still detect the failed url for reloads. + // We need to find a way to do this via the C API or find another + // way to do this. + toImpl(frame)->setUnreachableURL(error.url()); q->emitUrlChangeIfNeeded(); + QWebLoadRequest loadRequest(error.url(), QQuickWebView::LoadFailedStatus, error.description(), static_cast<QQuickWebView::ErrorDomain>(error.type()), errorCode); + emit q->loadingChanged(&loadRequest); } -void QQuickWebViewPrivate::loadDidCommit() +void QQuickWebViewPrivate::didCommitLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) { - Q_Q(QQuickWebView); - ASSERT(q->loading()); + if (!WKFrameIsMainFrame(frame)) + return; + QQuickWebViewPrivate* d = toQQuickWebViewPrivate(clientInfo); + + PageViewportController* pageViewportController = d->viewportController(); + if (pageViewportController) + pageViewportController->didCommitLoad(); - m_betweenLoadCommitAndFirstFrame = true; + QQuickWebView* const q = d->q_func(); + ASSERT(q->loading()); + d->m_betweenLoadCommitAndFirstFrame = true; emit q->navigationHistoryChanged(); emit q->titleChanged(); } -void QQuickWebViewPrivate::didSameDocumentNavigation() +void QQuickWebViewPrivate::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) { - Q_Q(QQuickWebView); + if (!WKFrameIsMainFrame(frame)) + return; + + QQuickWebView* const q = toQQuickWebViewPrivate(clientInfo)->q_func(); + ASSERT(!q->loading()); + + QWebLoadRequest loadRequest(q->url(), QQuickWebView::LoadSucceededStatus); + emit q->loadingChanged(&loadRequest); +} +void QQuickWebViewPrivate::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef frame, WKSameDocumentNavigationType type, WKTypeRef userData, const void* clientInfo) +{ + if (!WKFrameIsMainFrame(frame)) + return; + QQuickWebView* const q = toQQuickWebViewPrivate(clientInfo)->q_func(); q->emitUrlChangeIfNeeded(); emit q->navigationHistoryChanged(); } -void QQuickWebViewPrivate::titleDidChange() +void QQuickWebViewPrivate::didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef frame, WKTypeRef, const void* clientInfo) { - Q_Q(QQuickWebView); - - emit q->titleChanged(); + if (!WKFrameIsMainFrame(frame)) + return; + emit toQQuickWebViewPrivate(clientInfo)->q_func()->titleChanged(); } -void QQuickWebViewPrivate::loadProgressDidChange(int loadProgress) +void QQuickWebViewPrivate::didStartProgress(WKPageRef, const void* clientInfo) { - Q_Q(QQuickWebView); + toQQuickWebViewPrivate(clientInfo)->loadProgressDidChange(0); +} - m_loadProgress = loadProgress; +void QQuickWebViewPrivate::didChangeProgress(WKPageRef page, const void* clientInfo) +{ + toQQuickWebViewPrivate(clientInfo)->loadProgressDidChange(WKPageGetEstimatedProgress(page) * 100); +} - emit q->loadProgressChanged(); +void QQuickWebViewPrivate::didFinishProgress(WKPageRef, const void* clientInfo) +{ + toQQuickWebViewPrivate(clientInfo)->loadProgressDidChange(100); } -void QQuickWebViewPrivate::backForwardListDidChange() +void QQuickWebViewPrivate::didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef, WKArrayRef, const void *clientInfo) { - navigationHistory->d->reset(); + toQQuickWebViewPrivate(clientInfo)->navigationHistory->d->reset(); } -void QQuickWebViewPrivate::loadDidSucceed() +void QQuickWebViewPrivate::setTransparentBackground(bool enable) { - Q_Q(QQuickWebView); - ASSERT(!q->loading()); + webPageProxy->setDrawsTransparentBackground(enable); +} - QWebLoadRequest loadRequest(q->url(), QQuickWebView::LoadSucceededStatus); - emit q->loadingChanged(&loadRequest); +bool QQuickWebViewPrivate::transparentBackground() const +{ + return webPageProxy->drawsTransparentBackground(); } -void QQuickWebViewPrivate::loadDidFail(const QtWebError& error) +void QQuickWebViewPrivate::loadProgressDidChange(int loadProgress) { Q_Q(QQuickWebView); - ASSERT(!q->loading()); - QWebLoadRequest loadRequest(error.url(), QQuickWebView::LoadFailedStatus, error.description(), static_cast<QQuickWebView::ErrorDomain>(error.type()), error.errorCode()); - emit q->loadingChanged(&loadRequest); + m_loadProgress = loadProgress; + + emit q->loadProgressChanged(); } void QQuickWebViewPrivate::handleMouseEvent(QMouseEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: - pageView->eventHandler()->handleMousePressEvent(event); + pageEventHandler->handleMousePressEvent(event); break; case QEvent::MouseMove: - pageView->eventHandler()->handleMouseMoveEvent(event); + pageEventHandler->handleMouseMoveEvent(event); break; case QEvent::MouseButtonRelease: - pageView->eventHandler()->handleMouseReleaseEvent(event); + pageEventHandler->handleMouseReleaseEvent(event); break; case QEvent::MouseButtonDblClick: // If a MouseButtonDblClick was received then we got a MouseButtonPress before. @@ -475,7 +591,7 @@ void QQuickWebViewPrivate::processDidCrash() QUrl url(KURL(WebCore::ParsedURLString, webPageProxy->urlAtProcessExit())); qWarning("WARNING: The web process experienced a crash on '%s'.", qPrintable(url.toString(QUrl::RemoveUserInfo))); - pageView->eventHandler()->resetGestureRecognizers(); + pageEventHandler->resetGestureRecognizers(); // Check if loading was ongoing, when process crashed. if (m_loadProgress > 0 && m_loadProgress < 100) { @@ -494,29 +610,27 @@ void QQuickWebViewPrivate::didRelaunchProcess() qWarning("WARNING: The web process has been successfully restarted."); - webPageProxy->drawingArea()->setSize(viewSize(), IntSize()); + if (DrawingAreaProxy *drawingArea = webPageProxy->drawingArea()) { + drawingArea->setSize(viewSize(), IntSize(), IntSize()); - updateViewportSize(); - updateUserScripts(); - updateSchemeDelegates(); + updateViewportSize(); + updateUserScripts(); + updateSchemeDelegates(); + } emit q->experimental()->didRelaunchProcess(); } -void QQuickWebViewPrivate::processDidBecomeUnresponsive() +void QQuickWebViewPrivate::processDidBecomeUnresponsive(WKPageRef, const void* clientInfo) { - Q_Q(QQuickWebView); - - qWarning("WARNING: The web process has become unresponsive."); + QQuickWebView* q = toQQuickWebViewPrivate(clientInfo)->q_ptr; emit q->experimental()->processDidBecomeUnresponsive(); } -void QQuickWebViewPrivate::processDidBecomeResponsive() +void QQuickWebViewPrivate::processDidBecomeResponsive(WKPageRef, const void* clientInfo) { - Q_Q(QQuickWebView); - - qWarning("WARNING: The web process has become responsive."); + QQuickWebView* q = toQQuickWebViewPrivate(clientInfo)->q_ptr; emit q->experimental()->processDidBecomeResponsive(); } @@ -537,7 +651,7 @@ void QQuickWebViewPrivate::handleDownloadRequest(DownloadProxy* download) downloadItem->d->downloadProxy = download; q->connect(downloadItem->d, SIGNAL(receivedResponse(QWebDownloadItem*)), q, SLOT(_q_onReceivedResponseFromDownload(QWebDownloadItem*))); - QtWebContext::downloadManager()->addDownload(download, downloadItem); + QtWebContext::defaultContext()->downloadManager()->addDownload(toAPI(download), downloadItem); } void QQuickWebViewPrivate::_q_onVisibleChanged() @@ -552,7 +666,7 @@ void QQuickWebViewPrivate::_q_onUrlChanged() void QQuickWebViewPrivate::_q_onIconChangedForPageURL(const QString& pageUrl) { - if (pageUrl != QString(m_currentUrl)) + if (pageUrl != m_currentUrl) return; updateIcon(); @@ -572,7 +686,7 @@ void QQuickWebViewPrivate::updateIcon() if (!provider) return; - WTF::String iconUrl = provider->iconURLForPageURLInContext(m_currentUrl, context.get()); + QUrl iconUrl = provider->iconURLForPageURLInContext(m_currentUrl, context); if (iconUrl == m_iconUrl) return; @@ -748,10 +862,13 @@ void QQuickWebViewPrivate::setNavigatorQtObjectEnabled(bool enabled) ASSERT(enabled != m_navigatorQtObjectEnabled); // FIXME: Currently we have to keep this information in both processes and the setting is asynchronous. m_navigatorQtObjectEnabled = enabled; - context->setNavigatorQtObjectEnabled(webPageProxy.get(), enabled); + + static WKStringRef messageName = WKStringCreateWithUTF8CString("SetNavigatorQtObjectEnabled"); + WKRetainPtr<WKBooleanRef> wkEnabled = adoptWK(WKBooleanCreate(enabled)); + WKPagePostMessageToInjectedBundle(webPage.get(), messageName, wkEnabled.get()); } -static QString readUserScript(const QUrl& url) +static WKRetainPtr<WKStringRef> readUserScript(const QUrl& url) { QString path; if (url.isLocalFile()) @@ -760,26 +877,27 @@ static QString readUserScript(const QUrl& url) path = QStringLiteral(":") + url.path(); else { qWarning("QQuickWebView: Couldn't open '%s' as user script because only file:/// and qrc:/// URLs are supported.", qPrintable(url.toString())); - return QString(); + return 0; } QFile file(path); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning("QQuickWebView: Couldn't open '%s' as user script due to error '%s'.", qPrintable(url.toString()), qPrintable(file.errorString())); - return QString(); + return 0; } - QString contents = QString::fromUtf8(file.readAll()); + QByteArray contents = file.readAll(); if (contents.isEmpty()) qWarning("QQuickWebView: Ignoring '%s' as user script because file is empty.", qPrintable(url.toString())); - return contents; + return adoptWK(WKStringCreateWithUTF8CString(contents.constData())); } void QQuickWebViewPrivate::updateUserScripts() { - Vector<String> scripts; - scripts.reserveCapacity(userScripts.size()); + // This feature works per-WebView because we keep an unique page group for + // each Page/WebView pair we create. + WKPageGroupRemoveAllUserScripts(pageGroup.get()); for (unsigned i = 0; i < userScripts.size(); ++i) { const QUrl& url = userScripts.at(i); @@ -788,13 +906,11 @@ void QQuickWebViewPrivate::updateUserScripts() continue; } - QString contents = readUserScript(url); - if (contents.isEmpty()) + WKRetainPtr<WKStringRef> contents = readUserScript(url); + if (!contents || WKStringIsEmpty(contents.get())) continue; - scripts.append(String(contents)); + WKPageGroupAddUserScript(pageGroup.get(), contents.get(), /*baseURL*/ 0, /*whitelistedURLPatterns*/ 0, /*blacklistedURLPatterns*/ 0, kWKInjectInTopFrameOnly, kWKInjectAtDocumentEnd); } - - webPageProxy->setUserScripts(scripts); } void QQuickWebViewPrivate::updateSchemeDelegates() @@ -835,14 +951,32 @@ WebCore::IntSize QQuickWebViewPrivate::viewSize() const \sa postMessage */ -void QQuickWebViewPrivate::didReceiveMessageFromNavigatorQtObject(const String& message) +void QQuickWebViewPrivate::didReceiveMessageFromNavigatorQtObject(WKStringRef message) { QVariantMap variantMap; - variantMap.insert(QLatin1String("data"), QString(message)); + variantMap.insert(QLatin1String("data"), WKStringCopyQString(message)); variantMap.insert(QLatin1String("origin"), q_ptr->url()); emit q_ptr->experimental()->messageReceived(variantMap); } +CoordinatedGraphicsScene* QQuickWebViewPrivate::coordinatedGraphicsScene() +{ + if (webPageProxy && webPageProxy->drawingArea() && webPageProxy->drawingArea()->coordinatedLayerTreeHostProxy()) + return webPageProxy->drawingArea()->coordinatedLayerTreeHostProxy()->coordinatedGraphicsScene(); + + return 0; +} + +float QQuickWebViewPrivate::deviceScaleFactor() +{ + return webPageProxy->deviceScaleFactor(); +} + +void QQuickWebViewPrivate::setIntrinsicDeviceScaleFactor(float scaleFactor) +{ + webPageProxy->setIntrinsicDeviceScaleFactor(scaleFactor); +} + QQuickWebViewLegacyPrivate::QQuickWebViewLegacyPrivate(QQuickWebView* viewport) : QQuickWebViewPrivate(viewport) { @@ -865,23 +999,25 @@ void QQuickWebViewLegacyPrivate::updateViewportSize() pageView->setContentsSize(viewportSize); - // The fixed layout is handled by the FrameView and the drawing area doesn't behave differently - // whether its fixed or not. We still need to tell the drawing area which part of it - // has to be rendered on tiles, and in desktop mode it's all of it. - webPageProxy->drawingArea()->setSize(viewportSize.toSize(), IntSize()); - // The backing store scale factor should already be set to the device pixel ratio - // of the underlying window, thus we set the effective scale to 1 here. - webPageProxy->drawingArea()->setVisibleContentsRect(FloatRect(FloatPoint(), FloatSize(viewportSize)), 1, FloatPoint()); + if (DrawingAreaProxy *drawingArea = webPageProxy->drawingArea()) { + // The fixed layout is handled by the FrameView and the drawing area doesn't behave differently + // whether its fixed or not. We still need to tell the drawing area which part of it + // has to be rendered on tiles, and in desktop mode it's all of it. + drawingArea->setSize(viewportSize.toSize(), IntSize(), IntSize()); + // The backing store scale factor should already be set to the device pixel ratio + // of the underlying window, thus we set the effective scale to 1 here. + drawingArea->setVisibleContentsRect(FloatRect(FloatPoint(), FloatSize(viewportSize)), FloatPoint()); + } } qreal QQuickWebViewLegacyPrivate::zoomFactor() const { - return webPageProxy->pageZoomFactor(); + return WKPageGetPageZoomFactor(webPage.get()); } void QQuickWebViewLegacyPrivate::setZoomFactor(qreal factor) { - webPageProxy->setPageZoomFactor(factor); + WKPageSetPageZoomFactor(webPage.get(), factor); } QQuickWebViewFlickablePrivate::QQuickWebViewFlickablePrivate(QQuickWebView* viewport) @@ -901,7 +1037,7 @@ void QQuickWebViewFlickablePrivate::onComponentComplete() Q_Q(QQuickWebView); m_pageViewportControllerClient.reset(new PageViewportControllerClientQt(q, pageView.data())); m_pageViewportController.reset(new PageViewportController(webPageProxy.get(), m_pageViewportControllerClient.data())); - pageView->eventHandler()->setViewportController(m_pageViewportControllerClient.data()); + pageEventHandler->setViewportController(m_pageViewportControllerClient.data()); // Trigger setting of correct visibility flags after everything was allocated and initialized. _q_onVisibleChanged(); @@ -927,15 +1063,6 @@ void QQuickWebViewFlickablePrivate::pageDidRequestScroll(const QPoint& pos) m_pageViewportController->pageDidRequestScroll(pos); } -void QQuickWebViewFlickablePrivate::handleMouseEvent(QMouseEvent* event) -{ - if (!pageView->eventHandler()) - return; - - // FIXME: Update the axis locker for mouse events as well. - pageView->eventHandler()->handleInputEvent(event); -} - QQuickWebViewExperimental::QQuickWebViewExperimental(QQuickWebView *webView, QQuickWebViewPrivate* webViewPrivate) : QObject(webView) , q_ptr(webView) @@ -1045,7 +1172,9 @@ bool QQuickWebViewExperimental::flickableViewportEnabled() void QQuickWebViewExperimental::postMessage(const QString& message) { Q_D(QQuickWebView); - d->context->postMessageToNavigatorQtObject(d->webPageProxy.get(), message); + static WKStringRef messageName = WKStringCreateWithUTF8CString("MessageToNavigatorQtObject"); + WKRetainPtr<WKStringRef> contents = adoptWK(WKStringCreateWithQString(message)); + WKPagePostMessageToInjectedBundle(d->webPage.get(), messageName, contents.get()); } QQmlComponent* QQuickWebViewExperimental::alertDialog() const @@ -1214,16 +1343,19 @@ void QQuickWebViewExperimental::setColorChooser(QQmlComponent* colorChooser) QString QQuickWebViewExperimental::userAgent() const { Q_D(const QQuickWebView); - return d->webPageProxy->userAgent(); + WKRetainPtr<WKStringRef> ua = adoptWK(WKPageCopyCustomUserAgent(d->webPage.get())); + return WKStringCopyQString(ua.get()); } void QQuickWebViewExperimental::setUserAgent(const QString& userAgent) { Q_D(QQuickWebView); - if (userAgent == QString(d->webPageProxy->userAgent())) + WKRetainPtr<WKStringRef> newUserAgent = adoptWK(WKStringCreateWithQString(userAgent)); + WKRetainPtr<WKStringRef> currentUserAgent = adoptWK(WKPageCopyCustomUserAgent(d->webPage.get())); + if (WKStringIsEqual(newUserAgent.get(), currentUserAgent.get())) return; - d->webPageProxy->setUserAgent(userAgent); + WKPageSetCustomUserAgent(d->webPage.get(), newUserAgent.get()); emit userAgentChanged(); } @@ -1290,7 +1422,31 @@ void QQuickWebViewExperimental::evaluateJavaScript(const QString& script, const closure->receiver = this; closure->value = value; - d_ptr->webPageProxy.get()->runJavaScriptInMainFrame(script, ScriptValueCallback::create(closure, javaScriptCallback)); + WKRetainPtr<WKStringRef> scriptString = adoptWK(WKStringCreateWithQString(script)); + WKPageRunJavaScriptInMainFrame(d_ptr->webPage.get(), scriptString.get(), closure, javaScriptCallback); +} + +void QQuickWebViewExperimental::findText(const QString& string, FindFlags options) +{ + Q_D(QQuickWebView); + if (string.isEmpty()) { + WKPageHideFindUI(d->webPage.get()); + return; + } + + WKFindOptions wkOptions = kWKFindOptionsCaseInsensitive; + if (options & FindCaseSensitively) + wkOptions = wkOptions & ~kWKFindOptionsCaseInsensitive; + if (options & FindBackward) + wkOptions |= kWKFindOptionsBackwards; + if (options & FindWrapsAroundDocument) + wkOptions |= kWKFindOptionsWrapAround; + if (options & FindHighlightAllOccurrences) + wkOptions |= kWKFindOptionsShowHighlight; + + WKRetainPtr<WKStringRef> str = adoptWK(WKStringCreateWithQString(string)); + + WKPageFindString(d->webPage.get(), str.get(), wkOptions, std::numeric_limits<unsigned>::max() - 1); } QList<QUrl> QQuickWebViewExperimental::userScripts() const @@ -1420,8 +1576,8 @@ QQuickWebPage* QQuickWebViewExperimental::page() } /*! - \page qtwebkit-index.html - \title Qt WebKit + \page index.html + \title QtWebKit: QML WebView version 3.0 The WebView API allows QML applications to render regions of dynamic web content. A \e{WebView} component may share the screen with other @@ -1514,7 +1670,7 @@ QQuickWebPage* QQuickWebView::page() void QQuickWebView::goBack() { Q_D(QQuickWebView); - d->webPageProxy->goBack(); + WKPageGoBack(d->webPage.get()); } /*! @@ -1526,7 +1682,7 @@ void QQuickWebView::goBack() void QQuickWebView::goForward() { Q_D(QQuickWebView); - d->webPageProxy->goForward(); + WKPageGoForward(d->webPage.get()); } /*! @@ -1537,7 +1693,7 @@ void QQuickWebView::goForward() void QQuickWebView::stop() { Q_D(QQuickWebView); - d->webPageProxy->stopLoading(); + WKPageStopLoading(d->webPage.get()); } /*! @@ -1562,8 +1718,7 @@ void QQuickWebView::reload() return; } - const bool reloadFromOrigin = true; - d->webPageProxy->reload(reloadFromOrigin); + WKPageReloadFromOrigin(d->webPage.get()); } /*! @@ -1592,7 +1747,8 @@ void QQuickWebView::setUrl(const QUrl& url) if (url.isEmpty()) return; - d->webPageProxy->loadURL(url.toString()); + WKRetainPtr<WKURLRef> u = adoptWK(WKURLCreateWithQUrl(url)); + WKPageLoadURL(d->webPage.get(), u.get()); emitUrlChangeIfNeeded(); } @@ -1601,7 +1757,7 @@ void QQuickWebView::emitUrlChangeIfNeeded() { Q_D(QQuickWebView); - WTF::String activeUrl = d->webPageProxy->activeURL(); + QString activeUrl = d->webPageProxy->activeURL(); if (activeUrl != d->m_currentUrl) { d->m_currentUrl = activeUrl; emit urlChanged(); @@ -1629,7 +1785,7 @@ void QQuickWebView::emitUrlChangeIfNeeded() QUrl QQuickWebView::icon() const { Q_D(const QQuickWebView); - return QUrl(d->m_iconUrl); + return d->m_iconUrl; } /*! @@ -1653,7 +1809,7 @@ int QQuickWebView::loadProgress() const bool QQuickWebView::canGoBack() const { Q_D(const QQuickWebView); - return d->webPageProxy->canGoBack(); + return WKPageCanGoBack(d->webPage.get()); } /*! @@ -1665,7 +1821,7 @@ bool QQuickWebView::canGoBack() const bool QQuickWebView::canGoForward() const { Q_D(const QQuickWebView); - return d->webPageProxy->canGoForward(); + return WKPageCanGoForward(d->webPage.get()); } /*! @@ -1676,8 +1832,8 @@ bool QQuickWebView::canGoForward() const bool QQuickWebView::loading() const { Q_D(const QQuickWebView); - RefPtr<WebKit::WebFrameProxy> mainFrame = d->webPageProxy->mainFrame(); - return mainFrame && !(WebFrameProxy::LoadStateFinished == mainFrame->loadState()); + WKFrameRef mainFrame = WKPageGetMainFrame(d->webPage.get()); + return mainFrame && !(kWKFrameLoadStateFinished == WKFrameGetFrameLoadState(mainFrame)); } /*! @@ -1728,7 +1884,8 @@ QRectF QQuickWebView::mapRectFromWebContent(const QRectF& rectInCSSCoordinates) QString QQuickWebView::title() const { Q_D(const QQuickWebView); - return d->webPageProxy->pageTitle(); + WKRetainPtr<WKStringRef> t = adoptWK(WKPageCopyTitle(d->webPage.get())); + return WKStringCopyQString(t.get()); } QVariant QQuickWebView::inputMethodQuery(Qt::InputMethodQuery property) const @@ -1827,25 +1984,25 @@ void QQuickWebView::componentComplete() void QQuickWebView::keyPressEvent(QKeyEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleKeyPressEvent(event); + d->pageEventHandler->handleKeyPressEvent(event); } void QQuickWebView::keyReleaseEvent(QKeyEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleKeyReleaseEvent(event); + d->pageEventHandler->handleKeyReleaseEvent(event); } void QQuickWebView::inputMethodEvent(QInputMethodEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleInputMethodEvent(event); + d->pageEventHandler->handleInputMethodEvent(event); } void QQuickWebView::focusInEvent(QFocusEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleFocusInEvent(event); + d->pageEventHandler->handleFocusInEvent(event); } void QQuickWebView::itemChange(ItemChange change, const ItemChangeData &value) @@ -1854,7 +2011,7 @@ void QQuickWebView::itemChange(ItemChange change, const ItemChangeData &value) if (change == ItemActiveFocusHasChanged) { bool focus = value.boolValue; if (!focus) - d->pageView->eventHandler()->handleFocusLost(); + d->pageEventHandler->handleFocusLost(); } QQuickFlickable::itemChange(change, value); } @@ -1874,7 +2031,7 @@ void QQuickWebView::touchEvent(QTouchEvent* event) d->axisLocker.reset(); forceActiveFocus(); - d->pageView->eventHandler()->handleTouchEvent(event); + d->pageEventHandler->handleTouchEvent(event); } void QQuickWebView::mousePressEvent(QMouseEvent* event) @@ -1906,50 +2063,50 @@ void QQuickWebView::mouseDoubleClickEvent(QMouseEvent* event) void QQuickWebView::wheelEvent(QWheelEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleWheelEvent(event); + d->pageEventHandler->handleWheelEvent(event); } void QQuickWebView::hoverEnterEvent(QHoverEvent* event) { Q_D(QQuickWebView); // Map HoverEnter to Move, for WebKit the distinction doesn't matter. - d->pageView->eventHandler()->handleHoverMoveEvent(event); + d->pageEventHandler->handleHoverMoveEvent(event); } void QQuickWebView::hoverMoveEvent(QHoverEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleHoverMoveEvent(event); + d->pageEventHandler->handleHoverMoveEvent(event); } void QQuickWebView::hoverLeaveEvent(QHoverEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleHoverLeaveEvent(event); + d->pageEventHandler->handleHoverLeaveEvent(event); } void QQuickWebView::dragMoveEvent(QDragMoveEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleDragMoveEvent(event); + d->pageEventHandler->handleDragMoveEvent(event); } void QQuickWebView::dragEnterEvent(QDragEnterEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleDragEnterEvent(event); + d->pageEventHandler->handleDragEnterEvent(event); } void QQuickWebView::dragLeaveEvent(QDragLeaveEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleDragLeaveEvent(event); + d->pageEventHandler->handleDragLeaveEvent(event); } void QQuickWebView::dropEvent(QDropEvent* event) { Q_D(QQuickWebView); - d->pageView->eventHandler()->handleDropEvent(event); + d->pageEventHandler->handleDropEvent(event); } bool QQuickWebView::event(QEvent* ev) @@ -1961,7 +2118,7 @@ bool QQuickWebView::event(QEvent* ev) WKPageRef QQuickWebView::pageRef() const { Q_D(const QQuickWebView); - return toAPI(d->webPageProxy.get()); + return d->webPage.get(); } QPointF QQuickWebView::contentPos() const @@ -2028,10 +2185,14 @@ void QQuickWebView::handleFlickableMouseRelease(const QPointF& position, qint64 void QQuickWebView::loadHtml(const QString& html, const QUrl& baseUrl, const QUrl& unreachableUrl) { Q_D(QQuickWebView); + WKRetainPtr<WKStringRef> htmlRef = adoptWK(WKStringCreateWithQString(html)); + WKRetainPtr<WKURLRef> baseUrlRef = adoptWK(WKURLCreateWithQUrl(baseUrl)); + WKRetainPtr<WKURLRef> unreachableUrlRef = adoptWK(WKURLCreateWithQUrl(unreachableUrl)); + if (unreachableUrl.isValid()) - d->webPageProxy->loadAlternateHTMLString(html, baseUrl.toString(), unreachableUrl.toString()); + WKPageLoadAlternateHTMLString(d->webPage.get(), htmlRef.get(), baseUrlRef.get(), unreachableUrlRef.get()); else - d->webPageProxy->loadHTMLString(html, baseUrl.toString()); + WKPageLoadHTMLString(d->webPage.get(), htmlRef.get(), baseUrlRef.get()); } qreal QQuickWebView::zoomFactor() const @@ -2055,7 +2216,8 @@ void QQuickWebView::runJavaScriptInMainFrame(const QString &script, QObject *rec closure->receiver = receiver; closure->method = method; - d->webPageProxy.get()->runJavaScriptInMainFrame(script, ScriptValueCallback::create(closure, javaScriptCallback)); + WKRetainPtr<WKStringRef> scriptString = adoptWK(WKStringCreateWithQString(script)); + WKPageRunJavaScriptInMainFrame(d->webPage.get(), scriptString.get(), closure, javaScriptCallback); } bool QQuickWebView::allowAnyHTTPSCertificateForLocalHost() const @@ -2070,6 +2232,17 @@ void QQuickWebView::setAllowAnyHTTPSCertificateForLocalHost(bool allow) d->m_allowAnyHTTPSCertificateForLocalHost = allow; } +void QQuickWebViewPrivate::didFindString(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo) +{ + QQuickWebView* q = toQQuickWebViewPrivate(clientInfo)->q_ptr; + emit q->experimental()->textFound(matchCount); +} + +void QQuickWebViewPrivate::didFailToFindString(WKPageRef page, WKStringRef string, const void* clientInfo) +{ + QQuickWebViewPrivate::didFindString(page, string, 0, clientInfo); +} + /*! \qmlsignal WebView::onLoadingChanged(loadRequest) diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p.h b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p.h index 894224c7b..86d68fc15 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) + * Copyright (c) 2012 Hewlett-Packard Development Company, L.P. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -47,10 +48,13 @@ namespace WTR { class PlatformWebView; } +namespace TestWebKitAPI { +class PlatformWebView; +} + namespace WebKit { struct QtRefCountedNetworkRequestData; class PageViewportControllerClientQt; -class QtWebPageLoadClient; class QtWebPagePolicyClient; class QtWebPageUIClient; } @@ -219,10 +223,10 @@ private: friend class QWebKitTest; friend class WebKit::PageViewportControllerClientQt; - friend class WebKit::QtWebPageLoadClient; friend class WebKit::QtWebPagePolicyClient; friend class WebKit::QtWebPageUIClient; friend class WTR::PlatformWebView; + friend class TestWebKitAPI::PlatformWebView; friend class QQuickWebViewExperimental; }; @@ -277,12 +281,21 @@ class QWEBKIT_EXPORT QQuickWebViewExperimental : public QObject { Q_PROPERTY(QList<QUrl> userScripts READ userScripts WRITE setUserScripts NOTIFY userScriptsChanged) Q_PROPERTY(QUrl remoteInspectorUrl READ remoteInspectorUrl NOTIFY remoteInspectorUrlChanged FINAL) Q_ENUMS(NavigationRequestActionExperimental) + Q_FLAGS(FindFlags) public: enum NavigationRequestActionExperimental { DownloadRequest = QQuickWebView::IgnoreRequest - 1 }; + enum FindFlag { + FindCaseSensitively = 1 << 0, + FindBackward = 1 << 1, + FindWrapsAroundDocument = 1 << 2, + FindHighlightAllOccurrences = 1 << 3 + }; + Q_DECLARE_FLAGS(FindFlags, FindFlag) + virtual ~QQuickWebViewExperimental(); QQmlComponent* alertDialog() const; @@ -349,6 +362,7 @@ public Q_SLOTS: void goForwardTo(int index); void postMessage(const QString&); void evaluateJavaScript(const QString& script, const QJSValue& value = QJSValue()); + void findText(const QString& string, FindFlags options = 0); Q_SIGNALS: void loadVisuallyCommitted(); @@ -373,6 +387,7 @@ Q_SIGNALS: void userScriptsChanged(); void preferredMinimumContentsWidthChanged(); void remoteInspectorUrlChanged(); + void textFound(int matchCount); void processDidCrash(); void didRelaunchProcess(); @@ -392,4 +407,6 @@ private: Q_DECLARE_PUBLIC(QQuickWebView) }; +Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickWebViewExperimental::FindFlags) + #endif // qquickwebview_p_h diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h index 19ace9a3a..f1ce17114 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h @@ -33,9 +33,14 @@ #include <QtCore/QObject> #include <QtCore/QScopedPointer> #include <WebCore/ViewportArguments.h> +#include <WebKit2/WKRetainPtr.h> #include <wtf/OwnPtr.h> #include <wtf/RefPtr.h> +namespace WebCore { +class CoordinatedGraphicsScene; +} + namespace WebKit { class DownloadProxy; class DrawingAreaProxy; @@ -43,7 +48,7 @@ class QtDialogRunner; class PageViewportControllerClientQt; class QtWebContext; class QtWebError; -class QtWebPageLoadClient; +class QtWebPageEventHandler; class QtWebPagePolicyClient; class WebPageProxy; } @@ -65,6 +70,7 @@ class QQuickWebViewPrivate { public: static QQuickWebViewPrivate* get(QQuickWebView* q) { return q->d_ptr.data(); } + static QQuickWebViewPrivate* get(WKPageRef); virtual ~QQuickWebViewPrivate(); @@ -72,18 +78,12 @@ public: virtual void onComponentComplete() { } - virtual void provisionalLoadDidStart(const WTF::String& url); - virtual void didReceiveServerRedirectForProvisionalLoad(const WTF::String& url); - virtual void loadDidCommit(); - virtual void didSameDocumentNavigation(); - virtual void titleDidChange(); virtual void loadProgressDidChange(int loadProgress); - virtual void backForwardListDidChange(); - virtual void loadDidSucceed(); - virtual void loadDidStop(); - virtual void loadDidFail(const WebKit::QtWebError& error); virtual void handleMouseEvent(QMouseEvent*); + static void didFindString(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo); + static void didFailToFindString(WKPageRef page, WKStringRef string, const void* clientInfo); + virtual void didChangeViewportProperties(const WebCore::ViewportAttributes& attr) { } int loadProgress() const { return m_loadProgress; } @@ -130,15 +130,18 @@ public: // PageClient. WebCore::IntSize viewSize() const; - void didReceiveMessageFromNavigatorQtObject(const String& message); virtual void pageDidRequestScroll(const QPoint& pos) { } void processDidCrash(); void didRelaunchProcess(); - void processDidBecomeUnresponsive(); - void processDidBecomeResponsive(); PassOwnPtr<WebKit::DrawingAreaProxy> createDrawingAreaProxy(); void handleDownloadRequest(WebKit::DownloadProxy*); + void didReceiveMessageFromNavigatorQtObject(WKStringRef message); + + WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene(); + float deviceScaleFactor(); + void setIntrinsicDeviceScaleFactor(float); + protected: class FlickableAxisLocker { QQuickFlickable::FlickableDirection m_allowedDirection; @@ -159,22 +162,39 @@ protected: QPointF adjust(const QPointF&); }; + // WKPageLoadClient callbacks. + static void didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); + static void didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); + static void didFailLoad(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); + static void didCommitLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); + static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); + static void didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef, WKSameDocumentNavigationType, WKTypeRef userData, const void* clientInfo); + static void didReceiveTitleForFrame(WKPageRef, WKStringRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); + static void didStartProgress(WKPageRef, const void* clientInfo); + static void didChangeProgress(WKPageRef, const void* clientInfo); + static void didFinishProgress(WKPageRef, const void* clientInfo); + static void didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef, WKArrayRef, const void *clientInfo); + static void processDidBecomeUnresponsive(WKPageRef, const void* clientInfo); + static void processDidBecomeResponsive(WKPageRef, const void* clientInfo); + QQuickWebViewPrivate(QQuickWebView* viewport); - RefPtr<WebKit::QtWebContext> context; RefPtr<WebKit::WebPageProxy> webPageProxy; + WKRetainPtr<WKPageRef> webPage; + WKRetainPtr<WKPageGroupRef> pageGroup; WebKit::QtPageClient pageClient; WebKit::DefaultUndoController undoController; OwnPtr<QWebNavigationHistory> navigationHistory; OwnPtr<QWebPreferences> preferences; - QScopedPointer<WebKit::QtWebPageLoadClient> pageLoadClient; QScopedPointer<WebKit::QtWebPagePolicyClient> pagePolicyClient; QScopedPointer<WebKit::QtWebPageUIClient> pageUIClient; QScopedPointer<QQuickWebPage> pageView; + QScopedPointer<WebKit::QtWebPageEventHandler> pageEventHandler; QQuickWebView* q_ptr; QQuickWebViewExperimental* experimental; + WebKit::QtWebContext* context; FlickableAxisLocker axisLocker; @@ -196,9 +216,9 @@ protected: bool m_navigatorQtObjectEnabled; bool m_renderToOffscreenBuffer; bool m_allowAnyHTTPSCertificateForLocalHost; - WTF::String m_iconUrl; + QUrl m_iconUrl; int m_loadProgress; - WTF::String m_currentUrl; + QString m_currentUrl; }; class QQuickWebViewLegacyPrivate : public QQuickWebViewPrivate { @@ -226,7 +246,6 @@ public: virtual void updateViewportSize(); virtual void pageDidRequestScroll(const QPoint& pos); - virtual void handleMouseEvent(QMouseEvent*); private: QScopedPointer<WebKit::PageViewportController> m_pageViewportController; diff --git a/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp b/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp index aa26c0737..00ec6bc83 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp @@ -24,8 +24,6 @@ #include "QtWebIconDatabaseClient.h" #include <QtCore/QUrl> #include <QtGui/QImage> -#include <wtf/text/StringHash.h> -#include <wtf/text/WTFString.h> using namespace WebKit; @@ -38,44 +36,47 @@ QWebIconImageProvider::~QWebIconImageProvider() { } -WTF::String QWebIconImageProvider::iconURLForPageURLInContext(const WTF::String &pageURL, QtWebContext* context) +QUrl QWebIconImageProvider::iconURLForPageURLInContext(const QString &pageURL, QtWebContext* context) { QtWebIconDatabaseClient* iconDatabase = context->iconDatabase(); - WTF::String iconURL = iconDatabase->iconForPageURL(pageURL); - if (iconURL.isEmpty()) - return String(); + // Verify that the image data is actually available before reporting back + // a url, since clients assume that the url can be used directly. + if (iconDatabase->iconImageForPageURL(pageURL).isNull()) + return QUrl(); QUrl url; url.setScheme(QStringLiteral("image")); url.setHost(QWebIconImageProvider::identifier()); - // Make sure that QML doesn't show cached versions of the previous icon if the icon location changed. - url.setPath(QLatin1Char('/') + QString::number(WTF::StringHash::hash(iconURL))); + // Make sure that QML doesn't show a cached previous version of the icon after it changed. + url.setPath(QStringLiteral("/%1").arg(QtWebIconDatabaseClient::updateID())); // FIXME: Use QUrl::DecodedMode when landed in Qt - url.setFragment(QString::fromLatin1(QByteArray(QString(pageURL).toUtf8()).toBase64())); + url.setFragment(QString::fromLatin1(pageURL.toUtf8().toBase64())); // FIXME: We can't know when the icon url is no longer in use, // so we never release these icons. At some point we might want // to introduce expiry of icons to elevate this issue. iconDatabase->retainIconForPageURL(pageURL); - return url.toString(QUrl::FullyEncoded); + return url; } QImage QWebIconImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize) { QString pageURL = QString::fromUtf8(QByteArray::fromBase64(id.midRef(id.indexOf('#') + 1).toLatin1())); - QtWebIconDatabaseClient* iconDatabase = QtWebContext::iconDatabase(); - if (!iconDatabase) - return QImage(); + QtWebIconDatabaseClient* iconDatabase = QtWebContext::defaultContext()->iconDatabase(); + Q_ASSERT(iconDatabase); - QImage icon = requestedSize.isValid() ? iconDatabase->iconImageForPageURL(pageURL, requestedSize) : iconDatabase->iconImageForPageURL(pageURL); - ASSERT(!icon.isNull()); + QImage icon = iconDatabase->iconImageForPageURL(pageURL); + Q_ASSERT(!icon.isNull()); if (size) *size = icon.size(); + if (requestedSize.isValid()) + return icon.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); + return icon; } diff --git a/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider_p.h b/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider_p.h index 7efe21a14..10b2f697e 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider_p.h @@ -23,7 +23,6 @@ #include "qwebkitglobal.h" #include <QString> #include <QtQuick/QQuickImageProvider> -#include <wtf/text/WTFString.h> namespace WebKit { class QtWebContext; @@ -36,7 +35,7 @@ public: static QString identifier() { return QStringLiteral("webicon"); } - WTF::String iconURLForPageURLInContext(const WTF::String& pageURL, WebKit::QtWebContext* context); + QUrl iconURLForPageURLInContext(const QString& pageURL, WebKit::QtWebContext* context); virtual QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize); }; diff --git a/Source/WebKit2/UIProcess/API/qt/qwebkittest.cpp b/Source/WebKit2/UIProcess/API/qt/qwebkittest.cpp index a8a9c686b..20cfa388d 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebkittest.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qwebkittest.cpp @@ -151,8 +151,8 @@ QJsonObject QWebKitTest::viewport() const if (const PageViewportController* const viewportHandler = m_webViewPrivate->viewportController()) { viewportData.insert(QLatin1String("layoutSize"), toJsonObject(viewportHandler->contentsLayoutSize())); viewportData.insert(QLatin1String("isScalable"), viewportHandler->allowsUserScaling()); - viewportData.insert(QLatin1String("minimumScale"), viewportHandler->minimumContentsScale()); - viewportData.insert(QLatin1String("maximumScale"), viewportHandler->maximumContentsScale()); + viewportData.insert(QLatin1String("minimumScale"), viewportHandler->minimumScale()); + viewportData.insert(QLatin1String("maximumScale"), viewportHandler->maximumScale()); } else { viewportData.insert(QLatin1String("initialScale"), 1.0); viewportData.insert(QLatin1String("layoutSize"), toJsonObject(QSizeF())); @@ -166,13 +166,13 @@ QJsonObject QWebKitTest::viewport() const QVariant QWebKitTest::devicePixelRatio() const { if (const PageViewportController* const viewport = m_webViewPrivate->viewportController()) - return viewport->devicePixelRatio(); + return viewport->deviceScaleFactor(); return 1.0; } QVariant QWebKitTest::contentsScale() const { if (const PageViewportController* const viewport = m_webViewPrivate->viewportController()) - return viewport->currentContentsScale(); + return viewport->currentScale(); return 1.0; } diff --git a/Source/WebKit2/UIProcess/API/qt/qwebnavigationhistory.cpp b/Source/WebKit2/UIProcess/API/qt/qwebnavigationhistory.cpp index 0c9f7b856..95f40498f 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebnavigationhistory.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qwebnavigationhistory.cpp @@ -30,7 +30,6 @@ #include "WKStringQt.h" #include "WKURL.h" #include "WKURLQt.h" -#include "WebBackForwardList.h" #include "qwebnavigationhistory_p_p.h" #include <QString> @@ -39,7 +38,9 @@ #include <WebKit2/WKArray.h> #include <WebKit2/WKBackForwardListItem.h> #include <WebKit2/WKBase.h> +#include <WebKit2/WKPage.h> #include <WebKit2/WKRetainPtr.h> +#include <wtf/PassOwnPtr.h> using namespace WebKit; diff --git a/Source/WebKit2/UIProcess/API/qt/qwebpreferences.cpp b/Source/WebKit2/UIProcess/API/qt/qwebpreferences.cpp index 7ddfd9269..26eb944e9 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebpreferences.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qwebpreferences.cpp @@ -20,10 +20,12 @@ #include "config.h" #include "qwebpreferences_p.h" -#include "WebPageGroup.h" -#include "WebPageProxy.h" #include "qquickwebview_p_p.h" #include "qwebpreferences_p_p.h" +#include <WKPageGroup.h> +#include <WKPreferences.h> +#include <WKRetainPtr.h> +#include <WKStringQt.h> QWebPreferences* QWebPreferencesPrivate::createPreferences(QQuickWebViewPrivate* webViewPrivate) { @@ -35,51 +37,52 @@ QWebPreferences* QWebPreferencesPrivate::createPreferences(QQuickWebViewPrivate* bool QWebPreferencesPrivate::testAttribute(QWebPreferencesPrivate::WebAttribute attr) const { + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(webViewPrivate->pageGroup.get()); switch (attr) { case AutoLoadImages: - return preferences()->loadsImagesAutomatically(); + return WKPreferencesGetLoadsImagesAutomatically(preferencesRef); #if ENABLE(FULLSCREEN_API) case FullScreenEnabled: - return preferences()->fullScreenEnabled(); + return WKPreferencesGetFullScreenEnabled(preferencesRef); #endif case JavascriptEnabled: - return preferences()->javaScriptEnabled(); + return WKPreferencesGetJavaScriptEnabled(preferencesRef); case PluginsEnabled: - return preferences()->pluginsEnabled(); + return WKPreferencesGetPluginsEnabled(preferencesRef); case OfflineWebApplicationCacheEnabled: - return preferences()->offlineWebApplicationCacheEnabled(); + return WKPreferencesGetOfflineWebApplicationCacheEnabled(preferencesRef); case LocalStorageEnabled: - return preferences()->localStorageEnabled(); + return WKPreferencesGetLocalStorageEnabled(preferencesRef); case XSSAuditingEnabled: - return preferences()->xssAuditorEnabled(); + return WKPreferencesGetXSSAuditorEnabled(preferencesRef); case PrivateBrowsingEnabled: - return preferences()->privateBrowsingEnabled(); + return WKPreferencesGetPrivateBrowsingEnabled(preferencesRef); case DnsPrefetchEnabled: - return preferences()->dnsPrefetchingEnabled(); + return WKPreferencesGetDNSPrefetchingEnabled(preferencesRef); case FrameFlatteningEnabled: - return preferences()->frameFlatteningEnabled(); + return WKPreferencesGetFrameFlatteningEnabled(preferencesRef); case DeveloperExtrasEnabled: - return preferences()->developerExtrasEnabled(); + return WKPreferencesGetDeveloperExtrasEnabled(preferencesRef); #if ENABLE(WEBGL) case WebGLEnabled: - return preferences()->webGLEnabled(); + return WKPreferencesGetWebGLEnabled(preferencesRef); #if ENABLE(CSS_SHADERS) case CSSCustomFilterEnabled: - return preferences()->cssCustomFilterEnabled(); + return WKPreferencesGetCSSCustomFilterEnabled(preferencesRef); #endif #endif #if ENABLE(WEB_AUDIO) case WebAudioEnabled: - return preferences()->webAudioEnabled(); -#endif -#if ENABLE(SMOOTH_SCROLLING) - case ScrollAnimatorEnabled: - return preferences()->scrollAnimatorEnabled(); + return WKPreferencesGetWebAudioEnabled(preferencesRef); #endif case CaretBrowsingEnabled: - return preferences()->caretBrowsingEnabled(); + return WKPreferencesGetCaretBrowsingEnabled(preferencesRef); case NotificationsEnabled: - return preferences()->notificationsEnabled(); + return WKPreferencesGetNotificationsEnabled(preferencesRef); + case UniversalAccessFromFileURLsAllowed: + return WKPreferencesGetUniversalAccessFromFileURLsAllowed(preferencesRef); + case FileAccessFromFileURLsAllowed: + return WKPreferencesGetFileAccessFromFileURLsAllowed(preferencesRef); default: ASSERT_NOT_REACHED(); return false; @@ -88,67 +91,69 @@ bool QWebPreferencesPrivate::testAttribute(QWebPreferencesPrivate::WebAttribute void QWebPreferencesPrivate::setAttribute(QWebPreferencesPrivate::WebAttribute attr, bool enable) { + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(webViewPrivate->pageGroup.get()); switch (attr) { case AutoLoadImages: - preferences()->setLoadsImagesAutomatically(enable); + WKPreferencesSetLoadsImagesAutomatically(preferencesRef, enable); break; #if ENABLE(FULLSCREEN_API) case FullScreenEnabled: - preferences()->setFullScreenEnabled(enable); + WKPreferencesSetFullScreenEnabled(preferencesRef, enable); break; #endif case JavascriptEnabled: - preferences()->setJavaScriptEnabled(enable); + WKPreferencesSetJavaScriptEnabled(preferencesRef, enable); break; case PluginsEnabled: - preferences()->setPluginsEnabled(enable); + WKPreferencesSetPluginsEnabled(preferencesRef, enable); break; case OfflineWebApplicationCacheEnabled: - preferences()->setOfflineWebApplicationCacheEnabled(enable); + WKPreferencesSetOfflineWebApplicationCacheEnabled(preferencesRef, enable); break; case LocalStorageEnabled: - preferences()->setLocalStorageEnabled(enable); + WKPreferencesSetLocalStorageEnabled(preferencesRef, enable); break; case XSSAuditingEnabled: - preferences()->setXSSAuditorEnabled(enable); + WKPreferencesSetXSSAuditorEnabled(preferencesRef, enable); break; case PrivateBrowsingEnabled: - preferences()->setPrivateBrowsingEnabled(enable); + WKPreferencesSetPrivateBrowsingEnabled(preferencesRef, enable); break; case DnsPrefetchEnabled: - preferences()->setDNSPrefetchingEnabled(enable); + WKPreferencesSetDNSPrefetchingEnabled(preferencesRef, enable); break; case FrameFlatteningEnabled: - preferences()->setFrameFlatteningEnabled(enable); + WKPreferencesSetFrameFlatteningEnabled(preferencesRef, enable); case DeveloperExtrasEnabled: - preferences()->setDeveloperExtrasEnabled(enable); + WKPreferencesSetDeveloperExtrasEnabled(preferencesRef, enable); break; #if ENABLE(WEBGL) case WebGLEnabled: - preferences()->setWebGLEnabled(enable); + WKPreferencesSetWebGLEnabled(preferencesRef, enable); break; #if ENABLE(CSS_SHADERS) case CSSCustomFilterEnabled: - preferences()->setCSSCustomFilterEnabled(enable); + WKPreferencesSetCSSCustomFilterEnabled(preferencesRef, enable); break; #endif #endif #if ENABLE(WEB_AUDIO) case WebAudioEnabled: - preferences()->setWebAudioEnabled(enable); - break; -#endif -#if ENABLE(SMOOTH_SCROLLING) - case ScrollAnimatorEnabled: - preferences()->setScrollAnimatorEnabled(enable); + WKPreferencesSetWebAudioEnabled(preferencesRef, enable); break; #endif case CaretBrowsingEnabled: // FIXME: Caret browsing doesn't make much sense in touch mode. - preferences()->setCaretBrowsingEnabled(enable); + WKPreferencesSetCaretBrowsingEnabled(preferencesRef, enable); break; case NotificationsEnabled: - preferences()->setNotificationsEnabled(enable); + WKPreferencesSetNotificationsEnabled(preferencesRef, enable); + break; + case UniversalAccessFromFileURLsAllowed: + WKPreferencesSetUniversalAccessFromFileURLsAllowed(preferencesRef, enable); + break; + case FileAccessFromFileURLsAllowed: + WKPreferencesSetFileAccessFromFileURLsAllowed(preferencesRef, enable); break; default: ASSERT_NOT_REACHED(); @@ -181,24 +186,26 @@ void QWebPreferencesPrivate::initializeDefaultFontSettings() void QWebPreferencesPrivate::setFontFamily(QWebPreferencesPrivate::FontFamily which, const QString& family) { + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(webViewPrivate->pageGroup.get()); + WKRetainPtr<WKStringRef> familyRef = adoptWK(WKStringCreateWithQString(family)); switch (which) { case StandardFont: - preferences()->setStandardFontFamily(family); + WKPreferencesSetStandardFontFamily(preferencesRef, familyRef.get()); break; case FixedFont: - preferences()->setFixedFontFamily(family); + WKPreferencesSetFixedFontFamily(preferencesRef, familyRef.get()); break; case SerifFont: - preferences()->setSerifFontFamily(family); + WKPreferencesSetSerifFontFamily(preferencesRef, familyRef.get()); break; case SansSerifFont: - preferences()->setSansSerifFontFamily(family); + WKPreferencesSetSansSerifFontFamily(preferencesRef, familyRef.get()); break; case CursiveFont: - preferences()->setCursiveFontFamily(family); + WKPreferencesSetCursiveFontFamily(preferencesRef, familyRef.get()); break; case FantasyFont: - preferences()->setFantasyFontFamily(family); + WKPreferencesSetFantasyFontFamily(preferencesRef, familyRef.get()); break; default: break; @@ -207,35 +214,37 @@ void QWebPreferencesPrivate::setFontFamily(QWebPreferencesPrivate::FontFamily wh QString QWebPreferencesPrivate::fontFamily(QWebPreferencesPrivate::FontFamily which) const { + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(webViewPrivate->pageGroup.get()); switch (which) { case StandardFont: - return preferences()->standardFontFamily(); + return adoptToQString(WKPreferencesCopyStandardFontFamily(preferencesRef)); case FixedFont: - return preferences()->fixedFontFamily(); + return adoptToQString(WKPreferencesCopyFixedFontFamily(preferencesRef)); case SerifFont: - return preferences()->serifFontFamily(); + return adoptToQString(WKPreferencesCopySerifFontFamily(preferencesRef)); case SansSerifFont: - return preferences()->sansSerifFontFamily(); + return adoptToQString(WKPreferencesCopySansSerifFontFamily(preferencesRef)); case CursiveFont: - return preferences()->cursiveFontFamily(); + return adoptToQString(WKPreferencesCopyCursiveFontFamily(preferencesRef)); case FantasyFont: - return preferences()->fantasyFontFamily(); + return adoptToQString(WKPreferencesCopyFantasyFontFamily(preferencesRef)); default: return QString(); } } void QWebPreferencesPrivate::setFontSize(QWebPreferencesPrivate::FontSizeType type, unsigned size) -{ +{ + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(webViewPrivate->pageGroup.get()); switch (type) { case MinimumFontSize: - preferences()->setMinimumFontSize(size); + WKPreferencesSetMinimumFontSize(preferencesRef, static_cast<uint32_t>(size)); break; case DefaultFontSize: - preferences()->setDefaultFontSize(size); + WKPreferencesSetDefaultFontSize(preferencesRef, static_cast<uint32_t>(size)); break; case DefaultFixedFontSize: - preferences()->setDefaultFixedFontSize(size); + WKPreferencesSetDefaultFixedFontSize(preferencesRef, static_cast<uint32_t>(size)); break; default: ASSERT_NOT_REACHED(); @@ -244,13 +253,14 @@ void QWebPreferencesPrivate::setFontSize(QWebPreferencesPrivate::FontSizeType ty unsigned QWebPreferencesPrivate::fontSize(QWebPreferencesPrivate::FontSizeType type) const { + WKPreferencesRef preferencesRef = WKPageGroupGetPreferences(webViewPrivate->pageGroup.get()); switch (type) { case MinimumFontSize: - return preferences()->minimumFontSize(); + return static_cast<unsigned>(WKPreferencesGetMinimumFontSize(preferencesRef)); case DefaultFontSize: - return preferences()->defaultFontSize(); + return static_cast<unsigned>(WKPreferencesGetDefaultFontSize(preferencesRef)); case DefaultFixedFontSize: - return preferences()->defaultFixedFontSize(); + return static_cast<unsigned>(WKPreferencesGetDefaultFixedFontSize(preferencesRef)); default: ASSERT_NOT_REACHED(); return false; @@ -546,25 +556,6 @@ void QWebPreferences::setWebAudioEnabled(bool enable) #endif } -bool QWebPreferences::scrollAnimatorEnabled() const -{ -#if ENABLE(SMOOTH_SCROLLING) - return d->testAttribute(QWebPreferencesPrivate::ScrollAnimatorEnabled); -#else - return false; -#endif -} - -void QWebPreferences::setScrollAnimatorEnabled(bool enable) -{ -#if ENABLE(SMOOTH_SCROLLING) - d->setAttribute(QWebPreferencesPrivate::ScrollAnimatorEnabled, enable); - emit scrollAnimatorEnabledChanged(); -#else - UNUSED_PARAM(enable); -#endif -} - bool QWebPreferences::caretBrowsingEnabled() const { return d->testAttribute(QWebPreferencesPrivate::CaretBrowsingEnabled); @@ -587,9 +578,30 @@ void QWebPreferences::setNotificationsEnabled(bool enable) emit notificationsEnabledChanged(); } -WebKit::WebPreferences* QWebPreferencesPrivate::preferences() const +bool QWebPreferences::universalAccessFromFileURLsAllowed() const +{ + return d->testAttribute(QWebPreferencesPrivate::UniversalAccessFromFileURLsAllowed); +} + +void QWebPreferences::setUniversalAccessFromFileURLsAllowed(bool enable) +{ + if (universalAccessFromFileURLsAllowed() == enable) + return; + d->setAttribute(QWebPreferencesPrivate::UniversalAccessFromFileURLsAllowed, enable); + emit universalAccessFromFileURLsAllowedChanged(); +} + +bool QWebPreferences::fileAccessFromFileURLsAllowed() const { - return webViewPrivate->webPageProxy->pageGroup()->preferences(); + return d->testAttribute(QWebPreferencesPrivate::FileAccessFromFileURLsAllowed); +} + +void QWebPreferences::setFileAccessFromFileURLsAllowed(bool enable) +{ + if (fileAccessFromFileURLsAllowed() == enable) + return; + d->setAttribute(QWebPreferencesPrivate::FileAccessFromFileURLsAllowed, enable); + emit fileAccessFromFileURLsAllowedChanged(); } QWebPreferencesPrivate* QWebPreferencesPrivate::get(QWebPreferences* preferences) diff --git a/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p.h b/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p.h index e3fab79ab..9c503d431 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p.h @@ -45,9 +45,10 @@ public: Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled NOTIFY developerExtrasEnabledChanged FINAL) Q_PROPERTY(bool webGLEnabled READ webGLEnabled WRITE setWebGLEnabled NOTIFY webGLEnabledChanged FINAL) Q_PROPERTY(bool webAudioEnabled READ webAudioEnabled WRITE setWebAudioEnabled NOTIFY webAudioEnabledChanged FINAL) - Q_PROPERTY(bool scrollAnimatorEnabled READ scrollAnimatorEnabled WRITE setScrollAnimatorEnabled NOTIFY scrollAnimatorEnabledChanged FINAL) Q_PROPERTY(bool caretBrowsingEnabled READ caretBrowsingEnabled WRITE setCaretBrowsingEnabled NOTIFY caretBrowsingEnabledChanged FINAL) Q_PROPERTY(bool notificationsEnabled READ notificationsEnabled WRITE setNotificationsEnabled NOTIFY notificationsEnabledChanged FINAL) + Q_PROPERTY(bool universalAccessFromFileURLsAllowed READ universalAccessFromFileURLsAllowed WRITE setUniversalAccessFromFileURLsAllowed NOTIFY universalAccessFromFileURLsAllowedChanged FINAL) + Q_PROPERTY(bool fileAccessFromFileURLsAllowed READ fileAccessFromFileURLsAllowed WRITE setFileAccessFromFileURLsAllowed NOTIFY fileAccessFromFileURLsAllowedChanged FINAL) Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily NOTIFY standardFontFamilyChanged FINAL) Q_PROPERTY(QString fixedFontFamily READ fixedFontFamily WRITE setFixedFontFamily NOTIFY fixedFontFamilyChanged FINAL) @@ -102,15 +103,18 @@ public: bool webAudioEnabled() const; void setWebAudioEnabled(bool enable); - bool scrollAnimatorEnabled() const; - void setScrollAnimatorEnabled(bool enable); - bool caretBrowsingEnabled() const; void setCaretBrowsingEnabled(bool enable); bool notificationsEnabled() const; void setNotificationsEnabled(bool enable); + bool universalAccessFromFileURLsAllowed() const; + void setUniversalAccessFromFileURLsAllowed(bool enable); + + bool fileAccessFromFileURLsAllowed() const; + void setFileAccessFromFileURLsAllowed(bool enable); + QString standardFontFamily() const; void setStandardFontFamily(const QString& family); @@ -153,9 +157,10 @@ Q_SIGNALS: void developerExtrasEnabledChanged(); void webGLEnabledChanged(); void webAudioEnabledChanged(); - void scrollAnimatorEnabledChanged(); void caretBrowsingEnabledChanged(); void notificationsEnabledChanged(); + void universalAccessFromFileURLsAllowedChanged(); + void fileAccessFromFileURLsAllowedChanged(); void standardFontFamilyChanged(); void fixedFontFamilyChanged(); diff --git a/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p_p.h b/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p_p.h index c8098b50e..844fd5b4e 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qwebpreferences_p_p.h @@ -20,8 +20,6 @@ #ifndef qwebpreferences_p_p_h #define qwebpreferences_p_p_h -#include "WebPreferences.h" - class QQuickWebViewPrivate; class QWebPreferencesPrivate { @@ -42,9 +40,10 @@ public: WebGLEnabled, CSSCustomFilterEnabled, WebAudioEnabled, - ScrollAnimatorEnabled, CaretBrowsingEnabled, - NotificationsEnabled + NotificationsEnabled, + UniversalAccessFromFileURLsAllowed, + FileAccessFromFileURLsAllowed }; enum FontFamily { @@ -74,8 +73,6 @@ public: void setFontSize(FontSizeType type, unsigned size); unsigned fontSize(FontSizeType type) const; - WebKit::WebPreferences* preferences() const; - QQuickWebViewPrivate* webViewPrivate; static QWebPreferencesPrivate* get(QWebPreferences*); diff --git a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp index 3f9c3b2ae..89f729705 100644 --- a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp +++ b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp @@ -20,10 +20,9 @@ #include "config.h" #include "qrawwebview_p.h" +#include "CoordinatedLayerTreeHostProxy.h" #include "Cursor.h" #include "DrawingAreaProxyImpl.h" -#include "LayerTreeCoordinatorProxy.h" -#include "LayerTreeRenderer.h" #include "NativeWebKeyboardEvent.h" #include "NativeWebMouseEvent.h" #if ENABLE(TOUCH_EVENTS) @@ -35,13 +34,9 @@ #include "WebPageGroup.h" #include "WebPreferences.h" #include "qrawwebview_p_p.h" +#include <WebCore/CoordinatedGraphicsScene.h> #include <WebKit2/qrawwebview_p.h> -void QRawWebViewPrivate::didReceiveMessageFromNavigatorQtObject(const String& message) -{ - notImplemented(); -} - void QRawWebViewPrivate::didChangeViewportProperties(const WebCore::ViewportAttributes& attr) { notImplemented(); @@ -195,10 +190,10 @@ PassRefPtr<WebKit::WebContextMenuProxy> QRawWebViewPrivate::createContextMenuPro } #if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebKit::WebColorChooserProxy> QRawWebViewPrivate::createColorChooserProxy(WebKit::WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&) +PassRefPtr<WebKit::WebColorPicker> QRawWebViewPrivate::createColorPicker(WebKit::WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&) { notImplemented(); - return PassRefPtr<WebKit::WebColorChooserProxy>(); + return PassRefPtr<WebKit::WebColorPicker>(); } #endif @@ -329,7 +324,7 @@ void QRawWebView::setActive(bool active) { d->m_active = active; d->m_webPageProxy->viewStateDidChange(WebKit::WebPageProxy::ViewWindowIsActive); - layerTreeRenderer()->setActive(active); + coordinatedGraphicsScene()->setActive(active); } QSize QRawWebView::size() const @@ -344,18 +339,12 @@ void QRawWebView::setSize(const QSize& size) return; if (d->m_webPageProxy->useFixedLayout()) - d->m_webPageProxy->setViewportSize(size); - else { - WebKit::LayerTreeCoordinatorProxy* coordinator = drawingArea->layerTreeCoordinatorProxy(); - if (!coordinator) - return; - coordinator->setContentsSize(WebCore::FloatSize(size.width(), size.height())); - } + drawingArea->setSize(size, WebCore::IntSize(), WebCore::IntSize()); d->m_size = size; - drawingArea->setSize(d->m_size, WebCore::IntSize()); - drawingArea->setVisibleContentsRect(WebCore::IntRect(WebCore::IntPoint(), d->m_size), 1 /*scale*/, WebCore::FloatPoint()); + drawingArea->setSize(d->m_size, WebCore::IntSize(), WebCore::IntSize()); + drawingArea->setVisibleContentsRect(WebCore::IntRect(WebCore::IntPoint(), d->m_size), WebCore::FloatPoint()); } WKPageRef QRawWebView::pageRef() @@ -363,28 +352,28 @@ WKPageRef QRawWebView::pageRef() return toAPI(d->m_webPageProxy.get()); } -WebKit::LayerTreeRenderer* QRawWebView::layerTreeRenderer() const +WebCore::CoordinatedGraphicsScene* QRawWebView::coordinatedGraphicsScene() const { WebKit::DrawingAreaProxy* drawingArea = d->m_webPageProxy->drawingArea(); if (!drawingArea) return 0; - WebKit::LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy = drawingArea->layerTreeCoordinatorProxy(); - if (!layerTreeCoordinatorProxy) + WebKit::CoordinatedLayerTreeHostProxy* coordinatedLayerTreeHostProxy = drawingArea->coordinatedLayerTreeHostProxy(); + if (!coordinatedLayerTreeHostProxy) return 0; - return layerTreeCoordinatorProxy->layerTreeRenderer(); + return coordinatedLayerTreeHostProxy->coordinatedGraphicsScene(); } void QRawWebView::paint(const QMatrix4x4& transform, float opacity, unsigned paintFlags) { - WebKit::LayerTreeRenderer* renderer = layerTreeRenderer(); - if (!renderer) + WebCore::CoordinatedGraphicsScene* scene = coordinatedGraphicsScene(); + if (!scene) return; - renderer->setActive(true); + scene->setActive(true); WebCore::FloatRect rect(0, 0, d->m_size.width(), d->m_size.height()); - renderer->paintToCurrentGLContext(transform, opacity, transform.mapRect(rect), paintFlags); + scene->paintToCurrentGLContext(transform, opacity, transform.mapRect(rect), paintFlags); } void QRawWebView::sendKeyEvent(QKeyEvent* event) diff --git a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p.h b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p.h index 015815ad8..4ae3e5e53 100644 --- a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p.h +++ b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p.h @@ -47,8 +47,8 @@ QT_END_NAMESPACE class QRawWebViewPrivate; -namespace WebKit { -class LayerTreeRenderer; +namespace WebCore { +class CoordinatedGraphicsScene; } class QRawWebViewClient { @@ -101,7 +101,7 @@ public: void sendTouchEvent(QTouchEvent*); private: - WebKit::LayerTreeRenderer* layerTreeRenderer() const; + WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene() const; QRawWebViewPrivate* d; }; diff --git a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p_p.h b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p_p.h index 7bc6f1162..58d6b1390 100644 --- a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p_p.h @@ -37,17 +37,11 @@ public: virtual void pageClosed() { } + virtual void preferencesDidChange() { } + virtual void setFindIndicator(PassRefPtr<WebKit::FindIndicator>, bool fadeOut, bool animate) { } - virtual void didCommitLoadForMainFrame(bool useCustomRepresentation) { } - virtual void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&) { } - virtual double customRepresentationZoomFactor() { return 1; } - virtual void setCustomRepresentationZoomFactor(double) { } - virtual void didChangeScrollbarsForMainFrame() const { } - virtual void findStringInCustomRepresentation(const String&, WebKit::FindOptions, unsigned maxMatchCount) { } - virtual void countStringMatchesInCustomRepresentation(const String&, WebKit::FindOptions, unsigned maxMatchCount) { } virtual void clearAllEditCommands() { } - virtual void didReceiveMessageFromNavigatorQtObject(const String& message); virtual void didChangeViewportProperties(const WebCore::ViewportAttributes& attr); virtual void handleDownloadRequest(WebKit::DownloadProxy* download); @@ -76,6 +70,7 @@ public: virtual void doneWithGestureEvent(const WebKit::WebGestureEvent& event, bool wasEventHandled); #endif virtual void displayView(); + virtual bool canScrollView() { return false; } virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>&); @@ -91,7 +86,7 @@ public: virtual PassRefPtr<WebKit::WebContextMenuProxy> createContextMenuProxy(WebKit::WebPageProxy* webPageProxy); #if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebKit::WebColorChooserProxy> createColorChooserProxy(WebKit::WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&); + virtual PassRefPtr<WebKit::WebColorPicker> createColorPicker(WebKit::WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&); #endif QRawWebViewPrivate(WebKit::WebContext*, WebKit::WebPageGroup*, QRawWebViewClient*); diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_favIconLoad.qml b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_favIconLoad.qml index 6f0858696..4437b10a4 100644 --- a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_favIconLoad.qml +++ b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_favIconLoad.qml @@ -14,6 +14,7 @@ TestWebView { Image { id: favicon + asynchronous: true source: webView.icon } @@ -26,8 +27,8 @@ TestWebView { if (webView.icon != '') { // If this is not the first test, then load a blank page without favicon, restoring the initial state. webView.url = 'about:blank' - spy.wait() verify(webView.waitForLoadSucceeded()) + spy.wait() } spy.clear() } @@ -36,6 +37,7 @@ TestWebView { compare(spy.count, 0) var url = Qt.resolvedUrl("../common/favicon.html") webView.url = url + verify(webView.waitForLoadSucceeded()) spy.wait() compare(spy.count, 1) compare(favicon.width, 48) @@ -46,6 +48,7 @@ TestWebView { compare(spy.count, 0) var url = Qt.resolvedUrl("../common/favicon2.html?favicon=load should work with#whitespace!") webView.url = url + verify(webView.waitForLoadSucceeded()) spy.wait() compare(spy.count, 1) compare(favicon.width, 16) diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_findText.qml b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_findText.qml new file mode 100644 index 000000000..f1ea15c50 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_findText.qml @@ -0,0 +1,145 @@ +import QtQuick 2.0 +import QtTest 1.0 +import QtWebKit 3.0 +import QtWebKit.experimental 1.0 +import "../common" + +TestWebView { + id: webView + width: 400 + height: 300 + + property int matchCount: -1 + property bool findFailed: false + function clear() { + textFoundSpy.clear() + findFailed = false + matchCount = -1 + } + + SignalSpy { + id: textFoundSpy + target: webView.experimental + signalName: "textFound" + } + + experimental.onTextFound: { + webView.matchCount = matchCount + findFailed = matchCount == 0 + } + TestCase { + name: "WebViewFindText" + + function test_findText() { + var findFlags = WebViewExperimental.FindHighlightAllOccurrences | + WebViewExperimental.FindCaseSensitively + webView.clear() + webView.url = Qt.resolvedUrl("../common/test1.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("Hello", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(matchCount, 1) + } + function test_findTextCaseInsensitive() { + var findFlags = 0 + + webView.clear() + webView.url = Qt.resolvedUrl("../common/test1.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("heLLo", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(matchCount, 1) + } + function test_findTextManyMatches() { + var findFlags = WebViewExperimental.FindHighlightAllOccurrences + webView.clear() + webView.url = Qt.resolvedUrl("../common/test4.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("bla", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(matchCount, 100) + } + function test_findTextBackward() { + var findFlags = WebViewExperimental.FindHighlightAllOccurrences + webView.clear() + webView.url = Qt.resolvedUrl("../common/test4.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(matchCount, 10) + for(var i=0; i < 9; i++) { + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + } + compare(textFoundSpy.count, 10) + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 11) + compare(findFailed, true) + + webView.clear() + findFlags |= WebViewExperimental.FindBackward + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + } + function test_findTextFailNoWrap() { + var findFlags = WebViewExperimental.FindHighlightAllOccurrences + webView.clear() + webView.url = Qt.resolvedUrl("../common/test4.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(matchCount, 10) + for(var i=0; i < 9; i++) { + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + } + compare(textFoundSpy.count, 10) + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 11) + compare(findFailed, true) + } + function test_findTextWrap() { + var findFlags = WebViewExperimental.FindHighlightAllOccurrences + findFlags |= WebViewExperimental.FindWrapsAroundDocument + webView.clear() + webView.url = Qt.resolvedUrl("../common/test4.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(matchCount, 10) + for(var i=0; i < 19; i++) { + webView.experimental.findText("bla0", findFlags) + textFoundSpy.wait() + } + compare(textFoundSpy.count, 20) + } + function test_findTextFailCaseSensitive() { + var findFlags = WebViewExperimental.FindCaseSensitively + webView.clear() + webView.url = Qt.resolvedUrl("../common/test1.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("heLLo", findFlags) + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(findFailed, true) + } + function test_findTextNotFound() { + webView.clear() + webView.url = Qt.resolvedUrl("../common/test1.html") + verify(webView.waitForLoadSucceeded()) + webView.experimental.findText("string-that-is-not-threre") + textFoundSpy.wait() + compare(textFoundSpy.count, 1) + compare(findFailed, true) + } + } +} diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_resize.qml b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_resize.qml index 5f6c63b57..dea000868 100644 --- a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_resize.qml +++ b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_resize.qml @@ -52,7 +52,7 @@ Item { function init() { resultSpy.clear() scaleSpy.clear() - viewportSpy.clear() + sizeSpy.clear() } function run(signalSpy, script) { diff --git a/Source/WebKit2/UIProcess/API/qt/tests/util.cpp b/Source/WebKit2/UIProcess/API/qt/tests/util.cpp index fce3cc7f6..3b0c45f7d 100644 --- a/Source/WebKit2/UIProcess/API/qt/tests/util.cpp +++ b/Source/WebKit2/UIProcess/API/qt/tests/util.cpp @@ -74,26 +74,6 @@ void suppressDebugOutput() } #if defined(HAVE_QTQUICK) && HAVE_QTQUICK -class LoadSpy : public QEventLoop { - Q_OBJECT -public: - LoadSpy(QQuickWebView* webView) - { - connect(webView, SIGNAL(loadingChanged(QWebLoadRequest*)), SLOT(onLoadingChanged(QWebLoadRequest*))); - } -Q_SIGNALS: - void loadSucceeded(); - void loadFailed(); -private Q_SLOTS: - void onLoadingChanged(QWebLoadRequest* loadRequest) - { - if (loadRequest->status() == QQuickWebView::LoadSucceededStatus) - emit loadSucceeded(); - else if (loadRequest->status() == QQuickWebView::LoadFailedStatus) - emit loadFailed(); - } -}; - bool waitForLoadSucceeded(QQuickWebView* webView, int timeout) { QEventLoop loop; @@ -133,6 +113,19 @@ bool waitForViewportReady(QQuickWebView* webView, int timeout) return waitForSignal(webView->experimental(), SIGNAL(loadVisuallyCommitted()), timeout); } +LoadSpy::LoadSpy(QQuickWebView* webView) +{ + connect(webView, SIGNAL(loadingChanged(QWebLoadRequest*)), SLOT(onLoadingChanged(QWebLoadRequest*))); +} + +void LoadSpy::onLoadingChanged(QWebLoadRequest* loadRequest) +{ + if (loadRequest->status() == QQuickWebView::LoadSucceededStatus) + emit loadSucceeded(); + else if (loadRequest->status() == QQuickWebView::LoadFailedStatus) + emit loadFailed(); +} + LoadStartedCatcher::LoadStartedCatcher(QQuickWebView* webView) : m_webView(webView) { @@ -148,5 +141,3 @@ void LoadStartedCatcher::onLoadingChanged(QWebLoadRequest* loadRequest) } } #endif - -#include "util.moc" diff --git a/Source/WebKit2/UIProcess/API/qt/tests/util.h b/Source/WebKit2/UIProcess/API/qt/tests/util.h index 4834029b4..8711d5b1e 100644 --- a/Source/WebKit2/UIProcess/API/qt/tests/util.h +++ b/Source/WebKit2/UIProcess/API/qt/tests/util.h @@ -38,10 +38,22 @@ bool waitForLoadSucceeded(QQuickWebView* webView, int timeout = 10000); bool waitForLoadFailed(QQuickWebView* webView, int timeout = 10000); bool waitForViewportReady(QQuickWebView* webView, int timeout = 10000); +class LoadSpy : public QEventLoop { + Q_OBJECT +public: + LoadSpy(QQuickWebView* webView); +Q_SIGNALS: + void loadSucceeded(); + void loadFailed(); +private Q_SLOTS: + void onLoadingChanged(QWebLoadRequest* loadRequest); +}; + class LoadStartedCatcher : public QObject { Q_OBJECT public: LoadStartedCatcher(QQuickWebView* webView); + virtual ~LoadStartedCatcher() { } public Q_SLOTS: void onLoadingChanged(QWebLoadRequest* loadRequest); Q_SIGNALS: diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp index 7f4e958ed..9f64885ae 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp @@ -28,19 +28,19 @@ #include "AuthenticationDecisionListener.h" #include "AuthenticationManagerMessages.h" +#include "ChildProcessProxy.h" #include "WebCertificateInfo.h" #include "WebCoreArgumentCoders.h" #include "WebCredential.h" -#include "WebPageProxy.h" #include "WebProcessProxy.h" #include "WebProtectionSpace.h" namespace WebKit { -AuthenticationChallengeProxy::AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, WebProcessProxy* process) +AuthenticationChallengeProxy::AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, CoreIPC::Connection* connection) : m_coreAuthenticationChallenge(authenticationChallenge) , m_challengeID(challengeID) - , m_process(process) + , m_connection(connection) { ASSERT(m_challengeID); m_listener = AuthenticationDecisionListener::create(this); @@ -49,9 +49,9 @@ AuthenticationChallengeProxy::AuthenticationChallengeProxy(const WebCore::Authen AuthenticationChallengeProxy::~AuthenticationChallengeProxy() { // If an outstanding AuthenticationChallengeProxy is being destroyed even though it hasn't been responded to yet, - // we cancel it here so the WebProcess isn't waiting for an answer forever. + // we cancel it here so the process isn't waiting for an answer forever. if (m_challengeID) - m_process->send(Messages::AuthenticationManager::CancelChallenge(m_challengeID), 0); + m_connection->send(Messages::AuthenticationManager::CancelChallenge(m_challengeID), 0); if (m_listener) m_listener->detachChallenge(); @@ -63,11 +63,11 @@ void AuthenticationChallengeProxy::useCredential(WebCredential* credential) return; if (!credential) - m_process->send(Messages::AuthenticationManager::ContinueWithoutCredentialForChallenge(m_challengeID), 0); + m_connection->send(Messages::AuthenticationManager::ContinueWithoutCredentialForChallenge(m_challengeID), 0); else { WebCertificateInfo* certificateInfo = credential->certificateInfo(); PlatformCertificateInfo platformInfo = certificateInfo ? certificateInfo->platformCertificateInfo() : PlatformCertificateInfo(); - m_process->send(Messages::AuthenticationManager::UseCredentialForChallenge(m_challengeID, credential->core(), platformInfo), 0); + m_connection->send(Messages::AuthenticationManager::UseCredentialForChallenge(m_challengeID, credential->core(), platformInfo), 0); } m_challengeID = 0; @@ -78,7 +78,7 @@ void AuthenticationChallengeProxy::cancel() if (!m_challengeID) return; - m_process->send(Messages::AuthenticationManager::CancelChallenge(m_challengeID), 0); + m_connection->send(Messages::AuthenticationManager::CancelChallenge(m_challengeID), 0); m_challengeID = 0; } diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h index 51379eefb..ce3d6d6e5 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h @@ -31,25 +31,21 @@ #include <wtf/PassRefPtr.h> namespace CoreIPC { - class ArgumentDecoder; - class Connection; - class MessageID; +class Connection; } namespace WebKit { class AuthenticationDecisionListener; +class ChildProcessProxy; class WebCredential; -class WebProcessProxy; class WebProtectionSpace; -class AuthenticationChallengeProxy : public APIObject { +class AuthenticationChallengeProxy : public TypedAPIObject<APIObject::TypeAuthenticationChallenge> { public: - static const Type APIType = TypeAuthenticationChallenge; - - static PassRefPtr<AuthenticationChallengeProxy> create(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, WebProcessProxy* process) + static PassRefPtr<AuthenticationChallengeProxy> create(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, CoreIPC::Connection* connection) { - return adoptRef(new AuthenticationChallengeProxy(authenticationChallenge, challengeID, process)); + return adoptRef(new AuthenticationChallengeProxy(authenticationChallenge, challengeID, connection)); } ~AuthenticationChallengeProxy(); @@ -64,13 +60,11 @@ public: const WebCore::AuthenticationChallenge& core() { return m_coreAuthenticationChallenge; } private: - AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge&, uint64_t challengeID, WebProcessProxy*); + AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge&, uint64_t challengeID, CoreIPC::Connection*); - virtual Type type() const { return APIType; } - WebCore::AuthenticationChallenge m_coreAuthenticationChallenge; uint64_t m_challengeID; - RefPtr<WebProcessProxy> m_process; + RefPtr<CoreIPC::Connection> m_connection; RefPtr<AuthenticationDecisionListener> m_listener; mutable RefPtr<WebCredential> m_webCredential; mutable RefPtr<WebProtectionSpace> m_webProtectionSpace; diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h b/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h index b2f92f4b0..940a65021 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h @@ -35,10 +35,8 @@ namespace WebKit { class AuthenticationChallengeProxy; class WebCredential; -class AuthenticationDecisionListener : public APIObject { +class AuthenticationDecisionListener : public TypedAPIObject<APIObject::TypeAuthenticationDecisionListener> { public: - static const Type APIType = TypeAuthenticationDecisionListener; - static PassRefPtr<AuthenticationDecisionListener> create(AuthenticationChallengeProxy* authenticationChallenge) { return adoptRef(new AuthenticationDecisionListener(authenticationChallenge)); @@ -52,8 +50,6 @@ public: private: explicit AuthenticationDecisionListener(AuthenticationChallengeProxy*); - virtual Type type() const { return APIType; } - AuthenticationChallengeProxy* m_challengeProxy; }; diff --git a/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp b/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp index 6d70c5fbc..a69d509c7 100644 --- a/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp +++ b/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp @@ -40,6 +40,10 @@ WebCredential::WebCredential(WebCertificateInfo* certificateInfo) { } +WebCredential::~WebCredential() +{ +} + WebCertificateInfo* WebCredential::certificateInfo() { return m_certificateInfo.get(); diff --git a/Source/WebKit2/UIProcess/Authentication/WebCredential.h b/Source/WebKit2/UIProcess/Authentication/WebCredential.h index 9f42d02e4..a957e7827 100644 --- a/Source/WebKit2/UIProcess/Authentication/WebCredential.h +++ b/Source/WebKit2/UIProcess/Authentication/WebCredential.h @@ -37,9 +37,9 @@ namespace WebKit { class WebCertificateInfo; -class WebCredential : public APIObject { +class WebCredential : public TypedAPIObject<APIObject::TypeCredential> { public: - static const Type APIType = TypeCredential; + ~WebCredential(); static PassRefPtr<WebCredential> create(const WebCore::Credential& credential) { @@ -66,8 +66,6 @@ private: explicit WebCredential(const WebCore::Credential&); explicit WebCredential(WebCertificateInfo*); - virtual Type type() const { return APIType; } - WebCore::Credential m_coreCredential; RefPtr<WebCertificateInfo> m_certificateInfo; }; diff --git a/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h b/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h index 7c3882aad..4d4905fe9 100644 --- a/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h +++ b/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h @@ -32,10 +32,8 @@ namespace WebKit { -class WebProtectionSpace : public APIObject { +class WebProtectionSpace : public TypedAPIObject<APIObject::TypeProtectionSpace> { public: - static const Type APIType = TypeProtectionSpace; - static PassRefPtr<WebProtectionSpace> create(const WebCore::ProtectionSpace& protectionSpace) { return adoptRef(new WebProtectionSpace(protectionSpace)); @@ -53,8 +51,6 @@ public: private: explicit WebProtectionSpace(const WebCore::ProtectionSpace&); - virtual Type type() const { return APIType; } - WebCore::ProtectionSpace m_coreProtectionSpace; }; diff --git a/Source/WebKit2/UIProcess/BackingStore.h b/Source/WebKit2/UIProcess/BackingStore.h index bd301bbe4..7c2613feb 100644 --- a/Source/WebKit2/UIProcess/BackingStore.h +++ b/Source/WebKit2/UIProcess/BackingStore.h @@ -32,8 +32,6 @@ #if PLATFORM(MAC) #include <wtf/RetainPtr.h> -#elif PLATFORM(WIN) || PLATFORM(WIN_CAIRO) -#include <wtf/OwnPtr.h> #endif #if PLATFORM(QT) @@ -41,7 +39,7 @@ #include <QtGui/QPixmap> #endif -#if USE(CAIRO) && !PLATFORM(WIN_CAIRO) +#if USE(CAIRO) #include <RefPtrCairo.h> #include <WebCore/WidgetBackingStore.h> #endif @@ -64,8 +62,6 @@ public: #if PLATFORM(MAC) typedef CGContextRef PlatformGraphicsContext; -#elif PLATFORM(WIN) - typedef HDC PlatformGraphicsContext; #elif PLATFORM(QT) typedef QPainter* PlatformGraphicsContext; #elif USE(CAIRO) @@ -100,8 +96,6 @@ private: // Contents of m_scrolledRect are offset by this amount (and wrapped around) with respect to // their original location. WebCore::IntSize m_scrolledRectOffset; -#elif PLATFORM(WIN) || PLATFORM(WIN_CAIRO) - OwnPtr<HBITMAP> m_bitmap; #elif PLATFORM(QT) QPixmap m_pixmap; #elif USE(CAIRO) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp deleted file mode 100644 index 17c18bd1a..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "CoordinatedBackingStore.h" - -#if USE(COORDINATED_GRAPHICS) -#include "GraphicsLayer.h" -#include "ShareableSurface.h" -#include "TextureMapper.h" -#include "TextureMapperGL.h" - -using namespace WebCore; - -namespace WebKit { - -void CoordinatedBackingStoreTile::swapBuffers(WebCore::TextureMapper* textureMapper) -{ - if (!m_surface) - return; - - FloatRect tileRect(m_tileRect); - tileRect.scale(1. / m_scale); - bool shouldReset = false; - if (tileRect != rect()) { - setRect(tileRect); - shouldReset = true; - } - RefPtr<BitmapTexture> texture = this->texture(); - if (!texture) { - texture = textureMapper->createTexture(); - setTexture(texture.get()); - shouldReset = true; - } - - ASSERT(textureMapper->maxTextureSize().width() >= m_tileRect.size().width() && textureMapper->maxTextureSize().height() >= m_tileRect.size().height()); - if (shouldReset) - texture->reset(m_tileRect.size(), m_surface->flags() & ShareableBitmap::SupportsAlpha ? BitmapTexture::SupportsAlpha : 0); - - m_surface->copyToTexture(texture, m_sourceRect, m_surfaceOffset); - m_surface.clear(); -} - -void CoordinatedBackingStoreTile::setBackBuffer(const IntRect& tileRect, const IntRect& sourceRect, PassRefPtr<ShareableSurface> buffer, const IntPoint& offset) -{ - m_sourceRect = sourceRect; - m_tileRect = tileRect; - m_surfaceOffset = offset; - m_surface = buffer; -} - -void CoordinatedBackingStore::createTile(int id, float scale) -{ - m_tiles.add(id, CoordinatedBackingStoreTile(scale)); - m_scale = scale; -} - -void CoordinatedBackingStore::removeTile(int id) -{ - ASSERT(m_tiles.contains(id)); - m_tilesToRemove.add(id); -} - -void CoordinatedBackingStore::removeAllTiles() -{ - HashMap<int, CoordinatedBackingStoreTile>::iterator end = m_tiles.end(); - for (HashMap<int, CoordinatedBackingStoreTile>::iterator it = m_tiles.begin(); it != end; ++it) - m_tilesToRemove.add(it->key); -} - -void CoordinatedBackingStore::updateTile(int id, const IntRect& sourceRect, const IntRect& tileRect, PassRefPtr<ShareableSurface> backBuffer, const IntPoint& offset) -{ - HashMap<int, CoordinatedBackingStoreTile>::iterator it = m_tiles.find(id); - ASSERT(it != m_tiles.end()); - it->value.incrementRepaintCount(); - it->value.setBackBuffer(tileRect, sourceRect, backBuffer, offset); -} - -PassRefPtr<BitmapTexture> CoordinatedBackingStore::texture() const -{ - HashMap<int, CoordinatedBackingStoreTile>::const_iterator end = m_tiles.end(); - for (HashMap<int, CoordinatedBackingStoreTile>::const_iterator it = m_tiles.begin(); it != end; ++it) { - RefPtr<BitmapTexture> texture = it->value.texture(); - if (texture) - return texture; - } - - return PassRefPtr<BitmapTexture>(); -} - -void CoordinatedBackingStore::setSize(const WebCore::FloatSize& size) -{ - m_pendingSize = size; -} - -static bool shouldShowTileDebugVisuals() -{ -#if PLATFORM(QT) - return (qgetenv("QT_WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS") == "1"); -#elif USE(CAIRO) - return (String(getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS")) == "1"); -#endif - return false; -} - -void CoordinatedBackingStore::paintTilesToTextureMapper(Vector<TextureMapperTile*>& tiles, TextureMapper* textureMapper, const TransformationMatrix& transform, float opacity, BitmapTexture* mask, const FloatRect& rect) -{ - for (size_t i = 0; i < tiles.size(); ++i) { - TextureMapperTile* tile = tiles[i]; - tile->paint(textureMapper, transform, opacity, mask, calculateExposedTileEdges(rect, tile->rect())); - static bool shouldDebug = shouldShowTileDebugVisuals(); - if (!shouldDebug) - continue; - - textureMapper->drawBorder(Color(0xFF, 0, 0), 2, tile->rect(), transform); - textureMapper->drawRepaintCounter(static_cast<CoordinatedBackingStoreTile*>(tile)->repaintCount(), 8, tile->rect().location(), transform); - } -} - -void CoordinatedBackingStore::paintToTextureMapper(TextureMapper* textureMapper, const FloatRect& targetRect, const TransformationMatrix& transform, float opacity, BitmapTexture* mask) -{ - if (m_tiles.isEmpty()) - return; - ASSERT(!m_size.isZero()); - - Vector<TextureMapperTile*> tilesToPaint; - Vector<TextureMapperTile*> previousTilesToPaint; - - // We have to do this every time we paint, in case the opacity has changed. - HashMap<int, CoordinatedBackingStoreTile>::iterator end = m_tiles.end(); - FloatRect coveredRect; - for (HashMap<int, CoordinatedBackingStoreTile>::iterator it = m_tiles.begin(); it != end; ++it) { - CoordinatedBackingStoreTile& tile = it->value; - if (!tile.texture()) - continue; - - if (tile.scale() == m_scale) { - tilesToPaint.append(&tile); - coveredRect.unite(tile.rect()); - continue; - } - - // Only show the previous tile if the opacity is high, otherwise effect looks like a bug. - // We show the previous-scale tile anyway if it doesn't intersect with any current-scale tile. - if (opacity < 0.95 && coveredRect.intersects(tile.rect())) - continue; - - previousTilesToPaint.append(&tile); - } - - FloatRect rectOnContents(FloatPoint::zero(), m_size); - TransformationMatrix adjustedTransform = transform; - // targetRect is on the contents coordinate system, so we must compare two rects on the contents coordinate system. - // See TiledBackingStore. - adjustedTransform.multiply(TransformationMatrix::rectToRect(rectOnContents, targetRect)); - - paintTilesToTextureMapper(previousTilesToPaint, textureMapper, adjustedTransform, opacity, mask, rectOnContents); - paintTilesToTextureMapper(tilesToPaint, textureMapper, adjustedTransform, opacity, mask, rectOnContents); -} - -void CoordinatedBackingStore::commitTileOperations(TextureMapper* textureMapper) -{ - HashSet<int>::iterator tilesToRemoveEnd = m_tilesToRemove.end(); - if (!m_pendingSize.isZero()) { - m_size = m_pendingSize; - m_pendingSize = FloatSize(); - } - - for (HashSet<int>::iterator it = m_tilesToRemove.begin(); it != tilesToRemoveEnd; ++it) - m_tiles.remove(*it); - m_tilesToRemove.clear(); - - HashMap<int, CoordinatedBackingStoreTile>::iterator tilesEnd = m_tiles.end(); - for (HashMap<int, CoordinatedBackingStoreTile>::iterator it = m_tiles.begin(); it != tilesEnd; ++it) - it->value.swapBuffers(textureMapper); -} - -} // namespace WebKit -#endif diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h deleted file mode 100644 index 3b747372d..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedBackingStore.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef CoordinatedBackingStore_h -#define CoordinatedBackingStore_h - -#if USE(COORDINATED_GRAPHICS) - -#include "TextureMapper.h" -#include "TextureMapperBackingStore.h" -#include <wtf/HashMap.h> -#include <wtf/HashSet.h> - -namespace WebKit { - -class ShareableSurface; - -class CoordinatedBackingStoreTile : public WebCore::TextureMapperTile { -public: - explicit CoordinatedBackingStoreTile(float scale = 1) - : TextureMapperTile(WebCore::FloatRect()) - , m_scale(scale) - , m_repaintCount(0) - { - } - - inline float scale() const { return m_scale; } - inline void incrementRepaintCount() { ++m_repaintCount; } - inline int repaintCount() const { return m_repaintCount; } - void swapBuffers(WebCore::TextureMapper*); - void setBackBuffer(const WebCore::IntRect&, const WebCore::IntRect&, PassRefPtr<ShareableSurface> buffer, const WebCore::IntPoint&); - -private: - RefPtr<ShareableSurface> m_surface; - WebCore::IntRect m_sourceRect; - WebCore::IntRect m_tileRect; - WebCore::IntPoint m_surfaceOffset; - float m_scale; - int m_repaintCount; -}; - -class CoordinatedBackingStore : public WebCore::TextureMapperBackingStore { -public: - void createTile(int, float); - void removeTile(int); - void removeAllTiles(); - void updateTile(int, const WebCore::IntRect&, const WebCore::IntRect&, PassRefPtr<ShareableSurface>, const WebCore::IntPoint&); - static PassRefPtr<CoordinatedBackingStore> create() { return adoptRef(new CoordinatedBackingStore); } - void commitTileOperations(WebCore::TextureMapper*); - PassRefPtr<WebCore::BitmapTexture> texture() const; - void setSize(const WebCore::FloatSize&); - virtual void paintToTextureMapper(WebCore::TextureMapper*, const WebCore::FloatRect&, const WebCore::TransformationMatrix&, float, WebCore::BitmapTexture*); - -private: - CoordinatedBackingStore() - : m_scale(1.) - { } - void paintTilesToTextureMapper(Vector<WebCore::TextureMapperTile*>&, WebCore::TextureMapper*, const WebCore::TransformationMatrix&, float, WebCore::BitmapTexture*, const WebCore::FloatRect&); - - HashMap<int, CoordinatedBackingStoreTile> m_tiles; - HashSet<int> m_tilesToRemove; - WebCore::FloatSize m_size; - float m_scale; - // FIXME: m_pendingSize should be removed after the following bug is fixed: https://bugs.webkit.org/show_bug.cgi?id=108294 - WebCore::FloatSize m_pendingSize; -}; - -} // namespace WebKit -#endif - -#endif // CoordinatedBackingStore_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp new file mode 100644 index 000000000..d42dcfdf3 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp @@ -0,0 +1,103 @@ +/* + Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2013 Company 100, Inc. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" + +#if USE(COORDINATED_GRAPHICS) +#include "CoordinatedLayerTreeHostProxy.h" + +#include "CoordinatedLayerTreeHostMessages.h" +#include "CoordinatedLayerTreeHostProxyMessages.h" +#include "DrawingAreaProxy.h" +#include "WebPageProxy.h" +#include "WebProcessProxy.h" +#include <WebCore/CoordinatedGraphicsState.h> + +namespace WebKit { + +using namespace WebCore; + +CoordinatedLayerTreeHostProxy::CoordinatedLayerTreeHostProxy(DrawingAreaProxy* drawingAreaProxy) + : m_drawingAreaProxy(drawingAreaProxy) + , m_scene(adoptRef(new CoordinatedGraphicsScene(this))) +{ + m_drawingAreaProxy->page()->process()->addMessageReceiver(Messages::CoordinatedLayerTreeHostProxy::messageReceiverName(), m_drawingAreaProxy->page()->pageID(), this); +} + +CoordinatedLayerTreeHostProxy::~CoordinatedLayerTreeHostProxy() +{ + m_drawingAreaProxy->page()->process()->removeMessageReceiver(Messages::CoordinatedLayerTreeHostProxy::messageReceiverName(), m_drawingAreaProxy->page()->pageID()); + m_scene->detach(); +} + +void CoordinatedLayerTreeHostProxy::updateViewport() +{ + m_drawingAreaProxy->updateViewport(); +} + +void CoordinatedLayerTreeHostProxy::dispatchUpdate(const Function<void()>& function) +{ + m_scene->appendUpdate(function); +} + +void CoordinatedLayerTreeHostProxy::commitCoordinatedGraphicsState(const CoordinatedGraphicsState& graphicsState) +{ + dispatchUpdate(bind(&CoordinatedGraphicsScene::commitSceneState, m_scene.get(), graphicsState)); + updateViewport(); +#if USE(TILED_BACKING_STORE) + m_drawingAreaProxy->page()->didRenderFrame(graphicsState.contentsSize, graphicsState.coveredRect); +#endif +} + +void CoordinatedLayerTreeHostProxy::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector) +{ + // Inform the renderer to adjust viewport-fixed layers. + dispatchUpdate(bind(&CoordinatedGraphicsScene::setScrollPosition, m_scene.get(), rect.location())); + + if (rect == m_lastSentVisibleRect && trajectoryVector == m_lastSentTrajectoryVector) + return; + + m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::SetVisibleContentsRect(rect, trajectoryVector), m_drawingAreaProxy->page()->pageID()); + m_lastSentVisibleRect = rect; + m_lastSentTrajectoryVector = trajectoryVector; +} + +void CoordinatedLayerTreeHostProxy::renderNextFrame() +{ + m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::RenderNextFrame(), m_drawingAreaProxy->page()->pageID()); +} + +void CoordinatedLayerTreeHostProxy::purgeBackingStores() +{ + m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::PurgeBackingStores(), m_drawingAreaProxy->page()->pageID()); +} + +void CoordinatedLayerTreeHostProxy::setBackgroundColor(const Color& color) +{ + dispatchUpdate(bind(&CoordinatedGraphicsScene::setBackgroundColor, m_scene.get(), color)); +} + +void CoordinatedLayerTreeHostProxy::commitScrollOffset(uint32_t layerID, const IntSize& offset) +{ + m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::CommitScrollOffset(layerID, offset), m_drawingAreaProxy->page()->pageID()); +} + +} +#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h new file mode 100644 index 000000000..2fb17b3ed --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h @@ -0,0 +1,75 @@ +/* + Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2013 Company 100, Inc. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef CoordinatedLayerTreeHostProxy_h +#define CoordinatedLayerTreeHostProxy_h + +#if USE(COORDINATED_GRAPHICS) + +#include "CoordinatedGraphicsArgumentCoders.h" +#include "MessageReceiver.h" +#include <WebCore/CoordinatedGraphicsScene.h> +#include <wtf/Functional.h> + +namespace WebCore { +class CoordinatedGraphicsState; +class IntSize; +} + +namespace WebKit { + +class DrawingAreaProxy; + +class CoordinatedLayerTreeHostProxy : public WebCore::CoordinatedGraphicsSceneClient, public CoreIPC::MessageReceiver { + WTF_MAKE_NONCOPYABLE(CoordinatedLayerTreeHostProxy); + WTF_MAKE_FAST_ALLOCATED; +public: + explicit CoordinatedLayerTreeHostProxy(DrawingAreaProxy*); + virtual ~CoordinatedLayerTreeHostProxy(); + + void commitCoordinatedGraphicsState(const WebCore::CoordinatedGraphicsState&); + void setBackgroundColor(const WebCore::Color&); + + void setVisibleContentsRect(const WebCore::FloatRect&, const WebCore::FloatPoint& trajectoryVector); + WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene() const { return m_scene.get(); } + + virtual void updateViewport() OVERRIDE; + virtual void renderNextFrame() OVERRIDE; + virtual void purgeBackingStores() OVERRIDE; + + virtual void commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset); + +protected: + void dispatchUpdate(const Function<void()>&); + + // CoreIPC::MessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + + DrawingAreaProxy* m_drawingAreaProxy; + RefPtr<WebCore::CoordinatedGraphicsScene> m_scene; + WebCore::FloatRect m_lastSentVisibleRect; + WebCore::FloatPoint m_lastSentTrajectoryVector; +}; + +} // namespace WebKit + +#endif // USE(COORDINATED_GRAPHICS) + +#endif // CoordinatedLayerTreeHostProxy_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in new file mode 100644 index 000000000..ae84b4395 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in @@ -0,0 +1,27 @@ +# +# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) +# Copyright (C) 2013 Company 100, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Library General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public License +# along with this library; see the file COPYING.LIB. If not, write to +# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301, USA. +# + +#if USE(COORDINATED_GRAPHICS) +messages -> CoordinatedLayerTreeHostProxy { + + CommitCoordinatedGraphicsState(WebCore::CoordinatedGraphicsState state) + SetBackgroundColor(WebCore::Color color) +} +#endif diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.cpp deleted file mode 100644 index 9cb2c1bc5..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* - Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" - -#if USE(COORDINATED_GRAPHICS) -#include "LayerTreeCoordinatorProxy.h" - -#include "LayerTreeCoordinatorMessages.h" -#include "LayerTreeRenderer.h" -#include "UpdateInfo.h" -#include "WebCoreArgumentCoders.h" -#include "WebLayerTreeInfo.h" -#include "WebPageProxy.h" -#include "WebProcessProxy.h" -#include <WebCore/GraphicsSurface.h> - -#if ENABLE(CSS_SHADERS) -#include "CustomFilterProgramInfo.h" -#endif - -namespace WebKit { - -using namespace WebCore; - -LayerTreeCoordinatorProxy::LayerTreeCoordinatorProxy(DrawingAreaProxy* drawingAreaProxy) - : m_drawingAreaProxy(drawingAreaProxy) - , m_renderer(adoptRef(new LayerTreeRenderer(this))) - , m_lastSentScale(0) -{ -} - -LayerTreeCoordinatorProxy::~LayerTreeCoordinatorProxy() -{ - m_renderer->detach(); -} - -void LayerTreeCoordinatorProxy::updateViewport() -{ - m_drawingAreaProxy->updateViewport(); -} - -float LayerTreeCoordinatorProxy::deviceScaleFactor() const -{ - return m_drawingAreaProxy->page()->deviceScaleFactor(); -} - -void LayerTreeCoordinatorProxy::dispatchUpdate(const Function<void()>& function) -{ - m_renderer->appendUpdate(function); -} - -void LayerTreeCoordinatorProxy::createTileForLayer(int layerID, int tileID, const WebCore::IntRect& tileRect, const WebKit::SurfaceUpdateInfo& updateInfo) -{ - dispatchUpdate(bind(&LayerTreeRenderer::createTile, m_renderer.get(), layerID, tileID, updateInfo.scaleFactor)); - updateTileForLayer(layerID, tileID, tileRect, updateInfo); -} - -void LayerTreeCoordinatorProxy::updateTileForLayer(int layerID, int tileID, const IntRect& tileRect, const WebKit::SurfaceUpdateInfo& updateInfo) -{ - SurfaceMap::iterator it = m_surfaces.find(updateInfo.atlasID); - ASSERT(it != m_surfaces.end()); - dispatchUpdate(bind(&LayerTreeRenderer::updateTile, m_renderer.get(), layerID, tileID, LayerTreeRenderer::TileUpdate(updateInfo.updateRect, tileRect, it->value, updateInfo.surfaceOffset))); -} - -void LayerTreeCoordinatorProxy::removeTileForLayer(int layerID, int tileID) -{ - dispatchUpdate(bind(&LayerTreeRenderer::removeTile, m_renderer.get(), layerID, tileID)); -} - -void LayerTreeCoordinatorProxy::createUpdateAtlas(int atlasID, const ShareableSurface::Handle& handle) -{ - ASSERT(!m_surfaces.contains(atlasID)); - m_surfaces.add(atlasID, ShareableSurface::create(handle)); -} - -void LayerTreeCoordinatorProxy::removeUpdateAtlas(int atlasID) -{ - ASSERT(m_surfaces.contains(atlasID)); - m_surfaces.remove(atlasID); -} - -void LayerTreeCoordinatorProxy::deleteCompositingLayer(WebLayerID id) -{ - dispatchUpdate(bind(&LayerTreeRenderer::deleteLayer, m_renderer.get(), id)); - updateViewport(); -} - -void LayerTreeCoordinatorProxy::setRootCompositingLayer(WebLayerID id) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setRootLayerID, m_renderer.get(), id)); - updateViewport(); -} - -void LayerTreeCoordinatorProxy::setCompositingLayerState(WebLayerID id, const WebLayerInfo& info) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setLayerState, m_renderer.get(), id, info)); -} - -void LayerTreeCoordinatorProxy::setCompositingLayerChildren(WebLayerID id, const Vector<WebLayerID>& children) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setLayerChildren, m_renderer.get(), id, children)); -} - -#if ENABLE(CSS_FILTERS) -void LayerTreeCoordinatorProxy::setCompositingLayerFilters(WebLayerID id, const FilterOperations& filters) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setLayerFilters, m_renderer.get(), id, filters)); -} -#endif - -#if ENABLE(CSS_SHADERS) -void LayerTreeCoordinatorProxy::removeCustomFilterProgram(int id) -{ - dispatchUpdate(bind(&LayerTreeRenderer::removeCustomFilterProgram, m_renderer.get(), id)); -} -void LayerTreeCoordinatorProxy::createCustomFilterProgram(int id, const WebCore::CustomFilterProgramInfo& programInfo) -{ - dispatchUpdate(bind(&LayerTreeRenderer::createCustomFilterProgram, m_renderer.get(), id, programInfo)); -} -#endif - -void LayerTreeCoordinatorProxy::didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) -{ - dispatchUpdate(bind(&LayerTreeRenderer::flushLayerChanges, m_renderer.get())); - updateViewport(); -#if USE(TILED_BACKING_STORE) - m_drawingAreaProxy->page()->didRenderFrame(contentsSize, coveredRect); -#else - UNUSED_PARAM(contentsSize); - UNUSED_PARAM(coveredRect); -#endif -} - -void LayerTreeCoordinatorProxy::createImageBacking(CoordinatedImageBackingID imageID) -{ - dispatchUpdate(bind(&LayerTreeRenderer::createImageBacking, m_renderer.get(), imageID)); -} - -void LayerTreeCoordinatorProxy::updateImageBacking(CoordinatedImageBackingID imageID, const ShareableSurface::Handle& handle) -{ - dispatchUpdate(bind(&LayerTreeRenderer::updateImageBacking, m_renderer.get(), imageID, ShareableSurface::create(handle))); -} - -void LayerTreeCoordinatorProxy::clearImageBackingContents(CoordinatedImageBackingID imageID) -{ - dispatchUpdate(bind(&LayerTreeRenderer::clearImageBackingContents, m_renderer.get(), imageID)); -} - -void LayerTreeCoordinatorProxy::removeImageBacking(CoordinatedImageBackingID imageID) -{ - dispatchUpdate(bind(&LayerTreeRenderer::removeImageBacking, m_renderer.get(), imageID)); -} - -void LayerTreeCoordinatorProxy::setContentsSize(const FloatSize& contentsSize) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setContentsSize, m_renderer.get(), contentsSize)); -} - -void LayerTreeCoordinatorProxy::setLayerAnimations(WebLayerID id, const GraphicsLayerAnimations& animations) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setLayerAnimations, m_renderer.get(), id, animations)); -} - -void LayerTreeCoordinatorProxy::setAnimationsLocked(bool locked) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setAnimationsLocked, m_renderer.get(), locked)); -} - -void LayerTreeCoordinatorProxy::setVisibleContentsRect(const FloatRect& rect, float pageScaleFactor, const FloatPoint& trajectoryVector) -{ - // Inform the renderer to adjust viewport-fixed layers. - dispatchUpdate(bind(&LayerTreeRenderer::setVisibleContentsRect, m_renderer.get(), rect)); - - // Round the rect instead of enclosing it to make sure that its size stays the same while panning. This can have nasty effects on layout. - IntRect roundedRect = roundedIntRect(rect); - const float effectiveScale = deviceScaleFactor() * pageScaleFactor; - if (roundedRect == m_lastSentVisibleRect && effectiveScale == m_lastSentScale && trajectoryVector == m_lastSentTrajectoryVector) - return; - - m_drawingAreaProxy->page()->process()->send(Messages::LayerTreeCoordinator::SetVisibleContentsRect(roundedRect, effectiveScale, trajectoryVector), m_drawingAreaProxy->page()->pageID()); - m_lastSentVisibleRect = roundedRect; - m_lastSentScale = effectiveScale; - m_lastSentTrajectoryVector = trajectoryVector; -} - -void LayerTreeCoordinatorProxy::renderNextFrame() -{ - m_drawingAreaProxy->page()->process()->send(Messages::LayerTreeCoordinator::RenderNextFrame(), m_drawingAreaProxy->page()->pageID()); -} - -#if ENABLE(REQUEST_ANIMATION_FRAME) -void LayerTreeCoordinatorProxy::requestAnimationFrame() -{ - dispatchUpdate(bind(&LayerTreeRenderer::requestAnimationFrame, m_renderer.get())); - updateViewport(); -} - -void LayerTreeCoordinatorProxy::animationFrameReady() -{ - m_drawingAreaProxy->page()->process()->send(Messages::LayerTreeCoordinator::AnimationFrameReady(), m_drawingAreaProxy->page()->pageID()); -} -#endif - -void LayerTreeCoordinatorProxy::didChangeScrollPosition(const IntPoint& position) -{ - dispatchUpdate(bind(&LayerTreeRenderer::didChangeScrollPosition, m_renderer.get(), position)); -} - -#if USE(GRAPHICS_SURFACE) -void LayerTreeCoordinatorProxy::createCanvas(WebLayerID id, const IntSize& canvasSize, const GraphicsSurfaceToken& token) -{ - GraphicsSurface::Flags surfaceFlags = GraphicsSurface::SupportsTextureTarget | GraphicsSurface::SupportsSharing; - dispatchUpdate(bind(&LayerTreeRenderer::createCanvas, m_renderer.get(), id, canvasSize, GraphicsSurface::create(canvasSize, surfaceFlags, token))); -} - -void LayerTreeCoordinatorProxy::syncCanvas(WebLayerID id, uint32_t frontBuffer) -{ - dispatchUpdate(bind(&LayerTreeRenderer::syncCanvas, m_renderer.get(), id, frontBuffer)); -} - -void LayerTreeCoordinatorProxy::destroyCanvas(WebLayerID id) -{ - dispatchUpdate(bind(&LayerTreeRenderer::destroyCanvas, m_renderer.get(), id)); -} -#endif - -void LayerTreeCoordinatorProxy::purgeBackingStores() -{ - m_surfaces.clear(); - m_drawingAreaProxy->page()->process()->send(Messages::LayerTreeCoordinator::PurgeBackingStores(), m_drawingAreaProxy->page()->pageID()); -} - -void LayerTreeCoordinatorProxy::setBackgroundColor(const WebCore::Color& color) -{ - dispatchUpdate(bind(&LayerTreeRenderer::setBackgroundColor, m_renderer.get(), color)); -} - -} -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.h deleted file mode 100644 index a3961ffef..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.h +++ /dev/null @@ -1,115 +0,0 @@ -/* - Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef LayerTreeCoordinatorProxy_h -#define LayerTreeCoordinatorProxy_h - -#if USE(COORDINATED_GRAPHICS) - -#include "BackingStore.h" -#include "CoordinatedGraphicsArgumentCoders.h" -#include "DrawingAreaProxy.h" -#include "Region.h" -#include "ShareableSurface.h" -#include "SurfaceUpdateInfo.h" -#include "WebLayerTreeInfo.h" -#include <WebCore/GraphicsContext.h> -#include <WebCore/GraphicsLayer.h> -#include <WebCore/GraphicsLayerAnimation.h> -#include <WebCore/GraphicsSurfaceToken.h> -#include <WebCore/IntRect.h> -#include <WebCore/IntSize.h> -#include <WebCore/RunLoop.h> -#include <WebCore/Timer.h> -#include <wtf/Functional.h> -#include <wtf/HashSet.h> - -namespace WebKit { - -class WebLayerInfo; -class LayerTreeRenderer; -class WebLayerUpdateInfo; - -class LayerTreeCoordinatorProxy { - WTF_MAKE_NONCOPYABLE(LayerTreeCoordinatorProxy); - WTF_MAKE_FAST_ALLOCATED; -public: - explicit LayerTreeCoordinatorProxy(DrawingAreaProxy*); - ~LayerTreeCoordinatorProxy(); - void setCompositingLayerState(WebLayerID, const WebLayerInfo&); - void setCompositingLayerChildren(WebLayerID, const Vector<WebLayerID>&); -#if ENABLE(CSS_FILTERS) - void setCompositingLayerFilters(WebLayerID, const WebCore::FilterOperations&); -#endif -#if ENABLE(CSS_SHADERS) - void createCustomFilterProgram(int id, const WebCore::CustomFilterProgramInfo&); - void removeCustomFilterProgram(int id); -#endif - void deleteCompositingLayer(WebLayerID); - void setRootCompositingLayer(WebLayerID); - void setContentsSize(const WebCore::FloatSize&); - void setVisibleContentsRect(const WebCore::FloatRect&, float pageScaleFactor, const WebCore::FloatPoint& trajectoryVector); - void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect); - void createTileForLayer(int layerID, int tileID, const WebCore::IntRect&, const SurfaceUpdateInfo&); - void updateTileForLayer(int layerID, int tileID, const WebCore::IntRect&, const SurfaceUpdateInfo&); - void removeTileForLayer(int layerID, int tileID); - void createUpdateAtlas(int atlasID, const ShareableSurface::Handle&); - void removeUpdateAtlas(int atlasID); - void createImageBacking(CoordinatedImageBackingID); - void updateImageBacking(CoordinatedImageBackingID, const ShareableSurface::Handle&); - void clearImageBackingContents(CoordinatedImageBackingID); - void removeImageBacking(CoordinatedImageBackingID); - void didReceiveLayerTreeCoordinatorProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void updateViewport(); - void renderNextFrame(); - void didChangeScrollPosition(const WebCore::IntPoint& position); -#if USE(GRAPHICS_SURFACE) - void createCanvas(WebLayerID, const WebCore::IntSize&, const WebCore::GraphicsSurfaceToken&); - void syncCanvas(WebLayerID, uint32_t frontBuffer); - void destroyCanvas(WebLayerID); -#endif - void purgeBackingStores(); - LayerTreeRenderer* layerTreeRenderer() const { return m_renderer.get(); } - void setLayerAnimations(WebLayerID, const WebCore::GraphicsLayerAnimations&); - void setAnimationsLocked(bool); -#if ENABLE(REQUEST_ANIMATION_FRAME) - void requestAnimationFrame(); - void animationFrameReady(); -#endif - void setBackgroundColor(const WebCore::Color&); - - float deviceScaleFactor() const; - -protected: - void dispatchUpdate(const Function<void()>&); - - DrawingAreaProxy* m_drawingAreaProxy; - RefPtr<LayerTreeRenderer> m_renderer; - WebCore::IntRect m_lastSentVisibleRect; - float m_lastSentScale; - WebCore::FloatPoint m_lastSentTrajectoryVector; - typedef HashMap<int /* atlasID */, RefPtr<ShareableSurface> > SurfaceMap; - SurfaceMap m_surfaces; -}; - -} - -#endif - -#endif // LayerTreeCoordinatorProxy_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.messages.in b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.messages.in deleted file mode 100644 index 42c69bbef..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeCoordinatorProxy.messages.in +++ /dev/null @@ -1,59 +0,0 @@ -# -# Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Library General Public -# License as published by the Free Software Foundation; either -# version 2 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Library General Public License for more details. -# -# You should have received a copy of the GNU Library General Public License -# along with this library; see the file COPYING.LIB. If not, write to -# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -# Boston, MA 02110-1301, USA. -# - -#if USE(COORDINATED_GRAPHICS) -messages -> LayerTreeCoordinatorProxy { - SetCompositingLayerState(uint32_t id, WebKit::WebLayerInfo layerInfo) - SetCompositingLayerChildren(uint32_t id, Vector<uint32_t> children) -#if ENABLE(CSS_FILTERS) - SetCompositingLayerFilters(uint32_t id, WebCore::FilterOperations filters) -#endif -#if ENABLE(CSS_SHADERS) - CreateCustomFilterProgram(int id, WebCore::CustomFilterProgramInfo programInfo) - RemoveCustomFilterProgram(int id) -#endif - SetRootCompositingLayer(uint32_t id) - DeleteCompositingLayer(uint32_t id) - CreateTileForLayer(uint32_t layerID, int tileID, WebCore::IntRect tileRect, WebKit::SurfaceUpdateInfo updateInfo) - UpdateTileForLayer(uint32_t layerID, int tileID, WebCore::IntRect tileRect, WebKit::SurfaceUpdateInfo updateInfo) - RemoveTileForLayer(uint32_t layerID, int tileID) - CreateUpdateAtlas(int atlasID, WebKit::ShareableSurface::Handle handle) - RemoveUpdateAtlas(int atlasID) - CreateImageBacking(uint64_t imageID) - UpdateImageBacking(uint64_t imageID, WebKit::ShareableSurface::Handle handle) - ClearImageBackingContents(uint64_t imageID) - RemoveImageBacking(uint64_t imageID) - DidRenderFrame(WebCore::IntSize contentsSize, WebCore::IntRect coveredRect) - DidChangeScrollPosition(WebCore::IntPoint position) - SetLayerAnimations(uint32_t id, WebCore::GraphicsLayerAnimations animations) - SetAnimationsLocked(bool locked) - -#if ENABLE(REQUEST_ANIMATION_FRAME) - RequestAnimationFrame() -#endif - -#if USE(GRAPHICS_SURFACE) - CreateCanvas(uint32_t id, WebCore::IntSize canvasSize, WebCore::GraphicsSurfaceToken token) - SyncCanvas(uint32_t id, uint32_t frontBuffer) - DestroyCanvas(uint32_t id) -#endif - - SetBackgroundColor(WebCore::Color color) -} -#endif diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp deleted file mode 100644 index 6ed1b12fd..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.cpp +++ /dev/null @@ -1,744 +0,0 @@ -/* - Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) - Copyright (C) 2012 Company 100, Inc. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" - -#if USE(COORDINATED_GRAPHICS) - -#include "LayerTreeRenderer.h" - -#include "CoordinatedBackingStore.h" -#include "GraphicsLayerTextureMapper.h" -#include "LayerTreeCoordinatorProxy.h" -#include "MessageID.h" -#include "TextureMapper.h" -#include "TextureMapperBackingStore.h" -#include "TextureMapperGL.h" -#include "TextureMapperLayer.h" -#include "UpdateInfo.h" -#include <OpenGLShims.h> -#include <wtf/Atomics.h> -#include <wtf/MainThread.h> - -#if ENABLE(CSS_SHADERS) -#include "CustomFilterProgram.h" -#include "CustomFilterProgramInfo.h" -#include "WebCustomFilterOperation.h" -#include "WebCustomFilterProgram.h" -#endif - -namespace WebKit { - -using namespace WebCore; - -void LayerTreeRenderer::dispatchOnMainThread(const Function<void()>& function) -{ - if (isMainThread()) - function(); - else - callOnMainThread(function); -} - -static FloatPoint boundedScrollPosition(const FloatPoint& scrollPosition, const FloatRect& visibleContentRect, const FloatSize& contentSize) -{ - float scrollPositionX = std::max(scrollPosition.x(), 0.0f); - scrollPositionX = std::min(scrollPositionX, contentSize.width() - visibleContentRect.width()); - - float scrollPositionY = std::max(scrollPosition.y(), 0.0f); - scrollPositionY = std::min(scrollPositionY, contentSize.height() - visibleContentRect.height()); - return FloatPoint(scrollPositionX, scrollPositionY); -} - -static bool layerShouldHaveBackingStore(GraphicsLayer* layer) -{ - return layer->drawsContent() && layer->contentsAreVisible() && !layer->size().isEmpty(); -} - -LayerTreeRenderer::LayerTreeRenderer(LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy) - : m_layerTreeCoordinatorProxy(layerTreeCoordinatorProxy) - , m_isActive(false) - , m_rootLayerID(InvalidWebLayerID) - , m_animationsLocked(false) -#if ENABLE(REQUEST_ANIMATION_FRAME) - , m_animationFrameRequested(false) -#endif - , m_backgroundColor(Color::white) - , m_setDrawsBackground(false) -{ - ASSERT(isMainThread()); -} - -LayerTreeRenderer::~LayerTreeRenderer() -{ -} - -PassOwnPtr<GraphicsLayer> LayerTreeRenderer::createLayer(WebLayerID) -{ - GraphicsLayerTextureMapper* newLayer = new GraphicsLayerTextureMapper(this); - newLayer->setHasOwnBackingStore(false); - return adoptPtr(newLayer); -} - -void LayerTreeRenderer::paintToCurrentGLContext(const TransformationMatrix& matrix, float opacity, const FloatRect& clipRect, TextureMapper::PaintFlags PaintFlags) -{ - if (!m_textureMapper) { - m_textureMapper = TextureMapper::create(TextureMapper::OpenGLMode); - static_cast<TextureMapperGL*>(m_textureMapper.get())->setEnableEdgeDistanceAntialiasing(true); - } - - ASSERT(m_textureMapper->accelerationMode() == TextureMapper::OpenGLMode); - syncRemoteContent(); - - adjustPositionForFixedLayers(); - GraphicsLayer* currentRootLayer = rootLayer(); - if (!currentRootLayer) - return; - - TextureMapperLayer* layer = toTextureMapperLayer(currentRootLayer); - - if (!layer) - return; - - layer->setTextureMapper(m_textureMapper.get()); - if (!m_animationsLocked) - layer->applyAnimationsRecursively(); - m_textureMapper->beginPainting(PaintFlags); - m_textureMapper->beginClip(TransformationMatrix(), clipRect); - - if (m_setDrawsBackground) { - RGBA32 rgba = makeRGBA32FromFloats(m_backgroundColor.red(), - m_backgroundColor.green(), m_backgroundColor.blue(), - m_backgroundColor.alpha() * opacity); - m_textureMapper->drawSolidColor(clipRect, TransformationMatrix(), Color(rgba)); - } - - if (currentRootLayer->opacity() != opacity || currentRootLayer->transform() != matrix) { - currentRootLayer->setOpacity(opacity); - currentRootLayer->setTransform(matrix); - currentRootLayer->flushCompositingStateForThisLayerOnly(); - } - - layer->paint(); - m_textureMapper->endClip(); - m_textureMapper->endPainting(); - - if (layer->descendantsOrSelfHaveRunningAnimations()) - dispatchOnMainThread(bind(&LayerTreeRenderer::updateViewport, this)); - -#if ENABLE(REQUEST_ANIMATION_FRAME) - if (m_animationFrameRequested) { - m_animationFrameRequested = false; - dispatchOnMainThread(bind(&LayerTreeRenderer::animationFrameReady, this)); - } -#endif -} - -#if ENABLE(REQUEST_ANIMATION_FRAME) -void LayerTreeRenderer::animationFrameReady() -{ - ASSERT(isMainThread()); - if (m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy->animationFrameReady(); -} - -void LayerTreeRenderer::requestAnimationFrame() -{ - m_animationFrameRequested = true; -} -#endif - -void LayerTreeRenderer::paintToGraphicsContext(BackingStore::PlatformGraphicsContext painter) -{ - if (!m_textureMapper) - m_textureMapper = TextureMapper::create(); - ASSERT(m_textureMapper->accelerationMode() == TextureMapper::SoftwareMode); - syncRemoteContent(); - TextureMapperLayer* layer = toTextureMapperLayer(rootLayer()); - - if (!layer) - return; - - GraphicsContext graphicsContext(painter); - m_textureMapper->setGraphicsContext(&graphicsContext); - m_textureMapper->beginPainting(); - - if (m_setDrawsBackground) - m_textureMapper->drawSolidColor(graphicsContext.clipBounds(), TransformationMatrix(), m_backgroundColor); - - layer->paint(); - m_textureMapper->endPainting(); - m_textureMapper->setGraphicsContext(0); -} - -void LayerTreeRenderer::setContentsSize(const WebCore::FloatSize& contentsSize) -{ - m_contentsSize = contentsSize; -} - -void LayerTreeRenderer::setVisibleContentsRect(const FloatRect& rect) -{ - m_visibleContentsRect = rect; -} - -void LayerTreeRenderer::updateViewport() -{ - ASSERT(isMainThread()); - if (m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy->updateViewport(); -} - -void LayerTreeRenderer::adjustPositionForFixedLayers() -{ - if (m_fixedLayers.isEmpty()) - return; - - // Fixed layer positions are updated by the web process when we update the visible contents rect / scroll position. - // If we want those layers to follow accurately the viewport when we move between the web process updates, we have to offset - // them by the delta between the current position and the position of the viewport used for the last layout. - FloatPoint scrollPosition = boundedScrollPosition(m_visibleContentsRect.location(), m_visibleContentsRect, m_contentsSize); - FloatPoint renderedScrollPosition = boundedScrollPosition(m_renderedContentsScrollPosition, m_visibleContentsRect, m_contentsSize); - FloatSize delta = scrollPosition - renderedScrollPosition; - - LayerRawPtrMap::iterator end = m_fixedLayers.end(); - for (LayerRawPtrMap::iterator it = m_fixedLayers.begin(); it != end; ++it) - toTextureMapperLayer(it->value)->setScrollPositionDeltaIfNeeded(delta); -} - -void LayerTreeRenderer::didChangeScrollPosition(const IntPoint& position) -{ - m_pendingRenderedContentsScrollPosition = position; -} - -#if USE(GRAPHICS_SURFACE) -void LayerTreeRenderer::createCanvas(WebLayerID id, const WebCore::IntSize& canvasSize, PassRefPtr<GraphicsSurface> surface) -{ - ASSERT(m_textureMapper); - GraphicsLayer* layer = layerByID(id); - ASSERT(layer); - ASSERT(!m_surfaceBackingStores.contains(id)); - - RefPtr<TextureMapperSurfaceBackingStore> canvasBackingStore(TextureMapperSurfaceBackingStore::create()); - m_surfaceBackingStores.set(id, canvasBackingStore); - - canvasBackingStore->setGraphicsSurface(surface); - layer->setContentsToMedia(canvasBackingStore.get()); -} - -void LayerTreeRenderer::syncCanvas(WebLayerID id, uint32_t frontBuffer) -{ - ASSERT(m_textureMapper); - ASSERT(m_surfaceBackingStores.contains(id)); - - SurfaceBackingStoreMap::iterator it = m_surfaceBackingStores.find(id); - RefPtr<TextureMapperSurfaceBackingStore> canvasBackingStore = it->value; - - canvasBackingStore->swapBuffersIfNeeded(frontBuffer); -} - -void LayerTreeRenderer::destroyCanvas(WebLayerID id) -{ - ASSERT(m_textureMapper); - GraphicsLayer* layer = layerByID(id); - ASSERT(layer); - ASSERT(m_surfaceBackingStores.contains(id)); - - m_surfaceBackingStores.remove(id); - layer->setContentsToMedia(0); -} -#endif - -void LayerTreeRenderer::setLayerChildren(WebLayerID id, const Vector<WebLayerID>& childIDs) -{ - GraphicsLayer* layer = ensureLayer(id); - Vector<GraphicsLayer*> children; - - for (size_t i = 0; i < childIDs.size(); ++i) { - WebLayerID childID = childIDs[i]; - GraphicsLayer* child = layerByID(childID); - if (!child) { - OwnPtr<GraphicsLayer*> newChild = createLayer(childID); - child = newChild.get(); - m_layers.add(childID, newChild.release()); - } - children.append(child); - } - layer->setChildren(children); -} - -#if ENABLE(CSS_FILTERS) -void LayerTreeRenderer::setLayerFilters(WebLayerID id, const FilterOperations& filters) -{ - GraphicsLayer* layer = ensureLayer(id); - -#if ENABLE(CSS_SHADERS) - injectCachedCustomFilterPrograms(filters); -#endif - layer->setFilters(filters); -} -#endif - -#if ENABLE(CSS_SHADERS) -void LayerTreeRenderer::injectCachedCustomFilterPrograms(const FilterOperations& filters) const -{ - for (size_t i = 0; i < filters.size(); ++i) { - FilterOperation* operation = filters.operations().at(i).get(); - if (operation->getOperationType() != FilterOperation::CUSTOM) - continue; - - WebCustomFilterOperation* customOperation = static_cast<WebCustomFilterOperation*>(operation); - ASSERT(!customOperation->program()); - CustomFilterProgramMap::const_iterator iter = m_customFilterPrograms.find(customOperation->programID()); - ASSERT(iter != m_customFilterPrograms.end()); - customOperation->setProgram(iter->value.get()); - } -} - -void LayerTreeRenderer::createCustomFilterProgram(int id, const WebCore::CustomFilterProgramInfo& programInfo) -{ - ASSERT(!m_customFilterPrograms.contains(id)); - m_customFilterPrograms.set(id, WebCustomFilterProgram::create(programInfo.vertexShaderString(), programInfo.fragmentShaderString(), programInfo.programType(), programInfo.mixSettings(), programInfo.meshType())); -} - -void LayerTreeRenderer::removeCustomFilterProgram(int id) -{ - CustomFilterProgramMap::iterator iter = m_customFilterPrograms.find(id); - ASSERT(iter != m_customFilterPrograms.end()); - if (m_textureMapper) - m_textureMapper->removeCachedCustomFilterProgram(iter->value.get()); - m_customFilterPrograms.remove(iter); -} -#endif // ENABLE(CSS_SHADERS) - -void LayerTreeRenderer::setLayerState(WebLayerID id, const WebLayerInfo& layerInfo) -{ - GraphicsLayer* layer = ensureLayer(id); - - layer->setReplicatedByLayer(layerByID(layerInfo.replica)); - layer->setMaskLayer(layerByID(layerInfo.mask)); - - layer->setPosition(layerInfo.pos); - layer->setSize(layerInfo.size); - layer->setTransform(layerInfo.transform); - layer->setAnchorPoint(layerInfo.anchorPoint); - layer->setChildrenTransform(layerInfo.childrenTransform); - layer->setBackfaceVisibility(layerInfo.backfaceVisible); - layer->setContentsOpaque(layerInfo.contentsOpaque); - layer->setContentsRect(layerInfo.contentsRect); - layer->setDrawsContent(layerInfo.drawsContent); - layer->setContentsVisible(layerInfo.contentsVisible); - toGraphicsLayerTextureMapper(layer)->setFixedToViewport(layerInfo.fixedToViewport); - - if (layerInfo.fixedToViewport) - m_fixedLayers.add(id, layer); - else - m_fixedLayers.remove(id); - - assignImageBackingToLayer(layer, layerInfo.imageID); - prepareContentBackingStore(layer); - - // Never make the root layer clip. - layer->setMasksToBounds(layerInfo.isRootLayer ? false : layerInfo.masksToBounds); - layer->setOpacity(layerInfo.opacity); - layer->setPreserves3D(layerInfo.preserves3D); - if (layerInfo.isRootLayer && m_rootLayerID != id) - setRootLayerID(id); -} - -void LayerTreeRenderer::deleteLayer(WebLayerID layerID) -{ - OwnPtr<GraphicsLayer> layer = m_layers.take(layerID); - if (!layer) - return; - - layer->removeFromParent(); - m_fixedLayers.remove(layerID); -#if USE(GRAPHICS_SURFACE) - m_surfaceBackingStores.remove(layerID); -#endif -} - - -WebCore::GraphicsLayer* LayerTreeRenderer::ensureLayer(WebLayerID id) -{ - LayerMap::iterator it = m_layers.find(id); - if (it != m_layers.end()) - return it->value.get(); - - OwnPtr<WebCore::GraphicsLayer> newLayer = createLayer(id); - WebCore::GraphicsLayer* layer = newLayer.get(); - m_layers.add(id, newLayer.release()); - - return layer; -} - -void LayerTreeRenderer::setRootLayerID(WebLayerID layerID) -{ - if (layerID == m_rootLayerID) - return; - - m_rootLayerID = layerID; - - m_rootLayer->removeAllChildren(); - - if (!layerID) - return; - - GraphicsLayer* layer = layerByID(layerID); - if (!layer) - return; - - m_rootLayer->addChild(layer); -} - -CoordinatedBackingStore* LayerTreeRenderer::getBackingStore(GraphicsLayer* graphicsLayer) -{ - TextureMapperLayer* layer = toTextureMapperLayer(graphicsLayer); - ASSERT(layer); - CoordinatedBackingStore* backingStore = static_cast<CoordinatedBackingStore*>(layer->backingStore().get()); - - BackingStoreMap::iterator it = m_pendingSyncBackingStores.find(layer); - if (it != m_pendingSyncBackingStores.end()) - backingStore = it->value.get(); - return backingStore; -} - -void LayerTreeRenderer::prepareContentBackingStore(GraphicsLayer* graphicsLayer) -{ - if (!layerShouldHaveBackingStore(graphicsLayer)) { - removeBackingStoreIfNeeded(graphicsLayer); - return; - } - - createBackingStoreIfNeeded(graphicsLayer); - resetBackingStoreSizeToLayerSize(graphicsLayer); -} - -void LayerTreeRenderer::createBackingStoreIfNeeded(GraphicsLayer* graphicsLayer) -{ - TextureMapperLayer* layer = toTextureMapperLayer(graphicsLayer); - ASSERT(layer); - - // Make sure the layer does not already have a backing store (committed or pending). - BackingStoreMap::iterator it = m_pendingSyncBackingStores.find(layer); - if (it != m_pendingSyncBackingStores.end()) { - if (!it->value) { - // There is a pending removal, cancel it. - m_pendingSyncBackingStores.remove(it); - } - // There is already a pending addition. - return; - } - if (layer->backingStore()) - return; // The layer already has a backing store (and no pending removal). - - RefPtr<CoordinatedBackingStore> backingStore(CoordinatedBackingStore::create()); - ASSERT(!m_pendingSyncBackingStores.contains(layer)); - m_pendingSyncBackingStores.add(layer, backingStore); -} - -void LayerTreeRenderer::removeBackingStoreIfNeeded(GraphicsLayer* graphicsLayer) -{ - TextureMapperLayer* layer = toTextureMapperLayer(graphicsLayer); - ASSERT(layer); - - // Check if the layout already has a backing store (committed or pending). - BackingStoreMap::iterator it = m_pendingSyncBackingStores.find(layer); - if (it != m_pendingSyncBackingStores.end()) { - if (it->value) { - // There is a pending addition, cancel it. - m_pendingSyncBackingStores.remove(it); - } - // There is already a pending removal. - return; - } - - if (!layer->backingStore()) - return; // The layer has no backing store (and no pending addition). - - ASSERT(!m_pendingSyncBackingStores.contains(layer)); - m_pendingSyncBackingStores.add(layer, 0); -} - -void LayerTreeRenderer::resetBackingStoreSizeToLayerSize(GraphicsLayer* graphicsLayer) -{ - CoordinatedBackingStore* backingStore = getBackingStore(graphicsLayer); - ASSERT(backingStore); - backingStore->setSize(graphicsLayer->size()); - m_backingStoresWithPendingBuffers.add(backingStore); -} - -void LayerTreeRenderer::createTile(WebLayerID layerID, int tileID, float scale) -{ - GraphicsLayer* layer = layerByID(layerID); - ASSERT(layer); - CoordinatedBackingStore* backingStore = getBackingStore(layer); - ASSERT(backingStore); - backingStore->createTile(tileID, scale); -} - -void LayerTreeRenderer::removeTile(WebLayerID layerID, int tileID) -{ - GraphicsLayer* layer = layerByID(layerID); - ASSERT(layer); - CoordinatedBackingStore* backingStore = getBackingStore(layer); - if (!backingStore) - return; - - backingStore->removeTile(tileID); - m_backingStoresWithPendingBuffers.add(backingStore); -} - -void LayerTreeRenderer::updateTile(WebLayerID layerID, int tileID, const TileUpdate& update) -{ - GraphicsLayer* layer = layerByID(layerID); - ASSERT(layer); - RefPtr<CoordinatedBackingStore> backingStore = getBackingStore(layer); - ASSERT(backingStore); - backingStore->updateTile(tileID, update.sourceRect, update.tileRect, update.surface, update.offset); - m_backingStoresWithPendingBuffers.add(backingStore); -} - -void LayerTreeRenderer::createImageBacking(CoordinatedImageBackingID imageID) -{ - ASSERT(!m_imageBackings.contains(imageID)); - RefPtr<CoordinatedBackingStore> backingStore(CoordinatedBackingStore::create()); - m_imageBackings.add(imageID, backingStore.release()); -} - -void LayerTreeRenderer::updateImageBacking(CoordinatedImageBackingID imageID, PassRefPtr<ShareableSurface> surface) -{ - ASSERT(m_imageBackings.contains(imageID)); - ImageBackingMap::iterator it = m_imageBackings.find(imageID); - RefPtr<CoordinatedBackingStore> backingStore = it->value; - - // CoordinatedImageBacking is realized to CoordinatedBackingStore with only one tile in UI Process. - backingStore->createTile(1 /* id */, 1 /* scale */); - IntRect rect(IntPoint::zero(), surface->size()); - // See CoordinatedGraphicsLayer::shouldDirectlyCompositeImage() - ASSERT(2000 >= std::max(rect.width(), rect.height())); - backingStore->setSize(rect.size()); - backingStore->updateTile(1 /* id */, rect, rect, surface, rect.location()); - - m_backingStoresWithPendingBuffers.add(backingStore); -} - -void LayerTreeRenderer::clearImageBackingContents(CoordinatedImageBackingID imageID) -{ - ASSERT(m_imageBackings.contains(imageID)); - ImageBackingMap::iterator it = m_imageBackings.find(imageID); - RefPtr<CoordinatedBackingStore> backingStore = it->value; - backingStore->removeAllTiles(); - m_backingStoresWithPendingBuffers.add(backingStore); -} - -void LayerTreeRenderer::removeImageBacking(CoordinatedImageBackingID imageID) -{ - ASSERT(m_imageBackings.contains(imageID)); - - // We don't want TextureMapperLayer refers a dangling pointer. - ImageBackingMap::iterator it = m_imageBackings.find(imageID); - m_releasedImageBackings.append(it->value); - m_imageBackings.remove(imageID); -} - -void LayerTreeRenderer::assignImageBackingToLayer(GraphicsLayer* layer, CoordinatedImageBackingID imageID) -{ - if (imageID == InvalidCoordinatedImageBackingID) { - layer->setContentsToMedia(0); - return; - } - ImageBackingMap::iterator it = m_imageBackings.find(imageID); - ASSERT(it != m_imageBackings.end()); - layer->setContentsToMedia(it->value.get()); -} - -void LayerTreeRenderer::removeReleasedImageBackingsIfNeeded() -{ - m_releasedImageBackings.clear(); -} - -void LayerTreeRenderer::commitPendingBackingStoreOperations() -{ - HashSet<RefPtr<CoordinatedBackingStore> >::iterator end = m_backingStoresWithPendingBuffers.end(); - for (HashSet<RefPtr<CoordinatedBackingStore> >::iterator it = m_backingStoresWithPendingBuffers.begin(); it != end; ++it) - (*it)->commitTileOperations(m_textureMapper.get()); - - m_backingStoresWithPendingBuffers.clear(); - - { - BackingStoreMap::iterator end = m_pendingSyncBackingStores.end(); - BackingStoreMap::iterator it = m_pendingSyncBackingStores.begin(); - for (;it != end; ++it) - it->key->setBackingStore(it->value); - - m_pendingSyncBackingStores.clear(); - } -} - -void LayerTreeRenderer::flushLayerChanges() -{ - m_renderedContentsScrollPosition = m_pendingRenderedContentsScrollPosition; - - // Since the frame has now been rendered, we can safely unlock the animations until the next layout. - setAnimationsLocked(false); - - m_rootLayer->flushCompositingState(FloatRect()); - commitPendingBackingStoreOperations(); - removeReleasedImageBackingsIfNeeded(); - - // The pending tiles state is on its way for the screen, tell the web process to render the next one. - dispatchOnMainThread(bind(&LayerTreeRenderer::renderNextFrame, this)); -} - -void LayerTreeRenderer::renderNextFrame() -{ - if (m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy->renderNextFrame(); -} - -void LayerTreeRenderer::ensureRootLayer() -{ - if (m_rootLayer) - return; - - m_rootLayer = createLayer(InvalidWebLayerID); - m_rootLayer->setMasksToBounds(false); - m_rootLayer->setDrawsContent(false); - m_rootLayer->setAnchorPoint(FloatPoint3D(0, 0, 0)); - - // The root layer should not have zero size, or it would be optimized out. - m_rootLayer->setSize(FloatSize(1.0, 1.0)); - - ASSERT(m_textureMapper); - toTextureMapperLayer(m_rootLayer.get())->setTextureMapper(m_textureMapper.get()); -} - -void LayerTreeRenderer::syncRemoteContent() -{ - // We enqueue messages and execute them during paint, as they require an active GL context. - ensureRootLayer(); - - Vector<Function<void()> > renderQueue; - bool calledOnMainThread = WTF::isMainThread(); - if (!calledOnMainThread) - m_renderQueueMutex.lock(); - renderQueue.swap(m_renderQueue); - if (!calledOnMainThread) - m_renderQueueMutex.unlock(); - - for (size_t i = 0; i < renderQueue.size(); ++i) - renderQueue[i](); -} - -void LayerTreeRenderer::purgeGLResources() -{ - TextureMapperLayer* layer = toTextureMapperLayer(rootLayer()); - - if (layer) - layer->clearBackingStoresRecursive(); - - m_imageBackings.clear(); -#if USE(GRAPHICS_SURFACE) - m_surfaceBackingStores.clear(); -#endif - - if (m_rootLayer) { - m_rootLayer->removeAllChildren(); - } - m_rootLayer.clear(); - m_rootLayerID = InvalidWebLayerID; - m_layers.clear(); - m_fixedLayers.clear(); - m_textureMapper.clear(); - m_pendingSyncBackingStores.clear(); - m_backingStoresWithPendingBuffers.clear(); - - setActive(false); - dispatchOnMainThread(bind(&LayerTreeRenderer::purgeBackingStores, this)); -} - -void LayerTreeRenderer::purgeBackingStores() -{ - if (m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy->purgeBackingStores(); -} - -void LayerTreeRenderer::setLayerAnimations(WebLayerID id, const GraphicsLayerAnimations& animations) -{ - GraphicsLayerTextureMapper* layer = toGraphicsLayerTextureMapper(layerByID(id)); - if (!layer) - return; -#if ENABLE(CSS_SHADERS) - for (size_t i = 0; i < animations.animations().size(); ++i) { - const KeyframeValueList& keyframes = animations.animations().at(i).keyframes(); - if (keyframes.property() != AnimatedPropertyWebkitFilter) - continue; - for (size_t j = 0; j < keyframes.size(); ++j) { - const FilterAnimationValue* filterValue = static_cast<const FilterAnimationValue*>(keyframes.at(i)); - injectCachedCustomFilterPrograms(*filterValue->value()); - } - } -#endif - layer->setAnimations(animations); -} - -void LayerTreeRenderer::setAnimationsLocked(bool locked) -{ - m_animationsLocked = locked; -} - -void LayerTreeRenderer::detach() -{ - ASSERT(isMainThread()); - m_layerTreeCoordinatorProxy = 0; -} - -void LayerTreeRenderer::appendUpdate(const Function<void()>& function) -{ - if (!m_isActive) - return; - - ASSERT(isMainThread()); - MutexLocker locker(m_renderQueueMutex); - m_renderQueue.append(function); -} - -void LayerTreeRenderer::setActive(bool active) -{ - if (m_isActive == active) - return; - - // Have to clear render queue in both cases. - // If there are some updates in queue during activation then those updates are from previous instance of paint node - // and cannot be applied to the newly created instance. - m_renderQueue.clear(); - m_isActive = active; - if (m_isActive) - dispatchOnMainThread(bind(&LayerTreeRenderer::renderNextFrame, this)); -} - -void LayerTreeRenderer::setBackgroundColor(const WebCore::Color& color) -{ - m_backgroundColor = color; -} - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h deleted file mode 100644 index 946ac6d49..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/LayerTreeRenderer.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef LayerTreeRenderer_h -#define LayerTreeRenderer_h - -#if USE(COORDINATED_GRAPHICS) -#include "BackingStore.h" -#include "ShareableSurface.h" -#include "TextureMapper.h" -#include "TextureMapperBackingStore.h" -#include "WebLayerTreeInfo.h" -#include <WebCore/GraphicsContext.h> -#include <WebCore/GraphicsLayer.h> -#include <WebCore/GraphicsLayerAnimation.h> -#include <WebCore/GraphicsSurface.h> -#include <WebCore/IntRect.h> -#include <WebCore/IntSize.h> -#include <WebCore/RunLoop.h> -#include <WebCore/Timer.h> -#include <wtf/Functional.h> -#include <wtf/HashSet.h> -#include <wtf/ThreadingPrimitives.h> - -namespace WebCore { -class CustomFilterProgram; -class CustomFilterProgramInfo; -class TextureMapperLayer; -} - -namespace WebKit { - -class CoordinatedBackingStore; -class LayerTreeCoordinatorProxy; -class WebLayerInfo; -class WebLayerUpdateInfo; - -class LayerTreeRenderer : public ThreadSafeRefCounted<LayerTreeRenderer>, public WebCore::GraphicsLayerClient { -public: - struct TileUpdate { - WebCore::IntRect sourceRect; - WebCore::IntRect tileRect; - RefPtr<ShareableSurface> surface; - WebCore::IntPoint offset; - TileUpdate(const WebCore::IntRect& source, const WebCore::IntRect& tile, PassRefPtr<ShareableSurface> newSurface, const WebCore::IntPoint& newOffset) - : sourceRect(source) - , tileRect(tile) - , surface(newSurface) - , offset(newOffset) - { - } - }; - explicit LayerTreeRenderer(LayerTreeCoordinatorProxy*); - virtual ~LayerTreeRenderer(); - void paintToCurrentGLContext(const WebCore::TransformationMatrix&, float, const WebCore::FloatRect&, WebCore::TextureMapper::PaintFlags = 0); - void paintToGraphicsContext(BackingStore::PlatformGraphicsContext); - void setContentsSize(const WebCore::FloatSize&); - void setVisibleContentsRect(const WebCore::FloatRect&); - void didChangeScrollPosition(const WebCore::IntPoint& position); -#if USE(GRAPHICS_SURFACE) - void createCanvas(WebLayerID, const WebCore::IntSize&, PassRefPtr<WebCore::GraphicsSurface>); - void syncCanvas(WebLayerID, uint32_t frontBuffer); - void destroyCanvas(WebLayerID); -#endif - - void detach(); - void appendUpdate(const Function<void()>&); - - // The painting thread must lock the main thread to use below two methods, because two methods access members that the main thread manages. See m_layerTreeCoordinatorProxy. - // Currently, QQuickWebPage::updatePaintNode() locks the main thread before calling both methods. - void purgeGLResources(); - void setActive(bool); - - void deleteLayer(WebLayerID); - void setRootLayerID(WebLayerID); - void setLayerChildren(WebLayerID, const Vector<WebLayerID>&); - void setLayerState(WebLayerID, const WebLayerInfo&); -#if ENABLE(CSS_FILTERS) - void setLayerFilters(WebLayerID, const WebCore::FilterOperations&); -#endif -#if ENABLE(CSS_SHADERS) - void injectCachedCustomFilterPrograms(const WebCore::FilterOperations& filters) const; - void createCustomFilterProgram(int id, const WebCore::CustomFilterProgramInfo&); - void removeCustomFilterProgram(int id); -#endif - - void createTile(WebLayerID, int, float scale); - void removeTile(WebLayerID, int); - void updateTile(WebLayerID, int, const TileUpdate&); - void flushLayerChanges(); - void createImageBacking(CoordinatedImageBackingID); - void updateImageBacking(CoordinatedImageBackingID, PassRefPtr<ShareableSurface>); - void clearImageBackingContents(CoordinatedImageBackingID); - void removeImageBacking(CoordinatedImageBackingID); - void setLayerAnimations(WebLayerID, const WebCore::GraphicsLayerAnimations&); - void setAnimationsLocked(bool); - void setBackgroundColor(const WebCore::Color&); - void setDrawsBackground(bool enable) { m_setDrawsBackground = enable; } - -#if ENABLE(REQUEST_ANIMATION_FRAME) - void requestAnimationFrame(); -#endif - -private: - PassOwnPtr<WebCore::GraphicsLayer> createLayer(WebLayerID); - - WebCore::GraphicsLayer* layerByID(WebLayerID id) { return (id == InvalidWebLayerID) ? 0 : m_layers.get(id); } - WebCore::GraphicsLayer* rootLayer() { return m_rootLayer.get(); } - - void syncRemoteContent(); - void adjustPositionForFixedLayers(); - - // Reimplementations from WebCore::GraphicsLayerClient. - virtual void notifyAnimationStarted(const WebCore::GraphicsLayer*, double) { } - virtual void notifyFlushRequired(const WebCore::GraphicsLayer*) { } - virtual void paintContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect&) OVERRIDE { } - - void dispatchOnMainThread(const Function<void()>&); - void updateViewport(); -#if ENABLE(REQUEST_ANIMATION_FRAME) - void animationFrameReady(); -#endif - void renderNextFrame(); - void purgeBackingStores(); - - void assignImageBackingToLayer(WebCore::GraphicsLayer*, CoordinatedImageBackingID); - void removeReleasedImageBackingsIfNeeded(); - void ensureRootLayer(); - WebCore::GraphicsLayer* ensureLayer(WebLayerID); - void commitPendingBackingStoreOperations(); - - CoordinatedBackingStore* getBackingStore(WebCore::GraphicsLayer*); - void prepareContentBackingStore(WebCore::GraphicsLayer*); - void createBackingStoreIfNeeded(WebCore::GraphicsLayer*); - void removeBackingStoreIfNeeded(WebCore::GraphicsLayer*); - void resetBackingStoreSizeToLayerSize(WebCore::GraphicsLayer*); - - WebCore::FloatSize m_contentsSize; - WebCore::FloatRect m_visibleContentsRect; - - // Render queue can be accessed ony from main thread or updatePaintNode call stack! - Vector<Function<void()> > m_renderQueue; - Mutex m_renderQueueMutex; - - OwnPtr<WebCore::TextureMapper> m_textureMapper; - - typedef HashMap<CoordinatedImageBackingID, RefPtr<CoordinatedBackingStore> > ImageBackingMap; - ImageBackingMap m_imageBackings; - Vector<RefPtr<CoordinatedBackingStore> > m_releasedImageBackings; - - typedef HashMap<WebCore::TextureMapperLayer*, RefPtr<CoordinatedBackingStore> > BackingStoreMap; - BackingStoreMap m_pendingSyncBackingStores; - - HashSet<RefPtr<CoordinatedBackingStore> > m_backingStoresWithPendingBuffers; - -#if USE(GRAPHICS_SURFACE) - typedef HashMap<WebLayerID, RefPtr<WebCore::TextureMapperSurfaceBackingStore> > SurfaceBackingStoreMap; - SurfaceBackingStoreMap m_surfaceBackingStores; -#endif - - // Below two members are accessed by only the main thread. The painting thread must lock the main thread to access both members. - LayerTreeCoordinatorProxy* m_layerTreeCoordinatorProxy; - bool m_isActive; - - OwnPtr<WebCore::GraphicsLayer> m_rootLayer; - - typedef HashMap<WebLayerID, OwnPtr<WebCore::GraphicsLayer> > LayerMap; - LayerMap m_layers; - typedef HashMap<WebLayerID, WebCore::GraphicsLayer*> LayerRawPtrMap; - LayerRawPtrMap m_fixedLayers; - WebLayerID m_rootLayerID; - WebCore::IntPoint m_renderedContentsScrollPosition; - WebCore::IntPoint m_pendingRenderedContentsScrollPosition; - bool m_animationsLocked; -#if ENABLE(REQUEST_ANIMATION_FRAME) - bool m_animationFrameRequested; -#endif - WebCore::Color m_backgroundColor; - bool m_setDrawsBackground; - -#if ENABLE(CSS_SHADERS) - typedef HashMap<int, RefPtr<WebCore::CustomFilterProgram> > CustomFilterProgramMap; - CustomFilterProgramMap m_customFilterPrograms; -#endif -}; - -}; - -#endif // USE(COORDINATED_GRAPHICS) - -#endif // LayerTreeRenderer_h - - diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h new file mode 100644 index 000000000..fc9f0d608 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies) + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WKCoordinatedSceneAPICast_h +#define WKCoordinatedSceneAPICast_h + +#include <WebKit2/WKCoordinatedScene.h> + +namespace WebCore { + +class CoordinatedGraphicsScene; +class TextureMapperLayer; + +} // namespace WebCore + +inline WebCore::CoordinatedGraphicsScene* toImpl(WKCoordinatedScene scene) +{ + return reinterpret_cast<WebCore::CoordinatedGraphicsScene*>(scene); +} + +inline WKCoordinatedScene toAPI(WebCore::CoordinatedGraphicsScene* scene) +{ + return reinterpret_cast<WKCoordinatedScene>(scene); +} + +inline WebCore::TextureMapperLayer* toImpl(WKCoordinatedSceneLayer layer) +{ + return reinterpret_cast<WebCore::TextureMapperLayer*>(layer); +} + +inline WKCoordinatedSceneLayer toAPI(WebCore::TextureMapperLayer* layer) +{ + return reinterpret_cast<WKCoordinatedSceneLayer>(layer); +} + +#endif // WKCoordinatedSceneAPICast_h diff --git a/Source/WebKit2/UIProcess/win/WebUndoClient.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebPageProxyCoordinatedGraphics.cpp index 67e6cdf63..e34a9b338 100644 --- a/Source/WebKit2/UIProcess/win/WebUndoClient.h +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebPageProxyCoordinatedGraphics.cpp @@ -1,5 +1,6 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies) + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,26 +24,32 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebUndoClient_h -#define WebUndoClient_h +#include "config.h" +#if USE(COORDINATED_GRAPHICS) -#include "APIClient.h" -#include "WKView.h" #include "WebPageProxy.h" -#include <wtf/Forward.h> + +#include "PageClient.h" +#include "WebPageMessages.h" +#include "WebProcessProxy.h" + +using namespace WebCore; namespace WebKit { -class WebEditCommandProxy; +void WebPageProxy::findZoomableAreaForPoint(const IntPoint& point, const IntSize& area) +{ + if (!isValid()) + return; + + m_process->send(Messages::WebPage::FindZoomableAreaForPoint(point, area), m_pageID); +} -class WebUndoClient : public APIClient<WKViewUndoClient, kWKViewUndoClientCurrentVersion> { -public: - void registerEditCommand(WebView*, PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo); - void clearAllEditCommands(WebView*); - bool canUndoRedo(WebView*, WebPageProxy::UndoOrRedo); - void executeUndoRedo(WebView*, WebPageProxy::UndoOrRedo); -}; +void WebPageProxy::didFindZoomableArea(const IntPoint& target, const IntRect& area) +{ + m_pageClient->didFindZoomableArea(target, area); +} } // namespace WebKit -#endif // WebUndoClient_h +#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.cpp new file mode 100644 index 000000000..293745e48 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.cpp @@ -0,0 +1,515 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#if USE(COORDINATED_GRAPHICS) + +#include "WebView.h" + +#include "CoordinatedLayerTreeHostProxy.h" +#include "DrawingAreaProxyImpl.h" +#include "NotImplemented.h" +#include "WebContextMenuProxy.h" +#include "WebPageProxy.h" +#include <WebCore/CoordinatedGraphicsScene.h> + +#if ENABLE(FULLSCREEN_API) +#include "WebFullScreenManagerProxy.h" +#endif + +using namespace WebCore; + +namespace WebKit { + +WebView::WebView(WebContext* context, WebPageGroup* pageGroup) + : m_focused(false) + , m_visible(false) + , m_contentScaleFactor(1.0) + , m_opacity(1.0) +{ + // Need to call createWebPage after other data members, specifically m_visible, are initialized. + m_page = context->createWebPage(this, pageGroup); + + m_page->pageGroup()->preferences()->setAcceleratedCompositingEnabled(true); + m_page->pageGroup()->preferences()->setForceCompositingMode(true); + + char* debugVisualsEnvironment = getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS"); + bool showDebugVisuals = debugVisualsEnvironment && !strcmp(debugVisualsEnvironment, "1"); + m_page->pageGroup()->preferences()->setCompositingBordersVisible(showDebugVisuals); + m_page->pageGroup()->preferences()->setCompositingRepaintCountersVisible(showDebugVisuals); +} + +WebView::~WebView() +{ + if (m_page->isClosed()) + return; + + m_page->close(); +} + +void WebView::initialize() +{ + m_page->initializeWebPage(); + if (CoordinatedGraphicsScene* scene = coordinatedGraphicsScene()) + scene->setActive(true); +} + +void WebView::setSize(const WebCore::IntSize& size) +{ + if (m_size == size) + return; + + m_size = size; + + updateViewportSize(); +} + +void WebView::setFocused(bool focused) +{ + if (m_focused == focused) + return; + + m_focused = focused; + m_page->viewStateDidChange(WebPageProxy::ViewIsFocused | WebPageProxy::ViewWindowIsActive); +} + +void WebView::setVisible(bool visible) +{ + if (m_visible == visible) + return; + + m_visible = visible; + m_page->viewStateDidChange(WebPageProxy::ViewIsVisible); +} + +void WebView::setUserViewportTranslation(double tx, double ty) +{ + m_userViewportTransform = TransformationMatrix().translate(tx, ty); +} + +IntPoint WebView::userViewportToContents(const IntPoint& point) const +{ + return transformFromScene().mapPoint(point); +} + +IntPoint WebView::userViewportToScene(const WebCore::IntPoint& point) const +{ + return m_userViewportTransform.mapPoint(point); +} + +IntPoint WebView::contentsToUserViewport(const IntPoint& point) const +{ + return transformToScene().mapPoint(point); +} + +void WebView::paintToCurrentGLContext() +{ + CoordinatedGraphicsScene* scene = coordinatedGraphicsScene(); + if (!scene) + return; + + // FIXME: We need to clean up this code as it is split over CoordGfx and Page. + scene->setDrawsBackground(m_page->drawsBackground()); + const FloatRect& viewport = m_userViewportTransform.mapRect(IntRect(IntPoint(), m_size)); + + scene->paintToCurrentGLContext(transformToScene().toTransformationMatrix(), m_opacity, viewport); +} + +void WebView::setDrawsBackground(bool drawsBackground) +{ + m_page->setDrawsBackground(drawsBackground); +} + +bool WebView::drawsBackground() const +{ + return m_page->drawsBackground(); +} + +void WebView::setDrawsTransparentBackground(bool transparentBackground) +{ + m_page->setDrawsTransparentBackground(transparentBackground); +} + +bool WebView::drawsTransparentBackground() const +{ + return m_page->drawsTransparentBackground(); +} + +void WebView::suspendActiveDOMObjectsAndAnimations() +{ + m_page->suspendActiveDOMObjectsAndAnimations(); +} + +void WebView::resumeActiveDOMObjectsAndAnimations() +{ + m_page->resumeActiveDOMObjectsAndAnimations(); +} + +void WebView::setShowsAsSource(bool showsAsSource) +{ + m_page->setMainFrameInViewSourceMode(showsAsSource); +} + +bool WebView::showsAsSource() const +{ + return m_page->mainFrameInViewSourceMode(); +} + +#if ENABLE(FULLSCREEN_API) +bool WebView::exitFullScreen() +{ +#if PLATFORM(EFL) + // FIXME: Implement this for other platforms. + if (!m_page->fullScreenManager()->isFullScreen()) + return false; +#endif + m_page->fullScreenManager()->requestExitFullScreen(); + return true; +} +#endif + +void WebView::initializeClient(const WKViewClient* client) +{ + m_client.initialize(client); +} + +void WebView::didChangeContentsSize(const WebCore::IntSize& size) +{ + if (m_contentsSize == size) + return; + + m_contentsSize = size; + m_client.didChangeContentsSize(this, size); + + updateViewportSize(); +} + +void WebView::didFindZoomableArea(const WebCore::IntPoint& target, const WebCore::IntRect& area) +{ + m_client.didFindZoomableArea(this, target, area); +} + +AffineTransform WebView::transformFromScene() const +{ + return transformToScene().inverse(); +} + +AffineTransform WebView::transformToScene() const +{ + FloatPoint position = -m_contentPosition; + float effectiveScale = m_contentScaleFactor * m_page->deviceScaleFactor(); + position.scale(effectiveScale, effectiveScale); + + TransformationMatrix transform = m_userViewportTransform; + transform.translate(position.x(), position.y()); + transform.scale(effectiveScale); + + return transform.toAffineTransform(); +} + +CoordinatedGraphicsScene* WebView::coordinatedGraphicsScene() +{ + DrawingAreaProxy* drawingArea = m_page->drawingArea(); + if (!drawingArea) + return 0; + + WebKit::CoordinatedLayerTreeHostProxy* layerTreeHostProxy = drawingArea->coordinatedLayerTreeHostProxy(); + if (!layerTreeHostProxy) + return 0; + + return layerTreeHostProxy->coordinatedGraphicsScene(); +} + +void WebView::updateViewportSize() +{ + if (DrawingAreaProxy* drawingArea = page()->drawingArea()) { + // Web Process expects sizes in UI units, and not raw device units. + drawingArea->setSize(roundedIntSize(dipSize()), IntSize(), IntSize()); + FloatRect visibleContentsRect(contentPosition(), visibleContentsSize()); + visibleContentsRect.intersect(FloatRect(FloatPoint(), contentsSize())); + drawingArea->setVisibleContentsRect(visibleContentsRect, FloatPoint()); + } +} + +inline WebCore::FloatSize WebView::dipSize() const +{ + FloatSize dipSize(size()); + dipSize.scale(1 / m_page->deviceScaleFactor()); + + return dipSize; +} + +WebCore::FloatSize WebView::visibleContentsSize() const +{ + FloatSize visibleContentsSize(dipSize()); + visibleContentsSize.scale(1 / m_contentScaleFactor); + + return visibleContentsSize; +} + +// Page Client + +PassOwnPtr<DrawingAreaProxy> WebView::createDrawingAreaProxy() +{ + OwnPtr<DrawingAreaProxy> drawingArea = DrawingAreaProxyImpl::create(page()); + return drawingArea.release(); +} + +void WebView::setViewNeedsDisplay(const WebCore::IntRect& area) +{ + m_client.viewNeedsDisplay(this, area); +} + +void WebView::displayView() +{ + notImplemented(); +} + +void WebView::scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize&) +{ + setViewNeedsDisplay(scrollRect); +} + +WebCore::IntSize WebView::viewSize() +{ + return roundedIntSize(dipSize()); +} + +bool WebView::isViewWindowActive() +{ + notImplemented(); + return true; +} + +bool WebView::isViewFocused() +{ + return isFocused(); +} + +bool WebView::isViewVisible() +{ + return isVisible(); +} + +bool WebView::isViewInWindow() +{ + notImplemented(); + return true; +} + +void WebView::processDidCrash() +{ + m_client.webProcessCrashed(this, m_page->urlAtProcessExit()); +} + +void WebView::didRelaunchProcess() +{ + m_client.webProcessDidRelaunch(this); +} + +void WebView::pageClosed() +{ + notImplemented(); +} + +void WebView::preferencesDidChange() +{ + notImplemented(); +} + +void WebView::toolTipChanged(const String&, const String& newToolTip) +{ + m_client.didChangeTooltip(this, newToolTip); +} + +void WebView::setCursor(const WebCore::Cursor&) +{ + notImplemented(); +} + +void WebView::setCursorHiddenUntilMouseMoves(bool) +{ + notImplemented(); +} + +void WebView::registerEditCommand(PassRefPtr<WebEditCommandProxy> command, WebPageProxy::UndoOrRedo undoOrRedo) +{ + m_undoController.registerEditCommand(command, undoOrRedo); +} + +void WebView::clearAllEditCommands() +{ + m_undoController.clearAllEditCommands(); +} + +bool WebView::canUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) +{ + return m_undoController.canUndoRedo(undoOrRedo); +} + +void WebView::executeUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) +{ + m_undoController.executeUndoRedo(undoOrRedo); +} + +IntPoint WebView::screenToWindow(const IntPoint& point) +{ + notImplemented(); + return point; +} + +IntRect WebView::windowToScreen(const IntRect&) +{ + notImplemented(); + return IntRect(); +} + +void WebView::doneWithKeyEvent(const NativeWebKeyboardEvent&, bool) +{ + notImplemented(); +} + +#if ENABLE(TOUCH_EVENTS) +void WebView::doneWithTouchEvent(const NativeWebTouchEvent& event, bool wasEventHandled) +{ + m_client.doneWithTouchEvent(this, event, wasEventHandled); +} +#endif + +PassRefPtr<WebPopupMenuProxy> WebView::createPopupMenuProxy(WebPageProxy*) +{ + notImplemented(); + return 0; +} + +PassRefPtr<WebContextMenuProxy> WebView::createContextMenuProxy(WebPageProxy*) +{ + notImplemented(); + return 0; +} + +#if ENABLE(INPUT_TYPE_COLOR) +PassRefPtr<WebColorPicker> WebView::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) +{ + notImplemented(); + return 0; +} +#endif + +void WebView::setFindIndicator(PassRefPtr<FindIndicator>, bool, bool) +{ + notImplemented(); +} + +void WebView::enterAcceleratedCompositingMode(const LayerTreeContext&) +{ + if (CoordinatedGraphicsScene* scene = coordinatedGraphicsScene()) + scene->setActive(true); +} + +void WebView::exitAcceleratedCompositingMode() +{ + if (CoordinatedGraphicsScene* scene = coordinatedGraphicsScene()) + scene->setActive(false); +} + +void WebView::updateAcceleratedCompositingMode(const LayerTreeContext&) +{ + notImplemented(); +} + +void WebView::flashBackingStoreUpdates(const Vector<IntRect>&) +{ + notImplemented(); +} + +void WebView::updateTextInputState() +{ + notImplemented(); +} + +void WebView::handleDownloadRequest(DownloadProxy*) +{ + notImplemented(); +} + +FloatRect WebView::convertToDeviceSpace(const FloatRect& userRect) +{ + if (m_page->useFixedLayout()) { + FloatRect result = userRect; + result.scale(m_page->deviceScaleFactor()); + return result; + } + // Legacy mode. + notImplemented(); + return userRect; +} + +FloatRect WebView::convertToUserSpace(const FloatRect& deviceRect) +{ + if (m_page->useFixedLayout()) { + FloatRect result = deviceRect; + result.scale(1 / m_page->deviceScaleFactor()); + return result; + } + // Legacy mode. + notImplemented(); + return deviceRect; +} + +void WebView::didChangeViewportProperties(const WebCore::ViewportAttributes& attr) +{ + m_client.didChangeViewportAttributes(this, attr); +} + +void WebView::pageDidRequestScroll(const IntPoint& position) +{ + FloatPoint uiPosition(position); + uiPosition.scale(contentScaleFactor(), contentScaleFactor()); + setContentPosition(uiPosition); + + m_client.didChangeContentsPosition(this, position); +} + +void WebView::didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) +{ + m_client.didRenderFrame(this, contentsSize, coveredRect); +} + +void WebView::pageTransitionViewportReady() +{ + m_client.didCompletePageTransition(this); +} + +void WebView::findZoomableAreaForPoint(const IntPoint& point, const IntSize& size) +{ + m_page->findZoomableAreaForPoint(transformFromScene().mapPoint(point), transformFromScene().mapSize(size)); +} + +} // namespace WebKit + +#endif // USE(COORDINATED_GRAPHICS) + diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.h new file mode 100644 index 000000000..e79a238e3 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.h @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebView_h +#define WebView_h + +#if USE(COORDINATED_GRAPHICS) + +#include "APIObject.h" +#include "DefaultUndoController.h" +#include "PageClient.h" +#include "WebContext.h" +#include "WebGeometry.h" +#include "WebPageGroup.h" +#include "WebPageProxy.h" +#include "WebPreferences.h" +#include "WebViewClient.h" +#include <WebCore/TransformationMatrix.h> + +namespace WebCore { +class CoordinatedGraphicsScene; +} + +namespace WebKit { + +class WebView : public TypedAPIObject<APIObject::TypeView>, public PageClient { +public: + virtual ~WebView(); + + static PassRefPtr<WebView> create(WebContext*, WebPageGroup*); + + void initialize(); + + void setSize(const WebCore::IntSize&); + const WebCore::IntSize& size() const { return m_size; } + + bool isFocused() const { return m_focused; } + void setFocused(bool); + + bool isVisible() const { return m_visible; } + void setVisible(bool); + + void setContentScaleFactor(float scaleFactor) { m_contentScaleFactor = scaleFactor; } + float contentScaleFactor() const { return m_contentScaleFactor; } + + void setContentPosition(const WebCore::FloatPoint& position) { m_contentPosition = position; } + const WebCore::FloatPoint& contentPosition() const { return m_contentPosition; } + + void setUserViewportTranslation(double tx, double ty); + WebCore::IntPoint userViewportToContents(const WebCore::IntPoint&) const; + WebCore::IntPoint userViewportToScene(const WebCore::IntPoint&) const; + WebCore::IntPoint contentsToUserViewport(const WebCore::IntPoint&) const; + + void paintToCurrentGLContext(); + + WKPageRef pageRef() const { return toAPI(m_page.get()); } + + void setDrawsBackground(bool); + bool drawsBackground() const; + void setDrawsTransparentBackground(bool); + bool drawsTransparentBackground() const; + + void suspendActiveDOMObjectsAndAnimations(); + void resumeActiveDOMObjectsAndAnimations(); + + void setShowsAsSource(bool); + bool showsAsSource() const; + +#if ENABLE(FULLSCREEN_API) + bool exitFullScreen(); +#endif + + void findZoomableAreaForPoint(const WebCore::IntPoint&, const WebCore::IntSize&); + + // View client. + void initializeClient(const WKViewClient*); + + WebPageProxy* page() { return m_page.get(); } + + void didChangeContentsSize(const WebCore::IntSize&); + const WebCore::IntSize& contentsSize() const { return m_contentsSize; } + WebCore::FloatSize visibleContentsSize() const; + void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&); + + // FIXME: Should become private when Web Events creation is moved to WebView. + WebCore::AffineTransform transformFromScene() const; + WebCore::AffineTransform transformToScene() const; + + void setOpacity(double opacity) { m_opacity = clampTo(opacity, 0.0, 1.0); } + double opacity() const { return m_opacity; } + +protected: + WebView(WebContext*, WebPageGroup*); + WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene(); + + void updateViewportSize(); + WebCore::FloatSize dipSize() const; + // PageClient + virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy() OVERRIDE; + + virtual void setViewNeedsDisplay(const WebCore::IntRect&) OVERRIDE; + + virtual void displayView() OVERRIDE; + + virtual bool canScrollView() OVERRIDE { return false; } + virtual void scrollView(const WebCore::IntRect&, const WebCore::IntSize&) OVERRIDE; + + virtual WebCore::IntSize viewSize() OVERRIDE; + + virtual bool isViewWindowActive() OVERRIDE; + virtual bool isViewFocused() OVERRIDE; + virtual bool isViewVisible() OVERRIDE; + virtual bool isViewInWindow() OVERRIDE; + + virtual void processDidCrash() OVERRIDE; + virtual void didRelaunchProcess() OVERRIDE; + virtual void pageClosed() OVERRIDE; + + virtual void preferencesDidChange() OVERRIDE; + + virtual void toolTipChanged(const String&, const String&) OVERRIDE; + + virtual void pageDidRequestScroll(const WebCore::IntPoint&) OVERRIDE; + virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) OVERRIDE; + virtual void pageTransitionViewportReady() OVERRIDE; + + virtual void setCursor(const WebCore::Cursor&) OVERRIDE; + virtual void setCursorHiddenUntilMouseMoves(bool) OVERRIDE; + + virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&) OVERRIDE; + + virtual void registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo) OVERRIDE; + virtual void clearAllEditCommands() OVERRIDE; + virtual bool canUndoRedo(WebPageProxy::UndoOrRedo) OVERRIDE; + virtual void executeUndoRedo(WebPageProxy::UndoOrRedo) OVERRIDE; + + virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&) OVERRIDE; + virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&) OVERRIDE; + virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&) OVERRIDE; + virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&) OVERRIDE; + + virtual void updateTextInputState() OVERRIDE; + + virtual void handleDownloadRequest(DownloadProxy*) OVERRIDE; + + virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool) OVERRIDE; +#if ENABLE(TOUCH_EVENTS) + virtual void doneWithTouchEvent(const NativeWebTouchEvent&, bool wasEventHandled) OVERRIDE; +#endif + + virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*) OVERRIDE; + virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*) OVERRIDE; +#if ENABLE(INPUT_TYPE_COLOR) + virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&) OVERRIDE; +#endif + + virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool, bool) OVERRIDE; + + virtual void enterAcceleratedCompositingMode(const LayerTreeContext&) OVERRIDE; + virtual void exitAcceleratedCompositingMode() OVERRIDE; + virtual void updateAcceleratedCompositingMode(const LayerTreeContext&) OVERRIDE; + + virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>&) OVERRIDE; + +protected: + WebViewClient m_client; + RefPtr<WebPageProxy> m_page; + DefaultUndoController m_undoController; + WebCore::TransformationMatrix m_userViewportTransform; + WebCore::IntSize m_size; // Size in device units. + bool m_focused; + bool m_visible; + float m_contentScaleFactor; + double m_opacity; + WebCore::FloatPoint m_contentPosition; // Position in UI units. + WebCore::IntSize m_contentsSize; +}; + +} // namespace WebKit + +#endif // USE(COORDINATED_GRAPHICS) + +#endif // WebView_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.cpp new file mode 100644 index 000000000..f75de5023 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if USE(COORDINATED_GRAPHICS) + +#include "WebViewClient.h" + +#include "NotImplemented.h" +#include "WKAPICast.h" +#include "WKBase.h" +#include "WKRetainPtr.h" +#include "WebViewportAttributes.h" + +#if ENABLE(TOUCH_EVENTS) +#include "NativeWebTouchEvent.h" +#endif + +using namespace WebCore; + +namespace WebKit { + +void WebViewClient::viewNeedsDisplay(WebView* view, const IntRect& area) +{ + if (!m_client.viewNeedsDisplay) + return; + + m_client.viewNeedsDisplay(toAPI(view), toAPI(area), m_client.clientInfo); +} + +void WebViewClient::didChangeContentsSize(WebView* view, const IntSize& size) +{ + if (!m_client.didChangeContentsSize) + return; + + m_client.didChangeContentsSize(toAPI(view), toAPI(size), m_client.clientInfo); +} + +void WebViewClient::webProcessCrashed(WebView* view, const String& url) +{ + if (!m_client.webProcessCrashed) + return; + + m_client.webProcessCrashed(toAPI(view), adoptWK(toCopiedURLAPI(url)).get(), m_client.clientInfo); +} + +void WebViewClient::webProcessDidRelaunch(WebView* view) +{ + if (!m_client.webProcessDidRelaunch) + return; + + m_client.webProcessDidRelaunch(toAPI(view), m_client.clientInfo); +} + +void WebViewClient::didChangeContentsPosition(WebView* view, const WebCore::IntPoint& point) +{ + if (!m_client.didChangeContentsPosition) + return; + + m_client.didChangeContentsPosition(toAPI(view), toAPI(point), m_client.clientInfo); +} + +void WebViewClient::didRenderFrame(WebView* view, const WebCore::IntSize& size, const WebCore::IntRect& coveredRect) +{ + if (!m_client.didRenderFrame) + return; + + m_client.didRenderFrame(toAPI(view), toAPI(size), toAPI(coveredRect), m_client.clientInfo); +} + +void WebViewClient::didCompletePageTransition(WebView* view) +{ + if (!m_client.didCompletePageTransition) + return; + + m_client.didCompletePageTransition(toAPI(view), m_client.clientInfo); +} + +void WebViewClient::didChangeViewportAttributes(WebView* view, const ViewportAttributes& attributes) +{ + if (!m_client.didChangeViewportAttributes) + return; + + WKRetainPtr<WKViewportAttributesRef> wkAttributes = adoptWK(toAPI(WebViewportAttributes::create(attributes).leakRef())); + m_client.didChangeViewportAttributes(toAPI(view), wkAttributes.get(), m_client.clientInfo); +} + +void WebViewClient::didChangeTooltip(WebView* view, const String& tooltip) +{ + if (!m_client.didChangeTooltip) + return; + + m_client.didChangeTooltip(toAPI(view), adoptWK(toCopiedAPI(tooltip)).get(), m_client.clientInfo); +} + +void WebViewClient::didFindZoomableArea(WebView* view, const IntPoint& target, const IntRect& area) +{ + if (!m_client.didFindZoomableArea) + return; + + m_client.didFindZoomableArea(toAPI(view), toAPI(target), toAPI(area), m_client.clientInfo); +} + +#if ENABLE(TOUCH_EVENTS) +void WebViewClient::doneWithTouchEvent(WebView* view, const NativeWebTouchEvent& event, bool wasEventHandled) +{ +#if PLATFORM(EFL) + if (!m_client.doneWithTouchEvent) + return; + + m_client.doneWithTouchEvent(toAPI(view), toAPI(const_cast<EwkTouchEvent*>(event.nativeEvent())), wasEventHandled, m_client.clientInfo); +#else + notImplemented(); + UNUSED_PARAM(view); + UNUSED_PARAM(event); + UNUSED_PARAM(wasEventHandled); +#endif +} +#endif + +} // namespace WebKit + +#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.h new file mode 100644 index 000000000..51979e9c7 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.h @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebViewClient_h +#define WebViewClient_h + +#if USE(COORDINATED_GRAPHICS) + +#include "APIClient.h" +#include "WKView.h" +#include <wtf/text/WTFString.h> + +namespace WebCore { +class IntPoint; +class IntRect; +class IntSize; +class ViewportAttributes; +} + +namespace WebKit { + +class WebView; + +#if ENABLE(TOUCH_EVENTS) +class NativeWebTouchEvent; +#endif + +class WebViewClient: public APIClient<WKViewClient, kWKViewClientCurrentVersion> { +public: + void viewNeedsDisplay(WebView*, const WebCore::IntRect&); + void didChangeContentsSize(WebView*, const WebCore::IntSize&); + void webProcessCrashed(WebView*, const String& url); + void webProcessDidRelaunch(WebView*); + void didChangeContentsPosition(WebView*, const WebCore::IntPoint&); + void didRenderFrame(WebView*, const WebCore::IntSize&, const WebCore::IntRect&); + void didCompletePageTransition(WebView*); + void didChangeViewportAttributes(WebView*, const WebCore::ViewportAttributes&); + void didChangeTooltip(WebView*, const String& tooltip); + void didFindZoomableArea(WebView*, const WebCore::IntPoint&, const WebCore::IntRect&); +#if ENABLE(TOUCH_EVENTS) + void doneWithTouchEvent(WebView*, const NativeWebTouchEvent&, bool); +#endif +}; + +} // namespace WebKit + +#endif // USE(COORDINATED_GRAPHICS) + +#endif // WebViewClient_h diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp index 42d07379f..1070eb64d 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp @@ -28,12 +28,18 @@ #include "AuthenticationChallengeProxy.h" #include "DataReference.h" +#include "DownloadProxyMap.h" #include "WebContext.h" #include "WebData.h" #include "WebProcessMessages.h" #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> +#if ENABLE(NETWORK_PROCESS) +#include "NetworkProcessMessages.h" +#include "NetworkProcessProxy.h" +#endif + using namespace WebCore; namespace WebKit { @@ -44,13 +50,14 @@ static uint64_t generateDownloadID() return ++uniqueDownloadID; } -PassRefPtr<DownloadProxy> DownloadProxy::create(WebContext* webContext) +PassRefPtr<DownloadProxy> DownloadProxy::create(DownloadProxyMap& downloadProxyMap, WebContext* webContext) { - return adoptRef(new DownloadProxy(webContext)); + return adoptRef(new DownloadProxy(downloadProxyMap, webContext)); } -DownloadProxy::DownloadProxy(WebContext* webContext) - : m_webContext(webContext) +DownloadProxy::DownloadProxy(DownloadProxyMap& downloadProxyMap, WebContext* webContext) + : m_downloadProxyMap(downloadProxyMap) + , m_webContext(webContext) , m_downloadID(generateDownloadID()) { } @@ -65,7 +72,14 @@ void DownloadProxy::cancel() if (!m_webContext) return; - // FIXME (Multi-WebProcess): <rdar://problem/12239483> Downloads shouldn't be handled in the web process. +#if ENABLE(NETWORK_PROCESS) + if (m_webContext->usesNetworkProcess()) { + if (NetworkProcessProxy* networkProcess = m_webContext->networkProcess()) + networkProcess->connection()->send(Messages::NetworkProcess::CancelDownload(m_downloadID), 0); + return; + } +#endif + m_webContext->sendToAllProcesses(Messages::WebProcess::CancelDownload(m_downloadID)); } @@ -80,7 +94,7 @@ void DownloadProxy::processDidClose() if (!m_webContext) return; - m_webContext->downloadClient().processDidCrash(m_webContext, this); + m_webContext->downloadClient().processDidCrash(m_webContext.get(), this); } void DownloadProxy::didStart(const ResourceRequest& request) @@ -90,7 +104,7 @@ void DownloadProxy::didStart(const ResourceRequest& request) if (!m_webContext) return; - m_webContext->downloadClient().didStart(m_webContext, this); + m_webContext->downloadClient().didStart(m_webContext.get(), this); } void DownloadProxy::didReceiveAuthenticationChallenge(const AuthenticationChallenge& authenticationChallenge, uint64_t challengeID) @@ -98,10 +112,9 @@ void DownloadProxy::didReceiveAuthenticationChallenge(const AuthenticationChalle if (!m_webContext) return; - // FIXME (Multi-WebProcess): <rdar://problem/12239483> Downloads shouldn't be handled in the web process. - // Once this is fixed, remove WebContext::deprecatedSharedProcess(). - RefPtr<AuthenticationChallengeProxy> authenticationChallengeProxy = AuthenticationChallengeProxy::create(authenticationChallenge, challengeID, m_webContext->deprecatedSharedProcess()); - m_webContext->downloadClient().didReceiveAuthenticationChallenge(m_webContext, this, authenticationChallengeProxy.get()); + RefPtr<AuthenticationChallengeProxy> authenticationChallengeProxy = AuthenticationChallengeProxy::create(authenticationChallenge, challengeID, m_webContext->networkingProcessConnection()); + + m_webContext->downloadClient().didReceiveAuthenticationChallenge(m_webContext.get(), this, authenticationChallengeProxy.get()); } void DownloadProxy::didReceiveResponse(const ResourceResponse& response) @@ -109,7 +122,7 @@ void DownloadProxy::didReceiveResponse(const ResourceResponse& response) if (!m_webContext) return; - m_webContext->downloadClient().didReceiveResponse(m_webContext, this, response); + m_webContext->downloadClient().didReceiveResponse(m_webContext.get(), this, response); } void DownloadProxy::didReceiveData(uint64_t length) @@ -117,26 +130,30 @@ void DownloadProxy::didReceiveData(uint64_t length) if (!m_webContext) return; - m_webContext->downloadClient().didReceiveData(m_webContext, this, length); + m_webContext->downloadClient().didReceiveData(m_webContext.get(), this, length); } void DownloadProxy::shouldDecodeSourceDataOfMIMEType(const String& mimeType, bool& result) { + result = false; + if (!m_webContext) return; - result = m_webContext->downloadClient().shouldDecodeSourceDataOfMIMEType(m_webContext, this, mimeType); + result = m_webContext->downloadClient().shouldDecodeSourceDataOfMIMEType(m_webContext.get(), this, mimeType); } void DownloadProxy::decideDestinationWithSuggestedFilename(const String& filename, String& destination, bool& allowOverwrite, SandboxExtension::Handle& sandboxExtensionHandle) { + allowOverwrite = false; + if (!m_webContext) return; - destination = m_webContext->downloadClient().decideDestinationWithSuggestedFilename(m_webContext, this, filename, allowOverwrite); + destination = m_webContext->downloadClient().decideDestinationWithSuggestedFilename(m_webContext.get(), this, filename, allowOverwrite); if (!destination.isNull()) - SandboxExtension::createHandle(destination, SandboxExtension::WriteOnly, sandboxExtensionHandle); + SandboxExtension::createHandle(destination, SandboxExtension::ReadWrite, sandboxExtensionHandle); } void DownloadProxy::didCreateDestination(const String& path) @@ -144,7 +161,7 @@ void DownloadProxy::didCreateDestination(const String& path) if (!m_webContext) return; - m_webContext->downloadClient().didCreateDestination(m_webContext, this, path); + m_webContext->downloadClient().didCreateDestination(m_webContext.get(), this, path); } void DownloadProxy::didFinish() @@ -152,10 +169,10 @@ void DownloadProxy::didFinish() if (!m_webContext) return; - m_webContext->downloadClient().didFinish(m_webContext, this); + m_webContext->downloadClient().didFinish(m_webContext.get(), this); // This can cause the DownloadProxy object to be deleted. - m_webContext->downloadFinished(this); + m_downloadProxyMap.downloadFinished(this); } static PassRefPtr<WebData> createWebData(const CoreIPC::DataReference& data) @@ -173,20 +190,20 @@ void DownloadProxy::didFail(const ResourceError& error, const CoreIPC::DataRefer m_resumeData = createWebData(resumeData); - m_webContext->downloadClient().didFail(m_webContext, this, error); + m_webContext->downloadClient().didFail(m_webContext.get(), this, error); // This can cause the DownloadProxy object to be deleted. - m_webContext->downloadFinished(this); + m_downloadProxyMap.downloadFinished(this); } void DownloadProxy::didCancel(const CoreIPC::DataReference& resumeData) { m_resumeData = createWebData(resumeData); - m_webContext->downloadClient().didCancel(m_webContext, this); + m_webContext->downloadClient().didCancel(m_webContext.get(), this); // This can cause the DownloadProxy object to be deleted. - m_webContext->downloadFinished(this); + m_downloadProxyMap.downloadFinished(this); } #if PLATFORM(QT) diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h index 7108e272d..1d98305e0 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h @@ -41,15 +41,14 @@ namespace WebCore { namespace WebKit { +class DownloadProxyMap; class WebContext; class WebData; class WebPageProxy; -class DownloadProxy : public APIObject { +class DownloadProxy : public TypedAPIObject<APIObject::TypeDownload>, public CoreIPC::MessageReceiver { public: - static const Type APIType = TypeDownload; - - static PassRefPtr<DownloadProxy> create(WebContext*); + static PassRefPtr<DownloadProxy> create(DownloadProxyMap&, WebContext*); ~DownloadProxy(); uint64_t downloadID() const { return m_downloadID; } @@ -61,17 +60,19 @@ public: void invalidate(); void processDidClose(); - void didReceiveDownloadProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncDownloadProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + void didReceiveDownloadProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); + void didReceiveSyncDownloadProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); #if PLATFORM(QT) void startTransfer(const String& filename); #endif private: - explicit DownloadProxy(WebContext*); + explicit DownloadProxy(DownloadProxyMap&, WebContext*); - virtual Type type() const { return APIType; } + // CoreIPC::MessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; // Message handlers. void didStart(const WebCore::ResourceRequest&); @@ -85,7 +86,8 @@ private: void didFail(const WebCore::ResourceError&, const CoreIPC::DataReference& resumeData); void didCancel(const CoreIPC::DataReference& resumeData); - WebContext* m_webContext; + DownloadProxyMap& m_downloadProxyMap; + RefPtr<WebContext> m_webContext; uint64_t m_downloadID; RefPtr<WebData> m_resumeData; diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp new file mode 100644 index 000000000..f9b9f3ea8 --- /dev/null +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "DownloadProxyMap.h" + +#include "ChildProcessProxy.h" +#include "DownloadProxy.h" +#include "DownloadProxyMessages.h" +#include "MessageReceiverMap.h" +#include <wtf/StdLibExtras.h> + +namespace WebKit { + +DownloadProxyMap::DownloadProxyMap(ChildProcessProxy* process) + : m_process(process) +{ +} + +DownloadProxyMap::~DownloadProxyMap() +{ + ASSERT(m_downloads.isEmpty()); +} + +DownloadProxy* DownloadProxyMap::createDownloadProxy(WebContext* webContext) +{ + RefPtr<DownloadProxy> downloadProxy = DownloadProxy::create(*this, webContext); + m_downloads.set(downloadProxy->downloadID(), downloadProxy); + + m_process->addMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID(), downloadProxy.get()); + + return downloadProxy.get(); +} + +void DownloadProxyMap::downloadFinished(DownloadProxy* downloadProxy) +{ + ASSERT(m_downloads.contains(downloadProxy->downloadID())); + + downloadProxy->invalidate(); + m_downloads.remove(downloadProxy->downloadID()); + + m_process->removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID()); +} + +void DownloadProxyMap::processDidClose() +{ + // Invalidate all outstanding downloads. + for (HashMap<uint64_t, RefPtr<DownloadProxy>>::iterator::Values it = m_downloads.begin().values(), end = m_downloads.end().values(); it != end; ++it) { + (*it)->processDidClose(); + (*it)->invalidate(); + } + + m_downloads.clear(); + m_process = 0; +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_resource_private.h b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.h index df872c60a..f1648ad9f 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_resource_private.h +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,33 +23,38 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ewk_resource_private_h -#define ewk_resource_private_h +#ifndef DownloadProxyMap_h +#define DownloadProxyMap_h -#include "WKEinaSharedString.h" -#include "WKURL.h" -#include "ewk_object_private.h" +#include <wtf/HashMap.h> +#include <wtf/Noncopyable.h> #include <wtf/PassRefPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> -class EwkResource : public EwkObject { +namespace WebKit { + +class ChildProcessProxy; +class DownloadProxy; +class WebContext; + +class DownloadProxyMap { + WTF_MAKE_NONCOPYABLE(DownloadProxyMap); + public: - EWK_OBJECT_DECLARE(EwkResource) + explicit DownloadProxyMap(ChildProcessProxy*); + ~DownloadProxyMap(); - static PassRefPtr<EwkResource> create(WKURLRef url, bool isMainResource) - { - return adoptRef(new EwkResource(url, isMainResource)); - } + DownloadProxy* createDownloadProxy(WebContext*); + void downloadFinished(DownloadProxy*); - const char* url() const; - bool isMainResource() const; + bool isEmpty() const { return m_downloads.isEmpty(); } -private: - EwkResource(WKURLRef url, bool isMainResource); + void processDidClose(); - WKEinaSharedString m_url; - bool m_isMainResource; +private: + ChildProcessProxy* m_process; + HashMap<uint64_t, RefPtr<DownloadProxy>> m_downloads; }; -#endif // ewk_resource_private_h +} // namespace WebKit + +#endif // DownloadProxyMap_h diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp b/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp index 900d6a588..4d49d816c 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp +++ b/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp @@ -26,34 +26,40 @@ #include "config.h" #include "DrawingAreaProxy.h" +#include "DrawingAreaProxyMessages.h" #include "WebPageProxy.h" +#include "WebProcessProxy.h" #if USE(COORDINATED_GRAPHICS) -#include "LayerTreeCoordinatorProxy.h" -#include <CoreIPC/MessageID.h> +#include "CoordinatedLayerTreeHostProxy.h" #endif using namespace WebCore; namespace WebKit { +const double DrawingAreaProxy::didUpdateBackingStoreStateTimeout = 0.5; + DrawingAreaProxy::DrawingAreaProxy(DrawingAreaType type, WebPageProxy* webPageProxy) : m_type(type) , m_webPageProxy(webPageProxy) , m_size(webPageProxy->viewSize()) { + m_webPageProxy->process()->addMessageReceiver(Messages::DrawingAreaProxy::messageReceiverName(), webPageProxy->pageID(), this); } DrawingAreaProxy::~DrawingAreaProxy() { + m_webPageProxy->process()->removeMessageReceiver(Messages::DrawingAreaProxy::messageReceiverName(), m_webPageProxy->pageID()); } -void DrawingAreaProxy::setSize(const IntSize& size, const IntSize& scrollOffset) +void DrawingAreaProxy::setSize(const IntSize& size, const IntSize& layerPosition, const IntSize& scrollOffset) { - if (m_size == size && scrollOffset.isZero()) + if (m_size == size && m_layerPosition == layerPosition && scrollOffset.isZero()) return; m_size = size; + m_layerPosition = layerPosition; m_scrollOffset += scrollOffset; sizeDidChange(); } @@ -68,10 +74,6 @@ WebCore::IntRect DrawingAreaProxy::contentsRect() const { return IntRect(IntPoint::zero(), m_webPageProxy->viewSize()); } - -void DrawingAreaProxy::didReceiveLayerTreeCoordinatorProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) -{ -} #endif } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxy.h b/Source/WebKit2/UIProcess/DrawingAreaProxy.h index c4ed068b4..93b9f0b70 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxy.h +++ b/Source/WebKit2/UIProcess/DrawingAreaProxy.h @@ -29,32 +29,21 @@ #include "BackingStore.h" #include "DrawingAreaInfo.h" +#include "MessageReceiver.h" #include <WebCore/FloatPoint.h> #include <WebCore/IntRect.h> #include <WebCore/IntSize.h> #include <stdint.h> #include <wtf/Noncopyable.h> -namespace CoreIPC { - class Connection; - class MessageDecoder; - class MessageID; -} - -namespace WebCore { - class TransformationMatrix; -} - namespace WebKit { class LayerTreeContext; -class LayerTreeCoordinatorProxy; +class CoordinatedLayerTreeHostProxy; class UpdateInfo; -class WebLayerTreeInfo; -class WebLayerUpdateInfo; class WebPageProxy; -class DrawingAreaProxy { +class DrawingAreaProxy : public CoreIPC::MessageReceiver { WTF_MAKE_NONCOPYABLE(DrawingAreaProxy); public: @@ -62,8 +51,6 @@ public: DrawingAreaType type() const { return m_type; } - void didReceiveDrawingAreaProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - virtual void deviceScaleFactorDidChange() = 0; // FIXME: These should be pure virtual. @@ -75,21 +62,22 @@ public: virtual void waitForBackingStoreUpdateOnNextPaint() { } const WebCore::IntSize& size() const { return m_size; } - void setSize(const WebCore::IntSize&, const WebCore::IntSize& scrollOffset); + void setSize(const WebCore::IntSize&, const WebCore::IntSize&, const WebCore::IntSize& scrollOffset); - virtual void pageCustomRepresentationChanged() { } - virtual void waitForPossibleGeometryUpdate() { } + // The timeout, in seconds, we use when waiting for a DidUpdateGeometry message. + static const double didUpdateBackingStoreStateTimeout; + + virtual void waitForPossibleGeometryUpdate(double = didUpdateBackingStoreStateTimeout) { } virtual void colorSpaceDidChange() { } - virtual void minimumLayoutWidthDidChange() { } + virtual void minimumLayoutSizeDidChange() { } #if USE(COORDINATED_GRAPHICS) virtual void updateViewport(); virtual WebCore::IntRect viewportVisibleRect() const { return contentsRect(); } virtual WebCore::IntRect contentsRect() const; - LayerTreeCoordinatorProxy* layerTreeCoordinatorProxy() const { return m_layerTreeCoordinatorProxy.get(); } - virtual void setVisibleContentsRect(const WebCore::FloatRect& /* visibleContentsRect */, float /* scale */, const WebCore::FloatPoint& /* trajectoryVector */) { } - virtual void didReceiveLayerTreeCoordinatorProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + CoordinatedLayerTreeHostProxy* coordinatedLayerTreeHostProxy() const { return m_coordinatedLayerTreeHostProxy.get(); } + virtual void setVisibleContentsRect(const WebCore::FloatRect& /* visibleContentsRect */, const WebCore::FloatPoint& /* trajectoryVector */) { } WebPageProxy* page() { return m_webPageProxy; } #endif @@ -100,15 +88,19 @@ protected: WebPageProxy* m_webPageProxy; WebCore::IntSize m_size; + WebCore::IntSize m_layerPosition; WebCore::IntSize m_scrollOffset; #if USE(COORDINATED_GRAPHICS) - OwnPtr<LayerTreeCoordinatorProxy> m_layerTreeCoordinatorProxy; + OwnPtr<CoordinatedLayerTreeHostProxy> m_coordinatedLayerTreeHostProxy; #endif private: virtual void sizeDidChange() = 0; + // CoreIPC::MessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // CoreIPC message handlers. // FIXME: These should be pure virtual. virtual void update(uint64_t /* backingStoreStateID */, const UpdateInfo&) { } @@ -119,7 +111,7 @@ private: virtual void updateAcceleratedCompositingMode(uint64_t /* backingStoreStateID */, const LayerTreeContext&) { } #endif #if PLATFORM(MAC) - virtual void didUpdateGeometry(const WebCore::IntSize& newIntrinsicContentSize) { } + virtual void didUpdateGeometry() { } virtual void intrinsicContentSizeDidChange(const WebCore::IntSize& newIntrinsicContentSize) { } #endif }; diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in b/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in index b3f02afec..a272cb59d 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in +++ b/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in @@ -31,7 +31,7 @@ messages -> DrawingAreaProxy { #if PLATFORM(MAC) // Used by TiledCoreAnimationDrawingAreaProxy. - DidUpdateGeometry(WebCore::IntSize newIntrinsicContentSize) + DidUpdateGeometry() IntrinsicContentSizeDidChange(WebCore::IntSize newIntrinsicContentSize) #endif } diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp index 138f4c887..790c8a939 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp +++ b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp @@ -37,7 +37,7 @@ #include <WebCore/Region.h> #if USE(COORDINATED_GRAPHICS) -#include "LayerTreeCoordinatorProxy.h" +#include "CoordinatedLayerTreeHostProxy.h" #endif using namespace WebCore; @@ -61,7 +61,7 @@ DrawingAreaProxyImpl::DrawingAreaProxyImpl(WebPageProxy* webPageProxy) #if USE(COORDINATED_GRAPHICS) // Construct the proxy early to allow messages to be sent to the web process while AC is entered there. if (webPageProxy->pageGroup()->preferences()->forceCompositingMode()) - m_layerTreeCoordinatorProxy = adoptPtr(new LayerTreeCoordinatorProxy(this)); + m_coordinatedLayerTreeHostProxy = adoptPtr(new CoordinatedLayerTreeHostProxy(this)); #endif } @@ -193,11 +193,6 @@ void DrawingAreaProxyImpl::didUpdateBackingStoreState(uint64_t backingStoreState // Stop the responsiveness timer that was started in sendUpdateBackingStoreState. m_webPageProxy->process()->responsivenessTimer()->stop(); - if (m_nextBackingStoreStateID != m_currentBackingStoreStateID) - sendUpdateBackingStoreState(RespondImmediately); - else - m_hasReceivedFirstUpdate = true; - #if USE(ACCELERATED_COMPOSITING) if (layerTreeContext != m_layerTreeContext) { if (!m_layerTreeContext.isEmpty()) { @@ -210,7 +205,14 @@ void DrawingAreaProxyImpl::didUpdateBackingStoreState(uint64_t backingStoreState ASSERT(layerTreeContext == m_layerTreeContext); } } +#endif + + if (m_nextBackingStoreStateID != m_currentBackingStoreStateID) + sendUpdateBackingStoreState(RespondImmediately); + else + m_hasReceivedFirstUpdate = true; +#if USE(ACCELERATED_COMPOSITING) if (isInAcceleratedCompositingMode()) { ASSERT(!m_backingStore); return; @@ -280,10 +282,14 @@ void DrawingAreaProxyImpl::incorporateUpdate(const UpdateInfo& updateInfo) if (shouldScroll) m_webPageProxy->scrollView(updateInfo.scrollRect, updateInfo.scrollOffset); - - for (size_t i = 0; i < updateInfo.updateRects.size(); ++i) - m_webPageProxy->setViewNeedsDisplay(updateInfo.updateRects[i]); - + + if (shouldScroll && !m_webPageProxy->canScrollView()) + m_webPageProxy->setViewNeedsDisplay(IntRect(IntPoint(), m_webPageProxy->viewSize())); + else { + for (size_t i = 0; i < updateInfo.updateRects.size(); ++i) + m_webPageProxy->setViewNeedsDisplay(updateInfo.updateRects[i]); + } + if (WebPageProxy::debugPaintFlags() & kWKDebugFlashBackingStoreUpdates) m_webPageProxy->flashBackingStoreUpdates(updateInfo.updateRects); @@ -360,24 +366,17 @@ void DrawingAreaProxyImpl::enterAcceleratedCompositingMode(const LayerTreeContex m_layerTreeContext = layerTreeContext; m_webPageProxy->enterAcceleratedCompositingMode(layerTreeContext); #if USE(COORDINATED_GRAPHICS) - if (!m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy = adoptPtr(new LayerTreeCoordinatorProxy(this)); + if (!m_coordinatedLayerTreeHostProxy) + m_coordinatedLayerTreeHostProxy = adoptPtr(new CoordinatedLayerTreeHostProxy(this)); #endif } #if USE(COORDINATED_GRAPHICS) -void DrawingAreaProxyImpl::didReceiveLayerTreeCoordinatorProxyMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void DrawingAreaProxyImpl::setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, const WebCore::FloatPoint& trajectoryVector) { - if (m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy->didReceiveLayerTreeCoordinatorProxyMessage(connection, messageID, decoder); + if (m_coordinatedLayerTreeHostProxy) + m_coordinatedLayerTreeHostProxy->setVisibleContentsRect(visibleContentsRect, trajectoryVector); } - -void DrawingAreaProxyImpl::setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, float scale, const WebCore::FloatPoint& trajectoryVector) -{ - if (m_layerTreeCoordinatorProxy) - m_layerTreeCoordinatorProxy->setVisibleContentsRect(visibleContentsRect, scale, trajectoryVector); -} - #endif void DrawingAreaProxyImpl::exitAcceleratedCompositingMode() @@ -397,11 +396,6 @@ void DrawingAreaProxyImpl::updateAcceleratedCompositingMode(const LayerTreeConte } #endif -void DrawingAreaProxyImpl::pageCustomRepresentationChanged() -{ - m_webPageProxy->process()->send(Messages::DrawingArea::PageCustomRepresentationChanged(), m_webPageProxy->pageID()); -} - void DrawingAreaProxyImpl::discardBackingStoreSoon() { if (!m_isBackingStoreDiscardable || m_discardBackingStoreTimer.isActive()) diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h index fe0510ef8..27bc14307 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h +++ b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h @@ -39,7 +39,7 @@ class Region; namespace WebKit { -class LayerTreeCoordinatorProxy; +class CoordinatedLayerTreeHostProxy; class DrawingAreaProxyImpl : public DrawingAreaProxy { public: @@ -52,6 +52,8 @@ public: bool isInAcceleratedCompositingMode() const { return !m_layerTreeContext.isEmpty(); } #endif + bool hasReceivedFirstUpdate() const { return m_hasReceivedFirstUpdate; } + private: explicit DrawingAreaProxyImpl(WebPageProxy*); @@ -83,15 +85,12 @@ private: void exitAcceleratedCompositingMode(); void updateAcceleratedCompositingMode(const LayerTreeContext&); #if USE(COORDINATED_GRAPHICS) - virtual void setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, float scale, const WebCore::FloatPoint& trajectory); - void didReceiveLayerTreeCoordinatorProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, const WebCore::FloatPoint& trajectory) OVERRIDE; #endif #else bool isInAcceleratedCompositingMode() const { return false; } #endif - virtual void pageCustomRepresentationChanged(); - void discardBackingStoreSoon(); void discardBackingStore(); diff --git a/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h b/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h index 98885bf07..a5f685a9b 100644 --- a/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h +++ b/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h @@ -46,7 +46,7 @@ public: void didReceiveGeolocationPermissionDecision(uint64_t, bool allow); private: - typedef HashMap<uint64_t, RefPtr<GeolocationPermissionRequestProxy> > PendingRequestMap; + typedef HashMap<uint64_t, RefPtr<GeolocationPermissionRequestProxy>> PendingRequestMap; PendingRequestMap m_pendingRequests; WebPageProxy* m_page; }; diff --git a/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h b/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h index c34c3fd3c..391275412 100644 --- a/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h +++ b/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h @@ -33,10 +33,8 @@ namespace WebKit { class GeolocationPermissionRequestManagerProxy; -class GeolocationPermissionRequestProxy : public APIObject { +class GeolocationPermissionRequestProxy : public TypedAPIObject<APIObject::TypeGeolocationPermissionRequest> { public: - static const Type APIType = TypeGeolocationPermissionRequest; - static PassRefPtr<GeolocationPermissionRequestProxy> create(GeolocationPermissionRequestManagerProxy* manager, uint64_t geolocationID) { return adoptRef(new GeolocationPermissionRequestProxy(manager, geolocationID)); @@ -50,8 +48,6 @@ public: private: GeolocationPermissionRequestProxy(GeolocationPermissionRequestManagerProxy*, uint64_t geolocationID); - virtual Type type() const { return APIType; } - GeolocationPermissionRequestManagerProxy* m_manager; uint64_t m_geolocationID; }; diff --git a/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp new file mode 100644 index 000000000..734926c6c --- /dev/null +++ b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2011 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "HTTPRequest.h" + +#include <wtf/text/CString.h> + +using namespace WebCore; + +namespace WebKit { + +PassRefPtr<HTTPRequest> HTTPRequest::parseHTTPRequestFromBuffer(const char* data, size_t length, String& failureReason) +{ + if (!length) { + failureReason = "No data to parse."; + return 0; + } + + // Request we will be building. + RefPtr<HTTPRequest> request = HTTPRequest::create(); + + // Advance a pointer through the data as needed. + const char* pos = data; + size_t remainingLength = length; + + // 1. Parse Method + URL. + size_t requestLineLength = request->parseRequestLine(pos, remainingLength, failureReason); + if (!requestLineLength) + return 0; + pos += requestLineLength; + remainingLength -= requestLineLength; + + // 2. Parse HTTP Headers. + size_t headersLength = request->parseHeaders(pos, remainingLength, failureReason); + if (!headersLength) + return 0; + pos += headersLength; + remainingLength -= headersLength; + + // 3. Parse HTTP Data. + size_t dataLength = request->parseRequestBody(pos, remainingLength); + pos += dataLength; + remainingLength -= dataLength; + + // We should have processed the entire input. + ASSERT(!remainingLength); + return request.release(); +} + +size_t HTTPRequest::parseRequestLine(const char* data, size_t length, String& failureReason) +{ + String url; + size_t result = parseHTTPRequestLine(data, length, failureReason, m_requestMethod, url, m_httpVersion); + m_url = KURL(KURL(), url); + return result; +} + +size_t HTTPRequest::parseHeaders(const char* data, size_t length, String& failureReason) +{ + const char* p = data; + const char* end = data + length; + AtomicString name; + String value; + for (; p < data + length; p++) { + size_t consumedLength = parseHTTPHeader(p, end - p, failureReason, name, value); + if (!consumedLength) + return 0; + p += consumedLength; + if (name.isEmpty()) + break; + m_headerFields.add(name, value); + } + return p - data; +} + +size_t HTTPRequest::parseRequestBody(const char* data, size_t length) +{ + return parseHTTPRequestBody(data, length, m_body); +} + +HTTPRequest::HTTPRequest() + : m_httpVersion(WebCore::Unknown) +{ +} + +HTTPRequest::HTTPRequest(const String& requestMethod, const KURL& url, HTTPVersion version) + : m_url(url) + , m_httpVersion(version) + , m_requestMethod(requestMethod) +{ +} + +HTTPRequest::~HTTPRequest() +{ +} + +} // namespace WebCore diff --git a/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h new file mode 100644 index 000000000..719e24114 --- /dev/null +++ b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2010 Google Inc. All rights reserved. + * Copyright (C) 2011 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HTTPRequest_h +#define HTTPRequest_h + +#include <WebCore/HTTPHeaderMap.h> +#include <WebCore/HTTPParsers.h> +#include <WebCore/KURL.h> +#include <wtf/PassRefPtr.h> +#include <wtf/RefCounted.h> +#include <wtf/text/WTFString.h> + +namespace WebKit { + +class HTTPRequest : public RefCounted<HTTPRequest> { +public: + static PassRefPtr<HTTPRequest> create() { return adoptRef(new HTTPRequest()); } + static PassRefPtr<HTTPRequest> create(const String& requestMethod, const WebCore::KURL& url, WebCore::HTTPVersion version) { return adoptRef(new HTTPRequest(requestMethod, url, version)); } + static PassRefPtr<HTTPRequest> parseHTTPRequestFromBuffer(const char* data, size_t length, String& failureReason); + virtual ~HTTPRequest(); + + String requestMethod() const { return m_requestMethod; } + void setRequestMethod(const String& method) { m_requestMethod = method; } + + WebCore::KURL url() const { return m_url; } + void setURL(const WebCore::KURL& url) { m_url = url; } + + const Vector<unsigned char>& body() const { return m_body; } + + const WebCore::HTTPHeaderMap& headerFields() const { return m_headerFields; } + void addHeaderField(const AtomicString& name, const String& value) { m_headerFields.add(name, value); } + void addHeaderField(const char* name, const String& value) { m_headerFields.add(name, value); } + +protected: + HTTPRequest(); + HTTPRequest(const String& requestMethod, const WebCore::KURL&, WebCore::HTTPVersion); + + // Parsing helpers. + size_t parseRequestLine(const char* data, size_t length, String& failureReason); + size_t parseHeaders(const char* data, size_t length, String& failureReason); + size_t parseRequestBody(const char* data, size_t length); + + WebCore::KURL m_url; + WebCore::HTTPVersion m_httpVersion; + String m_requestMethod; + WebCore::HTTPHeaderMap m_headerFields; + Vector<unsigned char> m_body; +}; + +} // namespace WebKit + +#endif // HTTPRequest_h diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp index bc585e94d..cbbd73f66 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp @@ -30,9 +30,9 @@ #include "WebInspectorServer.h" +#include "HTTPRequest.h" #include "WebInspectorProxy.h" #include "WebSocketServerConnection.h" -#include <WebCore/HTTPRequest.h> using namespace WebCore; diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h index 5dd87f54a..fc8ddf485 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h +++ b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h @@ -54,19 +54,23 @@ private: ~WebInspectorServer(); // WebSocketServerClient implementation. Events coming from remote connections. - virtual void didReceiveUnrecognizedHTTPRequest(WebSocketServerConnection*, PassRefPtr<WebCore::HTTPRequest>); - virtual bool didReceiveWebSocketUpgradeHTTPRequest(WebSocketServerConnection*, PassRefPtr<WebCore::HTTPRequest>); - virtual void didEstablishWebSocketConnection(WebSocketServerConnection*, PassRefPtr<WebCore::HTTPRequest>); + virtual void didReceiveUnrecognizedHTTPRequest(WebSocketServerConnection*, PassRefPtr<HTTPRequest>); + virtual bool didReceiveWebSocketUpgradeHTTPRequest(WebSocketServerConnection*, PassRefPtr<HTTPRequest>); + virtual void didEstablishWebSocketConnection(WebSocketServerConnection*, PassRefPtr<HTTPRequest>); virtual void didReceiveWebSocketMessage(WebSocketServerConnection*, const String& message); virtual void didCloseWebSocketConnection(WebSocketServerConnection*); bool platformResourceForPath(const String& path, Vector<char>& data, String& contentType); -#if PLATFORM(QT) || PLATFORM(GTK) +#if PLATFORM(QT) || PLATFORM(GTK) || PLATFORM(EFL) void buildPageList(Vector<char>& data, String& contentType); #endif void closeConnection(WebInspectorProxy*, WebSocketServerConnection*); +#if PLATFORM(GTK) + String inspectorServerFilesPath(); + String m_inspectorServerFilesPath; +#endif unsigned m_nextAvailablePageId; ClientMap m_clientMap; HashMap<unsigned, WebSocketServerConnection*> m_connectionMap; diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h index 80405c6e9..68ed64f7c 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h @@ -29,15 +29,14 @@ #if ENABLE(INSPECTOR_SERVER) -#if PLATFORM(GTK) -#include <gio/gio.h> -#endif #include <wtf/Deque.h> #include <wtf/OwnPtr.h> -#if PLATFORM(GTK) +#include <wtf/text/WTFString.h> + +#if USE(SOUP) +#include <gio/gio.h> #include <wtf/gobject/GRefPtr.h> #endif -#include <wtf/text/WTFString.h> #if PLATFORM(QT) namespace WebKit { @@ -84,7 +83,7 @@ private: unsigned short m_port; #if PLATFORM(QT) OwnPtr<QtTcpServerHandler> m_tcpServerHandler; -#elif PLATFORM(GTK) +#elif USE(SOUP) GRefPtr<GSocketService> m_socketService; #endif friend class WebSocketServerConnection; diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerClient.h b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerClient.h index 448486877..a73a0f3cd 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerClient.h +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerClient.h @@ -28,7 +28,7 @@ #if ENABLE(INSPECTOR_SERVER) -#include <WebCore/HTTPRequest.h> +#include "HTTPRequest.h" #include <wtf/PassRefPtr.h> #include <wtf/text/WTFString.h> @@ -41,13 +41,13 @@ public: virtual ~WebSocketServerClient() { } // Received an HTTP request but didn't know what to do with it. - virtual void didReceiveUnrecognizedHTTPRequest(WebSocketServerConnection*, PassRefPtr<WebCore::HTTPRequest>) { } + virtual void didReceiveUnrecognizedHTTPRequest(WebSocketServerConnection*, PassRefPtr<HTTPRequest>) { } // Received a WebSocket Upgrade HTTP request. Ask if we should handle it and upgrade. - virtual bool didReceiveWebSocketUpgradeHTTPRequest(WebSocketServerConnection*, PassRefPtr<WebCore::HTTPRequest>) { return true; } + virtual bool didReceiveWebSocketUpgradeHTTPRequest(WebSocketServerConnection*, PassRefPtr<HTTPRequest>) { return true; } // Established a WebSocket Connection. - virtual void didEstablishWebSocketConnection(WebSocketServerConnection*, PassRefPtr<WebCore::HTTPRequest>) { } + virtual void didEstablishWebSocketConnection(WebSocketServerConnection*, PassRefPtr<HTTPRequest>) { } // Received a WebSocket message. virtual void didReceiveWebSocketMessage(WebSocketServerConnection*, const String&) { } diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp index b50b17cdb..a33855546 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp @@ -30,9 +30,9 @@ #include "WebSocketServerConnection.h" +#include "HTTPRequest.h" #include "WebSocketServer.h" #include "WebSocketServerClient.h" -#include <WebCore/HTTPRequest.h> #include <WebCore/NotImplemented.h> #include <WebCore/SocketStreamError.h> #include <WebCore/SocketStreamHandle.h> diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.h b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.h index b849fbb63..13c551644 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.h +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.h @@ -37,12 +37,12 @@ namespace WebCore { class HTTPHeaderMap; -class HTTPRequest; class SocketStreamHandle; } namespace WebKit { +class HTTPRequest; class WebSocketServer; class WebSocketServerClient; @@ -76,7 +76,7 @@ private: void readHTTPMessage(); // WebSocket Mode. - void upgradeToWebSocketServerConnection(PassRefPtr<WebCore::HTTPRequest>); + void upgradeToWebSocketServerConnection(PassRefPtr<HTTPRequest>); void readWebSocketFrames(); bool readWebSocketFrame(); diff --git a/Source/WebKit2/UIProcess/InspectorServer/efl/WebInspectorServerEfl.cpp b/Source/WebKit2/UIProcess/InspectorServer/efl/WebInspectorServerEfl.cpp new file mode 100644 index 000000000..0d94c5340 --- /dev/null +++ b/Source/WebKit2/UIProcess/InspectorServer/efl/WebInspectorServerEfl.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2012 Seokju Kwon (seokju.kwon@gmail.com) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(INSPECTOR_SERVER) +#include "WebInspectorServer.h" + +#include "WebInspectorProxy.h" +#include "WebPageProxy.h" +#include <WebCore/EflInspectorUtilities.h> +#include <WebCore/MIMETypeRegistry.h> +#include <sys/stat.h> +#include <wtf/text/StringBuilder.h> + +namespace WebKit { + +bool WebInspectorServer::platformResourceForPath(const String& path, Vector<char>& data, String& contentType) +{ + // The page list contains an unformated list of pages that can be inspected with a link to open a session. + if (path == "/pagelist.json") { + buildPageList(data, contentType); + return true; + } + + // Point the default path to a formatted page that queries the page list and display them. + String localPath = WebCore::inspectorResourcePath() + ((path == "/") ? ASCIILiteral("/inspectorPageIndex.html") : path); + + FILE* fileHandle = fopen(localPath.utf8().data(), "r"); + if (!fileHandle) + return false; + + struct stat fileStat; + if (fstat(fileno(fileHandle), &fileStat)) { + fclose(fileHandle); + return false; + } + + data.grow(fileStat.st_size); + int bytesRead = fread(data.data(), 1, fileStat.st_size, fileHandle); + fclose(fileHandle); + + if (bytesRead < fileStat.st_size) + return false; + + size_t extStart = localPath.reverseFind('.'); + if (extStart == notFound) + return false; + + String ext = localPath.substring(extStart + 1); + if (ext.isEmpty()) + return false; + + contentType = WebCore::MIMETypeRegistry::getMIMETypeForExtension(ext); + + return true; +} + +void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType) +{ + StringBuilder builder; + builder.append('['); + + ClientMap::iterator end = m_clientMap.end(); + for (ClientMap::iterator it = m_clientMap.begin(); it != end; ++it) { + WebPageProxy* webPage = it->value->page(); + if (it != m_clientMap.begin()) + builder.appendLiteral(", "); + builder.appendLiteral("{ \"id\": "); + builder.appendNumber(it->key); + builder.appendLiteral(", \"title\": \""); + builder.append(webPage->pageTitle()); + builder.appendLiteral("\", \"url\": \""); + builder.append(webPage->activeURL()); + builder.appendLiteral("\", \"inspectorUrl\": \""); + builder.appendLiteral("/inspector.html?page="); + builder.appendNumber(it->key); + builder.appendLiteral("\" }"); + } + + builder.append(']'); + CString clientList = builder.toString().utf8(); + data.append(clientList.data(), clientList.length()); + contentType = String("application/json; charset=utf-8", String::ConstructFromLiteral); +} + +} +#endif diff --git a/Source/WebKit2/UIProcess/InspectorServer/front-end/inspectorPageIndex.html b/Source/WebKit2/UIProcess/InspectorServer/front-end/inspectorPageIndex.html index 885389e06..1528d177f 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/front-end/inspectorPageIndex.html +++ b/Source/WebKit2/UIProcess/InspectorServer/front-end/inspectorPageIndex.html @@ -9,15 +9,19 @@ function createPageList() { var pages = JSON.parse(xhr.responseText); if (pages.length) document.getElementById("noPageNotice").style.display = "none"; + + var pageList = document.createElement("ol"); for (var i in pages) { var link = document.createElement("a"); var title = pages[i].title ? pages[i].title : ("Page " + (Number(pages[i].id))); var url = pages[i].url; link.appendChild(document.createTextNode(title + (url ? (" [" + url + "]") : "" ))); link.setAttribute("href", pages[i].inspectorUrl); - document.body.appendChild(link); - document.body.appendChild(document.createElement("br")); + var pageListItem = document.createElement("li"); + pageListItem.appendChild(link); + pageList.appendChild(pageListItem); } + document.body.appendChild(pageList); } }; xhr.send(); diff --git a/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp b/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp index e339bfed9..b4cd214b1 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp @@ -23,6 +23,8 @@ */ #include "config.h" + +#if ENABLE(INSPECTOR_SERVER) #include "WebInspectorServer.h" #include "WebInspectorProxy.h" @@ -46,14 +48,26 @@ bool WebInspectorServer::platformResourceForPath(const String& path, Vector<char } // Point the default path to a formatted page that queries the page list and display them. - CString localPath = WebCore::fileSystemRepresentation(String(WebCore::sharedResourcesPath().data()) + ((path == "/") ? "/webinspector/inspectorPageIndex.html" : path)); + CString localPath = WebCore::fileSystemRepresentation(inspectorServerFilesPath() + ((path == "/") ? "/inspectorPageIndex.html" : path)); if (localPath.isNull()) return false; GRefPtr<GFile> file = adoptGRef(g_file_new_for_path(localPath.data())); - GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(file.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE","G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE, G_FILE_QUERY_INFO_NONE, 0, 0)); - if (!fileInfo) - return false; + GOwnPtr<GError> error; + GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(file.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE "," G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE, G_FILE_QUERY_INFO_NONE, 0, &error.outPtr())); + if (!fileInfo) { + StringBuilder builder; + builder.appendLiteral("<!DOCTYPE html><html><head></head><body>Error: "); + builder.appendNumber(error->code); + builder.appendLiteral(", "); + builder.append(error->message); + builder.appendLiteral(" occurred during fetching webinspector resource files.<br>Make sure you ran make install or have set WEBKIT_INSPECTOR_SERVER_PATH in your environment to point to webinspector folder.</body></html>"); + CString cstr = builder.toString().utf8(); + data.append(cstr.data(), cstr.length()); + contentType = "text/html; charset=utf-8"; + g_warning("Error fetching webinspector resource files: %d, %s", error->code, error->message); + return true; + } GRefPtr<GFileInputStream> inputStream = adoptGRef(g_file_read(file.get(), 0, 0)); if (!inputStream) @@ -83,7 +97,7 @@ void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType) builder.appendLiteral("\", \"url\": \""); builder.append(webPage->activeURL()); builder.appendLiteral("\", \"inspectorUrl\": \""); - builder.appendLiteral("/webinspector/inspector.html?page="); + builder.appendLiteral("/inspector.html?page="); builder.appendNumber(it->key); builder.appendLiteral("\" }"); } @@ -93,4 +107,19 @@ void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType) contentType = "application/json; charset=utf-8"; } +String WebInspectorServer::inspectorServerFilesPath() +{ + if (!m_inspectorServerFilesPath.isNull()) + return m_inspectorServerFilesPath; + + const char* environmentPath = g_getenv("WEBKIT_INSPECTOR_SERVER_PATH"); + if (environmentPath && g_file_test(environmentPath, G_FILE_TEST_IS_DIR)) + m_inspectorServerFilesPath = String(environmentPath); + else + m_inspectorServerFilesPath = String(WebCore::sharedResourcesPath().data()) + "/webinspector"; + + return m_inspectorServerFilesPath; +} + } +#endif diff --git a/Source/WebKit2/UIProcess/InspectorServer/qt/WebInspectorServerQt.cpp b/Source/WebKit2/UIProcess/InspectorServer/qt/WebInspectorServerQt.cpp index 11e57cfd5..2d060d068 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/qt/WebInspectorServerQt.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/qt/WebInspectorServerQt.cpp @@ -21,6 +21,7 @@ #include "config.h" +#if ENABLE(INSPECTOR_SERVER) #include "WebInspectorServer.h" #include "WebInspectorProxy.h" @@ -104,3 +105,4 @@ void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType) } } +#endif diff --git a/Source/WebKit2/UIProcess/InspectorServer/gtk/WebSocketServerGtk.cpp b/Source/WebKit2/UIProcess/InspectorServer/soup/WebSocketServerSoup.cpp index 9753a05ce..28f4f21d4 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/gtk/WebSocketServerGtk.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/soup/WebSocketServerSoup.cpp @@ -39,7 +39,7 @@ using namespace WebCore; namespace WebKit { -static gboolean connectionCallback(GSocketService* service, GSocketConnection* connection, GObject* sourceObject, WebSocketServer* server) +static gboolean connectionCallback(GSocketService* /*service*/, GSocketConnection* connection, GObject* /*sourceObject*/, WebSocketServer* server) { #if !LOG_DISABLED GRefPtr<GSocketAddress> socketAddress = adoptGRef(g_socket_connection_get_remote_address(connection, 0)); @@ -52,7 +52,7 @@ static gboolean connectionCallback(GSocketService* service, GSocketConnection* c server->didAcceptConnection(webSocketConnection.release()); return TRUE; -} +} void WebSocketServer::platformInitialize() { diff --git a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp index 31f0de425..a25b18310 100644 --- a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp +++ b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp @@ -31,11 +31,9 @@ namespace WebKit { -static WorkQueue& processLauncherWorkQueue() +static WorkQueue* processLauncherWorkQueue() { - // Give in to VisualStudio and its 31 character thread name limit and shorten the thread name to ProcLauncher instead of class name. - // See createThread() in Threading.cpp. - DEFINE_STATIC_LOCAL(WorkQueue, processLauncherWorkQueue, ("com.apple.WebKit.ProcLauncher")); + static WorkQueue* processLauncherWorkQueue = WorkQueue::create("com.apple.WebKit.ProcessLauncher").leakRef(); return processLauncherWorkQueue; } @@ -46,7 +44,7 @@ ProcessLauncher::ProcessLauncher(Client* client, const LaunchOptions& launchOpti { // Launch the process. m_isLaunching = true; - processLauncherWorkQueue().dispatch(bind(&ProcessLauncher::launchProcess, this)); + processLauncherWorkQueue()->dispatch(bind(&ProcessLauncher::launchProcess, this)); } void ProcessLauncher::didFinishLaunchingProcess(PlatformProcessIdentifier processIdentifier, CoreIPC::Connection::Identifier identifier) @@ -55,7 +53,18 @@ void ProcessLauncher::didFinishLaunchingProcess(PlatformProcessIdentifier proces m_isLaunching = false; if (!m_client) { - // FIXME: Dispose of the connection identifier. + // FIXME: Make Identifier a move-only object and release port rights/connections in the destructor. +#if PLATFORM(MAC) + if (identifier.port) + mach_port_mod_refs(mach_task_self(), identifier.port, MACH_PORT_RIGHT_RECEIVE, -1); + +#if HAVE(XPC) + if (identifier.xpcConnection) { + xpc_release(identifier.xpcConnection); + identifier.xpcConnection = 0; + } +#endif +#endif return; } diff --git a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h index 3ccdf6c7c..85467ee44 100644 --- a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h +++ b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h @@ -28,12 +28,11 @@ #include "Connection.h" #include "PlatformProcessIdentifier.h" +#include <wtf/HashMap.h> #include <wtf/RefPtr.h> #include <wtf/Threading.h> - -#ifndef NDEBUG +#include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> -#endif namespace WebKit { @@ -61,6 +60,7 @@ public: struct LaunchOptions { ProcessType processType; + HashMap<String, String> extraInitializationData; #if PLATFORM(MAC) static const cpu_type_t MatchCurrentArchitecture = 0; cpu_type_t architecture; diff --git a/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp b/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp index 83bb3ba49..9b918abb8 100644 --- a/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp +++ b/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp @@ -1,5 +1,6 @@ /* Copyright (C) 2012 Samsung Electronics + Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies). This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public @@ -22,9 +23,12 @@ #include "Connection.h" #include "ProcessExecutablePath.h" +#include <WebCore/AuthenticationChallenge.h> #include <WebCore/FileSystem.h> +#include <WebCore/NetworkingContext.h> #include <WebCore/ResourceHandle.h> #include <WebCore/RunLoop.h> +#include <wtf/OwnArrayPtr.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> @@ -32,6 +36,34 @@ using namespace WebCore; namespace WebKit { +static Vector<OwnArrayPtr<char>> createArgsArray(const String& prefix, const String& executablePath, const String& socket, const String& pluginPath) +{ + ASSERT(!executablePath.isEmpty()); + ASSERT(!socket.isEmpty()); + + Vector<String> splitArgs; + prefix.split(' ', splitArgs); + + splitArgs.append(executablePath); + splitArgs.append(socket); + if (!pluginPath.isEmpty()) + splitArgs.append(pluginPath); + + Vector<OwnArrayPtr<char>> args; + args.resize(splitArgs.size() + 1); // Extra room for null. + + size_t numArgs = splitArgs.size(); + for (size_t i = 0; i < numArgs; ++i) { + CString param = splitArgs[i].utf8(); + args[i] = adoptArrayPtr(new char[param.length() + 1]); // Room for the terminating null coming from the CString. + strncpy(args[i].get(), param.data(), param.length() + 1); // +1 here so that strncpy copies the ending null. + } + // execvp() needs the pointers' array to be null-terminated. + args[numArgs] = nullptr; + + return args; +} + void ProcessLauncher::launchProcess() { int sockets[2]; @@ -40,38 +72,35 @@ void ProcessLauncher::launchProcess() return; } - pid_t pid = fork(); - if (!pid) { // child process - close(sockets[1]); - String socket = String::format("%d", sockets[0]); - String executablePath; - switch (m_launchOptions.processType) { - case WebProcess: - executablePath = executablePathOfWebProcess(); - break; + String processCmdPrefix, executablePath, pluginPath; + switch (m_launchOptions.processType) { + case WebProcess: + executablePath = executablePathOfWebProcess(); + break; #if ENABLE(PLUGIN_PROCESS) - case PluginProcess: - executablePath = executablePathOfPluginProcess(); - break; + case PluginProcess: + executablePath = executablePathOfPluginProcess(); + pluginPath = m_launchOptions.extraInitializationData.get("plugin-path"); + break; #endif - default: - ASSERT_NOT_REACHED(); - return; - } + default: + ASSERT_NOT_REACHED(); + return; + } #ifndef NDEBUG - if (m_launchOptions.processCmdPrefix.isEmpty()) -#endif - execl(executablePath.utf8().data(), executablePath.utf8().data(), socket.utf8().data(), static_cast<char*>(0)); -#ifndef NDEBUG - else { - String cmd = makeString(m_launchOptions.processCmdPrefix, ' ', executablePath, ' ', socket); - if (system(cmd.utf8().data()) == -1) { - ASSERT_NOT_REACHED(); - return; - } - } + if (!m_launchOptions.processCmdPrefix.isEmpty()) + processCmdPrefix = m_launchOptions.processCmdPrefix; #endif + Vector<OwnArrayPtr<char>> args = createArgsArray(processCmdPrefix, executablePath, String::number(sockets[0]), pluginPath); + + // Do not perform memory allocation in the middle of the fork() + // exec() below. FastMalloc can potentially deadlock because + // the fork() doesn't inherit the running threads. + pid_t pid = fork(); + if (!pid) { // Child process. + close(sockets[1]); + execvp(args.data()[0].get(), reinterpret_cast<char* const*>(args.data())); } else if (pid > 0) { // parent process; close(sockets[0]); m_processIdentifier = pid; @@ -85,9 +114,15 @@ void ProcessLauncher::launchProcess() void ProcessLauncher::terminateProcess() { + if (m_isLaunching) { + invalidate(); + return; + } + if (!m_processIdentifier) return; kill(m_processIdentifier, SIGKILL); + m_processIdentifier = 0; } void ProcessLauncher::platformInvalidate() diff --git a/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp b/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp index f9b8e5b02..2ae1fdb5c 100644 --- a/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp +++ b/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp @@ -29,10 +29,13 @@ #include "Connection.h" #include "ProcessExecutablePath.h" +#include <WebCore/AuthenticationChallenge.h> #include <WebCore/FileSystem.h> +#include <WebCore/NetworkingContext.h> #include <WebCore/ResourceHandle.h> #include <WebCore/RunLoop.h> #include <errno.h> +#include <glib.h> #include <locale.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> @@ -41,6 +44,7 @@ #if OS(LINUX) #include <sys/prctl.h> +#include <sys/socket.h> #endif #ifdef SOCK_SEQPACKET @@ -57,17 +61,6 @@ static void childSetupFunction(gpointer userData) { int socket = GPOINTER_TO_INT(userData); close(socket); - - // Make child process inherit parent's locale. - g_setenv("LC_ALL", setlocale(LC_ALL, 0), TRUE); -} - -static void childFinishedFunction(GPid, gint status, gpointer userData) -{ - if (WIFEXITED(status) && !WEXITSTATUS(status)) - return; - - close(GPOINTER_TO_INT(userData)); } void ProcessLauncher::launchProcess() @@ -81,18 +74,26 @@ void ProcessLauncher::launchProcess() return; } - String executablePath = m_launchOptions.processType == WebProcess ? - executablePathOfWebProcess() : executablePathOfPluginProcess(); - CString binaryPath = fileSystemRepresentation(executablePath); + String executablePath, pluginPath; + CString realExecutablePath, realPluginPath; + if (m_launchOptions.processType == WebProcess) + executablePath = executablePathOfWebProcess(); + else { + executablePath = executablePathOfPluginProcess(); + pluginPath = m_launchOptions.extraInitializationData.get("plugin-path"); + realPluginPath = fileSystemRepresentation(pluginPath); + } + + realExecutablePath = fileSystemRepresentation(executablePath); GOwnPtr<gchar> socket(g_strdup_printf("%d", sockets[0])); - char* argv[3]; - argv[0] = const_cast<char*>(binaryPath.data()); + char* argv[4]; + argv[0] = const_cast<char*>(realExecutablePath.data()); argv[1] = socket.get(); - argv[2] = 0; + argv[2] = const_cast<char*>(realPluginPath.data()); + argv[3] = 0; GOwnPtr<GError> error; - int spawnFlags = G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD; - if (!g_spawn_async(0, argv, 0, static_cast<GSpawnFlags>(spawnFlags), childSetupFunction, GINT_TO_POINTER(sockets[1]), &pid, &error.outPtr())) { + if (!g_spawn_async(0, argv, 0, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, childSetupFunction, GINT_TO_POINTER(sockets[1]), &pid, &error.outPtr())) { g_printerr("Unable to fork a new WebProcess: %s.\n", error->message); ASSERT_NOT_REACHED(); } @@ -100,20 +101,22 @@ void ProcessLauncher::launchProcess() close(sockets[0]); m_processIdentifier = pid; - // Monitor the child process, it calls waitpid to prevent the child process from becomming a zombie, - // and it allows us to close the socket when the child process crashes. - g_child_watch_add(m_processIdentifier, childFinishedFunction, GINT_TO_POINTER(sockets[1])); - // We've finished launching the process, message back to the main run loop. RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, m_processIdentifier, sockets[1])); } void ProcessLauncher::terminateProcess() -{ +{ + if (m_isLaunching) { + invalidate(); + return; + } + if (!m_processIdentifier) return; kill(m_processIdentifier, SIGKILL); + m_processIdentifier = 0; } void ProcessLauncher::platformInvalidate() diff --git a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.h b/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.h index 00b73a92a..7b2145424 100644 --- a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.h +++ b/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.h @@ -26,8 +26,6 @@ #ifndef DynamicLinkerEnvironmentExtractor_h #define DynamicLinkerEnvironmentExtractor_h -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - #include <mach/machine.h> #include <wtf/Noncopyable.h> #include <wtf/RetainPtr.h> @@ -56,11 +54,9 @@ private: RetainPtr<NSString> m_executablePath; cpu_type_t m_architecture; - Vector<std::pair<CString, CString> > m_extractedVariables; + Vector<std::pair<CString, CString>> m_extractedVariables; }; } // namespace WebKit -#endif // __MAC_OS_X_VERSION_MIN_REQUIRED == 1060 - #endif // DynamicLinkerEnvironmentExtractor_h diff --git a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm b/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm index 6f35280a0..bca9ac3d0 100644 --- a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm +++ b/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm @@ -26,8 +26,6 @@ #include "config.h" #include "DynamicLinkerEnvironmentExtractor.h" -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - #include "EnvironmentVariables.h" #include <mach-o/loader.h> #include <mach-o/swap.h> @@ -200,5 +198,3 @@ void DynamicLinkerEnvironmentExtractor::getExtractedEnvironmentVariables(Environ } } // namespace WebKit - -#endif // __MAC_OS_X_VERSION_MIN_REQUIRED == 1060 diff --git a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp b/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp index be0f909eb..39c6baf4c 100644 --- a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp +++ b/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp @@ -136,8 +136,6 @@ void EnvironmentVariables::copyEnvironmentVariables() m_environmentPointer = m_environmentVariables.data(); } -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - const char* EnvironmentVariables::preexistingProcessServiceNameKey() { return "WEBKIT_PREEXISTING_PROCESS_SERVICE_NAME"; @@ -148,6 +146,12 @@ const char* EnvironmentVariables::preexistingProcessTypeKey() return "WEBKIT_PREEXISTING_PROCESS_TYPE"; } -#endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 +void EnvironmentVariables::dump() +{ + for (size_t i = 0; (*_NSGetEnviron())[i]; i++) + printf("%s\n", (*_NSGetEnviron())[i]); + + printf("\n\n\n"); +} } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h b/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h index ff4ab1060..78343cf37 100644 --- a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h +++ b/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h @@ -46,10 +46,10 @@ public: char** environmentPointer() const { return m_environmentPointer; } -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 static const char* preexistingProcessServiceNameKey(); static const char* preexistingProcessTypeKey(); -#endif + + static void dump(); private: const char* valueIfVariableHasName(const char* environmentVariable, const char* name) const; diff --git a/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm b/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm index af010e9d4..7c951668c 100644 --- a/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm +++ b/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm @@ -28,7 +28,6 @@ #import "DynamicLinkerEnvironmentExtractor.h" #import "EnvironmentVariables.h" -#import "WebProcess.h" #import "WebKitSystemInterface.h" #import <WebCore/RunLoop.h> #import <crt_externs.h> @@ -97,10 +96,8 @@ static void setUpTerminationNotificationHandler(pid_t pid) static void addDYLDEnvironmentAdditions(const ProcessLauncher::LaunchOptions& launchOptions, bool isWebKitDevelopmentBuild, EnvironmentVariables& environmentVariables) { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 DynamicLinkerEnvironmentExtractor environmentExtractor([[NSBundle mainBundle] executablePath], _NSGetMachExecuteHeader()->cputype); environmentExtractor.getExtractedEnvironmentVariables(environmentVariables); -#endif NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"]; NSString *frameworksPath = [[webKit2Bundle bundlePath] stringByDeletingLastPathComponent]; @@ -125,6 +122,11 @@ static void addDYLDEnvironmentAdditions(const ProcessLauncher::LaunchOptions& la NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"WebProcessShim.dylib"]; + } else if (launchOptions.processType == ProcessLauncher::NetworkProcess) { + NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"NetworkProcess.app"]; + NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; + + processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"SecItemShim.dylib"]; } // Make sure that the shim library file exists and insert it. @@ -140,16 +142,61 @@ static void addDYLDEnvironmentAdditions(const ProcessLauncher::LaunchOptions& la typedef void (ProcessLauncher::*DidFinishLaunchingProcessFunction)(PlatformProcessIdentifier, CoreIPC::Connection::Identifier); #if HAVE(XPC) -static void connectToWebProcessServiceForWebKitDevelopment(const ProcessLauncher::LaunchOptions&, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction, UUIDHolder* instanceUUID) + +static const char* serviceName(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment) +{ + switch (launchOptions.processType) { + case ProcessLauncher::WebProcess: + if (forDevelopment) + return "com.apple.WebKit.WebContent.Development"; + return "com.apple.WebKit.WebContent"; +#if ENABLE(NETWORK_PROCESS) + case ProcessLauncher::NetworkProcess: + if (forDevelopment) + return "com.apple.WebKit.Networking.Development"; + return "com.apple.WebKit.Networking"; +#endif +#if ENABLE(PLUGIN_PROCESS) + case ProcessLauncher::PluginProcess: + if (forDevelopment) + return "com.apple.WebKit.Plugin.Development"; + + // FIXME: Support plugins that require an executable heap. + if (launchOptions.architecture == CPU_TYPE_X86) + return "com.apple.WebKit.Plugin.32"; + if (launchOptions.architecture == CPU_TYPE_X86_64) + return "com.apple.WebKit.Plugin.64"; + + ASSERT_NOT_REACHED(); + return 0; +#endif +#if ENABLE(SHARED_WORKER_PROCESS) + case ProcessLauncher::SharedWorkerProcess: + ASSERT_NOT_REACHED(); + return 0; +#endif + } +} + +static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction, UUIDHolder* instanceUUID) { // Create a connection to the WebKit2 XPC service. - xpc_connection_t connection = xpc_connection_create("com.apple.WebKit2.WebProcessServiceForWebKitDevelopment", 0); + xpc_connection_t connection = xpc_connection_create(serviceName(launchOptions, forDevelopment), 0); xpc_connection_set_instance(connection, instanceUUID->uuid); // XPC requires having an event handler, even if it is not used. xpc_connection_set_event_handler(connection, ^(xpc_object_t event) { }); xpc_connection_resume(connection); +#if ENABLE(NETWORK_PROCESS) + if (launchOptions.processType == ProcessLauncher::NetworkProcess) { + xpc_object_t preBootstrapMessage = xpc_dictionary_create(0, 0, 0); + xpc_dictionary_set_string(preBootstrapMessage, "message-name", "pre-bootstrap"); + xpc_connection_send_message(connection, preBootstrapMessage); + xpc_release(preBootstrapMessage); + } +#endif + // Create the listening port. mach_port_t listeningPort; mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort); @@ -160,15 +207,29 @@ static void connectToWebProcessServiceForWebKitDevelopment(const ProcessLauncher NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; CString clientIdentifier = bundleIdentifier ? String([[NSBundle mainBundle] bundleIdentifier]).utf8() : *_NSGetProgname(); - xpc_object_t bootStrapMessage = xpc_dictionary_create(0, 0, 0); - xpc_dictionary_set_string(bootStrapMessage, "message-name", "bootstrap"); - xpc_dictionary_set_string(bootStrapMessage, "framework-executable-path", [[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] executablePath] fileSystemRepresentation]); - xpc_dictionary_set_mach_send(bootStrapMessage, "server-port", listeningPort); - xpc_dictionary_set_string(bootStrapMessage, "client-identifier", clientIdentifier.data()); + xpc_object_t bootstrapMessage = xpc_dictionary_create(0, 0, 0); + xpc_dictionary_set_string(bootstrapMessage, "message-name", "bootstrap"); + xpc_dictionary_set_string(bootstrapMessage, "framework-executable-path", [[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] executablePath] fileSystemRepresentation]); + xpc_dictionary_set_mach_send(bootstrapMessage, "server-port", listeningPort); + xpc_dictionary_set_string(bootstrapMessage, "client-identifier", clientIdentifier.data()); + xpc_dictionary_set_string(bootstrapMessage, "ui-process-name", [[[NSProcessInfo processInfo] processName] UTF8String]); + + if (forDevelopment) { + xpc_dictionary_set_fd(bootstrapMessage, "stdout", STDOUT_FILENO); + xpc_dictionary_set_fd(bootstrapMessage, "stderr", STDERR_FILENO); + } + + xpc_object_t extraInitializationData = xpc_dictionary_create(0, 0, 0); + HashMap<String, String>::const_iterator it = launchOptions.extraInitializationData.begin(); + HashMap<String, String>::const_iterator end = launchOptions.extraInitializationData.end(); + for (; it != end; ++it) + xpc_dictionary_set_string(extraInitializationData, it->key.utf8().data(), it->value.utf8().data()); + xpc_dictionary_set_value(bootstrapMessage, "extra-initialization-data", extraInitializationData); + xpc_release(extraInitializationData); that->ref(); - xpc_connection_send_message_with_reply(connection, bootStrapMessage, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t reply) { + xpc_connection_send_message_with_reply(connection, bootstrapMessage, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t reply) { xpc_type_t type = xpc_get_type(reply); if (type == XPC_TYPE_ERROR) { // We failed to launch. Release the send right. @@ -191,19 +252,19 @@ static void connectToWebProcessServiceForWebKitDevelopment(const ProcessLauncher that->deref(); }); - xpc_release(bootStrapMessage); + xpc_release(bootstrapMessage); } -static void createWebProcessServiceForWebKitDevelopment(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) +static void connectToReExecService(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) { EnvironmentVariables environmentVariables; addDYLDEnvironmentAdditions(launchOptions, true, environmentVariables); // Generate the uuid for the service instance we are about to create. - // FIXME: This UUID should be stored on the WebProcessProxy. + // FIXME: This UUID should be stored on the ChildProcessProxy. RefPtr<UUIDHolder> instanceUUID = UUIDHolder::create(); - xpc_connection_t reExecConnection = xpc_connection_create("com.apple.WebKit2.WebProcessServiceForWebKitDevelopment", 0); + xpc_connection_t reExecConnection = xpc_connection_create(serviceName(launchOptions, true), 0); xpc_connection_set_instance(reExecConnection, instanceUUID->uuid); // Keep the ProcessLauncher alive while we do the re-execing (balanced in event handler). @@ -215,7 +276,7 @@ static void createWebProcessServiceForWebKitDevelopment(const ProcessLauncher::L xpc_connection_set_event_handler(reExecConnection, ^(xpc_object_t event) { ASSERT(xpc_get_type(event) == XPC_TYPE_ERROR); - connectToWebProcessServiceForWebKitDevelopment(launchOptions, that, didFinishLaunchingProcessFunction, instanceUUID.get()); + connectToService(launchOptions, true, that, didFinishLaunchingProcessFunction, instanceUUID.get()); // Release the connection. xpc_release(reExecConnection); @@ -243,73 +304,27 @@ static void createWebProcessServiceForWebKitDevelopment(const ProcessLauncher::L xpc_dictionary_set_value(reExecMessage, "environment", environment); xpc_release(environment); -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 xpc_dictionary_set_bool(reExecMessage, "executable-heap", launchOptions.executableHeap); -#endif xpc_connection_send_message(reExecConnection, reExecMessage); xpc_release(reExecMessage); } -static void createWebProcessService(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) +static void createService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) { + if (forDevelopment) { + connectToReExecService(launchOptions, that, didFinishLaunchingProcessFunction); + return; + } + // Generate the uuid for the service instance we are about to create. - // FIXME: This UUID should be stored on the WebProcessProxy. + // FIXME: This UUID should be stored on the ChildProcessProxy. RefPtr<UUIDHolder> instanceUUID = UUIDHolder::create(); - - // Create a connection to the WebKit2 XPC service. - xpc_connection_t connection = xpc_connection_create("com.apple.WebKit2.WebProcessService", 0); - xpc_connection_set_instance(connection, instanceUUID->uuid); - - // XPC requires having an event handler, even if it is not used. - xpc_connection_set_event_handler(connection, ^(xpc_object_t event) { }); - xpc_connection_resume(connection); - - // Create the listening port. - mach_port_t listeningPort; - mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort); - - // Insert a send right so we can send to it. - mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND); - - NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; - CString clientIdentifier = bundleIdentifier ? String([[NSBundle mainBundle] bundleIdentifier]).utf8() : *_NSGetProgname(); - - xpc_object_t bootStrapMessage = xpc_dictionary_create(0, 0, 0); - xpc_dictionary_set_string(bootStrapMessage, "message-name", "bootstrap"); - xpc_dictionary_set_mach_send(bootStrapMessage, "server-port", listeningPort); - xpc_dictionary_set_string(bootStrapMessage, "client-identifier", clientIdentifier.data()); - - that->ref(); - - xpc_connection_send_message_with_reply(connection, bootStrapMessage, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t reply) { - xpc_type_t type = xpc_get_type(reply); - if (type == XPC_TYPE_ERROR) { - // We failed to launch. Release the send right. - mach_port_deallocate(mach_task_self(), listeningPort); - - // And the receive right. - mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1); - - RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, 0, CoreIPC::Connection::Identifier())); - } else { - ASSERT(type == XPC_TYPE_DICTIONARY); - ASSERT(!strcmp(xpc_dictionary_get_string(reply, "message-name"), "process-finished-launching")); - - // The process has finished launching, grab the pid from the connection. - pid_t processIdentifier = xpc_connection_get_pid(connection); - - // We've finished launching the process, message back to the main run loop. - RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort, connection))); - } - - that->deref(); - }); - xpc_release(bootStrapMessage); + connectToService(launchOptions, false, that, didFinishLaunchingProcessFunction, instanceUUID.get()); } + #endif -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 static bool tryPreexistingProcess(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) { EnvironmentVariables environmentVariables; @@ -355,7 +370,6 @@ static bool tryPreexistingProcess(const ProcessLauncher::LaunchOptions& launchOp RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort))); return true; } -#endif static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, bool isWebKitDevelopmentBuild, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) { @@ -369,13 +383,13 @@ static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, b // Insert a send right so we can send to it. mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND); - RetainPtr<CFStringRef> cfLocalization(AdoptCF, WKCopyCFLocalizationPreferredName(NULL)); + RetainPtr<CFStringRef> cfLocalization = adoptCF(WKCopyCFLocalizationPreferredName(NULL)); CString localization = String(cfLocalization.get()).utf8(); NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"]; NSString *processPath = nil; - switch(launchOptions.processType) { + switch (launchOptions.processType) { case ProcessLauncher::WebProcess: processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"WebProcess.app"]; break; @@ -405,7 +419,35 @@ static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, b // Make a unique, per pid, per process launcher web process service name. CString serviceName = String::format("com.apple.WebKit.WebProcess-%d-%p", getpid(), that).utf8(); - const char* args[] = { [processAppExecutablePath fileSystemRepresentation], [frameworkExecutablePath fileSystemRepresentation], "-type", ProcessLauncher::processTypeAsString(launchOptions.processType), "-servicename", serviceName.data(), "-localization", localization.data(), "-client-identifier", clientIdentifier.data(), 0 }; + Vector<const char*> args; + args.append([processAppExecutablePath fileSystemRepresentation]); + args.append([frameworkExecutablePath fileSystemRepresentation]); + args.append("-type"); + args.append(ProcessLauncher::processTypeAsString(launchOptions.processType)); + args.append("-servicename"); + args.append(serviceName.data()); + args.append("-localization"); + args.append(localization.data()); + args.append("-client-identifier"); + args.append(clientIdentifier.data()); + args.append("-ui-process-name"); + args.append([[[NSProcessInfo processInfo] processName] UTF8String]); + + HashMap<String, String>::const_iterator it = launchOptions.extraInitializationData.begin(); + HashMap<String, String>::const_iterator end = launchOptions.extraInitializationData.end(); + Vector<CString> temps; + for (; it != end; ++it) { + String keyPlusDash = "-" + it->key; + CString key(keyPlusDash.utf8().data()); + temps.append(key); + args.append(key.data()); + + CString value(it->value.utf8().data()); + temps.append(value); + args.append(value.data()); + } + + args.append(nullptr); // Register ourselves. kern_return_t kr = bootstrap_register2(bootstrap_port, const_cast<char*>(serviceName.data()), listeningPort, 0); @@ -435,16 +477,14 @@ static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, b // Start suspended so we can set up the termination notification handler. flags |= POSIX_SPAWN_START_SUSPENDED; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 static const int allowExecutableHeapFlag = 0x2000; if (launchOptions.executableHeap) flags |= allowExecutableHeapFlag; -#endif posix_spawnattr_setflags(&attr, flags); pid_t processIdentifier = 0; - int result = posix_spawn(&processIdentifier, args[0], 0, &attr, const_cast<char**>(args), environmentVariables.environmentPointer()); + int result = posix_spawn(&processIdentifier, args[0], 0, &attr, const_cast<char**>(args.data()), environmentVariables.environmentPointer()); posix_spawnattr_destroy(&attr); @@ -469,22 +509,14 @@ static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, b void ProcessLauncher::launchProcess() { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 if (tryPreexistingProcess(m_launchOptions, this, &ProcessLauncher::didFinishLaunchingProcess)) return; -#endif bool isWebKitDevelopmentBuild = ![[[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] bundlePath] stringByDeletingLastPathComponent] hasPrefix:@"/System/"]; #if HAVE(XPC) if (m_launchOptions.useXPC) { - if (m_launchOptions.processType == ProcessLauncher::WebProcess) { - if (isWebKitDevelopmentBuild) - createWebProcessServiceForWebKitDevelopment(m_launchOptions, this, &ProcessLauncher::didFinishLaunchingProcess); - else - createWebProcessService(m_launchOptions, this, &ProcessLauncher::didFinishLaunchingProcess); - } else - ASSERT_NOT_REACHED(); + createService(m_launchOptions, isWebKitDevelopmentBuild, this, &ProcessLauncher::didFinishLaunchingProcess); return; } #endif @@ -493,11 +525,17 @@ void ProcessLauncher::launchProcess() } void ProcessLauncher::terminateProcess() -{ +{ + if (m_isLaunching) { + invalidate(); + return; + } + if (!m_processIdentifier) return; kill(m_processIdentifier, SIGKILL); + m_processIdentifier = 0; } void ProcessLauncher::platformInvalidate() diff --git a/Source/WebKit2/UIProcess/Launcher/qt/ProcessLauncherQt.cpp b/Source/WebKit2/UIProcess/Launcher/qt/ProcessLauncherQt.cpp index 29f4467a4..7d0203478 100644 --- a/Source/WebKit2/UIProcess/Launcher/qt/ProcessLauncherQt.cpp +++ b/Source/WebKit2/UIProcess/Launcher/qt/ProcessLauncherQt.cpp @@ -36,7 +36,6 @@ #include <QProcess> #include <QString> #include <QtCore/qglobal.h> -#include <WebCore/NotImplemented.h> #include <WebCore/RunLoop.h> #include <wtf/HashSet.h> #include <wtf/PassRefPtr.h> @@ -51,6 +50,7 @@ #include <sys/resource.h> #include <sys/socket.h> #include <unistd.h> +#include <wtf/UniStdExtras.h> #endif #if defined(Q_OS_LINUX) @@ -62,6 +62,10 @@ #include <windows.h> #endif +#if ENABLE(SUID_SANDBOX_LINUX) +#include <QCoreApplication> +#endif + #if OS(DARWIN) #include <mach/mach_init.h> #include <servers/bootstrap.h> @@ -109,12 +113,14 @@ void QtWebProcess::setupChildProcess() void ProcessLauncher::launchProcess() { - QString commandLine = QLatin1String("%1 \"%2\" %3"); + QString commandLine; if (m_launchOptions.processType == WebProcess) { + commandLine = QLatin1String("%1 \"%2\" %3"); QByteArray webProcessPrefix = qgetenv("QT_WEBKIT2_WP_CMD_PREFIX"); commandLine = commandLine.arg(QLatin1String(webProcessPrefix.constData())).arg(QString(executablePathOfWebProcess())); #if ENABLE(PLUGIN_PROCESS) } else if (m_launchOptions.processType == PluginProcess) { + commandLine = QLatin1String("%1 \"%2\" %3 %4"); QByteArray pluginProcessPrefix = qgetenv("QT_WEBKIT2_PP_CMD_PREFIX"); commandLine = commandLine.arg(QLatin1String(pluginProcessPrefix.constData())).arg(QString(executablePathOfPluginProcess())); #endif @@ -157,8 +163,8 @@ void ProcessLauncher::launchProcess() while (fcntl(sockets[1], F_SETFD, FD_CLOEXEC) == -1) { if (errno != EINTR) { ASSERT_NOT_REACHED(); - while (close(sockets[0]) == -1 && errno == EINTR) { } - while (close(sockets[1]) == -1 && errno == EINTR) { } + closeWithRetry(sockets[0]); + closeWithRetry(sockets[1]); return; } } @@ -167,37 +173,53 @@ void ProcessLauncher::launchProcess() commandLine = commandLine.arg(sockets[0]); #endif - QProcess* webProcess = new QtWebProcess(); - webProcess->setProcessChannelMode(QProcess::ForwardedChannels); - webProcess->start(commandLine); +#if ENABLE(PLUGIN_PROCESS) + if (m_launchOptions.processType == PluginProcess) + commandLine = commandLine.arg(QString(m_launchOptions.extraInitializationData.get("plugin-path"))); +#endif + + QProcess* webProcessOrSUIDHelper = new QtWebProcess(); + webProcessOrSUIDHelper->setProcessChannelMode(QProcess::ForwardedChannels); + +#if ENABLE(SUID_SANDBOX_LINUX) + if (m_launchOptions.processType == WebProcess) { + QString sandboxCommandLine = QLatin1String("\"%1\" \"%2\" %3"); + sandboxCommandLine = sandboxCommandLine.arg(QCoreApplication::applicationDirPath() + QLatin1String("/SUIDSandboxHelper")); + sandboxCommandLine = sandboxCommandLine.arg(executablePathOfWebProcess()); + sandboxCommandLine = sandboxCommandLine.arg(sockets[0]); + + webProcessOrSUIDHelper->start(sandboxCommandLine); + } else + webProcessOrSUIDHelper->start(commandLine); +#else + webProcessOrSUIDHelper->start(commandLine); +#endif #if OS(UNIX) && !OS(DARWIN) // Don't expose the web socket to possible future web processes while (fcntl(sockets[0], F_SETFD, FD_CLOEXEC) == -1) { if (errno != EINTR) { ASSERT_NOT_REACHED(); - delete webProcess; + delete webProcessOrSUIDHelper; return; } } #endif - if (!webProcess->waitForStarted()) { + if (!webProcessOrSUIDHelper->waitForStarted()) { qDebug() << "Failed to start" << commandLine; ASSERT_NOT_REACHED(); #if OS(DARWIN) mach_port_deallocate(mach_task_self(), connector); mach_port_mod_refs(mach_task_self(), connector, MACH_PORT_RIGHT_RECEIVE, -1); #endif - delete webProcess; + delete webProcessOrSUIDHelper; return; } - #if OS(UNIX) - setpriority(PRIO_PROCESS, webProcess->pid(), 10); + setpriority(PRIO_PROCESS, webProcessOrSUIDHelper->pid(), 10); #endif - - RunLoop::main()->dispatch(bind(&WebKit::ProcessLauncher::didFinishLaunchingProcess, this, webProcess, connector)); + RunLoop::main()->dispatch(bind(&WebKit::ProcessLauncher::didFinishLaunchingProcess, this, webProcessOrSUIDHelper, connector)); } void ProcessLauncher::terminateProcess() diff --git a/Source/WebKit2/UIProcess/Launcher/win/ProcessLauncherWin.cpp b/Source/WebKit2/UIProcess/Launcher/win/ProcessLauncherWin.cpp deleted file mode 100644 index 7de782f68..000000000 --- a/Source/WebKit2/UIProcess/Launcher/win/ProcessLauncherWin.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ProcessLauncher.h" - -#include "Connection.h" -#include <WebCore/RunLoop.h> -#include <shlwapi.h> -#include <wtf/text/WTFString.h> - -#ifdef DEBUG_ALL -const LPCWSTR webProcessName = L"WebKit2WebProcess_debug.exe"; -#else -const LPCWSTR webProcessName = L"WebKit2WebProcess.exe"; -#endif - -#ifdef DEBUG_ALL -const LPCWSTR webKitDLLName = L"WebKit_debug.dll"; -#else -const LPCWSTR webKitDLLName = L"WebKit.dll"; -#endif - -using namespace WebCore; - -namespace WebKit { - -void ProcessLauncher::launchProcess() -{ - // First, create the server and client identifiers. - HANDLE serverIdentifier, clientIdentifier; - if (!CoreIPC::Connection::createServerAndClientIdentifiers(serverIdentifier, clientIdentifier)) { - // FIXME: What should we do here? - ASSERT_NOT_REACHED(); - } - - // Ensure that the child process inherits the client identifier. - ::SetHandleInformation(clientIdentifier, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); - - // To get the full file path to WebKit2WebProcess.exe, we fild the location of WebKit.dll, - // remove the last path component, and then append WebKit2WebProcess(_debug).exe. - HMODULE webKitModule = ::GetModuleHandleW(webKitDLLName); - ASSERT(webKitModule); - if (!webKitModule) - return; - - WCHAR pathStr[MAX_PATH]; - if (!::GetModuleFileNameW(webKitModule, pathStr, WTF_ARRAY_LENGTH(pathStr))) - return; - - ::PathRemoveFileSpecW(pathStr); - if (!::PathAppendW(pathStr, webProcessName)) - return; - - String commandLine(pathStr); - - // FIXME: It would be nice if we could just create a CommandLine object and output a command line vector from it. - Vector<UChar> commandLineVector; - append(commandLineVector, "\""); - append(commandLineVector, commandLine); - append(commandLineVector, "\""); - append(commandLineVector, " -type webprocess"); - append(commandLineVector, " -clientIdentifier "); - append(commandLineVector, String::number(reinterpret_cast<uintptr_t>(clientIdentifier))); - commandLineVector.append('\0'); - - STARTUPINFO startupInfo = { 0 }; - startupInfo.cb = sizeof(startupInfo); - PROCESS_INFORMATION processInformation = { 0 }; - BOOL result = ::CreateProcessW(0, commandLineVector.data(), 0, 0, true, 0, 0, 0, &startupInfo, &processInformation); - - // We can now close the client identifier handle. - ::CloseHandle(clientIdentifier); - - if (!result) { - // FIXME: What should we do here? - DWORD error = ::GetLastError(); - ASSERT_NOT_REACHED(); - } - - // Don't leak the thread handle. - ::CloseHandle(processInformation.hThread); - - // We've finished launching the process, message back to the run loop. - RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, processInformation.hProcess, serverIdentifier)); -} - -void ProcessLauncher::terminateProcess() -{ - if (!m_processIdentifier) - return; - - ::TerminateProcess(m_processIdentifier, 0); -} - -void ProcessLauncher::platformInvalidate() -{ - if (!m_processIdentifier) - return; - - ::CloseHandle(m_processIdentifier); - m_processIdentifier = 0; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h b/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h index aba9577f2..214552570 100644 --- a/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h +++ b/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h @@ -28,7 +28,7 @@ #if ENABLE(CUSTOM_PROTOCOLS) -#include "MessageID.h" +#include "MessageReceiver.h" #if PLATFORM(MAC) #include <wtf/HashMap.h> @@ -36,34 +36,29 @@ OBJC_CLASS WKCustomProtocolLoader; #endif -namespace CoreIPC { -class Connection; -class MessageDecoder; -} // namespace CoreIPC - namespace WebCore { class ResourceRequest; } // namespace WebCore namespace WebKit { -class WebProcessProxy; +class ChildProcessProxy; -class CustomProtocolManagerProxy { +class CustomProtocolManagerProxy : public CoreIPC::MessageReceiver { public: - explicit CustomProtocolManagerProxy(WebProcessProxy*); + explicit CustomProtocolManagerProxy(ChildProcessProxy*); - void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); void startLoading(uint64_t customProtocolID, const WebCore::ResourceRequest&); void stopLoading(uint64_t customProtocolID); private: - void didReceiveCustomProtocolManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + // CoreIPC::MessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - WebProcessProxy* m_webProcessProxy; + ChildProcessProxy* m_childProcessProxy; #if PLATFORM(MAC) - typedef HashMap<uint64_t, RetainPtr<WKCustomProtocolLoader> > LoaderMap; + typedef HashMap<uint64_t, RetainPtr<WKCustomProtocolLoader>> LoaderMap; LoaderMap m_loaderMap; #endif }; diff --git a/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm b/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm index 5c4aa03f3..0582d4802 100644 --- a/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm +++ b/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm @@ -28,11 +28,14 @@ #if ENABLE(CUSTOM_PROTOCOLS) +#import "ChildProcessProxy.h" #import "Connection.h" #import "CustomProtocolManagerMessages.h" +#import "CustomProtocolManagerProxyMessages.h" #import "DataReference.h" -#import "WebProcessProxy.h" +#import "WebCoreArgumentCoders.h" #import <WebCore/ResourceError.h> +#import <WebCore/ResourceRequest.h> #import <WebCore/ResourceResponse.h> using namespace CoreIPC; @@ -119,24 +122,20 @@ using namespace WebKit; namespace WebKit { -CustomProtocolManagerProxy::CustomProtocolManagerProxy(WebProcessProxy* webProcessProxy) - : m_webProcessProxy(webProcessProxy) +CustomProtocolManagerProxy::CustomProtocolManagerProxy(ChildProcessProxy* childProcessProxy) + : m_childProcessProxy(childProcessProxy) { - ASSERT(m_webProcessProxy); -} - -void CustomProtocolManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveCustomProtocolManagerProxyMessage(connection, messageID, decoder); + ASSERT(m_childProcessProxy); + m_childProcessProxy->addMessageReceiver(Messages::CustomProtocolManagerProxy::messageReceiverName(), this); } void CustomProtocolManagerProxy::startLoading(uint64_t customProtocolID, const ResourceRequest& coreRequest) { - NSURLRequest *request = coreRequest.nsURLRequest(); + NSURLRequest *request = coreRequest.nsURLRequest(DoNotUpdateHTTPBody); if (!request) return; - WKCustomProtocolLoader *loader = [[WKCustomProtocolLoader alloc] initWithCustomProtocolManagerProxy:this customProtocolID:customProtocolID request:request connection:m_webProcessProxy->connection()]; + WKCustomProtocolLoader *loader = [[WKCustomProtocolLoader alloc] initWithCustomProtocolManagerProxy:this customProtocolID:customProtocolID request:request connection:m_childProcessProxy->connection()]; ASSERT(loader); ASSERT(!m_loaderMap.contains(customProtocolID)); m_loaderMap.add(customProtocolID, loader); diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessManager.cpp b/Source/WebKit2/UIProcess/Network/NetworkProcessManager.cpp deleted file mode 100644 index 4340da394..000000000 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessManager.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "NetworkProcessManager.h" - -#include "NetworkProcessProxy.h" - -#if ENABLE(NETWORK_PROCESS) - -namespace WebKit { - -NetworkProcessManager& NetworkProcessManager::shared() -{ - DEFINE_STATIC_LOCAL(NetworkProcessManager, networkProcessManager, ()); - return networkProcessManager; -} - -NetworkProcessManager::NetworkProcessManager() -{ -} - -void NetworkProcessManager::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) -{ - ASSERT(reply); - - ensureNetworkProcess(); - ASSERT(m_networkProcess); - - m_networkProcess->getNetworkProcessConnection(reply); -} - -void NetworkProcessManager::ensureNetworkProcess() -{ - if (m_networkProcess) - return; - - m_networkProcess = NetworkProcessProxy::create(this); -} - -void NetworkProcessManager::removeNetworkProcessProxy(NetworkProcessProxy* networkProcessProxy) -{ - ASSERT(m_networkProcess); - ASSERT(networkProcessProxy == m_networkProcess.get()); - - m_networkProcess = 0; -} - - -} // namespace WebKit - -#endif // ENABLE(NETWORK_PROCESS) diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp index 1f9ce89ed..f15bdb442 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp @@ -26,57 +26,81 @@ #include "config.h" #include "NetworkProcessProxy.h" +#if ENABLE(NETWORK_PROCESS) + +#include "AuthenticationChallengeProxy.h" +#include "CustomProtocolManagerProxyMessages.h" +#include "DownloadProxyMessages.h" #include "NetworkProcessCreationParameters.h" -#include "NetworkProcessManager.h" #include "NetworkProcessMessages.h" #include "WebContext.h" #include "WebProcessMessages.h" #include <WebCore/RunLoop.h> -#if ENABLE(NETWORK_PROCESS) +#if USE(SECURITY_FRAMEWORK) +#include "SecItemShimProxy.h" +#endif + +#define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection()) using namespace WebCore; namespace WebKit { -PassRefPtr<NetworkProcessProxy> NetworkProcessProxy::create(NetworkProcessManager* manager) +PassRefPtr<NetworkProcessProxy> NetworkProcessProxy::create(WebContext* webContext) { - return adoptRef(new NetworkProcessProxy(manager)); + return adoptRef(new NetworkProcessProxy(webContext)); } -NetworkProcessProxy::NetworkProcessProxy(NetworkProcessManager* manager) - : m_networkProcessManager(manager) +NetworkProcessProxy::NetworkProcessProxy(WebContext* webContext) + : m_webContext(webContext) , m_numPendingConnectionRequests(0) +#if ENABLE(CUSTOM_PROTOCOLS) + , m_customProtocolManagerProxy(this) +#endif { - ProcessLauncher::LaunchOptions launchOptions; - launchOptions.processType = ProcessLauncher::NetworkProcess; + connect(); +} -#if PLATFORM(MAC) - launchOptions.architecture = ProcessLauncher::LaunchOptions::MatchCurrentArchitecture; - launchOptions.executableHeap = false; -#if HAVE(XPC) - launchOptions.useXPC = false; -#endif -#endif +NetworkProcessProxy::~NetworkProcessProxy() +{ +} - m_processLauncher = ProcessLauncher::create(this, launchOptions); +void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +{ + launchOptions.processType = ProcessLauncher::NetworkProcess; + platformGetLaunchOptions(launchOptions); } -NetworkProcessProxy::~NetworkProcessProxy() +void NetworkProcessProxy::connectionWillOpen(CoreIPC::Connection* connection) { +#if USE(SECURITY_FRAMEWORK) + SecItemShimProxy::shared().initializeConnection(connection); +#endif +} +void NetworkProcessProxy::connectionWillClose(CoreIPC::Connection*) +{ } void NetworkProcessProxy::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) { m_pendingConnectionReplies.append(reply); - if (m_processLauncher->isLaunching()) { + if (isLaunching()) { m_numPendingConnectionRequests++; return; } - m_connection->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); + connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); +} + +DownloadProxy* NetworkProcessProxy::createDownloadProxy() +{ + if (!m_downloadProxyMap) + m_downloadProxyMap = adoptPtr(new DownloadProxyMap(this)); + + return m_downloadProxyMap->createDownloadProxy(m_webContext); } void NetworkProcessProxy::networkProcessCrashedOrFailedToLaunch() @@ -93,33 +117,39 @@ void NetworkProcessProxy::networkProcessCrashedOrFailedToLaunch() } // Tell the network process manager to forget about this network process proxy. This may cause us to be deleted. - m_networkProcessManager->removeNetworkProcessProxy(this); + m_webContext->networkProcessCrashed(this); } -void NetworkProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void NetworkProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) { - didReceiveNetworkProcessProxyMessage(connection, messageID, decoder); + if (dispatchMessage(connection, decoder)) + return; + + if (m_webContext->dispatchMessage(connection, decoder)) + return; + + didReceiveNetworkProcessProxyMessage(connection, decoder); } -void NetworkProcessProxy::didClose(CoreIPC::Connection*) +void NetworkProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) { - // Notify all WebProcesses that the NetworkProcess crashed. - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0; i < contexts.size(); ++i) - contexts[i]->sendToAllProcesses(Messages::WebProcess::NetworkProcessCrashed()); + if (dispatchSyncMessage(connection, decoder, replyEncoder)) + return; - // This may cause us to be deleted. - networkProcessCrashedOrFailedToLaunch(); + ASSERT_NOT_REACHED(); } -void NetworkProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference, CoreIPC::StringReference) +void NetworkProcessProxy::didClose(CoreIPC::Connection*) { + if (m_downloadProxyMap) + m_downloadProxyMap->processDidClose(); + // This may cause us to be deleted. + networkProcessCrashedOrFailedToLaunch(); } -void NetworkProcessProxy::syncMessageSendTimedOut(CoreIPC::Connection*) +void NetworkProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference, CoreIPC::StringReference) { - } void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const CoreIPC::Attachment& connectionIdentifier) @@ -136,36 +166,32 @@ void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const CoreIPC:: #endif } -void NetworkProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier connectionIdentifier) +void NetworkProcessProxy::didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, const WebCore::AuthenticationChallenge& coreChallenge, uint64_t challengeID) +{ + WebPageProxy* page = WebProcessProxy::webPage(pageID); + MESSAGE_CHECK(page); + + RefPtr<AuthenticationChallengeProxy> authenticationChallenge = AuthenticationChallengeProxy::create(coreChallenge, challengeID, connection()); + page->didReceiveAuthenticationChallengeProxy(frameID, authenticationChallenge.release()); +} + +void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC::Connection::Identifier connectionIdentifier) { - ASSERT(!m_connection); + ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier); if (CoreIPC::Connection::identifierIsNull(connectionIdentifier)) { // FIXME: Do better cleanup here. return; } - m_connection = CoreIPC::Connection::createServerConnection(connectionIdentifier, this, RunLoop::main()); -#if PLATFORM(MAC) - m_connection->setShouldCloseConnectionOnMachExceptions(); -#endif - - m_connection->open(); - - NetworkProcessCreationParameters parameters; - platformInitializeNetworkProcess(parameters); - - // Initialize the network host process. - m_connection->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0); - for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i) - m_connection->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0); + connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0); m_numPendingConnectionRequests = 0; #if PLATFORM(MAC) - if (WebContext::applicationIsOccluded()) - m_connection->send(Messages::NetworkProcess::SetApplicationIsOccluded(true), 0); + if (m_webContext->canEnableProcessSuppressionForNetworkProcess()) + setProcessSuppressionEnabled(true); #endif } diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h index 13fdfd89a..2cc9e8840 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h +++ b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h @@ -28,59 +28,74 @@ #if ENABLE(NETWORK_PROCESS) -#include "Connection.h" +#include "ChildProcessProxy.h" #include "ProcessLauncher.h" #include "WebProcessProxyMessages.h" #include <wtf/Deque.h> +#if ENABLE(CUSTOM_PROTOCOLS) +#include "CustomProtocolManagerProxy.h" +#endif + +namespace WebCore { +class AuthenticationChallenge; +} + namespace WebKit { -class NetworkProcessManager; +class DownloadProxy; +class DownloadProxyMap; +class WebContext; struct NetworkProcessCreationParameters; -class NetworkProcessProxy : public RefCounted<NetworkProcessProxy>, CoreIPC::Connection::Client, ProcessLauncher::Client { +class NetworkProcessProxy : public ChildProcessProxy { public: - static PassRefPtr<NetworkProcessProxy> create(NetworkProcessManager*); + static PassRefPtr<NetworkProcessProxy> create(WebContext*); ~NetworkProcessProxy(); void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); - bool isValid() const { return m_connection; } + DownloadProxy* createDownloadProxy(); #if PLATFORM(MAC) - void setApplicationIsOccluded(bool); + void setProcessSuppressionEnabled(bool); #endif private: - NetworkProcessProxy(NetworkProcessManager*); + NetworkProcessProxy(WebContext*); - void platformInitializeNetworkProcess(NetworkProcessCreationParameters&); + // ChildProcessProxy + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) OVERRIDE; + virtual void connectionWillOpen(CoreIPC::Connection*) OVERRIDE; + virtual void connectionWillClose(CoreIPC::Connection*) OVERRIDE; + void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&); void networkProcessCrashedOrFailedToLaunch(); // CoreIPC::Connection::Client - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - virtual void didClose(CoreIPC::Connection*); - virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName); - virtual void syncMessageSendTimedOut(CoreIPC::Connection*); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + virtual void didClose(CoreIPC::Connection*) OVERRIDE; + virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) OVERRIDE; // Message handlers - void didReceiveNetworkProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + void didReceiveNetworkProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); void didCreateNetworkConnectionToWebProcess(const CoreIPC::Attachment&); - + void didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, const WebCore::AuthenticationChallenge&, uint64_t challengeID); + // ProcessLauncher::Client virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); - // The connection to the network process. - RefPtr<CoreIPC::Connection> m_connection; - - // The process launcher for the network process. - RefPtr<ProcessLauncher> m_processLauncher; - - NetworkProcessManager* m_networkProcessManager; + WebContext* m_webContext; unsigned m_numPendingConnectionRequests; - Deque<RefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> > m_pendingConnectionReplies; + Deque<RefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>> m_pendingConnectionReplies; + + OwnPtr<DownloadProxyMap> m_downloadProxyMap; + +#if ENABLE(CUSTOM_PROTOCOLS) + CustomProtocolManagerProxy m_customProtocolManagerProxy; +#endif }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in index 379b10864..7e91c384e 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in @@ -22,8 +22,10 @@ #if ENABLE(NETWORK_PROCESS) -messages -> NetworkProcessProxy { +messages -> NetworkProcessProxy LegacyReceiver { DidCreateNetworkConnectionToWebProcess(CoreIPC::Attachment connectionIdentifier) + + DidReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, WebCore::AuthenticationChallenge challenge, uint64_t challengeID) } #endif // ENABLE(NETWORK_PROCESS) diff --git a/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm b/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm index 02534e9b9..1d1ff1ccf 100644 --- a/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm +++ b/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm @@ -26,7 +26,6 @@ #import "config.h" #import "NetworkProcessProxy.h" -#import "NetworkProcessCreationParameters.h" #import "NetworkProcessMessages.h" #if ENABLE(NETWORK_PROCESS) @@ -35,17 +34,36 @@ using namespace WebCore; namespace WebKit { -void NetworkProcessProxy::platformInitializeNetworkProcess(NetworkProcessCreationParameters& parameters) -{ - parameters.parentProcessName = [[NSProcessInfo processInfo] processName]; -} - -void NetworkProcessProxy::setApplicationIsOccluded(bool applicationIsOccluded) +void NetworkProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled) { if (!isValid()) return; - m_connection->send(Messages::NetworkProcess::SetApplicationIsOccluded(applicationIsOccluded), 0); + connection()->send(Messages::NetworkProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0); +} + +#if HAVE(XPC) +static bool shouldUseXPC() +{ + if (id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseXPCServiceForWebProcess"]) + return [value boolValue]; + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + return true; +#else + return false; +#endif +} +#endif + +void NetworkProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +{ + launchOptions.architecture = ProcessLauncher::LaunchOptions::MatchCurrentArchitecture; + launchOptions.executableHeap = false; + +#if HAVE(XPC) + launchOptions.useXPC = shouldUseXPC(); +#endif } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h index 24db98b0c..2576a7a6f 100644 --- a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h +++ b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h @@ -33,22 +33,18 @@ namespace WebKit { class NotificationPermissionRequestManagerProxy; -class NotificationPermissionRequest : public APIObject { +class NotificationPermissionRequest : public TypedAPIObject<APIObject::TypeNotificationPermissionRequest> { public: - static const Type APIType = TypeNotificationPermissionRequest; - static PassRefPtr<NotificationPermissionRequest> create(NotificationPermissionRequestManagerProxy*, uint64_t notificationID); - + void allow(); void deny(); - + void invalidate(); - + private: NotificationPermissionRequest(NotificationPermissionRequestManagerProxy*, uint64_t notificationID); - - virtual Type type() const { return APIType; } - + NotificationPermissionRequestManagerProxy* m_manager; uint64_t m_notificationID; }; diff --git a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h index f6228e72a..72ef99f23 100644 --- a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h +++ b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h @@ -32,7 +32,6 @@ namespace WebKit { -class GeolocationPermissionRequestProxy; class WebPageProxy; class NotificationPermissionRequestManagerProxy { @@ -48,7 +47,7 @@ public: void didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allow); private: - typedef HashMap<uint64_t, RefPtr<NotificationPermissionRequest> > PendingRequestMap; + typedef HashMap<uint64_t, RefPtr<NotificationPermissionRequest>> PendingRequestMap; PendingRequestMap m_pendingRequests; WebPageProxy* m_page; }; diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotification.h b/Source/WebKit2/UIProcess/Notifications/WebNotification.h index 8edccedff..14e905c53 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotification.h +++ b/Source/WebKit2/UIProcess/Notifications/WebNotification.h @@ -41,15 +41,13 @@ class ArgumentEncoder; namespace WebKit { -class WebNotification : public APIObject { +class WebNotification : public TypedAPIObject<APIObject::TypeNotification> { public: - static const Type APIType = TypeNotification; - static PassRefPtr<WebNotification> create(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID) { return adoptRef(new WebNotification(title, body, iconURL, tag, lang, dir, originString, notificationID)); } - + const String& title() const { return m_title; } const String& body() const { return m_body; } const String& iconURL() const { return m_iconURL; } @@ -63,8 +61,6 @@ public: private: WebNotification(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID); - virtual Type type() const { return APIType; } - String m_title; String m_body; String m_iconURL; diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp index 9dfe29b00..9e462af9b 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,40 +31,67 @@ #include "WebContext.h" #include "WebNotification.h" #include "WebNotificationManagerMessages.h" -#include "WebNotificationManagerProxyMessages.h" #include "WebPageProxy.h" +#include "WebProcessProxy.h" #include "WebSecurityOrigin.h" +using namespace std; using namespace WTF; using namespace WebCore; namespace WebKit { +static uint64_t generateGlobalNotificationID() +{ + static uint64_t uniqueGlobalNotificationID = 1; + return uniqueGlobalNotificationID++; +} + +const char* WebNotificationManagerProxy::supplementName() +{ + return "WebNotificationManagerProxy"; +} + PassRefPtr<WebNotificationManagerProxy> WebNotificationManagerProxy::create(WebContext* context) { return adoptRef(new WebNotificationManagerProxy(context)); } WebNotificationManagerProxy::WebNotificationManagerProxy(WebContext* context) - : m_context(context) + : WebContextSupplement(context) { - m_context->addMessageReceiver(Messages::WebNotificationManagerProxy::messageReceiverName(), this); } -void WebNotificationManagerProxy::invalidate() +void WebNotificationManagerProxy::initializeProvider(const WKNotificationProvider *provider) +{ + m_provider.initialize(provider); + m_provider.addNotificationManager(this); +} + +// WebContextSupplement + +void WebNotificationManagerProxy::contextDestroyed() { m_provider.removeNotificationManager(this); } -void WebNotificationManagerProxy::initializeProvider(const WKNotificationProvider *provider) +void WebNotificationManagerProxy::refWebContextSupplement() { - m_provider.initialize(provider); - m_provider.addNotificationManager(this); + APIObject::ref(); +} + +void WebNotificationManagerProxy::derefWebContextSupplement() +{ + APIObject::deref(); } void WebNotificationManagerProxy::populateCopyOfNotificationPermissions(HashMap<String, bool>& permissions) { RefPtr<ImmutableDictionary> knownPermissions = m_provider.notificationPermissions(); + + if (!knownPermissions) + return; + permissions.clear(); RefPtr<ImmutableArray> knownOrigins = knownPermissions->keys(); for (size_t i = 0; i < knownOrigins->size(); ++i) { @@ -73,100 +100,149 @@ void WebNotificationManagerProxy::populateCopyOfNotificationPermissions(HashMap< } } -void WebNotificationManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebNotificationManagerProxy::show(WebPageProxy* webPage, const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t pageNotificationID) { - didReceiveWebNotificationManagerProxyMessage(connection, messageID, decoder); + uint64_t globalNotificationID = generateGlobalNotificationID(); + RefPtr<WebNotification> notification = WebNotification::create(title, body, iconURL, tag, lang, dir, originString, globalNotificationID); + pair<uint64_t, uint64_t> notificationIDPair = make_pair(webPage->pageID(), pageNotificationID); + m_globalNotificationMap.set(globalNotificationID, notificationIDPair); + m_notifications.set(notificationIDPair, make_pair(globalNotificationID, notification)); + m_provider.show(webPage, notification.get()); } -void WebNotificationManagerProxy::show(WebPageProxy* page, const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID) +void WebNotificationManagerProxy::cancel(WebPageProxy* webPage, uint64_t pageNotificationID) { - if (!isNotificationIDValid(notificationID)) - return; + if (WebNotification* notification = m_notifications.get(make_pair(webPage->pageID(), pageNotificationID)).second.get()) + m_provider.cancel(notification); +} - RefPtr<WebNotification> notification = WebNotification::create(title, body, iconURL, tag, lang, dir, originString, notificationID); - m_notifications.set(notificationID, notification); - m_provider.show(page, notification.get()); +void WebNotificationManagerProxy::didDestroyNotification(WebPageProxy* webPage, uint64_t pageNotificationID) +{ + auto globalIDNotificationPair = m_notifications.take(make_pair(webPage->pageID(), pageNotificationID)); + if (uint64_t globalNotificationID = globalIDNotificationPair.first) { + WebNotification* notification = globalIDNotificationPair.second.get(); + m_globalNotificationMap.remove(globalNotificationID); + m_provider.didDestroyNotification(notification); + } } -void WebNotificationManagerProxy::cancel(uint64_t notificationID) +static bool pageIDsMatch(uint64_t pageID, uint64_t, uint64_t desiredPageID, const Vector<uint64_t>&) { - if (!isNotificationIDValid(notificationID)) - return; - - RefPtr<WebNotification> notification = m_notifications.get(notificationID); - if (!notification) - return; - - m_provider.cancel(notification.get()); + return pageID == desiredPageID; } - -void WebNotificationManagerProxy::didDestroyNotification(uint64_t notificationID) + +static bool pageAndNotificationIDsMatch(uint64_t pageID, uint64_t pageNotificationID, uint64_t desiredPageID, const Vector<uint64_t>& desiredPageNotificationIDs) { - if (!isNotificationIDValid(notificationID)) - return; + return pageID == desiredPageID && desiredPageNotificationIDs.contains(pageNotificationID); +} - RefPtr<WebNotification> notification = m_notifications.take(notificationID); - if (!notification) - return; +void WebNotificationManagerProxy::clearNotifications(WebPageProxy* webPage) +{ + clearNotifications(webPage, Vector<uint64_t>(), pageIDsMatch); +} - m_provider.didDestroyNotification(notification.get()); +void WebNotificationManagerProxy::clearNotifications(WebPageProxy* webPage, const Vector<uint64_t>& pageNotificationIDs) +{ + clearNotifications(webPage, pageNotificationIDs, pageAndNotificationIDsMatch); } -void WebNotificationManagerProxy::clearNotifications(const Vector<uint64_t>& notificationIDs) +void WebNotificationManagerProxy::clearNotifications(WebPageProxy* webPage, const Vector<uint64_t>& pageNotificationIDs, NotificationFilterFunction filterFunction) { - m_provider.clearNotifications(notificationIDs); - size_t count = notificationIDs.size(); - for (size_t i = 0; i < count; ++i) - m_notifications.remove(notificationIDs[i]); + uint64_t targetPageID = webPage->pageID(); + + Vector<uint64_t> globalNotificationIDs; + globalNotificationIDs.reserveCapacity(m_globalNotificationMap.size()); + + for (auto it = m_notifications.begin(), end = m_notifications.end(); it != end; ++it) { + uint64_t webPageID = it->key.first; + uint64_t pageNotificationID = it->key.second; + if (!filterFunction(webPageID, pageNotificationID, targetPageID, pageNotificationIDs)) + continue; + + uint64_t globalNotificationID = it->value.first; + globalNotificationIDs.append(globalNotificationID); + } + + for (auto it = globalNotificationIDs.begin(), end = globalNotificationIDs.end(); it != end; ++it) { + auto pageNotification = m_globalNotificationMap.take(*it); + m_notifications.remove(pageNotification); + } + + m_provider.clearNotifications(globalNotificationIDs); } -void WebNotificationManagerProxy::providerDidShowNotification(uint64_t notificationID) +void WebNotificationManagerProxy::providerDidShowNotification(uint64_t globalNotificationID) { - if (!m_context) + auto it = m_globalNotificationMap.find(globalNotificationID); + if (it == m_globalNotificationMap.end()) return; - - m_context->sendToAllProcesses(Messages::WebNotificationManager::DidShowNotification(notificationID)); + + uint64_t webPageID = it->value.first; + WebPageProxy* webPage = WebProcessProxy::webPage(webPageID); + if (!webPage) + return; + + uint64_t pageNotificationID = it->value.second; + webPage->process()->send(Messages::WebNotificationManager::DidShowNotification(pageNotificationID), 0); } -void WebNotificationManagerProxy::providerDidClickNotification(uint64_t notificationID) +void WebNotificationManagerProxy::providerDidClickNotification(uint64_t globalNotificationID) { - if (!m_context) + auto it = m_globalNotificationMap.find(globalNotificationID); + if (it == m_globalNotificationMap.end()) return; - m_context->sendToAllProcesses(Messages::WebNotificationManager::DidClickNotification(notificationID)); + uint64_t webPageID = it->value.first; + WebPageProxy* webPage = WebProcessProxy::webPage(webPageID); + if (!webPage) + return; + + uint64_t pageNotificationID = it->value.second; + webPage->process()->send(Messages::WebNotificationManager::DidClickNotification(pageNotificationID), 0); } -void WebNotificationManagerProxy::providerDidCloseNotifications(ImmutableArray* notificationIDs) +void WebNotificationManagerProxy::providerDidCloseNotifications(ImmutableArray* globalNotificationIDs) { - if (!m_context) - return; - - size_t size = notificationIDs->size(); - - Vector<uint64_t> vectorNotificationIDs; - vectorNotificationIDs.reserveInitialCapacity(size); + HashMap<WebPageProxy*, Vector<uint64_t>> pageNotificationIDs; + size_t size = globalNotificationIDs->size(); for (size_t i = 0; i < size; ++i) { - uint64_t notificationID = notificationIDs->at<WebUInt64>(i)->value(); - vectorNotificationIDs.append(notificationID); + auto it = m_globalNotificationMap.find(globalNotificationIDs->at<WebUInt64>(i)->value()); + if (it == m_globalNotificationMap.end()) + continue; + + if (WebPageProxy* webPage = WebProcessProxy::webPage(it->value.first)) { + auto pageIt = pageNotificationIDs.find(webPage); + if (pageIt == pageNotificationIDs.end()) { + Vector<uint64_t> newVector; + newVector.reserveInitialCapacity(size); + pageIt = pageNotificationIDs.add(webPage, newVector).iterator; + } + + uint64_t pageNotificationID = it->value.second; + pageIt->value.append(pageNotificationID); + } + + m_notifications.remove(it->value); + m_globalNotificationMap.remove(it); } - - if (vectorNotificationIDs.size()) - m_context->sendToAllProcesses(Messages::WebNotificationManager::DidCloseNotifications(vectorNotificationIDs)); + + for (auto it = pageNotificationIDs.begin(), end = pageNotificationIDs.end(); it != end; ++it) + it->key->process()->send(Messages::WebNotificationManager::DidCloseNotifications(it->value), 0); } void WebNotificationManagerProxy::providerDidUpdateNotificationPolicy(const WebSecurityOrigin* origin, bool allowed) { - if (!m_context) + if (!context()) return; - m_context->sendToAllProcesses(Messages::WebNotificationManager::DidUpdateNotificationDecision(origin->toString(), allowed)); + context()->sendToAllProcesses(Messages::WebNotificationManager::DidUpdateNotificationDecision(origin->toString(), allowed)); } void WebNotificationManagerProxy::providerDidRemoveNotificationPolicies(ImmutableArray* origins) { - if (!m_context) + if (!context()) return; size_t size = origins->size(); @@ -179,7 +255,7 @@ void WebNotificationManagerProxy::providerDidRemoveNotificationPolicies(Immutabl for (size_t i = 0; i < size; ++i) originStrings.append(origins->at<WebSecurityOrigin>(i)->toString()); - m_context->sendToAllProcesses(Messages::WebNotificationManager::DidRemoveNotificationDecisions(originStrings)); + context()->sendToAllProcesses(Messages::WebNotificationManager::DidRemoveNotificationDecisions(originStrings)); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h index d54338769..5890b5c1b 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h +++ b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,6 +28,7 @@ #include "APIObject.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include "WebNotificationProvider.h" #include <WebCore/NotificationClient.h> #include <wtf/HashMap.h> @@ -42,45 +43,47 @@ class WebContext; class WebPageProxy; class WebSecurityOrigin; -class WebNotificationManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebNotificationManagerProxy : public TypedAPIObject<APIObject::TypeNotificationManager>, public WebContextSupplement { public: - static const Type APIType = TypeNotificationManager; - + + static const char* supplementName(); + static PassRefPtr<WebNotificationManagerProxy> create(WebContext*); - - void invalidate(); - void clearContext() { m_context = 0; } void initializeProvider(const WKNotificationProvider*); void populateCopyOfNotificationPermissions(HashMap<String, bool>&); - void show(WebPageProxy*, const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID); + void show(WebPageProxy*, const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t pageNotificationID); + void cancel(WebPageProxy*, uint64_t pageNotificationID); + void clearNotifications(WebPageProxy*); + void clearNotifications(WebPageProxy*, const Vector<uint64_t>& pageNotificationIDs); + void didDestroyNotification(WebPageProxy*, uint64_t pageNotificationID); void providerDidShowNotification(uint64_t notificationID); void providerDidClickNotification(uint64_t notificationID); void providerDidCloseNotifications(ImmutableArray* notificationIDs); void providerDidUpdateNotificationPolicy(const WebSecurityOrigin*, bool allowed); void providerDidRemoveNotificationPolicies(ImmutableArray* origins); - + + using APIObject::ref; + using APIObject::deref; + private: explicit WebNotificationManagerProxy(WebContext*); - - virtual Type type() const { return APIType; } - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebNotificationManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - - // Message handlers - void cancel(uint64_t notificationID); - void didDestroyNotification(uint64_t notificationID); - void clearNotifications(const Vector<uint64_t>& notificationIDs); - - typedef HashMap<uint64_t, RefPtr<WebNotification> > WebNotificationMap; - - WebContext* m_context; + + typedef bool (*NotificationFilterFunction)(uint64_t pageID, uint64_t pageNotificationID, uint64_t desiredPageID, const Vector<uint64_t>& desiredPageNotificationIDs); + void clearNotifications(WebPageProxy*, const Vector<uint64_t>& pageNotificationIDs, NotificationFilterFunction); + + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; + WebNotificationProvider m_provider; - WebNotificationMap m_notifications; + // Pair comprised of web page ID and the web process's notification ID + HashMap<uint64_t, pair<uint64_t, uint64_t>> m_globalNotificationMap; + // Key pair comprised of web page ID and the web process's notification ID; value pair comprised of global notification ID, and notification object + HashMap<pair<uint64_t, uint64_t>, pair<uint64_t, RefPtr<WebNotification>>> m_notifications; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/PageClient.h b/Source/WebKit2/UIProcess/PageClient.h index 56dc9a141..3b7ecb836 100644 --- a/Source/WebKit2/UIProcess/PageClient.h +++ b/Source/WebKit2/UIProcess/PageClient.h @@ -27,7 +27,7 @@ #define PageClient_h #include "ShareableBitmap.h" -#include "WebColorChooserProxy.h" +#include "WebColorPicker.h" #include "WebPageProxy.h" #include "WebPopupMenuProxy.h" #include <WebCore/AlternativeTextClient.h> @@ -65,11 +65,7 @@ class WebContextMenuProxy; class WebEditCommandProxy; class WebPopupMenuProxy; #if ENABLE(INPUT_TYPE_COLOR) -class WebColorChooserProxy; -#endif - -#if PLATFORM(WIN) -struct WindowGeometry; +class WebColorPicker; #endif #if PLATFORM(MAC) @@ -89,6 +85,8 @@ public: // Tell the view to immediately display its invalid rect. virtual void displayView() = 0; + // Return true if scrollView() can copy bits in the view. + virtual bool canScrollView() = 0; // Tell the view to scroll scrollRect by scrollOffset. virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset) = 0; @@ -114,6 +112,8 @@ public: virtual void didRelaunchProcess() = 0; virtual void pageClosed() = 0; + virtual void preferencesDidChange() = 0; + virtual void toolTipChanged(const String&, const String&) = 0; #if USE(TILED_BACKING_STORE) @@ -121,18 +121,19 @@ public: virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) = 0; virtual void pageTransitionViewportReady() = 0; #endif -#if PLATFORM(QT) +#if USE(COORDINATED_GRAPHICS) virtual void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&) = 0; - virtual void didReceiveMessageFromNavigatorQtObject(const String&) = 0; +#endif +#if PLATFORM(QT) virtual void handleAuthenticationRequiredRequest(const String& hostname, const String& realm, const String& prefilledUsername, String& username, String& password) = 0; virtual void handleCertificateVerificationRequest(const String& hostname, bool& ignoreErrors) = 0; virtual void handleProxyAuthenticationRequiredRequest(const String& hostname, uint16_t port, const String& prefilledUsername, String& username, String& password) = 0; virtual void handleWillSetInputMethodState() = 0; #endif // PLATFORM(QT). -#if PLATFORM(QT) || PLATFORM(EFL) +#if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) virtual void updateTextInputState() = 0; -#endif // PLATFORM(QT) || PLATFORM(EFL) +#endif // PLATFORM(QT) || PLATFORM(EFL) || PLATOFRM(GTK) #if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) virtual void handleDownloadRequest(DownloadProxy*) = 0; @@ -159,15 +160,13 @@ public: virtual bool interpretKeyEvent(const NativeWebKeyboardEvent&, Vector<WebCore::KeypressCommand>&) = 0; virtual bool executeSavedCommandBySelector(const String& selector) = 0; virtual void setDragImage(const WebCore::IntPoint& clientPosition, PassRefPtr<ShareableBitmap> dragImage, bool isLinkDrag) = 0; - virtual void updateTextInputState(bool updateSecureInputState) = 0; - virtual void resetTextInputState() = 0; + virtual void updateSecureInputState() = 0; + virtual void resetSecureInputState() = 0; + virtual void notifyInputContextAboutDiscardedComposition() = 0; virtual void makeFirstResponder() = 0; virtual void setPromisedData(const String& pasteboardName, PassRefPtr<WebCore::SharedBuffer> imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleUrl, PassRefPtr<WebCore::SharedBuffer> archiveBuffer) = 0; #endif -#if PLATFORM(WIN) - virtual void compositionSelectionChanged(bool) = 0; -#endif #if PLATFORM(GTK) virtual void getEditorCommandsForKeyEvent(const NativeWebKeyboardEvent&, const AtomicString&, Vector<WTF::String>&) = 0; #endif @@ -188,13 +187,10 @@ public: virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*) = 0; #if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorChooserProxy> createColorChooserProxy(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&) = 0; + virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&) = 0; #endif virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate) = 0; -#if PLATFORM(WIN) - virtual void didInstallOrUninstallPageOverlay(bool) = 0; -#endif #if USE(ACCELERATED_COMPOSITING) virtual void enterAcceleratedCompositingMode(const LayerTreeContext&) = 0; @@ -202,12 +198,6 @@ public: virtual void updateAcceleratedCompositingMode(const LayerTreeContext&) = 0; #endif -#if PLATFORM(WIN) - virtual HWND nativeWindow() = 0; - virtual void setGestureReachedScrollingLimit(bool) = 0; - virtual void scheduleChildWindowGeometryUpdate(const WindowGeometry&) = 0; -#endif - #if PLATFORM(MAC) virtual void pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus) = 0; virtual void setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, PluginComplexTextInputState) = 0; @@ -230,23 +220,12 @@ public: virtual uint64_t addDictationAlternatives(const RetainPtr<NSTextAlternatives>&) = 0; virtual void removeDictationAlternatives(uint64_t dictationContext) = 0; virtual void showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext) = 0; - virtual void dismissDictationAlternativeUI() = 0; virtual Vector<String> dictationAlternatives(uint64_t dictationContext) = 0; #endif // USE(DICTATION_ALTERNATIVES) #endif // USE(APPKIT) #endif // PLATFORM(MAC) - virtual void didChangeScrollbarsForMainFrame() const = 0; - - // Custom representations. - virtual void didCommitLoadForMainFrame(bool useCustomRepresentation) = 0; - virtual void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&) = 0; - virtual double customRepresentationZoomFactor() = 0; - virtual void setCustomRepresentationZoomFactor(double) = 0; - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects) = 0; - virtual void findStringInCustomRepresentation(const String&, FindOptions, unsigned maxMatchCount) = 0; - virtual void countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned maxMatchCount) = 0; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/PageViewportController.cpp b/Source/WebKit2/UIProcess/PageViewportController.cpp index a34782c8f..6254cf75d 100644 --- a/Source/WebKit2/UIProcess/PageViewportController.cpp +++ b/Source/WebKit2/UIProcess/PageViewportController.cpp @@ -20,9 +20,9 @@ */ #include "config.h" -#include "PageViewportController.h" -#if USE(TILED_BACKING_STORE) +#if USE(ACCELERATED_COMPOSITING) +#include "PageViewportController.h" #include "PageViewportControllerClient.h" #include "WebPageProxy.h" @@ -47,8 +47,8 @@ PageViewportController::PageViewportController(WebKit::WebPageProxy* proxy, Page , m_initiallyFitToViewport(true) , m_hadUserInteraction(false) , m_pageScaleFactor(1) - , m_viewportPosIsLocked(false) - , m_pageScaleFactorIsLocked(false) + , m_pendingPositionChange(false) + , m_pendingScaleChange(false) { // Initializing Viewport Raw Attributes to avoid random negative or infinity scale factors // if there is a race condition between the first layout and setting the viewport attributes for the first time. @@ -81,17 +81,58 @@ float PageViewportController::outerBoundedViewportScale(float viewportScale) con return innerBoundedViewportScale(viewportScale); } -float PageViewportController::devicePixelRatio() const +float PageViewportController::deviceScaleFactor() const { return m_webPageProxy->deviceScaleFactor(); } -FloatPoint PageViewportController::clampViewportToContents(const WebCore::FloatPoint& viewportPos, float viewportScale) +static inline bool isIntegral(float value) +{ + return static_cast<int>(value) == value; +} + +FloatPoint PageViewportController::pixelAlignedFloatPoint(const FloatPoint& framePosition) { - const float horizontalRange = std::max(0.f, m_contentsSize.width() - m_viewportSize.width() / viewportScale); - const float verticalRange = std::max(0.f, m_contentsSize.height() - m_viewportSize.height() / viewportScale); +#if PLATFORM(EFL) + float effectiveScale = m_pageScaleFactor * deviceScaleFactor(); + if (!isIntegral(effectiveScale)) { + // To avoid blurryness, modify the position so that it maps into a discrete device position. + FloatPoint scaledPos(framePosition); - return FloatPoint(clampTo(viewportPos.x(), 0.f, horizontalRange), clampTo(viewportPos.y(), 0.f, verticalRange)); + // Scale by the effective scale factor to compute the screen-relative position. + scaledPos.scale(effectiveScale, effectiveScale); + + // Round to integer boundaries. + FloatPoint alignedPos = roundedIntPoint(scaledPos); + + // Convert back to CSS coordinates. + alignedPos.scale(1 / effectiveScale, 1 / effectiveScale); + + return alignedPos; + } +#endif + + return framePosition; +} + +FloatPoint PageViewportController::boundContentsPositionAtScale(const WebCore::FloatPoint& framePosition, float scale) +{ + // We need to floor the viewport here as to allow aligning the content in device units. If not, + // it might not be possible to scroll the last pixel and that affects fixed position elements. + FloatRect bounds; + bounds.setWidth(std::max(0.f, m_contentsSize.width() - floorf(m_viewportSize.width() / scale))); + bounds.setHeight(std::max(0.f, m_contentsSize.height() - floorf(m_viewportSize.height() / scale))); + + FloatPoint position; + position.setX(clampTo(framePosition.x(), bounds.x(), bounds.width())); + position.setY(clampTo(framePosition.y(), bounds.y(), bounds.height())); + + return position; +} + +FloatPoint PageViewportController::boundContentsPosition(const WebCore::FloatPoint& framePosition) +{ + return boundContentsPositionAtScale(framePosition, m_pageScaleFactor); } void PageViewportController::didCommitLoad() @@ -144,17 +185,25 @@ void PageViewportController::didRenderFrame(const IntSize& contentsSize, const I // All position and scale changes resulting from a web process event should // go through here to be applied on the viewport to avoid showing incomplete // tiles to the user during a few milliseconds. - if (m_pageScaleFactorIsLocked) { - m_client->setContentsScale(m_pageScaleFactor, false); - m_pageScaleFactorIsLocked = false; + + if (m_pendingScaleChange) { + m_pendingScaleChange = false; + m_client->setPageScaleFactor(m_pageScaleFactor); + + // The scale changed, we have to re-pixel align. + m_pendingPositionChange = true; + FloatPoint currentDiscretePos = roundedIntPoint(m_contentsPosition); + FloatPoint pixelAlignedPos = pixelAlignedFloatPoint(currentDiscretePos); + m_contentsPosition = boundContentsPosition(pixelAlignedPos); + + m_webPageProxy->scalePage(m_pageScaleFactor, roundedIntPoint(m_contentsPosition)); } - if (m_viewportPosIsLocked) { - FloatPoint clampedPos = clampViewportToContents(m_viewportPos, m_pageScaleFactor); - // There might be rendered frames not covering our requested position yet, wait for it. - if (FloatRect(clampedPos, viewportSizeInContentsCoordinates()).intersects(coveredRect)) { - m_client->setViewportPosition(clampedPos); - m_viewportPosIsLocked = false; - } + + // There might be rendered frames not covering our requested position yet, wait for it. + FloatRect endVisibleContentRect(m_contentsPosition, visibleContentsSize()); + if (m_pendingPositionChange && endVisibleContentRect.intersects(coveredRect)) { + m_client->setViewportPosition(m_contentsPosition); + m_pendingPositionChange = false; } } @@ -179,12 +228,17 @@ void PageViewportController::pageDidRequestScroll(const IntPoint& cssPosition) if (m_webPageProxy->areActiveDOMObjectsAndAnimationsSuspended()) return; - FloatRect endVisibleContentRect(clampViewportToContents(cssPosition, m_pageScaleFactor), viewportSizeInContentsCoordinates()); + FloatPoint boundPosition = boundContentsPosition(FloatPoint(cssPosition)); + FloatPoint alignedPosition = pixelAlignedFloatPoint(boundPosition); + FloatRect endVisibleContentRect(alignedPosition, visibleContentsSize()); + if (m_lastFrameCoveredRect.intersects(endVisibleContentRect)) - m_client->setViewportPosition(endVisibleContentRect.location()); - else - // Keep the unclamped position in case the contents size is changed later on. - applyPositionAfterRenderingContents(cssPosition); + m_client->setViewportPosition(alignedPosition); + else { + // Keep the unbound position in case the contents size is changed later on. + FloatPoint position = pixelAlignedFloatPoint(FloatPoint(cssPosition)); + applyPositionAfterRenderingContents(position); + } } void PageViewportController::didChangeViewportSize(const FloatSize& newSize) @@ -196,15 +250,15 @@ void PageViewportController::didChangeViewportSize(const FloatSize& newSize) // Let the WebProcess know about the new viewport size, so that // it can resize the content accordingly. - m_webPageProxy->setViewportSize(roundedIntSize(newSize)); + m_webPageProxy->drawingArea()->setSize(roundedIntSize(newSize), IntSize(), IntSize()); } -void PageViewportController::didChangeContentsVisibility(const FloatPoint& viewportPos, float viewportScale, const FloatPoint& trajectoryVector) +void PageViewportController::didChangeContentsVisibility(const FloatPoint& position, float scale, const FloatPoint& trajectoryVector) { - if (!m_viewportPosIsLocked) - m_viewportPos = viewportPos; - if (!m_pageScaleFactorIsLocked) - m_pageScaleFactor = viewportScale; + if (!m_pendingPositionChange) + m_contentsPosition = position; + if (!m_pendingScaleChange) + applyScaleAfterRenderingContents(scale); syncVisibleContents(trajectoryVector); } @@ -215,9 +269,9 @@ void PageViewportController::syncVisibleContents(const FloatPoint& trajectoryVec if (!drawingArea || m_viewportSize.isEmpty() || m_contentsSize.isEmpty()) return; - FloatRect visibleContentsRect(clampViewportToContents(m_viewportPos, m_pageScaleFactor), viewportSizeInContentsCoordinates()); + FloatRect visibleContentsRect(boundContentsPosition(m_contentsPosition), visibleContentsSize()); visibleContentsRect.intersect(FloatRect(FloatPoint::zero(), m_contentsSize)); - drawingArea->setVisibleContentsRect(visibleContentsRect, m_pageScaleFactor, trajectoryVector); + drawingArea->setVisibleContentsRect(visibleContentsRect, trajectoryVector); m_client->didChangeVisibleContents(); } @@ -234,28 +288,39 @@ void PageViewportController::didChangeViewportAttributes(const WebCore::Viewport if (!m_initiallyFitToViewport) WebCore::restrictScaleFactorToInitialScaleIfNotUserScalable(m_rawAttributes); - if (updateMinimumScaleToFit(true)) - m_client->didChangeViewportAttributes(); + updateMinimumScaleToFit(true); - syncVisibleContents(); + // As the viewport attributes are calculated when loading pages, after load, or after + // viewport resize, it is important that we inform the client of the new scale and + // position, so that the content can be positioned correctly and pixel aligned. + m_pendingPositionChange = true; + m_pendingScaleChange = true; + + m_client->didChangeViewportAttributes(); } -WebCore::FloatSize PageViewportController::viewportSizeInContentsCoordinates() const +FloatSize PageViewportController::visibleContentsSize() const { - return WebCore::FloatSize(m_viewportSize.width() / m_pageScaleFactor, m_viewportSize.height() / m_pageScaleFactor); + return FloatSize(m_viewportSize.width() / m_pageScaleFactor, m_viewportSize.height() / m_pageScaleFactor); } void PageViewportController::applyScaleAfterRenderingContents(float scale) { + if (m_pageScaleFactor == scale) + return; + m_pageScaleFactor = scale; - m_pageScaleFactorIsLocked = true; + m_pendingScaleChange = true; syncVisibleContents(); } void PageViewportController::applyPositionAfterRenderingContents(const FloatPoint& pos) { - m_viewportPos = pos; - m_viewportPosIsLocked = true; + if (m_contentsPosition == pos) + return; + + m_contentsPosition = pos; + m_pendingPositionChange = true; syncVisibleContents(); } @@ -264,14 +329,14 @@ bool PageViewportController::updateMinimumScaleToFit(bool userInitiatedUpdate) if (m_viewportSize.isEmpty() || m_contentsSize.isEmpty()) return false; - bool currentlyScaledToFit = fuzzyCompare(m_pageScaleFactor, m_minimumScaleToFit, 0.001); + bool currentlyScaledToFit = fuzzyCompare(m_pageScaleFactor, m_minimumScaleToFit, 0.0001); - float minimumScale = WebCore::computeMinimumScaleFactorForContentContained(m_rawAttributes, WebCore::roundedIntSize(m_viewportSize), WebCore::roundedIntSize(m_contentsSize), 1); + float minimumScale = WebCore::computeMinimumScaleFactorForContentContained(m_rawAttributes, WebCore::roundedIntSize(m_viewportSize), WebCore::roundedIntSize(m_contentsSize)); if (minimumScale <= 0) return false; - if (!fuzzyCompare(minimumScale, m_minimumScaleToFit, 0.001)) { + if (!fuzzyCompare(minimumScale, m_minimumScaleToFit, 0.0001)) { m_minimumScaleToFit = minimumScale; if (!m_webPageProxy->areActiveDOMObjectsAndAnimationsSuspended()) { @@ -280,7 +345,7 @@ bool PageViewportController::updateMinimumScaleToFit(bool userInitiatedUpdate) else { // Ensure the effective scale stays within bounds. float boundedScale = innerBoundedViewportScale(m_pageScaleFactor); - if (!fuzzyCompare(boundedScale, m_pageScaleFactor, 0.001)) + if (!fuzzyCompare(boundedScale, m_pageScaleFactor, 0.0001)) applyScaleAfterRenderingContents(boundedScale); } } diff --git a/Source/WebKit2/UIProcess/PageViewportController.h b/Source/WebKit2/UIProcess/PageViewportController.h index fcc4e170d..b8973abbd 100644 --- a/Source/WebKit2/UIProcess/PageViewportController.h +++ b/Source/WebKit2/UIProcess/PageViewportController.h @@ -22,6 +22,8 @@ #ifndef PageViewportController_h #define PageViewportController_h +#if USE(ACCELERATED_COMPOSITING) + #include <WebCore/FloatPoint.h> #include <WebCore/FloatRect.h> #include <WebCore/FloatSize.h> @@ -47,22 +49,28 @@ public: float innerBoundedViewportScale(float) const; float outerBoundedViewportScale(float) const; - WebCore::FloatPoint clampViewportToContents(const WebCore::FloatPoint& viewportPos, float viewportScale); + + WebCore::FloatPoint pixelAlignedFloatPoint(const WebCore::FloatPoint&); + + WebCore::FloatPoint boundContentsPosition(const WebCore::FloatPoint&); + WebCore::FloatPoint boundContentsPositionAtScale(const WebCore::FloatPoint&, float scale); + + WebCore::FloatSize visibleContentsSize() const; bool hadUserInteraction() const { return m_hadUserInteraction; } bool allowsUserScaling() const { return m_allowsUserScaling; } WebCore::FloatSize contentsLayoutSize() const { return m_rawAttributes.layoutSize; } - float devicePixelRatio() const; - float minimumContentsScale() const { return m_minimumScaleToFit; } - float maximumContentsScale() const { return m_rawAttributes.maximumScale; } - float currentContentsScale() const { return m_pageScaleFactor; } + float deviceScaleFactor() const; + float minimumScale() const { return m_minimumScaleToFit; } + float maximumScale() const { return m_rawAttributes.maximumScale; } + float currentScale() const { return m_pageScaleFactor; } void setHadUserInteraction(bool didUserInteract) { m_hadUserInteraction = didUserInteract; } // Notifications from the viewport. void didChangeViewportSize(const WebCore::FloatSize& newSize); - void didChangeContentsVisibility(const WebCore::FloatPoint& viewportPos, float viewportScale, const WebCore::FloatPoint& trajectoryVector = WebCore::FloatPoint::zero()); + void didChangeContentsVisibility(const WebCore::FloatPoint&, float scale, const WebCore::FloatPoint& trajectoryVector = WebCore::FloatPoint::zero()); // Notifications from the WebProcess. void didCommitLoad(); @@ -77,7 +85,6 @@ private: void applyScaleAfterRenderingContents(float scale); void applyPositionAfterRenderingContents(const WebCore::FloatPoint& pos); bool updateMinimumScaleToFit(bool userInitiatedUpdate); - WebCore::FloatSize viewportSizeInContentsCoordinates() const; WebPageProxy* const m_webPageProxy; PageViewportControllerClient* m_client; @@ -90,14 +97,14 @@ private: bool m_hadUserInteraction; - WebCore::FloatPoint m_viewportPos; - WebCore::FloatSize m_viewportSize; + WebCore::FloatPoint m_contentsPosition; WebCore::FloatSize m_contentsSize; + WebCore::FloatSize m_viewportSize; WebCore::IntSize m_clientContentsSize; float m_pageScaleFactor; - bool m_viewportPosIsLocked; - bool m_pageScaleFactorIsLocked; + bool m_pendingPositionChange; + bool m_pendingScaleChange; WebCore::FloatRect m_lastFrameCoveredRect; }; @@ -105,4 +112,5 @@ bool fuzzyCompare(float, float, float epsilon); } // namespace WebKit +#endif // USE(ACCELERATED_COMPOSITING) #endif // PageViewportController_h diff --git a/Source/WebKit2/UIProcess/PageViewportControllerClient.h b/Source/WebKit2/UIProcess/PageViewportControllerClient.h index 7b05ea854..15d9a5e5d 100644 --- a/Source/WebKit2/UIProcess/PageViewportControllerClient.h +++ b/Source/WebKit2/UIProcess/PageViewportControllerClient.h @@ -39,9 +39,8 @@ public: virtual ~PageViewportControllerClient() { } virtual void setViewportPosition(const WebCore::FloatPoint& contentsPoint) = 0; - virtual void setContentsScale(float, bool treatAsInitialValue) = 0; + virtual void setPageScaleFactor(float) = 0; - virtual void didResumeContent() = 0; virtual void didChangeContentsSize(const WebCore::IntSize&) = 0; virtual void didChangeVisibleContents() = 0; virtual void didChangeViewportAttributes() = 0; diff --git a/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp new file mode 100644 index 000000000..fd0e1d9ee --- /dev/null +++ b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2012, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlugInAutoStartProvider.h" + +#include "ImmutableArray.h" +#include "ImmutableDictionary.h" +#include "WebContext.h" +#include "WebContextClient.h" +#include "WebProcessMessages.h" +#include <wtf/CurrentTime.h> + +using namespace WebCore; + +static const double plugInAutoStartExpirationTimeThreshold = 30 * 24 * 60 * 60; + +namespace WebKit { + +PlugInAutoStartProvider::PlugInAutoStartProvider(WebContext* context) + : m_context(context) +{ +} + +static double expirationTimeFromNow() +{ + return currentTime() + plugInAutoStartExpirationTimeThreshold; +} + +void PlugInAutoStartProvider::addAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash) +{ + if (m_hashToOriginMap.contains(plugInOriginHash)) + return; + + AutoStartTable::iterator it = m_autoStartTable.find(pageOrigin); + if (it == m_autoStartTable.end()) + it = m_autoStartTable.add(pageOrigin, PlugInAutoStartOriginHash()).iterator; + + double expirationTime = expirationTimeFromNow(); + it->value.set(plugInOriginHash, expirationTime); + m_hashToOriginMap.set(plugInOriginHash, pageOrigin); + + m_context->sendToAllProcesses(Messages::WebProcess::DidAddPlugInAutoStartOriginHash(plugInOriginHash, expirationTime)); + m_context->client().plugInAutoStartOriginHashesChanged(m_context); +} + +PlugInAutoStartOriginHash PlugInAutoStartProvider::autoStartOriginHashesCopy() const +{ + PlugInAutoStartOriginHash copyMap; + AutoStartTable::const_iterator end = m_autoStartTable.end(); + for (AutoStartTable::const_iterator it = m_autoStartTable.begin(); it != end; ++it) { + PlugInAutoStartOriginHash::const_iterator mapEnd = it->value.end(); + for (PlugInAutoStartOriginHash::const_iterator mapIt = it->value.begin(); mapIt != mapEnd; ++mapIt) + copyMap.set(mapIt->key, mapIt->value); + } + return copyMap; +} + +PassRefPtr<ImmutableDictionary> PlugInAutoStartProvider::autoStartOriginsTableCopy() const +{ + ImmutableDictionary::MapType map; + AutoStartTable::const_iterator end = m_autoStartTable.end(); + double now = currentTime(); + for (AutoStartTable::const_iterator it = m_autoStartTable.begin(); it != end; ++it) { + ImmutableDictionary::MapType hashMap; + PlugInAutoStartOriginHash::const_iterator valueEnd = it->value.end(); + for (PlugInAutoStartOriginHash::const_iterator valueIt = it->value.begin(); valueIt != valueEnd; ++valueIt) { + if (now > valueIt->value) + continue; + hashMap.set(String::number(valueIt->key), WebDouble::create(valueIt->value)); + } + + if (hashMap.size()) + map.set(it->key, ImmutableDictionary::adopt(hashMap)); + } + + return ImmutableDictionary::adopt(map); +} + +void PlugInAutoStartProvider::setAutoStartOriginsTable(ImmutableDictionary& table) +{ + m_hashToOriginMap.clear(); + m_autoStartTable.clear(); + HashMap<unsigned, double> hashMap; + + ImmutableDictionary::MapType::const_iterator end = table.map().end(); + for (ImmutableDictionary::MapType::const_iterator it = table.map().begin(); it != end; ++it) { + PlugInAutoStartOriginHash hashes; + ImmutableDictionary* hashesForPage = static_cast<ImmutableDictionary*>(it->value.get()); + ImmutableDictionary::MapType::const_iterator hashEnd = hashesForPage->map().end(); + for (ImmutableDictionary::MapType::const_iterator hashIt = hashesForPage->map().begin(); hashIt != hashEnd; ++hashIt) { + bool ok; + unsigned hash = hashIt->key.toUInt(&ok); + if (!ok) + continue; + + if (hashIt->value->type() != WebDouble::APIType) + continue; + + double expirationTime = static_cast<WebDouble*>(hashIt->value.get())->value(); + hashes.set(hash, expirationTime); + hashMap.set(hash, expirationTime); + m_hashToOriginMap.set(hash, it->key); + } + + m_autoStartTable.set(it->key, hashes); + } + + m_context->sendToAllProcesses(Messages::WebProcess::ResetPlugInAutoStartOriginHashes(hashMap)); +} + +void PlugInAutoStartProvider::setAutoStartOriginsArray(ImmutableArray& originList) +{ + m_autoStartOrigins.clear(); + for (size_t i = 0, length = originList.size(); i < length; ++i) { + if (originList.at(i)->type() != WebString::APIType) + continue; + m_autoStartOrigins.append(static_cast<WebString*>(originList.at(i))->string()); + } +} + +void PlugInAutoStartProvider::didReceiveUserInteraction(unsigned plugInOriginHash) +{ + HashMap<unsigned, String>::const_iterator it = m_hashToOriginMap.find(plugInOriginHash); + if (it == m_hashToOriginMap.end()) { + ASSERT_NOT_REACHED(); + return; + } + + double newExpirationTime = expirationTimeFromNow(); + m_autoStartTable.find(it->value)->value.set(plugInOriginHash, newExpirationTime); + m_context->sendToAllProcesses(Messages::WebProcess::DidAddPlugInAutoStartOriginHash(plugInOriginHash, newExpirationTime)); + m_context->client().plugInAutoStartOriginHashesChanged(m_context); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebIntentData.h b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.h index 9d59f90ce..87c81fe3a 100644 --- a/Source/WebKit2/UIProcess/WebIntentData.h +++ b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,55 +23,51 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebIntentData_h -#define WebIntentData_h +#ifndef PlugInAutoStartProvider_h +#define PlugInAutoStartProvider_h -#if ENABLE(WEB_INTENTS) - -#include "APIObject.h" -#include "IntentData.h" -#include <WebCore/KURL.h> -#include <wtf/PassRefPtr.h> +#include <wtf/HashMap.h> +#include <wtf/HashSet.h> +#include <wtf/Noncopyable.h> +#include <wtf/Vector.h> +#include <wtf/text/StringHash.h> +#include <wtf/text/WTFString.h> namespace WebKit { class ImmutableArray; class ImmutableDictionary; -class WebProcessProxy; -class WebSerializedScriptValue; +class WebContext; -class WebIntentData : public APIObject { -public: - static const Type APIType = TypeIntentData; +typedef HashMap<unsigned, double> PlugInAutoStartOriginHash; +typedef Vector<String> PlugInAutoStartOrigins; - static PassRefPtr<WebIntentData> create(const IntentData& store, WebProcessProxy* process) - { - return adoptRef(new WebIntentData(store, process)); - } +class PlugInAutoStartProvider { + WTF_MAKE_NONCOPYABLE(PlugInAutoStartProvider); +public: + explicit PlugInAutoStartProvider(WebContext*); - virtual ~WebIntentData(); + void addAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash); + void didReceiveUserInteraction(unsigned plugInOriginHash); - const String& action() const { return m_store.action; } - const String& payloadType() const { return m_store.type; } - const WebCore::KURL& service() const { return m_store.service; } - PassRefPtr<WebSerializedScriptValue> data() const; - String extra(const String& key) const; - PassRefPtr<ImmutableDictionary> extras() const; - PassRefPtr<ImmutableArray> suggestions() const; + PassRefPtr<ImmutableDictionary> autoStartOriginsTableCopy() const; + void setAutoStartOriginsTable(ImmutableDictionary&); + void setAutoStartOriginsArray(ImmutableArray&); - const IntentData& store() const { return m_store; } + PlugInAutoStartOriginHash autoStartOriginHashesCopy() const; + const PlugInAutoStartOrigins& autoStartOrigins() const { return m_autoStartOrigins; } private: - WebIntentData(const IntentData&, WebProcessProxy*); + WebContext* m_context; - virtual Type type() const { return APIType; } + typedef HashMap<String, PlugInAutoStartOriginHash, CaseFoldingHash> AutoStartTable; + AutoStartTable m_autoStartTable; - IntentData m_store; - WebProcessProxy* m_process; + HashMap<unsigned, String> m_hashToOriginMap; + + PlugInAutoStartOrigins m_autoStartOrigins; }; } // namespace WebKit -#endif // ENABLE(WEB_INTENTS) - -#endif // WebIntentData_h +#endif /* PlugInAutoStartProvider_h */ diff --git a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp index 95f589b5f..ae95a0b68 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp @@ -35,13 +35,13 @@ #include <wtf/ListHashSet.h> #include <wtf/StdLibExtras.h> -using namespace std; using namespace WebCore; namespace WebKit { PluginInfoStore::PluginInfoStore() : m_pluginListIsUpToDate(false) + , m_client(0) { } @@ -71,16 +71,6 @@ typedef ListHashSet<String, 32, CaseFoldingHash> PathHashSet; typedef ListHashSet<String, 32> PathHashSet; #endif -static inline Vector<PluginModuleInfo> deepIsolatedCopyPluginInfoVector(const Vector<PluginModuleInfo>& vector) -{ - // Let the copy begin! - Vector<PluginModuleInfo> copy; - copy.reserveCapacity(vector.size()); - for (unsigned i = 0; i < vector.size(); ++i) - copy.append(vector[i].isolatedCopy()); - return copy; -} - void PluginInfoStore::loadPluginsIfNecessary() { if (m_pluginListIsUpToDate) @@ -100,15 +90,16 @@ void PluginInfoStore::loadPluginsIfNecessary() // Then load plug-ins that are not in the standard plug-ins directories. addFromVector(uniquePluginPaths, individualPluginPaths()); - Vector<PluginModuleInfo> plugins; + m_plugins.clear(); PathHashSet::const_iterator end = uniquePluginPaths.end(); for (PathHashSet::const_iterator it = uniquePluginPaths.begin(); it != end; ++it) - loadPlugin(plugins, *it); - - m_plugins = deepIsolatedCopyPluginInfoVector(plugins); + loadPlugin(m_plugins, *it); m_pluginListIsUpToDate = true; + + if (m_client) + m_client->pluginInfoStoreDidLoadPlugins(this); } void PluginInfoStore::loadPlugin(Vector<PluginModuleInfo>& plugins, const String& pluginPath) @@ -126,19 +117,19 @@ void PluginInfoStore::loadPlugin(Vector<PluginModuleInfo>& plugins, const String Vector<PluginModuleInfo> PluginInfoStore::plugins() { - MutexLocker locker(m_pluginsLock); loadPluginsIfNecessary(); - return deepIsolatedCopyPluginInfoVector(m_plugins); + return m_plugins; } -PluginModuleInfo PluginInfoStore::findPluginForMIMEType(const String& mimeType) const +PluginModuleInfo PluginInfoStore::findPluginForMIMEType(const String& mimeType, PluginData::AllowedPluginTypes allowedPluginTypes) const { - MutexLocker locker(m_pluginsLock); - ASSERT(!mimeType.isNull()); for (size_t i = 0; i < m_plugins.size(); ++i) { const PluginModuleInfo& plugin = m_plugins[i]; + + if (allowedPluginTypes == PluginData::OnlyApplicationPlugins && !plugin.info.isApplicationPlugin) + continue; for (size_t j = 0; j < plugin.info.mimes.size(); ++j) { const MimeClassInfo& mimeClassInfo = plugin.info.mimes[j]; @@ -150,21 +141,22 @@ PluginModuleInfo PluginInfoStore::findPluginForMIMEType(const String& mimeType) return PluginModuleInfo(); } -PluginModuleInfo PluginInfoStore::findPluginForExtension(const String& extension, String& mimeType) const +PluginModuleInfo PluginInfoStore::findPluginForExtension(const String& extension, String& mimeType, PluginData::AllowedPluginTypes allowedPluginTypes) const { - MutexLocker locker(m_pluginsLock); - ASSERT(!extension.isNull()); for (size_t i = 0; i < m_plugins.size(); ++i) { const PluginModuleInfo& plugin = m_plugins[i]; - + + if (allowedPluginTypes == PluginData::OnlyApplicationPlugins && !plugin.info.isApplicationPlugin) + continue; + for (size_t j = 0; j < plugin.info.mimes.size(); ++j) { const MimeClassInfo& mimeClassInfo = plugin.info.mimes[j]; - + const Vector<String>& extensions = mimeClassInfo.extensions; - if (find(extensions.begin(), extensions.end(), extension) != extensions.end()) { + if (std::find(extensions.begin(), extensions.end(), extension) != extensions.end()) { // We found a supported extension, set the correct MIME type. mimeType = mimeClassInfo.type; return plugin; @@ -189,32 +181,31 @@ static inline String pathExtension(const KURL& url) } #if !PLATFORM(MAC) -PluginModuleLoadPolicy PluginInfoStore::policyForPlugin(const PluginModuleInfo&) +PluginModuleLoadPolicy PluginInfoStore::defaultLoadPolicyForPlugin(const PluginModuleInfo&) { return PluginModuleLoadNormally; } -bool PluginInfoStore::reactivateInactivePlugin(const PluginModuleInfo&) -{ - return false; -} - String PluginInfoStore::getMIMETypeForExtension(const String& extension) { return MIMETypeRegistry::getMIMETypeForExtension(extension); } + +PluginModuleInfo PluginInfoStore::findPluginWithBundleIdentifier(const String&) +{ + ASSERT_NOT_REACHED(); + return PluginModuleInfo(); +} + #endif -PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url) +PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url, PluginData::AllowedPluginTypes allowedPluginTypes) { - { - MutexLocker locker(m_pluginsLock); - loadPluginsIfNecessary(); - } + loadPluginsIfNecessary(); // First, check if we can get the plug-in based on its MIME type. if (!mimeType.isNull()) { - PluginModuleInfo plugin = findPluginForMIMEType(mimeType); + PluginModuleInfo plugin = findPluginForMIMEType(mimeType, allowedPluginTypes); if (!plugin.path.isNull()) return plugin; } @@ -222,14 +213,14 @@ PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url) // Next, check if any plug-ins claim to support the URL extension. String extension = pathExtension(url).lower(); if (!extension.isNull() && mimeType.isEmpty()) { - PluginModuleInfo plugin = findPluginForExtension(extension, mimeType); + PluginModuleInfo plugin = findPluginForExtension(extension, mimeType, allowedPluginTypes); if (!plugin.path.isNull()) return plugin; // Finally, try to get the MIME type from the extension in a platform specific manner and use that. String extensionMimeType = getMIMETypeForExtension(extension); if (!extensionMimeType.isNull()) { - PluginModuleInfo plugin = findPluginForMIMEType(extensionMimeType); + PluginModuleInfo plugin = findPluginForMIMEType(extensionMimeType, allowedPluginTypes); if (!plugin.path.isNull()) { mimeType = extensionMimeType; return plugin; @@ -242,8 +233,6 @@ PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url) PluginModuleInfo PluginInfoStore::infoForPluginWithPath(const String& pluginPath) const { - MutexLocker locker(m_pluginsLock); - for (size_t i = 0; i < m_plugins.size(); ++i) { if (m_plugins[i].path == pluginPath) return m_plugins[i]; diff --git a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h index 9a6bd9f5c..c49cea7b9 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h +++ b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h @@ -29,7 +29,8 @@ #if ENABLE(NETSCAPE_PLUGIN_API) #include "PluginModuleInfo.h" -#include <wtf/ThreadingPrimitives.h> + +#include <WebCore/PluginData.h> namespace WebCore { class KURL; @@ -37,6 +38,17 @@ namespace WebCore { namespace WebKit { +class PluginInfoStore; + +class PluginInfoStoreClient { + WTF_MAKE_NONCOPYABLE(PluginInfoStoreClient); +public: + virtual ~PluginInfoStoreClient() { } + virtual void pluginInfoStoreDidLoadPlugins(PluginInfoStore*) = 0; +protected: + PluginInfoStoreClient() { } +}; + class PluginInfoStore { WTF_MAKE_NONCOPYABLE(PluginInfoStore); @@ -51,17 +63,22 @@ public: // Returns the info for a plug-in that can handle the given MIME type. // If the MIME type is null, the file extension of the given url will be used to infer the // plug-in type. In that case, mimeType will be filled in with the right MIME type. - PluginModuleInfo findPlugin(String& mimeType, const WebCore::KURL&); - + PluginModuleInfo findPlugin(String& mimeType, const WebCore::KURL&, WebCore::PluginData::AllowedPluginTypes = WebCore::PluginData::AllPlugins); + + // Returns the info for the plug-in with the given bundle identifier. + PluginModuleInfo findPluginWithBundleIdentifier(const String& bundleIdentifier); + // Returns the info for the plug-in with the given path. PluginModuleInfo infoForPluginWithPath(const String& pluginPath) const; - static PluginModuleLoadPolicy policyForPlugin(const PluginModuleInfo&); - static bool reactivateInactivePlugin(const PluginModuleInfo&); + static PluginModuleLoadPolicy defaultLoadPolicyForPlugin(const PluginModuleInfo&); + + void setClient(PluginInfoStoreClient* client) { m_client = client; } + PluginInfoStoreClient* client() const { return m_client; } private: - PluginModuleInfo findPluginForMIMEType(const String& mimeType) const; - PluginModuleInfo findPluginForExtension(const String& extension, String& mimeType) const; + PluginModuleInfo findPluginForMIMEType(const String& mimeType, WebCore::PluginData::AllowedPluginTypes) const; + PluginModuleInfo findPluginForExtension(const String& extension, String& mimeType, WebCore::PluginData::AllowedPluginTypes) const; void loadPluginsIfNecessary(); static void loadPlugin(Vector<PluginModuleInfo>& plugins, const String& pluginPath); @@ -89,8 +106,7 @@ private: Vector<String> m_additionalPluginsDirectories; Vector<PluginModuleInfo> m_plugins; bool m_pluginListIsUpToDate; - - mutable Mutex m_pluginsLock; + PluginInfoStoreClient* m_client; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp index 834c87fc4..2279aaecd 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp @@ -30,6 +30,7 @@ #include "PluginProcessProxy.h" #include "WebContext.h" +#include <wtf/CryptographicallyRandomNumber.h> #include <wtf/StdLibExtras.h> #include <wtf/text/WTFString.h> @@ -45,12 +46,42 @@ PluginProcessManager::PluginProcessManager() { } -void PluginProcessManager::getPluginProcessConnection(const PluginInfoStore& pluginInfoStore, const String& pluginPath, PluginProcess::Type processType, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) +uint64_t PluginProcessManager::pluginProcessToken(const PluginModuleInfo& pluginModuleInfo, PluginProcessType pluginProcessType, PluginProcessSandboxPolicy pluginProcessSandboxPolicy) { - ASSERT(!pluginPath.isNull()); + // See if we know this token already. + for (size_t i = 0; i < m_pluginProcessTokens.size(); ++i) { + const PluginProcessAttributes& attributes = m_pluginProcessTokens[i].first; + + if (attributes.moduleInfo.path == pluginModuleInfo.path + && attributes.processType == pluginProcessType + && attributes.sandboxPolicy == pluginProcessSandboxPolicy) + return m_pluginProcessTokens[i].second; + } + + uint64_t token; + while (true) { + cryptographicallyRandomValues(&token, sizeof(token)); + + if (m_knownTokens.isValidValue(token) && !m_knownTokens.contains(token)) + break; + } + + PluginProcessAttributes attributes; + attributes.moduleInfo = pluginModuleInfo; + attributes.processType = pluginProcessType; + attributes.sandboxPolicy = pluginProcessSandboxPolicy; + + m_pluginProcessTokens.append(std::make_pair(std::move(attributes), token)); + m_knownTokens.add(token); + + return token; +} - PluginModuleInfo plugin = pluginInfoStore.infoForPluginWithPath(pluginPath); - PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(plugin, processType); +void PluginProcessManager::getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) +{ + ASSERT(pluginProcessToken); + + PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(pluginProcessToken); pluginProcess->getPluginProcessConnection(reply); } @@ -64,38 +95,35 @@ void PluginProcessManager::removePluginProcessProxy(PluginProcessProxy* pluginPr void PluginProcessManager::getSitesWithData(const PluginModuleInfo& plugin, WebPluginSiteDataManager* webPluginSiteDataManager, uint64_t callbackID) { - PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(plugin, PluginProcess::TypeRegularProcess); + PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(pluginProcessToken(plugin, PluginProcessTypeNormal, PluginProcessSandboxPolicyNormal)); pluginProcess->getSitesWithData(webPluginSiteDataManager, callbackID); } void PluginProcessManager::clearSiteData(const PluginModuleInfo& plugin, WebPluginSiteDataManager* webPluginSiteDataManager, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID) { - PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(plugin, PluginProcess::TypeRegularProcess); + PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(pluginProcessToken(plugin, PluginProcessTypeNormal, PluginProcessSandboxPolicyNormal)); pluginProcess->clearSiteData(webPluginSiteDataManager, sites, flags, maxAgeInSeconds, callbackID); } -PluginProcessProxy* PluginProcessManager::pluginProcessWithPath(const String& pluginPath, PluginProcess::Type processType) +PluginProcessProxy* PluginProcessManager::getOrCreatePluginProcess(uint64_t pluginProcessToken) { for (size_t i = 0; i < m_pluginProcesses.size(); ++i) { - RefPtr<PluginProcessProxy>& pluginProcessProxy = m_pluginProcesses[i]; - if (pluginProcessProxy->pluginInfo().path == pluginPath && pluginProcessProxy->processType() == processType) - return pluginProcessProxy.get(); + if (m_pluginProcesses[i]->pluginProcessToken() == pluginProcessToken) + return m_pluginProcesses[i].get(); } - return 0; -} + for (size_t i = 0; i < m_pluginProcessTokens.size(); ++i) { + auto& attributesAndToken = m_pluginProcessTokens[i]; + if (attributesAndToken.second == pluginProcessToken) { + RefPtr<PluginProcessProxy> pluginProcess = PluginProcessProxy::create(this, attributesAndToken.first, attributesAndToken.second); + PluginProcessProxy* pluginProcessPtr = pluginProcess.get(); -PluginProcessProxy* PluginProcessManager::getOrCreatePluginProcess(const PluginModuleInfo& plugin, PluginProcess::Type processType) -{ - if (PluginProcessProxy* pluginProcess = pluginProcessWithPath(plugin.path, processType)) - return pluginProcess; - - RefPtr<PluginProcessProxy> pluginProcess = PluginProcessProxy::create(this, plugin, processType); - PluginProcessProxy* pluginProcessPtr = pluginProcess.get(); - - m_pluginProcesses.append(pluginProcess.release()); + m_pluginProcesses.append(pluginProcess.release()); + return pluginProcessPtr; + } + } - return pluginProcessPtr; + return nullptr; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h index f84521a49..307c39810 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h @@ -30,8 +30,10 @@ #include "PluginModuleInfo.h" #include "PluginProcess.h" +#include "PluginProcessAttributes.h" #include "WebProcessProxyMessages.h" #include <wtf/Forward.h> +#include <wtf/HashSet.h> #include <wtf/Noncopyable.h> #include <wtf/Vector.h> @@ -51,23 +53,27 @@ class PluginProcessManager { public: static PluginProcessManager& shared(); - void getPluginProcessConnection(const PluginInfoStore&, const String& pluginPath, PluginProcess::Type, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); + uint64_t pluginProcessToken(const PluginModuleInfo&, PluginProcessType, PluginProcessSandboxPolicy); + + void getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); void removePluginProcessProxy(PluginProcessProxy*); void getSitesWithData(const PluginModuleInfo&, WebPluginSiteDataManager*, uint64_t callbackID); void clearSiteData(const PluginModuleInfo&, WebPluginSiteDataManager*, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID); #if PLATFORM(MAC) - void setApplicationIsOccluded(bool); + void setProcessSuppressionEnabled(bool); #endif private: PluginProcessManager(); - PluginProcessProxy* getOrCreatePluginProcess(const PluginModuleInfo&, PluginProcess::Type); - PluginProcessProxy* pluginProcessWithPath(const String& pluginPath, PluginProcess::Type); + PluginProcessProxy* getOrCreatePluginProcess(uint64_t pluginProcessToken); + + Vector<std::pair<PluginProcessAttributes, uint64_t>> m_pluginProcessTokens; + HashSet<uint64_t> m_knownTokens; - Vector<RefPtr<PluginProcessProxy> > m_pluginProcesses; + Vector<RefPtr<PluginProcessProxy>> m_pluginProcesses; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp index 5a49f9598..107ad1633 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp @@ -28,13 +28,13 @@ #if ENABLE(PLUGIN_PROCESS) +#include "PluginProcessConnectionManagerMessages.h" #include "PluginProcessCreationParameters.h" #include "PluginProcessManager.h" #include "PluginProcessMessages.h" #include "WebContext.h" #include "WebCoreArgumentCoders.h" #include "WebPluginSiteDataManager.h" -#include "WebProcessMessages.h" #include "WebProcessProxy.h" #include <WebCore/NotImplemented.h> #include <WebCore/RunLoop.h> @@ -47,44 +47,48 @@ using namespace WebCore; namespace WebKit { -static const double minimumLifetime = 30 * 60; -static const double shutdownTimeout = 10 * 60; +static const double minimumLifetime = 2 * 60; +static const double snapshottingMinimumLifetime = 30; -PassRefPtr<PluginProcessProxy> PluginProcessProxy::create(PluginProcessManager* PluginProcessManager, const PluginModuleInfo& pluginInfo, PluginProcess::Type processType) +static const double shutdownTimeout = 1 * 60; +static const double snapshottingShutdownTimeout = 15; + +PassRefPtr<PluginProcessProxy> PluginProcessProxy::create(PluginProcessManager* PluginProcessManager, const PluginProcessAttributes& pluginProcessAttributes, uint64_t pluginProcessToken) { - return adoptRef(new PluginProcessProxy(PluginProcessManager, pluginInfo, processType)); + return adoptRef(new PluginProcessProxy(PluginProcessManager, pluginProcessAttributes, pluginProcessToken)); } -PluginProcessProxy::PluginProcessProxy(PluginProcessManager* PluginProcessManager, const PluginModuleInfo& pluginInfo, PluginProcess::Type processType) +PluginProcessProxy::PluginProcessProxy(PluginProcessManager* PluginProcessManager, const PluginProcessAttributes& pluginProcessAttributes, uint64_t pluginProcessToken) : m_pluginProcessManager(PluginProcessManager) - , m_pluginInfo(pluginInfo) + , m_pluginProcessAttributes(pluginProcessAttributes) + , m_pluginProcessToken(pluginProcessToken) , m_numPendingConnectionRequests(0) #if PLATFORM(MAC) , m_modalWindowIsShowing(false) , m_fullscreenWindowIsShowing(false) , m_preFullscreenAppPresentationOptions(0) #endif - , m_processType(processType) { - ProcessLauncher::LaunchOptions launchOptions; - launchOptions.processType = ProcessLauncher::PluginProcess; - - platformInitializeLaunchOptions(launchOptions, pluginInfo); - - m_processLauncher = ProcessLauncher::create(this, launchOptions); + connect(); } PluginProcessProxy::~PluginProcessProxy() { } +void PluginProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +{ + launchOptions.processType = ProcessLauncher::PluginProcess; + platformGetLaunchOptions(launchOptions, m_pluginProcessAttributes); +} + // Asks the plug-in process to create a new connection to a web process. The connection identifier will be // encoded in the given argument encoder and sent back to the connection of the given web process. void PluginProcessProxy::getPluginProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) { m_pendingConnectionReplies.append(reply); - if (m_processLauncher->isLaunching()) { + if (isLaunching()) { m_numPendingConnectionRequests++; return; } @@ -99,7 +103,7 @@ void PluginProcessProxy::getSitesWithData(WebPluginSiteDataManager* webPluginSit ASSERT(!m_pendingGetSitesReplies.contains(callbackID)); m_pendingGetSitesReplies.set(callbackID, webPluginSiteDataManager); - if (m_processLauncher->isLaunching()) { + if (isLaunching()) { m_pendingGetSitesRequests.append(callbackID); return; } @@ -113,7 +117,7 @@ void PluginProcessProxy::clearSiteData(WebPluginSiteDataManager* webPluginSiteDa ASSERT(!m_pendingClearSiteDataReplies.contains(callbackID)); m_pendingClearSiteDataReplies.set(callbackID, webPluginSiteDataManager); - if (m_processLauncher->isLaunching()) { + if (isLaunching()) { ClearSiteDataRequest request; request.sites = sites; request.flags = flags; @@ -127,11 +131,6 @@ void PluginProcessProxy::clearSiteData(WebPluginSiteDataManager* webPluginSiteDa m_connection->send(Messages::PluginProcess::ClearSiteData(sites, flags, maxAgeInSeconds, callbackID), 0); } -void PluginProcessProxy::terminate() -{ - m_processLauncher->terminateProcess(); -} - void PluginProcessProxy::pluginProcessCrashedOrFailedToLaunch() { // The plug-in process must have crashed or exited, send any pending sync replies we might have. @@ -157,11 +156,6 @@ void PluginProcessProxy::pluginProcessCrashedOrFailedToLaunch() m_pluginProcessManager->removePluginProcessProxy(this); } -void PluginProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceivePluginProcessProxyMessage(connection, messageID, decoder); -} - void PluginProcessProxy::didClose(CoreIPC::Connection*) { #if PLATFORM(MAC) @@ -174,7 +168,7 @@ void PluginProcessProxy::didClose(CoreIPC::Connection*) const Vector<WebContext*>& contexts = WebContext::allContexts(); for (size_t i = 0; i < contexts.size(); ++i) - contexts[i]->sendToAllProcesses(Messages::WebProcess::PluginProcessCrashed(m_pluginInfo.path, m_processType)); + contexts[i]->sendToAllProcesses(Messages::PluginProcessConnectionManager::PluginProcessCrashed(m_pluginProcessToken)); // This will cause us to be deleted. pluginProcessCrashedOrFailedToLaunch(); @@ -197,19 +191,20 @@ void PluginProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connectio #if PLATFORM(MAC) m_connection->setShouldCloseConnectionOnMachExceptions(); #elif PLATFORM(QT) - m_connection->setShouldCloseConnectionOnProcessTermination(m_processLauncher->processIdentifier()); + m_connection->setShouldCloseConnectionOnProcessTermination(processIdentifier()); #endif m_connection->open(); PluginProcessCreationParameters parameters; - - parameters.pluginPath = m_pluginInfo.path; - parameters.processType = m_processType; - - parameters.minimumLifetime = minimumLifetime; - parameters.terminationTimeout = shutdownTimeout; - + parameters.processType = m_pluginProcessAttributes.processType; + if (parameters.processType == PluginProcessTypeSnapshot) { + parameters.minimumLifetime = snapshottingMinimumLifetime; + parameters.terminationTimeout = snapshottingShutdownTimeout; + } else { + parameters.minimumLifetime = minimumLifetime; + parameters.terminationTimeout = shutdownTimeout; + } platformInitializePluginProcess(parameters); // Initialize the plug-in host process. @@ -232,8 +227,8 @@ void PluginProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connectio m_numPendingConnectionRequests = 0; #if PLATFORM(MAC) - if (WebContext::applicationIsOccluded()) - m_connection->send(Messages::PluginProcess::SetApplicationIsOccluded(true), 0); + if (WebContext::canEnableProcessSuppressionForGlobalChildProcesses()) + setProcessSuppressionEnabled(true); #endif } diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h index 194d7a373..1cb2268a9 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h @@ -28,9 +28,11 @@ #if ENABLE(PLUGIN_PROCESS) +#include "ChildProcessProxy.h" #include "Connection.h" #include "PluginModuleInfo.h" #include "PluginProcess.h" +#include "PluginProcessAttributes.h" #include "ProcessLauncher.h" #include "WebProcessProxyMessages.h" #include <wtf/Deque.h> @@ -61,14 +63,15 @@ struct RawPluginMetaData { }; #endif -class PluginProcessProxy : public RefCounted<PluginProcessProxy>, CoreIPC::Connection::Client, ProcessLauncher::Client { +class PluginProcessProxy : public ChildProcessProxy { public: - static PassRefPtr<PluginProcessProxy> create(PluginProcessManager*, const PluginModuleInfo&, PluginProcess::Type); + static PassRefPtr<PluginProcessProxy> create(PluginProcessManager*, const PluginProcessAttributes&, uint64_t pluginProcessToken); ~PluginProcessProxy(); - const PluginModuleInfo& pluginInfo() const { return m_pluginInfo; } + const PluginProcessAttributes& pluginProcessAttributes() const { return m_pluginProcessAttributes; } + uint64_t pluginProcessToken() const { return m_pluginProcessToken; } - // Asks the plug-in process to create a new connection to a web process. The connection identifier will be + // Asks the plug-in process to create a new connection to a web process. The connection identifier will be // encoded in the given argument encoder and sent back to the connection of the given web process. void getPluginProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); @@ -78,15 +81,10 @@ public: // Asks the plug-in process to clear the data for the given sites. void clearSiteData(WebPluginSiteDataManager*, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID); - // Terminates the plug-in process. - void terminate(); - bool isValid() const { return m_connection; } - PluginProcess::Type processType() const { return m_processType; } - #if PLATFORM(MAC) - void setApplicationIsOccluded(bool); + void setProcessSuppressionEnabled(bool); // Returns whether the plug-in needs the heap to be marked executable. static bool pluginNeedsExecutableHeap(const PluginModuleInfo&); @@ -100,12 +98,17 @@ public: #endif private: - PluginProcessProxy(PluginProcessManager*, const PluginModuleInfo&, PluginProcess::Type); + PluginProcessProxy(PluginProcessManager*, const PluginProcessAttributes&, uint64_t pluginProcessToken); + + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) OVERRIDE; + void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&, const PluginProcessAttributes&); void pluginProcessCrashedOrFailedToLaunch(); // CoreIPC::Connection::Client - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + virtual void didClose(CoreIPC::Connection*) OVERRIDE; virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) OVERRIDE; @@ -113,7 +116,6 @@ private: virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); // Message handlers - void didReceivePluginProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); void didCreateWebProcessConnection(const CoreIPC::Attachment&, bool supportsAsynchronousPluginInitialization); void didGetSitesWithData(const Vector<String>& sites, uint64_t callbackID); void didClearSiteData(uint64_t callbackID); @@ -132,27 +134,27 @@ private: void endModal(); void applicationDidBecomeActive(); + void openPluginPreferencePane(); + void launchProcess(const String& launchPath, const Vector<String>& arguments, bool& result); + void launchApplicationAtURL(const String& urlString, const Vector<String>& arguments, bool& result); + void openURL(const String& url, bool& result, int32_t& status, String& launchedURLString); #endif - static void platformInitializeLaunchOptions(ProcessLauncher::LaunchOptions&, const PluginModuleInfo& pluginInfo); void platformInitializePluginProcess(PluginProcessCreationParameters& parameters); // The plug-in host process manager. PluginProcessManager* m_pluginProcessManager; - - // Information about the plug-in. - PluginModuleInfo m_pluginInfo; + + PluginProcessAttributes m_pluginProcessAttributes; + uint64_t m_pluginProcessToken; // The connection to the plug-in host process. RefPtr<CoreIPC::Connection> m_connection; - // The process launcher for the plug-in host process. - RefPtr<ProcessLauncher> m_processLauncher; - - Deque<RefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> > m_pendingConnectionReplies; + Deque<RefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>> m_pendingConnectionReplies; Vector<uint64_t> m_pendingGetSitesRequests; - HashMap<uint64_t, RefPtr<WebPluginSiteDataManager> > m_pendingGetSitesReplies; + HashMap<uint64_t, RefPtr<WebPluginSiteDataManager>> m_pendingGetSitesReplies; struct ClearSiteDataRequest { Vector<String> sites; @@ -161,7 +163,7 @@ private: uint64_t callbackID; }; Vector<ClearSiteDataRequest> m_pendingClearSiteDataRequests; - HashMap<uint64_t, RefPtr<WebPluginSiteDataManager> > m_pendingClearSiteDataReplies; + HashMap<uint64_t, RefPtr<WebPluginSiteDataManager>> m_pendingClearSiteDataReplies; // If createPluginConnection is called while the process is still launching we'll keep count of it and send a bunch of requests // when the process finishes launching. @@ -174,8 +176,6 @@ private: bool m_fullscreenWindowIsShowing; unsigned m_preFullscreenAppPresentationOptions; #endif - - PluginProcess::Type m_processType; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in index 183cb0c68..aa3b106c5 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in @@ -31,6 +31,18 @@ messages -> PluginProcessProxy { #if PLATFORM(MAC) SetModalWindowIsShowing(bool modalWindowIsShowing) SetFullscreenWindowIsShowing(bool fullscreenWindowIsShowing) + + # Open the plug-ins preference pane (as specified in the plug-in's Info.plist file). + OpenPluginPreferencePane() + + # Returns true if the UI process launched the process. + LaunchProcess(WTF::String launchPath, Vector<WTF::String> arguments) -> (bool result) + + # Returns true if the UI process launched the application. + LaunchApplicationAtURL(WTF::String url, Vector<WTF::String> arguments) -> (bool result) + + # Returns true if the UI process did open the URL. + OpenURL(WTF::String urlString) -> (bool result, int32_t status, WTF::String launchedURLString) #endif } diff --git a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp b/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp index ff96ab96c..005591cc8 100644 --- a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp +++ b/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp @@ -139,9 +139,7 @@ void WebPluginSiteDataManager::invalidate() invalidateCallbackMap(m_arrayCallbacks); #if ENABLE(PLUGIN_PROCESS) - deleteAllValues(m_pendingGetSitesWithData); m_pendingGetSitesWithData.clear(); - deleteAllValues(m_pendingClearSiteData); m_pendingClearSiteData.clear(); #endif } @@ -162,7 +160,7 @@ void WebPluginSiteDataManager::getSitesWithData(PassRefPtr<ArrayCallback> prpCal ASSERT(!m_pendingGetSitesWithData.contains(callbackID)); GetSitesWithDataState* state = new GetSitesWithDataState(this, callbackID); - m_pendingGetSitesWithData.set(callbackID, state); + m_pendingGetSitesWithData.set(callbackID, adoptPtr(state)); state->getSitesWithDataForNextPlugin(); #else Vector<PluginModuleInfo> plugins = m_webContext->pluginInfoStore().plugins(); @@ -183,7 +181,7 @@ void WebPluginSiteDataManager::didGetSitesWithData(const Vector<String>& sites, return; } - Vector<RefPtr<APIObject> > sitesWK(sites.size()); + Vector<RefPtr<APIObject>> sitesWK(sites.size()); for (size_t i = 0; i < sites.size(); ++i) sitesWK[i] = WebString::create(sites[i]); @@ -222,7 +220,7 @@ void WebPluginSiteDataManager::clearSiteData(ImmutableArray* sites, uint64_t fla ASSERT(!m_pendingClearSiteData.contains(callbackID)); ClearSiteDataState* state = new ClearSiteDataState(this, sitesVector, flags, maxAgeInSeconds, callbackID); - m_pendingClearSiteData.set(callbackID, state); + m_pendingClearSiteData.set(callbackID, adoptPtr(state)); state->clearSiteDataForNextPlugin(); #else Vector<PluginModuleInfo> plugins = m_webContext->pluginInfoStore().plugins(); @@ -267,7 +265,7 @@ void WebPluginSiteDataManager::didGetSitesWithDataForSinglePlugin(const Vector<S void WebPluginSiteDataManager::didGetSitesWithDataForAllPlugins(const Vector<String>& sites, uint64_t callbackID) { - OwnPtr<GetSitesWithDataState> state = adoptPtr(m_pendingGetSitesWithData.take(callbackID)); + OwnPtr<GetSitesWithDataState> state = m_pendingGetSitesWithData.take(callbackID); ASSERT(state); didGetSitesWithData(sites, callbackID); @@ -283,7 +281,7 @@ void WebPluginSiteDataManager::didClearSiteDataForSinglePlugin(uint64_t callback void WebPluginSiteDataManager::didClearSiteDataForAllPlugins(uint64_t callbackID) { - OwnPtr<ClearSiteDataState> state = adoptPtr(m_pendingClearSiteData.take(callbackID)); + OwnPtr<ClearSiteDataState> state = m_pendingClearSiteData.take(callbackID); ASSERT(state); didClearSiteData(callbackID); diff --git a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h b/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h index 9b025cc38..1edeceef8 100644 --- a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h +++ b/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h @@ -41,10 +41,8 @@ class WebProcessProxy; typedef GenericCallback<WKArrayRef> ArrayCallback; -class WebPluginSiteDataManager : public APIObject { +class WebPluginSiteDataManager : public TypedAPIObject<APIObject::TypePluginSiteDataManager> { public: - static const Type APIType = TypePluginSiteDataManager; - static PassRefPtr<WebPluginSiteDataManager> create(WebContext*); virtual ~WebPluginSiteDataManager(); @@ -67,21 +65,19 @@ public: private: explicit WebPluginSiteDataManager(WebContext*); - virtual Type type() const { return APIType; } - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; - HashMap<uint64_t, RefPtr<VoidCallback> > m_voidCallbacks; + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; + HashMap<uint64_t, RefPtr<VoidCallback>> m_voidCallbacks; #if ENABLE(PLUGIN_PROCESS) void didGetSitesWithDataForAllPlugins(const Vector<String>& sites, uint64_t callbackID); void didClearSiteDataForAllPlugins(uint64_t callbackID); class GetSitesWithDataState; - HashMap<uint64_t, GetSitesWithDataState*> m_pendingGetSitesWithData; + HashMap<uint64_t, OwnPtr<GetSitesWithDataState>> m_pendingGetSitesWithData; class ClearSiteDataState; - HashMap<uint64_t, ClearSiteDataState*> m_pendingClearSiteData; + HashMap<uint64_t, OwnPtr<ClearSiteDataState>> m_pendingClearSiteData; #endif }; diff --git a/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm b/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm index 6ebde6476..61367c51b 100644 --- a/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm +++ b/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm @@ -61,7 +61,7 @@ Vector<String> PluginInfoStore::pluginPathsInDirectory(const String& directory) { Vector<String> pluginPaths; - RetainPtr<CFStringRef> directoryCFString(AdoptCF, safeCreateCFString(directory)); + RetainPtr<CFStringRef> directoryCFString = adoptCF(safeCreateCFString(directory)); NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:(NSString *)directoryCFString.get() error:nil]; for (NSString *filename in filenames) @@ -109,7 +109,7 @@ static bool checkForPreferredPlugin(Vector<PluginModuleInfo>& alreadyLoadedPlugi static bool shouldBlockPlugin(const PluginModuleInfo& plugin) { - return PluginInfoStore::policyForPlugin(plugin) == PluginModuleBlocked; + return PluginInfoStore::defaultLoadPolicyForPlugin(plugin) == PluginModuleBlocked; } bool PluginInfoStore::shouldUsePlugin(Vector<PluginModuleInfo>& alreadyLoadedPlugins, const PluginModuleInfo& plugin) @@ -132,49 +132,39 @@ bool PluginInfoStore::shouldUsePlugin(Vector<PluginModuleInfo>& alreadyLoadedPlu if (!checkForPreferredPlugin(alreadyLoadedPlugins, plugin, "com.apple.java.JavaAppletPlugin", oracleJavaAppletPluginBundleIdentifier)) return false; -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - if (plugin.bundleIdentifier == "com.apple.java.JavaAppletPlugin" && shouldBlockPlugin(plugin) && !WKIsJavaPlugInActive()) { - // If the Apple Java plug-in is blocked and there's no Java runtime installed, just pretend that the plug-in doesn't exist. - return false; - } -#endif - return true; } -PluginModuleLoadPolicy PluginInfoStore::policyForPlugin(const PluginModuleInfo& plugin) +PluginModuleLoadPolicy PluginInfoStore::defaultLoadPolicyForPlugin(const PluginModuleInfo& plugin) { if (WKShouldBlockPlugin(plugin.bundleIdentifier, plugin.versionString)) return PluginModuleBlocked; - if (plugin.bundleIdentifier == oracleJavaAppletPluginBundleIdentifier && !WKIsJavaPlugInActive()) - return PluginModuleInactive; - return PluginModuleLoadNormally; } -bool PluginInfoStore::reactivateInactivePlugin(const PluginModuleInfo& plugin) -{ -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - if (plugin.bundleIdentifier == oracleJavaAppletPluginBundleIdentifier) { - WKActivateJavaPlugIn(); - return true; - } -#endif - - return false; -} - String PluginInfoStore::getMIMETypeForExtension(const String& extension) { // FIXME: This should just call MIMETypeRegistry::getMIMETypeForExtension and be // strength reduced into the callsite once we can safely convert String // to CFStringRef off the main thread. - RetainPtr<CFStringRef> extensionCFString(AdoptCF, safeCreateCFString(extension)); + RetainPtr<CFStringRef> extensionCFString = adoptCF(safeCreateCFString(extension)); return WKGetMIMETypeForExtension((NSString *)extensionCFString.get()); } +PluginModuleInfo PluginInfoStore::findPluginWithBundleIdentifier(const String& bundleIdentifier) +{ + loadPluginsIfNecessary(); + + for (size_t i = 0; i < m_plugins.size(); ++i) { + if (m_plugins[i].bundleIdentifier == bundleIdentifier) + return m_plugins[i]; + } + + return PluginModuleInfo(); +} + } // namespace WebKit #endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm b/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm index 6a974dad7..771cf7801 100644 --- a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm +++ b/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm @@ -32,11 +32,11 @@ namespace WebKit { -void PluginProcessManager::setApplicationIsOccluded(bool applicationIsOccluded) +void PluginProcessManager::setProcessSuppressionEnabled(bool processSuppressionEnabled) { size_t processCount = m_pluginProcesses.size(); for (size_t i = 0; i < processCount; ++i) - m_pluginProcesses[i]->setApplicationIsOccluded(applicationIsOccluded); + m_pluginProcesses[i]->setProcessSuppressionEnabled(processSuppressionEnabled); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm b/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm index e92ef9e76..4ce88b3d2 100644 --- a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm +++ b/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm @@ -28,17 +28,20 @@ #if ENABLE(PLUGIN_PROCESS) +#import "DynamicLinkerEnvironmentExtractor.h" #import "EnvironmentVariables.h" #import "PluginProcessCreationParameters.h" #import "PluginProcessMessages.h" #import "WebKitSystemInterface.h" #import <WebCore/FileSystem.h> +#import <WebCore/KURL.h> +#import <WebCore/RuntimeApplicationChecks.h> +#import <crt_externs.h> +#import <mach-o/dyld.h> #import <spawn.h> #import <wtf/text/CString.h> -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 #import <QuartzCore/CARemoteLayerServer.h> -#endif @interface WKPlaceholderModalWindow : NSWindow @end @@ -54,8 +57,6 @@ @end -NSString * const WebKit2PlugInSandboxProfileDirectoryPathKey = @"WebKit2PlugInSandboxProfileDirectoryPath"; - using namespace WebCore; namespace WebKit { @@ -91,6 +92,9 @@ bool PluginProcessProxy::createPropertyListFile(const PluginModuleInfo& plugin) posix_spawnattr_setbinpref_np(&attr, 1, cpuTypes, &outCount); EnvironmentVariables environmentVariables; + + DynamicLinkerEnvironmentExtractor environmentExtractor([[NSBundle mainBundle] executablePath], _NSGetMachExecuteHeader()->cputype); + environmentExtractor.getExtractedEnvironmentVariables(environmentVariables); // To make engineering builds work, if the path is outside of /System set up // DYLD_FRAMEWORK_PATH to pick up other frameworks, but don't do it for the @@ -119,42 +123,54 @@ bool PluginProcessProxy::createPropertyListFile(const PluginModuleInfo& plugin) return true; } -void PluginProcessProxy::platformInitializeLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginModuleInfo& pluginInfo) +#if HAVE(XPC) +static bool shouldUseXPC() +{ + if (id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseXPCServiceForWebProcess"]) + return [value boolValue]; + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + // FIXME: Temporary workaround for <rdar://problem/13236883> + if (applicationIsSafari()) + return false; + + return true; +#else + return false; +#endif +} +#endif + +void PluginProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginProcessAttributes& pluginProcessAttributes) { - launchOptions.architecture = pluginInfo.pluginArchitecture; - launchOptions.executableHeap = PluginProcessProxy::pluginNeedsExecutableHeap(pluginInfo); + launchOptions.architecture = pluginProcessAttributes.moduleInfo.pluginArchitecture; + launchOptions.executableHeap = PluginProcessProxy::pluginNeedsExecutableHeap(pluginProcessAttributes.moduleInfo); + launchOptions.extraInitializationData.add("plugin-path", pluginProcessAttributes.moduleInfo.path); + + // FIXME: Don't allow this if the UI process is sandboxed. + if (pluginProcessAttributes.sandboxPolicy == PluginProcessSandboxPolicyUnsandboxed) + launchOptions.extraInitializationData.add("disable-sandbox", "1"); + #if HAVE(XPC) - launchOptions.useXPC = false; + launchOptions.useXPC = shouldUseXPC(); #endif } void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationParameters& parameters) { - // For know only Flash is known to behave with asynchronous plug-in initialization. - parameters.supportsAsynchronousPluginInitialization = m_pluginInfo.bundleIdentifier == "com.macromedia.Flash Player.plugin"; + // For now only Flash is known to behave with asynchronous plug-in initialization. + parameters.supportsAsynchronousPluginInitialization = m_pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.macromedia.Flash Player.plugin"; #if USE(ACCELERATED_COMPOSITING) && HAVE(HOSTED_CORE_ANIMATION) - parameters.parentProcessName = [[NSProcessInfo processInfo] processName]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 mach_port_t renderServerPort = [[CARemoteLayerServer sharedServer] serverPort]; -#else - mach_port_t renderServerPort = WKInitializeRenderServer(); -#endif - if (renderServerPort != MACH_PORT_NULL) parameters.acceleratedCompositingPort = CoreIPC::MachPort(renderServerPort, MACH_MSG_TYPE_COPY_SEND); #endif - - // FIXME: We should rip this out once we have a good place to install plug-in - // sandbox profiles. - NSString* sandboxProfileDirectoryPath = [[NSUserDefaults standardUserDefaults] stringForKey:WebKit2PlugInSandboxProfileDirectoryPathKey]; - if (sandboxProfileDirectoryPath) - parameters.sandboxProfileDirectoryPath = String(sandboxProfileDirectoryPath); } bool PluginProcessProxy::getPluginProcessSerialNumber(ProcessSerialNumber& pluginProcessSerialNumber) { - pid_t pluginProcessPID = m_processLauncher->processIdentifier(); + pid_t pluginProcessPID = processIdentifier(); #if COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -282,7 +298,7 @@ void PluginProcessProxy::beginModal() ASSERT(!m_placeholderWindow); ASSERT(!m_activationObserver); - m_placeholderWindow.adoptNS([[WKPlaceholderModalWindow alloc] initWithContentRect:NSMakeRect(0, 0, 1, 1) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]); + m_placeholderWindow = adoptNS([[WKPlaceholderModalWindow alloc] initWithContentRect:NSMakeRect(0, 0, 1, 1) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]); [m_placeholderWindow.get() setReleasedWhenClosed:NO]; m_activationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationWillBecomeActiveNotification object:NSApp queue:nil @@ -316,12 +332,144 @@ void PluginProcessProxy::applicationDidBecomeActive() makePluginProcessTheFrontProcess(); } -void PluginProcessProxy::setApplicationIsOccluded(bool applicationIsOccluded) +void PluginProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled) { if (!isValid()) return; - m_connection->send(Messages::PluginProcess::SetApplicationIsOccluded(applicationIsOccluded), 0); + m_connection->send(Messages::PluginProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0); +} + +void PluginProcessProxy::openPluginPreferencePane() +{ + if (!m_pluginProcessAttributes.moduleInfo.preferencePanePath) + return; + + NSURL *preferenceURL = [NSURL fileURLWithPath:m_pluginProcessAttributes.moduleInfo.preferencePanePath]; + if (!preferenceURL) { + LOG_ERROR("Creating URL for preference pane path \"%@\" failed.", (NSString *)m_pluginProcessAttributes.moduleInfo.preferencePanePath); + return; + } + + NSArray *preferenceURLs = [NSArray arrayWithObject:preferenceURL]; + + LSLaunchURLSpec prefSpec; + prefSpec.appURL = 0; + prefSpec.itemURLs = reinterpret_cast<CFArrayRef>(preferenceURLs); + prefSpec.passThruParams = 0; + prefSpec.launchFlags = kLSLaunchAsync | kLSLaunchDontAddToRecents; + prefSpec.asyncRefCon = 0; + + OSStatus error = LSOpenFromURLSpec(&prefSpec, 0); + if (error != noErr) + LOG_ERROR("LSOpenFromURLSpec to open \"%@\" failed with error %d.", (NSString *)m_pluginProcessAttributes.moduleInfo.preferencePanePath, error); +} + +static bool isFlashUpdater(const String& launchPath, const Vector<String>& arguments) +{ + if (launchPath != "/Applications/Utilities/Adobe Flash Player Install Manager.app/Contents/MacOS/Adobe Flash Player Install Manager") + return false; + + if (arguments.size() != 1) + return false; + + if (arguments[0] != "-update") + return false; + + return true; +} + +static bool shouldLaunchProcess(const PluginProcessAttributes& pluginProcessAttributes, const String& launchPath, const Vector<String>& arguments) +{ + if (pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.macromedia.Flash Player.plugin") + return isFlashUpdater(launchPath, arguments); + + return false; +} + +void PluginProcessProxy::launchProcess(const String& launchPath, const Vector<String>& arguments, bool& result) +{ + if (!shouldLaunchProcess(m_pluginProcessAttributes, launchPath, arguments)) { + result = false; + return; + } + + result = true; + + RetainPtr<NSMutableArray> argumentsArray = adoptNS([[NSMutableArray alloc] initWithCapacity:arguments.size()]); + for (size_t i = 0; i < arguments.size(); ++i) + [argumentsArray addObject:(NSString *)arguments[i]]; + + [NSTask launchedTaskWithLaunchPath:launchPath arguments:argumentsArray.get()]; +} + +static bool isJavaUpdaterURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) +{ + NSURL *url = [NSURL URLWithString:urlString]; + if (![url isFileURL]) + return false; + + NSString *javaUpdaterPath = [NSString pathWithComponents:[NSArray arrayWithObjects:(NSString *)pluginProcessAttributes.moduleInfo.path, @"Contents/Resources/Java Updater.app", nil]]; + return [url.path isEqualToString:javaUpdaterPath]; +} + +static bool shouldLaunchApplicationAtURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) +{ + if (pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.oracle.java.JavaAppletPlugin") + return isJavaUpdaterURL(pluginProcessAttributes, urlString); + + return false; +} + +void PluginProcessProxy::launchApplicationAtURL(const String& urlString, const Vector<String>& arguments, bool& result) +{ + if (!shouldLaunchApplicationAtURL(m_pluginProcessAttributes, urlString)) { + result = false; + return; + } + + result = true; + + RetainPtr<NSMutableArray> argumentsArray = adoptNS([[NSMutableArray alloc] initWithCapacity:arguments.size()]); + for (size_t i = 0; i < arguments.size(); ++i) + [argumentsArray addObject:(NSString *)arguments[i]]; + + NSDictionary *configuration = [NSDictionary dictionaryWithObject:argumentsArray.get() forKey:NSWorkspaceLaunchConfigurationArguments]; + [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL URLWithString:urlString] options:NSWorkspaceLaunchAsync configuration:configuration error:nullptr]; +} + +static bool isSilverlightPreferencesURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) +{ + NSURL *silverlightPreferencesURL = [NSURL fileURLWithPathComponents:[NSArray arrayWithObjects:(NSString *)pluginProcessAttributes.moduleInfo.path, @"Contents/Resources/Silverlight Preferences.app", nil]]; + + return [[NSURL URLWithString:urlString] isEqual:silverlightPreferencesURL]; +} + +static bool shouldOpenURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) +{ + if (pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.microsoft.SilverlightPlugin") + return isSilverlightPreferencesURL(pluginProcessAttributes, urlString); + + return false; +} + +void PluginProcessProxy::openURL(const String& urlString, bool& result, int32_t& status, String& launchedURLString) +{ + if (!shouldOpenURL(m_pluginProcessAttributes, urlString)) { + result = false; + return; + } + + result = true; + CFURLRef launchedURL; + status = LSOpenCFURLRef(KURL(ParsedURLString, urlString).createCFURL().get(), &launchedURL); + + if (launchedURL) { + launchedURLString = KURL(launchedURL).string(); + CFRelease(launchedURL); + } + + result = false; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp b/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp index cb4884d4c..47b118a4b 100644 --- a/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp +++ b/Source/WebKit2/UIProcess/Plugins/qt/PluginProcessProxyQt.cpp @@ -29,7 +29,6 @@ #if ENABLE(PLUGIN_PROCESS) #include "ProcessExecutablePath.h" -#include "QtDefaultDataLocation.h" #include <QByteArray> #include <QCoreApplication> #include <QDateTime> @@ -41,6 +40,7 @@ #include <QJsonObject> #include <QMap> #include <QProcess> +#include <QStandardPaths> #include <QStringBuilder> #include <QVariant> #include <WebCore/FileSystem.h> @@ -51,8 +51,9 @@ namespace WebKit { class PluginProcessCreationParameters; -void PluginProcessProxy::platformInitializeLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginModuleInfo& pluginInfo) +void PluginProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginProcessAttributes& pluginProcessAttributes) { + launchOptions.extraInitializationData.add("plugin-path", pluginProcessAttributes.moduleInfo.path); } void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationParameters&) @@ -61,10 +62,24 @@ void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationPa static PassOwnPtr<QFile> cacheFile() { - static QString cacheFilePath = defaultDataLocation() % QStringLiteral("plugin_meta_data.json"); + QString cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); + if (cachePath.isEmpty()) + return PassOwnPtr<QFile>(); + + // This should match the path set through WKContextSetDiskCacheDirectory. + cachePath.append(QDir::separator()).append(QStringLiteral(".QtWebKit")).append(QDir::separator()); + QString cacheFilePath = cachePath % QStringLiteral("plugin_meta_data.json"); + + QDir::root().mkpath(cachePath); return adoptPtr(new QFile(cacheFilePath)); } +static void removeCacheFile() +{ + if (OwnPtr<QFile> file = cacheFile()) + file->remove(); +} + struct ReadResult { enum Tag { Empty, @@ -76,7 +91,7 @@ struct ReadResult { static ReadResult::Tag readMetaDataFromCacheFile(QJsonDocument& result) { OwnPtr<QFile> file = cacheFile(); - if (!file->open(QFile::ReadOnly)) + if (!file || !file->open(QFile::ReadOnly)) return ReadResult::Empty; QByteArray data = file->readAll(); if (data.isEmpty()) @@ -96,14 +111,9 @@ static ReadResult::Tag readMetaDataFromCacheFile(QJsonDocument& result) static void writeToCacheFile(const QJsonArray& array) { OwnPtr<QFile> file = cacheFile(); - if (!file->open(QFile::WriteOnly | QFile::Truncate)) { - // It should never but let's be pessimistic, it is the file system after all. - qWarning("Cannot write into plugin meta data cache file: %s\n", qPrintable(file->fileName())); - return; - } - - // Don't care about write error here. We will detect it later. - file->write(QJsonDocument(array).toJson()); + if (file && file->open(QFile::WriteOnly | QFile::Truncate)) + // Don't care about write error here. We will detect it later. + file->write(QJsonDocument(array).toJson()); } static void appendToCacheFile(const QJsonObject& object) @@ -139,7 +149,7 @@ static MetaDataResult::Tag tryReadPluginMetaDataFromCacheFile(const QString& can for (QJsonArray::const_iterator i = array.constBegin(); i != array.constEnd(); ++i) { QJsonValue item = *i; if (!item.isObject()) { - cacheFile()->remove(); + removeCacheFile(); return MetaDataResult::NotAvailable; } @@ -147,7 +157,7 @@ static MetaDataResult::Tag tryReadPluginMetaDataFromCacheFile(const QString& can if (object.value(QStringLiteral("path")).toString() == canonicalPluginPath) { QString timestampString = object.value(QStringLiteral("timestamp")).toString(); if (timestampString.isEmpty()) { - cacheFile()->remove(); + removeCacheFile(); return MetaDataResult::NotAvailable; } QDateTime timestamp = QDateTime::fromString(timestampString); @@ -168,7 +178,7 @@ static MetaDataResult::Tag tryReadPluginMetaDataFromCacheFile(const QString& can if (result.mimeDescription.isEmpty()) { // Only the mime description is mandatory. // Don't trust in the cache file if it is empty. - cacheFile()->remove(); + removeCacheFile(); return MetaDataResult::NotAvailable; } diff --git a/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp b/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp index d4c9ec2c5..3726401f6 100644 --- a/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp +++ b/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp @@ -72,7 +72,7 @@ Vector<String> PluginInfoStore::pluginsDirectories() if (!mozillaPaths.isEmpty()) { Vector<String> paths; mozillaPaths.split(UChar(':'), /* allowEmptyEntries */ false, paths); - result.append(paths); + result.appendVector(paths); } return result; diff --git a/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp b/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp index 730dafeed..d52cae647 100644 --- a/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp +++ b/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp @@ -35,23 +35,24 @@ #include <WebCore/FileSystem.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> -#if PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT)) +#if PLATFORM(GTK) || PLATFORM(EFL) #include <glib.h> +#include <wtf/gobject/GOwnPtr.h> #endif using namespace WebCore; namespace WebKit { -void PluginProcessProxy::platformInitializeLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginModuleInfo&) +void PluginProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginProcessAttributes& pluginProcessAttributes) { #if PLATFORM(EFL) && !defined(NDEBUG) const char* commandPrefix = getenv("PLUGIN_PROCESS_COMMAND_PREFIX"); if (commandPrefix && *commandPrefix) launchOptions.processCmdPrefix = String::fromUTF8(commandPrefix); -#else - UNUSED_PARAM(launchOptions); #endif + + launchOptions.extraInitializationData.add("plugin-path", pluginProcessAttributes.moduleInfo.path); } void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationParameters&) @@ -60,7 +61,7 @@ void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationPa bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& result) { -#if PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT)) +#if PLATFORM(GTK) || PLATFORM(EFL) CString binaryPath = fileSystemRepresentation(executablePathOfPluginProcess()); CString pluginPathCString = fileSystemRepresentation(pluginPath); char* argv[4]; @@ -70,7 +71,7 @@ bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& argv[3] = 0; int status; - char* stdOut = 0; + GOwnPtr<char> stdOut; // If the disposition of SIGCLD signal is set to SIG_IGN (default) // then the signal will be ignored and g_spawn_sync() will not be @@ -84,16 +85,13 @@ bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& sigaction(SIGCLD, &action, 0); } - if (!g_spawn_sync(0, argv, 0, G_SPAWN_STDERR_TO_DEV_NULL, 0, 0, &stdOut, 0, &status, 0)) + if (!g_spawn_sync(0, argv, 0, G_SPAWN_STDERR_TO_DEV_NULL, 0, 0, &stdOut.outPtr(), 0, &status, 0)) return false; - if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS || !stdOut) { - free(stdOut); + if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS || !stdOut) return false; - } - String stdOutString(reinterpret_cast<const UChar*>(stdOut)); - free(stdOut); + String stdOutString(reinterpret_cast<const UChar*>(stdOut.get())); Vector<String> lines; stdOutString.split(UChar('\n'), true, lines); @@ -105,9 +103,9 @@ bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& result.description.swap(lines[1]); result.mimeDescription.swap(lines[2]); return !result.mimeDescription.isEmpty(); -#else // PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT)) +#else // PLATFORM(GTK) || PLATFORM(EFL) return false; -#endif // PLATFORM(GTK) || (PLATFORM(EFL) && ENABLE(GLIB_SUPPORT)) +#endif // PLATFORM(GTK) || PLATFORM(EFL) } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/win/PluginInfoStoreWin.cpp b/Source/WebKit2/UIProcess/Plugins/win/PluginInfoStoreWin.cpp deleted file mode 100644 index 634225eaf..000000000 --- a/Source/WebKit2/UIProcess/Plugins/win/PluginInfoStoreWin.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginInfoStore.h" - -#include "NetscapePluginModule.h" -#include <WebCore/FileSystem.h> -#include <WebCore/PathWalker.h> -#include <shlwapi.h> - -using namespace WebCore; - -namespace WebKit { - -static inline Vector<int> parseVersionString(const String& versionString) -{ - Vector<int> version; - - unsigned startPos = 0; - unsigned endPos; - - while (startPos < versionString.length()) { - for (endPos = startPos; endPos < versionString.length(); ++endPos) - if (versionString[endPos] == '.' || versionString[endPos] == '_') - break; - - int versionComponent = versionString.substring(startPos, endPos - startPos).toInt(); - version.append(versionComponent); - - startPos = endPos + 1; - } - - return version; -} - -// This returns whether versionA is higher than versionB -static inline bool compareVersions(const Vector<int>& versionA, const Vector<int>& versionB) -{ - for (unsigned i = 0; i < versionA.size(); i++) { - if (i >= versionB.size()) - return true; - - if (versionA[i] > versionB[i]) - return true; - else if (versionA[i] < versionB[i]) - return false; - } - - // If we come here, the versions are either the same or versionB has an extra component, just return false - return false; -} - -static inline String safariPluginsDirectory() -{ - static String pluginsDirectory; - static bool cachedPluginDirectory = false; - - if (!cachedPluginDirectory) { - cachedPluginDirectory = true; - - WCHAR moduleFileNameStr[MAX_PATH]; - int moduleFileNameLen = ::GetModuleFileNameW(0, moduleFileNameStr, WTF_ARRAY_LENGTH(moduleFileNameStr)); - - if (!moduleFileNameLen || moduleFileNameLen == WTF_ARRAY_LENGTH(moduleFileNameStr)) - return pluginsDirectory; - - if (!::PathRemoveFileSpecW(moduleFileNameStr)) - return pluginsDirectory; - - pluginsDirectory = String(moduleFileNameStr) + "\\Plugins"; - } - - return pluginsDirectory; -} - -static inline void addMozillaPluginDirectories(Vector<String>& directories) -{ - // Enumerate all Mozilla plugin directories in the registry - HKEY key; - LONG result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"Software\\Mozilla", 0, KEY_READ, &key); - if (result != ERROR_SUCCESS) - return; - - WCHAR name[128]; - FILETIME lastModified; - - // Enumerate subkeys - for (int i = 0;; i++) { - DWORD nameLen = WTF_ARRAY_LENGTH(name); - result = ::RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, &lastModified); - - if (result != ERROR_SUCCESS) - break; - - String extensionsPath = String(name, nameLen) + "\\Extensions"; - HKEY extensionsKey; - - // Try opening the key - result = ::RegOpenKeyExW(key, extensionsPath.charactersWithNullTermination(), 0, KEY_READ, &extensionsKey); - - if (result == ERROR_SUCCESS) { - // Now get the plugins directory - WCHAR pluginsDirectoryStr[MAX_PATH]; - DWORD pluginsDirectorySize = sizeof(pluginsDirectoryStr); - DWORD type; - - result = ::RegQueryValueExW(extensionsKey, L"Plugins", 0, &type, reinterpret_cast<LPBYTE>(&pluginsDirectoryStr), &pluginsDirectorySize); - - if (result == ERROR_SUCCESS && type == REG_SZ) - directories.append(String(pluginsDirectoryStr, pluginsDirectorySize / sizeof(WCHAR) - 1)); - - ::RegCloseKey(extensionsKey); - } - } - - ::RegCloseKey(key); -} - -static inline void addWindowsMediaPlayerPluginDirectory(Vector<String>& directories) -{ - // The new WMP Firefox plugin is installed in \PFiles\Plugins if it can't find any Firefox installs - WCHAR pluginDirectoryStr[MAX_PATH + 1]; - DWORD pluginDirectorySize = ::ExpandEnvironmentStringsW(L"%SYSTEMDRIVE%\\PFiles\\Plugins", pluginDirectoryStr, WTF_ARRAY_LENGTH(pluginDirectoryStr)); - - if (pluginDirectorySize > 0 && pluginDirectorySize <= WTF_ARRAY_LENGTH(pluginDirectoryStr)) - directories.append(String(pluginDirectoryStr, pluginDirectorySize - 1)); - - DWORD type; - WCHAR installationDirectoryStr[MAX_PATH]; - DWORD installationDirectorySize = sizeof(installationDirectoryStr); - - HRESULT result = ::SHGetValueW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer", L"Installation Directory", &type, reinterpret_cast<LPBYTE>(&installationDirectoryStr), &installationDirectorySize); - - if (result == ERROR_SUCCESS && type == REG_SZ) - directories.append(String(installationDirectoryStr, installationDirectorySize / sizeof(WCHAR) - 1)); -} - -static inline void addQuickTimePluginDirectory(Vector<String>& directories) -{ - DWORD type; - WCHAR installationDirectoryStr[MAX_PATH]; - DWORD installationDirectorySize = sizeof(installationDirectoryStr); - - HRESULT result = ::SHGetValueW(HKEY_LOCAL_MACHINE, L"Software\\Apple Computer, Inc.\\QuickTime", L"InstallDir", &type, reinterpret_cast<LPBYTE>(&installationDirectoryStr), &installationDirectorySize); - - if (result == ERROR_SUCCESS && type == REG_SZ) { - String pluginDir = String(installationDirectoryStr, installationDirectorySize / sizeof(WCHAR) - 1) + "\\plugins"; - directories.append(pluginDir); - } -} - -static inline void addAdobeAcrobatPluginDirectory(Vector<String>& directories) -{ - HKEY key; - HRESULT result = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"Software\\Adobe\\Acrobat Reader", 0, KEY_READ, &key); - if (result != ERROR_SUCCESS) - return; - - WCHAR name[128]; - FILETIME lastModified; - - Vector<int> latestAcrobatVersion; - String latestAcrobatVersionString; - - // Enumerate subkeys - for (int i = 0;; i++) { - DWORD nameLen = WTF_ARRAY_LENGTH(name); - result = ::RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, &lastModified); - - if (result != ERROR_SUCCESS) - break; - - Vector<int> acrobatVersion = parseVersionString(String(name, nameLen)); - if (compareVersions(acrobatVersion, latestAcrobatVersion)) { - latestAcrobatVersion = acrobatVersion; - latestAcrobatVersionString = String(name, nameLen); - } - } - - if (!latestAcrobatVersionString.isNull()) { - DWORD type; - WCHAR acrobatInstallPathStr[MAX_PATH]; - DWORD acrobatInstallPathSize = sizeof(acrobatInstallPathStr); - - String acrobatPluginKeyPath = "Software\\Adobe\\Acrobat Reader\\" + latestAcrobatVersionString + "\\InstallPath"; - result = ::SHGetValueW(HKEY_LOCAL_MACHINE, acrobatPluginKeyPath.charactersWithNullTermination(), 0, &type, reinterpret_cast<LPBYTE>(acrobatInstallPathStr), &acrobatInstallPathSize); - - if (result == ERROR_SUCCESS) { - String acrobatPluginDirectory = String(acrobatInstallPathStr, acrobatInstallPathSize / sizeof(WCHAR) - 1) + "\\browser"; - directories.append(acrobatPluginDirectory); - } - } - - ::RegCloseKey(key); -} - -static inline void addMacromediaPluginDirectories(Vector<String>& directories) -{ -#if !OS(WINCE) - WCHAR systemDirectoryStr[MAX_PATH]; - - if (!::GetSystemDirectoryW(systemDirectoryStr, WTF_ARRAY_LENGTH(systemDirectoryStr))) - return; - - WCHAR macromediaDirectoryStr[MAX_PATH]; - - if (!::PathCombineW(macromediaDirectoryStr, systemDirectoryStr, L"macromed\\Flash")) - return; - - directories.append(macromediaDirectoryStr); - - if (!::PathCombineW(macromediaDirectoryStr, systemDirectoryStr, L"macromed\\Shockwave 10")) - return; - - directories.append(macromediaDirectoryStr); -#endif -} - -Vector<String> PluginInfoStore::pluginsDirectories() -{ - Vector<String> directories; - - String ourDirectory = safariPluginsDirectory(); - if (!ourDirectory.isNull()) - directories.append(ourDirectory); - - addQuickTimePluginDirectory(directories); - addAdobeAcrobatPluginDirectory(directories); - addMozillaPluginDirectories(directories); - addWindowsMediaPlayerPluginDirectory(directories); - addMacromediaPluginDirectories(directories); - - return directories; -} - -Vector<String> PluginInfoStore::pluginPathsInDirectory(const String& directory) -{ - Vector<String> paths; - - PathWalker walker(directory, "*"); - if (!walker.isValid()) - return paths; - - do { - if (walker.data().dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - continue; - - String filename = walker.data().cFileName; - if ((!filename.startsWith("np", false) || !filename.endsWith("dll", false)) && (!equalIgnoringCase(filename, "Plugin.dll") || !directory.endsWith("Shockwave 10", false))) - continue; - - paths.append(directory + "\\" + filename); - } while (walker.step()); - - return paths; -} - -static void addPluginPathsFromRegistry(HKEY rootKey, Vector<String>& paths) -{ - HKEY key; - if (::RegOpenKeyExW(rootKey, L"Software\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &key) != ERROR_SUCCESS) - return; - - for (size_t i = 0; ; ++i) { - // MSDN says that key names have a maximum length of 255 characters. - wchar_t name[256]; - DWORD nameLen = WTF_ARRAY_LENGTH(name); - if (::RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, 0) != ERROR_SUCCESS) - break; - - wchar_t path[MAX_PATH]; - DWORD pathSizeInBytes = sizeof(path); - DWORD type; - if (::SHGetValueW(key, name, L"Path", &type, path, &pathSizeInBytes) != ERROR_SUCCESS) - continue; - if (type != REG_SZ) - continue; - - paths.append(path); - } - - ::RegCloseKey(key); -} - -Vector<String> PluginInfoStore::individualPluginPaths() -{ - Vector<String> paths; - - addPluginPathsFromRegistry(HKEY_LOCAL_MACHINE, paths); - addPluginPathsFromRegistry(HKEY_CURRENT_USER, paths); - - return paths; -} - -static uint64_t fileVersion(DWORD leastSignificant, DWORD mostSignificant) -{ - ULARGE_INTEGER version; - version.LowPart = leastSignificant; - version.HighPart = mostSignificant; - return version.QuadPart; -} - -bool PluginInfoStore::getPluginInfo(const String& pluginPath, PluginModuleInfo& plugin) -{ -#if ENABLE(NETSCAPE_PLUGIN_API) - return NetscapePluginModule::getPluginInfo(pluginPath, plugin); -#else - UNUSED_PARAM(pluginPath); - UNUSED_PARAM(plugin); - return false; -#endif -} - -static bool isOldWindowsMediaPlayerPlugin(const PluginModuleInfo& plugin) -{ - return equalIgnoringCase(plugin.info.file, "npdsplay.dll"); -} - -static bool isNewWindowsMediaPlayerPlugin(const PluginModuleInfo& plugin) -{ - return equalIgnoringCase(plugin.info.file, "np-mswmp.dll"); -} - -bool PluginInfoStore::shouldUsePlugin(Vector<PluginModuleInfo>& alreadyLoadedPlugins, const PluginModuleInfo& plugin) -{ - if (plugin.info.name == "Citrix ICA Client") { - // The Citrix ICA Client plug-in requires a Mozilla-based browser; see <rdar://6418681>. - return false; - } - - if (plugin.info.name == "Silverlight Plug-In") { - // workaround for <rdar://5557379> Crash in Silverlight when opening microsoft.com. - // the latest 1.0 version of Silverlight does not reproduce this crash, so allow it - // and any newer versions - static const uint64_t minimumRequiredVersion = fileVersion(0x51BE0000, 0x00010000); - return plugin.fileVersion >= minimumRequiredVersion; - } - - if (equalIgnoringCase(plugin.info.file, "npmozax.dll")) { - // Bug 15217: Mozilla ActiveX control complains about missing xpcom_core.dll - return false; - } - - if (equalIgnoringCase(plugin.info.file, "npwpf.dll")) { - // Bug 57119: Microsoft Windows Presentation Foundation (WPF) plug-in complains about missing xpcom.dll - return false; - } - - if (plugin.info.name == "Yahoo Application State Plugin") { - // https://bugs.webkit.org/show_bug.cgi?id=26860 - // Bug in Yahoo Application State plug-in earlier than 1.0.0.6 leads to heap corruption. - static const uint64_t minimumRequiredVersion = fileVersion(0x00000006, 0x00010000); - return plugin.fileVersion >= minimumRequiredVersion; - } - - if (isOldWindowsMediaPlayerPlugin(plugin)) { - // Don't load the old Windows Media Player plugin if we've already loaded the new Windows - // Media Player plugin. - for (size_t i = 0; i < alreadyLoadedPlugins.size(); ++i) { - if (!isNewWindowsMediaPlayerPlugin(alreadyLoadedPlugins[i])) - continue; - return false; - } - return true; - } - - if (isNewWindowsMediaPlayerPlugin(plugin)) { - // Remove the old Windows Media Player plugin if we've already added it. - for (size_t i = 0; i < alreadyLoadedPlugins.size(); ++i) { - if (!isOldWindowsMediaPlayerPlugin(alreadyLoadedPlugins[i])) - continue; - alreadyLoadedPlugins.remove(i); - } - return true; - } - - // FIXME: We should prefer a newer version of a plugin to an older version, rather than loading - // only the first. <http://webkit.org/b/58469> - String pluginFileName = pathGetFileName(plugin.path); - for (size_t i = 0; i < alreadyLoadedPlugins.size(); ++i) { - const PluginModuleInfo& loadedPlugin = alreadyLoadedPlugins[i]; - - // If a plug-in with the same filename already exists, we don't want to load it. - if (equalIgnoringCase(pluginFileName, pathGetFileName(loadedPlugin.path))) - return false; - } - - return true; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h index c2555ea4e..cd30dc00c 100644 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h +++ b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h @@ -54,7 +54,7 @@ public: void removeSharedWorkerProcessProxy(SharedWorkerProcessProxy*); #if PLATFORM(MAC) - void setApplicationIsOccluded(bool); + void setProcessSuppressionEnabled(bool); #endif private: @@ -62,7 +62,7 @@ private: SharedWorkerProcessProxy* getOrCreateSharedWorkerProcess(const String& url, const String& name); - Vector<RefPtr<SharedWorkerProcessProxy> > m_sharedWorkerProcesses; + Vector<RefPtr<SharedWorkerProcessProxy>> m_sharedWorkerProcesses; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp index b808efbac..636085b17 100644 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp @@ -115,9 +115,9 @@ void SharedWorkerProcessProxy::sharedWorkerProcessCrashedOrFailedToLaunch() m_sharedWorkerProcessManager->removeSharedWorkerProcessProxy(this); } -void SharedWorkerProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void SharedWorkerProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) { - didReceiveSharedWorkerProcessProxyMessage(connection, messageID, decoder); + didReceiveSharedWorkerProcessProxyMessage(connection, decoder); } void SharedWorkerProcessProxy::didClose(CoreIPC::Connection*) @@ -166,8 +166,8 @@ void SharedWorkerProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Con m_numPendingConnectionRequests = 0; #if PLATFORM(MAC) - if (WebContext::applicationIsOccluded()) - m_connection->send(Messages::SharedWorkerProcess::SetApplicationIsOccluded(true), 0); + if (WebContext::canEnableProcessSuppressionForGlobalChildProcesses()) + setProcessSuppressionEnabled(true); #endif } diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h index 6e9f20a86..c84e99be5 100644 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h +++ b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h @@ -59,7 +59,7 @@ public: bool isValid() const { return m_connection; } #if PLATFORM(MAC) - void setApplicationIsOccluded(bool); + void setProcessSuppressionEnabled(bool); #endif private: @@ -68,7 +68,7 @@ private: void sharedWorkerProcessCrashedOrFailedToLaunch(); // CoreIPC::Connection::Client - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); virtual void didClose(CoreIPC::Connection*); virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName); @@ -76,7 +76,7 @@ private: virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); // Message handlers - void didReceiveSharedWorkerProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + void didReceiveSharedWorkerProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); void didCreateWebProcessConnection(const CoreIPC::Attachment&); void platformInitializeSharedWorkerProcess(SharedWorkerProcessCreationParameters&); @@ -90,7 +90,7 @@ private: // The process launcher for the plug-in host process. RefPtr<ProcessLauncher> m_processLauncher; - Deque<RefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply> > m_pendingConnectionReplies; + Deque<RefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>> m_pendingConnectionReplies; // If createPluginConnection is called while the process is still launching we'll keep count of it and send a bunch of requests // when the process finishes launching. diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in index ec98b6d4c..f5dc4eadc 100644 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in @@ -22,7 +22,7 @@ #if ENABLE(SHARED_WORKER_PROCESS) -messages -> SharedWorkerProcessProxy { +messages -> SharedWorkerProcessProxy LegacyReceiver { DidCreateWebProcessConnection(CoreIPC::Attachment connectionIdentifier) } diff --git a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm b/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm index e63907ce6..85ca4aa25 100644 --- a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm +++ b/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm @@ -32,11 +32,11 @@ namespace WebKit { -void SharedWorkerProcessManager::setApplicationIsOccluded(bool applicationIsOccluded) +void SharedWorkerProcessManager::setProcessSuppressionEnabled(bool processSuppressionEnabled) { size_t processCount = m_sharedWorkerProcesses.size(); for (size_t i = 0; i < processCount; ++i) - m_sharedWorkerProcesses[i]->setApplicationIsOccluded(applicationIsOccluded); + m_sharedWorkerProcesses[i]->setProcessSuppressionEnabled(processSuppressionEnabled); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm b/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm index 5b3dd4639..fab4acdc6 100644 --- a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm +++ b/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm @@ -32,12 +32,12 @@ namespace WebKit { -void SharedWorkerProcessProxy::setApplicationIsOccluded(bool applicationIsOccluded) +void SharedWorkerProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled) { if (!isValid()) return; - m_connection->send(Messages::SharedWorkerProcess::SetApplicationIsOccluded(applicationIsOccluded), 0); + m_connection->send(Messages::SharedWorkerProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/StatisticsRequest.cpp b/Source/WebKit2/UIProcess/StatisticsRequest.cpp new file mode 100644 index 000000000..d2b22fa5b --- /dev/null +++ b/Source/WebKit2/UIProcess/StatisticsRequest.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "StatisticsRequest.h" + +#include "ImmutableArray.h" +#include "MutableDictionary.h" +#include <wtf/Atomics.h> + +namespace WebKit { + +StatisticsRequest::StatisticsRequest(PassRefPtr<DictionaryCallback> callback) + : m_callback(callback) +{ +} + +StatisticsRequest::~StatisticsRequest() +{ + if (m_callback) + m_callback->invalidate(); +} + +uint64_t StatisticsRequest::addOutstandingRequest() +{ + static int64_t uniqueRequestID; + + uint64_t requestID = atomicIncrement(&uniqueRequestID); + m_outstandingRequests.add(requestID); + return requestID; +} + +static void addToDictionaryFromHashMap(MutableDictionary* dictionary, const HashMap<String, uint64_t>& map) +{ + HashMap<String, uint64_t>::const_iterator end = map.end(); + for (HashMap<String, uint64_t>::const_iterator it = map.begin(); it != end; ++it) + dictionary->set(it->key, RefPtr<WebUInt64>(WebUInt64::create(it->value)).get()); +} + +static PassRefPtr<MutableDictionary> createDictionaryFromHashMap(const HashMap<String, uint64_t>& map) +{ + RefPtr<MutableDictionary> result = MutableDictionary::create(); + addToDictionaryFromHashMap(result.get(), map); + return result; +} + +void StatisticsRequest::completedRequest(uint64_t requestID, const StatisticsData& data) +{ + ASSERT(m_outstandingRequests.contains(requestID)); + m_outstandingRequests.remove(requestID); + + if (!m_responseDictionary) + m_responseDictionary = MutableDictionary::create(); + + // FIXME (Multi-WebProcess) <rdar://problem/13200059>: This code overwrites any previous response data received. + // When getting responses from multiple WebProcesses we need to combine items instead of clobbering them. + + addToDictionaryFromHashMap(m_responseDictionary.get(), data.statisticsNumbers); + + if (!data.javaScriptProtectedObjectTypeCounts.isEmpty()) + m_responseDictionary->set("JavaScriptProtectedObjectTypeCounts", createDictionaryFromHashMap(data.javaScriptProtectedObjectTypeCounts).get()); + if (!data.javaScriptObjectTypeCounts.isEmpty()) + m_responseDictionary->set("JavaScriptObjectTypeCounts", createDictionaryFromHashMap(data.javaScriptObjectTypeCounts).get()); + + size_t cacheStatisticsCount = data.webCoreCacheStatistics.size(); + if (cacheStatisticsCount) { + Vector<RefPtr<APIObject>> cacheStatisticsVector(cacheStatisticsCount); + for (size_t i = 0; i < cacheStatisticsCount; ++i) + cacheStatisticsVector[i] = createDictionaryFromHashMap(data.webCoreCacheStatistics[i]); + m_responseDictionary->set("WebCoreCacheStatistics", ImmutableArray::adopt(cacheStatisticsVector).get()); + } + + if (m_outstandingRequests.isEmpty()) { + m_callback->performCallbackWithReturnValue(m_responseDictionary.get()); + m_callback = 0; + } +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/WebContextMenuProxyWin.h b/Source/WebKit2/UIProcess/StatisticsRequest.h index a843b2625..bf9c37bbe 100644 --- a/Source/WebKit2/UIProcess/win/WebContextMenuProxyWin.h +++ b/Source/WebKit2/UIProcess/StatisticsRequest.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,39 +23,47 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebContextMenuProxyWin_h -#define WebContextMenuProxyWin_h +#ifndef StatisticsRequest_h +#define StatisticsRequest_h -#include "WebContextMenuItemData.h" -#include "WebContextMenuProxy.h" -#include "WebPageProxy.h" -#include <wtf/HashMap.h> +#include "GenericCallback.h" +#include "StatisticsData.h" + +#include <wtf/HashSet.h> namespace WebKit { -class WebContextMenuProxyWin : public WebContextMenuProxy { +struct StatisticsData; + +typedef GenericCallback<WKDictionaryRef> DictionaryCallback; + +enum StatisticsRequestType { + StatisticsRequestTypeWebContent = 0x00000001, + StatisticsRequestTypeNetworking = 0x00000002 +}; + +class StatisticsRequest : public RefCounted<StatisticsRequest> { public: - static PassRefPtr<WebContextMenuProxyWin> create(HWND parentWindow, WebPageProxy* page) + static PassRefPtr<StatisticsRequest> create(PassRefPtr<DictionaryCallback> callback) { - return adoptRef(new WebContextMenuProxyWin(parentWindow, page)); + return adoptRef(new StatisticsRequest(callback)); } -private: - WebContextMenuProxyWin(HWND parentWindow, WebPageProxy* page); + ~StatisticsRequest(); - virtual void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); - virtual void hideContextMenu(); + uint64_t addOutstandingRequest(); - void populateMenu(HMENU, const Vector<WebContextMenuItemData>&); + void completedRequest(uint64_t requestID, const StatisticsData&); + +private: + StatisticsRequest(PassRefPtr<DictionaryCallback>); - HMENU m_menu; - HWND m_window; - WebPageProxy* m_page; + HashSet<uint64_t> m_outstandingRequests; + RefPtr<DictionaryCallback> m_callback; - // Creates a map from the context menu item's action to the context menu item itself. - HashMap<int, WebContextMenuItemData> m_actionMap; + RefPtr<MutableDictionary> m_responseDictionary; }; } // namespace WebKit -#endif // WebContextMenuProxyWin_h +#endif // StatisticsRequest_h diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp new file mode 100644 index 000000000..7c58578eb --- /dev/null +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (C) 2008, 2009, 2010, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "LocalStorageDatabase.h" + +#include "LocalStorageDatabaseTracker.h" +#include "WorkQueue.h" +#include <WebCore/FileSystem.h> +#include <WebCore/SQLiteStatement.h> +#include <WebCore/SQLiteTransaction.h> +#include <WebCore/SecurityOrigin.h> +#include <WebCore/StorageMap.h> +#include <wtf/PassRefPtr.h> +#include <wtf/text/StringHash.h> +#include <wtf/text/WTFString.h> + +using namespace WebCore; + +static const double databaseUpdateIntervalInSeconds = 1.0; + +static const int maximumItemsToUpdate = 100; + +namespace WebKit { + +PassRefPtr<LocalStorageDatabase> LocalStorageDatabase::create(PassRefPtr<WorkQueue> queue, PassRefPtr<LocalStorageDatabaseTracker> tracker, PassRefPtr<SecurityOrigin> securityOrigin) +{ + return adoptRef(new LocalStorageDatabase(queue, tracker, securityOrigin)); +} + +LocalStorageDatabase::LocalStorageDatabase(PassRefPtr<WorkQueue> queue, PassRefPtr<LocalStorageDatabaseTracker> tracker, PassRefPtr<SecurityOrigin> securityOrigin) + : m_queue(queue) + , m_tracker(tracker) + , m_securityOrigin(securityOrigin) + , m_databasePath(m_tracker->databasePath(m_securityOrigin.get())) + , m_failedToOpenDatabase(false) + , m_didImportItems(false) + , m_isClosed(false) + , m_didScheduleDatabaseUpdate(false) + , m_shouldClearItems(false) +{ +} + +LocalStorageDatabase::~LocalStorageDatabase() +{ + ASSERT(m_isClosed); +} + +void LocalStorageDatabase::openDatabase(DatabaseOpeningStrategy openingStrategy) +{ + ASSERT(!m_database.isOpen()); + ASSERT(!m_failedToOpenDatabase); + + if (!tryToOpenDatabase(openingStrategy)) { + m_failedToOpenDatabase = true; + return; + } + + if (m_database.isOpen()) + m_tracker->didOpenDatabaseWithOrigin(m_securityOrigin.get()); +} + +bool LocalStorageDatabase::tryToOpenDatabase(DatabaseOpeningStrategy openingStrategy) +{ + if (!fileExists(m_databasePath) && openingStrategy == SkipIfNonExistent) + return true; + + if (m_databasePath.isEmpty()) { + LOG_ERROR("Filename for local storage database is empty - cannot open for persistent storage"); + return false; + } + + if (!m_database.open(m_databasePath)) { + LOG_ERROR("Failed to open database file %s for local storage", m_databasePath.utf8().data()); + return false; + } + + // Since a WorkQueue isn't bound to a specific thread, we have to disable threading checks + // even though we never access the database from different threads simultaneously. + m_database.disableThreadingChecks(); + + if (!migrateItemTableIfNeeded()) { + // We failed to migrate the item table. In order to avoid trying to migrate the table over and over, + // just delete it and start from scratch. + if (!m_database.executeCommand("DROP TABLE ItemTable")) + LOG_ERROR("Failed to delete table ItemTable for local storage"); + } + + if (!m_database.executeCommand("CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)")) { + LOG_ERROR("Failed to create table ItemTable for local storage"); + return false; + } + + return true; +} + +bool LocalStorageDatabase::migrateItemTableIfNeeded() +{ + if (!m_database.tableExists("ItemTable")) + return true; + + SQLiteStatement query(m_database, "SELECT value FROM ItemTable LIMIT 1"); + + // This query isn't ever executed, it's just used to check the column type. + if (query.isColumnDeclaredAsBlob(0)) + return true; + + // Create a new table with the right type, copy all the data over to it and then replace the new table with the old table. + static const char* commands[] = { + "DROP TABLE IF EXISTS ItemTable2", + "CREATE TABLE ItemTable2 (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)", + "INSERT INTO ItemTable2 SELECT * from ItemTable", + "DROP TABLE ItemTable", + "ALTER TABLE ItemTable2 RENAME TO ItemTable", + 0, + }; + + SQLiteTransaction transaction(m_database, false); + transaction.begin(); + + for (size_t i = 0; commands[i]; ++i) { + if (m_database.executeCommand(commands[i])) + continue; + + LOG_ERROR("Failed to migrate table ItemTable for local storage when executing: %s", commands[i]); + transaction.rollback(); + + return false; + } + + transaction.commit(); + return true; +} + +void LocalStorageDatabase::importItems(StorageMap& storageMap) +{ + if (m_didImportItems) + return; + + // FIXME: If it can't import, then the default WebKit behavior should be that of private browsing, + // not silently ignoring it. https://bugs.webkit.org/show_bug.cgi?id=25894 + + // We set this to true even if we don't end up importing any items due to failure because + // there's really no good way to recover other than not importing anything. + m_didImportItems = true; + + openDatabase(SkipIfNonExistent); + if (!m_database.isOpen()) + return; + + SQLiteStatement query(m_database, "SELECT key, value FROM ItemTable"); + if (query.prepare() != SQLResultOk) { + LOG_ERROR("Unable to select items from ItemTable for local storage"); + return; + } + + HashMap<String, String> items; + + int result = query.step(); + while (result == SQLResultRow) { + items.set(query.getColumnText(0), query.getColumnBlobAsString(1)); + result = query.step(); + } + + if (result != SQLResultDone) { + LOG_ERROR("Error reading items from ItemTable for local storage"); + return; + } + + storageMap.importItems(items); +} + +void LocalStorageDatabase::setItem(const String& key, const String& value) +{ + itemDidChange(key, value); +} + +void LocalStorageDatabase::removeItem(const String& key) +{ + itemDidChange(key, String()); +} + +void LocalStorageDatabase::clear() +{ + m_changedItems.clear(); + m_shouldClearItems = true; + + scheduleDatabaseUpdate(); +} + +void LocalStorageDatabase::close() +{ + ASSERT(!m_isClosed); + m_isClosed = true; + + if (m_didScheduleDatabaseUpdate) { + updateDatabaseWithChangedItems(m_changedItems); + m_changedItems.clear(); + } + + bool isEmpty = databaseIsEmpty(); + + if (m_database.isOpen()) + m_database.close(); + + if (isEmpty) + m_tracker->deleteDatabaseWithOrigin(m_securityOrigin.get()); +} + +void LocalStorageDatabase::itemDidChange(const String& key, const String& value) +{ + m_changedItems.set(key, value); + scheduleDatabaseUpdate(); +} + +void LocalStorageDatabase::scheduleDatabaseUpdate() +{ + if (m_didScheduleDatabaseUpdate) + return; + + m_didScheduleDatabaseUpdate = true; + m_queue->dispatchAfterDelay(bind(&LocalStorageDatabase::updateDatabase, this), databaseUpdateIntervalInSeconds); +} + +void LocalStorageDatabase::updateDatabase() +{ + if (m_isClosed) + return; + + ASSERT(m_didScheduleDatabaseUpdate); + m_didScheduleDatabaseUpdate = false; + + HashMap<String, String> changedItems; + if (m_changedItems.size() <= maximumItemsToUpdate) { + // There are few enough changed items that we can just always write all of them. + m_changedItems.swap(changedItems); + } else { + for (int i = 0; i < maximumItemsToUpdate; ++i) { + auto it = m_changedItems.begin(); + changedItems.add(it->key, it->value); + + m_changedItems.remove(it); + } + + ASSERT(changedItems.size() <= maximumItemsToUpdate); + + // Reschedule the update for the remaining items. + scheduleDatabaseUpdate(); + } + + updateDatabaseWithChangedItems(changedItems); +} + +void LocalStorageDatabase::updateDatabaseWithChangedItems(const HashMap<String, String>& changedItems) +{ + if (!m_database.isOpen()) + openDatabase(CreateIfNonExistent); + if (!m_database.isOpen()) + return; + + if (m_shouldClearItems) { + m_shouldClearItems = false; + + SQLiteStatement clearStatement(m_database, "DELETE FROM ItemTable"); + if (clearStatement.prepare() != SQLResultOk) { + LOG_ERROR("Failed to prepare clear statement - cannot write to local storage database"); + return; + } + + int result = clearStatement.step(); + if (result != SQLResultDone) { + LOG_ERROR("Failed to clear all items in the local storage database - %i", result); + return; + } + } + + SQLiteStatement insertStatement(m_database, "INSERT INTO ItemTable VALUES (?, ?)"); + if (insertStatement.prepare() != SQLResultOk) { + LOG_ERROR("Failed to prepare insert statement - cannot write to local storage database"); + return; + } + + SQLiteStatement deleteStatement(m_database, "DELETE FROM ItemTable WHERE key=?"); + if (deleteStatement.prepare() != SQLResultOk) { + LOG_ERROR("Failed to prepare delete statement - cannot write to local storage database"); + return; + } + + SQLiteTransaction transaction(m_database); + transaction.begin(); + + for (auto it = changedItems.begin(), end = changedItems.end(); it != end; ++it) { + // A null value means that the key/value pair should be deleted. + SQLiteStatement& statement = it->value.isNull() ? deleteStatement : insertStatement; + + statement.bindText(1, it->key); + + // If we're inserting a key/value pair, bind the value as well. + if (!it->value.isNull()) + statement.bindBlob(2, it->value); + + int result = statement.step(); + if (result != SQLResultDone) { + LOG_ERROR("Failed to update item in the local storage database - %i", result); + break; + } + + statement.reset(); + } + + transaction.commit(); +} + +bool LocalStorageDatabase::databaseIsEmpty() +{ + if (!m_database.isOpen()) + return false; + + SQLiteStatement query(m_database, "SELECT COUNT(*) FROM ItemTable"); + if (query.prepare() != SQLResultOk) { + LOG_ERROR("Unable to count number of rows in ItemTable for local storage"); + return false; + } + + int result = query.step(); + if (result != SQLResultRow) { + LOG_ERROR("No results when counting number of rows in ItemTable for local storage"); + return false; + } + + return !query.getColumnInt(0); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h new file mode 100644 index 000000000..1acd6b253 --- /dev/null +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2008, 2009, 2010, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LocalStorageDatabase_h +#define LocalStorageDatabase_h + +#include <WebCore/SQLiteDatabase.h> +#include <wtf/Forward.h> +#include <wtf/HashMap.h> +#include <wtf/RefPtr.h> +#include <wtf/ThreadSafeRefCounted.h> + +class WorkQueue; + +namespace WebCore { +class SecurityOrigin; +class StorageMap; +} + +namespace WebKit { + +class LocalStorageDatabaseTracker; + +class LocalStorageDatabase : public ThreadSafeRefCounted<LocalStorageDatabase> { +public: + static PassRefPtr<LocalStorageDatabase> create(PassRefPtr<WorkQueue>, PassRefPtr<LocalStorageDatabaseTracker>, PassRefPtr<WebCore::SecurityOrigin>); + ~LocalStorageDatabase(); + + // Will block until the import is complete. + void importItems(WebCore::StorageMap&); + + void setItem(const String& key, const String& value); + void removeItem(const String& key); + void clear(); + + // Will block until all pending changes have been written to disk. + void close(); + +private: + LocalStorageDatabase(PassRefPtr<WorkQueue>, PassRefPtr<LocalStorageDatabaseTracker>, PassRefPtr<WebCore::SecurityOrigin>); + + enum DatabaseOpeningStrategy { + CreateIfNonExistent, + SkipIfNonExistent + }; + bool tryToOpenDatabase(DatabaseOpeningStrategy); + void openDatabase(DatabaseOpeningStrategy); + + bool migrateItemTableIfNeeded(); + + void itemDidChange(const String& key, const String& value); + + void scheduleDatabaseUpdate(); + void updateDatabase(); + void updateDatabaseWithChangedItems(const HashMap<String, String>&); + + bool databaseIsEmpty(); + + RefPtr<WorkQueue> m_queue; + RefPtr<LocalStorageDatabaseTracker> m_tracker; + RefPtr<WebCore::SecurityOrigin> m_securityOrigin; + + String m_databasePath; + WebCore::SQLiteDatabase m_database; + bool m_failedToOpenDatabase; + bool m_didImportItems; + bool m_isClosed; + + bool m_didScheduleDatabaseUpdate; + bool m_shouldClearItems; + HashMap<String, String> m_changedItems; +}; + + +} // namespace WebKit + +#endif // LocalStorageDatabase_h diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp new file mode 100644 index 000000000..f58fe8a79 --- /dev/null +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "LocalStorageDatabaseTracker.h" + +#include "WorkQueue.h" +#include <WebCore/FileSystem.h> +#include <WebCore/SQLiteStatement.h> +#include <WebCore/SecurityOrigin.h> +#include <wtf/text/CString.h> + +using namespace WebCore; + +namespace WebKit { + +PassRefPtr<LocalStorageDatabaseTracker> LocalStorageDatabaseTracker::create(PassRefPtr<WorkQueue> queue) +{ + return adoptRef(new LocalStorageDatabaseTracker(queue)); +} + +LocalStorageDatabaseTracker::LocalStorageDatabaseTracker(PassRefPtr<WorkQueue> queue) + : m_queue(queue) +{ +} + +LocalStorageDatabaseTracker::~LocalStorageDatabaseTracker() +{ +} + +void LocalStorageDatabaseTracker::setLocalStorageDirectory(const String& localStorageDirectory) +{ + // FIXME: We should come up with a better idiom for safely copying strings across threads. + RefPtr<StringImpl> copiedLocalStorageDirectory = localStorageDirectory.impl() ? localStorageDirectory.impl()->isolatedCopy() : nullptr; + + m_queue->dispatch(bind(&LocalStorageDatabaseTracker::setLocalStorageDirectoryInternal, this, copiedLocalStorageDirectory.release())); +} + +String LocalStorageDatabaseTracker::databasePath(SecurityOrigin* securityOrigin) const +{ + return databasePath(securityOrigin->databaseIdentifier() + ".localstorage"); +} + +void LocalStorageDatabaseTracker::didOpenDatabaseWithOrigin(SecurityOrigin* securityOrigin) +{ + addDatabaseWithOriginIdentifier(securityOrigin->databaseIdentifier(), databasePath(securityOrigin)); +} + +void LocalStorageDatabaseTracker::deleteDatabaseWithOrigin(SecurityOrigin* securityOrigin) +{ + removeDatabaseWithOriginIdentifier(securityOrigin->databaseIdentifier()); +} + +void LocalStorageDatabaseTracker::deleteAllDatabases() +{ + m_origins.clear(); + + openTrackerDatabase(SkipIfNonExistent); + if (!m_database.isOpen()) + return; + + SQLiteStatement statement(m_database, "SELECT origin, path FROM Origins"); + if (statement.prepare() != SQLResultOk) { + LOG_ERROR("Failed to prepare statement."); + return; + } + + int result; + while ((result = statement.step()) == SQLResultRow) { + deleteFile(statement.getColumnText(1)); + + // FIXME: Call out to the client. + } + + if (result != SQLResultDone) + LOG_ERROR("Failed to read in all origins from the database."); + + if (m_database.isOpen()) + m_database.close(); + + if (!deleteFile(trackerDatabasePath())) { + // In the case where it is not possible to delete the database file (e.g some other program + // like a virus scanner is accessing it), make sure to remove all entries. + openTrackerDatabase(SkipIfNonExistent); + if (!m_database.isOpen()) + return; + + SQLiteStatement deleteStatement(m_database, "DELETE FROM Origins"); + if (deleteStatement.prepare() != SQLResultOk) { + LOG_ERROR("Unable to prepare deletion of all origins"); + return; + } + if (!deleteStatement.executeCommand()) { + LOG_ERROR("Unable to execute deletion of all origins"); + return; + } + } + + deleteEmptyDirectory(m_localStorageDirectory); +} + +Vector<RefPtr<WebCore::SecurityOrigin>> LocalStorageDatabaseTracker::origins() const +{ + Vector<RefPtr<SecurityOrigin>> origins; + origins.reserveInitialCapacity(m_origins.size()); + + for (HashSet<String>::const_iterator it = m_origins.begin(), end = m_origins.end(); it != end; ++it) + origins.uncheckedAppend(SecurityOrigin::createFromDatabaseIdentifier(*it)); + + return origins; +} + +void LocalStorageDatabaseTracker::setLocalStorageDirectoryInternal(StringImpl* localStorageDirectory) +{ + if (m_database.isOpen()) + m_database.close(); + + m_localStorageDirectory = localStorageDirectory; + m_origins.clear(); + + m_queue->dispatch(bind(&LocalStorageDatabaseTracker::importOriginIdentifiers, this)); +} + +String LocalStorageDatabaseTracker::databasePath(const String& filename) const +{ + if (!makeAllDirectories(m_localStorageDirectory)) { + LOG_ERROR("Unabled to create LocalStorage database path %s", m_localStorageDirectory.utf8().data()); + return String(); + } + + return pathByAppendingComponent(m_localStorageDirectory, filename); +} + +String LocalStorageDatabaseTracker::trackerDatabasePath() const +{ + return databasePath("StorageTracker.db"); +} + +void LocalStorageDatabaseTracker::openTrackerDatabase(DatabaseOpeningStrategy openingStrategy) +{ + if (m_database.isOpen()) + return; + + String databasePath = trackerDatabasePath(); + + if (!fileExists(databasePath) && openingStrategy == SkipIfNonExistent) + return; + + if (!m_database.open(databasePath)) { + LOG_ERROR("Failed to open databasePath %s.", databasePath.ascii().data()); + return; + } + + // Since a WorkQueue isn't bound to a specific thread, we have to disable threading checks + // even though we never access the database from different threads simultaneously. + m_database.disableThreadingChecks(); + + if (m_database.tableExists("Origins")) + return; + + if (!m_database.executeCommand("CREATE TABLE Origins (origin TEXT UNIQUE ON CONFLICT REPLACE, path TEXT);")) + LOG_ERROR("Failed to create Origins table."); +} + +void LocalStorageDatabaseTracker::importOriginIdentifiers() +{ + openTrackerDatabase(SkipIfNonExistent); + + if (m_database.isOpen()) { + SQLiteStatement statement(m_database, "SELECT origin FROM Origins"); + if (statement.prepare() != SQLResultOk) { + LOG_ERROR("Failed to prepare statement."); + return; + } + + int result; + + while ((result = statement.step()) == SQLResultRow) + m_origins.add(statement.getColumnText(0)); + + if (result != SQLResultDone) { + LOG_ERROR("Failed to read in all origins from the database."); + return; + } + } + + updateTrackerDatabaseFromLocalStorageDatabaseFiles(); +} + +void LocalStorageDatabaseTracker::updateTrackerDatabaseFromLocalStorageDatabaseFiles() +{ + Vector<String> paths = listDirectory(m_localStorageDirectory, "*.localstorage"); + + HashSet<String> origins(m_origins); + HashSet<String> originsFromLocalStorageDatabaseFiles; + + for (size_t i = 0; i < paths.size(); ++i) { + const String& path = paths[i]; + + if (!path.endsWith(".localstorage")) + continue; + + String filename = pathGetFileName(path); + + String originIdentifier = filename.substring(0, filename.length() - strlen(".localstorage")); + + if (!m_origins.contains(originIdentifier)) + addDatabaseWithOriginIdentifier(originIdentifier, path); + + originsFromLocalStorageDatabaseFiles.add(originIdentifier); + } + + for (auto it = origins.begin(), end = origins.end(); it != end; ++it) { + const String& originIdentifier = *it; + if (origins.contains(originIdentifier)) + continue; + + removeDatabaseWithOriginIdentifier(originIdentifier); + } +} + +void LocalStorageDatabaseTracker::addDatabaseWithOriginIdentifier(const String& originIdentifier, const String& databasePath) +{ + openTrackerDatabase(CreateIfNonExistent); + if (!m_database.isOpen()) + return; + + SQLiteStatement statement(m_database, "INSERT INTO Origins VALUES (?, ?)"); + if (statement.prepare() != SQLResultOk) { + LOG_ERROR("Unable to establish origin '%s' in the tracker", originIdentifier.utf8().data()); + return; + } + + statement.bindText(1, originIdentifier); + statement.bindText(2, databasePath); + + if (statement.step() != SQLResultDone) + LOG_ERROR("Unable to establish origin '%s' in the tracker", originIdentifier.utf8().data()); + + m_origins.add(originIdentifier); + + // FIXME: Tell clients that the origin was added. +} + +void LocalStorageDatabaseTracker::removeDatabaseWithOriginIdentifier(const String& originIdentifier) +{ + openTrackerDatabase(SkipIfNonExistent); + if (!m_database.isOpen()) + return; + + String path = pathForDatabaseWithOriginIdentifier(originIdentifier); + if (path.isEmpty()) + return; + + SQLiteStatement deleteStatement(m_database, "DELETE FROM Origins where origin=?"); + if (deleteStatement.prepare() != SQLResultOk) { + LOG_ERROR("Unable to prepare deletion of origin '%s'", originIdentifier.ascii().data()); + return; + } + deleteStatement.bindText(1, originIdentifier); + if (!deleteStatement.executeCommand()) { + LOG_ERROR("Unable to execute deletion of origin '%s'", originIdentifier.ascii().data()); + return; + } + + deleteFile(path); + + m_origins.remove(originIdentifier); + if (m_origins.isEmpty()) { + // There are no origins left, go ahead and delete the tracker database. + m_database.close(); + deleteFile(trackerDatabasePath()); + deleteEmptyDirectory(m_localStorageDirectory); + } + + // FIXME: Tell clients that the origin was removed. +} + +String LocalStorageDatabaseTracker::pathForDatabaseWithOriginIdentifier(const String& originIdentifier) +{ + if (!m_database.isOpen()) + return String(); + + SQLiteStatement pathStatement(m_database, "SELECT path FROM Origins WHERE origin=?"); + if (pathStatement.prepare() != SQLResultOk) { + LOG_ERROR("Unable to prepare selection of path for origin '%s'", originIdentifier.utf8().data()); + return String(); + } + + pathStatement.bindText(1, originIdentifier); + + int result = pathStatement.step(); + if (result != SQLResultRow) + return String(); + + return pathStatement.getColumnText(0); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h new file mode 100644 index 000000000..e16428907 --- /dev/null +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LocalStorageDatabaseTracker_h +#define LocalStorageDatabaseTracker_h + +#include <WebCore/SQLiteDatabase.h> +#include <wtf/HashSet.h> +#include <wtf/PassRefPtr.h> +#include <wtf/RefPtr.h> +#include <wtf/ThreadSafeRefCounted.h> +#include <wtf/text/StringHash.h> +#include <wtf/text/WTFString.h> + +namespace WebCore { +class SecurityOrigin; +} + +class WorkQueue; + +namespace WebKit { + +class LocalStorageDatabaseTracker : public ThreadSafeRefCounted<LocalStorageDatabaseTracker> { +public: + static PassRefPtr<LocalStorageDatabaseTracker> create(PassRefPtr<WorkQueue>); + ~LocalStorageDatabaseTracker(); + + void setLocalStorageDirectory(const String&); + String databasePath(WebCore::SecurityOrigin*) const; + + void didOpenDatabaseWithOrigin(WebCore::SecurityOrigin*); + void deleteDatabaseWithOrigin(WebCore::SecurityOrigin*); + void deleteAllDatabases(); + + Vector<RefPtr<WebCore::SecurityOrigin>> origins() const; + +private: + explicit LocalStorageDatabaseTracker(PassRefPtr<WorkQueue>); + + void setLocalStorageDirectoryInternal(StringImpl*); + + String databasePath(const String& filename) const; + String trackerDatabasePath() const; + + enum DatabaseOpeningStrategy { + CreateIfNonExistent, + SkipIfNonExistent + }; + void openTrackerDatabase(DatabaseOpeningStrategy); + + void importOriginIdentifiers(); + void updateTrackerDatabaseFromLocalStorageDatabaseFiles(); + + void addDatabaseWithOriginIdentifier(const String& originIdentifier, const String& databasePath); + void removeDatabaseWithOriginIdentifier(const String& originIdentifier); + String pathForDatabaseWithOriginIdentifier(const String& originIdentifier); + + RefPtr<WorkQueue> m_queue; + String m_localStorageDirectory; + + WebCore::SQLiteDatabase m_database; + HashSet<String> m_origins; +}; + +} // namespace WebKit + +#endif // LocalStorageDatabaseTracker_h diff --git a/Source/WebKit2/UIProcess/Storage/StorageManager.cpp b/Source/WebKit2/UIProcess/Storage/StorageManager.cpp new file mode 100644 index 000000000..5350dde05 --- /dev/null +++ b/Source/WebKit2/UIProcess/Storage/StorageManager.cpp @@ -0,0 +1,655 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "StorageManager.h" + +#include "LocalStorageDatabase.h" +#include "LocalStorageDatabaseTracker.h" +#include "SecurityOriginData.h" +#include "StorageAreaMapMessages.h" +#include "StorageManagerMessages.h" +#include "WebProcessProxy.h" +#include "WorkQueue.h" +#include <WebCore/SecurityOriginHash.h> +#include <WebCore/StorageMap.h> +#include <WebCore/TextEncoding.h> + +using namespace WebCore; + +namespace WebKit { + +class StorageManager::StorageArea : public ThreadSafeRefCounted<StorageManager::StorageArea> { +public: + static PassRefPtr<StorageArea> create(LocalStorageNamespace*, PassRefPtr<SecurityOrigin>, unsigned quotaInBytes); + ~StorageArea(); + + SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); } + + void addListener(CoreIPC::Connection*, uint64_t storageMapID); + void removeListener(CoreIPC::Connection*, uint64_t storageMapID); + + PassRefPtr<StorageArea> clone() const; + + void setItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException); + void removeItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString); + void clear(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString); + + const HashMap<String, String>& items(); + void clear(); + +private: + explicit StorageArea(LocalStorageNamespace*, PassRefPtr<SecurityOrigin>, unsigned quotaInBytes); + + void openDatabaseAndImportItemsIfNeeded(); + + void dispatchEvents(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const; + + // Will be null if the storage area belongs to a session storage namespace. + LocalStorageNamespace* m_localStorageNamespace; + RefPtr<LocalStorageDatabase> m_localStorageDatabase; + bool m_didImportItemsFromDatabase; + + RefPtr<SecurityOrigin> m_securityOrigin; + unsigned m_quotaInBytes; + + RefPtr<StorageMap> m_storageMap; + HashSet<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>> m_eventListeners; +}; + +class StorageManager::LocalStorageNamespace : public ThreadSafeRefCounted<LocalStorageNamespace> { +public: + static PassRefPtr<LocalStorageNamespace> create(StorageManager*, uint64_t storageManagerID); + ~LocalStorageNamespace(); + + StorageManager* storageManager() const { return m_storageManager; } + + PassRefPtr<StorageArea> getOrCreateStorageArea(PassRefPtr<SecurityOrigin>); + void didDestroyStorageArea(StorageArea*); + + void clearStorageAreasMatchingOrigin(SecurityOrigin*); + void clearAllStorageAreas(); + +private: + explicit LocalStorageNamespace(StorageManager*, uint64_t storageManagerID); + + StorageManager* m_storageManager; + uint64_t m_storageNamespaceID; + unsigned m_quotaInBytes; + + // We don't hold an explicit reference to the StorageAreas; they are kept alive by the m_storageAreasByConnection map in StorageManager. + HashMap<RefPtr<SecurityOrigin>, StorageArea*> m_storageAreaMap; +}; + +PassRefPtr<StorageManager::StorageArea> StorageManager::StorageArea::create(LocalStorageNamespace* localStorageNamespace, PassRefPtr<SecurityOrigin> securityOrigin, unsigned quotaInBytes) +{ + return adoptRef(new StorageArea(localStorageNamespace, securityOrigin, quotaInBytes)); +} + +StorageManager::StorageArea::StorageArea(LocalStorageNamespace* localStorageNamespace, PassRefPtr<SecurityOrigin> securityOrigin, unsigned quotaInBytes) + : m_localStorageNamespace(localStorageNamespace) + , m_didImportItemsFromDatabase(false) + , m_securityOrigin(securityOrigin) + , m_quotaInBytes(quotaInBytes) + , m_storageMap(StorageMap::create(m_quotaInBytes)) +{ +} + +StorageManager::StorageArea::~StorageArea() +{ + ASSERT(m_eventListeners.isEmpty()); + + if (m_localStorageDatabase) + m_localStorageDatabase->close(); + + if (m_localStorageNamespace) + m_localStorageNamespace->didDestroyStorageArea(this); +} + +void StorageManager::StorageArea::addListener(CoreIPC::Connection* connection, uint64_t storageMapID) +{ + ASSERT(!m_eventListeners.contains(std::make_pair(connection, storageMapID))); + m_eventListeners.add(std::make_pair(connection, storageMapID)); +} + +void StorageManager::StorageArea::removeListener(CoreIPC::Connection* connection, uint64_t storageMapID) +{ + ASSERT(m_eventListeners.contains(std::make_pair(connection, storageMapID))); + m_eventListeners.remove(std::make_pair(connection, storageMapID)); +} + +PassRefPtr<StorageManager::StorageArea> StorageManager::StorageArea::clone() const +{ + ASSERT(!m_localStorageNamespace); + + RefPtr<StorageArea> storageArea = StorageArea::create(0, m_securityOrigin, m_quotaInBytes); + storageArea->m_storageMap = m_storageMap; + + return storageArea.release(); +} + +void StorageManager::StorageArea::setItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException) +{ + openDatabaseAndImportItemsIfNeeded(); + + String oldValue; + + RefPtr<StorageMap> newStorageMap = m_storageMap->setItem(key, value, oldValue, quotaException); + if (newStorageMap) + m_storageMap = newStorageMap.release(); + + if (quotaException) + return; + + if (m_localStorageDatabase) + m_localStorageDatabase->setItem(key, value); + + dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, value, urlString); +} + +void StorageManager::StorageArea::removeItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString) +{ + openDatabaseAndImportItemsIfNeeded(); + + String oldValue; + RefPtr<StorageMap> newStorageMap = m_storageMap->removeItem(key, oldValue); + if (newStorageMap) + m_storageMap = newStorageMap.release(); + + if (oldValue.isNull()) + return; + + if (m_localStorageDatabase) + m_localStorageDatabase->removeItem(key); + + dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, String(), urlString); +} + +void StorageManager::StorageArea::clear(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString) +{ + openDatabaseAndImportItemsIfNeeded(); + + if (!m_storageMap->length()) + return; + + m_storageMap = StorageMap::create(m_quotaInBytes); + + if (m_localStorageDatabase) + m_localStorageDatabase->clear(); + + dispatchEvents(sourceConnection, sourceStorageAreaID, String(), String(), String(), urlString); +} + +const HashMap<String, String>& StorageManager::StorageArea::items() +{ + openDatabaseAndImportItemsIfNeeded(); + + return m_storageMap->items(); +} + +void StorageManager::StorageArea::clear() +{ + m_storageMap = StorageMap::create(m_quotaInBytes); + + if (m_localStorageDatabase) { + m_localStorageDatabase->close(); + m_localStorageDatabase = nullptr; + } + + for (auto it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) + it->first->send(Messages::StorageAreaMap::ClearCache(), it->second); +} + +void StorageManager::StorageArea::openDatabaseAndImportItemsIfNeeded() +{ + if (!m_localStorageNamespace) + return; + + // We open the database here even if we've already imported our items to ensure that the database is open if we need to write to it. + if (!m_localStorageDatabase) + m_localStorageDatabase = LocalStorageDatabase::create(m_localStorageNamespace->storageManager()->m_queue, m_localStorageNamespace->storageManager()->m_localStorageDatabaseTracker, m_securityOrigin.get()); + + if (m_didImportItemsFromDatabase) + return; + + m_localStorageDatabase->importItems(*m_storageMap); + m_didImportItemsFromDatabase = true; +} + +void StorageManager::StorageArea::dispatchEvents(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const +{ + for (HashSet<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>>::const_iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) { + uint64_t storageAreaID = it->first == sourceConnection ? sourceStorageAreaID : 0; + + it->first->send(Messages::StorageAreaMap::DispatchStorageEvent(storageAreaID, key, oldValue, newValue, urlString), it->second); + } +} + +PassRefPtr<StorageManager::LocalStorageNamespace> StorageManager::LocalStorageNamespace::create(StorageManager* storageManager, uint64_t storageNamespaceID) +{ + return adoptRef(new LocalStorageNamespace(storageManager, storageNamespaceID)); +} + +// FIXME: The quota value is copied from GroupSettings.cpp. +// We should investigate a way to share it with WebCore. +StorageManager::LocalStorageNamespace::LocalStorageNamespace(StorageManager* storageManager, uint64_t storageNamespaceID) + : m_storageManager(storageManager) + , m_storageNamespaceID(storageNamespaceID) + , m_quotaInBytes(5 * 1024 * 1024) +{ +} + +StorageManager::LocalStorageNamespace::~LocalStorageNamespace() +{ + ASSERT(m_storageAreaMap.isEmpty()); +} + +PassRefPtr<StorageManager::StorageArea> StorageManager::LocalStorageNamespace::getOrCreateStorageArea(PassRefPtr<SecurityOrigin> securityOrigin) +{ + HashMap<RefPtr<SecurityOrigin>, StorageArea*>::AddResult result = m_storageAreaMap.add(securityOrigin, 0); + if (!result.isNewEntry) + return result.iterator->value; + + RefPtr<StorageArea> storageArea = StorageArea::create(this, result.iterator->key, m_quotaInBytes); + result.iterator->value = storageArea.get(); + + return storageArea.release(); +} + +void StorageManager::LocalStorageNamespace::didDestroyStorageArea(StorageArea* storageArea) +{ + ASSERT(m_storageAreaMap.contains(storageArea->securityOrigin())); + + m_storageAreaMap.remove(storageArea->securityOrigin()); + if (!m_storageAreaMap.isEmpty()) + return; + + ASSERT(m_storageManager->m_localStorageNamespaces.contains(m_storageNamespaceID)); + m_storageManager->m_localStorageNamespaces.remove(m_storageNamespaceID); +} + +void StorageManager::LocalStorageNamespace::clearStorageAreasMatchingOrigin(SecurityOrigin* securityOrigin) +{ + for (auto it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) { + if (it->key->equal(securityOrigin)) + it->value->clear(); + } +} + +void StorageManager::LocalStorageNamespace::clearAllStorageAreas() +{ + for (auto it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) + it->value->clear(); +} + +class StorageManager::SessionStorageNamespace : public ThreadSafeRefCounted<SessionStorageNamespace> { +public: + static PassRefPtr<SessionStorageNamespace> create(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + ~SessionStorageNamespace(); + + bool isEmpty() const { return m_storageAreaMap.isEmpty(); } + + CoreIPC::Connection* allowedConnection() const { return m_allowedConnection.get(); } + void setAllowedConnection(CoreIPC::Connection*); + + PassRefPtr<StorageArea> getOrCreateStorageArea(PassRefPtr<SecurityOrigin>); + + void cloneTo(SessionStorageNamespace& newSessionStorageNamespace); + +private: + SessionStorageNamespace(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + + RefPtr<CoreIPC::Connection> m_allowedConnection; + unsigned m_quotaInBytes; + + HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea>> m_storageAreaMap; +}; + +PassRefPtr<StorageManager::SessionStorageNamespace> StorageManager::SessionStorageNamespace::create(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) +{ + return adoptRef(new SessionStorageNamespace(allowedConnection, quotaInBytes)); +} + +StorageManager::SessionStorageNamespace::SessionStorageNamespace(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) + : m_allowedConnection(allowedConnection) + , m_quotaInBytes(quotaInBytes) +{ +} + +StorageManager::SessionStorageNamespace::~SessionStorageNamespace() +{ +} + +void StorageManager::SessionStorageNamespace::setAllowedConnection(CoreIPC::Connection* allowedConnection) +{ + ASSERT(!allowedConnection || !m_allowedConnection); + + m_allowedConnection = allowedConnection; +} + +PassRefPtr<StorageManager::StorageArea> StorageManager::SessionStorageNamespace::getOrCreateStorageArea(PassRefPtr<SecurityOrigin> securityOrigin) +{ + HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea>>::AddResult result = m_storageAreaMap.add(securityOrigin, 0); + if (result.isNewEntry) + result.iterator->value = StorageArea::create(0, result.iterator->key, m_quotaInBytes); + + return result.iterator->value; +} + +void StorageManager::SessionStorageNamespace::cloneTo(SessionStorageNamespace& newSessionStorageNamespace) +{ + ASSERT_UNUSED(newSessionStorageNamespace, newSessionStorageNamespace.isEmpty()); + + for (HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea>>::const_iterator it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) + newSessionStorageNamespace.m_storageAreaMap.add(it->key, it->value->clone()); +} + +PassRefPtr<StorageManager> StorageManager::create() +{ + return adoptRef(new StorageManager); +} + +StorageManager::StorageManager() + : m_queue(WorkQueue::create("com.apple.WebKit.StorageManager")) + , m_localStorageDatabaseTracker(LocalStorageDatabaseTracker::create(m_queue)) +{ + // Make sure the encoding is initialized before we start dispatching things to the queue. + UTF8Encoding(); +} + +StorageManager::~StorageManager() +{ +} + +void StorageManager::setLocalStorageDirectory(const String& localStorageDirectory) +{ + m_localStorageDatabaseTracker->setLocalStorageDirectory(localStorageDirectory); +} + +void StorageManager::createSessionStorageNamespace(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) +{ + m_queue->dispatch(bind(&StorageManager::createSessionStorageNamespaceInternal, this, storageNamespaceID, RefPtr<CoreIPC::Connection>(allowedConnection), quotaInBytes)); +} + +void StorageManager::destroySessionStorageNamespace(uint64_t storageNamespaceID) +{ + m_queue->dispatch(bind(&StorageManager::destroySessionStorageNamespaceInternal, this, storageNamespaceID)); +} + +void StorageManager::setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection) +{ + m_queue->dispatch(bind(&StorageManager::setAllowedSessionStorageNamespaceConnectionInternal, this, storageNamespaceID, RefPtr<CoreIPC::Connection>(allowedConnection))); +} + +void StorageManager::cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID) +{ + m_queue->dispatch(bind(&StorageManager::cloneSessionStorageNamespaceInternal, this, storageNamespaceID, newStorageNamespaceID)); +} + +void StorageManager::processWillOpenConnection(WebProcessProxy* webProcessProxy) +{ + webProcessProxy->connection()->addWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName(), m_queue.get(), this); +} + +void StorageManager::processWillCloseConnection(WebProcessProxy* webProcessProxy) +{ + webProcessProxy->connection()->removeWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName()); + + m_queue->dispatch(bind(&StorageManager::invalidateConnectionInternal, this, RefPtr<CoreIPC::Connection>(webProcessProxy->connection()))); +} + +void StorageManager::getOrigins(FunctionDispatcher* callbackDispatcher, void* context, void (*callback)(const Vector<RefPtr<WebCore::SecurityOrigin>>& securityOrigins, void* context)) +{ + m_queue->dispatch(bind(&StorageManager::getOriginsInternal, this, RefPtr<FunctionDispatcher>(callbackDispatcher), context, callback)); +} + +void StorageManager::deleteEntriesForOrigin(SecurityOrigin* securityOrigin) +{ + m_queue->dispatch(bind(&StorageManager::deleteEntriesForOriginInternal, this, RefPtr<SecurityOrigin>(securityOrigin))); +} + +void StorageManager::deleteAllEntries() +{ + m_queue->dispatch(bind(&StorageManager::deleteAllEntriesInternal, this)); +} + +void StorageManager::createLocalStorageMap(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& securityOriginData) +{ + std::pair<RefPtr<CoreIPC::Connection>, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); + + // FIXME: This should be a message check. + ASSERT((HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair))); + + HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, 0); + + // FIXME: These should be a message checks. + ASSERT(result.isNewEntry); + ASSERT((HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::isValidKey(storageNamespaceID))); + + LocalStorageNamespace* localStorageNamespace = getOrCreateLocalStorageNamespace(storageNamespaceID); + + // FIXME: This should be a message check. + ASSERT(localStorageNamespace); + + RefPtr<StorageArea> storageArea = localStorageNamespace->getOrCreateStorageArea(securityOriginData.securityOrigin()); + storageArea->addListener(connection, storageMapID); + + result.iterator->value = storageArea.release(); +} + +void StorageManager::createSessionStorageMap(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& securityOriginData) +{ + // FIXME: This should be a message check. + ASSERT((HashMap<uint64_t, RefPtr<SessionStorageNamespace>>::isValidKey(storageNamespaceID))); + SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); + if (!sessionStorageNamespace) { + // We're getting an incoming message from the web process that's for session storage for a web page + // that has already been closed, just ignore it. + return; + } + + std::pair<RefPtr<CoreIPC::Connection>, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); + + // FIXME: This should be a message check. + ASSERT((HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair))); + + HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, 0); + + // FIXME: This should be a message check. + ASSERT(result.isNewEntry); + + // FIXME: This should be a message check. + ASSERT(connection == sessionStorageNamespace->allowedConnection()); + + RefPtr<StorageArea> storageArea = sessionStorageNamespace->getOrCreateStorageArea(securityOriginData.securityOrigin()); + storageArea->addListener(connection, storageMapID); + + result.iterator->value = storageArea.release(); +} + +void StorageManager::destroyStorageMap(CoreIPC::Connection* connection, uint64_t storageMapID) +{ + std::pair<RefPtr<CoreIPC::Connection>, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); + + // FIXME: This should be a message check. + ASSERT((HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair))); + + HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::iterator it = m_storageAreasByConnection.find(connectionAndStorageMapIDPair); + if (it == m_storageAreasByConnection.end()) { + // The connection has been removed because the last page was closed. + return; + } + + it->value->removeListener(connection, storageMapID); + m_storageAreasByConnection.remove(connectionAndStorageMapIDPair); +} + +void StorageManager::getValues(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values) +{ + StorageArea* storageArea = findStorageArea(connection, storageMapID); + if (!storageArea) { + // This is a session storage area for a page that has already been closed. Ignore it. + return; + } + + values = storageArea->items(); + connection->send(Messages::StorageAreaMap::DidGetValues(storageMapSeed), storageMapID); +} + +void StorageManager::setItem(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString) +{ + StorageArea* storageArea = findStorageArea(connection, storageMapID); + if (!storageArea) { + // This is a session storage area for a page that has already been closed. Ignore it. + return; + } + + bool quotaError; + storageArea->setItem(connection, sourceStorageAreaID, key, value, urlString, quotaError); + connection->send(Messages::StorageAreaMap::DidSetItem(storageMapSeed, key, quotaError), storageMapID); +} + +void StorageManager::removeItem(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString) +{ + StorageArea* storageArea = findStorageArea(connection, storageMapID); + if (!storageArea) { + // This is a session storage area for a page that has already been closed. Ignore it. + return; + } + + storageArea->removeItem(connection, sourceStorageAreaID, key, urlString); + connection->send(Messages::StorageAreaMap::DidRemoveItem(storageMapSeed, key), storageMapID); +} + +void StorageManager::clear(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString) +{ + StorageArea* storageArea = findStorageArea(connection, storageMapID); + if (!storageArea) { + // This is a session storage area for a page that has already been closed. Ignore it. + return; + } + + storageArea->clear(connection, sourceStorageAreaID, urlString); + connection->send(Messages::StorageAreaMap::DidClear(storageMapSeed), storageMapID); +} + +void StorageManager::createSessionStorageNamespaceInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) +{ + ASSERT(!m_sessionStorageNamespaces.contains(storageNamespaceID)); + + m_sessionStorageNamespaces.set(storageNamespaceID, SessionStorageNamespace::create(allowedConnection, quotaInBytes)); +} + +void StorageManager::destroySessionStorageNamespaceInternal(uint64_t storageNamespaceID) +{ + ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); + m_sessionStorageNamespaces.remove(storageNamespaceID); +} + +void StorageManager::setAllowedSessionStorageNamespaceConnectionInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection) +{ + ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); + + m_sessionStorageNamespaces.get(storageNamespaceID)->setAllowedConnection(allowedConnection); +} + +void StorageManager::cloneSessionStorageNamespaceInternal(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID) +{ + SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); + ASSERT(sessionStorageNamespace); + + SessionStorageNamespace* newSessionStorageNamespace = m_sessionStorageNamespaces.get(newStorageNamespaceID); + ASSERT(newSessionStorageNamespace); + + sessionStorageNamespace->cloneTo(*newSessionStorageNamespace); +} + +void StorageManager::invalidateConnectionInternal(CoreIPC::Connection* connection) +{ + Vector<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; + HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>> storageAreasByConnection = m_storageAreasByConnection; + for (HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::const_iterator it = storageAreasByConnection.begin(), end = storageAreasByConnection.end(); it != end; ++it) { + if (it->key.first != connection) + continue; + + it->value->removeListener(it->key.first.get(), it->key.second); + connectionAndStorageMapIDPairsToRemove.append(it->key); + } + + for (size_t i = 0; i < connectionAndStorageMapIDPairsToRemove.size(); ++i) + m_storageAreasByConnection.remove(connectionAndStorageMapIDPairsToRemove[i]); +} + +StorageManager::StorageArea* StorageManager::findStorageArea(CoreIPC::Connection* connection, uint64_t storageMapID) const +{ + std::pair<CoreIPC::Connection*, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); + if (!HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair)) + return 0; + + return m_storageAreasByConnection.get(connectionAndStorageMapIDPair); +} + +StorageManager::LocalStorageNamespace* StorageManager::getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID) +{ + if (!HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::isValidKey(storageNamespaceID)) + return 0; + + HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::AddResult result = m_localStorageNamespaces.add(storageNamespaceID, 0); + if (result.isNewEntry) + result.iterator->value = LocalStorageNamespace::create(this, storageNamespaceID); + + return result.iterator->value.get(); +} + +static void callCallbackFunction(void* context, void (*callbackFunction)(const Vector<RefPtr<WebCore::SecurityOrigin>>& securityOrigins, void* context), Vector<RefPtr<WebCore::SecurityOrigin>>* securityOriginsPtr) +{ + OwnPtr<Vector<RefPtr<WebCore::SecurityOrigin>>> securityOrigins = adoptPtr(securityOriginsPtr); + callbackFunction(*securityOrigins, context); +} + +void StorageManager::getOriginsInternal(FunctionDispatcher* dispatcher, void* context, void (*callbackFunction)(const Vector<RefPtr<WebCore::SecurityOrigin>>& securityOrigins, void* context)) +{ + OwnPtr<Vector<RefPtr<WebCore::SecurityOrigin>>> securityOrigins = adoptPtr(new Vector<RefPtr<WebCore::SecurityOrigin>>(m_localStorageDatabaseTracker->origins())); + dispatcher->dispatch(bind(callCallbackFunction, context, callbackFunction, securityOrigins.leakPtr())); +} + +void StorageManager::deleteEntriesForOriginInternal(SecurityOrigin* securityOrigin) +{ + for (auto it = m_localStorageNamespaces.begin(), end = m_localStorageNamespaces.end(); it != end; ++it) + it->value->clearStorageAreasMatchingOrigin(securityOrigin); + + m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(securityOrigin); +} + +void StorageManager::deleteAllEntriesInternal() +{ + for (auto it = m_localStorageNamespaces.begin(), end = m_localStorageNamespaces.end(); it != end; ++it) + it->value->clearAllStorageAreas(); + + m_localStorageDatabaseTracker->deleteAllDatabases(); +} + + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Storage/StorageManager.h b/Source/WebKit2/UIProcess/Storage/StorageManager.h new file mode 100644 index 000000000..5fc5261e4 --- /dev/null +++ b/Source/WebKit2/UIProcess/Storage/StorageManager.h @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef StorageManager_h +#define StorageManager_h + +#include "Connection.h" +#include <wtf/Forward.h> +#include <wtf/PassRefPtr.h> +#include <wtf/ThreadSafeRefCounted.h> +#include <wtf/text/StringHash.h> + +class WorkQueue; + +namespace WebCore { +class SecurityOrigin; +} + +namespace WebKit { + +struct SecurityOriginData; +class LocalStorageDatabaseTracker; +class WebProcessProxy; + +class StorageManager : public CoreIPC::Connection::WorkQueueMessageReceiver { +public: + static PassRefPtr<StorageManager> create(); + ~StorageManager(); + + void setLocalStorageDirectory(const String&); + + void createSessionStorageNamespace(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + void destroySessionStorageNamespace(uint64_t storageNamespaceID); + void setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection); + void cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID); + + void processWillOpenConnection(WebProcessProxy*); + void processWillCloseConnection(WebProcessProxy*); + + // FIXME: Instead of a context + C function, this should take a WTF::Function, but we currently don't + // support arguments in functions. + void getOrigins(FunctionDispatcher* callbackDispatcher, void* context, void (*callback)(const Vector<RefPtr<WebCore::SecurityOrigin>>& securityOrigins, void* context)); + void deleteEntriesForOrigin(WebCore::SecurityOrigin*); + void deleteAllEntries(); + +private: + StorageManager(); + + // CoreIPC::Connection::WorkQueueMessageReceiver. + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) OVERRIDE; + + // Message handlers. + void createLocalStorageMap(CoreIPC::Connection*, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData&); + void createSessionStorageMap(CoreIPC::Connection*, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData&); + void destroyStorageMap(CoreIPC::Connection*, uint64_t storageMapID); + + void getValues(CoreIPC::Connection*, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values); + void setItem(CoreIPC::Connection*, uint64_t storageAreaID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString); + void removeItem(CoreIPC::Connection*, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString); + void clear(CoreIPC::Connection*, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString); + + void createSessionStorageNamespaceInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + void destroySessionStorageNamespaceInternal(uint64_t storageNamespaceID); + void setAllowedSessionStorageNamespaceConnectionInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection); + void cloneSessionStorageNamespaceInternal(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID); + + void invalidateConnectionInternal(CoreIPC::Connection*); + + class StorageArea; + StorageArea* findStorageArea(CoreIPC::Connection*, uint64_t) const; + + class LocalStorageNamespace; + LocalStorageNamespace* getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID); + + void getOriginsInternal(FunctionDispatcher* callbackDispatcher, void* context, void (*callback)(const Vector<RefPtr<WebCore::SecurityOrigin>>& securityOrigins, void* context)); + void deleteEntriesForOriginInternal(WebCore::SecurityOrigin*); + void deleteAllEntriesInternal(); + + RefPtr<WorkQueue> m_queue; + + RefPtr<LocalStorageDatabaseTracker> m_localStorageDatabaseTracker; + HashMap<uint64_t, RefPtr<LocalStorageNamespace>> m_localStorageNamespaces; + + class SessionStorageNamespace; + HashMap<uint64_t, RefPtr<SessionStorageNamespace>> m_sessionStorageNamespaces; + + HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea>> m_storageAreasByConnection; +}; + +} // namespace WebKit + +#endif // StorageManager_h diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.messages.in b/Source/WebKit2/UIProcess/Storage/StorageManager.messages.in index a06e92812..22d0121fe 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.messages.in +++ b/Source/WebKit2/UIProcess/Storage/StorageManager.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2011 Apple Inc. All rights reserved. +# Copyright (C) 2013 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -20,8 +20,14 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> WebNotificationManagerProxy { - Cancel(uint64_t notificationID); - DidDestroyNotification(uint64_t notificationID); - ClearNotifications(Vector<uint64_t> notificationIDs); +messages -> StorageManager { + CreateLocalStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, WebKit::SecurityOriginData securityOriginData) WantsConnection + CreateSessionStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, WebKit::SecurityOriginData securityOriginData) WantsConnection + DestroyStorageMap(uint64_t storageMapID) WantsConnection + + GetValues(uint64_t storageMapID, uint64_t storageMapSeed) -> (WTF::HashMap<WTF::String, WTF::String> values) WantsConnection + + SetItem(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, WTF::String key, WTF::String value, WTF::String urlString) WantsConnection + RemoveItem(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, WTF::String key, WTF::String urlString) WantsConnection + Clear(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, WTF::String urlString) WantsConnection } diff --git a/Source/WebKit2/UIProcess/TextChecker.h b/Source/WebKit2/UIProcess/TextChecker.h index 49b5a48c3..bd08d354d 100644 --- a/Source/WebKit2/UIProcess/TextChecker.h +++ b/Source/WebKit2/UIProcess/TextChecker.h @@ -26,6 +26,7 @@ #ifndef TextChecker_h #define TextChecker_h +#include "TextCheckerCompletion.h" #include <WebCore/EditorClient.h> #include <WebCore/TextCheckerClient.h> @@ -49,6 +50,11 @@ public: static void setAutomaticLinkDetectionEnabled(bool); static void setAutomaticTextReplacementEnabled(bool); + static void didChangeAutomaticTextReplacementEnabled(); + static void didChangeAutomaticSpellingCorrectionEnabled(); + static void didChangeAutomaticQuoteSubstitutionEnabled(); + static void didChangeAutomaticDashSubstitutionEnabled(); + static bool isSmartInsertDeleteEnabled(); static void setSmartInsertDeleteEnabled(bool); @@ -72,6 +78,7 @@ public: static void getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& context, Vector<String>& guesses); static void learnWord(int64_t spellDocumentTag, const String& word); static void ignoreWord(int64_t spellDocumentTag, const String& word); + static void requestCheckingOfString(PassRefPtr<TextCheckerCompletion>); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/TextCheckerCompletion.cpp b/Source/WebKit2/UIProcess/TextCheckerCompletion.cpp new file mode 100644 index 000000000..1dd42dee6 --- /dev/null +++ b/Source/WebKit2/UIProcess/TextCheckerCompletion.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2013 Samsung Electronics + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "TextCheckerCompletion.h" + +using namespace WebCore; + +namespace WebKit { + +PassRefPtr<TextCheckerCompletion> TextCheckerCompletion::create(uint64_t requestID, const TextCheckingRequestData& requestData, WebPageProxy* page) +{ + return adoptRef(new TextCheckerCompletion(requestID, requestData, page)); +} + +TextCheckerCompletion::TextCheckerCompletion(uint64_t requestID, const TextCheckingRequestData& requestData, WebPageProxy* page) + : m_requestID(requestID) + , m_requestData(requestData) + , m_page(page) +{ +} + +const TextCheckingRequestData& TextCheckerCompletion::textCheckingRequestData() const +{ + return m_requestData; +} + +int64_t TextCheckerCompletion::spellDocumentTag() +{ + return m_page->spellDocumentTag(); +} + +void TextCheckerCompletion::didFinishCheckingText(const Vector<TextCheckingResult>& result) const +{ + if (result.isEmpty()) + didCancelCheckingText(); + + m_page->didFinishCheckingText(m_requestID, result); +} + +void TextCheckerCompletion::didCancelCheckingText() const +{ + m_page->didCancelCheckingText(m_requestID); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/TextCheckerCompletion.h b/Source/WebKit2/UIProcess/TextCheckerCompletion.h new file mode 100644 index 000000000..425e7656f --- /dev/null +++ b/Source/WebKit2/UIProcess/TextCheckerCompletion.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2013 Samsung Electronics + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef TextCheckerCompletion_h +#define TextCheckerCompletion_h + +#include "WebPageProxy.h" +#include <WebCore/TextChecking.h> +#include <wtf/Vector.h> + +namespace WebKit { + +class TextCheckerCompletion : public RefCounted<TextCheckerCompletion> { +public: + static PassRefPtr<TextCheckerCompletion> create(uint64_t requestID, const WebCore::TextCheckingRequestData&, WebPageProxy*); + + const WebCore::TextCheckingRequestData& textCheckingRequestData() const; + int64_t spellDocumentTag(); + void didFinishCheckingText(const Vector<WebCore::TextCheckingResult>&) const; + void didCancelCheckingText() const; + +private: + TextCheckerCompletion(uint64_t requestID, const WebCore::TextCheckingRequestData&, WebPageProxy*); + + const uint64_t m_requestID; + const WebCore::TextCheckingRequestData m_requestData; + WebPageProxy* m_page; +}; + +} // namespace WebKit + +#endif // TextCheckerCompletion_h diff --git a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp index 474f06dac..494ca6bd7 100644 --- a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,22 +34,33 @@ namespace WebKit { +const char* WebApplicationCacheManagerProxy::supplementName() +{ + return "WebApplicationCacheManagerProxy"; +} + PassRefPtr<WebApplicationCacheManagerProxy> WebApplicationCacheManagerProxy::create(WebContext* context) { return adoptRef(new WebApplicationCacheManagerProxy(context)); } WebApplicationCacheManagerProxy::WebApplicationCacheManagerProxy(WebContext* context) - : m_webContext(context) + : WebContextSupplement(context) { - m_webContext->addMessageReceiver(Messages::WebApplicationCacheManagerProxy::messageReceiverName(), this); + context->addMessageReceiver(Messages::WebApplicationCacheManagerProxy::messageReceiverName(), this); } WebApplicationCacheManagerProxy::~WebApplicationCacheManagerProxy() { } -void WebApplicationCacheManagerProxy::invalidate() + +void WebApplicationCacheManagerProxy::contextDestroyed() +{ + invalidateCallbackMap(m_arrayCallbacks); +} + +void WebApplicationCacheManagerProxy::processDidClose(WebProcessProxy*) { invalidateCallbackMap(m_arrayCallbacks); } @@ -59,20 +70,28 @@ bool WebApplicationCacheManagerProxy::shouldTerminate(WebProcessProxy*) const return m_arrayCallbacks.isEmpty(); } -void WebApplicationCacheManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebApplicationCacheManagerProxy::refWebContextSupplement() +{ + APIObject::ref(); +} + +void WebApplicationCacheManagerProxy::derefWebContextSupplement() { - didReceiveWebApplicationCacheManagerProxyMessage(connection, messageID, decoder); + APIObject::deref(); } void WebApplicationCacheManagerProxy::getApplicationCacheOrigins(PassRefPtr<ArrayCallback> prpCallback) { + if (!context()) + return; + RefPtr<ArrayCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_arrayCallbacks.set(callbackID, callback.release()); // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::GetApplicationCacheOrigins(callbackID)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::GetApplicationCacheOrigins(callbackID)); } void WebApplicationCacheManagerProxy::didGetApplicationCacheOrigins(const Vector<SecurityOriginData>& originDatas, uint64_t callbackID) @@ -83,19 +102,25 @@ void WebApplicationCacheManagerProxy::didGetApplicationCacheOrigins(const Vector void WebApplicationCacheManagerProxy::deleteEntriesForOrigin(WebSecurityOrigin* origin) { + if (!context()) + return; + SecurityOriginData securityOriginData; securityOriginData.protocol = origin->protocol(); securityOriginData.host = origin->host(); securityOriginData.port = origin->port(); // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteEntriesForOrigin(securityOriginData)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteEntriesForOrigin(securityOriginData)); } void WebApplicationCacheManagerProxy::deleteAllEntries() { + if (!context()) + return; + // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteAllEntries()); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteAllEntries()); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h index 32538b3d3..f5f8ce1c4 100644 --- a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,53 +30,52 @@ #include "GenericCallback.h" #include "ImmutableArray.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/Vector.h> namespace CoreIPC { class Connection; - class MessageID; } namespace WebKit { -struct SecurityOriginData; -class WebContext; -class WebProcessProxy; class WebSecurityOrigin; +struct SecurityOriginData; typedef GenericCallback<WKArrayRef> ArrayCallback; -class WebApplicationCacheManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebApplicationCacheManagerProxy : public TypedAPIObject<APIObject::TypeApplicationCacheManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeApplicationCacheManager; + static const char* supplementName(); static PassRefPtr<WebApplicationCacheManagerProxy> create(WebContext*); virtual ~WebApplicationCacheManagerProxy(); - void invalidate(); - void clearContext() { m_webContext = 0; } - void getApplicationCacheOrigins(PassRefPtr<ArrayCallback>); void deleteEntriesForOrigin(WebSecurityOrigin*); void deleteAllEntries(); - bool shouldTerminate(WebProcessProxy*) const; + using APIObject::ref; + using APIObject::deref; private: explicit WebApplicationCacheManagerProxy(WebContext*); - virtual Type type() const { return APIType; } - void didGetApplicationCacheOrigins(const Vector<SecurityOriginData>&, uint64_t callbackID); + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; + // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebApplicationCacheManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebBackForwardList.cpp b/Source/WebKit2/UIProcess/WebBackForwardList.cpp index 763023d07..18c93ecd4 100644 --- a/Source/WebKit2/UIProcess/WebBackForwardList.cpp +++ b/Source/WebKit2/UIProcess/WebBackForwardList.cpp @@ -74,7 +74,7 @@ void WebBackForwardList::addItem(WebBackForwardListItem* newItem) if (!m_capacity || !newItem || !m_page) return; - Vector<RefPtr<APIObject> > removedItems; + Vector<RefPtr<APIObject>> removedItems; if (m_hasCurrentIndex) { // Toss everything in the forward list. @@ -212,7 +212,7 @@ PassRefPtr<ImmutableArray> WebBackForwardList::backListAsImmutableArrayWithLimit if (!size) return ImmutableArray::create(); - Vector<RefPtr<APIObject> > vector; + Vector<RefPtr<APIObject>> vector; vector.reserveInitialCapacity(size); ASSERT(backListSize >= size); @@ -235,7 +235,7 @@ PassRefPtr<ImmutableArray> WebBackForwardList::forwardListAsImmutableArrayWithLi if (!size) return ImmutableArray::create(); - Vector<RefPtr<APIObject> > vector; + Vector<RefPtr<APIObject>> vector; vector.reserveInitialCapacity(size); unsigned last = m_currentIndex + size; @@ -257,7 +257,7 @@ void WebBackForwardList::clear() return; RefPtr<WebBackForwardListItem> currentItem = this->currentItem(); - Vector<RefPtr<APIObject> > removedItems; + Vector<RefPtr<APIObject>> removedItems; if (!currentItem) { // We should only ever have no current item if we also have no current item index. diff --git a/Source/WebKit2/UIProcess/WebBackForwardList.h b/Source/WebKit2/UIProcess/WebBackForwardList.h index b6de90b03..0525d5826 100644 --- a/Source/WebKit2/UIProcess/WebBackForwardList.h +++ b/Source/WebKit2/UIProcess/WebBackForwardList.h @@ -39,7 +39,7 @@ namespace WebKit { -typedef Vector<RefPtr<WebBackForwardListItem> > BackForwardListItemVector; +typedef Vector<RefPtr<WebBackForwardListItem>> BackForwardListItemVector; /* * Current @@ -47,10 +47,8 @@ typedef Vector<RefPtr<WebBackForwardListItem> > BackForwardListItemVector; * Back Forward */ -class WebBackForwardList : public APIObject { +class WebBackForwardList : public TypedAPIObject<APIObject::TypeBackForwardList> { public: - static const Type APIType = TypeBackForwardList; - static PassRefPtr<WebBackForwardList> create(WebPageProxy* page) { return adoptRef(new WebBackForwardList(page)); @@ -87,8 +85,6 @@ public: private: explicit WebBackForwardList(WebPageProxy*); - virtual Type type() const { return APIType; } - WebPageProxy* m_page; BackForwardListItemVector m_entries; diff --git a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp index 01eb98052..43e54f796 100644 --- a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp @@ -34,35 +34,69 @@ namespace WebKit { +const char* WebBatteryManagerProxy::supplementName() +{ + return "WebBatteryManagerProxy"; +} + PassRefPtr<WebBatteryManagerProxy> WebBatteryManagerProxy::create(WebContext* context) { return adoptRef(new WebBatteryManagerProxy(context)); } WebBatteryManagerProxy::WebBatteryManagerProxy(WebContext* context) - : m_isUpdating(false) - , m_context(context) + : WebContextSupplement(context) + , m_isUpdating(false) { - m_context->addMessageReceiver(Messages::WebBatteryManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebBatteryManagerProxy::messageReceiverName(), this); } WebBatteryManagerProxy::~WebBatteryManagerProxy() { } -void WebBatteryManagerProxy::invalidate() +void WebBatteryManagerProxy::initializeProvider(const WKBatteryProvider* provider) +{ + m_provider.initialize(provider); +} + + +void WebBatteryManagerProxy::providerDidChangeBatteryStatus(const WTF::AtomicString& eventType, WebBatteryStatus* status) +{ + if (!context()) + return; + + context()->sendToAllProcesses(Messages::WebBatteryManager::DidChangeBatteryStatus(eventType, status->data())); +} + +void WebBatteryManagerProxy::providerUpdateBatteryStatus(WebBatteryStatus* status) +{ + if (!context()) + return; + + context()->sendToAllProcesses(Messages::WebBatteryManager::UpdateBatteryStatus(status->data())); +} + +// WebContextSupplement + +void WebBatteryManagerProxy::contextDestroyed() +{ + stopUpdating(); +} + +void WebBatteryManagerProxy::processDidClose(WebProcessProxy*) { stopUpdating(); } -void WebBatteryManagerProxy::initializeProvider(const WKBatteryProvider* provider) +void WebBatteryManagerProxy::refWebContextSupplement() { - m_provider.initialize(provider); + APIObject::ref(); } -void WebBatteryManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebBatteryManagerProxy::derefWebContextSupplement() { - didReceiveWebBatteryManagerProxyMessage(connection, messageID, decoder); + APIObject::deref(); } void WebBatteryManagerProxy::startUpdating() @@ -83,22 +117,6 @@ void WebBatteryManagerProxy::stopUpdating() m_isUpdating = false; } -void WebBatteryManagerProxy::providerDidChangeBatteryStatus(const WTF::AtomicString& eventType, WebBatteryStatus* status) -{ - if (!m_context) - return; - - m_context->sendToAllProcesses(Messages::WebBatteryManager::DidChangeBatteryStatus(eventType, status->data())); -} - -void WebBatteryManagerProxy::providerUpdateBatteryStatus(WebBatteryStatus* status) -{ - if (!m_context) - return; - - m_context->sendToAllProcesses(Messages::WebBatteryManager::UpdateBatteryStatus(status->data())); -} - } // namespace WebKit #endif // ENABLE(BATTERY_STATUS) diff --git a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h index 83e2128ac..cbaed1050 100644 --- a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h @@ -31,45 +31,46 @@ #include "APIObject.h" #include "MessageReceiver.h" #include "WebBatteryProvider.h" +#include "WebContextSupplement.h" #include <wtf/Forward.h> namespace WebKit { class WebContext; class WebBatteryStatus; -class WebBatteryManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebBatteryManagerProxy : public TypedAPIObject<APIObject::TypeBatteryManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeBatteryManager; + static const char* supplementName(); static PassRefPtr<WebBatteryManagerProxy> create(WebContext*); virtual ~WebBatteryManagerProxy(); - void invalidate(); - void clearContext() { m_context = 0; } - void initializeProvider(const WKBatteryProvider*); void providerDidChangeBatteryStatus(const WTF::AtomicString&, WebBatteryStatus*); void providerUpdateBatteryStatus(WebBatteryStatus*); + using APIObject::ref; + using APIObject::deref; + private: explicit WebBatteryManagerProxy(WebContext*); - virtual Type type() const { return APIType; } + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - - // Implemented in generated WebBatteryManagerProxyMessageReceiver.cpp - void didReceiveWebBatteryManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; void startUpdating(); void stopUpdating(); bool m_isUpdating; - WebContext* m_context; WebBatteryProvider m_provider; }; diff --git a/Source/WebKit2/UIProcess/WebColorChooserProxy.cpp b/Source/WebKit2/UIProcess/WebColorPicker.cpp index 7554047ac..3487da97f 100644 --- a/Source/WebKit2/UIProcess/WebColorChooserProxy.cpp +++ b/Source/WebKit2/UIProcess/WebColorPicker.cpp @@ -24,22 +24,22 @@ */ #include "config.h" -#include "WebColorChooserProxy.h" +#include "WebColorPicker.h" #if ENABLE(INPUT_TYPE_COLOR) namespace WebKit { -WebColorChooserProxy::WebColorChooserProxy(Client* client) +WebColorPicker::WebColorPicker(Client* client) : m_client(client) { } -WebColorChooserProxy::~WebColorChooserProxy() +WebColorPicker::~WebColorPicker() { } -void WebColorChooserProxy::endChooser() +void WebColorPicker::endChooser() { if (!m_client) return; @@ -47,7 +47,7 @@ void WebColorChooserProxy::endChooser() m_client->didEndColorChooser(); } -void WebColorChooserProxy::setSelectedColor(const WebCore::Color& color) +void WebColorPicker::setSelectedColor(const WebCore::Color& color) { if (!m_client) return; diff --git a/Source/WebKit2/UIProcess/WebColorChooserProxy.h b/Source/WebKit2/UIProcess/WebColorPicker.h index 5da4cc781..bd886475b 100644 --- a/Source/WebKit2/UIProcess/WebColorChooserProxy.h +++ b/Source/WebKit2/UIProcess/WebColorPicker.h @@ -23,8 +23,8 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebColorChooserProxy_h -#define WebColorChooserProxy_h +#ifndef WebColorPicker_h +#define WebColorPicker_h #if ENABLE(INPUT_TYPE_COLOR) @@ -39,7 +39,7 @@ namespace WebKit { class WebPageProxy; -class WebColorChooserProxy : public RefCounted<WebColorChooserProxy> { +class WebColorPicker : public RefCounted<WebColorPicker> { public: class Client { protected: @@ -50,12 +50,12 @@ public: virtual void didEndColorChooser() = 0; }; - static PassRefPtr<WebColorChooserProxy> create(Client* client) + static PassRefPtr<WebColorPicker> create(Client* client) { - return adoptRef(new WebColorChooserProxy(client)); + return adoptRef(new WebColorPicker(client)); } - virtual ~WebColorChooserProxy(); + virtual ~WebColorPicker(); void invalidate() { m_client = 0; } @@ -63,7 +63,7 @@ public: virtual void setSelectedColor(const WebCore::Color&); protected: - explicit WebColorChooserProxy(Client*); + explicit WebColorPicker(Client*); Client* m_client; }; @@ -72,4 +72,4 @@ protected: #endif // ENABLE(INPUT_TYPE_COLOR) -#endif // WebColorChooserProxy_h +#endif // WebColorPicker_h diff --git a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp index eb6d5efa2..c2c6e2455 100644 --- a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp +++ b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp @@ -61,19 +61,19 @@ bool WebConnectionToWebProcess::decodeMessageBody(CoreIPC::ArgumentDecoder& deco return decoder.decode(messageBodyDecoder); } -CoreIPC::Connection* WebConnectionToWebProcess::connection() const +bool WebConnectionToWebProcess::hasValidConnection() const { - return m_process->connection(); + return m_process; } -uint64_t WebConnectionToWebProcess::destinationID() const +CoreIPC::Connection* WebConnectionToWebProcess::messageSenderConnection() { - return 0; + return m_process->connection(); } -bool WebConnectionToWebProcess::hasValidConnection() const +uint64_t WebConnectionToWebProcess::messageSenderDestinationID() { - return m_process; + return 0; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h index 44d107ea7..5717f4625 100644 --- a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h +++ b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h @@ -46,10 +46,12 @@ private: // WebConnection virtual void encodeMessageBody(CoreIPC::ArgumentEncoder&, APIObject*) OVERRIDE; virtual bool decodeMessageBody(CoreIPC::ArgumentDecoder&, RefPtr<APIObject>&) OVERRIDE; - virtual CoreIPC::Connection* connection() const OVERRIDE; - virtual uint64_t destinationID() const OVERRIDE; virtual bool hasValidConnection() const OVERRIDE; + // CoreIPC::MessageSender + virtual CoreIPC::Connection* messageSenderConnection() OVERRIDE; + virtual uint64_t messageSenderDestinationID() OVERRIDE; + WebProcessProxy* m_process; }; diff --git a/Source/WebKit2/UIProcess/WebContext.cpp b/Source/WebKit2/UIProcess/WebContext.cpp index 3f818d1c1..e1ef1021d 100644 --- a/Source/WebKit2/UIProcess/WebContext.cpp +++ b/Source/WebKit2/UIProcess/WebContext.cpp @@ -38,28 +38,31 @@ #include "WebApplicationCacheManagerProxy.h" #include "WebContextMessageKinds.h" #include "WebContextMessages.h" +#include "WebContextSupplement.h" #include "WebContextUserMessageCoders.h" #include "WebCookieManagerProxy.h" #include "WebCoreArgumentCoders.h" #include "WebDatabaseManagerProxy.h" #include "WebGeolocationManagerProxy.h" #include "WebIconDatabase.h" -#include "WebKeyValueStorageManagerProxy.h" +#include "WebKeyValueStorageManager.h" #include "WebMediaCacheManagerProxy.h" #include "WebNotificationManagerProxy.h" #include "WebPluginSiteDataManager.h" #include "WebPageGroup.h" +#include "WebPreferences.h" #include "WebMemorySampler.h" #include "WebProcessCreationParameters.h" #include "WebProcessMessages.h" #include "WebProcessProxy.h" #include "WebResourceCacheManagerProxy.h" +#include <WebCore/InitializeLogging.h> #include <WebCore/Language.h> #include <WebCore/LinkHash.h> -#include <WebCore/Logging.h> #include <WebCore/ResourceRequest.h> #include <WebCore/RunLoop.h> #include <runtime/InitializeThreading.h> +#include <runtime/Operations.h> #include <wtf/CurrentTime.h> #include <wtf/MainThread.h> @@ -72,7 +75,13 @@ #endif #if ENABLE(NETWORK_PROCESS) -#include "NetworkProcessManager.h" +#include "NetworkProcessCreationParameters.h" +#include "NetworkProcessMessages.h" +#include "NetworkProcessProxy.h" +#endif + +#if ENABLE(CUSTOM_PROTOCOLS) +#include "CustomProtocolManagerMessages.h" #endif #if USE(SOUP) @@ -96,9 +105,6 @@ PassRefPtr<WebContext> WebContext::create(const String& injectedBundlePath) JSC::initializeThreading(); WTF::initializeMainThread(); RunLoop::initializeMainRunLoop(); -#if PLATFORM(MAC) - WebContext::initializeProcessSuppressionSupport(); -#endif return adoptRef(new WebContext(ProcessModelSharedSecondaryProcess, injectedBundlePath)); } @@ -116,54 +122,62 @@ const Vector<WebContext*>& WebContext::allContexts() WebContext::WebContext(ProcessModel processModel, const String& injectedBundlePath) : m_processModel(processModel) + , m_webProcessCountLimit(UINT_MAX) , m_haveInitialEmptyProcess(false) + , m_processWithPageCache(0) , m_defaultPageGroup(WebPageGroup::create()) , m_injectedBundlePath(injectedBundlePath) , m_visitedLinkProvider(this) + , m_plugInAutoStartProvider(this) , m_alwaysUsesComplexTextCodePath(false) , m_shouldUseFontSmoothing(true) , m_cacheModel(CacheModelDocumentViewer) , m_memorySamplerEnabled(false) , m_memorySamplerInterval(1400.0) -#if PLATFORM(WIN) - , m_shouldPaintNativeControls(true) - , m_initialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyAlways) + , m_storageManager(StorageManager::create()) +#if USE(SOUP) + , m_initialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) #endif , m_processTerminationEnabled(true) #if ENABLE(NETWORK_PROCESS) , m_usesNetworkProcess(false) #endif +#if PLATFORM(MAC) + , m_processSuppressionEnabled(true) +#endif +#if USE(SOUP) + , m_ignoreTLSErrors(true) +#endif { + platformInitialize(); + addMessageReceiver(Messages::WebContext::messageReceiverName(), this); - addMessageReceiver(CoreIPC::MessageKindTraits<WebContextLegacyMessage::Kind>::messageReceiverName(), this); + addMessageReceiver(WebContextLegacyMessages::messageReceiverName(), this); // NOTE: These sub-objects must be initialized after m_messageReceiverMap.. - m_applicationCacheManagerProxy = WebApplicationCacheManagerProxy::create(this); -#if ENABLE(BATTERY_STATUS) - m_batteryManagerProxy = WebBatteryManagerProxy::create(this); -#endif - m_cookieManagerProxy = WebCookieManagerProxy::create(this); -#if ENABLE(SQL_DATABASE) - m_databaseManagerProxy = WebDatabaseManagerProxy::create(this); -#endif - m_geolocationManagerProxy = WebGeolocationManagerProxy::create(this); m_iconDatabase = WebIconDatabase::create(this); - m_keyValueStorageManagerProxy = WebKeyValueStorageManagerProxy::create(this); - m_mediaCacheManagerProxy = WebMediaCacheManagerProxy::create(this); -#if ENABLE(NETWORK_INFO) - m_networkInfoManagerProxy = WebNetworkInfoManagerProxy::create(this); -#endif - m_notificationManagerProxy = WebNotificationManagerProxy::create(this); #if ENABLE(NETSCAPE_PLUGIN_API) m_pluginSiteDataManager = WebPluginSiteDataManager::create(this); #endif // ENABLE(NETSCAPE_PLUGIN_API) - m_resourceCacheManagerProxy = WebResourceCacheManagerProxy::create(this); + + addSupplement<WebApplicationCacheManagerProxy>(); + addSupplement<WebCookieManagerProxy>(); + addSupplement<WebGeolocationManagerProxy>(); + addSupplement<WebKeyValueStorageManager>(); + addSupplement<WebMediaCacheManagerProxy>(); + addSupplement<WebNotificationManagerProxy>(); + addSupplement<WebResourceCacheManagerProxy>(); +#if ENABLE(SQL_DATABASE) + addSupplement<WebDatabaseManagerProxy>(); +#endif #if USE(SOUP) - m_soupRequestManagerProxy = WebSoupRequestManagerProxy::create(this); + addSupplement<WebSoupRequestManagerProxy>(); #endif - -#if !LOG_DISABLED - WebKit::initializeLogChannelsIfNecessary(); +#if ENABLE(BATTERY_STATUS) + addSupplement<WebBatteryManagerProxy>(); +#endif +#if ENABLE(NETWORK_INFO) + addSupplement<WebNetworkInfoManagerProxy>(); #endif contexts().append(this); @@ -172,13 +186,26 @@ WebContext::WebContext(ProcessModel processModel, const String& injectedBundlePa #if !LOG_DISABLED WebCore::initializeLoggingChannelsIfNecessary(); + WebKit::initializeLogChannelsIfNecessary(); #endif // !LOG_DISABLED +#if ENABLE(NETSCAPE_PLUGIN_API) + m_pluginInfoStore.setClient(this); +#endif + #ifndef NDEBUG webContextCounter.increment(); #endif + + m_storageManager->setLocalStorageDirectory(localStorageDirectory()); } +#if !PLATFORM(MAC) +void WebContext::platformInitialize() +{ +} +#endif + WebContext::~WebContext() { ASSERT(contexts().find(this) != notFound); @@ -188,64 +215,39 @@ WebContext::~WebContext() m_messageReceiverMap.invalidate(); - m_applicationCacheManagerProxy->invalidate(); - m_applicationCacheManagerProxy->clearContext(); - -#if ENABLE(BATTERY_STATUS) - m_batteryManagerProxy->invalidate(); - m_batteryManagerProxy->clearContext(); -#endif - - m_cookieManagerProxy->invalidate(); - m_cookieManagerProxy->clearContext(); - -#if ENABLE(SQL_DATABASE) - m_databaseManagerProxy->invalidate(); - m_databaseManagerProxy->clearContext(); -#endif - - m_geolocationManagerProxy->invalidate(); - m_geolocationManagerProxy->clearContext(); + WebContextSupplementMap::const_iterator it = m_supplements.begin(); + WebContextSupplementMap::const_iterator end = m_supplements.end(); + for (; it != end; ++it) { + it->value->contextDestroyed(); + it->value->clearContext(); + } m_iconDatabase->invalidate(); m_iconDatabase->clearContext(); - m_keyValueStorageManagerProxy->invalidate(); - m_keyValueStorageManagerProxy->clearContext(); - - m_mediaCacheManagerProxy->invalidate(); - m_mediaCacheManagerProxy->clearContext(); - -#if ENABLE(NETWORK_INFO) - m_networkInfoManagerProxy->invalidate(); - m_networkInfoManagerProxy->clearContext(); -#endif - - m_notificationManagerProxy->invalidate(); - m_notificationManagerProxy->clearContext(); - #if ENABLE(NETSCAPE_PLUGIN_API) m_pluginSiteDataManager->invalidate(); m_pluginSiteDataManager->clearContext(); #endif - m_resourceCacheManagerProxy->invalidate(); - m_resourceCacheManagerProxy->clearContext(); - -#if USE(SOUP) - m_soupRequestManagerProxy->invalidate(); - m_soupRequestManagerProxy->clearContext(); -#endif - invalidateCallbackMap(m_dictionaryCallbacks); platformInvalidateContext(); - + +#if ENABLE(NETSCAPE_PLUGIN_API) + m_pluginInfoStore.setClient(0); +#endif + #ifndef NDEBUG webContextCounter.decrement(); #endif } +void WebContext::initializeClient(const WKContextClient* client) +{ + m_client.initialize(client); +} + void WebContext::initializeInjectedBundleClient(const WKContextInjectedBundleClient* client) { m_injectedBundleClient.initialize(client); @@ -285,12 +287,37 @@ void WebContext::setProcessModel(ProcessModel processModel) m_processModel = processModel; } -WebProcessProxy* WebContext::deprecatedSharedProcess() +void WebContext::setMaximumNumberOfProcesses(unsigned maximumNumberOfProcesses) { - ASSERT(m_processModel == ProcessModelSharedSecondaryProcess); - if (m_processes.isEmpty()) - return 0; - return m_processes[0].get(); + // Guard against API misuse. + if (!m_processes.isEmpty()) + CRASH(); + + if (maximumNumberOfProcesses == 0) + m_webProcessCountLimit = UINT_MAX; + else + m_webProcessCountLimit = maximumNumberOfProcesses; +} + +CoreIPC::Connection* WebContext::networkingProcessConnection() +{ + switch (m_processModel) { + case ProcessModelSharedSecondaryProcess: +#if ENABLE(NETWORK_PROCESS) + if (m_usesNetworkProcess) + return m_networkProcess->connection(); +#endif + return m_processes[0]->connection(); + case ProcessModelMultipleSecondaryProcesses: +#if ENABLE(NETWORK_PROCESS) + ASSERT(m_usesNetworkProcess); + return m_networkProcess->connection(); +#else + break; +#endif + } + ASSERT_NOT_REACHED(); + return 0; } void WebContext::languageChanged(void* context) @@ -322,6 +349,119 @@ void WebContext::setUsesNetworkProcess(bool usesNetworkProcess) #endif } +bool WebContext::usesNetworkProcess() const +{ +#if ENABLE(NETWORK_PROCESS) + return m_usesNetworkProcess; +#else + return false; +#endif +} + +#if ENABLE(NETWORK_PROCESS) +void WebContext::ensureNetworkProcess() +{ + if (m_networkProcess) + return; + + m_networkProcess = NetworkProcessProxy::create(this); + + NetworkProcessCreationParameters parameters; + + parameters.diskCacheDirectory = diskCacheDirectory(); + if (!parameters.diskCacheDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(parameters.diskCacheDirectory, parameters.diskCacheDirectoryExtensionHandle); + + parameters.privateBrowsingEnabled = WebPreferences::anyPageGroupsAreUsingPrivateBrowsing(); + + parameters.cacheModel = m_cacheModel; + + // Add any platform specific parameters + platformInitializeNetworkProcess(parameters); + + // Initialize the network process. + m_networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0); +} + +void WebContext::networkProcessCrashed(NetworkProcessProxy* networkProcessProxy) +{ + ASSERT(m_networkProcess); + ASSERT(networkProcessProxy == m_networkProcess.get()); + + WebContextSupplementMap::const_iterator it = m_supplements.begin(); + WebContextSupplementMap::const_iterator end = m_supplements.end(); + for (; it != end; ++it) + it->value->processDidClose(networkProcessProxy); + + m_networkProcess = nullptr; + + m_client.networkProcessDidCrash(this); +} + +void WebContext::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) +{ + ASSERT(reply); + + ensureNetworkProcess(); + ASSERT(m_networkProcess); + + m_networkProcess->getNetworkProcessConnection(reply); +} +#endif + + +void WebContext::willStartUsingPrivateBrowsing() +{ + const Vector<WebContext*>& contexts = allContexts(); + for (size_t i = 0, count = contexts.size(); i < count; ++i) { +#if ENABLE(NETWORK_PROCESS) + if (contexts[i]->usesNetworkProcess() && contexts[i]->networkProcess()) + contexts[i]->networkProcess()->send(Messages::NetworkProcess::EnsurePrivateBrowsingSession(), 0); +#endif + contexts[i]->sendToAllProcesses(Messages::WebProcess::EnsurePrivateBrowsingSession()); + } +} + +void WebContext::willStopUsingPrivateBrowsing() +{ + const Vector<WebContext*>& contexts = allContexts(); + for (size_t i = 0, count = contexts.size(); i < count; ++i) { +#if ENABLE(NETWORK_PROCESS) + if (contexts[i]->usesNetworkProcess() && contexts[i]->networkProcess()) + contexts[i]->networkProcess()->send(Messages::NetworkProcess::DestroyPrivateBrowsingSession(), 0); +#endif + + contexts[i]->sendToAllProcesses(Messages::WebProcess::DestroyPrivateBrowsingSession()); + } +} + +void (*s_invalidMessageCallback)(WKStringRef messageName); + +void WebContext::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName)) +{ + s_invalidMessageCallback = invalidMessageCallback; +} + +void WebContext::didReceiveInvalidMessage(const CoreIPC::StringReference& messageReceiverName, const CoreIPC::StringReference& messageName) +{ + if (!s_invalidMessageCallback) + return; + + StringBuilder messageNameStringBuilder; + messageNameStringBuilder.append(messageReceiverName.data(), messageReceiverName.size()); + messageNameStringBuilder.append("."); + messageNameStringBuilder.append(messageName.data(), messageName.size()); + + s_invalidMessageCallback(toAPI(WebString::create(messageNameStringBuilder.toString()).get())); +} + +void WebContext::processDidCachePage(WebProcessProxy* process) +{ + if (m_processWithPageCache && m_processWithPageCache != process) + m_processWithPageCache->releasePageCache(); + m_processWithPageCache = process; +} + WebProcessProxy* WebContext::ensureSharedWebProcess() { ASSERT(m_processModel == ProcessModelSharedSecondaryProcess); @@ -330,11 +470,11 @@ WebProcessProxy* WebContext::ensureSharedWebProcess() return m_processes[0].get(); } -PassRefPtr<WebProcessProxy> WebContext::createNewWebProcess() +WebProcessProxy* WebContext::createNewWebProcess() { #if ENABLE(NETWORK_PROCESS) if (m_usesNetworkProcess) - NetworkProcessManager::shared().ensureNetworkProcess(); + ensureNetworkProcess(); #endif RefPtr<WebProcessProxy> process = WebProcessProxy::create(this); @@ -363,7 +503,7 @@ PassRefPtr<WebProcessProxy> WebContext::createNewWebProcess() parameters.cookieStorageDirectory = cookieStorageDirectory(); if (!parameters.cookieStorageDirectory.isEmpty()) - SandboxExtension::createHandle(parameters.cookieStorageDirectory, SandboxExtension::ReadWrite, parameters.cookieStorageDirectoryExtensionHandle); + SandboxExtension::createHandleForReadWriteDirectory(parameters.cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle); parameters.shouldTrackVisitedLinks = m_historyClient.shouldTrackVisitedLinks(); parameters.cacheModel = m_cacheModel; @@ -391,13 +531,17 @@ PassRefPtr<WebProcessProxy> WebContext::createNewWebProcess() parameters.defaultRequestTimeoutInterval = WebURLRequest::defaultTimeoutInterval(); #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) - m_notificationManagerProxy->populateCopyOfNotificationPermissions(parameters.notificationPermissions); + // FIXME: There should be a generic way for supplements to add to the intialization parameters. + supplement<WebNotificationManagerProxy>()->populateCopyOfNotificationPermissions(parameters.notificationPermissions); #endif #if ENABLE(NETWORK_PROCESS) parameters.usesNetworkProcess = m_usesNetworkProcess; #endif + parameters.plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy(); + copyToVector(m_plugInAutoStartProvider.autoStartOrigins(), parameters.plugInAutoStartOrigins); + // Add any platform specific parameters platformInitializeWebProcess(parameters); @@ -406,11 +550,14 @@ PassRefPtr<WebProcessProxy> WebContext::createNewWebProcess() injectedBundleInitializationUserData = m_injectedBundleInitializationUserData; process->send(Messages::WebProcess::InitializeWebProcess(parameters, WebContextUserMessageEncoder(injectedBundleInitializationUserData.get())), 0); + if (WebPreferences::anyPageGroupsAreUsingPrivateBrowsing()) + process->send(Messages::WebProcess::EnsurePrivateBrowsingSession(), 0); + m_processes.append(process); if (m_processModel == ProcessModelSharedSecondaryProcess) { for (size_t i = 0; i != m_messagesToInjectedBundlePostedToEmptyContext.size(); ++i) { - pair<String, RefPtr<APIObject> >& message = m_messagesToInjectedBundlePostedToEmptyContext[i]; + pair<String, RefPtr<APIObject>>& message = m_messagesToInjectedBundlePostedToEmptyContext[i]; OwnPtr<CoreIPC::ArgumentEncoder> messageData = CoreIPC::ArgumentEncoder::create(); @@ -422,8 +569,7 @@ PassRefPtr<WebProcessProxy> WebContext::createNewWebProcess() } else ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty()); - - return process.release(); + return process.get(); } void WebContext::warmInitialProcess() @@ -433,6 +579,9 @@ void WebContext::warmInitialProcess() return; } + if (m_processes.size() >= m_webProcessCountLimit) + return; + createNewWebProcess(); m_haveInitialEmptyProcess = true; } @@ -440,7 +589,7 @@ void WebContext::warmInitialProcess() void WebContext::enableProcessTermination() { m_processTerminationEnabled = true; - Vector<RefPtr<WebProcessProxy> > processes = m_processes; + Vector<RefPtr<WebProcessProxy>> processes = m_processes; for (size_t i = 0; i < processes.size(); ++i) { if (shouldTerminate(processes[i].get())) processes[i]->terminate(); @@ -454,31 +603,31 @@ bool WebContext::shouldTerminate(WebProcessProxy* process) if (!m_processTerminationEnabled) return false; - if (!m_downloads.isEmpty()) - return false; + WebContextSupplementMap::const_iterator it = m_supplements.begin(); + WebContextSupplementMap::const_iterator end = m_supplements.end(); + for (; it != end; ++it) { + if (!it->value->shouldTerminate(process)) + return false; + } - if (!m_applicationCacheManagerProxy->shouldTerminate(process)) - return false; - if (!m_cookieManagerProxy->shouldTerminate(process)) - return false; -#if ENABLE(SQL_DATABASE) - if (!m_databaseManagerProxy->shouldTerminate(process)) - return false; -#endif - if (!m_keyValueStorageManagerProxy->shouldTerminate(process)) - return false; - if (!m_mediaCacheManagerProxy->shouldTerminate(process)) - return false; #if ENABLE(NETSCAPE_PLUGIN_API) if (!m_pluginSiteDataManager->shouldTerminate(process)) return false; #endif - if (!m_resourceCacheManagerProxy->shouldTerminate(process)) - return false; return true; } +void WebContext::processWillOpenConnection(WebProcessProxy* process) +{ + m_storageManager->processWillOpenConnection(process); +} + +void WebContext::processWillCloseConnection(WebProcessProxy* process) +{ + m_storageManager->processWillCloseConnection(process); +} + void WebContext::processDidFinishLaunching(WebProcessProxy* process) { ASSERT(m_processes.contains(process)); @@ -491,7 +640,7 @@ void WebContext::processDidFinishLaunching(WebProcessProxy* process) SandboxExtension::Handle sampleLogSandboxHandle; double now = WTF::currentTime(); String sampleLogFilePath = String::format("WebProcess%llupid%d", static_cast<unsigned long long>(now), process->processIdentifier()); - sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::WriteOnly, sampleLogSandboxHandle); + sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::ReadWrite, sampleLogSandboxHandle); process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0); } @@ -508,41 +657,20 @@ void WebContext::disconnectProcess(WebProcessProxy* process) if (m_haveInitialEmptyProcess && process == m_processes.last()) m_haveInitialEmptyProcess = false; - // FIXME (Multi-WebProcess): <rdar://problem/12239765> All the invalidation calls below are still necessary in multi-process mode, but they should only affect data structures pertaining to the process being disconnected. + // FIXME (Multi-WebProcess): <rdar://problem/12239765> Some of the invalidation calls below are still necessary in multi-process mode, but they should only affect data structures pertaining to the process being disconnected. // Clearing everything causes assertion failures, so it's less trouble to skip that for now. if (m_processModel != ProcessModelSharedSecondaryProcess) { RefPtr<WebProcessProxy> protect(process); + if (m_processWithPageCache == process) + m_processWithPageCache = 0; m_processes.remove(m_processes.find(process)); return; } - // Invalidate all outstanding downloads. - for (HashMap<uint64_t, RefPtr<DownloadProxy> >::iterator::Values it = m_downloads.begin().values(), end = m_downloads.end().values(); it != end; ++it) { - (*it)->processDidClose(); - (*it)->invalidate(); - } - - m_downloads.clear(); - - m_applicationCacheManagerProxy->invalidate(); -#if ENABLE(BATTERY_STATUS) - m_batteryManagerProxy->invalidate(); -#endif - m_cookieManagerProxy->invalidate(); -#if ENABLE(SQL_DATABASE) - m_databaseManagerProxy->invalidate(); -#endif - m_geolocationManagerProxy->invalidate(); - m_keyValueStorageManagerProxy->invalidate(); - m_mediaCacheManagerProxy->invalidate(); -#if ENABLE(NETWORK_INFO) - m_networkInfoManagerProxy->invalidate(); -#endif - m_notificationManagerProxy->invalidate(); - m_resourceCacheManagerProxy->invalidate(); -#if USE(SOUP) - m_soupRequestManagerProxy->invalidate(); -#endif + WebContextSupplementMap::const_iterator it = m_supplements.begin(); + WebContextSupplementMap::const_iterator end = m_supplements.end(); + for (; it != end; ++it) + it->value->processDidClose(process); // When out of process plug-ins are enabled, we don't want to invalidate the plug-in site data // manager just because the web process crashes since it's not involved. @@ -554,9 +682,28 @@ void WebContext::disconnectProcess(WebProcessProxy* process) // Since vector elements are destroyed in place, we would recurse into WebProcessProxy destructor // if it were invoked from Vector::remove(). RefPtr delays destruction until it's safe. RefPtr<WebProcessProxy> protect(process); + if (m_processWithPageCache == process) + m_processWithPageCache = 0; m_processes.remove(m_processes.find(process)); } +WebProcessProxy* WebContext::createNewWebProcessRespectingProcessCountLimit() +{ + if (m_processes.size() < m_webProcessCountLimit) + return createNewWebProcess(); + + // Choose a process with fewest pages, to achieve flat distribution. + WebProcessProxy* result = 0; + unsigned fewestPagesSeen = UINT_MAX; + for (unsigned i = 0; i < m_processes.size(); ++i) { + if (fewestPagesSeen > m_processes[i]->pages().size()) { + result = m_processes[i].get(); + fewestPagesSeen = m_processes[i]->pages().size(); + } + } + return result; +} + PassRefPtr<WebPageProxy> WebContext::createWebPage(PageClient* pageClient, WebPageGroup* pageGroup, WebPageProxy* relatedPage) { RefPtr<WebProcessProxy> process; @@ -569,10 +716,8 @@ PassRefPtr<WebPageProxy> WebContext::createWebPage(PageClient* pageClient, WebPa } else if (relatedPage) { // Sharing processes, e.g. when creating the page via window.open(). process = relatedPage->process(); - } else { - // FIXME (Multi-WebProcess): <rdar://problem/12239661> Consider limiting the number of web processes in per-tab process model. - process = createNewWebProcess(); - } + } else + process = createNewWebProcessRespectingProcessCountLimit(); } if (!pageGroup) @@ -583,24 +728,24 @@ PassRefPtr<WebPageProxy> WebContext::createWebPage(PageClient* pageClient, WebPa DownloadProxy* WebContext::download(WebPageProxy* initiatingPage, const ResourceRequest& request) { - if (m_processModel == ProcessModelSharedSecondaryProcess) { - ensureSharedWebProcess(); + DownloadProxy* downloadProxy = createDownloadProxy(); + uint64_t initiatingPageID = initiatingPage ? initiatingPage->pageID() : 0; - DownloadProxy* download = createDownloadProxy(); - uint64_t initiatingPageID = initiatingPage ? initiatingPage->pageID() : 0; +#if ENABLE(NETWORK_PROCESS) + if (usesNetworkProcess() && networkProcess()) { + // FIXME (NetworkProcess): Replicate whatever FrameLoader::setOriginalURLForDownloadRequest does with the request here. + networkProcess()->connection()->send(Messages::NetworkProcess::DownloadRequest(downloadProxy->downloadID(), request), 0); + return downloadProxy; + } +#endif #if PLATFORM(QT) - ASSERT(initiatingPage); // Our design does not suppport downloads without a WebPage. - initiatingPage->handleDownloadRequest(download); + ASSERT(initiatingPage); // Our design does not suppport downloads without a WebPage. + initiatingPage->handleDownloadRequest(downloadProxy); #endif - m_processes[0]->send(Messages::WebProcess::DownloadRequest(download->downloadID(), initiatingPageID, request), 0); - return download; - - } else { - // FIXME (Multi-WebProcess): <rdar://problem/12239483> Make downloading work. - return 0; - } + m_processes[0]->send(Messages::WebProcess::DownloadRequest(downloadProxy->downloadID(), initiatingPageID, request), 0); + return downloadProxy; } void WebContext::postMessageToInjectedBundle(const String& messageName, APIObject* messageBody) @@ -714,6 +859,8 @@ void WebContext::setCacheModel(CacheModel cacheModel) { m_cacheModel = cacheModel; sendToAllProcesses(Messages::WebProcess::SetCacheModel(static_cast<uint32_t>(m_cacheModel))); + + // FIXME: Inform the Network Process if in use. } void WebContext::setDefaultRequestTimeoutInterval(double timeoutInterval) @@ -737,31 +884,12 @@ void WebContext::addVisitedLinkHash(LinkHash linkHash) DownloadProxy* WebContext::createDownloadProxy() { - RefPtr<DownloadProxy> downloadProxy = DownloadProxy::create(this); - m_downloads.set(downloadProxy->downloadID(), downloadProxy); - addMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID(), this); - return downloadProxy.get(); -} - -void WebContext::downloadFinished(DownloadProxy* downloadProxy) -{ - ASSERT(m_downloads.contains(downloadProxy->downloadID())); - - downloadProxy->invalidate(); - removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID()); - m_downloads.remove(downloadProxy->downloadID()); -} - -// FIXME: This is not the ideal place for this function. -HashSet<String, CaseFoldingHash> WebContext::pdfAndPostScriptMIMETypes() -{ - HashSet<String, CaseFoldingHash> mimeTypes; +#if ENABLE(NETWORK_PROCESS) + if (usesNetworkProcess()) + return m_networkProcess->createDownloadProxy(); +#endif - mimeTypes.add("application/pdf"); - mimeTypes.add("application/postscript"); - mimeTypes.add("text/pdf"); - - return mimeTypes; + return ensureSharedWebProcess()->createDownloadProxy(); } void WebContext::addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver* messageReceiver) @@ -779,83 +907,66 @@ void WebContext::removeMessageReceiver(CoreIPC::StringReference messageReceiverN m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID); } -bool WebContext::dispatchMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +bool WebContext::dispatchMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) { - return m_messageReceiverMap.dispatchMessage(connection, messageID, decoder); + return m_messageReceiverMap.dispatchMessage(connection, decoder); } -bool WebContext::dispatchSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) +bool WebContext::dispatchSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) { - return m_messageReceiverMap.dispatchSyncMessage(connection, messageID, decoder, replyEncoder); + return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder); } -void WebContext::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebContext::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) { - if (messageID.is<CoreIPC::MessageClassWebContext>()) { - didReceiveWebContextMessage(connection, messageID, decoder); + if (decoder.messageReceiverName() == Messages::WebContext::messageReceiverName()) { + didReceiveWebContextMessage(connection, decoder); return; } - if (messageID.is<CoreIPC::MessageClassDownloadProxy>()) { - if (DownloadProxy* downloadProxy = m_downloads.get(decoder.destinationID()).get()) - downloadProxy->didReceiveDownloadProxyMessage(connection, messageID, decoder); - - return; - } - - switch (messageID.get<WebContextLegacyMessage::Kind>()) { - case WebContextLegacyMessage::PostMessage: { - String messageName; - RefPtr<APIObject> messageBody; - WebContextUserMessageDecoder messageBodyDecoder(messageBody, WebProcessProxy::fromConnection(connection)); - if (!decoder.decode(messageName)) - return; - if (!decoder.decode(messageBodyDecoder)) - return; - - didReceiveMessageFromInjectedBundle(messageName, messageBody.get()); + if (decoder.messageReceiverName() == WebContextLegacyMessages::messageReceiverName() + && decoder.messageName() == WebContextLegacyMessages::postMessageMessageName()) { + String messageName; + RefPtr<APIObject> messageBody; + WebContextUserMessageDecoder messageBodyDecoder(messageBody, WebProcessProxy::fromConnection(connection)); + if (!decoder.decode(messageName)) return; - } - case WebContextLegacyMessage::PostSynchronousMessage: - ASSERT_NOT_REACHED(); + if (!decoder.decode(messageBodyDecoder)) + return; + + didReceiveMessageFromInjectedBundle(messageName, messageBody.get()); + return; } ASSERT_NOT_REACHED(); } -void WebContext::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) +void WebContext::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) { - if (messageID.is<CoreIPC::MessageClassWebContext>()) { - didReceiveSyncWebContextMessage(connection, messageID, decoder, replyEncoder); + if (decoder.messageReceiverName() == Messages::WebContext::messageReceiverName()) { + didReceiveSyncWebContextMessage(connection, decoder, replyEncoder); return; } - if (messageID.is<CoreIPC::MessageClassDownloadProxy>()) { - if (DownloadProxy* downloadProxy = m_downloads.get(decoder.destinationID()).get()) - downloadProxy->didReceiveSyncDownloadProxyMessage(connection, messageID, decoder, replyEncoder); - return; - } + if (decoder.messageReceiverName() == WebContextLegacyMessages::messageReceiverName() + && decoder.messageName() == WebContextLegacyMessages::postSynchronousMessageMessageName()) { + // FIXME: We should probably encode something in the case that the arguments do not decode correctly. - switch (messageID.get<WebContextLegacyMessage::Kind>()) { - case WebContextLegacyMessage::PostSynchronousMessage: { - // FIXME: We should probably encode something in the case that the arguments do not decode correctly. - - String messageName; - RefPtr<APIObject> messageBody; - WebContextUserMessageDecoder messageBodyDecoder(messageBody, WebProcessProxy::fromConnection(connection)); - if (!decoder.decode(messageName)) - return; - if (!decoder.decode(messageBodyDecoder)) - return; - - RefPtr<APIObject> returnData; - didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody.get(), returnData); - replyEncoder->encode(WebContextUserMessageEncoder(returnData.get())); + String messageName; + RefPtr<APIObject> messageBody; + WebContextUserMessageDecoder messageBodyDecoder(messageBody, WebProcessProxy::fromConnection(connection)); + if (!decoder.decode(messageName)) return; - } - case WebContextLegacyMessage::PostMessage: - ASSERT_NOT_REACHED(); + if (!decoder.decode(messageBodyDecoder)) + return; + + RefPtr<APIObject> returnData; + didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody.get(), returnData); + replyEncoder->encode(WebContextUserMessageEncoder(returnData.get())); + return; } + + ASSERT_NOT_REACHED(); } void WebContext::setEnhancedAccessibility(bool flag) @@ -878,7 +989,7 @@ void WebContext::startMemorySampler(const double interval) SandboxExtension::Handle sampleLogSandboxHandle; double now = WTF::currentTime(); String sampleLogFilePath = String::format("WebProcess%llu", static_cast<unsigned long long>(now)); - sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::WriteOnly, sampleLogSandboxHandle); + sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::ReadWrite, sampleLogSandboxHandle); sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval)); } @@ -896,6 +1007,14 @@ void WebContext::stopMemorySampler() sendToAllProcesses(Messages::WebProcess::StopMemorySampler()); } +String WebContext::applicationCacheDirectory() const +{ + if (!m_overrideApplicationCacheDirectory.isEmpty()) + return m_overrideApplicationCacheDirectory; + + return platformDefaultApplicationCacheDirectory(); +} + String WebContext::databaseDirectory() const { if (!m_overrideDatabaseDirectory.isEmpty()) @@ -918,6 +1037,12 @@ String WebContext::iconDatabasePath() const return platformDefaultIconDatabasePath(); } +void WebContext::setLocalStorageDirectory(const String& directory) +{ + m_overrideLocalStorageDirectory = directory; + m_storageManager->setLocalStorageDirectory(localStorageDirectory()); +} + String WebContext::localStorageDirectory() const { if (!m_overrideLocalStorageDirectory.isEmpty()) @@ -942,6 +1067,21 @@ String WebContext::cookieStorageDirectory() const return platformDefaultCookieStorageDirectory(); } +void WebContext::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host) +{ +#if ENABLE(NETWORK_PROCESS) + if (m_usesNetworkProcess && m_networkProcess) { + m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->platformCertificateInfo(), host), 0); + return; + } +#else + UNUSED_PARAM(certificate); + UNUSED_PARAM(host); +#endif + // FIXME: It's unclear whether we want this SPI to be exposed and used for clients that don't use the NetworkProcess. + ASSERT_NOT_REACHED(); +} + void WebContext::setHTTPPipeliningEnabled(bool enabled) { #if PLATFORM(MAC) @@ -960,32 +1100,58 @@ bool WebContext::httpPipeliningEnabled() const #endif } -void WebContext::getWebCoreStatistics(PassRefPtr<DictionaryCallback> callback) +void WebContext::getStatistics(uint32_t statisticsMask, PassRefPtr<DictionaryCallback> callback) +{ + if (!statisticsMask) { + callback->invalidate(); + return; + } + + RefPtr<StatisticsRequest> request = StatisticsRequest::create(callback); + + if (statisticsMask & StatisticsRequestTypeWebContent) + requestWebContentStatistics(request.get()); + + if (statisticsMask & StatisticsRequestTypeNetworking) + requestNetworkingStatistics(request.get()); +} + +void WebContext::requestWebContentStatistics(StatisticsRequest* request) { if (m_processModel == ProcessModelSharedSecondaryProcess) { - if (m_processes.isEmpty()) { - callback->invalidate(); + if (m_processes.isEmpty()) return; - } - uint64_t callbackID = callback->callbackID(); - m_dictionaryCallbacks.set(callbackID, callback.get()); - m_processes[0]->send(Messages::WebProcess::GetWebCoreStatistics(callbackID), 0); + uint64_t requestID = request->addOutstandingRequest(); + m_statisticsRequests.set(requestID, request); + m_processes[0]->send(Messages::WebProcess::GetWebCoreStatistics(requestID), 0); } else { - // FIXME (Multi-WebProcess): <rdar://problem/12239483> Make downloading work. - callback->invalidate(); + // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work. } } -static PassRefPtr<MutableDictionary> createDictionaryFromHashMap(const HashMap<String, uint64_t>& map) +void WebContext::requestNetworkingStatistics(StatisticsRequest* request) { - RefPtr<MutableDictionary> result = MutableDictionary::create(); - HashMap<String, uint64_t>::const_iterator end = map.end(); - for (HashMap<String, uint64_t>::const_iterator it = map.begin(); it != end; ++it) - result->set(it->key, RefPtr<WebUInt64>(WebUInt64::create(it->value)).get()); - - return result; + bool networkProcessUnavailable; +#if ENABLE(NETWORK_PROCESS) + networkProcessUnavailable = !m_usesNetworkProcess || !m_networkProcess; +#else + networkProcessUnavailable = true; +#endif + + if (networkProcessUnavailable) { + LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable"); + return; + } + +#if ENABLE(NETWORK_PROCESS) + uint64_t requestID = request->addOutstandingRequest(); + m_statisticsRequests.set(requestID, request); + m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0); +#else + UNUSED_PARAM(request); +#endif } #if !PLATFORM(MAC) @@ -994,25 +1160,15 @@ void WebContext::dummy(bool&) } #endif -void WebContext::didGetWebCoreStatistics(const StatisticsData& statisticsData, uint64_t callbackID) +void WebContext::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID) { - RefPtr<DictionaryCallback> callback = m_dictionaryCallbacks.take(callbackID); - if (!callback) { - // FIXME: Log error or assert. + RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID); + if (!request) { + LOG_ERROR("Cannot report networking statistics."); return; } - RefPtr<MutableDictionary> statistics = createDictionaryFromHashMap(statisticsData.statisticsNumbers); - statistics->set("JavaScriptProtectedObjectTypeCounts", createDictionaryFromHashMap(statisticsData.javaScriptProtectedObjectTypeCounts).get()); - statistics->set("JavaScriptObjectTypeCounts", createDictionaryFromHashMap(statisticsData.javaScriptObjectTypeCounts).get()); - - size_t cacheStatisticsCount = statisticsData.webCoreCacheStatistics.size(); - Vector<RefPtr<APIObject> > cacheStatisticsVector(cacheStatisticsCount); - for (size_t i = 0; i < cacheStatisticsCount; ++i) - cacheStatisticsVector[i] = createDictionaryFromHashMap(statisticsData.webCoreCacheStatistics[i]); - statistics->set("WebCoreCacheStatistics", ImmutableArray::adopt(cacheStatisticsVector).get()); - - callback->performCallbackWithReturnValue(statistics.get()); + request->completedRequest(requestID, statisticsData); } void WebContext::garbageCollectJavaScriptObjects() @@ -1025,4 +1181,75 @@ void WebContext::setJavaScriptGarbageCollectorTimerEnabled(bool flag) sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag)); } +void WebContext::addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash) +{ + m_plugInAutoStartProvider.addAutoStartOriginHash(pageOrigin, plugInOriginHash); +} + +void WebContext::plugInDidReceiveUserInteraction(unsigned plugInOriginHash) +{ + m_plugInAutoStartProvider.didReceiveUserInteraction(plugInOriginHash); +} + +PassRefPtr<ImmutableDictionary> WebContext::plugInAutoStartOriginHashes() const +{ + return m_plugInAutoStartProvider.autoStartOriginsTableCopy(); +} + +void WebContext::setPlugInAutoStartOriginHashes(ImmutableDictionary& dictionary) +{ + m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary); +} + +void WebContext::setPlugInAutoStartOrigins(ImmutableArray& array) +{ + m_plugInAutoStartProvider.setAutoStartOriginsArray(array); +} + +#if ENABLE(CUSTOM_PROTOCOLS) +void WebContext::registerSchemeForCustomProtocol(const String& scheme) +{ + sendToNetworkingProcess(Messages::CustomProtocolManager::RegisterScheme(scheme)); +} + +void WebContext::unregisterSchemeForCustomProtocol(const String& scheme) +{ + sendToNetworkingProcess(Messages::CustomProtocolManager::UnregisterScheme(scheme)); +} +#endif + +#if ENABLE(NETSCAPE_PLUGIN_API) +void WebContext::pluginInfoStoreDidLoadPlugins(PluginInfoStore* store) +{ +#ifdef NDEBUG + UNUSED_PARAM(store); +#endif + ASSERT(store == &m_pluginInfoStore); + + Vector<RefPtr<APIObject>> pluginArray; + + Vector<PluginModuleInfo> plugins = m_pluginInfoStore.plugins(); + for (size_t i = 0; i < plugins.size(); ++i) { + PluginModuleInfo& plugin = plugins[i]; + ImmutableDictionary::MapType map; + map.set(ASCIILiteral("path"), WebString::create(plugin.path)); + map.set(ASCIILiteral("name"), WebString::create(plugin.info.name)); + map.set(ASCIILiteral("file"), WebString::create(plugin.info.file)); + map.set(ASCIILiteral("desc"), WebString::create(plugin.info.desc)); + Vector<RefPtr<APIObject>> mimeArray; + for (size_t j = 0; j < plugin.info.mimes.size(); ++j) + mimeArray.append(WebString::create(plugin.info.mimes[j].type)); + map.set(ASCIILiteral("mimes"), ImmutableArray::adopt(mimeArray)); +#if PLATFORM(MAC) + map.set(ASCIILiteral("bundleId"), WebString::create(plugin.bundleIdentifier)); + map.set(ASCIILiteral("version"), WebString::create(plugin.versionString)); +#endif + + pluginArray.append(ImmutableDictionary::adopt(map)); + } + + m_client.plugInInformationBecameAvailable(this, ImmutableArray::adopt(pluginArray).get()); +} +#endif + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContext.h b/Source/WebKit2/UIProcess/WebContext.h index 2cf7bb507..4e9958d83 100644 --- a/Source/WebKit2/UIProcess/WebContext.h +++ b/Source/WebKit2/UIProcess/WebContext.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,12 +27,19 @@ #define WebContext_h #include "APIObject.h" +#include "DownloadProxyMap.h" #include "GenericCallback.h" +#include "ImmutableArray.h" +#include "ImmutableDictionary.h" #include "MessageReceiver.h" #include "MessageReceiverMap.h" +#include "PlugInAutoStartProvider.h" #include "PluginInfoStore.h" #include "ProcessModel.h" +#include "StatisticsRequest.h" +#include "StorageManager.h" #include "VisitedLinkProvider.h" +#include "WebContextClient.h" #include "WebContextConnectionClient.h" #include "WebContextInjectedBundleClient.h" #include "WebDownloadClient.h" @@ -40,61 +47,77 @@ #include "WebProcessProxy.h" #include <WebCore/LinkHash.h> #include <wtf/Forward.h> +#include <wtf/HashMap.h> #include <wtf/HashSet.h> #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> +#if ENABLE(NETWORK_PROCESS) +#include "NetworkProcessProxy.h" +#endif + +#if PLATFORM(MAC) +OBJC_CLASS NSObject; +OBJC_CLASS NSString; +#endif + namespace WebKit { class DownloadProxy; -class WebApplicationCacheManagerProxy; -#if ENABLE(BATTERY_STATUS) -class WebBatteryManagerProxy; -#endif -class WebCookieManagerProxy; -class WebDatabaseManagerProxy; -class WebGeolocationManagerProxy; +class WebContextSupplement; class WebIconDatabase; -class WebKeyValueStorageManagerProxy; -class WebMediaCacheManagerProxy; -#if ENABLE(NETWORK_INFO) -class WebNetworkInfoManagerProxy; -#endif -class WebNotificationManagerProxy; class WebPageGroup; class WebPageProxy; -class WebResourceCacheManagerProxy; -#if USE(SOUP) -class WebSoupRequestManagerProxy; -#endif struct StatisticsData; struct WebProcessCreationParameters; typedef GenericCallback<WKDictionaryRef> DictionaryCallback; +#if ENABLE(NETWORK_INFO) +class WebNetworkInfoManagerProxy; +#endif +#if ENABLE(NETWORK_PROCESS) +struct NetworkProcessCreationParameters; +#endif + #if PLATFORM(MAC) extern NSString *SchemeForCustomProtocolRegisteredNotificationName; extern NSString *SchemeForCustomProtocolUnregisteredNotificationName; #endif -class WebContext : public APIObject, private CoreIPC::MessageReceiver { +class WebContext : public TypedAPIObject<APIObject::TypeContext>, private CoreIPC::MessageReceiver +#if ENABLE(NETSCAPE_PLUGIN_API) + , private PluginInfoStoreClient +#endif + { public: - static const Type APIType = TypeContext; - static PassRefPtr<WebContext> create(const String& injectedBundlePath); virtual ~WebContext(); static const Vector<WebContext*>& allContexts(); + template <typename T> + T* supplement() + { + return static_cast<T*>(m_supplements.get(T::supplementName())); + } + + template <typename T> + void addSupplement() + { + m_supplements.add(T::supplementName(), T::create(this)); + } + void addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver*); void addMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID, CoreIPC::MessageReceiver*); void removeMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID); - bool dispatchMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - bool dispatchSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + bool dispatchMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); + bool dispatchSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + void initializeClient(const WKContextClient*); void initializeInjectedBundleClient(const WKContextInjectedBundleClient*); void initializeConnectionClient(const WKContextConnectionClient*); void initializeHistoryClient(const WKContextHistoryClient*); @@ -103,17 +126,29 @@ public: void setProcessModel(ProcessModel); // Can only be called when there are no processes running. ProcessModel processModel() const { return m_processModel; } - // FIXME (Multi-WebProcess): Remove. No code should assume that there is a shared process. - WebProcessProxy* deprecatedSharedProcess(); + void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running. + unsigned maximumNumberOfProcesses() const { return m_webProcessCountLimit; } + + // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null. + CoreIPC::Connection* networkingProcessConnection(); template<typename U> void sendToAllProcesses(const U& message); template<typename U> void sendToAllProcessesRelaunchingThemIfNecessary(const U& message); - + template<typename U> void sendToOneProcess(const U& message); + + // Sends the message to WebProcess or NetworkProcess as approporiate for current process model. + template<typename U> void sendToNetworkingProcess(const U& message); + template<typename U> void sendToNetworkingProcessRelaunchingIfNecessary(const U& message); + + void processWillOpenConnection(WebProcessProxy*); + void processWillCloseConnection(WebProcessProxy*); void processDidFinishLaunching(WebProcessProxy*); // Disconnect the process from the context. void disconnectProcess(WebProcessProxy*); + StorageManager& storageManager() const { return *m_storageManager; } + PassRefPtr<WebPageProxy> createWebPage(PageClient*, WebPageGroup*, WebPageProxy* relatedPage = 0); const String& injectedBundlePath() const { return m_injectedBundlePath; } @@ -135,7 +170,6 @@ public: PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; } #endif - String applicationCacheDirectory(); void setAlwaysUsesComplexTextCodePath(bool); void setShouldUseFontSmoothing(bool); @@ -152,8 +186,8 @@ public: void addVisitedLinkHash(WebCore::LinkHash); // MessageReceiver. - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; void setCacheModel(CacheModel); CacheModel cacheModel() const { return m_cacheModel; } @@ -163,46 +197,22 @@ public: void startMemorySampler(const double interval); void stopMemorySampler(); -#if PLATFORM(WIN) - void setShouldPaintNativeControls(bool); - +#if USE(SOUP) void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; } #endif - void setEnhancedAccessibility(bool); // Downloads. DownloadProxy* createDownloadProxy(); WebDownloadClient& downloadClient() { return m_downloadClient; } - void downloadFinished(DownloadProxy*); WebHistoryClient& historyClient() { return m_historyClient; } + WebContextClient& client() { return m_client; } - static HashSet<String, CaseFoldingHash> pdfAndPostScriptMIMETypes(); - - WebApplicationCacheManagerProxy* applicationCacheManagerProxy() const { return m_applicationCacheManagerProxy.get(); } -#if ENABLE(BATTERY_STATUS) - WebBatteryManagerProxy* batteryManagerProxy() const { return m_batteryManagerProxy.get(); } -#endif - WebCookieManagerProxy* cookieManagerProxy() const { return m_cookieManagerProxy.get(); } -#if ENABLE(SQL_DATABASE) - WebDatabaseManagerProxy* databaseManagerProxy() const { return m_databaseManagerProxy.get(); } -#endif - WebGeolocationManagerProxy* geolocationManagerProxy() const { return m_geolocationManagerProxy.get(); } WebIconDatabase* iconDatabase() const { return m_iconDatabase.get(); } - WebKeyValueStorageManagerProxy* keyValueStorageManagerProxy() const { return m_keyValueStorageManagerProxy.get(); } - WebMediaCacheManagerProxy* mediaCacheManagerProxy() const { return m_mediaCacheManagerProxy.get(); } -#if ENABLE(NETWORK_INFO) - WebNetworkInfoManagerProxy* networkInfoManagerProxy() const { return m_networkInfoManagerProxy.get(); } -#endif - WebNotificationManagerProxy* notificationManagerProxy() const { return m_notificationManagerProxy.get(); } #if ENABLE(NETSCAPE_PLUGIN_API) WebPluginSiteDataManager* pluginSiteDataManager() const { return m_pluginSiteDataManager.get(); } #endif - WebResourceCacheManagerProxy* resourceCacheManagerProxy() const { return m_resourceCacheManagerProxy.get(); } -#if USE(SOUP) - WebSoupRequestManagerProxy* soupRequestManagerProxy() const { return m_soupRequestManagerProxy.get(); } -#endif struct Statistics { unsigned wkViewCount; @@ -211,15 +221,18 @@ public: }; static Statistics& statistics(); + void setApplicationCacheDirectory(const String& dir) { m_overrideApplicationCacheDirectory = dir; } void setDatabaseDirectory(const String& dir) { m_overrideDatabaseDirectory = dir; } void setIconDatabasePath(const String&); String iconDatabasePath() const; - void setLocalStorageDirectory(const String& dir) { m_overrideLocalStorageDirectory = dir; } + void setLocalStorageDirectory(const String&); void setDiskCacheDirectory(const String& dir) { m_overrideDiskCacheDirectory = dir; } void setCookieStorageDirectory(const String& dir) { m_overrideCookieStorageDirectory = dir; } + void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host); + WebProcessProxy* ensureSharedWebProcess(); - PassRefPtr<WebProcessProxy> createNewWebProcess(); + WebProcessProxy* createNewWebProcessRespectingProcessCountLimit(); // Will return an existing one if limit is met. void warmInitialProcess(); bool shouldTerminate(WebProcessProxy*); @@ -230,8 +243,9 @@ public: // Defaults to false. void setHTTPPipeliningEnabled(bool); bool httpPipeliningEnabled() const; + + void getStatistics(uint32_t statisticsMask, PassRefPtr<DictionaryCallback>); - void getWebCoreStatistics(PassRefPtr<DictionaryCallback>); void garbageCollectJavaScriptObjects(); void setJavaScriptGarbageCollectorTimerEnabled(bool flag); @@ -243,20 +257,65 @@ public: void textCheckerStateChanged(); + PassRefPtr<ImmutableDictionary> plugInAutoStartOriginHashes() const; + void setPlugInAutoStartOriginHashes(ImmutableDictionary&); + void setPlugInAutoStartOrigins(ImmutableArray&); + + // Network Process Management + void setUsesNetworkProcess(bool); + bool usesNetworkProcess() const; + +#if ENABLE(NETWORK_PROCESS) + void ensureNetworkProcess(); + NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); } + void networkProcessCrashed(NetworkProcessProxy*); + + void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); +#endif + #if PLATFORM(MAC) - static bool applicationIsOccluded() { return s_applicationIsOccluded; } + void setProcessSuppressionEnabled(bool); + bool processSuppressionEnabled() const { return m_processSuppressionEnabled; } + bool canEnableProcessSuppressionForNetworkProcess() const; + bool canEnableProcessSuppressionForWebProcess(const WebProcessProxy*) const; + static bool canEnableProcessSuppressionForGlobalChildProcesses(); + void updateProcessSuppressionStateOfChildProcesses(); +#endif + + static void willStartUsingPrivateBrowsing(); + static void willStopUsingPrivateBrowsing(); + +#if USE(SOUP) + void setIgnoreTLSErrors(bool); + bool ignoreTLSErrors() const { return m_ignoreTLSErrors; } #endif + static void setInvalidMessageCallback(void (*)(WKStringRef)); + static void didReceiveInvalidMessage(const CoreIPC::StringReference& messageReceiverName, const CoreIPC::StringReference& messageName); + + void processDidCachePage(WebProcessProxy*); + + bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const; + void resetHSTSHosts(); + private: WebContext(ProcessModel, const String& injectedBundlePath); - - virtual Type type() const { return APIType; } + void platformInitialize(); void platformInitializeWebProcess(WebProcessCreationParameters&); void platformInvalidateContext(); + WebProcessProxy* createNewWebProcess(); + + void requestWebContentStatistics(StatisticsRequest*); + void requestNetworkingStatistics(StatisticsRequest*); + +#if ENABLE(NETWORK_PROCESS) + void platformInitializeNetworkProcess(NetworkProcessCreationParameters&); +#endif + #if PLATFORM(MAC) void getPasteboardTypes(const String& pasteboardName, Vector<String>& pasteboardTypes); void getPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, Vector<String>& pathnames); @@ -280,15 +339,18 @@ private: void dummy(bool&); #endif - void didGetWebCoreStatistics(const StatisticsData&, uint64_t callbackID); + void didGetStatistics(const StatisticsData&, uint64_t callbackID); // Implemented in generated WebContextMessageReceiver.cpp - void didReceiveWebContextMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebContextMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + void didReceiveWebContextMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); + void didReceiveSyncWebContextMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); static void languageChanged(void* context); void languageChanged(); + String applicationCacheDirectory() const; + String platformDefaultApplicationCacheDirectory() const; + String databaseDirectory() const; String platformDefaultDatabaseDirectory() const; @@ -304,31 +366,50 @@ private: String platformDefaultCookieStorageDirectory() const; #if PLATFORM(MAC) - static void applicationBecameVisible(uint32_t, void*, uint32_t, void*, uint32_t); - static void applicationBecameOccluded(uint32_t, void*, uint32_t, void*, uint32_t); - static void initializeProcessSuppressionSupport(); - static void registerOcclusionNotificationHandlers(); + void processSuppressionEnabledChanged(); + void registerNotificationObservers(); + void unregisterNotificationObservers(); +#endif + +#if ENABLE(CUSTOM_PROTOCOLS) + void registerSchemeForCustomProtocol(const String&); + void unregisterSchemeForCustomProtocol(const String&); #endif + void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash); + void plugInDidReceiveUserInteraction(unsigned plugInOriginHash); + +#if ENABLE(NETSCAPE_PLUGIN_API) + // PluginInfoStoreClient: + virtual void pluginInfoStoreDidLoadPlugins(PluginInfoStore*) OVERRIDE; +#endif + + CoreIPC::MessageReceiverMap m_messageReceiverMap; + ProcessModel m_processModel; + unsigned m_webProcessCountLimit; // The limit has no effect when process model is ProcessModelSharedSecondaryProcess. - Vector<RefPtr<WebProcessProxy> > m_processes; + Vector<RefPtr<WebProcessProxy>> m_processes; bool m_haveInitialEmptyProcess; + WebProcessProxy* m_processWithPageCache; + RefPtr<WebPageGroup> m_defaultPageGroup; RefPtr<APIObject> m_injectedBundleInitializationUserData; String m_injectedBundlePath; WebContextInjectedBundleClient m_injectedBundleClient; + WebContextClient m_client; WebContextConnectionClient m_connectionClient; - + WebDownloadClient m_downloadClient; WebHistoryClient m_historyClient; #if ENABLE(NETSCAPE_PLUGIN_API) PluginInfoStore m_pluginInfoStore; #endif VisitedLinkProvider m_visitedLinkProvider; + PlugInAutoStartProvider m_plugInAutoStartProvider; HashSet<String> m_schemesToRegisterAsEmptyDocument; HashSet<String> m_schemesToRegisterAsSecure; @@ -343,51 +424,41 @@ private: // Messages that were posted before any pages were created. // The client should use initialization messages instead, so that a restarted process would get the same state. - Vector<pair<String, RefPtr<APIObject> > > m_messagesToInjectedBundlePostedToEmptyContext; + Vector<pair<String, RefPtr<APIObject>>> m_messagesToInjectedBundlePostedToEmptyContext; CacheModel m_cacheModel; - WebDownloadClient m_downloadClient; - HashMap<uint64_t, RefPtr<DownloadProxy> > m_downloads; - bool m_memorySamplerEnabled; double m_memorySamplerInterval; - RefPtr<WebApplicationCacheManagerProxy> m_applicationCacheManagerProxy; -#if ENABLE(BATTERY_STATUS) - RefPtr<WebBatteryManagerProxy> m_batteryManagerProxy; -#endif - RefPtr<WebCookieManagerProxy> m_cookieManagerProxy; -#if ENABLE(SQL_DATABASE) - RefPtr<WebDatabaseManagerProxy> m_databaseManagerProxy; -#endif - RefPtr<WebGeolocationManagerProxy> m_geolocationManagerProxy; RefPtr<WebIconDatabase> m_iconDatabase; - RefPtr<WebKeyValueStorageManagerProxy> m_keyValueStorageManagerProxy; - RefPtr<WebMediaCacheManagerProxy> m_mediaCacheManagerProxy; -#if ENABLE(NETWORK_INFO) - RefPtr<WebNetworkInfoManagerProxy> m_networkInfoManagerProxy; -#endif - RefPtr<WebNotificationManagerProxy> m_notificationManagerProxy; #if ENABLE(NETSCAPE_PLUGIN_API) RefPtr<WebPluginSiteDataManager> m_pluginSiteDataManager; #endif - RefPtr<WebResourceCacheManagerProxy> m_resourceCacheManagerProxy; -#if USE(SOUP) - RefPtr<WebSoupRequestManagerProxy> m_soupRequestManagerProxy; -#endif -#if PLATFORM(WIN) - bool m_shouldPaintNativeControls; + RefPtr<StorageManager> m_storageManager; + + typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap; + WebContextSupplementMap m_supplements; + +#if USE(SOUP) HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy; #endif #if PLATFORM(MAC) - RetainPtr<CFTypeRef> m_enhancedAccessibilityObserver; - RetainPtr<CFTypeRef> m_customSchemeRegisteredObserver; - RetainPtr<CFTypeRef> m_customSchemeUnregisteredObserver; + RetainPtr<NSObject> m_enhancedAccessibilityObserver; + RetainPtr<NSObject> m_customSchemeRegisteredObserver; + RetainPtr<NSObject> m_customSchemeUnregisteredObserver; + + RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver; + RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver; + RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver; +#endif #endif + String m_overrideApplicationCacheDirectory; String m_overrideDatabaseDirectory; String m_overrideIconDatabasePath; String m_overrideLocalStorageDirectory; @@ -398,17 +469,59 @@ private: #if ENABLE(NETWORK_PROCESS) bool m_usesNetworkProcess; + RefPtr<NetworkProcessProxy> m_networkProcess; #endif - HashMap<uint64_t, RefPtr<DictionaryCallback> > m_dictionaryCallbacks; - - CoreIPC::MessageReceiverMap m_messageReceiverMap; + HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks; + HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests; #if PLATFORM(MAC) - static bool s_applicationIsOccluded; + bool m_processSuppressionEnabled; +#endif + +#if USE(SOUP) + bool m_ignoreTLSErrors; #endif }; +template<typename U> inline void WebContext::sendToNetworkingProcess(const U& message) +{ + switch (m_processModel) { + case ProcessModelSharedSecondaryProcess: + if (!m_processes.isEmpty() && m_processes[0]->canSendMessage()) + m_processes[0]->send(message, 0); + return; + case ProcessModelMultipleSecondaryProcesses: +#if ENABLE(NETWORK_PROCESS) + if (m_networkProcess->canSendMessage()) + m_networkProcess->send(message, 0); + return; +#else + break; +#endif + } + ASSERT_NOT_REACHED(); +} + +template<typename U> void WebContext::sendToNetworkingProcessRelaunchingIfNecessary(const U& message) +{ + switch (m_processModel) { + case ProcessModelSharedSecondaryProcess: + ensureSharedWebProcess(); + m_processes[0]->send(message, 0); + return; + case ProcessModelMultipleSecondaryProcesses: +#if ENABLE(NETWORK_PROCESS) + ensureNetworkProcess(); + m_networkProcess->send(message, 0); + return; +#else + break; +#endif + } + ASSERT_NOT_REACHED(); +} + template<typename U> inline void WebContext::sendToAllProcesses(const U& message) { size_t processCount = m_processes.size(); @@ -427,6 +540,30 @@ template<typename U> void WebContext::sendToAllProcessesRelaunchingThemIfNecessa sendToAllProcesses(message); } +template<typename U> inline void WebContext::sendToOneProcess(const U& message) +{ + if (m_processModel == ProcessModelSharedSecondaryProcess) + ensureSharedWebProcess(); + + bool messageSent = false; + size_t processCount = m_processes.size(); + for (size_t i = 0; i < processCount; ++i) { + WebProcessProxy* process = m_processes[i].get(); + if (process->canSendMessage()) { + process->send(message, 0); + messageSent = true; + break; + } + } + + if (!messageSent && m_processModel == ProcessModelMultipleSecondaryProcesses) { + warmInitialProcess(); + RefPtr<WebProcessProxy> process = m_processes.last(); + if (process->canSendMessage()) + process->send(message, 0); + } +} + } // namespace WebKit #endif // WebContext_h diff --git a/Source/WebKit2/UIProcess/WebContext.messages.in b/Source/WebKit2/UIProcess/WebContext.messages.in index 2664a5f4f..f3df087f9 100644 --- a/Source/WebKit2/UIProcess/WebContext.messages.in +++ b/Source/WebKit2/UIProcess/WebContext.messages.in @@ -20,12 +20,12 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> WebContext { +messages -> WebContext LegacyReceiver { # Visited link provider messages. AddVisitedLinkHash(uint64_t linkHash) - DidGetWebCoreStatistics(WebKit::StatisticsData statisticsData, uint64_t callbackID) + DidGetStatistics(WebKit::StatisticsData statisticsData, uint64_t callbackID) #if PLATFORM(MAC) # Pasteboard messages. @@ -51,4 +51,8 @@ messages -> WebContext { // any synchronous messages, and should be removed when <rdar://problem/8775115> is fixed. Dummy() -> (bool dummyReturn) #endif + + # Plug-in messages. + void AddPlugInAutoStartOriginHash(WTF::String pageOrigin, uint32_t hash) + void PlugInDidReceiveUserInteraction(uint32_t hash) } diff --git a/Source/WebKit2/UIProcess/WebContextClient.cpp b/Source/WebKit2/UIProcess/WebContextClient.cpp new file mode 100644 index 000000000..df13e8778 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebContextClient.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebContextClient.h" + +#include "WebContext.h" + +namespace WebKit { + +void WebContextClient::plugInAutoStartOriginHashesChanged(WebContext* context) +{ + if (!m_client.plugInAutoStartOriginHashesChanged) + return; + + m_client.plugInAutoStartOriginHashesChanged(toAPI(context), m_client.clientInfo); +} + +void WebContextClient::networkProcessDidCrash(WebContext* context) +{ + if (!m_client.networkProcessDidCrash) + return; + + m_client.networkProcessDidCrash(toAPI(context), m_client.clientInfo); +} + +void WebContextClient::plugInInformationBecameAvailable(WebContext* context, ImmutableArray* plugInInfo) +{ + if (!m_client.plugInInformationBecameAvailable) + return; + + // FIXME: The API contract expects us to hand a reference to the array here. This is wrong. + plugInInfo->ref(); + + m_client.plugInInformationBecameAvailable(toAPI(context), toAPI(plugInInfo), m_client.clientInfo); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/C/win/WKAPICastWin.h b/Source/WebKit2/UIProcess/WebContextClient.h index 5b71cf303..698607c73 100644 --- a/Source/WebKit2/UIProcess/API/C/win/WKAPICastWin.h +++ b/Source/WebKit2/UIProcess/WebContextClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,21 +23,24 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKAPICastWin_h -#define WKAPICastWin_h +#ifndef WebContextClient_h +#define WebContextClient_h -#ifndef WKAPICast_h -#error "Please #include \"WKAPICast.h\" instead of this file directly." -#endif +#include "APIClient.h" +#include "WKContext.h" namespace WebKit { -class WebView; -class WebEditCommandProxy; +class ImmutableArray; +class WebContext; -WK_ADD_API_MAPPING(WKViewRef, WebView) -WK_ADD_API_MAPPING(WKEditCommandRef, WebEditCommandProxy) +class WebContextClient : public APIClient<WKContextClient, kWKContextClientCurrentVersion> { +public: + void plugInAutoStartOriginHashesChanged(WebContext*); + void networkProcessDidCrash(WebContext*); + void plugInInformationBecameAvailable(WebContext*, ImmutableArray*); +}; } // namespace WebKit -#endif // WKAPICastWin_h +#endif // WebContextClient_h diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessManager.h b/Source/WebKit2/UIProcess/WebContextSupplement.h index 957e45f3e..69f87e4e4 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessManager.h +++ b/Source/WebKit2/UIProcess/WebContextSupplement.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,45 +23,56 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef NetworkProcessManager_h -#define NetworkProcessManager_h - -#if ENABLE(NETWORK_PROCESS) - -#include "Connection.h" -#include "WebProcessProxyMessages.h" -#include <wtf/RefCounted.h> -#include <wtf/text/WTFString.h> +#ifndef WebContextSupplement_h +#define WebContextSupplement_h namespace WebKit { -class NetworkProcessConnection; class NetworkProcessProxy; +class WebContext; class WebProcessProxy; -class NetworkProcessManager { - WTF_MAKE_NONCOPYABLE(NetworkProcessManager); +class WebContextSupplement { public: - static NetworkProcessManager& shared(); + WebContextSupplement(WebContext* context) + : m_context(context) + { + } + + virtual ~WebContextSupplement() + { + } + + virtual void contextDestroyed() + { + } - void ensureNetworkProcess(); + virtual void processDidClose(WebProcessProxy*) + { + } - void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); - - void removeNetworkProcessProxy(NetworkProcessProxy*); + virtual void processDidClose(NetworkProcessProxy*) + { + } -#if PLATFORM(MAC) - void setApplicationIsOccluded(bool); -#endif + virtual bool shouldTerminate(WebProcessProxy*) const + { + return true; + } + + WebContext* context() const { return m_context; } + void clearContext() { m_context = 0; } + + void ref() { refWebContextSupplement(); } + void deref() { derefWebContextSupplement(); } private: - NetworkProcessManager(); + virtual void refWebContextSupplement() = 0; + virtual void derefWebContextSupplement() = 0; - RefPtr<NetworkProcessProxy> m_networkProcess; + WebContext* m_context; }; } // namespace WebKit -#endif // ENABLE(NETWORK_PROCESS) - -#endif // NetworkProcessManager_h +#endif // WebContextSupplement_h diff --git a/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h b/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h index 29be36fc9..041c234fd 100644 --- a/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h +++ b/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h @@ -107,7 +107,7 @@ public: { } - static bool decode(CoreIPC::ArgumentDecoder* decoder, WebContextUserMessageDecoder& coder) + static bool decode(CoreIPC::ArgumentDecoder& decoder, WebContextUserMessageDecoder& coder) { APIObject::Type type = APIObject::TypeNull; if (!Base::baseDecode(decoder, coder, type)) @@ -119,21 +119,21 @@ public: switch (type) { case APIObject::TypeBundlePage: { uint64_t pageID; - if (!decoder->decode(pageID)) + if (!decoder.decode(pageID)) return false; coder.m_root = coder.m_process->webPage(pageID); break; } case APIObject::TypeBundleFrame: { uint64_t frameID; - if (!decoder->decode(frameID)) + if (!decoder.decode(frameID)) return false; coder.m_root = coder.m_process->webFrame(frameID); break; } case APIObject::TypeBundlePageGroup: { uint64_t pageGroupID; - if (!decoder->decode(pageGroupID)) + if (!decoder.decode(pageGroupID)) return false; coder.m_root = WebPageGroup::get(pageGroupID); break; @@ -142,7 +142,7 @@ public: case APIObject::TypeObjCObjectGraph: { RefPtr<ObjCObjectGraph> objectGraph; WebContextObjCObjectGraphDecoder objectGraphDecoder(objectGraph, coder.m_process); - if (!decoder->decode(objectGraphDecoder)) + if (!decoder.decode(objectGraphDecoder)) return false; coder.m_root = objectGraph.get(); break; diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp b/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp index b63c80c7e..b7986221d 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,22 +34,49 @@ namespace WebKit { +const char* WebCookieManagerProxy::supplementName() +{ + return "WebCookieManagerProxy"; +} + PassRefPtr<WebCookieManagerProxy> WebCookieManagerProxy::create(WebContext* context) { return adoptRef(new WebCookieManagerProxy(context)); } WebCookieManagerProxy::WebCookieManagerProxy(WebContext* context) - : m_webContext(context) + : WebContextSupplement(context) +#if USE(SOUP) + , m_cookiePersistentStorageType(SoupCookiePersistentStorageSQLite) +#endif { - m_webContext->addMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName(), this); } WebCookieManagerProxy::~WebCookieManagerProxy() { } -void WebCookieManagerProxy::invalidate() +void WebCookieManagerProxy::initializeClient(const WKCookieManagerClient* client) +{ + m_client.initialize(client); +} + +// WebContextSupplement + +void WebCookieManagerProxy::contextDestroyed() +{ + invalidateCallbackMap(m_arrayCallbacks); + invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks); +} + +void WebCookieManagerProxy::processDidClose(WebProcessProxy*) +{ + invalidateCallbackMap(m_arrayCallbacks); + invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks); +} + +void WebCookieManagerProxy::processDidClose(NetworkProcessProxy*) { invalidateCallbackMap(m_arrayCallbacks); invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks); @@ -57,29 +84,27 @@ void WebCookieManagerProxy::invalidate() bool WebCookieManagerProxy::shouldTerminate(WebProcessProxy*) const { - return m_arrayCallbacks.isEmpty() && m_httpCookieAcceptPolicyCallbacks.isEmpty(); + return context()->processModel() != ProcessModelSharedSecondaryProcess + || (m_arrayCallbacks.isEmpty() && m_httpCookieAcceptPolicyCallbacks.isEmpty()); } -void WebCookieManagerProxy::initializeClient(const WKCookieManagerClient* client) +void WebCookieManagerProxy::refWebContextSupplement() { - m_client.initialize(client); + APIObject::ref(); } -void WebCookieManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebCookieManagerProxy::derefWebContextSupplement() { - didReceiveWebCookieManagerProxyMessage(connection, messageID, decoder); + APIObject::deref(); } void WebCookieManagerProxy::getHostnamesWithCookies(PassRefPtr<ArrayCallback> prpCallback) { - ASSERT(m_webContext); - RefPtr<ArrayCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_arrayCallbacks.set(callbackID, callback.release()); - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Cookies shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::GetHostnamesWithCookies(callbackID)); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::GetHostnamesWithCookies(callbackID)); } void WebCookieManagerProxy::didGetHostnamesWithCookies(const Vector<String>& hostnameList, uint64_t callbackID) @@ -91,7 +116,7 @@ void WebCookieManagerProxy::didGetHostnamesWithCookies(const Vector<String>& hos } size_t hostnameCount = hostnameList.size(); - Vector<RefPtr<APIObject> > hostnames(hostnameCount); + Vector<RefPtr<APIObject>> hostnames(hostnameCount); for (size_t i = 0; i < hostnameCount; ++i) hostnames[i] = WebString::create(hostnameList[i]); @@ -101,26 +126,22 @@ void WebCookieManagerProxy::didGetHostnamesWithCookies(const Vector<String>& hos void WebCookieManagerProxy::deleteCookiesForHostname(const String& hostname) { - ASSERT(m_webContext); - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::DeleteCookiesForHostname(hostname)); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteCookiesForHostname(hostname)); } void WebCookieManagerProxy::deleteAllCookies() { - ASSERT(m_webContext); - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::DeleteAllCookies()); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteAllCookies()); } void WebCookieManagerProxy::startObservingCookieChanges() { - ASSERT(m_webContext); - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::StartObservingCookieChanges()); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StartObservingCookieChanges()); } void WebCookieManagerProxy::stopObservingCookieChanges() { - ASSERT(m_webContext); - m_webContext->sendToAllProcesses(Messages::WebCookieManager::StopObservingCookieChanges()); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StopObservingCookieChanges()); } void WebCookieManagerProxy::cookiesDidChange() @@ -130,26 +151,24 @@ void WebCookieManagerProxy::cookiesDidChange() void WebCookieManagerProxy::setHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { - ASSERT(m_webContext); #if PLATFORM(MAC) persistHTTPCookieAcceptPolicy(policy); #endif +#if USE(SOUP) + context()->setInitialHTTPCookieAcceptPolicy(policy); +#endif - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy)); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy)); } void WebCookieManagerProxy::getHTTPCookieAcceptPolicy(PassRefPtr<HTTPCookieAcceptPolicyCallback> prpCallback) { - ASSERT(m_webContext); - RefPtr<HTTPCookieAcceptPolicyCallback> callback = prpCallback; uint64_t callbackID = callback->callbackID(); m_httpCookieAcceptPolicyCallbacks.set(callbackID, callback.release()); - // FIXME (Multi-WebProcess): <rdar://problem/12240189> Make cookie policies work with per-tab WebProcess. - // We can't ber asking all web processes for this information. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::GetHTTPCookieAcceptPolicy(callbackID)); + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::GetHTTPCookieAcceptPolicy(callbackID)); } void WebCookieManagerProxy::didGetHTTPCookieAcceptPolicy(uint32_t policy, uint64_t callbackID) diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxy.h b/Source/WebKit2/UIProcess/WebCookieManagerProxy.h index c0168e28c..215f22d69 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,15 +30,15 @@ #include "GenericCallback.h" #include "ImmutableArray.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include "WebCookieManagerProxyClient.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/Vector.h> -namespace CoreIPC { - class Connection; - class MessageID; -} +#if USE(SOUP) +#include "SoupCookiePersistentStorageType.h" +#endif namespace WebKit { @@ -48,16 +48,13 @@ class WebProcessProxy; typedef GenericCallback<WKArrayRef> ArrayCallback; typedef GenericCallback<WKHTTPCookieAcceptPolicy, HTTPCookieAcceptPolicy> HTTPCookieAcceptPolicyCallback; -class WebCookieManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebCookieManagerProxy : public TypedAPIObject<APIObject::TypeCookieManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeCookieManager; + static const char* supplementName(); static PassRefPtr<WebCookieManagerProxy> create(WebContext*); virtual ~WebCookieManagerProxy(); - void invalidate(); - void clearContext() { m_webContext = 0; } - void initializeClient(const WKCookieManagerClient*); void getHostnamesWithCookies(PassRefPtr<ArrayCallback>); @@ -72,33 +69,44 @@ public: #if USE(SOUP) void setCookiePersistentStorage(const String& storagePath, uint32_t storageType); + void getCookiePersistentStorage(String& storagePath, uint32_t& storageType) const; #endif - bool shouldTerminate(WebProcessProxy*) const; + using APIObject::ref; + using APIObject::deref; private: WebCookieManagerProxy(WebContext*); - virtual Type type() const { return APIType; } - void didGetHostnamesWithCookies(const Vector<String>&, uint64_t callbackID); void didGetHTTPCookieAcceptPolicy(uint32_t policy, uint64_t callbackID); void cookiesDidChange(); - + + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual void processDidClose(NetworkProcessProxy*) OVERRIDE; + virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; + // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebCookieManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; #if PLATFORM(MAC) void persistHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy); #endif - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; - HashMap<uint64_t, RefPtr<HTTPCookieAcceptPolicyCallback> > m_httpCookieAcceptPolicyCallbacks; + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; + HashMap<uint64_t, RefPtr<HTTPCookieAcceptPolicyCallback>> m_httpCookieAcceptPolicyCallbacks; WebCookieManagerProxyClient m_client; + +#if USE(SOUP) + String m_cookiePersistentStoragePath; + SoupCookiePersistentStorageType m_cookiePersistentStorageType; +#endif }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp index 116fd56e6..959cb5f24 100644 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -39,6 +39,11 @@ using namespace WebCore; namespace WebKit { +const char* WebDatabaseManagerProxy::supplementName() +{ + return "WebDatabaseManagerProxy"; +} + String WebDatabaseManagerProxy::originKey() { DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerOriginKey"))); @@ -93,16 +98,28 @@ PassRefPtr<WebDatabaseManagerProxy> WebDatabaseManagerProxy::create(WebContext* } WebDatabaseManagerProxy::WebDatabaseManagerProxy(WebContext* webContext) - : m_webContext(webContext) + : WebContextSupplement(webContext) { - m_webContext->addMessageReceiver(Messages::WebDatabaseManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebDatabaseManagerProxy::messageReceiverName(), this); } WebDatabaseManagerProxy::~WebDatabaseManagerProxy() { } -void WebDatabaseManagerProxy::invalidate() +void WebDatabaseManagerProxy::initializeClient(const WKDatabaseManagerClient* client) +{ + m_client.initialize(client); +} + +// WebContextSupplement + +void WebDatabaseManagerProxy::contextDestroyed() +{ + invalidateCallbackMap(m_arrayCallbacks); +} + +void WebDatabaseManagerProxy::processDidClose(WebProcessProxy*) { invalidateCallbackMap(m_arrayCallbacks); } @@ -112,9 +129,14 @@ bool WebDatabaseManagerProxy::shouldTerminate(WebProcessProxy*) const return m_arrayCallbacks.isEmpty(); } -void WebDatabaseManagerProxy::initializeClient(const WKDatabaseManagerClient* client) +void WebDatabaseManagerProxy::refWebContextSupplement() { - m_client.initialize(client); + APIObject::ref(); +} + +void WebDatabaseManagerProxy::derefWebContextSupplement() +{ + APIObject::deref(); } void WebDatabaseManagerProxy::getDatabasesByOrigin(PassRefPtr<ArrayCallback> prpCallback) @@ -123,8 +145,7 @@ void WebDatabaseManagerProxy::getDatabasesByOrigin(PassRefPtr<ArrayCallback> prp uint64_t callbackID = callback->callbackID(); m_arrayCallbacks.set(callbackID, callback.release()); - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Databases shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebDatabaseManager::GetDatabasesByOrigin(callbackID)); + context()->sendToOneProcess(Messages::WebDatabaseManager::GetDatabasesByOrigin(callbackID)); } void WebDatabaseManagerProxy::didGetDatabasesByOrigin(const Vector<OriginAndDatabases>& originAndDatabasesVector, uint64_t callbackID) @@ -136,7 +157,7 @@ void WebDatabaseManagerProxy::didGetDatabasesByOrigin(const Vector<OriginAndData } size_t originAndDatabasesCount = originAndDatabasesVector.size(); - Vector<RefPtr<APIObject> > result(originAndDatabasesCount); + Vector<RefPtr<APIObject>> result(originAndDatabasesCount); for (size_t i = 0; i < originAndDatabasesCount; ++i) { const OriginAndDatabases& originAndDatabases = originAndDatabasesVector[i]; @@ -144,11 +165,11 @@ void WebDatabaseManagerProxy::didGetDatabasesByOrigin(const Vector<OriginAndData RefPtr<APIObject> origin = WebSecurityOrigin::createFromDatabaseIdentifier(originAndDatabases.originIdentifier); size_t databasesCount = originAndDatabases.databases.size(); - Vector<RefPtr<APIObject> > databases(databasesCount); + Vector<RefPtr<APIObject>> databases(databasesCount); for (size_t j = 0; j < databasesCount; ++j) { const DatabaseDetails& details = originAndDatabases.databases[i]; - HashMap<String, RefPtr<APIObject> > detailsMap; + HashMap<String, RefPtr<APIObject>> detailsMap; detailsMap.set(databaseDetailsNameKey(), WebString::create(details.name())); detailsMap.set(databaseDetailsDisplayNameKey(), WebString::create(details.displayName())); @@ -157,7 +178,7 @@ void WebDatabaseManagerProxy::didGetDatabasesByOrigin(const Vector<OriginAndData databases.append(ImmutableDictionary::adopt(detailsMap)); } - HashMap<String, RefPtr<APIObject> > originAndDatabasesMap; + HashMap<String, RefPtr<APIObject>> originAndDatabasesMap; originAndDatabasesMap.set(originKey(), origin); originAndDatabasesMap.set(originQuotaKey(), WebUInt64::create(originAndDatabases.originQuota)); originAndDatabasesMap.set(originUsageKey(), WebUInt64::create(originAndDatabases.originUsage)); @@ -176,8 +197,7 @@ void WebDatabaseManagerProxy::getDatabaseOrigins(PassRefPtr<ArrayCallback> prpCa uint64_t callbackID = callback->callbackID(); m_arrayCallbacks.set(callbackID, callback.release()); - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Databases shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebDatabaseManager::GetDatabaseOrigins(callbackID)); + context()->sendToOneProcess(Messages::WebDatabaseManager::GetDatabaseOrigins(callbackID)); } void WebDatabaseManagerProxy::didGetDatabaseOrigins(const Vector<String>& originIdentifiers, uint64_t callbackID) @@ -189,7 +209,7 @@ void WebDatabaseManagerProxy::didGetDatabaseOrigins(const Vector<String>& origin } size_t originIdentifiersCount = originIdentifiers.size(); - Vector<RefPtr<APIObject> > securityOrigins(originIdentifiersCount); + Vector<RefPtr<APIObject>> securityOrigins(originIdentifiersCount); for (size_t i = 0; i < originIdentifiersCount; ++i) securityOrigins[i] = WebSecurityOrigin::createFromDatabaseIdentifier(originIdentifiers[i]); @@ -199,26 +219,22 @@ void WebDatabaseManagerProxy::didGetDatabaseOrigins(const Vector<String>& origin void WebDatabaseManagerProxy::deleteDatabaseWithNameForOrigin(const String& databaseIdentifier, WebSecurityOrigin* origin) { - // FIXME (Multi-WebProcess): <rdar://problem/7855696> Databases shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebDatabaseManager::DeleteDatabaseWithNameForOrigin(databaseIdentifier, origin->databaseIdentifier())); + context()->sendToOneProcess(Messages::WebDatabaseManager::DeleteDatabaseWithNameForOrigin(databaseIdentifier, origin->databaseIdentifier())); } void WebDatabaseManagerProxy::deleteDatabasesForOrigin(WebSecurityOrigin* origin) { - // FIXME (Multi-WebProcess): <rdar://problem/7855696> Databases shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebDatabaseManager::DeleteDatabasesForOrigin(origin->databaseIdentifier())); + context()->sendToOneProcess(Messages::WebDatabaseManager::DeleteDatabasesForOrigin(origin->databaseIdentifier())); } void WebDatabaseManagerProxy::deleteAllDatabases() { - // FIXME (Multi-WebProcess): <rdar://problem/7855696> Databases shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebDatabaseManager::DeleteAllDatabases()); + context()->sendToOneProcess(Messages::WebDatabaseManager::DeleteAllDatabases()); } void WebDatabaseManagerProxy::setQuotaForOrigin(WebSecurityOrigin* origin, uint64_t quota) { - // FIXME (Multi-WebProcess): <rdar://problem/7855696> Databases shouldn't be stored in the web process. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebDatabaseManager::SetQuotaForOrigin(origin->databaseIdentifier(), quota)); + context()->sendToOneProcess(Messages::WebDatabaseManager::SetQuotaForOrigin(origin->databaseIdentifier(), quota)); } void WebDatabaseManagerProxy::didModifyOrigin(const String& originIdentifier) @@ -233,11 +249,6 @@ void WebDatabaseManagerProxy::didModifyDatabase(const String& originIdentifier, m_client.didModifyDatabase(this, origin.get(), databaseIdentifier); } -void WebDatabaseManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveWebDatabaseManagerProxyMessage(connection, messageID, decoder); -} - } // namespace WebKit #endif // ENABLE(SQL_DATABASE) diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h index 7c695fcbb..c8abbe400 100644 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -33,6 +33,7 @@ #include "GenericCallback.h" #include "MessageReceiver.h" #include "OriginAndDatabases.h" +#include "WebContextSupplement.h" #include "WebDatabaseManagerProxyClient.h" #include <wtf/HashMap.h> #include <wtf/PassRefPtr.h> @@ -45,16 +46,13 @@ class WebSecurityOrigin; typedef GenericCallback<WKArrayRef> ArrayCallback; -class WebDatabaseManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebDatabaseManagerProxy : public TypedAPIObject<APIObject::TypeDatabaseManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeDatabaseManager; + static const char* supplementName(); static PassRefPtr<WebDatabaseManagerProxy> create(WebContext*); virtual ~WebDatabaseManagerProxy(); - void invalidate(); - void clearContext() { m_webContext = 0; } - void initializeClient(const WKDatabaseManagerClient*); void getDatabasesByOrigin(PassRefPtr<ArrayCallback>); @@ -73,16 +71,21 @@ public: static String databaseDetailsExpectedUsageKey(); static String databaseDetailsCurrentUsageKey(); - bool shouldTerminate(WebProcessProxy*) const; + using APIObject::ref; + using APIObject::deref; private: explicit WebDatabaseManagerProxy(WebContext*); - virtual Type type() const { return APIType; } + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebDatabaseManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; // Message handlers. void didGetDatabasesByOrigin(const Vector<OriginAndDatabases>& originAndDatabases, uint64_t callbackID); @@ -90,9 +93,7 @@ private: void didModifyOrigin(const String& originIdentifier); void didModifyDatabase(const String& originIdentifier, const String& databaseIdentifier); - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; - + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; WebDatabaseManagerProxyClient m_client; }; diff --git a/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp b/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp index 25ffe2302..81f145d51 100644 --- a/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp +++ b/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp @@ -125,6 +125,10 @@ String WebEditCommandProxy::nameForEditAction(EditAction editAction) return WEB_UI_STRING_KEY("Drag", "Drag (Undo action name)", "Undo action name"); case EditActionCut: return WEB_UI_STRING_KEY("Cut", "Cut (Undo action name)", "Undo action name"); + case EditActionBold: + return WEB_UI_STRING_KEY("Bold", "Bold (Undo action name)", "Undo action name"); + case EditActionItalics: + return WEB_UI_STRING_KEY("Italics", "Italics (Undo action name)", "Undo action name"); case EditActionPaste: return WEB_UI_STRING_KEY("Paste", "Paste (Undo action name)", "Undo action name"); case EditActionPasteFont: diff --git a/Source/WebKit2/UIProcess/WebEditCommandProxy.h b/Source/WebKit2/UIProcess/WebEditCommandProxy.h index 67d1430f1..f4f32ca43 100644 --- a/Source/WebKit2/UIProcess/WebEditCommandProxy.h +++ b/Source/WebKit2/UIProcess/WebEditCommandProxy.h @@ -36,7 +36,7 @@ namespace WebKit { class WebPageProxy; -class WebEditCommandProxy : public APIObject { +class WebEditCommandProxy : public TypedAPIObject<APIObject::TypeEditCommandProxy> { public: static PassRefPtr<WebEditCommandProxy> create(uint64_t commandID, WebCore::EditAction editAction, WebPageProxy* page) { @@ -57,8 +57,6 @@ public: private: WebEditCommandProxy(uint64_t commandID, WebCore::EditAction, WebPageProxy*); - virtual Type type() const { return TypeEditCommandProxy; } - uint64_t m_commandID; WebCore::EditAction m_editAction; WebPageProxy* m_page; diff --git a/Source/WebKit2/UIProcess/WebFindClient.cpp b/Source/WebKit2/UIProcess/WebFindClient.cpp index c8df91dbd..702d187ca 100644 --- a/Source/WebKit2/UIProcess/WebFindClient.cpp +++ b/Source/WebKit2/UIProcess/WebFindClient.cpp @@ -55,5 +55,20 @@ void WebFindClient::didCountStringMatches(WebPageProxy* page, const String& stri m_client.didCountStringMatches(toAPI(page), toAPI(string.impl()), matchCount, m_client.clientInfo); } +void WebFindMatchesClient::didFindStringMatches(WebPageProxy* page, const String& string, ImmutableArray* matches, int firstIndex) +{ + if (!m_client.didFindStringMatches) + return; + + m_client.didFindStringMatches(toAPI(page), toAPI(string.impl()), toAPI(matches), firstIndex, m_client.clientInfo); +} + +void WebFindMatchesClient::didGetImageForMatchResult(WebPageProxy* page, WebImage* image, uint32_t index) +{ + if (!m_client.didGetImageForMatchResult) + return; + m_client.didGetImageForMatchResult(toAPI(page), toAPI(image), index, m_client.clientInfo); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFindClient.h b/Source/WebKit2/UIProcess/WebFindClient.h index 82380ab78..605f3d502 100644 --- a/Source/WebKit2/UIProcess/WebFindClient.h +++ b/Source/WebKit2/UIProcess/WebFindClient.h @@ -32,7 +32,9 @@ namespace WebKit { +class ImmutableArray; class WebPageProxy; +class WebImage; class WebFindClient : public APIClient<WKPageFindClient, kWKPageFindClientCurrentVersion> { public: @@ -41,6 +43,12 @@ public: void didCountStringMatches(WebPageProxy*, const String&, uint32_t matchCount); }; +class WebFindMatchesClient : public APIClient<WKPageFindMatchesClient, kWKPageFindMatchesClientCurrentVersion> { +public: + void didFindStringMatches(WebPageProxy*, const String&, ImmutableArray*, int); + void didGetImageForMatchResult(WebPageProxy*, WebImage*, uint32_t); +}; + } // namespace WebKit #endif // WebFindClient_h diff --git a/Source/WebKit2/UIProcess/WebFormClient.cpp b/Source/WebKit2/UIProcess/WebFormClient.cpp index ecddbcc42..a17f61344 100644 --- a/Source/WebKit2/UIProcess/WebFormClient.cpp +++ b/Source/WebKit2/UIProcess/WebFormClient.cpp @@ -33,7 +33,7 @@ namespace WebKit { -bool WebFormClient::willSubmitForm(WebPageProxy* page, WebFrameProxy* frame, WebFrameProxy* sourceFrame, const Vector<std::pair<String, String> >& textFieldValues, APIObject* userData, WebFormSubmissionListenerProxy* listener) +bool WebFormClient::willSubmitForm(WebPageProxy* page, WebFrameProxy* frame, WebFrameProxy* sourceFrame, const Vector<std::pair<String, String>>& textFieldValues, APIObject* userData, WebFormSubmissionListenerProxy* listener) { if (!m_client.willSubmitForm) return false; diff --git a/Source/WebKit2/UIProcess/WebFormClient.h b/Source/WebKit2/UIProcess/WebFormClient.h index 05925239f..ca0f2b4b6 100644 --- a/Source/WebKit2/UIProcess/WebFormClient.h +++ b/Source/WebKit2/UIProcess/WebFormClient.h @@ -41,7 +41,7 @@ class WebFormSubmissionListenerProxy; class WebFormClient : public APIClient<WKPageFormClient, kWKPageFormClientCurrentVersion> { public: - bool willSubmitForm(WebPageProxy*, WebFrameProxy*, WebFrameProxy*, const Vector<std::pair<String, String> >& textFieldValues, APIObject* userData, WebFormSubmissionListenerProxy*); + bool willSubmitForm(WebPageProxy*, WebFrameProxy*, WebFrameProxy*, const Vector<std::pair<String, String>>& textFieldValues, APIObject* userData, WebFormSubmissionListenerProxy*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFrameProxy.cpp b/Source/WebKit2/UIProcess/WebFrameProxy.cpp index f60fab040..a57087c1f 100644 --- a/Source/WebKit2/UIProcess/WebFrameProxy.cpp +++ b/Source/WebKit2/UIProcess/WebFrameProxy.cpp @@ -34,21 +34,16 @@ #include "WebPageProxy.h" #include <WebCore/DOMImplementation.h> #include <WebCore/Image.h> +#include <WebCore/MIMETypeRegistry.h> #include <stdio.h> #include <wtf/text/WTFString.h> using namespace WebCore; -using namespace std; namespace WebKit { WebFrameProxy::WebFrameProxy(WebPageProxy* page, uint64_t frameID) : m_page(page) - , m_parentFrame(0) - , m_nextSibling(0) - , m_previousSibling(0) - , m_firstChild(0) - , m_lastChild(0) , m_loadState(LoadStateFinished) , m_isFrameSet(false) , m_frameID(frameID) @@ -64,11 +59,6 @@ WebFrameProxy::~WebFrameProxy() void WebFrameProxy::disconnect() { m_page = 0; - m_parentFrame = 0; - m_nextSibling = 0; - m_previousSibling = 0; - m_firstChild = 0; - m_lastChild = 0; if (m_activeListener) { m_activeListener->invalidate(); @@ -105,16 +95,7 @@ bool WebFrameProxy::canShowMIMEType(const String& mimeType) const if (!m_page) return false; - if (m_page->canShowMIMEType(mimeType)) - return true; - -#if PLATFORM(MAC) - // On Mac, we can show PDFs. - if (!mimeType.isEmpty()) - return WebContext::pdfAndPostScriptMIMETypes().contains(mimeType) && !WebContext::omitPDFSupport(); -#endif - - return false; + return m_page->canShowMIMEType(mimeType); } bool WebFrameProxy::isDisplayingStandaloneImageDocument() const @@ -125,8 +106,7 @@ bool WebFrameProxy::isDisplayingStandaloneImageDocument() const bool WebFrameProxy::isDisplayingMarkupDocument() const { // FIXME: This check should be moved to somewhere in WebCore. - // FIXME: This returns false when displaying a web archive. - return m_MIMEType == "text/html" || m_MIMEType == "image/svg+xml" || DOMImplementation::isXMLMIMEType(m_MIMEType); + return m_MIMEType == "text/html" || m_MIMEType == "image/svg+xml" || m_MIMEType == "application/x-webarchive" || DOMImplementation::isXMLMIMEType(m_MIMEType); } bool WebFrameProxy::isDisplayingPDFDocument() const @@ -134,12 +114,11 @@ bool WebFrameProxy::isDisplayingPDFDocument() const if (m_MIMEType.isEmpty()) return false; - return WebContext::pdfAndPostScriptMIMETypes().contains(m_MIMEType); + return MIMETypeRegistry::isPDFOrPostScriptMIMEType(m_MIMEType); } void WebFrameProxy::didStartProvisionalLoad(const String& url) { - ASSERT(m_loadState == LoadStateFinished); ASSERT(m_provisionalURL.isEmpty()); m_loadState = LoadStateProvisional; m_provisionalURL = url; @@ -183,7 +162,6 @@ void WebFrameProxy::didFailLoad() ASSERT(m_loadState == LoadStateCommitted); ASSERT(m_provisionalURL.isEmpty()); m_loadState = LoadStateFinished; - m_title = String(); } void WebFrameProxy::didSameDocumentNavigation(const String& url) @@ -196,85 +174,6 @@ void WebFrameProxy::didChangeTitle(const String& title) m_title = title; } -void WebFrameProxy::appendChild(WebFrameProxy* child) -{ - ASSERT(child->page() == page()); - ASSERT(!child->m_parentFrame); - ASSERT(!child->m_nextSibling); - ASSERT(!child->m_previousSibling); - - child->m_parentFrame = this; - - WebFrameProxy* oldLast = m_lastChild; - m_lastChild = child; - - if (oldLast) { - ASSERT(!oldLast->m_nextSibling); - child->m_previousSibling = oldLast; - oldLast->m_nextSibling = child; - } else - m_firstChild = child; -} - -void WebFrameProxy::removeChild(WebFrameProxy* child) -{ - child->m_parentFrame = 0; - - WebFrameProxy*& newLocationForNext = m_firstChild == child ? m_firstChild : child->m_previousSibling->m_nextSibling; - WebFrameProxy*& newLocationForPrevious = m_lastChild == child ? m_lastChild : child->m_nextSibling->m_previousSibling; - swap(newLocationForNext, child->m_nextSibling); - swap(newLocationForPrevious, child->m_previousSibling); - child->m_previousSibling = 0; - child->m_nextSibling = 0; -} - -bool WebFrameProxy::isDescendantOf(const WebFrameProxy* ancestor) const -{ - if (!ancestor) - return false; - - if (m_page != ancestor->m_page) - return false; - - for (const WebFrameProxy* frame = this; frame; frame = frame->m_parentFrame) { - if (frame == ancestor) - return true; - } - - return false; -} - -void WebFrameProxy::dumpFrameTreeToSTDOUT(unsigned indent) -{ - if (!indent && m_parentFrame) - printf("NOTE: Printing subtree.\n"); - - for (unsigned i = 0; i < indent; ++i) - printf(" "); - printf("| FRAME %d %s\n", (int)m_frameID, m_url.utf8().data()); - - for (WebFrameProxy* child = m_firstChild; child; child = child->m_nextSibling) - child->dumpFrameTreeToSTDOUT(indent + 4); -} - -void WebFrameProxy::didRemoveFromHierarchy() -{ - if (m_parentFrame) - m_parentFrame->removeChild(this); -} - -PassRefPtr<ImmutableArray> WebFrameProxy::childFrames() -{ - if (!m_firstChild) - return ImmutableArray::create(); - - Vector<RefPtr<APIObject> > vector; - for (WebFrameProxy* child = m_firstChild; child; child = child->m_nextSibling) - vector.append(child); - - return ImmutableArray::adopt(vector); -} - void WebFrameProxy::receivedPolicyDecision(WebCore::PolicyAction action, uint64_t listenerID) { if (!m_page) diff --git a/Source/WebKit2/UIProcess/WebFrameProxy.h b/Source/WebKit2/UIProcess/WebFrameProxy.h index de5a58cb7..0bee666ff 100644 --- a/Source/WebKit2/UIProcess/WebFrameProxy.h +++ b/Source/WebKit2/UIProcess/WebFrameProxy.h @@ -38,7 +38,6 @@ namespace CoreIPC { class ArgumentDecoder; class Connection; - class MessageID; } namespace WebKit { @@ -52,10 +51,8 @@ class WebPageProxy; typedef GenericCallback<WKDataRef> DataCallback; -class WebFrameProxy : public APIObject { +class WebFrameProxy : public TypedAPIObject<APIObject::TypeFrame> { public: - static const Type APIType = TypeFrame; - static PassRefPtr<WebFrameProxy> create(WebPageProxy* page, uint64_t frameID) { return adoptRef(new WebFrameProxy(page, frameID)); @@ -72,12 +69,6 @@ public: uint64_t frameID() const { return m_frameID; } WebPageProxy* page() const { return m_page; } - WebFrameProxy* parentFrame() { return m_parentFrame; } - WebFrameProxy* nextSibling() { return m_nextSibling; } - WebFrameProxy* previousSibling() { return m_previousSibling; } - WebFrameProxy* firstChild() { return m_firstChild; } - WebFrameProxy* lastChild() { return m_lastChild; } - void disconnect(); bool isMainFrame() const; @@ -121,14 +112,6 @@ public: void didSameDocumentNavigation(const String&); // eg. anchor navigation, session state change. void didChangeTitle(const String&); - // Frame tree operations. - void appendChild(WebFrameProxy*); - void removeChild(WebFrameProxy*); - void didRemoveFromHierarchy(); - PassRefPtr<ImmutableArray> childFrames(); - bool isDescendantOf(const WebFrameProxy* ancestor) const; - void dumpFrameTreeToSTDOUT(unsigned indent = 0); - // Policy operations. void receivedPolicyDecision(WebCore::PolicyAction, uint64_t listenerID); WebFramePolicyListenerProxy* setUpPolicyListenerProxy(uint64_t listenerID); @@ -137,15 +120,7 @@ public: private: WebFrameProxy(WebPageProxy* page, uint64_t frameID); - virtual Type type() const { return APIType; } - WebPageProxy* m_page; - WebFrameProxy* m_parentFrame; - WebFrameProxy* m_nextSibling; - WebFrameProxy* m_previousSibling; - WebFrameProxy* m_firstChild; - WebFrameProxy* m_lastChild; - LoadState m_loadState; String m_url; String m_provisionalURL; diff --git a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp index e49ad86ef..58fbb5973 100644 --- a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp @@ -42,7 +42,11 @@ PassRefPtr<WebFullScreenManagerProxy> WebFullScreenManagerProxy::create(WebPageP WebFullScreenManagerProxy::WebFullScreenManagerProxy(WebPageProxy* page) : m_page(page) , m_webView(0) +#if PLATFORM(EFL) + , m_hasRequestedFullScreen(false) +#endif { + m_page->process()->addMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID(), this); } WebFullScreenManagerProxy::~WebFullScreenManagerProxy() @@ -54,16 +58,6 @@ void WebFullScreenManagerProxy::setWebView(PlatformWebView* webView) m_webView = webView; } -void WebFullScreenManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveWebFullScreenManagerProxyMessage(connection, messageID, decoder); -} - -void WebFullScreenManagerProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) -{ - didReceiveSyncWebFullScreenManagerProxyMessage(connection, messageID, decoder, replyEncoder); -} - void WebFullScreenManagerProxy::willEnterFullScreen() { m_page->process()->send(Messages::WebFullScreenManager::WillEnterFullScreen(), m_page->pageID()); @@ -99,6 +93,16 @@ void WebFullScreenManagerProxy::supportsFullScreen(bool withKeyboard, bool& supp supports = !withKeyboard; } +void WebFullScreenManagerProxy::saveScrollPosition() +{ + m_page->process()->send(Messages::WebFullScreenManager::SaveScrollPosition(), m_page->pageID()); +} + +void WebFullScreenManagerProxy::restoreScrollPosition() +{ + m_page->process()->send(Messages::WebFullScreenManager::RestoreScrollPosition(), m_page->pageID()); +} + } // namespace WebKit #endif // ENABLE(FULLSCREEN_API) diff --git a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h index 04aed9a3f..9dab61c3c 100644 --- a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h @@ -28,16 +28,11 @@ #if ENABLE(FULLSCREEN_API) -#include "Connection.h" +#include "MessageReceiver.h" #include <wtf/PassRefPtr.h> +#include <wtf/RefCounted.h> #include <wtf/RefPtr.h> -namespace CoreIPC { -class ArgumentDecoder; -class Connection; -class MessageID; -} - namespace WebCore { class IntRect; } @@ -54,9 +49,6 @@ namespace WebKit { #if PLATFORM(MAC) typedef WKView PlatformWebView; -#elif PLATFORM(WIN) -class WebView; -typedef WebView PlatformWebView; #elif PLATFORM(QT) typedef QQuickWebView PlatformWebView; #elif PLATFORM(GTK) @@ -68,7 +60,7 @@ typedef Evas_Object PlatformWebView; class WebPageProxy; class LayerTreeContext; -class WebFullScreenManagerProxy : public RefCounted<WebFullScreenManagerProxy> { +class WebFullScreenManagerProxy : public RefCounted<WebFullScreenManagerProxy>, public CoreIPC::MessageReceiver { public: static PassRefPtr<WebFullScreenManagerProxy> create(WebPageProxy*); virtual ~WebFullScreenManagerProxy(); @@ -79,15 +71,14 @@ public: bool isFullScreen(); void close(); - void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - void willEnterFullScreen(); void didEnterFullScreen(); void willExitFullScreen(); void didExitFullScreen(); void setAnimatingFullScreen(bool); void requestExitFullScreen(); + void saveScrollPosition(); + void restoreScrollPosition(); private: explicit WebFullScreenManagerProxy(WebPageProxy*); @@ -98,11 +89,15 @@ private: void beganEnterFullScreen(const WebCore::IntRect& initialFrame, const WebCore::IntRect& finalFrame); void beganExitFullScreen(const WebCore::IntRect& initialFrame, const WebCore::IntRect& finalFrame); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + WebPageProxy* m_page; PlatformWebView* m_webView; - void didReceiveWebFullScreenManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebFullScreenManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); +#if PLATFORM(EFL) + bool m_hasRequestedFullScreen; +#endif }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp index 74b90797f..5f5408024 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2012, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -32,51 +32,68 @@ namespace WebKit { +const char* WebGeolocationManagerProxy::supplementName() +{ + return "WebGeolocationManagerProxy"; +} + PassRefPtr<WebGeolocationManagerProxy> WebGeolocationManagerProxy::create(WebContext* context) { return adoptRef(new WebGeolocationManagerProxy(context)); } WebGeolocationManagerProxy::WebGeolocationManagerProxy(WebContext* context) - : m_isUpdating(false) - , m_context(context) + : WebContextSupplement(context) + , m_isUpdating(false) { - m_context->addMessageReceiver(Messages::WebGeolocationManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebGeolocationManagerProxy::messageReceiverName(), this); } WebGeolocationManagerProxy::~WebGeolocationManagerProxy() { } -void WebGeolocationManagerProxy::invalidate() +void WebGeolocationManagerProxy::initializeProvider(const WKGeolocationProvider* provider) +{ + m_provider.initialize(provider); +} + +// WebContextSupplement + +void WebGeolocationManagerProxy::contextDestroyed() { stopUpdating(); } -void WebGeolocationManagerProxy::initializeProvider(const WKGeolocationProvider* provider) +void WebGeolocationManagerProxy::processDidClose(WebProcessProxy*) { - m_provider.initialize(provider); + stopUpdating(); } -void WebGeolocationManagerProxy::providerDidChangePosition(WebGeolocationPosition* position) +void WebGeolocationManagerProxy::refWebContextSupplement() { - if (!m_context) - return; + APIObject::ref(); +} - m_context->sendToAllProcesses(Messages::WebGeolocationManager::DidChangePosition(position->data())); +void WebGeolocationManagerProxy::derefWebContextSupplement() +{ + APIObject::deref(); } -void WebGeolocationManagerProxy::providerDidFailToDeterminePosition(const String& errorMessage) +void WebGeolocationManagerProxy::providerDidChangePosition(WebGeolocationPosition* position) { - if (!m_context) + if (!context()) return; - m_context->sendToAllProcesses(Messages::WebGeolocationManager::DidFailToDeterminePosition(errorMessage)); + context()->sendToAllProcesses(Messages::WebGeolocationManager::DidChangePosition(position->data())); } -void WebGeolocationManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebGeolocationManagerProxy::providerDidFailToDeterminePosition(const String& errorMessage) { - didReceiveWebGeolocationManagerProxyMessage(connection, messageID, decoder); + if (!context()) + return; + + context()->sendToAllProcesses(Messages::WebGeolocationManager::DidFailToDeterminePosition(errorMessage)); } void WebGeolocationManagerProxy::startUpdating() diff --git a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h index 81fc19e8e..a2d97c6ea 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2012, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,6 +28,7 @@ #include "APIObject.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include "WebGeolocationProvider.h" #include <wtf/text/WTFString.h> @@ -36,38 +37,38 @@ namespace WebKit { class WebContext; class WebGeolocationPosition; -class WebGeolocationManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebGeolocationManagerProxy : public TypedAPIObject<APIObject::TypeGeolocationManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeGeolocationManager; + static const char* supplementName(); static PassRefPtr<WebGeolocationManagerProxy> create(WebContext*); virtual ~WebGeolocationManagerProxy(); - void invalidate(); - void clearContext() { m_context = 0; } - void initializeProvider(const WKGeolocationProvider*); void providerDidChangePosition(WebGeolocationPosition*); void providerDidFailToDeterminePosition(const String& errorMessage = String()); + using APIObject::ref; + using APIObject::deref; + private: explicit WebGeolocationManagerProxy(WebContext*); - virtual Type type() const { return APIType; } + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - - // Implemented in generated WebGeolocationManagerProxyMessageReceiver.cpp - void didReceiveWebGeolocationManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; void startUpdating(); void stopUpdating(); bool m_isUpdating; - WebContext* m_context; WebGeolocationProvider m_provider; }; diff --git a/Source/WebKit2/UIProcess/WebGrammarDetail.h b/Source/WebKit2/UIProcess/WebGrammarDetail.h index 2fcebc0ec..0460740e6 100644 --- a/Source/WebKit2/UIProcess/WebGrammarDetail.h +++ b/Source/WebKit2/UIProcess/WebGrammarDetail.h @@ -35,9 +35,8 @@ namespace WebKit { class ImmutableArray; -class WebGrammarDetail : public APIObject { +class WebGrammarDetail : public TypedAPIObject<APIObject::TypeGrammarDetail> { public: - static const Type APIType = TypeGrammarDetail; static PassRefPtr<WebGrammarDetail> create(int location, int length, ImmutableArray* guesses, const String& userDescription); static PassRefPtr<WebGrammarDetail> create(const WebCore::GrammarDetail&); @@ -52,8 +51,6 @@ private: WebGrammarDetail(int location, int length, ImmutableArray* guesses, const String& userDescription); explicit WebGrammarDetail(const WebCore::GrammarDetail&); - virtual Type type() const { return APIType; } - WebCore::GrammarDetail m_grammarDetail; }; diff --git a/Source/WebKit2/UIProcess/WebIconDatabase.cpp b/Source/WebKit2/UIProcess/WebIconDatabase.cpp index 655921084..7b7f9984b 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabase.cpp +++ b/Source/WebKit2/UIProcess/WebIconDatabase.cpp @@ -228,7 +228,8 @@ void WebIconDatabase::checkIntegrityBeforeOpening() void WebIconDatabase::close() { - m_iconDatabaseImpl->close(); + if (m_iconDatabaseImpl) + m_iconDatabaseImpl->close(); } void WebIconDatabase::initializeIconDatabaseClient(const WKIconDatabaseClient* client) @@ -286,16 +287,6 @@ void WebIconDatabase::didFinishURLImport() m_urlImportCompleted = true; } -void WebIconDatabase::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveWebIconDatabaseMessage(connection, messageID, decoder); -} - -void WebIconDatabase::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) -{ - didReceiveSyncWebIconDatabaseMessage(connection, messageID, decoder, replyEncoder); -} - void WebIconDatabase::notifyIconDataReadyForPageURL(const String& pageURL) { m_iconDatabaseClient.iconDataReadyForPageURL(this, WebURL::create(pageURL).get()); diff --git a/Source/WebKit2/UIProcess/WebIconDatabase.h b/Source/WebKit2/UIProcess/WebIconDatabase.h index 0947ec00b..be1b3dcbc 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabase.h +++ b/Source/WebKit2/UIProcess/WebIconDatabase.h @@ -42,7 +42,6 @@ namespace CoreIPC { class ArgumentDecoder; class DataReference; -class MessageID; } namespace WebCore { @@ -54,10 +53,8 @@ namespace WebKit { class WebContext; -class WebIconDatabase : public APIObject, public WebCore::IconDatabaseClient, private CoreIPC::MessageReceiver { +class WebIconDatabase : public TypedAPIObject<APIObject::TypeIconDatabase>, public WebCore::IconDatabaseClient, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeIconDatabase; - static PassRefPtr<WebIconDatabase> create(WebContext*); virtual ~WebIconDatabase(); @@ -93,8 +90,6 @@ public: private: WebIconDatabase(WebContext*); - virtual Type type() const { return APIType; } - // WebCore::IconDatabaseClient virtual void didImportIconURLForPageURL(const String&); virtual void didImportIconDataForPageURL(const String&); @@ -103,11 +98,8 @@ private: virtual void didFinishURLImport(); // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; - - void didReceiveWebIconDatabaseMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebIconDatabaseMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; void notifyIconDataReadyForPageURL(const String&); diff --git a/Source/WebKit2/UIProcess/WebInspectorProxy.cpp b/Source/WebKit2/UIProcess/WebInspectorProxy.cpp index 5bc270282..98802fff3 100644 --- a/Source/WebKit2/UIProcess/WebInspectorProxy.cpp +++ b/Source/WebKit2/UIProcess/WebInspectorProxy.cpp @@ -32,6 +32,7 @@ #include "WebFramePolicyListenerProxy.h" #include "WebFrameProxy.h" #include "WebInspectorMessages.h" +#include "WebInspectorProxyMessages.h" #include "WebPageCreationParameters.h" #include "WebPageGroup.h" #include "WebPageProxy.h" @@ -42,20 +43,18 @@ #if ENABLE(INSPECTOR_SERVER) #include "WebInspectorServer.h" #endif -#if PLATFORM(WIN) -#include "WebView.h" -#endif using namespace WebCore; namespace WebKit { -const unsigned WebInspectorProxy::minimumWindowWidth = 500; +const unsigned WebInspectorProxy::minimumWindowWidth = 750; const unsigned WebInspectorProxy::minimumWindowHeight = 400; -const unsigned WebInspectorProxy::initialWindowWidth = 750; +const unsigned WebInspectorProxy::initialWindowWidth = 1000; const unsigned WebInspectorProxy::initialWindowHeight = 650; +const unsigned WebInspectorProxy::minimumAttachedWidth = 750; const unsigned WebInspectorProxy::minimumAttachedHeight = 250; static PassRefPtr<WebPageGroup> createInspectorPageGroup() @@ -65,10 +64,10 @@ static PassRefPtr<WebPageGroup> createInspectorPageGroup() #ifndef NDEBUG // Allow developers to inspect the Web Inspector in debug builds. pageGroup->preferences()->setDeveloperExtrasEnabled(true); + pageGroup->preferences()->setLogsPageMessagesToSystemConsoleEnabled(true); #endif pageGroup->preferences()->setApplicationChromeModeEnabled(true); - pageGroup->preferences()->setSuppressesIncrementalRendering(true); return pageGroup.release(); } @@ -86,9 +85,11 @@ WebInspectorProxy::WebInspectorProxy(WebPageProxy* page) , m_isDebuggingJavaScript(false) , m_isProfilingJavaScript(false) , m_isProfilingPage(false) -#if PLATFORM(WIN) - , m_inspectorWindow(0) -#elif PLATFORM(GTK) || PLATFORM(EFL) + , m_showMessageSent(false) + , m_createdInspectorPage(false) + , m_ignoreFirstBringToFront(false) + , m_attachmentSide(AttachmentSideBottom) +#if PLATFORM(GTK) || PLATFORM(EFL) , m_inspectorView(0) , m_inspectorWindow(0) #endif @@ -96,6 +97,7 @@ WebInspectorProxy::WebInspectorProxy(WebPageProxy* page) , m_remoteInspectionPageId(0) #endif { + m_page->process()->addMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_page->pageID(), this); } WebInspectorProxy::~WebInspectorProxy() @@ -109,15 +111,13 @@ void WebInspectorProxy::invalidate() WebInspectorServer::shared().unregisterPage(m_remoteInspectionPageId); #endif + m_page->process()->removeMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_page->pageID()); + m_page->close(); + didClose(); m_page = 0; - - m_isVisible = false; - m_isDebuggingJavaScript = false; - m_isProfilingJavaScript = false; - m_isProfilingPage = false; } // Public APIs @@ -129,20 +129,54 @@ bool WebInspectorProxy::isFront() return platformIsFront(); } -void WebInspectorProxy::show() +void WebInspectorProxy::connect() { if (!m_page) return; + if (m_showMessageSent) + return; + + m_showMessageSent = true; + m_ignoreFirstBringToFront = true; + m_page->process()->send(Messages::WebInspector::Show(), m_page->pageID()); } +void WebInspectorProxy::show() +{ + if (!m_page) + return; + + if (isConnected()) { + bringToFront(); + return; + } + + connect(); + + // Don't ignore the first bringToFront so it opens the Inspector. + m_ignoreFirstBringToFront = false; +} + +void WebInspectorProxy::hide() +{ + if (!m_page) + return; + + m_isVisible = false; + + platformHide(); +} + void WebInspectorProxy::close() { if (!m_page) return; m_page->process()->send(Messages::WebInspector::Close(), m_page->pageID()); + + didClose(); } void WebInspectorProxy::showConsole() @@ -165,33 +199,57 @@ void WebInspectorProxy::showMainResourceForFrame(WebFrameProxy* frame) { if (!m_page) return; - + m_page->process()->send(Messages::WebInspector::ShowMainResourceForFrame(frame->frameID()), m_page->pageID()); } -void WebInspectorProxy::attach() +void WebInspectorProxy::attachBottom() +{ + attach(AttachmentSideBottom); +} + +void WebInspectorProxy::attachRight() { - if (!canAttach()) + attach(AttachmentSideRight); +} + +void WebInspectorProxy::attach(AttachmentSide side) +{ + if (!m_page || !canAttach()) return; m_isAttached = true; + m_attachmentSide = side; + + inspectorPageGroup()->preferences()->setInspectorAttachmentSide(side); if (m_isVisible) inspectorPageGroup()->preferences()->setInspectorStartsAttached(true); - m_page->process()->send(Messages::WebInspector::SetAttachedWindow(true), m_page->pageID()); + switch (m_attachmentSide) { + case AttachmentSideBottom: + m_page->process()->send(Messages::WebInspector::AttachedBottom(), m_page->pageID()); + break; + + case AttachmentSideRight: + m_page->process()->send(Messages::WebInspector::AttachedRight(), m_page->pageID()); + break; + } platformAttach(); } void WebInspectorProxy::detach() { + if (!m_page) + return; + m_isAttached = false; - + if (m_isVisible) inspectorPageGroup()->preferences()->setInspectorStartsAttached(false); - m_page->process()->send(Messages::WebInspector::SetAttachedWindow(false), m_page->pageID()); + m_page->process()->send(Messages::WebInspector::Detached(), m_page->pageID()); platformDetach(); } @@ -202,6 +260,12 @@ void WebInspectorProxy::setAttachedWindowHeight(unsigned height) platformSetAttachedWindowHeight(height); } +void WebInspectorProxy::setAttachedWindowWidth(unsigned width) +{ + inspectorPageGroup()->preferences()->setInspectorAttachedWidth(width); + platformSetAttachedWindowWidth(width); +} + void WebInspectorProxy::toggleJavaScriptDebugging() { if (!m_page) @@ -311,6 +375,7 @@ void WebInspectorProxy::createInspectorPage(uint64_t& inspectorPageID, WebPageCr return; m_isAttached = shouldOpenAttached(); + m_attachmentSide = static_cast<AttachmentSide>(inspectorPageGroup()->preferences()->inspectorAttachmentSide()); WebPageProxy* inspectorPage = platformCreateInspectorPage(); ASSERT(inspectorPage); @@ -332,41 +397,71 @@ void WebInspectorProxy::createInspectorPage(uint64_t& inspectorPageID, WebPageCr inspectorPage->initializePolicyClient(&policyClient); String url = inspectorPageURL(); + url.append("?dockSide="); - url.append(m_isAttached ? "bottom" : "undocked"); + + if (m_isAttached) { + switch (m_attachmentSide) { + case AttachmentSideBottom: + url.append("bottom"); + m_page->process()->send(Messages::WebInspector::AttachedBottom(), m_page->pageID()); + break; + case AttachmentSideRight: + url.append("right"); + m_page->process()->send(Messages::WebInspector::AttachedRight(), m_page->pageID()); + break; + } + } else + url.append("undocked"); m_page->process()->assumeReadAccessToBaseURL(inspectorBaseURL()); inspectorPage->loadURL(url); + + m_createdInspectorPage = true; } -void WebInspectorProxy::didLoadInspectorPage() +void WebInspectorProxy::open() { m_isVisible = true; - // platformOpen is responsible for rendering attached mode depending on m_isAttached. platformOpen(); } void WebInspectorProxy::didClose() { + if (!m_createdInspectorPage) + return; + m_isVisible = false; m_isDebuggingJavaScript = false; m_isProfilingJavaScript = false; m_isProfilingPage = false; + m_createdInspectorPage = false; + m_showMessageSent = false; + m_ignoreFirstBringToFront = false; - if (m_isAttached) { - // Detach here so we only need to have one code path that is responsible for cleaning up the inspector - // state. - detach(); - } + if (m_isAttached) + platformDetach(); + m_isAttached = false; platformDidClose(); } void WebInspectorProxy::bringToFront() { - platformBringToFront(); + // WebCore::InspectorFrontendClientLocal tells us to do this on load. We want to + // ignore it once if we only wanted to connect. This allows the Inspector to later + // request to be brought to the front when a breakpoint is hit or some other action. + if (m_ignoreFirstBringToFront) { + m_ignoreFirstBringToFront = false; + return; + } + + if (m_isVisible) + platformBringToFront(); + else + open(); } void WebInspectorProxy::attachAvailabilityChanged(bool available) @@ -379,6 +474,16 @@ void WebInspectorProxy::inspectedURLChanged(const String& urlString) platformInspectedURLChanged(urlString); } +void WebInspectorProxy::save(const String& filename, const String& content, bool forceSaveAs) +{ + platformSave(filename, content, forceSaveAs); +} + +void WebInspectorProxy::append(const String& filename, const String& content) +{ + platformAppend(filename, content); +} + bool WebInspectorProxy::canAttach() { // Keep this in sync with InspectorFrontendClientLocal::canAttachWindow. There are two implementations @@ -386,12 +491,20 @@ bool WebInspectorProxy::canAttach() // we can attach on open (on the UI process side). And InspectorFrontendClientLocal::canAttachWindow is // used to decide if we can attach when the attach button is pressed (on the WebProcess side). - // Don't allow the attach if the window would be too small to accommodate the minimum inspector height. - // Also don't allow attaching to another inspector -- two inspectors in one window is too much! + // If we are already attached, allow attaching again to allow switching sides. + if (m_isAttached) + return true; + + // Don't allow attaching to another inspector -- two inspectors in one window is too much! bool isInspectorPage = m_page->pageGroup() == inspectorPageGroup(); + if (isInspectorPage) + return false; + + // Don't allow the attach if the window would be too small to accommodate the minimum inspector height. unsigned inspectedPageHeight = platformInspectedWindowHeight(); + unsigned inspectedPageWidth = platformInspectedWindowWidth(); unsigned maximumAttachedHeight = inspectedPageHeight * 3 / 4; - return minimumAttachedHeight <= maximumAttachedHeight && !isInspectorPage; + return minimumAttachedHeight <= maximumAttachedHeight && minimumAttachedWidth <= inspectedPageWidth; } bool WebInspectorProxy::shouldOpenAttached() diff --git a/Source/WebKit2/UIProcess/WebInspectorProxy.h b/Source/WebKit2/UIProcess/WebInspectorProxy.h index 4a94d2e60..ef46b7823 100644 --- a/Source/WebKit2/UIProcess/WebInspectorProxy.h +++ b/Source/WebKit2/UIProcess/WebInspectorProxy.h @@ -30,7 +30,7 @@ #if ENABLE(INSPECTOR) #include "APIObject.h" -#include "Connection.h" +#include "MessageReceiver.h" #include <wtf/Forward.h> #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> @@ -38,18 +38,16 @@ #if PLATFORM(MAC) #include "WKGeometry.h" +#include <wtf/HashMap.h> #include <wtf/RetainPtr.h> OBJC_CLASS NSButton; +OBJC_CLASS NSURL; OBJC_CLASS NSWindow; OBJC_CLASS WKWebInspectorProxyObjCAdapter; OBJC_CLASS WKWebInspectorWKView; #endif -#if PLATFORM(WIN) -#include <WebCore/WindowMessageListener.h> -#endif - #if PLATFORM(GTK) #include "WebInspectorClientGtk.h" #endif @@ -66,18 +64,13 @@ class WebPageGroup; class WebPageProxy; struct WebPageCreationParameters; -#if PLATFORM(WIN) -class WebView; -#endif +enum AttachmentSide { + AttachmentSideBottom, + AttachmentSideRight +}; -class WebInspectorProxy : public APIObject -#if PLATFORM(WIN) - , public WebCore::WindowMessageListener -#endif -{ +class WebInspectorProxy : public TypedAPIObject<APIObject::TypeInspector>, public CoreIPC::MessageReceiver { public: - static const Type APIType = TypeInspector; - static PassRefPtr<WebInspectorProxy> create(WebPageProxy* page) { return adoptRef(new WebInspectorProxy(page)); @@ -90,16 +83,22 @@ public: // Public APIs WebPageProxy* page() const { return m_page; } + bool isConnected() const { return m_createdInspectorPage; } bool isVisible() const { return m_isVisible; } bool isFront(); + void connect(); + void show(); + void hide(); void close(); #if PLATFORM(MAC) void createInspectorWindow(); void updateInspectorWindowTitle() const; - void inspectedViewFrameDidChange(); + void inspectedViewFrameDidChange(CGFloat = 0); + void windowFrameDidChange(); + NSWindow* inspectorWindow() const { return m_inspectorWindow.get(); } void setInspectorWindowFrame(WKRect&); WKRect inspectorWindowFrame(); @@ -115,9 +114,14 @@ public: void showMainResourceForFrame(WebFrameProxy*); bool isAttached() const { return m_isAttached; } - void attach(); + void attachRight(); + void attachBottom(); + void attach(AttachmentSide = AttachmentSideBottom); void detach(); + void setAttachedWindowHeight(unsigned); + void setAttachedWindowWidth(unsigned); + void setToolbarHeight(unsigned height) { platformSetToolbarHeight(height); } bool isDebuggingJavaScript() const { return m_isDebuggingJavaScript; } void toggleJavaScriptDebugging(); @@ -128,12 +132,6 @@ public: bool isProfilingPage() const { return m_isProfilingPage; } void togglePageProfiling(); -#if ENABLE(INSPECTOR) - // Implemented in generated WebInspectorProxyMessageReceiver.cpp - void didReceiveWebInspectorProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebInspectorProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); -#endif - static bool isInspectorPage(WebPageProxy*); // Implemented the platform WebInspectorProxy file @@ -151,28 +149,38 @@ public: private: explicit WebInspectorProxy(WebPageProxy*); - virtual Type type() const { return APIType; } + // CoreIPC::MessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; WebPageProxy* platformCreateInspectorPage(); void platformOpen(); void platformDidClose(); void platformBringToFront(); + void platformHide(); bool platformIsFront(); void platformAttachAvailabilityChanged(bool); void platformInspectedURLChanged(const String&); unsigned platformInspectedWindowHeight(); + unsigned platformInspectedWindowWidth(); void platformAttach(); void platformDetach(); void platformSetAttachedWindowHeight(unsigned); + void platformSetAttachedWindowWidth(unsigned); + void platformSetToolbarHeight(unsigned); + void platformSave(const String& filename, const String& content, bool forceSaveAs); + void platformAppend(const String& filename, const String& content); // Called by WebInspectorProxy messages void createInspectorPage(uint64_t& inspectorPageID, WebPageCreationParameters&); - void didLoadInspectorPage(); void didClose(); void bringToFront(); void attachAvailabilityChanged(bool); void inspectedURLChanged(const String&); + void save(const String& filename, const String& content, bool forceSaveAs); + void append(const String& filename, const String& content); + #if ENABLE(INSPECTOR_SERVER) void sendMessageToRemoteFrontend(const String& message); #endif @@ -180,21 +188,9 @@ private: bool canAttach(); bool shouldOpenAttached(); - static WebPageGroup* inspectorPageGroup(); - -#if PLATFORM(WIN) - static bool registerInspectorViewWindowClass(); - static LRESULT CALLBACK InspectorViewWndProc(HWND, UINT, WPARAM, LPARAM); - LRESULT wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); + void open(); - LRESULT onSizeEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onMinMaxInfoEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onSetFocusEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onCloseEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - - void onWebViewWindowPosChangingEvent(WPARAM, LPARAM); - virtual void windowReceivedMessage(HWND, UINT message, WPARAM, LPARAM); -#endif + static WebPageGroup* inspectorPageGroup(); #if PLATFORM(GTK) || PLATFORM(EFL) void createInspectorWindow(); @@ -207,6 +203,7 @@ private: static const unsigned initialWindowHeight; // Keep this in sync with the value in InspectorFrontendClientLocal. + static const unsigned minimumAttachedWidth; static const unsigned minimumAttachedHeight; WebPageProxy* m_page; @@ -216,16 +213,20 @@ private: bool m_isDebuggingJavaScript; bool m_isProfilingJavaScript; bool m_isProfilingPage; + bool m_showMessageSent; + bool m_createdInspectorPage; + bool m_ignoreFirstBringToFront; + + AttachmentSide m_attachmentSide; #if PLATFORM(MAC) RetainPtr<WKWebInspectorWKView> m_inspectorView; RetainPtr<NSWindow> m_inspectorWindow; - RetainPtr<NSButton> m_dockButton; + RetainPtr<NSButton> m_dockBottomButton; + RetainPtr<NSButton> m_dockRightButton; RetainPtr<WKWebInspectorProxyObjCAdapter> m_inspectorProxyObjCAdapter; String m_urlString; -#elif PLATFORM(WIN) - HWND m_inspectorWindow; - RefPtr<WebView> m_inspectorView; + HashMap<String, RetainPtr<NSURL>> m_suggestedToActualURLMap; #elif PLATFORM(GTK) WebInspectorClientGtk m_client; GtkWidget* m_inspectorView; diff --git a/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in b/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in index 27a81d80f..17f77a5ca 100644 --- a/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in @@ -24,15 +24,21 @@ messages -> WebInspectorProxy { CreateInspectorPage() -> (uint64_t inspectorPageID, WebKit::WebPageCreationParameters inspectorPageParameters) - DidLoadInspectorPage() DidClose() BringToFront() InspectedURLChanged(WTF::String urlString) - Attach() + Save(WTF::String filename, WTF::String content, bool forceSaveAs) + Append(WTF::String filename, WTF::String content) + + AttachBottom() + AttachRight() Detach() AttachAvailabilityChanged(bool available) + SetAttachedWindowHeight(unsigned height) + SetAttachedWindowWidth(unsigned width) + SetToolbarHeight(unsigned height) #if ENABLE(INSPECTOR_SERVER) SendMessageToRemoteFrontend(WTF::String message) diff --git a/Source/WebKit2/UIProcess/WebIntentData.cpp b/Source/WebKit2/UIProcess/WebIntentData.cpp deleted file mode 100644 index c6d8c64ba..000000000 --- a/Source/WebKit2/UIProcess/WebIntentData.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebIntentData.h" - -#if ENABLE(WEB_INTENTS) - -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "WebProcessProxy.h" -#include "WebSerializedScriptValue.h" -#include "WebString.h" -#include "WebURL.h" - -namespace WebKit { - -WebIntentData::WebIntentData(const IntentData& store, WebProcessProxy* process) - : m_store(store) - , m_process(process) -{ -} - -WebIntentData::~WebIntentData() -{ - // Remove MessagePortChannels from WebProcess. - if (m_process) { - size_t numMessagePorts = m_store.messagePorts.size(); - for (size_t i = 0; i < numMessagePorts; ++i) - m_process->removeMessagePortChannel(m_store.messagePorts[i]); - } -} - -PassRefPtr<WebSerializedScriptValue> WebIntentData::data() const -{ - Vector<uint8_t> dataCopy = m_store.data; - return WebSerializedScriptValue::adopt(dataCopy); -} - -PassRefPtr<ImmutableArray> WebIntentData::suggestions() const -{ - const size_t numSuggestions = m_store.suggestions.size(); - Vector<RefPtr<APIObject> > wkSuggestions(numSuggestions); - for (unsigned i = 0; i < numSuggestions; ++i) - wkSuggestions[i] = WebURL::create(m_store.suggestions[i]); - return ImmutableArray::adopt(wkSuggestions); -} - -String WebIntentData::extra(const String& key) const -{ - return m_store.extras.get(key); -} - -PassRefPtr<ImmutableDictionary> WebIntentData::extras() const -{ - ImmutableDictionary::MapType wkExtras; - HashMap<String, String>::const_iterator end = m_store.extras.end(); - for (HashMap<String, String>::const_iterator it = m_store.extras.begin(); it != end; ++it) - wkExtras.set(it->key, WebString::create(it->value)); - - return ImmutableDictionary::adopt(wkExtras); -} - -} // namespace WebKit - -#endif // ENABLE(WEB_INTENTS) - diff --git a/Source/WebKit2/UIProcess/WebKeyValueStorageManager.cpp b/Source/WebKit2/UIProcess/WebKeyValueStorageManager.cpp new file mode 100644 index 000000000..8507543c0 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebKeyValueStorageManager.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebKeyValueStorageManager.h" + +#include "SecurityOriginData.h" +#include "WebContext.h" +#include "WebSecurityOrigin.h" + +using namespace WebCore; + +namespace WebKit { + +const char* WebKeyValueStorageManager::supplementName() +{ + return "WebKeyValueStorageManager"; +} + +PassRefPtr<WebKeyValueStorageManager> WebKeyValueStorageManager::create(WebContext* context) +{ + return adoptRef(new WebKeyValueStorageManager(context)); +} + +WebKeyValueStorageManager::WebKeyValueStorageManager(WebContext* context) + : WebContextSupplement(context) +{ +} + +WebKeyValueStorageManager::~WebKeyValueStorageManager() +{ +} + +// WebContextSupplement + +void WebKeyValueStorageManager::refWebContextSupplement() +{ + APIObject::ref(); +} + +void WebKeyValueStorageManager::derefWebContextSupplement() +{ + APIObject::deref(); +} + +static void didGetKeyValueStorageOrigins(const Vector<RefPtr<WebCore::SecurityOrigin>>& securityOrigins, void* context) +{ + RefPtr<ArrayCallback> callback = adoptRef(static_cast<ArrayCallback*>(context)); + + Vector<RefPtr<APIObject>> webSecurityOrigins; + webSecurityOrigins.reserveInitialCapacity(securityOrigins.size()); + + for (unsigned i = 0; i < securityOrigins.size(); ++i) + webSecurityOrigins.uncheckedAppend(WebSecurityOrigin::create(securityOrigins[i])); + + callback->performCallbackWithReturnValue(ImmutableArray::adopt(webSecurityOrigins).get()); +} + +void WebKeyValueStorageManager::getKeyValueStorageOrigins(PassRefPtr<ArrayCallback> prpCallback) +{ + context()->storageManager().getOrigins(RunLoop::main(), prpCallback.leakRef(), didGetKeyValueStorageOrigins); +} + +void WebKeyValueStorageManager::deleteEntriesForOrigin(WebSecurityOrigin* origin) +{ + context()->storageManager().deleteEntriesForOrigin(origin->securityOrigin()); +} + +void WebKeyValueStorageManager::deleteAllEntries() +{ + context()->storageManager().deleteAllEntries(); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.h b/Source/WebKit2/UIProcess/WebKeyValueStorageManager.h index ba392bb2e..eb1c8eb6e 100644 --- a/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebKeyValueStorageManager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,57 +23,44 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebKeyValueStorageManagerProxy_h -#define WebKeyValueStorageManagerProxy_h +#ifndef WebKeyValueStorageManager_h +#define WebKeyValueStorageManager_h #include "APIObject.h" #include "GenericCallback.h" #include "ImmutableArray.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/Vector.h> namespace WebKit { -struct SecurityOriginData; -class WebContext; -class WebProcessProxy; -class WebSecurityOrigin; - typedef GenericCallback<WKArrayRef> ArrayCallback; -class WebKeyValueStorageManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebKeyValueStorageManager : public TypedAPIObject<APIObject::TypeKeyValueStorageManager>, public WebContextSupplement { public: - static const Type APIType = TypeKeyValueStorageManager; + static const char* supplementName(); - static PassRefPtr<WebKeyValueStorageManagerProxy> create(WebContext*); - virtual ~WebKeyValueStorageManagerProxy(); + static PassRefPtr<WebKeyValueStorageManager> create(WebContext*); + virtual ~WebKeyValueStorageManager(); - void invalidate(); - void clearContext() { m_webContext = 0; } - void getKeyValueStorageOrigins(PassRefPtr<ArrayCallback>); void deleteEntriesForOrigin(WebSecurityOrigin*); void deleteAllEntries(); - bool shouldTerminate(WebProcessProxy*) const; + using APIObject::ref; + using APIObject::deref; private: - explicit WebKeyValueStorageManagerProxy(WebContext*); - - virtual Type type() const { return APIType; } - - void didGetKeyValueStorageOrigins(const Vector<SecurityOriginData>&, uint64_t callbackID); - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebKeyValueStorageManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + explicit WebKeyValueStorageManager(WebContext*); - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; + // WebContextSupplement + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; }; } // namespace WebKit -#endif // WebKeyValueStorageManagerProxy_h +#endif // WebKeyValueStorageManager_h diff --git a/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.cpp b/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.cpp deleted file mode 100644 index 43f69a445..000000000 --- a/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebKeyValueStorageManagerProxy.h" - -#include "SecurityOriginData.h" -#include "WebContext.h" -#include "WebKeyValueStorageManagerMessages.h" -#include "WebKeyValueStorageManagerProxyMessages.h" -#include "WebSecurityOrigin.h" - -namespace WebKit { - -PassRefPtr<WebKeyValueStorageManagerProxy> WebKeyValueStorageManagerProxy::create(WebContext* context) -{ - return adoptRef(new WebKeyValueStorageManagerProxy(context)); -} - -WebKeyValueStorageManagerProxy::WebKeyValueStorageManagerProxy(WebContext* context) - : m_webContext(context) -{ - m_webContext->addMessageReceiver(Messages::WebKeyValueStorageManagerProxy::messageReceiverName(), this); -} - -WebKeyValueStorageManagerProxy::~WebKeyValueStorageManagerProxy() -{ -} - -void WebKeyValueStorageManagerProxy::invalidate() -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -bool WebKeyValueStorageManagerProxy::shouldTerminate(WebProcessProxy*) const -{ - return m_arrayCallbacks.isEmpty(); -} - -void WebKeyValueStorageManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveWebKeyValueStorageManagerProxyMessage(connection, messageID, decoder); -} - -void WebKeyValueStorageManagerProxy::getKeyValueStorageOrigins(PassRefPtr<ArrayCallback> prpCallback) -{ - RefPtr<ArrayCallback> callback = prpCallback; - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Should key-value storage be handled in the web process? - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebKeyValueStorageManager::GetKeyValueStorageOrigins(callbackID)); -} - -void WebKeyValueStorageManagerProxy::didGetKeyValueStorageOrigins(const Vector<SecurityOriginData>& originDatas, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - performAPICallbackWithSecurityOriginDataVector(originDatas, callback.get()); -} - -void WebKeyValueStorageManagerProxy::deleteEntriesForOrigin(WebSecurityOrigin* origin) -{ - SecurityOriginData securityOriginData; - securityOriginData.protocol = origin->protocol(); - securityOriginData.host = origin->host(); - securityOriginData.port = origin->port(); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Should key-value storage be handled in the web process? - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebKeyValueStorageManager::DeleteEntriesForOrigin(securityOriginData)); -} - -void WebKeyValueStorageManagerProxy::deleteAllEntries() -{ - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Should key-value storage be handled in the web process? - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebKeyValueStorageManager::DeleteAllEntries()); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebLoaderClient.cpp b/Source/WebKit2/UIProcess/WebLoaderClient.cpp index 93c60d430..82123f4d8 100644 --- a/Source/WebKit2/UIProcess/WebLoaderClient.cpp +++ b/Source/WebKit2/UIProcess/WebLoaderClient.cpp @@ -27,15 +27,13 @@ #include "WebLoaderClient.h" #include "ImmutableArray.h" +#include "ImmutableDictionary.h" +#include "PluginInformation.h" #include "WKAPICast.h" #include "WebBackForwardListItem.h" +#include "WebPageProxy.h" #include <string.h> -#if ENABLE(WEB_INTENTS) -#include "WebIntentData.h" -#include "WebIntentServiceInfo.h" -#endif - using namespace WebCore; namespace WebKit { @@ -176,26 +174,6 @@ void WebLoaderClient::didDetectXSSForFrame(WebPageProxy* page, WebFrameProxy* fr m_client.didDetectXSSForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); } -#if ENABLE(WEB_INTENTS) -void WebLoaderClient::didReceiveIntentForFrame(WebPageProxy* page, WebFrameProxy* frame, WebIntentData* intentData, APIObject* userData) -{ - if (!m_client.didReceiveIntentForFrame) - return; - - m_client.didReceiveIntentForFrame(toAPI(page), toAPI(frame), toAPI(intentData), toAPI(userData), m_client.clientInfo); -} -#endif - -#if ENABLE(WEB_INTENTS_TAG) -void WebLoaderClient::registerIntentServiceForFrame(WebPageProxy* page, WebFrameProxy* frame, WebIntentServiceInfo* serviceInfo, APIObject* userData) -{ - if (!m_client.registerIntentServiceForFrame) - return; - - m_client.registerIntentServiceForFrame(toAPI(page), toAPI(frame), toAPI(serviceInfo), toAPI(userData), m_client.clientInfo); -} -#endif - bool WebLoaderClient::canAuthenticateAgainstProtectionSpaceInFrame(WebPageProxy* page, WebFrameProxy* frame, WebProtectionSpace* protectionSpace) { if (!m_client.canAuthenticateAgainstProtectionSpaceInFrame) @@ -268,7 +246,7 @@ void WebLoaderClient::processDidCrash(WebPageProxy* page) m_client.processDidCrash(toAPI(page), m_client.clientInfo); } -void WebLoaderClient::didChangeBackForwardList(WebPageProxy* page, WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject> >* removedItems) +void WebLoaderClient::didChangeBackForwardList(WebPageProxy* page, WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject>>* removedItems) { if (!m_client.didChangeBackForwardList) return; @@ -297,23 +275,66 @@ void WebLoaderClient::willGoToBackForwardListItem(WebPageProxy* page, WebBackFor m_client.willGoToBackForwardListItem(toAPI(page), toAPI(item), toAPI(userData), m_client.clientInfo); } -void WebLoaderClient::didFailToInitializePlugin(WebPageProxy* page, const String& mimeType) +void WebLoaderClient::didFailToInitializePlugin(WebPageProxy* page, ImmutableDictionary* pluginInformation) { if (m_client.didFailToInitializePlugin_deprecatedForUseWithV0) - m_client.didFailToInitializePlugin_deprecatedForUseWithV0(toAPI(page), toAPI(mimeType.impl()), m_client.clientInfo); - - if (!m_client.pluginDidFail) - return; - - m_client.pluginDidFail(toAPI(page), kWKErrorCodeCannotLoadPlugIn, toAPI(mimeType.impl()), 0, 0, m_client.clientInfo); -} - -void WebLoaderClient::didBlockInsecurePluginVersion(WebPageProxy* page, const String& mimeType, const String& pluginIdentifier, const String& pluginVersion) -{ - if (!m_client.pluginDidFail) - return; - - m_client.pluginDidFail(toAPI(page), kWKErrorCodeInsecurePlugInVersion, toAPI(mimeType.impl()), toAPI(pluginIdentifier.impl()), toAPI(pluginVersion.impl()), m_client.clientInfo); + m_client.didFailToInitializePlugin_deprecatedForUseWithV0( + toAPI(page), + toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), + m_client.clientInfo); + + if (m_client.pluginDidFail_deprecatedForUseWithV1) + m_client.pluginDidFail_deprecatedForUseWithV1( + toAPI(page), + kWKErrorCodeCannotLoadPlugIn, + toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), + 0, + 0, + m_client.clientInfo); + + if (m_client.pluginDidFail) + m_client.pluginDidFail( + toAPI(page), + kWKErrorCodeCannotLoadPlugIn, + toAPI(pluginInformation), + m_client.clientInfo); +} + +void WebLoaderClient::didBlockInsecurePluginVersion(WebPageProxy* page, ImmutableDictionary* pluginInformation) +{ + if (m_client.pluginDidFail_deprecatedForUseWithV1) + m_client.pluginDidFail_deprecatedForUseWithV1( + toAPI(page), + kWKErrorCodeInsecurePlugInVersion, + toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), + toAPI(pluginInformation->get<WebString>(pluginInformationBundleIdentifierKey())), + toAPI(pluginInformation->get<WebString>(pluginInformationBundleVersionKey())), + m_client.clientInfo); + + if (m_client.pluginDidFail) + m_client.pluginDidFail( + toAPI(page), + kWKErrorCodeInsecurePlugInVersion, + toAPI(pluginInformation), + m_client.clientInfo); +} + +PluginModuleLoadPolicy WebLoaderClient::pluginLoadPolicy(WebPageProxy* page, PluginModuleLoadPolicy currentPluginLoadPolicy, ImmutableDictionary* pluginInformation, String& unavailabilityDescription) +{ + WKStringRef unavailabilityDescriptionOut = 0; + PluginModuleLoadPolicy loadPolicy = currentPluginLoadPolicy; + + if (m_client.pluginLoadPolicy_deprecatedForUseWithV2) + loadPolicy = toPluginModuleLoadPolicy(m_client.pluginLoadPolicy_deprecatedForUseWithV2(toAPI(page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), m_client.clientInfo)); + else if (m_client.pluginLoadPolicy) + loadPolicy = toPluginModuleLoadPolicy(m_client.pluginLoadPolicy(toAPI(page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), &unavailabilityDescriptionOut, m_client.clientInfo)); + + if (unavailabilityDescriptionOut) { + RefPtr<WebString> webUnavailabilityDescription = adoptRef(toImpl(unavailabilityDescriptionOut)); + unavailabilityDescription = webUnavailabilityDescription->string(); + } + + return loadPolicy; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebLoaderClient.h b/Source/WebKit2/UIProcess/WebLoaderClient.h index 85f107287..ce5a31cb3 100644 --- a/Source/WebKit2/UIProcess/WebLoaderClient.h +++ b/Source/WebKit2/UIProcess/WebLoaderClient.h @@ -27,6 +27,7 @@ #define WebLoaderClient_h #include "APIClient.h" +#include "PluginModuleInfo.h" #include "SameDocumentNavigationType.h" #include "WKPage.h" #include <WebCore/LayoutMilestones.h> @@ -43,19 +44,12 @@ namespace WebKit { class APIObject; class AuthenticationChallengeProxy; class AuthenticationDecisionListener; +class ImmutableDictionary; class WebBackForwardListItem; class WebFrameProxy; class WebPageProxy; class WebProtectionSpace; -#if ENABLE(WEB_INTENTS) -class WebIntentData; -#endif - -#if ENABLE(WEB_INTENTS_TAG) -class WebIntentServiceInfo; -#endif - class WebLoaderClient : public APIClient<WKPageLoaderClient, kWKPageLoaderClientCurrentVersion> { public: void didStartProvisionalLoadForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); @@ -73,13 +67,6 @@ public: void didDisplayInsecureContentForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); void didRunInsecureContentForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); void didDetectXSSForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); -#if ENABLE(WEB_INTENTS) - void didReceiveIntentForFrame(WebPageProxy*, WebFrameProxy*, WebIntentData*, APIObject*); -#endif - -#if ENABLE(WEB_INTENTS_TAG) - void registerIntentServiceForFrame(WebPageProxy*, WebFrameProxy*, WebIntentServiceInfo*, APIObject*); -#endif // FIXME: didNewFirstVisuallyNonEmptyLayout should be removed. We should consider removing didFirstVisuallyNonEmptyLayoutForFrame // as well. They are both being replaced by didLayout. @@ -99,12 +86,13 @@ public: void processDidBecomeResponsive(WebPageProxy*); void processDidCrash(WebPageProxy*); - void didChangeBackForwardList(WebPageProxy*, WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject> >* removedItems); + void didChangeBackForwardList(WebPageProxy*, WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject>>* removedItems); bool shouldGoToBackForwardListItem(WebPageProxy*, WebBackForwardListItem*); void willGoToBackForwardListItem(WebPageProxy*, WebBackForwardListItem*, APIObject*); - void didFailToInitializePlugin(WebPageProxy*, const String& mimeType); - void didBlockInsecurePluginVersion(WebPageProxy*, const String& mimeType, const String& pluginIdentifier, const String& pluginVersion); + PluginModuleLoadPolicy pluginLoadPolicy(WebPageProxy*, PluginModuleLoadPolicy currentPluginLoadPolicy, ImmutableDictionary*, String& unavailabilityDescriptionOutParameter); + void didFailToInitializePlugin(WebPageProxy*, ImmutableDictionary*); + void didBlockInsecurePluginVersion(WebPageProxy*, ImmutableDictionary*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp index b0f9bd196..b8d6ffd8f 100644 --- a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -33,22 +33,34 @@ namespace WebKit { +const char* WebMediaCacheManagerProxy::supplementName() +{ + return "WebMediaCacheManagerProxy"; +} + PassRefPtr<WebMediaCacheManagerProxy> WebMediaCacheManagerProxy::create(WebContext* context) { return adoptRef(new WebMediaCacheManagerProxy(context)); } WebMediaCacheManagerProxy::WebMediaCacheManagerProxy(WebContext* context) - : m_webContext(context) + : WebContextSupplement(context) { - m_webContext->addMessageReceiver(Messages::WebMediaCacheManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebMediaCacheManagerProxy::messageReceiverName(), this); } WebMediaCacheManagerProxy::~WebMediaCacheManagerProxy() { } -void WebMediaCacheManagerProxy::invalidate() +// WebContextSupplement + +void WebMediaCacheManagerProxy::contextDestroyed() +{ + invalidateCallbackMap(m_arrayCallbacks); +} + +void WebMediaCacheManagerProxy::processDidClose(WebProcessProxy*) { invalidateCallbackMap(m_arrayCallbacks); } @@ -58,9 +70,14 @@ bool WebMediaCacheManagerProxy::shouldTerminate(WebProcessProxy*) const return m_arrayCallbacks.isEmpty(); } -void WebMediaCacheManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebMediaCacheManagerProxy::refWebContextSupplement() +{ + APIObject::ref(); +} + +void WebMediaCacheManagerProxy::derefWebContextSupplement() { - didReceiveWebMediaCacheManagerProxyMessage(connection, messageID, decoder); + APIObject::deref(); } void WebMediaCacheManagerProxy::getHostnamesWithMediaCache(PassRefPtr<ArrayCallback> prpCallback) @@ -70,7 +87,7 @@ void WebMediaCacheManagerProxy::getHostnamesWithMediaCache(PassRefPtr<ArrayCallb m_arrayCallbacks.set(callbackID, callback.release()); // FIXME (Multi-WebProcess): <rdar://problem/12239765> When we're sending this to multiple processes, we need to aggregate the callback data when it comes back. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::GetHostnamesWithMediaCache(callbackID)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::GetHostnamesWithMediaCache(callbackID)); } void WebMediaCacheManagerProxy::didGetHostnamesWithMediaCache(const Vector<String>& hostnameList, uint64_t callbackID) @@ -82,7 +99,7 @@ void WebMediaCacheManagerProxy::didGetHostnamesWithMediaCache(const Vector<Strin } size_t hostnameCount = hostnameList.size(); - Vector<RefPtr<APIObject> > hostnames(hostnameCount); + Vector<RefPtr<APIObject>> hostnames(hostnameCount); for (size_t i = 0; i < hostnameCount; ++i) hostnames[i] = WebString::create(hostnameList[i]); @@ -92,12 +109,12 @@ void WebMediaCacheManagerProxy::didGetHostnamesWithMediaCache(const Vector<Strin void WebMediaCacheManagerProxy::clearCacheForHostname(const String& hostname) { - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::ClearCacheForHostname(hostname)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::ClearCacheForHostname(hostname)); } void WebMediaCacheManagerProxy::clearCacheForAllHostnames() { - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::ClearCacheForAllHostnames()); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::ClearCacheForAllHostnames()); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h index 4531a7210..5d557879e 100644 --- a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,6 +30,7 @@ #include "GenericCallback.h" #include "ImmutableArray.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/Vector.h> @@ -41,35 +42,36 @@ class WebProcessProxy; typedef GenericCallback<WKArrayRef> ArrayCallback; -class WebMediaCacheManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebMediaCacheManagerProxy : public TypedAPIObject<APIObject::TypeMediaCacheManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeMediaCacheManager; + static const char* supplementName(); static PassRefPtr<WebMediaCacheManagerProxy> create(WebContext*); virtual ~WebMediaCacheManagerProxy(); - - void invalidate(); - void clearContext() { m_webContext = 0; } void getHostnamesWithMediaCache(PassRefPtr<ArrayCallback>); void clearCacheForHostname(const String&); void clearCacheForAllHostnames(); - bool shouldTerminate(WebProcessProxy*) const; + using APIObject::ref; + using APIObject::deref; private: explicit WebMediaCacheManagerProxy(WebContext*); - virtual Type type() const { return APIType; } - void didGetHostnamesWithMediaCache(const Vector<String>&, uint64_t callbackID); + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; + // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebMediaCacheManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebNavigationData.h b/Source/WebKit2/UIProcess/WebNavigationData.h index c2e20f368..297485f5a 100644 --- a/Source/WebKit2/UIProcess/WebNavigationData.h +++ b/Source/WebKit2/UIProcess/WebNavigationData.h @@ -32,10 +32,8 @@ namespace WebKit { -class WebNavigationData : public APIObject { +class WebNavigationData : public TypedAPIObject<APIObject::TypeNavigationData> { public: - static const Type APIType = TypeNavigationData; - static PassRefPtr<WebNavigationData> create(const WebNavigationDataStore& store) { return adoptRef(new WebNavigationData(store)); @@ -50,8 +48,6 @@ public: private: explicit WebNavigationData(const WebNavigationDataStore&); - virtual Type type() const { return APIType; } - WebNavigationDataStore m_store; }; diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp index 4173463f4..0e439d219 100644 --- a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp @@ -35,27 +35,27 @@ namespace WebKit { +const char* WebNetworkInfoManagerProxy::supplementName() +{ + return "WebNetworkInfoManagerProxy"; +} + PassRefPtr<WebNetworkInfoManagerProxy> WebNetworkInfoManagerProxy::create(WebContext* context) { return adoptRef(new WebNetworkInfoManagerProxy(context)); } WebNetworkInfoManagerProxy::WebNetworkInfoManagerProxy(WebContext* context) - : m_isUpdating(false) - , m_context(context) + : WebContextSupplement(context) + , m_isUpdating(false) { - m_context->addMessageReceiver(Messages::WebNetworkInfoManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebNetworkInfoManagerProxy::messageReceiverName(), this); } WebNetworkInfoManagerProxy::~WebNetworkInfoManagerProxy() { } -void WebNetworkInfoManagerProxy::invalidate() -{ - stopUpdating(); -} - void WebNetworkInfoManagerProxy::initializeProvider(const WKNetworkInfoProvider* provider) { m_provider.initialize(provider); @@ -63,20 +63,32 @@ void WebNetworkInfoManagerProxy::initializeProvider(const WKNetworkInfoProvider* void WebNetworkInfoManagerProxy::providerDidChangeNetworkInformation(const AtomicString& eventType, WebNetworkInfo* networkInformation) { - if (!m_context) + if (!context()) return; - m_context->sendToAllProcesses(Messages::WebNetworkInfoManager::DidChangeNetworkInformation(eventType, networkInformation->data())); + context()->sendToAllProcesses(Messages::WebNetworkInfoManager::DidChangeNetworkInformation(eventType, networkInformation->data())); +} + +// WebContextSupplement + +void WebNetworkInfoManagerProxy::contextDestroyed() +{ + stopUpdating(); +} + +void WebNetworkInfoManagerProxy::processDidClose(WebProcessProxy*) +{ + stopUpdating(); } -void WebNetworkInfoManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebNetworkInfoManagerProxy::refWebContextSupplement() { - didReceiveWebNetworkInfoManagerProxyMessage(connection, messageID, decoder); + APIObject::ref(); } -void WebNetworkInfoManagerProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) +void WebNetworkInfoManagerProxy::derefWebContextSupplement() { - didReceiveSyncWebNetworkInfoManagerProxyMessage(connection, messageID, decoder, replyEncoder); + APIObject::deref(); } void WebNetworkInfoManagerProxy::startUpdating() diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h index 456010c25..a74a2b8ba 100644 --- a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h @@ -30,6 +30,7 @@ #include "APIObject.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include "WebNetworkInfoProvider.h" #include <wtf/Forward.h> @@ -38,32 +39,32 @@ namespace WebKit { class WebContext; class WebNetworkInfo; -class WebNetworkInfoManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebNetworkInfoManagerProxy : public TypedAPIObject<APIObject::TypeNetworkInfoManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeNetworkInfoManager; + static const char* supplementName(); static PassRefPtr<WebNetworkInfoManagerProxy> create(WebContext*); virtual ~WebNetworkInfoManagerProxy(); - void invalidate(); - void clearContext() { m_context = 0; } - void initializeProvider(const WKNetworkInfoProvider*); void providerDidChangeNetworkInformation(const WTF::AtomicString& eventType, WebNetworkInfo*); + using APIObject::ref; + using APIObject::deref; + private: explicit WebNetworkInfoManagerProxy(WebContext*); - virtual Type type() const { return APIType; } + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; - - // Implemented in generated WebNetworkInfoManagerProxyMessageReceiver.cpp - void didReceiveWebNetworkInfoManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebNetworkInfoManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; void startUpdating(); void stopUpdating(); diff --git a/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h b/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h index 5ec369c9b..98ab30ce8 100644 --- a/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h +++ b/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h @@ -35,10 +35,8 @@ namespace WebKit { class ImmutableArray; class WebPageProxy; -class WebOpenPanelResultListenerProxy : public APIObject { +class WebOpenPanelResultListenerProxy : public TypedAPIObject<APIObject::TypeFramePolicyListener> { public: - static const Type APIType = TypeFramePolicyListener; - static PassRefPtr<WebOpenPanelResultListenerProxy> create(WebPageProxy* page) { return adoptRef(new WebOpenPanelResultListenerProxy(page)); @@ -54,8 +52,6 @@ public: private: explicit WebOpenPanelResultListenerProxy(WebPageProxy*); - virtual Type type() const { return APIType; } - RefPtr<WebPageProxy> m_page; }; diff --git a/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp b/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp index 8a11ebb89..f81df3a57 100644 --- a/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp +++ b/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp @@ -42,7 +42,7 @@ bool WebPageContextMenuClient::getContextMenuFromProposedMenu(WebPageProxy* page if (!m_client.getContextMenuFromProposedMenu && !m_client.getContextMenuFromProposedMenu_deprecatedForUseWithV0) return false; - if (m_client.version == kWKPageContextMenuClientCurrentVersion && !m_client.getContextMenuFromProposedMenu) + if (m_client.version >= 2 && !m_client.getContextMenuFromProposedMenu) return false; unsigned size = proposedMenuVector.size(); @@ -52,7 +52,7 @@ bool WebPageContextMenuClient::getContextMenuFromProposedMenu(WebPageProxy* page proposedMenu->append(WebContextMenuItem::create(proposedMenuVector[i]).get()); WKArrayRef newMenu = 0; - if (m_client.version == kWKPageContextMenuClientCurrentVersion) { + if (m_client.version >= 2) { RefPtr<WebHitTestResult> webHitTestResult = WebHitTestResult::create(hitTestResultData); m_client.getContextMenuFromProposedMenu(toAPI(page), toAPI(proposedMenu.get()), &newMenu, toAPI(webHitTestResult.get()), toAPI(userData), m_client.clientInfo); } else @@ -93,5 +93,33 @@ void WebPageContextMenuClient::contextMenuDismissed(WebPageProxy* page) m_client.contextMenuDismissed(toAPI(page), m_client.clientInfo); } +bool WebPageContextMenuClient::showContextMenu(WebPageProxy* page, const WebCore::IntPoint& menuLocation, const Vector<WebContextMenuItemData>& menuItemsVector) +{ + if (!m_client.showContextMenu) + return false; + + unsigned size = menuItemsVector.size(); + + Vector<RefPtr<APIObject>> menuItems; + menuItems.reserveCapacity(size); + + for (unsigned i = 0; i < size; ++i) + menuItems.uncheckedAppend(WebContextMenuItem::create(menuItemsVector[i]).get()); + + m_client.showContextMenu(toAPI(page), toAPI(menuLocation), toAPI(ImmutableArray::adopt(menuItems).get()), m_client.clientInfo); + + return true; +} + +bool WebPageContextMenuClient::hideContextMenu(WebPageProxy* page) +{ + if (!m_client.hideContextMenu) + return false; + + m_client.hideContextMenu(toAPI(page), m_client.clientInfo); + + return true; +} + } // namespace WebKit #endif // ENABLE(CONTEXT_MENUS) diff --git a/Source/WebKit2/UIProcess/WebPageContextMenuClient.h b/Source/WebKit2/UIProcess/WebPageContextMenuClient.h index dff9019c1..442a0763d 100644 --- a/Source/WebKit2/UIProcess/WebPageContextMenuClient.h +++ b/Source/WebKit2/UIProcess/WebPageContextMenuClient.h @@ -31,6 +31,7 @@ #include "APIClient.h" #include "WebHitTestResult.h" #include "WKPage.h" +#include <WebCore/IntPoint.h> #include <wtf/Vector.h> namespace WebKit { @@ -44,6 +45,8 @@ public: bool getContextMenuFromProposedMenu(WebPageProxy*, const Vector<WebContextMenuItemData>& proposedMenu, Vector<WebContextMenuItemData>& customMenu, const WebHitTestResult::Data&, APIObject* userData); void customContextMenuItemSelected(WebPageProxy*, const WebContextMenuItemData&); void contextMenuDismissed(WebPageProxy*); + bool showContextMenu(WebPageProxy*, const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); + bool hideContextMenu(WebPageProxy*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPageGroup.h b/Source/WebKit2/UIProcess/WebPageGroup.h index 176b9ee46..f0fddf551 100644 --- a/Source/WebKit2/UIProcess/WebPageGroup.h +++ b/Source/WebKit2/UIProcess/WebPageGroup.h @@ -38,10 +38,8 @@ namespace WebKit { class WebPreferences; class WebPageProxy; -class WebPageGroup : public APIObject { +class WebPageGroup : public TypedAPIObject<APIObject::TypePageGroup> { public: - static const Type APIType = TypePageGroup; - static PassRefPtr<WebPageGroup> create(const String& identifier = String(), bool visibleToInjectedBundle = true, bool visibleToHistoryClient = true); static WebPageGroup* get(uint64_t pageGroupID); @@ -68,8 +66,6 @@ public: private: WebPageGroup(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient); - virtual Type type() const { return APIType; } - template<typename MessageType> void sendToAllProcessesInGroup(const MessageType&, uint64_t destinationID); WebPageGroupData m_data; diff --git a/Source/WebKit2/UIProcess/WebPageProxy.cpp b/Source/WebKit2/UIProcess/WebPageProxy.cpp index 819fd7ad3..737d71356 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.cpp +++ b/Source/WebKit2/UIProcess/WebPageProxy.cpp @@ -32,19 +32,21 @@ #include "DataReference.h" #include "DownloadProxy.h" #include "DrawingAreaProxy.h" +#include "DrawingAreaProxyMessages.h" #include "EventDispatcherMessages.h" #include "FindIndicator.h" +#include "ImmutableArray.h" #include "Logging.h" -#include "MessageID.h" #include "NativeWebKeyboardEvent.h" #include "NativeWebMouseEvent.h" #include "NativeWebWheelEvent.h" #include "NotificationPermissionRequest.h" #include "NotificationPermissionRequestManager.h" #include "PageClient.h" +#include "PluginInformation.h" +#include "PluginProcessManager.h" #include "PrintInfo.h" #include "SessionState.h" -#include "StringPairVector.h" #include "TextChecker.h" #include "TextCheckerState.h" #include "WKContextPrivate.h" @@ -62,13 +64,16 @@ #include "WebFormSubmissionListenerProxy.h" #include "WebFramePolicyListenerProxy.h" #include "WebFullScreenManagerProxy.h" +#include "WebFullScreenManagerProxyMessages.h" #include "WebInspectorProxy.h" +#include "WebInspectorProxyMessages.h" #include "WebNotificationManagerProxy.h" #include "WebOpenPanelResultListenerProxy.h" #include "WebPageCreationParameters.h" #include "WebPageGroup.h" #include "WebPageGroupData.h" #include "WebPageMessages.h" +#include "WebPageProxyMessages.h" #include "WebPopupItem.h" #include "WebPopupMenuProxy.h" #include "WebPreferences.h" @@ -88,15 +93,8 @@ #include <WebCore/WindowFeatures.h> #include <stdio.h> -#if ENABLE(WEB_INTENTS) -#include "IntentData.h" -#include "IntentServiceInfo.h" -#include "WebIntentData.h" -#include "WebIntentServiceInfo.h" -#endif - #if USE(COORDINATED_GRAPHICS) -#include "LayerTreeCoordinatorProxyMessages.h" +#include "CoordinatedLayerTreeHostProxyMessages.h" #endif #if PLATFORM(QT) @@ -136,6 +134,77 @@ WKPageDebugPaintFlags WebPageProxy::s_debugPaintFlags = 0; DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageProxyCounter, ("WebPageProxy")); +class ExceededDatabaseQuotaRecords { + WTF_MAKE_NONCOPYABLE(ExceededDatabaseQuotaRecords); WTF_MAKE_FAST_ALLOCATED; +public: + struct Record { + uint64_t frameID; + String originIdentifier; + String databaseName; + String displayName; + uint64_t currentQuota; + uint64_t currentOriginUsage; + uint64_t currentDatabaseUsage; + uint64_t expectedUsage; + RefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply; + }; + + static ExceededDatabaseQuotaRecords& shared(); + + PassOwnPtr<Record> createRecord(uint64_t frameID, String originIdentifier, + String databaseName, String displayName, uint64_t currentQuota, + uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, + PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply>); + + void add(PassOwnPtr<Record>); + bool areBeingProcessed() const { return m_currentRecord; } + Record* next(); + +private: + ExceededDatabaseQuotaRecords() { } + ~ExceededDatabaseQuotaRecords() { } + + Deque<OwnPtr<Record>> m_records; + OwnPtr<Record> m_currentRecord; +}; + +ExceededDatabaseQuotaRecords& ExceededDatabaseQuotaRecords::shared() +{ + DEFINE_STATIC_LOCAL(ExceededDatabaseQuotaRecords, records, ()); + return records; +} + +PassOwnPtr<ExceededDatabaseQuotaRecords::Record> ExceededDatabaseQuotaRecords::createRecord( + uint64_t frameID, String originIdentifier, String databaseName, String displayName, + uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, + uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply) +{ + OwnPtr<Record> record = adoptPtr(new Record); + record->frameID = frameID; + record->originIdentifier = originIdentifier; + record->databaseName = databaseName; + record->displayName = displayName; + record->currentQuota = currentQuota; + record->currentOriginUsage = currentOriginUsage; + record->currentDatabaseUsage = currentDatabaseUsage; + record->expectedUsage = expectedUsage; + record->reply = reply; + return record.release(); +} + +void ExceededDatabaseQuotaRecords::add(PassOwnPtr<ExceededDatabaseQuotaRecords::Record> record) +{ + m_records.append(record); +} + +ExceededDatabaseQuotaRecords::Record* ExceededDatabaseQuotaRecords::next() +{ + m_currentRecord.clear(); + if (!m_records.isEmpty()) + m_currentRecord = m_records.takeFirst(); + return m_currentRecord.get(); +} + #if !LOG_DISABLED static const char* webKeyboardEventTypeString(WebEvent::Type type) { @@ -177,6 +246,7 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p , m_isVisible(m_pageClient->isViewVisible()) , m_backForwardList(WebBackForwardList::create(this)) , m_loadStateAtProcessExit(WebFrameProxy::LoadStateFinished) + , m_temporarilyClosedComposition(false) , m_textZoomFactor(1) , m_pageZoomFactor(1) , m_pageScaleFactor(1) @@ -201,7 +271,8 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p , m_canRunModal(false) , m_isInPrintingMode(false) , m_isPerformingDOMPrintOperation(false) - , m_inDecidePolicyForResponse(false) + , m_inDecidePolicyForResponseSync(false) + , m_decidePolicyForResponseRequest(0) , m_syncMimeTypePolicyActionIsValid(false) , m_syncMimeTypePolicyAction(PolicyUse) , m_syncMimeTypePolicyDownloadID(0) @@ -221,7 +292,6 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p , m_spellDocumentTag(0) , m_hasSpellDocumentTag(false) , m_pendingLearnOrIgnoreWordMessageCount(0) - , m_mainFrameHasCustomRepresentation(false) , m_mainFrameHasHorizontalScrollbar(false) , m_mainFrameHasVerticalScrollbar(false) , m_canShortCircuitHorizontalWheelEvents(true) @@ -229,16 +299,25 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p , m_mainFrameIsPinnedToRightSide(false) , m_mainFrameIsPinnedToTopSide(false) , m_mainFrameIsPinnedToBottomSide(false) + , m_rubberBandsAtBottom(false) + , m_rubberBandsAtTop(false) + , m_mainFrameInViewSourceMode(false) , m_pageCount(0) , m_renderTreeSize(0) , m_shouldSendEventsSynchronously(false) , m_suppressVisibilityUpdates(false) - , m_minimumLayoutWidth(0) , m_mediaVolume(1) , m_mayStartMediaWhenInWindow(true) + , m_waitingForDidUpdateInWindowState(false) +#if PLATFORM(MAC) + , m_exposedRectChangedTimer(this, &WebPageProxy::exposedRectChangedTimerFired) + , m_clipsToExposedRect(false) + , m_lastSentClipsToExposedRect(false) +#endif #if ENABLE(PAGE_VISIBILITY_API) , m_visibilityState(PageVisibilityStateVisible) #endif + , m_scrollPinningBehavior(DoNotPin) { #if ENABLE(PAGE_VISIBILITY_API) if (!m_isVisible) @@ -252,9 +331,24 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p m_pageGroup->addPage(this); +#if ENABLE(INSPECTOR) + m_inspector = WebInspectorProxy::create(this); +#endif +#if ENABLE(FULLSCREEN_API) + m_fullScreenManager = WebFullScreenManagerProxy::create(this); +#endif #if ENABLE(VIBRATION) m_vibration = WebVibrationProxy::create(this); #endif +#if ENABLE(THREADED_SCROLLING) + m_rubberBandsAtBottom = true; + m_rubberBandsAtTop = true; +#endif + + m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, this); + + // FIXME: If we ever expose the session storage size as a preference, we need to pass it here. + m_process->context()->storageManager().createSessionStorageNamespace(m_pageID, m_process->isValid() ? m_process->connection() : 0, std::numeric_limits<unsigned>::max()); } WebPageProxy::~WebPageProxy() @@ -281,13 +375,13 @@ WebProcessProxy* WebPageProxy::process() const PlatformProcessIdentifier WebPageProxy::processIdentifier() const { - if (!m_process) + if (m_isClosed) return 0; return m_process->processIdentifier(); } -bool WebPageProxy::isValid() +bool WebPageProxy::isValid() const { // A page that has been explicitly closed is never valid. if (m_isClosed) @@ -301,7 +395,7 @@ PassRefPtr<ImmutableArray> WebPageProxy::relatedPages() const // pages() returns a list of pages in WebProcess, so this page may or may not be among them - a client can use a reference to WebPageProxy after the page has closed. Vector<WebPageProxy*> pages = m_process->pages(); - Vector<RefPtr<APIObject> > result; + Vector<RefPtr<APIObject>> result; result.reserveCapacity(pages.size()); for (size_t i = 0; i < pages.size(); ++i) { if (pages[i] != this) @@ -345,11 +439,6 @@ void WebPageProxy::initializeFormClient(const WKPageFormClient* formClient) m_formClient.initialize(formClient); } -void WebPageProxy::initializeResourceLoadClient(const WKPageResourceLoadClient* client) -{ - m_resourceLoadClient.initialize(client); -} - void WebPageProxy::initializeUIClient(const WKPageUIClient* client) { if (!isValid()) @@ -366,6 +455,11 @@ void WebPageProxy::initializeFindClient(const WKPageFindClient* client) m_findClient.initialize(client); } +void WebPageProxy::initializeFindMatchesClient(const WKPageFindMatchesClient* client) +{ + m_findMatchesClient.initialize(client); +} + #if ENABLE(CONTEXT_MENUS) void WebPageProxy::initializeContextMenuClient(const WKPageContextMenuClient* client) { @@ -385,8 +479,16 @@ void WebPageProxy::reattachToWebProcess() if (m_process->context()->processModel() == ProcessModelSharedSecondaryProcess) m_process = m_process->context()->ensureSharedWebProcess(); else - m_process = m_process->context()->createNewWebProcess(); + m_process = m_process->context()->createNewWebProcessRespectingProcessCountLimit(); m_process->addExistingWebPage(this, m_pageID); + m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, this); + +#if ENABLE(INSPECTOR) + m_inspector = WebInspectorProxy::create(this); +#endif +#if ENABLE(FULLSCREEN_API) + m_fullScreenManager = WebFullScreenManagerProxy::create(this); +#endif initializeWebPage(); @@ -431,6 +533,10 @@ void WebPageProxy::initializeWebPage() #elif ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING) m_process->send(Messages::WebPage::SetVisibilityState(m_isVisible ? PageVisibilityStateVisible : PageVisibilityStateHidden, /* isInitialState */ true), m_pageID); #endif + +#if PLATFORM(MAC) + m_process->send(Messages::WebPage::SetSmartInsertDeleteEnabled(m_isSmartInsertDeleteEnabled), m_pageID); +#endif } void WebPageProxy::close() @@ -470,9 +576,9 @@ void WebPageProxy::close() } #if ENABLE(INPUT_TYPE_COLOR) - if (m_colorChooser) { - m_colorChooser->invalidate(); - m_colorChooser = nullptr; + if (m_colorPicker) { + m_colorPicker->invalidate(); + m_colorPicker = nullptr; } if (m_colorPickerResultListener) { @@ -486,6 +592,7 @@ void WebPageProxy::close() #endif m_notificationPermissionRequestManager.invalidateRequests(); + m_process->context()->supplement<WebNotificationManagerProxy>()->clearNotifications(this); m_toolTip = String(); @@ -519,15 +626,30 @@ void WebPageProxy::close() m_activePopupMenu = 0; m_estimatedProgress = 0.0; - + m_loaderClient.initialize(0); m_policyClient.initialize(0); + m_formClient.initialize(0); m_uiClient.initialize(0); +#if PLATFORM(EFL) + m_uiPopupMenuClient.initialize(0); +#endif + m_findClient.initialize(0); + m_findMatchesClient.initialize(0); +#if ENABLE(CONTEXT_MENUS) + m_contextMenuClient.initialize(0); +#endif m_drawingArea = nullptr; +#if PLATFORM(MAC) + m_exposedRectChangedTimer.stop(); +#endif + m_process->send(Messages::WebPage::Close(), m_pageID); m_process->removeWebPage(m_pageID); + m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID); + m_process->context()->storageManager().destroySessionStorageNamespace(m_pageID); } bool WebPageProxy::tryClose() @@ -555,7 +677,7 @@ bool WebPageProxy::maybeInitializeSandboxExtensionHandle(const KURL& url, Sandbo return true; } -void WebPageProxy::loadURL(const String& url) +void WebPageProxy::loadURL(const String& url, APIObject* userData) { setPendingAPIRequestURL(url); @@ -566,11 +688,11 @@ void WebPageProxy::loadURL(const String& url) bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), url), sandboxExtensionHandle); if (createdExtension) m_process->willAcquireUniversalFileReadSandboxExtension(); - m_process->send(Messages::WebPage::LoadURL(url, sandboxExtensionHandle), m_pageID); + m_process->send(Messages::WebPage::LoadURL(url, sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID); m_process->responsivenessTimer()->start(); } -void WebPageProxy::loadURLRequest(WebURLRequest* urlRequest) +void WebPageProxy::loadURLRequest(WebURLRequest* urlRequest, APIObject* userData) { setPendingAPIRequestURL(urlRequest->resourceRequest().url()); @@ -581,21 +703,58 @@ void WebPageProxy::loadURLRequest(WebURLRequest* urlRequest) bool createdExtension = maybeInitializeSandboxExtensionHandle(urlRequest->resourceRequest().url(), sandboxExtensionHandle); if (createdExtension) m_process->willAcquireUniversalFileReadSandboxExtension(); - m_process->send(Messages::WebPage::LoadURLRequest(urlRequest->resourceRequest(), sandboxExtensionHandle), m_pageID); + m_process->send(Messages::WebPage::LoadURLRequest(urlRequest->resourceRequest(), sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID); + m_process->responsivenessTimer()->start(); +} + +void WebPageProxy::loadFile(const String& fileURLString, const String& resourceDirectoryURLString, APIObject* userData) +{ + if (!isValid()) + reattachToWebProcess(); + + KURL fileURL = KURL(KURL(), fileURLString); + if (!fileURL.isLocalFile()) + return; + + KURL resourceDirectoryURL; + if (resourceDirectoryURLString.isNull()) + resourceDirectoryURL = KURL(ParsedURLString, ASCIILiteral("file:///")); + else { + resourceDirectoryURL = KURL(KURL(), resourceDirectoryURLString); + if (!resourceDirectoryURL.isLocalFile()) + return; + } + + String resourceDirectoryPath = resourceDirectoryURL.fileSystemPath(); + + SandboxExtension::Handle sandboxExtensionHandle; + SandboxExtension::createHandle(resourceDirectoryPath, SandboxExtension::ReadOnly, sandboxExtensionHandle); + m_process->assumeReadAccessToBaseURL(resourceDirectoryURL); + m_process->send(Messages::WebPage::LoadURL(fileURL, sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID); + m_process->responsivenessTimer()->start(); +} + +void WebPageProxy::loadData(WebData* data, const String& MIMEType, const String& encoding, const String& baseURL, APIObject* userData) +{ + if (!isValid()) + reattachToWebProcess(); + + m_process->assumeReadAccessToBaseURL(baseURL); + m_process->send(Messages::WebPage::LoadData(data->dataReference(), MIMEType, encoding, baseURL, WebContextUserMessageEncoder(userData)), m_pageID); m_process->responsivenessTimer()->start(); } -void WebPageProxy::loadHTMLString(const String& htmlString, const String& baseURL) +void WebPageProxy::loadHTMLString(const String& htmlString, const String& baseURL, APIObject* userData) { if (!isValid()) reattachToWebProcess(); m_process->assumeReadAccessToBaseURL(baseURL); - m_process->send(Messages::WebPage::LoadHTMLString(htmlString, baseURL), m_pageID); + m_process->send(Messages::WebPage::LoadHTMLString(htmlString, baseURL, WebContextUserMessageEncoder(userData)), m_pageID); m_process->responsivenessTimer()->start(); } -void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL) +void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, APIObject* userData) { if (!isValid()) reattachToWebProcess(); @@ -604,25 +763,25 @@ void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const Strin m_mainFrame->setUnreachableURL(unreachableURL); m_process->assumeReadAccessToBaseURL(baseURL); - m_process->send(Messages::WebPage::LoadAlternateHTMLString(htmlString, baseURL, unreachableURL), m_pageID); + m_process->send(Messages::WebPage::LoadAlternateHTMLString(htmlString, baseURL, unreachableURL, WebContextUserMessageEncoder(userData)), m_pageID); m_process->responsivenessTimer()->start(); } -void WebPageProxy::loadPlainTextString(const String& string) +void WebPageProxy::loadPlainTextString(const String& string, APIObject* userData) { if (!isValid()) reattachToWebProcess(); - m_process->send(Messages::WebPage::LoadPlainTextString(string), m_pageID); + m_process->send(Messages::WebPage::LoadPlainTextString(string, WebContextUserMessageEncoder(userData)), m_pageID); m_process->responsivenessTimer()->start(); } -void WebPageProxy::loadWebArchiveData(const WebData* webArchiveData) +void WebPageProxy::loadWebArchiveData(const WebData* webArchiveData, APIObject* userData) { if (!isValid()) reattachToWebProcess(); - m_process->send(Messages::WebPage::LoadWebArchiveData(webArchiveData->dataReference()), m_pageID); + m_process->send(Messages::WebPage::LoadWebArchiveData(webArchiveData->dataReference(), WebContextUserMessageEncoder(userData)), m_pageID); m_process->responsivenessTimer()->start(); } @@ -729,7 +888,7 @@ void WebPageProxy::tryRestoreScrollPosition() m_process->send(Messages::WebPage::TryRestoreScrollPosition(), m_pageID); } -void WebPageProxy::didChangeBackForwardList(WebBackForwardListItem* added, Vector<RefPtr<APIObject> >* removed) +void WebPageProxy::didChangeBackForwardList(WebBackForwardListItem* added, Vector<RefPtr<APIObject>>* removed) { m_loaderClient.didChangeBackForwardList(this, added, removed); } @@ -803,6 +962,13 @@ bool WebPageProxy::canShowMIMEType(const String& mimeType) const if (!plugin.path.isNull() && m_pageGroup->preferences()->pluginsEnabled()) return true; #endif // ENABLE(NETSCAPE_PLUGIN_API) + +#if PLATFORM(MAC) + // On Mac, we can show PDFs. + if (MIMETypeRegistry::isPDFOrPostScriptMIMEType(mimeType) && !WebContext::omitPDFSupport()) + return true; +#endif // PLATFORM(MAC) + return false; } @@ -828,6 +994,17 @@ void WebPageProxy::setDrawsTransparentBackground(bool drawsTransparentBackground m_process->send(Messages::WebPage::SetDrawsTransparentBackground(drawsTransparentBackground), m_pageID); } +void WebPageProxy::setUnderlayColor(const Color& color) +{ + if (m_underlayColor == color) + return; + + m_underlayColor = color; + + if (isValid()) + m_process->send(Messages::WebPage::SetUnderlayColor(color), m_pageID); +} + void WebPageProxy::viewWillStartLiveResize() { if (!isValid()) @@ -852,6 +1029,11 @@ void WebPageProxy::displayView() m_pageClient->displayView(); } +bool WebPageProxy::canScrollView() +{ + return m_pageClient->canScrollView(); +} + void WebPageProxy::scrollView(const IntRect& scrollRect, const IntSize& scrollOffset) { m_pageClient->scrollView(scrollRect, scrollOffset); @@ -872,6 +1054,7 @@ void WebPageProxy::viewStateDidChange(ViewStateFlags flags) bool isVisible = m_pageClient->isViewVisible(); if (isVisible != m_isVisible) { m_isVisible = isVisible; + m_process->pageVisibilityChanged(this); m_drawingArea->visibilityDidChange(); if (!m_isVisible) { @@ -919,6 +1102,23 @@ void WebPageProxy::viewStateDidChange(ViewStateFlags flags) updateBackingStoreDiscardableState(); } +void WebPageProxy::waitForDidUpdateInWindowState() +{ + // If we have previously timed out with no response from the WebProcess, don't block the UIProcess again until it starts responding. + if (m_waitingForDidUpdateInWindowState) + return; + + if (!isValid()) + return; + + m_waitingForDidUpdateInWindowState = true; + + if (!m_process->isLaunching()) { + const double inWindowStateUpdateTimeout = 0.25; + m_process->connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidUpdateInWindowState>(m_pageID, inWindowStateUpdateTimeout); + } +} + IntSize WebPageProxy::viewSize() const { return m_pageClient->viewSize(); @@ -975,14 +1175,6 @@ void WebPageProxy::executeEditCommand(const String& commandName) } #if USE(TILED_BACKING_STORE) -void WebPageProxy::setViewportSize(const IntSize& size) -{ - if (!isValid()) - return; - - m_process->send(Messages::WebPage::SetViewportSize(size), m_pageID); -} - void WebPageProxy::commitPageTransitionViewport() { if (!isValid()) @@ -1023,11 +1215,7 @@ void WebPageProxy::performDragControllerAction(DragControllerAction action, Drag { if (!isValid()) return; -#if PLATFORM(WIN) - // FIXME: We should pass the drag data map only on DragEnter. - m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData->clientPosition(), dragData->globalPosition(), - dragData->draggingSourceOperationMask(), dragData->dragDataMap(), dragData->flags()), m_pageID); -#elif PLATFORM(QT) || PLATFORM(GTK) +#if PLATFORM(QT) || PLATFORM(GTK) m_process->send(Messages::WebPage::PerformDragControllerAction(action, *dragData), m_pageID); #else m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData->clientPosition(), dragData->globalPosition(), dragData->draggingSourceOperationMask(), dragStorageName, dragData->flags(), sandboxExtensionHandle, sandboxExtensionsForUpload), m_pageID); @@ -1174,7 +1362,7 @@ void WebPageProxy::handleWheelEvent(const NativeWebWheelEvent& event) return; } - OwnPtr<Vector<NativeWebWheelEvent> > coalescedWheelEvent = adoptPtr(new Vector<NativeWebWheelEvent>); + OwnPtr<Vector<NativeWebWheelEvent>> coalescedWheelEvent = adoptPtr(new Vector<NativeWebWheelEvent>); coalescedWheelEvent->append(event); m_currentlyProcessedWheelEvents.append(coalescedWheelEvent.release()); sendWheelEvent(event); @@ -1182,7 +1370,7 @@ void WebPageProxy::handleWheelEvent(const NativeWebWheelEvent& event) void WebPageProxy::processNextQueuedWheelEvent() { - OwnPtr<Vector<NativeWebWheelEvent> > nextCoalescedEvent = adoptPtr(new Vector<NativeWebWheelEvent>); + OwnPtr<Vector<NativeWebWheelEvent>> nextCoalescedEvent = adoptPtr(new Vector<NativeWebWheelEvent>); WebWheelEvent nextWheelEvent = coalescedWheelEvent(m_wheelEventQueue, *nextCoalescedEvent.get()); m_currentlyProcessedWheelEvents.append(nextCoalescedEvent.release()); sendWheelEvent(nextWheelEvent); @@ -1220,6 +1408,50 @@ void WebPageProxy::handleKeyboardEvent(const NativeWebKeyboardEvent& event) m_process->send(Messages::WebPage::KeyEvent(event), m_pageID); } +#if ENABLE(NETSCAPE_PLUGIN_API) +void WebPageProxy::findPlugin(const String& mimeType, uint32_t processType, const String& urlString, const String& frameURLString, const String& pageURLString, bool allowOnlyApplicationPlugins, uint64_t& pluginProcessToken, String& newMimeType, uint32_t& pluginLoadPolicy, String& unavailabilityDescription) +{ + MESSAGE_CHECK_URL(urlString); + + newMimeType = mimeType.lower(); + pluginLoadPolicy = PluginModuleLoadNormally; + + PluginData::AllowedPluginTypes allowedPluginTypes = allowOnlyApplicationPlugins ? PluginData::OnlyApplicationPlugins : PluginData::AllPlugins; + PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString), allowedPluginTypes); + if (!plugin.path) { + pluginProcessToken = 0; + return; + } + + pluginLoadPolicy = PluginInfoStore::defaultLoadPolicyForPlugin(plugin); + +#if PLATFORM(MAC) + RefPtr<ImmutableDictionary> pluginInformation = createPluginInformationDictionary(plugin, frameURLString, String(), pageURLString, String(), String()); + pluginLoadPolicy = m_loaderClient.pluginLoadPolicy(this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get(), unavailabilityDescription); +#else + UNUSED_PARAM(frameURLString); + UNUSED_PARAM(pageURLString); +#endif + + PluginProcessSandboxPolicy pluginProcessSandboxPolicy = PluginProcessSandboxPolicyNormal; + switch (pluginLoadPolicy) { + case PluginModuleLoadNormally: + pluginProcessSandboxPolicy = PluginProcessSandboxPolicyNormal; + break; + case PluginModuleLoadUnsandboxed: + pluginProcessSandboxPolicy = PluginProcessSandboxPolicyUnsandboxed; + break; + + case PluginModuleBlocked: + pluginProcessToken = 0; + return; + } + + pluginProcessToken = PluginProcessManager::shared().pluginProcessToken(plugin, static_cast<PluginProcessType>(processType), pluginProcessSandboxPolicy); +} + +#endif // ENABLE(NETSCAPE_PLUGIN_API) + #if ENABLE(GESTURE_EVENTS) void WebPageProxy::handleGestureEvent(const WebGestureEvent& event) { @@ -1292,7 +1524,7 @@ void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy* fr { if (!isValid()) return; - + if (action == PolicyIgnore) clearPendingAPIRequestURL(); @@ -1309,7 +1541,7 @@ void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy* fr // If we received a policy decision while in decidePolicyForResponse the decision will // be sent back to the web process by decidePolicyForResponse. - if (m_inDecidePolicyForResponse) { + if (m_inDecidePolicyForResponseSync) { m_syncMimeTypePolicyActionIsValid = true; m_syncMimeTypePolicyAction = action; m_syncMimeTypePolicyDownloadID = downloadID; @@ -1398,7 +1630,8 @@ void WebPageProxy::suspendActiveDOMObjectsAndAnimations() bool WebPageProxy::supportsTextEncoding() const { - return !m_mainFrameHasCustomRepresentation && m_mainFrame && !m_mainFrame->isDisplayingStandaloneImageDocument(); + // FIXME (118840): We should probably only support this for text documents, not all non-image documents. + return m_mainFrame && !m_mainFrame->isDisplayingStandaloneImageDocument(); } void WebPageProxy::setCustomTextEncodingName(const String& encodingName) @@ -1419,7 +1652,8 @@ void WebPageProxy::terminateProcess() if (!m_isValid) return; - m_process->terminate(); + m_process->requestTermination(); + resetStateAfterProcessExited(); } #if !USE(CF) || defined(BUILDING_QT__) @@ -1437,10 +1671,7 @@ void WebPageProxy::restoreFromSessionStateData(WebData*) bool WebPageProxy::supportsTextZoom() const { - if (m_mainFrameHasCustomRepresentation) - return false; - - // FIXME: This should also return false for standalone media and plug-in documents. + // FIXME (118840): This should also return false for standalone media and plug-in documents. if (!m_mainFrame || m_mainFrame->isDisplayingStandaloneImageDocument()) return false; @@ -1452,9 +1683,6 @@ void WebPageProxy::setTextZoomFactor(double zoomFactor) if (!isValid()) return; - if (m_mainFrameHasCustomRepresentation) - return; - if (m_textZoomFactor == zoomFactor) return; @@ -1462,21 +1690,11 @@ void WebPageProxy::setTextZoomFactor(double zoomFactor) m_process->send(Messages::WebPage::SetTextZoomFactor(m_textZoomFactor), m_pageID); } -double WebPageProxy::pageZoomFactor() const -{ - return m_mainFrameHasCustomRepresentation ? m_pageClient->customRepresentationZoomFactor() : m_pageZoomFactor; -} - void WebPageProxy::setPageZoomFactor(double zoomFactor) { if (!isValid()) return; - if (m_mainFrameHasCustomRepresentation) { - m_pageClient->setCustomRepresentationZoomFactor(zoomFactor); - return; - } - if (m_pageZoomFactor == zoomFactor) return; @@ -1489,11 +1707,6 @@ void WebPageProxy::setPageAndTextZoomFactors(double pageZoomFactor, double textZ if (!isValid()) return; - if (m_mainFrameHasCustomRepresentation) { - m_pageClient->setCustomRepresentationZoomFactor(pageZoomFactor); - return; - } - if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor) return; @@ -1613,6 +1826,32 @@ void WebPageProxy::setSuppressScrollbarAnimations(bool suppressAnimations) m_process->send(Messages::WebPage::SetSuppressScrollbarAnimations(suppressAnimations), m_pageID); } +void WebPageProxy::setRubberBandsAtBottom(bool rubberBandsAtBottom) +{ + if (rubberBandsAtBottom == m_rubberBandsAtBottom) + return; + + m_rubberBandsAtBottom = rubberBandsAtBottom; + + if (!isValid()) + return; + + m_process->send(Messages::WebPage::SetRubberBandsAtBottom(rubberBandsAtBottom), m_pageID); +} + +void WebPageProxy::setRubberBandsAtTop(bool rubberBandsAtTop) +{ + if (rubberBandsAtTop == m_rubberBandsAtTop) + return; + + m_rubberBandsAtTop = rubberBandsAtTop; + + if (!isValid()) + return; + + m_process->send(Messages::WebPage::SetRubberBandsAtTop(rubberBandsAtTop), m_pageID); +} + void WebPageProxy::setPaginationMode(WebCore::Pagination::Mode mode) { if (mode == m_paginationMode) @@ -1666,6 +1905,11 @@ void WebPageProxy::pageScaleFactorDidChange(double scaleFactor) m_pageScaleFactor = scaleFactor; } +void WebPageProxy::pageZoomFactorDidChange(double zoomFactor) +{ + m_pageZoomFactor = zoomFactor; +} + void WebPageProxy::setMemoryCacheClientCallsEnabled(bool memoryCacheClientCallsEnabled) { if (!isValid()) @@ -1678,12 +1922,29 @@ void WebPageProxy::setMemoryCacheClientCallsEnabled(bool memoryCacheClientCallsE m_process->send(Messages::WebPage::SetMemoryCacheMessagesEnabled(memoryCacheClientCallsEnabled), m_pageID); } +void WebPageProxy::findStringMatches(const String& string, FindOptions options, unsigned maxMatchCount) +{ + if (string.isEmpty()) { + didFindStringMatches(string, Vector<Vector<WebCore::IntRect>> (), 0); + return; + } + + m_process->send(Messages::WebPage::FindStringMatches(string, options, maxMatchCount), m_pageID); +} + void WebPageProxy::findString(const String& string, FindOptions options, unsigned maxMatchCount) { - if (m_mainFrameHasCustomRepresentation) - m_pageClient->findStringInCustomRepresentation(string, options, maxMatchCount); - else - m_process->send(Messages::WebPage::FindString(string, options, maxMatchCount), m_pageID); + m_process->send(Messages::WebPage::FindString(string, options, maxMatchCount), m_pageID); +} + +void WebPageProxy::getImageForFindMatch(int32_t matchIndex) +{ + m_process->send(Messages::WebPage::GetImageForFindMatch(matchIndex), m_pageID); +} + +void WebPageProxy::selectFindMatch(int32_t matchIndex) +{ + m_process->send(Messages::WebPage::SelectFindMatch(matchIndex), m_pageID); } void WebPageProxy::hideFindUI() @@ -1693,11 +1954,6 @@ void WebPageProxy::hideFindUI() void WebPageProxy::countStringMatches(const String& string, FindOptions options, unsigned maxMatchCount) { - if (m_mainFrameHasCustomRepresentation) { - m_pageClient->countStringMatchesInCustomRepresentation(string, options, maxMatchCount); - return; - } - if (!isValid()) return; @@ -1744,16 +2000,6 @@ void WebPageProxy::getSourceForFrame(WebFrameProxy* frame, PassRefPtr<StringCall m_process->send(Messages::WebPage::GetSourceForFrame(frame->frameID(), callbackID), m_pageID); } -#if ENABLE(WEB_INTENTS) -void WebPageProxy::deliverIntentToFrame(WebFrameProxy* frame, WebIntentData* webIntentData) -{ - if (!isValid()) - return; - - m_process->send(Messages::WebPage::DeliverIntentToFrame(frame->frameID(), webIntentData->store()), m_pageID); -} -#endif - void WebPageProxy::getContentsAsString(PassRefPtr<StringCallback> prpCallback) { RefPtr<StringCallback> callback = prpCallback; @@ -1796,6 +2042,19 @@ void WebPageProxy::getSelectionOrContentsAsString(PassRefPtr<StringCallback> prp m_process->send(Messages::WebPage::GetSelectionOrContentsAsString(callbackID), m_pageID); } +void WebPageProxy::getSelectionAsWebArchiveData(PassRefPtr<DataCallback> prpCallback) +{ + RefPtr<DataCallback> callback = prpCallback; + if (!isValid()) { + callback->invalidate(); + return; + } + + uint64_t callbackID = callback->callbackID(); + m_dataCallbacks.set(callbackID, callback.get()); + m_process->send(Messages::WebPage::GetSelectionAsWebArchiveData(callbackID), m_pageID); +} + void WebPageProxy::getMainResourceDataOfFrame(WebFrameProxy* frame, PassRefPtr<DataCallback> prpCallback) { RefPtr<DataCallback> callback = prpCallback; @@ -1859,6 +2118,10 @@ void WebPageProxy::preferencesDidChange() inspector()->enableRemoteInspection(); #endif + m_process->pagePreferencesChanged(this); + + m_pageClient->preferencesDidChange(); + // FIXME: It probably makes more sense to send individual preference changes. // However, WebKitTestRunner depends on getting a preference change notification // even if nothing changed in UI process, so that overrides get removed. @@ -1867,59 +2130,6 @@ void WebPageProxy::preferencesDidChange() m_process->send(Messages::WebPage::PreferencesDidChange(pageGroup()->preferences()->store()), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } -void WebPageProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - if (messageID.is<CoreIPC::MessageClassDrawingAreaProxy>()) { - m_drawingArea->didReceiveDrawingAreaProxyMessage(connection, messageID, decoder); - return; - } - -#if USE(COORDINATED_GRAPHICS) - if (messageID.is<CoreIPC::MessageClassLayerTreeCoordinatorProxy>()) { - m_drawingArea->didReceiveLayerTreeCoordinatorProxyMessage(connection, messageID, decoder); - return; - } -#endif - -#if ENABLE(INSPECTOR) - if (messageID.is<CoreIPC::MessageClassWebInspectorProxy>()) { - if (WebInspectorProxy* inspector = this->inspector()) - inspector->didReceiveWebInspectorProxyMessage(connection, messageID, decoder); - return; - } -#endif - -#if ENABLE(FULLSCREEN_API) - if (messageID.is<CoreIPC::MessageClassWebFullScreenManagerProxy>()) { - fullScreenManager()->didReceiveMessage(connection, messageID, decoder); - return; - } -#endif - - didReceiveWebPageProxyMessage(connection, messageID, decoder); -} - -void WebPageProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) -{ -#if ENABLE(INSPECTOR) - if (messageID.is<CoreIPC::MessageClassWebInspectorProxy>()) { - if (WebInspectorProxy* inspector = this->inspector()) - inspector->didReceiveSyncWebInspectorProxyMessage(connection, messageID, decoder, replyEncoder); - return; - } -#endif - -#if ENABLE(FULLSCREEN_API) - if (messageID.is<CoreIPC::MessageClassWebFullScreenManagerProxy>()) { - fullScreenManager()->didReceiveSyncMessage(connection, messageID, decoder, replyEncoder); - return; - } -#endif - - // FIXME: Do something with reply. - didReceiveSyncWebPageProxyMessage(connection, messageID, decoder, replyEncoder); -} - void WebPageProxy::didCreateMainFrame(uint64_t frameID) { MESSAGE_CHECK(!m_mainFrame); @@ -1931,63 +2141,17 @@ void WebPageProxy::didCreateMainFrame(uint64_t frameID) m_process->frameCreated(frameID, m_mainFrame.get()); } -void WebPageProxy::didCreateSubframe(uint64_t frameID, uint64_t parentFrameID) +void WebPageProxy::didCreateSubframe(uint64_t frameID) { MESSAGE_CHECK(m_mainFrame); - - WebFrameProxy* parentFrame = m_process->webFrame(parentFrameID); - MESSAGE_CHECK(parentFrame); - MESSAGE_CHECK(parentFrame->isDescendantOf(m_mainFrame.get())); - MESSAGE_CHECK(m_process->canCreateFrame(frameID)); RefPtr<WebFrameProxy> subFrame = WebFrameProxy::create(this, frameID); // Add the frame to the process wide map. m_process->frameCreated(frameID, subFrame.get()); - - // Insert the frame into the frame hierarchy. - parentFrame->appendChild(subFrame.get()); -} - -static bool isDisconnectedFrame(WebFrameProxy* frame) -{ - return !frame->page() || !frame->page()->mainFrame() || !frame->isDescendantOf(frame->page()->mainFrame()); -} - -void WebPageProxy::didSaveFrameToPageCache(uint64_t frameID) -{ - MESSAGE_CHECK(m_mainFrame); - - WebFrameProxy* subframe = m_process->webFrame(frameID); - MESSAGE_CHECK(subframe); - - if (isDisconnectedFrame(subframe)) - return; - - MESSAGE_CHECK(subframe->isDescendantOf(m_mainFrame.get())); - - subframe->didRemoveFromHierarchy(); -} - -void WebPageProxy::didRestoreFrameFromPageCache(uint64_t frameID, uint64_t parentFrameID) -{ - MESSAGE_CHECK(m_mainFrame); - - WebFrameProxy* subframe = m_process->webFrame(frameID); - MESSAGE_CHECK(subframe); - MESSAGE_CHECK(!subframe->parentFrame()); - MESSAGE_CHECK(subframe->page() == m_mainFrame->page()); - - WebFrameProxy* parentFrame = m_process->webFrame(parentFrameID); - MESSAGE_CHECK(parentFrame); - MESSAGE_CHECK(parentFrame->isDescendantOf(m_mainFrame.get())); - - // Insert the frame into the frame hierarchy. - parentFrame->appendChild(subframe); } - // Always start progress at initialProgressValue. This helps provide feedback as // soon as a load starts. @@ -2021,22 +2185,6 @@ void WebPageProxy::didFinishProgress() m_loaderClient.didFinishProgress(this); } -#if ENABLE(WEB_INTENTS_TAG) -void WebPageProxy::registerIntentServiceForFrame(uint64_t frameID, const IntentServiceInfo& serviceInfo, CoreIPC::MessageDecoder& decoder) -{ - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; - - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - - RefPtr<WebIntentServiceInfo> webIntentServiceInfo = WebIntentServiceInfo::create(serviceInfo); - m_loaderClient.registerIntentServiceForFrame(this, frame, webIntentServiceInfo.get(), userData.get()); -} -#endif - void WebPageProxy::didStartProvisionalLoadForFrame(uint64_t frameID, const String& url, const String& unreachableURL, CoreIPC::MessageDecoder& decoder) { clearPendingAPIRequestURL(); @@ -2100,7 +2248,7 @@ void WebPageProxy::clearLoadDependentCallbacks() } } -void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, const String& mimeType, bool frameHasCustomRepresentation, const PlatformCertificateInfo& certificateInfo, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, const String& mimeType, uint32_t opaqueFrameLoadType, const PlatformCertificateInfo& certificateInfo, CoreIPC::MessageDecoder& decoder) { RefPtr<APIObject> userData; WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); @@ -2112,32 +2260,22 @@ void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, const String& mimeTyp #if PLATFORM(MAC) // FIXME (bug 59111): didCommitLoadForFrame comes too late when restoring a page from b/f cache, making us disable secure event mode in password fields. - // FIXME (bug 59121): A load going on in one frame shouldn't affect typing in sibling frames. - m_pageClient->resetTextInputState(); -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - // FIXME: Should this be moved inside resetTextInputState()? + // FIXME: A load going on in one frame shouldn't affect text editing in other frames on the page. + m_pageClient->resetSecureInputState(); dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored); m_pageClient->dismissDictionaryLookupPanel(); #endif -#endif clearLoadDependentCallbacks(); frame->didCommitLoad(mimeType, certificateInfo); - if (frame->isMainFrame()) { - m_mainFrameHasCustomRepresentation = frameHasCustomRepresentation; - - if (m_mainFrameHasCustomRepresentation) { - // Always assume that the main frame is pinned here, since the custom representation view will handle - // any wheel events and dispatch them to the WKView when necessary. - m_mainFrameIsPinnedToLeftSide = true; - m_mainFrameIsPinnedToRightSide = true; - m_mainFrameIsPinnedToTopSide = true; - m_mainFrameIsPinnedToBottomSide = true; - } - m_pageClient->didCommitLoadForMainFrame(frameHasCustomRepresentation); - } + // Even if WebPage has the default pageScaleFactor (and therefore doesn't reset it), + // WebPageProxy's cache of the value can get out of sync (e.g. in the case where a + // plugin is handling page scaling itself) so we should reset it to the default + // for standard main frame loads. + if (frame->isMainFrame() && static_cast<FrameLoadType>(opaqueFrameLoadType) == FrameLoadTypeStandard) + m_pageScaleFactor = 1; m_loaderClient.didCommitLoadForFrame(this, frame, userData.get()); } @@ -2275,8 +2413,6 @@ void WebPageProxy::didRemoveFrameFromHierarchy(uint64_t frameID, CoreIPC::Messag WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - frame->didRemoveFromHierarchy(); - m_loaderClient.didRemoveFrameFromHierarchy(this, frame, userData.get()); } @@ -2319,22 +2455,6 @@ void WebPageProxy::didDetectXSSForFrame(uint64_t frameID, CoreIPC::MessageDecode m_loaderClient.didDetectXSSForFrame(this, frame, userData.get()); } -#if ENABLE(WEB_INTENTS) -void WebPageProxy::didReceiveIntentForFrame(uint64_t frameID, const IntentData& intentData, CoreIPC::MessageDecoder& decoder) -{ - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; - - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - - RefPtr<WebIntentData> webIntentData = WebIntentData::create(intentData, m_process.get()); - m_loaderClient.didReceiveIntentForFrame(this, frame, webIntentData.get(), userData.get()); -} -#endif - void WebPageProxy::frameDidBecomeFrameSet(uint64_t frameID, bool value) { WebFrameProxy* frame = m_process->webFrame(frameID); @@ -2404,7 +2524,7 @@ void WebPageProxy::decidePolicyForNewWindowAction(uint64_t frameID, uint32_t opa listener->use(); } -void WebPageProxy::decidePolicyForResponse(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID) +void WebPageProxy::decidePolicyForResponse(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder) { RefPtr<APIObject> userData; WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); @@ -2415,18 +2535,25 @@ void WebPageProxy::decidePolicyForResponse(uint64_t frameID, const ResourceRespo MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(request.url()); MESSAGE_CHECK_URL(response.url()); - + RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); - ASSERT(!m_inDecidePolicyForResponse); + if (!m_policyClient.decidePolicyForResponse(this, frame, response, request, listener.get(), userData.get())) + listener->use(); +} - m_inDecidePolicyForResponse = true; +void WebPageProxy::decidePolicyForResponseSync(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID) +{ + ASSERT(!m_inDecidePolicyForResponseSync); + + m_inDecidePolicyForResponseSync = true; + m_decidePolicyForResponseRequest = &request; m_syncMimeTypePolicyActionIsValid = false; - if (!m_policyClient.decidePolicyForResponse(this, frame, response, request, listener.get(), userData.get())) - listener->use(); + decidePolicyForResponse(frameID, response, request, listenerID, decoder); - m_inDecidePolicyForResponse = false; + m_inDecidePolicyForResponseSync = false; + m_decidePolicyForResponseRequest = 0; // Check if we received a policy decision already. If we did, we can just pass it back. receivedPolicyAction = m_syncMimeTypePolicyActionIsValid; @@ -2451,7 +2578,7 @@ void WebPageProxy::unableToImplementPolicy(uint64_t frameID, const ResourceError // FormClient -void WebPageProxy::willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const StringPairVector& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String>>& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder& decoder) { RefPtr<APIObject> userData; WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); @@ -2465,73 +2592,23 @@ void WebPageProxy::willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, cons MESSAGE_CHECK(sourceFrame); RefPtr<WebFormSubmissionListenerProxy> listener = frame->setUpFormSubmissionListenerProxy(listenerID); - if (!m_formClient.willSubmitForm(this, frame, sourceFrame, textFieldValues.stringPairVector(), userData.get(), listener.get())) + if (!m_formClient.willSubmitForm(this, frame, sourceFrame, textFieldValues, userData.get(), listener.get())) listener->continueSubmission(); } -// ResourceLoad Client - -void WebPageProxy::didInitiateLoadForResource(uint64_t frameID, uint64_t resourceIdentifier, const ResourceRequest& request, bool pageIsProvisionallyLoading) -{ - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK_URL(request.url()); - - m_resourceLoadClient.didInitiateLoadForResource(this, frame, resourceIdentifier, request, pageIsProvisionallyLoading); -} - -void WebPageProxy::didSendRequestForResource(uint64_t frameID, uint64_t resourceIdentifier, const ResourceRequest& request, const ResourceResponse& redirectResponse) -{ - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK_URL(request.url()); - - m_resourceLoadClient.didSendRequestForResource(this, frame, resourceIdentifier, request, redirectResponse); -} - -void WebPageProxy::didReceiveResponseForResource(uint64_t frameID, uint64_t resourceIdentifier, const ResourceResponse& response) -{ - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK_URL(response.url()); - - m_resourceLoadClient.didReceiveResponseForResource(this, frame, resourceIdentifier, response); -} - -void WebPageProxy::didReceiveContentLengthForResource(uint64_t frameID, uint64_t resourceIdentifier, uint64_t contentLength) -{ - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - - m_resourceLoadClient.didReceiveContentLengthForResource(this, frame, resourceIdentifier, contentLength); -} - -void WebPageProxy::didFinishLoadForResource(uint64_t frameID, uint64_t resourceIdentifier) -{ - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - - m_resourceLoadClient.didFinishLoadForResource(this, frame, resourceIdentifier); -} - -void WebPageProxy::didFailLoadForResource(uint64_t frameID, uint64_t resourceIdentifier, const ResourceError& error) -{ - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - - m_resourceLoadClient.didFailLoadForResource(this, frame, resourceIdentifier, error); -} - // UIClient void WebPageProxy::createNewPage(const ResourceRequest& request, const WindowFeatures& windowFeatures, uint32_t opaqueModifiers, int32_t opaqueMouseButton, uint64_t& newPageID, WebPageCreationParameters& newPageParameters) { RefPtr<WebPageProxy> newPage = m_uiClient.createNewPage(this, request, windowFeatures, static_cast<WebEvent::Modifiers>(opaqueModifiers), static_cast<WebMouseEvent::Button>(opaqueMouseButton)); - if (newPage) { - newPageID = newPage->pageID(); - newPageParameters = newPage->creationParameters(); - } else + if (!newPage) { newPageID = 0; + return; + } + + newPageID = newPage->pageID(); + newPageParameters = newPage->creationParameters(); + process()->context()->storageManager().cloneSessionStorageNamespace(m_pageID, newPage->pageID()); } void WebPageProxy::showPage() @@ -2606,10 +2683,33 @@ void WebPageProxy::mouseDidMoveOverElement(const WebHitTestResult::Data& hitTest m_uiClient.mouseDidMoveOverElement(this, hitTestResultData, modifiers, userData.get()); } -void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& url, const String& pluginsPageURL) +void WebPageProxy::connectionWillOpen(CoreIPC::Connection* connection) { - MESSAGE_CHECK_URL(url); - MESSAGE_CHECK_URL(pluginsPageURL); + ASSERT(connection == m_process->connection()); + + m_process->context()->storageManager().setAllowedSessionStorageNamespaceConnection(m_pageID, connection); +} + +void WebPageProxy::connectionWillClose(CoreIPC::Connection* connection) +{ + ASSERT_UNUSED(connection, connection == m_process->connection()); + + m_process->context()->storageManager().setAllowedSessionStorageNamespaceConnection(m_pageID, 0); +} + +void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& pluginURLString, const String& pluginspageAttributeURLString, const String& frameURLString, const String& pageURLString) +{ + MESSAGE_CHECK_URL(pluginURLString); + MESSAGE_CHECK_URL(pluginspageAttributeURLString); + MESSAGE_CHECK_URL(frameURLString); + MESSAGE_CHECK_URL(pageURLString); + + RefPtr<ImmutableDictionary> pluginInformation; +#if ENABLE(NETSCAPE_PLUGIN_API) + String newMimeType = mimeType; + PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), pluginURLString)); + pluginInformation = createPluginInformationDictionary(plugin, frameURLString, mimeType, pageURLString, pluginspageAttributeURLString, pluginURLString); +#endif WKPluginUnavailabilityReason pluginUnavailabilityReason = kWKPluginUnavailabilityReasonPluginMissing; switch (static_cast<RenderEmbeddedObject::PluginUnavailabilityReason>(opaquePluginUnavailabilityReason)) { @@ -2622,25 +2722,11 @@ void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailab case RenderEmbeddedObject::PluginCrashed: pluginUnavailabilityReason = kWKPluginUnavailabilityReasonPluginCrashed; break; - - case RenderEmbeddedObject::PluginInactive: { -#if ENABLE(NETSCAPE_PLUGIN_API) - String newMimeType = mimeType; - PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), url)); - - if (!plugin.path.isEmpty() && PluginInfoStore::reactivateInactivePlugin(plugin)) { - // The plug-in has been reactivated now; reload the page so it'll be instantiated. - reload(false); - } - return; -#endif - } - case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy: ASSERT_NOT_REACHED(); } - m_uiClient.unavailablePluginButtonClicked(this, pluginUnavailabilityReason, mimeType, url, pluginsPageURL); + m_uiClient.unavailablePluginButtonClicked(this, pluginUnavailabilityReason, pluginInformation.get()); } void WebPageProxy::setToolbarsAreVisible(bool toolbarsAreVisible) @@ -2740,7 +2826,7 @@ void WebPageProxy::didChangeViewportProperties(const ViewportAttributes& attr) void WebPageProxy::pageDidScroll() { m_uiClient.pageDidScroll(this); -#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 +#if PLATFORM(MAC) dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored); #endif } @@ -2834,7 +2920,7 @@ void WebPageProxy::needTouchEvents(bool needTouchEvents) #if ENABLE(INPUT_TYPE_COLOR) void WebPageProxy::showColorChooser(const WebCore::Color& initialColor, const IntRect& elementRect) { - ASSERT(!m_colorChooser); + ASSERT(!m_colorPicker); if (m_colorPickerResultListener) { m_colorPickerResultListener->invalidate(); @@ -2842,28 +2928,28 @@ void WebPageProxy::showColorChooser(const WebCore::Color& initialColor, const In } m_colorPickerResultListener = WebColorPickerResultListenerProxy::create(this); - m_colorChooser = WebColorChooserProxy::create(this); + m_colorPicker = WebColorPicker::create(this); if (m_uiClient.showColorPicker(this, initialColor.serialized(), m_colorPickerResultListener.get())) return; - m_colorChooser = m_pageClient->createColorChooserProxy(this, initialColor, elementRect); - if (!m_colorChooser) + m_colorPicker = m_pageClient->createColorPicker(this, initialColor, elementRect); + if (!m_colorPicker) didEndColorChooser(); } void WebPageProxy::setColorChooserColor(const WebCore::Color& color) { - ASSERT(m_colorChooser); + ASSERT(m_colorPicker); - m_colorChooser->setSelectedColor(color); + m_colorPicker->setSelectedColor(color); } void WebPageProxy::endColorChooser() { - ASSERT(m_colorChooser); + ASSERT(m_colorPicker); - m_colorChooser->endChooser(); + m_colorPicker->endChooser(); } void WebPageProxy::didChooseColor(const WebCore::Color& color) @@ -2879,9 +2965,9 @@ void WebPageProxy::didEndColorChooser() if (!isValid()) return; - if (m_colorChooser) { - m_colorChooser->invalidate(); - m_colorChooser = nullptr; + if (m_colorPicker) { + m_colorPicker->invalidate(); + m_colorPicker = nullptr; } m_process->send(Messages::WebPage::DidEndColorChooser(), m_pageID); @@ -2906,8 +2992,6 @@ WebInspectorProxy* WebPageProxy::inspector() { if (isClosed() || !isValid()) return 0; - if (!m_inspector) - m_inspector = WebInspectorProxy::create(this); return m_inspector.get(); } @@ -2916,8 +3000,6 @@ WebInspectorProxy* WebPageProxy::inspector() #if ENABLE(FULLSCREEN_API) WebFullScreenManagerProxy* WebPageProxy::fullScreenManager() { - if (!m_fullScreenManager) - m_fullScreenManager = WebFullScreenManagerProxy::create(this); return m_fullScreenManager.get(); } #endif @@ -2961,13 +3043,29 @@ void WebPageProxy::editorStateChanged(const EditorState& editorState) { #if PLATFORM(MAC) bool couldChangeSecureInputState = m_editorState.isInPasswordField != editorState.isInPasswordField || m_editorState.selectionIsNone; + bool closedComposition = !editorState.shouldIgnoreCompositionSelectionChange && !editorState.hasComposition && (m_editorState.hasComposition || m_temporarilyClosedComposition); + m_temporarilyClosedComposition = editorState.shouldIgnoreCompositionSelectionChange && (m_temporarilyClosedComposition || m_editorState.hasComposition) && !editorState.hasComposition; #endif m_editorState = editorState; #if PLATFORM(MAC) - m_pageClient->updateTextInputState(couldChangeSecureInputState); -#elif PLATFORM(QT) || PLATFORM(EFL) + // Selection being none is a temporary state when editing. Flipping secure input state too quickly was causing trouble (not fully understood). + if (couldChangeSecureInputState && !editorState.selectionIsNone) + m_pageClient->updateSecureInputState(); + + if (editorState.shouldIgnoreCompositionSelectionChange) + return; + + if (closedComposition) + m_pageClient->notifyInputContextAboutDiscardedComposition(); + if (editorState.hasComposition) { + // Abandon the current inline input session if selection changed for any other reason but an input method changing the composition. + // FIXME: This logic should be in WebCore, no need to round-trip to UI process to cancel the composition. + cancelComposition(); + m_pageClient->notifyInputContextAboutDiscardedComposition(); + } +#elif PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) m_pageClient->updateTextInputState(); #endif } @@ -3000,6 +3098,11 @@ void WebPageProxy::didCountStringMatches(const String& string, uint32_t matchCou m_findClient.didCountStringMatches(this, string, matchCount); } +void WebPageProxy::didGetImageForFindMatch(const ShareableBitmap::Handle& contentImageHandle, uint32_t matchIndex) +{ + m_findMatchesClient.didGetImageForMatchResult(this, WebImage::create(ShareableBitmap::create(contentImageHandle)).get(), matchIndex); +} + void WebPageProxy::setFindIndicator(const FloatRect& selectionRectInWindowCoordinates, const Vector<FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle, bool fadeOut, bool animate) { RefPtr<FindIndicator> findIndicator = FindIndicator::create(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, contentImageScaleFactor, contentImageHandle); @@ -3011,6 +3114,24 @@ void WebPageProxy::didFindString(const String& string, uint32_t matchCount) m_findClient.didFindString(this, string, matchCount); } +void WebPageProxy::didFindStringMatches(const String& string, Vector<Vector<WebCore::IntRect>> matchRects, int32_t firstIndexAfterSelection) +{ + Vector<RefPtr<APIObject>> matches; + matches.reserveInitialCapacity(matchRects.size()); + + for (size_t i = 0; i < matchRects.size(); ++i) { + const Vector<WebCore::IntRect>& rects = matchRects[i]; + size_t numRects = matchRects[i].size(); + Vector<RefPtr<APIObject>> apiRects; + apiRects.reserveInitialCapacity(numRects); + + for (size_t i = 0; i < numRects; ++i) + apiRects.uncheckedAppend(WebRect::create(toAPI(rects[i]))); + matches.uncheckedAppend(ImmutableArray::adopt(apiRects)); + } + m_findMatchesClient.didFindStringMatches(this, string, ImmutableArray::adopt(matches).get(), firstIndexAfterSelection); +} + void WebPageProxy::didFailToFindString(const String& string) { m_findClient.didFailToFindString(this, string); @@ -3046,7 +3167,11 @@ void WebPageProxy::failedToShowPopupMenu() void WebPageProxy::showPopupMenu(const IntRect& rect, uint64_t textDirection, const Vector<WebPopupItem>& items, int32_t selectedIndex, const PlatformPopupMenuData& data) { if (m_activePopupMenu) { +#if PLATFORM(EFL) + m_uiPopupMenuClient.hidePopupMenu(this); +#else m_activePopupMenu->hidePopupMenu(); +#endif m_activePopupMenu->invalidate(); m_activePopupMenu = 0; } @@ -3059,15 +3184,20 @@ void WebPageProxy::showPopupMenu(const IntRect& rect, uint64_t textDirection, co // Since showPopupMenu() can spin a nested run loop we need to turn off the responsiveness timer. m_process->responsivenessTimer()->stop(); +#if PLATFORM(EFL) + UNUSED_PARAM(data); + m_uiPopupMenuClient.showPopupMenu(this, m_activePopupMenu.get(), rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, selectedIndex); +#else RefPtr<WebPopupMenuProxy> protectedActivePopupMenu = m_activePopupMenu; protectedActivePopupMenu->showPopupMenu(rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, data, selectedIndex); // Since Qt and Efl doesn't use a nested mainloop to show the popup and get the answer, we need to keep the client pointer valid. -#if !PLATFORM(QT) && !PLATFORM(EFL) +#if !PLATFORM(QT) protectedActivePopupMenu->invalidate(); #endif protectedActivePopupMenu = 0; +#endif } void WebPageProxy::hidePopupMenu() @@ -3075,7 +3205,11 @@ void WebPageProxy::hidePopupMenu() if (!m_activePopupMenu) return; +#if PLATFORM(EFL) + m_uiPopupMenuClient.hidePopupMenu(this); +#else m_activePopupMenu->hidePopupMenu(); +#endif m_activePopupMenu->invalidate(); m_activePopupMenu = 0; } @@ -3098,7 +3232,7 @@ void WebPageProxy::internalShowContextMenu(const IntPoint& menuLocation, const W m_activeContextMenuHitTestResultData = hitTestResultData; - if (m_activeContextMenu) { + if (!m_contextMenuClient.hideContextMenu(this) && m_activeContextMenu) { m_activeContextMenu->hideContextMenu(); m_activeContextMenu = 0; } @@ -3112,9 +3246,10 @@ void WebPageProxy::internalShowContextMenu(const IntPoint& menuLocation, const W // Give the PageContextMenuClient one last swipe at changing the menu. Vector<WebContextMenuItemData> items; - if (!m_contextMenuClient.getContextMenuFromProposedMenu(this, proposedItems, items, hitTestResultData, userData.get())) - m_activeContextMenu->showContextMenu(menuLocation, proposedItems); - else + if (!m_contextMenuClient.getContextMenuFromProposedMenu(this, proposedItems, items, hitTestResultData, userData.get())) { + if (!m_contextMenuClient.showContextMenu(this, menuLocation, proposedItems)) + m_activeContextMenu->showContextMenu(menuLocation, proposedItems); + } else if (!m_contextMenuClient.showContextMenu(this, menuLocation, items)) m_activeContextMenu->showContextMenu(menuLocation, items); m_contextMenuClient.contextMenuDismissed(this); @@ -3171,6 +3306,10 @@ void WebPageProxy::contextMenuItemSelected(const WebContextMenuItemData& item) m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteLinkURL)); return; } + if (item.action() == ContextMenuItemTagDownloadMediaToDisk) { + m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteMediaURL)); + return; + } if (item.action() == ContextMenuItemTagCheckSpellingWhileTyping) { TextChecker::setContinuousSpellCheckingEnabled(!TextChecker::state().isContinuousSpellCheckingEnabled); m_process->updateTextCheckerState(); @@ -3326,6 +3465,20 @@ void WebPageProxy::ignoreWord(const String& word) TextChecker::ignoreWord(spellDocumentTag(), word); } +void WebPageProxy::requestCheckingOfString(uint64_t requestID, const TextCheckingRequestData& request) +{ + TextChecker::requestCheckingOfString(TextCheckerCompletion::create(requestID, request, this)); +} + +void WebPageProxy::didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>& result) const +{ + m_process->send(Messages::WebPage::DidFinishCheckingText(requestID, result), m_pageID); +} + +void WebPageProxy::didCancelCheckingText(uint64_t requestID) const +{ + m_process->send(Messages::WebPage::DidCancelCheckingText(requestID), m_pageID); +} // Other void WebPageProxy::setFocus(bool focused) @@ -3423,7 +3576,7 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) case WebEvent::Wheel: { ASSERT(!m_currentlyProcessedWheelEvents.isEmpty()); - OwnPtr<Vector<NativeWebWheelEvent> > oldestCoalescedEvent = m_currentlyProcessedWheelEvents.takeFirst(); + OwnPtr<Vector<NativeWebWheelEvent>> oldestCoalescedEvent = m_currentlyProcessedWheelEvents.takeFirst(); // FIXME: Dispatch additional events to the didNotHandleWheelEvent client function. if (!handled && m_uiClient.implementsDidNotHandleWheelEvent()) @@ -3454,10 +3607,6 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) if (m_uiClient.implementsDidNotHandleKeyEvent()) m_uiClient.didNotHandleKeyEvent(this, event); -#if PLATFORM(WIN) - else - ::TranslateMessage(event.nativeEvent()); -#endif break; } #if ENABLE(TOUCH_EVENTS) @@ -3639,10 +3788,25 @@ void WebPageProxy::processDidBecomeResponsive() void WebPageProxy::processDidCrash() { + ASSERT(m_isValid); + + resetStateAfterProcessExited(); + + m_pageClient->processDidCrash(); + m_loaderClient.processDidCrash(this); +} + +void WebPageProxy::resetStateAfterProcessExited() +{ + if (!isValid()) + return; + ASSERT(m_pageClient); + m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID); m_isValid = false; m_isPageSuspended = false; + m_waitingForDidUpdateInWindowState = false; if (m_mainFrame) { m_urlAtProcessExit = m_mainFrame->url(); @@ -3653,17 +3817,13 @@ void WebPageProxy::processDidCrash() m_drawingArea = nullptr; #if ENABLE(INSPECTOR) - if (m_inspector) { - m_inspector->invalidate(); - m_inspector = nullptr; - } + m_inspector->invalidate(); + m_inspector = nullptr; #endif #if ENABLE(FULLSCREEN_API) - if (m_fullScreenManager) { - m_fullScreenManager->invalidate(); - m_fullScreenManager = nullptr; - } + m_fullScreenManager->invalidate(); + m_fullScreenManager = nullptr; #endif #if ENABLE(VIBRATION) @@ -3676,9 +3836,9 @@ void WebPageProxy::processDidCrash() } #if ENABLE(INPUT_TYPE_COLOR) - if (m_colorChooser) { - m_colorChooser->invalidate(); - m_colorChooser = nullptr; + if (m_colorPicker) { + m_colorPicker->invalidate(); + m_colorPicker = nullptr; } if (m_colorPickerResultListener) { @@ -3729,20 +3889,17 @@ void WebPageProxy::processDidCrash() m_pendingLearnOrIgnoreWordMessageCount = 0; - m_pageClient->processDidCrash(); - m_loaderClient.processDidCrash(this); - - if (!m_isValid) { - // If the call out to the loader client didn't cause the web process to be relaunched, - // we'll call setNeedsDisplay on the view so that we won't have the old contents showing. - // If the call did cause the web process to be relaunched, we'll keep the old page contents showing - // until the new web process has painted its contents. - setViewNeedsDisplay(IntRect(IntPoint(), viewSize())); - } + // If the call out to the loader client didn't cause the web process to be relaunched, + // we'll call setNeedsDisplay on the view so that we won't have the old contents showing. + // If the call did cause the web process to be relaunched, we'll keep the old page contents showing + // until the new web process has painted its contents. + setViewNeedsDisplay(IntRect(IntPoint(), viewSize())); // Can't expect DidReceiveEvent notifications from a crashed web process. +#if ENABLE(GESTURE_EVENTS) + m_gestureEventQueue.clear(); +#endif m_keyEventQueue.clear(); - m_wheelEventQueue.clear(); m_currentlyProcessedWheelEvents.clear(); @@ -3756,7 +3913,11 @@ void WebPageProxy::processDidCrash() m_touchEventQueue.clear(); #endif -#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 + // FIXME: Reset m_editorState. + // FIXME: Notify input methods about abandoned composition. + m_temporarilyClosedComposition = false; + +#if PLATFORM(MAC) dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored); m_pageClient->dismissDictionaryLookupPanel(); #endif @@ -3776,6 +3937,7 @@ WebPageCreationParameters WebPageProxy::creationParameters() const parameters.pageGroupData = m_pageGroup->data(); parameters.drawsBackground = m_drawsBackground; parameters.drawsTransparentBackground = m_drawsTransparentBackground; + parameters.underlayColor = m_underlayColor; parameters.areMemoryCacheClientCallsEnabled = m_areMemoryCacheClientCallsEnabled; parameters.useFixedLayout = m_useFixedLayout; parameters.fixedLayoutSize = m_fixedLayoutSize; @@ -3789,19 +3951,17 @@ WebPageCreationParameters WebPageProxy::creationParameters() const parameters.highestUsedBackForwardItemID = WebBackForwardListItem::highedUsedItemID(); parameters.canRunBeforeUnloadConfirmPanel = m_uiClient.canRunBeforeUnloadConfirmPanel(); parameters.canRunModal = m_canRunModal; - parameters.deviceScaleFactor = m_intrinsicDeviceScaleFactor; + parameters.deviceScaleFactor = deviceScaleFactor(); parameters.mediaVolume = m_mediaVolume; parameters.mayStartMediaWhenInWindow = m_mayStartMediaWhenInWindow; + parameters.minimumLayoutSize = m_minimumLayoutSize; + parameters.scrollPinningBehavior = m_scrollPinningBehavior; #if PLATFORM(MAC) - parameters.isSmartInsertDeleteEnabled = m_isSmartInsertDeleteEnabled; parameters.layerHostingMode = m_layerHostingMode; parameters.colorSpace = m_pageClient->colorSpace(); #endif -#if PLATFORM(WIN) - parameters.nativeWindow = m_pageClient->nativeWindow(); -#endif return parameters; } @@ -3839,22 +3999,45 @@ void WebPageProxy::canAuthenticateAgainstProtectionSpaceInFrame(uint64_t frameID void WebPageProxy::didReceiveAuthenticationChallenge(uint64_t frameID, const AuthenticationChallenge& coreChallenge, uint64_t challengeID) { + didReceiveAuthenticationChallengeProxy(frameID, AuthenticationChallengeProxy::create(coreChallenge, challengeID, m_process->connection())); +} + +void WebPageProxy::didReceiveAuthenticationChallengeProxy(uint64_t frameID, PassRefPtr<AuthenticationChallengeProxy> prpAuthenticationChallenge) +{ + ASSERT(prpAuthenticationChallenge); + WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - RefPtr<AuthenticationChallengeProxy> authenticationChallenge = AuthenticationChallengeProxy::create(coreChallenge, challengeID, m_process.get()); - + RefPtr<AuthenticationChallengeProxy> authenticationChallenge = prpAuthenticationChallenge; m_loaderClient.didReceiveAuthenticationChallengeInFrame(this, frame, authenticationChallenge.get()); } -void WebPageProxy::exceededDatabaseQuota(uint64_t frameID, const String& originIdentifier, const String& databaseName, const String& displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, uint64_t& newQuota) +void WebPageProxy::exceededDatabaseQuota(uint64_t frameID, const String& originIdentifier, const String& databaseName, const String& displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply) { - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); + ExceededDatabaseQuotaRecords& records = ExceededDatabaseQuotaRecords::shared(); + OwnPtr<ExceededDatabaseQuotaRecords::Record> newRecord = records.createRecord(frameID, + originIdentifier, databaseName, displayName, currentQuota, currentOriginUsage, + currentDatabaseUsage, expectedUsage, reply); + records.add(newRecord.release()); - RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromDatabaseIdentifier(originIdentifier); + if (records.areBeingProcessed()) + return; + + ExceededDatabaseQuotaRecords::Record* record = records.next(); + while (record) { + WebFrameProxy* frame = m_process->webFrame(record->frameID); + MESSAGE_CHECK(frame); - newQuota = m_uiClient.exceededDatabaseQuota(this, frame, origin.get(), databaseName, displayName, currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage); + RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromDatabaseIdentifier(record->originIdentifier); + + uint64_t newQuota = m_uiClient.exceededDatabaseQuota(this, frame, origin.get(), + record->databaseName, record->displayName, record->currentQuota, + record->currentOriginUsage, record->currentDatabaseUsage, record->expectedUsage); + + record->reply->send(newQuota); + record = records.next(); + } } void WebPageProxy::requestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, String originIdentifier) @@ -3884,7 +4067,22 @@ void WebPageProxy::requestNotificationPermission(uint64_t requestID, const Strin void WebPageProxy::showNotification(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID) { - m_process->context()->notificationManagerProxy()->show(this, title, body, iconURL, tag, lang, dir, originString, notificationID); + m_process->context()->supplement<WebNotificationManagerProxy>()->show(this, title, body, iconURL, tag, lang, dir, originString, notificationID); +} + +void WebPageProxy::cancelNotification(uint64_t notificationID) +{ + m_process->context()->supplement<WebNotificationManagerProxy>()->cancel(this, notificationID); +} + +void WebPageProxy::clearNotifications(const Vector<uint64_t>& notificationIDs) +{ + m_process->context()->supplement<WebNotificationManagerProxy>()->clearNotifications(this, notificationIDs); +} + +void WebPageProxy::didDestroyNotification(uint64_t notificationID) +{ + m_process->context()->supplement<WebNotificationManagerProxy>()->didDestroyNotification(this, notificationID); } float WebPageProxy::headerHeight(WebFrameProxy* frame) @@ -3947,8 +4145,6 @@ void WebPageProxy::didChangeScrollbarsForMainFrame(bool hasHorizontalScrollbar, { m_mainFrameHasHorizontalScrollbar = hasHorizontalScrollbar; m_mainFrameHasVerticalScrollbar = hasVerticalScrollbar; - - m_pageClient->didChangeScrollbarsForMainFrame(); } void WebPageProxy::didChangeScrollOffsetPinningForMainFrame(bool pinnedToLeftSide, bool pinnedToRightSide, bool pinnedToTopSide, bool pinnedToBottomSide) @@ -3964,28 +4160,24 @@ void WebPageProxy::didChangePageCount(unsigned pageCount) m_pageCount = pageCount; } -void WebPageProxy::didFailToInitializePlugin(const String& mimeType) +void WebPageProxy::didFailToInitializePlugin(const String& mimeType, const String& frameURLString, const String& pageURLString) { - m_loaderClient.didFailToInitializePlugin(this, mimeType); + m_loaderClient.didFailToInitializePlugin(this, createPluginInformationDictionary(mimeType, frameURLString, pageURLString).get()); } -// FIXME: ENABLE(NETSCAPE_PLUGIN_API) -void WebPageProxy::didBlockInsecurePluginVersion(const String& mimeType, const String& urlString) +void WebPageProxy::didBlockInsecurePluginVersion(const String& mimeType, const String& pluginURLString, const String& frameURLString, const String& pageURLString, bool replacementObscured) { - String pluginIdentifier; - String pluginVersion; - String newMimeType = mimeType; + RefPtr<ImmutableDictionary> pluginInformation; #if PLATFORM(MAC) && ENABLE(NETSCAPE_PLUGIN_API) - PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString)); - - pluginIdentifier = plugin.bundleIdentifier; - pluginVersion = plugin.versionString; + String newMimeType = mimeType; + PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), pluginURLString)); + pluginInformation = createPluginInformationDictionary(plugin, frameURLString, mimeType, pageURLString, String(), String(), replacementObscured); #else - UNUSED_PARAM(urlString); + UNUSED_PARAM(pluginURLString); #endif - m_loaderClient.didBlockInsecurePluginVersion(this, newMimeType, pluginIdentifier, pluginVersion); + m_loaderClient.didBlockInsecurePluginVersion(this, pluginInformation.get()); } bool WebPageProxy::willHandleHorizontalScrollEvents() const @@ -3993,11 +4185,6 @@ bool WebPageProxy::willHandleHorizontalScrollEvents() const return !m_canShortCircuitHorizontalWheelEvents; } -void WebPageProxy::didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference& dataReference) -{ - m_pageClient->didFinishLoadingDataForCustomRepresentation(suggestedFilename, dataReference); -} - void WebPageProxy::backForwardRemovedItem(uint64_t itemID) { m_process->send(Messages::WebPage::DidRemoveBackForwardItem(itemID), m_pageID); @@ -4052,8 +4239,8 @@ void WebPageProxy::computePagesForPrinting(WebFrameProxy* frame, const PrintInfo m_process->send(Messages::WebPage::ComputePagesForPrinting(frame->frameID(), printInfo, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } -#if PLATFORM(MAC) || PLATFORM(WIN) -void WebPageProxy::drawRectToImage(WebFrameProxy* frame, const PrintInfo& printInfo, const IntRect& rect, PassRefPtr<ImageCallback> prpCallback) +#if PLATFORM(MAC) +void WebPageProxy::drawRectToImage(WebFrameProxy* frame, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, PassRefPtr<ImageCallback> prpCallback) { RefPtr<ImageCallback> callback = prpCallback; if (!isValid()) { @@ -4063,7 +4250,7 @@ void WebPageProxy::drawRectToImage(WebFrameProxy* frame, const PrintInfo& printI uint64_t callbackID = callback->callbackID(); m_imageCallbacks.set(callbackID, callback.get()); - m_process->send(Messages::WebPage::DrawRectToImage(frame->frameID(), printInfo, rect, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_process->send(Messages::WebPage::DrawRectToImage(frame->frameID(), printInfo, rect, imageSize, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } void WebPageProxy::drawPagesToPDF(WebFrameProxy* frame, const PrintInfo& printInfo, uint32_t first, uint32_t count, PassRefPtr<DataCallback> prpCallback) @@ -4143,16 +4330,21 @@ void WebPageProxy::linkClicked(const String& url, const WebMouseEvent& event) m_process->send(Messages::WebPage::LinkClicked(url, event), m_pageID, 0); } -void WebPageProxy::setMinimumLayoutWidth(double minimumLayoutWidth) +void WebPageProxy::setMinimumLayoutSize(const IntSize& minimumLayoutSize) { - if (m_minimumLayoutWidth == minimumLayoutWidth) + if (m_minimumLayoutSize == minimumLayoutSize) + return; + + m_minimumLayoutSize = minimumLayoutSize; + + if (!isValid()) return; - m_minimumLayoutWidth = minimumLayoutWidth; - m_drawingArea->minimumLayoutWidthDidChange(); + m_process->send(Messages::WebPage::SetMinimumLayoutSize(minimumLayoutSize), m_pageID, 0); + m_drawingArea->minimumLayoutSizeDidChange(); #if PLATFORM(MAC) - if (m_minimumLayoutWidth <= 0) + if (m_minimumLayoutSize.width() <= 0) intrinsicContentSizeDidChange(IntSize(-1, -1)); #endif } @@ -4164,7 +4356,6 @@ void WebPageProxy::substitutionsPanelIsShowing(bool& isShowing) isShowing = TextChecker::substitutionsPanelIsShowing(); } -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 void WebPageProxy::showCorrectionPanel(int32_t panelType, const FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) { m_pageClient->showCorrectionPanel((AlternativeTextType)panelType, boundingBoxOfReplacedString, replacedString, replacementString, alternativeReplacementStrings); @@ -4184,14 +4375,11 @@ void WebPageProxy::recordAutocorrectionResponse(int32_t responseType, const Stri { m_pageClient->recordAutocorrectionResponse((AutocorrectionResponseType)responseType, replacedString, replacementString); } -#endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 void WebPageProxy::handleAlternativeTextUIResult(const String& result) { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 if (!isClosed()) m_process->send(Messages::WebPage::HandleAlternativeTextUIResult(result), m_pageID, 0); -#endif } #if USE(DICTATION_ALTERNATIVES) @@ -4200,11 +4388,6 @@ void WebPageProxy::showDictationAlternativeUI(const WebCore::FloatRect& bounding m_pageClient->showDictationAlternativeUI(boundingBoxOfDictatedText, dictationContext); } -void WebPageProxy::dismissDictationAlternativeUI() -{ - m_pageClient->dismissDictationAlternativeUI(); -} - void WebPageProxy::removeDictationAlternatives(uint64_t dictationContext) { m_pageClient->removeDictationAlternatives(dictationContext); @@ -4221,8 +4404,62 @@ void WebPageProxy::dictationAlternatives(uint64_t dictationContext, Vector<Strin #if USE(SOUP) void WebPageProxy::didReceiveURIRequest(String uriString, uint64_t requestID) { - m_process->context()->soupRequestManagerProxy()->didReceiveURIRequest(uriString, this, requestID); + m_process->context()->supplement<WebSoupRequestManagerProxy>()->didReceiveURIRequest(uriString, this, requestID); } #endif +#if PLATFORM(QT) || PLATFORM(GTK) +void WebPageProxy::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) +{ + // FIXME: We need to find out how to proper handle the crashes case. + if (!isValid()) + return; + + process()->send(Messages::WebPage::SetComposition(text, underlines, selectionStart, selectionEnd, replacementRangeStart, replacementRangeEnd), m_pageID); +} + +void WebPageProxy::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength) +{ + if (!isValid()) + return; + + process()->send(Messages::WebPage::ConfirmComposition(compositionString, selectionStart, selectionLength), m_pageID); +} + +void WebPageProxy::cancelComposition() +{ + if (!isValid()) + return; + + process()->send(Messages::WebPage::CancelComposition(), m_pageID); +} +#endif // PLATFORM(QT) || PLATFORM(GTK) + +void WebPageProxy::setMainFrameInViewSourceMode(bool mainFrameInViewSourceMode) +{ + if (m_mainFrameInViewSourceMode == mainFrameInViewSourceMode) + return; + + m_mainFrameInViewSourceMode = mainFrameInViewSourceMode; + + if (isValid()) + m_process->send(Messages::WebPage::SetMainFrameInViewSourceMode(mainFrameInViewSourceMode), m_pageID); +} + +void WebPageProxy::didSaveToPageCache() +{ + m_process->didSaveToPageCache(); +} + +void WebPageProxy::setScrollPinningBehavior(ScrollPinningBehavior pinning) +{ + if (m_scrollPinningBehavior == pinning) + return; + + m_scrollPinningBehavior = pinning; + + if (isValid()) + m_process->send(Messages::WebPage::SetScrollPinningBehavior(pinning), m_pageID); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPageProxy.h b/Source/WebKit2/UIProcess/WebPageProxy.h index b97cdf35e..64aa05116 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.h +++ b/Source/WebKit2/UIProcess/WebPageProxy.h @@ -32,12 +32,6 @@ #include "DrawingAreaProxy.h" #include "EditorState.h" #include "GeolocationPermissionRequestManagerProxy.h" -#if ENABLE(TOUCH_EVENTS) -#include "NativeWebTouchEvent.h" -#endif -#if PLATFORM(QT) -#include "QtNetworkRequestData.h" -#endif #include "LayerTreeContext.h" #include "NotificationPermissionRequestManagerProxy.h" #include "PlatformProcessIdentifier.h" @@ -45,7 +39,7 @@ #include "ShareableBitmap.h" #include "WKBase.h" #include "WKPagePrivate.h" -#include "WebColorChooserProxy.h" +#include "WebColorPicker.h" #include "WebContextMenuItemData.h" #include "WebCoreArgumentCoders.h" #include "WebFindClient.h" @@ -55,11 +49,11 @@ #include "WebHitTestResult.h" #include "WebLoaderClient.h" #include "WebPageContextMenuClient.h" +#include <WebCore/AlternativeTextClient.h> // FIXME: Needed by WebPageProxyMessages.h for DICTATION_ALTERNATIVES. +#include "WebPageProxyMessages.h" #include "WebPolicyClient.h" #include "WebPopupMenuProxy.h" -#include "WebResourceLoadClient.h" #include "WebUIClient.h" -#include <WebCore/AlternativeTextClient.h> #include <WebCore/Color.h> #include <WebCore/DragActions.h> #include <WebCore/DragSession.h> @@ -82,14 +76,23 @@ #include <WebCore/DragSession.h> #endif +#if ENABLE(TOUCH_EVENTS) +#include "NativeWebTouchEvent.h" +#endif + #if PLATFORM(EFL) +#include "WKPageEfl.h" +#include "WebUIPopupMenuClient.h" #include <Evas.h> #endif +#if PLATFORM(QT) +#include "QtNetworkRequestData.h" +#endif + namespace CoreIPC { class ArgumentDecoder; class Connection; - class MessageID; } namespace WebCore { @@ -97,6 +100,7 @@ namespace WebCore { class Cursor; class DragData; class FloatRect; + class GraphicsLayer; class IntSize; class ProtectionSpace; class SharedBuffer; @@ -121,12 +125,6 @@ class WKView; #if PLATFORM(GTK) typedef GtkWidget* PlatformWidget; -#elif PLATFORM(EFL) -typedef Evas_Object* PlatformWidget; -#endif - -#if ENABLE(WEB_INTENTS) -class WebIntentData; #endif namespace WebKit { @@ -160,10 +158,6 @@ struct PrintInfo; struct WebPageCreationParameters; struct WebPopupItem; -#if PLATFORM(WIN) -struct WindowGeometry; -#endif - #if ENABLE(GESTURE_EVENTS) class WebGestureEvent; #endif @@ -172,14 +166,6 @@ class WebGestureEvent; class WebVibrationProxy; #endif -#if ENABLE(WEB_INTENTS) -struct IntentData; -#endif - -#if ENABLE(WEB_INTENTS_TAG) -struct IntentServiceInfo; -#endif - typedef GenericCallback<WKStringRef, StringImpl*> StringCallback; typedef GenericCallback<WKSerializedScriptValueRef, WebSerializedScriptValue*> ScriptValueCallback; @@ -244,13 +230,13 @@ private: }; class WebPageProxy - : public APIObject + : public TypedAPIObject<APIObject::TypePage> #if ENABLE(INPUT_TYPE_COLOR) - , public WebColorChooserProxy::Client + , public WebColorPicker::Client #endif - , public WebPopupMenuProxy::Client { + , public WebPopupMenuProxy::Client + , public CoreIPC::MessageReceiver { public: - static const Type APIType = TypePage; static PassRefPtr<WebPageProxy> create(PageClient*, PassRefPtr<WebProcessProxy>, WebPageGroup*, uint64_t pageID); virtual ~WebPageProxy(); @@ -281,11 +267,14 @@ public: void initializeContextMenuClient(const WKPageContextMenuClient*); #endif void initializeFindClient(const WKPageFindClient*); + void initializeFindMatchesClient(const WKPageFindMatchesClient*); void initializeFormClient(const WKPageFormClient*); void initializeLoaderClient(const WKPageLoaderClient*); void initializePolicyClient(const WKPagePolicyClient*); - void initializeResourceLoadClient(const WKPageResourceLoadClient*); void initializeUIClient(const WKPageUIClient*); +#if PLATFORM(EFL) + void initializeUIPopupMenuClient(const WKPageUIPopupMenuClient*); +#endif void initializeWebPage(); @@ -293,12 +282,14 @@ public: bool tryClose(); bool isClosed() const { return m_isClosed; } - void loadURL(const String&); - void loadURLRequest(WebURLRequest*); - void loadHTMLString(const String& htmlString, const String& baseURL); - void loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL); - void loadPlainTextString(const String& string); - void loadWebArchiveData(const WebData*); + void loadURL(const String&, APIObject* userData = 0); + void loadURLRequest(WebURLRequest*, APIObject* userData = 0); + void loadFile(const String& fileURL, const String& resourceDirectoryURL, APIObject* userData = 0); + void loadData(WebData*, const String& MIMEType, const String& encoding, const String& baseURL, APIObject* userData = 0); + void loadHTMLString(const String& htmlString, const String& baseURL, APIObject* userData = 0); + void loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, APIObject* userData = 0); + void loadPlainTextString(const String& string, APIObject* userData = 0); + void loadWebArchiveData(const WebData*, APIObject* userData = 0); void stopLoading(); void reload(bool reloadFromOrigin); @@ -310,7 +301,7 @@ public: void goToBackForwardItem(WebBackForwardListItem*); void tryRestoreScrollPosition(); - void didChangeBackForwardList(WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject> >* removedItems); + void didChangeBackForwardList(WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject>>* removedItems); void shouldGoToBackForwardListItem(uint64_t itemID, bool& shouldGoToBackForwardListItem); void willGoToBackForwardListItem(uint64_t itemID, CoreIPC::MessageDecoder&); @@ -328,6 +319,9 @@ public: bool drawsTransparentBackground() const { return m_drawsTransparentBackground; } void setDrawsTransparentBackground(bool); + WebCore::Color underlayColor() const { return m_underlayColor; } + void setUnderlayColor(const WebCore::Color&); + void viewWillStartLiveResize(); void viewWillEndLiveResize(); @@ -338,6 +332,7 @@ public: void setViewNeedsDisplay(const WebCore::IntRect&); void displayView(); + bool canScrollView(); void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); enum { @@ -348,6 +343,8 @@ public: }; typedef unsigned ViewStateFlags; void viewStateDidChange(ViewStateFlags flags); + bool isInWindow() const { return m_isInWindow; } + void waitForDidUpdateInWindowState(); WebCore::IntSize viewSize() const; bool isViewVisible() const { return m_isVisible; } @@ -373,20 +370,27 @@ public: void authenticationRequiredRequest(const String& hostname, const String& realm, const String& prefilledUsername, String& username, String& password); void certificateVerificationRequest(const String& hostname, bool& ignoreErrors); void proxyAuthenticationRequiredRequest(const String& hostname, uint16_t port, const String& prefilledUsername, String& username, String& password); - void setUserScripts(const Vector<String>&); #endif // PLATFORM(QT). #if PLATFORM(EFL) void setThemePath(const String&); #endif -#if PLATFORM(QT) +#if PLATFORM(QT) || PLATFORM(GTK) void setComposition(const String& text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd); void confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength); void cancelComposition(); #endif + +#if PLATFORM(GTK) + void setInputMethodState(bool enabled); +#endif + #if PLATFORM(MAC) void updateWindowIsVisible(bool windowIsVisible); - void windowAndViewFramesChanged(const WebCore::IntRect& windowFrameInScreenCoordinates, const WebCore::IntRect& viewFrameInWindowCoordinates, const WebCore::IntPoint& accessibilityViewCoordinates); + void windowAndViewFramesChanged(const WebCore::FloatRect& viewFrameInWindowCoordinates, const WebCore::FloatPoint& accessibilityViewCoordinates); + void viewExposedRectChanged(const WebCore::FloatRect& exposedRect, bool); + void exposedRectChangedTimerFired(WebCore::Timer<WebPageProxy>*); + void setMainFrameIsScrollable(bool); void setComposition(const String& text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd); void confirmComposition(); @@ -412,32 +416,16 @@ public: void intrinsicContentSizeDidChange(const WebCore::IntSize& intrinsicContentSize); #endif #endif -#if PLATFORM(WIN) - void didChangeCompositionSelection(bool); - void confirmComposition(const String&); - void setComposition(const String&, Vector<WebCore::CompositionUnderline>&, int); - WebCore::IntRect firstRectForCharacterInSelectedRange(int); - String getSelectedText(); - - bool gestureWillBegin(const WebCore::IntPoint&); - void gestureDidScroll(const WebCore::IntSize&); - void gestureDidEnd(); - - void setGestureReachedScrollingLimit(bool); - - HWND nativeWindow() const; -#endif #if PLATFORM(EFL) void handleInputMethodKeydown(bool& handled); void confirmComposition(const String&); void setComposition(const String&, Vector<WebCore::CompositionUnderline>&, int); void cancelComposition(); #endif -#if USE(CAIRO) && !PLATFORM(WIN_CAIRO) +#if PLATFORM(GTK) PlatformWidget viewWidget(); #endif #if USE(TILED_BACKING_STORE) - void setViewportSize(const WebCore::IntSize&); void commitPageTransitionViewport(); #endif @@ -485,9 +473,9 @@ public: void restoreFromSessionStateData(WebData*); bool supportsTextZoom() const; - double textZoomFactor() const { return m_mainFrameHasCustomRepresentation ? 1 : m_textZoomFactor; } + double textZoomFactor() const { return m_textZoomFactor; } void setTextZoomFactor(double); - double pageZoomFactor() const; + double pageZoomFactor() const { return m_pageZoomFactor; } void setPageZoomFactor(double); void setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor); @@ -509,6 +497,7 @@ public: void listenForLayoutMilestones(WebCore::LayoutMilestones); void setVisibilityState(WebCore::PageVisibilityState, bool isInitialState); + void didUpdateInWindowState() { m_waitingForDidUpdateInWindowState = false; } bool hasHorizontalScrollbar() const { return m_mainFrameHasHorizontalScrollbar; } bool hasVerticalScrollbar() const { return m_mainFrameHasVerticalScrollbar; } @@ -521,6 +510,11 @@ public: bool isPinnedToTopSide() const { return m_mainFrameIsPinnedToTopSide; } bool isPinnedToBottomSide() const { return m_mainFrameIsPinnedToBottomSide; } + bool rubberBandsAtBottom() const { return m_rubberBandsAtBottom; } + void setRubberBandsAtBottom(bool); + bool rubberBandsAtTop() const { return m_rubberBandsAtTop; } + void setRubberBandsAtTop(bool); + void setPaginationMode(WebCore::Pagination::Mode); WebCore::Pagination::Mode paginationMode() const { return m_paginationMode; } void setPaginationBehavesLikeColumns(bool); @@ -545,20 +539,23 @@ public: #endif void pageScaleFactorDidChange(double); + void pageZoomFactorDidChange(double); void setMemoryCacheClientCallsEnabled(bool); // Find. void findString(const String&, FindOptions, unsigned maxMatchCount); + void findStringMatches(const String&, FindOptions, unsigned maxMatchCount); + void getImageForFindMatch(int32_t matchIndex); + void selectFindMatch(int32_t matchIndex); + void didGetImageForFindMatch(const ShareableBitmap::Handle& contentImageHandle, uint32_t matchIndex); void hideFindUI(); void countStringMatches(const String&, FindOptions, unsigned maxMatchCount); void didCountStringMatches(const String&, uint32_t matchCount); void setFindIndicator(const WebCore::FloatRect& selectionRectInWindowCoordinates, const Vector<WebCore::FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle, bool fadeOut, bool animate); void didFindString(const String&, uint32_t matchCount); void didFailToFindString(const String&); -#if PLATFORM(WIN) - void didInstallOrUninstallPageOverlay(bool); -#endif + void didFindStringMatches(const String&, Vector<Vector<WebCore::IntRect>> matchRects, int32_t firstIndexAfterSelection); void getContentsAsString(PassRefPtr<StringCallback>); #if ENABLE(MHTML) @@ -568,15 +565,12 @@ public: void getResourceDataFromFrame(WebFrameProxy*, WebURL*, PassRefPtr<DataCallback>); void getRenderTreeExternalRepresentation(PassRefPtr<StringCallback>); void getSelectionOrContentsAsString(PassRefPtr<StringCallback>); + void getSelectionAsWebArchiveData(PassRefPtr<DataCallback>); void getSourceForFrame(WebFrameProxy*, PassRefPtr<StringCallback>); void getWebArchiveOfFrame(WebFrameProxy*, PassRefPtr<DataCallback>); void runJavaScriptInMainFrame(const String&, PassRefPtr<ScriptValueCallback>); void forceRepaint(PassRefPtr<VoidCallback>); -#if ENABLE(WEB_INTENTS) - void deliverIntentToFrame(WebFrameProxy*, WebIntentData*); -#endif - float headerHeight(WebFrameProxy*); float footerHeight(WebFrameProxy*); void drawHeader(WebFrameProxy*, const WebCore::FloatRect&); @@ -605,17 +599,11 @@ public: void setPromisedData(const String& pasteboardName, const SharedMemory::Handle& imageHandle, uint64_t imageSize, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL, const SharedMemory::Handle& archiveHandle, uint64_t archiveSize); #endif -#if PLATFORM(WIN) - void startDragDrop(const WebCore::IntPoint& imagePoint, const WebCore::IntPoint& dragPoint, uint64_t okEffect, const HashMap<UINT, Vector<String> >& dataMap, uint64_t fileSize, const String& pathname, const SharedMemory::Handle& fileContentHandle, const WebCore::IntSize& dragImageSize, const SharedMemory::Handle& dragImageHandle, bool isLinkDrag); -#endif #if PLATFORM(QT) || PLATFORM(GTK) void startDrag(const WebCore::DragData&, const ShareableBitmap::Handle& dragImage); #endif #endif - void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - void processDidBecomeUnresponsive(); void interactionOccurredWhileProcessUnresponsive(); void processDidBecomeResponsive(); @@ -645,7 +633,7 @@ public: WebPageGroup* pageGroup() const { return m_pageGroup.get(); } - bool isValid(); + bool isValid() const; PassRefPtr<ImmutableArray> relatedPages() const; @@ -670,9 +658,8 @@ public: WebPageCreationParameters creationParameters() const; -#if PLATFORM(QT) +#if USE(COORDINATED_GRAPHICS) void findZoomableAreaForPoint(const WebCore::IntPoint&, const WebCore::IntSize&); - void didReceiveMessageFromNavigatorQtObject(const String&); #endif #if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) @@ -702,8 +689,8 @@ public: void beginPrinting(WebFrameProxy*, const PrintInfo&); void endPrinting(); void computePagesForPrinting(WebFrameProxy*, const PrintInfo&, PassRefPtr<ComputedPagesCallback>); -#if PLATFORM(MAC) || PLATFORM(WIN) - void drawRectToImage(WebFrameProxy*, const PrintInfo&, const WebCore::IntRect&, PassRefPtr<ImageCallback>); +#if PLATFORM(MAC) + void drawRectToImage(WebFrameProxy*, const PrintInfo&, const WebCore::IntRect&, const WebCore::IntSize&, PassRefPtr<ImageCallback>); void drawPagesToPDF(WebFrameProxy*, const PrintInfo&, uint32_t first, uint32_t count, PassRefPtr<DataCallback>); #elif PLATFORM(GTK) void drawPagesForPrinting(WebFrameProxy*, const PrintInfo&, PassRefPtr<PrintFinishedCallback>); @@ -728,6 +715,11 @@ public: void saveDataToFileInDownloadsFolder(const String& suggestedFilename, const String& mimeType, const String& originatingURLString, WebData*); void savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference&); +#if PLATFORM(MAC) + void savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID); + void savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference&, const String& pdfUUID); + void openPDFFromTemporaryFolderWithNativeApplication(const String& pdfUUID); +#endif void linkClicked(const String&, const WebMouseEvent&); @@ -761,13 +753,34 @@ public: const WebLoaderClient& loaderClient() { return m_loaderClient; } - double minimumLayoutWidth() const { return m_minimumLayoutWidth; } - void setMinimumLayoutWidth(double); + WebCore::IntSize minimumLayoutSize() const { return m_minimumLayoutSize; } + void setMinimumLayoutSize(const WebCore::IntSize&); + + bool mainFrameInViewSourceMode() const { return m_mainFrameInViewSourceMode; } + void setMainFrameInViewSourceMode(bool); + void didReceiveAuthenticationChallengeProxy(uint64_t frameID, PassRefPtr<AuthenticationChallengeProxy>); + + int64_t spellDocumentTag(); + void didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>&) const; + void didCancelCheckingText(uint64_t requestID) const; + + void connectionWillOpen(CoreIPC::Connection*); + void connectionWillClose(CoreIPC::Connection*); + + void didSaveToPageCache(); + + void setScrollPinningBehavior(WebCore::ScrollPinningBehavior); + WebCore::ScrollPinningBehavior scrollPinningBehavior() { return m_scrollPinningBehavior; } + private: WebPageProxy(PageClient*, PassRefPtr<WebProcessProxy>, WebPageGroup*, uint64_t pageID); - virtual Type type() const { return APIType; } + void resetStateAfterProcessExited(); + + // CoreIPC::MessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; // WebPopupMenuProxy::Client virtual void valueChangedForPopupMenu(WebPopupMenuProxy*, int32_t newSelectedIndex); @@ -781,18 +794,16 @@ private: #endif // Implemented in generated WebPageProxyMessageReceiver.cpp - void didReceiveWebPageProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebPageProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + void didReceiveWebPageProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); + void didReceiveSyncWebPageProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); void didCreateMainFrame(uint64_t frameID); - void didCreateSubframe(uint64_t frameID, uint64_t parentFrameID); - void didSaveFrameToPageCache(uint64_t frameID); - void didRestoreFrameFromPageCache(uint64_t frameID, uint64_t parentFrameID); + void didCreateSubframe(uint64_t frameID); void didStartProvisionalLoadForFrame(uint64_t frameID, const String& url, const String& unreachableURL, CoreIPC::MessageDecoder&); void didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, const String&, CoreIPC::MessageDecoder&); void didFailProvisionalLoadForFrame(uint64_t frameID, const WebCore::ResourceError&, CoreIPC::MessageDecoder&); - void didCommitLoadForFrame(uint64_t frameID, const String& mimeType, bool frameHasCustomRepresentation, const PlatformCertificateInfo&, CoreIPC::MessageDecoder&); + void didCommitLoadForFrame(uint64_t frameID, const String& mimeType, uint32_t frameLoadType, const PlatformCertificateInfo&, CoreIPC::MessageDecoder&); void didFinishDocumentLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); void didFinishLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); void didFailLoadForFrame(uint64_t frameID, const WebCore::ResourceError&, CoreIPC::MessageDecoder&); @@ -811,27 +822,13 @@ private: void didChangeProgress(double); void didFinishProgress(); -#if ENABLE(WEB_INTENTS) - void didReceiveIntentForFrame(uint64_t frameID, const IntentData&, CoreIPC::MessageDecoder&); -#endif -#if ENABLE(WEB_INTENTS_TAG) - void registerIntentServiceForFrame(uint64_t frameID, const IntentServiceInfo&, CoreIPC::MessageDecoder&); -#endif - void decidePolicyForNavigationAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID); void decidePolicyForNewWindowAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, const WebCore::ResourceRequest&, const String& frameName, uint64_t listenerID, CoreIPC::MessageDecoder&); - void decidePolicyForResponse(uint64_t frameID, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID); + void decidePolicyForResponse(uint64_t frameID, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&); + void decidePolicyForResponseSync(uint64_t frameID, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID); void unableToImplementPolicy(uint64_t frameID, const WebCore::ResourceError&, CoreIPC::MessageDecoder&); - void willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const StringPairVector& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder&); - - // Resource load client - void didInitiateLoadForResource(uint64_t frameID, uint64_t resourceIdentifier, const WebCore::ResourceRequest&, bool pageIsProvisionallyLoading); - void didSendRequestForResource(uint64_t frameID, uint64_t resourceIdentifier, const WebCore::ResourceRequest&, const WebCore::ResourceResponse& redirectResponse); - void didReceiveResponseForResource(uint64_t frameID, uint64_t resourceIdentifier, const WebCore::ResourceResponse&); - void didReceiveContentLengthForResource(uint64_t frameID, uint64_t resourceIdentifier, uint64_t contentLength); - void didFinishLoadForResource(uint64_t frameID, uint64_t resourceIdentifier); - void didFailLoadForResource(uint64_t frameID, uint64_t resourceIdentifier, const WebCore::ResourceError&); + void willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String>>& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder&); // UI client void createNewPage(const WebCore::ResourceRequest&, const WebCore::WindowFeatures&, uint32_t modifiers, int32_t mouseButton, uint64_t& newPageID, WebPageCreationParameters&); @@ -843,7 +840,7 @@ private: void shouldInterruptJavaScript(bool& result); void setStatusText(const String&); void mouseDidMoveOverElement(const WebHitTestResult::Data& hitTestResultData, uint32_t modifiers, CoreIPC::MessageDecoder&); - void unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& url, const String& pluginsPageURL); + void unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& pluginURLString, const String& pluginsPageURLString, const String& frameURLString, const String& pageURLString); void setToolbarsAreVisible(bool toolbarsAreVisible); void getToolbarsAreVisible(bool& toolbarsAreVisible); void setMenuBarIsVisible(bool menuBarIsVisible); @@ -861,7 +858,7 @@ private: void pageDidScroll(); void runOpenPanel(uint64_t frameID, const WebCore::FileChooserSettings&); void printFrame(uint64_t frameID); - void exceededDatabaseQuota(uint64_t frameID, const String& originIdentifier, const String& databaseName, const String& displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, uint64_t& newQuota); + void exceededDatabaseQuota(uint64_t frameID, const String& originIdentifier, const String& databaseName, const String& displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply>); void requestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, String originIdentifier); void runModal(); void notifyScrollerThumbIsVisibleInRect(const WebCore::IntRect&); @@ -869,8 +866,8 @@ private: void didChangeScrollbarsForMainFrame(bool hasHorizontalScrollbar, bool hasVerticalScrollbar); void didChangeScrollOffsetPinningForMainFrame(bool pinnedToLeftSide, bool pinnedToRightSide, bool pinnedToTopSide, bool pinnedToBottomSide); void didChangePageCount(unsigned); - void didFailToInitializePlugin(const String& mimeType); - void didBlockInsecurePluginVersion(const String& mimeType, const String& urlString); + void didFailToInitializePlugin(const String& mimeType, const String& frameURLString, const String& pageURLString); + void didBlockInsecurePluginVersion(const String& mimeType, const String& pluginURLString, const String& frameURLString, const String& pageURLString, bool replacementObscured); void setCanShortCircuitHorizontalWheelEvents(bool canShortCircuitHorizontalWheelEvents) { m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents; } void reattachToWebProcess(); @@ -878,15 +875,17 @@ private: void requestNotificationPermission(uint64_t notificationID, const String& originString); void showNotification(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID); - + void cancelNotification(uint64_t notificationID); + void clearNotifications(const Vector<uint64_t>& notificationIDs); + void didDestroyNotification(uint64_t notificationID); + #if USE(TILED_BACKING_STORE) void pageDidRequestScroll(const WebCore::IntPoint&); void pageTransitionViewportReady(); #endif -#if PLATFORM(QT) +#if USE(COORDINATED_GRAPHICS) void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&); #endif - #if PLATFORM(QT) || PLATFORM(EFL) void didChangeContentsSize(const WebCore::IntSize&); #endif @@ -937,9 +936,6 @@ private: // Popup Menu. void showPopupMenu(const WebCore::IntRect& rect, uint64_t textDirection, const Vector<WebPopupItem>& items, int32_t selectedIndex, const PlatformPopupMenuData&); void hidePopupMenu(); -#if PLATFORM(WIN) - void setPopupMenuSelectedIndex(int32_t); -#endif #if ENABLE(CONTEXT_MENUS) // Context Menu. @@ -959,13 +955,14 @@ private: // Spotlight. void searchWithSpotlight(const String&); + + void searchTheWeb(const String&); // Dictionary. void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&); #endif // Spelling and grammar. - int64_t spellDocumentTag(); #if USE(UNIFIED_TEXT_CHECKING) void checkTextOfParagraph(const String& text, uint64_t checkingTypes, Vector<WebCore::TextCheckingResult>& results); #endif @@ -977,6 +974,7 @@ private: void getGuessesForWord(const String& word, const String& context, Vector<String>& guesses); void learnWord(const String& word); void ignoreWord(const String& word); + void requestCheckingOfString(uint64_t requestID, const WebCore::TextCheckingRequestData&); void setFocus(bool focused); void takeFocus(uint32_t direction); @@ -1004,8 +1002,6 @@ private: void canAuthenticateAgainstProtectionSpaceInFrame(uint64_t frameID, const WebCore::ProtectionSpace&, bool& canAuthenticate); void didReceiveAuthenticationChallenge(uint64_t frameID, const WebCore::AuthenticationChallenge&, uint64_t challengeID); - void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&); - #if PLATFORM(MAC) void pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus); void setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, uint64_t complexTextInputState); @@ -1018,16 +1014,13 @@ private: #if PLATFORM(MAC) void substitutionsPanelIsShowing(bool&); -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 void showCorrectionPanel(int32_t panelType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings); void dismissCorrectionPanel(int32_t reason); void dismissCorrectionPanelSoon(int32_t reason, String& result); void recordAutocorrectionResponse(int32_t responseType, const String& replacedString, const String& replacementString); -#endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 #if USE(DICTATION_ALTERNATIVES) void showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext); - void dismissDictationAlternativeUI(); void removeDictationAlternatives(uint64_t dictationContext); void dictationAlternatives(uint64_t dictationContext, Vector<String>& result); #endif @@ -1043,10 +1036,6 @@ private: void updateBackingStoreDiscardableState(); -#if PLATFORM(WIN) - void scheduleChildWindowGeometryUpdate(const WindowGeometry&); -#endif - void setRenderTreeSize(uint64_t treeSize) { m_renderTreeSize = treeSize; } #if PLUGIN_ARCHITECTURE(X11) @@ -1057,13 +1046,20 @@ private: void processNextQueuedWheelEvent(); void sendWheelEvent(const WebWheelEvent&); +#if ENABLE(NETSCAPE_PLUGIN_API) + void findPlugin(const String& mimeType, uint32_t processType, const String& urlString, const String& frameURLString, const String& pageURLString, bool allowOnlyApplicationPlugins, uint64_t& pluginProcessToken, String& newMIMEType, uint32_t& pluginLoadPolicy, String& unavailabilityDescription); +#endif + PageClient* m_pageClient; WebLoaderClient m_loaderClient; WebPolicyClient m_policyClient; WebFormClient m_formClient; - WebResourceLoadClient m_resourceLoadClient; WebUIClient m_uiClient; +#if PLATFORM(EFL) + WebUIPopupMenuClient m_uiPopupMenuClient; +#endif WebFindClient m_findClient; + WebFindMatchesClient m_findMatchesClient; #if ENABLE(CONTEXT_MENUS) WebPageContextMenuClient m_contextMenuClient; #endif @@ -1092,16 +1088,16 @@ private: RefPtr<WebVibrationProxy> m_vibration; #endif - HashMap<uint64_t, RefPtr<VoidCallback> > m_voidCallbacks; - HashMap<uint64_t, RefPtr<DataCallback> > m_dataCallbacks; - HashMap<uint64_t, RefPtr<ImageCallback> > m_imageCallbacks; - HashMap<uint64_t, RefPtr<StringCallback> > m_stringCallbacks; + HashMap<uint64_t, RefPtr<VoidCallback>> m_voidCallbacks; + HashMap<uint64_t, RefPtr<DataCallback>> m_dataCallbacks; + HashMap<uint64_t, RefPtr<ImageCallback>> m_imageCallbacks; + HashMap<uint64_t, RefPtr<StringCallback>> m_stringCallbacks; HashSet<uint64_t> m_loadDependentStringCallbackIDs; - HashMap<uint64_t, RefPtr<ScriptValueCallback> > m_scriptValueCallbacks; - HashMap<uint64_t, RefPtr<ComputedPagesCallback> > m_computedPagesCallbacks; - HashMap<uint64_t, RefPtr<ValidateCommandCallback> > m_validateCommandCallbacks; + HashMap<uint64_t, RefPtr<ScriptValueCallback>> m_scriptValueCallbacks; + HashMap<uint64_t, RefPtr<ComputedPagesCallback>> m_computedPagesCallbacks; + HashMap<uint64_t, RefPtr<ValidateCommandCallback>> m_validateCommandCallbacks; #if PLATFORM(GTK) - HashMap<uint64_t, RefPtr<PrintFinishedCallback> > m_printFinishedCallbacks; + HashMap<uint64_t, RefPtr<PrintFinishedCallback>> m_printFinishedCallbacks; #endif HashSet<WebEditCommandProxy*> m_editCommandSet; @@ -1137,6 +1133,7 @@ private: WebFrameProxy::LoadState m_loadStateAtProcessExit; EditorState m_editorState; + bool m_temporarilyClosedComposition; // Editor state changed from hasComposition to !hasComposition, but that was only with shouldIgnoreCompositionSelectionChange yet. double m_textZoomFactor; double m_pageZoomFactor; @@ -1149,6 +1146,8 @@ private: bool m_drawsBackground; bool m_drawsTransparentBackground; + WebCore::Color m_underlayColor; + bool m_areMemoryCacheClientCallsEnabled; bool m_useFixedLayout; @@ -1173,7 +1172,8 @@ private: bool m_isInPrintingMode; bool m_isPerformingDOMPrintOperation; - bool m_inDecidePolicyForResponse; + bool m_inDecidePolicyForResponseSync; + const WebCore::ResourceRequest* m_decidePolicyForResponseRequest; bool m_syncMimeTypePolicyActionIsValid; WebCore::PolicyAction m_syncMimeTypePolicyAction; uint64_t m_syncMimeTypePolicyDownloadID; @@ -1188,7 +1188,7 @@ private: #endif Deque<NativeWebKeyboardEvent> m_keyEventQueue; Deque<NativeWebWheelEvent> m_wheelEventQueue; - Deque<OwnPtr<Vector<NativeWebWheelEvent> > > m_currentlyProcessedWheelEvents; + Deque<OwnPtr<Vector<NativeWebWheelEvent>>> m_currentlyProcessedWheelEvents; bool m_processingMouseMoveEvent; OwnPtr<NativeWebMouseEvent> m_nextMouseMoveEvent; @@ -1199,7 +1199,7 @@ private: Deque<QueuedTouchEvents> m_touchEventQueue; #endif #if ENABLE(INPUT_TYPE_COLOR) - RefPtr<WebColorChooserProxy> m_colorChooser; + RefPtr<WebColorPicker> m_colorPicker; RefPtr<WebColorPickerResultListenerProxy> m_colorPickerResultListener; #endif @@ -1219,8 +1219,6 @@ private: bool m_hasSpellDocumentTag; unsigned m_pendingLearnOrIgnoreWordMessageCount; - bool m_mainFrameHasCustomRepresentation; - #if ENABLE(DRAG_SUPPORT) WebCore::DragSession m_currentDragSession; #endif @@ -1238,6 +1236,11 @@ private: bool m_mainFrameIsPinnedToTopSide; bool m_mainFrameIsPinnedToBottomSide; + bool m_rubberBandsAtBottom; + bool m_rubberBandsAtTop; + + bool m_mainFrameInViewSourceMode; + unsigned m_pageCount; WebCore::IntRect m_visibleScrollerThumbRect; @@ -1249,18 +1252,34 @@ private: bool m_shouldSendEventsSynchronously; bool m_suppressVisibilityUpdates; - float m_minimumLayoutWidth; + WebCore::IntSize m_minimumLayoutSize; float m_mediaVolume; bool m_mayStartMediaWhenInWindow; + bool m_waitingForDidUpdateInWindowState; + +#if PLATFORM(MAC) + WebCore::Timer<WebPageProxy> m_exposedRectChangedTimer; + WebCore::FloatRect m_exposedRect; + WebCore::FloatRect m_lastSentExposedRect; + bool m_clipsToExposedRect; + bool m_lastSentClipsToExposedRect; +#endif + #if PLATFORM(QT) - WTF::HashSet<RefPtr<QtRefCountedNetworkRequestData> > m_applicationSchemeRequests; + WTF::HashSet<RefPtr<QtRefCountedNetworkRequestData>> m_applicationSchemeRequests; #endif #if ENABLE(PAGE_VISIBILITY_API) WebCore::PageVisibilityState m_visibilityState; #endif + +#if PLATFORM(MAC) + HashMap<String, String> m_temporaryPDFFiles; +#endif + + WebCore::ScrollPinningBehavior m_scrollPinningBehavior; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPageProxy.messages.in b/Source/WebKit2/UIProcess/WebPageProxy.messages.in index 5c89fae35..667bfa2c8 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebPageProxy.messages.in @@ -30,7 +30,7 @@ messages -> WebPageProxy { RunJavaScriptPrompt(uint64_t frameID, WTF::String message, WTF::String defaultValue) -> (WTF::String result) ShouldInterruptJavaScript() -> (bool shouldInterupt) MouseDidMoveOverElement(WebKit::WebHitTestResult::Data hitTestResultData, uint32_t modifiers, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - UnavailablePluginButtonClicked(uint32_t pluginUnavailabilityReason, WTF::String mimeType, WTF::String url, WTF::String pluginsPageURL) + UnavailablePluginButtonClicked(uint32_t pluginUnavailabilityReason, WTF::String mimeType, WTF::String pluginURLString, WTF::String pluginspageAttributeURLString, WTF::String frameURLString, WTF::String pageURLString) DidChangeViewportProperties(WebCore::ViewportAttributes attributes) DidReceiveEvent(uint32_t type, bool handled) StopResponsivenessTimer() @@ -65,8 +65,8 @@ messages -> WebPageProxy { DidChangeScrollbarsForMainFrame(bool hasHorizontalScrollbar, bool hasVerticalScrollbar) DidChangeScrollOffsetPinningForMainFrame(bool pinnedToLeftSide, bool pinnedToRightSide, bool pinnedToTopSide, bool pinnedToBottomSide) DidChangePageCount(unsigned pageCount); - DidFailToInitializePlugin(WTF::String mimeType) - DidBlockInsecurePluginVersion(WTF::String mimeType, WTF::String urlString) + DidFailToInitializePlugin(WTF::String mimeType, WTF::String frameURLString, WTF::String pageURLString) + DidBlockInsecurePluginVersion(WTF::String mimeType, WTF::String pluginURLString, WTF::String frameURLString, WTF::String pageURLString, bool replacementObscured) SetCanShortCircuitHorizontalWheelEvents(bool canShortCircuitHorizontalWheelEvents) #if PLATFORM(EFL) @@ -77,8 +77,10 @@ messages -> WebPageProxy { PageDidRequestScroll(WebCore::IntPoint point) PageTransitionViewportReady() #endif -#if PLATFORM(QT) +#if USE(COORDINATED_GRAPHICS) DidFindZoomableArea(WebCore::IntPoint target, WebCore::IntRect area) +#endif +#if PLATFORM(QT) AuthenticationRequiredRequest(WTF::String hostname, WTF::String realm, WTF::String prefilledUsername) -> (WTF::String username, WTF::String password) CertificateVerificationRequest(WTF::String hostname) -> (bool ignoreErrors) ProxyAuthenticationRequiredRequest(WTF::String hostname, uint16_t port, WTF::String prefilledUsername) -> (WTF::String username, WTF::String password) @@ -99,19 +101,11 @@ messages -> WebPageProxy { #endif # Policy messages - DecidePolicyForResponse(uint64_t frameID, WebCore::ResourceResponse response, WebCore::ResourceRequest request, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) -> (bool receivedPolicyAction, uint64_t policyAction, uint64_t downloadID) Variadic + DecidePolicyForResponseSync(uint64_t frameID, WebCore::ResourceResponse response, WebCore::ResourceRequest request, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) -> (bool receivedPolicyAction, uint64_t policyAction, uint64_t downloadID) Variadic DecidePolicyForNavigationAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, WebCore::ResourceRequest request, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) -> (bool receivedPolicyAction, uint64_t policyAction, uint64_t downloadID) Variadic DecidePolicyForNewWindowAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, WebCore::ResourceRequest request, WTF::String frameName, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic UnableToImplementPolicy(uint64_t frameID, WebCore::ResourceError error, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - # Intent messages -#if ENABLE(WEB_INTENTS) - DidReceiveIntentForFrame(uint64_t frameID, WebKit::IntentData intent, WebKit::InjectedBundleUserMessageEncoder userData) Variadic -#endif -#if ENABLE(WEB_INTENTS_TAG) - RegisterIntentServiceForFrame(uint64_t frameID, WebKit::IntentServiceInfo serviceInfo, WebKit::InjectedBundleUserMessageEncoder userData) Variadic -#endif - # Progress messages DidChangeProgress(double value) DidFinishProgress() @@ -119,12 +113,10 @@ messages -> WebPageProxy { # Frame lifetime messages DidCreateMainFrame(uint64_t frameID) - DidCreateSubframe(uint64_t frameID, uint64_t parentFrameID) - DidSaveFrameToPageCache(uint64_t frameID); - DidRestoreFrameFromPageCache(uint64_t frameID, uint64_t parentFrameID); + DidCreateSubframe(uint64_t frameID) # Frame load messages - DidCommitLoadForFrame(uint64_t frameID, WTF::String mimeType, bool hasCustomRepresentation, WebKit::PlatformCertificateInfo certificateInfo, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + DidCommitLoadForFrame(uint64_t frameID, WTF::String mimeType, uint32_t loadType, WebKit::PlatformCertificateInfo certificateInfo, WebKit::InjectedBundleUserMessageEncoder userData) Variadic DidFailLoadForFrame(uint64_t frameID, WebCore::ResourceError error, WebKit::InjectedBundleUserMessageEncoder userData) Variadic DidFailProvisionalLoadForFrame(uint64_t frameID, WebCore::ResourceError error, WebKit::InjectedBundleUserMessageEncoder userData) Variadic DidFinishDocumentLoadForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic @@ -144,23 +136,12 @@ messages -> WebPageProxy { FrameDidBecomeFrameSet(uint64_t frameID, bool value) - # Resource load messages - DidInitiateLoadForResource(uint64_t frameID, uint64_t resourceIdentifier, WebCore::ResourceRequest request, bool pageIsProvisionallyLoading) - DidSendRequestForResource(uint64_t frameID, uint64_t resourceIdentifier, WebCore::ResourceRequest request, WebCore::ResourceResponse redirectResponse) - DidReceiveResponseForResource(uint64_t frameID, uint64_t resourceIdentifier, WebCore::ResourceResponse response) - DidReceiveContentLengthForResource(uint64_t frameID, uint64_t resourceIdentifier, uint64_t contentLength) - DidFinishLoadForResource(uint64_t frameID, uint64_t resourceIdentifier) - DidFailLoadForResource(uint64_t frameID, uint64_t resourceIdentifier, WebCore::ResourceError error) #if PLATFORM(QT) ResolveApplicationSchemeRequest(WebKit::QtNetworkRequestData request) #endif - - # Custom representations - DidFinishLoadingDataForCustomRepresentation(WTF::String suggestedFilename, CoreIPC::DataReference data) - # Forms messages - WillSubmitForm(uint64_t frameID, uint64_t sourceFrameID, WebKit::StringPairVector textFieldValues, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + WillSubmitForm(uint64_t frameID, uint64_t sourceFrameID, WTF::Vector<std::pair<WTF::String, WTF::String>> textFieldValues, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic # Callback messages VoidCallback(uint64_t callbackID) @@ -175,6 +156,7 @@ messages -> WebPageProxy { #endif PageScaleFactorDidChange(double scaleFactor) + PageZoomFactorDidChange(double zoomFactor) #if PLATFORM(GTK) # Support for GTK+ platform keybindings @@ -182,6 +164,8 @@ messages -> WebPageProxy { # Support for connecting the Accessibility worlds of the UI and the Web processes BindAccessibilityTree(WTF::String plugID) + + SetInputMethodState(bool enabled); #endif # BackForward messages @@ -202,9 +186,6 @@ messages -> WebPageProxy { # Editor notifications EditorStateChanged(WebKit::EditorState editorState) -#if PLATFORM(WIN) - DidChangeCompositionSelection(bool hasChanged) -#endif #if PLATFORM(QT) WillSetInputMethodState() #endif @@ -213,16 +194,12 @@ messages -> WebPageProxy { SetFindIndicator(WebCore::FloatRect selectionRect, Vector<WebCore::FloatRect> textRects, float contentImageScaleFactor, WebKit::ShareableBitmap::Handle contentImageHandle, bool fadeOut, bool animate) DidFindString(WTF::String string, uint32_t matchCount) DidFailToFindString(WTF::String string) -#if PLATFORM(WIN) - DidInstallOrUninstallPageOverlay(bool didInstall) -#endif + DidFindStringMatches(WTF::String string, Vector<Vector<WebCore::IntRect>> matches, int32_t firstIndexAfterSelection) + DidGetImageForFindMatch(WebKit::ShareableBitmap::Handle contentImageHandle, uint32_t matchIndex) # PopupMenu messages ShowPopupMenu(WebCore::IntRect rect, uint64_t textDirection, Vector<WebKit::WebPopupItem> items, int32_t selectedIndex, WebKit::PlatformPopupMenuData data) HidePopupMenu() -#if PLATFORM(WIN) - SetPopupMenuSelectedIndex(int32_t selectedIndex) -#endif #if ENABLE(CONTEXT_MENUS) # ContextMenu messages @@ -234,7 +211,7 @@ messages -> WebPageProxy { DidReceiveAuthenticationChallenge(uint64_t frameID, WebCore::AuthenticationChallenge challenge, uint64_t challengeID) # Database messages - ExceededDatabaseQuota(uint64_t frameID, WTF::String originIdentifier, WTF::String databaseName, WTF::String databaseDisplayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage) -> (uint64_t newQuota) + ExceededDatabaseQuota(uint64_t frameID, WTF::String originIdentifier, WTF::String databaseName, WTF::String databaseDisplayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage) -> (uint64_t newQuota) Delayed # Geolocation messages RequestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, WTF::String originIdentifier) @@ -242,6 +219,9 @@ messages -> WebPageProxy { # Notification messages RequestNotificationPermission(uint64_t requestID, WTF::String originIdentifier) ShowNotification(WTF::String title, WTF::String body, WTF::String iconURL, WTF::String tag, WTF::String lang, WTF::String dir, WTF::String originIdentifier, uint64_t notificationID) + CancelNotification(uint64_t notificationID) + ClearNotifications(Vector<uint64_t> notificationIDs) + DidDestroyNotification(uint64_t notificationID) # Spelling and grammar messages #if USE(UNIFIED_TEXT_CHECKING) @@ -255,6 +235,7 @@ messages -> WebPageProxy { GetGuessesForWord(WTF::String word, WTF::String context) -> (Vector<WTF::String> guesses) LearnWord(WTF::String word); IgnoreWord(WTF::String word); + RequestCheckingOfString(uint64_t requestID, WebCore::TextCheckingRequestData request) # Drag and drop messages #if ENABLE(DRAG_SUPPORT) @@ -264,9 +245,6 @@ messages -> WebPageProxy { SetDragImage(WebCore::IntPoint clientPosition, WebKit::ShareableBitmap::Handle dragImage, bool linkDrag) SetPromisedData(WTF::String pasteboardName, WebKit::SharedMemory::Handle imageHandle, uint64_t imageSize, WTF::String filename, WTF::String extension, WTF::String title, WTF::String url, WTF::String visibleURL, WebKit::SharedMemory::Handle archiveHandle, uint64_t archiveSize) #endif -#if PLATFORM(WIN) && ENABLE(DRAG_SUPPORT) - StartDragDrop(WebCore::IntPoint imagePoint, WebCore::IntPoint dragPoint, uint64_t okEffect, HashMap<UINT,Vector<String> > dataMap, uint64_t fileSize, String pathname, WebKit::SharedMemory::Handle fileContentHandle, WebCore::IntSize dragImageSize, WebKit::SharedMemory::Handle dragImage, bool linkDrag) -#endif #if (PLATFORM(QT) || PLATFORM(GTK)) && ENABLE(DRAG_SUPPORT) StartDrag(WebCore::DragData dragData, WebKit::ShareableBitmap::Handle dragImage) #endif @@ -295,12 +273,14 @@ messages -> WebPageProxy { # Spotlight SearchWithSpotlight(WTF::String string) + + SearchTheWeb(WTF::String string) #endif #if PLATFORM(MAC) SubstitutionsPanelIsShowing() -> (bool isShowing) #endif -#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 +#if PLATFORM(MAC) # Autocorrection messages ShowCorrectionPanel(int32_t panelType, WebCore::FloatRect boundingBoxOfReplacedString, String replacedString, String replacementString, Vector<String> alternativeReplacementStrings) DismissCorrectionPanel(int32_t reason) @@ -310,19 +290,10 @@ messages -> WebPageProxy { #if USE(DICTATION_ALTERNATIVES) ShowDictationAlternativeUI(WebCore::FloatRect boundingBoxOfDictatedText, uint64_t dictationContext) - DismissDictationAlternativeUI() RemoveDictationAlternatives(uint64_t dictationContext) DictationAlternatives(uint64_t dictationContext) -> (Vector<String> alternatives) #endif -#if PLATFORM(WIN) - # Windows 7 Gesture Messages - SetGestureReachedScrollingLimit(bool limitReached) - - # Miscellaneous Windows messages - ScheduleChildWindowGeometryUpdate(WebKit::WindowGeometry geometry) -#endif - #if PLUGIN_ARCHITECTURE(X11) # X11 windowed plugin messages CreatePluginContainer() -> (uint64_t windowID) @@ -339,4 +310,17 @@ messages -> WebPageProxy { #endif SavePDFToFileInDownloadsFolder(WTF::String suggestedFilename, WTF::String originatingURLString, CoreIPC::DataReference data) + +#if PLATFORM(MAC) + SavePDFToTemporaryFolderAndOpenWithNativeApplication(WTF::String suggestedFilename, WTF::String originatingURLString, CoreIPC::DataReference data, WTF::String pdfUUID) + OpenPDFFromTemporaryFolderWithNativeApplication(WTF::String pdfUUID) +#endif + +#if ENABLE(NETSCAPE_PLUGIN_API) + FindPlugin(WTF::String mimeType, uint32_t processType, WTF::String urlString, WTF::String frameURLString, WTF::String pageURLString, bool allowOnlyApplicationPlugins) -> (uint64_t pluginProcessToken, WTF::String newMIMEType, uint32_t pluginLoadPolicy, WTF::String unavailabilityDescription) +#endif + + DidUpdateInWindowState() + + DidSaveToPageCache() } diff --git a/Source/WebKit2/UIProcess/WebPopupMenuProxy.h b/Source/WebKit2/UIProcess/WebPopupMenuProxy.h index 0d7788dc4..1caf8dd64 100644 --- a/Source/WebKit2/UIProcess/WebPopupMenuProxy.h +++ b/Source/WebKit2/UIProcess/WebPopupMenuProxy.h @@ -66,8 +66,10 @@ public: { } +#if !PLATFORM(EFL) virtual void showPopupMenu(const WebCore::IntRect& rect, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, const PlatformPopupMenuData&, int32_t selectedIndex) = 0; virtual void hidePopupMenu() = 0; +#endif void invalidate() { m_client = 0; } diff --git a/Source/WebKit2/UIProcess/WebPreferences.cpp b/Source/WebKit2/UIProcess/WebPreferences.cpp index bbc2380d1..4768f28bf 100644 --- a/Source/WebKit2/UIProcess/WebPreferences.cpp +++ b/Source/WebKit2/UIProcess/WebPreferences.cpp @@ -26,10 +26,16 @@ #include "config.h" #include "WebPreferences.h" +#include "WebContext.h" #include "WebPageGroup.h" +#include <wtf/ThreadingPrimitives.h> namespace WebKit { +// FIXME: Manipulating this variable is not thread safe. +// Instead of tracking private browsing state as a boolean preference, we should let the client provide storage sessions explicitly. +static unsigned privateBrowsingPageGroupCount; + WebPreferences::WebPreferences() { platformInitializeStore(); @@ -42,24 +48,39 @@ WebPreferences::WebPreferences(const String& identifier) } WebPreferences::WebPreferences(const WebPreferences& other) - : APIObject() - , m_store(other.m_store) + : m_store(other.m_store) { platformInitializeStore(); } WebPreferences::~WebPreferences() { + ASSERT(m_pageGroups.isEmpty()); } void WebPreferences::addPageGroup(WebPageGroup* pageGroup) { - m_pageGroups.add(pageGroup); + bool didAddPageGroup = m_pageGroups.add(pageGroup).isNewEntry; + if (didAddPageGroup && privateBrowsingEnabled()) { + if (!privateBrowsingPageGroupCount) + WebContext::willStartUsingPrivateBrowsing(); + ++privateBrowsingPageGroupCount; + } } void WebPreferences::removePageGroup(WebPageGroup* pageGroup) { - m_pageGroups.remove(pageGroup); + HashSet<WebPageGroup*>::iterator iter = m_pageGroups.find(pageGroup); + if (iter == m_pageGroups.end()) + return; + + m_pageGroups.remove(iter); + + if (privateBrowsingEnabled()) { + --privateBrowsingPageGroupCount; + if (!privateBrowsingPageGroupCount) + WebContext::willStopUsingPrivateBrowsing(); + } } void WebPreferences::update() @@ -76,6 +97,11 @@ void WebPreferences::updateStringValueForKey(const String& key, const String& va void WebPreferences::updateBoolValueForKey(const String& key, bool value) { + if (key == WebPreferencesKey::privateBrowsingEnabledKey()) { + updatePrivateBrowsingValue(value); + return; + } + platformUpdateBoolValueForKey(key, value); update(); // FIXME: Only send over the changed key and value. } @@ -98,6 +124,30 @@ void WebPreferences::updateFloatValueForKey(const String& key, float value) update(); // FIXME: Only send over the changed key and value. } +void WebPreferences::updatePrivateBrowsingValue(bool value) +{ + platformUpdateBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey(), value); + + unsigned pageGroupsChanged = m_pageGroups.size(); + if (!pageGroupsChanged) + return; + + if (value) { + if (!privateBrowsingPageGroupCount) + WebContext::willStartUsingPrivateBrowsing(); + privateBrowsingPageGroupCount += pageGroupsChanged; + } + + update(); // FIXME: Only send over the changed key and value. + + if (!value) { + ASSERT(privateBrowsingPageGroupCount >= pageGroupsChanged); + privateBrowsingPageGroupCount -= pageGroupsChanged; + if (!privateBrowsingPageGroupCount) + WebContext::willStopUsingPrivateBrowsing(); + } +} + #define DEFINE_PREFERENCE_GETTER_AND_SETTERS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) \ void WebPreferences::set##KeyUpper(const Type& value) \ { \ @@ -116,4 +166,9 @@ FOR_EACH_WEBKIT_PREFERENCE(DEFINE_PREFERENCE_GETTER_AND_SETTERS) #undef DEFINE_PREFERENCE_GETTER_AND_SETTERS +bool WebPreferences::anyPageGroupsAreUsingPrivateBrowsing() +{ + return privateBrowsingPageGroupCount; +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPreferences.h b/Source/WebKit2/UIProcess/WebPreferences.h index 50bc0258b..26d23fbb1 100644 --- a/Source/WebKit2/UIProcess/WebPreferences.h +++ b/Source/WebKit2/UIProcess/WebPreferences.h @@ -41,10 +41,8 @@ namespace WebKit { class WebPageGroup; -class WebPreferences : public APIObject { +class WebPreferences : public TypedAPIObject<APIObject::TypePreferences> { public: - static const Type APIType = TypePreferences; - static PassRefPtr<WebPreferences> create() { return adoptRef(new WebPreferences); @@ -77,6 +75,8 @@ public: // Exposed for WebKitTestRunner use only. void forceUpdate() { update(); } + static bool anyPageGroupsAreUsingPrivateBrowsing(); + private: WebPreferences(); explicit WebPreferences(const String&); @@ -84,8 +84,6 @@ private: void platformInitializeStore(); - virtual Type type() const { return APIType; } - void update(); void updateStringValueForKey(const String& key, const String& value); @@ -99,6 +97,8 @@ private: void platformUpdateDoubleValueForKey(const String& key, double value); void platformUpdateFloatValueForKey(const String& key, float value); + void updatePrivateBrowsingValue(bool value); + HashSet<WebPageGroup*> m_pageGroups; WebPreferencesStore m_store; String m_identifier; diff --git a/Source/WebKit2/UIProcess/WebProcessProxy.cpp b/Source/WebKit2/UIProcess/WebProcessProxy.cpp index 6ca003ab3..88659844a 100644 --- a/Source/WebKit2/UIProcess/WebProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/WebProcessProxy.cpp @@ -27,6 +27,7 @@ #include "WebProcessProxy.h" #include "DataReference.h" +#include "DownloadProxyMap.h" #include "PluginInfoStore.h" #include "PluginProcessManager.h" #include "TextChecker.h" @@ -40,15 +41,12 @@ #include "WebProcessMessages.h" #include "WebProcessProxyMessages.h" #include <WebCore/KURL.h> +#include <WebCore/SuddenTermination.h> #include <stdio.h> #include <wtf/MainThread.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> -#if ENABLE(NETWORK_PROCESS) -#include "NetworkProcessManager.h" -#endif - #if PLATFORM(MAC) #include "SimplePDFPlugin.h" #if ENABLE(PDFKIT_PLUGIN) @@ -56,33 +54,33 @@ #endif #endif +#if ENABLE(CUSTOM_PROTOCOLS) +#include "CustomProtocolManagerProxyMessages.h" +#endif + +#if USE(SECURITY_FRAMEWORK) +#include "SecItemShimProxy.h" +#endif + using namespace WebCore; -using namespace std; #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection()) #define MESSAGE_CHECK_URL(url) MESSAGE_CHECK_BASE(checkURLReceivedFromWebProcess(url), connection()) namespace WebKit { -template<typename HashMap> -static inline bool isGoodKey(const typename HashMap::KeyType& key) -{ - return key != HashTraits<typename HashMap::KeyType>::emptyValue() && !HashTraits<typename HashMap::KeyType>::isDeletedValue(key); -} - static uint64_t generatePageID() { - static uint64_t uniquePageID = 1; - return uniquePageID++; + static uint64_t uniquePageID; + return ++uniquePageID; } -#if ENABLE(NETSCAPE_PLUGIN_API) -static WorkQueue& pluginWorkQueue() +static WebProcessProxy::WebPageProxyMap& globalPageMap() { - DEFINE_STATIC_LOCAL(WorkQueue, queue, ("com.apple.CoreIPC.PluginQueue")); - return queue; + ASSERT(isMainThread()); + DEFINE_STATIC_LOCAL(WebProcessProxy::WebPageProxyMap, pageMap, ()); + return pageMap; } -#endif // ENABLE(NETSCAPE_PLUGIN_API) PassRefPtr<WebProcessProxy> WebProcessProxy::create(PassRefPtr<WebContext> context) { @@ -96,121 +94,76 @@ WebProcessProxy::WebProcessProxy(PassRefPtr<WebContext> context) #if ENABLE(CUSTOM_PROTOCOLS) , m_customProtocolManagerProxy(this) #endif +#if PLATFORM(MAC) + , m_processSuppressionEnabled(false) +#endif { connect(); } WebProcessProxy::~WebProcessProxy() { - if (m_connection) - m_connection->invalidate(); - if (m_webConnection) m_webConnection->invalidate(); +} - for (size_t i = 0; i < m_pendingMessages.size(); ++i) - m_pendingMessages[i].first.releaseArguments(); - - if (m_processLauncher) { - m_processLauncher->invalidate(); - m_processLauncher = 0; - } +void WebProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +{ + launchOptions.processType = ProcessLauncher::WebProcess; + platformGetLaunchOptions(launchOptions); } -WebProcessProxy* WebProcessProxy::fromConnection(CoreIPC::Connection* connection) +void WebProcessProxy::connectionWillOpen(CoreIPC::Connection* connection) { - ASSERT(connection); + ASSERT(this->connection() == connection); + +#if USE(SECURITY_FRAMEWORK) + SecItemShimProxy::shared().initializeConnection(connection); +#endif - WebProcessProxy* webProcessProxy = static_cast<WebProcessProxy*>(connection->client()); - ASSERT(webProcessProxy->connection() == connection); + for (WebPageProxyMap::iterator it = m_pageMap.begin(), end = m_pageMap.end(); it != end; ++it) + it->value->connectionWillOpen(connection); - return webProcessProxy; + m_context->processWillOpenConnection(this); } -void WebProcessProxy::connect() +void WebProcessProxy::connectionWillClose(CoreIPC::Connection* connection) { - ASSERT(!m_processLauncher); + ASSERT(this->connection() == connection); - ProcessLauncher::LaunchOptions launchOptions; - launchOptions.processType = ProcessLauncher::WebProcess; - platformConnect(launchOptions); - - m_processLauncher = ProcessLauncher::create(this, launchOptions); + for (WebPageProxyMap::iterator it = m_pageMap.begin(), end = m_pageMap.end(); it != end; ++it) + it->value->connectionWillClose(connection); + + m_context->processWillCloseConnection(this); } void WebProcessProxy::disconnect() { - if (m_connection) { - m_connection->removeQueueClient(this); - m_connection->invalidate(); - m_connection = nullptr; - } + clearConnection(); if (m_webConnection) { m_webConnection->invalidate(); m_webConnection = nullptr; } - m_responsivenessTimer.stop(); + m_responsivenessTimer.invalidate(); - Vector<RefPtr<WebFrameProxy> > frames; + Vector<RefPtr<WebFrameProxy>> frames; copyValuesToVector(m_frameMap, frames); for (size_t i = 0, size = frames.size(); i < size; ++i) frames[i]->disconnect(); m_frameMap.clear(); - m_context->disconnectProcess(this); -} - -bool WebProcessProxy::sendMessage(CoreIPC::MessageID messageID, PassOwnPtr<CoreIPC::MessageEncoder> encoder, unsigned messageSendFlags) -{ - // If we're waiting for the web process to launch, we need to stash away the messages so we can send them once we have - // a CoreIPC connection. - if (isLaunching()) { - m_pendingMessages.append(make_pair(CoreIPC::Connection::OutgoingMessage(messageID, encoder), messageSendFlags)); - return true; - } - - // If the web process has exited, m_connection will be null here. - if (!m_connection) - return false; - - return connection()->sendMessage(messageID, encoder, messageSendFlags); -} - -bool WebProcessProxy::isLaunching() const -{ - if (m_processLauncher) - return m_processLauncher->isLaunching(); - - return false; -} - -void WebProcessProxy::terminate() -{ - if (m_processLauncher) - m_processLauncher->terminateProcess(); -} + if (m_downloadProxyMap) + m_downloadProxyMap->processDidClose(); -void WebProcessProxy::addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver* messageReceiver) -{ - m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver); -} - -void WebProcessProxy::addMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID, CoreIPC::MessageReceiver* messageReceiver) -{ - m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver); -} - -void WebProcessProxy::removeMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID) -{ - m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID); + m_context->disconnectProcess(this); } -WebPageProxy* WebProcessProxy::webPage(uint64_t pageID) const +WebPageProxy* WebProcessProxy::webPage(uint64_t pageID) { - return m_pageMap.get(pageID); + return globalPageMap().get(pageID); } PassRefPtr<WebPageProxy> WebProcessProxy::createWebPage(PageClient* pageClient, WebContext*, WebPageGroup* pageGroup) @@ -218,17 +171,41 @@ PassRefPtr<WebPageProxy> WebProcessProxy::createWebPage(PageClient* pageClient, uint64_t pageID = generatePageID(); RefPtr<WebPageProxy> webPage = WebPageProxy::create(pageClient, this, pageGroup, pageID); m_pageMap.set(pageID, webPage.get()); + globalPageMap().set(pageID, webPage.get()); +#if PLATFORM(MAC) + if (pageIsProcessSuppressible(webPage.get())) + m_processSuppressiblePages.add(pageID); + updateProcessSuppressionState(); +#endif return webPage.release(); } void WebProcessProxy::addExistingWebPage(WebPageProxy* webPage, uint64_t pageID) { m_pageMap.set(pageID, webPage); + globalPageMap().set(pageID, webPage); +#if PLATFORM(MAC) + if (pageIsProcessSuppressible(webPage)) + m_processSuppressiblePages.add(pageID); + updateProcessSuppressionState(); +#endif } void WebProcessProxy::removeWebPage(uint64_t pageID) { m_pageMap.remove(pageID); + globalPageMap().remove(pageID); +#if PLATFORM(MAC) + m_processSuppressiblePages.remove(pageID); + updateProcessSuppressionState(); +#endif + + // If this was the last WebPage open in that web process, and we have no other reason to keep it alive, let it go. + // We only allow this when using a network process, as otherwise the WebProcess needs to preserve its session state. + if (m_context->usesNetworkProcess() && canTerminateChildProcess()) { + abortProcessLaunchIfNeeded(); + disconnect(); + } } Vector<WebPageProxy*> WebProcessProxy::pages() const @@ -238,19 +215,9 @@ Vector<WebPageProxy*> WebProcessProxy::pages() const return result; } -#if ENABLE(WEB_INTENTS) -void WebProcessProxy::removeMessagePortChannel(uint64_t channelID) -{ - if (!isValid()) - return; - - send(Messages::WebProcess::RemoveMessagePortChannel(channelID), /* destinationID */ 0); -} -#endif - WebBackForwardListItem* WebProcessProxy::webBackForwardItem(uint64_t itemID) const { - return m_backForwardListItemMap.get(itemID).get(); + return m_backForwardListItemMap.get(itemID); } void WebProcessProxy::registerNewWebBackForwardListItem(WebBackForwardListItem* item) @@ -342,73 +309,31 @@ void WebProcessProxy::addBackForwardItem(uint64_t itemID, const String& original } #if ENABLE(NETSCAPE_PLUGIN_API) -void WebProcessProxy::sendDidGetPlugins(uint64_t requestID, PassOwnPtr<Vector<PluginInfo> > pluginInfos) +void WebProcessProxy::getPlugins(bool refresh, Vector<PluginInfo>& plugins) { - ASSERT(isMainThread()); + if (refresh) + m_context->pluginInfoStore().refresh(); - OwnPtr<Vector<PluginInfo> > plugins(pluginInfos); + Vector<PluginModuleInfo> pluginModules = m_context->pluginInfoStore().plugins(); + for (size_t i = 0; i < pluginModules.size(); ++i) + plugins.append(pluginModules[i].info); #if PLATFORM(MAC) // Add built-in PDF last, so that it's not used when a real plug-in is installed. - // NOTE: This has to be done on the main thread as it calls localizedString(). if (!m_context->omitPDFSupport()) { #if ENABLE(PDFKIT_PLUGIN) - plugins->append(PDFPlugin::pluginInfo()); + plugins.append(PDFPlugin::pluginInfo()); #endif - plugins->append(SimplePDFPlugin::pluginInfo()); + plugins.append(SimplePDFPlugin::pluginInfo()); } #endif - - send(Messages::WebProcess::DidGetPlugins(requestID, *plugins), 0); -} - -void WebProcessProxy::handleGetPlugins(uint64_t requestID, bool refresh) -{ - if (refresh) - m_context->pluginInfoStore().refresh(); - - OwnPtr<Vector<PluginInfo> > pluginInfos = adoptPtr(new Vector<PluginInfo>); - - { - Vector<PluginModuleInfo> plugins = m_context->pluginInfoStore().plugins(); - for (size_t i = 0; i < plugins.size(); ++i) - pluginInfos->append(plugins[i].info); - } - - // NOTE: We have to pass the PluginInfo vector to the secondary thread via a pointer as otherwise - // we'd end up with a deref() race on all the WTF::Strings it contains. - RunLoop::main()->dispatch(bind(&WebProcessProxy::sendDidGetPlugins, this, requestID, pluginInfos.release())); -} - -void WebProcessProxy::getPlugins(CoreIPC::Connection*, uint64_t requestID, bool refresh) -{ - pluginWorkQueue().dispatch(bind(&WebProcessProxy::handleGetPlugins, this, requestID, refresh)); -} - -void WebProcessProxy::getPluginPath(const String& mimeType, const String& urlString, String& pluginPath, uint32_t& pluginLoadPolicy) -{ - MESSAGE_CHECK_URL(urlString); - - String newMimeType = mimeType.lower(); - - pluginLoadPolicy = PluginModuleLoadNormally; - PluginModuleInfo plugin = m_context->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString)); - if (!plugin.path) - return; - - pluginLoadPolicy = PluginInfoStore::policyForPlugin(plugin); - if (pluginLoadPolicy != PluginModuleLoadNormally) - return; - - pluginPath = plugin.path; } #endif // ENABLE(NETSCAPE_PLUGIN_API) #if ENABLE(PLUGIN_PROCESS) - -void WebProcessProxy::getPluginProcessConnection(const String& pluginPath, uint32_t processType, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) +void WebProcessProxy::getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) { - PluginProcessManager::shared().getPluginProcessConnection(m_context->pluginInfoStore(), pluginPath, static_cast<PluginProcess::Type>(processType), reply); + PluginProcessManager::shared().getPluginProcessConnection(pluginProcessToken, reply); } #elif ENABLE(NETSCAPE_PLUGIN_API) @@ -435,69 +360,40 @@ void WebProcessProxy::getSharedWorkerProcessConnection(const String& /* url */, #if ENABLE(NETWORK_PROCESS) void WebProcessProxy::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) { - NetworkProcessManager::shared().getNetworkProcessConnection(reply); + m_context->getNetworkProcessConnection(reply); } #endif // ENABLE(NETWORK_PROCESS) -void WebProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) { - if (m_messageReceiverMap.dispatchMessage(connection, messageID, decoder)) - return; - - if (m_context->dispatchMessage(connection, messageID, decoder)) + if (dispatchMessage(connection, decoder)) return; - if (messageID.is<CoreIPC::MessageClassWebProcessProxy>()) { - didReceiveWebProcessProxyMessage(connection, messageID, decoder); + if (m_context->dispatchMessage(connection, decoder)) return; - } -#if ENABLE(CUSTOM_PROTOCOLS) - if (messageID.is<CoreIPC::MessageClassCustomProtocolManagerProxy>()) { - m_customProtocolManagerProxy.didReceiveMessage(connection, messageID, decoder); + if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) { + didReceiveWebProcessProxyMessage(connection, decoder); return; } -#endif - uint64_t pageID = decoder.destinationID(); - if (!pageID) - return; - - WebPageProxy* pageProxy = webPage(pageID); - if (!pageProxy) - return; - - pageProxy->didReceiveMessage(connection, messageID, decoder); + // FIXME: Add unhandled message logging. } -void WebProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) +void WebProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) { - if (m_messageReceiverMap.dispatchSyncMessage(connection, messageID, decoder, replyEncoder)) + if (dispatchSyncMessage(connection, decoder, replyEncoder)) return; - if (m_context->dispatchSyncMessage(connection, messageID, decoder, replyEncoder)) + if (m_context->dispatchSyncMessage(connection, decoder, replyEncoder)) return; - if (messageID.is<CoreIPC::MessageClassWebProcessProxy>()) { - didReceiveSyncWebProcessProxyMessage(connection, messageID, decoder, replyEncoder); + if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) { + didReceiveSyncWebProcessProxyMessage(connection, decoder, replyEncoder); return; } - uint64_t pageID = decoder.destinationID(); - if (!pageID) - return; - - WebPageProxy* pageProxy = webPage(pageID); - if (!pageProxy) - return; - - pageProxy->didReceiveSyncMessage(connection, messageID, decoder, replyEncoder); -} - -void WebProcessProxy::didReceiveMessageOnConnectionWorkQueue(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder, bool& didHandleMessage) -{ - if (messageID.is<CoreIPC::MessageClassWebProcessProxy>()) - didReceiveWebProcessProxyMessageOnConnectionWorkQueue(connection, messageID, decoder, didHandleMessage); + // FIXME: Add unhandled message logging. } void WebProcessProxy::didClose(CoreIPC::Connection*) @@ -508,7 +404,7 @@ void WebProcessProxy::didClose(CoreIPC::Connection*) webConnection()->didClose(); - Vector<RefPtr<WebPageProxy> > pages; + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); disconnect(); @@ -522,7 +418,9 @@ void WebProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection* connection, { WTFLogAlways("Received an invalid message \"%s.%s\" from the web process.\n", messageReceiverName.toString().data(), messageName.toString().data()); - // Terminate the WebProcesses. + WebContext::didReceiveInvalidMessage(messageReceiverName, messageName); + + // Terminate the WebProcess. terminate(); // Since we've invalidated the connection we'll never get a CoreIPC::Connection::Client::didClose @@ -532,7 +430,7 @@ void WebProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection* connection, void WebProcessProxy::didBecomeUnresponsive(ResponsivenessTimer*) { - Vector<RefPtr<WebPageProxy> > pages; + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->processDidBecomeUnresponsive(); @@ -540,7 +438,7 @@ void WebProcessProxy::didBecomeUnresponsive(ResponsivenessTimer*) void WebProcessProxy::interactionOccurredWhileUnresponsive(ResponsivenessTimer*) { - Vector<RefPtr<WebPageProxy> > pages; + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->interactionOccurredWhileProcessUnresponsive(); @@ -548,58 +446,36 @@ void WebProcessProxy::interactionOccurredWhileUnresponsive(ResponsivenessTimer*) void WebProcessProxy::didBecomeResponsive(ResponsivenessTimer*) { - Vector<RefPtr<WebPageProxy> > pages; + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->processDidBecomeResponsive(); } -void WebProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier connectionIdentifier) -{ - didFinishLaunching(connectionIdentifier); -} - -void WebProcessProxy::didFinishLaunching(CoreIPC::Connection::Identifier connectionIdentifier) +void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC::Connection::Identifier connectionIdentifier) { - ASSERT(!m_connection); - - m_connection = CoreIPC::Connection::createServerConnection(connectionIdentifier, this, RunLoop::main()); -#if OS(DARWIN) - m_connection->setShouldCloseConnectionOnMachExceptions(); -#elif PLATFORM(QT) && !OS(WINDOWS) - m_connection->setShouldCloseConnectionOnProcessTermination(processIdentifier()); -#endif - - m_connection->addQueueClient(this); - m_connection->open(); + ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier); m_webConnection = WebConnectionToWebProcess::create(this); - for (size_t i = 0; i < m_pendingMessages.size(); ++i) { - CoreIPC::Connection::OutgoingMessage& outgoingMessage = m_pendingMessages[i].first; - unsigned messageSendFlags = m_pendingMessages[i].second; - connection()->sendMessage(outgoingMessage.messageID(), adoptPtr(outgoingMessage.arguments()), messageSendFlags); - } - - m_pendingMessages.clear(); - - // Tell the context that we finished launching. m_context->processDidFinishLaunching(this); #if PLATFORM(MAC) - if (WebContext::applicationIsOccluded()) - connection()->send(Messages::WebProcess::SetApplicationIsOccluded(true), 0); + updateProcessSuppressionState(); #endif } WebFrameProxy* WebProcessProxy::webFrame(uint64_t frameID) const { - return isGoodKey<WebFrameProxyMap>(frameID) ? m_frameMap.get(frameID).get() : 0; + if (!WebFrameProxyMap::isValidKey(frameID)) + return 0; + + return m_frameMap.get(frameID); } bool WebProcessProxy::canCreateFrame(uint64_t frameID) const { - return isGoodKey<WebFrameProxyMap>(frameID) && !m_frameMap.contains(frameID); + return WebFrameProxyMap::isValidKey(frameID) && !m_frameMap.contains(frameID); } void WebProcessProxy::frameCreated(uint64_t frameID, WebFrameProxy* frameProxy) @@ -613,13 +489,13 @@ void WebProcessProxy::didDestroyFrame(uint64_t frameID) // If the page is closed before it has had the chance to send the DidCreateMainFrame message // back to the UIProcess, then the frameDestroyed message will still be received because it // gets sent directly to the WebProcessProxy. - ASSERT(isGoodKey<WebFrameProxyMap>(frameID)); + ASSERT(WebFrameProxyMap::isValidKey(frameID)); m_frameMap.remove(frameID); } void WebProcessProxy::disconnectFramesFromPage(WebPageProxy* page) { - Vector<RefPtr<WebFrameProxy> > frames; + Vector<RefPtr<WebFrameProxy>> frames; copyValuesToVector(m_frameMap, frames); for (size_t i = 0, size = frames.size(); i < size; ++i) { if (frames[i]->page() == page) @@ -630,24 +506,34 @@ void WebProcessProxy::disconnectFramesFromPage(WebPageProxy* page) size_t WebProcessProxy::frameCountInPage(WebPageProxy* page) const { size_t result = 0; - for (HashMap<uint64_t, RefPtr<WebFrameProxy> >::const_iterator iter = m_frameMap.begin(); iter != m_frameMap.end(); ++iter) { + for (HashMap<uint64_t, RefPtr<WebFrameProxy>>::const_iterator iter = m_frameMap.begin(); iter != m_frameMap.end(); ++iter) { if (iter->value->page() == page) ++result; } return result; } -void WebProcessProxy::shouldTerminate(bool& shouldTerminate) +bool WebProcessProxy::canTerminateChildProcess() { - if (!m_pageMap.isEmpty() || !m_context->shouldTerminate(this)) { - shouldTerminate = false; - return; - } + if (!m_pageMap.isEmpty()) + return false; - shouldTerminate = true; + if (m_downloadProxyMap && !m_downloadProxyMap->isEmpty()) + return false; - // We know that the web process is going to terminate so disconnect it from the context. - disconnect(); + if (!m_context->shouldTerminate(this)) + return false; + + return true; +} + +void WebProcessProxy::shouldTerminate(bool& shouldTerminate) +{ + shouldTerminate = canTerminateChildProcess(); + if (shouldTerminate) { + // We know that the web process is going to terminate so disconnect it from the context. + disconnect(); + } } void WebProcessProxy::updateTextCheckerState() @@ -656,6 +542,18 @@ void WebProcessProxy::updateTextCheckerState() send(Messages::WebProcess::SetTextCheckerState(TextChecker::state()), 0); } +DownloadProxy* WebProcessProxy::createDownloadProxy() +{ +#if ENABLE(NETWORK_PROCESS) + ASSERT(!m_context->usesNetworkProcess()); +#endif + + if (!m_downloadProxyMap) + m_downloadProxyMap = adoptPtr(new DownloadProxyMap(this)); + + return m_downloadProxyMap->createDownloadProxy(m_context.get()); +} + void WebProcessProxy::didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore& store, uint64_t frameID) { WebPageProxy* page = webPage(pageID); @@ -719,4 +617,72 @@ void WebProcessProxy::didUpdateHistoryTitle(uint64_t pageID, const String& title m_context->historyClient().didUpdateHistoryTitle(m_context.get(), page, title, url, frame); } +void WebProcessProxy::pageVisibilityChanged(WebKit::WebPageProxy *page) +{ +#if PLATFORM(MAC) + if (pageIsProcessSuppressible(page)) + m_processSuppressiblePages.add(page->pageID()); + else + m_processSuppressiblePages.remove(page->pageID()); + updateProcessSuppressionState(); +#else + UNUSED_PARAM(page); +#endif +} + +void WebProcessProxy::pagePreferencesChanged(WebKit::WebPageProxy *page) +{ +#if PLATFORM(MAC) + if (pageIsProcessSuppressible(page)) + m_processSuppressiblePages.add(page->pageID()); + else + m_processSuppressiblePages.remove(page->pageID()); + updateProcessSuppressionState(); +#else + UNUSED_PARAM(page); +#endif +} + +void WebProcessProxy::didSaveToPageCache() +{ + m_context->processDidCachePage(this); +} + +void WebProcessProxy::releasePageCache() +{ + if (canSendMessage()) + send(Messages::WebProcess::ReleasePageCache(), 0); +} + + +void WebProcessProxy::requestTermination() +{ + if (!isValid()) + return; + + ChildProcessProxy::terminate(); + + if (webConnection()) + webConnection()->didClose(); + + disconnect(); +} + + +void WebProcessProxy::enableSuddenTermination() +{ + if (!isValid()) + return; + + WebCore::enableSuddenTermination(); +} + +void WebProcessProxy::disableSuddenTermination() +{ + if (!isValid()) + return; + + WebCore::disableSuddenTermination(); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebProcessProxy.h b/Source/WebKit2/UIProcess/WebProcessProxy.h index 32325d508..7d9b7f6ba 100644 --- a/Source/WebKit2/UIProcess/WebProcessProxy.h +++ b/Source/WebKit2/UIProcess/WebProcessProxy.h @@ -26,6 +26,7 @@ #ifndef WebProcessProxy_h #define WebProcessProxy_h +#include "ChildProcessProxy.h" #include "MessageReceiverMap.h" #include "PlatformProcessIdentifier.h" #include "PluginInfoStore.h" @@ -45,70 +46,46 @@ #endif namespace WebCore { - class KURL; +class KURL; +struct PluginInfo; }; namespace WebKit { -#if USE(SECURITY_FRAMEWORK) -class SecItemRequestData; -class SecItemResponseData; -#endif - +class DownloadProxyMap; class WebBackForwardListItem; class WebContext; class WebPageGroup; struct WebNavigationDataStore; -class WebProcessProxy : public ThreadSafeRefCounted<WebProcessProxy>, CoreIPC::Connection::Client, ResponsivenessTimer::Client, ProcessLauncher::Client, CoreIPC::Connection::QueueClient { +class WebProcessProxy : public ChildProcessProxy, ResponsivenessTimer::Client { public: - typedef HashMap<uint64_t, RefPtr<WebFrameProxy> > WebFrameProxyMap; - typedef HashMap<uint64_t, RefPtr<WebBackForwardListItem> > WebBackForwardListItemMap; + typedef HashMap<uint64_t, RefPtr<WebBackForwardListItem>> WebBackForwardListItemMap; + typedef HashMap<uint64_t, RefPtr<WebFrameProxy>> WebFrameProxyMap; + typedef HashMap<uint64_t, WebPageProxy*> WebPageProxyMap; static PassRefPtr<WebProcessProxy> create(PassRefPtr<WebContext>); ~WebProcessProxy(); - static WebProcessProxy* fromConnection(CoreIPC::Connection*); - - void terminate(); - - template<typename T> bool send(const T& message, uint64_t destinationID, unsigned messageSendFlags = 0); - template<typename U> bool sendSync(const U& message, const typename U::Reply& reply, uint64_t destinationID, double timeout = 1); - - CoreIPC::Connection* connection() const - { - ASSERT(m_connection); - return m_connection.get(); + static WebProcessProxy* fromConnection(CoreIPC::Connection* connection) + { + return static_cast<WebProcessProxy*>(ChildProcessProxy::fromConnection(connection)); } - void addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver*); - void addMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID, CoreIPC::MessageReceiver*); - void removeMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID); - WebConnection* webConnection() const { return m_webConnection.get(); } WebContext* context() const { return m_context.get(); } - PlatformProcessIdentifier processIdentifier() const { return m_processLauncher->processIdentifier(); } - - WebPageProxy* webPage(uint64_t pageID) const; + static WebPageProxy* webPage(uint64_t pageID); PassRefPtr<WebPageProxy> createWebPage(PageClient*, WebContext*, WebPageGroup*); void addExistingWebPage(WebPageProxy*, uint64_t pageID); void removeWebPage(uint64_t pageID); Vector<WebPageProxy*> pages() const; -#if ENABLE(WEB_INTENTS) - void removeMessagePortChannel(uint64_t channelID); -#endif - WebBackForwardListItem* webBackForwardItem(uint64_t itemID) const; ResponsivenessTimer* responsivenessTimer() { return &m_responsivenessTimer; } - bool isValid() const { return m_connection; } - bool isLaunching() const; - bool canSendMessage() const { return isValid() || isLaunching(); } - WebFrameProxy* webFrame(uint64_t) const; bool canCreateFrame(uint64_t frameID) const; void frameCreated(uint64_t, WebFrameProxy*); @@ -127,19 +104,38 @@ public: static bool fullKeyboardAccessEnabled(); + DownloadProxy* createDownloadProxy(); + + void pageVisibilityChanged(WebPageProxy*); + void pagePreferencesChanged(WebPageProxy*); + + void didSaveToPageCache(); + void releasePageCache(); + +#if PLATFORM(MAC) + bool allPagesAreProcessSuppressible() const; + static bool pageIsProcessSuppressible(WebPageProxy*); + void updateProcessSuppressionState(); +#endif + + void enableSuddenTermination(); + void disableSuddenTermination(); + + void requestTermination(); + private: explicit WebProcessProxy(PassRefPtr<WebContext>); - // Initializes the process launcher which will begin launching the process. - void connect(); - void platformConnect(ProcessLauncher::LaunchOptions&); + // From ChildProcessProxy + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) OVERRIDE; + void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&); + virtual void connectionWillOpen(CoreIPC::Connection*) OVERRIDE; + virtual void connectionWillClose(CoreIPC::Connection*) OVERRIDE; // Called when the web process has crashed or we know that it will terminate soon. // Will potentially cause the WebProcessProxy object to be freed. void disconnect(); - bool sendMessage(CoreIPC::MessageID, PassOwnPtr<CoreIPC::MessageEncoder>, unsigned messageSendFlags); - // CoreIPC message handlers. void addBackForwardItem(uint64_t itemID, const String& originalURLString, const String& urlString, const String& title, const CoreIPC::DataReference& backForwardData); void didDestroyFrame(uint64_t); @@ -148,13 +144,10 @@ private: // Plugins #if ENABLE(NETSCAPE_PLUGIN_API) - void getPlugins(CoreIPC::Connection*, uint64_t requestID, bool refresh); - void getPluginPath(const String& mimeType, const String& urlString, String& pluginPath, uint32_t& pluginLoadPolicy); - void handleGetPlugins(uint64_t requestID, bool refresh); - void sendDidGetPlugins(uint64_t requestID, PassOwnPtr<Vector<WebCore::PluginInfo> >); + void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins); #endif // ENABLE(NETSCAPE_PLUGIN_API) #if ENABLE(PLUGIN_PROCESS) - void getPluginProcessConnection(const String& pluginPath, uint32_t processType, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); + void getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); #elif ENABLE(NETSCAPE_PLUGIN_API) void didGetSitesWithPluginData(const Vector<String>& sites, uint64_t callbackID); void didClearPluginSiteData(uint64_t callbackID); @@ -166,23 +159,12 @@ private: void getSharedWorkerProcessConnection(const String& url, const String& name, PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>); #endif -#if USE(SECURITY_FRAMEWORK) - void secItemRequest(CoreIPC::Connection*, uint64_t requestID, const SecItemRequestData&); - void secKeychainItemRequest(CoreIPC::Connection*, uint64_t requestID, const SecKeychainItemRequestData&); -#endif - // CoreIPC::Connection::Client friend class WebConnectionToWebProcess; - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - virtual void didClose(CoreIPC::Connection*); - virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName); -#if PLATFORM(WIN) - virtual Vector<HWND> windowsToReceiveSentMessagesWhileWaitingForSyncReply(); -#endif - - // CoreIPC::Connection::QueueClient - virtual void didReceiveMessageOnConnectionWorkQueue(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, bool& didHandleMessage) OVERRIDE; + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + virtual void didClose(CoreIPC::Connection*) OVERRIDE; + virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) OVERRIDE; // ResponsivenessTimer::Client void didBecomeUnresponsive(ResponsivenessTimer*) OVERRIDE; @@ -190,9 +172,7 @@ private: void didBecomeResponsive(ResponsivenessTimer*) OVERRIDE; // ProcessLauncher::Client - virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); - - void didFinishLaunching(CoreIPC::Connection::Identifier); + virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier) OVERRIDE; // History client void didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore&, uint64_t frameID); @@ -201,55 +181,34 @@ private: void didUpdateHistoryTitle(uint64_t pageID, const String& title, const String& url, uint64_t frameID); // Implemented in generated WebProcessProxyMessageReceiver.cpp - void didReceiveWebProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - void didReceiveSyncWebProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - void didReceiveWebProcessProxyMessageOnConnectionWorkQueue(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&, bool& didHandleMessage); + void didReceiveWebProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); + void didReceiveSyncWebProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + + bool canTerminateChildProcess(); ResponsivenessTimer m_responsivenessTimer; - - RefPtr<CoreIPC::Connection> m_connection; RefPtr<WebConnectionToWebProcess> m_webConnection; - CoreIPC::MessageReceiverMap m_messageReceiverMap; - - Vector<std::pair<CoreIPC::Connection::OutgoingMessage, unsigned> > m_pendingMessages; - RefPtr<ProcessLauncher> m_processLauncher; - RefPtr<WebContext> m_context; bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it. HashSet<String> m_localPathsWithAssumedReadAccess; - HashMap<uint64_t, WebPageProxy*> m_pageMap; + WebPageProxyMap m_pageMap; WebFrameProxyMap m_frameMap; WebBackForwardListItemMap m_backForwardListItemMap; - + + OwnPtr<DownloadProxyMap> m_downloadProxyMap; + #if ENABLE(CUSTOM_PROTOCOLS) CustomProtocolManagerProxy m_customProtocolManagerProxy; #endif -}; - -template<typename T> -bool WebProcessProxy::send(const T& message, uint64_t destinationID, unsigned messageSendFlags) -{ - COMPILE_ASSERT(!T::isSync, AsyncMessageExpected); - - OwnPtr<CoreIPC::MessageEncoder> encoder = CoreIPC::MessageEncoder::create(T::receiverName(), T::name(), destinationID); - encoder->encode(message); - - return sendMessage(CoreIPC::MessageID(T::messageID), encoder.release(), messageSendFlags); -} -template<typename U> -bool WebProcessProxy::sendSync(const U& message, const typename U::Reply& reply, uint64_t destinationID, double timeout) -{ - COMPILE_ASSERT(U::isSync, SyncMessageExpected); - - if (!m_connection) - return false; - - return connection()->sendSync(message, reply, destinationID, timeout); -} +#if PLATFORM(MAC) + HashSet<uint64_t> m_processSuppressiblePages; + bool m_processSuppressionEnabled; +#endif +}; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebProcessProxy.messages.in b/Source/WebKit2/UIProcess/WebProcessProxy.messages.in index a83e1e84c..fe6d3a295 100644 --- a/Source/WebKit2/UIProcess/WebProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebProcessProxy.messages.in @@ -20,7 +20,7 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> WebProcessProxy { +messages -> WebProcessProxy LegacyReceiver { # History client messages. DidNavigateWithNavigationData(uint64_t pageID, WebKit::WebNavigationDataStore store, uint64_t frameID) @@ -33,13 +33,15 @@ messages -> WebProcessProxy { ShouldTerminate() -> (bool shouldTerminate) + EnableSuddenTermination() + DisableSuddenTermination() + # Plugin messages. #if ENABLE(NETSCAPE_PLUGIN_API) - GetPlugins(uint64_t requestID, bool refresh) DispatchOnConnectionQueue - GetPluginPath(WTF::String mimeType, WTF::String urlString) -> (WTF::String pluginPath, uint32_t pluginLoadPolicy) + GetPlugins(bool refresh) -> (Vector<WebCore::PluginInfo> plugins) #endif // ENABLE(NETSCAPE_PLUGIN_API) #if ENABLE(PLUGIN_PROCESS) - GetPluginProcessConnection(WTF::String pluginPath, uint32_t processType) -> (CoreIPC::Attachment connectionHandle, bool supportsAsynchronousInitialization) Delayed + GetPluginProcessConnection(uint64_t pluginProcessToken) -> (CoreIPC::Attachment connectionHandle, bool supportsAsynchronousInitialization) Delayed #endif #if ENABLE(NETSCAPE_PLUGIN_API) && !ENABLE(PLUGIN_PROCESS) void DidGetSitesWithPluginData(Vector<WTF::String> sites, uint64_t callbackID) @@ -52,9 +54,4 @@ messages -> WebProcessProxy { GetSharedWorkerProcessConnection(WTF::String url, WTF::String name) -> (CoreIPC::Attachment connectionHandle) Delayed #endif -#if USE(SECURITY_FRAMEWORK) - SecItemRequest(uint64_t requestID, WebKit::SecItemRequestData request) DispatchOnConnectionQueue - SecKeychainItemRequest(uint64_t requestID, WebKit::SecKeychainItemRequestData request) DispatchOnConnectionQueue -#endif - } diff --git a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp index 22a41a12d..38299871c 100644 --- a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,26 +34,42 @@ #include "WebResourceCacheManagerProxyMessages.h" #include "WebSecurityOrigin.h" +#if ENABLE(NETWORK_PROCESS) +#include "NetworkProcessMessages.h" +#endif + using namespace WebCore; namespace WebKit { +const char* WebResourceCacheManagerProxy::supplementName() +{ + return "WebResourceCacheManagerProxy"; +} + PassRefPtr<WebResourceCacheManagerProxy> WebResourceCacheManagerProxy::create(WebContext* webContext) { return adoptRef(new WebResourceCacheManagerProxy(webContext)); } WebResourceCacheManagerProxy::WebResourceCacheManagerProxy(WebContext* webContext) - : m_webContext(webContext) + : WebContextSupplement(webContext) { - m_webContext->addMessageReceiver(Messages::WebResourceCacheManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebResourceCacheManagerProxy::messageReceiverName(), this); } WebResourceCacheManagerProxy::~WebResourceCacheManagerProxy() { } -void WebResourceCacheManagerProxy::invalidate() +// WebContextSupplement + +void WebResourceCacheManagerProxy::contextDestroyed() +{ + invalidateCallbackMap(m_arrayCallbacks); +} + +void WebResourceCacheManagerProxy::processDidClose(WebProcessProxy*) { invalidateCallbackMap(m_arrayCallbacks); } @@ -63,6 +79,16 @@ bool WebResourceCacheManagerProxy::shouldTerminate(WebProcessProxy*) const return m_arrayCallbacks.isEmpty(); } +void WebResourceCacheManagerProxy::refWebContextSupplement() +{ + APIObject::ref(); +} + +void WebResourceCacheManagerProxy::derefWebContextSupplement() +{ + APIObject::deref(); +} + void WebResourceCacheManagerProxy::getCacheOrigins(PassRefPtr<ArrayCallback> prpCallback) { RefPtr<ArrayCallback> callback = prpCallback; @@ -70,7 +96,7 @@ void WebResourceCacheManagerProxy::getCacheOrigins(PassRefPtr<ArrayCallback> prp m_arrayCallbacks.set(callbackID, callback.release()); // FIXME (Multi-WebProcess): <rdar://problem/12239765> When multi-process is enabled, we need to aggregate the callback data from all processes. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::GetCacheOrigins(callbackID)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::GetCacheOrigins(callbackID)); } void WebResourceCacheManagerProxy::didGetCacheOrigins(const Vector<SecurityOriginData>& origins, uint64_t callbackID) @@ -87,18 +113,17 @@ void WebResourceCacheManagerProxy::clearCacheForOrigin(WebSecurityOrigin* origin securityOrigin.port = origin->port(); // FIXME (Multi-WebProcess): <rdar://problem/12239765> There is no need to relaunch all processes. One process to take care of persistent cache is enough. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::ClearCacheForOrigin(securityOrigin, cachesToClear)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::ClearCacheForOrigin(securityOrigin, cachesToClear)); } void WebResourceCacheManagerProxy::clearCacheForAllOrigins(ResourceCachesToClear cachesToClear) { - // FIXME (Multi-WebProcess): <rdar://problem/12239765> There is no need to relaunch all processes. One process to take care of persistent cache is enough. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::ClearCacheForAllOrigins(cachesToClear)); -} +#if ENABLE(NETWORK_PROCESS) + context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::ClearCacheForAllOrigins(cachesToClear)); +#endif -void WebResourceCacheManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveWebResourceCacheManagerProxyMessage(connection, messageID, decoder); + // FIXME (Multi-WebProcess): <rdar://problem/12239765> There is no need to relaunch all processes. One process to take care of persistent cache is enough. + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::ClearCacheForAllOrigins(cachesToClear)); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h index 1c620707b..e80afc3c6 100644 --- a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,6 +31,7 @@ #include "GenericCallback.h" #include "MessageReceiver.h" #include "ResourceCachesToClear.h" +#include "WebContextSupplement.h" #include <wtf/HashMap.h> #include <wtf/PassRefPtr.h> @@ -43,36 +44,37 @@ class WebSecurityOrigin; typedef GenericCallback<WKArrayRef> ArrayCallback; -class WebResourceCacheManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebResourceCacheManagerProxy : public TypedAPIObject<APIObject::TypeCacheManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeCacheManager; + static const char* supplementName(); static PassRefPtr<WebResourceCacheManagerProxy> create(WebContext*); virtual ~WebResourceCacheManagerProxy(); - void invalidate(); - void clearContext() { m_webContext = 0; } - void getCacheOrigins(PassRefPtr<ArrayCallback>); void clearCacheForOrigin(WebSecurityOrigin*, ResourceCachesToClear); void clearCacheForAllOrigins(ResourceCachesToClear); - bool shouldTerminate(WebProcessProxy*) const; + using APIObject::ref; + using APIObject::deref; private: explicit WebResourceCacheManagerProxy(WebContext*); - virtual Type type() const { return APIType; } + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebResourceCacheManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; // Message handlers. void didGetCacheOrigins(const Vector<SecurityOriginData>& originIdentifiers, uint64_t callbackID); - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebResourceLoadClient.cpp b/Source/WebKit2/UIProcess/WebResourceLoadClient.cpp deleted file mode 100644 index f6dbe593b..000000000 --- a/Source/WebKit2/UIProcess/WebResourceLoadClient.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebResourceLoadClient.h" - -#include "WKAPICast.h" -#include "WebURLRequest.h" -#include "WebURLResponse.h" - -using namespace WebCore; - -namespace WebKit { - -void WebResourceLoadClient::didInitiateLoadForResource(WebPageProxy* page, WebFrameProxy* frame, uint64_t resourceIdentifier, const ResourceRequest& resourceRequest, bool pageIsProvisionallyLoading) -{ - if (!m_client.didInitiateLoadForResource) - return; - - RefPtr<WebURLRequest> request = WebURLRequest::create(resourceRequest); - return m_client.didInitiateLoadForResource(toAPI(page), toAPI(frame), resourceIdentifier, toAPI(request.get()), pageIsProvisionallyLoading, m_client.clientInfo); -} - -void WebResourceLoadClient::didSendRequestForResource(WebPageProxy* page, WebFrameProxy* frame, uint64_t resourceIdentifier, const ResourceRequest& resourceRequest, const ResourceResponse& redirectResourceResponse) -{ - if (!m_client.didSendRequestForResource) - return; - - RefPtr<WebURLRequest> request = WebURLRequest::create(resourceRequest); - RefPtr<WebURLResponse> response; - if (!redirectResourceResponse.isNull()) - response = WebURLResponse::create(redirectResourceResponse); - return m_client.didSendRequestForResource(toAPI(page), toAPI(frame), resourceIdentifier, toAPI(request.get()), toAPI(response.get()), m_client.clientInfo); -} - -void WebResourceLoadClient::didReceiveResponseForResource(WebPageProxy* page, WebFrameProxy* frame, uint64_t resourceIdentifier, const ResourceResponse& resourceResponse) -{ - if (!m_client.didReceiveResponseForResource) - return; - - RefPtr<WebURLResponse> response = WebURLResponse::create(resourceResponse); - return m_client.didReceiveResponseForResource(toAPI(page), toAPI(frame), resourceIdentifier, toAPI(response.get()), m_client.clientInfo); -} - -void WebResourceLoadClient::didReceiveContentLengthForResource(WebPageProxy* page, WebFrameProxy* frame, uint64_t resourceIdentifier, uint64_t contentLength) -{ - if (!m_client.didReceiveContentLengthForResource) - return; - - return m_client.didReceiveContentLengthForResource(toAPI(page), toAPI(frame), resourceIdentifier, contentLength, m_client.clientInfo); -} - -void WebResourceLoadClient::didFinishLoadForResource(WebPageProxy* page, WebFrameProxy* frame, uint64_t resourceIdentifier) -{ - if (!m_client.didFinishLoadForResource) - return; - - return m_client.didFinishLoadForResource(toAPI(page), toAPI(frame), resourceIdentifier, m_client.clientInfo); -} - -void WebResourceLoadClient::didFailLoadForResource(WebPageProxy* page, WebFrameProxy* frame, uint64_t resourceIdentifier, const ResourceError& error) -{ - if (!m_client.didFailLoadForResource) - return; - - return m_client.didFailLoadForResource(toAPI(page), toAPI(frame), resourceIdentifier, toAPI(error), m_client.clientInfo); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebResourceLoadClient.h b/Source/WebKit2/UIProcess/WebResourceLoadClient.h deleted file mode 100644 index 125546cd0..000000000 --- a/Source/WebKit2/UIProcess/WebResourceLoadClient.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebResourceLoadClient_h -#define WebResourceLoadClient_h - -#include "APIClient.h" -#include "WKPage.h" - -namespace WebCore { -class ResourceError; -class ResourceRequest; -class ResourceResponse; -} - -namespace WebKit { - -class APIObject; -class WebFrameProxy; -class WebPageProxy; - -class WebResourceLoadClient : public APIClient<WKPageResourceLoadClient, kWKPageResourceLoadClientCurrentVersion> { -public: - void didInitiateLoadForResource(WebPageProxy*, WebFrameProxy*, uint64_t resourceIdentifier, const WebCore::ResourceRequest&, bool pageIsProvisionallyLoading); - void didSendRequestForResource(WebPageProxy*, WebFrameProxy*, uint64_t resourceIdentifier, const WebCore::ResourceRequest&, const WebCore::ResourceResponse&); - void didReceiveResponseForResource(WebPageProxy*, WebFrameProxy*, uint64_t resourceIdentifier, const WebCore::ResourceResponse&); - void didReceiveContentLengthForResource(WebPageProxy*, WebFrameProxy*, uint64_t resourceIdentifier, uint64_t contentLength); - void didFinishLoadForResource(WebPageProxy*, WebFrameProxy*, uint64_t resourceIdentifier); - void didFailLoadForResource(WebPageProxy*, WebFrameProxy*, uint64_t resourceIdentifier, const WebCore::ResourceError&); -}; - -} // namespace WebKit - -#endif // WebResourceLoadClient_h diff --git a/Source/WebKit2/UIProcess/WebTextChecker.h b/Source/WebKit2/UIProcess/WebTextChecker.h index a1c574ca9..863ed03c7 100644 --- a/Source/WebKit2/UIProcess/WebTextChecker.h +++ b/Source/WebKit2/UIProcess/WebTextChecker.h @@ -35,10 +35,8 @@ namespace WebKit { class WebPageProxy; -class WebTextChecker : public APIObject { +class WebTextChecker : public TypedAPIObject<APIObject::TypeTextChecker> { public: - static const Type APIType = TypeTextChecker; - static WebTextChecker* shared(); void setClient(const WKTextCheckerClient*); @@ -53,8 +51,6 @@ public: private: WebTextChecker(); - virtual Type type() const { return APIType; } - WebTextCheckerClient m_client; }; diff --git a/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp b/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp index 86e52c637..cc69d5e69 100644 --- a/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp +++ b/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp @@ -93,6 +93,9 @@ void WebTextCheckerClient::closeSpellDocumentWithTag(uint64_t tag) void WebTextCheckerClient::checkSpellingOfString(uint64_t tag, const String& text, int32_t& misspellingLocation, int32_t& misspellingLength) { + misspellingLocation = -1; + misspellingLength = 0; + if (!m_client.checkSpellingOfString) return; @@ -101,6 +104,9 @@ void WebTextCheckerClient::checkSpellingOfString(uint64_t tag, const String& tex void WebTextCheckerClient::checkGrammarOfString(uint64_t tag, const String& text, Vector<WebCore::GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength) { + badGrammarLocation = -1; + badGrammarLength = 0; + if (!m_client.checkGrammarOfString) return; diff --git a/Source/WebKit2/UIProcess/WebUIClient.cpp b/Source/WebKit2/UIProcess/WebUIClient.cpp index f88c00a24..bfa4d8e43 100644 --- a/Source/WebKit2/UIProcess/WebUIClient.cpp +++ b/Source/WebKit2/UIProcess/WebUIClient.cpp @@ -30,6 +30,7 @@ #include "NativeWebKeyboardEvent.h" #include "NativeWebWheelEvent.h" #include "NotificationPermissionRequest.h" +#include "PluginInformation.h" #include "WKAPICast.h" #include "WebColorPickerResultListenerProxy.h" #include "WebNumber.h" @@ -175,18 +176,33 @@ void WebUIClient::mouseDidMoveOverElement(WebPageProxy* page, const WebHitTestRe m_client.mouseDidMoveOverElement(toAPI(page), toAPI(webHitTestResult.get()), toAPI(modifiers), toAPI(userData), m_client.clientInfo); } -void WebUIClient::unavailablePluginButtonClicked(WebPageProxy* page, WKPluginUnavailabilityReason pluginUnavailabilityReason, const String& mimeType, const String& url, const String& pluginsPageURL) +void WebUIClient::unavailablePluginButtonClicked(WebPageProxy* page, WKPluginUnavailabilityReason pluginUnavailabilityReason, ImmutableDictionary* pluginInformation) { if (pluginUnavailabilityReason == kWKPluginUnavailabilityReasonPluginMissing) { if (m_client.missingPluginButtonClicked_deprecatedForUseWithV0) - m_client.missingPluginButtonClicked_deprecatedForUseWithV0(toAPI(page), toAPI(mimeType.impl()), toAPI(url.impl()), toAPI(pluginsPageURL.impl()), m_client.clientInfo); + m_client.missingPluginButtonClicked_deprecatedForUseWithV0( + toAPI(page), + toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), + toAPI(pluginInformation->get<WebString>(pluginInformationPluginURLKey())), + toAPI(pluginInformation->get<WebString>(pluginInformationPluginspageAttributeURLKey())), + m_client.clientInfo); } - if (!m_client.unavailablePluginButtonClicked) - return; - - m_client.unavailablePluginButtonClicked(toAPI(page), pluginUnavailabilityReason, toAPI(mimeType.impl()), toAPI(url.impl()), toAPI(pluginsPageURL.impl()), m_client.clientInfo); - + if (m_client.unavailablePluginButtonClicked_deprecatedForUseWithV1) + m_client.unavailablePluginButtonClicked_deprecatedForUseWithV1( + toAPI(page), + pluginUnavailabilityReason, + toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), + toAPI(pluginInformation->get<WebString>(pluginInformationPluginURLKey())), + toAPI(pluginInformation->get<WebString>(pluginInformationPluginspageAttributeURLKey())), + m_client.clientInfo); + + if (m_client.unavailablePluginButtonClicked) + m_client.unavailablePluginButtonClicked( + toAPI(page), + pluginUnavailabilityReason, + toAPI(pluginInformation), + m_client.clientInfo); } bool WebUIClient::implementsDidNotHandleKeyEvent() const diff --git a/Source/WebKit2/UIProcess/WebUIClient.h b/Source/WebKit2/UIProcess/WebUIClient.h index 9b52bfd0e..9813f5754 100644 --- a/Source/WebKit2/UIProcess/WebUIClient.h +++ b/Source/WebKit2/UIProcess/WebUIClient.h @@ -45,6 +45,7 @@ namespace WebKit { class APIObject; class GeolocationPermissionRequestProxy; +class ImmutableDictionary; class NativeWebKeyboardEvent; class NativeWebWheelEvent; class NotificationPermissionRequest; @@ -71,7 +72,7 @@ public: void setStatusText(WebPageProxy*, const String&); void mouseDidMoveOverElement(WebPageProxy*, const WebHitTestResult::Data&, WebEvent::Modifiers, APIObject*); - void unavailablePluginButtonClicked(WebPageProxy*, WKPluginUnavailabilityReason, const String& mimeType, const String& url, const String& pluginsPageURL); + void unavailablePluginButtonClicked(WebPageProxy*, WKPluginUnavailabilityReason, ImmutableDictionary*); bool implementsDidNotHandleKeyEvent() const; void didNotHandleKeyEvent(WebPageProxy*, const NativeWebKeyboardEvent&); diff --git a/Source/WebKit2/UIProcess/WebVibrationProvider.cpp b/Source/WebKit2/UIProcess/WebVibrationProvider.cpp index 095bd978b..a12f5973b 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProvider.cpp +++ b/Source/WebKit2/UIProcess/WebVibrationProvider.cpp @@ -33,7 +33,7 @@ namespace WebKit { -void WebVibrationProvider::vibrate(WebVibrationProxy* vibration, uint64_t vibrationTime) +void WebVibrationProvider::vibrate(WebVibrationProxy* vibration, uint32_t vibrationTime) { if (!m_client.vibrate) return; diff --git a/Source/WebKit2/UIProcess/WebVibrationProvider.h b/Source/WebKit2/UIProcess/WebVibrationProvider.h index 76d98a8d2..36159de83 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProvider.h +++ b/Source/WebKit2/UIProcess/WebVibrationProvider.h @@ -38,7 +38,7 @@ class WebVibrationProxy; class WebVibrationProvider : public APIClient<WKVibrationProvider, kWKVibrationProviderCurrentVersion> { public: - void vibrate(WebVibrationProxy*, uint64_t vibrationTime); + void vibrate(WebVibrationProxy*, uint32_t vibrationTime); void cancelVibration(WebVibrationProxy*); }; diff --git a/Source/WebKit2/UIProcess/WebVibrationProxy.cpp b/Source/WebKit2/UIProcess/WebVibrationProxy.cpp index 2e790c2f8..90da393da 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProxy.cpp +++ b/Source/WebKit2/UIProcess/WebVibrationProxy.cpp @@ -62,12 +62,7 @@ void WebVibrationProxy::initializeProvider(const WKVibrationProvider* provider) m_provider.initialize(provider); } -void WebVibrationProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) -{ - didReceiveWebVibrationProxyMessage(connection, messageID, decoder); -} - -void WebVibrationProxy::vibrate(uint64_t vibrationTime) +void WebVibrationProxy::vibrate(uint32_t vibrationTime) { m_provider.vibrate(this, vibrationTime); } diff --git a/Source/WebKit2/UIProcess/WebVibrationProxy.h b/Source/WebKit2/UIProcess/WebVibrationProxy.h index 0031dfd36..1f9c891e4 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProxy.h +++ b/Source/WebKit2/UIProcess/WebVibrationProxy.h @@ -37,10 +37,8 @@ namespace WebKit { class WebPageProxy; -class WebVibrationProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebVibrationProxy : public TypedAPIObject<APIObject::TypeVibration>, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeVibration; - static PassRefPtr<WebVibrationProxy> create(WebPageProxy*); virtual ~WebVibrationProxy(); @@ -48,18 +46,13 @@ public: void initializeProvider(const WKVibrationProvider*); - // Implemented in generated WebVibrationProxyMessageReceiver.cpp - void didReceiveWebVibrationProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - private: explicit WebVibrationProxy(WebPageProxy*); - virtual Type type() const { return APIType; } - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - void vibrate(uint64_t vibrationTime); + void vibrate(uint32_t vibrationTime); void cancelVibration(); WebPageProxy* m_page; diff --git a/Source/WebKit2/UIProcess/WebVibrationProxy.messages.in b/Source/WebKit2/UIProcess/WebVibrationProxy.messages.in index ff40b0d9f..ad5bdfd2a 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebVibrationProxy.messages.in @@ -23,7 +23,7 @@ #if ENABLE(VIBRATION) messages -> WebVibrationProxy { - Vibrate(uint64_t vibrationTime); + Vibrate(uint32_t vibrationTime); CancelVibration(); } diff --git a/Source/WebKit2/UIProcess/WebViewportAttributes.cpp b/Source/WebKit2/UIProcess/WebViewportAttributes.cpp new file mode 100644 index 000000000..64b4a7679 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebViewportAttributes.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebViewportAttributes.h" + +namespace WebKit { + +WebViewportAttributes::WebViewportAttributes(const WebCore::ViewportAttributes& attributes) + : m_attributes(attributes) +{ +} + +WebViewportAttributes::~WebViewportAttributes() +{ +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebViewportAttributes.h b/Source/WebKit2/UIProcess/WebViewportAttributes.h new file mode 100644 index 000000000..9fb3f59eb --- /dev/null +++ b/Source/WebKit2/UIProcess/WebViewportAttributes.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list Viewof conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebViewportAttributes_h +#define WebViewportAttributes_h + +#include "APIObject.h" +#include <WebCore/ViewportArguments.h> +#include <wtf/PassRefPtr.h> + +namespace WebKit { + +class WebViewportAttributes : public TypedAPIObject<APIObject::TypeViewportAttributes> { +public: + static PassRefPtr<WebViewportAttributes> create(const WebCore::ViewportAttributes& attributes) + { + return adoptRef(new WebViewportAttributes(attributes)); + } + + virtual ~WebViewportAttributes(); + + const WebCore::ViewportAttributes& originalAttributes() const { return m_attributes; } + +private: + explicit WebViewportAttributes(const WebCore::ViewportAttributes&); + + WebCore::ViewportAttributes m_attributes; +}; + +} // namespace WebKit + +#endif // WebViewportAttributes_h diff --git a/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp b/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp index 71f48e7f0..8369a2bd4 100644 --- a/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp +++ b/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp @@ -31,16 +31,34 @@ #include "UpdateInfo.h" #include "WebPageProxy.h" #include <WebCore/GraphicsContext.h> +#include <WebCore/WidgetBackingStoreCairo.h> #include <cairo.h> +#if PLATFORM(GTK) && defined(GDK_WINDOWING_X11) +#include <WebCore/WidgetBackingStoreGtkX11.h> +#include <gdk/gdkx.h> +#endif + #if PLATFORM(EFL) -#include "EwkViewImpl.h" +#include "EwkView.h" #endif using namespace WebCore; namespace WebKit { +#if PLATFORM(GTK) +static OwnPtr<WidgetBackingStore> createBackingStoreForGTK(GtkWidget* widget, const IntSize& size) +{ +#ifdef GDK_WINDOWING_X11 + GdkDisplay* display = gdk_display_manager_get_default_display(gdk_display_manager_get()); + if (GDK_IS_X11_DISPLAY(display)) + return WebCore::WidgetBackingStoreGtkX11::create(widget, size); +#endif + return WebCore::WidgetBackingStoreCairo::create(widget, size); +} +#endif + void BackingStore::paint(cairo_t* context, const IntRect& rect) { ASSERT(m_backingStore); @@ -54,7 +72,11 @@ void BackingStore::paint(cairo_t* context, const IntRect& rect) void BackingStore::incorporateUpdate(ShareableBitmap* bitmap, const UpdateInfo& updateInfo) { if (!m_backingStore) - m_backingStore = WidgetBackingStore::create(m_webPageProxy->viewWidget(), size()); +#if PLATFORM(EFL) + m_backingStore = WidgetBackingStoreCairo::create(EwkView::toEvasObject(toAPI(m_webPageProxy)), size()); +#else + m_backingStore = createBackingStoreForGTK(m_webPageProxy->viewWidget(), size()); +#endif scroll(updateInfo.scrollRect, updateInfo.scrollOffset); @@ -68,12 +90,6 @@ void BackingStore::incorporateUpdate(ShareableBitmap* bitmap, const UpdateInfo& srcRect.move(-updateRectLocation.x(), -updateRectLocation.y()); bitmap->paint(graphicsContext, updateRect.location(), srcRect); } - -#if PLATFORM(EFL) - // Update ewk_view with new backingStore image. - EwkViewImpl* viewImpl = EwkViewImpl::fromEvasObject(m_webPageProxy->viewWidget()); - viewImpl->setImageData(cairo_image_surface_get_data(m_backingStore->cairoSurface()), m_size); -#endif } void BackingStore::scroll(const IntRect& scrollRect, const IntSize& scrollOffset) diff --git a/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp b/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp index 7c1f240ec..e85d909ed 100644 --- a/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp +++ b/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp @@ -74,7 +74,7 @@ CFDictionaryRef WebBackForwardList::createCFDictionaryRepresentation(WebPageProx return createEmptySessionHistoryDictionary(); } - RetainPtr<CFMutableArrayRef> entries(AdoptCF, CFArrayCreateMutable(0, m_entries.size(), &kCFTypeArrayCallBacks)); + RetainPtr<CFMutableArrayRef> entries = adoptCF(CFArrayCreateMutable(0, m_entries.size(), &kCFTypeArrayCallBacks)); // We may need to update the current index to account for entries that are filtered by the callback. CFIndex currentIndex = m_currentIndex; @@ -88,10 +88,13 @@ CFDictionaryRef WebBackForwardList::createCFDictionaryRepresentation(WebPageProx return 0; } - if (filter && !filter(toAPI(m_page), WKPageGetSessionHistoryURLValueType(), toURLRef(m_entries[i]->originalURL().impl()), context)) { - if (i <= m_currentIndex) - currentIndex--; - continue; + if (filter) { + if (!filter(toAPI(m_page), WKPageGetSessionBackForwardListItemValueType(), toAPI(m_entries[i].get()), context) + || !filter(toAPI(m_page), WKPageGetSessionHistoryURLValueType(), toURLRef(m_entries[i]->originalURL().impl()), context)) { + if (i <= m_currentIndex) + currentIndex--; + continue; + } } RetainPtr<CFStringRef> url = m_entries[i]->url().createCFString(); @@ -100,12 +103,12 @@ CFDictionaryRef WebBackForwardList::createCFDictionaryRepresentation(WebPageProx // FIXME: This uses the CoreIPC data encoding format, which means that whenever we change the CoreIPC encoding we need to bump the CurrentSessionStateDataVersion // constant in WebPageProxyCF.cpp. The CoreIPC data format is meant to be an implementation detail, and not something that should be written to disk. - RetainPtr<CFDataRef> entryData(AdoptCF, CFDataCreate(kCFAllocatorDefault, m_entries[i]->backForwardData().data(), m_entries[i]->backForwardData().size())); + RetainPtr<CFDataRef> entryData = adoptCF(CFDataCreate(kCFAllocatorDefault, m_entries[i]->backForwardData().data(), m_entries[i]->backForwardData().size())); const void* keys[4] = { SessionHistoryEntryURLKey(), SessionHistoryEntryTitleKey(), SessionHistoryEntryOriginalURLKey(), SessionHistoryEntryDataKey() }; const void* values[4] = { url.get(), title.get(), originalURL.get(), entryData.get() }; - RetainPtr<CFDictionaryRef> entryDictionary(AdoptCF, CFDictionaryCreate(0, keys, values, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); + RetainPtr<CFDictionaryRef> entryDictionary = adoptCF(CFDictionaryCreate(0, keys, values, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFArrayAppendValue(entries.get(), entryDictionary.get()); } @@ -126,7 +129,7 @@ CFDictionaryRef WebBackForwardList::createCFDictionaryRepresentation(WebPageProx } if (hasCurrentIndex) { - RetainPtr<CFNumberRef> currentIndexNumber(AdoptCF, CFNumberCreate(0, kCFNumberCFIndexType, ¤tIndex)); + RetainPtr<CFNumberRef> currentIndexNumber = adoptCF(CFNumberCreate(0, kCFNumberCFIndexType, ¤tIndex)); const void* keys[3] = { SessionHistoryVersionKey(), SessionHistoryCurrentIndexKey(), SessionHistoryEntriesKey() }; const void* values[3] = { SessionHistoryCurrentVersion(), currentIndexNumber.get(), entries.get() }; diff --git a/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp b/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp index fac02c1b4..082b09fd3 100644 --- a/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp +++ b/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp @@ -52,7 +52,7 @@ PassRefPtr<WebData> WebPageProxy::sessionStateData(WebPageProxySessionStateFilte const void* values[2]; CFIndex numValues = 0; - RetainPtr<CFDictionaryRef> sessionHistoryDictionary(AdoptCF, m_backForwardList->createCFDictionaryRepresentation(filter, context)); + RetainPtr<CFDictionaryRef> sessionHistoryDictionary = adoptCF(m_backForwardList->createCFDictionaryRepresentation(filter, context)); if (sessionHistoryDictionary) { keys[numValues] = SessionHistoryKey(); values[numValues] = sessionHistoryDictionary.get(); @@ -75,9 +75,9 @@ PassRefPtr<WebData> WebPageProxy::sessionStateData(WebPageProxySessionStateFilte if (!numValues) return 0; - RetainPtr<CFDictionaryRef> stateDictionary(AdoptCF, CFDictionaryCreate(0, keys, values, numValues, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); + RetainPtr<CFDictionaryRef> stateDictionary = adoptCF(CFDictionaryCreate(0, keys, values, numValues, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); - RetainPtr<CFWriteStreamRef> writeStream(AdoptCF, CFWriteStreamCreateWithAllocatedBuffers(0, 0)); + RetainPtr<CFWriteStreamRef> writeStream = adoptCF(CFWriteStreamCreateWithAllocatedBuffers(0, 0)); if (!writeStream) return 0; @@ -87,7 +87,7 @@ PassRefPtr<WebData> WebPageProxy::sessionStateData(WebPageProxySessionStateFilte if (!CFPropertyListWriteToStream(stateDictionary.get(), writeStream.get(), kCFPropertyListBinaryFormat_v1_0, 0)) return 0; - RetainPtr<CFDataRef> stateCFData(AdoptCF, (CFDataRef)CFWriteStreamCopyProperty(writeStream.get(), kCFStreamPropertyDataWritten)); + RetainPtr<CFDataRef> stateCFData = adoptCF((CFDataRef)CFWriteStreamCopyProperty(writeStream.get(), kCFStreamPropertyDataWritten)); CFIndex length = CFDataGetLength(stateCFData.get()); Vector<unsigned char> stateVector(length + sizeof(UInt32)); @@ -117,10 +117,10 @@ void WebPageProxy::restoreFromSessionStateData(WebData* webData) return; } - RetainPtr<CFDataRef> data(AdoptCF, CFDataCreate(0, webData->bytes() + sizeof(UInt32), webData->size() - sizeof(UInt32))); + RetainPtr<CFDataRef> data = adoptCF(CFDataCreate(0, webData->bytes() + sizeof(UInt32), webData->size() - sizeof(UInt32))); CFStringRef propertyListError = 0; - RetainPtr<CFPropertyListRef> propertyList(AdoptCF, CFPropertyListCreateFromXMLData(0, data.get(), kCFPropertyListImmutable, &propertyListError)); + RetainPtr<CFPropertyListRef> propertyList = adoptCF(CFPropertyListCreateFromXMLData(0, data.get(), kCFPropertyListImmutable, &propertyListError)); if (propertyListError) { CFRelease(propertyListError); LOG(SessionState, "Could not read session state property list"); @@ -190,7 +190,7 @@ void WebPageProxy::saveRecentSearches(const String& name, const Vector<String>& RetainPtr<CFMutableArrayRef> items; if (size_t size = searchItems.size()) { - items.adoptCF(CFArrayCreateMutable(0, size, &kCFTypeArrayCallBacks)); + items = adoptCF(CFArrayCreateMutable(0, size, &kCFTypeArrayCallBacks)); for (size_t i = 0; i < size; ++i) CFArrayAppendValue(items.get(), searchItems[i].createCFString().get()); } @@ -205,7 +205,7 @@ void WebPageProxy::loadRecentSearches(const String& name, Vector<String>& search ASSERT(!name.isEmpty()); searchItems.clear(); - RetainPtr<CFArrayRef> items(AdoptCF, reinterpret_cast<CFArrayRef>(CFPreferencesCopyAppValue(autosaveKey(name).get(), kCFPreferencesCurrentApplication))); + RetainPtr<CFArrayRef> items = adoptCF(reinterpret_cast<CFArrayRef>(CFPreferencesCopyAppValue(autosaveKey(name).get(), kCFPreferencesCurrentApplication))); if (!items || CFGetTypeID(items.get()) != CFArrayGetTypeID()) return; diff --git a/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp b/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp index d61b98c60..f2463a735 100644 --- a/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp +++ b/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp @@ -35,7 +35,7 @@ namespace WebKit { static RetainPtr<CFStringRef> cfStringFromWebCoreString(const String& string) { - return RetainPtr<CFStringRef>(AdoptCF, CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(string.characters()), string.length())); + return RetainPtr<CFStringRef> = adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(string.characters()), string.length())); } static inline RetainPtr<CFStringRef> makeKey(const String& identifier, const String& baseKey) @@ -45,7 +45,7 @@ static inline RetainPtr<CFStringRef> makeKey(const String& identifier, const Str static void setStringValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) { - RetainPtr<CFPropertyListRef> value(AdoptCF, CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); + RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); if (!value) return; if (CFGetTypeID(value.get()) != CFStringGetTypeID()) @@ -56,7 +56,7 @@ static void setStringValueIfInUserDefaults(const String& identifier, const Strin static void setBoolValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) { - RetainPtr<CFPropertyListRef> value(AdoptCF, CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); + RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); if (!value) return; if (CFGetTypeID(value.get()) != CFBooleanGetTypeID()) @@ -67,7 +67,7 @@ static void setBoolValueIfInUserDefaults(const String& identifier, const String& static void setUInt32ValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) { - RetainPtr<CFPropertyListRef> value(AdoptCF, CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); + RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); if (!value) return; if (CFGetTypeID(value.get()) != CFNumberGetTypeID()) @@ -81,7 +81,7 @@ static void setUInt32ValueIfInUserDefaults(const String& identifier, const Strin static void setDoubleValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) { - RetainPtr<CFPropertyListRef> value(AdoptCF, CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); + RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); if (!value) return; if (CFGetTypeID(value.get()) != CFNumberGetTypeID()) @@ -128,7 +128,7 @@ void WebPreferences::platformUpdateUInt32ValueForKey(const String& key, uint32_t if (!m_identifier) return; - RetainPtr<CFNumberRef> number(AdoptCF, CFNumberCreate(0, kCFNumberSInt32Type, &value)); + RetainPtr<CFNumberRef> number = adoptCF(CFNumberCreate(0, kCFNumberSInt32Type, &value)); CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), number.get(), kCFPreferencesCurrentApplication); } @@ -137,7 +137,7 @@ void WebPreferences::platformUpdateDoubleValueForKey(const String& key, double v if (!m_identifier) return; - RetainPtr<CFNumberRef> number(AdoptCF, CFNumberCreate(0, kCFNumberDoubleType, &value)); + RetainPtr<CFNumberRef> number = adoptCF(CFNumberCreate(0, kCFNumberDoubleType, &value)); CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), number.get(), kCFPreferencesCurrentApplication); } @@ -146,7 +146,7 @@ void WebPreferences::platformUpdateFloatValueForKey(const String& key, float val if (!m_identifier) return; - RetainPtr<CFNumberRef> number(AdoptCF, CFNumberCreate(0, kCFNumberFloatType, &value)); + RetainPtr<CFNumberRef> number = adoptCF(CFNumberCreate(0, kCFNumberFloatType, &value)); CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), number.get(), kCFPreferencesCurrentApplication); } diff --git a/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp b/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp index 96346317f..52b14eb12 100644 --- a/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp +++ b/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp @@ -30,9 +30,7 @@ #include "WKAPICast.h" #include "WKBatteryManager.h" -#include "WebBatteryManagerProxy.h" -#include "WebBatteryStatus.h" -#include "WebContext.h" +#include "WKBatteryStatus.h" using namespace WebCore; using namespace WebKit; @@ -56,21 +54,20 @@ BatteryProvider::~BatteryProvider() { m_provider.stopUpdating(); - ASSERT(m_context->batteryManagerProxy()); - m_context->batteryManagerProxy()->initializeProvider(0); + WKBatteryManagerSetProvider(m_batteryManager.get(), 0); } -PassRefPtr<BatteryProvider> BatteryProvider::create(PassRefPtr<WebContext> context) +PassRefPtr<BatteryProvider> BatteryProvider::create(WKContextRef context) { ASSERT(context); return adoptRef(new BatteryProvider(context)); } -BatteryProvider::BatteryProvider(PassRefPtr<WebContext> context) - : m_context(context) +BatteryProvider::BatteryProvider(WKContextRef context) + : m_batteryManager(WKContextGetBatteryManager(context)) , m_provider(this) { - ASSERT(m_context); + ASSERT(m_batteryManager); WKBatteryProvider wkBatteryProvider = { kWKBatteryProviderCurrentVersion, @@ -79,8 +76,7 @@ BatteryProvider::BatteryProvider(PassRefPtr<WebContext> context) stopUpdatingCallback }; - ASSERT(m_context->batteryManagerProxy()); - m_context->batteryManagerProxy()->initializeProvider(&wkBatteryProvider); + WKBatteryManagerSetProvider(m_batteryManager.get(), &wkBatteryProvider); } void BatteryProvider::startUpdating() @@ -95,9 +91,8 @@ void BatteryProvider::stopUpdating() void BatteryProvider::didChangeBatteryStatus(const AtomicString& eventType, PassRefPtr<BatteryStatus> status) { - RefPtr<WebBatteryStatus> batteryStatus = WebBatteryStatus::create(status->charging(), status->chargingTime(), status->dischargingTime(), status->level()); + WKRetainPtr<WKBatteryStatusRef> wkBatteryStatus = adoptWK(WKBatteryStatusCreate(status->charging(), status->chargingTime(), status->dischargingTime(), status->level())); - ASSERT(m_context->batteryManagerProxy()); - m_context->batteryManagerProxy()->providerDidChangeBatteryStatus(eventType, batteryStatus.get()); + WKBatteryManagerProviderDidChangeBatteryStatus(m_batteryManager.get(), toAPI(eventType.impl()), wkBatteryStatus.get()); } #endif // ENABLE(BATTERY_STATUS) diff --git a/Source/WebKit2/UIProcess/efl/BatteryProvider.h b/Source/WebKit2/UIProcess/efl/BatteryProvider.h index d76336cd2..893d0f8ea 100644 --- a/Source/WebKit2/UIProcess/efl/BatteryProvider.h +++ b/Source/WebKit2/UIProcess/efl/BatteryProvider.h @@ -31,8 +31,8 @@ #include "BatteryProviderEfl.h" #include "BatteryProviderEflClient.h" #include "BatteryStatus.h" -#include "WebContext.h" #include <WebKit2/WKBase.h> +#include <WebKit2/WKRetainPtr.h> #include <wtf/PassRefPtr.h> namespace WebKit { @@ -40,18 +40,18 @@ namespace WebKit { class BatteryProvider : public RefCounted<BatteryProvider>, public WebCore::BatteryProviderEflClient { public: virtual ~BatteryProvider(); - static PassRefPtr<BatteryProvider> create(PassRefPtr<WebContext>); + static PassRefPtr<BatteryProvider> create(WKContextRef); void startUpdating(); void stopUpdating(); private: - explicit BatteryProvider(PassRefPtr<WebContext>); + explicit BatteryProvider(WKContextRef); // BatteryProviderEflClient interface. virtual void didChangeBatteryStatus(const AtomicString& eventType, PassRefPtr<WebCore::BatteryStatus>); - RefPtr<WebContext> m_context; + WKRetainPtr<WKBatteryManagerRef> m_batteryManager; WebCore::BatteryProviderEfl m_provider; }; diff --git a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp index 5f20c175b..2cc4b3013 100644 --- a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp @@ -26,8 +26,7 @@ #include "config.h" #include "ContextHistoryClientEfl.h" -#include "DownloadProxy.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKAPICast.h" #include "WKContext.h" #include "WKEinaSharedString.h" @@ -54,7 +53,7 @@ void ContextHistoryClientEfl::didNavigateWithNavigationData(WKContextRef, WKPage return; RefPtr<EwkNavigationData> navigationDataEwk = EwkNavigationData::create(navigationData); - historyClient->m_navigate(EwkViewImpl::viewFromPageViewMap(page), navigationDataEwk.get(), historyClient->m_userData); + historyClient->m_navigate(EwkView::toEvasObject(page), navigationDataEwk.get(), historyClient->m_userData); } void ContextHistoryClientEfl::didPerformClientRedirect(WKContextRef, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef, const void* clientInfo) @@ -67,7 +66,7 @@ void ContextHistoryClientEfl::didPerformClientRedirect(WKContextRef, WKPageRef p WKEinaSharedString sourceURLString(sourceURL); WKEinaSharedString destinationURLString(destinationURL); - historyClient->m_clientRedirect(EwkViewImpl::viewFromPageViewMap(page), sourceURLString, destinationURLString, historyClient->m_userData); + historyClient->m_clientRedirect(EwkView::toEvasObject(page), sourceURLString, destinationURLString, historyClient->m_userData); } void ContextHistoryClientEfl::didPerformServerRedirect(WKContextRef, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef, const void* clientInfo) @@ -80,7 +79,7 @@ void ContextHistoryClientEfl::didPerformServerRedirect(WKContextRef, WKPageRef p WKEinaSharedString sourceURLString(sourceURL); WKEinaSharedString destinationURLString(destinationURL); - historyClient->m_serverRedirect(EwkViewImpl::viewFromPageViewMap(page), sourceURLString, destinationURLString, historyClient->m_userData); + historyClient->m_serverRedirect(EwkView::toEvasObject(page), sourceURLString, destinationURLString, historyClient->m_userData); } void ContextHistoryClientEfl::didUpdateHistoryTitle(WKContextRef, WKPageRef page, WKStringRef title, WKURLRef URL, WKFrameRef, const void* clientInfo) @@ -93,7 +92,7 @@ void ContextHistoryClientEfl::didUpdateHistoryTitle(WKContextRef, WKPageRef page WKEinaSharedString titleString(title); WKEinaSharedString stringURL(URL); - historyClient->m_titleUpdated(EwkViewImpl::viewFromPageViewMap(page), titleString, stringURL, historyClient->m_userData); + historyClient->m_titleUpdated(EwkView::toEvasObject(page), titleString, stringURL, historyClient->m_userData); } void ContextHistoryClientEfl::populateVisitedLinks(WKContextRef, const void* clientInfo) @@ -106,15 +105,16 @@ void ContextHistoryClientEfl::populateVisitedLinks(WKContextRef, const void* cli historyClient->m_populateVisitedLinks(historyClient->m_userData); } -ContextHistoryClientEfl::ContextHistoryClientEfl(PassRefPtr<WebContext> context) - : m_userData(0) +ContextHistoryClientEfl::ContextHistoryClientEfl(WKContextRef context) + : m_context(context) + , m_userData(0) , m_navigate(0) , m_clientRedirect(0) , m_serverRedirect(0) , m_titleUpdated(0) , m_populateVisitedLinks(0) { - ASSERT(context); + ASSERT(m_context); WKContextHistoryClient wkHistoryClient; memset(&wkHistoryClient, 0, sizeof(WKContextHistoryClient)); @@ -128,7 +128,12 @@ ContextHistoryClientEfl::ContextHistoryClientEfl(PassRefPtr<WebContext> context) wkHistoryClient.didUpdateHistoryTitle = didUpdateHistoryTitle; wkHistoryClient.populateVisitedLinks = populateVisitedLinks; - context->initializeHistoryClient(&wkHistoryClient); + WKContextSetHistoryClient(m_context.get(), &wkHistoryClient); +} + +ContextHistoryClientEfl::~ContextHistoryClientEfl() +{ + WKContextSetHistoryClient(m_context.get(), 0); } void ContextHistoryClientEfl::setCallbacks(Ewk_History_Navigation_Cb navigate, Ewk_History_Client_Redirection_Cb clientRedirect, Ewk_History_Server_Redirection_Cb serverRedirect, Ewk_History_Title_Update_Cb titleUpdate, Ewk_History_Populate_Visited_Links_Cb populateVisitedLinks, void* data) diff --git a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h b/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h index b670271be..ffebfab28 100644 --- a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h @@ -26,24 +26,26 @@ #ifndef ContextHistoryClientEfl_h #define ContextHistoryClientEfl_h -#include "WebContext.h" #include "ewk_context.h" #include <WebKit2/WKBase.h> +#include <WebKit2/WKRetainPtr.h> #include <wtf/PassOwnPtr.h> namespace WebKit { class ContextHistoryClientEfl { public: - static PassOwnPtr<ContextHistoryClientEfl> create(PassRefPtr<WebContext> context) + static PassOwnPtr<ContextHistoryClientEfl> create(WKContextRef context) { return adoptPtr(new ContextHistoryClientEfl(context)); } + ~ContextHistoryClientEfl(); + void setCallbacks(Ewk_History_Navigation_Cb, Ewk_History_Client_Redirection_Cb, Ewk_History_Server_Redirection_Cb, Ewk_History_Title_Update_Cb, Ewk_History_Populate_Visited_Links_Cb, void*); private: - explicit ContextHistoryClientEfl(PassRefPtr<WebContext>); + explicit ContextHistoryClientEfl(WKContextRef); static void didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef, WKFrameRef, const void*); static void didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef, WKFrameRef, const void*); @@ -51,6 +53,7 @@ private: static void didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef, WKURLRef, WKFrameRef, const void*); static void populateVisitedLinks(WKContextRef, const void*); + WKRetainPtr<WKContextRef> m_context; void* m_userData; Ewk_History_Navigation_Cb m_navigate; Ewk_History_Client_Redirection_Cb m_clientRedirect; diff --git a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp index 7a86028e0..16ca07d3e 100644 --- a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp @@ -26,12 +26,9 @@ #include "config.h" #include "ContextMenuClientEfl.h" -#include "EwkViewImpl.h" -#include "NotImplemented.h" +#include "EwkView.h" #include "WKArray.h" #include "WKPage.h" -#include "WebContextMenuItem.h" -#include <Evas.h> using namespace WebKit; @@ -40,10 +37,25 @@ static inline ContextMenuClientEfl* toContextClientEfl(const void* clientInfo) return static_cast<ContextMenuClientEfl*>(const_cast<void*>(clientInfo)); } -ContextMenuClientEfl::ContextMenuClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +static void customContextMenuItemSelected(WKPageRef, WKContextMenuItemRef contextMenuItem, const void* clientInfo) { - WKPageRef pageRef = m_viewImpl->wkPage(); + toContextClientEfl(clientInfo)->view()->customContextMenuItemSelected(contextMenuItem); +} + +static void showContextMenu(WKPageRef, WKPoint menuLocation, WKArrayRef menuItems, const void* clientInfo) +{ + toContextClientEfl(clientInfo)->view()->showContextMenu(menuLocation, menuItems); +} + +static void hideContextMenu(WKPageRef, const void* clientInfo) +{ + toContextClientEfl(clientInfo)->view()->hideContextMenu(); +} + +ContextMenuClientEfl::ContextMenuClientEfl(EwkView* view) + : m_view(view) +{ + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKPageContextMenuClient contextMenuClient; @@ -51,14 +63,12 @@ ContextMenuClientEfl::ContextMenuClientEfl(EwkViewImpl* viewImpl) contextMenuClient.version = kWKPageContextMenuClientCurrentVersion; contextMenuClient.clientInfo = this; contextMenuClient.getContextMenuFromProposedMenu_deprecatedForUseWithV0 = 0; - contextMenuClient.customContextMenuItemSelected = 0; + contextMenuClient.customContextMenuItemSelected = customContextMenuItemSelected; contextMenuClient.contextMenuDismissed = 0; contextMenuClient.getContextMenuFromProposedMenu = 0; + contextMenuClient.showContextMenu = showContextMenu; + contextMenuClient.hideContextMenu = hideContextMenu; WKPageSetPageContextMenuClient(pageRef, &contextMenuClient); } -void ContextMenuClientEfl::getContextMenuFromProposedMenu(WKPageRef, WKArrayRef, WKArrayRef*, WKHitTestResultRef, WKTypeRef, const void*) -{ - notImplemented(); -} diff --git a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.h b/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.h index b29e4ed3c..f036b3fcf 100644 --- a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.h @@ -26,30 +26,25 @@ #ifndef ContextMenuClientEfl_h #define ContextMenuClientEfl_h -#include "WKRetainPtr.h" -#include "ewk_context.h" -#include <WebKit2/WKBase.h> -#include <wtf/HashMap.h> #include <wtf/PassOwnPtr.h> -#include <wtf/text/WTFString.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class ContextMenuClientEfl { public: - static PassOwnPtr<ContextMenuClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<ContextMenuClientEfl> create(EwkView* viewImpl) { return adoptPtr(new ContextMenuClientEfl(viewImpl)); } - static void getContextMenuFromProposedMenu(WKPageRef, WKArrayRef proposedMenu, WKArrayRef* newMenu, WKHitTestResultRef, WKTypeRef userData, const void* clientInfo); + EwkView* view() { return m_view; } private: - explicit ContextMenuClientEfl(EwkViewImpl*); + explicit ContextMenuClientEfl(EwkView*); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp b/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp index dff66a630..0ae172a71 100644 --- a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp @@ -26,9 +26,9 @@ #include "config.h" #include "DownloadManagerEfl.h" -#include "DownloadProxy.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKContext.h" +#include "WKDownload.h" #include "WKString.h" #include "ewk_context_private.h" #include "ewk_error_private.h" @@ -45,14 +45,14 @@ static inline DownloadManagerEfl* toDownloadManagerEfl(const void* clientInfo) WKStringRef DownloadManagerEfl::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef wkDownload, WKStringRef filename, bool* /*allowOverwrite*/, const void* clientInfo) { - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->downloadJob(toImpl(wkDownload)->downloadID()); + EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); ASSERT(download); download->setSuggestedFileName(toImpl(filename)->string().utf8().data()); // We send the new download signal on the Ewk_View only once we have received the response // and the suggested file name. - download->viewImpl()->smartCallback<DownloadJobRequested>().call(download); + download->view()->smartCallback<DownloadJobRequested>().call(download); // DownloadSoup expects the destination to be a URL. String destination = ASCIILiteral("file://") + String::fromUTF8(download->destination()); @@ -62,14 +62,14 @@ WKStringRef DownloadManagerEfl::decideDestinationWithSuggestedFilename(WKContext void DownloadManagerEfl::didReceiveResponse(WKContextRef, WKDownloadRef wkDownload, WKURLResponseRef wkResponse, const void* clientInfo) { - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->downloadJob(toImpl(wkDownload)->downloadID()); + EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); ASSERT(download); download->setResponse(EwkUrlResponse::create(wkResponse)); } void DownloadManagerEfl::didCreateDestination(WKContextRef, WKDownloadRef wkDownload, WKStringRef /*path*/, const void* clientInfo) { - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->downloadJob(toImpl(wkDownload)->downloadID()); + EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); ASSERT(download); download->setState(EWK_DOWNLOAD_JOB_STATE_DOWNLOADING); @@ -77,7 +77,7 @@ void DownloadManagerEfl::didCreateDestination(WKContextRef, WKDownloadRef wkDown void DownloadManagerEfl::didReceiveData(WKContextRef, WKDownloadRef wkDownload, uint64_t length, const void* clientInfo) { - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->downloadJob(toImpl(wkDownload)->downloadID()); + EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); ASSERT(download); download->incrementReceivedData(length); } @@ -85,42 +85,39 @@ void DownloadManagerEfl::didReceiveData(WKContextRef, WKDownloadRef wkDownload, void DownloadManagerEfl::didFail(WKContextRef, WKDownloadRef wkDownload, WKErrorRef error, const void* clientInfo) { DownloadManagerEfl* downloadManager = toDownloadManagerEfl(clientInfo); - uint64_t downloadId = toImpl(wkDownload)->downloadID(); - EwkDownloadJob* download = downloadManager->downloadJob(downloadId); + EwkDownloadJob* download = downloadManager->ewkDownloadJob(wkDownload); ASSERT(download); OwnPtr<EwkError> ewkError = EwkError::create(error); download->setState(EWK_DOWNLOAD_JOB_STATE_FAILED); Ewk_Download_Job_Error downloadError = { download, ewkError.get() }; - download->viewImpl()->smartCallback<DownloadJobFailed>().call(&downloadError); - downloadManager->unregisterDownloadJob(downloadId); + download->view()->smartCallback<DownloadJobFailed>().call(&downloadError); + downloadManager->unregisterDownloadJob(wkDownload); } void DownloadManagerEfl::didCancel(WKContextRef, WKDownloadRef wkDownload, const void* clientInfo) { DownloadManagerEfl* downloadManager = toDownloadManagerEfl(clientInfo); - uint64_t downloadId = toImpl(wkDownload)->downloadID(); - EwkDownloadJob* download = downloadManager->downloadJob(downloadId); + EwkDownloadJob* download = downloadManager->ewkDownloadJob(wkDownload); ASSERT(download); download->setState(EWK_DOWNLOAD_JOB_STATE_CANCELLED); - download->viewImpl()->smartCallback<DownloadJobCancelled>().call(download); - downloadManager->unregisterDownloadJob(downloadId); + download->view()->smartCallback<DownloadJobCancelled>().call(download); + downloadManager->unregisterDownloadJob(wkDownload); } void DownloadManagerEfl::didFinish(WKContextRef, WKDownloadRef wkDownload, const void* clientInfo) { DownloadManagerEfl* downloadManager = toDownloadManagerEfl(clientInfo); - uint64_t downloadId = toImpl(wkDownload)->downloadID(); - EwkDownloadJob* download = downloadManager->downloadJob(downloadId); + EwkDownloadJob* download = downloadManager->ewkDownloadJob(wkDownload); ASSERT(download); download->setState(EWK_DOWNLOAD_JOB_STATE_FINISHED); - download->viewImpl()->smartCallback<DownloadJobFinished>().call(download); - downloadManager->unregisterDownloadJob(downloadId); + download->view()->smartCallback<DownloadJobFinished>().call(download); + downloadManager->unregisterDownloadJob(wkDownload); } -DownloadManagerEfl::DownloadManagerEfl(EwkContext* context) +DownloadManagerEfl::DownloadManagerEfl(WKContextRef context) : m_context(context) { WKContextDownloadClient wkDownloadClient; @@ -136,12 +133,17 @@ DownloadManagerEfl::DownloadManagerEfl(EwkContext* context) wkDownloadClient.didFail = didFail; wkDownloadClient.didFinish = didFinish; - WKContextSetDownloadClient(toAPI(context->webContext().get()), &wkDownloadClient); + WKContextSetDownloadClient(m_context.get(), &wkDownloadClient); } -void DownloadManagerEfl::registerDownload(DownloadProxy* download, EwkViewImpl* viewImpl) +DownloadManagerEfl::~DownloadManagerEfl() { - uint64_t downloadId = download->downloadID(); + WKContextSetDownloadClient(m_context.get(), 0); +} + +void DownloadManagerEfl::registerDownloadJob(WKDownloadRef download, EwkView* viewImpl) +{ + uint64_t downloadId = WKDownloadGetID(download); if (m_downloadJobs.contains(downloadId)) return; @@ -149,14 +151,14 @@ void DownloadManagerEfl::registerDownload(DownloadProxy* download, EwkViewImpl* m_downloadJobs.add(downloadId, ewkDownload); } -EwkDownloadJob* DownloadManagerEfl::downloadJob(uint64_t id) const +EwkDownloadJob* DownloadManagerEfl::ewkDownloadJob(WKDownloadRef wkDownload) { - return m_downloadJobs.get(id).get(); + return m_downloadJobs.get(WKDownloadGetID(wkDownload)); } -void DownloadManagerEfl::unregisterDownloadJob(uint64_t id) +void DownloadManagerEfl::unregisterDownloadJob(WKDownloadRef wkDownload) { - m_downloadJobs.remove(id); + m_downloadJobs.remove(WKDownloadGetID(wkDownload)); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.h b/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.h index 77516428b..0317a9d86 100644 --- a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.h +++ b/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.h @@ -27,29 +27,29 @@ #define DownloadManagerEfl_h #include "ewk_download_job_private.h" +#include <WebKit2/WKRetainPtr.h> #include <wtf/HashMap.h> #include <wtf/PassOwnPtr.h> #include <wtf/RefPtr.h> -class EwkContext; -class EwkDownloadJob; - namespace WebKit { class DownloadManagerEfl { public: - static PassOwnPtr<DownloadManagerEfl> create(EwkContext* context) + static PassOwnPtr<DownloadManagerEfl> create(WKContextRef context) { return adoptPtr(new DownloadManagerEfl(context)); } - void registerDownload(DownloadProxy*, EwkViewImpl*); + ~DownloadManagerEfl(); + + void registerDownloadJob(WKDownloadRef, EwkView*); private: - explicit DownloadManagerEfl(EwkContext*); + explicit DownloadManagerEfl(WKContextRef); - EwkDownloadJob* downloadJob(uint64_t id) const; - void unregisterDownloadJob(uint64_t id); + EwkDownloadJob* ewkDownloadJob(WKDownloadRef); + void unregisterDownloadJob(WKDownloadRef); static WKStringRef decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool* allowOverwrite, const void* clientInfo); static void didReceiveResponse(WKContextRef, WKDownloadRef, WKURLResponseRef, const void* clientInfo); @@ -59,7 +59,7 @@ private: static void didCancel(WKContextRef, WKDownloadRef, const void* clientInfo); static void didFinish(WKContextRef, WKDownloadRef, const void* clientInfo); - EwkContext* m_context; + WKRetainPtr<WKContextRef> m_context; HashMap<uint64_t, RefPtr<EwkDownloadJob> > m_downloadJobs; }; diff --git a/Source/WebKit2/UIProcess/Network/mac/NetworkProcessManagerMac.mm b/Source/WebKit2/UIProcess/efl/EwkTouchEvent.cpp index eaf9888a5..97cd70eb6 100644 --- a/Source/WebKit2/UIProcess/Network/mac/NetworkProcessManagerMac.mm +++ b/Source/WebKit2/UIProcess/efl/EwkTouchEvent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,21 +23,21 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#import "config.h" -#import "NetworkProcessManager.h" +#include "config.h" +#include "EwkTouchEvent.h" -#if ENABLE(NETWORK_PROCESS) - -#import "NetworkProcessProxy.h" +#if ENABLE(TOUCH_EVENTS) namespace WebKit { -void NetworkProcessManager::setApplicationIsOccluded(bool applicationIsOccluded) +EwkTouchEvent::EwkTouchEvent(WKEventType type, WKArrayRef touchPoints, WKEventModifiers modifiers, double timestamp) + : m_eventType(type) + , m_touchPoints(touchPoints) + , m_modifiers(modifiers) + , m_timestamp(timestamp) { - if (m_networkProcess) - return m_networkProcess->setApplicationIsOccluded(applicationIsOccluded); } } // namespace WebKit -#endif // ENABLE(NETWORK_PROCESS) +#endif // ENABLE(TOUCH_EVENTS) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_intent_private.h b/Source/WebKit2/UIProcess/efl/EwkTouchEvent.h index 199ec79c1..312c3d05b 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent_private.h +++ b/Source/WebKit2/UIProcess/efl/EwkTouchEvent.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,53 +23,46 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ewk_intent_private_h -#define ewk_intent_private_h +#ifndef EwkTouchEvent_h +#define EwkTouchEvent_h -#if ENABLE(WEB_INTENTS) +#if ENABLE(TOUCH_EVENTS) -#include "WKEinaSharedString.h" -#include "WKIntentData.h" +#include "APIObject.h" +#include "WKArray.h" +#include "WKEventEfl.h" #include "WKRetainPtr.h" -#include "ewk_object_private.h" -#include <WebKit2/WKBase.h> #include <wtf/PassRefPtr.h> -#include <wtf/text/WTFString.h> namespace WebKit { -class WebIntentData; -} -/** - * \struct EwkIntent - * @brief Contains the intent data. - */ -class EwkIntent : public EwkObject { +class EwkTouchEvent : public APIObject { public: - EWK_OBJECT_DECLARE(EwkIntent) + static const APIObject::Type APIType = TypeTouchEvent; - static PassRefPtr<EwkIntent> create(WKIntentDataRef intentRef) + static PassRefPtr<EwkTouchEvent> create(WKEventType type, WKArrayRef touchPoints, WKEventModifiers modifiers, double timestamp) { - return adoptRef(new EwkIntent(intentRef)); + return adoptRef(new EwkTouchEvent(type, touchPoints, modifiers, timestamp)); } - WebKit::WebIntentData* webIntentData() const; - const char* action() const; - const char* type() const; - const char* service() const; - WKRetainPtr<WKArrayRef> suggestions() const; - String extra(const char* key) const; - WKRetainPtr<WKArrayRef> extraKeys() const; + WKEventType eventType() const { return m_eventType; } + WKArrayRef touchPoints() const { return m_touchPoints.get(); } + WKEventModifiers modifiers() const { return m_modifiers; } + double timestamp() const { return m_timestamp; } private: - explicit EwkIntent(WKIntentDataRef intentRef); + EwkTouchEvent(WKEventType, WKArrayRef, WKEventModifiers, double timestamp); + + virtual APIObject::Type type() const { return APIType; } - WKRetainPtr<WKIntentDataRef> m_wkIntent; - WKEinaSharedString m_action; - WKEinaSharedString m_type; - WKEinaSharedString m_service; + WKEventType m_eventType; + WKRetainPtr<WKArrayRef> m_touchPoints; + WKEventModifiers m_modifiers; + double m_timestamp; }; -#endif // ENABLE(WEB_INTENTS) +} // namespace WebKit + +#endif // ENABLE(TOUCH_EVENTS) -#endif // ewk_intent_private_h +#endif /* EwkTouchEvent_h */ diff --git a/Source/WebKit2/UIProcess/efl/EwkTouchPoint.cpp b/Source/WebKit2/UIProcess/efl/EwkTouchPoint.cpp new file mode 100644 index 000000000..6efa67d9f --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/EwkTouchPoint.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "EwkTouchPoint.h" + +#if ENABLE(TOUCH_EVENTS) + +namespace WebKit { + +EwkTouchPoint::EwkTouchPoint(uint32_t id, WKTouchPointState state, const WKPoint& screenPosition, const WKPoint& position, const WKSize& radius, float rotationAngle, float forceFactor) + : m_id(id) + , m_state(state) + , m_screenPosition(screenPosition) + , m_position(position) + , m_radius(radius) + , m_rotationAngle(rotationAngle) + , m_forceFactor(forceFactor) +{ +} + +} // namespace WebKit + +#endif // ENABLE(TOUCH_EVENTS) diff --git a/Source/WebKit2/UIProcess/efl/EwkTouchPoint.h b/Source/WebKit2/UIProcess/efl/EwkTouchPoint.h new file mode 100644 index 000000000..943bcbbd1 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/EwkTouchPoint.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef EwkTouchPoint_h +#define EwkTouchPoint_h + +#if ENABLE(TOUCH_EVENTS) + +#include "APIObject.h" +#include "WKArray.h" +#include "WKEventEfl.h" +#include "WKRetainPtr.h" +#include <wtf/PassRefPtr.h> + +namespace WebKit { + +class EwkTouchPoint : public APIObject { +public: + static const APIObject::Type APIType = TypeTouchPoint; + + static PassRefPtr<EwkTouchPoint> create(uint32_t id, WKTouchPointState state, const WKPoint& screenPosition, const WKPoint& position, const WKSize& radius, float rotationAngle = 0, float forceFactor = 1) + { + return adoptRef(new EwkTouchPoint(id, state, screenPosition, position, radius, rotationAngle, forceFactor)); + } + + uint32_t id() const { return m_id; } + WKTouchPointState state() const { return m_state; } + WKPoint screenPosition() const { return m_screenPosition; } + WKPoint position() const { return m_position; } + WKSize radius() const { return m_radius; } + float rotationAngle() const { return m_rotationAngle; } + float forceFactor() const { return m_forceFactor; } + +private: + EwkTouchPoint(uint32_t id, WKTouchPointState, const WKPoint&, const WKPoint&, const WKSize&, float rotationAngle, float forceFactor); + + virtual APIObject::Type type() const { return APIType; } + + uint32_t m_id; + WKTouchPointState m_state; + WKPoint m_screenPosition; + WKPoint m_position; + WKSize m_radius; + float m_rotationAngle; + float m_forceFactor; +}; + +} // namespace WebKit + +#endif // ENABLE(TOUCH_EVENTS) + +#endif /* EwkTouchPoint_h */ diff --git a/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp b/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp index 5b2e88ea2..334b4b5bd 100644 --- a/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp @@ -27,7 +27,7 @@ #include "config.h" #include "FindClientEfl.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKPage.h" using namespace EwkViewCallbacks; @@ -42,20 +42,20 @@ static inline FindClientEfl* toFindClientEfl(const void* clientInfo) void FindClientEfl::didFindString(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo) { FindClientEfl* findClient = toFindClientEfl(clientInfo); - findClient->m_viewImpl->smartCallback<TextFound>().call(&matchCount); + findClient->m_view->smartCallback<TextFound>().call(&matchCount); } void FindClientEfl::didFailToFindString(WKPageRef, WKStringRef, const void* clientInfo) { FindClientEfl* findClient = toFindClientEfl(clientInfo); unsigned matchCount = 0; - findClient->m_viewImpl->smartCallback<TextFound>().call(&matchCount); + findClient->m_view->smartCallback<TextFound>().call(&matchCount); } -FindClientEfl::FindClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +FindClientEfl::FindClientEfl(EwkView* viewImpl) + : m_view(viewImpl) { - WKPageRef pageRef = m_viewImpl->wkPage(); + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKPageFindClient findClient; diff --git a/Source/WebKit2/UIProcess/efl/FindClientEfl.h b/Source/WebKit2/UIProcess/efl/FindClientEfl.h index 274460b1a..dd12e2f94 100644 --- a/Source/WebKit2/UIProcess/efl/FindClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/FindClientEfl.h @@ -30,24 +30,24 @@ #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class FindClientEfl { public: - static PassOwnPtr<FindClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<FindClientEfl> create(EwkView* viewImpl) { return adoptPtr(new FindClientEfl(viewImpl)); } private: - explicit FindClientEfl(EwkViewImpl*); + explicit FindClientEfl(EwkView*); static void didFindString(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo); static void didFailToFindString(WKPageRef, WKStringRef, const void* clientInfo); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp b/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp index 001bba466..155bea22c 100644 --- a/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp @@ -26,7 +26,7 @@ #include "config.h" #include "FormClientEfl.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKPage.h" #include "ewk_form_submission_request_private.h" @@ -44,13 +44,13 @@ void FormClientEfl::willSubmitForm(WKPageRef, WKFrameRef /*frame*/, WKFrameRef / FormClientEfl* formClient = toFormClientEfl(clientInfo); RefPtr<EwkFormSubmissionRequest> request = EwkFormSubmissionRequest::create(values, listener); - formClient->m_viewImpl->smartCallback<NewFormSubmissionRequest>().call(request.get()); + formClient->m_view->smartCallback<NewFormSubmissionRequest>().call(request.get()); } -FormClientEfl::FormClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +FormClientEfl::FormClientEfl(EwkView* viewImpl) + : m_view(viewImpl) { - WKPageRef pageRef = m_viewImpl->wkPage(); + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKPageFormClient formClient; diff --git a/Source/WebKit2/UIProcess/efl/FormClientEfl.h b/Source/WebKit2/UIProcess/efl/FormClientEfl.h index 66e060c14..666c44bb1 100644 --- a/Source/WebKit2/UIProcess/efl/FormClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/FormClientEfl.h @@ -29,23 +29,23 @@ #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class FormClientEfl { public: - static PassOwnPtr<FormClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<FormClientEfl> create(EwkView* viewImpl) { return adoptPtr(new FormClientEfl(viewImpl)); } private: - explicit FormClientEfl(EwkViewImpl*); + explicit FormClientEfl(EwkView*); static void willSubmitForm(WKPageRef, WKFrameRef, WKFrameRef, WKDictionaryRef values, WKTypeRef userData, WKFormSubmissionListenerRef, const void* clientInfo); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp b/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp index 531e3bead..87df14208 100644 --- a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp @@ -21,17 +21,18 @@ #include "config.h" #include "InputMethodContextEfl.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WebPageProxy.h" #include <Ecore_Evas.h> #include <Ecore_IMF_Evas.h> +#include <WebCore/Editor.h> using namespace WebCore; namespace WebKit { -InputMethodContextEfl::InputMethodContextEfl(EwkViewImpl* viewImpl, PassOwnPtr<Ecore_IMF_Context> context) - : m_viewImpl(viewImpl) +InputMethodContextEfl::InputMethodContextEfl(EwkView* view, PassOwnPtr<Ecore_IMF_Context> context) + : m_view(view) , m_context(context) , m_focused(false) { @@ -50,14 +51,14 @@ void InputMethodContextEfl::onIMFInputSequenceComplete(void* data, Ecore_IMF_Con if (!eventInfo || !inputMethodContext->m_focused) return; - inputMethodContext->m_viewImpl->page()->confirmComposition(String::fromUTF8(static_cast<char*>(eventInfo))); + inputMethodContext->m_view->page()->confirmComposition(String::fromUTF8(static_cast<char*>(eventInfo))); } void InputMethodContextEfl::onIMFPreeditSequenceChanged(void* data, Ecore_IMF_Context* context, void*) { InputMethodContextEfl* inputMethodContext = static_cast<InputMethodContextEfl*>(data); - if (!inputMethodContext->m_viewImpl->page()->focusedFrame() || !inputMethodContext->m_focused) + if (!inputMethodContext->m_view->page()->focusedFrame() || !inputMethodContext->m_focused) return; char* buffer = 0; @@ -69,7 +70,7 @@ void InputMethodContextEfl::onIMFPreeditSequenceChanged(void* data, Ecore_IMF_Co free(buffer); Vector<CompositionUnderline> underlines; underlines.append(CompositionUnderline(0, preeditString.length(), Color(0, 0, 0), false)); - inputMethodContext->m_viewImpl->page()->setComposition(preeditString, underlines, 0); + inputMethodContext->m_view->page()->setComposition(preeditString, underlines, 0); } PassOwnPtr<Ecore_IMF_Context> InputMethodContextEfl::createIMFContext(Evas* canvas) @@ -107,7 +108,7 @@ void InputMethodContextEfl::updateTextInputState() if (!m_context) return; - const EditorState& editor = m_viewImpl->page()->editorState(); + const EditorState& editor = m_view->page()->editorState(); if (editor.isContentEditable) { if (m_focused) @@ -121,7 +122,7 @@ void InputMethodContextEfl::updateTextInputState() return; if (editor.hasComposition) - m_viewImpl->page()->cancelComposition(); + m_view->page()->cancelComposition(); m_focused = false; ecore_imf_context_reset(m_context.get()); diff --git a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h b/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h index aaf51b936..12de0acaa 100644 --- a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h +++ b/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h @@ -26,7 +26,7 @@ #include <wtf/OwnPtr.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { @@ -34,7 +34,7 @@ class WebPageProxy; class InputMethodContextEfl { public: - static PassOwnPtr<InputMethodContextEfl> create(EwkViewImpl* viewImpl, Evas* canvas) + static PassOwnPtr<InputMethodContextEfl> create(EwkView* viewImpl, Evas* canvas) { OwnPtr<Ecore_IMF_Context> context = createIMFContext(canvas); if (!context) @@ -49,13 +49,13 @@ public: void updateTextInputState(); private: - InputMethodContextEfl(EwkViewImpl*, PassOwnPtr<Ecore_IMF_Context>); + InputMethodContextEfl(EwkView*, PassOwnPtr<Ecore_IMF_Context>); static PassOwnPtr<Ecore_IMF_Context> createIMFContext(Evas* canvas); static void onIMFInputSequenceComplete(void* data, Ecore_IMF_Context*, void* eventInfo); static void onIMFPreeditSequenceChanged(void* data, Ecore_IMF_Context*, void* eventInfo); - EwkViewImpl* m_viewImpl; + EwkView* m_view; OwnPtr<Ecore_IMF_Context> m_context; bool m_focused; }; diff --git a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp b/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp index 556837f2c..de7f05f53 100644 --- a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp +++ b/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp @@ -29,8 +29,6 @@ #if ENABLE(NETWORK_INFO) #include "WKNetworkInfoManager.h" -#include "WebContext.h" -#include "WebNetworkInfoManagerProxy.h" #include <NotImplemented.h> using namespace WebKit; @@ -60,16 +58,19 @@ static bool isMeteredCallback(WKNetworkInfoManagerRef, const void* clientInfo) return toNetworkInfoProvider(clientInfo)->metered(); } -PassRefPtr<NetworkInfoProvider> NetworkInfoProvider::create(PassRefPtr<WebContext> context) +PassRefPtr<NetworkInfoProvider> NetworkInfoProvider::create(WKContextRef context) { return adoptRef(new NetworkInfoProvider(context)); } -NetworkInfoProvider::NetworkInfoProvider(PassRefPtr<WebContext> context) +NetworkInfoProvider::NetworkInfoProvider(WKContextRef context) : m_context(context) { ASSERT(m_context); + WKNetworkInfoManagerRef wkNetworkInfoManager = WKContextGetNetworkInfoManager(m_context.get()); + ASSERT(wkNetworkInfoManager); + WKNetworkInfoProvider wkNetworkInfoProvider = { kWKNetworkInfoProviderCurrentVersion, this, // clientInfo @@ -79,14 +80,20 @@ NetworkInfoProvider::NetworkInfoProvider(PassRefPtr<WebContext> context) isMeteredCallback }; - ASSERT(m_context->networkInfoManagerProxy()); - m_context->networkInfoManagerProxy()->initializeProvider(&wkNetworkInfoProvider); + WKNetworkInfoManagerSetProvider(wkNetworkInfoManager, &wkNetworkInfoProvider); } NetworkInfoProvider::~NetworkInfoProvider() { - ASSERT(m_context->networkInfoManagerProxy()); - m_context->networkInfoManagerProxy()->initializeProvider(0); + WKNetworkInfoManagerRef wkNetworkInfoManager = WKContextGetNetworkInfoManager(m_context.get()); + ASSERT(wkNetworkInfoManager); + + WKNetworkInfoManagerSetProvider(wkNetworkInfoManager, 0); +} + +void NetworkInfoProvider::networkInfoControllerDestroyed() +{ + delete this; } double NetworkInfoProvider::bandwidth() const diff --git a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h b/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h index 6785a5b0e..bf72384aa 100644 --- a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h +++ b/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h @@ -28,10 +28,10 @@ #if ENABLE(NETWORK_INFO) -#include "WebContext.h" #include <NetworkInfoClient.h> #include <NetworkInfoProviderEfl.h> #include <WebKit2/WKBase.h> +#include <WebKit2/WKContext.h> #include <WebKit2/WKRetainPtr.h> #include <wtf/PassRefPtr.h> @@ -40,9 +40,11 @@ namespace WebKit { class NetworkInfoProvider : public RefCounted<NetworkInfoProvider>, public WebCore::NetworkInfoClient { public: virtual ~NetworkInfoProvider(); - static PassRefPtr<NetworkInfoProvider> create(PassRefPtr<WebContext>); + static PassRefPtr<NetworkInfoProvider> create(WKContextRef); // NetworkInfoClient interface. + virtual void networkInfoControllerDestroyed(); + virtual double bandwidth() const; virtual bool metered() const; @@ -50,9 +52,9 @@ public: virtual void stopUpdating(); private: - explicit NetworkInfoProvider(PassRefPtr<WebContext>); + explicit NetworkInfoProvider(WKContextRef); - RefPtr<WebContext> m_context; + WKRetainPtr<WKContextRef> m_context; WebCore::NetworkInfoProviderEfl m_provider; }; diff --git a/Source/WebKit2/UIProcess/efl/PageClientBase.cpp b/Source/WebKit2/UIProcess/efl/PageClientBase.cpp deleted file mode 100644 index b3d511b2e..000000000 --- a/Source/WebKit2/UIProcess/efl/PageClientBase.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PageClientBase.h" - -#include "DrawingAreaProxyImpl.h" -#include "EwkViewImpl.h" -#include "InputMethodContextEfl.h" -#include "LayerTreeCoordinatorProxy.h" -#include "LayerTreeRenderer.h" -#include "NativeWebKeyboardEvent.h" -#include "NotImplemented.h" -#include "TextureMapper.h" -#include "WebContext.h" -#include "WebContextMenuProxyEfl.h" -#include "WebPageGroup.h" -#include "WebPageProxy.h" -#include "WebPopupMenuProxyEfl.h" -#include "WebPreferences.h" -#include "ewk_context.h" -#include "ewk_context_private.h" -#include "ewk_download_job.h" -#include "ewk_download_job_private.h" -#include "ewk_private.h" -#include "ewk_view.h" - -using namespace WebCore; -using namespace EwkViewCallbacks; - -namespace WebKit { - -PageClientBase::PageClientBase(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) -{ -} - -PageClientBase::~PageClientBase() -{ -} - -EwkViewImpl* PageClientBase::viewImpl() const -{ - return m_viewImpl; -} - -// PageClient -PassOwnPtr<DrawingAreaProxy> PageClientBase::createDrawingAreaProxy() -{ - OwnPtr<DrawingAreaProxy> drawingArea = DrawingAreaProxyImpl::create(m_viewImpl->page()); - return drawingArea.release(); -} - -void PageClientBase::setViewNeedsDisplay(const WebCore::IntRect& rect) -{ - m_viewImpl->update(rect); -} - -void PageClientBase::displayView() -{ - notImplemented(); -} - -void PageClientBase::scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize&) -{ - setViewNeedsDisplay(scrollRect); -} - -WebCore::IntSize PageClientBase::viewSize() -{ - return m_viewImpl->size(); -} - -bool PageClientBase::isViewWindowActive() -{ - notImplemented(); - return true; -} - -bool PageClientBase::isViewFocused() -{ - return m_viewImpl->isFocused(); -} - -bool PageClientBase::isViewVisible() -{ - return m_viewImpl->isVisible(); -} - -bool PageClientBase::isViewInWindow() -{ - notImplemented(); - return true; -} - -void PageClientBase::processDidCrash() -{ - // Check if loading was ongoing, when web process crashed. - double loadProgress = ewk_view_load_progress_get(m_viewImpl->view()); - if (loadProgress >= 0 && loadProgress < 1) { - loadProgress = 1; - m_viewImpl->smartCallback<LoadProgress>().call(&loadProgress); - } - - m_viewImpl->smartCallback<TooltipTextUnset>().call(); - - bool handled = false; - m_viewImpl->smartCallback<WebProcessCrashed>().call(&handled); - - if (!handled) { - CString url = m_viewImpl->page()->urlAtProcessExit().utf8(); - WARN("WARNING: The web process experienced a crash on '%s'.\n", url.data()); - - // Display an error page - ewk_view_html_string_load(m_viewImpl->view(), "The web process has crashed.", 0, url.data()); - } -} - -void PageClientBase::didRelaunchProcess() -{ - const char* themePath = m_viewImpl->themePath(); - if (themePath) - m_viewImpl->page()->setThemePath(themePath); -} - -void PageClientBase::pageClosed() -{ - notImplemented(); -} - -void PageClientBase::toolTipChanged(const String&, const String& newToolTip) -{ - if (newToolTip.isEmpty()) - m_viewImpl->smartCallback<TooltipTextUnset>().call(); - else - m_viewImpl->smartCallback<TooltipTextSet>().call(newToolTip); -} - -void PageClientBase::setCursor(const Cursor& cursor) -{ - m_viewImpl->setCursor(cursor); -} - -void PageClientBase::setCursorHiddenUntilMouseMoves(bool) -{ - notImplemented(); -} - -void PageClientBase::registerEditCommand(PassRefPtr<WebEditCommandProxy> command, WebPageProxy::UndoOrRedo undoOrRedo) -{ - m_undoController.registerEditCommand(command, undoOrRedo); -} - -void PageClientBase::clearAllEditCommands() -{ - m_undoController.clearAllEditCommands(); -} - -bool PageClientBase::canUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - return m_undoController.canUndoRedo(undoOrRedo); -} - -void PageClientBase::executeUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - m_undoController.executeUndoRedo(undoOrRedo); -} - -IntPoint PageClientBase::screenToWindow(const IntPoint& point) -{ - notImplemented(); - return point; -} - -IntRect PageClientBase::windowToScreen(const IntRect&) -{ - notImplemented(); - return IntRect(); -} - -void PageClientBase::doneWithKeyEvent(const NativeWebKeyboardEvent&, bool) -{ - notImplemented(); -} - -#if ENABLE(TOUCH_EVENTS) -void PageClientBase::doneWithTouchEvent(const NativeWebTouchEvent&, bool /*wasEventHandled*/) -{ - notImplemented(); -} -#endif - -PassRefPtr<WebPopupMenuProxy> PageClientBase::createPopupMenuProxy(WebPageProxy* page) -{ - return WebPopupMenuProxyEfl::create(m_viewImpl, page); -} - -PassRefPtr<WebContextMenuProxy> PageClientBase::createContextMenuProxy(WebPageProxy* page) -{ - return WebContextMenuProxyEfl::create(m_viewImpl, page); -} - -#if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorChooserProxy> PageClientBase::createColorChooserProxy(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) -{ - notImplemented(); - return 0; -} -#endif - -void PageClientBase::setFindIndicator(PassRefPtr<FindIndicator>, bool, bool) -{ - notImplemented(); -} - -#if USE(ACCELERATED_COMPOSITING) -void PageClientBase::enterAcceleratedCompositingMode(const LayerTreeContext&) -{ - m_viewImpl->enterAcceleratedCompositingMode(); -} - -void PageClientBase::exitAcceleratedCompositingMode() -{ - m_viewImpl->exitAcceleratedCompositingMode(); -} - -void PageClientBase::updateAcceleratedCompositingMode(const LayerTreeContext&) -{ - notImplemented(); -} -#endif // USE(ACCELERATED_COMPOSITING) - -void PageClientBase::didChangeScrollbarsForMainFrame() const -{ - notImplemented(); -} - -void PageClientBase::didCommitLoadForMainFrame(bool) -{ - notImplemented(); -} - -void PageClientBase::didFinishLoadingDataForCustomRepresentation(const String&, const CoreIPC::DataReference&) -{ - notImplemented(); -} - -double PageClientBase::customRepresentationZoomFactor() -{ - notImplemented(); - return 0; -} - -void PageClientBase::setCustomRepresentationZoomFactor(double) -{ - notImplemented(); -} - -void PageClientBase::flashBackingStoreUpdates(const Vector<IntRect>&) -{ - notImplemented(); -} - -void PageClientBase::findStringInCustomRepresentation(const String&, FindOptions, unsigned) -{ - notImplemented(); -} - -void PageClientBase::countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned) -{ - notImplemented(); -} - -void PageClientBase::updateTextInputState() -{ - InputMethodContextEfl* inputMethodContext = m_viewImpl->inputMethodContext(); - if (inputMethodContext) - inputMethodContext->updateTextInputState(); -} - -void PageClientBase::handleDownloadRequest(DownloadProxy* download) -{ - EwkContext* context = m_viewImpl->ewkContext(); - context->downloadManager()->registerDownload(download, m_viewImpl); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageClientBase.h b/Source/WebKit2/UIProcess/efl/PageClientBase.h deleted file mode 100644 index 292b43539..000000000 --- a/Source/WebKit2/UIProcess/efl/PageClientBase.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PageClientBase_h -#define PageClientBase_h - -#include "DefaultUndoController.h" -#include "PageClient.h" -#include <Evas.h> - -class EwkViewImpl; - -namespace WebKit { - -class PageClientBase : public PageClient { -public: - virtual ~PageClientBase(); - - // Called from the view - virtual void didCommitLoad() = 0; - virtual void updateViewportSize(const WebCore::IntSize&) = 0; - virtual void didChangeContentsSize(const WebCore::IntSize&) = 0; - - EwkViewImpl* viewImpl() const; - -protected: - explicit PageClientBase(EwkViewImpl*); - - // PageClient - virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy(); - virtual void setViewNeedsDisplay(const WebCore::IntRect&); - virtual void displayView(); - virtual void scrollView(const WebCore::IntRect&, const WebCore::IntSize&); - virtual WebCore::IntSize viewSize(); - virtual bool isViewWindowActive(); - virtual bool isViewFocused(); - virtual bool isViewVisible(); - virtual bool isViewInWindow(); - - virtual void processDidCrash(); - virtual void didRelaunchProcess(); - virtual void pageClosed(); - - virtual void toolTipChanged(const String&, const String&); - - virtual void setCursor(const WebCore::Cursor&); - virtual void setCursorHiddenUntilMouseMoves(bool); - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&) = 0; - - virtual void registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo); - virtual void clearAllEditCommands(); - virtual bool canUndoRedo(WebPageProxy::UndoOrRedo); - virtual void executeUndoRedo(WebPageProxy::UndoOrRedo); - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&) = 0; - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&) = 0; - virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&); - virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&); - - void updateTextInputState(); - virtual void handleDownloadRequest(DownloadProxy*); - - virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool); -#if ENABLE(TOUCH_EVENTS) - virtual void doneWithTouchEvent(const NativeWebTouchEvent&, bool wasEventHandled); -#endif - - virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*); - virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); - -#if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorChooserProxy> createColorChooserProxy(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&); -#endif - - virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool, bool); -#if USE(ACCELERATED_COMPOSITING) - virtual void enterAcceleratedCompositingMode(const LayerTreeContext&); - virtual void exitAcceleratedCompositingMode(); - virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); -#endif - - virtual void didChangeScrollbarsForMainFrame() const; - - virtual void didCommitLoadForMainFrame(bool); - virtual void didFinishLoadingDataForCustomRepresentation(const String&, const CoreIPC::DataReference&); - virtual double customRepresentationZoomFactor(); - virtual void setCustomRepresentationZoomFactor(double); - - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>&); - virtual void findStringInCustomRepresentation(const String&, FindOptions, unsigned); - virtual void countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned); - -#if USE(TILED_BACKING_STORE) - virtual void pageDidRequestScroll(const WebCore::IntPoint&) = 0; - virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) = 0; - virtual void pageTransitionViewportReady() = 0; -#endif - -protected: - EwkViewImpl* m_viewImpl; - DefaultUndoController m_undoController; -}; - -} // namespace WebKit - -#endif // PageClientBase_h diff --git a/Source/WebKit2/UIProcess/efl/PageClientDefaultImpl.cpp b/Source/WebKit2/UIProcess/efl/PageClientDefaultImpl.cpp deleted file mode 100644 index ceff53468..000000000 --- a/Source/WebKit2/UIProcess/efl/PageClientDefaultImpl.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PageClientDefaultImpl.h" - -#include "EwkViewImpl.h" - -#if USE(TILED_BACKING_STORE) -#include "PageViewportController.h" -#include "PageViewportControllerClientEfl.h" -#endif - -using namespace WebCore; -using namespace EwkViewCallbacks; - -namespace WebKit { - -PageClientDefaultImpl::PageClientDefaultImpl(EwkViewImpl* viewImpl) - : PageClientBase(viewImpl) -{ -} - -void PageClientDefaultImpl::didCommitLoad() -{ -#if USE(TILED_BACKING_STORE) - ASSERT(m_pageViewportController); - m_pageViewportController->didCommitLoad(); -#endif -} - -void PageClientDefaultImpl::updateViewportSize(const WebCore::IntSize& size) -{ -#if USE(TILED_BACKING_STORE) - if (!m_pageViewportControllerClient) { - m_pageViewportControllerClient = PageViewportControllerClientEfl::create(m_viewImpl); - m_pageViewportController = adoptPtr(new PageViewportController(m_viewImpl->page(), m_pageViewportControllerClient.get())); - } - m_pageViewportControllerClient->updateViewportSize(size); -#else - UNUSED_PARAM(size); -#endif -} - -FloatRect PageClientDefaultImpl::convertToDeviceSpace(const FloatRect& userRect) -{ - FloatRect result = userRect; - result.scale(m_viewImpl->page()->deviceScaleFactor()); - return result; -} - -FloatRect PageClientDefaultImpl::convertToUserSpace(const FloatRect& deviceRect) -{ - FloatRect result = deviceRect; - result.scale(1 / m_viewImpl->page()->deviceScaleFactor()); - return result; -} - -void PageClientDefaultImpl::didChangeViewportProperties(const WebCore::ViewportAttributes& attr) -{ -#if USE(TILED_BACKING_STORE) - ASSERT(m_pageViewportController); - m_pageViewportController->didChangeViewportAttributes(attr); -#else - UNUSED_PARAM(attr); -#endif -} - -void PageClientDefaultImpl::didChangeContentsSize(const WebCore::IntSize& size) -{ -#if USE(TILED_BACKING_STORE) - ASSERT(m_pageViewportController); - m_pageViewportController->didChangeContentsSize(size); -#else - m_viewImpl->informContentsSizeChange(size); -#endif -} - -#if USE(TILED_BACKING_STORE) -void PageClientDefaultImpl::pageDidRequestScroll(const IntPoint& position) -{ - ASSERT(m_pageViewportController); - m_pageViewportController->pageDidRequestScroll(position); -} - -void PageClientDefaultImpl::didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) -{ - ASSERT(m_pageViewportController); - m_pageViewportController->didRenderFrame(contentsSize, coveredRect); -} - -void PageClientDefaultImpl::pageTransitionViewportReady() -{ - ASSERT(m_pageViewportController); - m_pageViewportController->pageTransitionViewportReady(); -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageClientDefaultImpl.h b/Source/WebKit2/UIProcess/efl/PageClientDefaultImpl.h deleted file mode 100644 index 1b9225112..000000000 --- a/Source/WebKit2/UIProcess/efl/PageClientDefaultImpl.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PageClientDefaultImpl_h -#define PageClientDefaultImpl_h - -#include "PageClientBase.h" -#include "PageViewportController.h" -#include "PageViewportControllerClientEfl.h" - - -namespace WebKit { - -class PageClientDefaultImpl : public PageClientBase { -public: - static PassOwnPtr<PageClientBase> create(EwkViewImpl* viewImpl) - { - return adoptPtr(new PageClientDefaultImpl(viewImpl)); - } - - virtual ~PageClientDefaultImpl() { } - - virtual void didCommitLoad(); - virtual void updateViewportSize(const WebCore::IntSize&); - - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&); - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&); - -private: - explicit PageClientDefaultImpl(EwkViewImpl*); - - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); - virtual void didChangeContentsSize(const WebCore::IntSize&); -#if USE(TILED_BACKING_STORE) - virtual void pageDidRequestScroll(const WebCore::IntPoint&); - virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect); - virtual void pageTransitionViewportReady(); - - OwnPtr<WebKit::PageViewportControllerClientEfl> m_pageViewportControllerClient; - OwnPtr<WebKit::PageViewportController> m_pageViewportController; -#endif -}; - -} // namespace WebKit - -#endif // PageClientDefaultImpl_h diff --git a/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp b/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp deleted file mode 100644 index f62b8671a..000000000 --- a/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PageClientLegacyImpl.h" - -#include "EwkViewImpl.h" -#include "LayerTreeCoordinatorProxy.h" -#include "NotImplemented.h" - -using namespace WebCore; -using namespace EwkViewCallbacks; - -namespace WebKit { - -PageClientLegacyImpl::PageClientLegacyImpl(EwkViewImpl* viewImpl) - : PageClientBase(viewImpl) -{ -} - -void PageClientLegacyImpl::didCommitLoad() -{ - m_viewImpl->update(); -} - -void PageClientLegacyImpl::updateViewportSize(const WebCore::IntSize& size) -{ -#if USE(TILED_BACKING_STORE) - m_viewImpl->page()->drawingArea()->setVisibleContentsRect(IntRect(m_viewImpl->discretePagePosition(), size), m_viewImpl->scaleFactor(), FloatPoint()); -#else - UNUSED_PARAM(size); -#endif -} - -FloatRect PageClientLegacyImpl::convertToDeviceSpace(const FloatRect& viewRect) -{ - notImplemented(); - return viewRect; -} - -FloatRect PageClientLegacyImpl::convertToUserSpace(const FloatRect& viewRect) -{ - notImplemented(); - return viewRect; -} - -void PageClientLegacyImpl::didChangeViewportProperties(const WebCore::ViewportAttributes&) -{ - m_viewImpl->update(); -} - -void PageClientLegacyImpl::didChangeContentsSize(const WebCore::IntSize& size) -{ -#if USE(TILED_BACKING_STORE) - // m_viewImpl->informContentSizeChanged will be called as a result of setContentsSize - m_viewImpl->page()->drawingArea()->layerTreeCoordinatorProxy()->setContentsSize(FloatSize(size.width(), size.height())); - m_viewImpl->update(); -#else - m_viewImpl->informContentsSizeChange(size); -#endif -} - -#if USE(TILED_BACKING_STORE) -void PageClientLegacyImpl::pageDidRequestScroll(const IntPoint& position) -{ - m_viewImpl->setPagePosition(FloatPoint(position)); - m_viewImpl->update(); -} - -void PageClientLegacyImpl::didRenderFrame(const WebCore::IntSize&, const WebCore::IntRect&) -{ - m_viewImpl->update(); -} - -void PageClientLegacyImpl::pageTransitionViewportReady() -{ - m_viewImpl->update(); -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp index 97ee5625f..8b961fb9c 100644 --- a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp @@ -26,15 +26,14 @@ #include "config.h" #include "PageLoadClientEfl.h" -#include "EwkViewImpl.h" +#include "EwkView.h" +#include "PageViewportController.h" #include "WKAPICast.h" #include "WKFrame.h" #include "WKPage.h" #include "ewk_auth_request_private.h" #include "ewk_back_forward_list_private.h" #include "ewk_error_private.h" -#include "ewk_intent_private.h" -#include "ewk_intent_service_private.h" #include "ewk_view.h" using namespace EwkViewCallbacks; @@ -51,33 +50,15 @@ void PageLoadClientEfl::didReceiveTitleForFrame(WKPageRef, WKStringRef title, WK if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - viewImpl->smartCallback<TitleChange>().call(toImpl(title)->string()); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + view->smartCallback<TitleChange>().call(toImpl(title)->string()); } -#if ENABLE(WEB_INTENTS) -void PageLoadClientEfl::didReceiveIntentForFrame(WKPageRef, WKFrameRef, WKIntentDataRef intent, WKTypeRef, const void* clientInfo) -{ - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - RefPtr<EwkIntent> ewkIntent = EwkIntent::create(intent); - viewImpl->smartCallback<IntentRequest>().call(ewkIntent.get()); -} -#endif - -#if ENABLE(WEB_INTENTS_TAG) -void PageLoadClientEfl::registerIntentServiceForFrame(WKPageRef, WKFrameRef, WKIntentServiceInfoRef serviceInfo, WKTypeRef, const void* clientInfo) -{ - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - RefPtr<EwkIntentService> ewkIntentService = EwkIntentService::create(serviceInfo); - viewImpl->smartCallback<IntentServiceRegistration>().call(ewkIntentService.get()); -} -#endif - void PageLoadClientEfl::didChangeProgress(WKPageRef page, const void* clientInfo) { - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); double progress = WKPageGetEstimatedProgress(page); - viewImpl->smartCallback<LoadProgress>().call(&progress); + view->smartCallback<LoadProgress>().call(&progress); } void PageLoadClientEfl::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) @@ -85,8 +66,8 @@ void PageLoadClientEfl::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTyp if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - viewImpl->smartCallback<LoadFinished>().call(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + view->smartCallback<LoadFinished>().call(); } void PageLoadClientEfl::didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) @@ -94,10 +75,10 @@ void PageLoadClientEfl::didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef frame if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); OwnPtr<EwkError> ewkError = EwkError::create(error); - viewImpl->smartCallback<LoadError>().call(ewkError.get()); - viewImpl->smartCallback<LoadFinished>().call(); + view->smartCallback<LoadError>().call(ewkError.get()); + view->smartCallback<LoadFinished>().call(); } void PageLoadClientEfl::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) @@ -105,9 +86,9 @@ void PageLoadClientEfl::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef fr if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - viewImpl->informURLChange(); - viewImpl->smartCallback<ProvisionalLoadStarted>().call(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + view->informURLChange(); + view->smartCallback<ProvisionalLoadStarted>().call(); } void PageLoadClientEfl::didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) @@ -115,9 +96,9 @@ void PageLoadClientEfl::didReceiveServerRedirectForProvisionalLoadForFrame(WKPag if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - viewImpl->informURLChange(); - viewImpl->smartCallback<ProvisionalLoadRedirect>().call(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + view->informURLChange(); + view->smartCallback<ProvisionalLoadRedirect>().call(); } void PageLoadClientEfl::didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) @@ -125,32 +106,37 @@ void PageLoadClientEfl::didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFra if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); OwnPtr<EwkError> ewkError = EwkError::create(error); - viewImpl->smartCallback<ProvisionalLoadFailed>().call(ewkError.get()); + view->smartCallback<ProvisionalLoadFailed>().call(ewkError.get()); } -#if USE(TILED_BACKING_STORE) void PageLoadClientEfl::didCommitLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - viewImpl->informLoadCommitted(); -} + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + if (WKPageUseFixedLayout(view->wkPage())) { +#if USE(ACCELERATED_COMPOSITING) + view->pageViewportController()->didCommitLoad(); #endif + return; + } + + view->scheduleUpdateDisplay(); +} void PageLoadClientEfl::didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void* clientInfo) { - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - ASSERT(viewImpl); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + ASSERT(view); - Ewk_Back_Forward_List* list = ewk_view_back_forward_list_get(viewImpl->view()); + Ewk_Back_Forward_List* list = ewk_view_back_forward_list_get(view->evasObject()); ASSERT(list); list->update(addedItem, removedItems); - viewImpl->smartCallback<BackForwardListChange>().call(); + view->smartCallback<BackForwardListChange>().call(); } void PageLoadClientEfl::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef frame, WKSameDocumentNavigationType, WKTypeRef, const void* clientInfo) @@ -158,22 +144,22 @@ void PageLoadClientEfl::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef if (!WKFrameIsMainFrame(frame)) return; - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); - viewImpl->informURLChange(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); + view->informURLChange(); } void PageLoadClientEfl::didReceiveAuthenticationChallengeInFrame(WKPageRef, WKFrameRef, WKAuthenticationChallengeRef authenticationChallenge, const void* clientInfo) { - EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); + EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - RefPtr<EwkAuthRequest> authenticationRequest = EwkAuthRequest::create(toImpl(authenticationChallenge)); - viewImpl->smartCallback<AuthenticationRequest>().call(authenticationRequest.get()); + RefPtr<EwkAuthRequest> authenticationRequest = EwkAuthRequest::create(authenticationChallenge); + view->smartCallback<AuthenticationRequest>().call(authenticationRequest.get()); } -PageLoadClientEfl::PageLoadClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +PageLoadClientEfl::PageLoadClientEfl(EwkView* view) + : m_view(view) { - WKPageRef pageRef = m_viewImpl->wkPage(); + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKPageLoaderClient loadClient; @@ -181,12 +167,6 @@ PageLoadClientEfl::PageLoadClientEfl(EwkViewImpl* viewImpl) loadClient.version = kWKPageLoaderClientCurrentVersion; loadClient.clientInfo = this; loadClient.didReceiveTitleForFrame = didReceiveTitleForFrame; -#if ENABLE(WEB_INTENTS) - loadClient.didReceiveIntentForFrame = didReceiveIntentForFrame; -#endif -#if ENABLE(WEB_INTENTS_TAG) - loadClient.registerIntentServiceForFrame = registerIntentServiceForFrame; -#endif loadClient.didStartProgress = didChangeProgress; loadClient.didChangeProgress = didChangeProgress; loadClient.didFinishProgress = didChangeProgress; @@ -195,9 +175,7 @@ PageLoadClientEfl::PageLoadClientEfl(EwkViewImpl* viewImpl) loadClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; loadClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame; loadClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame; -#if USE(TILED_BACKING_STORE) loadClient.didCommitLoadForFrame = didCommitLoadForFrame; -#endif loadClient.didChangeBackForwardList = didChangeBackForwardList; loadClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; loadClient.didReceiveAuthenticationChallengeInFrame = didReceiveAuthenticationChallengeInFrame; diff --git a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h b/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h index cd713a3cd..cae1f84fc 100644 --- a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h @@ -30,43 +30,35 @@ #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class PageLoadClientEfl { public: - static PassOwnPtr<PageLoadClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<PageLoadClientEfl> create(EwkView* viewImpl) { return adoptPtr(new PageLoadClientEfl(viewImpl)); } private: - explicit PageLoadClientEfl(EwkViewImpl*); + explicit PageLoadClientEfl(EwkView*); - inline EwkViewImpl* viewImpl() const { return m_viewImpl; } + inline EwkView* view() const { return m_view; } static void didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef, WKTypeRef, const void* clientInfo); -#if ENABLE(WEB_INTENTS) - static void didReceiveIntentForFrame(WKPageRef, WKFrameRef, WKIntentDataRef, WKTypeRef, const void* clientInfo); -#endif -#if ENABLE(WEB_INTENTS_TAG) - static void registerIntentServiceForFrame(WKPageRef, WKFrameRef, WKIntentServiceInfoRef, WKTypeRef, const void* clientInfo); -#endif static void didChangeProgress(WKPageRef, const void* clientInfo); static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); static void didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); static void didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); static void didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); static void didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); -#if USE(TILED_BACKING_STORE) static void didCommitLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); -#endif static void didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void* clientInfo); static void didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef, WKSameDocumentNavigationType, WKTypeRef, const void* clientInfo); static void didReceiveAuthenticationChallengeInFrame(WKPageRef, WKFrameRef, WKAuthenticationChallengeRef, const void* clientInfo); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp index 0253faa4f..ecda5cb52 100644 --- a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp @@ -26,10 +26,11 @@ #include "config.h" #include "PagePolicyClientEfl.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKFrame.h" #include "WKFramePolicyListener.h" -#include "WebFrameProxy.h" +#include "WKString.h" +#include "WKURLResponse.h" #include "ewk_navigation_policy_decision.h" #include "ewk_navigation_policy_decision_private.h" #include <WebCore/HTTPStatusCodes.h> @@ -49,7 +50,7 @@ void PagePolicyClientEfl::decidePolicyForNavigationAction(WKPageRef, WKFrameRef, PagePolicyClientEfl* policyClient = toPagePolicyClientEfl(clientInfo); RefPtr<EwkNavigationPolicyDecision> decision = EwkNavigationPolicyDecision::create(navigationType, mouseButton, modifiers, request, 0, listener); - policyClient->m_viewImpl->smartCallback<NavigationPolicyDecision>().call(decision.get()); + policyClient->m_view->smartCallback<NavigationPolicyDecision>().call(decision.get()); } void PagePolicyClientEfl::decidePolicyForNewWindowAction(WKPageRef, WKFrameRef, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKStringRef frameName, WKFramePolicyListenerRef listener, WKTypeRef /*userData*/, const void* clientInfo) @@ -57,30 +58,26 @@ void PagePolicyClientEfl::decidePolicyForNewWindowAction(WKPageRef, WKFrameRef, PagePolicyClientEfl* policyClient = toPagePolicyClientEfl(clientInfo); RefPtr<EwkNavigationPolicyDecision> decision = EwkNavigationPolicyDecision::create(navigationType, mouseButton, modifiers, request, toImpl(frameName)->string().utf8().data(), listener); - policyClient->m_viewImpl->smartCallback<NewWindowPolicyDecision>().call(decision.get()); + policyClient->m_view->smartCallback<NewWindowPolicyDecision>().call(decision.get()); } void PagePolicyClientEfl::decidePolicyForResponseCallback(WKPageRef, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef, WKFramePolicyListenerRef listener, WKTypeRef /*userData*/, const void* /*clientInfo*/) { - using namespace WebCore; - - const ResourceResponse resourceResponse = toImpl(response)->resourceResponse(); - // Ignore responses with an HTTP status code of 204 (No Content) - if (resourceResponse.httpStatusCode() == HTTPNoContent) { + if (WKURLResponseHTTPStatusCode(response) == WebCore::HTTPNoContent) { WKFramePolicyListenerIgnore(listener); return; } // If the URL Response has "Content-Disposition: attachment;" header, then // we should download it. - if (resourceResponse.isAttachment()) { + if (WKURLResponseIsAttachment(response)) { WKFramePolicyListenerDownload(listener); return; } - String mimeType = toImpl(response)->resourceResponse().mimeType().lower(); - bool canShowMIMEType = toImpl(frame)->canShowMIMEType(mimeType); + WKRetainPtr<WKStringRef> mimeType = adoptWK(WKURLResponseCopyMIMEType(response)); + bool canShowMIMEType = WKFrameCanShowMIMEType(frame, mimeType.get()); if (WKFrameIsMainFrame(frame)) { if (canShowMIMEType) { WKFramePolicyListenerUse(listener); @@ -94,7 +91,8 @@ void PagePolicyClientEfl::decidePolicyForResponseCallback(WKPageRef, WKFrameRef // We should ignore downloadable top-level content for subframes, with an exception for text/xml and application/xml so we can still support Acid3 test. // It makes the browser intentionally behave differently when it comes to text(application)/xml content in subframes vs. mainframe. - if (!canShowMIMEType && !(mimeType == "text/xml" || mimeType == "application/xml")) { + bool isXMLType = WKStringIsEqualToUTF8CString(mimeType.get(), "text/xml") || WKStringIsEqualToUTF8CString(mimeType.get(), "application/xml"); + if (!canShowMIMEType && !isXMLType) { WKFramePolicyListenerIgnore(listener); return; } @@ -102,10 +100,10 @@ void PagePolicyClientEfl::decidePolicyForResponseCallback(WKPageRef, WKFrameRef WKFramePolicyListenerUse(listener); } -PagePolicyClientEfl::PagePolicyClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +PagePolicyClientEfl::PagePolicyClientEfl(EwkView* view) + : m_view(view) { - WKPageRef pageRef = m_viewImpl->wkPage(); + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKPagePolicyClient policyClient; diff --git a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h b/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h index 68d9a9ee9..0d05b733b 100644 --- a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h @@ -31,25 +31,25 @@ #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class PagePolicyClientEfl { public: - static PassOwnPtr<PagePolicyClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<PagePolicyClientEfl> create(EwkView* view) { - return adoptPtr(new PagePolicyClientEfl(viewImpl)); + return adoptPtr(new PagePolicyClientEfl(view)); } private: - explicit PagePolicyClientEfl(EwkViewImpl*); + explicit PagePolicyClientEfl(EwkView*); static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef, WKFramePolicyListenerRef, WKTypeRef, const void*); static void decidePolicyForNewWindowAction(WKPageRef, WKFrameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef, WKStringRef, WKFramePolicyListenerRef, WKTypeRef, const void*); static void decidePolicyForResponseCallback(WKPageRef, WKFrameRef, WKURLResponseRef, WKURLRequestRef, WKFramePolicyListenerRef, WKTypeRef, const void*); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp index cd5c7793b..5488ea136 100644 --- a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp @@ -27,9 +27,10 @@ #include "config.h" #include "PageUIClientEfl.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKAPICast.h" #include "WKEvent.h" +#include "WKPageEfl.h" #include "WKString.h" #include "ewk_file_chooser_request_private.h" #include "ewk_window_features_private.h" @@ -45,183 +46,209 @@ static inline PageUIClientEfl* toPageUIClientEfl(const void* clientInfo) return static_cast<PageUIClientEfl*>(const_cast<void*>(clientInfo)); } -void PageUIClientEfl::closePage(WKPageRef, const void* clientInfo) +PageUIClientEfl::PageUIClientEfl(EwkView* view) + : m_view(view) { - toPageUIClientEfl(clientInfo)->m_viewImpl->closePage(); + WKPageRef pageRef = m_view->wkPage(); + ASSERT(pageRef); + + WKPageUIClient uiClient; + memset(&uiClient, 0, sizeof(WKPageUIClient)); + uiClient.version = kWKPageUIClientCurrentVersion; + uiClient.clientInfo = this; + uiClient.close = close; + uiClient.takeFocus = takeFocus; + uiClient.focus = focus; + uiClient.unfocus = unfocus; + uiClient.runJavaScriptAlert = runJavaScriptAlert; + uiClient.runJavaScriptConfirm = runJavaScriptConfirm; + uiClient.runJavaScriptPrompt = runJavaScriptPrompt; + uiClient.toolbarsAreVisible = toolbarsAreVisible; + uiClient.setToolbarsAreVisible = setToolbarsAreVisible; + uiClient.menuBarIsVisible = menuBarIsVisible; + uiClient.setMenuBarIsVisible = setMenuBarIsVisible; + uiClient.statusBarIsVisible = statusBarIsVisible; + uiClient.setStatusBarIsVisible = setStatusBarIsVisible; + uiClient.isResizable = isResizable; + uiClient.setIsResizable = setIsResizable; + uiClient.getWindowFrame = getWindowFrame; + uiClient.setWindowFrame = setWindowFrame; + uiClient.runBeforeUnloadConfirmPanel = runBeforeUnloadConfirmPanel; +#if ENABLE(SQL_DATABASE) + uiClient.exceededDatabaseQuota = exceededDatabaseQuota; +#endif + uiClient.runOpenPanel = runOpenPanel; + uiClient.createNewPage = createNewPage; +#if ENABLE(INPUT_TYPE_COLOR) + uiClient.showColorPicker = showColorPicker; + uiClient.hideColorPicker = hideColorPicker; +#endif + + WKPageSetPageUIClient(pageRef, &uiClient); + + // Popup Menu UI client. + WKPageUIPopupMenuClient uiPopupMenuClient; + memset(&uiPopupMenuClient, 0, sizeof(WKPageUIPopupMenuClient)); + uiPopupMenuClient.version = kWKPageUIPopupMenuClientCurrentVersion; + uiPopupMenuClient.clientInfo = this; + uiPopupMenuClient.showPopupMenu = showPopupMenu; + uiPopupMenuClient.hidePopupMenu = hidePopupMenu; + WKPageSetUIPopupMenuClient(pageRef, &uiPopupMenuClient); +} + + +void PageUIClientEfl::close(WKPageRef, const void* clientInfo) +{ + toPageUIClientEfl(clientInfo)->m_view->close(); +} + +void PageUIClientEfl::takeFocus(WKPageRef, WKFocusDirection, const void* clientInfo) +{ + // FIXME: this is only a partial implementation. + evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_view->evasObject(), false); } -WKPageRef PageUIClientEfl::createNewPage(WKPageRef, WKURLRequestRef, WKDictionaryRef wkWindowFeatures, WKEventModifiers, WKEventMouseButton, const void* clientInfo) +void PageUIClientEfl::focus(WKPageRef, const void* clientInfo) { - return toPageUIClientEfl(clientInfo)->m_viewImpl->createNewPage(toImpl(wkWindowFeatures)); + evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_view->evasObject(), true); +} + +void PageUIClientEfl::unfocus(WKPageRef, const void* clientInfo) +{ + evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_view->evasObject(), false); } void PageUIClientEfl::runJavaScriptAlert(WKPageRef, WKStringRef alertText, WKFrameRef, const void* clientInfo) { - toPageUIClientEfl(clientInfo)->m_viewImpl->requestJSAlertPopup(WKEinaSharedString(alertText)); + toPageUIClientEfl(clientInfo)->m_view->requestJSAlertPopup(WKEinaSharedString(alertText)); } bool PageUIClientEfl::runJavaScriptConfirm(WKPageRef, WKStringRef message, WKFrameRef, const void* clientInfo) { - return toPageUIClientEfl(clientInfo)->m_viewImpl->requestJSConfirmPopup(WKEinaSharedString(message)); + return toPageUIClientEfl(clientInfo)->m_view->requestJSConfirmPopup(WKEinaSharedString(message)); } WKStringRef PageUIClientEfl::runJavaScriptPrompt(WKPageRef, WKStringRef message, WKStringRef defaultValue, WKFrameRef, const void* clientInfo) { - WKEinaSharedString value = toPageUIClientEfl(clientInfo)->m_viewImpl->requestJSPromptPopup(WKEinaSharedString(message), WKEinaSharedString(defaultValue)); + WKEinaSharedString value = toPageUIClientEfl(clientInfo)->m_view->requestJSPromptPopup(WKEinaSharedString(message), WKEinaSharedString(defaultValue)); return value ? WKStringCreateWithUTF8CString(value) : 0; } bool PageUIClientEfl::toolbarsAreVisible(WKPageRef, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); return features->toolbarVisible(); } void PageUIClientEfl::setToolbarsAreVisible(WKPageRef, bool toolbarVisible, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); features->setToolbarVisible(toolbarVisible); } bool PageUIClientEfl::menuBarIsVisible(WKPageRef, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); return features->menuBarVisible(); } void PageUIClientEfl::setMenuBarIsVisible(WKPageRef, bool menuBarVisible, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); features->setMenuBarVisible(menuBarVisible); } bool PageUIClientEfl::statusBarIsVisible(WKPageRef, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); return features->statusBarVisible(); } void PageUIClientEfl::setStatusBarIsVisible(WKPageRef, bool statusBarVisible, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); features->setStatusBarVisible(statusBarVisible); } bool PageUIClientEfl::isResizable(WKPageRef, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); return features->resizable(); } void PageUIClientEfl::setIsResizable(WKPageRef, bool resizable, const void* clientInfo) { - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_viewImpl->windowFeatures(); + EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); ASSERT(features); features->setResizable(resizable); } -#if ENABLE(INPUT_TYPE_COLOR) -void PageUIClientEfl::showColorPicker(WKPageRef, WKStringRef initialColor, WKColorPickerResultListenerRef listener, const void* clientInfo) +WKRect PageUIClientEfl::getWindowFrame(WKPageRef, const void* clientInfo) { - PageUIClientEfl* pageUIClient = toPageUIClientEfl(clientInfo); - WebCore::Color color = WebCore::Color(WebKit::toWTFString(initialColor)); - pageUIClient->m_viewImpl->requestColorPicker(listener, color); + return toPageUIClientEfl(clientInfo)->m_view->windowGeometry(); } -void PageUIClientEfl::hideColorPicker(WKPageRef, const void* clientInfo) +void PageUIClientEfl::setWindowFrame(WKPageRef, WKRect frame, const void* clientInfo) { - PageUIClientEfl* pageUIClient = toPageUIClientEfl(clientInfo); - pageUIClient->m_viewImpl->dismissColorPicker(); + toPageUIClientEfl(clientInfo)->m_view->setWindowGeometry(frame); } -#endif -#if ENABLE(SQL_DATABASE) -unsigned long long PageUIClientEfl::exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef databaseName, WKStringRef displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void* clientInfo) +bool PageUIClientEfl::runBeforeUnloadConfirmPanel(WKPageRef, WKStringRef message, WKFrameRef, const void* clientInfo) { - EwkViewImpl* viewImpl = toPageUIClientEfl(clientInfo)->m_viewImpl; - return viewImpl->informDatabaseQuotaReached(toImpl(databaseName)->string(), toImpl(displayName)->string(), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage); + return toPageUIClientEfl(clientInfo)->m_view->requestJSConfirmPopup(WKEinaSharedString(message)); } -#endif -void PageUIClientEfl::focus(WKPageRef, const void* clientInfo) +#if ENABLE(SQL_DATABASE) +unsigned long long PageUIClientEfl::exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef databaseName, WKStringRef displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void* clientInfo) { - evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_viewImpl->view(), true); + EwkView* view = toPageUIClientEfl(clientInfo)->m_view; + return view->informDatabaseQuotaReached(toImpl(databaseName)->string(), toImpl(displayName)->string(), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage); } +#endif -void PageUIClientEfl::unfocus(WKPageRef, const void* clientInfo) +void PageUIClientEfl::runOpenPanel(WKPageRef, WKFrameRef, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void* clientInfo) { - evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_viewImpl->view(), false); + EwkView* view = toPageUIClientEfl(clientInfo)->m_view; + RefPtr<EwkFileChooserRequest> fileChooserRequest = EwkFileChooserRequest::create(parameters, listener); + view->smartCallback<FileChooserRequest>().call(fileChooserRequest.get()); } -void PageUIClientEfl::takeFocus(WKPageRef, WKFocusDirection, const void* clientInfo) +WKPageRef PageUIClientEfl::createNewPage(WKPageRef, WKURLRequestRef wkRequest, WKDictionaryRef wkWindowFeatures, WKEventModifiers, WKEventMouseButton, const void* clientInfo) { - // FIXME: this is only a partial implementation. - evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_viewImpl->view(), false); + RefPtr<EwkUrlRequest> request = EwkUrlRequest::create(wkRequest); + return toPageUIClientEfl(clientInfo)->m_view->createNewPage(request, wkWindowFeatures); } -WKRect PageUIClientEfl::getWindowFrame(WKPageRef, const void* clientInfo) +#if ENABLE(INPUT_TYPE_COLOR) +void PageUIClientEfl::showColorPicker(WKPageRef, WKStringRef initialColor, WKColorPickerResultListenerRef listener, const void* clientInfo) { - return toPageUIClientEfl(clientInfo)->m_viewImpl->windowGeometry(); + PageUIClientEfl* pageUIClient = toPageUIClientEfl(clientInfo); + WebCore::Color color = WebCore::Color(WebKit::toWTFString(initialColor)); + pageUIClient->m_view->requestColorPicker(listener, color); } -void PageUIClientEfl::setWindowFrame(WKPageRef, WKRect frame, const void* clientInfo) +void PageUIClientEfl::hideColorPicker(WKPageRef, const void* clientInfo) { - toPageUIClientEfl(clientInfo)->m_viewImpl->setWindowGeometry(frame); + PageUIClientEfl* pageUIClient = toPageUIClientEfl(clientInfo); + pageUIClient->m_view->dismissColorPicker(); } +#endif -void PageUIClientEfl::runOpenPanel(WKPageRef, WKFrameRef, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void* clientInfo) +void PageUIClientEfl::showPopupMenu(WKPageRef, WKPopupMenuListenerRef menuListenerRef, WKRect rect, WKPopupItemTextDirection textDirection, double pageScaleFactor, WKArrayRef itemsRef, int32_t selectedIndex, const void* clientInfo) { - EwkViewImpl* viewImpl = toPageUIClientEfl(clientInfo)->m_viewImpl; - RefPtr<EwkFileChooserRequest> fileChooserRequest = EwkFileChooserRequest::create(toImpl(parameters), toImpl(listener)); - viewImpl->smartCallback<FileChooserRequest>().call(fileChooserRequest.get()); + return toPageUIClientEfl(clientInfo)->m_view->requestPopupMenu(menuListenerRef, rect, textDirection, pageScaleFactor, itemsRef, selectedIndex); } -PageUIClientEfl::PageUIClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +void PageUIClientEfl::hidePopupMenu(WKPageRef, const void* clientInfo) { - WKPageRef pageRef = m_viewImpl->wkPage(); - ASSERT(pageRef); - - WKPageUIClient uiClient; - memset(&uiClient, 0, sizeof(WKPageUIClient)); - uiClient.version = kWKPageUIClientCurrentVersion; - uiClient.clientInfo = this; - uiClient.close = closePage; - uiClient.createNewPage = createNewPage; - uiClient.runJavaScriptAlert = runJavaScriptAlert; - uiClient.runJavaScriptConfirm = runJavaScriptConfirm; - uiClient.runJavaScriptPrompt = runJavaScriptPrompt; - uiClient.toolbarsAreVisible = toolbarsAreVisible; - uiClient.setToolbarsAreVisible = setToolbarsAreVisible; - uiClient.menuBarIsVisible = menuBarIsVisible; - uiClient.setMenuBarIsVisible = setMenuBarIsVisible; - uiClient.statusBarIsVisible = statusBarIsVisible; - uiClient.setStatusBarIsVisible = setStatusBarIsVisible; - uiClient.isResizable = isResizable; - uiClient.setIsResizable = setIsResizable; - uiClient.takeFocus = takeFocus; - uiClient.focus = focus; - uiClient.unfocus = unfocus; - uiClient.getWindowFrame = getWindowFrame; - uiClient.setWindowFrame = setWindowFrame; - uiClient.runOpenPanel = runOpenPanel; -#if ENABLE(SQL_DATABASE) - uiClient.exceededDatabaseQuota = exceededDatabaseQuota; -#endif - -#if ENABLE(INPUT_TYPE_COLOR) - uiClient.showColorPicker = showColorPicker; - uiClient.hideColorPicker = hideColorPicker; -#endif - - WKPageSetPageUIClient(pageRef, &uiClient); + return toPageUIClientEfl(clientInfo)->m_view->closePopupMenu(); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h b/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h index e68414acf..df47b9716 100644 --- a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h @@ -28,25 +28,28 @@ #define PageUIClientEfl_h #include "WKPage.h" +#include "WKPopupItem.h" #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class PageUIClientEfl { public: - static PassOwnPtr<PageUIClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<PageUIClientEfl> create(EwkView* view) { - return adoptPtr(new PageUIClientEfl(viewImpl)); + return adoptPtr(new PageUIClientEfl(view)); } private: - explicit PageUIClientEfl(EwkViewImpl*); + explicit PageUIClientEfl(EwkView*); - static void closePage(WKPageRef, const void*); - static WKPageRef createNewPage(WKPageRef, WKURLRequestRef, WKDictionaryRef, WKEventModifiers, WKEventMouseButton, const void*); + static void close(WKPageRef, const void*); + static void takeFocus(WKPageRef, WKFocusDirection, const void*); + static void focus(WKPageRef, const void*); + static void unfocus(WKPageRef, const void*); static void runJavaScriptAlert(WKPageRef, WKStringRef, WKFrameRef, const void*); static bool runJavaScriptConfirm(WKPageRef, WKStringRef, WKFrameRef, const void*); static WKStringRef runJavaScriptPrompt(WKPageRef, WKStringRef, WKStringRef, WKFrameRef, const void*); @@ -58,21 +61,23 @@ private: static void setStatusBarIsVisible(WKPageRef, bool, const void* clientInfo); static bool isResizable(WKPageRef, const void* clientInfo); static void setIsResizable(WKPageRef, bool, const void* clientInfo); -#if ENABLE(INPUT_TYPE_COLOR) - static void showColorPicker(WKPageRef, WKStringRef initialColor, WKColorPickerResultListenerRef, const void*); - static void hideColorPicker(WKPageRef, const void*); -#endif + static WKRect getWindowFrame(WKPageRef, const void*); + static void setWindowFrame(WKPageRef, WKRect, const void*); + static bool runBeforeUnloadConfirmPanel(WKPageRef, WKStringRef, WKFrameRef, const void*); #if ENABLE(SQL_DATABASE) static unsigned long long exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef, WKStringRef, unsigned long long currentQuota, unsigned long long, unsigned long long, unsigned long long, const void*); #endif - static void focus(WKPageRef, const void*); - static void unfocus(WKPageRef, const void*); - static void takeFocus(WKPageRef, WKFocusDirection, const void*); - static WKRect getWindowFrame(WKPageRef, const void*); - static void setWindowFrame(WKPageRef, WKRect, const void*); static void runOpenPanel(WKPageRef, WKFrameRef, WKOpenPanelParametersRef, WKOpenPanelResultListenerRef, const void*); + static WKPageRef createNewPage(WKPageRef, WKURLRequestRef, WKDictionaryRef, WKEventModifiers, WKEventMouseButton, const void*); +#if ENABLE(INPUT_TYPE_COLOR) + static void showColorPicker(WKPageRef, WKStringRef initialColor, WKColorPickerResultListenerRef, const void*); + static void hideColorPicker(WKPageRef, const void*); +#endif + + static void showPopupMenu(WKPageRef, WKPopupMenuListenerRef, WKRect, WKPopupItemTextDirection, double pageScaleFactor, WKArrayRef itemsRef, int32_t selectedIndex, const void* clientInfo); + static void hidePopupMenu(WKPageRef, const void* clientInfo); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp index fe2913969..22a45b52f 100644 --- a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2013 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,83 +25,50 @@ */ #include "config.h" -#include "PageViewportControllerClientEfl.h" -#if USE(TILED_BACKING_STORE) +#if USE(ACCELERATED_COMPOSITING) + +#include "PageViewportControllerClientEfl.h" -#include "EwkViewImpl.h" -#include "LayerTreeCoordinatorProxy.h" -#include "LayerTreeRenderer.h" +#include "EwkView.h" #include "PageViewportController.h" -#include "TransformationMatrix.h" using namespace WebCore; namespace WebKit { -PageViewportControllerClientEfl::PageViewportControllerClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +PageViewportControllerClientEfl::PageViewportControllerClientEfl(EwkView* view) + : m_view(view) , m_controller(0) { - ASSERT(m_viewImpl); -} - -PageViewportControllerClientEfl::~PageViewportControllerClientEfl() -{ + ASSERT(m_view); } -DrawingAreaProxy* PageViewportControllerClientEfl::drawingArea() const +void PageViewportControllerClientEfl::didChangeContentsSize(const WebCore::IntSize&) { - return m_viewImpl->page()->drawingArea(); -} - -void PageViewportControllerClientEfl::setRendererActive(bool active) -{ - drawingArea()->layerTreeCoordinatorProxy()->layerTreeRenderer()->setActive(active); -} - -void PageViewportControllerClientEfl::updateViewportSize(const IntSize& viewportSize) -{ - m_viewportSize = viewportSize; - - ASSERT(m_controller); - m_controller->didChangeViewportSize(viewportSize); -} - -void PageViewportControllerClientEfl::didChangeContentsSize(const WebCore::IntSize& contentsSize) -{ - drawingArea()->layerTreeCoordinatorProxy()->setContentsSize(contentsSize); - m_viewImpl->update(); + m_view->scheduleUpdateDisplay(); } void PageViewportControllerClientEfl::setViewportPosition(const WebCore::FloatPoint& contentsPoint) { - m_contentPosition = roundedIntPoint(contentsPoint); + m_contentPosition = contentsPoint; FloatPoint pos(contentsPoint); - pos.scale(scaleFactor(), scaleFactor()); - m_viewImpl->setPagePosition(pos); + float scaleFactor = WKViewGetContentScaleFactor(m_view->wkView()); + pos.scale(scaleFactor, scaleFactor); + WKViewSetContentPosition(m_view->wkView(), WKPointMake(pos.x(), pos.y())); - m_controller->didChangeContentsVisibility(m_contentPosition, scaleFactor()); + m_controller->didChangeContentsVisibility(m_contentPosition, scaleFactor); } -void PageViewportControllerClientEfl::setContentsScale(float newScale, bool treatAsInitialValue) +void PageViewportControllerClientEfl::setPageScaleFactor(float newScale) { - if (treatAsInitialValue) - setViewportPosition(FloatPoint(0, 0)); - - m_viewImpl->setScaleFactor(newScale); -} - -void PageViewportControllerClientEfl::didResumeContent() -{ - ASSERT(m_controller); - m_controller->didChangeContentsVisibility(m_contentPosition, scaleFactor()); + WKViewSetContentScaleFactor(m_view->wkView(), newScale); } void PageViewportControllerClientEfl::didChangeVisibleContents() { - m_viewImpl->update(); + m_view->scheduleUpdateDisplay(); } void PageViewportControllerClientEfl::didChangeViewportAttributes() @@ -113,5 +81,4 @@ void PageViewportControllerClientEfl::setController(PageViewportController* cont } } // namespace WebKit -#endif // USE(TILED_BACKING_STORE) - +#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h index 1ae6a541d..e4045b6e1 100644 --- a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2013 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,52 +27,39 @@ #ifndef PageViewportControllerClientEfl_h #define PageViewportControllerClientEfl_h -#if USE(TILED_BACKING_STORE) - -#include "EwkViewImpl.h" -#include "PageClientBase.h" #include "PageViewportControllerClient.h" +#include <WebCore/FloatPoint.h> #include <wtf/PassOwnPtr.h> +class EwkView; + namespace WebKit { class PageViewportControllerClientEfl : public PageViewportControllerClient { public: - static PassOwnPtr<PageViewportControllerClientEfl> create(EwkViewImpl* viewImpl) + static PassOwnPtr<PageViewportControllerClientEfl> create(EwkView* viewImpl) { return adoptPtr(new PageViewportControllerClientEfl(viewImpl)); } - ~PageViewportControllerClientEfl(); - - DrawingAreaProxy* drawingArea() const; - WebCore::IntSize viewSize() { return m_viewportSize; } - float scaleFactor() const { return m_viewImpl->scaleFactor(); } - WebCore::IntPoint contentPosition() const { return m_contentPosition; } + virtual ~PageViewportControllerClientEfl() { } - void updateViewportSize(const WebCore::IntSize& viewportSize); - void setRendererActive(bool); + virtual void setViewportPosition(const WebCore::FloatPoint&) OVERRIDE; + virtual void setPageScaleFactor(float) OVERRIDE; - virtual void setViewportPosition(const WebCore::FloatPoint& contentsPoint); - virtual void setContentsScale(float, bool treatAsInitialValue); + virtual void didChangeContentsSize(const WebCore::IntSize&) OVERRIDE; + virtual void didChangeVisibleContents() OVERRIDE; + virtual void didChangeViewportAttributes() OVERRIDE; - virtual void didResumeContent(); - virtual void didChangeContentsSize(const WebCore::IntSize&); - virtual void didChangeVisibleContents(); - virtual void didChangeViewportAttributes(); - - virtual void setController(PageViewportController*); + virtual void setController(PageViewportController*) OVERRIDE; private: - explicit PageViewportControllerClientEfl(EwkViewImpl*); + explicit PageViewportControllerClientEfl(EwkView*); - EwkViewImpl* m_viewImpl; - WebCore::IntSize m_viewportSize; - WebCore::IntPoint m_contentPosition; + EwkView* m_view; + WebCore::FloatPoint m_contentPosition; PageViewportController* m_controller; }; } // namespace WebKit -#endif - #endif // PageViewportControllerClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp index e21d69954..eff93281d 100644 --- a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp @@ -28,7 +28,6 @@ #include "WKContextSoup.h" #include "WKSoupRequestManager.h" -#include "WebSoupRequestManagerProxy.h" #include "ewk_context_private.h" #include "ewk_url_scheme_request_private.h" @@ -66,10 +65,10 @@ void RequestManagerClientEfl::didReceiveURIRequest(WKSoupRequestManagerRef soupR handler.callback(schemeRequest.get(), handler.userData); } -RequestManagerClientEfl::RequestManagerClientEfl(EwkContext* context) - : m_soupRequestManager(WKContextGetSoupRequestManager(toAPI(context->webContext().get()))) +RequestManagerClientEfl::RequestManagerClientEfl(WKContextRef context) + : m_soupRequestManager(WKContextGetSoupRequestManager(context)) { - ASSERT(context); + ASSERT(m_soupRequestManager); WKSoupRequestManagerClient wkRequestManagerClient; memset(&wkRequestManagerClient, 0, sizeof(WKSoupRequestManagerClient)); @@ -90,7 +89,7 @@ void RequestManagerClientEfl::registerURLSchemeHandler(const String& scheme, Ewk ASSERT(callback); m_urlSchemeHandlers.set(scheme, EwkUrlSchemeHandler(callback, userData)); - toImpl(m_soupRequestManager.get())->registerURIScheme(scheme); + WKSoupRequestManagerRegisterURIScheme(m_soupRequestManager.get(), adoptWK(toCopiedAPI(scheme)).get()); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.h b/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.h index 353bc2516..cd6f225fa 100644 --- a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.h @@ -26,9 +26,9 @@ #ifndef RequestManagerClientEfl_h #define RequestManagerClientEfl_h -#include "WKRetainPtr.h" #include "ewk_context_private.h" #include <WebKit2/WKBase.h> +#include <WebKit2/WKRetainPtr.h> #include <wtf/HashMap.h> #include <wtf/PassOwnPtr.h> #include <wtf/text/WTFString.h> @@ -38,7 +38,7 @@ namespace WebKit { class RequestManagerClientEfl { public: ~RequestManagerClientEfl(); - static PassOwnPtr<RequestManagerClientEfl> create(EwkContext* context) + static PassOwnPtr<RequestManagerClientEfl> create(WKContextRef context) { return adoptPtr(new RequestManagerClientEfl(context)); } @@ -46,7 +46,7 @@ public: void registerURLSchemeHandler(const String& scheme, Ewk_Url_Scheme_Request_Cb callback, void* userData); private: - explicit RequestManagerClientEfl(EwkContext*); + explicit RequestManagerClientEfl(WKContextRef); static void didReceiveURIRequest(WKSoupRequestManagerRef, WKURLRef, WKPageRef, uint64_t requestID, const void* clientInfo); diff --git a/Source/WebKit2/UIProcess/efl/ResourceLoadClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ResourceLoadClientEfl.cpp deleted file mode 100644 index f1a700c56..000000000 --- a/Source/WebKit2/UIProcess/efl/ResourceLoadClientEfl.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ResourceLoadClientEfl.h" - -#include "EwkViewImpl.h" -#include "WKAPICast.h" -#include "WKFrame.h" -#include "WKPage.h" -#include "WKRetainPtr.h" -#include "ewk_error_private.h" -#include "ewk_url_request_private.h" -#include "ewk_url_response_private.h" -#include "ewk_view.h" - -using namespace WebCore; -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline ResourceLoadClientEfl* toResourceLoadClientEfl(const void* clientInfo) -{ - return static_cast<ResourceLoadClientEfl*>(const_cast<void*>(clientInfo)); -} - -void ResourceLoadClientEfl::didInitiateLoadForResource(WKPageRef, WKFrameRef wkFrame, uint64_t resourceIdentifier, WKURLRequestRef wkRequest, bool pageIsProvisionallyLoading, const void* clientInfo) -{ - ResourceLoadClientEfl* resourceLoadClient = toResourceLoadClientEfl(clientInfo); - bool isMainResource = (WKFrameIsMainFrame(wkFrame) && pageIsProvisionallyLoading); - WKRetainPtr<WKURLRef> wkUrl(AdoptWK, WKURLRequestCopyURL(wkRequest)); - - RefPtr<EwkResource> resource = EwkResource::create(wkUrl.get(), isMainResource); - - // Keep the resource internally to reuse it later. - resourceLoadClient->m_loadingResourcesMap.add(resourceIdentifier, resource); - - RefPtr<EwkUrlRequest> request = EwkUrlRequest::create(wkRequest); - Ewk_Resource_Request resourceRequest = {resource.get(), request.get(), 0}; - resourceLoadClient->m_viewImpl->smartCallback<ResourceLoadStarted>().call(&resourceRequest); -} - -void ResourceLoadClientEfl::didSendRequestForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLRequestRef wkRequest, WKURLResponseRef wkRedirectResponse, const void* clientInfo) -{ - ResourceLoadClientEfl* resourceLoadClient = toResourceLoadClientEfl(clientInfo); - - RefPtr<EwkResource> resource = resourceLoadClient->m_loadingResourcesMap.get(resourceIdentifier); - // Only process if we know about this resource. - if (!resource) - return; - - RefPtr<EwkUrlRequest> request = EwkUrlRequest::create(wkRequest); - RefPtr<EwkUrlResponse> redirectResponse = EwkUrlResponse::create(wkRedirectResponse); - Ewk_Resource_Request resourceRequest = {resource.get(), request.get(), redirectResponse.get()}; - resourceLoadClient->m_viewImpl->smartCallback<ResourceRequestSent>().call(&resourceRequest); -} - -void ResourceLoadClientEfl::didReceiveResponseForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLResponseRef wkResponse, const void* clientInfo) -{ - ResourceLoadClientEfl* resourceLoadClient = toResourceLoadClientEfl(clientInfo); - - RefPtr<EwkResource> resource = resourceLoadClient->m_loadingResourcesMap.get(resourceIdentifier); - // Only process if we know about this resource. - if (!resource) - return; - - RefPtr<EwkUrlResponse> response = EwkUrlResponse::create(wkResponse); - Ewk_Resource_Load_Response resourceLoadResponse = {resource.get(), response.get()}; - resourceLoadClient->m_viewImpl->smartCallback<ResourceLoadResponse>().call(&resourceLoadResponse); -} - -void ResourceLoadClientEfl::didFinishLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, const void* clientInfo) -{ - ResourceLoadClientEfl* resourceLoadClient = toResourceLoadClientEfl(clientInfo); - - RefPtr<EwkResource> resource = resourceLoadClient->m_loadingResourcesMap.get(resourceIdentifier); - // Only process if we know about this resource. - if (!resource) - return; - - resourceLoadClient->m_viewImpl->smartCallback<ResourceLoadFinished>().call(resource.get()); -} - -void ResourceLoadClientEfl::didFailLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKErrorRef wkError, const void* clientInfo) -{ - ResourceLoadClientEfl* resourceLoadClient = toResourceLoadClientEfl(clientInfo); - - RefPtr<EwkResource> resource = resourceLoadClient->m_loadingResourcesMap.take(resourceIdentifier); - // Only process if we know about this resource. - if (!resource) - return; - - OwnPtr<EwkError> ewkError = EwkError::create(wkError); - Ewk_Resource_Load_Error resourceLoadError = {resource.get(), ewkError.get()}; - resourceLoadClient->m_viewImpl->smartCallback<ResourceLoadFailed>().call(&resourceLoadError); - resourceLoadClient->m_viewImpl->smartCallback<ResourceLoadFinished>().call(resource.get()); -} - -void ResourceLoadClientEfl::onViewProvisionalLoadStarted(void* userData, Evas_Object*, void*) -{ - ResourceLoadClientEfl* resourceLoadClient = toResourceLoadClientEfl(userData); - - // The view started a new load, clear internal resource map. - resourceLoadClient->m_loadingResourcesMap.clear(); -} - -ResourceLoadClientEfl::ResourceLoadClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) -{ - // Listen for "load,provisional,started" on the view to clear internal resources map. - evas_object_smart_callback_add(m_viewImpl->view(), CallBackInfo<ProvisionalLoadStarted>::name(), onViewProvisionalLoadStarted, this); - - WKPageRef pageRef = m_viewImpl->wkPage(); - ASSERT(pageRef); - - WKPageResourceLoadClient wkResourceLoadClient; - memset(&wkResourceLoadClient, 0, sizeof(WKPageResourceLoadClient)); - wkResourceLoadClient.version = kWKPageResourceLoadClientCurrentVersion; - wkResourceLoadClient.clientInfo = this; - wkResourceLoadClient.didInitiateLoadForResource = didInitiateLoadForResource; - wkResourceLoadClient.didSendRequestForResource = didSendRequestForResource; - wkResourceLoadClient.didReceiveResponseForResource = didReceiveResponseForResource; - wkResourceLoadClient.didFinishLoadForResource = didFinishLoadForResource; - wkResourceLoadClient.didFailLoadForResource = didFailLoadForResource; - - WKPageSetPageResourceLoadClient(pageRef, &wkResourceLoadClient); -} - -ResourceLoadClientEfl::~ResourceLoadClientEfl() -{ - evas_object_smart_callback_del(m_viewImpl->view(), CallBackInfo<ProvisionalLoadStarted>::name(), onViewProvisionalLoadStarted); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/ResourceLoadClientEfl.h b/Source/WebKit2/UIProcess/efl/ResourceLoadClientEfl.h deleted file mode 100644 index 7efe5a22a..000000000 --- a/Source/WebKit2/UIProcess/efl/ResourceLoadClientEfl.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ResourceLoadClientEfl_h -#define ResourceLoadClientEfl_h - -#include "ewk_resource.h" -#include "ewk_resource_private.h" -#include <wtf/HashMap.h> -#include <wtf/PassOwnPtr.h> - -class EwkViewImpl; - -namespace WebKit { - -class ResourceLoadClientEfl { -public: - ~ResourceLoadClientEfl(); - - static PassOwnPtr<ResourceLoadClientEfl> create(EwkViewImpl* viewImpl) - { - return adoptPtr(new ResourceLoadClientEfl(viewImpl)); - } - -private: - explicit ResourceLoadClientEfl(EwkViewImpl*); - - static void didInitiateLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLRequestRef, bool pageIsProvisionallyLoading, const void* clientInfo); - static void didSendRequestForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLRequestRef, WKURLResponseRef, const void* clientInfo); - static void didReceiveResponseForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKURLResponseRef, const void* clientInfo); - static void didFinishLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, const void* clientInfo); - static void didFailLoadForResource(WKPageRef, WKFrameRef, uint64_t resourceIdentifier, WKErrorRef, const void* clientInfo); - - static void onViewProvisionalLoadStarted(void* userData, Evas_Object* view, void* clientInfo); - - EwkViewImpl* m_viewImpl; - HashMap< uint64_t, RefPtr<EwkResource> > m_loadingResourcesMap; -}; - -} // namespace WebKit - -#endif // ResourceLoadClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp new file mode 100644 index 000000000..53c220ec9 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (C) 2013 Samsung Electronics + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "TextCheckerClientEfl.h" + +#if ENABLE(SPELLCHECK) + +#include "EwkView.h" +#include "TextChecker.h" +#include "TextCheckerState.h" +#include "WKAPICast.h" +#include "WKEinaSharedString.h" +#include "WKMutableArray.h" +#include "WKRetainPtr.h" +#include "WKString.h" +#include "WebPageProxy.h" +#include "ewk_text_checker_private.h" +#include <Eina.h> + +using namespace WebCore; +using namespace WebKit; + +static inline TextCheckerClientEfl* toTextCheckerClientEfl(const void* clientInfo) +{ + return static_cast<TextCheckerClientEfl*>(const_cast<void*>(clientInfo)); +} + +TextCheckerClientEfl::TextCheckerClientEfl() + : m_languagesUpdateTimer(this, &TextCheckerClientEfl::languagesUpdateTimerFired) + , m_spellCheckingSettingChangeTimer(this, &TextCheckerClientEfl::spellCheckingSettingChangeTimerFired) + , m_textCheckerEnchant(TextCheckerEnchant::create()) +{ + memset(&m_clientCallbacks, 0, sizeof(ClientCallbacks)); + + WKTextCheckerClient wkTextCheckerClient = { + kWKTextCheckerClientCurrentVersion, + this, + 0, // continuousSpellCheckingAllowed + isContinuousSpellCheckingEnabledCallback, + setContinuousSpellCheckingEnabledCallback, + 0, // grammarCheckingEnabled + 0, // setGrammarCheckingEnabled + uniqueSpellDocumentTagCallback, + closeSpellDocumentWithTagCallback, + checkSpellingOfStringCallback, + 0, // checkGrammarOfString, + 0, // spellingUIIsShowing + 0, // toggleSpellingUIIsShowing + 0, // updateSpellingUIWithMisspelledWord + 0, // updateSpellingUIWithGrammarString + guessesForWordCallback, + learnWordCallback, + ignoreWordCallback + }; + WKTextCheckerSetClient(&wkTextCheckerClient); +} + +TextCheckerClientEfl& TextCheckerClientEfl::instance() +{ + DEFINE_STATIC_LOCAL(TextCheckerClientEfl, textCheckerClient, ()); + return textCheckerClient; +} + +bool TextCheckerClientEfl::isContinuousSpellCheckingEnabled() const +{ + return isContinuousSpellCheckingEnabledCallback(0 /* clientInfo */); +} + +void TextCheckerClientEfl::ensureSpellCheckingLanguage() +{ + if (!m_textCheckerEnchant->hasDictionary()) + updateSpellCheckingLanguages(); +} + +void TextCheckerClientEfl::updateSpellCheckingLanguages(const Vector<String>& defaultLanguages) +{ + m_spellCheckingLanguages = defaultLanguages; + m_languagesUpdateTimer.startOneShot(0); +} + +void TextCheckerClientEfl::languagesUpdateTimerFired(Timer<TextCheckerClientEfl>*) +{ + m_textCheckerEnchant->updateSpellCheckingLanguages(m_spellCheckingLanguages); +} + +void TextCheckerClientEfl::spellCheckingSettingChangeTimerFired(Timer<TextCheckerClientEfl>*) +{ + m_clientCallbacks.continuous_spell_checking_change( + isContinuousSpellCheckingEnabledCallback(0 /* clientInfo */) + ); +} + +Vector<String> TextCheckerClientEfl::availableSpellCheckingLanguages() const +{ + return m_textCheckerEnchant->availableSpellCheckingLanguages(); +} + +Vector<String> TextCheckerClientEfl::loadedSpellCheckingLanguages() const +{ + return m_textCheckerEnchant->loadedSpellCheckingLanguages(); +} + +void TextCheckerClientEfl::callContinuousSpellCheckingChangeCallbackAsync() +{ + m_spellCheckingSettingChangeTimer.startOneShot(0); +} + +bool TextCheckerClientEfl::isContinuousSpellCheckingEnabledCallback(const void*) +{ + return TextChecker::state().isContinuousSpellCheckingEnabled; +} + +void TextCheckerClientEfl::setContinuousSpellCheckingEnabledCallback(bool, const void* clientInfo) +{ + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().continuous_spell_checking_change) + textCheckerClient->callContinuousSpellCheckingChangeCallbackAsync(); +} + +uint64_t TextCheckerClientEfl::uniqueSpellDocumentTagCallback(WKPageRef page, const void* clientInfo) +{ + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().unique_spell_document_tag_get) + return textCheckerClient->clientCallbacks().unique_spell_document_tag_get(EwkView::toEvasObject(page)); + + return 0; +} + +void TextCheckerClientEfl::closeSpellDocumentWithTagCallback(uint64_t tag, const void* clientInfo) +{ + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().unique_spell_document_tag_close) + textCheckerClient->clientCallbacks().unique_spell_document_tag_close(tag); +} + +void TextCheckerClientEfl::checkSpellingOfStringCallback(uint64_t tag, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void* clientInfo) +{ + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().string_spelling_check) + textCheckerClient->clientCallbacks().string_spelling_check(tag, WKEinaSharedString(text), misspellingLocation, misspellingLength); + else + textCheckerClient->m_textCheckerEnchant->checkSpellingOfString(toWTFString(text), *misspellingLocation, *misspellingLength); +} + +WKArrayRef TextCheckerClientEfl::guessesForWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) +{ + WKMutableArrayRef suggestionsForWord = WKMutableArrayCreate(); + + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().word_guesses_get) { + Eina_List* list = textCheckerClient->clientCallbacks().word_guesses_get(tag, WKEinaSharedString(word)); + void* item; + + EINA_LIST_FREE(list, item) { + WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(static_cast<const char*>(item))); + WKArrayAppendItem(suggestionsForWord, suggestion.get()); + free(item); + } + } else { + const Vector<String>& guesses = textCheckerClient->m_textCheckerEnchant->getGuessesForWord(toWTFString(word)); + size_t numberOfGuesses = guesses.size(); + for (size_t i = 0; i < numberOfGuesses; ++i) { + WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(guesses[i].utf8().data())); + WKArrayAppendItem(suggestionsForWord, suggestion.get()); + } + } + + return suggestionsForWord; +} + +void TextCheckerClientEfl::learnWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) +{ + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().word_learn) + textCheckerClient->clientCallbacks().word_learn(tag, WKEinaSharedString(word)); + else + textCheckerClient->m_textCheckerEnchant->learnWord(toWTFString(word)); +} + +void TextCheckerClientEfl::ignoreWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) +{ + TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); + if (textCheckerClient->clientCallbacks().word_ignore) + textCheckerClient->clientCallbacks().word_ignore(tag, WKEinaSharedString(word)); + else + textCheckerClient->m_textCheckerEnchant->ignoreWord(toWTFString(word)); +} + +#endif // ENABLE(SPELLCHECK) diff --git a/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.h b/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.h new file mode 100644 index 000000000..ed013b133 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2013 Samsung Electronics + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef TextCheckerClientEfl_h +#define TextCheckerClientEfl_h + +#if ENABLE(SPELLCHECK) + +#include "TextCheckerEnchant.h" +#include "Timer.h" +#include <WebKit2/WKTextChecker.h> +#include <WebKit2/ewk_text_checker_private.h> + +namespace WebKit { + +class TextCheckerClientEfl { +public: + static TextCheckerClientEfl& instance(); + + // Can be set by ewk APIs, by default they are 0. + ClientCallbacks& clientCallbacks() { return m_clientCallbacks; } + + bool isContinuousSpellCheckingEnabled() const; + + // Languages support. + void ensureSpellCheckingLanguage(); + Vector<String> availableSpellCheckingLanguages() const; + Vector<String> loadedSpellCheckingLanguages() const; + void updateSpellCheckingLanguages(const Vector<String>& defaultLanguages = Vector<String>()); + +private: + TextCheckerClientEfl(); + + // To set languages on timer. + void languagesUpdateTimerFired(WebCore::Timer<TextCheckerClientEfl>*); + WebCore::Timer<TextCheckerClientEfl> m_languagesUpdateTimer; + Vector<String> m_spellCheckingLanguages; + + // To notify the client about the setting change on timer. + void spellCheckingSettingChangeTimerFired(WebCore::Timer<TextCheckerClientEfl>*); + void callContinuousSpellCheckingChangeCallbackAsync(); + WebCore::Timer<TextCheckerClientEfl> m_spellCheckingSettingChangeTimer; + + // WKTextCheckerClient callbacks. + static bool isContinuousSpellCheckingEnabledCallback(const void*); + static void setContinuousSpellCheckingEnabledCallback(bool, const void*); + static uint64_t uniqueSpellDocumentTagCallback(WKPageRef, const void*); + static void closeSpellDocumentWithTagCallback(uint64_t, const void*); + static void checkSpellingOfStringCallback(uint64_t, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void*); + static WKArrayRef guessesForWordCallback(uint64_t, WKStringRef word, const void*); + static void learnWordCallback(uint64_t, WKStringRef word, const void*); + static void ignoreWordCallback(uint64_t, WKStringRef word, const void*); + + ClientCallbacks m_clientCallbacks; + OwnPtr<WebCore::TextCheckerEnchant> m_textCheckerEnchant; +}; + +} // namespace WebKit + +#endif // ENABLE(SPELLCHECK) +#endif // TextCheckerClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp b/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp index d56606e58..86a7d6c6b 100644 --- a/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2010 Apple Inc. All rights reserved. * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011-2012 Samsung Electronics + * Copyright (C) 2011-2013 Samsung Electronics * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,9 +28,12 @@ #include "config.h" #include "TextChecker.h" +#include "NotImplemented.h" #include "TextCheckerState.h" #if ENABLE(SPELLCHECK) +#include "TextBreakIterator.h" +#include "TextCheckerClientEfl.h" #include "WebTextChecker.h" #endif @@ -42,27 +45,22 @@ static TextCheckerState textCheckerState; const TextCheckerState& TextChecker::state() { -#if ENABLE(SPELLCHECK) static bool didInitializeState = false; if (didInitializeState) return textCheckerState; - WebTextCheckerClient& client = WebTextChecker::shared()->client(); - textCheckerState.isContinuousSpellCheckingEnabled = client.continuousSpellCheckingEnabled(); - textCheckerState.isGrammarCheckingEnabled = client.grammarCheckingEnabled(); + textCheckerState.isContinuousSpellCheckingEnabled = false; + textCheckerState.isGrammarCheckingEnabled = false; didInitializeState = true; -#endif + return textCheckerState; } bool TextChecker::isContinuousSpellCheckingAllowed() { -#if ENABLE(SPELLCHECK) - return WebTextChecker::shared()->client().continuousSpellCheckingAllowed(); -#else + notImplemented(); return false; -#endif } void TextChecker::setContinuousSpellCheckingEnabled(bool isContinuousSpellCheckingEnabled) @@ -72,39 +70,36 @@ void TextChecker::setContinuousSpellCheckingEnabled(bool isContinuousSpellChecki return; textCheckerState.isContinuousSpellCheckingEnabled = isContinuousSpellCheckingEnabled; + + // Notify the client about the setting change. WebTextChecker::shared()->client().setContinuousSpellCheckingEnabled(isContinuousSpellCheckingEnabled); #else UNUSED_PARAM(isContinuousSpellCheckingEnabled); #endif } -void TextChecker::setGrammarCheckingEnabled(bool isGrammarCheckingEnabled) +void TextChecker::setGrammarCheckingEnabled(bool) { -#if ENABLE(SPELLCHECK) - if (state().isGrammarCheckingEnabled == isGrammarCheckingEnabled) - return; - - textCheckerState.isGrammarCheckingEnabled = isGrammarCheckingEnabled; - WebTextChecker::shared()->client().setGrammarCheckingEnabled(isGrammarCheckingEnabled); -#else - UNUSED_PARAM(isGrammarCheckingEnabled); -#endif + notImplemented(); } void TextChecker::continuousSpellCheckingEnabledStateChanged(bool enabled) { - TextChecker::setContinuousSpellCheckingEnabled(enabled); -} - -void TextChecker::grammarCheckingEnabledStateChanged(bool enabled) -{ #if ENABLE(SPELLCHECK) - textCheckerState.isGrammarCheckingEnabled = enabled; + if (state().isContinuousSpellCheckingEnabled == enabled) + return; + + textCheckerState.isContinuousSpellCheckingEnabled = enabled; #else UNUSED_PARAM(enabled); #endif } +void TextChecker::grammarCheckingEnabledStateChanged(bool) +{ + notImplemented(); +} + int64_t TextChecker::uniqueSpellDocumentTag(WebPageProxy* page) { #if ENABLE(SPELLCHECK) @@ -124,68 +119,115 @@ void TextChecker::closeSpellDocumentWithTag(int64_t tag) #endif } -void TextChecker::checkSpellingOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, int32_t& misspellingLocation, int32_t& misspellingLength) +#if ENABLE(SPELLCHECK) +static int nextWordOffset(const UChar* text, int length, int currentOffset) +{ + // FIXME: avoid creating textIterator object here, it could be passed as a parameter. + // isTextBreak() leaves the iterator pointing to the first boundary position at + // or after "offset" (ubrk_isBoundary side effect). + // For many word separators, the method doesn't properly determine the boundaries + // without resetting the iterator. + TextBreakIterator* textIterator = wordBreakIterator(text, length); + if (!textIterator) + return currentOffset; + + int wordOffset = currentOffset; + while (wordOffset < length && isTextBreak(textIterator, wordOffset)) + ++wordOffset; + + // Do not treat the word's boundary as a separator. + if (!currentOffset && wordOffset == 1) + return currentOffset; + + // Omit multiple separators. + if ((wordOffset - currentOffset) > 1) + --wordOffset; + + return wordOffset; +} +#endif // ENABLE(SPELLCHECK) + +#if USE(UNIFIED_TEXT_CHECKING) +Vector<TextCheckingResult> TextChecker::checkTextOfParagraph(int64_t spellDocumentTag, const UChar* text, int length, uint64_t checkingTypes) { + Vector<TextCheckingResult> paragraphCheckingResult; #if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().checkSpellingOfString(spellDocumentTag, String(text, length), misspellingLocation, misspellingLength); + if (checkingTypes & TextCheckingTypeSpelling) { + TextBreakIterator* textIterator = wordBreakIterator(text, length); + if (!textIterator) + return paragraphCheckingResult; + + // Omit the word separators at the beginning/end of the text to don't unnecessarily + // involve the client to check spelling for them. + int offset = nextWordOffset(text, length, 0); + int lengthStrip = length; + while (lengthStrip > 0 && isTextBreak(textIterator, lengthStrip - 1)) + --lengthStrip; + + while (offset >= 0 && offset < lengthStrip) { + int32_t misspellingLocation = -1; + int32_t misspellingLength = 0; + checkSpellingOfString(spellDocumentTag, text + offset, lengthStrip - offset, misspellingLocation, misspellingLength); + if (!misspellingLength) + break; + + TextCheckingResult misspellingResult; + misspellingResult.type = TextCheckingTypeSpelling; + misspellingResult.location = offset + misspellingLocation; + misspellingResult.length = misspellingLength; + paragraphCheckingResult.append(misspellingResult); + offset += misspellingLocation + misspellingLength; + // Generally, we end up checking at the word separator, move to the adjacent word. + offset = nextWordOffset(text, lengthStrip, offset); + } + } #else UNUSED_PARAM(spellDocumentTag); UNUSED_PARAM(text); UNUSED_PARAM(length); - UNUSED_PARAM(misspellingLocation); - UNUSED_PARAM(misspellingLength); + UNUSED_PARAM(checkingTypes); #endif + return paragraphCheckingResult; } +#endif -void TextChecker::checkGrammarOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, Vector<GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength) +void TextChecker::checkSpellingOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, int32_t& misspellingLocation, int32_t& misspellingLength) { #if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().checkGrammarOfString(spellDocumentTag, String(text, length), grammarDetails, badGrammarLocation, badGrammarLength); + WebTextChecker::shared()->client().checkSpellingOfString(spellDocumentTag, String(text, length), misspellingLocation, misspellingLength); #else UNUSED_PARAM(spellDocumentTag); UNUSED_PARAM(text); UNUSED_PARAM(length); - UNUSED_PARAM(grammarDetails); - UNUSED_PARAM(badGrammarLocation); - UNUSED_PARAM(badGrammarLength); + UNUSED_PARAM(misspellingLocation); + UNUSED_PARAM(misspellingLength); #endif } +void TextChecker::checkGrammarOfString(int64_t, const UChar*, uint32_t, Vector<GrammarDetail>&, int32_t&, int32_t&) +{ + notImplemented(); +} + bool TextChecker::spellingUIIsShowing() { -#if ENABLE(SPELLCHECK) - return WebTextChecker::shared()->client().spellingUIIsShowing(); -#else + notImplemented(); return false; -#endif } void TextChecker::toggleSpellingUIIsShowing() { -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().toggleSpellingUIIsShowing(); -#endif + notImplemented(); } -void TextChecker::updateSpellingUIWithMisspelledWord(int64_t spellDocumentTag, const String& misspelledWord) +void TextChecker::updateSpellingUIWithMisspelledWord(int64_t, const String&) { -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().updateSpellingUIWithMisspelledWord(spellDocumentTag, misspelledWord); -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(misspelledWord); -#endif + notImplemented(); } -void TextChecker::updateSpellingUIWithGrammarString(int64_t spellDocumentTag, const String& badGrammarPhrase, const GrammarDetail& grammarDetail) +void TextChecker::updateSpellingUIWithGrammarString(int64_t, const String&, const GrammarDetail&) { -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().updateSpellingUIWithGrammarString(spellDocumentTag, badGrammarPhrase, grammarDetail); -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(badGrammarPhrase); - UNUSED_PARAM(grammarDetail); -#endif + notImplemented(); } void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& , Vector<String>& guesses) @@ -219,4 +261,23 @@ void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) #endif } +void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion> completion) +{ +#if ENABLE(SPELLCHECK) + if (!completion) + return; + + TextCheckingRequestData request = completion->textCheckingRequestData(); + ASSERT(request.sequence() != unrequestedTextCheckingSequence); + ASSERT(request.mask() != TextCheckingTypeNone); + + String text = request.text(); + Vector<TextCheckingResult> result = checkTextOfParagraph(completion->spellDocumentTag(), text.characters(), text.length(), request.mask()); + + completion->didFinishCheckingText(result); +#else + UNUSED_PARAM(completion); +#endif +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.cpp b/Source/WebKit2/UIProcess/efl/VibrationClientEfl.cpp index deb419f9b..5662a8ed0 100644 --- a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/VibrationClientEfl.cpp @@ -28,7 +28,7 @@ #if ENABLE(VIBRATION) -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WKAPICast.h" #include "WKVibration.h" @@ -40,27 +40,27 @@ static inline VibrationClientEfl* toVibrationClient(const void* clientInfo) return static_cast<VibrationClientEfl*>(const_cast<void*>(clientInfo)); } -void VibrationClientEfl::vibrateCallback(WKVibrationRef, uint64_t vibrationTime, const void* clientInfo) +void VibrationClientEfl::vibrateCallback(WKVibrationRef, uint32_t vibrationTime, const void* clientInfo) { - toVibrationClient(clientInfo)->m_viewImpl->smartCallback<Vibrate>().call(&vibrationTime); + toVibrationClient(clientInfo)->m_view->smartCallback<Vibrate>().call(&vibrationTime); } void VibrationClientEfl::cancelVibrationCallback(WKVibrationRef, const void* clientInfo) { - toVibrationClient(clientInfo)->m_viewImpl->smartCallback<CancelVibration>().call(); + toVibrationClient(clientInfo)->m_view->smartCallback<CancelVibration>().call(); } -PassOwnPtr<VibrationClientEfl> VibrationClientEfl::create(EwkViewImpl* viewImpl) +PassOwnPtr<VibrationClientEfl> VibrationClientEfl::create(EwkView* viewImpl) { return adoptPtr(new VibrationClientEfl(viewImpl)); } -VibrationClientEfl::VibrationClientEfl(EwkViewImpl* viewImpl) - : m_viewImpl(viewImpl) +VibrationClientEfl::VibrationClientEfl(EwkView* view) + : m_view(view) { - ASSERT(m_viewImpl); + ASSERT(m_view); - WKPageRef pageRef = m_viewImpl->wkPage(); + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKVibrationRef wkVibration = WKPageGetVibration(pageRef); @@ -77,7 +77,7 @@ VibrationClientEfl::VibrationClientEfl(EwkViewImpl* viewImpl) VibrationClientEfl::~VibrationClientEfl() { - WKPageRef pageRef = m_viewImpl->wkPage(); + WKPageRef pageRef = m_view->wkPage(); ASSERT(pageRef); WKVibrationRef wkVibration = WKPageGetVibration(pageRef); diff --git a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.h b/Source/WebKit2/UIProcess/efl/VibrationClientEfl.h index c6d3f79e1..ec49e9a2c 100644 --- a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.h +++ b/Source/WebKit2/UIProcess/efl/VibrationClientEfl.h @@ -31,23 +31,23 @@ #include <WebKit2/WKBase.h> #include <wtf/PassOwnPtr.h> -class EwkViewImpl; +class EwkView; namespace WebKit { class VibrationClientEfl { public: - static PassOwnPtr<VibrationClientEfl> create(EwkViewImpl*); + static PassOwnPtr<VibrationClientEfl> create(EwkView*); virtual ~VibrationClientEfl(); private: - explicit VibrationClientEfl(EwkViewImpl*); + explicit VibrationClientEfl(EwkView*); - static void vibrateCallback(WKVibrationRef, uint64_t vibrationTime, const void* clientInfo); + static void vibrateCallback(WKVibrationRef, uint32_t vibrationTime, const void* clientInfo); static void cancelVibrationCallback(WKVibrationRef, const void* clientInfo); - EwkViewImpl* m_viewImpl; + EwkView* m_view; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/ViewClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ViewClientEfl.cpp new file mode 100644 index 000000000..e14214fa4 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/ViewClientEfl.cpp @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ViewClientEfl.h" + +#include "EwkView.h" +#include "PageViewportController.h" +#include "WebViewportAttributes.h" +#include <WebKit2/WKString.h> +#include <WebKit2/WKView.h> +#include <WebKit2/WKViewEfl.h> + +using namespace EwkViewCallbacks; +using namespace WebCore; + +namespace WebKit { + +EwkView* ViewClientEfl::toEwkView(const void* clientInfo) +{ + return static_cast<ViewClientEfl*>(const_cast<void*>(clientInfo))->m_view; +} + +void ViewClientEfl::viewNeedsDisplay(WKViewRef, WKRect, const void* clientInfo) +{ + toEwkView(clientInfo)->scheduleUpdateDisplay(); +} + +void ViewClientEfl::didChangeContentsSize(WKViewRef, WKSize size, const void* clientInfo) +{ + EwkView* ewkView = toEwkView(clientInfo); + if (WKPageUseFixedLayout(ewkView->wkPage())) +#if USE(ACCELERATED_COMPOSITING) + ewkView->pageViewportController()->didChangeContentsSize(toIntSize(size)); +#else + { } +#endif + else + ewkView->scheduleUpdateDisplay(); + + ewkView->smartCallback<ContentsSizeChanged>().call(size); +} + +void ViewClientEfl::webProcessCrashed(WKViewRef, WKURLRef url, const void* clientInfo) +{ + EwkView* ewkView = toEwkView(clientInfo); + + // Check if loading was ongoing, when web process crashed. + double loadProgress = WKPageGetEstimatedProgress(ewkView->wkPage()); + if (loadProgress >= 0 && loadProgress < 1) { + loadProgress = 1; + ewkView->smartCallback<LoadProgress>().call(&loadProgress); + } + + ewkView->smartCallback<TooltipTextUnset>().call(); + + bool handled = false; + ewkView->smartCallback<WebProcessCrashed>().call(&handled); + + if (!handled) { + WKEinaSharedString urlString(url); + WARN("WARNING: The web process experienced a crash on '%s'.\n", static_cast<const char*>(urlString)); + + // Display an error page + ewk_view_html_string_load(ewkView->evasObject(), "The web process has crashed.", 0, urlString); + } +} + +void ViewClientEfl::webProcessDidRelaunch(WKViewRef viewRef, const void* clientInfo) +{ + if (const char* themePath = toEwkView(clientInfo)->themePath()) + WKViewSetThemePath(viewRef, adoptWK(WKStringCreateWithUTF8CString(themePath)).get()); +} + +void ViewClientEfl::didChangeContentsPosition(WKViewRef, WKPoint position, const void* clientInfo) +{ + EwkView* ewkView = toEwkView(clientInfo); + if (WKPageUseFixedLayout(ewkView->wkPage())) { +#if USE(ACCELERATED_COMPOSITING) + ewkView->pageViewportController()->pageDidRequestScroll(toIntPoint(position)); +#endif + return; + } + + ewkView->scheduleUpdateDisplay(); +} + +void ViewClientEfl::didRenderFrame(WKViewRef, WKSize contentsSize, WKRect coveredRect, const void* clientInfo) +{ + EwkView* ewkView = toEwkView(clientInfo); + if (WKPageUseFixedLayout(ewkView->wkPage())) { +#if USE(ACCELERATED_COMPOSITING) + ewkView->pageViewportController()->didRenderFrame(toIntSize(contentsSize), toIntRect(coveredRect)); +#endif + return; + } + + ewkView->scheduleUpdateDisplay(); +} + +void ViewClientEfl::didCompletePageTransition(WKViewRef, const void* clientInfo) +{ + EwkView* ewkView = toEwkView(clientInfo); + if (WKPageUseFixedLayout(ewkView->wkPage())) { +#if USE(ACCELERATED_COMPOSITING) + ewkView->pageViewportController()->pageTransitionViewportReady(); +#endif + return; + } + + ewkView->scheduleUpdateDisplay(); +} + +void ViewClientEfl::didChangeViewportAttributes(WKViewRef, WKViewportAttributesRef attributes, const void* clientInfo) +{ + EwkView* ewkView = toEwkView(clientInfo); + if (WKPageUseFixedLayout(ewkView->wkPage())) { +#if USE(ACCELERATED_COMPOSITING) + // FIXME: pageViewportController should accept WKViewportAttributesRef. + ewkView->pageViewportController()->didChangeViewportAttributes(toImpl(attributes)->originalAttributes()); +#endif + return; + } + ewkView->scheduleUpdateDisplay(); +} + +void ViewClientEfl::didChangeTooltip(WKViewRef, WKStringRef tooltip, const void* clientInfo) +{ + if (WKStringIsEmpty(tooltip)) + toEwkView(clientInfo)->smartCallback<TooltipTextUnset>().call(); + else + toEwkView(clientInfo)->smartCallback<TooltipTextSet>().call(WKEinaSharedString(tooltip)); +} + +void ViewClientEfl::didFindZoomableArea(WKViewRef, WKPoint point, WKRect area, const void* clientInfo) +{ + toEwkView(clientInfo)->didFindZoomableArea(point, area); +} + +#if ENABLE(TOUCH_EVENTS) +void ViewClientEfl::doneWithTouchEvent(WKViewRef, WKTouchEventRef event, bool wasEventHandled, const void* clientInfo) +{ + toEwkView(clientInfo)->doneWithTouchEvent(event, wasEventHandled); +} +#endif + +ViewClientEfl::ViewClientEfl(EwkView* view) + : m_view(view) +{ + ASSERT(m_view); + + WKViewClient viewClient; + memset(&viewClient, 0, sizeof(WKViewClient)); + viewClient.version = kWKViewClientCurrentVersion; + viewClient.clientInfo = this; + viewClient.didChangeContentsSize = didChangeContentsSize; + viewClient.didFindZoomableArea = didFindZoomableArea; + viewClient.viewNeedsDisplay = viewNeedsDisplay; + viewClient.webProcessCrashed = webProcessCrashed; + viewClient.webProcessDidRelaunch = webProcessDidRelaunch; + viewClient.didChangeContentsPosition = didChangeContentsPosition; + viewClient.didRenderFrame = didRenderFrame; + viewClient.didCompletePageTransition = didCompletePageTransition; + viewClient.didChangeViewportAttributes = didChangeViewportAttributes; + viewClient.didChangeTooltip = didChangeTooltip; +#if ENABLE(TOUCH_EVENTS) + viewClient.doneWithTouchEvent = doneWithTouchEvent; +#endif + + WKViewSetViewClient(m_view->wkView(), &viewClient); +} + +ViewClientEfl::~ViewClientEfl() +{ + WKViewSetViewClient(m_view->wkView(), 0); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/ViewClientEfl.h b/Source/WebKit2/UIProcess/efl/ViewClientEfl.h new file mode 100644 index 000000000..a384cf597 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/ViewClientEfl.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ViewClientEfl_h +#define ViewClientEfl_h + +#include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> +#include <wtf/PassOwnPtr.h> + +class EwkView; + +namespace WebKit { + +class ViewClientEfl { +public: + static PassOwnPtr<ViewClientEfl> create(EwkView* view) + { + return adoptPtr(new ViewClientEfl(view)); + } + + ~ViewClientEfl(); + +private: + explicit ViewClientEfl(EwkView*); + + static EwkView* toEwkView(const void* clientInfo); + static void viewNeedsDisplay(WKViewRef, WKRect area, const void* clientInfo); + static void didChangeContentsSize(WKViewRef, WKSize, const void* clientInfo); + static void webProcessCrashed(WKViewRef, WKURLRef, const void* clientInfo); + static void webProcessDidRelaunch(WKViewRef, const void* clientInfo); + static void didChangeContentsPosition(WKViewRef, WKPoint, const void* clientInfo); + static void didRenderFrame(WKViewRef, WKSize, WKRect, const void* clientInfo); + static void didCompletePageTransition(WKViewRef, const void* clientInfo); + static void didChangeViewportAttributes(WKViewRef, WKViewportAttributesRef, const void* clientInfo); + static void didChangeTooltip(WKViewRef, WKStringRef, const void* clientInfo); + static void didFindZoomableArea(WKViewRef, WKPoint, WKRect, const void* clientInfo); +#if ENABLE(TOUCH_EVENTS) + static void doneWithTouchEvent(WKViewRef, WKTouchEventRef, bool, const void* clientInfo); +#endif + + EwkView* m_view; +}; + +} // namespace WebKit + +#endif // ViewClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp b/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp index d43145caf..d2dca3dfc 100644 --- a/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp @@ -24,8 +24,14 @@ */ #include "config.h" +#include "WebCookieManagerProxy.h" #include "WebContext.h" +#include "Logging.h" +#include "WebInspectorServer.h" +#include "WebProcessCreationParameters.h" +#include "WebProcessMessages.h" +#include "WebSoupRequestManagerProxy.h" #include <Efreet.h> #include <WebCore/ApplicationCacheStorage.h> #include <WebCore/IconDatabase.h> @@ -33,14 +39,60 @@ namespace WebKit { -String WebContext::applicationCacheDirectory() +static void initializeInspectorServer() +{ +#if ENABLE(INSPECTOR_SERVER) + static bool initialized = false; + if (initialized) + return; + + // It should be set to true always. + // Because it is to ensure initializeInspectorServer() is executed only once, + // even if the server fails to run. + initialized = true; + + String serverAddress(getenv("WEBKIT_INSPECTOR_SERVER")); + if (!serverAddress.isNull()) { + String bindAddress = ASCIILiteral("127.0.0.1"); + unsigned short port = 2999; + + Vector<String> result; + serverAddress.split(':', result); + + if (result.size() == 2) { + bindAddress = result[0]; + bool ok = false; + port = result[1].toUInt(&ok); + if (!ok) { + port = 2999; + LOG_ERROR("Couldn't parse the port. Using 2999 instead."); + } + } else + LOG_ERROR("Couldn't parse %s, wrong format? Using 127.0.0.1:2999 instead.", serverAddress.utf8().data()); + + if (!WebInspectorServer::shared().listen(bindAddress, port)) + LOG_ERROR("Couldn't start listening on: IP address=%s, port=%d.", bindAddress.utf8().data(), port); + + return; + } + + LOG(InspectorServer, "To start inspector server set WEBKIT_INSPECTOR_SERVER to 127.0.0.1:2999 for example."); +#endif +} + +String WebContext::platformDefaultApplicationCacheDirectory() const { return String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl/Applications"; } -void WebContext::platformInitializeWebProcess(WebProcessCreationParameters&) +void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) { - notImplemented(); + initializeInspectorServer(); + + parameters.urlSchemesRegistered = supplement<WebSoupRequestManagerProxy>()->registeredURISchemes(); + supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(parameters.cookiePersistentStoragePath, parameters.cookiePersistentStorageType); + parameters.cookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy; + parameters.ignoreTLSErrors = m_ignoreTLSErrors; } void WebContext::platformInvalidateContext() @@ -65,8 +117,7 @@ String WebContext::platformDefaultLocalStorageDirectory() const String WebContext::platformDefaultDiskCacheDirectory() const { - notImplemented(); - return String(); + return String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl"; } String WebContext::platformDefaultCookieStorageDirectory() const @@ -75,4 +126,10 @@ String WebContext::platformDefaultCookieStorageDirectory() const return String(); } +void WebContext::setIgnoreTLSErrors(bool ignoreTLSErrors) +{ + m_ignoreTLSErrors = ignoreTLSErrors; + sendToAllProcesses(Messages::WebProcess::SetIgnoreTLSErrors(m_ignoreTLSErrors)); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp index ec7e0eb81..830d919c1 100644 --- a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp @@ -28,17 +28,17 @@ #if ENABLE(CONTEXT_MENUS) -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WebContextMenuItemData.h" #include "WebPageProxy.h" -#include <wtf/text/CString.h> +#include <WebCore/NotImplemented.h> using namespace WebCore; namespace WebKit { -WebContextMenuProxyEfl::WebContextMenuProxyEfl(EwkViewImpl* viewImpl, WebPageProxy* page) - : m_viewImpl(viewImpl) +WebContextMenuProxyEfl::WebContextMenuProxyEfl(EwkView* view, WebPageProxy* page) + : m_view(view) , m_page(page) { } @@ -47,19 +47,14 @@ WebContextMenuProxyEfl::~WebContextMenuProxyEfl() { } -void WebContextMenuProxyEfl::showContextMenu(const WebCore::IntPoint& position, const Vector<WebContextMenuItemData>& items) +void WebContextMenuProxyEfl::showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&) { - m_viewImpl->showContextMenu(this, position, items); + notImplemented(); } void WebContextMenuProxyEfl::hideContextMenu() { - m_viewImpl->hideContextMenu(); -} - -void WebContextMenuProxyEfl::contextMenuItemSelected(const WebContextMenuItemData& item) -{ - m_page->contextMenuItemSelected(item); + notImplemented(); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h b/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h index e7be2ab9c..b74a54f96 100644 --- a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h +++ b/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h @@ -32,7 +32,7 @@ #include <WebCore/ContextMenu.h> #include <WebCore/IntPoint.h> -class EwkViewImpl; +class EwkView; namespace WebKit { @@ -41,7 +41,7 @@ class WebPageProxy; class WebContextMenuProxyEfl : public WebContextMenuProxy { public: - static PassRefPtr<WebContextMenuProxyEfl> create(EwkViewImpl* viewImpl, WebPageProxy* page) + static PassRefPtr<WebContextMenuProxyEfl> create(EwkView* viewImpl, WebPageProxy* page) { return adoptRef(new WebContextMenuProxyEfl(viewImpl, page)); } @@ -51,12 +51,10 @@ public: void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); void hideContextMenu(); - void contextMenuItemSelected(const WebContextMenuItemData&); - private: - WebContextMenuProxyEfl(EwkViewImpl*, WebPageProxy*); + WebContextMenuProxyEfl(EwkView*, WebPageProxy*); - EwkViewImpl* m_viewImpl; + EwkView* m_view; WebPageProxy* m_page; }; diff --git a/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp index 468cbf884..4d834bc63 100644 --- a/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp @@ -25,10 +25,11 @@ #include "config.h" #include "WebFullScreenManagerProxy.h" +#include "WebFullScreenManagerProxyMessages.h" #if ENABLE(FULLSCREEN_API) -#include "EwkViewImpl.h" +#include "EwkView.h" #include <WebCore/NotImplemented.h> using namespace WebCore; @@ -37,6 +38,7 @@ namespace WebKit { void WebFullScreenManagerProxy::invalidate() { + m_page->process()->removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); m_webView = 0; } @@ -47,28 +49,30 @@ void WebFullScreenManagerProxy::close() bool WebFullScreenManagerProxy::isFullScreen() { - notImplemented(); - return false; + return m_hasRequestedFullScreen; } void WebFullScreenManagerProxy::enterFullScreen() { - if (!m_webView) + if (!m_webView || m_hasRequestedFullScreen) return; + m_hasRequestedFullScreen = true; + willEnterFullScreen(); - EwkViewImpl::fromEvasObject(m_webView)->enterFullScreen(); + toEwkView(m_webView)->enterFullScreen(); didEnterFullScreen(); } void WebFullScreenManagerProxy::exitFullScreen() { - if (!m_webView) + if (!m_webView || !m_hasRequestedFullScreen) return; + m_hasRequestedFullScreen = false; willExitFullScreen(); - EwkViewImpl::fromEvasObject(m_webView)->exitFullScreen(); + toEwkView(m_webView)->exitFullScreen(); didExitFullScreen(); } diff --git a/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp index b9b5d92b5..d11386f21 100644 --- a/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp @@ -28,13 +28,20 @@ #if ENABLE(INSPECTOR) -#include "EwkViewImpl.h" +#include "EwkView.h" #include "WebProcessProxy.h" +#include "ewk_context_private.h" +#include "ewk_page_group_private.h" #include "ewk_settings.h" #include "ewk_view.h" #include "ewk_view_private.h" +#include <WebCore/EflInspectorUtilities.h> #include <WebCore/NotImplemented.h> -#include <unistd.h> +#include <WebKit2/WKPage.h> +#include <WebKit2/WKPageGroup.h> +#include <WebKit2/WKPreferencesPrivate.h> +#include <WebKit2/WKString.h> +#include <WebKit2/WKViewEfl.h> #include <wtf/text/CString.h> #include <wtf/text/StringBuilder.h> #include <wtf/text/WTFString.h> @@ -87,25 +94,30 @@ WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() { ASSERT(m_page); -#if USE(ACCELERATED_COMPOSITING) && defined HAVE_ECORE_X +#ifdef HAVE_ECORE_X const char* engine = "opengl_x11"; m_inspectorWindow = ecore_evas_new(engine, 0, 0, initialWindowWidth, initialWindowHeight, 0); // Gracefully fall back to software if evas_gl engine is not available. if (!m_inspectorWindow) #endif - m_inspectorWindow = ecore_evas_new(0, 0, 0, initialWindowWidth, initialWindowHeight, 0); + m_inspectorWindow = ecore_evas_new(0, 0, 0, initialWindowWidth, initialWindowHeight, 0); if (!m_inspectorWindow) return 0; - m_inspectorView = ewk_view_base_add(ecore_evas_get(m_inspectorWindow), toAPI(page()->process()->context()), toAPI(inspectorPageGroup()), EwkViewImpl::LegacyBehavior); - EwkViewImpl* inspectorViewImpl = EwkViewImpl::fromEvasObject(m_inspectorView); - inspectorViewImpl->setThemePath(TEST_THEME_DIR "/default.edj"); + WKContextRef wkContext = toAPI(page()->process()->context()); + WKPageGroupRef wkPageGroup = toAPI(inspectorPageGroup()); - Ewk_Settings* settings = inspectorViewImpl->settings(); - ewk_settings_file_access_from_file_urls_allowed_set(settings, true); + m_inspectorView = EWKViewCreate(wkContext, wkPageGroup, ecore_evas_get(m_inspectorWindow), /* smart */ 0); + WKViewRef wkView = EWKViewGetWKView(m_inspectorView); - return inspectorViewImpl->page(); + WKRetainPtr<WKStringRef> wkTheme = adoptWK(WKStringCreateWithUTF8CString(TEST_THEME_DIR "/default.edj")); + WKViewSetThemePath(wkView, wkTheme.get()); + + WKPreferencesRef wkPreferences = WKPageGroupGetPreferences(wkPageGroup); + WKPreferencesSetFileAccessFromFileURLsAllowed(wkPreferences, true); + + return toImpl(WKViewGetPage(wkView)); } void WebInspectorProxy::platformOpen() @@ -131,6 +143,11 @@ void WebInspectorProxy::platformDidClose() } } +void WebInspectorProxy::platformHide() +{ + notImplemented(); +} + void WebInspectorProxy::platformBringToFront() { notImplemented(); @@ -162,11 +179,7 @@ String WebInspectorProxy::inspectorPageURL() const String WebInspectorProxy::inspectorBaseURL() const { - String inspectorFilesPath = WEB_INSPECTOR_INSTALL_DIR; - if (access(inspectorFilesPath.utf8().data(), R_OK)) - inspectorFilesPath = WEB_INSPECTOR_DIR; - - return "file://" + inspectorFilesPath; + return "file://" + WebCore::inspectorResourcePath(); } unsigned WebInspectorProxy::platformInspectedWindowHeight() @@ -175,6 +188,12 @@ unsigned WebInspectorProxy::platformInspectedWindowHeight() return 0; } +unsigned WebInspectorProxy::platformInspectedWindowWidth() +{ + notImplemented(); + return 0; +} + void WebInspectorProxy::platformAttach() { notImplemented(); @@ -190,6 +209,26 @@ void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned) notImplemented(); } +void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformSetToolbarHeight(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformSave(const String&, const String&, bool) +{ + notImplemented(); +} + +void WebInspectorProxy::platformAppend(const String&, const String&) +{ + notImplemented(); +} + void WebInspectorProxy::platformAttachAvailabilityChanged(bool) { notImplemented(); diff --git a/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp index befa247c2..a5e44e6d5 100644 --- a/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp @@ -26,23 +26,18 @@ #include "config.h" #include "WebPageProxy.h" -#include "EwkViewImpl.h" +#include "EwkView.h" #include "NativeWebKeyboardEvent.h" #include "NotImplemented.h" -#include "PageClientBase.h" #include "WebKitVersion.h" #include "WebPageMessages.h" #include "WebProcessProxy.h" +#include "WebView.h" #include <sys/utsname.h> namespace WebKit { -Evas_Object* WebPageProxy::viewWidget() -{ - return static_cast<PageClientBase*>(m_pageClient)->viewImpl()->view(); -} - String WebPageProxy::standardUserAgent(const String& /*applicationNameForUserAgent*/) { WTF::String platform; @@ -82,6 +77,9 @@ void WebPageProxy::loadRecentSearches(const String&, Vector<String>&) void WebPageProxy::setThemePath(const String& themePath) { + if (!isValid()) + return; + process()->send(Messages::WebPage::SetThemePath(themePath), m_pageID, 0); } @@ -124,4 +122,9 @@ void WebPageProxy::cancelComposition() process()->send(Messages::WebPage::CancelComposition(), m_pageID, 0); } +void WebPageProxy::initializeUIPopupMenuClient(const WKPageUIPopupMenuClient* client) +{ + m_uiPopupMenuClient.initialize(client); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.cpp b/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.cpp new file mode 100644 index 000000000..f420c0eba --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebPopupItemEfl.h" + +namespace WebKit { + +WebPopupItemEfl::WebPopupItemEfl(const WebPopupItem& data) + : m_data(data) +{ +} + +WebPopupItemEfl::~WebPopupItemEfl() +{ +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.h b/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.h index 6d13ff99d..c3245a481 100644 --- a/Source/WebKit2/UIProcess/efl/PageClientLegacyImpl.h +++ b/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.h @@ -1,6 +1,5 @@ /* - * Copyright (C) 2011 Samsung Electronics - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -13,7 +12,7 @@ * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF @@ -24,40 +23,41 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef PageClientLegacyImpl_h -#define PageClientLegacyImpl_h +#ifndef WebPopupItemEfl_h +#define WebPopupItemEfl_h -#include "PageClientBase.h" +#include "APIObject.h" +#include "WebPopupItem.h" +#include <wtf/PassRefPtr.h> namespace WebKit { -class PageClientLegacyImpl : public PageClientBase { +class WebPopupItemEfl : public TypedAPIObject<APIObject::TypePopupMenuItem> { public: - static PassOwnPtr<PageClientBase> create(EwkViewImpl* viewImpl) + static PassRefPtr<WebPopupItemEfl> create(const WebPopupItem& data) { - return adoptPtr(new PageClientLegacyImpl(viewImpl)); + return adoptRef(new WebPopupItemEfl(data)); } - virtual ~PageClientLegacyImpl() { } + virtual ~WebPopupItemEfl(); + const WebPopupItem& data() const { return m_data; } - virtual void didCommitLoad(); - virtual void updateViewportSize(const WebCore::IntSize&); - - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&); - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&); + WebPopupItem::Type itemType() const { return m_data.m_type; } + String text() const { return m_data.m_text; } + WebCore::TextDirection textDirection() const { return m_data.m_textDirection; } + bool hasTextDirectionOverride() const { return m_data.m_hasTextDirectionOverride; } + String toolTipText() const { return m_data.m_toolTip; } + String accessibilityText() const { return m_data.m_accessibilityText; } + bool isEnabled() const { return m_data.m_isEnabled; } + bool isLabel() const { return m_data.m_isLabel; } + bool isSelected() const { return m_data.m_isSelected; } private: - explicit PageClientLegacyImpl(EwkViewImpl*); - - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); - virtual void didChangeContentsSize(const WebCore::IntSize&); -#if USE(TILED_BACKING_STORE) - virtual void pageDidRequestScroll(const WebCore::IntPoint&); - virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect); - virtual void pageTransitionViewportReady(); -#endif + explicit WebPopupItemEfl(const WebPopupItem&); + + WebPopupItem m_data; }; } // namespace WebKit -#endif // PageClientLegacyImpl_h +#endif // WebPopupItemEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebPopupMenuProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.cpp index f5b104d9f..11b29e65b 100644 --- a/Source/WebKit2/UIProcess/efl/WebPopupMenuProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.cpp @@ -24,37 +24,22 @@ */ #include "config.h" -#include "WebPopupMenuProxyEfl.h" - -#include "EwkViewImpl.h" -#include "NativeWebMouseEvent.h" -#include "WebPopupItem.h" -#include "ewk_view.h" -#include <wtf/text/CString.h> - -using namespace WebCore; +#include "WebPopupMenuListenerEfl.h" namespace WebKit { -WebPopupMenuProxyEfl::WebPopupMenuProxyEfl(EwkViewImpl* viewImpl, WebPopupMenuProxy::Client* client) +WebPopupMenuListenerEfl::WebPopupMenuListenerEfl(WebPopupMenuProxy::Client* client) : WebPopupMenuProxy(client) - , m_viewImpl(viewImpl) { } -void WebPopupMenuProxyEfl::showPopupMenu(const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, const PlatformPopupMenuData&, int32_t selectedIndex) +void WebPopupMenuListenerEfl::valueChanged(int newSelectedIndex) { - m_viewImpl->requestPopupMenu(this, rect, textDirection, pageScaleFactor, items, selectedIndex); -} + if (!m_client) + return; -void WebPopupMenuProxyEfl::hidePopupMenu() -{ - m_viewImpl->closePopupMenu(); -} - -void WebPopupMenuProxyEfl::valueChanged(int newSelectedIndex) -{ m_client->valueChangedForPopupMenu(this, newSelectedIndex); + invalidate(); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebPopupMenuProxyEfl.h b/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.h index e4edb9635..6bcf83344 100644 --- a/Source/WebKit2/UIProcess/efl/WebPopupMenuProxyEfl.h +++ b/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.h @@ -23,41 +23,26 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebPopupMenuProxyEfl_h -#define WebPopupMenuProxyEfl_h +#ifndef WebPopupMenuListenerEfl_h +#define WebPopupMenuListenerEfl_h #include "WebPopupMenuProxy.h" -typedef struct _Evas_Object Evas_Object; - -namespace WebCore { -class IntRect; -} - -class EwkViewImpl; - namespace WebKit { -class WebPageProxy; - -class WebPopupMenuProxyEfl : public WebPopupMenuProxy { +class WebPopupMenuListenerEfl : public WebPopupMenuProxy { public: - static PassRefPtr<WebPopupMenuProxyEfl> create(EwkViewImpl* viewImpl, WebPopupMenuProxy::Client* client) + static PassRefPtr<WebPopupMenuListenerEfl> create(WebPopupMenuProxy::Client* client) { - return adoptRef(new WebPopupMenuProxyEfl(viewImpl, client)); + return adoptRef(new WebPopupMenuListenerEfl(client)); } - void showPopupMenu(const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>&, const PlatformPopupMenuData&, int32_t selectedIndex); - void hidePopupMenu(); - void valueChanged(int newSelectedIndex); private: - WebPopupMenuProxyEfl(EwkViewImpl*, WebPopupMenuProxy::Client*); - - EwkViewImpl* m_viewImpl; + WebPopupMenuListenerEfl(WebPopupMenuProxy::Client*); }; } // namespace WebKit -#endif // WebPopupMenuProxyEfl_h +#endif // WebPopupMenuListenerEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebProcessProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebProcessProxyEfl.cpp index c057e9c34..9ea9cfc3c 100644 --- a/Source/WebKit2/UIProcess/efl/WebProcessProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/efl/WebProcessProxyEfl.cpp @@ -28,7 +28,7 @@ namespace WebKit { -void WebProcessProxy::platformConnect(ProcessLauncher::LaunchOptions& launchOptions) +void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) { #ifndef NDEBUG const char* webProcessCmdPrefix = getenv("WEB_PROCESS_CMD_PREFIX"); diff --git a/Source/WebKit2/UIProcess/win/WebFullScreenManagerProxyWin.cpp b/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.cpp index b53e2bd48..2e6ff5a6b 100644 --- a/Source/WebKit2/UIProcess/win/WebFullScreenManagerProxyWin.cpp +++ b/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2013 Samsung Electronics. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -12,7 +12,7 @@ * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF @@ -24,63 +24,35 @@ */ #include "config.h" -#include "WebFullScreenManagerProxy.h" +#include "WebUIPopupMenuClient.h" -#if ENABLE(FULLSCREEN_API) - -#include "WebView.h" -#include <WebCore/FullScreenController.h> -#include <WebCore/IntRect.h> +#include "ImmutableArray.h" +#include "WKAPICast.h" +#include "WebPopupItemEfl.h" +#include "WebPopupMenuListenerEfl.h" using namespace WebCore; +using namespace WebKit; -namespace WebKit { - -void WebFullScreenManagerProxy::invalidate() +void WebUIPopupMenuClient::showPopupMenu(WebPageProxy* pageProxy, WebPopupMenuProxy* popupMenuProxy, const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, int32_t selectedIndex) { - if (!m_webView) + if (!m_client.showPopupMenu) return; - - m_webView->fullScreenController()->close(); - m_webView = 0; -} -void WebFullScreenManagerProxy::close() -{ - if (!m_webView) - return; - m_webView->fullScreenController()->close(); -} + Vector<RefPtr<APIObject> > webPopupItems; + size_t size = items.size(); + for (size_t i = 0; i < size; ++i) + webPopupItems.append(WebPopupItemEfl::create(items[i])); -bool WebFullScreenManagerProxy::isFullScreen() -{ - return m_webView->fullScreenController()->isFullScreen(); -} + RefPtr<ImmutableArray> ItemsArray; + if (!webPopupItems.isEmpty()) + ItemsArray = ImmutableArray::adopt(webPopupItems); -void WebFullScreenManagerProxy::enterFullScreen() -{ - if (!m_webView) - return; - m_webView->fullScreenController()->enterFullScreen(); + m_client.showPopupMenu(toAPI(pageProxy), toAPI(static_cast<WebPopupMenuListenerEfl*>(popupMenuProxy)), toAPI(rect), toAPI(textDirection), pageScaleFactor, toAPI(ItemsArray.get()), selectedIndex, m_client.clientInfo); } -void WebFullScreenManagerProxy::exitFullScreen() +void WebUIPopupMenuClient::hidePopupMenu(WebPageProxy* pageProxy) { - if (!m_webView) - return; - m_webView->fullScreenController()->exitFullScreen(); + if (m_client.hidePopupMenu) + m_client.hidePopupMenu(toAPI(pageProxy), m_client.clientInfo); } - -void WebFullScreenManagerProxy::beganEnterFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) -{ - // No-op. -} - -void WebFullScreenManagerProxy::beganExitFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) -{ - // No-op. -} - -} // namespace WebKit - -#endif diff --git a/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.h b/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.h new file mode 100644 index 000000000..25932e8be --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebUIPopupMenuClient_h +#define WebUIPopupMenuClient_h + +#include "APIClient.h" +#include "APIObject.h" +#include "WKPageEfl.h" +#include "WebPopupItem.h" +#include <WebCore/IntRect.h> +#include <WebCore/TextDirection.h> + +namespace WebKit { + +class WebPageProxy; +class WebPopupMenuProxy; + +class WebUIPopupMenuClient : public APIClient<WKPageUIPopupMenuClient, kWKPageUIPopupMenuClientCurrentVersion> { +public: + void showPopupMenu(WebPageProxy*, WebPopupMenuProxy*, const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, int32_t selectedIndex); + void hidePopupMenu(WebPageProxy*); +}; + +} // namespace WebKit +#endif // WebUIPopupMenuClient_h diff --git a/Source/WebKit2/UIProcess/efl/WebViewEfl.cpp b/Source/WebKit2/UIProcess/efl/WebViewEfl.cpp new file mode 100644 index 000000000..5660be111 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/WebViewEfl.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebViewEfl.h" + +#include "DownloadManagerEfl.h" +#include "EwkView.h" +#include "InputMethodContextEfl.h" +#include "WebContextMenuProxyEfl.h" +#include "WebPopupMenuListenerEfl.h" +#include "ewk_context_private.h" +#include <WebCore/CoordinatedGraphicsScene.h> +#include <WebCore/PlatformContextCairo.h> + +#if ENABLE(FULLSCREEN_API) +#include "WebFullScreenManagerProxy.h" +#endif + +#if ENABLE(TOUCH_EVENTS) +#include "EwkTouchEvent.h" +#endif + +using namespace EwkViewCallbacks; +using namespace WebCore; + +namespace WebKit { + +PassRefPtr<WebView> WebView::create(WebContext* context, WebPageGroup* pageGroup) +{ + return adoptRef(new WebViewEfl(context, pageGroup)); +} + +WebViewEfl::WebViewEfl(WebContext* context, WebPageGroup* pageGroup) + : WebView(context, pageGroup) + , m_ewkView(0) +{ +} + +void WebViewEfl::setEwkView(EwkView* ewkView) +{ + m_ewkView = ewkView; + +#if ENABLE(FULLSCREEN_API) + m_page->fullScreenManager()->setWebView(ewkView->evasObject()); +#endif +} + +void WebViewEfl::paintToCairoSurface(cairo_surface_t* surface) +{ + CoordinatedGraphicsScene* scene = coordinatedGraphicsScene(); + if (!scene) + return; + + PlatformContextCairo context(cairo_create(surface)); + + const FloatPoint& position = contentPosition(); + double effectiveScale = m_page->deviceScaleFactor() * contentScaleFactor(); + + cairo_matrix_t transform = { effectiveScale, 0, 0, effectiveScale, - position.x() * m_page->deviceScaleFactor(), - position.y() * m_page->deviceScaleFactor() }; + cairo_set_matrix(context.cr(), &transform); + scene->paintToGraphicsContext(&context); +} + +PassRefPtr<WebPopupMenuProxy> WebViewEfl::createPopupMenuProxy(WebPageProxy* page) +{ + return WebPopupMenuListenerEfl::create(page); +} + +PassRefPtr<WebContextMenuProxy> WebViewEfl::createContextMenuProxy(WebPageProxy* page) +{ + return WebContextMenuProxyEfl::create(m_ewkView, page); +} + +void WebViewEfl::setCursor(const Cursor& cursor) +{ + m_ewkView->setCursor(cursor); +} + +void WebViewEfl::updateTextInputState() +{ + if (InputMethodContextEfl* inputMethodContext = m_ewkView->inputMethodContext()) + inputMethodContext->updateTextInputState(); +} + +void WebViewEfl::handleDownloadRequest(DownloadProxy* download) +{ + EwkContext* context = m_ewkView->ewkContext(); + context->downloadManager()->registerDownloadJob(toAPI(download), m_ewkView); +} + +void WebViewEfl::setThemePath(const String& theme) +{ + m_page->setThemePath(theme); +} + +#if ENABLE(TOUCH_EVENTS) +void WebViewEfl::sendTouchEvent(EwkTouchEvent* touchEvent) +{ + ASSERT(touchEvent); + m_page->handleTouchEvent(NativeWebTouchEvent(touchEvent, transformFromScene())); +} +#endif + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebViewEfl.h b/Source/WebKit2/UIProcess/efl/WebViewEfl.h new file mode 100644 index 000000000..d717234c6 --- /dev/null +++ b/Source/WebKit2/UIProcess/efl/WebViewEfl.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2013 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef WebViewEfl_h +#define WebViewEfl_h + +#include "WebView.h" + +class EwkView; + +namespace WebKit { + +#if ENABLE(TOUCH_EVENTS) +class EwkTouchEvent; +#endif + +class WebViewEfl : public WebView { +public: + void setEwkView(EwkView*); + EwkView* ewkView() { return m_ewkView; } + + void paintToCairoSurface(cairo_surface_t*); + void setThemePath(const String&); + +#if ENABLE(TOUCH_EVENTS) + void sendTouchEvent(EwkTouchEvent*); +#endif + +private: + WebViewEfl(WebContext*, WebPageGroup*); + + void setCursor(const WebCore::Cursor&) OVERRIDE; + PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*) OVERRIDE; + PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*) OVERRIDE; + void updateTextInputState() OVERRIDE; + void handleDownloadRequest(DownloadProxy*) OVERRIDE; + +private: + EwkView* m_ewkView; + + friend class WebView; +}; + +} // namespace WebKit + +#endif // WebViewEfl_h diff --git a/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.cpp b/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.cpp new file mode 100644 index 000000000..2b45fb61f --- /dev/null +++ b/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2013, Opera Software ASA. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Opera Software ASA nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ExperimentalFeatures.h" + +namespace WebKit { + +struct Setting { + ExperimentalFeatures::Feature feature; + const char* featureName; + bool enabled; +}; + +static Setting settings[] = { + { ExperimentalFeatures::RegionBasedColumns, "REGION_BASED_COLUMNS", false } +}; + +ExperimentalFeatures::ExperimentalFeatures() +{ + parseEnvironment(); +} + +bool ExperimentalFeatures::isEnabled(Feature feature) +{ + return settings[feature].enabled; +} + +void ExperimentalFeatures::setEnableByName(const String& key, bool enable) +{ + for (unsigned i = 0; i < WTF_ARRAY_LENGTH(settings); i++) { + if (key == settings[i].featureName) { + settings[i].enabled = enable; + break; + } + } +} + +void ExperimentalFeatures::parseEnvironment() +{ + const char* data = getenv("WEBKITGTK_EXPERIMENTAL_FEATURES"); + if (!data) + return; + if (!strcmp(data, "all")) { + for (unsigned i = 0; i < WTF_ARRAY_LENGTH(settings); i++) + settings[i].enabled = true; + } else { + Vector<String> variables; + String(data).split(',', false, variables); + for (unsigned i = 0; i < variables.size(); i++) { + Vector<String> keyAndValue; + variables[i].split('=', false, keyAndValue); + if (keyAndValue.size() != 2) + continue; + setEnableByName(keyAndValue[0], keyAndValue[1][0] - '0'); + } + } +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.h b/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.h new file mode 100644 index 000000000..eb0422884 --- /dev/null +++ b/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2013, Opera Software ASA. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Opera Software ASA nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ExperimentalFeatures_h +#define ExperimentalFeatures_h + +#include <wtf/text/WTFString.h> + +namespace WebKit { + +class ExperimentalFeatures { +public: + enum Feature { + RegionBasedColumns + }; + + ExperimentalFeatures(); + + bool isEnabled(Feature); + +private: + void setEnableByName(const String& key, bool enable); + void parseEnvironment(); +}; + +} // namespace WebKit + +#endif // ExperimentalFeatures_h diff --git a/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp b/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp index 405c0e132..6bc419079 100644 --- a/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp @@ -29,6 +29,7 @@ #include "TextCheckerState.h" #include "WebTextChecker.h" +#include <WebCore/NotImplemented.h> using namespace WebCore; @@ -137,4 +138,9 @@ void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) WebTextChecker::shared()->client().ignoreWord(spellDocumentTag, word); } +void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion>) +{ + notImplemented(); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp index 46c452cba..22ba2f176 100644 --- a/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp @@ -29,7 +29,11 @@ #include "WebContext.h" #include "Logging.h" +#include "WebCookieManagerProxy.h" #include "WebInspectorServer.h" +#include "WebProcessCreationParameters.h" +#include "WebProcessMessages.h" +#include "WebSoupRequestManagerProxy.h" #include <WebCore/FileSystem.h> #include <WebCore/NotImplemented.h> #include <wtf/gobject/GOwnPtr.h> @@ -74,15 +78,21 @@ static void initInspectorServer() #endif } -WTF::String WebContext::applicationCacheDirectory() +WTF::String WebContext::platformDefaultApplicationCacheDirectory() const { GOwnPtr<gchar> cacheDirectory(g_build_filename(g_get_user_cache_dir(), "webkitgtk", "applications", NULL)); return WebCore::filenameToString(cacheDirectory.get()); } -void WebContext::platformInitializeWebProcess(WebProcessCreationParameters&) +void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) { initInspectorServer(); + + parameters.urlSchemesRegistered = supplement<WebSoupRequestManagerProxy>()->registeredURISchemes(); + supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(parameters.cookiePersistentStoragePath, parameters.cookiePersistentStorageType); + parameters.cookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy; + parameters.ignoreTLSErrors = m_ignoreTLSErrors; + parameters.shouldTrackVisitedLinks = true; } void WebContext::platformInvalidateContext() @@ -109,8 +119,8 @@ String WebContext::platformDefaultLocalStorageDirectory() const String WebContext::platformDefaultDiskCacheDirectory() const { - notImplemented(); - return String(); + GOwnPtr<char> diskCacheDirectory(g_build_filename(g_get_user_cache_dir(), g_get_prgname(), NULL)); + return WebCore::filenameToString(diskCacheDirectory.get()); } String WebContext::platformDefaultCookieStorageDirectory() const @@ -119,4 +129,10 @@ String WebContext::platformDefaultCookieStorageDirectory() const return String(); } +void WebContext::setIgnoreTLSErrors(bool ignoreTLSErrors) +{ + m_ignoreTLSErrors = ignoreTLSErrors; + sendToAllProcesses(Messages::WebProcess::SetIgnoreTLSErrors(m_ignoreTLSErrors)); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp index ed2b4df8f..d7d068340 100644 --- a/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp @@ -47,9 +47,9 @@ static void contextMenuItemActivatedCallback(GtkAction* action, WebPageProxy* pa { gboolean isToggle = GTK_IS_TOGGLE_ACTION(action); WebKit::WebContextMenuItemData item(isToggle ? WebCore::CheckableActionType : WebCore::ActionType, - static_cast<WebCore::ContextMenuAction>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(action), gContextMenuActionId))), - gtk_action_get_label(action), gtk_action_get_sensitive(action), - isToggle ? gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action)) : false); + static_cast<WebCore::ContextMenuAction>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(action), gContextMenuActionId))), + String::fromUTF8(gtk_action_get_label(action)), gtk_action_get_sensitive(action), + isToggle ? gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action)) : false); page->contextMenuItemSelected(item); } diff --git a/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp index 16147dccf..6fd0a9f2b 100644 --- a/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp @@ -35,6 +35,7 @@ namespace WebKit { void WebFullScreenManagerProxy::invalidate() { + m_page->process()->removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); m_webView = 0; } diff --git a/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp index 2b411fde0..a4c771a3c 100644 --- a/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp @@ -49,9 +49,8 @@ static const char* inspectorFilesBasePath() if (environmentPath && g_file_test(environmentPath, G_FILE_TEST_IS_DIR)) return environmentPath; - static const char* inspectorFilesPath = DATA_DIR""G_DIR_SEPARATOR_S - "webkitgtk-"WEBKITGTK_API_VERSION_STRING""G_DIR_SEPARATOR_S - "webinspector"G_DIR_SEPARATOR_S; + static const char* inspectorFilesPath = DATA_DIR G_DIR_SEPARATOR_S "webkitgtk-" WEBKITGTK_API_VERSION_STRING + G_DIR_SEPARATOR_S "webinspector" G_DIR_SEPARATOR_S; return inspectorFilesPath; } @@ -93,7 +92,7 @@ void WebInspectorProxy::createInspectorWindow() gtk_window_set_title(GTK_WINDOW(m_inspectorWindow), _("Web Inspector")); gtk_window_set_default_size(GTK_WINDOW(m_inspectorWindow), initialWindowWidth, initialWindowHeight); - webkitWebViewBaseAddWebInspector(WEBKIT_WEB_VIEW_BASE(m_inspectorWindow), m_inspectorView); + gtk_container_add(GTK_CONTAINER(m_inspectorWindow), m_inspectorView); gtk_widget_show(m_inspectorView); g_object_add_weak_pointer(G_OBJECT(m_inspectorWindow), reinterpret_cast<void**>(&m_inspectorWindow)); @@ -126,6 +125,11 @@ void WebInspectorProxy::platformDidClose() m_inspectorView = 0; } +void WebInspectorProxy::platformHide() +{ + notImplemented(); +} + void WebInspectorProxy::platformBringToFront() { if (m_client.bringToFront(this)) @@ -169,9 +173,12 @@ String WebInspectorProxy::inspectorBaseURL() const unsigned WebInspectorProxy::platformInspectedWindowHeight() { - GtkAllocation allocation; - gtk_widget_get_allocation(m_page->viewWidget(), &allocation); - return allocation.height; + return gtk_widget_get_allocated_height(m_page->viewWidget()); +} + +unsigned WebInspectorProxy::platformInspectedWindowWidth() +{ + return gtk_widget_get_allocated_width(m_page->viewWidget()); } void WebInspectorProxy::platformAttach() @@ -191,7 +198,7 @@ void WebInspectorProxy::platformAttach() if (m_client.attach(this)) return; - gtk_container_add(GTK_CONTAINER(m_page->viewWidget()), m_inspectorView); + webkitWebViewBaseAddWebInspector(WEBKIT_WEB_VIEW_BASE(m_page->viewWidget()), m_inspectorView); gtk_widget_show(m_inspectorView); } @@ -222,6 +229,26 @@ void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned height) webkitWebViewBaseSetInspectorViewHeight(WEBKIT_WEB_VIEW_BASE(m_page->viewWidget()), height); } +void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformSetToolbarHeight(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformSave(const String&, const String&, bool) +{ + notImplemented(); +} + +void WebInspectorProxy::platformAppend(const String&, const String&) +{ + notImplemented(); +} + void WebInspectorProxy::platformAttachAvailabilityChanged(bool) { notImplemented(); diff --git a/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp index 6b01bb027..4b5204941 100644 --- a/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp @@ -50,7 +50,10 @@ String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent void WebPageProxy::getEditorCommandsForKeyEvent(const AtomicString& eventType, Vector<WTF::String>& commandsList) { - m_pageClient->getEditorCommandsForKeyEvent(m_keyEventQueue.first(), eventType, commandsList); + // When the keyboard event is started in the WebProcess side (e.g. from the Inspector) + // it will arrive without a GdkEvent associated, so the keyEventQueue will be empty. + if (!m_keyEventQueue.isEmpty()) + m_pageClient->getEditorCommandsForKeyEvent(m_keyEventQueue.first(), eventType, commandsList); } void WebPageProxy::bindAccessibilityTree(const String& plugID) @@ -109,6 +112,11 @@ void WebPageProxy::windowedPluginGeometryDidChange(const WebCore::IntRect& frame webkitWebViewBaseChildMoveResize(WEBKIT_WEB_VIEW_BASE(viewWidget()), plugin, frameRect); } +void WebPageProxy::setInputMethodState(bool enabled) +{ + webkitWebViewBaseSetInputMethodState(WEBKIT_WEB_VIEW_BASE(viewWidget()), enabled); +} + #if USE(TEXTURE_MAPPER_GL) void WebPageProxy::setAcceleratedCompositingWindowId(uint64_t nativeWindowId) { diff --git a/Source/WebKit2/UIProcess/gtk/WebProcessProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebProcessProxyGtk.cpp index 3ad528f27..e8b173d07 100644 --- a/Source/WebKit2/UIProcess/gtk/WebProcessProxyGtk.cpp +++ b/Source/WebKit2/UIProcess/gtk/WebProcessProxyGtk.cpp @@ -28,7 +28,7 @@ namespace WebKit { -void WebProcessProxy::platformConnect(ProcessLauncher::LaunchOptions&) +void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions&) { } diff --git a/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm b/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm index ac59e6fbb..7256f2e35 100644 --- a/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm +++ b/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm @@ -100,8 +100,8 @@ void BackingStore::resetScrolledRect() IntSize scaledSize = m_scrolledRect.size(); scaledSize.scale(m_deviceScaleFactor); - RetainPtr<CGColorSpaceRef> colorSpace(AdoptCF, CGColorSpaceCreateDeviceRGB()); - RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(0, scaledSize.width(), scaledSize.height(), 8, scaledSize.width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); + RetainPtr<CGColorSpaceRef> colorSpace = adoptCF(CGColorSpaceCreateDeviceRGB()); + RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, scaledSize.width(), scaledSize.height(), 8, scaledSize.width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); CGContextScaleCTM(context.get(), m_deviceScaleFactor, m_deviceScaleFactor); @@ -147,7 +147,7 @@ CGContextRef BackingStore::backingStoreContext() // Try to create a layer. if (CGContextRef containingWindowContext = m_webPageProxy->containingWindowGraphicsContext()) { - m_cgLayer.adoptCF(CGLayerCreateWithContext(containingWindowContext, m_size, 0)); + m_cgLayer = adoptCF(CGLayerCreateWithContext(containingWindowContext, m_size, 0)); CGContextRef layerContext = CGLayerGetContext(m_cgLayer.get()); CGContextSetBlendMode(layerContext, kCGBlendModeCopy); @@ -166,11 +166,11 @@ CGContextRef BackingStore::backingStoreContext() } if (!m_bitmapContext) { - RetainPtr<CGColorSpaceRef> colorSpace(AdoptCF, CGColorSpaceCreateDeviceRGB()); + RetainPtr<CGColorSpaceRef> colorSpace = adoptCF(CGColorSpaceCreateDeviceRGB()); IntSize scaledSize(m_size); scaledSize.scale(m_deviceScaleFactor); - m_bitmapContext.adoptCF(CGBitmapContextCreate(0, scaledSize.width(), scaledSize.height(), 8, scaledSize.width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); + m_bitmapContext = adoptCF(CGBitmapContextCreate(0, scaledSize.width(), scaledSize.height(), 8, scaledSize.width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); CGContextSetBlendMode(m_bitmapContext.get(), kCGBlendModeCopy); diff --git a/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm b/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm index 33f3fe982..615e15227 100644 --- a/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm +++ b/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm @@ -144,7 +144,7 @@ void CorrectionPanel::handleAcceptedReplacement(NSString* acceptedReplacement, N [m_view.get() handleAcceptedAlternativeText:acceptedReplacement]; m_view.clear(); if (acceptedReplacement) - m_resultForDismissal.adoptNS([acceptedReplacement copy]); + m_resultForDismissal = adoptNS([acceptedReplacement copy]); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h b/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h index 78d6742f2..c4b952ae1 100644 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h +++ b/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h @@ -42,16 +42,13 @@ public: private: // CoreIPC::MessageReceiver. - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; // WebCore::GraphicsLayerClient. virtual void notifyAnimationStarted(const WebCore::GraphicsLayer*, double time) OVERRIDE; virtual void notifyFlushRequired(const WebCore::GraphicsLayer*) OVERRIDE; virtual void paintContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect) OVERRIDE; - // Implemented in generated RemoteLayerTreeHostMessageReceiver.cpp - void didReceiveRemoteLayerTreeHostMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); - // Message handlers. void commit(const RemoteLayerTreeTransaction&); diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm b/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm index 4308b1978..a006a384b 100644 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm +++ b/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm @@ -48,11 +48,6 @@ RemoteLayerTreeHost::~RemoteLayerTreeHost() m_webPageProxy->process()->removeMessageReceiver(Messages::RemoteLayerTreeHost::messageReceiverName(), m_webPageProxy->pageID()); } -void RemoteLayerTreeHost::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder&decoder) -{ - didReceiveRemoteLayerTreeHostMessage(connection, messageID, decoder); -} - void RemoteLayerTreeHost::notifyAnimationStarted(const GraphicsLayer*, double time) { } diff --git a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.cpp b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.cpp new file mode 100644 index 000000000..0eb69d1d8 --- /dev/null +++ b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "SecItemShimProxy.h" + +#if USE(SECURITY_FRAMEWORK) + +#include "SecItemRequestData.h" +#include "SecItemResponseData.h" +#include "SecItemShimMessages.h" +#include "SecItemShimProxyMessages.h" +#include <Security/SecItem.h> + +namespace WebKit { + +SecItemShimProxy& SecItemShimProxy::shared() +{ + static SecItemShimProxy* proxy; + static dispatch_once_t once; + dispatch_once(&once, ^{ + proxy = adoptRef(new SecItemShimProxy).leakRef(); + }); + return *proxy; +} + +SecItemShimProxy::SecItemShimProxy() + : m_queue(WorkQueue::create("com.apple.WebKit.SecItemShimProxy")) +{ +} + +void SecItemShimProxy::initializeConnection(CoreIPC::Connection* connection) +{ + connection->addWorkQueueMessageReceiver(Messages::SecItemShimProxy::messageReceiverName(), m_queue.get(), this); +} + +void SecItemShimProxy::secItemRequest(CoreIPC::Connection* connection, uint64_t requestID, const SecItemRequestData& request) +{ + SecItemResponseData response; + + switch (request.type()) { + case SecItemRequestData::Invalid: + ASSERT_NOT_REACHED(); + return; + + case SecItemRequestData::CopyMatching: { + CFTypeRef resultObject = 0; + OSStatus resultCode = SecItemCopyMatching(request.query(), &resultObject); + response = SecItemResponseData(resultCode, adoptCF(resultObject).get()); + break; + } + + case SecItemRequestData::Add: { + CFTypeRef resultObject = 0; + OSStatus resultCode = SecItemAdd(request.query(), &resultObject); + response = SecItemResponseData(resultCode, adoptCF(resultObject).get()); + break; + } + + case SecItemRequestData::Update: { + OSStatus resultCode = SecItemUpdate(request.query(), request.attributesToMatch()); + response = SecItemResponseData(resultCode, 0); + break; + } + + case SecItemRequestData::Delete: { + OSStatus resultCode = SecItemDelete(request.query()); + response = SecItemResponseData(resultCode, 0); + break; + } + } + + connection->send(Messages::SecItemShim::SecItemResponse(requestID, response), 0); +} + +} // namespace WebKit + +#endif // USE(SECURITY_FRAMEWORK) diff --git a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.h b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.h new file mode 100644 index 000000000..62684000d --- /dev/null +++ b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef SecItemShimProxy_h +#define SecItemShimProxy_h + +#if USE(SECURITY_FRAMEWORK) + +#include "Connection.h" + +namespace WebKit { + +class SecItemRequestData; + +class SecItemShimProxy : public CoreIPC::Connection::WorkQueueMessageReceiver { +WTF_MAKE_NONCOPYABLE(SecItemShimProxy); +public: + static SecItemShimProxy& shared(); + + void initializeConnection(CoreIPC::Connection*); + +private: + SecItemShimProxy(); + + // CoreIPC::Connection::WorkQueueMessageReceiver + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + + void secItemRequest(CoreIPC::Connection*, uint64_t requestID, const SecItemRequestData&); + + RefPtr<WorkQueue> m_queue; +}; + +} // namespace WebKit + +#endif // USE(SECURITY_FRAMEWORK) + +#endif // SecItemShimProxy_h diff --git a/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.messages.in b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.messages.in index b76389a70..b6baf8ac8 100644 --- a/Source/WebKit2/UIProcess/WebKeyValueStorageManagerProxy.messages.in +++ b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2011 Apple Inc. All rights reserved. +# Copyright (C) 2013 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -20,6 +20,10 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> WebKeyValueStorageManagerProxy { - DidGetKeyValueStorageOrigins(Vector<WebKit::SecurityOriginData> originIdentifiers, uint64_t callbackID); +messages -> SecItemShimProxy { + +#if USE(SECURITY_FRAMEWORK) + SecItemRequest(uint64_t requestID, WebKit::SecItemRequestData request) WantsConnection +#endif + } diff --git a/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm b/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm index 6da8a4301..c9e3d6bc3 100644 --- a/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm +++ b/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm @@ -30,11 +30,9 @@ #import <WebCore/NotImplemented.h> #import <wtf/RetainPtr.h> -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 @interface NSSpellChecker (WebNSSpellCheckerDetails) - (NSString *)languageForWordRange:(NSRange)range inString:(NSString *)string orthography:(NSOrthography *)orthography; @end -#endif static NSString* const WebAutomaticSpellingCorrectionEnabled = @"WebAutomaticSpellingCorrectionEnabled"; static NSString* const WebContinuousSpellCheckingEnabled = @"WebContinuousSpellCheckingEnabled"; @@ -51,24 +49,56 @@ namespace WebKit { TextCheckerState textCheckerState; +static bool shouldAutomaticTextReplacementBeEnabled() +{ + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + if (![defaults objectForKey:WebAutomaticTextReplacementEnabled]) + return [NSSpellChecker isAutomaticTextReplacementEnabled]; + return [defaults boolForKey:WebAutomaticTextReplacementEnabled]; +} + +static bool shouldAutomaticSpellingCorrectionBeEnabled() +{ + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + if (![defaults objectForKey:WebAutomaticSpellingCorrectionEnabled]) + return [NSSpellChecker isAutomaticTextReplacementEnabled]; + return [defaults boolForKey:WebAutomaticSpellingCorrectionEnabled]; +} + +static bool shouldAutomaticQuoteSubstitutionBeEnabled() +{ + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + if (![defaults objectForKey:WebAutomaticQuoteSubstitutionEnabled]) + return [NSSpellChecker isAutomaticQuoteSubstitutionEnabled]; +#endif + return [defaults boolForKey:WebAutomaticQuoteSubstitutionEnabled]; +} + +static bool shouldAutomaticDashSubstitutionBeEnabled() +{ + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + if (![defaults objectForKey:WebAutomaticDashSubstitutionEnabled]) + return [NSSpellChecker isAutomaticDashSubstitutionEnabled]; +#endif + return [defaults boolForKey:WebAutomaticDashSubstitutionEnabled]; +} + static void initializeState() { - static bool didInitializeState; + static bool didInitializeState = false; + if (didInitializeState) return; textCheckerState.isContinuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled] && TextChecker::isContinuousSpellCheckingAllowed(); textCheckerState.isGrammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled]; - textCheckerState.isAutomaticSpellingCorrectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticSpellingCorrectionEnabled]; - textCheckerState.isAutomaticQuoteSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticQuoteSubstitutionEnabled]; - textCheckerState.isAutomaticDashSubstitutionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticDashSubstitutionEnabled]; + textCheckerState.isAutomaticTextReplacementEnabled = shouldAutomaticTextReplacementBeEnabled(); + textCheckerState.isAutomaticSpellingCorrectionEnabled = shouldAutomaticSpellingCorrectionBeEnabled(); + textCheckerState.isAutomaticQuoteSubstitutionEnabled = shouldAutomaticQuoteSubstitutionBeEnabled(); + textCheckerState.isAutomaticDashSubstitutionEnabled = shouldAutomaticDashSubstitutionBeEnabled(); textCheckerState.isAutomaticLinkDetectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticLinkDetectionEnabled]; - textCheckerState.isAutomaticTextReplacementEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticTextReplacementEnabled]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 - if (![[NSUserDefaults standardUserDefaults] objectForKey:WebAutomaticSpellingCorrectionEnabled]) - textCheckerState.isAutomaticSpellingCorrectionEnabled = [NSSpellChecker isAutomaticSpellingCorrectionEnabled]; -#endif didInitializeState = true; } @@ -198,6 +228,34 @@ void TextChecker::setSmartInsertDeleteEnabled(bool flag) [[NSUserDefaults standardUserDefaults] setBool:flag forKey:WebSmartInsertDeleteEnabled]; } +void TextChecker::didChangeAutomaticTextReplacementEnabled() +{ + textCheckerState.isAutomaticTextReplacementEnabled = shouldAutomaticTextReplacementBeEnabled(); + [[NSSpellChecker sharedSpellChecker] updatePanels]; +} + +void TextChecker::didChangeAutomaticSpellingCorrectionEnabled() +{ + textCheckerState.isAutomaticSpellingCorrectionEnabled = shouldAutomaticSpellingCorrectionBeEnabled(); + [[NSSpellChecker sharedSpellChecker] updatePanels]; +} + +void TextChecker::didChangeAutomaticQuoteSubstitutionEnabled() +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + textCheckerState.isAutomaticQuoteSubstitutionEnabled = shouldAutomaticQuoteSubstitutionBeEnabled(); + [[NSSpellChecker sharedSpellChecker] updatePanels]; +#endif +} + +void TextChecker::didChangeAutomaticDashSubstitutionEnabled() +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + textCheckerState.isAutomaticDashSubstitutionEnabled = shouldAutomaticDashSubstitutionBeEnabled(); + [[NSSpellChecker sharedSpellChecker] updatePanels]; +#endif +} + bool TextChecker::substitutionsPanelIsShowing() { return [[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible]; @@ -239,7 +297,7 @@ Vector<TextCheckingResult> TextChecker::checkTextOfParagraph(int64_t spellDocume { Vector<TextCheckingResult> results; - RetainPtr<NSString> textString(AdoptNS, [[NSString alloc] initWithCharactersNoCopy:const_cast<UChar*>(text) length:length freeWhenDone:NO]); + RetainPtr<NSString> textString = adoptNS([[NSString alloc] initWithCharactersNoCopy:const_cast<UChar*>(text) length:length freeWhenDone:NO]); NSArray *incomingResults = [[NSSpellChecker sharedSpellChecker] checkString:textString .get() range:NSMakeRange(0, length) types:checkingTypes | NSTextCheckingTypeOrthography @@ -357,7 +415,7 @@ void TextChecker::updateSpellingUIWithMisspelledWord(int64_t, const String& miss void TextChecker::updateSpellingUIWithGrammarString(int64_t, const String& badGrammarPhrase, const GrammarDetail& grammarDetail) { - RetainPtr<NSMutableArray> corrections(AdoptNS, [[NSMutableArray alloc] init]); + RetainPtr<NSMutableArray> corrections = adoptNS([[NSMutableArray alloc] init]); for (size_t i = 0; i < grammarDetail.guesses.size(); ++i) { NSString *guess = grammarDetail.guesses[i]; [corrections.get() addObject:guess]; @@ -365,14 +423,13 @@ void TextChecker::updateSpellingUIWithGrammarString(int64_t, const String& badGr NSRange grammarRange = NSMakeRange(grammarDetail.location, grammarDetail.length); NSString *grammarUserDescription = grammarDetail.userDescription; - RetainPtr<NSDictionary> grammarDetailDict(AdoptNS, [[NSDictionary alloc] initWithObjectsAndKeys:[NSValue valueWithRange:grammarRange], NSGrammarRange, grammarUserDescription, NSGrammarUserDescription, corrections.get(), NSGrammarCorrections, nil]); + RetainPtr<NSDictionary> grammarDetailDict = adoptNS([[NSDictionary alloc] initWithObjectsAndKeys:[NSValue valueWithRange:grammarRange], NSGrammarRange, grammarUserDescription, NSGrammarUserDescription, corrections.get(), NSGrammarCorrections, nil]); [[NSSpellChecker sharedSpellChecker] updateSpellingPanelWithGrammarString:badGrammarPhrase detail:grammarDetailDict.get()]; } void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& context, Vector<String>& guesses) { -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 NSString* language = nil; NSOrthography* orthography = nil; NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker]; @@ -381,9 +438,6 @@ void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word language = [checker languageForWordRange:NSMakeRange(0, context.length()) inString:context orthography:orthography]; } NSArray* stringsArray = [checker guessesForWordRange:NSMakeRange(0, word.length()) inString:word language:language inSpellDocumentWithTag:spellDocumentTag]; -#else - NSArray* stringsArray = [[NSSpellChecker sharedSpellChecker] guessesForWord:word]; -#endif for (NSString *guess in stringsArray) guesses.append(guess); @@ -399,4 +453,9 @@ void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) [[NSSpellChecker sharedSpellChecker] ignoreWord:word inSpellDocumentWithTag:spellDocumentTag]; } +void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion>) +{ + notImplemented(); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h b/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h index c78610984..ad1043b4b 100644 --- a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h +++ b/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h @@ -46,16 +46,16 @@ private: virtual void layerHostingModeDidChange() OVERRIDE; virtual void visibilityDidChange() OVERRIDE; virtual void sizeDidChange() OVERRIDE; - virtual void waitForPossibleGeometryUpdate() OVERRIDE; + virtual void waitForPossibleGeometryUpdate(double timeout = didUpdateBackingStoreStateTimeout) OVERRIDE; virtual void colorSpaceDidChange() OVERRIDE; - virtual void minimumLayoutWidthDidChange() OVERRIDE; + virtual void minimumLayoutSizeDidChange() OVERRIDE; virtual void enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&) OVERRIDE; virtual void exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo&) OVERRIDE; virtual void updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&) OVERRIDE; // Message handlers. - virtual void didUpdateGeometry(const WebCore::IntSize& newIntrinsicContentSize) OVERRIDE; + virtual void didUpdateGeometry() OVERRIDE; virtual void intrinsicContentSizeDidChange(const WebCore::IntSize& newIntrinsicContentSize) OVERRIDE; void sendUpdateGeometry(); @@ -65,9 +65,10 @@ private: // The last size we sent to the web process. WebCore::IntSize m_lastSentSize; + WebCore::IntSize m_lastSentLayerPosition; - // The last minimum layout width we sent to the web process. - double m_lastSentMinimumLayoutWidth; + // The last minimum layout size we sent to the web process. + WebCore::IntSize m_lastSentMinimumLayoutSize; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm b/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm index 3de8be7a6..973768df9 100644 --- a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm +++ b/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm @@ -47,7 +47,6 @@ PassOwnPtr<TiledCoreAnimationDrawingAreaProxy> TiledCoreAnimationDrawingAreaProx TiledCoreAnimationDrawingAreaProxy::TiledCoreAnimationDrawingAreaProxy(WebPageProxy* webPageProxy) : DrawingAreaProxy(DrawingAreaTypeTiledCoreAnimation, webPageProxy) , m_isWaitingForDidUpdateGeometry(false) - , m_lastSentMinimumLayoutWidth(0) { } @@ -86,7 +85,7 @@ void TiledCoreAnimationDrawingAreaProxy::sizeDidChange() sendUpdateGeometry(); } -void TiledCoreAnimationDrawingAreaProxy::waitForPossibleGeometryUpdate() +void TiledCoreAnimationDrawingAreaProxy::waitForPossibleGeometryUpdate(double timeout) { if (!m_isWaitingForDidUpdateGeometry) return; @@ -94,9 +93,7 @@ void TiledCoreAnimationDrawingAreaProxy::waitForPossibleGeometryUpdate() if (m_webPageProxy->process()->isLaunching()) return; - // The timeout, in seconds, we use when waiting for a DidUpdateGeometry message. - static const double didUpdateBackingStoreStateTimeout = 0.5; - m_webPageProxy->process()->connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateGeometry>(m_webPageProxy->pageID(), didUpdateBackingStoreStateTimeout); + m_webPageProxy->process()->connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateGeometry>(m_webPageProxy->pageID(), timeout); } void TiledCoreAnimationDrawingAreaProxy::colorSpaceDidChange() @@ -104,7 +101,7 @@ void TiledCoreAnimationDrawingAreaProxy::colorSpaceDidChange() m_webPageProxy->process()->send(Messages::DrawingArea::SetColorSpace(m_webPageProxy->colorSpace()), m_webPageProxy->pageID()); } -void TiledCoreAnimationDrawingAreaProxy::minimumLayoutWidthDidChange() +void TiledCoreAnimationDrawingAreaProxy::minimumLayoutSizeDidChange() { if (!m_webPageProxy->isValid()) return; @@ -133,26 +130,23 @@ void TiledCoreAnimationDrawingAreaProxy::updateAcceleratedCompositingMode(uint64 m_webPageProxy->updateAcceleratedCompositingMode(layerTreeContext); } -void TiledCoreAnimationDrawingAreaProxy::didUpdateGeometry(const IntSize& newIntrinsicContentSize) +void TiledCoreAnimationDrawingAreaProxy::didUpdateGeometry() { ASSERT(m_isWaitingForDidUpdateGeometry); m_isWaitingForDidUpdateGeometry = false; - double minimumLayoutWidth = m_webPageProxy->minimumLayoutWidth(); + IntSize minimumLayoutSize = m_webPageProxy->minimumLayoutSize(); // If the WKView was resized while we were waiting for a DidUpdateGeometry reply from the web process, // we need to resend the new size here. - if (m_lastSentSize != m_size || m_lastSentMinimumLayoutWidth != minimumLayoutWidth) + if (m_lastSentSize != m_size || m_lastSentLayerPosition != m_layerPosition || m_lastSentMinimumLayoutSize != minimumLayoutSize) sendUpdateGeometry(); - - if (minimumLayoutWidth > 0) - m_webPageProxy->intrinsicContentSizeDidChange(newIntrinsicContentSize); } void TiledCoreAnimationDrawingAreaProxy::intrinsicContentSizeDidChange(const IntSize& newIntrinsicContentSize) { - if (m_webPageProxy->minimumLayoutWidth() > 0) + if (m_webPageProxy->minimumLayoutSize().width() > 0) m_webPageProxy->intrinsicContentSizeDidChange(newIntrinsicContentSize); } @@ -160,9 +154,10 @@ void TiledCoreAnimationDrawingAreaProxy::sendUpdateGeometry() { ASSERT(!m_isWaitingForDidUpdateGeometry); - m_lastSentMinimumLayoutWidth = m_webPageProxy->minimumLayoutWidth(); + m_lastSentMinimumLayoutSize = m_webPageProxy->minimumLayoutSize(); m_lastSentSize = m_size; - m_webPageProxy->process()->send(Messages::DrawingArea::UpdateGeometry(m_size, m_lastSentMinimumLayoutWidth), m_webPageProxy->pageID()); + m_lastSentLayerPosition = m_layerPosition; + m_webPageProxy->process()->send(Messages::DrawingArea::UpdateGeometry(m_size, m_layerPosition), m_webPageProxy->pageID()); m_isWaitingForDidUpdateGeometry = true; } diff --git a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h index d832ab663..c174a7a79 100644 --- a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h +++ b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h @@ -42,6 +42,8 @@ class IntRect; @class WebWindowScaleAnimation; @class WebWindowFadeAnimation; +typedef enum FullScreenState : NSInteger FullScreenState; + @interface WKFullScreenWindowController : NSWindowController<NSWindowDelegate> { @private WKView *_webView; @@ -52,16 +54,17 @@ class IntRect; NSRect _initialFrame; NSRect _finalFrame; RetainPtr<NSTimer> _watchdogTimer; - - BOOL _isEnteringFullScreen; - BOOL _isExitingFullScreen; - BOOL _isFullScreen; - BOOL _isPlaying; + + FullScreenState _fullScreenState; + + double _savedScale; } - (WKView*)webView; - (void)setWebView:(WKView*)webView; +- (WebCoreFullScreenPlaceholderView*)webViewPlaceholder; + - (BOOL)isFullScreen; - (void)enterFullScreen:(NSScreen *)screen; diff --git a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm index 7a891cb71..dd02ee212 100644 --- a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm +++ b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm @@ -45,7 +45,6 @@ #import <WebCore/WebWindowAnimation.h> #import <WebKit/WebNSWindowExtras.h> #import <WebKitSystemInterface.h> -#import <wtf/UnusedParam.h> using namespace WebKit; using namespace WebCore; @@ -55,6 +54,15 @@ static RetainPtr<NSWindow> createBackgroundFullscreenWindow(NSRect frame); static const CFTimeInterval defaultAnimationDuration = 0.5; static const NSTimeInterval DefaultWatchdogTimerInterval = 1; +enum FullScreenState : NSInteger { + NotInFullScreen, + WaitingToEnterFullScreen, + EnteringFullScreen, + InFullScreen, + WaitingToExitFullScreen, + ExitingFullScreen, +}; + @interface NSWindow (WebNSWindowDetails) - (void)exitFullScreenMode:(id)sender; - (void)enterFullScreenMode:(id)sender; @@ -68,20 +76,10 @@ static const NSTimeInterval DefaultWatchdogTimerInterval = 1; - (void)_startExitFullScreenAnimationWithDuration:(NSTimeInterval)duration; @end -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 static NSRect convertRectToScreen(NSWindow *window, NSRect rect) { return [window convertRectToScreen:rect]; } -#else -static NSRect convertRectToScreen(NSWindow *window, NSRect rect) -{ - NSRect frame = [window frame]; - rect.origin.x += frame.origin.x; - rect.origin.y += frame.origin.y; - return rect; -} -#endif @interface NSWindow(IsOnActiveSpaceAdditionForTigerAndLeopard) - (BOOL)isOnActiveSpace; @@ -91,14 +89,13 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) #pragma mark - #pragma mark Initialization -- (id)init +- (id)initWithWindow:(NSWindow *)window { - RetainPtr<NSWindow> window = adoptNS([[WebCoreFullScreenWindow alloc] initWithContentRect:NSZeroRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]); - self = [super initWithWindow:window.get()]; + self = [super initWithWindow:window]; if (!self) return nil; - [window.get() setDelegate:self]; - [window.get() setCollectionBehavior:([window collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary)]; + [window setDelegate:self]; + [window setCollectionBehavior:([window collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary)]; [self windowDidLoad]; return self; @@ -119,7 +116,6 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) { [super windowDidLoad]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidResignActive:) name:NSApplicationDidResignActiveNotification object:NSApp]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidChangeScreenParameters:) name:NSApplicationDidChangeScreenParametersNotification object:NSApp]; } @@ -140,7 +136,14 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) - (BOOL)isFullScreen { - return _isFullScreen; + return _fullScreenState == WaitingToEnterFullScreen + || _fullScreenState == EnteringFullScreen + || _fullScreenState == InFullScreen; +} + +- (WebCoreFullScreenPlaceholderView*)webViewPlaceholder +{ + return _webViewPlaceholder.get(); } #pragma mark - @@ -148,11 +151,10 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) - (void)cancelOperation:(id)sender { - [self _manager]->requestExitFullScreen(); - // If the page doesn't respond in DefaultWatchdogTimerInterval seconds, it could be because // the WebProcess has hung, so exit anyway. if (!_watchdogTimer) { + [self _manager]->requestExitFullScreen(); _watchdogTimer = adoptNS([[NSTimer alloc] initWithFireDate:nil interval:DefaultWatchdogTimerInterval target:self selector:@selector(exitFullScreen) userInfo:nil repeats:NO]); [[NSRunLoop mainRunLoop] addTimer:_watchdogTimer.get() forMode:NSDefaultRunLoopMode]; } @@ -161,21 +163,6 @@ static NSRect convertRectToScreen(NSWindow *window, NSRect rect) #pragma mark - #pragma mark Notifications -- (void)applicationDidResignActive:(NSNotification*)notification -{ - // Check to see if the fullScreenWindow is on the active space; this function is available - // on 10.6 and later, so default to YES if the function is not available: - NSWindow* fullScreenWindow = [self window]; - BOOL isOnActiveSpace = ([fullScreenWindow respondsToSelector:@selector(isOnActiveSpace)] ? [fullScreenWindow isOnActiveSpace] : YES); - - // Replicate the QuickTime Player (X) behavior when losing active application status: - // Is the fullScreen screen the main screen? (Note: this covers the case where only a - // single screen is available.) Is the fullScreen screen on the current space? IFF so, - // then exit fullScreen mode. - if ([fullScreenWindow screen] == [[NSScreen screens] objectAtIndex:0] && isOnActiveSpace) - [self cancelOperation:self]; -} - - (void)applicationDidChangeScreenParameters:(NSNotification*)notification { // The user may have changed the main screen by moving the menu bar, or they may have changed @@ -215,9 +202,9 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) - (void)enterFullScreen:(NSScreen *)screen { - if (_isFullScreen) + if ([self isFullScreen]) return; - _isFullScreen = YES; + _fullScreenState = WaitingToEnterFullScreen; if (!screen) screen = [NSScreen mainScreen]; @@ -229,7 +216,7 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) webViewFrame.origin.y = NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]) - NSMaxY(webViewFrame); CGWindowID windowID = [[_webView window] windowNumber]; - RetainPtr<CGImageRef> webViewContents(AdoptCF, CGWindowListCreateImage(NSRectToCGRect(webViewFrame), kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageShouldBeOpaque)); + RetainPtr<CGImageRef> webViewContents = adoptCF(CGWindowListCreateImage(NSRectToCGRect(webViewFrame), kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageShouldBeOpaque)); // Using the returned CGImage directly would result in calls to the WindowServer every time // the image was painted. Instead, copy the image data into our own process to eliminate that @@ -241,6 +228,7 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) [[self window] setAutodisplay:NO]; NSResponder *webWindowFirstResponder = [[_webView window] firstResponder]; + [self _manager]->saveScrollPosition(); [[self window] setFrame:screenFrame display:NO]; // Painting is normally suspended when the WKView is removed from the window, but this is @@ -251,10 +239,10 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) // Swap the webView placeholder into place. if (!_webViewPlaceholder) { - _webViewPlaceholder.adoptNS([[WebCoreFullScreenPlaceholderView alloc] initWithFrame:[_webView frame]]); - [_webViewPlaceholder.get() setTarget:self]; + _webViewPlaceholder = adoptNS([[WebCoreFullScreenPlaceholderView alloc] initWithFrame:[_webView frame]]); [_webViewPlaceholder.get() setAction:@selector(cancelOperation:)]; } + [_webViewPlaceholder.get() setTarget:nil]; [_webViewPlaceholder.get() setContents:(id)webViewContents.get()]; [self _replaceView:_webView with:_webViewPlaceholder.get()]; @@ -267,13 +255,15 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) [self _manager]->setAnimatingFullScreen(true); [self _manager]->willEnterFullScreen(); + _savedScale = [self _page]->pageScaleFactor(); + [self _page]->scalePage(1, IntPoint()); } - (void)beganEnterFullScreenWithInitialFrame:(const WebCore::IntRect&)initialFrame finalFrame:(const WebCore::IntRect&)finalFrame { - if (_isEnteringFullScreen) + if (_fullScreenState != WaitingToEnterFullScreen) return; - _isEnteringFullScreen = YES; + _fullScreenState = EnteringFullScreen; _initialFrame = initialFrame; _finalFrame = finalFrame; @@ -286,9 +276,9 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) - (void)finishedEnterFullScreenAnimation:(bool)completed { - if (!_isEnteringFullScreen) + if (_fullScreenState != EnteringFullScreen) return; - _isEnteringFullScreen = NO; + _fullScreenState = InFullScreen; if (completed) { // Screen updates to be re-enabled ta the end of the current block. @@ -308,6 +298,7 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) [_backgroundWindow.get() setFrame:NSZeroRect display:YES]; [_webViewPlaceholder.get() setExitWarningVisible:YES]; + [_webViewPlaceholder.get() setTarget:self]; NSEnableScreenUpdates(); } else [_scaleAnimation.get() stopAnimation]; @@ -320,9 +311,9 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) _watchdogTimer.clear(); } - if (!_isFullScreen) + if (![self isFullScreen]) return; - _isFullScreen = NO; + _fullScreenState = WaitingToExitFullScreen; [_webViewPlaceholder.get() setExitWarningVisible:NO]; @@ -333,6 +324,7 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) // See the related comment in enterFullScreen: // We will resume the normal behavior in _startExitFullScreenAnimationWithDuration: [_webView _setSuppressVisibilityUpdates:YES]; + [_webViewPlaceholder.get() setTarget:nil]; [self _manager]->setAnimatingFullScreen(true); [self _manager]->willExitFullScreen(); @@ -340,12 +332,10 @@ static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) - (void)beganExitFullScreenWithInitialFrame:(const WebCore::IntRect&)initialFrame finalFrame:(const WebCore::IntRect&)finalFrame { - if (_isExitingFullScreen) - return; - _isExitingFullScreen = YES; - if (_isEnteringFullScreen) - [self finishedEnterFullScreenAnimation:NO]; + if (_fullScreenState != WaitingToExitFullScreen) + return; + _fullScreenState = ExitingFullScreen; if (![[self window] isOnActiveSpace]) { // If the full screen window is not in the active space, the NSWindow full screen animation delegate methods @@ -365,9 +355,9 @@ static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void*) - (void)finishedExitFullScreenAnimation:(bool)completed { - if (!_isExitingFullScreen) + if (_fullScreenState != ExitingFullScreen) return; - _isExitingFullScreen = NO; + _fullScreenState = NotInFullScreen; // Screen updates to be re-enabled in completeFinishExitFullScreenAnimationAfterRepaint. NSDisableScreenUpdates(); @@ -396,7 +386,8 @@ static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void*) // These messages must be sent after the swap or flashing will occur during forceRepaint: [self _manager]->didExitFullScreen(); [self _manager]->setAnimatingFullScreen(false); - + [self _page]->scalePage(_savedScale, IntPoint()); + [self _manager]->restoreScrollPosition(); [self _page]->forceRepaint(VoidCallback::create(self, completeFinishExitFullScreenAnimationAfterRepaint)); } @@ -412,16 +403,22 @@ static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void* [(WKFullScreenWindowController*)_self completeFinishExitFullScreenAnimationAfterRepaint]; } +- (void)performClose:(id)sender +{ + if ([self isFullScreen]) + [self cancelOperation:sender]; +} + - (void)close { // We are being asked to close rapidly, most likely because the page // has closed or the web process has crashed. Just walk through our // normal exit full screen sequence, but don't wait to be called back // in response. - if (_isFullScreen) + if ([self isFullScreen]) [self exitFullScreen]; - if (_isExitingFullScreen) + if (_fullScreenState == ExitingFullScreen) [self finishedExitFullScreenAnimation:YES]; [super close]; @@ -529,7 +526,7 @@ static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFr NSRect screenFrame = [[[self window] screen] frame]; NSRect initialWindowFrame = windowFrameFromApparentFrames(screenFrame, _initialFrame, _finalFrame); - _scaleAnimation.adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:initialWindowFrame finalFrame:screenFrame]); + _scaleAnimation = adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:initialWindowFrame finalFrame:screenFrame]); [_scaleAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; [_scaleAnimation.get() setCurrentProgress:0]; @@ -559,7 +556,7 @@ static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFr [_fadeAnimation.get() setWindow:nil]; } - _fadeAnimation.adoptNS([[WebWindowFadeAnimation alloc] initWithDuration:duration + _fadeAnimation = adoptNS([[WebWindowFadeAnimation alloc] initWithDuration:duration window:_backgroundWindow.get() initialAlpha:currentAlpha finalAlpha:1]); @@ -577,11 +574,19 @@ static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFr - (void)_startExitFullScreenAnimationWithDuration:(NSTimeInterval)duration { + if ([self isFullScreen]) { + // We still believe we're in full screen mode, so we must have been asked to exit full + // screen by the system full screen button. + [self _manager]->requestExitFullScreen(); + [self exitFullScreen]; + _fullScreenState = ExitingFullScreen; + } + NSRect screenFrame = [[[self window] screen] frame]; NSRect initialWindowFrame = windowFrameFromApparentFrames(screenFrame, _initialFrame, _finalFrame); NSRect currentFrame = _scaleAnimation ? [_scaleAnimation.get() currentFrame] : [[self window] frame]; - _scaleAnimation.adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:currentFrame finalFrame:initialWindowFrame]); + _scaleAnimation = adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:currentFrame finalFrame:initialWindowFrame]); [_scaleAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; [_scaleAnimation.get() setCurrentProgress:0]; @@ -598,7 +603,7 @@ static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFr [_fadeAnimation.get() stopAnimation]; [_fadeAnimation.get() setWindow:nil]; } - _fadeAnimation.adoptNS([[WebWindowFadeAnimation alloc] initWithDuration:duration + _fadeAnimation = adoptNS([[WebWindowFadeAnimation alloc] initWithDuration:duration window:_backgroundWindow.get() initialAlpha:currentAlpha finalAlpha:0]); diff --git a/Source/WebKit2/UIProcess/mac/WebContextMac.mm b/Source/WebKit2/UIProcess/mac/WebContextMac.mm index 5ba161b4d..a07faae4f 100644 --- a/Source/WebKit2/UIProcess/mac/WebContextMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebContextMac.mm @@ -26,21 +26,36 @@ #import "config.h" #import "WebContext.h" -#import "NetworkProcessManager.h" #import "PluginProcessManager.h" #import "SharedWorkerProcessManager.h" +#import "TextChecker.h" +#import "WKBrowsingContextControllerInternal.h" #import "WKBrowsingContextControllerInternal.h" #import "WebKitSystemInterface.h" #import "WebProcessCreationParameters.h" #import "WebProcessMessages.h" +#import <QuartzCore/CARemoteLayerServer.h> #import <WebCore/Color.h> #import <WebCore/FileSystem.h> -#include <WebCore/NotImplemented.h> +#import <WebCore/NotImplemented.h> #import <WebCore/PlatformPasteboard.h> #import <sys/param.h> -#if HAVE(HOSTED_CORE_ANIMATION) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 -#import <QuartzCore/CARemoteLayerServer.h> +#if ENABLE(NETWORK_PROCESS) +#import "NetworkProcessCreationParameters.h" +#import "NetworkProcessProxy.h" +#endif + + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + +#if __has_include(<CFNetwork/CFURLProtocolPriv.h>) +#include <CFNetwork/CFURLProtocolPriv.h> +#else +extern "C" Boolean _CFNetworkIsKnownHSTSHostWithSession(CFURLRef url, CFURLStorageSessionRef session); +extern "C" void _CFNetworkResetHSTSHostsWithSession(CFURLStorageSessionRef session); +#endif + #endif using namespace WebCore; @@ -55,69 +70,222 @@ static NSString *WebKitApplicationDidChangeAccessibilityEnhancedUserInterfaceNot // FIXME: <rdar://problem/9138817> - After this "backwards compatibility" radar is removed, this code should be removed to only return an empty String. NSString *WebIconDatabaseDirectoryDefaultsKey = @"WebIconDatabaseDirectoryDefaultsKey"; +static NSString * const WebKit2HTTPProxyDefaultsKey = @"WebKit2HTTPProxy"; +static NSString * const WebKit2HTTPSProxyDefaultsKey = @"WebKit2HTTPSProxy"; + namespace WebKit { NSString *SchemeForCustomProtocolRegisteredNotificationName = @"WebKitSchemeForCustomProtocolRegisteredNotification"; NSString *SchemeForCustomProtocolUnregisteredNotificationName = @"WebKitSchemeForCustomProtocolUnregisteredNotification"; -bool WebContext::s_applicationIsOccluded = false; +static bool s_applicationIsOccluded = false; +static bool s_applicationWindowModificationsHaveStopped = false; +static bool s_occlusionNotificationHandlersRegistered = false; +static bool s_processSuppressionEnabledForAllContexts = true; -String WebContext::applicationCacheDirectory() +static void registerUserDefaultsIfNeeded() { - NSString *appName = [[NSBundle mainBundle] bundleIdentifier]; - if (!appName) - appName = [[NSProcessInfo processInfo] processName]; - - ASSERT(appName); - - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSString *cacheDir = [defaults objectForKey:WebKitLocalCacheDefaultsKey]; + static bool didRegister; + if (didRegister) + return; - if (!cacheDir || ![cacheDir isKindOfClass:[NSString class]]) { - char cacheDirectory[MAXPATHLEN]; - size_t cacheDirectoryLen = confstr(_CS_DARWIN_USER_CACHE_DIR, cacheDirectory, MAXPATHLEN); + didRegister = true; + NSMutableDictionary *registrationDictionary = [NSMutableDictionary dictionary]; - if (cacheDirectoryLen) - cacheDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:cacheDirectory length:cacheDirectoryLen - 1]; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + [registrationDictionary setObject:[NSNumber numberWithBool:YES] forKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]; +#endif + + [[NSUserDefaults standardUserDefaults] registerDefaults:registrationDictionary]; +} + +static void updateProcessSuppressionStateOfGlobalChildProcesses() +{ + // The plan is to have all child processes become context specific. This function + // can be removed once that is complete. +#if ENABLE(PLUGIN_PROCESS) || ENABLE(SHARED_WORKER_PROCESS) + bool canEnable = WebContext::canEnableProcessSuppressionForGlobalChildProcesses(); +#endif +#if ENABLE(PLUGIN_PROCESS) + PluginProcessManager::shared().setProcessSuppressionEnabled(canEnable); +#endif +#if ENABLE(SHARED_WORKER_PROCESS) + SharedWorkerProcessManager::shared().setProcessSuppressionEnabled(canEnable); +#endif +} + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 +static void applicationOcclusionStateChanged() +{ + const Vector<WebContext*>& contexts = WebContext::allContexts(); + for (size_t i = 0, count = contexts.size(); i < count; ++i) { + if (contexts[i]->processSuppressionEnabled()) + contexts[i]->updateProcessSuppressionStateOfChildProcesses(); } - return [cacheDir stringByAppendingPathComponent:appName]; + if (s_processSuppressionEnabledForAllContexts) + updateProcessSuppressionStateOfGlobalChildProcesses(); } -static void registerUserDefaultsIfNeeded() +static void applicationBecameVisible(uint32_t, void*, uint32_t, void*, uint32_t) { - static bool didRegister; - if (didRegister) + if (!s_applicationIsOccluded) return; + s_applicationIsOccluded = false; + applicationOcclusionStateChanged(); +} - didRegister = true; +static void applicationBecameOccluded(uint32_t, void*, uint32_t, void*, uint32_t) +{ + if (s_applicationIsOccluded) + return; + s_applicationIsOccluded = true; + applicationOcclusionStateChanged(); +} + +static void applicationWindowModificationsStarted(uint32_t, void*, uint32_t, void*, uint32_t) +{ + if (!s_applicationWindowModificationsHaveStopped) + return; + s_applicationWindowModificationsHaveStopped = false; + applicationOcclusionStateChanged(); +} + +static void applicationWindowModificationsStopped(uint32_t, void*, uint32_t, void*, uint32_t) +{ + if (s_applicationWindowModificationsHaveStopped) + return; + s_applicationWindowModificationsHaveStopped = true; + applicationOcclusionStateChanged(); +} + +struct OcclusionNotificationHandler { + WKOcclusionNotificationType notificationType; + WKOcclusionNotificationHandler handler; + const char *name; +}; + +static const OcclusionNotificationHandler occlusionNotificationHandlers[] = { + { WKOcclusionNotificationTypeApplicationBecameVisible, applicationBecameVisible, "Application Became Visible" }, + { WKOcclusionNotificationTypeApplicationBecameOccluded, applicationBecameOccluded, "Application Became Occluded" }, + { WKOcclusionNotificationTypeApplicationWindowModificationsStarted, applicationWindowModificationsStarted, "Application Window Modifications Started" }, + { WKOcclusionNotificationTypeApplicationWindowModificationsStopped, applicationWindowModificationsStopped, "Application Window Modifications Stopped" }, +}; + +#endif + +static void registerOcclusionNotificationHandlers() +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + for (const OcclusionNotificationHandler& occlusionNotificationHandler : occlusionNotificationHandlers) { + bool result = WKRegisterOcclusionNotificationHandler(occlusionNotificationHandler.notificationType, occlusionNotificationHandler.handler); + UNUSED_PARAM(result); + ASSERT_WITH_MESSAGE(result, "Registration of \"%s\" notification handler failed.\n", occlusionNotificationHandler.name); + } +#endif +} + +static void unregisterOcclusionNotificationHandlers() +{ #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]]; + for (const OcclusionNotificationHandler& occlusionNotificationHandler : occlusionNotificationHandlers) { + bool result = WKUnregisterOcclusionNotificationHandler(occlusionNotificationHandler.notificationType, occlusionNotificationHandler.handler); + UNUSED_PARAM(result); + ASSERT_WITH_MESSAGE(result, "Unregistration of \"%s\" notification handler failed.\n", occlusionNotificationHandler.name); + } #endif } +static void enableOcclusionNotifications() +{ + if (s_occlusionNotificationHandlersRegistered) + return; + + s_occlusionNotificationHandlersRegistered = true; + registerOcclusionNotificationHandlers(); +} + +static void disableOcclusionNotifications() +{ + if (!s_occlusionNotificationHandlersRegistered) + return; + + s_occlusionNotificationHandlersRegistered = false; + unregisterOcclusionNotificationHandlers(); +} + +static bool processSuppressionIsEnabledForAnyContext() +{ + bool result = false; + const Vector<WebContext*>& contexts = WebContext::allContexts(); + for (size_t i = 0, count = contexts.size(); i < count; ++i) { + if (contexts[i]->processSuppressionEnabled()) { + result = true; + break; + } + } + return result; +} + +static bool processSuppressionIsEnabledForAllContexts() +{ + bool result = true; + const Vector<WebContext*>& contexts = WebContext::allContexts(); + for (size_t i = 0, count = contexts.size(); i < count; ++i) { + if (!contexts[i]->processSuppressionEnabled()) { + result = false; + break; + } + } + return result; +} + +static bool omitProcessSuppression() +{ + static bool result = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKit2OmitProcessSuppression"]; + return result; +} + +void WebContext::platformInitialize() +{ + registerUserDefaultsIfNeeded(); + registerNotificationObservers(); + ASSERT(m_processSuppressionEnabled); + enableOcclusionNotifications(); +} + +String WebContext::platformDefaultApplicationCacheDirectory() const +{ + NSString *appName = [[NSBundle mainBundle] bundleIdentifier]; + if (!appName) + appName = [[NSProcessInfo processInfo] processName]; + + ASSERT(appName); + + char cacheDirectory[MAXPATHLEN]; + size_t cacheDirectoryLen = confstr(_CS_DARWIN_USER_CACHE_DIR, cacheDirectory, MAXPATHLEN); + if (!cacheDirectoryLen) + return String(); + + NSString *cacheDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:cacheDirectory length:cacheDirectoryLen - 1]; + return [cacheDir stringByAppendingPathComponent:appName]; +} + void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) { parameters.presenterApplicationPid = getpid(); - parameters.parentProcessName = [[NSProcessInfo processInfo] processName]; - NSURLCache *urlCache = [NSURLCache sharedURLCache]; parameters.nsURLCacheMemoryCapacity = [urlCache memoryCapacity]; parameters.nsURLCacheDiskCapacity = [urlCache diskCapacity]; - registerUserDefaultsIfNeeded(); #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 parameters.shouldForceScreenFontSubstitution = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"]; #endif parameters.shouldEnableKerningAndLigaturesByDefault = [[NSUserDefaults standardUserDefaults] boolForKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]; #if USE(ACCELERATED_COMPOSITING) && HAVE(HOSTED_CORE_ANIMATION) -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 mach_port_t renderServerPort = [[CARemoteLayerServer sharedServer] serverPort]; -#else - mach_port_t renderServerPort = WKInitializeRenderServer(); -#endif if (renderServerPort != MACH_PORT_NULL) parameters.acceleratedCompositingPort = CoreIPC::MachPort(renderServerPort, MACH_MSG_TYPE_COPY_SEND); #endif @@ -127,37 +295,43 @@ void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& para SandboxExtension::createHandle(parameters.uiProcessBundleResourcePath, SandboxExtension::ReadOnly, parameters.uiProcessBundleResourcePathExtensionHandle); parameters.uiProcessBundleIdentifier = String([[NSBundle mainBundle] bundleIdentifier]); - - NSArray *schemes = [[WKBrowsingContextController customSchemes] allObjects]; - for (size_t i = 0; i < [schemes count]; ++i) - parameters.urlSchemesRegisteredForCustomProtocols.append([schemes objectAtIndex:i]); - - m_customSchemeRegisteredObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKit::SchemeForCustomProtocolRegisteredNotificationName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - NSString *scheme = [notification object]; - ASSERT([scheme isKindOfClass:[NSString class]]); - sendToAllProcesses(Messages::WebProcess::RegisterSchemeForCustomProtocol(scheme)); - }]; - - m_customSchemeUnregisteredObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKit::SchemeForCustomProtocolUnregisteredNotificationName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - NSString *scheme = [notification object]; - ASSERT([scheme isKindOfClass:[NSString class]]); - sendToAllProcesses(Messages::WebProcess::UnregisterSchemeForCustomProtocol(scheme)); - }]; - - // Listen for enhanced accessibility changes and propagate them to the WebProcess. - m_enhancedAccessibilityObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKitApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { - setEnhancedAccessibility([[[note userInfo] objectForKey:@"AXEnhancedUserInterface"] boolValue]); - }]; + +#if ENABLE(NETWORK_PROCESS) + if (!m_usesNetworkProcess) { +#endif + for (NSString *scheme in [WKBrowsingContextController customSchemes]) + parameters.urlSchemesRegisteredForCustomProtocols.append(scheme); +#if ENABLE(NETWORK_PROCESS) + } +#endif } +#if ENABLE(NETWORK_PROCESS) +void WebContext::platformInitializeNetworkProcess(NetworkProcessCreationParameters& parameters) +{ + NSURLCache *urlCache = [NSURLCache sharedURLCache]; + parameters.nsURLCacheMemoryCapacity = [urlCache memoryCapacity]; + parameters.nsURLCacheDiskCapacity = [urlCache diskCapacity]; + + parameters.parentProcessName = [[NSProcessInfo processInfo] processName]; + parameters.uiProcessBundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; + + for (NSString *scheme in [WKBrowsingContextController customSchemes]) + parameters.urlSchemesRegisteredForCustomProtocols.append(scheme); + + parameters.httpProxy = [[NSUserDefaults standardUserDefaults] stringForKey:WebKit2HTTPProxyDefaultsKey]; + parameters.httpsProxy = [[NSUserDefaults standardUserDefaults] stringForKey:WebKit2HTTPSProxyDefaultsKey]; +} +#endif + void WebContext::platformInvalidateContext() { - [[NSNotificationCenter defaultCenter] removeObserver:(id)m_enhancedAccessibilityObserver.get()]; + unregisterNotificationObservers(); } String WebContext::platformDefaultDiskCacheDirectory() const { - RetainPtr<NSString> cachePath(AdoptNS, (NSString *)WKCopyFoundationCacheDirectory()); + RetainPtr<NSString> cachePath = adoptNS((NSString *)WKCopyFoundationCacheDirectory()); if (!cachePath) cachePath = @"~/Library/Caches/com.apple.WebKit2.WebProcess"; @@ -283,71 +457,147 @@ void WebContext::setPasteboardBufferForType(const String& pasteboardName, const PlatformPasteboard(pasteboardName).setBufferForType(buffer, pasteboardType); } -void WebContext::applicationBecameVisible(uint32_t, void*, uint32_t, void*, uint32_t) +void WebContext::setProcessSuppressionEnabled(bool enabled) { - if (s_applicationIsOccluded) { - s_applicationIsOccluded = false; - - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) - contexts[i]->sendToAllProcesses(Messages::WebProcess::SetApplicationIsOccluded(false)); + if (m_processSuppressionEnabled == enabled) + return; + m_processSuppressionEnabled = enabled; + processSuppressionEnabledChanged(); +} -#if ENABLE(PLUGIN_PROCESS) - PluginProcessManager::shared().setApplicationIsOccluded(false); -#endif +void WebContext::updateProcessSuppressionStateOfChildProcesses() +{ #if ENABLE(NETWORK_PROCESS) - NetworkProcessManager::shared().setApplicationIsOccluded(false); -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - SharedWorkerProcessManager::shared().setApplicationIsOccluded(false); + bool canEnable = canEnableProcessSuppressionForNetworkProcess(); + if (usesNetworkProcess() && networkProcess()) + networkProcess()->setProcessSuppressionEnabled(canEnable); #endif + size_t processCount = m_processes.size(); + for (size_t i = 0; i < processCount; ++i) { + WebProcessProxy* process = m_processes[i].get(); + process->updateProcessSuppressionState(); } } -void WebContext::applicationBecameOccluded(uint32_t, void*, uint32_t, void*, uint32_t) +bool WebContext::canEnableProcessSuppressionForNetworkProcess() const { - if (!s_applicationIsOccluded) { - s_applicationIsOccluded = true; - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) - contexts[i]->sendToAllProcesses(Messages::WebProcess::SetApplicationIsOccluded(true)); + return (s_applicationIsOccluded || s_applicationWindowModificationsHaveStopped) && m_processSuppressionEnabled && !omitProcessSuppression(); +} -#if ENABLE(PLUGIN_PROCESS) - PluginProcessManager::shared().setApplicationIsOccluded(true); -#endif -#if ENABLE(NETWORK_PROCESS) - NetworkProcessManager::shared().setApplicationIsOccluded(true); +bool WebContext::canEnableProcessSuppressionForWebProcess(const WebKit::WebProcessProxy *webProcess) const +{ + return (s_applicationIsOccluded || s_applicationWindowModificationsHaveStopped || webProcess->allPagesAreProcessSuppressible()) + && m_processSuppressionEnabled && !omitProcessSuppression(); +} + +bool WebContext::canEnableProcessSuppressionForGlobalChildProcesses() +{ + return (s_applicationIsOccluded || s_applicationWindowModificationsHaveStopped) && s_processSuppressionEnabledForAllContexts && !omitProcessSuppression(); +} + +void WebContext::processSuppressionEnabledChanged() +{ + updateProcessSuppressionStateOfChildProcesses(); + + if (processSuppressionIsEnabledForAnyContext()) + enableOcclusionNotifications(); + else + disableOcclusionNotifications(); + + bool newProcessSuppressionEnabledForAllContexts = processSuppressionIsEnabledForAllContexts(); + if (s_processSuppressionEnabledForAllContexts != newProcessSuppressionEnabledForAllContexts) { + s_processSuppressionEnabledForAllContexts = newProcessSuppressionEnabledForAllContexts; + updateProcessSuppressionStateOfGlobalChildProcesses(); + } +} + +void WebContext::registerNotificationObservers() +{ + m_customSchemeRegisteredObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKit::SchemeForCustomProtocolRegisteredNotificationName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { + NSString *scheme = [notification object]; + ASSERT([scheme isKindOfClass:[NSString class]]); + registerSchemeForCustomProtocol(scheme); + }]; + + m_customSchemeUnregisteredObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKit::SchemeForCustomProtocolUnregisteredNotificationName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { + NSString *scheme = [notification object]; + ASSERT([scheme isKindOfClass:[NSString class]]); + unregisterSchemeForCustomProtocol(scheme); + }]; + + // Listen for enhanced accessibility changes and propagate them to the WebProcess. + m_enhancedAccessibilityObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKitApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { + setEnhancedAccessibility([[[note userInfo] objectForKey:@"AXEnhancedUserInterface"] boolValue]); + }]; + + m_automaticTextReplacementNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticTextReplacementNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { + TextChecker::didChangeAutomaticTextReplacementEnabled(); + textCheckerStateChanged(); + }]; + + m_automaticSpellingCorrectionNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticSpellingCorrectionNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { + TextChecker::didChangeAutomaticSpellingCorrectionEnabled(); + textCheckerStateChanged(); + }]; + +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + m_automaticQuoteSubstitutionNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticQuoteSubstitutionNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { + TextChecker::didChangeAutomaticQuoteSubstitutionEnabled(); + textCheckerStateChanged(); + }]; + + m_automaticDashSubstitutionNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticDashSubstitutionNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { + TextChecker::didChangeAutomaticDashSubstitutionEnabled(); + textCheckerStateChanged(); + }]; #endif -#if ENABLE(SHARED_WORKER_PROCESS) - SharedWorkerProcessManager::shared().setApplicationIsOccluded(true); +} + +void WebContext::unregisterNotificationObservers() +{ + [[NSNotificationCenter defaultCenter] removeObserver:m_customSchemeRegisteredObserver.get()]; + [[NSNotificationCenter defaultCenter] removeObserver:m_customSchemeUnregisteredObserver.get()]; + [[NSNotificationCenter defaultCenter] removeObserver:m_enhancedAccessibilityObserver.get()]; + + [[NSNotificationCenter defaultCenter] removeObserver:m_automaticTextReplacementNotificationObserver.get()]; + [[NSNotificationCenter defaultCenter] removeObserver:m_automaticSpellingCorrectionNotificationObserver.get()]; +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + [[NSNotificationCenter defaultCenter] removeObserver:m_automaticQuoteSubstitutionNotificationObserver.get()]; + [[NSNotificationCenter defaultCenter] removeObserver:m_automaticDashSubstitutionNotificationObserver.get()]; #endif - } } -void WebContext::initializeProcessSuppressionSupport() +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 +static CFURLStorageSessionRef privateBrowsingSession() { - static bool didInitialize = false; - if (didInitialize) - return; + static CFURLStorageSessionRef session; + static dispatch_once_t once; + dispatch_once(&once, ^{ + NSString *identifier = [NSString stringWithFormat:@"%@.PrivateBrowsing", [[NSBundle mainBundle] bundleIdentifier]]; + + session = WKCreatePrivateStorageSession((CFStringRef)identifier); + }); - didInitialize = true; - // A temporary default until process suppression is enabled by default, at which point a context setting can be added with the - // interpretation that any context disabling process suppression disables it for plugin/network and shared worker processes. - bool processSuppressionSupportEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitProcessSuppressionSupportEnabled"]; - if (processSuppressionSupportEnabled) - registerOcclusionNotificationHandlers(); + return session; } +#endif -void WebContext::registerOcclusionNotificationHandlers() +bool WebContext::isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const { #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - if (!WKRegisterOcclusionNotificationHandler(WKOcclusionNotificationTypeApplicationBecameVisible, applicationBecameVisible)) { - WTFLogAlways("Registeration of \"App Became Visible\" notification handler failed.\n"); - return; - } + RetainPtr<CFURLRef> url = KURL(KURL(), urlString).createCFURL(); - if (!WKRegisterOcclusionNotificationHandler(WKOcclusionNotificationTypeApplicationBecameOccluded, applicationBecameOccluded)) - WTFLogAlways("Registeration of \"App Became Occluded\" notification handler failed.\n"); + return _CFNetworkIsKnownHSTSHostWithSession(url.get(), privateBrowsingEnabled ? privateBrowsingSession() : nullptr); +#else + return false; +#endif +} + +void WebContext::resetHSTSHosts() +{ +#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 + _CFNetworkResetHSTSHostsWithSession(nullptr); + _CFNetworkResetHSTSHostsWithSession(privateBrowsingSession()); #endif } diff --git a/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm index 74c64464d..a0e1c33af 100644 --- a/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm @@ -122,7 +122,7 @@ void WebContextMenuProxyMac::contextMenuItemSelected(const WebContextMenuItemDat m_page->contextMenuItemSelected(item); } -static void populateNSMenu(NSMenu* menu, const Vector<RetainPtr<NSMenuItem> >& menuItemVector) +static void populateNSMenu(NSMenu* menu, const Vector<RetainPtr<NSMenuItem>>& menuItemVector) { for (unsigned i = 0; i < menuItemVector.size(); ++i) { NSInteger oldState = [menuItemVector[i].get() state]; @@ -131,9 +131,9 @@ static void populateNSMenu(NSMenu* menu, const Vector<RetainPtr<NSMenuItem> >& m } } -static Vector<RetainPtr<NSMenuItem> > nsMenuItemVector(const Vector<WebContextMenuItemData>& items) +static Vector<RetainPtr<NSMenuItem>> nsMenuItemVector(const Vector<WebContextMenuItemData>& items) { - Vector<RetainPtr<NSMenuItem> > result; + Vector<RetainPtr<NSMenuItem>> result; unsigned size = items.size(); result.reserveCapacity(size); @@ -152,7 +152,7 @@ static Vector<RetainPtr<NSMenuItem> > nsMenuItemVector(const Vector<WebContextMe [wrapper release]; } - result.append(RetainPtr<NSMenuItem>(AdoptNS, menuItem)); + result.append(adoptNS(menuItem)); break; } case SeparatorType: @@ -168,7 +168,7 @@ static Vector<RetainPtr<NSMenuItem> > nsMenuItemVector(const Vector<WebContextMe [menuItem setSubmenu:menu]; [menu release]; - result.append(RetainPtr<NSMenuItem>(AdoptNS, menuItem)); + result.append(adoptNS(menuItem)); break; } @@ -189,7 +189,7 @@ void WebContextMenuProxyMac::populate(const Vector<WebContextMenuItemData>& item if (m_popup) [m_popup.get() removeAllItems]; else { - m_popup.adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]); + m_popup = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]); [m_popup.get() setUsesItemFromMenu:NO]; [m_popup.get() setAutoenablesItems:NO]; } diff --git a/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm index b8427d56f..daabb8397 100644 --- a/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm @@ -31,6 +31,9 @@ #import "LayerTreeContext.h" #import "WKFullScreenWindowController.h" #import "WKViewInternal.h" +#import "WebFullScreenManagerProxyMessages.h" +#import "WebPageProxy.h" +#import "WebProcessProxy.h" #import <WebCore/IntRect.h> using namespace WebCore; @@ -39,6 +42,8 @@ namespace WebKit { void WebFullScreenManagerProxy::invalidate() { + m_page->process()->removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); + if (!m_webView) return; diff --git a/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm index 86266daaf..69883621e 100644 --- a/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm @@ -31,18 +31,26 @@ #import "WKAPICast.h" #import "WebContext.h" #import "WKInspectorPrivateMac.h" +#import "WKMutableArray.h" +#import "WKOpenPanelParameters.h" +#import "WKOpenPanelResultListener.h" +#import "WKRetainPtr.h" +#import "WKURLCF.h" #import "WKViewPrivate.h" +#import "WebInspectorMessages.h" #import "WebPageGroup.h" #import "WebPageProxy.h" #import "WebPreferences.h" #import "WebProcessProxy.h" +#import <algorithm> +#import <mach-o/dyld.h> #import <WebKitSystemInterface.h> #import <WebCore/InspectorFrontendClientLocal.h> #import <WebCore/LocalizedStrings.h> #import <WebCore/SoftLinking.h> #import <wtf/text/WTFString.h> -SOFT_LINK_STAGED_FRAMEWORK_OPTIONAL(WebInspector, PrivateFrameworks, A) +SOFT_LINK_STAGED_FRAMEWORK(WebInspectorUI, PrivateFrameworks, A) using namespace WebCore; using namespace WebKit; @@ -53,6 +61,11 @@ static const CGFloat windowContentBorderThickness = 55; // The margin from the top and right of the dock button (same as the full screen button). static const CGFloat dockButtonMargin = 3; +// The spacing between the dock buttons. +static const CGFloat dockButtonSpacing = dockButtonMargin * 2; + +static const NSUInteger windowStyleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask | NSTexturedBackgroundWindowMask; + // WKWebInspectorProxyObjCAdapter is a helper ObjC object used as a delegate or notification observer // for the sole purpose of getting back into the C++ code from an ObjC caller. @@ -82,9 +95,14 @@ static const CGFloat dockButtonMargin = 3; return self; } -- (IBAction)attach:(id)sender +- (IBAction)attachRight:(id)sender +{ + static_cast<WebInspectorProxy*>(_inspectorProxy)->attach(AttachmentSideRight); +} + +- (IBAction)attachBottom:(id)sender { - static_cast<WebInspectorProxy*>(_inspectorProxy)->attach(); + static_cast<WebInspectorProxy*>(_inspectorProxy)->attach(AttachmentSideBottom); } - (void)close @@ -92,6 +110,16 @@ static const CGFloat dockButtonMargin = 3; _inspectorProxy = 0; } +- (void)windowDidMove:(NSNotification *)notification +{ + static_cast<WebInspectorProxy*>(_inspectorProxy)->windowFrameDidChange(); +} + +- (void)windowDidResize:(NSNotification *)notification +{ + static_cast<WebInspectorProxy*>(_inspectorProxy)->windowFrameDidChange(); +} + - (void)windowWillClose:(NSNotification *)notification { static_cast<WebInspectorProxy*>(_inspectorProxy)->close(); @@ -132,7 +160,8 @@ static const CGFloat dockButtonMargin = 3; @interface WKWebInspectorWindow : NSWindow { @public - RetainPtr<NSButton> _dockButton; + RetainPtr<NSButton> _dockBottomButton; + RetainPtr<NSButton> _dockRightButton; } @end @@ -142,7 +171,7 @@ static const CGFloat dockButtonMargin = 3; { // Don't show a resize cursor for the northeast (top right) direction if the dock button is visible. // This matches what happens when the full screen button is visible. - if (direction == 1 && ![_dockButton isHidden]) + if (direction == 1 && ![_dockRightButton isHidden]) return nil; return [super _cursorForResizeDirection:direction]; } @@ -151,7 +180,7 @@ static const CGFloat dockButtonMargin = 3; { // Adjust the title frame if needed to prevent it from intersecting the dock button. NSRect titleFrame = [super _customTitleFrame]; - NSRect dockButtonFrame = _dockButton.get().frame; + NSRect dockButtonFrame = _dockBottomButton.get().frame; if (NSMaxX(titleFrame) > NSMinX(dockButtonFrame) - dockButtonMargin) titleFrame.size.width -= (NSMaxX(titleFrame) - NSMinX(dockButtonFrame)) + dockButtonMargin; return titleFrame; @@ -166,9 +195,9 @@ static bool inspectorReallyUsesWebKitUserInterface(WebPreferences* preferences) // This matches a similar check in WebInspectorMac.mm. Keep them in sync. // Call the soft link framework function to dlopen it, then [NSBundle bundleWithIdentifier:] will work. - WebInspectorLibrary(); + WebInspectorUILibrary(); - if (![[NSBundle bundleWithIdentifier:@"com.apple.WebInspector"] pathForResource:@"Main" ofType:@"html"]) + if (![[NSBundle bundleWithIdentifier:@"com.apple.WebInspectorUI"] pathForResource:@"Main" ofType:@"html"]) return true; if (![[NSBundle bundleWithIdentifier:@"com.apple.WebCore"] pathForResource:@"inspector" ofType:@"html" inDirectory:@"inspector"]) @@ -193,6 +222,42 @@ static void setWindowFrame(WKPageRef, WKRect frame, const void* clientInfo) webInspectorProxy->setInspectorWindowFrame(frame); } +static unsigned long long exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef, WKStringRef, unsigned long long, unsigned long long, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void*) +{ + return std::max<unsigned long long>(expectedUsage, currentDatabaseUsage * 1.25); +} + +static void runOpenPanel(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void* clientInfo) +{ + WebInspectorProxy* webInspectorProxy = static_cast<WebInspectorProxy*>(const_cast<void*>(clientInfo)); + ASSERT(webInspectorProxy); + + NSOpenPanel *openPanel = [NSOpenPanel openPanel]; + [openPanel setAllowsMultipleSelection:WKOpenPanelParametersGetAllowsMultipleFiles(parameters)]; + + WKRetain(listener); + + // If the inspector is detached, then openPanel will be window-modal; otherwise, openPanel is opened in a new window. + [openPanel beginSheetModalForWindow:webInspectorProxy->inspectorWindow() completionHandler:^(NSInteger result) { + if (result == NSFileHandlingPanelOKButton) { + WKMutableArrayRef fileURLs = WKMutableArrayCreate(); + + for (NSURL* nsURL in [openPanel URLs]) { + WKURLRef wkURL = WKURLCreateWithCFURL(reinterpret_cast<CFURLRef>(nsURL)); + WKArrayAppendItem(fileURLs, wkURL); + WKRelease(wkURL); + } + + WKOpenPanelResultListenerChooseFiles(listener, fileURLs); + + WKRelease(fileURLs); + } else + WKOpenPanelResultListenerCancel(listener); + + WKRelease(listener); + }]; +} + void WebInspectorProxy::setInspectorWindowFrame(WKRect& frame) { if (m_isAttached) @@ -209,12 +274,38 @@ WKRect WebInspectorProxy::inspectorWindowFrame() return WKRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height); } +static NSButton *createDockButton(NSString *imageName) +{ + // Create a full screen button so we can turn it into a dock button. + NSButton *dockButton = [NSWindow standardWindowButton:NSWindowFullScreenButton forStyleMask:windowStyleMask]; + + // Set the autoresizing mask to keep the dock button pinned to the top right corner. + dockButton.autoresizingMask = NSViewMinXMargin | NSViewMinYMargin; + + // Get the dock image and make it a template so the button cell effects will apply. + NSImage *dockImage = [[NSBundle bundleForClass:[WKWebInspectorWKView class]] imageForResource:imageName]; + [dockImage setTemplate:YES]; + + // Set the dock image on the button cell. + NSCell *dockButtonCell = dockButton.cell; + dockButtonCell.image = dockImage; + + return [dockButton retain]; +} + void WebInspectorProxy::createInspectorWindow() { ASSERT(!m_inspectorWindow); - NSUInteger styleMask = (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask | NSTexturedBackgroundWindowMask); - WKWebInspectorWindow *window = [[WKWebInspectorWindow alloc] initWithContentRect:NSMakeRect(0, 0, initialWindowWidth, initialWindowHeight) styleMask:styleMask backing:NSBackingStoreBuffered defer:NO]; + NSRect windowFrame = NSMakeRect(0, 0, initialWindowWidth, initialWindowHeight); + + // Restore the saved window frame, if there was one. + NSString *savedWindowFrameString = page()->pageGroup()->preferences()->inspectorWindowFrame(); + NSRect savedWindowFrame = NSRectFromString(savedWindowFrameString); + if (!NSIsEmptyRect(savedWindowFrame)) + windowFrame = savedWindowFrame; + + WKWebInspectorWindow *window = [[WKWebInspectorWindow alloc] initWithContentRect:windowFrame styleMask:windowStyleMask backing:NSBackingStoreBuffered defer:NO]; [window setDelegate:m_inspectorProxyObjCAdapter.get()]; [window setMinSize:NSMakeSize(minimumWindowWidth, minimumWindowHeight)]; [window setReleasedWhenClosed:NO]; @@ -222,29 +313,33 @@ void WebInspectorProxy::createInspectorWindow() [window setContentBorderThickness:windowContentBorderThickness forEdge:NSMaxYEdge]; WKNSWindowMakeBottomCornersSquare(window); + m_inspectorWindow = adoptNS(window); + NSView *contentView = [window contentView]; - // Create a full screen button so we can turn it into a dock button. - m_dockButton = [NSWindow standardWindowButton:NSWindowFullScreenButton forStyleMask:styleMask]; - m_dockButton.get().target = m_inspectorProxyObjCAdapter.get(); - m_dockButton.get().action = @selector(attach:); + static const int32_t firstVersionOfSafariWithDockToRightSupport = 0x02181d0d; // 536.29.13 + static bool supportsDockToRight = NSVersionOfLinkTimeLibrary("Safari") >= firstVersionOfSafariWithDockToRightSupport; - // Store the dock button on the window too so it can check its visibility. - window->_dockButton = m_dockButton; + m_dockBottomButton = adoptNS(createDockButton(@"DockBottom")); + m_dockRightButton = adoptNS(createDockButton(@"DockRight")); - // Get the dock image and make it a template so the button cell effects will apply. - NSImage *dockImage = [[NSBundle bundleForClass:[WKWebInspectorWKView class]] imageForResource:@"Dock"]; - [dockImage setTemplate:YES]; + m_dockBottomButton.get().target = m_inspectorProxyObjCAdapter.get(); + m_dockBottomButton.get().action = @selector(attachBottom:); - // Set the dock image on the button cell. - NSCell *dockButtonCell = m_dockButton.get().cell; - dockButtonCell.image = dockImage; + m_dockRightButton.get().target = m_inspectorProxyObjCAdapter.get(); + m_dockRightButton.get().action = @selector(attachRight:); + m_dockRightButton.get().enabled = supportsDockToRight; + m_dockRightButton.get().alphaValue = supportsDockToRight ? 1 : 0.5; + + // Store the dock buttons on the window too so it can check its visibility. + window->_dockBottomButton = m_dockBottomButton; + window->_dockRightButton = m_dockRightButton; // Get the frame view, the superview of the content view, and its frame. // This will be the superview of the dock button too. NSView *frameView = contentView.superview; NSRect frameViewBounds = frameView.bounds; - NSSize dockButtonSize = m_dockButton.get().frame.size; + NSSize dockButtonSize = m_dockBottomButton.get().frame.size; ASSERT(!frameView.isFlipped); @@ -252,26 +347,25 @@ void WebInspectorProxy::createInspectorWindow() NSPoint dockButtonOrigin; dockButtonOrigin.x = NSMaxX(frameViewBounds) - dockButtonSize.width - dockButtonMargin; dockButtonOrigin.y = NSMaxY(frameViewBounds) - dockButtonSize.height - dockButtonMargin; - m_dockButton.get().frameOrigin = dockButtonOrigin; + m_dockRightButton.get().frameOrigin = dockButtonOrigin; - // Set the autoresizing mask to keep the dock button pinned to the top right corner. - m_dockButton.get().autoresizingMask = NSViewMinXMargin | NSViewMinYMargin; + dockButtonOrigin.x -= dockButtonSize.width + dockButtonSpacing; + m_dockBottomButton.get().frameOrigin = dockButtonOrigin; - [frameView addSubview:m_dockButton.get()]; + [frameView addSubview:m_dockBottomButton.get()]; + [frameView addSubview:m_dockRightButton.get()]; - // Hide the dock button if we can't attach. - m_dockButton.get().hidden = !canAttach(); + // Hide the dock buttons if we can't attach. + m_dockBottomButton.get().hidden = !canAttach(); + m_dockRightButton.get().hidden = !canAttach(); [m_inspectorView.get() setFrame:[contentView bounds]]; [m_inspectorView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [contentView addSubview:m_inspectorView.get()]; - // Center the window initially before setting the frame autosave name so that the window will be in a good - // position if there is no saved frame yet. - [window center]; - [window setFrameAutosaveName:@"Web Inspector 2"]; - - m_inspectorWindow.adoptNS(window); + // Center the window if the saved frame was empty. + if (NSIsEmptyRect(savedWindowFrame)) + [window center]; updateInspectorWindowTitle(); } @@ -290,17 +384,33 @@ WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() ASSERT(m_page); ASSERT(!m_inspectorView); - m_inspectorView.adoptNS([[WKWebInspectorWKView alloc] initWithFrame:NSMakeRect(0, 0, initialWindowWidth, initialWindowHeight) contextRef:toAPI(page()->process()->context()) pageGroupRef:toAPI(inspectorPageGroup()) relatedToPage:toAPI(m_page)]); + NSRect initialRect; + if (m_isAttached) { + NSRect inspectedViewFrame = m_page->wkView().frame; + + switch (m_attachmentSide) { + case AttachmentSideBottom: + initialRect = NSMakeRect(0, 0, NSWidth(inspectedViewFrame), inspectorPageGroup()->preferences()->inspectorAttachedHeight()); + break; + case AttachmentSideRight: + initialRect = NSMakeRect(0, 0, inspectorPageGroup()->preferences()->inspectorAttachedWidth(), NSHeight(inspectedViewFrame)); + break; + } + } else { + initialRect = NSMakeRect(0, 0, initialWindowWidth, initialWindowHeight); + + NSString *windowFrameString = page()->pageGroup()->preferences()->inspectorWindowFrame(); + NSRect windowFrame = NSRectFromString(windowFrameString); + if (!NSIsEmptyRect(windowFrame)) + initialRect = [NSWindow contentRectForFrameRect:windowFrame styleMask:windowStyleMask]; + } + + m_inspectorView = adoptNS([[WKWebInspectorWKView alloc] initWithFrame:initialRect contextRef:toAPI(page()->process()->context()) pageGroupRef:toAPI(inspectorPageGroup()) relatedToPage:toAPI(m_page)]); ASSERT(m_inspectorView); [m_inspectorView.get() setDrawsBackground:NO]; - m_inspectorProxyObjCAdapter.adoptNS([[WKWebInspectorProxyObjCAdapter alloc] initWithWebInspectorProxy:this]); - - if (m_isAttached) - platformAttach(); - else - createInspectorWindow(); + m_inspectorProxyObjCAdapter = adoptNS([[WKWebInspectorProxyObjCAdapter alloc] initWithWebInspectorProxy:this]); WebPageProxy* inspectorPage = toImpl(m_inspectorView.get().pageRef); @@ -334,8 +444,8 @@ WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() 0, // runBeforeUnloadConfirmPanel 0, // didDraw 0, // pageDidScroll - 0, // exceededDatabaseQuota - 0, // runOpenPanel + exceededDatabaseQuota, + runOpenPanel, 0, // decidePolicyForGeolocationPermissionRequest 0, // headerHeight 0, // footerHeight @@ -349,9 +459,10 @@ WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() 0, // createPage 0, // mouseDidMoveOverElement 0, // decidePolicyForNotificationPermissionRequest - 0, // unavailablePluginButtonClicked + 0, // unavailablePluginButtonClicked_deprecatedForUseWithV1 0, // showColorPicker 0, // hideColorPicker + 0, // unavailablePluginButtonClicked }; inspectorPage->initializeUIClient(&uiClient); @@ -361,14 +472,12 @@ WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() void WebInspectorProxy::platformOpen() { - if (m_isAttached) { - // Make the inspector view visible since it was hidden while loading. - [m_inspectorView.get() setHidden:NO]; + if (m_isAttached) + platformAttach(); + else + createInspectorWindow(); - // Adjust the frames now that we are visible and inspectedViewFrameDidChange wont return early. - inspectedViewFrameDidChange(); - } else - [m_inspectorWindow.get() makeKeyAndOrderFront:nil]; + platformBringToFront(); } void WebInspectorProxy::platformDidClose() @@ -385,8 +494,30 @@ void WebInspectorProxy::platformDidClose() m_inspectorProxyObjCAdapter = 0; } +void WebInspectorProxy::platformHide() +{ + if (m_isAttached) { + platformDetach(); + return; + } + + if (m_inspectorWindow) { + [m_inspectorWindow.get() setDelegate:nil]; + [m_inspectorWindow.get() orderOut:nil]; + m_inspectorWindow = 0; + } +} + void WebInspectorProxy::platformBringToFront() { + // If the Web Inspector is no longer in the same window as the inspected view, + // then we need to reopen the Inspector to get it attached to the right window. + // This can happen when dragging tabs to another window in Safari. + if (m_isAttached && m_inspectorView.get().window != m_page->wkView().window) { + platformOpen(); + return; + } + // FIXME <rdar://problem/10937688>: this will not bring a background tab in Safari to the front, only its window. [m_inspectorView.get().window makeKeyAndOrderFront:nil]; [m_inspectorView.get().window makeFirstResponder:m_inspectorView.get()]; @@ -400,7 +531,8 @@ bool WebInspectorProxy::platformIsFront() void WebInspectorProxy::platformAttachAvailabilityChanged(bool available) { - m_dockButton.get().hidden = !available; + m_dockBottomButton.get().hidden = !available; + m_dockRightButton.get().hidden = !available; } void WebInspectorProxy::platformInspectedURLChanged(const String& urlString) @@ -410,24 +542,125 @@ void WebInspectorProxy::platformInspectedURLChanged(const String& urlString) updateInspectorWindowTitle(); } -void WebInspectorProxy::inspectedViewFrameDidChange() +void WebInspectorProxy::platformSave(const String& suggestedURL, const String& content, bool forceSaveDialog) +{ + ASSERT(!suggestedURL.isEmpty()); + + NSURL *platformURL = m_suggestedToActualURLMap.get(suggestedURL).get(); + if (!platformURL) { + platformURL = [NSURL URLWithString:suggestedURL]; + // The user must confirm new filenames before we can save to them. + forceSaveDialog = true; + } + + ASSERT(platformURL); + if (!platformURL) + return; + + // Necessary for the block below. + String suggestedURLCopy = suggestedURL; + String contentCopy = content; + + auto saveToURL = ^(NSURL *actualURL) { + ASSERT(actualURL); + + m_suggestedToActualURLMap.set(suggestedURLCopy, actualURL); + [contentCopy writeToURL:actualURL atomically:YES encoding:NSUTF8StringEncoding error:NULL]; + m_page->process()->send(Messages::WebInspector::DidSave([actualURL absoluteString]), m_page->pageID()); + }; + + if (!forceSaveDialog) { + saveToURL(platformURL); + return; + } + + NSSavePanel *panel = [NSSavePanel savePanel]; + panel.nameFieldStringValue = platformURL.lastPathComponent; + panel.directoryURL = [platformURL URLByDeletingLastPathComponent]; + + [panel beginSheetModalForWindow:m_inspectorWindow.get() completionHandler:^(NSInteger result) { + if (result == NSFileHandlingPanelCancelButton) + return; + ASSERT(result == NSFileHandlingPanelOKButton); + saveToURL(panel.URL); + }]; +} + +void WebInspectorProxy::platformAppend(const String& suggestedURL, const String& content) +{ + ASSERT(!suggestedURL.isEmpty()); + + RetainPtr<NSURL> actualURL = m_suggestedToActualURLMap.get(suggestedURL); + // Do not append unless the user has already confirmed this filename in save(). + if (!actualURL) + return; + + NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:actualURL.get() error:NULL]; + [handle seekToEndOfFile]; + [handle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]]; + [handle closeFile]; + + m_page->process()->send(Messages::WebInspector::DidAppend([actualURL absoluteString]), m_page->pageID()); +} + +void WebInspectorProxy::windowFrameDidChange() +{ + ASSERT(!m_isAttached); + ASSERT(m_isVisible); + ASSERT(m_inspectorWindow); + + if (m_isAttached || !m_isVisible || !m_inspectorWindow) + return; + + NSString *frameString = NSStringFromRect([m_inspectorWindow frame]); + page()->pageGroup()->preferences()->setInspectorWindowFrame(frameString); +} + +void WebInspectorProxy::inspectedViewFrameDidChange(CGFloat currentDimension) { if (!m_isAttached || !m_isVisible) return; WKView *inspectedView = m_page->wkView(); NSRect inspectedViewFrame = [inspectedView frame]; + NSRect inspectorFrame = NSZeroRect; + NSRect parentBounds = [[inspectedView superview] bounds]; + CGFloat inspectedViewTop = NSMaxY(inspectedViewFrame); + + switch (m_attachmentSide) { + case AttachmentSideBottom: { + if (!currentDimension) + currentDimension = NSHeight([m_inspectorView.get() frame]); + + CGFloat parentHeight = NSHeight(parentBounds); + CGFloat inspectorHeight = InspectorFrontendClientLocal::constrainedAttachedWindowHeight(currentDimension, parentHeight); + + // Preserve the top position of the inspected view so banners in Safari still work. + inspectedViewFrame = NSMakeRect(0, inspectorHeight, NSWidth(parentBounds), inspectedViewTop - inspectorHeight); + inspectorFrame = NSMakeRect(0, 0, NSWidth(inspectedViewFrame), inspectorHeight); + break; + } + + case AttachmentSideRight: { + if (!currentDimension) + currentDimension = NSWidth([m_inspectorView.get() frame]); + + CGFloat parentWidth = NSWidth(parentBounds); + CGFloat inspectorWidth = InspectorFrontendClientLocal::constrainedAttachedWindowWidth(currentDimension, parentWidth); + + // Preserve the top position of the inspected view so banners in Safari still work. But don't use that + // top position for the inspector view since the banners only stretch as wide as the the inspected view. + inspectedViewFrame = NSMakeRect(0, 0, parentWidth - inspectorWidth, inspectedViewTop); + inspectorFrame = NSMakeRect(parentWidth - inspectorWidth, 0, inspectorWidth, NSHeight(parentBounds)); + break; + } + } - CGFloat inspectedLeft = NSMinX(inspectedViewFrame); - CGFloat inspectedTop = NSMaxY(inspectedViewFrame); - CGFloat inspectedWidth = NSWidth(inspectedViewFrame); - CGFloat inspectorHeight = NSHeight([m_inspectorView.get() frame]); - - CGFloat parentHeight = NSHeight([[inspectedView superview] frame]); - inspectorHeight = InspectorFrontendClientLocal::constrainedAttachedWindowHeight(inspectorHeight, parentHeight); + // Disable screen updates to make sure the layers for both views resize in sync. + [[m_inspectorView window] disableScreenUpdatesUntilFlush]; - [m_inspectorView.get() setFrame:NSMakeRect(inspectedLeft, 0.0, inspectedWidth, inspectorHeight)]; - [inspectedView setFrame:NSMakeRect(inspectedLeft, inspectorHeight, inspectedWidth, inspectedTop - inspectorHeight)]; + [m_inspectorView setFrame:inspectorFrame]; + [inspectedView setFrame:inspectedViewFrame]; } unsigned WebInspectorProxy::platformInspectedWindowHeight() @@ -437,32 +670,44 @@ unsigned WebInspectorProxy::platformInspectedWindowHeight() return static_cast<unsigned>(inspectedViewRect.size.height); } +unsigned WebInspectorProxy::platformInspectedWindowWidth() +{ + WKView *inspectedView = m_page->wkView(); + NSRect inspectedViewRect = [inspectedView frame]; + return static_cast<unsigned>(inspectedViewRect.size.width); +} + void WebInspectorProxy::platformAttach() { WKView *inspectedView = m_page->wkView(); [[NSNotificationCenter defaultCenter] addObserver:m_inspectorProxyObjCAdapter.get() selector:@selector(inspectedViewFrameDidChange:) name:NSViewFrameDidChangeNotification object:inspectedView]; - [m_inspectorView.get() removeFromSuperview]; + if (m_inspectorWindow) { + [m_inspectorWindow.get() setDelegate:nil]; + [m_inspectorWindow.get() orderOut:nil]; + m_inspectorWindow = 0; + } - // The inspector view shares the width and the left starting point of the inspected view. - NSRect inspectedViewFrame = [inspectedView frame]; - [m_inspectorView.get() setFrame:NSMakeRect(NSMinX(inspectedViewFrame), 0, NSWidth(inspectedViewFrame), inspectorPageGroup()->preferences()->inspectorAttachedHeight())]; + [m_inspectorView.get() removeFromSuperview]; [m_inspectorView.get() setAutoresizingMask:NSViewWidthSizable | NSViewMaxYMargin]; - // Start out hidden if we are not visible yet. When platformOpen is called, hidden will be set to NO. - [m_inspectorView.get() setHidden:!m_isVisible]; + CGFloat currentDimension; - [[inspectedView superview] addSubview:m_inspectorView.get() positioned:NSWindowBelow relativeTo:inspectedView]; - [[inspectedView window] makeFirstResponder:m_inspectorView.get()]; - - if (m_inspectorWindow) { - [m_inspectorWindow.get() setDelegate:nil]; - [m_inspectorWindow.get() orderOut:nil]; - m_inspectorWindow = 0; + switch (m_attachmentSide) { + case AttachmentSideBottom: + currentDimension = inspectorPageGroup()->preferences()->inspectorAttachedHeight(); + break; + case AttachmentSideRight: + currentDimension = inspectorPageGroup()->preferences()->inspectorAttachedWidth(); + break; } - inspectedViewFrameDidChange(); + inspectedViewFrameDidChange(currentDimension); + + [[inspectedView superview] addSubview:m_inspectorView.get() positioned:NSWindowBelow relativeTo:inspectedView]; + + [[inspectedView window] makeFirstResponder:m_inspectorView.get()]; } void WebInspectorProxy::platformDetach() @@ -473,11 +718,9 @@ void WebInspectorProxy::platformDetach() [m_inspectorView.get() removeFromSuperview]; // Make sure that we size the inspected view's frame after detaching so that it takes up the space that the - // attached inspector used to. This assumes the previous height was the Y origin. - NSRect inspectedViewRect = [inspectedView frame]; - inspectedViewRect.size.height += NSMinY(inspectedViewRect); - inspectedViewRect.origin.y = 0.0; - [inspectedView setFrame:inspectedViewRect]; + // attached inspector used to. Preserve the top position of the inspected view so banners in Safari still work. + + inspectedView.frame = NSMakeRect(0, 0, NSWidth(inspectedView.superview.bounds), NSMaxY(inspectedView.frame)); // Return early if we are not visible. This means the inspector was closed while attached // and we should not create and show the inspector window. @@ -486,10 +729,7 @@ void WebInspectorProxy::platformDetach() createInspectorWindow(); - // Make the inspector view visible in case it is still hidden from loading while attached. - [m_inspectorView.get() setHidden:NO]; - - [m_inspectorWindow.get() makeKeyAndOrderFront:nil]; + platformBringToFront(); } void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned height) @@ -497,13 +737,20 @@ void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned height) if (!m_isAttached) return; - WKView *inspectedView = m_page->wkView(); - NSRect inspectedViewFrame = [inspectedView frame]; + inspectedViewFrameDidChange(height); +} + +void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned width) +{ + if (!m_isAttached) + return; - // The inspector view shares the width and the left starting point of the inspected view. - [m_inspectorView.get() setFrame:NSMakeRect(NSMinX(inspectedViewFrame), 0.0, NSWidth(inspectedViewFrame), height)]; + inspectedViewFrameDidChange(width); +} - inspectedViewFrameDidChange(); +void WebInspectorProxy::platformSetToolbarHeight(unsigned height) +{ + [m_inspectorWindow setContentBorderThickness:height forEdge:NSMaxYEdge]; } String WebInspectorProxy::inspectorPageURL() const @@ -512,7 +759,7 @@ String WebInspectorProxy::inspectorPageURL() const if (inspectorReallyUsesWebKitUserInterface(page()->pageGroup()->preferences())) path = [[NSBundle bundleWithIdentifier:@"com.apple.WebCore"] pathForResource:@"inspector" ofType:@"html" inDirectory:@"inspector"]; else - path = [[NSBundle bundleWithIdentifier:@"com.apple.WebInspector"] pathForResource:@"Main" ofType:@"html"]; + path = [[NSBundle bundleWithIdentifier:@"com.apple.WebInspectorUI"] pathForResource:@"Main" ofType:@"html"]; ASSERT([path length]); @@ -525,7 +772,7 @@ String WebInspectorProxy::inspectorBaseURL() const if (inspectorReallyUsesWebKitUserInterface(page()->pageGroup()->preferences())) path = [[NSBundle bundleWithIdentifier:@"com.apple.WebCore"] resourcePath]; else - path = [[NSBundle bundleWithIdentifier:@"com.apple.WebInspector"] resourcePath]; + path = [[NSBundle bundleWithIdentifier:@"com.apple.WebInspectorUI"] resourcePath]; ASSERT([path length]); diff --git a/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm index 849ba20f8..c7f96a5ac 100644 --- a/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm @@ -42,6 +42,7 @@ #import <WebCore/DictationAlternative.h> #import <WebCore/GraphicsLayer.h> #import <WebCore/SharedBuffer.h> +#import <WebCore/SystemVersionMac.h> #import <WebCore/TextAlternativeWithRange.h> #import <WebKitSystemInterface.h> #import <wtf/text/StringConcatenate.h> @@ -64,43 +65,14 @@ namespace WebKit { #error Unknown architecture #endif -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 - -static String macOSXVersionString() +static NSString *systemMarketingVersionForUserAgentString() { // Use underscores instead of dots because when we first added the Mac OS X version to the user agent string // we were concerned about old DHTML libraries interpreting "4." as Netscape 4. That's no longer a concern for us // but we're sticking with the underscores for compatibility with the format used by older versions of Safari. - return [WKGetMacOSXVersionString() stringByReplacingOccurrencesOfString:@"." withString:@"_"]; -} - -#else - -static inline int callGestalt(OSType selector) -{ - SInt32 value = 0; - Gestalt(selector, &value); - return value; -} - -// Uses underscores instead of dots because if "4." ever appears in a user agent string, old DHTML libraries treat it as Netscape 4. -static String macOSXVersionString() -{ - // Can't use -[NSProcessInfo operatingSystemVersionString] because it has too much stuff we don't want. - int major = callGestalt(gestaltSystemVersionMajor); - ASSERT(major); - - int minor = callGestalt(gestaltSystemVersionMinor); - int bugFix = callGestalt(gestaltSystemVersionBugFix); - if (bugFix) - return String::format("%d_%d_%d", major, minor, bugFix); - if (minor) - return String::format("%d_%d", major, minor); - return String::format("%d", major); + return [systemMarketingVersion() stringByReplacingOccurrencesOfString:@"." withString:@"_"]; } -#endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 - static String userVisibleWebKitVersionString() { // If the version is 4 digits long or longer, then the first digit represents @@ -117,7 +89,7 @@ static String userVisibleWebKitVersionString() String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent) { - DEFINE_STATIC_LOCAL(String, osVersion, (macOSXVersionString())); + DEFINE_STATIC_LOCAL(String, osVersion, (systemMarketingVersionForUserAgentString())); DEFINE_STATIC_LOCAL(String, webKitVersion, (userVisibleWebKitVersionString())); if (applicationNameForUserAgent.isEmpty()) @@ -145,6 +117,15 @@ void WebPageProxy::searchWithSpotlight(const String& string) [[NSWorkspace sharedWorkspace] showSearchResultsForQueryString:nsStringFromWebCoreString(string)]; } +void WebPageProxy::searchTheWeb(const String& string) +{ + NSPasteboard *pasteboard = [NSPasteboard pasteboardWithUniqueName]; + [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil]; + [pasteboard setString:string forType:NSStringPboardType]; + + NSPerformService(@"Search With %WebSearchProvider@", pasteboard); +} + CGContextRef WebPageProxy::containingWindowGraphicsContext() { return m_pageClient->containingWindowGraphicsContext(); @@ -157,12 +138,49 @@ void WebPageProxy::updateWindowIsVisible(bool windowIsVisible) process()->send(Messages::WebPage::SetWindowIsVisible(windowIsVisible), m_pageID); } -void WebPageProxy::windowAndViewFramesChanged(const IntRect& windowFrameInScreenCoordinates, const IntRect& viewFrameInWindowCoordinates, const IntPoint& accessibilityViewCoordinates) +void WebPageProxy::windowAndViewFramesChanged(const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates) { if (!isValid()) return; - process()->send(Messages::WebPage::WindowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates, accessibilityViewCoordinates), m_pageID); + // In case the UI client overrides getWindowFrame(), we call it here to make sure we send the appropriate window frame. + FloatRect windowFrameInScreenCoordinates = m_uiClient.windowFrame(this); + FloatRect windowFrameInUnflippedScreenCoordinates = m_pageClient->convertToUserSpace(windowFrameInScreenCoordinates); + + process()->send(Messages::WebPage::WindowAndViewFramesChanged(windowFrameInScreenCoordinates, windowFrameInUnflippedScreenCoordinates, viewFrameInWindowCoordinates, accessibilityViewCoordinates), m_pageID); +} + +void WebPageProxy::viewExposedRectChanged(const FloatRect& exposedRect, bool clipsToExposedRect) +{ + if (!isValid()) + return; + + m_exposedRect = exposedRect; + m_clipsToExposedRect = clipsToExposedRect; + + if (!m_exposedRectChangedTimer.isActive()) + m_exposedRectChangedTimer.startOneShot(0); +} + +void WebPageProxy::exposedRectChangedTimerFired(Timer<WebPageProxy>*) +{ + if (!isValid()) + return; + + if (m_exposedRect == m_lastSentExposedRect && m_clipsToExposedRect == m_lastSentClipsToExposedRect) + return; + + process()->send(Messages::WebPage::ViewExposedRectChanged(m_exposedRect, m_clipsToExposedRect), m_pageID); + m_lastSentExposedRect = m_exposedRect; + m_lastSentClipsToExposedRect = m_clipsToExposedRect; +} + +void WebPageProxy::setMainFrameIsScrollable(bool isScrollable) +{ + if (!isValid()) + return; + + process()->send(Messages::WebPage::SetMainFrameIsScrollable(isScrollable), m_pageID); } void WebPageProxy::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) @@ -199,6 +217,8 @@ bool WebPageProxy::insertText(const String& text, uint64_t replacementRangeStart bool handled = true; process()->sendSync(Messages::WebPage::InsertText(text, replacementRangeStart, replacementRangeEnd), Messages::WebPage::InsertText::Reply(handled, m_editorState), m_pageID); + m_temporarilyClosedComposition = false; + return handled; } @@ -484,4 +504,102 @@ void WebPageProxy::setAcceleratedCompositingRootLayer(const GraphicsLayer* rootL m_pageClient->setAcceleratedCompositingRootLayer(rootLayer->platformLayer()); } +static NSString *temporaryPDFDirectoryPath() +{ + static NSString *temporaryPDFDirectoryPath; + + if (!temporaryPDFDirectoryPath) { + NSString *temporaryDirectoryTemplate = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WebKitPDFs-XXXXXX"]; + CString templateRepresentation = [temporaryDirectoryTemplate fileSystemRepresentation]; + + if (mkdtemp(templateRepresentation.mutableData())) + temporaryPDFDirectoryPath = [[[NSFileManager defaultManager] stringWithFileSystemRepresentation:templateRepresentation.data() length:templateRepresentation.length()] copy]; + } + + return temporaryPDFDirectoryPath; +} + +static NSString *pathToPDFOnDisk(const String& suggestedFilename) +{ + NSString *pdfDirectoryPath = temporaryPDFDirectoryPath(); + if (!pdfDirectoryPath) { + WTFLogAlways("Cannot create temporary PDF download directory."); + return nil; + } + + NSString *path = [pdfDirectoryPath stringByAppendingPathComponent:suggestedFilename]; + + NSFileManager *fileManager = [NSFileManager defaultManager]; + if ([fileManager fileExistsAtPath:path]) { + NSString *pathTemplatePrefix = [pdfDirectoryPath stringByAppendingPathComponent:@"XXXXXX-"]; + NSString *pathTemplate = [pathTemplatePrefix stringByAppendingString:suggestedFilename]; + CString pathTemplateRepresentation = [pathTemplate fileSystemRepresentation]; + + int fd = mkstemps(pathTemplateRepresentation.mutableData(), pathTemplateRepresentation.length() - strlen([pathTemplatePrefix fileSystemRepresentation]) + 1); + if (fd < 0) { + WTFLogAlways("Cannot create PDF file in the temporary directory (%s).", suggestedFilename.utf8().data()); + return nil; + } + + close(fd); + path = [fileManager stringWithFileSystemRepresentation:pathTemplateRepresentation.data() length:pathTemplateRepresentation.length()]; + } + + return path; +} + +void WebPageProxy::savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID) +{ + // FIXME: Write originatingURLString to the file's originating URL metadata (perhaps WKSetMetadataURL?). + UNUSED_PARAM(originatingURLString); + + if (!suggestedFilename.endsWith(".pdf", false)) { + WTFLogAlways("Cannot save file without .pdf extension to the temporary directory."); + return; + } + + if (!size) { + WTFLogAlways("Cannot save empty PDF file to the temporary directory."); + return; + } + + NSString *nsPath = pathToPDFOnDisk(suggestedFilename); + + if (!nsPath) + return; + + RetainPtr<NSNumber> permissions = adoptNS([[NSNumber alloc] initWithInt:S_IRUSR]); + RetainPtr<NSDictionary> fileAttributes = adoptNS([[NSDictionary alloc] initWithObjectsAndKeys:permissions.get(), NSFilePosixPermissions, nil]); + RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:(void*)data length:size freeWhenDone:NO]); + + if (![[NSFileManager defaultManager] createFileAtPath:nsPath contents:nsData.get() attributes:fileAttributes.get()]) { + WTFLogAlways("Cannot create PDF file in the temporary directory (%s).", suggestedFilename.utf8().data()); + return; + } + + m_temporaryPDFFiles.add(pdfUUID, nsPath); + + [[NSWorkspace sharedWorkspace] openFile:nsPath]; +} + +void WebPageProxy::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference& data, const String& pdfUUID) +{ + if (data.isEmpty()) { + WTFLogAlways("Cannot save empty PDF file to the temporary directory."); + return; + } + + savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(suggestedFilename, originatingURLString, data.data(), data.size(), pdfUUID); +} + +void WebPageProxy::openPDFFromTemporaryFolderWithNativeApplication(const String& pdfUUID) +{ + String pdfFilename = m_temporaryPDFFiles.get(pdfUUID); + + if (!pdfFilename.endsWith(".pdf", false)) + return; + + [[NSWorkspace sharedWorkspace] openFile:pdfFilename]; +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm index 29033e421..f74b76015 100644 --- a/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm @@ -57,7 +57,7 @@ void WebPopupMenuProxyMac::populate(const Vector<WebPopupItem>& items, NSFont *f if (m_popup) [m_popup.get() removeAllItems]; else { - m_popup.adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]); + m_popup = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]); [m_popup.get() setUsesItemFromMenu:NO]; [m_popup.get() setAutoenablesItems:NO]; } @@ -71,20 +71,20 @@ void WebPopupMenuProxyMac::populate(const Vector<WebPopupItem>& items, NSFont *f [m_popup.get() addItemWithTitle:@""]; NSMenuItem *menuItem = [m_popup.get() lastItem]; - RetainPtr<NSMutableParagraphStyle> paragraphStyle(AdoptNS, [[NSParagraphStyle defaultParagraphStyle] mutableCopy]); + RetainPtr<NSMutableParagraphStyle> paragraphStyle = adoptNS([[NSParagraphStyle defaultParagraphStyle] mutableCopy]); NSWritingDirection writingDirection = items[i].m_textDirection == LTR ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft; [paragraphStyle.get() setBaseWritingDirection:writingDirection]; [paragraphStyle.get() setAlignment:menuTextDirection == LTR ? NSLeftTextAlignment : NSRightTextAlignment]; - RetainPtr<NSMutableDictionary> attributes(AdoptNS, [[NSMutableDictionary alloc] initWithObjectsAndKeys: + RetainPtr<NSMutableDictionary> attributes = adoptNS([[NSMutableDictionary alloc] initWithObjectsAndKeys: paragraphStyle.get(), NSParagraphStyleAttributeName, font, NSFontAttributeName, nil]); if (items[i].m_hasTextDirectionOverride) { - RetainPtr<NSNumber> writingDirectionValue(AdoptNS, [[NSNumber alloc] initWithInteger:writingDirection + NSTextWritingDirectionOverride]); - RetainPtr<NSArray> writingDirectionArray(AdoptNS, [[NSArray alloc] initWithObjects:writingDirectionValue.get(), nil]); + RetainPtr<NSNumber> writingDirectionValue = adoptNS([[NSNumber alloc] initWithInteger:writingDirection + NSTextWritingDirectionOverride]); + RetainPtr<NSArray> writingDirectionArray = adoptNS([[NSArray alloc] initWithObjects:writingDirectionValue.get(), nil]); [attributes.get() setObject:writingDirectionArray.get() forKey:NSWritingDirectionAttributeName]; } - RetainPtr<NSAttributedString> string(AdoptNS, [[NSAttributedString alloc] initWithString:nsStringFromWebCoreString(items[i].m_text) attributes:attributes.get()]); + RetainPtr<NSAttributedString> string = adoptNS([[NSAttributedString alloc] initWithString:nsStringFromWebCoreString(items[i].m_text) attributes:attributes.get()]); [menuItem setAttributedTitle:string.get()]; // We set the title as well as the attributed title here. The attributed title will be displayed in the menu, @@ -130,7 +130,7 @@ void WebPopupMenuProxyMac::showPopupMenu(const IntRect& rect, TextDirection text } else location = NSMakePoint(NSMinX(rect) + popUnderHorizontalAdjust, NSMaxY(rect) + popUnderVerticalAdjust); - RetainPtr<NSView> dummyView(AdoptNS, [[NSView alloc] initWithFrame:rect]); + RetainPtr<NSView> dummyView = adoptNS([[NSView alloc] initWithFrame:rect]); [m_webView addSubview:dummyView.get()]; location = [dummyView.get() convertPoint:location fromView:m_webView]; diff --git a/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm index a182faa42..2ca0b3f2a 100644 --- a/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm +++ b/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm @@ -26,124 +26,14 @@ #import "config.h" #import "WebProcessProxy.h" -#import "SecItemRequestData.h" -#import "SecItemResponseData.h" -#import "SecKeychainItemRequestData.h" -#import "SecKeychainItemResponseData.h" +#import "WebContext.h" +#import "WebPageGroup.h" +#import "WebPreferences.h" #import "WebProcessMessages.h" #import "WKFullKeyboardAccessWatcher.h" -#import <Security/SecItem.h> namespace WebKit { -static void handleSecItemRequest(CoreIPC::Connection* connection, uint64_t requestID, const SecItemRequestData& request) -{ - SecItemResponseData response; - - switch (request.type()) { - case SecItemRequestData::CopyMatching: { - CFTypeRef resultObject = 0; - OSStatus resultCode = SecItemCopyMatching(request.query(), &resultObject); - response = SecItemResponseData(resultCode, adoptCF(resultObject).get()); - break; - } - - case SecItemRequestData::Add: { - CFTypeRef resultObject = 0; - OSStatus resultCode = SecItemAdd(request.query(), &resultObject); - response = SecItemResponseData(resultCode, adoptCF(resultObject).get()); - break; - } - - case SecItemRequestData::Update: { - OSStatus resultCode = SecItemUpdate(request.query(), request.attributesToMatch()); - response = SecItemResponseData(resultCode, 0); - break; - } - - case SecItemRequestData::Delete: { - OSStatus resultCode = SecItemDelete(request.query()); - response = SecItemResponseData(resultCode, 0); - break; - } - - default: - return; - } - - connection->send(Messages::WebProcess::SecItemResponse(requestID, response), 0); -} - -static void dispatchFunctionOnQueue(dispatch_queue_t queue, const Function<void ()>& function) -{ -#if COMPILER(CLANG) - dispatch_async(queue, function); -#else - Function<void ()>* functionPtr = new Function<void ()>(function); - dispatch_async(queue, ^{ - (*functionPtr)(); - delete functionPtr; - }); -#endif -} - -void WebProcessProxy::secItemRequest(CoreIPC::Connection* connection, uint64_t requestID, const SecItemRequestData& request) -{ - // Since we don't want the connection work queue to be held up, we do all - // keychain interaction work on a global dispatch queue. - dispatch_queue_t keychainWorkQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - dispatchFunctionOnQueue(keychainWorkQueue, bind(handleSecItemRequest, RefPtr<CoreIPC::Connection>(connection), requestID, request)); -} - -static void handleSecKeychainItemRequest(CoreIPC::Connection* connection, uint64_t requestID, const SecKeychainItemRequestData& request) -{ - SecKeychainItemResponseData response; - - switch (request.type()) { - case SecKeychainItemRequestData::CopyContent: { - SecKeychainItemRef item = request.keychainItem(); - SecItemClass itemClass; - SecKeychainAttributeList* attrList = request.attributeList(); - UInt32 length = 0; - void* outData = 0; - - OSStatus resultCode = SecKeychainItemCopyContent(item, &itemClass, attrList, &length, &outData); - RetainPtr<CFDataRef> data(AdoptCF, CFDataCreate(0, static_cast<const UInt8*>(outData), length)); - response = SecKeychainItemResponseData(resultCode, itemClass, attrList, data.get()); - - SecKeychainItemFreeContent(attrList, outData); - break; - } - - case SecKeychainItemRequestData::CreateFromContent: { - SecKeychainItemRef keychainItem; - - OSStatus resultCode = SecKeychainItemCreateFromContent(request.itemClass(), request.attributeList(), request.length(), request.data(), 0, 0, &keychainItem); - response = SecKeychainItemResponseData(resultCode, adoptCF(keychainItem)); - break; - } - - case SecKeychainItemRequestData::ModifyContent: { - OSStatus resultCode = SecKeychainItemModifyContent(request.keychainItem(), request.attributeList(), request.length(), request.data()); - response = resultCode; - break; - } - - default: - return; - } - - connection->send(Messages::WebProcess::SecKeychainItemResponse(requestID, response), 0); -} - -void WebProcessProxy::secKeychainItemRequest(CoreIPC::Connection* connection, uint64_t requestID, const SecKeychainItemRequestData& request) -{ - // Since we don't want the connection work queue to be held up, we do all - // keychain interaction work on a global dispatch queue. - dispatch_queue_t keychainWorkQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - dispatchFunctionOnQueue(keychainWorkQueue, bind(handleSecKeychainItemRequest, RefPtr<CoreIPC::Connection>(connection), requestID, request)); -} - bool WebProcessProxy::fullKeyboardAccessEnabled() { return [WKFullKeyboardAccessWatcher fullKeyboardAccessEnabled]; @@ -163,7 +53,7 @@ static bool shouldUseXPC() } #endif -void WebProcessProxy::platformConnect(ProcessLauncher::LaunchOptions& launchOptions) +void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) { // We want the web process to match the architecture of the UI process. launchOptions.architecture = ProcessLauncher::LaunchOptions::MatchCurrentArchitecture; @@ -174,4 +64,27 @@ void WebProcessProxy::platformConnect(ProcessLauncher::LaunchOptions& launchOpti #endif } +bool WebProcessProxy::pageIsProcessSuppressible(WebPageProxy* page) +{ + return !page->isViewVisible() && page->pageGroup()->preferences()->pageVisibilityBasedProcessSuppressionEnabled(); +} + +bool WebProcessProxy::allPagesAreProcessSuppressible() const +{ + return (m_processSuppressiblePages.size() == m_pageMap.size()) && !m_processSuppressiblePages.isEmpty(); +} + +void WebProcessProxy::updateProcessSuppressionState() +{ + if (!isValid()) + return; + + bool canEnable = m_context->canEnableProcessSuppressionForWebProcess(this); + if (m_processSuppressionEnabled == canEnable) + return; + m_processSuppressionEnabled = canEnable; + + connection()->send(Messages::WebProcess::SetProcessSuppressionEnabled(m_processSuppressionEnabled), 0); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.cpp b/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.cpp index 6351555cf..f72946529 100644 --- a/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.cpp +++ b/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.cpp @@ -125,11 +125,8 @@ void PageViewportControllerClientQt::setContentRectVisiblePositionAtScale(const void PageViewportControllerClientQt::animateContentRectVisible(const QRectF& contentRect) { - ASSERT(m_scaleAnimation->state() == QAbstractAnimation::Stopped); - + ASSERT(!scaleAnimationActive()); ASSERT(!scrollAnimationActive()); - if (scrollAnimationActive()) - return; QRectF viewportRectInContentCoords = m_viewportItem->mapRectToWebContent(m_viewportItem->boundingRect()); if (contentRect == viewportRectInContentCoords) { @@ -192,6 +189,10 @@ void PageViewportControllerClientQt::scaleAnimationStateChanged(QAbstractAnimati void PageViewportControllerClientQt::touchBegin() { + // Check for sane event delivery. At this point neither a pan gesture nor a pinch gesture should be active. + ASSERT(!m_viewportItem->isDragging()); + ASSERT(!(m_pinchStartScale > 0)); + m_controller->setHadUserInteraction(true); // Prevent resuming the page during transition between gestures while the user is interacting. @@ -231,7 +232,7 @@ void PageViewportControllerClientQt::focusEditableArea(const QRectF& caretArea, const QPointF viewportHotspot = QPointF(x, /* FIXME: visibleCenter */ viewportRect.center().y()); QPointF endPosition = hotspot - viewportHotspot / targetScale; - endPosition = m_controller->clampViewportToContents(endPosition, targetScale); + endPosition = m_controller->boundContentsPositionAtScale(endPosition, targetScale); QRectF endVisibleContentRect(endPosition, viewportRect.size() / targetScale); animateContentRectVisible(endVisibleContentRect); @@ -253,7 +254,7 @@ void PageViewportControllerClientQt::zoomToAreaGestureEnded(const QPointF& touch const QRectF viewportRect = m_viewportItem->boundingRect(); - qreal minViewportScale = qreal(2.5); + const qreal minViewportScale = qreal(2.5); qreal targetScale = viewportRect.size().width() / endArea.size().width(); targetScale = m_controller->innerBoundedViewportScale(qMin(minViewportScale, targetScale)); qreal currentScale = m_pageItem->contentsScale(); @@ -265,7 +266,7 @@ void PageViewportControllerClientQt::zoomToAreaGestureEnded(const QPointF& touch const QPointF viewportHotspot = viewportRect.center(); QPointF endPosition = hotspot - viewportHotspot / targetScale; - endPosition = m_controller->clampViewportToContents(endPosition, targetScale); + endPosition = m_controller->boundContentsPositionAtScale(endPosition, targetScale); QRectF endVisibleContentRect(endPosition, viewportRect.size() / targetScale); enum { ZoomIn, ZoomBack, ZoomOut, NoZoom } zoomAction = ZoomIn; @@ -295,7 +296,7 @@ void PageViewportControllerClientQt::zoomToAreaGestureEnded(const QPointF& touch break; case ZoomBack: { if (m_scaleStack.isEmpty()) { - targetScale = m_controller->minimumContentsScale(); + targetScale = m_controller->minimumScale(); endPosition.setY(hotspot.y() - viewportHotspot.y() / targetScale); endPosition.setX(0); m_zoomOutScale = 0; @@ -306,7 +307,7 @@ void PageViewportControllerClientQt::zoomToAreaGestureEnded(const QPointF& touch endPosition.setY(hotspot.y() - viewportHotspot.y() / targetScale); endPosition.setX(lastScale.xPosition); } - endPosition = m_controller->clampViewportToContents(endPosition, targetScale); + endPosition = m_controller->boundContentsPositionAtScale(endPosition, targetScale); endVisibleContentRect = QRectF(endPosition, viewportRect.size() / targetScale); break; } @@ -338,7 +339,7 @@ QRectF PageViewportControllerClientQt::nearestValidVisibleContentsRect() const // Keep the center at the position of the old center, and substract viewportHotspot / targetScale to get the top left position. QPointF endPosition = m_viewportItem->mapToWebContent(viewportHotspot) - viewportHotspot / targetScale; - endPosition = m_controller->clampViewportToContents(endPosition, targetScale); + endPosition = m_controller->boundContentsPositionAtScale(endPosition, targetScale); return QRectF(endPosition, viewportRect.size() / targetScale); } @@ -349,13 +350,9 @@ void PageViewportControllerClientQt::setViewportPosition(const FloatPoint& conte m_viewportItem->setContentPos(newPosition); } -void PageViewportControllerClientQt::setContentsScale(float localScale, bool treatAsInitialValue) +void PageViewportControllerClientQt::setPageScaleFactor(float localScale) { - if (treatAsInitialValue) { - clearRelativeZoomState(); - setContentRectVisiblePositionAtScale(QPointF(), localScale); - } else - scaleContent(localScale); + scaleContent(localScale); } void PageViewportControllerClientQt::setContentsRectToNearestValidBounds() @@ -365,26 +362,15 @@ void PageViewportControllerClientQt::setContentsRectToNearestValidBounds() updateViewportController(); } -void PageViewportControllerClientQt::didResumeContent() -{ - // Make sure that tiles all around the viewport will be requested. - updateViewportController(); -} - bool PageViewportControllerClientQt::scrollAnimationActive() const { return m_viewportItem->isFlicking(); } -bool PageViewportControllerClientQt::panGestureActive() const -{ - return m_controller->hadUserInteraction() && m_viewportItem->isDragging(); -} - void PageViewportControllerClientQt::panGestureStarted(const QPointF& position, qint64 eventTimestampMillis) { // This can only happen as a result of a user interaction. - ASSERT(m_controller->hadUserInteraction()); + ASSERT(m_touchInteraction.inProgress()); m_viewportItem->handleFlickableMousePress(position, eventTimestampMillis); m_lastPinchCenterInViewportCoordinates = position; @@ -439,15 +425,10 @@ void PageViewportControllerClientQt::interruptScaleAnimation() m_scaleAnimation->stop(); } -bool PageViewportControllerClientQt::pinchGestureActive() const -{ - return m_controller->hadUserInteraction() && (m_pinchStartScale > 0); -} - void PageViewportControllerClientQt::pinchGestureStarted(const QPointF& pinchCenterInViewportCoordinates) { // This can only happen as a result of a user interaction. - ASSERT(m_controller->hadUserInteraction()); + ASSERT(m_touchInteraction.inProgress()); if (!m_controller->allowsUserScaling() || !m_viewportItem->isInteractive()) return; diff --git a/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.h b/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.h index 22c4c3d3c..c0b75cee1 100644 --- a/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.h +++ b/Source/WebKit2/UIProcess/qt/PageViewportControllerClientQt.h @@ -48,9 +48,8 @@ public: ~PageViewportControllerClientQt(); virtual void setViewportPosition(const WebCore::FloatPoint& contentsPoint); - virtual void setContentsScale(float scale, bool treatAsInitialValue); + virtual void setPageScaleFactor(float); - virtual void didResumeContent(); virtual void didChangeContentsSize(const WebCore::IntSize&); virtual void didChangeVisibleContents(); virtual void didChangeViewportAttributes(); @@ -64,7 +63,6 @@ public: bool scrollAnimationActive() const; void cancelScrollAnimation(); - bool panGestureActive() const; void panGestureStarted(const QPointF& position, qint64 eventTimestampMillis); void panGestureRequestUpdate(const QPointF& position, qint64 eventTimestampMillis); void panGestureEnded(const QPointF& position, qint64 eventTimestampMillis); @@ -73,7 +71,6 @@ public: bool scaleAnimationActive() const; void interruptScaleAnimation(); - bool pinchGestureActive() const; void pinchGestureStarted(const QPointF& pinchCenterInViewportCoordinates); void pinchGestureRequestUpdate(const QPointF& pinchCenterInViewportCoordinates, qreal totalScaleFactor); void pinchGestureEnded(); diff --git a/Source/WebKit2/UIProcess/qt/QtDownloadManager.cpp b/Source/WebKit2/UIProcess/qt/QtDownloadManager.cpp index eb76f1aed..514a3e554 100644 --- a/Source/WebKit2/UIProcess/qt/QtDownloadManager.cpp +++ b/Source/WebKit2/UIProcess/qt/QtDownloadManager.cpp @@ -21,17 +21,23 @@ #include "config.h" #include "QtDownloadManager.h" -#include "DownloadProxy.h" #include "QtWebError.h" -#include "WKStringQt.h" -#include "WKURLQt.h" -#include "WebContext.h" #include "qwebdownloaditem_p.h" #include "qwebdownloaditem_p_p.h" +#include <WKDownload.h> +#include <WKStringQt.h> +#include <WKURLQt.h> +#include <WKURLResponse.h> namespace WebKit { -QtDownloadManager::QtDownloadManager(WebContext* context) +static inline QtDownloadManager* toQtDownloadManager(const void* clientInfo) +{ + ASSERT(clientInfo); + return reinterpret_cast<QtDownloadManager*>(const_cast<void*>(clientInfo)); +} + +QtDownloadManager::QtDownloadManager(WKContextRef context) { WKContextDownloadClient downloadClient; memset(&downloadClient, 0, sizeof(WKContextDownloadClient)); @@ -42,52 +48,60 @@ QtDownloadManager::QtDownloadManager(WebContext* context) downloadClient.didCreateDestination = didCreateDestination; downloadClient.didFinish = didFinishDownload; downloadClient.didFail = didFailDownload; - WKContextSetDownloadClient(toAPI(context), &downloadClient); + WKContextSetDownloadClient(context, &downloadClient); } QtDownloadManager::~QtDownloadManager() { } -void QtDownloadManager::addDownload(DownloadProxy* download, QWebDownloadItem* downloadItem) +void QtDownloadManager::addDownload(WKDownloadRef download, QWebDownloadItem* downloadItem) { - m_downloads[download->downloadID()] = downloadItem; + m_downloads[WKDownloadGetID(download)] = downloadItem; } -void QtDownloadManager::downloadReceivedResponse(DownloadProxy* download, const WebCore::ResourceResponse& response) +void QtDownloadManager::didReceiveResponse(WKContextRef, WKDownloadRef download, WKURLResponseRef response, const void* clientInfo) { + QtDownloadManager* q = toQtDownloadManager(clientInfo); + // Will be called when the headers are read by WebProcess. - QWebDownloadItem* downloadItem = m_downloads.value(download->downloadID()); + QWebDownloadItem* downloadItem = q->m_downloads.value(WKDownloadGetID(download)); ASSERT(downloadItem); - downloadItem->d->sourceUrl = response.url(); - downloadItem->d->mimeType = response.mimeType(); - downloadItem->d->expectedContentLength = response.expectedContentLength(); - downloadItem->d->suggestedFilename = response.suggestedFilename(); + downloadItem->d->sourceUrl = adoptToQUrl(WKURLResponseCopyURL(response)); + downloadItem->d->mimeType = adoptToQString(WKURLResponseCopyMIMEType(response)); + downloadItem->d->expectedContentLength = WKURLResponseGetExpectedContentLength(response); + downloadItem->d->suggestedFilename = WKStringCopyQString(adoptWK(WKURLResponseCopySuggestedFilename(response)).get()); downloadItem->d->didReceiveResponse(downloadItem); } -void QtDownloadManager::downloadCreatedDestination(DownloadProxy* download, const QString& path) +void QtDownloadManager::didCreateDestination(WKContextRef, WKDownloadRef download, WKStringRef path, const void* clientInfo) { - QWebDownloadItem* downloadItem = m_downloads.value(download->downloadID()); + QtDownloadManager* q = toQtDownloadManager(clientInfo); + + QWebDownloadItem* downloadItem = q->m_downloads.value(WKDownloadGetID(download)); ASSERT(downloadItem); - downloadItem->d->destinationPath = path; + downloadItem->d->destinationPath = WKStringCopyQString(path); emit downloadItem->destinationFileCreated(downloadItem->d->destinationPath); } -void QtDownloadManager::downloadFinished(DownloadProxy* download) +void QtDownloadManager::didFinishDownload(WKContextRef, WKDownloadRef download, const void *clientInfo) { + QtDownloadManager* q = toQtDownloadManager(clientInfo); + // Will be called when download finishes with success. - QWebDownloadItem* downloadItem = m_downloads.take(download->downloadID()); + QWebDownloadItem* downloadItem = q->m_downloads.take(WKDownloadGetID(download)); ASSERT(downloadItem); emit downloadItem->succeeded(); } -void QtDownloadManager::downloadFailed(DownloadProxy* download, const QtWebError& error) +void QtDownloadManager::didFailDownload(WKContextRef, WKDownloadRef download, WKErrorRef error, const void* clientInfo) { + QtDownloadManager* q = toQtDownloadManager(clientInfo); + // Will be called when download fails or is aborted. - QWebDownloadItem* downloadItem = m_downloads.take(download->downloadID()); + QWebDownloadItem* downloadItem = q->m_downloads.take(WKDownloadGetID(download)); ASSERT(downloadItem); // If the parent is null at this point, the download failed before it @@ -99,47 +113,19 @@ void QtDownloadManager::downloadFailed(DownloadProxy* download, const QtWebError return; } - emit downloadItem->failed(error.errorCodeAsDownloadError(), error.url(), error.description()); + QtWebError qtError(error); + emit downloadItem->failed(qtError.errorCodeAsDownloadError(), qtError.url(), qtError.description()); } -void QtDownloadManager::downloadDataReceived(DownloadProxy* download, uint64_t length) +void QtDownloadManager::didReceiveDataForDownload(WKContextRef, WKDownloadRef download, uint64_t length, const void* clientInfo) { + QtDownloadManager* q = toQtDownloadManager(clientInfo); + // Will be called everytime bytes were written to destination file by WebProcess. - QWebDownloadItem* downloadItem = m_downloads.value(download->downloadID()); + QWebDownloadItem* downloadItem = q->m_downloads.value(WKDownloadGetID(download)); ASSERT(downloadItem); downloadItem->d->totalBytesReceived += length; emit downloadItem->totalBytesReceivedChanged(length); } -static inline QtDownloadManager* toQtDownloadManager(const void* clientInfo) -{ - ASSERT(clientInfo); - return reinterpret_cast<QtDownloadManager*>(const_cast<void*>(clientInfo)); -} - -void QtDownloadManager::didReceiveResponse(WKContextRef, WKDownloadRef download, WKURLResponseRef response, const void *clientInfo) -{ - toQtDownloadManager(clientInfo)->downloadReceivedResponse(toImpl(download), toImpl(response)->resourceResponse()); -} - -void QtDownloadManager::didCreateDestination(WKContextRef, WKDownloadRef download, WKStringRef path, const void *clientInfo) -{ - toQtDownloadManager(clientInfo)->downloadCreatedDestination(toImpl(download), WKStringCopyQString(path)); -} - -void QtDownloadManager::didFinishDownload(WKContextRef, WKDownloadRef download, const void *clientInfo) -{ - toQtDownloadManager(clientInfo)->downloadFinished(toImpl(download)); -} - -void QtDownloadManager::didFailDownload(WKContextRef, WKDownloadRef download, WKErrorRef error, const void *clientInfo) -{ - toQtDownloadManager(clientInfo)->downloadFailed(toImpl(download), QtWebError(error)); -} - -void QtDownloadManager::didReceiveDataForDownload(WKContextRef, WKDownloadRef download, uint64_t length, const void *clientInfo) -{ - toQtDownloadManager(clientInfo)->downloadDataReceived(toImpl(download), length); -} - } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/QtDownloadManager.h b/Source/WebKit2/UIProcess/qt/QtDownloadManager.h index a49f5e2a4..a52309b1a 100644 --- a/Source/WebKit2/UIProcess/qt/QtDownloadManager.h +++ b/Source/WebKit2/UIProcess/qt/QtDownloadManager.h @@ -26,31 +26,19 @@ class QWebDownloadItem; -namespace WebCore { -class ResourceResponse; -} - namespace WebKit { class DownloadProxy; class QtWebError; -class WebContext; class QtDownloadManager { public: - QtDownloadManager(WebContext*); + QtDownloadManager(WKContextRef); ~QtDownloadManager(); - void addDownload(DownloadProxy*, QWebDownloadItem*); + void addDownload(WKDownloadRef, QWebDownloadItem*); private: - void downloadReceivedResponse(DownloadProxy*, const WebCore::ResourceResponse&); - void downloadCreatedDestination(DownloadProxy*, const QString& path); - void downloadFinished(DownloadProxy*); - void downloadFailed(DownloadProxy*, const QtWebError&); - void downloadDataReceived(DownloadProxy*, uint64_t length); - - // WKContextDownloadClient callbacks. static void didReceiveResponse(WKContextRef, WKDownloadRef, WKURLResponseRef, const void* clientInfo); static void didCreateDestination(WKContextRef, WKDownloadRef, WKStringRef path, const void* clientInfo); static void didFinishDownload(WKContextRef, WKDownloadRef, const void* clientInfo); diff --git a/Source/WebKit2/UIProcess/qt/QtPageClient.cpp b/Source/WebKit2/UIProcess/qt/QtPageClient.cpp index 89a40c923..2f242c609 100644 --- a/Source/WebKit2/UIProcess/qt/QtPageClient.cpp +++ b/Source/WebKit2/UIProcess/qt/QtPageClient.cpp @@ -27,7 +27,7 @@ #include "QtWebPageEventHandler.h" #include "ShareableBitmap.h" #if ENABLE(INPUT_TYPE_COLOR) -#include "WebColorChooserProxyQt.h" +#include "WebColorPickerQt.h" #endif #include "WebContextMenuProxyQt.h" #include "WebEditCommandProxy.h" @@ -221,9 +221,9 @@ PassRefPtr<WebContextMenuProxy> QtPageClient::createContextMenuProxy(WebPageProx } #if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorChooserProxy> QtPageClient::createColorChooserProxy(WebPageProxy* webPageProxy, const WebCore::Color& initialColor, const WebCore::IntRect& elementRect) +PassRefPtr<WebColorPicker> QtPageClient::createColorPicker(WebPageProxy* webPageProxy, const WebCore::Color& initialColor, const WebCore::IntRect& elementRect) { - return WebColorChooserProxyQt::create(webPageProxy, m_webView, initialColor, elementRect); + return WebColorPickerQt::create(webPageProxy, m_webView, initialColor, elementRect); } #endif @@ -245,11 +245,6 @@ void QtPageClient::didFindZoomableArea(const IntPoint& target, const IntRect& ar m_eventHandler->didFindZoomableArea(target, area); } -void QtPageClient::didReceiveMessageFromNavigatorQtObject(const String& message) -{ - QQuickWebViewPrivate::get(m_webView)->didReceiveMessageFromNavigatorQtObject(message); -} - void QtPageClient::updateTextInputState() { ASSERT(m_eventHandler); diff --git a/Source/WebKit2/UIProcess/qt/QtPageClient.h b/Source/WebKit2/UIProcess/qt/QtPageClient.h index fc10ca653..e6d9db307 100644 --- a/Source/WebKit2/UIProcess/qt/QtPageClient.h +++ b/Source/WebKit2/UIProcess/qt/QtPageClient.h @@ -47,7 +47,6 @@ public: virtual WebCore::IntSize viewSize(); virtual bool isViewFocused(); virtual bool isViewVisible(); - virtual void didReceiveMessageFromNavigatorQtObject(const String&); virtual void pageDidRequestScroll(const WebCore::IntPoint&); virtual void didChangeContentsSize(const WebCore::IntSize&); virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); @@ -61,6 +60,7 @@ public: virtual void handleProxyAuthenticationRequiredRequest(const String& hostname, uint16_t port, const String& prefilledUsername, String& username, String& password); virtual void displayView(); + virtual bool canScrollView() { return false; } virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); virtual bool isViewWindowActive(); virtual bool isViewInWindow(); @@ -70,6 +70,7 @@ public: virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); #endif // USE(ACCELERATED_COMPOSITING) virtual void pageClosed() { } + virtual void preferencesDidChange() { } virtual void startDrag(const WebCore::DragData&, PassRefPtr<ShareableBitmap> dragImage); virtual void setCursor(const WebCore::Cursor&); virtual void setCursorHiddenUntilMouseMoves(bool); @@ -89,17 +90,10 @@ public: virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*); virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); #if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorChooserProxy> createColorChooserProxy(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&); + virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&); #endif virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate) { } - virtual void didCommitLoadForMainFrame(bool useCustomRepresentation) { } - virtual void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&) { } - virtual double customRepresentationZoomFactor() { return 1; } - virtual void setCustomRepresentationZoomFactor(double) { } - virtual void didChangeScrollbarsForMainFrame() const { } virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); - virtual void findStringInCustomRepresentation(const String&, WebKit::FindOptions, unsigned maxMatchCount) { } - virtual void countStringMatchesInCustomRepresentation(const String&, WebKit::FindOptions, unsigned maxMatchCount) { } virtual void pageTransitionViewportReady(); virtual void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&); virtual void updateTextInputState(); diff --git a/Source/WebKit2/UIProcess/qt/QtWebContext.cpp b/Source/WebKit2/UIProcess/qt/QtWebContext.cpp index 7eb3b7196..4489d74c8 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebContext.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebContext.cpp @@ -21,24 +21,29 @@ #include "config.h" #include "QtWebContext.h" -#include "MutableArray.h" #include "QtDownloadManager.h" #include "QtWebIconDatabaseClient.h" -#include "WKAPICast.h" -#include "WebContext.h" #include "WebInspectorServer.h" -#include "WebPageProxy.h" +#include "qquickwebview_p_p.h" +#include <QDir> +#include <QStandardPaths> +#include <QStringBuilder> +#include <WKAPICast.h> #include <WKArray.h> +#include <WKContextPrivate.h> #include <WKPage.h> #include <WKString.h> +#include <WKStringQt.h> #include <WKType.h> namespace WebKit { -static WebContext* s_defaultWebContext = 0; +// Prevent the destruction of the WKContext for two reasons: +// - An internal reference is kept to the WebContext waiting until the web process shut down, which +// does so 60 seconds after the last page closed. We want to reuse that web process if possible and +// avoid creating a second parallel WKContext + web process. +// - The IconDatabase wasn't designed to have more than one instance, or to be quickly opened/closed. static QtWebContext* s_defaultQtWebContext = 0; -static OwnPtr<QtDownloadManager> s_downloadManager; -static OwnPtr<QtWebIconDatabaseClient> s_iconDatabase; static void initInspectorServer() { @@ -98,117 +103,95 @@ static void didReceiveMessageFromInjectedBundle(WKContextRef, WKStringRef messag WKPageRef page = static_cast<WKPageRef>(WKArrayGetItemAtIndex(body, 0)); WKStringRef str = static_cast<WKStringRef>(WKArrayGetItemAtIndex(body, 1)); - toImpl(page)->didReceiveMessageFromNavigatorQtObject(toImpl(str)->string()); + QQuickWebViewPrivate::get(page)->didReceiveMessageFromNavigatorQtObject(str); } -static void initializeContextInjectedBundleClient(WebContext* context) +static void initializeContextInjectedBundleClient(WKContextRef context) { WKContextInjectedBundleClient injectedBundleClient; memset(&injectedBundleClient, 0, sizeof(WKContextInjectedBundleClient)); injectedBundleClient.version = kWKContextInjectedBundleClientCurrentVersion; injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; - WKContextSetInjectedBundleClient(toAPI(context), &injectedBundleClient); + WKContextSetInjectedBundleClient(context, &injectedBundleClient); } -QtWebContext::QtWebContext(WebContext* context) +QtWebContext::QtWebContext(WKContextRef context) : m_context(context) + , m_downloadManager(new QtDownloadManager(context)) + , m_iconDatabase(new QtWebIconDatabaseClient(context)) { } QtWebContext::~QtWebContext() { - ASSERT(!s_defaultQtWebContext || s_defaultQtWebContext == this); - s_defaultQtWebContext = 0; } // Used directly only by WebKitTestRunner. -PassRefPtr<QtWebContext> QtWebContext::create(WebContext* context) +QtWebContext* QtWebContext::create(WKContextRef context) { globalInitialization(); - // The lifetime of WebContext is a bit special, it is bound to the reference held - // by QtWebContext at first and then enters a circular dependency with WebProcessProxy - // once the first page is created until the web process exits. Because of this we can't - // assume that destroying the last QtWebContext will destroy the WebContext and we - // have to make sure that WebContext's clients follow its lifetime and aren't attached - // to QtWebContext. QtWebContext itself is only attached to QQuickWebView. - // Since we only support one WebContext at a time, initialize those clients globally - // here. They have to be available to views spawned by WebKitTestRunner as well. - if (!s_downloadManager) - s_downloadManager = adoptPtr(new QtDownloadManager(context)); - if (!s_iconDatabase) - s_iconDatabase = adoptPtr(new QtWebIconDatabaseClient(context)); - return adoptRef(new QtWebContext(context)); + return new QtWebContext(context); } -PassRefPtr<QtWebContext> QtWebContext::defaultContext() +QtWebContext* QtWebContext::defaultContext() { - // Keep local references until we can return a ref to QtWebContext holding the WebContext. - RefPtr<WebContext> webContext(s_defaultWebContext); - RefPtr<QtWebContext> qtWebContext(s_defaultQtWebContext); - - if (!webContext) { - webContext = WebContext::create(String()); - s_defaultWebContext = webContext.get(); + if (!s_defaultQtWebContext) { + WKRetainPtr<WKContextRef> wkContext = adoptWK(WKContextCreate()); // Make sure for WebKitTestRunner that the injected bundle client isn't initialized - // and that the page cache isn't enabled (defaultContext isn't used there). - initializeContextInjectedBundleClient(webContext.get()); + // and that the page cache isn't enabled (defaultContext() isn't used there). + initializeContextInjectedBundleClient(wkContext.get()); // A good all-around default. - webContext->setCacheModel(CacheModelDocumentBrowser); - } - - if (!qtWebContext) { - qtWebContext = QtWebContext::create(webContext.get()); - s_defaultQtWebContext = qtWebContext.get(); - } + WKContextSetCacheModel(wkContext.get(), kWKCacheModelDocumentBrowser); - return qtWebContext.release(); -} - -PassRefPtr<WebPageProxy> QtWebContext::createWebPage(PageClient* client, WebPageGroup* pageGroup) -{ - return m_context->createWebPage(client, pageGroup); -} + // Those paths have to be set before the first web process is spawned. + WKContextSetDatabaseDirectory(wkContext.get(), adoptWK(WKStringCreateWithQString(preparedStoragePath(DatabaseStorage))).get()); + WKContextSetLocalStorageDirectory(wkContext.get(), adoptWK(WKStringCreateWithQString(preparedStoragePath(LocalStorage))).get()); + WKContextSetCookieStorageDirectory(wkContext.get(), adoptWK(WKStringCreateWithQString(preparedStoragePath(CookieStorage))).get()); + WKContextSetDiskCacheDirectory(wkContext.get(), adoptWK(WKStringCreateWithQString(preparedStoragePath(DiskCacheStorage))).get()); -void QtWebContext::setNavigatorQtObjectEnabled(WebPageProxy* webPageProxy, bool enabled) -{ - static String messageName("SetNavigatorQtObjectEnabled"); - RefPtr<MutableArray> body = MutableArray::create(); - body->append(webPageProxy); - RefPtr<WebBoolean> webEnabled = WebBoolean::create(enabled); - body->append(webEnabled.get()); - m_context->postMessageToInjectedBundle(messageName, body.get()); -} + s_defaultQtWebContext = QtWebContext::create(wkContext.get()); + } -void QtWebContext::postMessageToNavigatorQtObject(WebPageProxy* webPageProxy, const QString& message) -{ - static String messageName("MessageToNavigatorQtObject"); - RefPtr<MutableArray> body = MutableArray::create(); - body->append(webPageProxy); - RefPtr<WebString> contents = WebString::create(String(message)); - body->append(contents.get()); - m_context->postMessageToInjectedBundle(messageName, body.get()); + return s_defaultQtWebContext; } -QtDownloadManager* QtWebContext::downloadManager() +static QString defaultLocation(QStandardPaths::StandardLocation type) { - ASSERT(s_downloadManager); - return s_downloadManager.get(); + QString path = QStandardPaths::writableLocation(type); + Q_ASSERT(!path.isEmpty()); + return path % QDir::separator() % QStringLiteral(".QtWebKit") % QDir::separator(); } -QtWebIconDatabaseClient* QtWebContext::iconDatabase() +QString QtWebContext::preparedStoragePath(StorageType type) { - ASSERT(s_iconDatabase); - return s_iconDatabase.get(); -} + QString path; + switch (type) { + case DatabaseStorage: + path = defaultLocation(QStandardPaths::DataLocation) % QStringLiteral("Databases"); + QDir::root().mkpath(path); + break; + case LocalStorage: + path = defaultLocation(QStandardPaths::DataLocation) % QStringLiteral("LocalStorage"); + QDir::root().mkpath(path); + break; + case CookieStorage: + path = defaultLocation(QStandardPaths::DataLocation); + QDir::root().mkpath(path); + break; + case DiskCacheStorage: + path = defaultLocation(QStandardPaths::CacheLocation) % QStringLiteral("DiskCache"); + QDir::root().mkpath(path); + break; + case IconDatabaseStorage: + path = defaultLocation(QStandardPaths::DataLocation); + QDir::root().mkpath(path); + path += QStringLiteral("WebpageIcons.db"); + break; + default: + Q_ASSERT(false); + } -void QtWebContext::invalidateContext(WebContext* context) -{ - UNUSED_PARAM(context); - ASSERT(!s_defaultQtWebContext); - ASSERT(!s_defaultWebContext || s_defaultWebContext == context); - s_downloadManager.clear(); - s_iconDatabase.clear(); - s_defaultWebContext = 0; + return path; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/QtWebContext.h b/Source/WebKit2/UIProcess/qt/QtWebContext.h index 2fa39f8c0..4251f29e7 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebContext.h +++ b/Source/WebKit2/UIProcess/qt/QtWebContext.h @@ -21,48 +21,44 @@ #ifndef QtWebContext_h #define QtWebContext_h +#include <QScopedPointer> #include <QtGlobal> #include <WKContext.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> -#include <wtf/RefPtr.h> - -QT_BEGIN_NAMESPACE -class QString; -QT_END_NAMESPACE +#include <WKRetainPtr.h> namespace WebKit { -class PageClient; class QtDownloadManager; class QtWebIconDatabaseClient; -class WebContext; -class WebPageGroup; -class WebPageProxy; -class QtWebContext : public RefCounted<QtWebContext> { +class QtWebContext { public: ~QtWebContext(); - static PassRefPtr<QtWebContext> create(WebContext*); - static PassRefPtr<QtWebContext> defaultContext(); + enum StorageType { + DatabaseStorage, + LocalStorage, + CookieStorage, + DiskCacheStorage, + IconDatabaseStorage + }; - PassRefPtr<WebPageProxy> createWebPage(PageClient*, WebPageGroup*); + static QtWebContext* create(WKContextRef); + static QtWebContext* defaultContext(); - WebContext* context() { return m_context.get(); } + static QString preparedStoragePath(StorageType); - void setNavigatorQtObjectEnabled(WebPageProxy*, bool); - void postMessageToNavigatorQtObject(WebPageProxy*, const QString&); + WKContextRef context() { return m_context.get(); } - static QtDownloadManager* downloadManager(); - static QtWebIconDatabaseClient* iconDatabase(); - static void invalidateContext(WebContext*); + QtDownloadManager* downloadManager() { return m_downloadManager.data(); } + QtWebIconDatabaseClient* iconDatabase() { return m_iconDatabase.data(); } private: - explicit QtWebContext(WebContext*); + explicit QtWebContext(WKContextRef); - RefPtr<WebContext> m_context; + WKRetainPtr<WKContextRef> m_context; + QScopedPointer<QtDownloadManager> m_downloadManager; + QScopedPointer<QtWebIconDatabaseClient> m_iconDatabase; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/QtWebError.cpp b/Source/WebKit2/UIProcess/qt/QtWebError.cpp index 75884f440..c2f506c8f 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebError.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebError.cpp @@ -57,12 +57,12 @@ int QtWebError::errorCode() const QString QtWebError::url() const { - return toImpl(error.get())->failingURL(); + return adoptToQString(WKErrorCopyFailingURL(error.get())); } QString QtWebError::description() const { - return WKStringCopyQString(WKErrorCopyLocalizedDescription(error.get())); + return adoptToQString(WKErrorCopyLocalizedDescription(error.get())); } bool QtWebError::isCancellation() const diff --git a/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.cpp b/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.cpp index 7dbb273fd..86ac710bf 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.cpp @@ -20,89 +20,73 @@ #include "config.h" #include "QtWebIconDatabaseClient.h" -#include "Image.h" -#include "KURL.h" -#include "SharedBuffer.h" -#include "WKURLQt.h" -#include "WebContext.h" -#include "WebIconDatabase.h" +#include "QtWebContext.h" #include <QtCore/QHash> #include <QtCore/QObject> #include <QtCore/QUrl> #include <QtGui/QImage> +#include <WKContext.h> +#include <WKContextPrivate.h> +#include <WKIconDatabaseQt.h> +#include <WKRetainPtr.h> +#include <WKStringQt.h> +#include <WKURLQt.h> namespace WebKit { +static unsigned s_updateId = 0; + static inline QtWebIconDatabaseClient* toQtWebIconDatabaseClient(const void* clientInfo) { ASSERT(clientInfo); return reinterpret_cast<QtWebIconDatabaseClient*>(const_cast<void*>(clientInfo)); } -QtWebIconDatabaseClient::QtWebIconDatabaseClient(WebContext *context) +QtWebIconDatabaseClient::QtWebIconDatabaseClient(WKContextRef context) { - // The setter calls the getter here as it triggers the startup of the icon database. - if (!context->iconDatabase()->isOpen()) - context->setIconDatabasePath(context->iconDatabasePath()); - m_iconDatabase = context->iconDatabase(); + m_iconDatabase = WKContextGetIconDatabase(context); WKIconDatabaseClient iconDatabaseClient; memset(&iconDatabaseClient, 0, sizeof(WKIconDatabaseClient)); iconDatabaseClient.version = kWKIconDatabaseClientCurrentVersion; iconDatabaseClient.clientInfo = this; iconDatabaseClient.didChangeIconForPageURL = didChangeIconForPageURL; - WKIconDatabaseSetIconDatabaseClient(toAPI(m_iconDatabase.get()), &iconDatabaseClient); + WKIconDatabaseSetIconDatabaseClient(m_iconDatabase, &iconDatabaseClient); + // Triggers the startup of the icon database. + WKRetainPtr<WKStringRef> path = adoptWK(WKStringCreateWithQString(QtWebContext::preparedStoragePath(QtWebContext::IconDatabaseStorage))); + WKContextSetIconDatabasePath(context, path.get()); } QtWebIconDatabaseClient::~QtWebIconDatabaseClient() { - m_iconDatabase->close(); - WKIconDatabaseSetIconDatabaseClient(toAPI(m_iconDatabase.get()), 0); + WKIconDatabaseClose(m_iconDatabase); + WKIconDatabaseSetIconDatabaseClient(m_iconDatabase, 0); } -void QtWebIconDatabaseClient::didChangeIconForPageURL(WKIconDatabaseRef, WKURLRef pageURL, const void* clientInfo) +unsigned QtWebIconDatabaseClient::updateID() { - emit toQtWebIconDatabaseClient(clientInfo)->iconChangedForPageURL(toImpl(pageURL)->string()); + return s_updateId; } -WTF::String QtWebIconDatabaseClient::iconForPageURL(const WTF::String& pageURL) +void QtWebIconDatabaseClient::didChangeIconForPageURL(WKIconDatabaseRef, WKURLRef pageURL, const void* clientInfo) { - String iconURL; - m_iconDatabase->synchronousIconURLForPageURL(pageURL, iconURL); - - if (iconURL.isEmpty()) - return String(); - - // Verify that the image data is actually available before reporting back - // a url, since clients assume that the url can be used directly. - WebCore::Image* iconImage = m_iconDatabase->imageForPageURL(pageURL); - if (!iconImage || iconImage->isNull()) - return String(); - - return iconURL; + ++s_updateId; + emit toQtWebIconDatabaseClient(clientInfo)->iconChangedForPageURL(WKURLCopyQString(pageURL)); } -QImage QtWebIconDatabaseClient::iconImageForPageURL(const WTF::String& pageURL, const QSize& iconSize) +QImage QtWebIconDatabaseClient::iconImageForPageURL(const QString& pageURL) { - MutexLocker locker(m_imageLock); - - WebCore::IntSize size(iconSize.width(), iconSize.height()); - - QPixmap* nativeImage = m_iconDatabase->nativeImageForPageURL(pageURL, size); - if (!nativeImage) - return QImage(); - - return nativeImage->toImage(); + return WKIconDatabaseTryGetQImageForURL(m_iconDatabase, adoptWK(WKURLCreateWithQString(pageURL)).get()); } -void QtWebIconDatabaseClient::retainIconForPageURL(const String& pageURL) +void QtWebIconDatabaseClient::retainIconForPageURL(const QString& pageURL) { - m_iconDatabase->retainIconForPageURL(pageURL); + WKIconDatabaseRetainIconForURL(m_iconDatabase, adoptWK(WKURLCreateWithQString(pageURL)).get()); } -void QtWebIconDatabaseClient::releaseIconForPageURL(const String& pageURL) +void QtWebIconDatabaseClient::releaseIconForPageURL(const QString& pageURL) { - m_iconDatabase->releaseIconForPageURL(pageURL); + WKIconDatabaseReleaseIconForURL(m_iconDatabase, adoptWK(WKURLCreateWithQString(pageURL)).get()); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.h b/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.h index 97197d8d6..69b7965ed 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.h +++ b/Source/WebKit2/UIProcess/qt/QtWebIconDatabaseClient.h @@ -21,47 +21,37 @@ #ifndef QtWebIconDatabaseClient_h #define QtWebIconDatabaseClient_h -#include "WKIconDatabase.h" #include "qwebkitglobal.h" #include <QtCore/QObject> -#include <QtCore/QSize> -#include <wtf/RefPtr.h> -#include <wtf/Threading.h> +#include <WKIconDatabase.h> QT_BEGIN_NAMESPACE class QImage; class QUrl; QT_END_NAMESPACE -namespace WTF { -class String; -} - namespace WebKit { -class WebContext; -class WebIconDatabase; - class QtWebIconDatabaseClient : public QObject { Q_OBJECT public: - QtWebIconDatabaseClient(WebContext*); + QtWebIconDatabaseClient(WKContextRef); ~QtWebIconDatabaseClient(); - WTF::String iconForPageURL(const WTF::String& pageURL); - QImage iconImageForPageURL(const WTF::String& pageURL, const QSize& iconSize = QSize(32, 32)); + QImage iconImageForPageURL(const QString&); + + void retainIconForPageURL(const QString&); + void releaseIconForPageURL(const QString&); - void retainIconForPageURL(const WTF::String&); - void releaseIconForPageURL(const WTF::String&); + static unsigned updateID(); public: Q_SIGNAL void iconChangedForPageURL(const QString& pageURL); private: static void didChangeIconForPageURL(WKIconDatabaseRef, WKURLRef pageURL, const void* clientInfo); - RefPtr<WebKit::WebIconDatabase> m_iconDatabase; - Mutex m_imageLock; + WKIconDatabaseRef m_iconDatabase; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/QtWebPageEventHandler.cpp b/Source/WebKit2/UIProcess/qt/QtWebPageEventHandler.cpp index 8176ed1cd..8e7c5c221 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebPageEventHandler.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebPageEventHandler.cpp @@ -463,8 +463,6 @@ void QtWebPageEventHandler::handleInputEvent(const QInputEvent* event) switch (event->type()) { case QEvent::MouseButtonPress: case QEvent::TouchBegin: - ASSERT(!m_viewportController->panGestureActive()); - ASSERT(!m_viewportController->pinchGestureActive()); m_viewportController->touchBegin(); // The page viewport controller might still be animating kinetic scrolling or a scale animation diff --git a/Source/WebKit2/UIProcess/qt/QtWebPageLoadClient.cpp b/Source/WebKit2/UIProcess/qt/QtWebPageLoadClient.cpp deleted file mode 100644 index 9f9021221..000000000 --- a/Source/WebKit2/UIProcess/qt/QtWebPageLoadClient.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#include "config.h" -#include "QtWebPageLoadClient.h" - -#include "QtWebError.h" -#include "qquickwebview_p_p.h" - -using namespace WebCore; - -namespace WebKit { - -QtWebPageLoadClient::QtWebPageLoadClient(WKPageRef pageRef, QQuickWebView* webView) - : m_webView(webView) -{ - WKPageLoaderClient loadClient; - memset(&loadClient, 0, sizeof(WKPageLoaderClient)); - loadClient.version = kWKPageLoaderClientCurrentVersion; - loadClient.clientInfo = this; - loadClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; - loadClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame; - loadClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame; - loadClient.didCommitLoadForFrame = didCommitLoadForFrame; - loadClient.didFinishLoadForFrame = didFinishLoadForFrame; - loadClient.didFailLoadWithErrorForFrame = didFailLoadWithErrorForFrame; - loadClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; - loadClient.didReceiveTitleForFrame = didReceiveTitleForFrame; - loadClient.didStartProgress = didStartProgress; - loadClient.didChangeProgress = didChangeProgress; - loadClient.didFinishProgress = didFinishProgress; - loadClient.didChangeBackForwardList = didChangeBackForwardList; - loadClient.processDidBecomeUnresponsive = processDidBecomeUnresponsive; - loadClient.processDidBecomeResponsive = processDidBecomeResponsive; - WKPageSetPageLoaderClient(pageRef, &loadClient); -} - -void QtWebPageLoadClient::didStartProvisionalLoad(const WTF::String& url) -{ - m_webView->d_func()->provisionalLoadDidStart(url); -} - -void QtWebPageLoadClient::didReceiveServerRedirectForProvisionalLoad(const WTF::String& url) -{ - m_webView->d_func()->didReceiveServerRedirectForProvisionalLoad(url); -} - -void QtWebPageLoadClient::didCommitLoad() -{ - PageViewportController* pvc = m_webView->d_func()->viewportController(); - if (pvc) - pvc->didCommitLoad(); - m_webView->d_func()->loadDidCommit(); -} - -void QtWebPageLoadClient::didSameDocumentNavigation() -{ - m_webView->d_func()->didSameDocumentNavigation(); -} - -void QtWebPageLoadClient::didReceiveTitle() -{ - m_webView->d_func()->titleDidChange(); -} - -void QtWebPageLoadClient::didChangeProgress(int loadProgress) -{ - m_webView->d_func()->loadProgressDidChange(loadProgress); -} - -void QtWebPageLoadClient::didChangeBackForwardList() -{ - m_webView->d_func()->backForwardListDidChange(); -} - -void QtWebPageLoadClient::processDidBecomeUnresponsive() -{ - m_webView->d_func()->processDidBecomeUnresponsive(); -} - -void QtWebPageLoadClient::processDidBecomeResponsive() -{ - m_webView->d_func()->processDidBecomeResponsive(); -} - -void QtWebPageLoadClient::dispatchLoadSucceeded() -{ - m_webView->d_func()->loadDidSucceed(); -} - -void QtWebPageLoadClient::dispatchLoadStopped() -{ - m_webView->d_func()->loadDidStop(); -} - -void QtWebPageLoadClient::dispatchLoadFailed(WebFrameProxy* frame, const QtWebError& error) -{ - if (error.isCancellation()) { - dispatchLoadStopped(); - return; - } - - int errorCode = error.errorCode(); - - if (errorCode == kWKErrorCodeFrameLoadInterruptedByPolicyChange || errorCode == kWKErrorCodePlugInWillHandleLoad) { - // The active url might have changed - m_webView->emitUrlChangeIfNeeded(); - - // Make sure that LoadStartedStatus has a counterpart when e.g. requesting a download. - dispatchLoadSucceeded(); - - return; - } - - // We set the unreachable url unconditionally so that the current - // active url of the webview when the loadingChanged signal is - // emitted reflects the failed url, not the previously committed - // url. This also ensures that if the user does not do a loadHtml - // with an error page and and unreachable url as a reponse to the - // failed load, we can still detect the failed url for reloads. - frame->setUnreachableURL(error.url()); - m_webView->emitUrlChangeIfNeeded(); - - m_webView->d_func()->loadDidFail(error); -} - -static QtWebPageLoadClient* toQtWebPageLoadClient(const void* clientInfo) -{ - ASSERT(clientInfo); - return reinterpret_cast<QtWebPageLoadClient*>(const_cast<void*>(clientInfo)); -} - -void QtWebPageLoadClient::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->didStartProvisionalLoad(toImpl(frame)->provisionalURL()); -} - -void QtWebPageLoadClient::didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WebFrameProxy* wkframe = toImpl(frame); - toQtWebPageLoadClient(clientInfo)->didReceiveServerRedirectForProvisionalLoad(wkframe->provisionalURL()); -} - -void QtWebPageLoadClient::didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->dispatchLoadFailed(toImpl(frame), error); -} - -void QtWebPageLoadClient::didCommitLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->didCommitLoad(); -} - -void QtWebPageLoadClient::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->dispatchLoadSucceeded(); -} - -void QtWebPageLoadClient::didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->dispatchLoadFailed(toImpl(frame), error); -} - -void QtWebPageLoadClient::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef frame, WKSameDocumentNavigationType type, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->didSameDocumentNavigation(); -} - -void QtWebPageLoadClient::didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - toQtWebPageLoadClient(clientInfo)->didReceiveTitle(); -} - -void QtWebPageLoadClient::didStartProgress(WKPageRef, const void* clientInfo) -{ - toQtWebPageLoadClient(clientInfo)->didChangeProgress(0); -} - -void QtWebPageLoadClient::didChangeProgress(WKPageRef page, const void* clientInfo) -{ - toQtWebPageLoadClient(clientInfo)->didChangeProgress(WKPageGetEstimatedProgress(page) * 100); -} - -void QtWebPageLoadClient::didFinishProgress(WKPageRef, const void* clientInfo) -{ - toQtWebPageLoadClient(clientInfo)->didChangeProgress(100); -} - -void QtWebPageLoadClient::didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef, WKArrayRef, const void *clientInfo) -{ - toQtWebPageLoadClient(clientInfo)->didChangeBackForwardList(); -} - -void QtWebPageLoadClient::processDidBecomeUnresponsive(WKPageRef, const void* clientInfo) -{ - toQtWebPageLoadClient(clientInfo)->processDidBecomeUnresponsive(); -} - -void QtWebPageLoadClient::processDidBecomeResponsive(WKPageRef, const void* clientInfo) -{ - toQtWebPageLoadClient(clientInfo)->processDidBecomeResponsive(); -} - -} // namespace Webkit diff --git a/Source/WebKit2/UIProcess/qt/QtWebPageLoadClient.h b/Source/WebKit2/UIProcess/qt/QtWebPageLoadClient.h deleted file mode 100644 index fd49543d4..000000000 --- a/Source/WebKit2/UIProcess/qt/QtWebPageLoadClient.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this program; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef QtWebPageLoadClient_h -#define QtWebPageLoadClient_h - -#include <QtGlobal> -#include <WebFrameProxy.h> -#include <WKPage.h> -#include <wtf/text/WTFString.h> - -QT_BEGIN_NAMESPACE -class QUrl; -QT_END_NAMESPACE - -class QQuickWebView; - -namespace WebKit { - -class QtWebError; - -class QtWebPageLoadClient { -public: - QtWebPageLoadClient(WKPageRef, QQuickWebView*); - -private: - void didStartProvisionalLoad(const WTF::String&); - void didReceiveServerRedirectForProvisionalLoad(const WTF::String&); - void didCommitLoad(); - void didSameDocumentNavigation(); - void didReceiveTitle(); - void didChangeProgress(int); - void didChangeBackForwardList(); - void processDidBecomeUnresponsive(); - void processDidBecomeResponsive(); - - void dispatchLoadSucceeded(); - void dispatchLoadStopped(); - void dispatchLoadFailed(WebFrameProxy*, const QtWebError&); - - - // WKPageLoadClient callbacks. - static void didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); - static void didCommitLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); - static void didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef, WKSameDocumentNavigationType, WKTypeRef userData, const void* clientInfo); - static void didReceiveTitleForFrame(WKPageRef, WKStringRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didStartProgress(WKPageRef, const void* clientInfo); - static void didChangeProgress(WKPageRef, const void* clientInfo); - static void didFinishProgress(WKPageRef, const void* clientInfo); - static void didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef, WKArrayRef, const void *clientInfo); - static void processDidBecomeUnresponsive(WKPageRef, const void* clientInfo); - static void processDidBecomeResponsive(WKPageRef, const void* clientInfo); - - QQuickWebView* m_webView; -}; - -} // namespace Webkit - -#endif // QtWebPageLoadClient_h diff --git a/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.cpp b/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.cpp index f536c4217..002d00507 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.cpp @@ -21,11 +21,11 @@ #include "config.h" #include "QtWebPageSGNode.h" -#include "LayerTreeRenderer.h" #include <QtGui/QPolygonF> #include <QtQuick/QQuickItem> #include <QtQuick/QQuickWindow> #include <QtQuick/QSGSimpleRectNode> +#include <WebCore/CoordinatedGraphicsScene.h> #include <WebCore/TransformationMatrix.h> #include <private/qsgrendernode_p.h> @@ -35,10 +35,10 @@ namespace WebKit { class ContentsSGNode : public QSGRenderNode { public: - ContentsSGNode(PassRefPtr<LayerTreeRenderer> renderer) - : m_renderer(renderer) + ContentsSGNode(PassRefPtr<CoordinatedGraphicsScene> scene) + : m_scene(scene) { - layerTreeRenderer()->setActive(true); + coordinatedGraphicsScene()->setActive(true); } virtual StateFlags changedStates() @@ -62,12 +62,12 @@ public: bool mirrored = projection && (*projection)(0, 0) * (*projection)(1, 1) - (*projection)(0, 1) * (*projection)(1, 0) > 0; // FIXME: Support non-rectangular clippings. - layerTreeRenderer()->paintToCurrentGLContext(renderMatrix, inheritedOpacity(), clipRect(), mirrored ? TextureMapper::PaintingMirrored : 0); + coordinatedGraphicsScene()->paintToCurrentGLContext(renderMatrix, inheritedOpacity(), clipRect(), mirrored ? TextureMapper::PaintingMirrored : 0); } ~ContentsSGNode() { - layerTreeRenderer()->purgeGLResources(); + coordinatedGraphicsScene()->purgeGLResources(); } const QtWebPageSGNode* pageNode() const @@ -77,7 +77,7 @@ public: return parent; } - LayerTreeRenderer* layerTreeRenderer() const { return m_renderer.get(); } + WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene() const { return m_scene.get(); } private: QRectF clipRect() const @@ -126,7 +126,7 @@ private: return resultRect; } - RefPtr<LayerTreeRenderer> m_renderer; + RefPtr<WebCore::CoordinatedGraphicsScene> m_scene; }; QtWebPageSGNode::QtWebPageSGNode() @@ -150,13 +150,13 @@ void QtWebPageSGNode::setScale(float scale) setMatrix(matrix); } -void QtWebPageSGNode::setRenderer(PassRefPtr<LayerTreeRenderer> renderer) +void QtWebPageSGNode::setCoordinatedGraphicsScene(PassRefPtr<WebCore::CoordinatedGraphicsScene> scene) { - if (m_contentsNode && m_contentsNode->layerTreeRenderer() == renderer) + if (m_contentsNode && m_contentsNode->coordinatedGraphicsScene() == scene) return; delete m_contentsNode; - m_contentsNode = new ContentsSGNode(renderer); + m_contentsNode = new ContentsSGNode(scene); // This sets the parent node of the content to QtWebPageSGNode. appendChildNode(m_contentsNode); } diff --git a/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.h b/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.h index 1bcc28e43..77ad81b6f 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.h +++ b/Source/WebKit2/UIProcess/qt/QtWebPageSGNode.h @@ -29,17 +29,20 @@ class QQuickItem; class QSGSimpleRectNode; QT_END_NAMESPACE +namespace WebCore { +class CoordinatedGraphicsScene; +} + namespace WebKit { class ContentsSGNode; -class LayerTreeRenderer; class QtWebPageSGNode : public QSGTransformNode { public: QtWebPageSGNode(); void setBackground(const QRectF&, const QColor&); void setScale(float); - void setRenderer(PassRefPtr<LayerTreeRenderer>); + void setCoordinatedGraphicsScene(PassRefPtr<WebCore::CoordinatedGraphicsScene>); qreal devicePixelRatio() const { return m_devicePixelRatio; } void setDevicePixelRatio(qreal devicePixelRatio) { m_devicePixelRatio = devicePixelRatio; } diff --git a/Source/WebKit2/UIProcess/qt/QtWebPageUIClient.cpp b/Source/WebKit2/UIProcess/qt/QtWebPageUIClient.cpp index 39e1e3d21..af88423c6 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebPageUIClient.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebPageUIClient.cpp @@ -26,7 +26,7 @@ #include "qquickwebview_p.h" #include "qquickwebview_p_p.h" #include "qwebpermissionrequest_p.h" -#include <WKAPICast.h> +#include <WKArray.h> #include <WKHitTestResult.h> #include <WKOpenPanelParameters.h> #include <WKOpenPanelResultListener.h> @@ -136,11 +136,13 @@ WKStringRef QtWebPageUIClient::runJavaScriptPrompt(WKPageRef, WKStringRef messag void QtWebPageUIClient::runOpenPanel(WKPageRef, WKFrameRef, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void* clientInfo) { - Vector<String> wkSelectedFileNames = toImpl(parameters)->selectedFileNames(); - + WKRetainPtr<WKArrayRef> wkSelectedFileNames = adoptWK(WKOpenPanelParametersCopySelectedFileNames(parameters)); QStringList selectedFileNames; - for (size_t i = 0; i < wkSelectedFileNames.size(); ++i) - selectedFileNames += wkSelectedFileNames.at(i); + size_t selectedFilesSize = WKArrayGetSize(wkSelectedFileNames.get()); + selectedFileNames.reserve(selectedFilesSize); + + for (size_t i = 0; i < selectedFilesSize; ++i) + selectedFileNames += WKStringCopyQString(static_cast<WKStringRef>(WKArrayGetItemAtIndex(wkSelectedFileNames.get(), i))); FileChooserType allowMultipleFiles = WKOpenPanelParametersGetAllowsMultipleFiles(parameters) ? MultipleFilesSelection : SingleFileSelection; toQtWebPageUIClient(clientInfo)->runOpenPanel(listener, selectedFileNames, allowMultipleFiles); diff --git a/Source/WebKit2/UIProcess/qt/TextCheckerQt.cpp b/Source/WebKit2/UIProcess/qt/TextCheckerQt.cpp index 4a3318405..7e343e179 100644 --- a/Source/WebKit2/UIProcess/qt/TextCheckerQt.cpp +++ b/Source/WebKit2/UIProcess/qt/TextCheckerQt.cpp @@ -126,4 +126,9 @@ void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) notImplemented(); } +void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion>) +{ + notImplemented(); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/WebColorChooserProxyQt.cpp b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.cpp index 6b747b77b..5fe35d771 100644 --- a/Source/WebKit2/UIProcess/qt/WebColorChooserProxyQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.cpp @@ -20,7 +20,7 @@ */ #include "config.h" -#include "WebColorChooserProxyQt.h" +#include "WebColorPickerQt.h" #include "qquickwebview_p.h" #include "qquickwebview_p_p.h" @@ -58,8 +58,8 @@ private: QRectF m_rect; }; -WebColorChooserProxyQt::WebColorChooserProxyQt(WebColorChooserProxy::Client* client, QQuickWebView* webView, const Color& initialColor, const IntRect& elementRect) - : WebColorChooserProxy(client) +WebColorPickerQt::WebColorPickerQt(WebColorPicker::Client* client, QQuickWebView* webView, const Color& initialColor, const IntRect& elementRect) + : WebColorPicker(client) , m_webView(webView) { const QRectF mappedRect= m_webView->mapRectFromWebContent(QRect(elementRect)); @@ -67,11 +67,11 @@ WebColorChooserProxyQt::WebColorChooserProxyQt(WebColorChooserProxy::Client* cli createItem(contextObject); } -WebColorChooserProxyQt::~WebColorChooserProxyQt() +WebColorPickerQt::~WebColorPickerQt() { } -void WebColorChooserProxyQt::createItem(QObject* contextObject) +void WebColorPickerQt::createItem(QObject* contextObject) { QQmlComponent* component = m_webView->experimental()->colorChooser(); if (!component) { @@ -102,7 +102,7 @@ void WebColorChooserProxyQt::createItem(QObject* contextObject) component->completeCreate(); } -void WebColorChooserProxyQt::createContext(QQmlComponent* component, QObject* contextObject) +void WebColorPickerQt::createContext(QQmlComponent* component, QObject* contextObject) { QQmlContext* baseContext = component->creationContext(); if (!baseContext) @@ -114,7 +114,7 @@ void WebColorChooserProxyQt::createContext(QQmlComponent* component, QObject* co m_context->setContextObject(contextObject); } -void WebColorChooserProxyQt::setSelectedColor(const Color&) +void WebColorPickerQt::setSelectedColor(const Color&) { // This is suppose to be used to react to DOM changes. When // a user script changes the input value, the method gives the @@ -123,7 +123,7 @@ void WebColorChooserProxyQt::setSelectedColor(const Color&) // And yes, the name sounds misleading but comes from WebCore. } -void WebColorChooserProxyQt::notifyColorSelected(const QColor& color) +void WebColorPickerQt::notifyColorSelected(const QColor& color) { if (!m_client) return; @@ -135,7 +135,7 @@ void WebColorChooserProxyQt::notifyColorSelected(const QColor& color) endChooser(); } -void WebColorChooserProxyQt::endChooser() +void WebColorPickerQt::endChooser() { m_colorChooser.clear(); m_context.clear(); @@ -148,5 +148,5 @@ void WebColorChooserProxyQt::endChooser() } // namespace WebKit -#include "WebColorChooserProxyQt.moc" -#include "moc_WebColorChooserProxyQt.cpp" +#include "WebColorPickerQt.moc" +#include "moc_WebColorPickerQt.cpp" diff --git a/Source/WebKit2/UIProcess/qt/WebColorChooserProxyQt.h b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.h index 77c37fc84..01c5bf97d 100644 --- a/Source/WebKit2/UIProcess/qt/WebColorChooserProxyQt.h +++ b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.h @@ -18,11 +18,11 @@ * */ -#ifndef WebColorChooserProxyQt_h -#define WebColorChooserProxyQt_h +#ifndef WebColorPickerQt_h +#define WebColorPickerQt_h #include "IntRect.h" -#include "WebColorChooserProxy.h" +#include "WebColorPicker.h" #include <QtCore/QObject> #include <wtf/OwnPtr.h> @@ -40,15 +40,15 @@ class Color; namespace WebKit { -class WebColorChooserProxyQt : public QObject, public WebColorChooserProxy { +class WebColorPickerQt : public QObject, public WebColorPicker { Q_OBJECT public: - static PassRefPtr<WebColorChooserProxy> create(WebColorChooserProxy::Client* client, QQuickWebView* webView, const WebCore::Color& initialColor, const WebCore::IntRect& elementRect) + static PassRefPtr<WebColorPicker> create(WebColorPicker::Client* client, QQuickWebView* webView, const WebCore::Color& initialColor, const WebCore::IntRect& elementRect) { - return adoptRef(new WebColorChooserProxyQt(client, webView, initialColor, elementRect)); + return adoptRef(new WebColorPickerQt(client, webView, initialColor, elementRect)); } - ~WebColorChooserProxyQt(); + ~WebColorPickerQt(); virtual void setSelectedColor(const WebCore::Color&); @@ -59,7 +59,7 @@ private Q_SLOTS: void notifyColorSelected(const QColor&); private: - WebColorChooserProxyQt(WebColorChooserProxy::Client*, QQuickWebView*, const WebCore::Color&, const WebCore::IntRect&); + WebColorPickerQt(WebColorPicker::Client*, QQuickWebView*, const WebCore::Color&, const WebCore::IntRect&); void createItem(QObject*); void createContext(QQmlComponent*, QObject*); @@ -72,4 +72,4 @@ private: } // namespace WebKit -#endif // WebColorChooserProxyQt_h +#endif // WebColorPickerQt_h diff --git a/Source/WebKit2/UIProcess/qt/WebContextQt.cpp b/Source/WebKit2/UIProcess/qt/WebContextQt.cpp index 726e62408..7661559fe 100644 --- a/Source/WebKit2/UIProcess/qt/WebContextQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebContextQt.cpp @@ -28,42 +28,23 @@ #include "WebContext.h" #include "ApplicationCacheStorage.h" -#include "FileSystem.h" -#include "QtDefaultDataLocation.h" -#include "QtWebContext.h" #include "WKSharedAPICast.h" +#include "WebProcessCreationParameters.h" +#include <QProcess> + #if ENABLE(GEOLOCATION) +#include "WebGeolocationManagerProxy.h" #include "WebGeolocationProviderQt.h" #endif -#include "WebProcessCreationParameters.h" -#include <QCoreApplication> -#include <QDir> -#include <QProcess> namespace WebKit { -static QString s_defaultDatabaseDirectory; -static QString s_defaultLocalStorageDirectory; -static QString s_defaultCookieStorageDirectory; - -String WebContext::platformDefaultDiskCacheDirectory() const -{ - static String s_defaultDiskCacheDirectory; - - if (!s_defaultDiskCacheDirectory.isEmpty()) - return s_defaultDiskCacheDirectory; - - s_defaultDiskCacheDirectory = WebCore::pathByAppendingComponent(defaultDataLocation(), "cache/"); - WebCore::makeAllDirectories(s_defaultDiskCacheDirectory); - return s_defaultDiskCacheDirectory; -} - -String WebContext::applicationCacheDirectory() +String WebContext::platformDefaultApplicationCacheDirectory() const { const String cacheDirectory = WebCore::cacheStorage().cacheDirectory(); if (cacheDirectory.isEmpty()) - return platformDefaultDiskCacheDirectory(); + return diskCacheDirectory(); return cacheDirectory; } @@ -71,51 +52,39 @@ String WebContext::applicationCacheDirectory() void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) { qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus"); -#if ENABLE(GEOLOCATION) - static WebGeolocationProviderQt* location = WebGeolocationProviderQt::create(toAPI(geolocationManagerProxy())); - WKGeolocationManagerSetProvider(toAPI(geolocationManagerProxy()), WebGeolocationProviderQt::provider(location)); +#if ENABLE(GEOLOCATION) && HAVE(QTLOCATION) + static WebGeolocationProviderQt* location = WebGeolocationProviderQt::create(toAPI(supplement<WebGeolocationManagerProxy>())); + WKGeolocationManagerSetProvider(toAPI(supplement<WebGeolocationManagerProxy>()), WebGeolocationProviderQt::provider(location)); #endif } void WebContext::platformInvalidateContext() { -#if HAVE(QTQUICK) - QtWebContext::invalidateContext(this); -#endif } String WebContext::platformDefaultDatabaseDirectory() const { - if (!s_defaultDatabaseDirectory.isEmpty()) - return s_defaultDatabaseDirectory; - - s_defaultDatabaseDirectory = defaultDataLocation() + QLatin1String("Databases"); - QDir().mkpath(s_defaultDatabaseDirectory); - return s_defaultDatabaseDirectory; + return String(); } String WebContext::platformDefaultIconDatabasePath() const { - return defaultDataLocation() + QLatin1String("WebpageIcons.db"); + return String(); } String WebContext::platformDefaultLocalStorageDirectory() const { - if (!s_defaultLocalStorageDirectory.isEmpty()) - return s_defaultLocalStorageDirectory; + return String(); +} - s_defaultLocalStorageDirectory = defaultDataLocation() + QLatin1String("LocalStorage"); - QDir().mkpath(s_defaultLocalStorageDirectory); - return s_defaultLocalStorageDirectory; +String WebContext::platformDefaultDiskCacheDirectory() const +{ + return String(); } String WebContext::platformDefaultCookieStorageDirectory() const { - if (!s_defaultCookieStorageDirectory.isEmpty()) - return s_defaultCookieStorageDirectory; - - s_defaultCookieStorageDirectory = defaultDataLocation(); - return s_defaultCookieStorageDirectory; + return String(); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/WebGeolocationProviderQt.cpp b/Source/WebKit2/UIProcess/qt/WebGeolocationProviderQt.cpp index 8b87f0a72..038992143 100644 --- a/Source/WebKit2/UIProcess/qt/WebGeolocationProviderQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebGeolocationProviderQt.cpp @@ -21,7 +21,7 @@ #include "config.h" #include "WebGeolocationProviderQt.h" -#if ENABLE(GEOLOCATION) +#if ENABLE(GEOLOCATION) && HAVE(QTLOCATION) #include <QtLocation/QGeoPositionInfoSource> namespace WebKit { diff --git a/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp b/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp index 95f041282..b9058478d 100644 --- a/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp @@ -49,6 +49,11 @@ void WebInspectorProxy::platformDidClose() notImplemented(); } +void WebInspectorProxy::platformHide() +{ + notImplemented(); +} + void WebInspectorProxy::platformBringToFront() { notImplemented(); @@ -71,6 +76,12 @@ unsigned WebInspectorProxy::platformInspectedWindowHeight() return 0; } +unsigned WebInspectorProxy::platformInspectedWindowWidth() +{ + notImplemented(); + return 0; +} + void WebInspectorProxy::platformAttach() { notImplemented(); @@ -91,6 +102,26 @@ void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned) notImplemented(); } +void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformSetToolbarHeight(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformSave(const String&, const String&, bool) +{ + notImplemented(); +} + +void WebInspectorProxy::platformAppend(const String&, const String&) +{ + notImplemented(); +} + String WebInspectorProxy::inspectorPageURL() const { notImplemented(); diff --git a/Source/WebKit2/UIProcess/qt/WebPageProxyQt.cpp b/Source/WebKit2/UIProcess/qt/WebPageProxyQt.cpp index 8a205f91d..a89782506 100644 --- a/Source/WebKit2/UIProcess/qt/WebPageProxyQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebPageProxyQt.cpp @@ -60,31 +60,6 @@ void WebPageProxy::loadRecentSearches(const String&, Vector<String>&) notImplemented(); } -void WebPageProxy::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) -{ - // FIXME: We need to find out how to proper handle the crashes case. - if (!isValid()) - return; - - process()->send(Messages::WebPage::SetComposition(text, underlines, selectionStart, selectionEnd, replacementRangeStart, replacementRangeEnd), m_pageID); -} - -void WebPageProxy::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::ConfirmComposition(compositionString, selectionStart, selectionLength), m_pageID); -} - -void WebPageProxy::cancelComposition() -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::CancelComposition(), m_pageID); -} - void WebPageProxy::registerApplicationScheme(const String& scheme) { process()->send(Messages::WebPage::RegisterApplicationScheme(scheme), m_pageID); @@ -111,29 +86,6 @@ void WebPageProxy::sendApplicationSchemeReply(const QQuickNetworkReply* reply) #endif } -void WebPageProxy::setUserScripts(const Vector<String>& scripts) -{ - process()->send(Messages::WebPage::SetUserScripts(scripts), m_pageID); -} - -void WebPageProxy::didFindZoomableArea(const IntPoint& target, const IntRect& area) -{ - m_pageClient->didFindZoomableArea(target, area); -} - -void WebPageProxy::findZoomableAreaForPoint(const IntPoint& point, const IntSize& area) -{ - if (!isValid()) - return; - - m_process->send(Messages::WebPage::FindZoomableAreaForPoint(point, area), m_pageID); -} - -void WebPageProxy::didReceiveMessageFromNavigatorQtObject(const String& contents) -{ - m_pageClient->didReceiveMessageFromNavigatorQtObject(contents); -} - void WebPageProxy::authenticationRequiredRequest(const String& hostname, const String& realm, const String& prefilledUsername, String& username, String& password) { m_pageClient->handleAuthenticationRequiredRequest(hostname, realm, prefilledUsername, username, password); diff --git a/Source/WebKit2/UIProcess/qt/WebProcessProxyQt.cpp b/Source/WebKit2/UIProcess/qt/WebProcessProxyQt.cpp index 3ad528f27..e8b173d07 100644 --- a/Source/WebKit2/UIProcess/qt/WebProcessProxyQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebProcessProxyQt.cpp @@ -28,7 +28,7 @@ namespace WebKit { -void WebProcessProxy::platformConnect(ProcessLauncher::LaunchOptions&) +void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions&) { } diff --git a/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp b/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp index 08914ed81..f964e4981 100644 --- a/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp +++ b/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp @@ -33,7 +33,16 @@ namespace WebKit { void WebCookieManagerProxy::setCookiePersistentStorage(const String& storagePath, uint32_t storageType) { - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::SetCookiePersistentStorage(storagePath, storageType)); + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::SetCookiePersistentStorage(storagePath, storageType)); + + m_cookiePersistentStoragePath = storagePath; + m_cookiePersistentStorageType = static_cast<SoupCookiePersistentStorageType>(storageType); +} + +void WebCookieManagerProxy::getCookiePersistentStorage(String& storagePath, uint32_t& storageType) const +{ + storagePath = m_cookiePersistentStoragePath; + storageType = static_cast<uint32_t>(m_cookiePersistentStorageType); } } diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h index e247fecd7..60b34937f 100644 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h +++ b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h @@ -21,6 +21,7 @@ #define WebSoupRequestManagerClient_h #include "APIClient.h" +#include "WKAPICast.h" #include "WKSoupRequestManager.h" namespace WebKit { diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp index 33698cd7c..c5e6c6096 100644 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2013 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -27,55 +28,80 @@ namespace WebKit { +const char* WebSoupRequestManagerProxy::supplementName() +{ + return "WebSoupRequestManagerProxy"; +} + PassRefPtr<WebSoupRequestManagerProxy> WebSoupRequestManagerProxy::create(WebContext* context) { return adoptRef(new WebSoupRequestManagerProxy(context)); } WebSoupRequestManagerProxy::WebSoupRequestManagerProxy(WebContext* context) - : m_webContext(context) + : WebContextSupplement(context) , m_loadFailed(false) { - m_webContext->addMessageReceiver(Messages::WebSoupRequestManagerProxy::messageReceiverName(), this); + WebContextSupplement::context()->addMessageReceiver(Messages::WebSoupRequestManagerProxy::messageReceiverName(), this); } WebSoupRequestManagerProxy::~WebSoupRequestManagerProxy() { } -void WebSoupRequestManagerProxy::invalidate() +void WebSoupRequestManagerProxy::initializeClient(const WKSoupRequestManagerClient* client) { + m_client.initialize(client); } -void WebSoupRequestManagerProxy::initializeClient(const WKSoupRequestManagerClient* client) +// WebContextSupplement + +void WebSoupRequestManagerProxy::contextDestroyed() { - m_client.initialize(client); } -void WebSoupRequestManagerProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::MessageDecoder& decoder) +void WebSoupRequestManagerProxy::processDidClose(WebProcessProxy*) +{ +} + +void WebSoupRequestManagerProxy::refWebContextSupplement() +{ + APIObject::ref(); +} + +void WebSoupRequestManagerProxy::derefWebContextSupplement() { - didReceiveWebSoupRequestManagerProxyMessage(connection, messageID, decoder); + APIObject::deref(); } void WebSoupRequestManagerProxy::registerURIScheme(const String& scheme) { - ASSERT(m_webContext); - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebSoupRequestManager::RegisterURIScheme(scheme)); + if (!context()) + return; + + context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebSoupRequestManager::RegisterURIScheme(scheme)); + + ASSERT(!m_registeredURISchemes.contains(scheme)); + m_registeredURISchemes.append(scheme); } void WebSoupRequestManagerProxy::didHandleURIRequest(const WebData* requestData, uint64_t contentLength, const String& mimeType, uint64_t requestID) { - ASSERT(m_webContext); - m_webContext->sendToAllProcesses(Messages::WebSoupRequestManager::DidHandleURIRequest(requestData->dataReference(), contentLength, mimeType, requestID)); + if (!context()) + return; + + context()->sendToAllProcesses(Messages::WebSoupRequestManager::DidHandleURIRequest(requestData->dataReference(), contentLength, mimeType, requestID)); } void WebSoupRequestManagerProxy::didReceiveURIRequestData(const WebData* requestData, uint64_t requestID) { + if (!context()) + return; + if (m_loadFailed) return; - ASSERT(m_webContext); - m_webContext->sendToAllProcesses(Messages::WebSoupRequestManager::DidReceiveURIRequestData(requestData->dataReference(), requestID)); + context()->sendToAllProcesses(Messages::WebSoupRequestManager::DidReceiveURIRequestData(requestData->dataReference(), requestID)); } void WebSoupRequestManagerProxy::didReceiveURIRequest(const String& uriString, WebPageProxy* initiaingPage, uint64_t requestID) @@ -90,4 +116,13 @@ void WebSoupRequestManagerProxy::didFailToLoadURIRequest(uint64_t requestID) m_client.didFailToLoadURIRequest(this, requestID); } +void WebSoupRequestManagerProxy::didFailURIRequest(const WebCore::ResourceError& error, uint64_t requestID) +{ + if (!context()) + return; + + m_loadFailed = true; + context()->sendToAllProcesses(Messages::WebSoupRequestManager::DidFailURIRequest(error, requestID)); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h index e4b8cce37..f78b967ed 100644 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h +++ b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2013 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -22,6 +23,7 @@ #include "APIObject.h" #include "MessageReceiver.h" +#include "WebContextSupplement.h" #include "WebSoupRequestManagerClient.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> @@ -32,37 +34,43 @@ namespace WebKit { class WebContext; class WebData; -class WebSoupRequestManagerProxy : public APIObject, private CoreIPC::MessageReceiver { +class WebSoupRequestManagerProxy : public TypedAPIObject<APIObject::TypeSoupRequestManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { public: - static const Type APIType = TypeSoupRequestManager; + static const char* supplementName(); static PassRefPtr<WebSoupRequestManagerProxy> create(WebContext*); virtual ~WebSoupRequestManagerProxy(); - void invalidate(); - void clearContext() { m_webContext = 0; } - void initializeClient(const WKSoupRequestManagerClient*); void registerURIScheme(const String& scheme); void didHandleURIRequest(const WebData*, uint64_t contentLength, const String& mimeType, uint64_t requestID); void didReceiveURIRequestData(const WebData*, uint64_t requestID); - void didFailToLoadURIRequest(uint64_t requestID); - void didReceiveURIRequest(const String& uriString, WebPageProxy*, uint64_t requestID); + void didFailURIRequest(const WebCore::ResourceError&, uint64_t requestID); + + const Vector<String>& registeredURISchemes() const { return m_registeredURISchemes; } + + using APIObject::ref; + using APIObject::deref; private: WebSoupRequestManagerProxy(WebContext*); - virtual Type type() const { return APIType; } + // WebContextSupplement + virtual void contextDestroyed() OVERRIDE; + virtual void processDidClose(WebProcessProxy*) OVERRIDE; + virtual void refWebContextSupplement() OVERRIDE; + virtual void derefWebContextSupplement() OVERRIDE; // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&) OVERRIDE; - void didReceiveWebSoupRequestManagerProxyMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&); + virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + + void didFailToLoadURIRequest(uint64_t requestID); - WebContext* m_webContext; WebSoupRequestManagerClient m_client; bool m_loadFailed; + Vector<String> m_registeredURISchemes; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/BackingStoreWin.cpp b/Source/WebKit2/UIProcess/win/BackingStoreWin.cpp deleted file mode 100644 index 60bba75bf..000000000 --- a/Source/WebKit2/UIProcess/win/BackingStoreWin.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "BackingStore.h" - -#include "ShareableBitmap.h" -#include "UpdateInfo.h" -#include <WebCore/BitmapInfo.h> -#include <WebCore/GraphicsContext.h> -#include <WebCore/IntRect.h> - -using namespace WebCore; - -namespace WebKit { - -class BitmapDC { - WTF_MAKE_NONCOPYABLE(BitmapDC); - -public: - BitmapDC(HBITMAP, HDC destinationDC); - ~BitmapDC(); - - operator HDC() const { return m_dc.get(); } - -private: - OwnPtr<HDC> m_dc; - HBITMAP m_originalBitmap; -}; - -BitmapDC::BitmapDC(HBITMAP bitmap, HDC destinationDC) - : m_dc(adoptPtr(::CreateCompatibleDC(destinationDC))) - , m_originalBitmap(static_cast<HBITMAP>(::SelectObject(m_dc.get(), bitmap))) -{ -} - -BitmapDC::~BitmapDC() -{ - ::SelectObject(m_dc.get(), m_originalBitmap); -} - -void BackingStore::paint(HDC dc, const IntRect& rect) -{ - ASSERT(m_bitmap); - ::BitBlt(dc, rect.x(), rect.y(), rect.width(), rect.height(), BitmapDC(m_bitmap.get(), dc), rect.x(), rect.y(), SRCCOPY); -} - -static PassOwnPtr<HBITMAP> createBitmap(const IntSize& size) -{ - // FIXME: Maybe it would be better for performance to create a device-dependent bitmap here? - BitmapInfo info = BitmapInfo::createBottomUp(size); - void* bits; - return adoptPtr(::CreateDIBSection(0, &info, DIB_RGB_COLORS, &bits, 0, 0)); -} - -void BackingStore::incorporateUpdate(ShareableBitmap* bitmap, const UpdateInfo& updateInfo) -{ - if (!m_bitmap) - m_bitmap = createBitmap(m_size); - - scroll(updateInfo.scrollRect, updateInfo.scrollOffset); - - IntPoint updateRectLocation = updateInfo.updateRectBounds.location(); - - BitmapDC backingStoreDC(m_bitmap.get(), 0); - HDC bitmapDC = bitmap->windowsContext(); - - // Paint all update rects. - for (size_t i = 0; i < updateInfo.updateRects.size(); ++i) { - IntRect updateRect = updateInfo.updateRects[i]; - IntRect srcRect = updateRect; - srcRect.move(-updateRectLocation.x(), -updateRectLocation.y()); - - ::BitBlt(backingStoreDC, updateRect.location().x(), updateRect.location().y(), updateRect.size().width(), updateRect.size().height(), - bitmapDC, srcRect.x(), srcRect.y(), SRCCOPY); - } -} - -void BackingStore::scroll(const IntRect& scrollRect, const IntSize& scrollOffset) -{ - if (scrollOffset.isZero()) - return; - - RECT winScrollRect = scrollRect; - ::ScrollDC(BitmapDC(m_bitmap.get(), 0), scrollOffset.width(), scrollOffset.height(), &winScrollRect, &winScrollRect, 0, 0); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/TextCheckerWin.cpp b/Source/WebKit2/UIProcess/win/TextCheckerWin.cpp deleted file mode 100644 index 9f7c766f4..000000000 --- a/Source/WebKit2/UIProcess/win/TextCheckerWin.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "TextChecker.h" - -#include "TextCheckerState.h" -#include "WebTextChecker.h" -#include <WebCore/NotImplemented.h> - -using namespace WebCore; - -namespace WebKit { - -static TextCheckerState textCheckerState; - -const TextCheckerState& TextChecker::state() -{ - static bool didInitializeState; - if (didInitializeState) - return textCheckerState; - - WebTextCheckerClient& client = WebTextChecker::shared()->client(); - textCheckerState.isContinuousSpellCheckingEnabled = client.continuousSpellCheckingEnabled(); - textCheckerState.isGrammarCheckingEnabled = client.grammarCheckingEnabled(); - - didInitializeState = true; - - return textCheckerState; -} - -bool TextChecker::isContinuousSpellCheckingAllowed() -{ - return WebTextChecker::shared()->client().continuousSpellCheckingAllowed(); -} - -void TextChecker::setContinuousSpellCheckingEnabled(bool isContinuousSpellCheckingEnabled) -{ - if (state().isContinuousSpellCheckingEnabled == isContinuousSpellCheckingEnabled) - return; - textCheckerState.isContinuousSpellCheckingEnabled = isContinuousSpellCheckingEnabled; - WebTextChecker::shared()->client().setContinuousSpellCheckingEnabled(isContinuousSpellCheckingEnabled); -} - -void TextChecker::setGrammarCheckingEnabled(bool isGrammarCheckingEnabled) -{ - if (state().isGrammarCheckingEnabled == isGrammarCheckingEnabled) - return; - textCheckerState.isGrammarCheckingEnabled = isGrammarCheckingEnabled; - WebTextChecker::shared()->client().setGrammarCheckingEnabled(isGrammarCheckingEnabled); -} - -void TextChecker::continuousSpellCheckingEnabledStateChanged(bool enabled) -{ - textCheckerState.isContinuousSpellCheckingEnabled = enabled; -} - -void TextChecker::grammarCheckingEnabledStateChanged(bool enabled) -{ - textCheckerState.isGrammarCheckingEnabled = enabled; -} - -int64_t TextChecker::uniqueSpellDocumentTag(WebPageProxy* page) -{ - return WebTextChecker::shared()->client().uniqueSpellDocumentTag(page); -} - -void TextChecker::closeSpellDocumentWithTag(int64_t tag) -{ - WebTextChecker::shared()->client().closeSpellDocumentWithTag(tag); -} - -void TextChecker::checkSpellingOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, int32_t& misspellingLocation, int32_t& misspellingLength) -{ - WebTextChecker::shared()->client().checkSpellingOfString(spellDocumentTag, String(text, length), misspellingLocation, misspellingLength); -} - -void TextChecker::checkGrammarOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, Vector<WebCore::GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength) -{ - WebTextChecker::shared()->client().checkGrammarOfString(spellDocumentTag, String(text, length), grammarDetails, badGrammarLocation, badGrammarLength); -} - -bool TextChecker::spellingUIIsShowing() -{ - return WebTextChecker::shared()->client().spellingUIIsShowing(); -} - -void TextChecker::toggleSpellingUIIsShowing() -{ - WebTextChecker::shared()->client().toggleSpellingUIIsShowing(); -} - -void TextChecker::updateSpellingUIWithMisspelledWord(int64_t spellDocumentTag, const String& misspelledWord) -{ - WebTextChecker::shared()->client().updateSpellingUIWithMisspelledWord(spellDocumentTag, misspelledWord); -} - -void TextChecker::updateSpellingUIWithGrammarString(int64_t spellDocumentTag, const String& badGrammarPhrase, const GrammarDetail& grammarDetail) -{ - WebTextChecker::shared()->client().updateSpellingUIWithGrammarString(spellDocumentTag, badGrammarPhrase, grammarDetail); -} - -void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& context, Vector<String>& guesses) -{ - WebTextChecker::shared()->client().guessesForWord(spellDocumentTag, word, guesses); -} - -void TextChecker::learnWord(int64_t spellDocumentTag, const String& word) -{ - WebTextChecker::shared()->client().learnWord(spellDocumentTag, word); -} - -void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) -{ - WebTextChecker::shared()->client().ignoreWord(spellDocumentTag, word); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/WebContextMenuProxyWin.cpp b/Source/WebKit2/UIProcess/win/WebContextMenuProxyWin.cpp deleted file mode 100644 index 4b5a5a70d..000000000 --- a/Source/WebKit2/UIProcess/win/WebContextMenuProxyWin.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebContextMenuProxyWin.h" - -#include <WebCore/NotImplemented.h> - -using namespace WebCore; - -namespace WebKit { - -WebContextMenuProxyWin::WebContextMenuProxyWin(HWND parentWindow, WebPageProxy* page) - : m_window(parentWindow) - , m_page(page) - , m_menu(0) -{ -} - -void WebContextMenuProxyWin::populateMenu(HMENU menu, const Vector<WebContextMenuItemData>& items) -{ - for (size_t i = 0; i < items.size(); ++i) { - const WebContextMenuItemData& itemData = items[i]; - switch (itemData.type()) { - case ActionType: - case CheckableActionType: { - UINT flags = itemData.enabled() ? MF_ENABLED : MF_DISABLED; - if (itemData.checked()) - flags |= MF_CHECKED; - String title = itemData.title(); - ::AppendMenu(menu, flags, itemData.action(), title.charactersWithNullTermination()); - - m_actionMap.add(itemData.action(), itemData); - break; - } - case SeparatorType: - ::AppendMenu(menu, MF_SEPARATOR, 0, 0); - break; - case SubmenuType: { - HMENU subMenu = ::CreatePopupMenu(); - populateMenu(subMenu, itemData.submenu()); - String title = itemData.title(); - ::AppendMenu(menu, MF_POPUP, reinterpret_cast<UINT>(subMenu), title.charactersWithNullTermination()); - break; - } - default: - ASSERT_NOT_REACHED(); - } - } -} - -void WebContextMenuProxyWin::showContextMenu(const IntPoint& origin, const Vector<WebContextMenuItemData>& items) -{ - if (items.isEmpty()) - return; - - // Hide any context menu we have showing (this also destroys the menu). - hideContextMenu(); - - m_menu = ::CreatePopupMenu(); - populateMenu(m_menu, items); - - POINT point = POINT(origin); - if (!::ClientToScreen(m_window, &point)) - return; - - UINT flags = TPM_RIGHTBUTTON | TPM_TOPALIGN | TPM_VERPOSANIMATION | TPM_HORIZONTAL | TPM_LEFTALIGN | TPM_HORPOSANIMATION | TPM_RETURNCMD | TPM_NONOTIFY; - int selectedCommand = ::TrackPopupMenuEx(m_menu, flags, point.x, point.y, m_window, 0); - if (!selectedCommand) - return; - - m_page->contextMenuItemSelected(m_actionMap.get(selectedCommand)); -} - -void WebContextMenuProxyWin::hideContextMenu() -{ - if (m_menu) { - ::DestroyMenu(m_menu); - m_menu = 0; - } - - m_actionMap.clear(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/WebContextWin.cpp b/Source/WebKit2/UIProcess/win/WebContextWin.cpp deleted file mode 100644 index 0d2e9542e..000000000 --- a/Source/WebKit2/UIProcess/win/WebContextWin.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebContext.h" - -#include "WebProcessCreationParameters.h" -#include "WebProcessMessages.h" -#include <WebCore/FileSystem.h> -#include <WebCore/NotImplemented.h> - -#if USE(CFNETWORK) -#include <CFNetwork/CFURLCachePriv.h> -#include <WebKitSystemInterface/WebKitSystemInterface.h> -#endif - -using namespace WebCore; - -namespace WebKit { - -String WebContext::applicationCacheDirectory() -{ - return localUserSpecificStorageDirectory(); -} - -void WebContext::setShouldPaintNativeControls(bool b) -{ - m_shouldPaintNativeControls = b; - - sendToAllProcesses(Messages::WebProcess::SetShouldPaintNativeControls(m_shouldPaintNativeControls)); -} - -void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) -{ - parameters.shouldPaintNativeControls = m_shouldPaintNativeControls; - -#if USE(CFNETWORK) - RetainPtr<CFURLCacheRef> cfurlCache(AdoptCF, CFURLCacheCopySharedURLCache()); - parameters.cfURLCacheDiskCapacity = CFURLCacheDiskCapacity(cfurlCache.get()); - parameters.cfURLCacheMemoryCapacity = CFURLCacheMemoryCapacity(cfurlCache.get()); - - RetainPtr<CFStringRef> cfURLCachePath(AdoptCF, wkCopyFoundationCacheDirectory(0)); - parameters.diskCacheDirectory = String(cfURLCachePath.get()); - // Remove the ending '\' (necessary to have CFNetwork find the Cache file). - ASSERT(parameters.diskCacheDirectory.length()); - if (parameters.diskCacheDirectory.endsWith(UChar('\\'))) - parameters.diskCacheDirectory.remove(parameters.diskCacheDirectory.length() - 1); - - parameters.uiProcessBundleIdentifier = String(reinterpret_cast<CFStringRef>(CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleIdentifierKey))); - parameters.serializedDefaultStorageSession.adoptCF(wkCopySerializedDefaultStorageSession()); - - parameters.initialHTTPCookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy; - -#endif // USE(CFNETWORK) -} - -void WebContext::platformInvalidateContext() -{ -} - -String WebContext::platformDefaultDatabaseDirectory() const -{ - return WebCore::pathByAppendingComponent(WebCore::localUserSpecificStorageDirectory(), "Databases"); -} - -String WebContext::platformDefaultIconDatabasePath() const -{ - // IconDatabase should be disabled by default on Windows, and should therefore have no default path. - return String(); -} - -String WebContext::platformDefaultLocalStorageDirectory() const -{ - return WebCore::pathByAppendingComponent(WebCore::localUserSpecificStorageDirectory(), "LocalStorage"); -} - -String WebContext::platformDefaultDiskCacheDirectory() const -{ - return WebCore::pathByAppendingComponent(WebCore::localUserSpecificStorageDirectory(), "cache"); -} - -String WebContext::platformDefaultCookieStorageDirectory() const -{ - notImplemented(); - return String(); -} - -} // namespace WebKit - diff --git a/Source/WebKit2/UIProcess/win/WebInspectorProxyWin.cpp b/Source/WebKit2/UIProcess/win/WebInspectorProxyWin.cpp deleted file mode 100644 index ee67feb6c..000000000 --- a/Source/WebKit2/UIProcess/win/WebInspectorProxyWin.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebInspectorProxy.h" - -#if ENABLE(INSPECTOR) - -#include "WebKitBundle.h" -#include "WebPageProxy.h" -#include "WebProcessProxy.h" -#include "WebView.h" -#include <WebCore/InspectorFrontendClientLocal.h> -#include <WebCore/NotImplemented.h> -#include <WebCore/WebCoreInstanceHandle.h> -#include <WebCore/WindowMessageBroadcaster.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RetainPtr.h> -#include <wtf/text/StringConcatenate.h> -#include <wtf/text/WTFString.h> - -using namespace WebCore; - -namespace WebKit { - -static const LPCWSTR kWebKit2InspectorWindowClassName = L"WebKit2InspectorWindowClass"; - -bool WebInspectorProxy::registerInspectorViewWindowClass() -{ - static bool haveRegisteredWindowClass = false; - if (haveRegisteredWindowClass) - return true; - haveRegisteredWindowClass = true; - - WNDCLASSEX wcex; - - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = WebInspectorProxy::InspectorViewWndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = sizeof(WebInspectorProxy*); - wcex.hInstance = instanceHandle(); - wcex.hIcon = 0; - wcex.hCursor = ::LoadCursor(0, IDC_ARROW); - wcex.hbrBackground = 0; - wcex.lpszMenuName = 0; - wcex.lpszClassName = kWebKit2InspectorWindowClassName; - wcex.hIconSm = 0; - - return !!::RegisterClassEx(&wcex); -} - -LRESULT CALLBACK WebInspectorProxy::InspectorViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - LONG_PTR longPtr = ::GetWindowLongPtr(hWnd, 0); - - if (WebInspectorProxy* inspectorView = reinterpret_cast<WebInspectorProxy*>(longPtr)) - return inspectorView->wndProc(hWnd, message, wParam, lParam); - - if (message == WM_CREATE) { - LPCREATESTRUCT createStruct = reinterpret_cast<LPCREATESTRUCT>(lParam); - - // Associate the WebInspectorProxy with the window. - ::SetWindowLongPtr(hWnd, 0, (LONG_PTR)createStruct->lpCreateParams); - return 0; - } - - return ::DefWindowProc(hWnd, message, wParam, lParam); -} - -void WebInspectorProxy::windowReceivedMessage(HWND, UINT msg, WPARAM wParam, LPARAM lParam) -{ - ASSERT(m_isAttached); - - switch (msg) { - case WM_WINDOWPOSCHANGING: - onWebViewWindowPosChangingEvent(wParam, lParam); - break; - default: - break; - } -} - -LRESULT WebInspectorProxy::wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - LRESULT lResult = 0; - bool handled = true; - - switch (message) { - case WM_SIZE: - lResult = onSizeEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_GETMINMAXINFO: - lResult = onMinMaxInfoEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_SETFOCUS: - lResult = onSetFocusEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_CLOSE: - lResult = onCloseEvent(hWnd, message, wParam, lParam, handled); - break; - default: - handled = false; - break; - } - - if (!handled) - lResult = ::DefWindowProc(hWnd, message, wParam, lParam); - - return lResult; -} - -LRESULT WebInspectorProxy::onSizeEvent(HWND, UINT, WPARAM, LPARAM, bool&) -{ - RECT rect; - ::GetClientRect(m_inspectorWindow, &rect); - - ::SetWindowPos(m_inspectorView->window(), 0, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER); - - return 0; -} - -LRESULT WebInspectorProxy::onSetFocusEvent(HWND, UINT, WPARAM, LPARAM lParam, bool&) -{ - ::SetFocus(m_inspectorView->window()); - - return 0; -} - -LRESULT WebInspectorProxy::onMinMaxInfoEvent(HWND, UINT, WPARAM, LPARAM lParam, bool&) -{ - MINMAXINFO* info = reinterpret_cast<MINMAXINFO*>(lParam); - POINT size = {minimumWindowWidth, minimumWindowHeight}; - info->ptMinTrackSize = size; - - return 0; -} - -LRESULT WebInspectorProxy::onCloseEvent(HWND, UINT, WPARAM, LPARAM, bool&) -{ - ::ShowWindow(m_inspectorWindow, SW_HIDE); - close(); - - return 0; -} - -void WebInspectorProxy::onWebViewWindowPosChangingEvent(WPARAM wParam, LPARAM lParam) -{ - WINDOWPOS* windowPos = reinterpret_cast<WINDOWPOS*>(lParam); - - if (windowPos->flags & SWP_NOSIZE) - return; - - HWND inspectorWindow = m_inspectorView->window(); - - RECT inspectorRect; - ::GetClientRect(inspectorWindow, &inspectorRect); - unsigned inspectorHeight = inspectorRect.bottom - inspectorRect.top; - - RECT parentRect; - ::GetClientRect(::GetParent(inspectorWindow), &parentRect); - inspectorHeight = InspectorFrontendClientLocal::constrainedAttachedWindowHeight(inspectorHeight, parentRect.bottom - parentRect.top); - - windowPos->cy -= inspectorHeight; - - ::SetWindowPos(inspectorWindow, 0, windowPos->x, windowPos->y + windowPos->cy, windowPos->cx, inspectorHeight, SWP_NOZORDER); -} - -WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() -{ - ASSERT(!m_inspectorView); - ASSERT(!m_inspectorWindow); - - RECT initialRect = { 0, 0, initialWindowWidth, initialWindowHeight }; - m_inspectorView = WebView::create(initialRect, m_page->process()->context(), inspectorPageGroup(), 0); - - return m_inspectorView->page(); -} - -void WebInspectorProxy::platformOpen() -{ - registerInspectorViewWindowClass(); - - m_inspectorWindow = ::CreateWindowEx(0, kWebKit2InspectorWindowClassName, 0, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, initialWindowWidth, initialWindowHeight, 0, 0, instanceHandle(), this); - ASSERT(::IsWindow(m_inspectorWindow)); - - m_inspectorView->setParentWindow(m_inspectorWindow); - - if (m_isAttached) - platformAttach(); - else - ::ShowWindow(m_inspectorWindow, SW_SHOW); -} - -void WebInspectorProxy::platformDidClose() -{ - ASSERT(!m_isAttached); - ASSERT(!m_isVisible || m_inspectorWindow); - ASSERT(!m_isVisible || m_inspectorView); - - if (m_inspectorWindow) { - ASSERT(::IsWindow(m_inspectorWindow)); - ::DestroyWindow(m_inspectorWindow); - } - - m_inspectorWindow = 0; - m_inspectorView = 0; -} - -void WebInspectorProxy::platformBringToFront() -{ - // FIXME: this will not bring a background tab in Safari to the front, only its window. - HWND parentWindow = m_isAttached ? ::GetAncestor(m_page->nativeWindow(), GA_ROOT) : m_inspectorWindow; - if (!parentWindow) - return; - - ASSERT(::IsWindow(parentWindow)); - ::SetWindowPos(parentWindow, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE); -} - -bool WebInspectorProxy::platformIsFront() -{ - notImplemented(); - return false; -} - -void WebInspectorProxy::platformAttachAvailabilityChanged(bool) -{ - notImplemented(); -} - -void WebInspectorProxy::platformInspectedURLChanged(const String& urlString) -{ - // FIXME: this should be made localizable once WebKit2 supports it. <rdar://problem/8728860> - String title = makeString("Web Inspector ", static_cast<UChar>(0x2014), ' ', urlString); - ::SetWindowTextW(m_inspectorWindow, title.charactersWithNullTermination()); -} - -unsigned WebInspectorProxy::platformInspectedWindowHeight() -{ - HWND inspectedWindow = m_page->nativeWindow(); - - RECT inspectedWindowRect; - ::GetWindowRect(inspectedWindow, &inspectedWindowRect); - - return static_cast<unsigned>(inspectedWindowRect.bottom - inspectedWindowRect.top); -} - -void WebInspectorProxy::platformAttach() -{ - HWND webViewWindow = m_page->nativeWindow(); - HWND parentWindow = ::GetParent(webViewWindow); - - WindowMessageBroadcaster::addListener(webViewWindow, this); - m_inspectorView->setParentWindow(parentWindow); - ::ShowWindow(m_inspectorWindow, SW_HIDE); - - ::PostMessage(parentWindow, WM_SIZE, 0, 0); -} - -void WebInspectorProxy::platformDetach() -{ - HWND webViewWindow = m_page->nativeWindow(); - WindowMessageBroadcaster::removeListener(webViewWindow, this); - - m_inspectorView->setParentWindow(m_inspectorWindow); - - if (m_isVisible) - ::ShowWindow(m_inspectorWindow, SW_SHOW); - - // Send the detached inspector window and the WebView's parent window WM_SIZE messages - // to have them re-layout correctly. - ::PostMessage(m_inspectorWindow, WM_SIZE, 0, 0); - ::PostMessage(::GetParent(webViewWindow), WM_SIZE, 0, 0); -} - -void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned height) -{ - if (!m_isAttached) - return; - - HWND inspectedWindow = m_page->nativeWindow(); - HWND parentWindow = ::GetParent(inspectedWindow); - - RECT parentWindowRect; - ::GetWindowRect(parentWindow, &parentWindowRect); - - RECT inspectedWindowRect; - ::GetWindowRect(inspectedWindow, &inspectedWindowRect); - - int totalHeight = parentWindowRect.bottom - parentWindowRect.top; - int webViewWidth = inspectedWindowRect.right - inspectedWindowRect.left; - - POINT inspectedWindowOrigin = { inspectedWindowRect.left, inspectedWindowRect.top }; - ::ScreenToClient(parentWindow, &inspectedWindowOrigin); - - HWND inspectorWindow = m_inspectorView->window(); - ::SetWindowPos(inspectorWindow, 0, inspectedWindowOrigin.x, totalHeight - height, webViewWidth, height, SWP_NOZORDER); - - // We want to set the inspected web view height to the totalHeight, because the height adjustment - // of the inspected WebView happens in onWindowPosChanging, not here. - ::SetWindowPos(inspectedWindow, 0, inspectedWindowOrigin.x, inspectedWindowOrigin.y, webViewWidth, totalHeight, SWP_NOZORDER); - - ::RedrawWindow(inspectorWindow, 0, 0, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW); - ::RedrawWindow(inspectedWindow, 0, 0, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW); -} - -String WebInspectorProxy::inspectorPageURL() const -{ - RetainPtr<CFURLRef> htmlURLRef(AdoptCF, CFBundleCopyResourceURL(webKitBundle(), CFSTR("inspector"), CFSTR("html"), CFSTR("inspector"))); - if (!htmlURLRef) - return String(); - - return String(CFURLGetString(htmlURLRef.get())); -} - -String WebInspectorProxy::inspectorBaseURL() const -{ - // Web Inspector uses localized strings, so it's not contained within inspector directory. - RetainPtr<CFURLRef> htmlURLRef(AdoptCF, CFBundleCopyResourcesDirectoryURL(webKitBundle())); - if (!htmlURLRef) - return String(); - - return String(CFURLGetString(htmlURLRef.get())); -} - -} // namespace WebKit - -#endif // ENABLE(INSPECTOR) diff --git a/Source/WebKit2/UIProcess/win/WebPageProxyWin.cpp b/Source/WebKit2/UIProcess/win/WebPageProxyWin.cpp deleted file mode 100644 index bc1fa57c8..000000000 --- a/Source/WebKit2/UIProcess/win/WebPageProxyWin.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* -* Copyright (C) 2010 Apple Inc. All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* -* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS -* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -* THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "config.h" -#include "WebPageProxy.h" - -#include "PageClient.h" -#include "WebDragSource.h" -#include "WebPageMessages.h" -#include "WebPopupMenuProxyWin.h" -#include "WebProcessProxy.h" - -#include "resource.h" -#include <WebCore/BitmapInfo.h> -#include <WebCore/COMPtr.h> -#include <WebCore/ClipboardUtilitiesWin.h> -#include <WebCore/SystemInfo.h> -#include <WebCore/WCDataObject.h> -#include <WebCore/WebCoreInstanceHandle.h> -#include <tchar.h> -#include <wtf/StdLibExtras.h> -#include <wtf/text/StringConcatenate.h> - -using namespace WebCore; - -namespace WebKit { - -static String userVisibleWebKitVersionString() -{ - LPWSTR buildNumberStringPtr; - if (!::LoadStringW(instanceHandle(), BUILD_NUMBER, reinterpret_cast<LPWSTR>(&buildNumberStringPtr), 0) || !buildNumberStringPtr) - return "534+"; - - return buildNumberStringPtr; -} - -String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent) -{ - DEFINE_STATIC_LOCAL(String, osVersion, (windowsVersionForUAString())); - DEFINE_STATIC_LOCAL(String, webKitVersion, (userVisibleWebKitVersionString())); - - return makeString("Mozilla/5.0 (", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)", applicationNameForUserAgent.isEmpty() ? "" : " ", applicationNameForUserAgent); -} - -void WebPageProxy::setPopupMenuSelectedIndex(int32_t selectedIndex) -{ - if (!m_activePopupMenu) - return; - - static_cast<WebPopupMenuProxyWin*>(m_activePopupMenu.get())->setFocusedIndex(selectedIndex); -} - -HWND WebPageProxy::nativeWindow() const -{ - return m_pageClient->nativeWindow(); -} - -void WebPageProxy::scheduleChildWindowGeometryUpdate(const WindowGeometry& geometry) -{ - m_pageClient->scheduleChildWindowGeometryUpdate(geometry); -} - -void WebPageProxy::didInstallOrUninstallPageOverlay(bool didInstall) -{ - m_pageClient->didInstallOrUninstallPageOverlay(didInstall); -} - -IntRect WebPageProxy::firstRectForCharacterInSelectedRange(int characterPosition) -{ - IntRect resultRect; - process()->sendSync(Messages::WebPage::FirstRectForCharacterInSelectedRange(characterPosition), Messages::WebPage::FirstRectForCharacterInSelectedRange::Reply(resultRect), m_pageID); - return resultRect; -} - -String WebPageProxy::getSelectedText() -{ - String text; - process()->sendSync(Messages::WebPage::GetSelectedText(), Messages::WebPage::GetSelectedText::Reply(text), m_pageID); - return text; -} - -bool WebPageProxy::gestureWillBegin(const IntPoint& point) -{ - bool canBeginPanning = false; - process()->sendSync(Messages::WebPage::GestureWillBegin(point), Messages::WebPage::GestureWillBegin::Reply(canBeginPanning), m_pageID); - return canBeginPanning; -} - -void WebPageProxy::gestureDidScroll(const IntSize& size) -{ - process()->send(Messages::WebPage::GestureDidScroll(size), m_pageID); -} - -void WebPageProxy::gestureDidEnd() -{ - process()->send(Messages::WebPage::GestureDidEnd(), m_pageID); -} - -void WebPageProxy::setGestureReachedScrollingLimit(bool limitReached) -{ - m_pageClient->setGestureReachedScrollingLimit(limitReached); -} - -void WebPageProxy::startDragDrop(const IntPoint& imageOrigin, const IntPoint& dragPoint, uint64_t okEffect, const HashMap<UINT, Vector<String> >& dataMap, uint64_t fileSize, const String& pathname, const SharedMemory::Handle& fileContentHandle, const IntSize& dragImageSize, const SharedMemory::Handle& dragImageHandle, bool isLinkDrag) -{ - COMPtr<WCDataObject> dataObject; - WCDataObject::createInstance(&dataObject, dataMap); - - if (fileSize) { - RefPtr<SharedMemory> fileContentBuffer = SharedMemory::create(fileContentHandle, SharedMemory::ReadOnly); - setFileDescriptorData(dataObject.get(), fileSize, pathname); - setFileContentData(dataObject.get(), fileSize, fileContentBuffer->data()); - } - - RefPtr<SharedMemory> memoryBuffer = SharedMemory::create(dragImageHandle, SharedMemory::ReadOnly); - if (!memoryBuffer) - return; - - RefPtr<WebDragSource> source = WebDragSource::createInstance(); - if (!source) - return; - - COMPtr<IDragSourceHelper> helper; - if (FAILED(::CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDragSourceHelper, reinterpret_cast<LPVOID*>(&helper)))) - return; - - BitmapInfo bitmapInfo = BitmapInfo::create(dragImageSize); - void* bits; - OwnPtr<HBITMAP> hbmp = adoptPtr(::CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &bits, 0, 0)); - memcpy(bits, memoryBuffer->data(), memoryBuffer->size()); - - SHDRAGIMAGE sdi; - sdi.sizeDragImage.cx = bitmapInfo.bmiHeader.biWidth; - sdi.sizeDragImage.cy = bitmapInfo.bmiHeader.biHeight; - sdi.crColorKey = 0xffffffff; - sdi.hbmpDragImage = hbmp.leakPtr(); - sdi.ptOffset.x = dragPoint.x() - imageOrigin.x(); - sdi.ptOffset.y = dragPoint.y() - imageOrigin.y(); - if (isLinkDrag) - sdi.ptOffset.y = bitmapInfo.bmiHeader.biHeight - sdi.ptOffset.y; - - helper->InitializeFromBitmap(&sdi, dataObject.get()); - - DWORD effect = DROPEFFECT_NONE; - - DragOperation operation = DragOperationNone; - if (::DoDragDrop(dataObject.get(), source.get(), okEffect, &effect) == DRAGDROP_S_DROP) { - if (effect & DROPEFFECT_COPY) - operation = DragOperationCopy; - else if (effect & DROPEFFECT_LINK) - operation = DragOperationLink; - else if (effect & DROPEFFECT_MOVE) - operation = DragOperationMove; - } - POINT globalPoint; - ::GetCursorPos(&globalPoint); - POINT localPoint = globalPoint; - ::ScreenToClient(m_pageClient->nativeWindow(), &localPoint); - - dragEnded(localPoint, globalPoint, operation); -} - -void WebPageProxy::didChangeCompositionSelection(bool hasComposition) -{ - m_pageClient->compositionSelectionChanged(hasComposition); -} - -void WebPageProxy::confirmComposition(const String& compositionString) -{ - process()->send(Messages::WebPage::ConfirmComposition(compositionString), m_pageID); -} - -void WebPageProxy::setComposition(const String& compositionString, Vector<CompositionUnderline>& underlines, int cursorPosition) -{ - process()->send(Messages::WebPage::SetComposition(compositionString, underlines, cursorPosition), m_pageID); -} - - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/WebPopupMenuProxyWin.cpp b/Source/WebKit2/UIProcess/win/WebPopupMenuProxyWin.cpp deleted file mode 100644 index a45280733..000000000 --- a/Source/WebKit2/UIProcess/win/WebPopupMenuProxyWin.cpp +++ /dev/null @@ -1,982 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -// NOTE: This implementation is very similar to the implementation of popups in WebCore::PopupMenuWin. -// We should try and factor out the common bits and share them. - -#include "config.h" -#include "WebPopupMenuProxyWin.h" - -#include "NativeWebMouseEvent.h" -#include "WebView.h" -#include <WebCore/WebCoreInstanceHandle.h> -#include <WebCore/ScrollbarTheme.h> -#include <WebCore/BitmapInfo.h> -#include <WebCore/HWndDC.h> -#include <WebCore/PlatformMouseEvent.h> -#include <windowsx.h> - -using namespace WebCore; -using namespace std; - -namespace WebKit { - -static const LPCWSTR kWebKit2WebPopupMenuProxyWindowClassName = L"WebKit2WebPopupMenuProxyWindowClass"; - -static const int defaultAnimationDuration = 200; -static const int maxPopupHeight = 320; -static const int popupWindowBorderWidth = 1; -static const int separatorPadding = 4; -static const int separatorHeight = 1; - -// This is used from within our custom message pump when we want to send a -// message to the web view and not have our message stolen and sent to -// the popup window. -static const UINT WM_HOST_WINDOW_FIRST = WM_USER; -static const UINT WM_HOST_WINDOW_CHAR = WM_USER + WM_CHAR; -static const UINT WM_HOST_WINDOW_MOUSEMOVE = WM_USER + WM_MOUSEMOVE; - -static inline bool isASCIIPrintable(unsigned c) -{ - return c >= 0x20 && c <= 0x7E; -} - -static void translatePoint(LPARAM& lParam, HWND from, HWND to) -{ - POINT pt; - pt.x = static_cast<short>(GET_X_LPARAM(lParam)); - pt.y = static_cast<short>(GET_Y_LPARAM(lParam)); - ::MapWindowPoints(from, to, &pt, 1); - lParam = MAKELPARAM(pt.x, pt.y); -} - -LRESULT CALLBACK WebPopupMenuProxyWin::WebPopupMenuProxyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - LONG_PTR longPtr = ::GetWindowLongPtr(hWnd, 0); - - if (WebPopupMenuProxyWin* popupMenuProxy = reinterpret_cast<WebPopupMenuProxyWin*>(longPtr)) - return popupMenuProxy->wndProc(hWnd, message, wParam, lParam); - - if (message == WM_CREATE) { - LPCREATESTRUCT createStruct = reinterpret_cast<LPCREATESTRUCT>(lParam); - - // Associate the WebView with the window. - ::SetWindowLongPtr(hWnd, 0, (LONG_PTR)createStruct->lpCreateParams); - return 0; - } - - return ::DefWindowProc(hWnd, message, wParam, lParam); -} - -LRESULT WebPopupMenuProxyWin::wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - LRESULT lResult = 0; - bool handled = true; - - switch (message) { - case WM_MOUSEACTIVATE: - lResult = onMouseActivate(hWnd, message, wParam, lParam, handled); - break; - case WM_SIZE: - lResult = onSize(hWnd, message, wParam, lParam, handled); - break; - case WM_KEYDOWN: - lResult = onKeyDown(hWnd, message, wParam, lParam, handled); - break; - case WM_CHAR: - lResult = onChar(hWnd, message, wParam, lParam, handled); - break; - case WM_MOUSEMOVE: - lResult = onMouseMove(hWnd, message, wParam, lParam, handled); - break; - case WM_LBUTTONDOWN: - lResult = onLButtonDown(hWnd, message, wParam, lParam, handled); - break; - case WM_LBUTTONUP: - lResult = onLButtonUp(hWnd, message, wParam, lParam, handled); - break; - case WM_MOUSEWHEEL: - lResult = onMouseWheel(hWnd, message, wParam, lParam, handled); - break; - case WM_PAINT: - lResult = onPaint(hWnd, message, wParam, lParam, handled); - break; - case WM_PRINTCLIENT: - lResult = onPrintClient(hWnd, message, wParam, lParam, handled); - break; - default: - handled = false; - break; - } - - if (!handled) - lResult = ::DefWindowProc(hWnd, message, wParam, lParam); - - return lResult; -} - -bool WebPopupMenuProxyWin::registerWindowClass() -{ - static bool haveRegisteredWindowClass = false; - if (haveRegisteredWindowClass) - return true; - haveRegisteredWindowClass = true; - - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_DROPSHADOW; - wcex.lpfnWndProc = WebPopupMenuProxyWin::WebPopupMenuProxyWndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = sizeof(WebPopupMenuProxyWin*); - wcex.hInstance = instanceHandle(); - wcex.hIcon = 0; - wcex.hCursor = ::LoadCursor(0, IDC_ARROW); - wcex.hbrBackground = 0; - wcex.lpszMenuName = 0; - wcex.lpszClassName = kWebKit2WebPopupMenuProxyWindowClassName; - wcex.hIconSm = 0; - - return !!::RegisterClassEx(&wcex); -} - -WebPopupMenuProxyWin::WebPopupMenuProxyWin(WebView* webView, WebPopupMenuProxy::Client* client) - : WebPopupMenuProxy(client) - , m_webView(webView) - , m_newSelectedIndex(0) - , m_popup(0) - , m_DC(0) - , m_bmp(0) - , m_itemHeight(0) - , m_scrollOffset(0) - , m_wheelDelta(0) - , m_focusedIndex(0) - , m_wasClicked(false) - , m_scrollbarCapturingMouse(false) - , m_showPopup(false) -{ -} - -WebPopupMenuProxyWin::~WebPopupMenuProxyWin() -{ - if (m_bmp) - ::DeleteObject(m_bmp); - if (m_DC) - ::DeleteDC(m_DC); - if (m_popup) - ::DestroyWindow(m_popup); - if (m_scrollbar) - m_scrollbar->setParent(0); -} - -void WebPopupMenuProxyWin::showPopupMenu(const IntRect& rect, TextDirection, double, const Vector<WebPopupItem>& items, const PlatformPopupMenuData& data, int32_t selectedIndex) -{ - m_items = items; - m_data = data; - m_newSelectedIndex = selectedIndex; - - calculatePositionAndSize(rect); - if (clientRect().isEmpty()) - return; - - HWND hostWindow = m_webView->window(); - - if (!m_scrollbar && visibleItems() < m_items.size()) { - m_scrollbar = Scrollbar::createNativeScrollbar(this, VerticalScrollbar, SmallScrollbar); - m_scrollbar->styleChanged(); - } - - if (!m_popup) { - registerWindowClass(); - - DWORD exStyle = WS_EX_LTRREADING; - - m_popup = ::CreateWindowEx(exStyle, kWebKit2WebPopupMenuProxyWindowClassName, TEXT("PopupMenu"), - WS_POPUP | WS_BORDER, - m_windowRect.x(), m_windowRect.y(), m_windowRect.width(), m_windowRect.height(), - hostWindow, 0, instanceHandle(), this); - - if (!m_popup) - return; - } - - BOOL shouldAnimate = FALSE; - ::SystemParametersInfo(SPI_GETCOMBOBOXANIMATION, 0, &shouldAnimate, 0); - - if (shouldAnimate) { - RECT viewRect = {0}; - ::GetWindowRect(hostWindow, &viewRect); - - if (!::IsRectEmpty(&viewRect)) { - // Popups should slide into view away from the <select> box - // NOTE: This may have to change for Vista - DWORD slideDirection = (m_windowRect.y() < viewRect.top + rect.location().y()) ? AW_VER_NEGATIVE : AW_VER_POSITIVE; - - ::AnimateWindow(m_popup, defaultAnimationDuration, AW_SLIDE | slideDirection); - } - } else - ::ShowWindow(m_popup, SW_SHOWNOACTIVATE); - - - int index = selectedIndex; - if (index >= 0) - setFocusedIndex(index); - - m_showPopup = true; - - // Protect the popup menu in case its owner is destroyed while we're running the message pump. - RefPtr<WebPopupMenuProxyWin> protect(this); - - ::SetCapture(hostWindow); - - MSG msg; - HWND activeWindow; - - while (::GetMessage(&msg, 0, 0, 0)) { - switch (msg.message) { - case WM_HOST_WINDOW_MOUSEMOVE: - case WM_HOST_WINDOW_CHAR: - if (msg.hwnd == m_popup) { - // This message should be sent to the host window. - msg.hwnd = hostWindow; - msg.message -= WM_HOST_WINDOW_FIRST; - } - break; - - // Steal mouse messages. - case WM_NCMOUSEMOVE: - case WM_NCLBUTTONDOWN: - case WM_NCLBUTTONUP: - case WM_NCLBUTTONDBLCLK: - case WM_NCRBUTTONDOWN: - case WM_NCRBUTTONUP: - case WM_NCRBUTTONDBLCLK: - case WM_NCMBUTTONDOWN: - case WM_NCMBUTTONUP: - case WM_NCMBUTTONDBLCLK: - case WM_MOUSEWHEEL: - msg.hwnd = m_popup; - break; - - // These mouse messages use client coordinates so we need to convert them. - case WM_MOUSEMOVE: - case WM_LBUTTONDOWN: - case WM_LBUTTONUP: - case WM_LBUTTONDBLCLK: - case WM_RBUTTONDOWN: - case WM_RBUTTONUP: - case WM_RBUTTONDBLCLK: - case WM_MBUTTONDOWN: - case WM_MBUTTONUP: - case WM_MBUTTONDBLCLK: { - // Translate the coordinate. - translatePoint(msg.lParam, msg.hwnd, m_popup); - msg.hwnd = m_popup; - break; - } - - // Steal all keyboard messages. - case WM_KEYDOWN: - case WM_KEYUP: - case WM_CHAR: - case WM_DEADCHAR: - case WM_SYSKEYUP: - case WM_SYSCHAR: - case WM_SYSDEADCHAR: - msg.hwnd = m_popup; - break; - } - - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - - if (!m_showPopup) - break; - activeWindow = ::GetActiveWindow(); - if (activeWindow != hostWindow && !::IsChild(activeWindow, hostWindow)) - break; - if (::GetCapture() != hostWindow) - break; - } - - if (::GetCapture() == hostWindow) - ::ReleaseCapture(); - - m_showPopup = false; - ::ShowWindow(m_popup, SW_HIDE); - - if (!WebPopupMenuProxy::m_client) - return; - - WebPopupMenuProxy::m_client->valueChangedForPopupMenu(this, m_newSelectedIndex); - - // <https://bugs.webkit.org/show_bug.cgi?id=57904> In order to properly call the onClick() - // handler on a <select> element, we need to fake a mouse up event in the main window. - // The main window already received the mouse down, which showed this popup, but upon - // selection of an item the mouse up gets eaten by the popup menu. So we take the mouse down - // event, change the message type to a mouse up event, and post that in the message queue. - // Thus, we are virtually clicking at the - // same location where the mouse down event occurred. This allows the hit test to select - // the correct element, and thereby call the onClick() JS handler. - if (!WebPopupMenuProxy::m_client->currentlyProcessedMouseDownEvent()) - return; - - const MSG* initiatingWinEvent = WebPopupMenuProxy::m_client->currentlyProcessedMouseDownEvent()->nativeEvent(); - MSG fakeEvent = *initiatingWinEvent; - fakeEvent.message = WM_LBUTTONUP; - ::PostMessage(fakeEvent.hwnd, fakeEvent.message, fakeEvent.wParam, fakeEvent.lParam); -} - -void WebPopupMenuProxyWin::hidePopupMenu() -{ - if (!m_showPopup) - return; - m_showPopup = false; - - ::ShowWindow(m_popup, SW_HIDE); - - // Post a WM_NULL message to wake up the message pump if necessary. - ::PostMessage(m_popup, WM_NULL, 0, 0); -} - -void WebPopupMenuProxyWin::calculatePositionAndSize(const IntRect& rect) -{ - // Convert the rect (which is in view cooridates) into screen coordinates. - IntRect rectInScreenCoords = rect; - POINT location(rectInScreenCoords .location()); - if (!::ClientToScreen(m_webView->window(), &location)) - return; - rectInScreenCoords.setLocation(location); - - int itemCount = m_items.size(); - m_itemHeight = m_data.m_itemHeight; - - int naturalHeight = m_itemHeight * itemCount; - int popupHeight = min(maxPopupHeight, naturalHeight); - - // The popup should show an integral number of items (i.e. no partial items should be visible) - popupHeight -= popupHeight % m_itemHeight; - - // Next determine its width - int popupWidth = m_data.m_popupWidth; - - if (naturalHeight > maxPopupHeight) { - // We need room for a scrollbar - popupWidth += ScrollbarTheme::theme()->scrollbarThickness(SmallScrollbar); - } - - popupHeight += 2 * popupWindowBorderWidth; - - // The popup should be at least as wide as the control on the page - popupWidth = max(rectInScreenCoords.width() - m_data.m_clientInsetLeft - m_data.m_clientInsetRight, popupWidth); - - // Always left-align items in the popup. This matches popup menus on the mac. - int popupX = rectInScreenCoords.x() + m_data.m_clientInsetLeft; - - IntRect popupRect(popupX, rectInScreenCoords.maxY(), popupWidth, popupHeight); - - // The popup needs to stay within the bounds of the screen and not overlap any toolbars - HMONITOR monitor = ::MonitorFromWindow(m_webView->window(), MONITOR_DEFAULTTOPRIMARY); - MONITORINFOEX monitorInfo; - monitorInfo.cbSize = sizeof(MONITORINFOEX); - ::GetMonitorInfo(monitor, &monitorInfo); - FloatRect screen = static_cast<IntRect>(monitorInfo.rcWork); - - // Check that we don't go off the screen vertically - if (popupRect.maxY() > screen.height()) { - // The popup will go off the screen, so try placing it above the client - if (rectInScreenCoords.y() - popupRect.height() < 0) { - // The popup won't fit above, either, so place it whereever's bigger and resize it to fit - if ((rectInScreenCoords.y() + rectInScreenCoords.height() / 2) < (screen.height() / 2)) { - // Below is bigger - popupRect.setHeight(screen.height() - popupRect.y()); - } else { - // Above is bigger - popupRect.setY(0); - popupRect.setHeight(rectInScreenCoords.y()); - } - } else { - // The popup fits above, so reposition it - popupRect.setY(rectInScreenCoords.y() - popupRect.height()); - } - } - - // Check that we don't go off the screen horizontally - if (popupRect.x() < screen.x()) { - popupRect.setWidth(popupRect.width() - (screen.x() - popupRect.x())); - popupRect.setX(screen.x()); - } - - m_windowRect = popupRect; -} - -IntRect WebPopupMenuProxyWin::clientRect() const -{ - IntRect clientRect = m_windowRect; - clientRect.inflate(-popupWindowBorderWidth); - clientRect.setLocation(IntPoint(0, 0)); - return clientRect; -} - -void WebPopupMenuProxyWin::invalidateItem(int index) -{ - if (!m_popup) - return; - - IntRect damageRect(clientRect()); - damageRect.setY(m_itemHeight * (index - m_scrollOffset)); - damageRect.setHeight(m_itemHeight); - if (m_scrollbar) - damageRect.setWidth(damageRect.width() - m_scrollbar->frameRect().width()); - - RECT r = damageRect; - ::InvalidateRect(m_popup, &r, TRUE); -} - -int WebPopupMenuProxyWin::scrollSize(ScrollbarOrientation orientation) const -{ - return ((orientation == VerticalScrollbar) && m_scrollbar) ? (m_scrollbar->totalSize() - m_scrollbar->visibleSize()) : 0; -} - -int WebPopupMenuProxyWin::scrollPosition(Scrollbar*) const -{ - return m_scrollOffset; -} - -void WebPopupMenuProxyWin::setScrollOffset(const IntPoint& offset) -{ - scrollTo(offset.y()); -} - -int WebPopupMenuProxyWin::visibleHeight() const -{ - return m_scrollbar ? m_scrollbar->visibleSize() : contentsSize().height(); -} - -int WebPopupMenuProxyWin::visibleWidth() const -{ - int scrollbarWidth = m_scrollbar ? m_scrollbar->frameRect().width() : 0; - return contentsSize().width() - scrollbarWidth; -} - -WebCore::IntSize WebPopupMenuProxyWin::contentsSize() const -{ - return clientRect().size(); -} - -WebCore::IntRect WebPopupMenuProxyWin::scrollableAreaBoundingBox() const -{ - return m_windowRect; -} - -void WebPopupMenuProxyWin::scrollTo(int offset) -{ - ASSERT(m_scrollbar); - - if (!m_popup) - return; - - if (m_scrollOffset == offset) - return; - - int scrolledLines = m_scrollOffset - offset; - m_scrollOffset = offset; - - UINT flags = SW_INVALIDATE; - -#ifdef CAN_SET_SMOOTH_SCROLLING_DURATION - BOOL shouldSmoothScroll = FALSE; - ::SystemParametersInfo(SPI_GETLISTBOXSMOOTHSCROLLING, 0, &shouldSmoothScroll, 0); - if (shouldSmoothScroll) - flags |= MAKEWORD(SW_SMOOTHSCROLL, smoothScrollAnimationDuration); -#endif - - IntRect listRect = clientRect(); - if (m_scrollbar) - listRect.setWidth(listRect.width() - m_scrollbar->frameRect().width()); - RECT r = listRect; - ::ScrollWindowEx(m_popup, 0, scrolledLines * m_itemHeight, &r, 0, 0, 0, flags); - if (m_scrollbar) { - r = m_scrollbar->frameRect(); - ::InvalidateRect(m_popup, &r, TRUE); - } - ::UpdateWindow(m_popup); -} - -void WebPopupMenuProxyWin::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect) -{ - IntRect scrollRect = rect; - scrollRect.move(scrollbar->x(), scrollbar->y()); - RECT r = scrollRect; - ::InvalidateRect(m_popup, &r, false); -} - -// Message pump messages. - -LRESULT WebPopupMenuProxyWin::onMouseActivate(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled) -{ - handled = true; - return MA_NOACTIVATE; -} - -LRESULT WebPopupMenuProxyWin::onSize(HWND hWnd, UINT message, WPARAM, LPARAM lParam, bool& handled) -{ - handled = true; - if (!scrollbar()) - return 0; - - IntSize size(LOWORD(lParam), HIWORD(lParam)); - scrollbar()->setFrameRect(IntRect(size.width() - scrollbar()->width(), 0, scrollbar()->width(), size.height())); - - int visibleItems = this->visibleItems(); - scrollbar()->setEnabled(visibleItems < m_items.size()); - scrollbar()->setSteps(1, max(1, visibleItems - 1)); - scrollbar()->setProportion(visibleItems, m_items.size()); - return 0; -} - -LRESULT WebPopupMenuProxyWin::onKeyDown(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - handled = true; - - LRESULT lResult = 0; - switch (LOWORD(wParam)) { - case VK_DOWN: - case VK_RIGHT: - down(); - break; - case VK_UP: - case VK_LEFT: - up(); - break; - case VK_HOME: - focusFirst(); - break; - case VK_END: - focusLast(); - break; - case VK_PRIOR: - if (focusedIndex() != scrollOffset()) { - // Set the selection to the first visible item - int firstVisibleItem = scrollOffset(); - up(focusedIndex() - firstVisibleItem); - } else { - // The first visible item is selected, so move the selection back one page - up(visibleItems()); - } - break; - case VK_NEXT: { - int lastVisibleItem = scrollOffset() + visibleItems() - 1; - if (focusedIndex() != lastVisibleItem) { - // Set the selection to the last visible item - down(lastVisibleItem - focusedIndex()); - } else { - // The last visible item is selected, so move the selection forward one page - down(visibleItems()); - } - break; - } - case VK_TAB: - ::SendMessage(m_webView->window(), message, wParam, lParam); - hide(); - break; - case VK_ESCAPE: - hide(); - break; - default: - if (isASCIIPrintable(wParam)) { - // Send the keydown to the WebView so it can be used for type-to-select. - // Since we know that the virtual key is ASCII printable, it's OK to convert this to - // a WM_CHAR message. (We don't want to call TranslateMessage because that will post a - // WM_CHAR message that will be stolen and redirected to the popup HWND. - ::PostMessage(m_popup, WM_HOST_WINDOW_CHAR, wParam, lParam); - } else - lResult = 1; - break; - } - - return lResult; -} - -LRESULT WebPopupMenuProxyWin::onChar(HWND hWnd, UINT message, WPARAM wParam, LPARAM, bool& handled) -{ - handled = true; - - LRESULT lResult = 0; - int index; - switch (wParam) { - case 0x0D: // Enter/Return - hide(); - index = focusedIndex(); - ASSERT(index >= 0); - // FIXME: Do we need to send back the index right away? - m_newSelectedIndex = index; - break; - case 0x1B: // Escape - hide(); - break; - case 0x09: // TAB - case 0x08: // Backspace - case 0x0A: // Linefeed - default: // Character - lResult = 1; - break; - } - - return lResult; -} - -LRESULT WebPopupMenuProxyWin::onMouseMove(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - handled = true; - - IntPoint mousePoint(MAKEPOINTS(lParam)); - if (scrollbar()) { - IntRect scrollBarRect = scrollbar()->frameRect(); - if (scrollbarCapturingMouse() || scrollBarRect.contains(mousePoint)) { - // Put the point into coordinates relative to the scroll bar - mousePoint.move(-scrollBarRect.x(), -scrollBarRect.y()); - PlatformMouseEvent event(hWnd, message, wParam, MAKELPARAM(mousePoint.x(), mousePoint.y())); - scrollbar()->mouseMoved(event); - return 0; - } - } - - BOOL shouldHotTrack = FALSE; - ::SystemParametersInfo(SPI_GETHOTTRACKING, 0, &shouldHotTrack, 0); - - RECT bounds; - ::GetClientRect(m_popup, &bounds); - if (!::PtInRect(&bounds, mousePoint) && !(wParam & MK_LBUTTON)) { - // When the mouse is not inside the popup menu and the left button isn't down, just - // repost the message to the web view. - - // Translate the coordinate. - translatePoint(lParam, m_popup, m_webView->window()); - - ::PostMessage(m_popup, WM_HOST_WINDOW_MOUSEMOVE, wParam, lParam); - return 0; - } - - if ((shouldHotTrack || wParam & MK_LBUTTON) && ::PtInRect(&bounds, mousePoint)) - setFocusedIndex(listIndexAtPoint(mousePoint), true); - - return 0; -} - -LRESULT WebPopupMenuProxyWin::onLButtonDown(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - handled = true; - - IntPoint mousePoint(MAKEPOINTS(lParam)); - if (scrollbar()) { - IntRect scrollBarRect = scrollbar()->frameRect(); - if (scrollBarRect.contains(mousePoint)) { - // Put the point into coordinates relative to the scroll bar - mousePoint.move(-scrollBarRect.x(), -scrollBarRect.y()); - PlatformMouseEvent event(hWnd, message, wParam, MAKELPARAM(mousePoint.x(), mousePoint.y())); - scrollbar()->mouseDown(event); - setScrollbarCapturingMouse(true); - return 0; - } - } - - // If the mouse is inside the window, update the focused index. Otherwise, - // hide the popup. - RECT bounds; - ::GetClientRect(m_popup, &bounds); - if (::PtInRect(&bounds, mousePoint)) - setFocusedIndex(listIndexAtPoint(mousePoint), true); - else - hide(); - - return 0; -} - - -LRESULT WebPopupMenuProxyWin::onLButtonUp(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - handled = true; - - IntPoint mousePoint(MAKEPOINTS(lParam)); - if (scrollbar()) { - IntRect scrollBarRect = scrollbar()->frameRect(); - if (scrollbarCapturingMouse() || scrollBarRect.contains(mousePoint)) { - setScrollbarCapturingMouse(false); - // Put the point into coordinates relative to the scroll bar - mousePoint.move(-scrollBarRect.x(), -scrollBarRect.y()); - PlatformMouseEvent event(hWnd, message, wParam, MAKELPARAM(mousePoint.x(), mousePoint.y())); - scrollbar()->mouseUp(event); - // FIXME: This is a hack to work around Scrollbar not invalidating correctly when it doesn't have a parent widget - RECT r = scrollBarRect; - ::InvalidateRect(m_popup, &r, TRUE); - return 0; - } - } - // Only hide the popup if the mouse is inside the popup window. - RECT bounds; - ::GetClientRect(m_popup, &bounds); - if (::PtInRect(&bounds, mousePoint)) { - hide(); - int index = focusedIndex(); - if (index >= 0) { - // FIXME: Do we need to send back the index right away? - m_newSelectedIndex = index; - } - } - - return 0; -} - -LRESULT WebPopupMenuProxyWin::onMouseWheel(HWND hWnd, UINT message, WPARAM wParam, LPARAM, bool& handled) -{ - handled = true; - - if (!scrollbar()) - return 0; - - int i = 0; - for (incrementWheelDelta(GET_WHEEL_DELTA_WPARAM(wParam)); abs(wheelDelta()) >= WHEEL_DELTA; reduceWheelDelta(WHEEL_DELTA)) { - if (wheelDelta() > 0) - ++i; - else - --i; - } - - ScrollableArea::scroll(i > 0 ? ScrollUp : ScrollDown, ScrollByLine, abs(i)); - return 0; -} - -LRESULT WebPopupMenuProxyWin::onPaint(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled) -{ - handled = true; - - PAINTSTRUCT paintStruct; - ::BeginPaint(m_popup, &paintStruct); - paint(paintStruct.rcPaint, paintStruct.hdc); - ::EndPaint(m_popup, &paintStruct); - - return 0; -} - -LRESULT WebPopupMenuProxyWin::onPrintClient(HWND hWnd, UINT, WPARAM wParam, LPARAM, bool& handled) -{ - handled = true; - - HDC hdc = reinterpret_cast<HDC>(wParam); - paint(clientRect(), hdc); - - return 0; -} - -bool WebPopupMenuProxyWin::down(unsigned lines) -{ - int size = m_items.size(); - - int lastSelectableIndex, selectedListIndex; - lastSelectableIndex = selectedListIndex = focusedIndex(); - for (int i = selectedListIndex + 1; i >= 0 && i < size; ++i) { - if (m_items[i].m_isEnabled) { - lastSelectableIndex = i; - if (i >= selectedListIndex + (int)lines) - break; - } - } - - return setFocusedIndex(lastSelectableIndex); -} - -bool WebPopupMenuProxyWin::up(unsigned lines) -{ - int size = m_items.size(); - - int lastSelectableIndex, selectedListIndex; - lastSelectableIndex = selectedListIndex = focusedIndex(); - for (int i = selectedListIndex - 1; i >= 0 && i < size; --i) { - if (m_items[i].m_isEnabled) { - lastSelectableIndex = i; - if (i <= selectedListIndex - (int)lines) - break; - } - } - - return setFocusedIndex(lastSelectableIndex); -} - -void WebPopupMenuProxyWin::paint(const IntRect& damageRect, HDC hdc) -{ - if (!m_popup) - return; - - if (!m_DC) { - m_DC = ::CreateCompatibleDC(HWndDC(m_popup)); - if (!m_DC) - return; - } - - if (m_bmp) { - bool keepBitmap = false; - BITMAP bitmap; - if (::GetObject(m_bmp, sizeof(bitmap), &bitmap)) - keepBitmap = bitmap.bmWidth == clientRect().width() && bitmap.bmHeight == clientRect().height(); - if (!keepBitmap) { - ::DeleteObject(m_bmp); - m_bmp = 0; - } - } - - if (!m_bmp) { - BitmapInfo bitmapInfo = BitmapInfo::createBottomUp(clientRect().size()); - void* pixels = 0; - m_bmp = ::CreateDIBSection(m_DC, &bitmapInfo, DIB_RGB_COLORS, &pixels, 0, 0); - if (!m_bmp) - return; - ::SelectObject(m_DC, m_bmp); - } - - GraphicsContext context(m_DC); - - IntRect translatedDamageRect = damageRect; - translatedDamageRect.move(IntSize(0, m_scrollOffset * m_itemHeight)); - m_data.m_notSelectedBackingStore->paint(context, damageRect.location(), translatedDamageRect); - - IntRect selectedIndexRectInBackingStore(0, focusedIndex() * m_itemHeight, m_data.m_selectedBackingStore->size().width(), m_itemHeight); - IntPoint selectedIndexDstPoint = selectedIndexRectInBackingStore.location(); - selectedIndexDstPoint.move(0, -m_scrollOffset * m_itemHeight); - - m_data.m_selectedBackingStore->paint(context, selectedIndexDstPoint, selectedIndexRectInBackingStore); - - if (m_scrollbar) - m_scrollbar->paint(&context, damageRect); - - - HWndDC hWndDC; - HDC localDC = hdc ? hdc : hWndDC.setHWnd(m_popup); - - ::BitBlt(localDC, damageRect.x(), damageRect.y(), damageRect.width(), damageRect.height(), m_DC, damageRect.x(), damageRect.y(), SRCCOPY); -} - -bool WebPopupMenuProxyWin::setFocusedIndex(int i, bool hotTracking) -{ - if (i < 0 || i >= m_items.size() || i == focusedIndex()) - return false; - - if (!m_items[i].m_isEnabled) - return false; - - invalidateItem(focusedIndex()); - invalidateItem(i); - - m_focusedIndex = i; - - if (!hotTracking) { - if (WebPopupMenuProxy::m_client) - WebPopupMenuProxy::m_client->setTextFromItemForPopupMenu(this, i); - } - - if (!scrollToRevealSelection()) - ::UpdateWindow(m_popup); - - return true; -} - -int WebPopupMenuProxyWin::visibleItems() const -{ - return clientRect().height() / m_itemHeight; -} - -int WebPopupMenuProxyWin::listIndexAtPoint(const IntPoint& point) const -{ - return m_scrollOffset + point.y() / m_itemHeight; -} - -int WebPopupMenuProxyWin::focusedIndex() const -{ - return m_focusedIndex; -} - -void WebPopupMenuProxyWin::focusFirst() -{ - int size = m_items.size(); - - for (int i = 0; i < size; ++i) { - if (m_items[i].m_isEnabled) { - setFocusedIndex(i); - break; - } - } -} - -void WebPopupMenuProxyWin::focusLast() -{ - int size = m_items.size(); - - for (int i = size - 1; i > 0; --i) { - if (m_items[i].m_isEnabled) { - setFocusedIndex(i); - break; - } - } -} - - -void WebPopupMenuProxyWin::incrementWheelDelta(int delta) -{ - m_wheelDelta += delta; -} - -void WebPopupMenuProxyWin::reduceWheelDelta(int delta) -{ - ASSERT(delta >= 0); - ASSERT(delta <= abs(m_wheelDelta)); - - if (m_wheelDelta > 0) - m_wheelDelta -= delta; - else if (m_wheelDelta < 0) - m_wheelDelta += delta; - else - return; -} - -bool WebPopupMenuProxyWin::scrollToRevealSelection() -{ - if (!m_scrollbar) - return false; - - int index = focusedIndex(); - - if (index < m_scrollOffset) { - ScrollableArea::scrollToOffsetWithoutAnimation(VerticalScrollbar, index); - return true; - } - - if (index >= m_scrollOffset + visibleItems()) { - ScrollableArea::scrollToOffsetWithoutAnimation(VerticalScrollbar, index - visibleItems() + 1); - return true; - } - - return false; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/WebPopupMenuProxyWin.h b/Source/WebKit2/UIProcess/win/WebPopupMenuProxyWin.h deleted file mode 100644 index f4104f75f..000000000 --- a/Source/WebKit2/UIProcess/win/WebPopupMenuProxyWin.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebPopupMenuProxyWin_h -#define WebPopupMenuProxyWin_h - -#include "PlatformPopupMenuData.h" -#include "WebPopupItem.h" -#include "WebPopupMenuProxy.h" -#include <WebCore/Scrollbar.h> -#include <WebCore/ScrollableArea.h> - -typedef struct HWND__* HWND; -typedef struct HDC__* HDC; -typedef struct HBITMAP__* HBITMAP; - -namespace WebKit { - -class WebView; - -class WebPopupMenuProxyWin : public WebPopupMenuProxy, private WebCore::ScrollableArea { -public: - static PassRefPtr<WebPopupMenuProxyWin> create(WebView* webView, WebPopupMenuProxy::Client* client) - { - return adoptRef(new WebPopupMenuProxyWin(webView, client)); - } - ~WebPopupMenuProxyWin(); - - virtual void showPopupMenu(const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>&, const PlatformPopupMenuData&, int32_t selectedIndex); - virtual void hidePopupMenu(); - - bool setFocusedIndex(int index, bool hotTracking = false); - - void hide() { hidePopupMenu(); } - -private: - WebPopupMenuProxyWin(WebView*, WebPopupMenuProxy::Client*); - - WebCore::Scrollbar* scrollbar() const { return m_scrollbar.get(); } - - // ScrollableArea - virtual int scrollSize(WebCore::ScrollbarOrientation) const OVERRIDE; - virtual int scrollPosition(WebCore::Scrollbar*) const OVERRIDE; - virtual void setScrollOffset(const WebCore::IntPoint&) OVERRIDE; - virtual void invalidateScrollbarRect(WebCore::Scrollbar*, const WebCore::IntRect&) OVERRIDE; - virtual void invalidateScrollCornerRect(const WebCore::IntRect&) OVERRIDE { } - virtual bool isActive() const OVERRIDE { return true; } - virtual bool isScrollCornerVisible() const OVERRIDE { return false; } - virtual WebCore::IntRect scrollCornerRect() const OVERRIDE { return WebCore::IntRect(); } - virtual WebCore::Scrollbar* verticalScrollbar() const OVERRIDE { return m_scrollbar.get(); } - virtual WebCore::ScrollableArea* enclosingScrollableArea() const OVERRIDE { return 0; } - virtual int visibleHeight() const OVERRIDE; - virtual int visibleWidth() const OVERRIDE; - virtual WebCore::IntSize contentsSize() const OVERRIDE; - virtual WebCore::IntRect scrollableAreaBoundingBox() const OVERRIDE; - virtual bool scrollbarsCanBeActive() const OVERRIDE { return true; } - - // NOTE: This should only be called by the overriden setScrollOffset from ScrollableArea. - void scrollTo(int offset); - - static bool registerWindowClass(); - static LRESULT CALLBACK WebPopupMenuProxyWndProc(HWND, UINT, WPARAM, LPARAM); - LRESULT wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - // Message pump messages. - LRESULT onMouseActivate(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onSize(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onKeyDown(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onChar(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onMouseMove(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onLButtonDown(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onLButtonUp(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onMouseWheel(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onPaint(HWND, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onPrintClient(HWND, UINT message, WPARAM, LPARAM, bool& handled); - - void calculatePositionAndSize(const WebCore::IntRect&); - WebCore::IntRect clientRect() const; - void invalidateItem(int index); - - int itemHeight() const { return m_itemHeight; } - const WebCore::IntRect& windowRect() const { return m_windowRect; } - int wheelDelta() const { return m_wheelDelta; } - void setWasClicked(bool b = true) { m_wasClicked = b; } - bool wasClicked() const { return m_wasClicked; } - void setScrollOffset(int offset) { m_scrollOffset = offset; } - int scrollOffset() const { return m_scrollOffset; } - bool scrollbarCapturingMouse() const { return m_scrollbarCapturingMouse; } - void setScrollbarCapturingMouse(bool b) { m_scrollbarCapturingMouse = b; } - - - bool up(unsigned lines = 1); - bool down(unsigned lines = 1); - - void paint(const WebCore::IntRect& damageRect, HDC = 0); - int visibleItems() const; - int listIndexAtPoint(const WebCore::IntPoint&) const; - int focusedIndex() const; - void focusFirst(); - void focusLast(); - bool scrollToRevealSelection(); - void incrementWheelDelta(int delta); - void reduceWheelDelta(int delta); - - WebView* m_webView; - Vector<WebPopupItem> m_items; - PlatformPopupMenuData m_data; - int m_newSelectedIndex; - - RefPtr<WebCore::Scrollbar> m_scrollbar; - HWND m_popup; - HDC m_DC; - HBITMAP m_bmp; - WebCore::IntRect m_windowRect; - - int m_itemHeight; - int m_scrollOffset; - int m_wheelDelta; - int m_focusedIndex; - bool m_wasClicked; - bool m_scrollbarCapturingMouse; - bool m_showPopup; -}; - -} // namespace WebKit - -#endif // WebPopupMenuProxyWin_h diff --git a/Source/WebKit2/UIProcess/win/WebUndoClient.cpp b/Source/WebKit2/UIProcess/win/WebUndoClient.cpp deleted file mode 100644 index a408bc3a2..000000000 --- a/Source/WebKit2/UIProcess/win/WebUndoClient.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebUndoClient.h" - -#include "WKAPICast.h" -#include "WebEditCommandProxy.h" -#include "WebView.h" - -namespace WebKit { - -void WebUndoClient::registerEditCommand(WebView* view, PassRefPtr<WebEditCommandProxy> prpCommand, WebPageProxy::UndoOrRedo undoOrRedo) -{ - if (!m_client.registerEditCommand) - return; - - RefPtr<WebEditCommandProxy> command = prpCommand; - m_client.registerEditCommand(toAPI(view), toAPI(command.release().leakRef()), (undoOrRedo == WebPageProxy::Undo) ? kWKViewUndo : kWKViewRedo, m_client.clientInfo); -} - -void WebUndoClient::clearAllEditCommands(WebView* view) -{ - if (!m_client.clearAllEditCommands) - return; - - m_client.clearAllEditCommands(toAPI(view), m_client.clientInfo); -} - -bool WebUndoClient::canUndoRedo(WebView* view, WebPageProxy::UndoOrRedo undoOrRedo) -{ - if (!m_client.canUndoRedo) - return false; - - return m_client.canUndoRedo(toAPI(view), undoOrRedo, m_client.clientInfo); -} - -void WebUndoClient::executeUndoRedo(WebView* view, WebPageProxy::UndoOrRedo undoOrRedo) -{ - if (!m_client.executeUndoRedo) - return; - - m_client.executeUndoRedo(toAPI(view), undoOrRedo, m_client.clientInfo); -} - -} // namespace WebKit - diff --git a/Source/WebKit2/UIProcess/win/WebView.cpp b/Source/WebKit2/UIProcess/win/WebView.cpp deleted file mode 100644 index 70b875bb6..000000000 --- a/Source/WebKit2/UIProcess/win/WebView.cpp +++ /dev/null @@ -1,1810 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebView.h" - -#include "DrawingAreaProxyImpl.h" -#include "FindIndicator.h" -#include "Logging.h" -#include "NativeWebKeyboardEvent.h" -#include "NativeWebMouseEvent.h" -#include "NativeWebWheelEvent.h" -#include "WKAPICast.h" -#include "WebContext.h" -#include "WebContextMenuProxyWin.h" -#include "WebEditCommandProxy.h" -#include "WebEventFactory.h" -#include "WebPageProxy.h" -#include "WebPopupMenuProxyWin.h" -#include <Commctrl.h> -#include <WebCore/BitmapInfo.h> -#include <WebCore/Cursor.h> -#include <WebCore/DragSession.h> -#include <WebCore/Editor.h> -#include <WebCore/FileSystem.h> -#include <WebCore/FloatRect.h> -#include <WebCore/HWndDC.h> -#include <WebCore/IntRect.h> -#include <WebCore/NotImplemented.h> -#include <WebCore/Region.h> -#include <WebCore/RunLoop.h> -#include <WebCore/SoftLinking.h> -#include <WebCore/WebCoreInstanceHandle.h> -#include <WebCore/WindowMessageBroadcaster.h> -#include <WebCore/WindowsTouch.h> -#include <wtf/text/StringBuilder.h> -#include <wtf/text/WTFString.h> - -#if USE(CG) -#include "WKCACFViewWindow.h" -#include <WebCore/GraphicsContextCG.h> -#endif - -#if ENABLE(FULLSCREEN_API) -#include "WebFullScreenManagerProxy.h" -#include <WebCore/FullScreenController.h> -#endif - -namespace Ime { -// We need these functions in a separate namespace, because in the global namespace they conflict -// with the definitions in imm.h only by the type modifier (the macro defines them as static) and -// imm.h is included by windows.h -SOFT_LINK_LIBRARY(IMM32) -SOFT_LINK(IMM32, ImmGetContext, HIMC, WINAPI, (HWND hwnd), (hwnd)) -SOFT_LINK(IMM32, ImmReleaseContext, BOOL, WINAPI, (HWND hWnd, HIMC hIMC), (hWnd, hIMC)) -SOFT_LINK(IMM32, ImmGetCompositionStringW, LONG, WINAPI, (HIMC hIMC, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen), (hIMC, dwIndex, lpBuf, dwBufLen)) -SOFT_LINK(IMM32, ImmSetCandidateWindow, BOOL, WINAPI, (HIMC hIMC, LPCANDIDATEFORM lpCandidate), (hIMC, lpCandidate)) -SOFT_LINK(IMM32, ImmSetOpenStatus, BOOL, WINAPI, (HIMC hIMC, BOOL fOpen), (hIMC, fOpen)) -SOFT_LINK(IMM32, ImmNotifyIME, BOOL, WINAPI, (HIMC hIMC, DWORD dwAction, DWORD dwIndex, DWORD dwValue), (hIMC, dwAction, dwIndex, dwValue)) -SOFT_LINK(IMM32, ImmAssociateContextEx, BOOL, WINAPI, (HWND hWnd, HIMC hIMC, DWORD dwFlags), (hWnd, hIMC, dwFlags)) -}; - -// Soft link functions for gestures and panning. -SOFT_LINK_LIBRARY(USER32); -SOFT_LINK_OPTIONAL(USER32, GetGestureInfo, BOOL, WINAPI, (HGESTUREINFO, PGESTUREINFO)); -SOFT_LINK_OPTIONAL(USER32, SetGestureConfig, BOOL, WINAPI, (HWND, DWORD, UINT, PGESTURECONFIG, UINT)); -SOFT_LINK_OPTIONAL(USER32, CloseGestureInfoHandle, BOOL, WINAPI, (HGESTUREINFO)); - -SOFT_LINK_LIBRARY(Uxtheme); -SOFT_LINK_OPTIONAL(Uxtheme, BeginPanningFeedback, BOOL, WINAPI, (HWND)); -SOFT_LINK_OPTIONAL(Uxtheme, EndPanningFeedback, BOOL, WINAPI, (HWND, BOOL)); -SOFT_LINK_OPTIONAL(Uxtheme, UpdatePanningFeedback, BOOL, WINAPI, (HWND, LONG, LONG, BOOL)); - -using namespace WebCore; - -namespace WebKit { - -static const LPCWSTR kWebKit2WebViewWindowClassName = L"WebKit2WebViewWindowClass"; - -// Constants not available on all platforms. -const int WM_XP_THEMECHANGED = 0x031A; -const int WM_VISTA_MOUSEHWHEEL = 0x020E; - -static const int kMaxToolTipWidth = 250; - -enum { - UpdateActiveStateTimer = 1, -}; - -LRESULT CALLBACK WebView::WebViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - LONG_PTR longPtr = ::GetWindowLongPtr(hWnd, 0); - - if (WebView* webView = reinterpret_cast<WebView*>(longPtr)) - return webView->wndProc(hWnd, message, wParam, lParam); - - if (message == WM_CREATE) { - LPCREATESTRUCT createStruct = reinterpret_cast<LPCREATESTRUCT>(lParam); - - // Associate the WebView with the window. - ::SetWindowLongPtr(hWnd, 0, (LONG_PTR)createStruct->lpCreateParams); - return 0; - } - - return ::DefWindowProc(hWnd, message, wParam, lParam); -} - -LRESULT WebView::wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - LRESULT lResult = 0; - bool handled = true; - - switch (message) { - case WM_CLOSE: - m_page->tryClose(); - break; - case WM_DESTROY: - m_isBeingDestroyed = true; - close(); - break; - case WM_ERASEBKGND: - lResult = 1; - break; - case WM_PAINT: - lResult = onPaintEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_PRINTCLIENT: - lResult = onPrintClientEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_MOUSEACTIVATE: - setWasActivatedByMouseEvent(true); - handled = false; - break; - case WM_MOUSEMOVE: - case WM_LBUTTONDOWN: - case WM_MBUTTONDOWN: - case WM_RBUTTONDOWN: - case WM_LBUTTONDBLCLK: - case WM_MBUTTONDBLCLK: - case WM_RBUTTONDBLCLK: - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - case WM_MOUSELEAVE: - lResult = onMouseEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_MOUSEWHEEL: - case WM_VISTA_MOUSEHWHEEL: - lResult = onWheelEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_HSCROLL: - lResult = onHorizontalScroll(hWnd, message, wParam, lParam, handled); - break; - case WM_VSCROLL: - lResult = onVerticalScroll(hWnd, message, wParam, lParam, handled); - break; - case WM_GESTURENOTIFY: - lResult = onGestureNotify(hWnd, message, wParam, lParam, handled); - break; - case WM_GESTURE: - lResult = onGesture(hWnd, message, wParam, lParam, handled); - break; - case WM_SYSKEYDOWN: - case WM_KEYDOWN: - case WM_SYSCHAR: - case WM_CHAR: - case WM_SYSKEYUP: - case WM_KEYUP: - lResult = onKeyEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_SIZE: - lResult = onSizeEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_WINDOWPOSCHANGED: - lResult = onWindowPositionChangedEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_SETFOCUS: - lResult = onSetFocusEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_KILLFOCUS: - lResult = onKillFocusEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_TIMER: - lResult = onTimerEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_SHOWWINDOW: - lResult = onShowWindowEvent(hWnd, message, wParam, lParam, handled); - break; - case WM_SETCURSOR: - lResult = onSetCursor(hWnd, message, wParam, lParam, handled); - break; - case WM_IME_STARTCOMPOSITION: - handled = onIMEStartComposition(); - break; - case WM_IME_REQUEST: - lResult = onIMERequest(wParam, lParam); - break; - case WM_IME_COMPOSITION: - handled = onIMEComposition(lParam); - break; - case WM_IME_ENDCOMPOSITION: - handled = onIMEEndComposition(); - break; - case WM_IME_SELECT: - handled = onIMESelect(wParam, lParam); - break; - case WM_IME_SETCONTEXT: - handled = onIMESetContext(wParam, lParam); - break; - default: - handled = false; - break; - } - - if (!handled) - lResult = ::DefWindowProc(hWnd, message, wParam, lParam); - - return lResult; -} - -bool WebView::registerWebViewWindowClass() -{ - static bool haveRegisteredWindowClass = false; - if (haveRegisteredWindowClass) - return true; - haveRegisteredWindowClass = true; - - WNDCLASSEX wcex; - - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = WebView::WebViewWndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = sizeof(WebView*); - wcex.hInstance = instanceHandle(); - wcex.hIcon = 0; - wcex.hCursor = ::LoadCursor(0, IDC_ARROW); - wcex.hbrBackground = 0; - wcex.lpszMenuName = 0; - wcex.lpszClassName = kWebKit2WebViewWindowClassName; - wcex.hIconSm = 0; - - return !!::RegisterClassEx(&wcex); -} - -WebView::WebView(RECT rect, WebContext* context, WebPageGroup* pageGroup, HWND parentWindow) - : m_topLevelParentWindow(0) - , m_toolTipWindow(0) - , m_lastCursorSet(0) - , m_webCoreCursor(0) - , m_overrideCursor(0) - , m_trackingMouseLeave(false) - , m_isInWindow(false) - , m_isVisible(false) - , m_wasActivatedByMouseEvent(false) - , m_isBeingDestroyed(false) - , m_inIMEComposition(0) - , m_findIndicatorCallback(0) - , m_findIndicatorCallbackContext(0) - , m_pageOverlayInstalled(false) - , m_lastPanX(0) - , m_lastPanY(0) - , m_overPanY(0) - , m_gestureReachedScrollingLimit(false) -#if USE(ACCELERATED_COMPOSITING) - , m_layerHostWindow(0) -#endif -{ - registerWebViewWindowClass(); - - m_window = ::CreateWindowExW(0, kWebKit2WebViewWindowClassName, 0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE, - rect.top, rect.left, rect.right - rect.left, rect.bottom - rect.top, parentWindow ? parentWindow : HWND_MESSAGE, 0, instanceHandle(), this); - ASSERT(::IsWindow(m_window)); - // We only check our window style, and not ::IsWindowVisible, because m_isVisible only tracks - // this window's visibility status, while ::IsWindowVisible takes our ancestors' visibility - // status into account. <http://webkit.org/b/54104> - ASSERT(m_isVisible == static_cast<bool>(::GetWindowLong(m_window, GWL_STYLE) & WS_VISIBLE)); - - m_page = context->createWebPage(this, pageGroup); - m_page->initializeWebPage(); - - CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper, (void**)&m_dropTargetHelper); - - // FIXME: Initializing the tooltip window here matches WebKit win, but seems like something - // we could do on demand to save resources. - initializeToolTipWindow(); - - // Initialize the top level parent window and register it with the WindowMessageBroadcaster. - windowAncestryDidChange(); - -#if ENABLE(FULLSCREEN_API) - m_page->fullScreenManager()->setWebView(this); -#endif -} - -WebView::~WebView() -{ - // Tooltip window needs to be explicitly destroyed since it isn't a WS_CHILD. - if (::IsWindow(m_toolTipWindow)) - ::DestroyWindow(m_toolTipWindow); -} - -void WebView::initialize() -{ - ::RegisterDragDrop(m_window, this); - - if (shouldInitializeTrackPointHack()) { - // If we detected a registry key belonging to a TrackPoint driver, then create fake - // scrollbars, so the WebView will receive WM_VSCROLL and WM_HSCROLL messages. - // We create an invisible vertical scrollbar and an invisible horizontal scrollbar to allow - // for receiving both types of messages. - ::CreateWindow(TEXT("SCROLLBAR"), TEXT("FAKETRACKPOINTHSCROLLBAR"), WS_CHILD | WS_VISIBLE | SBS_HORZ, 0, 0, 0, 0, m_window, 0, instanceHandle(), 0); - ::CreateWindow(TEXT("SCROLLBAR"), TEXT("FAKETRACKPOINTVSCROLLBAR"), WS_CHILD | WS_VISIBLE | SBS_VERT, 0, 0, 0, 0, m_window, 0, instanceHandle(), 0); - } -} - -void WebView::initializeUndoClient(const WKViewUndoClient* client) -{ - m_undoClient.initialize(client); -} - -void WebView::setParentWindow(HWND parentWindow) -{ - if (m_window) { - // If the host window hasn't changed, bail. - if (::GetParent(m_window) == parentWindow) - return; - if (parentWindow) - ::SetParent(m_window, parentWindow); - else if (!m_isBeingDestroyed) { - // Turn the WebView into a message-only window so it will no longer be a child of the - // old parent window and will be hidden from screen. We only do this when - // isBeingDestroyed() is false because doing this while handling WM_DESTROY can leave - // m_window in a weird state (see <http://webkit.org/b/29337>). - ::SetParent(m_window, HWND_MESSAGE); - } - } - - windowAncestryDidChange(); -} - -static HWND findTopLevelParentWindow(HWND window) -{ - if (!window) - return 0; - - HWND current = window; - for (HWND parent = GetParent(current); current; current = parent, parent = GetParent(parent)) { - if (!parent || !(GetWindowLongPtr(current, GWL_STYLE) & (WS_POPUP | WS_CHILD))) - return current; - } - ASSERT_NOT_REACHED(); - return 0; -} - -void WebView::windowAncestryDidChange() -{ - HWND newTopLevelParentWindow; - if (m_window) - newTopLevelParentWindow = findTopLevelParentWindow(m_window); - else { - // There's no point in tracking active state changes of our parent window if we don't have - // a window ourselves. - newTopLevelParentWindow = 0; - } - - if (newTopLevelParentWindow == m_topLevelParentWindow) - return; - - if (m_topLevelParentWindow) - WindowMessageBroadcaster::removeListener(m_topLevelParentWindow, this); - - m_topLevelParentWindow = newTopLevelParentWindow; - - if (m_topLevelParentWindow) - WindowMessageBroadcaster::addListener(m_topLevelParentWindow, this); - - updateActiveState(); -} - -LRESULT WebView::onMouseEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - NativeWebMouseEvent mouseEvent = NativeWebMouseEvent(hWnd, message, wParam, lParam, m_wasActivatedByMouseEvent); - setWasActivatedByMouseEvent(false); - - switch (message) { - case WM_LBUTTONDOWN: - case WM_MBUTTONDOWN: - case WM_RBUTTONDOWN: - ::SetFocus(m_window); - ::SetCapture(m_window); - break; - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - ::ReleaseCapture(); - break; - case WM_MOUSEMOVE: - startTrackingMouseLeave(); - break; - case WM_MOUSELEAVE: - stopTrackingMouseLeave(); - break; - case WM_LBUTTONDBLCLK: - case WM_MBUTTONDBLCLK: - case WM_RBUTTONDBLCLK: - break; - default: - ASSERT_NOT_REACHED(); - } - - m_page->handleMouseEvent(mouseEvent); - - handled = true; - return 0; -} - -LRESULT WebView::onWheelEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - NativeWebWheelEvent wheelEvent(hWnd, message, wParam, lParam); - if (wheelEvent.controlKey()) { - // We do not want WebKit to handle Control + Wheel, this should be handled by the client application - // to zoom the page. - handled = false; - return 0; - } - - m_page->handleWheelEvent(wheelEvent); - - handled = true; - return 0; -} - -LRESULT WebView::onHorizontalScroll(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - ScrollDirection direction; - ScrollGranularity granularity; - switch (LOWORD(wParam)) { - case SB_LINELEFT: - granularity = ScrollByLine; - direction = ScrollLeft; - break; - case SB_LINERIGHT: - granularity = ScrollByLine; - direction = ScrollRight; - break; - case SB_PAGELEFT: - granularity = ScrollByDocument; - direction = ScrollLeft; - break; - case SB_PAGERIGHT: - granularity = ScrollByDocument; - direction = ScrollRight; - break; - default: - handled = false; - return 0; - } - - m_page->scrollBy(direction, granularity); - - handled = true; - return 0; -} - -LRESULT WebView::onVerticalScroll(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - ScrollDirection direction; - ScrollGranularity granularity; - switch (LOWORD(wParam)) { - case SB_LINEDOWN: - granularity = ScrollByLine; - direction = ScrollDown; - break; - case SB_LINEUP: - granularity = ScrollByLine; - direction = ScrollUp; - break; - case SB_PAGEDOWN: - granularity = ScrollByDocument; - direction = ScrollDown; - break; - case SB_PAGEUP: - granularity = ScrollByDocument; - direction = ScrollUp; - break; - default: - handled = false; - return 0; - } - - m_page->scrollBy(direction, granularity); - - handled = true; - return 0; -} - -LRESULT WebView::onGestureNotify(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - // We shouldn't be getting any gesture messages without SetGestureConfig soft-linking correctly. - ASSERT(SetGestureConfigPtr()); - - GESTURENOTIFYSTRUCT* gn = reinterpret_cast<GESTURENOTIFYSTRUCT*>(lParam); - - POINT localPoint = { gn->ptsLocation.x, gn->ptsLocation.y }; - ::ScreenToClient(m_window, &localPoint); - - bool canPan = m_page->gestureWillBegin(localPoint); - - DWORD dwPanWant = GC_PAN | GC_PAN_WITH_INERTIA | GC_PAN_WITH_GUTTER; - DWORD dwPanBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY; - if (canPan) - dwPanWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY; - else - dwPanBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY; - - GESTURECONFIG gc = { GID_PAN, dwPanWant, dwPanBlock }; - return SetGestureConfigPtr()(m_window, 0, 1, &gc, sizeof(gc)); -} - -LRESULT WebView::onGesture(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - ASSERT(GetGestureInfoPtr()); - ASSERT(CloseGestureInfoHandlePtr()); - ASSERT(UpdatePanningFeedbackPtr()); - ASSERT(BeginPanningFeedbackPtr()); - ASSERT(EndPanningFeedbackPtr()); - - if (!GetGestureInfoPtr() || !CloseGestureInfoHandlePtr() || !UpdatePanningFeedbackPtr() || !BeginPanningFeedbackPtr() || !EndPanningFeedbackPtr()) { - handled = false; - return 0; - } - - HGESTUREINFO gestureHandle = reinterpret_cast<HGESTUREINFO>(lParam); - GESTUREINFO gi = {0}; - gi.cbSize = sizeof(GESTUREINFO); - - if (!GetGestureInfoPtr()(gestureHandle, &gi)) { - handled = false; - return 0; - } - - switch (gi.dwID) { - case GID_BEGIN: - m_lastPanX = gi.ptsLocation.x; - m_lastPanY = gi.ptsLocation.y; - break; - case GID_END: - m_page->gestureDidEnd(); - break; - case GID_PAN: { - int currentX = gi.ptsLocation.x; - int currentY = gi.ptsLocation.y; - - // Reverse the calculations because moving your fingers up should move the screen down, and - // vice-versa. - int deltaX = m_lastPanX - currentX; - int deltaY = m_lastPanY - currentY; - - m_lastPanX = currentX; - m_lastPanY = currentY; - - // Calculate the overpan for window bounce. - m_overPanY -= deltaY; - - if (deltaX || deltaY) - m_page->gestureDidScroll(IntSize(deltaX, deltaY)); - - if (gi.dwFlags & GF_BEGIN) { - BeginPanningFeedbackPtr()(m_window); - m_gestureReachedScrollingLimit = false; - m_overPanY = 0; - } else if (gi.dwFlags & GF_END) { - EndPanningFeedbackPtr()(m_window, true); - m_overPanY = 0; - } - - // FIXME: Support horizontal window bounce - <http://webkit.org/b/58068>. - // FIXME: Window Bounce doesn't undo until user releases their finger - <http://webkit.org/b/58069>. - - if (m_gestureReachedScrollingLimit) - UpdatePanningFeedbackPtr()(m_window, 0, m_overPanY, gi.dwFlags & GF_INERTIA); - - CloseGestureInfoHandlePtr()(gestureHandle); - - handled = true; - return 0; - } - default: - break; - } - - // If we get to this point, the gesture has not been handled. We forward - // the call to DefWindowProc by returning false, and we don't need to - // to call CloseGestureInfoHandle. - // http://msdn.microsoft.com/en-us/library/dd353228(VS.85).aspx - handled = false; - return 0; -} - -LRESULT WebView::onKeyEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ -#if ENABLE(FULLSCREEN_API) - // Trap the ESC key when in full screen mode. - if (message == WM_KEYDOWN && wParam == VK_ESCAPE && m_fullScreenController && m_fullScreenController->isFullScreen()) { - m_fullScreenController->exitFullScreen(); - return false; - } -#endif - - m_page->handleKeyboardEvent(NativeWebKeyboardEvent(hWnd, message, wParam, lParam)); - - // We claim here to always have handled the event. If the event is not in fact handled, we will - // find out later in didNotHandleKeyEvent. - handled = true; - return 0; -} - -static void drawPageBackground(HDC dc, const WebPageProxy* page, const RECT& rect) -{ - if (!page->drawsBackground() || page->drawsTransparentBackground()) - return; - - ::FillRect(dc, &rect, reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1)); -} - -void WebView::paint(HDC hdc, const IntRect& dirtyRect) -{ - m_page->endPrinting(); - if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(m_page->drawingArea())) { - // FIXME: We should port WebKit1's rect coalescing logic here. - Region unpaintedRegion; - drawingArea->paint(hdc, dirtyRect, unpaintedRegion); - - Vector<IntRect> unpaintedRects = unpaintedRegion.rects(); - for (size_t i = 0; i < unpaintedRects.size(); ++i) { - RECT winRect = unpaintedRects[i]; - drawPageBackground(hdc, m_page.get(), unpaintedRects[i]); - } - } else - drawPageBackground(hdc, m_page.get(), dirtyRect); - - m_page->didDraw(); -} - -static void flashRects(HDC dc, const IntRect rects[], size_t rectCount, HBRUSH brush) -{ - for (size_t i = 0; i < rectCount; ++i) { - RECT winRect = rects[i]; - ::FillRect(dc, &winRect, brush); - } - - ::GdiFlush(); - ::Sleep(50); -} - -static OwnPtr<HBRUSH> createBrush(const Color& color) -{ - return adoptPtr(::CreateSolidBrush(RGB(color.red(), color.green(), color.blue()))); -} - -LRESULT WebView::onPaintEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled) -{ - // Update child windows now so that any areas of our window they reveal will be included in the - // invalid region that ::BeginPaint sees. - updateChildWindowGeometries(); - - PAINTSTRUCT paintStruct; - HDC hdc = ::BeginPaint(m_window, &paintStruct); - - if (WebPageProxy::debugPaintFlags() & kWKDebugFlashViewUpdates) { - static HBRUSH brush = createBrush(WebPageProxy::viewUpdatesFlashColor().rgb()).leakPtr(); - IntRect rect = paintStruct.rcPaint; - flashRects(hdc, &rect, 1, brush); - } - - paint(hdc, paintStruct.rcPaint); - - ::EndPaint(m_window, &paintStruct); - - handled = true; - return 0; -} - -LRESULT WebView::onPrintClientEvent(HWND hWnd, UINT, WPARAM wParam, LPARAM, bool& handled) -{ - HDC hdc = reinterpret_cast<HDC>(wParam); - RECT winRect; - ::GetClientRect(hWnd, &winRect); - - // Twidding the visibility flags tells the DrawingArea to resume painting. Right now, the - // the visible state of the view only affects whether or not painting happens, but in the - // future it could affect more, which we wouldn't want to touch here. - - // FIXME: We should have a better way of telling the WebProcess to draw even if we're - // invisible than twiddling the visibility flag. - - bool wasVisible = isViewVisible(); - if (!wasVisible) - setIsVisible(true); - - paint(hdc, winRect); - - if (!wasVisible) - setIsVisible(false); - - handled = true; - return 0; -} - -LRESULT WebView::onSizeEvent(HWND, UINT, WPARAM, LPARAM lParam, bool& handled) -{ - int width = LOWORD(lParam); - int height = HIWORD(lParam); - - if (m_page && m_page->drawingArea()) { - m_page->drawingArea()->setSize(IntSize(width, height), m_nextResizeScrollOffset); - m_nextResizeScrollOffset = IntSize(); - } - -#if USE(ACCELERATED_COMPOSITING) - if (m_layerHostWindow) - ::MoveWindow(m_layerHostWindow, 0, 0, width, height, FALSE); -#endif - - handled = true; - return 0; -} - -LRESULT WebView::onWindowPositionChangedEvent(HWND, UINT, WPARAM, LPARAM lParam, bool& handled) -{ - if (reinterpret_cast<WINDOWPOS*>(lParam)->flags & SWP_SHOWWINDOW) - updateActiveStateSoon(); - - handled = false; - return 0; -} - -LRESULT WebView::onSetFocusEvent(HWND, UINT, WPARAM, LPARAM lParam, bool& handled) -{ - m_page->viewStateDidChange(WebPageProxy::ViewIsFocused); - handled = true; - return 0; -} - -LRESULT WebView::onKillFocusEvent(HWND, UINT, WPARAM, LPARAM lParam, bool& handled) -{ - m_page->viewStateDidChange(WebPageProxy::ViewIsFocused); - handled = true; - return 0; -} - -LRESULT WebView::onTimerEvent(HWND hWnd, UINT, WPARAM wParam, LPARAM, bool& handled) -{ - switch (wParam) { - case UpdateActiveStateTimer: - ::KillTimer(hWnd, UpdateActiveStateTimer); - updateActiveState(); - break; - } - - handled = true; - return 0; -} - -LRESULT WebView::onShowWindowEvent(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - // lParam is 0 when the message is sent because of a ShowWindow call. - // FIXME: Since we don't get notified when an ancestor window is hidden or shown, we will keep - // painting even when we have a hidden ancestor. <http://webkit.org/b/54104> - if (!lParam) - setIsVisible(wParam); - - handled = false; - return 0; -} - -LRESULT WebView::onSetCursor(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool& handled) -{ - if (!m_lastCursorSet) { - handled = false; - return 0; - } - - ::SetCursor(m_lastCursorSet); - return 0; -} - -void WebView::updateActiveState() -{ - m_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); -} - -void WebView::updateActiveStateSoon() -{ - // This function is called while processing the WM_NCACTIVATE message. - // While processing WM_NCACTIVATE when we are being deactivated, GetActiveWindow() will - // still return our window. If we were to call updateActiveState() in that case, we would - // wrongly think that we are still the active window. To work around this, we update our - // active state after a 0-delay timer fires, at which point GetActiveWindow() will return - // the newly-activated window. - - ::SetTimer(m_window, UpdateActiveStateTimer, 0, 0); -} - -static bool initCommonControls() -{ - static bool haveInitialized = false; - if (haveInitialized) - return true; - - INITCOMMONCONTROLSEX init; - init.dwSize = sizeof(init); - init.dwICC = ICC_TREEVIEW_CLASSES; - haveInitialized = !!::InitCommonControlsEx(&init); - return haveInitialized; -} - -void WebView::initializeToolTipWindow() -{ - if (!initCommonControls()) - return; - - m_toolTipWindow = ::CreateWindowEx(WS_EX_TRANSPARENT, TOOLTIPS_CLASS, 0, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - m_window, 0, 0, 0); - if (!m_toolTipWindow) - return; - - TOOLINFO info = {0}; - info.cbSize = sizeof(info); - info.uFlags = TTF_IDISHWND | TTF_SUBCLASS; - info.uId = reinterpret_cast<UINT_PTR>(m_window); - - ::SendMessage(m_toolTipWindow, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&info)); - ::SendMessage(m_toolTipWindow, TTM_SETMAXTIPWIDTH, 0, kMaxToolTipWidth); - ::SetWindowPos(m_toolTipWindow, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); -} - -void WebView::startTrackingMouseLeave() -{ - if (m_trackingMouseLeave) - return; - m_trackingMouseLeave = true; - - TRACKMOUSEEVENT trackMouseEvent; - trackMouseEvent.cbSize = sizeof(TRACKMOUSEEVENT); - trackMouseEvent.dwFlags = TME_LEAVE; - trackMouseEvent.hwndTrack = m_window; - - ::TrackMouseEvent(&trackMouseEvent); -} - -void WebView::stopTrackingMouseLeave() -{ - if (!m_trackingMouseLeave) - return; - m_trackingMouseLeave = false; - - TRACKMOUSEEVENT trackMouseEvent; - trackMouseEvent.cbSize = sizeof(TRACKMOUSEEVENT); - trackMouseEvent.dwFlags = TME_LEAVE | TME_CANCEL; - trackMouseEvent.hwndTrack = m_window; - - ::TrackMouseEvent(&trackMouseEvent); -} - -bool WebView::shouldInitializeTrackPointHack() -{ - static bool shouldCreateScrollbars; - static bool hasRunTrackPointCheck; - - if (hasRunTrackPointCheck) - return shouldCreateScrollbars; - - hasRunTrackPointCheck = true; - const wchar_t* trackPointKeys[] = { - L"Software\\Lenovo\\TrackPoint", - L"Software\\Lenovo\\UltraNav", - L"Software\\Alps\\Apoint\\TrackPoint", - L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB", - L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2" - }; - - for (size_t i = 0; i < WTF_ARRAY_LENGTH(trackPointKeys); ++i) { - HKEY trackPointKey; - int readKeyResult = ::RegOpenKeyExW(HKEY_CURRENT_USER, trackPointKeys[i], 0, KEY_READ, &trackPointKey); - ::RegCloseKey(trackPointKey); - if (readKeyResult == ERROR_SUCCESS) { - shouldCreateScrollbars = true; - return shouldCreateScrollbars; - } - } - - return shouldCreateScrollbars; -} - -void WebView::close() -{ - m_undoClient.initialize(0); - ::RevokeDragDrop(m_window); - if (m_window) { - // We can't check IsWindow(m_window) here, because that will return true even while - // we're already handling WM_DESTROY. So we check !m_isBeingDestroyed instead. - if (!m_isBeingDestroyed) - DestroyWindow(m_window); - // Either we just destroyed m_window, or it's in the process of being destroyed. Either - // way, we clear it out to make sure we don't try to use it later. - m_window = 0; - } - setParentWindow(0); - m_page->close(); -} - -// PageClient - -PassOwnPtr<DrawingAreaProxy> WebView::createDrawingAreaProxy() -{ - return DrawingAreaProxyImpl::create(m_page.get()); -} - -void WebView::setViewNeedsDisplay(const WebCore::IntRect& rect) -{ - RECT r = rect; - ::InvalidateRect(m_window, &r, false); -} - -void WebView::displayView() -{ - ::UpdateWindow(m_window); -} - -void WebView::scrollView(const IntRect& scrollRect, const IntSize& scrollOffset) -{ - // FIXME: Actually scroll the view contents. - setViewNeedsDisplay(scrollRect); -} - -void WebView::flashBackingStoreUpdates(const Vector<IntRect>& updateRects) -{ - static HBRUSH brush = createBrush(WebPageProxy::backingStoreUpdatesFlashColor().rgb()).leakPtr(); - HWndDC dc(m_window); - flashRects(dc, updateRects.data(), updateRects.size(), brush); -} - -WebCore::IntSize WebView::viewSize() -{ - RECT clientRect; - GetClientRect(m_window, &clientRect); - - return IntRect(clientRect).size(); -} - -bool WebView::isViewWindowActive() -{ - HWND activeWindow = ::GetActiveWindow(); - return (activeWindow && m_topLevelParentWindow == findTopLevelParentWindow(activeWindow)); -} - -bool WebView::isViewFocused() -{ - return ::GetFocus() == m_window; -} - -bool WebView::isViewVisible() -{ - return m_isVisible; -} - -bool WebView::isViewInWindow() -{ - return m_isInWindow; -} - -void WebView::pageClosed() -{ -} - -void WebView::processDidCrash() -{ - updateNativeCursor(); - ::InvalidateRect(m_window, 0, TRUE); -} - -void WebView::didRelaunchProcess() -{ - updateNativeCursor(); - ::InvalidateRect(m_window, 0, TRUE); -} - -void WebView::toolTipChanged(const String&, const String& newToolTip) -{ - if (!m_toolTipWindow) - return; - - if (!newToolTip.isEmpty()) { - // This is necessary because String::charactersWithNullTermination() is not const. - String toolTip = newToolTip; - - TOOLINFO info = {0}; - info.cbSize = sizeof(info); - info.uFlags = TTF_IDISHWND; - info.uId = reinterpret_cast<UINT_PTR>(m_window); - info.lpszText = const_cast<UChar*>(toolTip.charactersWithNullTermination()); - ::SendMessage(m_toolTipWindow, TTM_UPDATETIPTEXT, 0, reinterpret_cast<LPARAM>(&info)); - } - - ::SendMessage(m_toolTipWindow, TTM_ACTIVATE, !newToolTip.isEmpty(), 0); -} - -HCURSOR WebView::cursorToShow() const -{ - if (!m_page->isValid()) - return 0; - - // We only show the override cursor if the default (arrow) cursor is showing. - static HCURSOR arrowCursor = ::LoadCursor(0, IDC_ARROW); - if (m_overrideCursor && m_webCoreCursor == arrowCursor) - return m_overrideCursor; - - return m_webCoreCursor; -} - -void WebView::updateNativeCursor() -{ - m_lastCursorSet = cursorToShow(); - if (!m_lastCursorSet) - return; - ::SetCursor(m_lastCursorSet); -} - -void WebView::setCursor(const WebCore::Cursor& cursor) -{ - if (!cursor.platformCursor()->nativeCursor()) - return; - m_webCoreCursor = cursor.platformCursor()->nativeCursor(); - updateNativeCursor(); -} - -void WebView::setCursorHiddenUntilMouseMoves(bool) -{ - notImplemented(); -} - -void WebView::setOverrideCursor(HCURSOR overrideCursor) -{ - m_overrideCursor = overrideCursor; - updateNativeCursor(); -} - -void WebView::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& event) -{ - m_page->setInitialFocus(forward, isKeyboardEventValid, event); -} - -void WebView::setScrollOffsetOnNextResize(const IntSize& scrollOffset) -{ - // The next time we get a WM_SIZE message, scroll by the specified amount in onSizeEvent(). - m_nextResizeScrollOffset = scrollOffset; -} - -void WebView::didChangeViewportProperties(const WebCore::ViewportAttributes&) -{ -} - -void WebView::registerEditCommand(PassRefPtr<WebEditCommandProxy> prpCommand, WebPageProxy::UndoOrRedo undoOrRedo) -{ - RefPtr<WebEditCommandProxy> command = prpCommand; - m_undoClient.registerEditCommand(this, command, undoOrRedo); -} - -void WebView::clearAllEditCommands() -{ - m_undoClient.clearAllEditCommands(this); -} - -bool WebView::canUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - return m_undoClient.canUndoRedo(this, undoOrRedo); -} - -void WebView::executeUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - m_undoClient.executeUndoRedo(this, undoOrRedo); -} - -void WebView::reapplyEditCommand(WebEditCommandProxy* command) -{ - if (!m_page->isValid() || !m_page->isValidEditCommand(command)) - return; - - command->reapply(); -} - -void WebView::unapplyEditCommand(WebEditCommandProxy* command) -{ - if (!m_page->isValid() || !m_page->isValidEditCommand(command)) - return; - - command->unapply(); -} - -void WebView::setCustomDropTarget(IDropTarget* dropTarget) -{ - if (!m_page->isValid() || !m_window) - return; - - ::RevokeDragDrop(m_window); - - if (dropTarget) - ::RegisterDragDrop(m_window, dropTarget); - else - ::RegisterDragDrop(m_window, this); -} - -FloatRect WebView::convertToDeviceSpace(const FloatRect& rect) -{ - return rect; -} - -IntPoint WebView::screenToWindow(const IntPoint& point) -{ - return point; -} - -IntRect WebView::windowToScreen(const IntRect& rect) -{ - return rect; -} - -FloatRect WebView::convertToUserSpace(const FloatRect& rect) -{ - return rect; -} - -HIMC WebView::getIMMContext() -{ - return Ime::ImmGetContext(m_window); -} - -void WebView::prepareCandidateWindow(HIMC hInputContext) -{ - IntRect caret = m_page->firstRectForCharacterInSelectedRange(0); - CANDIDATEFORM form; - form.dwIndex = 0; - form.dwStyle = CFS_EXCLUDE; - form.ptCurrentPos.x = caret.x(); - form.ptCurrentPos.y = caret.maxY(); - form.rcArea.top = caret.y(); - form.rcArea.bottom = caret.maxY(); - form.rcArea.left = caret.x(); - form.rcArea.right = caret.maxX(); - Ime::ImmSetCandidateWindow(hInputContext, &form); -} - -void WebView::resetIME() -{ - HIMC hInputContext = getIMMContext(); - if (!hInputContext) - return; - Ime::ImmNotifyIME(hInputContext, NI_COMPOSITIONSTR, CPS_CANCEL, 0); - Ime::ImmReleaseContext(m_window, hInputContext); -} - -void WebView::setInputMethodState(bool enabled) -{ - Ime::ImmAssociateContextEx(m_window, 0, enabled ? IACE_DEFAULT : 0); -} - -void WebView::compositionSelectionChanged(bool hasChanged) -{ - if (m_page->editorState().hasComposition && !hasChanged) - resetIME(); -} - -bool WebView::onIMEStartComposition() -{ - LOG(TextInput, "onIMEStartComposition"); - m_inIMEComposition++; - - HIMC hInputContext = getIMMContext(); - if (!hInputContext) - return false; - prepareCandidateWindow(hInputContext); - Ime::ImmReleaseContext(m_window, hInputContext); - return true; -} - -static bool getCompositionString(HIMC hInputContext, DWORD type, String& result) -{ - LONG compositionLength = Ime::ImmGetCompositionStringW(hInputContext, type, 0, 0); - if (compositionLength <= 0) - return false; - Vector<UChar> compositionBuffer(compositionLength / 2); - compositionLength = Ime::ImmGetCompositionStringW(hInputContext, type, compositionBuffer.data(), compositionLength); - result = String::adopt(compositionBuffer); - return true; -} - -static void compositionToUnderlines(const Vector<DWORD>& clauses, const Vector<BYTE>& attributes, Vector<CompositionUnderline>& underlines) -{ - if (clauses.isEmpty()) { - underlines.clear(); - return; - } - - size_t numBoundaries = clauses.size() - 1; - underlines.resize(numBoundaries); - for (unsigned i = 0; i < numBoundaries; ++i) { - underlines[i].startOffset = clauses[i]; - underlines[i].endOffset = clauses[i + 1]; - BYTE attribute = attributes[clauses[i]]; - underlines[i].thick = attribute == ATTR_TARGET_CONVERTED || attribute == ATTR_TARGET_NOTCONVERTED; - underlines[i].color = Color::black; - } -} - -#if !LOG_DISABLED -#define APPEND_ARGUMENT_NAME(name) \ - if (lparam & name) { \ - if (needsComma) \ - result.appendLiteral(", "); \ - result.appendLiteral(#name); \ - needsComma = true; \ - } - -static String imeCompositionArgumentNames(LPARAM lparam) -{ - StringBuilder result; - bool needsComma = false; - - APPEND_ARGUMENT_NAME(GCS_COMPATTR); - APPEND_ARGUMENT_NAME(GCS_COMPCLAUSE); - APPEND_ARGUMENT_NAME(GCS_COMPREADSTR); - APPEND_ARGUMENT_NAME(GCS_COMPREADATTR); - APPEND_ARGUMENT_NAME(GCS_COMPREADCLAUSE); - APPEND_ARGUMENT_NAME(GCS_COMPSTR); - APPEND_ARGUMENT_NAME(GCS_CURSORPOS); - APPEND_ARGUMENT_NAME(GCS_DELTASTART); - APPEND_ARGUMENT_NAME(GCS_RESULTCLAUSE); - APPEND_ARGUMENT_NAME(GCS_RESULTREADCLAUSE); - APPEND_ARGUMENT_NAME(GCS_RESULTREADSTR); - APPEND_ARGUMENT_NAME(GCS_RESULTSTR); - APPEND_ARGUMENT_NAME(CS_INSERTCHAR); - APPEND_ARGUMENT_NAME(CS_NOMOVECARET); - - return result.toString(); -} - -static String imeRequestName(WPARAM wparam) -{ - switch (wparam) { - case IMR_CANDIDATEWINDOW: - return "IMR_CANDIDATEWINDOW"; - case IMR_COMPOSITIONFONT: - return "IMR_COMPOSITIONFONT"; - case IMR_COMPOSITIONWINDOW: - return "IMR_COMPOSITIONWINDOW"; - case IMR_CONFIRMRECONVERTSTRING: - return "IMR_CONFIRMRECONVERTSTRING"; - case IMR_DOCUMENTFEED: - return "IMR_DOCUMENTFEED"; - case IMR_QUERYCHARPOSITION: - return "IMR_QUERYCHARPOSITION"; - case IMR_RECONVERTSTRING: - return "IMR_RECONVERTSTRING"; - default: - return "Unknown (" + String::number(wparam) + ")"; - } -} -#endif - -bool WebView::onIMEComposition(LPARAM lparam) -{ - LOG(TextInput, "onIMEComposition %s", imeCompositionArgumentNames(lparam).latin1().data()); - HIMC hInputContext = getIMMContext(); - if (!hInputContext) - return true; - - if (!m_page->editorState().isContentEditable) - return true; - - prepareCandidateWindow(hInputContext); - - if (lparam & GCS_RESULTSTR || !lparam) { - String compositionString; - if (!getCompositionString(hInputContext, GCS_RESULTSTR, compositionString) && lparam) - return true; - - m_page->confirmComposition(compositionString); - return true; - } - - String compositionString; - if (!getCompositionString(hInputContext, GCS_COMPSTR, compositionString)) - return true; - - // Composition string attributes - int numAttributes = Ime::ImmGetCompositionStringW(hInputContext, GCS_COMPATTR, 0, 0); - Vector<BYTE> attributes(numAttributes); - Ime::ImmGetCompositionStringW(hInputContext, GCS_COMPATTR, attributes.data(), numAttributes); - - // Get clauses - int numBytes = Ime::ImmGetCompositionStringW(hInputContext, GCS_COMPCLAUSE, 0, 0); - Vector<DWORD> clauses(numBytes / sizeof(DWORD)); - Ime::ImmGetCompositionStringW(hInputContext, GCS_COMPCLAUSE, clauses.data(), numBytes); - - Vector<CompositionUnderline> underlines; - compositionToUnderlines(clauses, attributes, underlines); - - int cursorPosition = LOWORD(Ime::ImmGetCompositionStringW(hInputContext, GCS_CURSORPOS, 0, 0)); - - m_page->setComposition(compositionString, underlines, cursorPosition); - - return true; -} - -bool WebView::onIMEEndComposition() -{ - LOG(TextInput, "onIMEEndComposition"); - // If the composition hasn't been confirmed yet, it needs to be cancelled. - // This happens after deleting the last character from inline input hole. - if (m_page->editorState().hasComposition) - m_page->confirmComposition(String()); - - if (m_inIMEComposition) - m_inIMEComposition--; - - return true; -} - -LRESULT WebView::onIMERequestCharPosition(IMECHARPOSITION* charPos) -{ - if (charPos->dwCharPos && !m_page->editorState().hasComposition) - return 0; - IntRect caret = m_page->firstRectForCharacterInSelectedRange(charPos->dwCharPos); - charPos->pt.x = caret.x(); - charPos->pt.y = caret.y(); - ::ClientToScreen(m_window, &charPos->pt); - charPos->cLineHeight = caret.height(); - ::GetWindowRect(m_window, &charPos->rcDocument); - return true; -} - -LRESULT WebView::onIMERequestReconvertString(RECONVERTSTRING* reconvertString) -{ - String text = m_page->getSelectedText(); - unsigned totalSize = sizeof(RECONVERTSTRING) + text.length() * sizeof(UChar); - - if (!reconvertString) - return totalSize; - - if (totalSize > reconvertString->dwSize) - return 0; - reconvertString->dwCompStrLen = text.length(); - reconvertString->dwStrLen = text.length(); - reconvertString->dwTargetStrLen = text.length(); - reconvertString->dwStrOffset = sizeof(RECONVERTSTRING); - memcpy(reconvertString + 1, text.characters(), text.length() * sizeof(UChar)); - return totalSize; -} - -LRESULT WebView::onIMERequest(WPARAM request, LPARAM data) -{ - LOG(TextInput, "onIMERequest %s", imeRequestName(request).latin1().data()); - if (!m_page->editorState().isContentEditable) - return 0; - - switch (request) { - case IMR_RECONVERTSTRING: - return onIMERequestReconvertString(reinterpret_cast<RECONVERTSTRING*>(data)); - - case IMR_QUERYCHARPOSITION: - return onIMERequestCharPosition(reinterpret_cast<IMECHARPOSITION*>(data)); - } - return 0; -} - -bool WebView::onIMESelect(WPARAM wparam, LPARAM lparam) -{ - UNUSED_PARAM(wparam); - UNUSED_PARAM(lparam); - LOG(TextInput, "onIMESelect locale %ld %s", lparam, wparam ? "select" : "deselect"); - return false; -} - -bool WebView::onIMESetContext(WPARAM wparam, LPARAM) -{ - LOG(TextInput, "onIMESetContext %s", wparam ? "active" : "inactive"); - return false; -} - -void WebView::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool wasEventHandled) -{ - // Calling ::DefWindowProcW will ensure that pressing the Alt key will generate a WM_SYSCOMMAND - // event, e.g. See <http://webkit.org/b/47671>. - if (!wasEventHandled) - ::DefWindowProcW(event.nativeEvent()->hwnd, event.nativeEvent()->message, event.nativeEvent()->wParam, event.nativeEvent()->lParam); -} - -PassRefPtr<WebPopupMenuProxy> WebView::createPopupMenuProxy(WebPageProxy* page) -{ - return WebPopupMenuProxyWin::create(this, page); -} - -PassRefPtr<WebContextMenuProxy> WebView::createContextMenuProxy(WebPageProxy* page) -{ - return WebContextMenuProxyWin::create(m_window, page); -} - -#if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorChooserProxy> WebView::createColorChooserProxy(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) -{ - notImplemented(); - return 0; -} -#endif - -void WebView::setFindIndicator(PassRefPtr<FindIndicator> prpFindIndicator, bool fadeOut, bool animate) -{ - UNUSED_PARAM(animate); - - if (!m_findIndicatorCallback) - return; - - HBITMAP hbmp = 0; - IntRect selectionRect; - - if (RefPtr<FindIndicator> findIndicator = prpFindIndicator) { - if (ShareableBitmap* contentImage = findIndicator->contentImage()) { - // Render the contentImage to an HBITMAP. - void* bits; - HDC hdc = ::CreateCompatibleDC(0); - int width = contentImage->bounds().width(); - int height = contentImage->bounds().height(); - BitmapInfo bitmapInfo = BitmapInfo::create(contentImage->size()); - - hbmp = CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, static_cast<void**>(&bits), 0, 0); - HBITMAP hbmpOld = static_cast<HBITMAP>(SelectObject(hdc, hbmp)); -#if USE(CG) - RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(bits, width, height, - 8, width * sizeof(RGBQUAD), deviceRGBColorSpaceRef(), kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst)); - - GraphicsContext graphicsContext(context.get()); - contentImage->paint(graphicsContext, IntPoint(), contentImage->bounds()); -#else - // FIXME: Implement! -#endif - - ::SelectObject(hdc, hbmpOld); - ::DeleteDC(hdc); - } - - selectionRect = IntRect(findIndicator->selectionRectInWindowCoordinates()); - } - - // The callback is responsible for calling ::DeleteObject(hbmp). - (*m_findIndicatorCallback)(toAPI(this), hbmp, selectionRect, fadeOut, m_findIndicatorCallbackContext); -} - -void WebView::setFindIndicatorCallback(WKViewFindIndicatorCallback callback, void* context) -{ - m_findIndicatorCallback = callback; - m_findIndicatorCallbackContext = context; -} - -WKViewFindIndicatorCallback WebView::getFindIndicatorCallback(void** context) -{ - if (context) - *context = m_findIndicatorCallbackContext; - - return m_findIndicatorCallback; -} - -void WebView::didInstallOrUninstallPageOverlay(bool didInstall) -{ - m_pageOverlayInstalled = didInstall; -} - -void WebView::didCommitLoadForMainFrame(bool useCustomRepresentation) -{ -} - -void WebView::didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&) -{ -} - -double WebView::customRepresentationZoomFactor() -{ - return 1; -} - -void WebView::setCustomRepresentationZoomFactor(double) -{ -} - -void WebView::didChangeScrollbarsForMainFrame() const -{ -} - -void WebView::findStringInCustomRepresentation(const String&, FindOptions, unsigned) -{ -} - -void WebView::countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned) -{ -} - -void WebView::setIsInWindow(bool isInWindow) -{ - m_isInWindow = isInWindow; - m_page->viewStateDidChange(WebPageProxy::ViewIsInWindow); -} - -void WebView::setIsVisible(bool isVisible) -{ - m_isVisible = isVisible; - - if (m_page) - m_page->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -#if USE(ACCELERATED_COMPOSITING) - -void WebView::enterAcceleratedCompositingMode(const LayerTreeContext& context) -{ -#if HAVE(WKQCA) - ASSERT(!context.isEmpty()); - - m_layerHostWindow = context.window; - - IntSize size = viewSize(); - // Ensure the layer host window is behind all other child windows (since otherwise it would obscure them). - ::SetWindowPos(m_layerHostWindow, HWND_BOTTOM, 0, 0, size.width(), size.height(), SWP_SHOWWINDOW | SWP_NOACTIVATE); -#else - ASSERT_NOT_REACHED(); -#endif -} - -void WebView::exitAcceleratedCompositingMode() -{ -#if HAVE(WKQCA) - ASSERT(m_layerHostWindow); - - // Tell the WKCACFViewWindow to destroy itself. We can't call ::DestroyWindow directly because - // the window is owned by another thread. - ::PostMessageW(m_layerHostWindow, WKCACFViewWindow::customDestroyMessage, 0, 0); - m_layerHostWindow = 0; -#else - ASSERT_NOT_REACHED(); -#endif -} - -void WebView::updateAcceleratedCompositingMode(const LayerTreeContext&) -{ -} -#endif // USE(ACCELERATED_COMPOSITING) - -HWND WebView::nativeWindow() -{ - return m_window; -} - -void WebView::scheduleChildWindowGeometryUpdate(const WindowGeometry& geometry) -{ - m_geometriesUpdater.addPendingUpdate(geometry); -} - -void WebView::updateChildWindowGeometries() -{ - m_geometriesUpdater.updateGeometries(DoNotBringToTop); -} - -// WebCore::WindowMessageListener - -void WebView::windowReceivedMessage(HWND, UINT message, WPARAM wParam, LPARAM) -{ - switch (message) { - case WM_NCACTIVATE: - updateActiveStateSoon(); - break; - case WM_SETTINGCHANGE: - // systemParameterChanged(wParam); - break; - } -} - -HRESULT STDMETHODCALLTYPE WebView::QueryInterface(REFIID riid, void** ppvObject) -{ - *ppvObject = 0; - if (IsEqualGUID(riid, IID_IUnknown)) - *ppvObject = static_cast<IUnknown*>(this); - else if (IsEqualGUID(riid, IID_IDropTarget)) - *ppvObject = static_cast<IDropTarget*>(this); - else - return E_NOINTERFACE; - - AddRef(); - return S_OK; -} - -ULONG STDMETHODCALLTYPE WebView::AddRef(void) -{ - ref(); - return refCount(); -} - -ULONG STDMETHODCALLTYPE WebView::Release(void) -{ - deref(); - return refCount(); -} - -static DWORD dragOperationToDragCursor(DragOperation op) -{ - DWORD res = DROPEFFECT_NONE; - if (op & DragOperationCopy) - res = DROPEFFECT_COPY; - else if (op & DragOperationLink) - res = DROPEFFECT_LINK; - else if (op & DragOperationMove) - res = DROPEFFECT_MOVE; - else if (op & DragOperationGeneric) - res = DROPEFFECT_MOVE; // This appears to be the Firefox behaviour - return res; -} - -WebCore::DragOperation WebView::keyStateToDragOperation(DWORD grfKeyState) const -{ - if (!m_page) - return DragOperationNone; - - // Conforms to Microsoft's key combinations as documented for - // IDropTarget::DragOver. Note, grfKeyState is the current - // state of the keyboard modifier keys on the keyboard. See: - // <http://msdn.microsoft.com/en-us/library/ms680129(VS.85).aspx>. - DragOperation operation = m_page->dragSession().operation; - - if ((grfKeyState & (MK_CONTROL | MK_SHIFT)) == (MK_CONTROL | MK_SHIFT)) - operation = DragOperationLink; - else if ((grfKeyState & MK_CONTROL) == MK_CONTROL) - operation = DragOperationCopy; - else if ((grfKeyState & MK_SHIFT) == MK_SHIFT) - operation = DragOperationGeneric; - - return operation; -} - -HRESULT STDMETHODCALLTYPE WebView::DragEnter(IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) -{ - m_dragData = 0; - m_page->resetDragOperation(); - - if (m_dropTargetHelper) - m_dropTargetHelper->DragEnter(m_window, pDataObject, (POINT*)&pt, *pdwEffect); - - POINTL localpt = pt; - ::ScreenToClient(m_window, (LPPOINT)&localpt); - DragData data(pDataObject, IntPoint(localpt.x, localpt.y), IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState)); - m_page->dragEntered(&data); - *pdwEffect = dragOperationToDragCursor(m_page->dragSession().operation); - - m_lastDropEffect = *pdwEffect; - m_dragData = pDataObject; - - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebView::DragOver(DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) -{ - if (m_dropTargetHelper) - m_dropTargetHelper->DragOver((POINT*)&pt, *pdwEffect); - - if (m_dragData) { - POINTL localpt = pt; - ::ScreenToClient(m_window, (LPPOINT)&localpt); - DragData data(m_dragData.get(), IntPoint(localpt.x, localpt.y), IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState)); - m_page->dragUpdated(&data); - *pdwEffect = dragOperationToDragCursor(m_page->dragSession().operation); - } else - *pdwEffect = DROPEFFECT_NONE; - - m_lastDropEffect = *pdwEffect; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebView::DragLeave() -{ - if (m_dropTargetHelper) - m_dropTargetHelper->DragLeave(); - - if (m_dragData) { - DragData data(m_dragData.get(), IntPoint(), IntPoint(), DragOperationNone); - m_page->dragExited(&data); - m_dragData = 0; - m_page->resetDragOperation(); - } - return S_OK; -} - -static bool maybeCreateSandboxExtensionFromDragData(const DragData& dragData, SandboxExtension::Handle& sandboxExtensionHandle) -{ - if (!dragData.containsFiles()) - return false; - - // Unlike on Mac, we allow multiple files and directories, since on Windows - // we have actions for those (open the first file, open a Windows Explorer window). - - SandboxExtension::createHandle("\\", SandboxExtension::ReadOnly, sandboxExtensionHandle); - return true; -} - -HRESULT STDMETHODCALLTYPE WebView::Drop(IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect) -{ - if (m_dropTargetHelper) - m_dropTargetHelper->Drop(pDataObject, (POINT*)&pt, *pdwEffect); - - m_dragData = 0; - *pdwEffect = m_lastDropEffect; - POINTL localpt = pt; - ::ScreenToClient(m_window, (LPPOINT)&localpt); - DragData data(pDataObject, IntPoint(localpt.x, localpt.y), IntPoint(pt.x, pt.y), keyStateToDragOperation(grfKeyState)); - - SandboxExtension::Handle sandboxExtensionHandle; - bool createdExtension = maybeCreateSandboxExtensionFromDragData(data, sandboxExtensionHandle); - if (createdExtension) - m_page->process()->willAcquireUniversalFileReadSandboxExtension(); - SandboxExtension::HandleArray sandboxExtensionForUpload; - m_page->performDrag(&data, String(), sandboxExtensionHandle, sandboxExtensionForUpload); - return S_OK; -} - -#if ENABLE(FULLSCREEN_API) -FullScreenController* WebView::fullScreenController() -{ - if (!m_fullScreenController) - m_fullScreenController = adoptPtr(new FullScreenController(this)); - return m_fullScreenController.get(); -} - -HWND WebView::fullScreenClientWindow() const -{ - return m_window; -} - -HWND WebView::fullScreenClientParentWindow() const -{ - return ::GetParent(m_window); -} - -void WebView::fullScreenClientSetParentWindow(HWND hostWindow) -{ - setParentWindow(hostWindow); -} - -void WebView::fullScreenClientWillEnterFullScreen() -{ - page()->fullScreenManager()->willEnterFullScreen(); -} - -void WebView::fullScreenClientDidEnterFullScreen() -{ - page()->fullScreenManager()->didEnterFullScreen(); -} - -void WebView::fullScreenClientWillExitFullScreen() -{ - page()->fullScreenManager()->willExitFullScreen(); -} - -void WebView::fullScreenClientDidExitFullScreen() -{ - page()->fullScreenManager()->didExitFullScreen(); -} - -static void fullScreenClientForceRepaintCompleted(WKErrorRef, void* context) -{ - ASSERT(context); - static_cast<WebView*>(context)->fullScreenController()->repaintCompleted(); -} - -void WebView::fullScreenClientForceRepaint() -{ - page()->forceRepaint(VoidCallback::create(this, &fullScreenClientForceRepaintCompleted)); -} - -#endif -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/win/WebView.h b/Source/WebKit2/UIProcess/win/WebView.h deleted file mode 100644 index 565633125..000000000 --- a/Source/WebKit2/UIProcess/win/WebView.h +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebView_h -#define WebView_h - -#include "APIObject.h" -#include "CoalescedWindowGeometriesUpdater.h" -#include "PageClient.h" -#include "WKView.h" -#include "WebPageProxy.h" -#include "WebUndoClient.h" -#include <ShlObj.h> -#include <WebCore/COMPtr.h> -#include <WebCore/DragActions.h> -#include <WebCore/DragData.h> -#include <WebCore/WindowMessageListener.h> -#include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> - -#if ENABLE(FULLSCREEN_API) -#include <WebCore/FullScreenControllerClient.h> -#endif - -namespace WebCore { - class FullScreenController; -} - -interface IDropTargetHelper; - -namespace WebKit { - -class DrawingAreaProxy; - -class WebView - : public APIObject - , public PageClient - , WebCore::WindowMessageListener - , public IDropTarget -#if ENABLE(FULLSCREEN_API) - , WebCore::FullScreenControllerClient -#endif -{ -public: - static PassRefPtr<WebView> create(RECT rect, WebContext* context, WebPageGroup* pageGroup, HWND parentWindow) - { - RefPtr<WebView> webView = adoptRef(new WebView(rect, context, pageGroup, parentWindow)); - webView->initialize(); - return webView; - } - ~WebView(); - - HWND window() const { return m_window; } - void setParentWindow(HWND); - void windowAncestryDidChange(); - void setIsInWindow(bool); - void setIsVisible(bool); - void setOverrideCursor(HCURSOR); - void setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent&); - void setScrollOffsetOnNextResize(const WebCore::IntSize&); - void setFindIndicatorCallback(WKViewFindIndicatorCallback, void*); - WKViewFindIndicatorCallback getFindIndicatorCallback(void**); - bool pageOverlayInstalled() const { return m_pageOverlayInstalled; } - void initialize(); - - void initializeUndoClient(const WKViewUndoClient*); - void reapplyEditCommand(WebEditCommandProxy*); - void unapplyEditCommand(WebEditCommandProxy*); - - void setCustomDropTarget(IDropTarget*); - - // IUnknown - virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject); - virtual ULONG STDMETHODCALLTYPE AddRef(void); - virtual ULONG STDMETHODCALLTYPE Release(void); - - // IDropTarget - virtual HRESULT STDMETHODCALLTYPE DragEnter(IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect); - virtual HRESULT STDMETHODCALLTYPE DragOver(DWORD grfKeyState, POINTL pt, DWORD* pdwEffect); - virtual HRESULT STDMETHODCALLTYPE DragLeave(); - virtual HRESULT STDMETHODCALLTYPE Drop(IDataObject* pDataObject, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect); - - WebPageProxy* page() const { return m_page.get(); } - -#if ENABLE(FULLSCREEN_API) - WebCore::FullScreenController* fullScreenController(); -#endif - -private: - WebView(RECT, WebContext*, WebPageGroup*, HWND parentWindow); - - virtual Type type() const { return TypeView; } - - static bool registerWebViewWindowClass(); - static LRESULT CALLBACK WebViewWndProc(HWND, UINT, WPARAM, LPARAM); - LRESULT wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - LRESULT onMouseEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onWheelEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onHorizontalScroll(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onVerticalScroll(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onGestureNotify(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onGesture(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onKeyEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onPaintEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onPrintClientEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onSizeEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onWindowPositionChangedEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onSetFocusEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onKillFocusEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onTimerEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onShowWindowEvent(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - LRESULT onSetCursor(HWND hWnd, UINT message, WPARAM, LPARAM, bool& handled); - - void paint(HDC, const WebCore::IntRect& dirtyRect); - void setWasActivatedByMouseEvent(bool flag) { m_wasActivatedByMouseEvent = flag; } - bool onIMEStartComposition(); - bool onIMEComposition(LPARAM); - bool onIMEEndComposition(); - LRESULT onIMERequest(WPARAM, LPARAM); - bool onIMESelect(WPARAM, LPARAM); - bool onIMESetContext(WPARAM, LPARAM); - void resetIME(); - void setInputMethodState(bool); - HIMC getIMMContext(); - void prepareCandidateWindow(HIMC); - LRESULT onIMERequestCharPosition(IMECHARPOSITION*); - LRESULT onIMERequestReconvertString(RECONVERTSTRING*); - - void updateActiveState(); - void updateActiveStateSoon(); - - void initializeToolTipWindow(); - - void startTrackingMouseLeave(); - void stopTrackingMouseLeave(); - - bool shouldInitializeTrackPointHack(); - - void close(); - - HCURSOR cursorToShow() const; - void updateNativeCursor(); - - void updateChildWindowGeometries(); - - // PageClient - virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy(); - virtual void setViewNeedsDisplay(const WebCore::IntRect&); - virtual void displayView(); - virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); - - virtual WebCore::IntSize viewSize(); - virtual bool isViewWindowActive(); - virtual bool isViewFocused(); - virtual bool isViewVisible(); - virtual bool isViewInWindow(); - virtual void processDidCrash(); - virtual void didRelaunchProcess(); - virtual void pageClosed(); - virtual void toolTipChanged(const WTF::String&, const WTF::String&); - virtual void setCursor(const WebCore::Cursor&); - virtual void setCursorHiddenUntilMouseMoves(bool); - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); - virtual void registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo); - virtual void clearAllEditCommands(); - virtual bool canUndoRedo(WebPageProxy::UndoOrRedo); - virtual void executeUndoRedo(WebPageProxy::UndoOrRedo); - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&); - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&); - virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&); - virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&); - virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool wasEventHandled); - virtual void compositionSelectionChanged(bool); - virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*); - virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); -#if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorChooserProxy> createColorChooserProxy(WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&); -#endif - virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate); - virtual void didInstallOrUninstallPageOverlay(bool); - -#if USE(ACCELERATED_COMPOSITING) - virtual void enterAcceleratedCompositingMode(const LayerTreeContext&); - virtual void exitAcceleratedCompositingMode(); - virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); -#endif - - void didCommitLoadForMainFrame(bool useCustomRepresentation); - void didFinishLoadingDataForCustomRepresentation(const String& suggestedFilename, const CoreIPC::DataReference&); - virtual double customRepresentationZoomFactor(); - virtual void setCustomRepresentationZoomFactor(double); - WebCore::DragOperation keyStateToDragOperation(DWORD grfKeyState) const; - virtual void didChangeScrollbarsForMainFrame() const; - - virtual void findStringInCustomRepresentation(const String&, FindOptions, unsigned maxMatchCount); - virtual void countStringMatchesInCustomRepresentation(const String&, FindOptions, unsigned maxMatchCount); - - virtual HWND nativeWindow(); - virtual void scheduleChildWindowGeometryUpdate(const WindowGeometry&); - - virtual void setGestureReachedScrollingLimit(bool limitReached) { m_gestureReachedScrollingLimit = limitReached; } - - // WebCore::WindowMessageListener - virtual void windowReceivedMessage(HWND, UINT message, WPARAM, LPARAM); - -#if ENABLE(FULLSCREEN_API) - virtual HWND fullScreenClientWindow() const; - virtual HWND fullScreenClientParentWindow() const; - virtual void fullScreenClientSetParentWindow(HWND); - virtual void fullScreenClientWillEnterFullScreen(); - virtual void fullScreenClientDidEnterFullScreen(); - virtual void fullScreenClientWillExitFullScreen(); - virtual void fullScreenClientDidExitFullScreen(); - virtual void fullScreenClientForceRepaint(); -#endif - - HWND m_window; - HWND m_topLevelParentWindow; - HWND m_toolTipWindow; - - WebCore::IntSize m_nextResizeScrollOffset; - - HCURSOR m_lastCursorSet; - HCURSOR m_webCoreCursor; - HCURSOR m_overrideCursor; - - bool m_isInWindow; - bool m_isVisible; - bool m_wasActivatedByMouseEvent; - bool m_trackingMouseLeave; - bool m_isBeingDestroyed; - - RefPtr<WebPageProxy> m_page; - - unsigned m_inIMEComposition; - - WebUndoClient m_undoClient; - - WKViewFindIndicatorCallback m_findIndicatorCallback; - void* m_findIndicatorCallbackContext; - bool m_pageOverlayInstalled; - - COMPtr<IDataObject> m_dragData; - COMPtr<IDropTargetHelper> m_dropTargetHelper; - // FIXME: This variable is part of a workaround. The drop effect (pdwEffect) passed to Drop is incorrect. - // We set this variable in DragEnter and DragOver so that it can be used in Drop to set the correct drop effect. - // Thus, on return from DoDragDrop we have the correct pdwEffect for the drag-and-drop operation. - // (see https://bugs.webkit.org/show_bug.cgi?id=29264) - DWORD m_lastDropEffect; - - int m_lastPanX; - int m_lastPanY; - - int m_overPanY; - - bool m_gestureReachedScrollingLimit; - - CoalescedWindowGeometriesUpdater m_geometriesUpdater; - -#if ENABLE(FULLSCREEN_API) - OwnPtr<WebCore::FullScreenController> m_fullScreenController; -#endif - -#if USE(ACCELERATED_COMPOSITING) - HWND m_layerHostWindow; -#endif -}; - -} // namespace WebKit - -#endif // WebView_h |