diff options
author | Allan Sandfeld Jensen <allan.jensen@digia.com> | 2013-09-13 12:51:20 +0200 |
---|---|---|
committer | The Qt Project <gerrit-noreply@qt-project.org> | 2013-09-19 20:50:05 +0200 |
commit | d441d6f39bb846989d95bcf5caf387b42414718d (patch) | |
tree | e367e64a75991c554930278175d403c072de6bb8 /Source/WebKit2/UIProcess/API | |
parent | 0060b2994c07842f4c59de64b5e3e430525c4b90 (diff) | |
download | qtwebkit-d441d6f39bb846989d95bcf5caf387b42414718d.tar.gz |
Import Qt5x2 branch of QtWebkit for Qt 5.2
Importing a new snapshot of webkit.
Change-Id: I2d01ad12cdc8af8cb015387641120a9d7ea5f10c
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@digia.com>
Diffstat (limited to 'Source/WebKit2/UIProcess/API')
323 files changed, 14027 insertions, 7704 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/efl/WKPageEfl.h b/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.h new file mode 100644 index 000000000..77b9d140b --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.h @@ -0,0 +1,56 @@ +/* + * 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 WKPageEfl_h +#define WKPageEfl_h + +#include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> +#include <WebKit2/WKPopupItem.h> + +#ifdef __cplusplus +extern "C" { +#endif + +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 /* 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/WKIntentServiceInfo.h b/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.h index 121cffde8..b418ed526 100644 --- a/Source/WebKit2/UIProcess/API/C/WKIntentServiceInfo.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 WKIntentServiceInfo_h -#define WKIntentServiceInfo_h +#ifndef WKPopupItem_h +#define WKPopupItem_h #include <WebKit2/WKBase.h> @@ -32,15 +32,33 @@ 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); +enum { + kWKPopupItemTypeSeparator, + kWKPopupItemTypeItem +}; +typedef uint32_t WKPopupItemType; + +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 // WKIntentServiceInfo_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/API/C/win/WKAPICastWin.h b/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.h index 5b71cf303..b472dfb98 100644 --- a/Source/WebKit2/UIProcess/API/C/win/WKAPICastWin.h +++ b/Source/WebKit2/UIProcess/API/C/qt/WKIconDatabaseQt.h @@ -1,5 +1,6 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * 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 @@ -23,21 +24,16 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKAPICastWin_h -#define WKAPICastWin_h +#ifndef WKIconDatabaseQt_h +#define WKIconDatabaseQt_h -#ifndef WKAPICast_h -#error "Please #include \"WKAPICast.h\" instead of this file directly." -#endif +#include <WebKit2/WKBase.h> +#include <WebKit2/WKGeometry.h> -namespace WebKit { +QT_BEGIN_NAMESPACE +class QImage; +QT_END_NAMESPACE -class WebView; -class WebEditCommandProxy; +WK_EXPORT QImage WKIconDatabaseTryGetQImageForURL(WKIconDatabaseRef iconDatabase, WKURLRef url); -WK_ADD_API_MAPPING(WKViewRef, WebView) -WK_ADD_API_MAPPING(WKEditCommandRef, WebEditCommandProxy) - -} // namespace WebKit - -#endif // WKAPICastWin_h +#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/WKIntentData.h b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h index caf1b459f..0a7b4ff05 100644 --- a/Source/WebKit2/UIProcess/API/C/WKIntentData.h +++ b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h @@ -23,8 +23,8 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKIntentData_h -#define WKIntentData_h +#ifndef WKCookieManagerSoup_h +#define WKCookieManagerSoup_h #include <WebKit2/WKBase.h> @@ -32,17 +32,16 @@ extern "C" { #endif -WK_EXPORT WKTypeID WKIntentDataGetTypeID(); +enum { + kWKCookieStorageTypeText = 0, + kWKCookieStorageTypeSQLite = 1 +}; +typedef uint32_t WKCookieStorageType; -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); +WK_EXPORT void WKCookieManagerSetCookiePersistentStorage(WKCookieManagerRef cookieManager, WKStringRef storagePath, WKCookieStorageType storageType); #ifdef __cplusplus } #endif -#endif // WKIntentData_h +#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_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_intent_private.h deleted file mode 100644 index 199ec79c1..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent_private.h +++ /dev/null @@ -1,75 +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 ewk_intent_private_h -#define ewk_intent_private_h - -#if ENABLE(WEB_INTENTS) - -#include "WKEinaSharedString.h" -#include "WKIntentData.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 { -public: - EWK_OBJECT_DECLARE(EwkIntent) - - static PassRefPtr<EwkIntent> create(WKIntentDataRef intentRef) - { - return adoptRef(new EwkIntent(intentRef)); - } - - 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; - -private: - explicit EwkIntent(WKIntentDataRef intentRef); - - WKRetainPtr<WKIntentDataRef> m_wkIntent; - WKEinaSharedString m_action; - WKEinaSharedString m_type; - WKEinaSharedString m_service; -}; - -#endif // ENABLE(WEB_INTENTS) - -#endif // ewk_intent_private_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_intent_service_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_intent_service_private.h deleted file mode 100644 index 7a98a645d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_intent_service_private.h +++ /dev/null @@ -1,68 +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 ewk_intent_service_private_h -#define ewk_intent_service_private_h - -#if ENABLE(WEB_INTENTS_TAG) - -#include "WKEinaSharedString.h" -#include "WKIntentServiceInfo.h" -#include "ewk_object_private.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassRefPtr.h> - -/** - * \struct EwkIntentService - * @brief Contains the intent service data. - */ -class EwkIntentService : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkIntentService) - - static PassRefPtr<EwkIntentService> create(WKIntentServiceInfoRef serviceRef) - { - return adoptRef(new EwkIntentService(serviceRef)); - } - - const char* action() const; - const char* type() const; - const char* href() const; - const char* title() const; - const char* disposition() const; - -private: - explicit EwkIntentService(WKIntentServiceInfoRef serviceRef); - - WKEinaSharedString m_action; - WKEinaSharedString m_type; - WKEinaSharedString m_href; - WKEinaSharedString m_title; - WKEinaSharedString m_disposition; -}; - -#endif // ENABLE(WEB_INTENTS_TAG) - -#endif // ewk_intent_service_private_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_resource_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_page_group_private.h index df872c60a..3f922017d 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_resource_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,33 +23,39 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ewk_resource_private_h -#define ewk_resource_private_h +#ifndef ewk_page_group_private_h +#define ewk_page_group_private_h -#include "WKEinaSharedString.h" -#include "WKURL.h" #include "ewk_object_private.h" -#include <wtf/PassRefPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> +#include <Evas.h> +#include <WebKit2/WKBase.h> +#include <WebKit2/WKRetainPtr.h> +#include <WebKit2/WKURL.h> +#include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> -class EwkResource : public EwkObject { +class EwkView; + +class EwkPageGroup : public EwkObject { public: - EWK_OBJECT_DECLARE(EwkResource) + EWK_OBJECT_DECLARE(EwkPageGroup) + + static PassRefPtr<EwkPageGroup> findOrCreateWrapper(WKPageGroupRef pageGroupRef); + static PassRefPtr<EwkPageGroup> create(const String& identifier = String()); - static PassRefPtr<EwkResource> create(WKURLRef url, bool isMainResource) - { - return adoptRef(new EwkResource(url, isMainResource)); - } + ~EwkPageGroup(); - const char* url() const; - bool isMainResource() 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: - EwkResource(WKURLRef url, bool isMainResource); + explicit EwkPageGroup(WKPageGroupRef pageGroupRef); + + static const char defaultIdentifier[]; - WKEinaSharedString m_url; - bool m_isMainResource; + WKRetainPtr<WKPageGroupRef> m_pageGroupRef; }; -#endif // ewk_resource_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: |