diff options
author | Konstantin Tokarev <annulen@yandex.ru> | 2016-08-25 19:20:41 +0300 |
---|---|---|
committer | Konstantin Tokarev <annulen@yandex.ru> | 2017-02-02 12:30:55 +0000 |
commit | 6882a04fb36642862b11efe514251d32070c3d65 (patch) | |
tree | b7959826000b061fd5ccc7512035c7478742f7b0 /Source/WebKit2/UIProcess | |
parent | ab6df191029eeeb0b0f16f127d553265659f739e (diff) | |
download | qtwebkit-6882a04fb36642862b11efe514251d32070c3d65.tar.gz |
Imported QtWebKit TP3 (git b57bc6801f1876c3220d5a4bfea33d620d477443)
Change-Id: I3b1d8a2808782c9f34d50240000e20cb38d3680f
Reviewed-by: Konstantin Tokarev <annulen@yandex.ru>
Diffstat (limited to 'Source/WebKit2/UIProcess')
944 files changed, 27598 insertions, 94687 deletions
diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKAPICastGtk.h b/Source/WebKit2/UIProcess/API/APIAutomationClient.h index 9eb0c78ad..299581095 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKAPICastGtk.h +++ b/Source/WebKit2/UIProcess/API/APIAutomationClient.h @@ -1,6 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. + * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,19 +23,25 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKAPICastGtk_h -#define WKAPICastGtk_h +#ifndef APIAutomationClient_h +#define APIAutomationClient_h -#ifndef WKAPICast_h -#error "Please #include \"WKAPICast.h\" instead of this file directly." -#endif - -typedef struct _WebKitWebViewBase WebKitWebViewBase; +#include <wtf/Forward.h> namespace WebKit { +class WebProcessPool; +} -WK_ADD_API_MAPPING(WKViewRef, WebKitWebViewBase) +namespace API { -} +class AutomationClient { +public: + virtual ~AutomationClient() { } + + virtual bool allowsRemoteAutomation(WebKit::WebProcessPool*) { return false; } + virtual void didRequestAutomationSession(WebKit::WebProcessPool*, const WTF::String&) { } +}; + +} // namespace API -#endif // WKAPICastGtk_h +#endif // APIAutomationClient_h diff --git a/Source/WebKit2/UIProcess/API/APIAutomationSessionClient.h b/Source/WebKit2/UIProcess/API/APIAutomationSessionClient.h new file mode 100644 index 000000000..18edacb56 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIAutomationSessionClient.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2016 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 APIAutomationSessionClient_h +#define APIAutomationSessionClient_h + +#include <wtf/text/WTFString.h> + +namespace WebKit { +class WebAutomationSession; +class WebProcessPool; +} + +namespace API { + +class AutomationSessionClient { +public: + virtual ~AutomationSessionClient() { } + + virtual String sessionIdentifier() const { return String(); } + virtual void didRequestNewWindow(WebKit::WebProcessPool*, WebKit::WebAutomationSession*) { } +}; + +} // namespace API + +#endif // APIAutomationSessionClient_h diff --git a/Source/WebKit2/UIProcess/WebPageContextMenuClient.h b/Source/WebKit2/UIProcess/API/APIContextMenuClient.h index 442a0763d..f8f2023c1 100644 --- a/Source/WebKit2/UIProcess/WebPageContextMenuClient.h +++ b/Source/WebKit2/UIProcess/API/APIContextMenuClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2014 Igalia S.L. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,33 +23,44 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebPageContextMenuClient_h -#define WebPageContextMenuClient_h +#ifndef APIContextMenuClient_h +#define APIContextMenuClient_h #if ENABLE(CONTEXT_MENUS) -#include "APIClient.h" -#include "WebHitTestResult.h" -#include "WKPage.h" -#include <WebCore/IntPoint.h> +#include "WebHitTestResultData.h" +#include <wtf/RefPtr.h> #include <wtf/Vector.h> -namespace WebKit { +OBJC_CLASS NSMenu; + +namespace WebCore { +class IntPoint; +} -class APIObject; +namespace WebKit { +class WebContextMenuItem; class WebContextMenuItemData; class WebPageProxy; +} -class WebPageContextMenuClient : public APIClient<WKPageContextMenuClient, kWKPageContextMenuClientCurrentVersion> { +namespace API { + +class ContextMenuClient { public: - bool getContextMenuFromProposedMenu(WebPageProxy*, const Vector<WebContextMenuItemData>& proposedMenu, Vector<WebContextMenuItemData>& customMenu, const WebHitTestResult::Data&, APIObject* userData); - void customContextMenuItemSelected(WebPageProxy*, const WebContextMenuItemData&); - void contextMenuDismissed(WebPageProxy*); - bool showContextMenu(WebPageProxy*, const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); - bool hideContextMenu(WebPageProxy*); + virtual ~ContextMenuClient() { } + + virtual bool getContextMenuFromProposedMenu(WebKit::WebPageProxy&, const Vector<RefPtr<WebKit::WebContextMenuItem>>& /* proposedMenu */, Vector<RefPtr<WebKit::WebContextMenuItem>>& /* customMenu */, const WebKit::WebHitTestResultData&, API::Object* /* userData */) { return false; } + virtual void customContextMenuItemSelected(WebKit::WebPageProxy&, const WebKit::WebContextMenuItemData&) { } + virtual bool showContextMenu(WebKit::WebPageProxy&, const WebCore::IntPoint&, const Vector<RefPtr<WebKit::WebContextMenuItem>>&) { return false; } + virtual bool hideContextMenu(WebKit::WebPageProxy&) { return false; } + +#if PLATFORM(MAC) + virtual RetainPtr<NSMenu> menuFromProposedMenu(WebKit::WebPageProxy&, NSMenu *menu, const WebKit::WebHitTestResultData&, API::Object*) { return menu; } +#endif }; -} // namespace WebKit +} // namespace API #endif // ENABLE(CONTEXT_MENUS) -#endif // WebPageContextMenuClient_h +#endif // APIContextMenuClient_h diff --git a/Source/WebKit2/UIProcess/WebColorPickerResultListenerProxy.h b/Source/WebKit2/UIProcess/API/APIDiagnosticLoggingClient.h index d28eb8aa9..f54a0b1ad 100644 --- a/Source/WebKit2/UIProcess/WebColorPickerResultListenerProxy.h +++ b/Source/WebKit2/UIProcess/API/APIDiagnosticLoggingClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,7 +10,7 @@ * 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'' + * 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 @@ -23,44 +23,28 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebColorPickerResultListenerProxy_h -#define WebColorPickerResultListenerProxy_h +#ifndef APIDiagnosticLoggingClient_h +#define APIDiagnosticLoggingClient_h -#if ENABLE(INPUT_TYPE_COLOR) - -#include "APIObject.h" -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> +#include <WebCore/DiagnosticLoggingResultType.h> #include <wtf/text/WTFString.h> namespace WebKit { - class WebPageProxy; +} -class WebColorPickerResultListenerProxy : public APIObject { -public: - static const Type APIType = TypeColorPickerResultListener; - - static PassRefPtr<WebColorPickerResultListenerProxy> create(WebPageProxy* page) - { - return adoptRef(new WebColorPickerResultListenerProxy(page)); - } +namespace API { - virtual ~WebColorPickerResultListenerProxy(); - - void invalidate(); - void setColor(const String&); - -private: - explicit WebColorPickerResultListenerProxy(WebPageProxy*); - - virtual Type type() const { return APIType; } +class DiagnosticLoggingClient { +public: + virtual ~DiagnosticLoggingClient() { } - RefPtr<WebPageProxy> m_page; + virtual void logDiagnosticMessage(WebKit::WebPageProxy*, const WTF::String& message, const WTF::String& description) { UNUSED_PARAM(message); UNUSED_PARAM(description); } + virtual void logDiagnosticMessageWithResult(WebKit::WebPageProxy*, const WTF::String& message, const WTF::String& description, WebCore::DiagnosticLoggingResultType) { UNUSED_PARAM(message); UNUSED_PARAM(description); } + virtual void logDiagnosticMessageWithValue(WebKit::WebPageProxy*, const WTF::String& message, const WTF::String& description, const WTF::String& value) { UNUSED_PARAM(message); UNUSED_PARAM(description); UNUSED_PARAM(value); } }; -} // namespace WebKit +} // namespace API -#endif // ENABLE(INPUT_TYPE_COLOR) +#endif // APIDiagnosticLoggingClient_h -#endif // WebColorPickerResultListenerProxy_h diff --git a/Source/WebKit2/UIProcess/API/APIDownloadClient.h b/Source/WebKit2/UIProcess/API/APIDownloadClient.h new file mode 100644 index 000000000..2a7e3a6ba --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIDownloadClient.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2014 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 APIDownloadClient_h +#define APIDownloadClient_h + +#include <functional> +#include <wtf/text/WTFString.h> + +namespace WebCore { +class ResourceError; +class ResourceRequest; +class ResourceResponse; +} + +namespace WebKit { +class AuthenticationChallengeProxy; +class DownloadProxy; +class WebProcessPool; +class WebProtectionSpace; +} + +namespace API { + +class DownloadClient { +public: + virtual ~DownloadClient() { } + + virtual void didStart(WebKit::WebProcessPool*, WebKit::DownloadProxy*) { } + virtual void didReceiveAuthenticationChallenge(WebKit::WebProcessPool*, WebKit::DownloadProxy*, WebKit::AuthenticationChallengeProxy*) { } + virtual void didReceiveResponse(WebKit::WebProcessPool*, WebKit::DownloadProxy*, const WebCore::ResourceResponse&) { } + virtual void didReceiveData(WebKit::WebProcessPool*, WebKit::DownloadProxy*, uint64_t) { } + virtual bool shouldDecodeSourceDataOfMIMEType(WebKit::WebProcessPool*, WebKit::DownloadProxy*, const WTF::String&) { return true; } + virtual WTF::String decideDestinationWithSuggestedFilename(WebKit::WebProcessPool*, WebKit::DownloadProxy*, const WTF::String&, bool&) { return { }; } + virtual void didCreateDestination(WebKit::WebProcessPool*, WebKit::DownloadProxy*, const WTF::String&) { } + virtual void didFinish(WebKit::WebProcessPool*, WebKit::DownloadProxy*) { } + virtual void didFail(WebKit::WebProcessPool*, WebKit::DownloadProxy*, const WebCore::ResourceError&) { } + virtual void didCancel(WebKit::WebProcessPool*, WebKit::DownloadProxy*) { } + virtual void processDidCrash(WebKit::WebProcessPool*, WebKit::DownloadProxy*) { } + virtual bool canAuthenticateAgainstProtectionSpace(WebKit::WebProtectionSpace*) { return true; } + virtual void willSendRequest(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse&, std::function<void(const WebCore::ResourceRequest&)> callback) { callback(request); } +}; + +} // namespace API + +#endif // APIDownloadClient_h diff --git a/Source/WebKit2/UIProcess/API/APIFindClient.h b/Source/WebKit2/UIProcess/API/APIFindClient.h new file mode 100644 index 000000000..0abf8f673 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIFindClient.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2014 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 APIFindClient_h +#define APIFindClient_h + +#include <wtf/text/WTFString.h> + +namespace WebCore { +class IntRect; +} + +namespace WebKit { +class WebPageProxy; +} + +namespace API { + +class FindClient { +public: + virtual ~FindClient() { } + + virtual void didCountStringMatches(WebKit::WebPageProxy*, const WTF::String&, uint32_t) { } + virtual void didFindString(WebKit::WebPageProxy*, const WTF::String&, const Vector<WebCore::IntRect>& matchRects, uint32_t, int32_t) { } + virtual void didFailToFindString(WebKit::WebPageProxy*, const WTF::String&) { } +}; + +} // namespace API + +#endif // APIFindClient_h diff --git a/Source/WebKit2/UIProcess/API/APIFindMatchesClient.h b/Source/WebKit2/UIProcess/API/APIFindMatchesClient.h new file mode 100644 index 000000000..c6f457342 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIFindMatchesClient.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2015 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 APIFindMatchesClient_h +#define APIFindMatchesClient_h + +#include <WebCore/IntRect.h> +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace WebKit { +class WebImage; +class WebPageProxy; +} + +namespace API { + +class FindMatchesClient { +public: + virtual ~FindMatchesClient() { } + + virtual void didFindStringMatches(WebKit::WebPageProxy*, const WTF::String&, const WTF::Vector<WTF::Vector<WebCore::IntRect>>&, int32_t) { } + virtual void didGetImageForMatchResult(WebKit::WebPageProxy*, WebKit::WebImage*, int32_t) { } +}; + +} // namespace API + +#endif // APIFindMatchesClient_h diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxyClient.h b/Source/WebKit2/UIProcess/API/APIFormClient.h index 31646d2c8..44c005ba6 100644 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxyClient.h +++ b/Source/WebKit2/UIProcess/API/APIFormClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,24 +23,31 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebDatabaseManagerProxyClient_h -#define WebDatabaseManagerProxyClient_h +#ifndef APIFormClient_h +#define APIFormClient_h -#include "APIClient.h" -#include "WKDatabaseManager.h" +#include "WebFormSubmissionListenerProxy.h" #include <wtf/Forward.h> +#include <wtf/Vector.h> namespace WebKit { +class WebFrameProxy; +class WebPageProxy; +} -class WebDatabaseManagerProxy; -class WebSecurityOrigin; +namespace API { +class Object; -class WebDatabaseManagerProxyClient : public APIClient<WKDatabaseManagerClient, kWKDatabaseManagerClientCurrentVersion> { +class FormClient { public: - void didModifyOrigin(WebDatabaseManagerProxy*, WebSecurityOrigin*); - void didModifyDatabase(WebDatabaseManagerProxy*, WebSecurityOrigin*, const String& databaseIdentifier); + virtual ~FormClient() { } + + virtual void willSubmitForm(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, WebKit::WebFrameProxy&, const Vector<std::pair<WTF::String, WTF::String>>&, API::Object*, Ref<WebKit::WebFormSubmissionListenerProxy>&& listener) + { + listener->continueSubmission(); + } }; -} // namespace WebKit +} // namespace API -#endif // WebDatabaseManagerProxyClient_h +#endif // APIFormClient_h diff --git a/Source/WebKit2/UIProcess/API/APIFrameInfo.cpp b/Source/WebKit2/UIProcess/API/APIFrameInfo.cpp new file mode 100644 index 000000000..91dc42957 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIFrameInfo.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2015 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 "APIFrameInfo.h" + +#include "APIFrameHandle.h" +#include "WebFrameProxy.h" + +namespace API { + +// FIXME: This should use the full request of the frame, not just the URL. +FrameInfo::FrameInfo(const WebKit::WebFrameProxy& frame, const WebCore::SecurityOrigin& securityOrigin) + : m_isMainFrame(frame.isMainFrame()) + , m_request(WebCore::ResourceRequest(frame.url())) + , m_securityOrigin(adoptRef(*SecurityOrigin::create(securityOrigin).leakRef())) + , m_handle(API::FrameHandle::create(frame.frameID())) +{ +} + +FrameInfo::~FrameInfo() +{ +} + +} // namespace API diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.h b/Source/WebKit2/UIProcess/API/APIFrameInfo.h index 2ef7364dc..7a4796374 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.h +++ b/Source/WebKit2/UIProcess/API/APIFrameInfo.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,39 +23,47 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef EvasGLContext_h -#define EvasGLContext_h -#if USE(ACCELERATED_COMPOSITING) +#ifndef APIFrameInfo_h +#define APIFrameInfo_h -#include <Evas_GL.h> -#include <wtf/PassOwnPtr.h> +#include "APIObject.h" +#include <WebCore/ResourceRequest.h> + +namespace WebCore { +class SecurityOrigin; +} namespace WebKit { +class WebFrameProxy; +} + +namespace API { + +class FrameHandle; +class SecurityOrigin; -class EvasGLContext { +class FrameInfo final : public ObjectImpl<Object::Type::FrameInfo> { public: - static PassOwnPtr<EvasGLContext> create(Evas_GL* evasGL) + static Ref<FrameInfo> create(const WebKit::WebFrameProxy& frame, const WebCore::SecurityOrigin& securityOrigin) { - ASSERT(evasGL); - Evas_GL_Context* context = evas_gl_context_create(evasGL, 0); - if (!context) - return nullptr; - - // Ownership of context is passed to EvasGLContext. - return adoptPtr(new EvasGLContext(evasGL, context)); + return adoptRef(*new FrameInfo(frame, securityOrigin)); } - ~EvasGLContext(); + virtual ~FrameInfo(); - Evas_GL_Context* context() { return m_context; } + FrameInfo(const WebKit::WebFrameProxy&, const WebCore::SecurityOrigin&); -private: - EvasGLContext(Evas_GL* evasGL, Evas_GL_Context* passContext); + bool isMainFrame() const { return m_isMainFrame; } + const WebCore::ResourceRequest& request() const { return m_request; } + SecurityOrigin& securityOrigin() { return m_securityOrigin.get(); } + API::FrameHandle& handle() { return m_handle.get(); } - Evas_GL* m_evasGL; - Evas_GL_Context* m_context; +private: + bool m_isMainFrame; + WebCore::ResourceRequest m_request; + Ref<SecurityOrigin> m_securityOrigin; + Ref<FrameHandle> m_handle; }; -} // namespace WebKit +} // namespace API -#endif // USE(ACCELERATED_COMPOSITING) -#endif // EvasGLContext_h +#endif // APIFrameInfo_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings_private.h b/Source/WebKit2/UIProcess/API/APIHistoryClient.h index 0b85d9b2f..77fca2656 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings_private.h +++ b/Source/WebKit2/UIProcess/API/APIHistoryClient.h @@ -1,6 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2014, 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,37 +23,28 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ewk_settings_private_h -#define ewk_settings_private_h +#ifndef APIHistoryClient_h +#define APIHistoryClient_h -#include <wtf/PassOwnPtr.h> +#include <wtf/Forward.h> namespace WebKit { -class WebPreferences; +class WebPageProxy; +struct WebNavigationDataStore; } -class EwkView; -/** - * \struct Ewk_Settings - * @brief Contains the settings data. - */ -class EwkSettings { + +namespace API { + +class HistoryClient { public: - static PassOwnPtr<EwkSettings> create(EwkView* viewImpl) - { - return adoptPtr(new EwkSettings(viewImpl)); - } - - const WebKit::WebPreferences* preferences() const; - WebKit::WebPreferences* preferences(); - -private: - explicit EwkSettings(EwkView* viewImpl) - : m_view(viewImpl) - { - ASSERT(m_view); - } - - EwkView* m_view; + virtual ~HistoryClient() { } + + virtual void didNavigateWithNavigationData(WebKit::WebPageProxy&, const WebKit::WebNavigationDataStore&) { } + virtual void didPerformClientRedirect(WebKit::WebPageProxy&, const WTF::String&, const WTF::String&) { } + virtual void didPerformServerRedirect(WebKit::WebPageProxy&, const WTF::String&, const WTF::String&) { } + virtual void didUpdateHistoryTitle(WebKit::WebPageProxy&, const WTF::String&, const WTF::String&) { } }; -#endif // ewk_settings_private_h +} // namespace API + +#endif // APIHistoryClient_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadClient.h b/Source/WebKit2/UIProcess/API/APIHitTestResult.cpp index c2566e897..4d4e06234 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadClient.h +++ b/Source/WebKit2/UIProcess/API/APIHitTestResult.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -17,11 +17,16 @@ * Boston, MA 02110-1301, USA. */ -#ifndef WebKitDownloadClient_h -#define WebKitDownloadClient_h +#include "config.h" +#include "APIHitTestResult.h" -#include "WebKitWebContext.h" +using namespace WebCore; -void attachDownloadClientToContext(WebKitWebContext*); +namespace API { -#endif +PassRefPtr<HitTestResult> HitTestResult::create(const WebKit::WebHitTestResultData& hitTestResultData) +{ + return adoptRef(new HitTestResult(hitTestResultData)); +} + +} // namespace API diff --git a/Source/WebKit2/UIProcess/API/APIHitTestResult.h b/Source/WebKit2/UIProcess/API/APIHitTestResult.h new file mode 100644 index 000000000..709579a6b --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIHitTestResult.h @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifndef APIHitTestResult_h +#define APIHitTestResult_h + +#include "APIObject.h" +#include "SharedMemory.h" +#include "WebHitTestResultData.h" +#include <WebCore/DictionaryPopupInfo.h> +#include <WebCore/FloatPoint.h> +#include <WebCore/IntRect.h> +#include <WebCore/PageOverlay.h> +#include <wtf/Forward.h> +#include <wtf/PassRefPtr.h> +#include <wtf/RefPtr.h> +#include <wtf/text/WTFString.h> + +OBJC_CLASS DDActionContext; + +namespace IPC { +class ArgumentDecoder; +class ArgumentEncoder; +} + +namespace WebCore { +class HitTestResult; +} + +namespace API { + +class WebFrame; + +class HitTestResult : public API::ObjectImpl<API::Object::Type::HitTestResult> { +public: + static PassRefPtr<HitTestResult> create(const WebKit::WebHitTestResultData&); + + WTF::String absoluteImageURL() const { return m_data.absoluteImageURL; } + WTF::String absolutePDFURL() const { return m_data.absolutePDFURL; } + WTF::String absoluteLinkURL() const { return m_data.absoluteLinkURL; } + WTF::String absoluteMediaURL() const { return m_data.absoluteMediaURL; } + + WTF::String linkLabel() const { return m_data.linkLabel; } + WTF::String linkTitle() const { return m_data.linkTitle; } + WTF::String lookupText() const { return m_data.lookupText; } + + bool isContentEditable() const { return m_data.isContentEditable; } + + WebCore::IntRect elementBoundingBox() const { return m_data.elementBoundingBox; } + + bool isScrollbar() const { return m_data.isScrollbar; } + + bool isSelected() const { return m_data.isSelected; } + + bool isTextNode() const { return m_data.isTextNode; } + + bool isOverTextInsideFormControlElement() const { return m_data.isOverTextInsideFormControlElement; } + + bool allowsCopy() const { return m_data.allowsCopy; } + + bool isDownloadableMedia() const { return m_data.isDownloadableMedia; } + +private: + explicit HitTestResult(const WebKit::WebHitTestResultData& hitTestResultData) + : m_data(hitTestResultData) + { + } + + WebKit::WebHitTestResultData m_data; +}; + +} // namespace API + +#endif // APIHitTestResult_h diff --git a/Source/WebKit2/UIProcess/WebHistoryClient.h b/Source/WebKit2/UIProcess/API/APILegacyContextHistoryClient.h index daaea4f4e..cbb9e0a97 100644 --- a/Source/WebKit2/UIProcess/WebHistoryClient.h +++ b/Source/WebKit2/UIProcess/API/APILegacyContextHistoryClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,31 +23,32 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebHistoryClient_h -#define WebHistoryClient_h +#ifndef APILegacyContextHistoryClient_h +#define APILegacyContextHistoryClient_h -#include "APIClient.h" -#include "WKContext.h" #include <wtf/Forward.h> namespace WebKit { - -class WebContext; class WebFrameProxy; class WebPageProxy; +class WebProcessPool; struct WebNavigationDataStore; +} -class WebHistoryClient : public APIClient<WKContextHistoryClient, kWKContextHistoryClientCurrentVersion> { -public: - void didNavigateWithNavigationData(WebContext*, WebPageProxy*, const WebNavigationDataStore&, WebFrameProxy*); - void didPerformClientRedirect(WebContext*, WebPageProxy*, const String& sourceURL, const String& destinationURL, WebFrameProxy*); - void didPerformServerRedirect(WebContext*, WebPageProxy*, const String& sourceURL, const String& destinationURL, WebFrameProxy*); - void didUpdateHistoryTitle(WebContext*, WebPageProxy*, const String& title, const String& url, WebFrameProxy*); - void populateVisitedLinks(WebContext*); +namespace API { - bool shouldTrackVisitedLinks() const { return m_client.populateVisitedLinks; } +class LegacyContextHistoryClient { +public: + virtual ~LegacyContextHistoryClient() { } + + virtual void didNavigateWithNavigationData(WebKit::WebProcessPool&, WebKit::WebPageProxy&, const WebKit::WebNavigationDataStore&, WebKit::WebFrameProxy&) { } + virtual void didPerformClientRedirect(WebKit::WebProcessPool&, WebKit::WebPageProxy&, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy&) { } + virtual void didPerformServerRedirect(WebKit::WebProcessPool&, WebKit::WebPageProxy&, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy&) { } + virtual void didUpdateHistoryTitle(WebKit::WebProcessPool&, WebKit::WebPageProxy&, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy&) { } + virtual void populateVisitedLinks(WebKit::WebProcessPool&) { } + virtual bool addsVisitedLinks() const { return false; } }; -} // namespace WebKit +} // namespace API -#endif // WebHistoryClient_h +#endif // APILegacyContextHistoryClient_h diff --git a/Source/WebKit2/UIProcess/API/APILoaderClient.h b/Source/WebKit2/UIProcess/API/APILoaderClient.h new file mode 100644 index 000000000..eff556ae8 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APILoaderClient.h @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2014 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 APILoaderClient_h +#define APILoaderClient_h + +#include "APIData.h" +#include "PluginModuleInfo.h" +#include "SameDocumentNavigationType.h" +#include <WebCore/FrameLoaderTypes.h> +#include <WebCore/LayoutMilestones.h> +#include <wtf/Forward.h> + +namespace WebCore { +class ResourceError; +} + +namespace WebKit { +class AuthenticationChallengeProxy; +class QuickLookDocumentData; +class WebBackForwardListItem; +class WebFrameProxy; +class WebPageProxy; +class WebProtectionSpace; +struct WebNavigationDataStore; +} + +namespace API { + +class Dictionary; +class Navigation; +class Object; + +class LoaderClient { +public: + virtual ~LoaderClient() { } + + virtual void didStartProvisionalLoadForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, API::Object*) { } + virtual void didReceiveServerRedirectForProvisionalLoadForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, API::Object*) { } + virtual void didFailProvisionalLoadWithErrorForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, const WebCore::ResourceError&, API::Object*) { } + virtual void didCommitLoadForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, API::Object*) { } + virtual void didFinishDocumentLoadForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, API::Object*) { } + virtual void didFinishLoadForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, API::Object*) { } + virtual void didFailLoadWithErrorForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, const WebCore::ResourceError&, API::Object*) { } + virtual void didSameDocumentNavigationForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, WebKit::SameDocumentNavigationType, API::Object*) { } + virtual void didReceiveTitleForFrame(WebKit::WebPageProxy&, const WTF::String&, WebKit::WebFrameProxy&, API::Object*) { } + virtual void didFirstLayoutForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Object*) { } + + // FIXME: We should consider removing didFirstVisuallyNonEmptyLayoutForFrame since it is replaced by didLayout. + virtual void didFirstVisuallyNonEmptyLayoutForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Object*) { } + + virtual void didDisplayInsecureContentForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Object*) { } + virtual void didRunInsecureContentForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Object*) { } + virtual void didDetectXSSForFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Object*) { } + + virtual void didLayout(WebKit::WebPageProxy&, WebCore::LayoutMilestones) { } + + virtual bool canAuthenticateAgainstProtectionSpaceInFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, WebKit::WebProtectionSpace*) { return false; } + virtual void didReceiveAuthenticationChallengeInFrame(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, WebKit::AuthenticationChallengeProxy*) { } + + virtual void didStartProgress(WebKit::WebPageProxy&) { } + virtual void didChangeProgress(WebKit::WebPageProxy&) { } + virtual void didFinishProgress(WebKit::WebPageProxy&) { } + + // FIXME: These functions should not be part of this client. + virtual void processDidBecomeUnresponsive(WebKit::WebPageProxy&) { } + virtual void processDidBecomeResponsive(WebKit::WebPageProxy&) { } + virtual void processDidCrash(WebKit::WebPageProxy&) { } + + virtual void didChangeBackForwardList(WebKit::WebPageProxy&, WebKit::WebBackForwardListItem*, Vector<RefPtr<WebKit::WebBackForwardListItem>>) { } + virtual bool shouldKeepCurrentBackForwardListItemInList(WebKit::WebPageProxy&, WebKit::WebBackForwardListItem*) { return true; } + virtual void willGoToBackForwardListItem(WebKit::WebPageProxy&, WebKit::WebBackForwardListItem*, API::Object*) { } + + virtual RefPtr<Data> webCryptoMasterKey(WebKit::WebPageProxy&) { return nullptr; } + + virtual void didNavigateWithNavigationData(WebKit::WebPageProxy&, const WebKit::WebNavigationDataStore&, WebKit::WebFrameProxy&) { } + virtual void didPerformClientRedirect(WebKit::WebPageProxy&, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy&) { } + virtual void didPerformServerRedirect(WebKit::WebPageProxy&, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy&) { } + virtual void didUpdateHistoryTitle(WebKit::WebPageProxy&, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy&) { } + + virtual void navigationGestureDidBegin(WebKit::WebPageProxy&) { } + virtual void navigationGestureWillEnd(WebKit::WebPageProxy&, bool willNavigate, WebKit::WebBackForwardListItem&) { } + virtual void navigationGestureDidEnd(WebKit::WebPageProxy&, bool willNavigate, WebKit::WebBackForwardListItem&) { } + +#if ENABLE(NETSCAPE_PLUGIN_API) + virtual WebKit::PluginModuleLoadPolicy pluginLoadPolicy(WebKit::WebPageProxy&, WebKit::PluginModuleLoadPolicy currentPluginLoadPolicy, API::Dictionary*, WTF::String& /* unavailabilityDescription */) { return currentPluginLoadPolicy; } + virtual void didFailToInitializePlugin(WebKit::WebPageProxy&, API::Dictionary*) { } + virtual void didBlockInsecurePluginVersion(WebKit::WebPageProxy&, API::Dictionary*) { } +#endif // ENABLE(NETSCAPE_PLUGIN_API) + +#if ENABLE(WEBGL) + virtual WebCore::WebGLLoadPolicy webGLLoadPolicy(WebKit::WebPageProxy&, const WTF::String&) const { return WebCore::WebGLLoadPolicy::WebGLAllowCreation; } + virtual WebCore::WebGLLoadPolicy resolveWebGLLoadPolicy(WebKit::WebPageProxy&, const WTF::String&) const { return WebCore::WebGLLoadPolicy::WebGLAllowCreation; } +#endif // ENABLE(WEBGL) + +#if USE(QUICK_LOOK) + virtual void didStartLoadForQuickLookDocumentInMainFrame(const WTF::String& fileName, const WTF::String& uti) { } + virtual void didFinishLoadForQuickLookDocumentInMainFrame(const WebKit::QuickLookDocumentData&) { } +#endif +}; + +} // namespace API + +#endif // APILoaderClient_h diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.cpp b/Source/WebKit2/UIProcess/API/APINavigation.cpp index 862ddbb39..1a80b04ce 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLContext.cpp +++ b/Source/WebKit2/UIProcess/API/APINavigation.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,25 +24,25 @@ */ #include "config.h" +#include "APINavigation.h" -#if USE(ACCELERATED_COMPOSITING) +#include "WebNavigationState.h" -#include "EvasGLContext.h" +namespace API { -namespace WebKit { +Navigation::Navigation(WebKit::WebNavigationState& state) + : m_navigationID(state.generateNavigationID()) +{ +} -EvasGLContext::EvasGLContext(Evas_GL* evasGL, Evas_GL_Context* passContext) - : m_evasGL(evasGL) - , m_context(passContext) +Navigation::Navigation(WebKit::WebNavigationState& state, const WebCore::ResourceRequest& request) + : m_navigationID(state.generateNavigationID()) + , m_request(request) { - ASSERT(evasGL); - ASSERT(passContext); } -EvasGLContext::~EvasGLContext() +Navigation::~Navigation() { - evas_gl_context_destroy(m_evasGL, m_context); } } // namespace WebKit -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequestPrivate.h b/Source/WebKit2/UIProcess/API/APINavigation.h index 12586153b..a014898c1 100644 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequestPrivate.h +++ b/Source/WebKit2/UIProcess/API/APINavigation.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Igalia S.L. + * Copyright (C) 2015 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,13 +23,46 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebKitURIRequestPrivate_h -#define WebKitURIRequestPrivate_h +#ifndef APINavigation_h +#define APINavigation_h -#include "WebKitURIRequest.h" +#include "APIObject.h" #include <WebCore/ResourceRequest.h> +#include <wtf/Ref.h> -WebKitURIRequest* webkitURIRequestCreateForResourceRequest(const WebCore::ResourceRequest&); -void webkitURIRequestGetResourceRequest(WebKitURIRequest*, WebCore::ResourceRequest&); +namespace WebKit { +class WebNavigationState; +} -#endif // WebKitURIRequestPrivate_h +namespace API { + +class Navigation : public ObjectImpl<Object::Type::Navigation> { +public: + static Ref<Navigation> create(WebKit::WebNavigationState& state) + { + return adoptRef(*new Navigation(state)); + } + + static Ref<Navigation> create(WebKit::WebNavigationState& state, const WebCore::ResourceRequest& request) + { + return adoptRef(*new Navigation(state, request)); + } + + virtual ~Navigation(); + + uint64_t navigationID() const { return m_navigationID; } + + const WebCore::ResourceRequest& request() const { return m_request; } + +private: + explicit Navigation(WebKit::WebNavigationState&); + explicit Navigation(WebKit::WebNavigationState&, const WebCore::ResourceRequest&); + + uint64_t m_navigationID; + WebCore::ResourceRequest m_request; +}; + +} // namespace API + + +#endif // APINavigation_h diff --git a/Source/WebKit2/UIProcess/API/APINavigationAction.h b/Source/WebKit2/UIProcess/API/APINavigationAction.h new file mode 100644 index 000000000..5ab91b274 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APINavigationAction.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2015 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 APINavigationAction_h +#define APINavigationAction_h + +#include "APIFrameInfo.h" +#include "APIObject.h" +#include "NavigationActionData.h" +#include <WebCore/ResourceRequest.h> +#include <WebCore/URL.h> + +namespace API { + +class FrameInfo; + +class NavigationAction final : public ObjectImpl<Object::Type::NavigationAction> { +public: + static Ref<NavigationAction> create(const WebKit::NavigationActionData& navigationActionData, API::FrameInfo* sourceFrame, API::FrameInfo* targetFrame, const WebCore::ResourceRequest& request, const WebCore::URL& originalURL, bool shouldOpenAppLinks) + { + return adoptRef(*new NavigationAction(navigationActionData, sourceFrame, targetFrame, request, originalURL, shouldOpenAppLinks)); + } + + NavigationAction(const WebKit::NavigationActionData& navigationActionData, API::FrameInfo* sourceFrame, API::FrameInfo* targetFrame, const WebCore::ResourceRequest& request, const WebCore::URL& originalURL, bool shouldOpenAppLinks) + : m_sourceFrame(sourceFrame) + , m_targetFrame(targetFrame) + , m_request(request) + , m_originalURL(originalURL) + , m_shouldOpenAppLinks(shouldOpenAppLinks) + , m_navigationActionData(navigationActionData) + { + } + + FrameInfo* sourceFrame() const { return m_sourceFrame.get(); } + FrameInfo* targetFrame() const { return m_targetFrame.get(); } + + const WebCore::ResourceRequest& request() const { return m_request; } + const WebCore::URL& originalURL() const { return m_originalURL; } + + WebCore::NavigationType navigationType() const { return m_navigationActionData.navigationType; } + WebKit::WebEvent::Modifiers modifiers() const { return m_navigationActionData.modifiers; } + WebKit::WebMouseEvent::Button mouseButton() const { return m_navigationActionData.mouseButton; } + bool isProcessingUserGesture() const { return m_navigationActionData.isProcessingUserGesture; } + bool canHandleRequest() const { return m_navigationActionData.canHandleRequest; } + bool shouldOpenExternalSchemes() const { return m_navigationActionData.shouldOpenExternalURLsPolicy == WebCore::ShouldOpenExternalURLsPolicy::ShouldAllow || m_navigationActionData.shouldOpenExternalURLsPolicy == WebCore::ShouldOpenExternalURLsPolicy::ShouldAllowExternalSchemes; } + bool shouldOpenAppLinks() const { return m_shouldOpenAppLinks && m_navigationActionData.shouldOpenExternalURLsPolicy == WebCore::ShouldOpenExternalURLsPolicy::ShouldAllow; } + +private: + RefPtr<FrameInfo> m_sourceFrame; + RefPtr<FrameInfo> m_targetFrame; + + WebCore::ResourceRequest m_request; + WebCore::URL m_originalURL; + + bool m_shouldOpenAppLinks; + + WebKit::NavigationActionData m_navigationActionData; +}; + +} // namespace API + +#endif // APINavigationAction_h diff --git a/Source/WebKit2/UIProcess/API/APINavigationClient.h b/Source/WebKit2/UIProcess/API/APINavigationClient.h new file mode 100644 index 000000000..fb5a26785 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APINavigationClient.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2014, 2015 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 APINavigationClient_h +#define APINavigationClient_h + +#include "APIData.h" +#include "PluginModuleInfo.h" +#include "SameDocumentNavigationType.h" +#include "WebEvent.h" +#include "WebFramePolicyListenerProxy.h" +#include <WebCore/FrameLoaderTypes.h> +#include <WebCore/LayoutMilestones.h> +#include <wtf/Forward.h> + +namespace WebCore { +class ResourceError; +class ResourceRequest; +class ResourceResponse; +struct SecurityOriginData; +} + +namespace WebKit { +class AuthenticationChallengeProxy; +class QuickLookDocumentData; +class WebBackForwardListItem; +class WebFramePolicyListenerProxy; +class WebFrameProxy; +class WebPageProxy; +class WebProtectionSpace; +struct NavigationActionData; +struct WebNavigationDataStore; +} + +namespace API { + +class Dictionary; +class Navigation; +class NavigationAction; +class NavigationResponse; +class Object; + +class NavigationClient { +public: + virtual ~NavigationClient() { } + + virtual void didStartProvisionalNavigation(WebKit::WebPageProxy&, API::Navigation*, API::Object*) { } + virtual void didReceiveServerRedirectForProvisionalNavigation(WebKit::WebPageProxy&, API::Navigation*, API::Object*) { } + virtual void didFailProvisionalNavigationWithError(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, const WebCore::ResourceError&, API::Object*) { } + virtual void didFailProvisionalLoadInSubframeWithError(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, const WebCore::SecurityOriginData&, API::Navigation*, const WebCore::ResourceError&, API::Object*) { } + virtual void didCommitNavigation(WebKit::WebPageProxy&, API::Navigation*, API::Object*) { } + virtual void didFinishDocumentLoad(WebKit::WebPageProxy&, API::Navigation*, API::Object*) { } + virtual void didFinishNavigation(WebKit::WebPageProxy&, API::Navigation*, API::Object*) { } + virtual void didFailNavigationWithError(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, API::Navigation*, const WebCore::ResourceError&, API::Object*) { } + virtual void didSameDocumentNavigation(WebKit::WebPageProxy&, API::Navigation*, WebKit::SameDocumentNavigationType, API::Object*) { } + + virtual void renderingProgressDidChange(WebKit::WebPageProxy&, WebCore::LayoutMilestones) { } + + virtual bool canAuthenticateAgainstProtectionSpace(WebKit::WebPageProxy&, WebKit::WebProtectionSpace*) { return false; } + virtual void didReceiveAuthenticationChallenge(WebKit::WebPageProxy&, WebKit::AuthenticationChallengeProxy*) { } + + // FIXME: These function should not be part of this client. + virtual void processDidCrash(WebKit::WebPageProxy&) { } + virtual void processDidBecomeResponsive(WebKit::WebPageProxy&) { } + virtual void processDidBecomeUnresponsive(WebKit::WebPageProxy&) { } + + virtual RefPtr<Data> webCryptoMasterKey(WebKit::WebPageProxy&) { return nullptr; } + +#if USE(QUICK_LOOK) + virtual void didStartLoadForQuickLookDocumentInMainFrame(const WTF::String& fileName, const WTF::String& uti) { } + virtual void didFinishLoadForQuickLookDocumentInMainFrame(const WebKit::QuickLookDocumentData&) { } +#endif + + virtual void decidePolicyForNavigationAction(WebKit::WebPageProxy&, API::NavigationAction&, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object*) + { + listener->use(); + } + + virtual void decidePolicyForNavigationResponse(WebKit::WebPageProxy&, API::NavigationResponse&, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object*) + { + listener->use(); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + virtual WebKit::PluginModuleLoadPolicy decidePolicyForPluginLoad(WebKit::WebPageProxy&, WebKit::PluginModuleLoadPolicy currentPluginLoadPolicy, API::Dictionary*, WTF::String&) + { + return currentPluginLoadPolicy; + } +#endif + + virtual void didBeginNavigationGesture(WebKit::WebPageProxy&) { } + virtual void willEndNavigationGesture(WebKit::WebPageProxy&, bool willNavigate, WebKit::WebBackForwardListItem&) { } + virtual void didEndNavigationGesture(WebKit::WebPageProxy&, bool willNavigate, WebKit::WebBackForwardListItem&) { } + virtual void didRemoveNavigationGestureSnapshot(WebKit::WebPageProxy&) { } +}; + +} // namespace API + +#endif // APINavigationClient_h diff --git a/Source/WebKit2/UIProcess/WebNavigationData.cpp b/Source/WebKit2/UIProcess/API/APINavigationData.cpp index eefc7d096..7415e5358 100644 --- a/Source/WebKit2/UIProcess/WebNavigationData.cpp +++ b/Source/WebKit2/UIProcess/API/APINavigationData.cpp @@ -24,16 +24,16 @@ */ #include "config.h" -#include "WebNavigationData.h" +#include "APINavigationData.h" -namespace WebKit { +namespace API { -WebNavigationData::WebNavigationData(const WebNavigationDataStore& store) +NavigationData::NavigationData(const WebKit::WebNavigationDataStore& store) : m_store(store) { } -WebNavigationData::~WebNavigationData() +NavigationData::~NavigationData() { } diff --git a/Source/WebKit2/UIProcess/WebNavigationData.h b/Source/WebKit2/UIProcess/API/APINavigationData.h index 297485f5a..01c4c8b8d 100644 --- a/Source/WebKit2/UIProcess/WebNavigationData.h +++ b/Source/WebKit2/UIProcess/API/APINavigationData.h @@ -23,34 +23,35 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebNavigationData_h -#define WebNavigationData_h +#ifndef APINavigationData_h +#define APINavigationData_h #include "APIObject.h" #include "WebNavigationDataStore.h" #include <wtf/PassRefPtr.h> -namespace WebKit { +namespace API { -class WebNavigationData : public TypedAPIObject<APIObject::TypeNavigationData> { +class NavigationData : public ObjectImpl<Object::Type::NavigationData> { public: - static PassRefPtr<WebNavigationData> create(const WebNavigationDataStore& store) + static Ref<NavigationData> create(const WebKit::WebNavigationDataStore& store) { - return adoptRef(new WebNavigationData(store)); + return adoptRef(*new NavigationData(store)); } - virtual ~WebNavigationData(); + virtual ~NavigationData(); - String title() const { return m_store.title; } - String url() const { return m_store.url; } + WTF::String title() const { return m_store.title; } + WTF::String url() const { return m_store.url; } const WebCore::ResourceRequest& originalRequest() const { return m_store.originalRequest; } + const WebCore::ResourceResponse& response() const { return m_store.response; } private: - explicit WebNavigationData(const WebNavigationDataStore&); + explicit NavigationData(const WebKit::WebNavigationDataStore&); - WebNavigationDataStore m_store; + WebKit::WebNavigationDataStore m_store; }; -} // namespace WebKit +} // namespace API -#endif // WebNavigationData_h +#endif // APINavigationData_h diff --git a/Source/WebKit2/UIProcess/efl/EwkTouchEvent.h b/Source/WebKit2/UIProcess/API/APINavigationResponse.h index 312c3d05b..75c456f53 100644 --- a/Source/WebKit2/UIProcess/efl/EwkTouchEvent.h +++ b/Source/WebKit2/UIProcess/API/APINavigationResponse.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * Copyright (C) 2015 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,46 +23,48 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef EwkTouchEvent_h -#define EwkTouchEvent_h - -#if ENABLE(TOUCH_EVENTS) +#ifndef APINavigationResponse_h +#define APINavigationResponse_h +#include "APIFrameInfo.h" #include "APIObject.h" -#include "WKArray.h" -#include "WKEventEfl.h" -#include "WKRetainPtr.h" -#include <wtf/PassRefPtr.h> +#include <WebCore/ResourceRequest.h> +#include <WebCore/ResourceResponse.h> + +namespace API { -namespace WebKit { +class FrameInfo; -class EwkTouchEvent : public APIObject { +class NavigationResponse final : public ObjectImpl<Object::Type::NavigationResponse> { public: - static const APIObject::Type APIType = TypeTouchEvent; + static Ref<NavigationResponse> create(API::FrameInfo& frame, const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, bool canShowMIMEType) + { + return adoptRef(*new NavigationResponse(frame, request, response, canShowMIMEType)); + } - static PassRefPtr<EwkTouchEvent> create(WKEventType type, WKArrayRef touchPoints, WKEventModifiers modifiers, double timestamp) + NavigationResponse(API::FrameInfo& frame, const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, bool canShowMIMEType) + : m_frame(frame) + , m_request(request) + , m_response(response) + , m_canShowMIMEType(canShowMIMEType) { - return adoptRef(new EwkTouchEvent(type, touchPoints, modifiers, timestamp)); } - WKEventType eventType() const { return m_eventType; } - WKArrayRef touchPoints() const { return m_touchPoints.get(); } - WKEventModifiers modifiers() const { return m_modifiers; } - double timestamp() const { return m_timestamp; } + FrameInfo& frame() { return m_frame.get(); } -private: - EwkTouchEvent(WKEventType, WKArrayRef, WKEventModifiers, double timestamp); + const WebCore::ResourceRequest& request() const { return m_request; } + const WebCore::ResourceResponse& response() const { return m_response; } - virtual APIObject::Type type() const { return APIType; } + bool canShowMIMEType() const { return m_canShowMIMEType; } - WKEventType m_eventType; - WKRetainPtr<WKArrayRef> m_touchPoints; - WKEventModifiers m_modifiers; - double m_timestamp; -}; +private: + Ref<FrameInfo> m_frame; -} // namespace WebKit + WebCore::ResourceRequest m_request; + WebCore::ResourceResponse m_response; + bool m_canShowMIMEType; +}; -#endif // ENABLE(TOUCH_EVENTS) +} // namespace API -#endif /* EwkTouchEvent_h */ +#endif // APINavigationResponse_h diff --git a/Source/WebKit2/UIProcess/API/APIPageConfiguration.cpp b/Source/WebKit2/UIProcess/API/APIPageConfiguration.cpp new file mode 100644 index 000000000..f2fc3b801 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIPageConfiguration.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2015 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 "APIPageConfiguration.h" + +#include "APIProcessPoolConfiguration.h" +#include "WebPageGroup.h" +#include "WebPageProxy.h" +#include "WebPreferences.h" +#include "WebProcessPool.h" +#include "WebUserContentControllerProxy.h" + +using namespace WebKit; + +namespace API { + +Ref<PageConfiguration> PageConfiguration::create() +{ + return adoptRef(*new PageConfiguration); +} + +PageConfiguration::PageConfiguration() +{ +} + +PageConfiguration::~PageConfiguration() +{ +} + +Ref<PageConfiguration> PageConfiguration::copy() const +{ + auto copy = create(); + + copy->m_processPool = this->m_processPool; + copy->m_userContentController = this->m_userContentController; + copy->m_pageGroup = this->m_pageGroup; + copy->m_preferences = this->m_preferences; + copy->m_preferenceValues = this->m_preferenceValues; + copy->m_relatedPage = this->m_relatedPage; + copy->m_visitedLinkStore = this->m_visitedLinkStore; + copy->m_websiteDataStore = this->m_websiteDataStore; + copy->m_sessionID = this->m_sessionID; + copy->m_treatsSHA1SignedCertificatesAsInsecure = this->m_treatsSHA1SignedCertificatesAsInsecure; +#if PLATFORM(IOS) + copy->m_alwaysRunsAtForegroundPriority = this->m_alwaysRunsAtForegroundPriority; +#endif + + return copy; +} + + +WebProcessPool* PageConfiguration::processPool() +{ + return m_processPool.get(); +} + +void PageConfiguration::setProcessPool(WebProcessPool* processPool) +{ + m_processPool = processPool; +} + +WebUserContentControllerProxy* PageConfiguration::userContentController() +{ + return m_userContentController.get(); +} + +void PageConfiguration::setUserContentController(WebUserContentControllerProxy* userContentController) +{ + m_userContentController = userContentController; +} + +WebPageGroup* PageConfiguration::pageGroup() +{ + return m_pageGroup.get(); +} + +void PageConfiguration::setPageGroup(WebPageGroup* pageGroup) +{ + m_pageGroup = pageGroup; +} + +WebPreferences* PageConfiguration::preferences() +{ + return m_preferences.get(); +} + +void PageConfiguration::setPreferences(WebPreferences* preferences) +{ + m_preferences = preferences; +} + +WebPageProxy* PageConfiguration::relatedPage() +{ + return m_relatedPage.get(); +} + +void PageConfiguration::setRelatedPage(WebPageProxy* relatedPage) +{ + m_relatedPage = relatedPage; +} + + +VisitedLinkStore* PageConfiguration::visitedLinkStore() +{ + return m_visitedLinkStore.get(); +} + +void PageConfiguration::setVisitedLinkStore(VisitedLinkStore* visitedLinkStore) +{ + m_visitedLinkStore = visitedLinkStore; +} + +API::WebsiteDataStore* PageConfiguration::websiteDataStore() +{ + return m_websiteDataStore.get(); +} + +void PageConfiguration::setWebsiteDataStore(API::WebsiteDataStore* websiteDataStore) +{ + m_websiteDataStore = websiteDataStore; + + if (m_websiteDataStore) + m_sessionID = m_websiteDataStore->websiteDataStore().sessionID(); + else + m_sessionID = WebCore::SessionID(); +} + +WebCore::SessionID PageConfiguration::sessionID() +{ + return m_sessionID; +} + +void PageConfiguration::setSessionID(WebCore::SessionID sessionID) +{ + m_sessionID = sessionID; +} + +} // namespace API diff --git a/Source/WebKit2/UIProcess/API/APIPageConfiguration.h b/Source/WebKit2/UIProcess/API/APIPageConfiguration.h new file mode 100644 index 000000000..5c62532a8 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIPageConfiguration.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2015 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 APIPageConfiguration_h +#define APIPageConfiguration_h + +#include "APIObject.h" +#include "WebPreferencesStore.h" +#include <WebCore/SessionID.h> +#include <wtf/GetPtr.h> + +namespace WebKit { +class VisitedLinkStore; +class WebPageGroup; +class WebPageProxy; +class WebPreferences; +class WebProcessPool; +class WebUserContentControllerProxy; +} + +namespace API { + +class WebsiteDataStore; + +class PageConfiguration : public ObjectImpl<Object::Type::PageConfiguration> { +public: + static Ref<PageConfiguration> create(); + + explicit PageConfiguration(); + virtual ~PageConfiguration(); + + Ref<PageConfiguration> copy() const; + + // FIXME: The configuration properties should return their default values + // rather than nullptr. + + WebKit::WebProcessPool* processPool(); + void setProcessPool(WebKit::WebProcessPool*); + + WebKit::WebUserContentControllerProxy* userContentController(); + void setUserContentController(WebKit::WebUserContentControllerProxy*); + + WebKit::WebPageGroup* pageGroup(); + void setPageGroup(WebKit::WebPageGroup*); + + WebKit::WebPreferences* preferences(); + void setPreferences(WebKit::WebPreferences*); + + WebKit::WebPreferencesStore::ValueMap& preferenceValues() { return m_preferenceValues; } + + WebKit::WebPageProxy* relatedPage(); + void setRelatedPage(WebKit::WebPageProxy*); + + WebKit::VisitedLinkStore* visitedLinkStore(); + void setVisitedLinkStore(WebKit::VisitedLinkStore*); + + WebsiteDataStore* websiteDataStore(); + void setWebsiteDataStore(WebsiteDataStore*); + + WebCore::SessionID sessionID(); + void setSessionID(WebCore::SessionID); + + bool treatsSHA1SignedCertificatesAsInsecure() { return m_treatsSHA1SignedCertificatesAsInsecure; } + void setTreatsSHA1SignedCertificatesAsInsecure(bool treatsSHA1SignedCertificatesAsInsecure) { m_treatsSHA1SignedCertificatesAsInsecure = treatsSHA1SignedCertificatesAsInsecure; } + +#if PLATFORM(IOS) + bool alwaysRunsAtForegroundPriority() { return m_alwaysRunsAtForegroundPriority; } + void setAlwaysRunsAtForegroundPriority(bool alwaysRunsAtForegroundPriority) { m_alwaysRunsAtForegroundPriority = alwaysRunsAtForegroundPriority; } +#endif + +private: + + RefPtr<WebKit::WebProcessPool> m_processPool; + RefPtr<WebKit::WebUserContentControllerProxy> m_userContentController; + RefPtr<WebKit::WebPageGroup> m_pageGroup; + RefPtr<WebKit::WebPreferences> m_preferences; + WebKit::WebPreferencesStore::ValueMap m_preferenceValues; + RefPtr<WebKit::WebPageProxy> m_relatedPage; + RefPtr<WebKit::VisitedLinkStore> m_visitedLinkStore; + + RefPtr<WebsiteDataStore> m_websiteDataStore; + // FIXME: We currently have to pass the session ID separately here to support the legacy private browsing session. + // Once we get rid of it we should get rid of this configuration parameter as well. + WebCore::SessionID m_sessionID; + + bool m_treatsSHA1SignedCertificatesAsInsecure = false; +#if PLATFORM(IOS) + bool m_alwaysRunsAtForegroundPriority = false; +#endif +}; + +} // namespace API + + +#endif // APIPageConfiguration_h diff --git a/Source/WebKit2/UIProcess/WebPolicyClient.h b/Source/WebKit2/UIProcess/API/APIPolicyClient.h index e4eef4867..8edfaa1a9 100644 --- a/Source/WebKit2/UIProcess/WebPolicyClient.h +++ b/Source/WebKit2/UIProcess/API/APIPolicyClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,36 +23,49 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebPolicyClient_h -#define WebPolicyClient_h +#ifndef APIPolicyClient_h +#define APIPolicyClient_h -#include "APIClient.h" -#include "WKPage.h" #include "WebEvent.h" +#include "WebFramePolicyListenerProxy.h" #include <WebCore/FrameLoaderTypes.h> #include <wtf/Forward.h> namespace WebCore { - class ResourceError; - class ResourceRequest; - class ResourceResponse; +class ResourceError; +class ResourceRequest; +class ResourceResponse; } namespace WebKit { - -class APIObject; +struct NavigationActionData; class WebPageProxy; class WebFrameProxy; class WebFramePolicyListenerProxy; +} -class WebPolicyClient : public APIClient<WKPagePolicyClient, kWKPagePolicyClientCurrentVersion> { +namespace API { +class Object; + +class PolicyClient { public: - bool decidePolicyForNavigationAction(WebPageProxy*, WebFrameProxy*, WebCore::NavigationType, WebEvent::Modifiers, WebMouseEvent::Button, const WebCore::ResourceRequest&, WebFramePolicyListenerProxy*, APIObject* userData); - bool decidePolicyForNewWindowAction(WebPageProxy*, WebFrameProxy*, WebCore::NavigationType, WebEvent::Modifiers, WebMouseEvent::Button, const WebCore::ResourceRequest&, const String& frameName, WebFramePolicyListenerProxy*, APIObject* userData); - bool decidePolicyForResponse(WebPageProxy*, WebFrameProxy*, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, WebFramePolicyListenerProxy*, APIObject* userData); - void unableToImplementPolicy(WebPageProxy*, WebFrameProxy*, const WebCore::ResourceError&, APIObject* userData); + virtual ~PolicyClient() { } + + virtual void decidePolicyForNavigationAction(WebKit::WebPageProxy&, WebKit::WebFrameProxy*, const WebKit::NavigationActionData&, WebKit::WebFrameProxy*, const WebCore::ResourceRequest&, const WebCore::ResourceRequest&, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object*) + { + listener->use(); + } + virtual void decidePolicyForNewWindowAction(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, const WebKit::NavigationActionData&, const WebCore::ResourceRequest&, const WTF::String&, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object*) + { + listener->use(); + } + virtual void decidePolicyForResponse(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, bool, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object*) + { + listener->use(); + } + virtual void unableToImplementPolicy(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, const WebCore::ResourceError&, API::Object*) { } }; -} // namespace WebKit +} // namespace API -#endif // WebPolicyClient_h +#endif // APIPolicyClient_h diff --git a/Source/WebKit2/UIProcess/API/APIProcessPoolConfiguration.cpp b/Source/WebKit2/UIProcess/API/APIProcessPoolConfiguration.cpp new file mode 100644 index 000000000..7895e137b --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIProcessPoolConfiguration.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2014 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 "APIProcessPoolConfiguration.h" + +#include "APIWebsiteDataStore.h" +#include "WebProcessPool.h" + +namespace API { + +Ref<ProcessPoolConfiguration> ProcessPoolConfiguration::create() +{ + return adoptRef(*new ProcessPoolConfiguration); +} + +Ref<ProcessPoolConfiguration> ProcessPoolConfiguration::createWithLegacyOptions() +{ + auto configuration = ProcessPoolConfiguration::create(); + + configuration->m_shouldHaveLegacyDataStore = true; + configuration->m_maximumProcessCount = 1; + configuration->m_cacheModel = WebKit::CacheModelDocumentViewer; + + configuration->m_applicationCacheDirectory = WebKit::WebProcessPool::legacyPlatformDefaultApplicationCacheDirectory(); + configuration->m_diskCacheDirectory = WebKit::WebProcessPool::legacyPlatformDefaultNetworkCacheDirectory(); + configuration->m_indexedDBDatabaseDirectory = WebKit::WebProcessPool::legacyPlatformDefaultIndexedDBDatabaseDirectory(); + configuration->m_localStorageDirectory = WebKit::WebProcessPool::legacyPlatformDefaultLocalStorageDirectory(); + configuration->m_mediaKeysStorageDirectory = WebKit::WebProcessPool::legacyPlatformDefaultMediaKeysStorageDirectory(); + configuration->m_webSQLDatabaseDirectory = WebKit::WebProcessPool::legacyPlatformDefaultWebSQLDatabaseDirectory(); + + return configuration; +} + +ProcessPoolConfiguration::ProcessPoolConfiguration() + : m_applicationCacheDirectory(WebsiteDataStore::defaultApplicationCacheDirectory()) + , m_diskCacheDirectory(WebsiteDataStore::defaultNetworkCacheDirectory()) + , m_indexedDBDatabaseDirectory(WebsiteDataStore::defaultIndexedDBDatabaseDirectory()) + , m_localStorageDirectory(WebsiteDataStore::defaultLocalStorageDirectory()) + , m_webSQLDatabaseDirectory(WebsiteDataStore::defaultWebSQLDatabaseDirectory()) + , m_mediaKeysStorageDirectory(WebsiteDataStore::defaultMediaKeysStorageDirectory()) +{ +} + +ProcessPoolConfiguration::~ProcessPoolConfiguration() +{ +} + +Ref<ProcessPoolConfiguration> ProcessPoolConfiguration::copy() +{ + auto copy = this->create(); + + copy->m_shouldHaveLegacyDataStore = this->m_shouldHaveLegacyDataStore; + copy->m_maximumProcessCount = this->m_maximumProcessCount; + copy->m_cacheModel = this->m_cacheModel; + copy->m_diskCacheSizeOverride = this->m_diskCacheSizeOverride; + copy->m_applicationCacheDirectory = this->m_applicationCacheDirectory; + copy->m_diskCacheDirectory = this->m_diskCacheDirectory; + copy->m_indexedDBDatabaseDirectory = this->m_indexedDBDatabaseDirectory; + copy->m_injectedBundlePath = this->m_injectedBundlePath; + copy->m_localStorageDirectory = this->m_localStorageDirectory; + copy->m_mediaKeysStorageDirectory = this->m_mediaKeysStorageDirectory; + copy->m_webSQLDatabaseDirectory = this->m_webSQLDatabaseDirectory; + copy->m_cachePartitionedURLSchemes = this->m_cachePartitionedURLSchemes; + copy->m_alwaysRevalidatedURLSchemes = this->m_alwaysRevalidatedURLSchemes; + copy->m_fullySynchronousModeIsAllowedForTesting = this->m_fullySynchronousModeIsAllowedForTesting; + copy->m_overrideLanguages = this->m_overrideLanguages; + + return copy; +} + +} // namespace API diff --git a/Source/WebKit2/UIProcess/API/APIProcessPoolConfiguration.h b/Source/WebKit2/UIProcess/API/APIProcessPoolConfiguration.h new file mode 100644 index 000000000..a5d813ff0 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIProcessPoolConfiguration.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2014 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 APIContextConfiguration_h +#define APIContextConfiguration_h + +#include "APIObject.h" +#include "CacheModel.h" +#include <wtf/Ref.h> +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace API { + +class ProcessPoolConfiguration final : public ObjectImpl<Object::Type::ProcessPoolConfiguration> { +public: + static Ref<ProcessPoolConfiguration> create(); + static Ref<ProcessPoolConfiguration> createWithLegacyOptions(); + + explicit ProcessPoolConfiguration(); + virtual ~ProcessPoolConfiguration(); + + Ref<ProcessPoolConfiguration> copy(); + + bool shouldHaveLegacyDataStore() const { return m_shouldHaveLegacyDataStore; } + void setShouldHaveLegacyDataStore(bool shouldHaveLegacyDataStore) { m_shouldHaveLegacyDataStore = shouldHaveLegacyDataStore; } + + unsigned maximumProcessCount() const { return m_maximumProcessCount; } + void setMaximumProcessCount(unsigned maximumProcessCount) { m_maximumProcessCount = maximumProcessCount; } + + WebKit::CacheModel cacheModel() const { return m_cacheModel; } + void setCacheModel(WebKit::CacheModel cacheModel) { m_cacheModel = cacheModel; } + + int64_t diskCacheSizeOverride() const { return m_diskCacheSizeOverride; } + void setDiskCacheSizeOverride(int64_t size) { m_diskCacheSizeOverride = size; } + + const WTF::String& applicationCacheDirectory() const { return m_applicationCacheDirectory; } + void setApplicationCacheDirectory(const WTF::String& applicationCacheDirectory) { m_applicationCacheDirectory = applicationCacheDirectory; } + + const WTF::String& diskCacheDirectory() const { return m_diskCacheDirectory; } + void setDiskCacheDirectory(const WTF::String& diskCacheDirectory) { m_diskCacheDirectory = diskCacheDirectory; } + + const WTF::String& indexedDBDatabaseDirectory() const { return m_indexedDBDatabaseDirectory; } + void setIndexedDBDatabaseDirectory(const WTF::String& indexedDBDatabaseDirectory) { m_indexedDBDatabaseDirectory = indexedDBDatabaseDirectory; } + + const WTF::String& injectedBundlePath() const { return m_injectedBundlePath; } + void setInjectedBundlePath(const WTF::String& injectedBundlePath) { m_injectedBundlePath = injectedBundlePath; } + + const WTF::String& localStorageDirectory() const { return m_localStorageDirectory; } + void setLocalStorageDirectory(const WTF::String& localStorageDirectory) { m_localStorageDirectory = localStorageDirectory; } + + const WTF::String& webSQLDatabaseDirectory() const { return m_webSQLDatabaseDirectory; } + void setWebSQLDatabaseDirectory(const WTF::String& webSQLDatabaseDirectory) { m_webSQLDatabaseDirectory = webSQLDatabaseDirectory; } + + const WTF::String& mediaKeysStorageDirectory() const { return m_mediaKeysStorageDirectory; } + void setMediaKeysStorageDirectory(const WTF::String& mediaKeysStorageDirectory) { m_mediaKeysStorageDirectory = mediaKeysStorageDirectory; } + + const Vector<WTF::String>& cachePartitionedURLSchemes() { return m_cachePartitionedURLSchemes; } + void setCachePartitionedURLSchemes(Vector<WTF::String>&& cachePartitionedURLSchemes) { m_cachePartitionedURLSchemes = WTFMove(cachePartitionedURLSchemes); } + + const Vector<WTF::String>& alwaysRevalidatedURLSchemes() { return m_alwaysRevalidatedURLSchemes; } + void setAlwaysRevalidatedURLSchemes(Vector<WTF::String>&& alwaysRevalidatedURLSchemes) { m_alwaysRevalidatedURLSchemes = WTFMove(alwaysRevalidatedURLSchemes); } + + bool fullySynchronousModeIsAllowedForTesting() const { return m_fullySynchronousModeIsAllowedForTesting; } + void setFullySynchronousModeIsAllowedForTesting(bool allowed) { m_fullySynchronousModeIsAllowedForTesting = allowed; } + + const Vector<WTF::String>& overrideLanguages() const { return m_overrideLanguages; } + void setOverrideLanguages(Vector<WTF::String>&& languages) { m_overrideLanguages = WTFMove(languages); } + +private: + bool m_shouldHaveLegacyDataStore { false }; + + unsigned m_maximumProcessCount { 0 }; + WebKit::CacheModel m_cacheModel { WebKit::CacheModelPrimaryWebBrowser }; + int64_t m_diskCacheSizeOverride { -1 }; + + WTF::String m_applicationCacheDirectory; + WTF::String m_diskCacheDirectory; + WTF::String m_indexedDBDatabaseDirectory; + WTF::String m_injectedBundlePath; + WTF::String m_localStorageDirectory; + WTF::String m_webSQLDatabaseDirectory; + WTF::String m_mediaKeysStorageDirectory; + Vector<WTF::String> m_cachePartitionedURLSchemes; + Vector<WTF::String> m_alwaysRevalidatedURLSchemes; + bool m_fullySynchronousModeIsAllowedForTesting { false }; + Vector<WTF::String> m_overrideLanguages; +}; + +} // namespace API + +#endif // APIContextConfiguration_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data.cpp b/Source/WebKit2/UIProcess/API/APISession.cpp index a2ae9a4ef..61553b195 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data.cpp +++ b/Source/WebKit2/UIProcess/API/APISession.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,50 +24,63 @@ */ #include "config.h" -#include "ewk_navigation_data.h" +#include "APISession.h" -#include "ewk_navigation_data_private.h" +#include "NetworkProcessMessages.h" +#include "WebProcessPool.h" +#include <wtf/RunLoop.h> -using namespace WebKit; +namespace API { -EwkNavigationData::EwkNavigationData(WKNavigationDataRef dataRef) - : m_request(EwkUrlRequest::create(adoptWK(WKNavigationDataCopyOriginalRequest(dataRef)).get())) - , m_title(AdoptWK, WKNavigationDataCopyTitle(dataRef)) - , m_url(AdoptWK, WKNavigationDataCopyURL(dataRef)) -{ } - -EwkUrlRequest* EwkNavigationData::originalRequest() const +static uint64_t generateID() { - return m_request.get(); + ASSERT(RunLoop::isMain()); + + static uint64_t uniqueSessionID = WebCore::SessionID::legacyPrivateSessionID().sessionID(); + + return ++uniqueSessionID; } -const char* EwkNavigationData::title() const +Session& Session::defaultSession() { - return m_title; + ASSERT(RunLoop::isMain()); + + static Session* defaultSession = new Session(WebCore::SessionID::defaultSessionID()); + return *defaultSession; } -const char* EwkNavigationData::url() const +Session::Session() + : m_sessionID(generateID()) { - return m_url; } -const char* ewk_navigation_data_title_get(const Ewk_Navigation_Data* data) +Session::Session(WebCore::SessionID sessionID) + : m_sessionID(sessionID) { - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationData, data, impl, 0); - - return impl->title(); } -Ewk_Url_Request* ewk_navigation_data_original_request_get(const Ewk_Navigation_Data* data) +Ref<Session> Session::createEphemeral() { - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationData, data, impl, 0); + // FIXME: support creation of non-default, non-ephemeral sessions + return adoptRef(*new Session()); +} - return impl->originalRequest(); +bool Session::isEphemeral() const +{ + return m_sessionID.isEphemeral(); } -const char* ewk_navigation_data_url_get(const Ewk_Navigation_Data* data) +WebCore::SessionID Session::getID() const { - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationData, data, impl, 0); + return m_sessionID; +} - return impl->url(); +Session::~Session() +{ + if (m_sessionID.isEphemeral()) { + for (auto& processPool : WebKit::WebProcessPool::allProcessPools()) + processPool->sendToNetworkingProcess(Messages::NetworkProcess::DestroyPrivateBrowsingSession(m_sessionID)); + } } + +} // namespace API diff --git a/Source/WebKit2/UIProcess/API/APISession.h b/Source/WebKit2/UIProcess/API/APISession.h new file mode 100644 index 000000000..d2091dd3a --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APISession.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2014 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 APISession_h +#define APISession_h + +#include "APIObject.h" +#include <WebCore/SessionID.h> +#include <wtf/PassRefPtr.h> + +namespace API { + +class Session : public API::ObjectImpl<API::Object::Type::Session> { +public: + static Ref<Session> createEphemeral(); + virtual ~Session(); + + static Session& defaultSession(); + bool isEphemeral() const; + WebCore::SessionID getID() const; + +private: + Session(); + explicit Session(WebCore::SessionID); + + WebCore::SessionID m_sessionID; +}; + +} // namespace API + +#endif // APISession_h diff --git a/Source/WebKit2/UIProcess/API/APISessionState.cpp b/Source/WebKit2/UIProcess/API/APISessionState.cpp new file mode 100644 index 000000000..473e5c750 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APISessionState.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2014 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 "APISessionState.h" + +namespace API { + +Ref<SessionState> SessionState::create(WebKit::SessionState sessionState) +{ + return adoptRef(*new SessionState(WTFMove(sessionState))); +} + +SessionState::SessionState(WebKit::SessionState sessionState) + : m_sessionState(WTFMove(sessionState)) +{ +} + +SessionState::~SessionState() +{ +} + +} // namespace API diff --git a/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.mm b/Source/WebKit2/UIProcess/API/APISessionState.h index fd80ac248..e4d32f7fc 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.mm +++ b/Source/WebKit2/UIProcess/API/APISessionState.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,38 +23,27 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#import "config.h" +#ifndef APISessionState_h +#define APISessionState_h -#if defined(__LP64__) && defined(__clang__) +#include "APIObject.h" +#include "SessionState.h" -#import "WKTypeRefWrapper.h" +namespace API { -#import "WKRetainPtr.h" +class SessionState final : public ObjectImpl<Object::Type::SessionState> { +public: + static Ref<SessionState> create(WebKit::SessionState); + virtual ~SessionState(); -@interface WKTypeRefWrapper () { - // Underlying WKTypeRef. - WKRetainPtr<WKTypeRef> _object; -} -@end + const WebKit::SessionState& sessionState() const { return m_sessionState; } -@implementation WKTypeRefWrapper +private: + explicit SessionState(WebKit::SessionState); -- (id)initWithObject:(WKTypeRef)object -{ - self = [super init]; - if (!self) - return nil; + const WebKit::SessionState m_sessionState; +}; - _object = object; +} // namespace API - return self; -} - -- (WKTypeRef)object -{ - return _object.get(); -} - -@end - -#endif // defined(__LP64__) && defined(__clang__) +#endif // APISessionState_h diff --git a/Source/WebKit2/UIProcess/API/APIUIClient.h b/Source/WebKit2/UIProcess/API/APIUIClient.h new file mode 100644 index 000000000..0e5927f9b --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIUIClient.h @@ -0,0 +1,175 @@ +/* + * Copyright (C) 2014 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 APIUIClient_h +#define APIUIClient_h + +#include "WKPage.h" +#include "WebEvent.h" +#include "WebHitTestResultData.h" +#include "WebPageProxy.h" +#include <WebCore/FloatRect.h> +#include <functional> +#include <wtf/PassRefPtr.h> + +#if PLATFORM(IOS) +OBJC_CLASS NSArray; +OBJC_CLASS _WKActivatedElementInfo; +OBJC_CLASS UIViewController; +#endif + +namespace WebCore { +class ResourceRequest; +struct SecurityOriginData; +struct WindowFeatures; +} + +namespace WebKit { +class GeolocationPermissionRequestProxy; +class NativeWebKeyboardEvent; +class NativeWebWheelEvent; +class NotificationPermissionRequest; +class UserMediaPermissionCheckProxy; +class UserMediaPermissionRequestProxy; +class WebColorPickerResultListenerProxy; +class WebFrameProxy; +class WebOpenPanelParameters; +class WebOpenPanelResultListenerProxy; +class WebPageProxy; +struct NavigationActionData; + +#if ENABLE(MEDIA_SESSION) +class WebMediaSessionMetadata; +#endif +} + +namespace API { + +class Data; +class Dictionary; +class Object; +class SecurityOrigin; + +class UIClient { +public: + virtual ~UIClient() { } + + virtual PassRefPtr<WebKit::WebPageProxy> createNewPage(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, const WebCore::SecurityOriginData&, const WebCore::ResourceRequest&, const WebCore::WindowFeatures&, const WebKit::NavigationActionData&) { return nullptr; } + virtual void showPage(WebKit::WebPageProxy*) { } + virtual void fullscreenMayReturnToInline(WebKit::WebPageProxy*) { } + virtual void didEnterFullscreen(WebKit::WebPageProxy*) { } + virtual void didExitFullscreen(WebKit::WebPageProxy*) { } + virtual void close(WebKit::WebPageProxy*) { } + + virtual void takeFocus(WebKit::WebPageProxy*, WKFocusDirection) { } + virtual void focus(WebKit::WebPageProxy*) { } + virtual void unfocus(WebKit::WebPageProxy*) { } + + virtual void runJavaScriptAlert(WebKit::WebPageProxy*, const WTF::String&, WebKit::WebFrameProxy*, const WebCore::SecurityOriginData&, std::function<void ()> completionHandler) { completionHandler(); } + virtual void runJavaScriptConfirm(WebKit::WebPageProxy*, const WTF::String&, WebKit::WebFrameProxy*, const WebCore::SecurityOriginData&, std::function<void (bool)> completionHandler) { completionHandler(false); } + virtual void runJavaScriptPrompt(WebKit::WebPageProxy*, const WTF::String&, const WTF::String&, WebKit::WebFrameProxy*, const WebCore::SecurityOriginData&, std::function<void (const WTF::String&)> completionHandler) { completionHandler(WTF::String()); } + + virtual void setStatusText(WebKit::WebPageProxy*, const WTF::String&) { } + virtual void mouseDidMoveOverElement(WebKit::WebPageProxy*, const WebKit::WebHitTestResultData&, WebKit::WebEvent::Modifiers, API::Object*) { } +#if ENABLE(NETSCAPE_PLUGIN_API) + virtual void unavailablePluginButtonClicked(WebKit::WebPageProxy*, WKPluginUnavailabilityReason, API::Dictionary*) { } +#endif // ENABLE(NETSCAPE_PLUGIN_API) + + virtual bool implementsDidNotHandleKeyEvent() const { return false; } + virtual void didNotHandleKeyEvent(WebKit::WebPageProxy*, const WebKit::NativeWebKeyboardEvent&) { } + + virtual bool implementsDidNotHandleWheelEvent() const { return false; } + virtual void didNotHandleWheelEvent(WebKit::WebPageProxy*, const WebKit::NativeWebWheelEvent&) { } + + virtual bool toolbarsAreVisible(WebKit::WebPageProxy*) { return true; } + virtual void setToolbarsAreVisible(WebKit::WebPageProxy*, bool) { } + virtual bool menuBarIsVisible(WebKit::WebPageProxy*) { return true; } + virtual void setMenuBarIsVisible(WebKit::WebPageProxy*, bool) { } + virtual bool statusBarIsVisible(WebKit::WebPageProxy*) { return true; } + virtual void setStatusBarIsVisible(WebKit::WebPageProxy*, bool) { } + virtual bool isResizable(WebKit::WebPageProxy*) { return true; } + virtual void setIsResizable(WebKit::WebPageProxy*, bool) { } + + virtual void setWindowFrame(WebKit::WebPageProxy*, const WebCore::FloatRect&) { } + virtual WebCore::FloatRect windowFrame(WebKit::WebPageProxy*) { return WebCore::FloatRect(); } + + virtual bool canRunBeforeUnloadConfirmPanel() const { return false; } + virtual void runBeforeUnloadConfirmPanel(WebKit::WebPageProxy*, const WTF::String&, WebKit::WebFrameProxy*, std::function<void (bool)> completionHandler) { completionHandler(true); } + + virtual void pageDidScroll(WebKit::WebPageProxy*) { } + + virtual void exceededDatabaseQuota(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, SecurityOrigin*, const WTF::String&, const WTF::String&, unsigned long long currentQuota, unsigned long long, unsigned long long, unsigned long long, std::function<void (unsigned long long)> completionHandler) + { + completionHandler(currentQuota); + } + + virtual void reachedApplicationCacheOriginQuota(WebKit::WebPageProxy*, const WebCore::SecurityOrigin&, uint64_t currentQuota, uint64_t, std::function<void (unsigned long long)> completionHandler) + { + completionHandler(currentQuota); + } + + virtual bool runOpenPanel(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, WebKit::WebOpenPanelParameters*, WebKit::WebOpenPanelResultListenerProxy*) { return false; } + virtual bool decidePolicyForGeolocationPermissionRequest(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, SecurityOrigin*, WebKit::GeolocationPermissionRequestProxy*) { return false; } + virtual bool decidePolicyForUserMediaPermissionRequest(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, SecurityOrigin&, WebKit::UserMediaPermissionRequestProxy&) { return false; } + virtual bool checkUserMediaPermissionForOrigin(WebKit::WebPageProxy&, WebKit::WebFrameProxy&, SecurityOrigin&, WebKit::UserMediaPermissionCheckProxy&) { return false; } + virtual bool decidePolicyForNotificationPermissionRequest(WebKit::WebPageProxy*, SecurityOrigin*, WebKit::NotificationPermissionRequest*) { return false; } + + // Printing. + virtual float headerHeight(WebKit::WebPageProxy*, WebKit::WebFrameProxy*) { return 0; } + virtual float footerHeight(WebKit::WebPageProxy*, WebKit::WebFrameProxy*) { return 0; } + virtual void drawHeader(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, const WebCore::FloatRect&) { } + virtual void drawFooter(WebKit::WebPageProxy*, WebKit::WebFrameProxy*, const WebCore::FloatRect&) { } + virtual void printFrame(WebKit::WebPageProxy*, WebKit::WebFrameProxy*) { } + + virtual bool canRunModal() const { return false; } + virtual void runModal(WebKit::WebPageProxy*) { } + + virtual void saveDataToFileInDownloadsFolder(WebKit::WebPageProxy*, const WTF::String&, const WTF::String&, const WTF::String&, API::Data*) { } + + virtual void pinnedStateDidChange(WebKit::WebPageProxy&) { } + + virtual void isPlayingAudioDidChange(WebKit::WebPageProxy&) { } + +#if ENABLE(MEDIA_SESSION) + virtual void mediaSessionMetadataDidChange(WebKit::WebPageProxy&, WebKit::WebMediaSessionMetadata*) { } +#endif + +#if PLATFORM(IOS) +#if HAVE(APP_LINKS) + virtual bool shouldIncludeAppLinkActionsForElement(_WKActivatedElementInfo *) { return true; } +#endif + virtual RetainPtr<NSArray> actionsForElement(_WKActivatedElementInfo *, RetainPtr<NSArray> defaultActions) { return defaultActions; } + virtual void didNotHandleTapAsClick(const WebCore::IntPoint&) { } + virtual UIViewController *presentingViewController() { return nullptr; } +#endif + + virtual void didClickAutoFillButton(WebKit::WebPageProxy&, API::Object*) { } + + virtual void imageOrMediaDocumentSizeChanged(const WebCore::IntSize&) { } +}; + +} // namespace API + +#endif // APIUIClient_h diff --git a/Source/WebKit2/UIProcess/efl/EwkTouchEvent.cpp b/Source/WebKit2/UIProcess/API/APIUserContentExtension.cpp index 97cd70eb6..b06d9d43b 100644 --- a/Source/WebKit2/UIProcess/efl/EwkTouchEvent.cpp +++ b/Source/WebKit2/UIProcess/API/APIUserContentExtension.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,20 +24,24 @@ */ #include "config.h" -#include "EwkTouchEvent.h" +#include "APIUserContentExtension.h" -#if ENABLE(TOUCH_EVENTS) +#if ENABLE(CONTENT_EXTENSIONS) -namespace WebKit { +#include "WebCompiledContentExtension.h" -EwkTouchEvent::EwkTouchEvent(WKEventType type, WKArrayRef touchPoints, WKEventModifiers modifiers, double timestamp) - : m_eventType(type) - , m_touchPoints(touchPoints) - , m_modifiers(modifiers) - , m_timestamp(timestamp) +namespace API { + +UserContentExtension::UserContentExtension(const WTF::String& name, Ref<WebKit::WebCompiledContentExtension>&& contentExtension) + : m_name(name) + , m_compiledExtension(WTFMove(contentExtension)) +{ +} + +UserContentExtension::~UserContentExtension() { } -} // namespace WebKit +} // namespace API -#endif // ENABLE(TOUCH_EVENTS) +#endif // ENABLE(CONTENT_EXTENSIONS) diff --git a/Source/WebKit2/UIProcess/API/APIUserContentExtension.h b/Source/WebKit2/UIProcess/API/APIUserContentExtension.h new file mode 100644 index 000000000..c60661870 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIUserContentExtension.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2015 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 APIUserContentExtension_h +#define APIUserContentExtension_h + +#include "APIObject.h" +#include <wtf/text/WTFString.h> + +namespace WebKit { +class WebCompiledContentExtension; +} + +namespace API { + +class UserContentExtension final : public ObjectImpl<Object::Type::UserContentExtension> { +public: +#if ENABLE(CONTENT_EXTENSIONS) + static Ref<UserContentExtension> create(const WTF::String& name, Ref<WebKit::WebCompiledContentExtension>&& contentExtension) + { + return adoptRef(*new UserContentExtension(name, WTFMove(contentExtension))); + } + + UserContentExtension(const WTF::String& name, Ref<WebKit::WebCompiledContentExtension>&&); + virtual ~UserContentExtension(); + + const WTF::String& name() const { return m_name; } + const WebKit::WebCompiledContentExtension& compiledExtension() const { return m_compiledExtension.get(); } + +private: + WTF::String m_name; + Ref<WebKit::WebCompiledContentExtension> m_compiledExtension; +#endif // ENABLE(CONTENT_EXTENSIONS) +}; + +} // namespace API + +#endif // APIUserContentExtension_h diff --git a/Source/WebKit2/UIProcess/API/APIUserContentExtensionStore.cpp b/Source/WebKit2/UIProcess/API/APIUserContentExtensionStore.cpp new file mode 100644 index 000000000..ae08a2ad5 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIUserContentExtensionStore.cpp @@ -0,0 +1,425 @@ +/* + * Copyright (C) 2015 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 "APIUserContentExtensionStore.h" + +#if ENABLE(CONTENT_EXTENSIONS) + +#include "APIUserContentExtension.h" +#include "NetworkCacheData.h" +#include "NetworkCacheDecoder.h" +#include "NetworkCacheEncoder.h" +#include "NetworkCacheFileSystem.h" +#include "SharedMemory.h" +#include "WebCompiledContentExtension.h" +#include <WebCore/ContentExtensionCompiler.h> +#include <WebCore/ContentExtensionError.h> +#include <string> +#include <wtf/NeverDestroyed.h> +#include <wtf/RunLoop.h> +#include <wtf/WorkQueue.h> + +using namespace WebKit::NetworkCache; + +namespace API { + +UserContentExtensionStore& UserContentExtensionStore::defaultStore() +{ + static UserContentExtensionStore* defaultStore = adoptRef(new UserContentExtensionStore).leakRef(); + return *defaultStore; +} + +Ref<UserContentExtensionStore> UserContentExtensionStore::storeWithPath(const WTF::String& storePath) +{ + return adoptRef(*new UserContentExtensionStore(storePath)); +} + +UserContentExtensionStore::UserContentExtensionStore() + : UserContentExtensionStore(defaultStorePath()) +{ +} + +UserContentExtensionStore::UserContentExtensionStore(const WTF::String& storePath) + : m_storePath(storePath) + , m_compileQueue(WorkQueue::create("UserContentExtensionStore Compile Queue", WorkQueue::Type::Concurrent)) + , m_readQueue(WorkQueue::create("UserContentExtensionStore Read Queue")) + , m_removeQueue(WorkQueue::create("UserContentExtensionStore Remove Queue")) +{ +} + +UserContentExtensionStore::~UserContentExtensionStore() +{ +} + +static String constructedPath(const String& base, const String& identifier) +{ + return WebCore::pathByAppendingComponent(base, "ContentExtension-" + WebCore::encodeForFileName(identifier)); +} + +const size_t ContentExtensionFileHeaderSize = sizeof(uint32_t) + 4 * sizeof(uint64_t); +struct ContentExtensionMetaData { + uint32_t version { UserContentExtensionStore::CurrentContentExtensionFileVersion }; + uint64_t actionsSize { 0 }; + uint64_t filtersWithoutDomainsBytecodeSize { 0 }; + uint64_t filtersWithDomainBytecodeSize { 0 }; + uint64_t domainFiltersBytecodeSize { 0 }; + + size_t fileSize() const + { + return ContentExtensionFileHeaderSize + + actionsSize + + filtersWithoutDomainsBytecodeSize + + filtersWithDomainBytecodeSize + + domainFiltersBytecodeSize; + } +}; + +static Data encodeContentExtensionMetaData(const ContentExtensionMetaData& metaData) +{ + WebKit::NetworkCache::Encoder encoder; + + encoder << metaData.version; + encoder << metaData.actionsSize; + encoder << metaData.filtersWithoutDomainsBytecodeSize; + encoder << metaData.filtersWithDomainBytecodeSize; + encoder << metaData.domainFiltersBytecodeSize; + + ASSERT(encoder.bufferSize() == ContentExtensionFileHeaderSize); + return Data(encoder.buffer(), encoder.bufferSize()); +} + +static bool decodeContentExtensionMetaData(ContentExtensionMetaData& metaData, const Data& fileData) +{ + bool success = false; + fileData.apply([&metaData, &success, &fileData](const uint8_t* data, size_t size) { + // The file data should be mapped into one continuous memory segment so the size + // passed to the applier should always equal the data size. + if (size != fileData.size()) + return false; + + WebKit::NetworkCache::Decoder decoder(data, size); + if (!decoder.decode(metaData.version)) + return false; + if (!decoder.decode(metaData.actionsSize)) + return false; + if (!decoder.decode(metaData.filtersWithoutDomainsBytecodeSize)) + return false; + if (!decoder.decode(metaData.filtersWithDomainBytecodeSize)) + return false; + if (!decoder.decode(metaData.domainFiltersBytecodeSize)) + return false; + success = true; + return false; + }); + return success; +} + +static bool openAndMapContentExtension(const String& path, ContentExtensionMetaData& metaData, Data& fileData) +{ + fileData = mapFile(WebCore::fileSystemRepresentation(path).data()); + if (fileData.isNull()) + return false; + + if (!decodeContentExtensionMetaData(metaData, fileData)) + return false; + + return true; +} + +static bool writeDataToFile(const Data& fileData, WebCore::PlatformFileHandle fd) +{ + bool success = true; + fileData.apply([fd, &success](const uint8_t* data, size_t size) { + if (WebCore::writeToFile(fd, (const char*)data, size) == -1) { + success = false; + return false; + } + return true; + }); + + return success; +} + +static std::error_code compiledToFile(String&& json, const String& finalFilePath, ContentExtensionMetaData& metaData, Data& mappedData) +{ + using namespace WebCore::ContentExtensions; + + class CompilationClient final : public ContentExtensionCompilationClient { + public: + CompilationClient(WebCore::PlatformFileHandle fileHandle, ContentExtensionMetaData& metaData) + : m_fileHandle(fileHandle) + , m_metaData(metaData) + { + ASSERT(!metaData.actionsSize); + ASSERT(!metaData.filtersWithoutDomainsBytecodeSize); + ASSERT(!metaData.filtersWithDomainBytecodeSize); + ASSERT(!metaData.domainFiltersBytecodeSize); + } + + virtual void writeFiltersWithoutDomainsBytecode(Vector<DFABytecode>&& bytecode) override + { + ASSERT(!m_filtersWithDomainBytecodeWritten); + ASSERT(!m_domainFiltersBytecodeWritten); + m_filtersWithoutDomainsBytecodeWritten += bytecode.size(); + writeToFile(Data(bytecode.data(), bytecode.size())); + } + + virtual void writeFiltersWithDomainsBytecode(Vector<DFABytecode>&& bytecode) override + { + ASSERT(!m_domainFiltersBytecodeWritten); + m_filtersWithDomainBytecodeWritten += bytecode.size(); + writeToFile(Data(bytecode.data(), bytecode.size())); + } + + virtual void writeDomainFiltersBytecode(Vector<DFABytecode>&& bytecode) override + { + m_domainFiltersBytecodeWritten += bytecode.size(); + writeToFile(Data(bytecode.data(), bytecode.size())); + } + + virtual void writeActions(Vector<SerializedActionByte>&& actions) override + { + ASSERT(!m_filtersWithoutDomainsBytecodeWritten); + ASSERT(!m_filtersWithDomainBytecodeWritten); + ASSERT(!m_domainFiltersBytecodeWritten); + ASSERT(!m_actionsWritten); + m_actionsWritten += actions.size(); + writeToFile(Data(actions.data(), actions.size())); + } + + virtual void finalize() override + { + m_metaData.actionsSize = m_actionsWritten; + m_metaData.filtersWithoutDomainsBytecodeSize = m_filtersWithoutDomainsBytecodeWritten; + m_metaData.filtersWithDomainBytecodeSize = m_filtersWithDomainBytecodeWritten; + m_metaData.domainFiltersBytecodeSize = m_domainFiltersBytecodeWritten; + + Data header = encodeContentExtensionMetaData(m_metaData); + if (!m_fileError && WebCore::seekFile(m_fileHandle, 0ll, WebCore::FileSeekOrigin::SeekFromBeginning) == -1) { + WebCore::closeFile(m_fileHandle); + m_fileError = true; + } + writeToFile(header); + } + + bool hadErrorWhileWritingToFile() { return m_fileError; } + + private: + void writeToFile(const Data& data) + { + if (!m_fileError && !writeDataToFile(data, m_fileHandle)) { + WebCore::closeFile(m_fileHandle); + m_fileError = true; + } + } + + WebCore::PlatformFileHandle m_fileHandle; + ContentExtensionMetaData& m_metaData; + size_t m_filtersWithoutDomainsBytecodeWritten { 0 }; + size_t m_filtersWithDomainBytecodeWritten { 0 }; + size_t m_domainFiltersBytecodeWritten { 0 }; + size_t m_actionsWritten { 0 }; + bool m_fileError { false }; + }; + + auto temporaryFileHandle = WebCore::invalidPlatformFileHandle; + String temporaryFilePath = WebCore::openTemporaryFile("ContentExtension", temporaryFileHandle); + if (temporaryFileHandle == WebCore::invalidPlatformFileHandle) + return UserContentExtensionStore::Error::CompileFailed; + + char invalidHeader[ContentExtensionFileHeaderSize]; + memset(invalidHeader, 0xFF, sizeof(invalidHeader)); + // This header will be rewritten in CompilationClient::finalize. + if (WebCore::writeToFile(temporaryFileHandle, invalidHeader, sizeof(invalidHeader)) == -1) { + WebCore::closeFile(temporaryFileHandle); + return UserContentExtensionStore::Error::CompileFailed; + } + + CompilationClient compilationClient(temporaryFileHandle, metaData); + + if (auto compilerError = compileRuleList(compilationClient, WTFMove(json))) { + WebCore::closeFile(temporaryFileHandle); + return compilerError; + } + if (compilationClient.hadErrorWhileWritingToFile()) { + WebCore::closeFile(temporaryFileHandle); + return UserContentExtensionStore::Error::CompileFailed; + } + + mappedData = adoptAndMapFile(temporaryFileHandle, 0, metaData.fileSize()); + if (mappedData.isNull()) + return UserContentExtensionStore::Error::CompileFailed; + + if (!WebCore::moveFile(temporaryFilePath, finalFilePath)) + return UserContentExtensionStore::Error::CompileFailed; + + return { }; +} + +static RefPtr<API::UserContentExtension> createExtension(const String& identifier, const ContentExtensionMetaData& metaData, const Data& fileData) +{ + auto sharedMemory = WebKit::SharedMemory::create(const_cast<uint8_t*>(fileData.data()), fileData.size(), WebKit::SharedMemory::Protection::ReadOnly); + auto compiledContentExtensionData = WebKit::WebCompiledContentExtensionData( + WTFMove(sharedMemory), + fileData, + ContentExtensionFileHeaderSize, + metaData.actionsSize, + ContentExtensionFileHeaderSize + + metaData.actionsSize, + metaData.filtersWithoutDomainsBytecodeSize, + ContentExtensionFileHeaderSize + + metaData.actionsSize + + metaData.filtersWithoutDomainsBytecodeSize, + metaData.filtersWithDomainBytecodeSize, + ContentExtensionFileHeaderSize + + metaData.actionsSize + + metaData.filtersWithoutDomainsBytecodeSize + + metaData.filtersWithDomainBytecodeSize, + metaData.domainFiltersBytecodeSize + ); + auto compiledContentExtension = WebKit::WebCompiledContentExtension::create(WTFMove(compiledContentExtensionData)); + return API::UserContentExtension::create(identifier, WTFMove(compiledContentExtension)); +} + +void UserContentExtensionStore::lookupContentExtension(const WTF::String& identifier, std::function<void(RefPtr<API::UserContentExtension>, std::error_code)> completionHandler) +{ + RefPtr<UserContentExtensionStore> self(this); + StringCapture identifierCapture(identifier); + StringCapture pathCapture(m_storePath); + + m_readQueue->dispatch([self, identifierCapture, pathCapture, completionHandler] { + auto path = constructedPath(pathCapture.string(), identifierCapture.string()); + + ContentExtensionMetaData metaData; + Data fileData; + if (!openAndMapContentExtension(path, metaData, fileData)) { + RunLoop::main().dispatch([self, completionHandler] { + completionHandler(nullptr, Error::LookupFailed); + }); + return; + } + + if (metaData.version != UserContentExtensionStore::CurrentContentExtensionFileVersion) { + RunLoop::main().dispatch([self, completionHandler] { + completionHandler(nullptr, Error::VersionMismatch); + }); + return; + } + + RunLoop::main().dispatch([self, identifierCapture, fileData, metaData, completionHandler] { + RefPtr<API::UserContentExtension> userContentExtension = createExtension(identifierCapture.string(), metaData, fileData); + completionHandler(userContentExtension, { }); + }); + }); +} + +void UserContentExtensionStore::compileContentExtension(const WTF::String& identifier, WTF::String&& json, std::function<void(RefPtr<API::UserContentExtension>, std::error_code)> completionHandler) +{ + RefPtr<UserContentExtensionStore> self(this); + StringCapture identifierCapture(identifier); + StringCapture jsonCapture(WTFMove(json)); + StringCapture pathCapture(m_storePath); + + m_compileQueue->dispatch([self, identifierCapture, jsonCapture, pathCapture, completionHandler] () mutable { + auto path = constructedPath(pathCapture.string(), identifierCapture.string()); + + ContentExtensionMetaData metaData; + Data fileData; + auto error = compiledToFile(jsonCapture.releaseString(), path, metaData, fileData); + if (error) { + RunLoop::main().dispatch([self, error, completionHandler] { + completionHandler(nullptr, error); + }); + return; + } + + RunLoop::main().dispatch([self, identifierCapture, fileData, metaData, completionHandler] { + RefPtr<API::UserContentExtension> userContentExtension = createExtension(identifierCapture.string(), metaData, fileData); + completionHandler(userContentExtension, { }); + }); + }); +} + +void UserContentExtensionStore::removeContentExtension(const WTF::String& identifier, std::function<void(std::error_code)> completionHandler) +{ + RefPtr<UserContentExtensionStore> self(this); + StringCapture identifierCapture(identifier); + StringCapture pathCapture(m_storePath); + + m_removeQueue->dispatch([self, identifierCapture, pathCapture, completionHandler] { + auto path = constructedPath(pathCapture.string(), identifierCapture.string()); + + if (!WebCore::deleteFile(path)) { + RunLoop::main().dispatch([self, completionHandler] { + completionHandler(Error::RemoveFailed); + }); + return; + } + + RunLoop::main().dispatch([self, completionHandler] { + completionHandler({ }); + }); + }); +} + +void UserContentExtensionStore::synchronousRemoveAllContentExtensions() +{ + for (const auto& path : WebCore::listDirectory(m_storePath, "*")) + WebCore::deleteFile(path); +} + +const std::error_category& userContentExtensionStoreErrorCategory() +{ + class UserContentExtensionStoreErrorCategory : public std::error_category { + const char* name() const noexcept override + { + return "user content extension store"; + } + + virtual std::string message(int errorCode) const override + { + switch (static_cast<UserContentExtensionStore::Error>(errorCode)) { + case UserContentExtensionStore::Error::LookupFailed: + return "Unspecified error during lookup."; + case UserContentExtensionStore::Error::VersionMismatch: + return "Version of file does not match version of interpreter."; + case UserContentExtensionStore::Error::CompileFailed: + return "Unspecified error during compile."; + case UserContentExtensionStore::Error::RemoveFailed: + return "Unspecified error during remove."; + } + + return std::string(); + } + }; + + static NeverDestroyed<UserContentExtensionStoreErrorCategory> contentExtensionErrorCategory; + return contentExtensionErrorCategory; +} + +} // namespace API + +#endif // ENABLE(CONTENT_EXTENSIONS) diff --git a/Source/WebKit2/UIProcess/API/APIUserContentExtensionStore.h b/Source/WebKit2/UIProcess/API/APIUserContentExtensionStore.h new file mode 100644 index 000000000..28309fbb6 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIUserContentExtensionStore.h @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2015 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 APIUserContentExtensionStore_h +#define APIUserContentExtensionStore_h + +#if ENABLE(CONTENT_EXTENSIONS) + +#include "APIObject.h" +#include <system_error> +#include <wtf/text/WTFString.h> + +namespace WTF { +class WorkQueue; +} + +namespace API { + +class UserContentExtension; + +class UserContentExtensionStore final : public ObjectImpl<Object::Type::UserContentExtensionStore> { +public: + enum class Error { + LookupFailed = 1, + VersionMismatch, + CompileFailed, + RemoveFailed + }; + + // This should be incremented every time a functional change is made to the bytecode, file format, etc. + // to prevent crashing while loading old data. + const static uint32_t CurrentContentExtensionFileVersion = 7; + + static UserContentExtensionStore& defaultStore(); + static Ref<UserContentExtensionStore> storeWithPath(const WTF::String& storePath); + + explicit UserContentExtensionStore(); + explicit UserContentExtensionStore(const WTF::String& storePath); + virtual ~UserContentExtensionStore(); + + void compileContentExtension(const WTF::String& identifier, WTF::String&& json, std::function<void(RefPtr<API::UserContentExtension>, std::error_code)>); + void lookupContentExtension(const WTF::String& identifier, std::function<void(RefPtr<API::UserContentExtension>, std::error_code)>); + void removeContentExtension(const WTF::String& identifier, std::function<void(std::error_code)>); + + // For testing only. + void synchronousRemoveAllContentExtensions(); + +private: + WTF::String defaultStorePath(); + + const WTF::String m_storePath; + Ref<WTF::WorkQueue> m_compileQueue; + Ref<WTF::WorkQueue> m_readQueue; + Ref<WTF::WorkQueue> m_removeQueue; +}; + +const std::error_category& userContentExtensionStoreErrorCategory(); + +inline std::error_code make_error_code(UserContentExtensionStore::Error error) +{ + return { static_cast<int>(error), userContentExtensionStoreErrorCategory() }; +} + +} // namespace API + +namespace std { + template<> struct is_error_code_enum<API::UserContentExtensionStore::Error> : public true_type { }; +} + +#endif // ENABLE(CONTENT_EXTENSIONS) +#endif // APIUserContentExtensionStore_h diff --git a/Source/WebKit2/UIProcess/API/APIUserScript.cpp b/Source/WebKit2/UIProcess/API/APIUserScript.cpp new file mode 100644 index 000000000..84ea6a1c8 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIUserScript.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2015 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 "APIUserScript.h" + +#include <wtf/text/StringBuilder.h> + +namespace API { + +static uint64_t generateIdentifier() +{ + static uint64_t identifier; + + return ++identifier; +} + +WebCore::URL UserScript::generateUniqueURL() +{ + StringBuilder urlStringBuilder; + urlStringBuilder.appendLiteral("user-script:"); + urlStringBuilder.appendNumber(generateIdentifier()); + return { { }, urlStringBuilder.toString() }; +} + + +} // namespace API diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.h b/Source/WebKit2/UIProcess/API/APIUserScript.h index 3a82af5e4..03e2f62cd 100644 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.h +++ b/Source/WebKit2/UIProcess/API/APIUserScript.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,28 +23,34 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef RemoteLayerTreeDrawingAreaProxy_h -#define RemoteLayerTreeDrawingAreaProxy_h +#ifndef APIUserScript_h +#define APIUserScript_h -#include "DrawingAreaProxy.h" -#include "RemoteLayerTreeHost.h" +#include "APIObject.h" +#include <WebCore/UserScript.h> -namespace WebKit { +namespace API { -class RemoteLayerTreeDrawingAreaProxy : public DrawingAreaProxy { +class UserScript final : public ObjectImpl<Object::Type::UserScript> { public: - static PassOwnPtr<RemoteLayerTreeDrawingAreaProxy> create(WebPageProxy*); - virtual ~RemoteLayerTreeDrawingAreaProxy(); + static WebCore::URL generateUniqueURL(); -private: - explicit RemoteLayerTreeDrawingAreaProxy(WebPageProxy*); + static Ref<UserScript> create(WebCore::UserScript userScript) + { + return adoptRef(*new UserScript(WTFMove(userScript))); + } + + UserScript(WebCore::UserScript userScript) + : m_userScript(userScript) + { + } - virtual void sizeDidChange() OVERRIDE; - virtual void deviceScaleFactorDidChange() OVERRIDE; + const WebCore::UserScript& userScript() const { return m_userScript; } - RemoteLayerTreeHost m_remoteLayerTreeHost; +private: + WebCore::UserScript m_userScript; }; -} // namespace WebKit +} // namespace API -#endif // RemoteLayerTreeDrawingAreaProxy_h +#endif // APIUserScript_h diff --git a/Source/WebKit2/UIProcess/gtk/WebFullScreenClientGtk.cpp b/Source/WebKit2/UIProcess/API/APIUserStyleSheet.cpp index ba22485e1..0c1b2ac22 100644 --- a/Source/WebKit2/UIProcess/gtk/WebFullScreenClientGtk.cpp +++ b/Source/WebKit2/UIProcess/API/APIUserStyleSheet.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,27 +24,26 @@ */ #include "config.h" -#include "WebFullScreenClientGtk.h" +#include "APIUserStyleSheet.h" -#include "WKAPICast.h" -#include "WKSharedAPICast.h" +#include <wtf/text/StringBuilder.h> -namespace WebKit { +namespace API { -bool WebFullScreenClientGtk::willEnterFullScreen() +static uint64_t generateIdentifier() { - if (!m_client.willEnterFullScreen) - return true; + static uint64_t identifier; - return m_client.willEnterFullScreen(m_client.clientInfo); + return ++identifier; } -bool WebFullScreenClientGtk::willExitFullScreen() +WebCore::URL UserStyleSheet::generateUniqueURL() { - if (!m_client.willExitFullScreen) - return true; - - return m_client.willExitFullScreen(m_client.clientInfo); + StringBuilder urlStringBuilder; + urlStringBuilder.appendLiteral("user-style-sheet:"); + urlStringBuilder.appendNumber(generateIdentifier()); + return { { }, urlStringBuilder.toString() }; } -} // namespace WebKit + +} // namespace API diff --git a/Source/WebKit2/UIProcess/efl/FormClientEfl.h b/Source/WebKit2/UIProcess/API/APIUserStyleSheet.h index 666c44bb1..ac5754cac 100644 --- a/Source/WebKit2/UIProcess/efl/FormClientEfl.h +++ b/Source/WebKit2/UIProcess/API/APIUserStyleSheet.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 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,31 +23,29 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef FormClientEfl_h -#define FormClientEfl_h +#ifndef APIUserStyleSheet_h +#define APIUserStyleSheet_h -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> +#include "APIObject.h" +#include <WebCore/UserStyleSheet.h> -class EwkView; +namespace API { -namespace WebKit { - -class FormClientEfl { +class UserStyleSheet final : public ObjectImpl<Object::Type::UserStyleSheet> { public: - static PassOwnPtr<FormClientEfl> create(EwkView* viewImpl) + static WebCore::URL generateUniqueURL(); + + UserStyleSheet(WebCore::UserStyleSheet userStyleSheet) + : m_userStyleSheet(userStyleSheet) { - return adoptPtr(new FormClientEfl(viewImpl)); } -private: - explicit FormClientEfl(EwkView*); + const WebCore::UserStyleSheet& userStyleSheet() const { return m_userStyleSheet; } - static void willSubmitForm(WKPageRef, WKFrameRef, WKFrameRef, WKDictionaryRef values, WKTypeRef userData, WKFormSubmissionListenerRef, const void* clientInfo); - - EwkView* m_view; +private: + WebCore::UserStyleSheet m_userStyleSheet; }; -} // namespace WebKit +} // namespace API -#endif // FormClientEfl_h +#endif // APIUserStyleSheet_h diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.cpp b/Source/WebKit2/UIProcess/API/APIWebsiteDataRecord.cpp index c7ec13c8e..d4885904c 100644 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.cpp +++ b/Source/WebKit2/UIProcess/API/APIWebsiteDataRecord.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,24 +24,22 @@ */ #include "config.h" -#if USE(ACCELERATED_COMPOSITING) +#include "APIWebsiteDataRecord.h" -#include "EvasGLSurface.h" +namespace API { -namespace WebKit { +Ref<WebsiteDataRecord> WebsiteDataRecord::create(WebKit::WebsiteDataRecord&& websiteDataRecord) +{ + return adoptRef(*new WebsiteDataRecord(WTFMove(websiteDataRecord))); +} -EvasGLSurface::EvasGLSurface(Evas_GL* evasGL, Evas_GL_Surface* passSurface) - : m_evasGL(evasGL) - , m_surface(passSurface) +WebsiteDataRecord::WebsiteDataRecord(WebKit::WebsiteDataRecord&& websiteDataRecord) + : m_websiteDataRecord(WTFMove(websiteDataRecord)) { - ASSERT(evasGL); - ASSERT(passSurface); } -EvasGLSurface::~EvasGLSurface() +WebsiteDataRecord::~WebsiteDataRecord() { - evas_gl_surface_destroy(m_evasGL, m_surface); } -} // namespace WebKit -#endif +} diff --git a/Source/WebKit2/UIProcess/API/APIWebsiteDataRecord.h b/Source/WebKit2/UIProcess/API/APIWebsiteDataRecord.h new file mode 100644 index 000000000..0ccdb2190 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIWebsiteDataRecord.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2015 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 APIWebsiteDataRecord_h +#define APIWebsiteDataRecord_h + +#include "APIObject.h" +#include "WebsiteDataRecord.h" + +namespace API { + +class WebsiteDataRecord final : public ObjectImpl<Object::Type::WebsiteDataRecord> { +public: + static Ref<WebsiteDataRecord> create(WebKit::WebsiteDataRecord&&); + virtual ~WebsiteDataRecord(); + + const WebKit::WebsiteDataRecord& websiteDataRecord() const { return m_websiteDataRecord; } + +private: + explicit WebsiteDataRecord(WebKit::WebsiteDataRecord&&); + + const WebKit::WebsiteDataRecord m_websiteDataRecord; +}; + +} + +#endif // APIWebsiteDataRecord_h diff --git a/Source/WebKit2/UIProcess/API/APIWebsiteDataStore.cpp b/Source/WebKit2/UIProcess/API/APIWebsiteDataStore.cpp new file mode 100644 index 000000000..1d0873890 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIWebsiteDataStore.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2014 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 "APIWebsiteDataStore.h" + +#include "WebsiteDataStore.h" + +namespace API { + +RefPtr<WebsiteDataStore> WebsiteDataStore::defaultDataStore() +{ + static WebsiteDataStore* defaultDataStore = adoptRef(new WebsiteDataStore(defaultDataStoreConfiguration())).leakRef(); + + return defaultDataStore; +} + +Ref<WebsiteDataStore> WebsiteDataStore::createNonPersistentDataStore() +{ + return adoptRef(*new WebsiteDataStore); +} + +Ref<WebsiteDataStore> WebsiteDataStore::create(WebKit::WebsiteDataStore::Configuration configuration) +{ + return adoptRef(*new WebsiteDataStore(WTFMove(configuration))); +} + +WebsiteDataStore::WebsiteDataStore() + : m_websiteDataStore(WebKit::WebsiteDataStore::createNonPersistent()) +{ +} + +WebsiteDataStore::WebsiteDataStore(WebKit::WebsiteDataStore::Configuration configuration) + : m_websiteDataStore(WebKit::WebsiteDataStore::create(WTFMove(configuration))) +{ +} + +WebsiteDataStore::~WebsiteDataStore() +{ +} + +bool WebsiteDataStore::isPersistent() +{ + return m_websiteDataStore->isPersistent(); +} + +#if !PLATFORM(COCOA) && !PLATFORM(EFL) && !PLATFORM(GTK) +WebKit::WebsiteDataStore::Configuration WebsiteDataStore::defaultDataStoreConfiguration() +{ + // FIXME: Fill everything in. + WebKit::WebsiteDataStore::Configuration configuration; + + return configuration; +} + +String WebsiteDataStore::websiteDataDirectoryFileSystemRepresentation(const String&) +{ + // FIXME: Implement. + return String(); +} + +String WebsiteDataStore::defaultLocalStorageDirectory() +{ + // FIXME: Implement. + return String(); +} + +String WebsiteDataStore::defaultWebSQLDatabaseDirectory() +{ + // FIXME: Implement. + return String(); +} + +String WebsiteDataStore::defaultNetworkCacheDirectory() +{ + // FIXME: Implement. + return String(); +} + +String WebsiteDataStore::defaultApplicationCacheDirectory() +{ + // FIXME: Implement. + return String(); +} + +String WebsiteDataStore::defaultMediaKeysStorageDirectory() +{ + // FIXME: Implement. + return String(); +} + +String WebsiteDataStore::defaultIndexedDBDatabaseDirectory() +{ + // FIXME: Implement. + return String(); +} + +#endif + +} diff --git a/Source/WebKit2/UIProcess/API/APIWebsiteDataStore.h b/Source/WebKit2/UIProcess/API/APIWebsiteDataStore.h new file mode 100644 index 000000000..559b4a99b --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIWebsiteDataStore.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2014 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 APIWebsiteDataStore_h +#define APIWebsiteDataStore_h + +#include "APIObject.h" +#include "WebsiteDataStore.h" +#include <WebCore/SessionID.h> +#include <wtf/text/WTFString.h> + +namespace API { + +class WebsiteDataStore final : public ObjectImpl<Object::Type::WebsiteDataStore> { +public: + static RefPtr<WebsiteDataStore> defaultDataStore(); + static Ref<WebsiteDataStore> createNonPersistentDataStore(); + static Ref<WebsiteDataStore> create(WebKit::WebsiteDataStore::Configuration); + virtual ~WebsiteDataStore(); + + bool isPersistent(); + + WebKit::WebsiteDataStore& websiteDataStore() { return *m_websiteDataStore; } + + static String defaultApplicationCacheDirectory(); + static String defaultNetworkCacheDirectory(); + + static String defaultIndexedDBDatabaseDirectory(); + static String defaultLocalStorageDirectory(); + static String defaultMediaKeysStorageDirectory(); + static String defaultWebSQLDatabaseDirectory(); + +private: + WebsiteDataStore(WebKit::WebsiteDataStore::Configuration); + WebsiteDataStore(); + + static String cacheDirectoryFileSystemRepresentation(const String& directoryName); + static String websiteDataDirectoryFileSystemRepresentation(const String& directoryName); + + static WebKit::WebsiteDataStore::Configuration defaultDataStoreConfiguration(); + + RefPtr<WebKit::WebsiteDataStore> m_websiteDataStore; +}; + +} + +#endif // APIWebsiteDataStore_h diff --git a/Source/WebKit2/UIProcess/API/APIWindowFeatures.cpp b/Source/WebKit2/UIProcess/API/APIWindowFeatures.cpp new file mode 100644 index 000000000..f6fa0dc31 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIWindowFeatures.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2015 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 "APIWindowFeatures.h" + +namespace API { + +Ref<WindowFeatures> WindowFeatures::create(const WebCore::WindowFeatures& windowFeatures) +{ + return adoptRef(*new WindowFeatures(windowFeatures)); +} + +WindowFeatures::WindowFeatures(const WebCore::WindowFeatures& windowFeatures) + : m_windowFeatures(windowFeatures) +{ +} + +WindowFeatures::~WindowFeatures() +{ +} + +} diff --git a/Source/WebKit2/UIProcess/API/APIWindowFeatures.h b/Source/WebKit2/UIProcess/API/APIWindowFeatures.h new file mode 100644 index 000000000..ccedf79fd --- /dev/null +++ b/Source/WebKit2/UIProcess/API/APIWindowFeatures.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2015 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 APIWindowFeatures_h +#define APIWindowFeatures_h + +#include "APIObject.h" +#include <WebCore/WindowFeatures.h> + +namespace API { + +class WindowFeatures final : public ObjectImpl<Object::Type::WindowFeatures> { +public: + static Ref<WindowFeatures> create(const WebCore::WindowFeatures&); + virtual ~WindowFeatures(); + + const WebCore::WindowFeatures& windowFeatures() const { return m_windowFeatures; } + +private: + explicit WindowFeatures(const WebCore::WindowFeatures&); + + const WebCore::WindowFeatures m_windowFeatures; +}; + +} + +#endif // APIWindowFeatures_h diff --git a/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp index 2ed74d376..b14b99503 100644 --- a/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp +++ b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.cpp @@ -23,23 +23,19 @@ #include "WKView.h" +#include "APIPageConfiguration.h" #include "WKAPICast.h" #include "WebView.h" using namespace WebCore; using namespace WebKit; -WKViewRef WKViewCreate(WKContextRef contextRef, WKPageGroupRef pageGroupRef) +WKViewRef WKViewCreate(WKContextRef context, WKPageConfigurationRef pageConfiguration) { - RefPtr<WebView> webView = WebView::create(toImpl(contextRef), toImpl(pageGroupRef)); + RefPtr<WebView> webView = WebView::create(toImpl(context), *toImpl(pageConfiguration)); return toAPI(webView.release().leakRef()); } -void WKViewInitialize(WKViewRef viewRef) -{ - toImpl(viewRef)->initialize(); -} - WKSize WKViewGetSize(WKViewRef viewRef) { return toAPI(toImpl(viewRef)->size()); @@ -50,11 +46,21 @@ void WKViewSetSize(WKViewRef viewRef, WKSize size) toImpl(viewRef)->setSize(toIntSize(size)); } -void WKViewSetViewClient(WKViewRef viewRef, const WKViewClient* client) +void WKViewSetViewClient(WKViewRef viewRef, const WKViewClientBase* client) { toImpl(viewRef)->initializeClient(client); } +bool WKViewIsActive(WKViewRef viewRef) +{ + return toImpl(viewRef)->isActive(); +} + +void WKViewSetIsActive(WKViewRef viewRef, bool isActive) +{ + toImpl(viewRef)->setActive(isActive); +} + bool WKViewIsFocused(WKViewRef viewRef) { return toImpl(viewRef)->isFocused(); @@ -159,20 +165,10 @@ 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(); + return toImpl(viewRef)->requestExitFullScreen(); #else UNUSED_PARAM(viewRef); return false; @@ -191,8 +187,19 @@ double WKViewOpacity(WKViewRef view) void WKViewFindZoomableAreaForRect(WKViewRef viewRef, WKRect wkRect) { +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) IntRect rect = toIntRect(wkRect); toImpl(viewRef)->findZoomableAreaForPoint(rect.center(), rect.size()); +#else + UNUSED_PARAM(viewRef); + UNUSED_PARAM(wkRect); +#endif +} + +WKSize WKViewGetContentsSize(WKViewRef viewRef) +{ + const WebCore::IntSize& size = toImpl(viewRef)->contentsSize(); + return WKSizeMake(size.width(), size.height()); } #endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h index 1ee55ea34..60f4239e0 100644 --- a/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h +++ b/Source/WebKit2/UIProcess/API/C/CoordinatedGraphics/WKView.h @@ -21,8 +21,8 @@ #ifndef WKView_h #define WKView_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKGeometry.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKGeometry.h> #ifndef __cplusplus #include <stdbool.h> @@ -43,10 +43,13 @@ typedef void (*WKViewPageDidChangeTooltipCallback)(WKViewRef view, WKStringRef n 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 { +typedef struct WKViewClientBase { int version; const void* clientInfo; +} WKViewClientBase; +typedef struct WKViewClientV0 { + WKViewClientBase base; // Version 0 WKViewViewNeedsDisplayCallback viewNeedsDisplay; WKViewPageDidChangeContentsSizeCallback didChangeContentsSize; @@ -59,19 +62,17 @@ struct WKViewClient { WKViewPageDidChangeTooltipCallback didChangeTooltip; WKViewDidFindZoomableAreaCallback didFindZoomableArea; WKViewDoneWithTouchEventCallback doneWithTouchEvent; -}; -typedef struct WKViewClient WKViewClient; +} WKViewClientV0; -enum { kWKViewClientCurrentVersion = 0 }; - -WK_EXPORT WKViewRef WKViewCreate(WKContextRef context, WKPageGroupRef pageGroup); - -WK_EXPORT void WKViewInitialize(WKViewRef); +WK_EXPORT WKViewRef WKViewCreate(WKContextRef context, WKPageConfigurationRef pageConfiguration); WK_EXPORT WKSize WKViewGetSize(WKViewRef); WK_EXPORT void WKViewSetSize(WKViewRef, WKSize size); -WK_EXPORT void WKViewSetViewClient(WKViewRef, const WKViewClient*); +WK_EXPORT void WKViewSetViewClient(WKViewRef, const WKViewClientBase*); + +WK_EXPORT bool WKViewIsActive(WKViewRef); +WK_EXPORT void WKViewSetIsActive(WKViewRef, bool); WK_EXPORT bool WKViewIsFocused(WKViewRef); WK_EXPORT void WKViewSetIsFocused(WKViewRef, bool); @@ -103,9 +104,6 @@ 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); @@ -113,6 +111,8 @@ WK_EXPORT double WKViewOpacity(WKViewRef view); WK_EXPORT void WKViewFindZoomableAreaForRect(WKViewRef, WKRect); +WK_EXPORT WKSize WKViewGetContentsSize(WKViewRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKAPICast.h b/Source/WebKit2/UIProcess/API/C/WKAPICast.h index 64c8d1abf..ee7f2dfc5 100644 --- a/Source/WebKit2/UIProcess/API/C/WKAPICast.h +++ b/Source/WebKit2/UIProcess/API/C/WKAPICast.h @@ -32,24 +32,41 @@ #include "HTTPCookieAcceptPolicy.h" #include "InjectedBundleHitTestResultMediaType.h" #include "PluginModuleInfo.h" -#include "ProcessModel.h" #include "ResourceCachesToClear.h" #include "WKBundleHitTestResult.h" #include "WKContext.h" #include "WKCookieManager.h" #include "WKCredentialTypes.h" #include "WKPage.h" -#include "WKPreferences.h" -#include "WKPreferencesPrivate.h" +#include "WKPreferencesRef.h" +#include "WKPreferencesRefPrivate.h" #include "WKProtectionSpaceTypes.h" #include "WKResourceCacheManager.h" #include "WKSharedAPICast.h" #include "WebGrammarDetail.h" #include <WebCore/Credential.h> #include <WebCore/FrameLoaderTypes.h> +#include <WebCore/PluginData.h> #include <WebCore/ProtectionSpace.h> #include <WebCore/Settings.h> +namespace API { +class FrameInfo; +class HitTestResult; +class Navigation; +class NavigationAction; +class NavigationData; +class NavigationResponse; +class PageConfiguration; +class ProcessPoolConfiguration; +class SessionState; +class UserContentExtension; +class UserContentExtensionStore; +class UserScript; +class WebsiteDataStore; +class WindowFeatures; +} + namespace WebKit { class AuthenticationChallengeProxy; @@ -57,48 +74,42 @@ class AuthenticationDecisionListener; class DownloadProxy; class GeolocationPermissionRequestProxy; class NotificationPermissionRequest; -class WebApplicationCacheManagerProxy; +class UserMediaPermissionCheckProxy; +class UserMediaPermissionRequestProxy; class WebBackForwardList; class WebBackForwardListItem; class WebBatteryManagerProxy; class WebBatteryStatus; -class WebResourceCacheManagerProxy; class WebColorPickerResultListenerProxy; -class WebContext; class WebCookieManagerProxy; class WebCredential; -class WebDatabaseManagerProxy; class WebFormSubmissionListenerProxy; class WebFramePolicyListenerProxy; class WebFrameProxy; class WebGeolocationManagerProxy; class WebGeolocationPosition; class WebGrammarDetail; -class WebHitTestResult; class WebIconDatabase; class WebInspectorProxy; -class WebKeyValueStorageManager; -class WebMediaCacheManagerProxy; -class WebNavigationData; -class WebNetworkInfoManagerProxy; -class WebNetworkInfo; +class WebMediaSessionFocusManager; +class WebMediaSessionMetadata; class WebNotification; -class WebNotificationProvider; class WebNotificationManagerProxy; +class WebNotificationProvider; class WebOpenPanelParameters; class WebOpenPanelResultListenerProxy; class WebPageGroup; class WebPageProxy; -class WebPluginSiteDataManager; class WebPreferences; +class WebProcessPool; class WebProtectionSpace; class WebRenderLayer; class WebRenderObject; class WebTextChecker; +class WebUserContentControllerProxy; class WebVibrationProxy; class WebViewportAttributes; -WK_ADD_API_MAPPING(WKApplicationCacheManagerRef, WebApplicationCacheManagerProxy) WK_ADD_API_MAPPING(WKAuthenticationChallengeRef, AuthenticationChallengeProxy) WK_ADD_API_MAPPING(WKAuthenticationDecisionListenerRef, AuthenticationDecisionListener) WK_ADD_API_MAPPING(WKBackForwardListItemRef, WebBackForwardListItem) @@ -106,27 +117,29 @@ 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) +WK_ADD_API_MAPPING(WKContextRef, WebProcessPool) +WK_ADD_API_MAPPING(WKContextConfigurationRef, API::ProcessPoolConfiguration) WK_ADD_API_MAPPING(WKCookieManagerRef, WebCookieManagerProxy) WK_ADD_API_MAPPING(WKCredentialRef, WebCredential) -WK_ADD_API_MAPPING(WKDatabaseManagerRef, WebDatabaseManagerProxy) WK_ADD_API_MAPPING(WKDownloadRef, DownloadProxy) WK_ADD_API_MAPPING(WKFormSubmissionListenerRef, WebFormSubmissionListenerProxy) WK_ADD_API_MAPPING(WKFramePolicyListenerRef, WebFramePolicyListenerProxy) +WK_ADD_API_MAPPING(WKFrameInfoRef, API::FrameInfo) WK_ADD_API_MAPPING(WKFrameRef, WebFrameProxy) WK_ADD_API_MAPPING(WKGeolocationManagerRef, WebGeolocationManagerProxy) WK_ADD_API_MAPPING(WKGeolocationPermissionRequestRef, GeolocationPermissionRequestProxy) WK_ADD_API_MAPPING(WKGeolocationPositionRef, WebGeolocationPosition) WK_ADD_API_MAPPING(WKGrammarDetailRef, WebGrammarDetail) -WK_ADD_API_MAPPING(WKHitTestResultRef, WebHitTestResult) +WK_ADD_API_MAPPING(WKHitTestResultRef, API::HitTestResult) WK_ADD_API_MAPPING(WKIconDatabaseRef, WebIconDatabase) -WK_ADD_API_MAPPING(WKKeyValueStorageManagerRef, WebKeyValueStorageManager) -WK_ADD_API_MAPPING(WKMediaCacheManagerRef, WebMediaCacheManagerProxy) -WK_ADD_API_MAPPING(WKNavigationDataRef, WebNavigationData) -WK_ADD_API_MAPPING(WKNetworkInfoManagerRef, WebNetworkInfoManagerProxy) -WK_ADD_API_MAPPING(WKNetworkInfoRef, WebNetworkInfo) +WK_ADD_API_MAPPING(WKInspectorRef, WebInspectorProxy) +WK_ADD_API_MAPPING(WKMediaSessionFocusManagerRef, WebMediaSessionFocusManager) +WK_ADD_API_MAPPING(WKMediaSessionMetadataRef, WebMediaSessionMetadata) +WK_ADD_API_MAPPING(WKNavigationActionRef, API::NavigationAction) +WK_ADD_API_MAPPING(WKNavigationDataRef, API::NavigationData) +WK_ADD_API_MAPPING(WKNavigationRef, API::Navigation) +WK_ADD_API_MAPPING(WKNavigationResponseRef, API::NavigationResponse) WK_ADD_API_MAPPING(WKNotificationManagerRef, WebNotificationManagerProxy) WK_ADD_API_MAPPING(WKNotificationPermissionRequestRef, NotificationPermissionRequest) WK_ADD_API_MAPPING(WKNotificationProviderRef, WebNotificationProvider) @@ -134,16 +147,24 @@ WK_ADD_API_MAPPING(WKNotificationRef, WebNotification) WK_ADD_API_MAPPING(WKOpenPanelParametersRef, WebOpenPanelParameters) WK_ADD_API_MAPPING(WKOpenPanelResultListenerRef, WebOpenPanelResultListenerProxy) WK_ADD_API_MAPPING(WKPageGroupRef, WebPageGroup) +WK_ADD_API_MAPPING(WKPageConfigurationRef, API::PageConfiguration) WK_ADD_API_MAPPING(WKPageRef, WebPageProxy) -WK_ADD_API_MAPPING(WKPluginSiteDataManagerRef, WebPluginSiteDataManager) WK_ADD_API_MAPPING(WKPreferencesRef, WebPreferences) WK_ADD_API_MAPPING(WKProtectionSpaceRef, WebProtectionSpace) WK_ADD_API_MAPPING(WKRenderLayerRef, WebRenderLayer) WK_ADD_API_MAPPING(WKRenderObjectRef, WebRenderObject) +WK_ADD_API_MAPPING(WKSessionStateRef, API::SessionState) WK_ADD_API_MAPPING(WKTextCheckerRef, WebTextChecker) +WK_ADD_API_MAPPING(WKUserContentControllerRef, WebUserContentControllerProxy) +WK_ADD_API_MAPPING(WKUserContentExtensionStoreRef, API::UserContentExtensionStore) +WK_ADD_API_MAPPING(WKUserContentFilterRef, API::UserContentExtension) +WK_ADD_API_MAPPING(WKUserMediaPermissionCheckRef, UserMediaPermissionCheckProxy) +WK_ADD_API_MAPPING(WKUserMediaPermissionRequestRef, UserMediaPermissionRequestProxy) +WK_ADD_API_MAPPING(WKUserScriptRef, API::UserScript) WK_ADD_API_MAPPING(WKVibrationRef, WebVibrationProxy) WK_ADD_API_MAPPING(WKViewportAttributesRef, WebViewportAttributes) -WK_ADD_API_MAPPING(WKInspectorRef, WebInspectorProxy) +WK_ADD_API_MAPPING(WKWebsiteDataStoreRef, API::WebsiteDataStore) +WK_ADD_API_MAPPING(WKWindowFeaturesRef, API::WindowFeatures) /* Enum conversions */ @@ -206,31 +227,6 @@ inline WKCacheModel toAPI(CacheModel cacheModel) return kWKCacheModelDocumentViewer; } -inline ProcessModel toProcessModel(WKProcessModel wkProcessModel) -{ - switch (wkProcessModel) { - case kWKProcessModelSharedSecondaryProcess: - return ProcessModelSharedSecondaryProcess; - case kWKProcessModelMultipleSecondaryProcesses: - return ProcessModelMultipleSecondaryProcesses; - } - - ASSERT_NOT_REACHED(); - return ProcessModelSharedSecondaryProcess; -} - -inline WKProcessModel toAPI(ProcessModel processModel) -{ - switch (processModel) { - case ProcessModelSharedSecondaryProcess: - return kWKProcessModelSharedSecondaryProcess; - case ProcessModelMultipleSecondaryProcesses: - return kWKProcessModelMultipleSecondaryProcesses; - } - - return kWKProcessModelSharedSecondaryProcess; -} - inline FontSmoothingLevel toFontSmoothingLevel(WKFontSmoothingLevel wkLevel) { switch (wkLevel) { @@ -387,6 +383,8 @@ inline HTTPCookieAcceptPolicy toHTTPCookieAcceptPolicy(WKHTTPCookieAcceptPolicy return HTTPCookieAcceptPolicyNever; case kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain: return HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain; + case kWKHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain: + return HTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain; } ASSERT_NOT_REACHED(); @@ -402,6 +400,8 @@ inline WKHTTPCookieAcceptPolicy toAPI(HTTPCookieAcceptPolicy policy) return kWKHTTPCookieAcceptPolicyNever; case HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain: return kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain; + case HTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain: + return kWKHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain; } ASSERT_NOT_REACHED(); @@ -445,27 +445,99 @@ inline WKPluginLoadPolicy toWKPluginLoadPolicy(PluginModuleLoadPolicy pluginModu return kWKPluginLoadPolicyLoadNormally; case PluginModuleLoadUnsandboxed: return kWKPluginLoadPolicyLoadUnsandboxed; - case PluginModuleBlocked: + case PluginModuleBlockedForSecurity: return kWKPluginLoadPolicyBlocked; + case PluginModuleBlockedForCompatibility: + return kWKPluginLoadPolicyBlockedForCompatibility; } ASSERT_NOT_REACHED(); return kWKPluginLoadPolicyBlocked; } +inline WKPluginLoadClientPolicy toWKPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy PluginLoadClientPolicy) +{ + switch (PluginLoadClientPolicy) { + case WebCore::PluginLoadClientPolicyUndefined: + return kWKPluginLoadClientPolicyUndefined; + case WebCore::PluginLoadClientPolicyBlock: + return kWKPluginLoadClientPolicyBlock; + case WebCore::PluginLoadClientPolicyAsk: + return kWKPluginLoadClientPolicyAsk; + case WebCore::PluginLoadClientPolicyAllow: + return kWKPluginLoadClientPolicyAllow; + case WebCore::PluginLoadClientPolicyAllowAlways: + return kWKPluginLoadClientPolicyAllowAlways; + } + + ASSERT_NOT_REACHED(); + return kWKPluginLoadClientPolicyBlock; +} + inline PluginModuleLoadPolicy toPluginModuleLoadPolicy(WKPluginLoadPolicy pluginLoadPolicy) { switch (pluginLoadPolicy) { case kWKPluginLoadPolicyLoadNormally: return PluginModuleLoadNormally; case kWKPluginLoadPolicyBlocked: - return PluginModuleBlocked; + return PluginModuleBlockedForSecurity; + case kWKPluginLoadPolicyBlockedForCompatibility: + return PluginModuleBlockedForCompatibility; case kWKPluginLoadPolicyLoadUnsandboxed: return PluginModuleLoadUnsandboxed; } ASSERT_NOT_REACHED(); - return PluginModuleBlocked; + return PluginModuleBlockedForSecurity; +} + +inline WebCore::PluginLoadClientPolicy toPluginLoadClientPolicy(WKPluginLoadClientPolicy pluginLoadClientPolicy) +{ + switch (pluginLoadClientPolicy) { + case kWKPluginLoadClientPolicyUndefined: + return WebCore::PluginLoadClientPolicyUndefined; + case kWKPluginLoadClientPolicyBlock: + return WebCore::PluginLoadClientPolicyBlock; + case kWKPluginLoadClientPolicyAsk: + return WebCore::PluginLoadClientPolicyAsk; + case kWKPluginLoadClientPolicyAllow: + return WebCore::PluginLoadClientPolicyAllow; + case kWKPluginLoadClientPolicyAllowAlways: + return WebCore::PluginLoadClientPolicyAllowAlways; + } + + ASSERT_NOT_REACHED(); + return WebCore::PluginLoadClientPolicyBlock; +} + +inline WebCore::WebGLLoadPolicy toWebGLLoadPolicy(WKWebGLLoadPolicy webGLLoadPolicy) +{ + switch (webGLLoadPolicy) { + case kWKWebGLLoadPolicyLoadNormally: + return WebCore::WebGLAllowCreation; + case kWKWebGLLoadPolicyBlocked: + return WebCore::WebGLBlockCreation; + case kWKWebGLLoadPolicyPending: + return WebCore::WebGLPendingCreation; + } + + ASSERT_NOT_REACHED(); + return WebCore::WebGLAllowCreation; +} + +inline WKWebGLLoadPolicy toAPI(WebCore::WebGLLoadPolicy webGLLoadPolicy) +{ + switch (webGLLoadPolicy) { + case WebCore::WebGLAllowCreation: + return kWKWebGLLoadPolicyLoadNormally; + case WebCore::WebGLBlockCreation: + return kWKWebGLLoadPolicyBlocked; + case WebCore::WebGLPendingCreation: + return kWKWebGLLoadPolicyPending; + } + + ASSERT_NOT_REACHED(); + return kWKWebGLLoadPolicyLoadNormally; } inline ProxyingRefPtr<WebGrammarDetail> toAPI(const WebCore::GrammarDetail& grammarDetail) diff --git a/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.cpp b/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.cpp index 2d95c6721..72b3fa5c8 100644 --- a/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.cpp @@ -26,27 +26,43 @@ #include "config.h" #include "WKApplicationCacheManager.h" +#include "APIWebsiteDataStore.h" #include "WKAPICast.h" -#include "WebApplicationCacheManagerProxy.h" +#include "WebsiteDataRecord.h" using namespace WebKit; WKTypeID WKApplicationCacheManagerGetTypeID() { - return toAPI(WebApplicationCacheManagerProxy::APIType); + return toAPI(API::WebsiteDataStore::APIType); } -void WKApplicationCacheManagerGetApplicationCacheOrigins(WKApplicationCacheManagerRef applicationCacheManagerRef, void* context, WKApplicationCacheManagerGetApplicationCacheOriginsFunction callback) +void WKApplicationCacheManagerGetApplicationCacheOrigins(WKApplicationCacheManagerRef applicationCacheManager, void* context, WKApplicationCacheManagerGetApplicationCacheOriginsFunction callback) { - toImpl(applicationCacheManagerRef)->getApplicationCacheOrigins(ArrayCallback::create(context, callback)); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(applicationCacheManager))->websiteDataStore(); + websiteDataStore.fetchData(WebsiteDataTypes::WebsiteDataTypeOfflineWebApplicationCache, [context, callback](Vector<WebsiteDataRecord> dataRecords) { + Vector<RefPtr<API::Object>> securityOrigins; + for (const auto& dataRecord : dataRecords) { + for (const auto& origin : dataRecord.origins) + securityOrigins.append(API::SecurityOrigin::create(*origin)); + } + + callback(toAPI(API::Array::create(WTFMove(securityOrigins)).ptr()), nullptr, context); + }); } -void WKApplicationCacheManagerDeleteEntriesForOrigin(WKApplicationCacheManagerRef applicationCacheManagerRef, WKSecurityOriginRef originRef) +void WKApplicationCacheManagerDeleteEntriesForOrigin(WKApplicationCacheManagerRef applicationCacheManager, WKSecurityOriginRef origin) { - toImpl(applicationCacheManagerRef)->deleteEntriesForOrigin(toImpl(originRef)); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(applicationCacheManager))->websiteDataStore(); + + WebsiteDataRecord dataRecord; + dataRecord.add(WebsiteDataTypes::WebsiteDataTypeOfflineWebApplicationCache, &toImpl(origin)->securityOrigin()); + + websiteDataStore.removeData(WebsiteDataTypes::WebsiteDataTypeOfflineWebApplicationCache, { dataRecord }, [] { }); } -void WKApplicationCacheManagerDeleteAllEntries(WKApplicationCacheManagerRef applicationCacheManagerRef) +void WKApplicationCacheManagerDeleteAllEntries(WKApplicationCacheManagerRef applicationCacheManager) { - toImpl(applicationCacheManagerRef)->deleteAllEntries(); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(applicationCacheManager))->websiteDataStore(); + websiteDataStore.removeData(WebsiteDataTypes::WebsiteDataTypeOfflineWebApplicationCache, std::chrono::system_clock::time_point::min(), [] { }); } diff --git a/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.h b/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.h index c40039e37..065a462d4 100644 --- a/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKApplicationCacheManager.h @@ -26,7 +26,7 @@ #ifndef WKApplicationCacheManager_h #define WKApplicationCacheManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.cpp b/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.cpp index c42b85732..17067cc32 100644 --- a/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.cpp @@ -27,10 +27,11 @@ #include "WKAuthenticationChallenge.h" #include "AuthenticationChallengeProxy.h" +#include "AuthenticationDecisionListener.h" +#include "WKAPICast.h" #include "WebCertificateInfo.h" #include "WebCredential.h" #include "WebProtectionSpace.h" -#include "WKAPICast.h" using namespace WebKit; diff --git a/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.h b/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.h index 3802f417f..bc2cf2e7e 100644 --- a/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.h +++ b/Source/WebKit2/UIProcess/API/C/WKAuthenticationChallenge.h @@ -26,7 +26,7 @@ #ifndef WKAuthenticationChallenge_h #define WKAuthenticationChallenge_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.cpp b/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.cpp index bcb175dfd..06ca308b5 100644 --- a/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.cpp @@ -28,6 +28,7 @@ #include "AuthenticationDecisionListener.h" #include "WKAPICast.h" +#include "WebCredential.h" using namespace WebKit; diff --git a/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.h b/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.h index f0724610b..2134de091 100644 --- a/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.h +++ b/Source/WebKit2/UIProcess/API/C/WKAuthenticationDecisionListener.h @@ -26,7 +26,7 @@ #ifndef WKAuthenticationDecisionListener_h #define WKAuthenticationDecisionListener_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKBackForwardListItem.cpp b/Source/WebKit2/UIProcess/API/C/WKBackForwardListItemRef.cpp index 00dc6da41..fea7fb941 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBackForwardListItem.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKBackForwardListItemRef.cpp @@ -24,7 +24,7 @@ */ #include "config.h" -#include "WKBackForwardListItem.h" +#include "WKBackForwardListItemRef.h" #include "WKAPICast.h" #include "WebBackForwardListItem.h" diff --git a/Source/WebKit2/UIProcess/API/C/WKBackForwardListItem.h b/Source/WebKit2/UIProcess/API/C/WKBackForwardListItemRef.h index 3810d1523..f63ba5f45 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBackForwardListItem.h +++ b/Source/WebKit2/UIProcess/API/C/WKBackForwardListItemRef.h @@ -23,10 +23,10 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKBackForwardListItem_h -#define WKBackForwardListItem_h +#ifndef WKBackForwardListItemRef_h +#define WKBackForwardListItemRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -42,4 +42,4 @@ WK_EXPORT WKURLRef WKBackForwardListItemCopyOriginalURL(WKBackForwardListItemRef } #endif -#endif /* WKBackForwardListItem_h */ +#endif /* WKBackForwardListItemRef_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKBackForwardList.cpp b/Source/WebKit2/UIProcess/API/C/WKBackForwardListRef.cpp index f7129b866..4be7fc369 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBackForwardList.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKBackForwardListRef.cpp @@ -24,8 +24,9 @@ */ #include "config.h" -#include "WKBackForwardList.h" +#include "WKBackForwardListRef.h" +#include "APIArray.h" #include "WebBackForwardList.h" #include "WKAPICast.h" @@ -56,6 +57,11 @@ WKBackForwardListItemRef WKBackForwardListGetItemAtIndex(WKBackForwardListRef li return toAPI(toImpl(listRef)->itemAtIndex(index)); } +void WKBackForwardListClear(WKBackForwardListRef listRef) +{ + toImpl(listRef)->clear(); +} + unsigned WKBackForwardListGetBackListCount(WKBackForwardListRef listRef) { return toImpl(listRef)->backListCount(); @@ -68,10 +74,10 @@ unsigned WKBackForwardListGetForwardListCount(WKBackForwardListRef listRef) WKArrayRef WKBackForwardListCopyBackListWithLimit(WKBackForwardListRef listRef, unsigned limit) { - return toAPI(toImpl(listRef)->backListAsImmutableArrayWithLimit(limit).leakRef()); + return toAPI(&toImpl(listRef)->backListAsAPIArrayWithLimit(limit).leakRef()); } WKArrayRef WKBackForwardListCopyForwardListWithLimit(WKBackForwardListRef listRef, unsigned limit) { - return toAPI(toImpl(listRef)->forwardListAsImmutableArrayWithLimit(limit).leakRef()); + return toAPI(&toImpl(listRef)->forwardListAsAPIArrayWithLimit(limit).leakRef()); } diff --git a/Source/WebKit2/UIProcess/API/C/WKBackForwardList.h b/Source/WebKit2/UIProcess/API/C/WKBackForwardListRef.h index 214a6bc81..97b2209d2 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBackForwardList.h +++ b/Source/WebKit2/UIProcess/API/C/WKBackForwardListRef.h @@ -23,10 +23,10 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKBackForwardList_h -#define WKBackForwardList_h +#ifndef WKBackForwardListRef_h +#define WKBackForwardListRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -39,6 +39,8 @@ WK_EXPORT WKBackForwardListItemRef WKBackForwardListGetBackItem(WKBackForwardLis WK_EXPORT WKBackForwardListItemRef WKBackForwardListGetForwardItem(WKBackForwardListRef list); WK_EXPORT WKBackForwardListItemRef WKBackForwardListGetItemAtIndex(WKBackForwardListRef list, int index); +WK_EXPORT void WKBackForwardListClear(WKBackForwardListRef list); + WK_EXPORT unsigned WKBackForwardListGetBackListCount(WKBackForwardListRef list); WK_EXPORT unsigned WKBackForwardListGetForwardListCount(WKBackForwardListRef list); @@ -49,4 +51,4 @@ WK_EXPORT WKArrayRef WKBackForwardListCopyForwardListWithLimit(WKBackForwardList } #endif -#endif // WKBackForwardList_h +#endif // WKBackForwardListRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WKBatteryManager.cpp b/Source/WebKit2/UIProcess/API/C/WKBatteryManager.cpp index 950336d56..7a87d5d85 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBatteryManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKBatteryManager.cpp @@ -31,6 +31,7 @@ #if ENABLE(BATTERY_STATUS) #include "WebBatteryManagerProxy.h" +#include "WebBatteryStatus.h" #endif using namespace WebKit; @@ -44,10 +45,13 @@ WKTypeID WKBatteryManagerGetTypeID() #endif } -void WKBatteryManagerSetProvider(WKBatteryManagerRef batteryManager, const WKBatteryProvider* provider) +void WKBatteryManagerSetProvider(WKBatteryManagerRef batteryManager, const WKBatteryProviderBase* provider) { #if ENABLE(BATTERY_STATUS) toImpl(batteryManager)->initializeProvider(provider); +#else + UNUSED_PARAM(batteryManager); + UNUSED_PARAM(provider); #endif } @@ -55,6 +59,10 @@ void WKBatteryManagerProviderDidChangeBatteryStatus(WKBatteryManagerRef batteryM { #if ENABLE(BATTERY_STATUS) toImpl(batteryManager)->providerDidChangeBatteryStatus(AtomicString(toImpl(eventType)->string()), toImpl(status)); +#else + UNUSED_PARAM(batteryManager); + UNUSED_PARAM(eventType); + UNUSED_PARAM(status); #endif } @@ -62,5 +70,8 @@ void WKBatteryManagerProviderUpdateBatteryStatus(WKBatteryManagerRef batteryMana { #if ENABLE(BATTERY_STATUS) toImpl(batteryManager)->providerUpdateBatteryStatus(toImpl(status)); +#else + UNUSED_PARAM(batteryManager); + UNUSED_PARAM(status); #endif } diff --git a/Source/WebKit2/UIProcess/API/C/WKBatteryManager.h b/Source/WebKit2/UIProcess/API/C/WKBatteryManager.h index 712cbfb4c..5c2ce7585 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBatteryManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKBatteryManager.h @@ -26,7 +26,7 @@ #ifndef WKBatteryManager_h #define WKBatteryManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -36,19 +36,21 @@ extern "C" { typedef void (*WKBatteryProviderStartUpdatingCallback)(WKBatteryManagerRef batteryManager, const void* clientInfo); typedef void (*WKBatteryProviderStopUpdatingCallback)(WKBatteryManagerRef batteryManager, const void* clientInfo); -struct WKBatteryProvider { +typedef struct WKBatteryProviderBase { int version; const void * clientInfo; +} WKBatteryProviderBase; + +typedef struct WKBatteryProviderV0 { + WKBatteryProviderBase base; + WKBatteryProviderStartUpdatingCallback startUpdating; WKBatteryProviderStopUpdatingCallback stopUpdating; -}; -typedef struct WKBatteryProvider WKBatteryProvider; - -enum { kWKBatteryProviderCurrentVersion = 0 }; +} WKBatteryProviderV0; WK_EXPORT WKTypeID WKBatteryManagerGetTypeID(); -WK_EXPORT void WKBatteryManagerSetProvider(WKBatteryManagerRef batteryManager, const WKBatteryProvider* provider); +WK_EXPORT void WKBatteryManagerSetProvider(WKBatteryManagerRef batteryManager, const WKBatteryProviderBase* provider); WK_EXPORT void WKBatteryManagerProviderDidChangeBatteryStatus(WKBatteryManagerRef batteryManager, WKStringRef eventType, WKBatteryStatusRef status); WK_EXPORT void WKBatteryManagerProviderUpdateBatteryStatus(WKBatteryManagerRef batteryManager, WKBatteryStatusRef status); diff --git a/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.cpp b/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.cpp index 0069a6f95..953850d8b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.cpp @@ -49,6 +49,10 @@ WKBatteryStatusRef WKBatteryStatusCreate(bool isCharging, double chargingTime, d RefPtr<WebBatteryStatus> status = WebBatteryStatus::create(isCharging, chargingTime, dischargingTime, level); return toAPI(status.release().leakRef()); #else + UNUSED_PARAM(isCharging); + UNUSED_PARAM(chargingTime); + UNUSED_PARAM(dischargingTime); + UNUSED_PARAM(level); return 0; #endif } diff --git a/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.h b/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.h index afa1dd931..b32b99fd7 100644 --- a/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.h +++ b/Source/WebKit2/UIProcess/API/C/WKBatteryStatus.h @@ -26,7 +26,7 @@ #ifndef WKBatteryStatus_h #define WKBatteryStatus_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKColorPickerResultListener.cpp b/Source/WebKit2/UIProcess/API/C/WKColorPickerResultListener.cpp deleted file mode 100644 index de5539de1..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKColorPickerResultListener.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2012 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 "WKColorPickerResultListener.h" - -#include "WKAPICast.h" -#include "WebColorPickerResultListenerProxy.h" - -using namespace WebKit; - -WKTypeID WKColorPickerResultListenerGetTypeID() -{ -#if ENABLE(INPUT_TYPE_COLOR) - return toAPI(WebColorPickerResultListenerProxy::APIType); -#else - return 0; -#endif -} - -void WKColorPickerResultListenerSetColor(WKColorPickerResultListenerRef listenerRef, const WKStringRef color) -{ -#if ENABLE(INPUT_TYPE_COLOR) - toImpl(listenerRef)->setColor(toWTFString(color)); -#endif -} diff --git a/Source/WebKit2/UIProcess/API/C/WKColorPickerResultListener.h b/Source/WebKit2/UIProcess/API/C/WKColorPickerResultListener.h deleted file mode 100644 index bfd4732c9..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKColorPickerResultListener.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WKColorPickerResultListener_h -#define WKColorPickerResultListener_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -WK_EXPORT WKTypeID WKColorPickerResultListenerGetTypeID(); - -WK_EXPORT void WKColorPickerResultListenerSetColor(WKColorPickerResultListenerRef listenerRef, const WKStringRef color); - -#ifdef __cplusplus -} -#endif - -#endif /* WKColorPickerResultListener_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKContext.cpp b/Source/WebKit2/UIProcess/API/C/WKContext.cpp index 1629a5627..98555a2d6 100644 --- a/Source/WebKit2/UIProcess/API/C/WKContext.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKContext.cpp @@ -24,91 +24,266 @@ */ #include "config.h" -#include "WKContext.h" #include "WKContextPrivate.h" +#include "APIClient.h" +#include "APIDownloadClient.h" +#include "APILegacyContextHistoryClient.h" +#include "APINavigationData.h" +#include "APIProcessPoolConfiguration.h" +#include "APIURLRequest.h" +#include "AuthenticationChallengeProxy.h" +#include "DownloadProxy.h" #include "WKAPICast.h" -#include "WebContext.h" -#include "WebURLRequest.h" +#include "WKContextConfigurationRef.h" +#include "WKRetainPtr.h" +#include "WebCertificateInfo.h" +#include "WebIconDatabase.h" +#include "WebProcessPool.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.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" { -// For binary compatibility with Safari 5.1. Should be removed eventually. -WK_EXPORT void _WKContextSetAdditionalPluginsDirectory(WKContextRef context, WKStringRef pluginsDirectory); -WK_EXPORT void _WKContextRegisterURLSchemeAsEmptyDocument(WKContextRef context, WKStringRef urlScheme); -WK_EXPORT void _WKContextSetAlwaysUsesComplexTextCodePath(WKContextRef context, bool alwaysUseComplexTextCodePath); -WK_EXPORT void _WKContextSetHTTPPipeliningEnabled(WKContextRef context, bool enabled); +namespace API { +template<> struct ClientTraits<WKContextDownloadClientBase> { + typedef std::tuple<WKContextDownloadClientV0> Versions; +}; +template<> struct ClientTraits<WKContextHistoryClientBase> { + typedef std::tuple<WKContextHistoryClientV0> Versions; +}; } +using namespace WebCore; +using namespace WebKit; + WKTypeID WKContextGetTypeID() { - return toAPI(WebContext::APIType); + return toAPI(WebProcessPool::APIType); } WKContextRef WKContextCreate() { - RefPtr<WebContext> context = WebContext::create(String()); - return toAPI(context.release().leakRef()); + auto configuration = API::ProcessPoolConfiguration::createWithLegacyOptions(); + return toAPI(&WebProcessPool::create(configuration).leakRef()); } WKContextRef WKContextCreateWithInjectedBundlePath(WKStringRef pathRef) { - RefPtr<WebContext> context = WebContext::create(toImpl(pathRef)->string()); - return toAPI(context.release().leakRef()); + auto configuration = API::ProcessPoolConfiguration::createWithLegacyOptions(); + configuration->setInjectedBundlePath(toWTFString(pathRef)); + + return toAPI(&WebProcessPool::create(configuration).leakRef()); } -void WKContextSetClient(WKContextRef contextRef, const WKContextClient* wkClient) +WKContextRef WKContextCreateWithConfiguration(WKContextConfigurationRef configuration) { - toImpl(contextRef)->initializeClient(wkClient); + return toAPI(&WebProcessPool::create(*toImpl(configuration)).leakRef()); } -void WKContextSetInjectedBundleClient(WKContextRef contextRef, const WKContextInjectedBundleClient* wkClient) +void WKContextSetClient(WKContextRef contextRef, const WKContextClientBase* wkClient) { - toImpl(contextRef)->initializeInjectedBundleClient(wkClient); + toImpl(contextRef)->initializeClient(wkClient); } -void WKContextSetHistoryClient(WKContextRef contextRef, const WKContextHistoryClient* wkClient) +void WKContextSetInjectedBundleClient(WKContextRef contextRef, const WKContextInjectedBundleClientBase* wkClient) { - toImpl(contextRef)->initializeHistoryClient(wkClient); + toImpl(contextRef)->initializeInjectedBundleClient(wkClient); } -void WKContextSetDownloadClient(WKContextRef contextRef, const WKContextDownloadClient* wkClient) +void WKContextSetHistoryClient(WKContextRef contextRef, const WKContextHistoryClientBase* wkClient) { - toImpl(contextRef)->initializeDownloadClient(wkClient); -} + class HistoryClient final : public API::Client<WKContextHistoryClientBase>, public API::LegacyContextHistoryClient { + public: + explicit HistoryClient(const WKContextHistoryClientBase* client) + { + initialize(client); + } -void WKContextSetConnectionClient(WKContextRef contextRef, const WKContextConnectionClient* wkClient) + private: + virtual void didNavigateWithNavigationData(WebProcessPool& processPool, WebPageProxy& page, const WebNavigationDataStore& navigationDataStore, WebFrameProxy& frame) override + { + if (!m_client.didNavigateWithNavigationData) + return; + + RefPtr<API::NavigationData> navigationData = API::NavigationData::create(navigationDataStore); + m_client.didNavigateWithNavigationData(toAPI(&processPool), toAPI(&page), toAPI(navigationData.get()), toAPI(&frame), m_client.base.clientInfo); + } + + virtual void didPerformClientRedirect(WebProcessPool& processPool, WebPageProxy& page, const String& sourceURL, const String& destinationURL, WebFrameProxy& frame) override + { + if (!m_client.didPerformClientRedirect) + return; + + m_client.didPerformClientRedirect(toAPI(&processPool), toAPI(&page), toURLRef(sourceURL.impl()), toURLRef(destinationURL.impl()), toAPI(&frame), m_client.base.clientInfo); + } + + virtual void didPerformServerRedirect(WebProcessPool& processPool, WebPageProxy& page, const String& sourceURL, const String& destinationURL, WebFrameProxy& frame) override + { + if (!m_client.didPerformServerRedirect) + return; + + m_client.didPerformServerRedirect(toAPI(&processPool), toAPI(&page), toURLRef(sourceURL.impl()), toURLRef(destinationURL.impl()), toAPI(&frame), m_client.base.clientInfo); + } + + virtual void didUpdateHistoryTitle(WebProcessPool& processPool, WebPageProxy& page, const String& title, const String& url, WebFrameProxy& frame) override + { + if (!m_client.didUpdateHistoryTitle) + return; + + m_client.didUpdateHistoryTitle(toAPI(&processPool), toAPI(&page), toAPI(title.impl()), toURLRef(url.impl()), toAPI(&frame), m_client.base.clientInfo); + } + + virtual void populateVisitedLinks(WebProcessPool& processPool) override + { + if (!m_client.populateVisitedLinks) + return; + + m_client.populateVisitedLinks(toAPI(&processPool), m_client.base.clientInfo); + } + + virtual bool addsVisitedLinks() const override + { + return m_client.populateVisitedLinks; + } + }; + + WebProcessPool& processPool = *toImpl(contextRef); + processPool.setHistoryClient(std::make_unique<HistoryClient>(wkClient)); + + bool addsVisitedLinks = processPool.historyClient().addsVisitedLinks(); + + for (auto& process : processPool.processes()) { + for (auto& page : process->pages()) + page->setAddsVisitedLinks(addsVisitedLinks); + } +} + +void WKContextSetDownloadClient(WKContextRef contextRef, const WKContextDownloadClientBase* wkClient) +{ + class DownloadClient final : public API::Client<WKContextDownloadClientBase>, public API::DownloadClient { + public: + explicit DownloadClient(const WKContextDownloadClientBase* client) + { + initialize(client); + } + private: + virtual void didStart(WebProcessPool* processPool, DownloadProxy* downloadProxy) override + { + if (!m_client.didStart) + return; + + m_client.didStart(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo); + } + + virtual void didReceiveAuthenticationChallenge(WebProcessPool* processPool, DownloadProxy* downloadProxy, AuthenticationChallengeProxy* authenticationChallengeProxy) override + { + if (!m_client.didReceiveAuthenticationChallenge) + return; + + m_client.didReceiveAuthenticationChallenge(toAPI(processPool), toAPI(downloadProxy), toAPI(authenticationChallengeProxy), m_client.base.clientInfo); + } + + virtual void didReceiveResponse(WebProcessPool* processPool, DownloadProxy* downloadProxy, const ResourceResponse& response) override + { + if (!m_client.didReceiveResponse) + return; + + m_client.didReceiveResponse(toAPI(processPool), toAPI(downloadProxy), toAPI(API::URLResponse::create(response).ptr()), m_client.base.clientInfo); + } + + virtual void didReceiveData(WebProcessPool* processPool, DownloadProxy* downloadProxy, uint64_t length) override + { + if (!m_client.didReceiveData) + return; + + m_client.didReceiveData(toAPI(processPool), toAPI(downloadProxy), length, m_client.base.clientInfo); + } + + virtual bool shouldDecodeSourceDataOfMIMEType(WebProcessPool* processPool, DownloadProxy* downloadProxy, const String& mimeType) override + { + if (!m_client.shouldDecodeSourceDataOfMIMEType) + return true; + + return m_client.shouldDecodeSourceDataOfMIMEType(toAPI(processPool), toAPI(downloadProxy), toAPI(mimeType.impl()), m_client.base.clientInfo); + } + + virtual String decideDestinationWithSuggestedFilename(WebProcessPool* processPool, DownloadProxy* downloadProxy, const String& filename, bool& allowOverwrite) override + { + if (!m_client.decideDestinationWithSuggestedFilename) + return String(); + + WKRetainPtr<WKStringRef> destination(AdoptWK, m_client.decideDestinationWithSuggestedFilename(toAPI(processPool), toAPI(downloadProxy), toAPI(filename.impl()), &allowOverwrite, m_client.base.clientInfo)); + return toWTFString(destination.get()); + } + + virtual void didCreateDestination(WebProcessPool* processPool, DownloadProxy* downloadProxy, const String& path) override + { + if (!m_client.didCreateDestination) + return; + + m_client.didCreateDestination(toAPI(processPool), toAPI(downloadProxy), toAPI(path.impl()), m_client.base.clientInfo); + } + + virtual void didFinish(WebProcessPool* processPool, DownloadProxy* downloadProxy) override + { + if (!m_client.didFinish) + return; + + m_client.didFinish(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo); + } + + virtual void didFail(WebProcessPool* processPool, DownloadProxy* downloadProxy, const ResourceError& error) override + { + if (!m_client.didFail) + return; + + m_client.didFail(toAPI(processPool), toAPI(downloadProxy), toAPI(error), m_client.base.clientInfo); + } + + virtual void didCancel(WebProcessPool* processPool, DownloadProxy* downloadProxy) override + { + if (!m_client.didCancel) + return; + + m_client.didCancel(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo); + } + + virtual void processDidCrash(WebProcessPool* processPool, DownloadProxy* downloadProxy) override + { + if (!m_client.processDidCrash) + return; + + m_client.processDidCrash(toAPI(processPool), toAPI(downloadProxy), m_client.base.clientInfo); + } + + }; + + toImpl(contextRef)->setDownloadClient(std::make_unique<DownloadClient>(wkClient)); +} + +void WKContextSetConnectionClient(WKContextRef contextRef, const WKContextConnectionClientBase* wkClient) { toImpl(contextRef)->initializeConnectionClient(wkClient); } -WKDownloadRef WKContextDownloadURLRequest(WKContextRef contextRef, const WKURLRequestRef requestRef) +WKDownloadRef WKContextDownloadURLRequest(WKContextRef contextRef, WKURLRequestRef requestRef) { return toAPI(toImpl(contextRef)->download(0, toImpl(requestRef)->resourceRequest())); } +WKDownloadRef WKContextResumeDownload(WKContextRef contextRef, WKDataRef resumeData, WKStringRef path) +{ + return toAPI(toImpl(contextRef)->resumeDownload(toImpl(resumeData), toWTFString(path))); +} + void WKContextSetInitializationUserDataForInjectedBundle(WKContextRef contextRef, WKTypeRef userDataRef) { toImpl(contextRef)->setInjectedBundleInitializationUserData(toImpl(userDataRef)); @@ -121,7 +296,7 @@ void WKContextPostMessageToInjectedBundle(WKContextRef contextRef, WKStringRef m void WKContextGetGlobalStatistics(WKContextStatistics* statistics) { - const WebContext::Statistics& webContextStatistics = WebContext::statistics(); + const WebProcessPool::Statistics& webContextStatistics = WebProcessPool::statistics(); statistics->wkViewCount = webContextStatistics.wkViewCount; statistics->wkPageCount = webContextStatistics.wkPageCount; @@ -130,27 +305,26 @@ void WKContextGetGlobalStatistics(WKContextStatistics* statistics) void WKContextAddVisitedLink(WKContextRef contextRef, WKStringRef visitedURL) { - toImpl(contextRef)->addVisitedLink(toImpl(visitedURL)->string()); -} + String visitedURLString = toImpl(visitedURL)->string(); + if (visitedURLString.isEmpty()) + return; -void WKContextSetCacheModel(WKContextRef contextRef, WKCacheModel cacheModel) -{ - toImpl(contextRef)->setCacheModel(toCacheModel(cacheModel)); + toImpl(contextRef)->visitedLinkStore().addVisitedLinkHash(visitedLinkHash(visitedURLString)); } -WKCacheModel WKContextGetCacheModel(WKContextRef contextRef) +void WKContextClearVisitedLinks(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->cacheModel()); + toImpl(contextRef)->visitedLinkStore().removeAll(); } -void WKContextSetProcessModel(WKContextRef contextRef, WKProcessModel processModel) +void WKContextSetCacheModel(WKContextRef contextRef, WKCacheModel cacheModel) { - toImpl(contextRef)->setProcessModel(toProcessModel(processModel)); + toImpl(contextRef)->setCacheModel(toCacheModel(cacheModel)); } -WKProcessModel WKContextGetProcessModel(WKContextRef contextRef) +WKCacheModel WKContextGetCacheModel(WKContextRef contextRef) { - return toAPI(toImpl(contextRef)->processModel()); + return toAPI(toImpl(contextRef)->cacheModel()); } void WKContextSetMaximumNumberOfProcesses(WKContextRef contextRef, unsigned numberOfProcesses) @@ -193,35 +367,52 @@ void WKContextRegisterURLSchemeAsSecure(WKContextRef contextRef, WKStringRef url toImpl(contextRef)->registerURLSchemeAsSecure(toImpl(urlScheme)->string()); } +void WKContextRegisterURLSchemeAsBypassingContentSecurityPolicy(WKContextRef contextRef, WKStringRef urlScheme) +{ + toImpl(contextRef)->registerURLSchemeAsBypassingContentSecurityPolicy(toImpl(urlScheme)->string()); +} + +void WKContextRegisterURLSchemeAsCachePartitioned(WKContextRef contextRef, WKStringRef urlScheme) +{ +#if ENABLE(CACHE_PARTITIONING) + toImpl(contextRef)->registerURLSchemeAsCachePartitioned(toImpl(urlScheme)->string()); +#else + UNUSED_PARAM(contextRef); + UNUSED_PARAM(urlScheme); +#endif +} + void WKContextSetDomainRelaxationForbiddenForURLScheme(WKContextRef contextRef, WKStringRef urlScheme) { toImpl(contextRef)->setDomainRelaxationForbiddenForURLScheme(toImpl(urlScheme)->string()); } +void WKContextSetCanHandleHTTPSServerTrustEvaluation(WKContextRef contextRef, bool value) +{ + toImpl(contextRef)->setCanHandleHTTPSServerTrustEvaluation(value); +} + WKCookieManagerRef WKContextGetCookieManager(WKContextRef contextRef) { return toAPI(toImpl(contextRef)->supplement<WebCookieManagerProxy>()); } -WKApplicationCacheManagerRef WKContextGetApplicationCacheManager(WKContextRef contextRef) +WKWebsiteDataStoreRef WKContextGetWebsiteDataStore(WKContextRef context) { - return toAPI(toImpl(contextRef)->supplement<WebApplicationCacheManagerProxy>()); + return toAPI(toImpl(context)->websiteDataStore()); } -WKBatteryManagerRef WKContextGetBatteryManager(WKContextRef contextRef) +WKApplicationCacheManagerRef WKContextGetApplicationCacheManager(WKContextRef context) { -#if ENABLE(BATTERY_STATUS) - return toAPI(toImpl(contextRef)->supplement<WebBatteryManagerProxy>()); -#else - return 0; -#endif + return reinterpret_cast<WKApplicationCacheManagerRef>(WKContextGetWebsiteDataStore(context)); } -WKDatabaseManagerRef WKContextGetDatabaseManager(WKContextRef contextRef) +WKBatteryManagerRef WKContextGetBatteryManager(WKContextRef contextRef) { -#if ENABLE(SQL_DATABASE) - return toAPI(toImpl(contextRef)->supplement<WebDatabaseManagerProxy>()); +#if ENABLE(BATTERY_STATUS) + return toAPI(toImpl(contextRef)->supplement<WebBatteryManagerProxy>()); #else + UNUSED_PARAM(contextRef); return 0; #endif } @@ -231,28 +422,24 @@ WKGeolocationManagerRef WKContextGetGeolocationManager(WKContextRef contextRef) return toAPI(toImpl(contextRef)->supplement<WebGeolocationManagerProxy>()); } -WKNetworkInfoManagerRef WKContextGetNetworkInfoManager(WKContextRef contextRef) -{ -#if ENABLE(NETWORK_INFO) - return toAPI(toImpl(contextRef)->supplement<WebNetworkInfoManagerProxy>()); -#else - return 0; -#endif -} - WKIconDatabaseRef WKContextGetIconDatabase(WKContextRef contextRef) { return toAPI(toImpl(contextRef)->iconDatabase()); } -WKKeyValueStorageManagerRef WKContextGetKeyValueStorageManager(WKContextRef contextRef) +WKKeyValueStorageManagerRef WKContextGetKeyValueStorageManager(WKContextRef context) { - return toAPI(toImpl(contextRef)->supplement<WebKeyValueStorageManager>()); + return reinterpret_cast<WKKeyValueStorageManagerRef>(WKContextGetWebsiteDataStore(context)); } -WKMediaCacheManagerRef WKContextGetMediaCacheManager(WKContextRef contextRef) +WKMediaSessionFocusManagerRef WKContextGetMediaSessionFocusManager(WKContextRef context) { - return toAPI(toImpl(contextRef)->supplement<WebMediaCacheManagerProxy>()); +#if ENABLE(MEDIA_SESSION) + return toAPI(toImpl(context)->supplement<WebMediaSessionFocusManager>()); +#else + UNUSED_PARAM(context); + return nullptr; +#endif } WKNotificationManagerRef WKContextGetNotificationManager(WKContextRef contextRef) @@ -260,18 +447,19 @@ WKNotificationManagerRef WKContextGetNotificationManager(WKContextRef contextRef return toAPI(toImpl(contextRef)->supplement<WebNotificationManagerProxy>()); } -WKPluginSiteDataManagerRef WKContextGetPluginSiteDataManager(WKContextRef contextRef) +WKPluginSiteDataManagerRef WKContextGetPluginSiteDataManager(WKContextRef context) { #if ENABLE(NETSCAPE_PLUGIN_API) - return toAPI(toImpl(contextRef)->pluginSiteDataManager()); + return reinterpret_cast<WKPluginSiteDataManagerRef>(WKContextGetWebsiteDataStore(context)); #else - return 0; + UNUSED_PARAM(context); + return nullptr; #endif } -WKResourceCacheManagerRef WKContextGetResourceCacheManager(WKContextRef contextRef) +WKResourceCacheManagerRef WKContextGetResourceCacheManager(WKContextRef context) { - return toAPI(toImpl(contextRef)->supplement<WebResourceCacheManagerProxy>()); + return reinterpret_cast<WKResourceCacheManagerRef>(WKContextGetWebsiteDataStore(context)); } void WKContextStartMemorySampler(WKContextRef contextRef, WKDoubleRef interval) @@ -294,26 +482,6 @@ void WKContextAllowSpecificHTTPSCertificateForHost(WKContextRef contextRef, WKCe 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()); -} - -void WKContextSetLocalStorageDirectory(WKContextRef contextRef, WKStringRef localStorageDirectory) -{ - toImpl(contextRef)->setLocalStorageDirectory(toImpl(localStorageDirectory)->string()); -} - -WK_EXPORT void WKContextSetDiskCacheDirectory(WKContextRef contextRef, WKStringRef diskCacheDirectory) -{ - toImpl(contextRef)->setDiskCacheDirectory(toImpl(diskCacheDirectory)->string()); -} - WK_EXPORT void WKContextSetCookieStorageDirectory(WKContextRef contextRef, WKStringRef cookieStorageDirectory) { toImpl(contextRef)->setCookieStorageDirectory(toImpl(cookieStorageDirectory)->string()); @@ -341,12 +509,12 @@ void WKContextWarmInitialProcess(WKContextRef contextRef) void WKContextGetStatistics(WKContextRef contextRef, void* context, WKContextGetStatisticsFunction callback) { - toImpl(contextRef)->getStatistics(0xFFFFFFFF, DictionaryCallback::create(context, callback)); + toImpl(contextRef)->getStatistics(0xFFFFFFFF, toGenericCallbackFunction(context, callback)); } void WKContextGetStatisticsWithOptions(WKContextRef contextRef, WKStatisticsOptions optionsMask, void* context, WKContextGetStatisticsFunction callback) { - toImpl(contextRef)->getStatistics(optionsMask, DictionaryCallback::create(context, callback)); + toImpl(contextRef)->getStatistics(optionsMask, toGenericCallbackFunction(context, callback)); } void WKContextGarbageCollectJavaScriptObjects(WKContextRef contextRef) @@ -359,9 +527,14 @@ void WKContextSetJavaScriptGarbageCollectorTimerEnabled(WKContextRef contextRef, toImpl(contextRef)->setJavaScriptGarbageCollectorTimerEnabled(enable); } -void WKContextSetUsesNetworkProcess(WKContextRef contextRef, bool usesNetworkProcess) +void WKContextUseTestingNetworkSession(WKContextRef context) +{ + toImpl(context)->useTestingNetworkSession(); +} + +void WKContextClearCachedCredentials(WKContextRef context) { - toImpl(contextRef)->setUsesNetworkProcess(usesNetworkProcess); + toImpl(context)->clearCachedCredentials(); } WKDictionaryRef WKContextCopyPlugInAutoStartOriginHashes(WKContextRef contextRef) @@ -376,6 +549,13 @@ void WKContextSetPlugInAutoStartOriginHashes(WKContextRef contextRef, WKDictiona toImpl(contextRef)->setPlugInAutoStartOriginHashes(*toImpl(dictionaryRef)); } +void WKContextSetPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(WKContextRef contextRef, WKDictionaryRef dictionaryRef, double time) +{ + if (!dictionaryRef) + return; + toImpl(contextRef)->setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(*toImpl(dictionaryRef), time); +} + void WKContextSetPlugInAutoStartOrigins(WKContextRef contextRef, WKArrayRef arrayRef) { if (!arrayRef) @@ -385,26 +565,15 @@ void WKContextSetPlugInAutoStartOrigins(WKContextRef contextRef, WKArrayRef arra void WKContextSetInvalidMessageFunction(WKContextInvalidMessageFunction invalidMessageFunction) { - WebContext::setInvalidMessageCallback(invalidMessageFunction); -} - -// Deprecated functions. -void _WKContextSetAdditionalPluginsDirectory(WKContextRef context, WKStringRef pluginsDirectory) -{ - WKContextSetAdditionalPluginsDirectory(context, pluginsDirectory); -} - -void _WKContextRegisterURLSchemeAsEmptyDocument(WKContextRef context, WKStringRef urlScheme) -{ - WKContextRegisterURLSchemeAsEmptyDocument(context, urlScheme); + WebProcessPool::setInvalidMessageCallback(invalidMessageFunction); } -void _WKContextSetAlwaysUsesComplexTextCodePath(WKContextRef context, bool alwaysUseComplexTextCodePath) +void WKContextSetMemoryCacheDisabled(WKContextRef contextRef, bool disabled) { - WKContextSetAlwaysUsesComplexTextCodePath(context, alwaysUseComplexTextCodePath); + toImpl(contextRef)->setMemoryCacheDisabled(disabled); } -void _WKContextSetHTTPPipeliningEnabled(WKContextRef context, bool enabled) +void WKContextSetFontWhitelist(WKContextRef contextRef, WKArrayRef arrayRef) { - WKContextSetHTTPPipeliningEnabled(context, enabled); + toImpl(contextRef)->setFontWhitelist(toImpl(arrayRef)); } diff --git a/Source/WebKit2/UIProcess/API/C/WKContext.h b/Source/WebKit2/UIProcess/API/C/WKContext.h index 3ce731e78..279096991 100644 --- a/Source/WebKit2/UIProcess/API/C/WKContext.h +++ b/Source/WebKit2/UIProcess/API/C/WKContext.h @@ -26,7 +26,11 @@ #ifndef WKContext_h #define WKContext_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKContextConnectionClient.h> +#include <WebKit/WKContextDownloadClient.h> +#include <WebKit/WKContextHistoryClient.h> +#include <WebKit/WKContextInjectedBundleClient.h> #ifdef __cplusplus extern "C" { @@ -43,104 +47,35 @@ typedef uint32_t WKCacheModel; 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); +typedef WKDataRef (*WKContextCopyWebCryptoMasterKeyCallback)(WKContextRef context, const void *clientInfo); -struct WKContextClient { +typedef struct WKContextClientBase { int version; const void * clientInfo; +} WKContextClientBase; + +typedef struct WKContextClientV0 { + WKContextClientBase base; // Version 0. WKContextPlugInAutoStartOriginHashesChangedCallback plugInAutoStartOriginHashesChanged; WKContextNetworkProcessDidCrashCallback networkProcessDidCrash; WKContextPlugInInformationBecameAvailableCallback plugInInformationBecameAvailable; -}; -typedef struct WKContextClient WKContextClient; +} WKContextClientV0; -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); -typedef WKTypeRef (*WKContextGetInjectedBundleInitializationUserDataCallback)(WKContextRef context, const void *clientInfo); - -struct WKContextInjectedBundleClient { - int version; - const void * clientInfo; +typedef struct WKContextClientV1 { + WKContextClientBase base; // Version 0. - WKContextDidReceiveMessageFromInjectedBundleCallback didReceiveMessageFromInjectedBundle; - WKContextDidReceiveSynchronousMessageFromInjectedBundleCallback didReceiveSynchronousMessageFromInjectedBundle; + WKContextPlugInAutoStartOriginHashesChangedCallback plugInAutoStartOriginHashesChanged; + WKContextNetworkProcessDidCrashCallback networkProcessDidCrash; + WKContextPlugInInformationBecameAvailableCallback plugInInformationBecameAvailable; // Version 1. - WKContextGetInjectedBundleInitializationUserDataCallback getInjectedBundleInitializationUserData; -}; -typedef struct WKContextInjectedBundleClient WKContextInjectedBundleClient; - -enum { kWKContextInjectedBundleClientCurrentVersion = 1 }; - -// History Client -typedef void (*WKContextDidNavigateWithNavigationDataCallback)(WKContextRef context, WKPageRef page, WKNavigationDataRef navigationData, WKFrameRef frame, const void *clientInfo); -typedef void (*WKContextDidPerformClientRedirectCallback)(WKContextRef context, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void *clientInfo); -typedef void (*WKContextDidPerformServerRedirectCallback)(WKContextRef context, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void *clientInfo); -typedef void (*WKContextDidUpdateHistoryTitleCallback)(WKContextRef context, WKPageRef page, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void *clientInfo); -typedef void (*WKContextPopulateVisitedLinksCallback)(WKContextRef context, const void *clientInfo); - -struct WKContextHistoryClient { - int version; - const void * clientInfo; - WKContextDidNavigateWithNavigationDataCallback didNavigateWithNavigationData; - WKContextDidPerformClientRedirectCallback didPerformClientRedirect; - WKContextDidPerformServerRedirectCallback didPerformServerRedirect; - WKContextDidUpdateHistoryTitleCallback didUpdateHistoryTitle; - WKContextPopulateVisitedLinksCallback populateVisitedLinks; -}; -typedef struct WKContextHistoryClient WKContextHistoryClient; - -enum { kWKContextHistoryClientCurrentVersion = 0 }; - -// Download Client -typedef void (*WKContextDownloadDidStartCallback)(WKContextRef context, WKDownloadRef download, const void *clientInfo); -typedef void (*WKContextDownloadDidReceiveAuthenticationChallengeCallback)(WKContextRef context, WKDownloadRef download, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo); -typedef void (*WKContextDownloadDidReceiveResponseCallback)(WKContextRef context, WKDownloadRef download, WKURLResponseRef response, const void *clientInfo); -typedef void (*WKContextDownloadDidReceiveDataCallback)(WKContextRef context, WKDownloadRef download, uint64_t length, const void *clientInfo); -typedef bool (*WKContextDownloadShouldDecodeSourceDataOfMIMETypeCallback)(WKContextRef context, WKDownloadRef download, WKStringRef mimeType, const void *clientInfo); -typedef WKStringRef (*WKContextDownloadDecideDestinationWithSuggestedFilenameCallback)(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void *clientInfo); -typedef void (*WKContextDownloadDidCreateDestinationCallback)(WKContextRef context, WKDownloadRef download, WKStringRef path, const void *clientInfo); -typedef void (*WKContextDownloadDidFinishCallback)(WKContextRef context, WKDownloadRef download, const void *clientInfo); -typedef void (*WKContextDownloadDidFailCallback)(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void *clientInfo); -typedef void (*WKContextDownloadDidCancel)(WKContextRef context, WKDownloadRef download, const void *clientInfo); -typedef void (*WKContextDownloadProcessDidCrashCallback)(WKContextRef context, WKDownloadRef download, const void *clientInfo); - -struct WKContextDownloadClient { - int version; - const void * clientInfo; - WKContextDownloadDidStartCallback didStart; - WKContextDownloadDidReceiveAuthenticationChallengeCallback didReceiveAuthenticationChallenge; - WKContextDownloadDidReceiveResponseCallback didReceiveResponse; - WKContextDownloadDidReceiveDataCallback didReceiveData; - WKContextDownloadShouldDecodeSourceDataOfMIMETypeCallback shouldDecodeSourceDataOfMIMEType; - WKContextDownloadDecideDestinationWithSuggestedFilenameCallback decideDestinationWithSuggestedFilename; - WKContextDownloadDidCreateDestinationCallback didCreateDestination; - WKContextDownloadDidFinishCallback didFinish; - WKContextDownloadDidFailCallback didFail; - WKContextDownloadDidCancel didCancel; - WKContextDownloadProcessDidCrashCallback processDidCrash; -}; -typedef struct WKContextDownloadClient WKContextDownloadClient; - -enum { kWKContextDownloadClientCurrentVersion = 0 }; - -// Connection Client -typedef void (*WKContextDidCreateConnection)(WKContextRef context, WKConnectionRef connection, const void* clientInfo); - -struct WKContextConnectionClient { - int version; - const void * clientInfo; - WKContextDidCreateConnection didCreateConnection; -}; -typedef struct WKContextConnectionClient WKContextConnectionClient; - -enum { kWKContextConnectionClientCurrentVersion = 0 }; + WKContextCopyWebCryptoMasterKeyCallback copyWebCryptoMasterKey; +} WKContextClientV1; +// FIXME: Remove these once support for Mavericks has been dropped. enum { kWKProcessModelSharedSecondaryProcess = 0, kWKProcessModelMultipleSecondaryProcesses = 1 @@ -157,25 +92,29 @@ WK_EXPORT WKTypeID WKContextGetTypeID(); WK_EXPORT WKContextRef WKContextCreate(); WK_EXPORT WKContextRef WKContextCreateWithInjectedBundlePath(WKStringRef path); +WK_EXPORT WKContextRef WKContextCreateWithConfiguration(WKContextConfigurationRef configuration); -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); -WK_EXPORT void WKContextSetConnectionClient(WKContextRef context, const WKContextConnectionClient* client); +WK_EXPORT void WKContextSetClient(WKContextRef context, const WKContextClientBase* client); +WK_EXPORT void WKContextSetInjectedBundleClient(WKContextRef context, const WKContextInjectedBundleClientBase* client); +WK_EXPORT void WKContextSetHistoryClient(WKContextRef context, const WKContextHistoryClientBase* client); +WK_EXPORT void WKContextSetDownloadClient(WKContextRef context, const WKContextDownloadClientBase* client); +WK_EXPORT void WKContextSetConnectionClient(WKContextRef context, const WKContextConnectionClientBase* client); -WK_EXPORT WKDownloadRef WKContextDownloadURLRequest(WKContextRef context, const WKURLRequestRef request); +WK_EXPORT WKDownloadRef WKContextDownloadURLRequest(WKContextRef context, WKURLRequestRef request); +WK_EXPORT WKDownloadRef WKContextResumeDownload(WKContextRef context, WKDataRef resumeData, WKStringRef path); WK_EXPORT void WKContextSetInitializationUserDataForInjectedBundle(WKContextRef context, WKTypeRef userData); WK_EXPORT void WKContextPostMessageToInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody); WK_EXPORT void WKContextAddVisitedLink(WKContextRef context, WKStringRef visitedURL); +WK_EXPORT void WKContextClearVisitedLinks(WKContextRef contextRef); WK_EXPORT void WKContextSetCacheModel(WKContextRef context, WKCacheModel cacheModel); WK_EXPORT WKCacheModel WKContextGetCacheModel(WKContextRef context); -WK_EXPORT void WKContextSetProcessModel(WKContextRef context, WKProcessModel processModel); -WK_EXPORT WKProcessModel WKContextGetProcessModel(WKContextRef context); +// FIXME: Move these to WKDeprecatedFunctions.cpp once support for Mavericks has been dropped. +WK_EXPORT void WKContextSetProcessModel(WKContextRef, WKProcessModel); +WK_EXPORT WKProcessModel WKContextGetProcessModel(WKContextRef); WK_EXPORT void WKContextSetMaximumNumberOfProcesses(WKContextRef context, unsigned numberOfProcesses); WK_EXPORT unsigned WKContextGetMaximumNumberOfProcesses(WKContextRef context); @@ -183,19 +122,19 @@ WK_EXPORT unsigned WKContextGetMaximumNumberOfProcesses(WKContextRef context); WK_EXPORT void WKContextStartMemorySampler(WKContextRef context, WKDoubleRef interval); WK_EXPORT void WKContextStopMemorySampler(WKContextRef context); +WK_EXPORT WKWebsiteDataStoreRef WKContextGetWebsiteDataStore(WKContextRef context); + WK_EXPORT WKApplicationCacheManagerRef WKContextGetApplicationCacheManager(WKContextRef context); WK_EXPORT WKBatteryManagerRef WKContextGetBatteryManager(WKContextRef context); WK_EXPORT WKCookieManagerRef WKContextGetCookieManager(WKContextRef context); -WK_EXPORT WKDatabaseManagerRef WKContextGetDatabaseManager(WKContextRef context); WK_EXPORT WKGeolocationManagerRef WKContextGetGeolocationManager(WKContextRef context); WK_EXPORT WKIconDatabaseRef WKContextGetIconDatabase(WKContextRef context); WK_EXPORT WKKeyValueStorageManagerRef WKContextGetKeyValueStorageManager(WKContextRef context); -WK_EXPORT WKMediaCacheManagerRef WKContextGetMediaCacheManager(WKContextRef context); -WK_EXPORT WKNetworkInfoManagerRef WKContextGetNetworkInfoManager(WKContextRef context); +WK_EXPORT WKMediaSessionFocusManagerRef WKContextGetMediaSessionFocusManager(WKContextRef context); WK_EXPORT WKNotificationManagerRef WKContextGetNotificationManager(WKContextRef context); WK_EXPORT WKPluginSiteDataManagerRef WKContextGetPluginSiteDataManager(WKContextRef context); WK_EXPORT WKResourceCacheManagerRef WKContextGetResourceCacheManager(WKContextRef context); - + 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); @@ -206,6 +145,7 @@ WK_EXPORT void WKContextSetJavaScriptGarbageCollectorTimerEnabled(WKContextRef c WK_EXPORT WKDictionaryRef WKContextCopyPlugInAutoStartOriginHashes(WKContextRef context); WK_EXPORT void WKContextSetPlugInAutoStartOriginHashes(WKContextRef context, WKDictionaryRef dictionary); WK_EXPORT void WKContextSetPlugInAutoStartOrigins(WKContextRef contextRef, WKArrayRef arrayRef); +WK_EXPORT void WKContextSetPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(WKContextRef contextRef, WKDictionaryRef dictionaryRef, double time); #ifdef __cplusplus } diff --git a/Source/WebKit2/UIProcess/API/C/WKContextConfigurationRef.cpp b/Source/WebKit2/UIProcess/API/C/WKContextConfigurationRef.cpp new file mode 100644 index 000000000..fe4f9139a --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKContextConfigurationRef.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2014 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 "WKContextConfigurationRef.h" + +#include "APIProcessPoolConfiguration.h" +#include "WKAPICast.h" + +using namespace WebKit; + +WKContextConfigurationRef WKContextConfigurationCreate() +{ + auto configuration = API::ProcessPoolConfiguration::create(); + + // FIXME: A context created like this shouldn't have a data store, + // instead there should be a WKPageConfigurationRef object that specifies the data store. + configuration->setShouldHaveLegacyDataStore(true); + + return toAPI(&configuration.leakRef()); +} + +WKStringRef WKContextConfigurationCopyDiskCacheDirectory(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->diskCacheDirectory()); +} + +void WKContextConfigurationSetDiskCacheDirectory(WKContextConfigurationRef configuration, WKStringRef diskCacheDirectory) +{ + toImpl(configuration)->setDiskCacheDirectory(toImpl(diskCacheDirectory)->string()); +} + +WKStringRef WKContextConfigurationCopyApplicationCacheDirectory(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->applicationCacheDirectory()); +} + +void WKContextConfigurationSetApplicationCacheDirectory(WKContextConfigurationRef configuration, WKStringRef applicationCacheDirectory) +{ + toImpl(configuration)->setApplicationCacheDirectory(toImpl(applicationCacheDirectory)->string()); +} + +WKStringRef WKContextConfigurationCopyIndexedDBDatabaseDirectory(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->indexedDBDatabaseDirectory()); +} + +void WKContextConfigurationSetIndexedDBDatabaseDirectory(WKContextConfigurationRef configuration, WKStringRef indexedDBDatabaseDirectory) +{ + toImpl(configuration)->setIndexedDBDatabaseDirectory(toImpl(indexedDBDatabaseDirectory)->string()); +} + +WKStringRef WKContextConfigurationCopyInjectedBundlePath(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->injectedBundlePath()); +} + +void WKContextConfigurationSetInjectedBundlePath(WKContextConfigurationRef configuration, WKStringRef injectedBundlePath) +{ + toImpl(configuration)->setInjectedBundlePath(toImpl(injectedBundlePath)->string()); +} + +WKStringRef WKContextConfigurationCopyLocalStorageDirectory(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->localStorageDirectory()); +} + +void WKContextConfigurationSetLocalStorageDirectory(WKContextConfigurationRef configuration, WKStringRef localStorageDirectory) +{ + toImpl(configuration)->setLocalStorageDirectory(toImpl(localStorageDirectory)->string()); +} + +WKStringRef WKContextConfigurationCopyWebSQLDatabaseDirectory(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->webSQLDatabaseDirectory()); +} + +void WKContextConfigurationSetWebSQLDatabaseDirectory(WKContextConfigurationRef configuration, WKStringRef webSQLDatabaseDirectory) +{ + toImpl(configuration)->setWebSQLDatabaseDirectory(toImpl(webSQLDatabaseDirectory)->string()); +} + +WKStringRef WKContextConfigurationCopyMediaKeysStorageDirectory(WKContextConfigurationRef configuration) +{ + return toCopiedAPI(toImpl(configuration)->mediaKeysStorageDirectory()); +} + +void WKContextConfigurationSetMediaKeysStorageDirectory(WKContextConfigurationRef configuration, WKStringRef mediaKeysStorageDirectory) +{ + toImpl(configuration)->setMediaKeysStorageDirectory(toImpl(mediaKeysStorageDirectory)->string()); +} + +bool WKContextConfigurationFullySynchronousModeIsAllowedForTesting(WKContextConfigurationRef configuration) +{ + return toImpl(configuration)->fullySynchronousModeIsAllowedForTesting(); +} + +void WKContextConfigurationSetFullySynchronousModeIsAllowedForTesting(WKContextConfigurationRef configuration, bool allowed) +{ + toImpl(configuration)->setFullySynchronousModeIsAllowedForTesting(allowed); +} + +WKArrayRef WKContextConfigurationCopyOverrideLanguages(WKContextConfigurationRef configuration) +{ + return toAPI(&API::Array::createStringArray(toImpl(configuration)->overrideLanguages()).leakRef()); +} + +void WKContextConfigurationSetOverrideLanguages(WKContextConfigurationRef configuration, WKArrayRef overrideLanguages) +{ + toImpl(configuration)->setOverrideLanguages(toImpl(overrideLanguages)->toStringVector()); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKContextConfigurationRef.h b/Source/WebKit2/UIProcess/API/C/WKContextConfigurationRef.h new file mode 100644 index 000000000..1ee343a47 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKContextConfigurationRef.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2014 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 WKContextConfigurationRef_h +#define WKContextConfigurationRef_h + +#include <WebKit/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT WKContextConfigurationRef WKContextConfigurationCreate(); + +WK_EXPORT WKStringRef WKContextConfigurationCopyApplicationCacheDirectory(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetApplicationCacheDirectory(WKContextConfigurationRef configuration, WKStringRef applicationCacheDirectory); + +WK_EXPORT WKStringRef WKContextConfigurationCopyDiskCacheDirectory(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetDiskCacheDirectory(WKContextConfigurationRef configuration, WKStringRef diskCacheDirectory); + +WK_EXPORT WKStringRef WKContextConfigurationCopyIndexedDBDatabaseDirectory(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetIndexedDBDatabaseDirectory(WKContextConfigurationRef configuration, WKStringRef indexedDBDatabaseDirectory); + +WK_EXPORT WKStringRef WKContextConfigurationCopyInjectedBundlePath(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetInjectedBundlePath(WKContextConfigurationRef configuration, WKStringRef injectedBundlePath); + +WK_EXPORT WKStringRef WKContextConfigurationCopyLocalStorageDirectory(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetLocalStorageDirectory(WKContextConfigurationRef configuration, WKStringRef localStorageDirectory); + +WK_EXPORT WKStringRef WKContextConfigurationCopyWebSQLDatabaseDirectory(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetWebSQLDatabaseDirectory(WKContextConfigurationRef configuration, WKStringRef webSQLDatabaseDirectory); + +WK_EXPORT WKStringRef WKContextConfigurationCopyMediaKeysStorageDirectory(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetMediaKeysStorageDirectory(WKContextConfigurationRef configuration, WKStringRef mediaKeysStorageDirectory); + +WK_EXPORT bool WKContextConfigurationFullySynchronousModeIsAllowedForTesting(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetFullySynchronousModeIsAllowedForTesting(WKContextConfigurationRef configuration, bool allowed); + +WK_EXPORT WKArrayRef WKContextConfigurationCopyOverrideLanguages(WKContextConfigurationRef configuration); +WK_EXPORT void WKContextConfigurationSetOverrideLanguages(WKContextConfigurationRef configuration, WKArrayRef overrideLanguages); + +#ifdef __cplusplus +} +#endif + + +#endif // WKContextConfigurationRef_h diff --git a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.h b/Source/WebKit2/UIProcess/API/C/WKContextConnectionClient.h index 62684000d..e7c576310 100644 --- a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.h +++ b/Source/WebKit2/UIProcess/API/C/WKContextConnectionClient.h @@ -23,37 +23,23 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef SecItemShimProxy_h -#define SecItemShimProxy_h +#ifndef WKContextConnectionClient_h +#define WKContextConnectionClient_h -#if USE(SECURITY_FRAMEWORK) +#include <WebKit/WKBase.h> -#include "Connection.h" +typedef void (*WKContextDidCreateConnection)(WKContextRef context, WKConnectionRef connection, const void* clientInfo); -namespace WebKit { +typedef struct WKContextConnectionClientBase { + int version; + const void * clientInfo; +} WKContextConnectionClientBase; -class SecItemRequestData; +typedef struct WKContextConnectionClientV0 { + WKContextConnectionClientBase base; -class SecItemShimProxy : public CoreIPC::Connection::WorkQueueMessageReceiver { -WTF_MAKE_NONCOPYABLE(SecItemShimProxy); -public: - static SecItemShimProxy& shared(); + // Version 0. + WKContextDidCreateConnection didCreateConnection; +} WKContextConnectionClientV0; - void initializeConnection(CoreIPC::Connection*); - -private: - SecItemShimProxy(); - - // CoreIPC::Connection::WorkQueueMessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - void secItemRequest(CoreIPC::Connection*, uint64_t requestID, const SecItemRequestData&); - - RefPtr<WorkQueue> m_queue; -}; - -} // namespace WebKit - -#endif // USE(SECURITY_FRAMEWORK) - -#endif // SecItemShimProxy_h +#endif // WKContextConnectionClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKContextDownloadClient.h b/Source/WebKit2/UIProcess/API/C/WKContextDownloadClient.h new file mode 100644 index 000000000..5bb8d83a8 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKContextDownloadClient.h @@ -0,0 +1,65 @@ +/* + * 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 WKContextDownloadClient_h +#define WKContextDownloadClient_h + +#include <WebKit/WKBase.h> + +typedef void (*WKContextDownloadDidStartCallback)(WKContextRef context, WKDownloadRef download, const void *clientInfo); +typedef void (*WKContextDownloadDidReceiveAuthenticationChallengeCallback)(WKContextRef context, WKDownloadRef download, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo); +typedef void (*WKContextDownloadDidReceiveResponseCallback)(WKContextRef context, WKDownloadRef download, WKURLResponseRef response, const void *clientInfo); +typedef void (*WKContextDownloadDidReceiveDataCallback)(WKContextRef context, WKDownloadRef download, uint64_t length, const void *clientInfo); +typedef bool (*WKContextDownloadShouldDecodeSourceDataOfMIMETypeCallback)(WKContextRef context, WKDownloadRef download, WKStringRef mimeType, const void *clientInfo); +typedef WKStringRef (*WKContextDownloadDecideDestinationWithSuggestedFilenameCallback)(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void *clientInfo); +typedef void (*WKContextDownloadDidCreateDestinationCallback)(WKContextRef context, WKDownloadRef download, WKStringRef path, const void *clientInfo); +typedef void (*WKContextDownloadDidFinishCallback)(WKContextRef context, WKDownloadRef download, const void *clientInfo); +typedef void (*WKContextDownloadDidFailCallback)(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void *clientInfo); +typedef void (*WKContextDownloadDidCancel)(WKContextRef context, WKDownloadRef download, const void *clientInfo); +typedef void (*WKContextDownloadProcessDidCrashCallback)(WKContextRef context, WKDownloadRef download, const void *clientInfo); + +typedef struct WKContextDownloadClientBase { + int version; + const void * clientInfo; +} WKContextDownloadClientBase; + +typedef struct WKContextDownloadClientV0 { + WKContextDownloadClientBase base; + + // Version 0. + WKContextDownloadDidStartCallback didStart; + WKContextDownloadDidReceiveAuthenticationChallengeCallback didReceiveAuthenticationChallenge; + WKContextDownloadDidReceiveResponseCallback didReceiveResponse; + WKContextDownloadDidReceiveDataCallback didReceiveData; + WKContextDownloadShouldDecodeSourceDataOfMIMETypeCallback shouldDecodeSourceDataOfMIMEType; + WKContextDownloadDecideDestinationWithSuggestedFilenameCallback decideDestinationWithSuggestedFilename; + WKContextDownloadDidCreateDestinationCallback didCreateDestination; + WKContextDownloadDidFinishCallback didFinish; + WKContextDownloadDidFailCallback didFail; + WKContextDownloadDidCancel didCancel; + WKContextDownloadProcessDidCrashCallback processDidCrash; +} WKContextDownloadClientV0; + +#endif // WKContextDownloadClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKContextHistoryClient.h b/Source/WebKit2/UIProcess/API/C/WKContextHistoryClient.h new file mode 100644 index 000000000..0558efdba --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKContextHistoryClient.h @@ -0,0 +1,53 @@ +/* + * 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 WKContextHistoryClient_h +#define WKContextHistoryClient_h + +#include <WebKit/WKBase.h> + +typedef void (*WKContextDidNavigateWithNavigationDataCallback)(WKContextRef context, WKPageRef page, WKNavigationDataRef navigationData, WKFrameRef frame, const void *clientInfo); +typedef void (*WKContextDidPerformClientRedirectCallback)(WKContextRef context, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void *clientInfo); +typedef void (*WKContextDidPerformServerRedirectCallback)(WKContextRef context, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void *clientInfo); +typedef void (*WKContextDidUpdateHistoryTitleCallback)(WKContextRef context, WKPageRef page, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void *clientInfo); +typedef void (*WKContextPopulateVisitedLinksCallback)(WKContextRef context, const void *clientInfo); + +typedef struct WKContextHistoryClientBase { + int version; + const void * clientInfo; +} WKContextHistoryClientBase; + +typedef struct WKContextHistoryClientV0 { + WKContextHistoryClientBase base; + + // Version 0. + WKContextDidNavigateWithNavigationDataCallback didNavigateWithNavigationData; + WKContextDidPerformClientRedirectCallback didPerformClientRedirect; + WKContextDidPerformServerRedirectCallback didPerformServerRedirect; + WKContextDidUpdateHistoryTitleCallback didUpdateHistoryTitle; + WKContextPopulateVisitedLinksCallback populateVisitedLinks; +} WKContextHistoryClientV0; + +#endif // WKContextHistoryClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKContextInjectedBundleClient.h b/Source/WebKit2/UIProcess/API/C/WKContextInjectedBundleClient.h new file mode 100644 index 000000000..d3456aa68 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKContextInjectedBundleClient.h @@ -0,0 +1,60 @@ +/* + * 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 WKContextInjectedBundleClient_h +#define WKContextInjectedBundleClient_h + +#include <WebKit/WKBase.h> + +// 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); +typedef WKTypeRef (*WKContextGetInjectedBundleInitializationUserDataCallback)(WKContextRef context, const void *clientInfo); + +typedef struct WKContextInjectedBundleClientBase { + int version; + const void * clientInfo; +} WKContextInjectedBundleClientBase; + +typedef struct WKContextInjectedBundleClientV0 { + WKContextInjectedBundleClientBase base; + + // Version 0. + WKContextDidReceiveMessageFromInjectedBundleCallback didReceiveMessageFromInjectedBundle; + WKContextDidReceiveSynchronousMessageFromInjectedBundleCallback didReceiveSynchronousMessageFromInjectedBundle; +} WKContextInjectedBundleClientV0; + +typedef struct WKContextInjectedBundleClientV1 { + WKContextInjectedBundleClientBase base; + + // Version 0. + WKContextDidReceiveMessageFromInjectedBundleCallback didReceiveMessageFromInjectedBundle; + WKContextDidReceiveSynchronousMessageFromInjectedBundleCallback didReceiveSynchronousMessageFromInjectedBundle; + + // Version 1. + WKContextGetInjectedBundleInitializationUserDataCallback getInjectedBundleInitializationUserData; +} WKContextInjectedBundleClientV1; + +#endif // WKContextInjectedBundleClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h b/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h index 79e7f7f25..05d27fd10 100644 --- a/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKContextPrivate.h @@ -26,8 +26,8 @@ #ifndef WKContextPrivate_h #define WKContextPrivate_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKContext.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKContext.h> #ifdef __cplusplus extern "C" { @@ -52,18 +52,18 @@ WK_EXPORT void WKContextSetShouldUseFontSmoothing(WKContextRef context, bool use WK_EXPORT void WKContextRegisterURLSchemeAsSecure(WKContextRef context, WKStringRef urlScheme); +WK_EXPORT void WKContextRegisterURLSchemeAsBypassingContentSecurityPolicy(WKContextRef context, WKStringRef urlScheme); + +WK_EXPORT void WKContextRegisterURLSchemeAsCachePartitioned(WKContextRef context, WKStringRef urlScheme); + WK_EXPORT void WKContextSetDomainRelaxationForbiddenForURLScheme(WKContextRef context, WKStringRef urlScheme); +WK_EXPORT void WKContextSetCanHandleHTTPSServerTrustEvaluation(WKContextRef context, bool value); + 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); WK_EXPORT void WKContextSetCookieStorageDirectory(WKContextRef context, WKStringRef cookieStorageDirectory); // FIXME: This is a workaround for testing purposes only and should be removed once a better @@ -77,10 +77,20 @@ WK_EXPORT void WKContextWarmInitialProcess(WKContextRef context); // FIXME: This function is temporary and useful during the development of the NetworkProcess feature. // At some point it should be removed. -WK_EXPORT void WKContextSetUsesNetworkProcess(WKContextRef context, bool usesNetworkProcess); +WK_EXPORT void WKContextSetUsesNetworkProcess(WKContextRef, bool); + +// Test only. Should be called before any secondary processes are started. +WK_EXPORT void WKContextUseTestingNetworkSession(WKContextRef context); + +// Test only. Should be called before running a test. +WK_EXPORT void WKContextClearCachedCredentials(WKContextRef context); typedef void (*WKContextInvalidMessageFunction)(WKStringRef messageName); WK_EXPORT void WKContextSetInvalidMessageFunction(WKContextInvalidMessageFunction invalidMessageFunction); + +WK_EXPORT void WKContextSetMemoryCacheDisabled(WKContextRef, bool disabled); + +WK_EXPORT void WKContextSetFontWhitelist(WKContextRef, WKArrayRef); #ifdef __cplusplus } diff --git a/Source/WebKit2/UIProcess/API/C/WKCookieManager.cpp b/Source/WebKit2/UIProcess/API/C/WKCookieManager.cpp index 49ce6ac0c..e4a30611a 100644 --- a/Source/WebKit2/UIProcess/API/C/WKCookieManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKCookieManager.cpp @@ -36,14 +36,14 @@ WKTypeID WKCookieManagerGetTypeID() return toAPI(WebCookieManagerProxy::APIType); } -void WKCookieManagerSetClient(WKCookieManagerRef cookieManagerRef, const WKCookieManagerClient* wkClient) +void WKCookieManagerSetClient(WKCookieManagerRef cookieManagerRef, const WKCookieManagerClientBase* wkClient) { toImpl(cookieManagerRef)->initializeClient(wkClient); } void WKCookieManagerGetHostnamesWithCookies(WKCookieManagerRef cookieManagerRef, void* context, WKCookieManagerGetCookieHostnamesFunction callback) { - toImpl(cookieManagerRef)->getHostnamesWithCookies(ArrayCallback::create(context, callback)); + toImpl(cookieManagerRef)->getHostnamesWithCookies(toGenericCallbackFunction(context, callback)); } void WKCookieManagerDeleteCookiesForHostname(WKCookieManagerRef cookieManagerRef, WKStringRef hostname) @@ -56,6 +56,14 @@ void WKCookieManagerDeleteAllCookies(WKCookieManagerRef cookieManagerRef) toImpl(cookieManagerRef)->deleteAllCookies(); } +void WKCookieManagerDeleteAllCookiesModifiedAfterDate(WKCookieManagerRef cookieManagerRef, double date) +{ + using namespace std::chrono; + + auto time = system_clock::time_point(duration_cast<system_clock::duration>(duration<double>(date))); + toImpl(cookieManagerRef)->deleteAllCookiesModifiedSince(time); +} + void WKCookieManagerSetHTTPCookieAcceptPolicy(WKCookieManagerRef cookieManager, WKHTTPCookieAcceptPolicy policy) { toImpl(cookieManager)->setHTTPCookieAcceptPolicy(toHTTPCookieAcceptPolicy(policy)); @@ -63,7 +71,7 @@ void WKCookieManagerSetHTTPCookieAcceptPolicy(WKCookieManagerRef cookieManager, void WKCookieManagerGetHTTPCookieAcceptPolicy(WKCookieManagerRef cookieManager, void* context, WKCookieManagerGetHTTPCookieAcceptPolicyFunction callback) { - toImpl(cookieManager)->getHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyCallback::create(context, callback)); + toImpl(cookieManager)->getHTTPCookieAcceptPolicy(toGenericCallbackFunction<WKHTTPCookieAcceptPolicy, HTTPCookieAcceptPolicy>(context, callback)); } void WKCookieManagerStartObservingCookieChanges(WKCookieManagerRef cookieManager) diff --git a/Source/WebKit2/UIProcess/API/C/WKCookieManager.h b/Source/WebKit2/UIProcess/API/C/WKCookieManager.h index 88f56dc37..8f4111c3f 100644 --- a/Source/WebKit2/UIProcess/API/C/WKCookieManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKCookieManager.h @@ -26,7 +26,7 @@ #ifndef WKCookieManager_h #define WKCookieManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -35,25 +35,29 @@ extern "C" { enum { kWKHTTPCookieAcceptPolicyAlways = 0, kWKHTTPCookieAcceptPolicyNever = 1, - kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain = 2 + kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain = 2, + kWKHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain = 3 }; typedef uint32_t WKHTTPCookieAcceptPolicy; // Cookie Manager Client typedef void (*WKCookieManagerCookiesDidChangeCallback)(WKCookieManagerRef cookieManager, const void *clientInfo); -struct WKCookieManagerClient { +typedef struct WKCookieManagerClientBase { int version; const void * clientInfo; - WKCookieManagerCookiesDidChangeCallback cookiesDidChange; -}; -typedef struct WKCookieManagerClient WKCookieManagerClient; +} WKCookieManagerClientBase; -enum { kWKCookieManagerClientCurrentVersion = 0 }; +typedef struct WKCookieManagerClientV0 { + WKCookieManagerClientBase base; + + // Version 0. + WKCookieManagerCookiesDidChangeCallback cookiesDidChange; +} WKCookieManagerClientV0; WK_EXPORT WKTypeID WKCookieManagerGetTypeID(); -WK_EXPORT void WKCookieManagerSetClient(WKCookieManagerRef cookieManager, const WKCookieManagerClient* client); +WK_EXPORT void WKCookieManagerSetClient(WKCookieManagerRef cookieManager, const WKCookieManagerClientBase* client); typedef void (*WKCookieManagerGetCookieHostnamesFunction)(WKArrayRef, WKErrorRef, void*); WK_EXPORT void WKCookieManagerGetHostnamesWithCookies(WKCookieManagerRef cookieManager, void* context, WKCookieManagerGetCookieHostnamesFunction function); @@ -61,6 +65,9 @@ WK_EXPORT void WKCookieManagerGetHostnamesWithCookies(WKCookieManagerRef cookieM WK_EXPORT void WKCookieManagerDeleteCookiesForHostname(WKCookieManagerRef cookieManager, WKStringRef hostname); WK_EXPORT void WKCookieManagerDeleteAllCookies(WKCookieManagerRef cookieManager); +// The time here is relative to the Unix epoch. +WK_EXPORT void WKCookieManagerDeleteAllCookiesModifiedAfterDate(WKCookieManagerRef cookieManager, double); + WK_EXPORT void WKCookieManagerSetHTTPCookieAcceptPolicy(WKCookieManagerRef cookieManager, WKHTTPCookieAcceptPolicy policy); typedef void (*WKCookieManagerGetHTTPCookieAcceptPolicyFunction)(WKHTTPCookieAcceptPolicy, WKErrorRef, void*); WK_EXPORT void WKCookieManagerGetHTTPCookieAcceptPolicy(WKCookieManagerRef cookieManager, void* context, WKCookieManagerGetHTTPCookieAcceptPolicyFunction callback); diff --git a/Source/WebKit2/UIProcess/API/C/WKCredential.cpp b/Source/WebKit2/UIProcess/API/C/WKCredential.cpp index 8b4c33ba1..35ecb203b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKCredential.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKCredential.cpp @@ -26,9 +26,9 @@ #include "config.h" #include "WKCredential.h" +#include "APIString.h" #include "WebCertificateInfo.h" #include "WebCredential.h" -#include "WebString.h" #include "WKAPICast.h" using namespace WebKit; @@ -40,18 +40,16 @@ WKTypeID WKCredentialGetTypeID() WKCredentialRef WKCredentialCreate(WKStringRef username, WKStringRef password, WKCredentialPersistence persistence) { - RefPtr<WebCredential> credential = WebCredential::create(toImpl(username), toImpl(password), toCredentialPersistence(persistence)); - return toAPI(credential.release().leakRef()); + return toAPI(&WebCredential::create(WebCore::Credential(toImpl(username)->string(), toImpl(password)->string(), toCredentialPersistence(persistence))).leakRef()); } WKCredentialRef WKCredentialCreateWithCertificateInfo(WKCertificateInfoRef certificateInfo) { - RefPtr<WebCredential> credential = WebCredential::create(toImpl(certificateInfo)); - return toAPI(credential.release().leakRef()); + return toAPI(&WebCredential::create(toImpl(certificateInfo)).leakRef()); } WKStringRef WKCredentialCopyUser(WKCredentialRef credentialRef) { - return toCopiedAPI(toImpl(credentialRef)->user()); + return toCopiedAPI(toImpl(credentialRef)->credential().user()); } diff --git a/Source/WebKit2/UIProcess/API/C/WKCredential.h b/Source/WebKit2/UIProcess/API/C/WKCredential.h index 560fc419a..57842fbda 100644 --- a/Source/WebKit2/UIProcess/API/C/WKCredential.h +++ b/Source/WebKit2/UIProcess/API/C/WKCredential.h @@ -26,8 +26,8 @@ #ifndef WKCredential_h #define WKCredential_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKCredentialTypes.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKCredentialTypes.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKCredentialTypes.h b/Source/WebKit2/UIProcess/API/C/WKCredentialTypes.h index bba31ac58..71ea8e9ee 100644 --- a/Source/WebKit2/UIProcess/API/C/WKCredentialTypes.h +++ b/Source/WebKit2/UIProcess/API/C/WKCredentialTypes.h @@ -26,6 +26,8 @@ #ifndef WKCredentialTypes_h #define WKCredentialTypes_h +#include <stdint.h> + #ifdef __cplusplus extern "C" { #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKDatabaseManager.cpp b/Source/WebKit2/UIProcess/API/C/WKDatabaseManager.cpp deleted file mode 100644 index 4f9496878..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKDatabaseManager.cpp +++ /dev/null @@ -1,212 +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 "WKDatabaseManager.h" - -#include "WebDatabaseManagerProxy.h" -#include "WKAPICast.h" - -#ifdef __BLOCKS__ -#include <Block.h> -#endif - -using namespace WebKit; - -WKTypeID WKDatabaseManagerGetTypeID() -{ -#if ENABLE(SQL_DATABASE) - return toAPI(WebDatabaseManagerProxy::APIType); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetOriginKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::originKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetOriginQuotaKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::originQuotaKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetOriginUsageKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::originUsageKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetDatabaseDetailsKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::databaseDetailsKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetDatabaseDetailsNameKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::databaseDetailsNameKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetDatabaseDetailsDisplayNameKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::databaseDetailsDisplayNameKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetDatabaseDetailsExpectedUsageKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::databaseDetailsExpectedUsageKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -WKStringRef WKDatabaseManagerGetDatabaseDetailsCurrentUsageKey() -{ -#if ENABLE(SQL_DATABASE) - static WebString* key = WebString::create(WebDatabaseManagerProxy::databaseDetailsCurrentUsageKey()).leakRef(); - return toAPI(key); -#else - return 0; -#endif -} - -void WKDatabaseManagerSetClient(WKDatabaseManagerRef databaseManagerRef, const WKDatabaseManagerClient* wkClient) -{ -#if ENABLE(SQL_DATABASE) - if (wkClient && wkClient->version) - return; - toImpl(databaseManagerRef)->initializeClient(wkClient); -#endif -} - -void WKDatabaseManagerGetDatabasesByOrigin(WKDatabaseManagerRef databaseManagerRef, void* context, WKDatabaseManagerGetDatabasesByOriginFunction callback) -{ -#if ENABLE(SQL_DATABASE) - toImpl(databaseManagerRef)->getDatabasesByOrigin(ArrayCallback::create(context, callback)); -#endif -} - -#ifdef __BLOCKS__ -static void callGetDatabasesByOriginBlockAndDispose(WKArrayRef resultValue, WKErrorRef errorRef, void* context) -{ -#if ENABLE(SQL_DATABASE) - WKDatabaseManagerGetDatabasesByOriginBlock block = (WKDatabaseManagerGetDatabasesByOriginBlock)context; - block(resultValue, errorRef); - Block_release(block); -#endif -} - -void WKDatabaseManagerGetDatabasesByOrigin_b(WKDatabaseManagerRef databaseManagerRef, WKDatabaseManagerGetDatabasesByOriginBlock block) -{ -#if ENABLE(SQL_DATABASE) - WKDatabaseManagerGetDatabasesByOrigin(databaseManagerRef, Block_copy(block), callGetDatabasesByOriginBlockAndDispose); -#endif -} -#endif // __BLOCKS__ - -void WKDatabaseManagerGetDatabaseOrigins(WKDatabaseManagerRef databaseManagerRef, void* context, WKDatabaseManagerGetDatabaseOriginsFunction callback) -{ -#if ENABLE(SQL_DATABASE) - toImpl(databaseManagerRef)->getDatabaseOrigins(ArrayCallback::create(context, callback)); -#endif -} - -#ifdef __BLOCKS__ -static void callGetDatabaseOriginsBlockBlockAndDispose(WKArrayRef resultValue, WKErrorRef errorRef, void* context) -{ -#if ENABLE(SQL_DATABASE) - WKDatabaseManagerGetDatabaseOriginsBlock block = (WKDatabaseManagerGetDatabaseOriginsBlock)context; - block(resultValue, errorRef); - Block_release(block); -#endif -} - -void WKDatabaseManagerGetDatabaseOrigins_b(WKDatabaseManagerRef databaseManagerRef, WKDatabaseManagerGetDatabaseOriginsBlock block) -{ -#if ENABLE(SQL_DATABASE) - WKDatabaseManagerGetDatabaseOrigins(databaseManagerRef, Block_copy(block), callGetDatabaseOriginsBlockBlockAndDispose); -#endif -} -#endif // __BLOCKS__ - -void WKDatabaseManagerDeleteDatabasesWithNameForOrigin(WKDatabaseManagerRef databaseManagerRef, WKStringRef databaseNameRef, WKSecurityOriginRef originRef) -{ -#if ENABLE(SQL_DATABASE) - toImpl(databaseManagerRef)->deleteDatabaseWithNameForOrigin(toWTFString(databaseNameRef), toImpl(originRef)); -#endif -} - -void WKDatabaseManagerDeleteDatabasesForOrigin(WKDatabaseManagerRef databaseManagerRef, WKSecurityOriginRef originRef) -{ -#if ENABLE(SQL_DATABASE) - toImpl(databaseManagerRef)->deleteDatabasesForOrigin(toImpl(originRef)); -#endif -} - -void WKDatabaseManagerDeleteAllDatabases(WKDatabaseManagerRef databaseManagerRef) -{ -#if ENABLE(SQL_DATABASE) - toImpl(databaseManagerRef)->deleteAllDatabases(); -#endif -} - -void WKDatabaseManagerSetQuotaForOrigin(WKDatabaseManagerRef databaseManagerRef, WKSecurityOriginRef originRef, uint64_t quota) -{ -#if ENABLE(SQL_DATABASE) - toImpl(databaseManagerRef)->setQuotaForOrigin(toImpl(originRef), quota); -#endif -} diff --git a/Source/WebKit2/UIProcess/API/C/WKDatabaseManager.h b/Source/WebKit2/UIProcess/API/C/WKDatabaseManager.h deleted file mode 100644 index 820f0f870..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKDatabaseManager.h +++ /dev/null @@ -1,108 +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 WKDatabaseManager_h -#define WKDatabaseManager_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/* Value type: WKSecurityOriginRef */ -WK_EXPORT WKStringRef WKDatabaseManagerGetOriginKey(); - -/* Value type: WKUInt64Ref */ -WK_EXPORT WKStringRef WKDatabaseManagerGetOriginQuotaKey(); - -/* Value type: WKUInt64Ref */ -WK_EXPORT WKStringRef WKDatabaseManagerGetOriginUsageKey(); - -/* Value type: WKArrayRef (array of WKDictionaryRef's with keys that include: - - WKDatabaseManagerGetDatabaseNameKey() - - WKDatabaseManagerGetDatabaseDisplayNameKey() - - WKDatabaseManagerGetDatabaseExpectedUsageKey() - - WKDatabaseManagerGetDatabaseCurrentUsageKey() - */ -WK_EXPORT WKStringRef WKDatabaseManagerGetDatabaseDetailsKey(); - -/* Value type: WKStringRef */ -WK_EXPORT WKStringRef WKDatabaseManagerGetDatabaseDetailsNameKey(); - -/* Value type: WKStringRef */ -WK_EXPORT WKStringRef WKDatabaseManagerGetDatabaseDetailsDisplayNameKey(); - -/* Value type: WKUInt64Ref */ -WK_EXPORT WKStringRef WKDatabaseManagerGetDatabaseDetailsExpectedUsageKey(); - -/* Value type: WKUInt64Ref */ -WK_EXPORT WKStringRef WKDatabaseManagerGetDatabaseDetailsCurrentUsageKey(); - - -// Database Manager Client -typedef void (*WKDatabaseManagerDidModifyOriginCallback)(WKDatabaseManagerRef databaseManager, WKSecurityOriginRef origin, const void *clientInfo); -typedef void (*WKDatabaseManagerDidModifyDatabaseCallback)(WKDatabaseManagerRef databaseManager, WKSecurityOriginRef origin, WKStringRef databaseIdentifier, const void *clientInfo); - -struct WKDatabaseManagerClient { - int version; - const void * clientInfo; - WKDatabaseManagerDidModifyOriginCallback didModifyOrigin; - WKDatabaseManagerDidModifyDatabaseCallback didModifyDatabase; -}; -typedef struct WKDatabaseManagerClient WKDatabaseManagerClient; - -enum { kWKDatabaseManagerClientCurrentVersion = 0 }; - - -WK_EXPORT WKTypeID WKDatabaseManagerGetTypeID(); - -WK_EXPORT void WKDatabaseManagerSetClient(WKDatabaseManagerRef databaseManager, const WKDatabaseManagerClient* client); - -typedef void (*WKDatabaseManagerGetDatabasesByOriginFunction)(WKArrayRef, WKErrorRef, void*); -WK_EXPORT void WKDatabaseManagerGetDatabasesByOrigin(WKDatabaseManagerRef databaseManager, void* context, WKDatabaseManagerGetDatabasesByOriginFunction function); -#ifdef __BLOCKS__ -typedef void (^WKDatabaseManagerGetDatabasesByOriginBlock)(WKArrayRef, WKErrorRef); -WK_EXPORT void WKDatabaseManagerGetDatabasesByOrigin_b(WKDatabaseManagerRef databaseManager, WKDatabaseManagerGetDatabasesByOriginBlock block); -#endif - -typedef void (*WKDatabaseManagerGetDatabaseOriginsFunction)(WKArrayRef, WKErrorRef, void*); -WK_EXPORT void WKDatabaseManagerGetDatabaseOrigins(WKDatabaseManagerRef contextRef, void* context, WKDatabaseManagerGetDatabaseOriginsFunction function); -#ifdef __BLOCKS__ -typedef void (^WKDatabaseManagerGetDatabaseOriginsBlock)(WKArrayRef, WKErrorRef); -WK_EXPORT void WKDatabaseManagerGetDatabaseOrigins_b(WKDatabaseManagerRef databaseManager, WKDatabaseManagerGetDatabaseOriginsBlock block); -#endif - -WK_EXPORT void WKDatabaseManagerDeleteDatabasesWithNameForOrigin(WKDatabaseManagerRef databaseManager, WKStringRef databaseName, WKSecurityOriginRef origin); -WK_EXPORT void WKDatabaseManagerDeleteDatabasesForOrigin(WKDatabaseManagerRef databaseManager, WKSecurityOriginRef origin); -WK_EXPORT void WKDatabaseManagerDeleteAllDatabases(WKDatabaseManagerRef databaseManager); - -WK_EXPORT void WKDatabaseManagerSetQuotaForOrigin(WKDatabaseManagerRef databaseManager, WKSecurityOriginRef origin, uint64_t quota); - -#ifdef __cplusplus -} -#endif - -#endif // WKDatabaseManager_h diff --git a/Source/WebKit2/UIProcess/API/C/WKDownload.cpp b/Source/WebKit2/UIProcess/API/C/WKDownload.cpp index 3588fd563..abf93f12f 100644 --- a/Source/WebKit2/UIProcess/API/C/WKDownload.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKDownload.cpp @@ -26,9 +26,10 @@ #include "config.h" #include "WKDownload.h" +#include "APIData.h" +#include "APIURLRequest.h" #include "DownloadProxy.h" #include "WKAPICast.h" -#include "WebURLRequest.h" using namespace WebKit; @@ -39,12 +40,12 @@ WKTypeID WKDownloadGetTypeID() uint64_t WKDownloadGetID(WKDownloadRef download) { - return toImpl(download)->downloadID(); + return toImpl(download)->downloadID().downloadID(); } WKURLRequestRef WKDownloadCopyRequest(WKDownloadRef download) { - return toAPI(WebURLRequest::create(toImpl(download)->request()).leakRef()); + return toAPI(&API::URLRequest::create(toImpl(download)->request()).leakRef()); } WKDataRef WKDownloadGetResumeData(WKDownloadRef download) diff --git a/Source/WebKit2/UIProcess/API/C/WKDownload.h b/Source/WebKit2/UIProcess/API/C/WKDownload.h index 8acc9106d..5dbea7e44 100644 --- a/Source/WebKit2/UIProcess/API/C/WKDownload.h +++ b/Source/WebKit2/UIProcess/API/C/WKDownload.h @@ -26,7 +26,7 @@ #ifndef WKDownload_h #define WKDownload_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifndef __cplusplus #include <stdbool.h> diff --git a/Source/WebKit2/UIProcess/API/C/WKFormSubmissionListener.h b/Source/WebKit2/UIProcess/API/C/WKFormSubmissionListener.h index 4b9b79acb..c320b68d4 100644 --- a/Source/WebKit2/UIProcess/API/C/WKFormSubmissionListener.h +++ b/Source/WebKit2/UIProcess/API/C/WKFormSubmissionListener.h @@ -26,7 +26,7 @@ #ifndef WKFormSubmissionListener_h #define WKFormSubmissionListener_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKFrame.cpp b/Source/WebKit2/UIProcess/API/C/WKFrame.cpp index 3bb375f7d..f54e70d8a 100644 --- a/Source/WebKit2/UIProcess/API/C/WKFrame.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKFrame.cpp @@ -26,12 +26,12 @@ #include "config.h" #include "WKFrame.h" +#include "APIData.h" +#include "APIFrameInfo.h" #include "WKAPICast.h" +#include "WebCertificateInfo.h" #include "WebFrameProxy.h" - -#ifdef __BLOCKS__ -#include <Block.h> -#endif +#include "WebPageProxy.h" using namespace WebKit; @@ -48,13 +48,13 @@ bool WKFrameIsMainFrame(WKFrameRef frameRef) WKFrameLoadState WKFrameGetFrameLoadState(WKFrameRef frameRef) { WebFrameProxy* frame = toImpl(frameRef); - switch (frame->loadState()) { - case WebFrameProxy::LoadStateProvisional: - return kWKFrameLoadStateProvisional; - case WebFrameProxy::LoadStateCommitted: - return kWKFrameLoadStateCommitted; - case WebFrameProxy::LoadStateFinished: - return kWKFrameLoadStateFinished; + switch (frame->frameLoadState().state()) { + case FrameLoadState::State::Provisional: + return kWKFrameLoadStateProvisional; + case FrameLoadState::State::Committed: + return kWKFrameLoadStateCommitted; + case FrameLoadState::State::Finished: + return kWKFrameLoadStateFinished; } ASSERT_NOT_REACHED(); @@ -126,63 +126,22 @@ bool WKFrameIsFrameSet(WKFrameRef frameRef) return toImpl(frameRef)->isFrameSet(); } -void WKFrameGetMainResourceData(WKFrameRef frameRef, WKFrameGetResourceDataFunction callback, void* context) +WKFrameInfoRef WKFrameCreateFrameInfo(WKFrameRef frameRef) { - toImpl(frameRef)->getMainResourceData(DataCallback::create(context, callback)); + return toAPI(&API::FrameInfo::create(*toImpl(frameRef), WebCore::SecurityOrigin::createFromString(toImpl(frameRef)->url())).leakRef()); } -void WKFrameGetResourceData(WKFrameRef frameRef, WKURLRef resourceURL, WKFrameGetResourceDataFunction callback, void* context) -{ - toImpl(frameRef)->getResourceData(toImpl(resourceURL), DataCallback::create(context, callback)); -} - -#ifdef __BLOCKS__ -static void callGetResourceDataBlockAndDispose(WKDataRef data, WKErrorRef error, void* context) -{ - WKFrameGetResourceDataBlock block = (WKFrameGetResourceDataBlock)context; - block(data, error); - Block_release(block); -} - -void WKFrameGetMainResourceData_b(WKFrameRef frameRef, WKFrameGetResourceDataBlock block) +void WKFrameGetMainResourceData(WKFrameRef frameRef, WKFrameGetResourceDataFunction callback, void* context) { - WKFrameGetMainResourceData(frameRef, callGetResourceDataBlockAndDispose, Block_copy(block)); + toImpl(frameRef)->getMainResourceData(toGenericCallbackFunction(context, callback)); } -void WKFrameGetResourceData_b(WKFrameRef frameRef, WKURLRef resourceURL, WKFrameGetResourceDataBlock block) +void WKFrameGetResourceData(WKFrameRef frameRef, WKURLRef resourceURL, WKFrameGetResourceDataFunction callback, void* context) { - WKFrameGetResourceData(frameRef, resourceURL, callGetResourceDataBlockAndDispose, Block_copy(block)); + toImpl(frameRef)->getResourceData(toImpl(resourceURL), toGenericCallbackFunction(context, callback)); } -#endif void WKFrameGetWebArchive(WKFrameRef frameRef, WKFrameGetWebArchiveFunction callback, void* context) { - toImpl(frameRef)->getWebArchive(DataCallback::create(context, callback)); -} - -#ifdef __BLOCKS__ -static void callGetWebArchiveBlockAndDispose(WKDataRef archiveData, WKErrorRef error, void* context) -{ - WKFrameGetWebArchiveBlock block = (WKFrameGetWebArchiveBlock)context; - block(archiveData, error); - Block_release(block); -} - -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; + toImpl(frameRef)->getWebArchive(toGenericCallbackFunction(context, callback)); } diff --git a/Source/WebKit2/UIProcess/API/C/WKFrame.h b/Source/WebKit2/UIProcess/API/C/WKFrame.h index d8221cc0c..4fd29a608 100644 --- a/Source/WebKit2/UIProcess/API/C/WKFrame.h +++ b/Source/WebKit2/UIProcess/API/C/WKFrame.h @@ -26,7 +26,7 @@ #ifndef WKFrame_h #define WKFrame_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifndef __cplusplus #include <stdbool.h> @@ -68,27 +68,14 @@ WK_EXPORT bool WKFrameIsDisplayingMarkupDocument(WKFrameRef frame); WK_EXPORT bool WKFrameIsFrameSet(WKFrameRef frame); +WK_EXPORT WKFrameInfoRef WKFrameCreateFrameInfo(WKFrameRef frame); + typedef void (*WKFrameGetResourceDataFunction)(WKDataRef data, WKErrorRef error, void* functionContext); WK_EXPORT void WKFrameGetMainResourceData(WKFrameRef frame, WKFrameGetResourceDataFunction function, void* functionContext); WK_EXPORT void WKFrameGetResourceData(WKFrameRef frame, WKURLRef resourceURL, WKFrameGetResourceDataFunction function, void* functionContext); -#ifdef __BLOCKS__ -typedef void (^WKFrameGetResourceDataBlock)(WKDataRef data, WKErrorRef error); -WK_EXPORT void WKFrameGetMainResourceData_b(WKFrameRef frame, WKFrameGetResourceDataBlock block); -WK_EXPORT void WKFrameGetResourceData_b(WKFrameRef frame, WKURLRef resourceURL, WKFrameGetResourceDataBlock block); -#endif typedef void (*WKFrameGetWebArchiveFunction)(WKDataRef archiveData, WKErrorRef error, void* functionContext); WK_EXPORT void WKFrameGetWebArchive(WKFrameRef frame, WKFrameGetWebArchiveFunction function, void* functionContext); -#ifdef __BLOCKS__ -typedef void (^WKFrameGetWebArchiveBlock)(WKDataRef archiveData, WKErrorRef error); -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 } diff --git a/Source/WebKit2/UIProcess/gtk/WebProcessProxyGtk.cpp b/Source/WebKit2/UIProcess/API/C/WKFrameInfoRef.cpp index e8b173d07..dbdd10113 100644 --- a/Source/WebKit2/UIProcess/gtk/WebProcessProxyGtk.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKFrameInfoRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,12 +24,14 @@ */ #include "config.h" -#include "WebProcessProxy.h" +#include "WKFrameInfoRef.h" -namespace WebKit { +#include "APIFrameInfo.h" +#include "WKAPICast.h" -void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions&) +using namespace WebKit; + +WKTypeID WKFrameInfoGetTypeID() { + return toAPI(API::FrameInfo::APIType); } - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKViewPrivate.h b/Source/WebKit2/UIProcess/API/C/WKFrameInfoRef.h index 2c1b2d1f0..f7ddadd92 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKViewPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKFrameInfoRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 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,19 +23,19 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKViewPrivate_h -#define WKViewPrivate_h +#ifndef WKFrameInfoRef_h +#define WKFrameInfoRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT void WKViewSetFocus(WKViewRef viewRef, bool focused); +WK_EXPORT WKTypeID WKFrameInfoGetTypeID(); #ifdef __cplusplus } #endif -#endif /* WKViewPrivate_h */ +#endif // WKFrameInfoRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WKFramePolicyListener.h b/Source/WebKit2/UIProcess/API/C/WKFramePolicyListener.h index 99b013d54..046c68131 100644 --- a/Source/WebKit2/UIProcess/API/C/WKFramePolicyListener.h +++ b/Source/WebKit2/UIProcess/API/C/WKFramePolicyListener.h @@ -26,7 +26,7 @@ #ifndef WKFramePolicyListener_h #define WKFramePolicyListener_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.cpp b/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.cpp index 384e05156..18b1a09bc 100644 --- a/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.cpp @@ -28,6 +28,7 @@ #include "WKAPICast.h" #include "WebGeolocationManagerProxy.h" +#include "WebGeolocationPosition.h" using namespace WebKit; @@ -36,7 +37,7 @@ WKTypeID WKGeolocationManagerGetTypeID() return toAPI(WebGeolocationManagerProxy::APIType); } -void WKGeolocationManagerSetProvider(WKGeolocationManagerRef geolocationManagerRef, const WKGeolocationProvider* wkProvider) +void WKGeolocationManagerSetProvider(WKGeolocationManagerRef geolocationManagerRef, const WKGeolocationProviderBase* wkProvider) { toImpl(geolocationManagerRef)->initializeProvider(wkProvider); } diff --git a/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.h b/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.h index 7f9cb6891..581ae0472 100644 --- a/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKGeolocationManager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2012, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,7 +26,7 @@ #ifndef WKGeolocationManager_h #define WKGeolocationManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -35,20 +35,36 @@ extern "C" { // Provider. typedef void (*WKGeolocationProviderStartUpdatingCallback)(WKGeolocationManagerRef geolocationManager, const void* clientInfo); typedef void (*WKGeolocationProviderStopUpdatingCallback)(WKGeolocationManagerRef geolocationManager, const void* clientInfo); +typedef void (*WKGeolocationProviderSetEnableHighAccuracyCallback)(WKGeolocationManagerRef geolocationManager, bool enabled, const void* clientInfo); -struct WKGeolocationProvider { +typedef struct WKGeolocationProviderBase { int version; const void * clientInfo; +} WKGeolocationProviderBase; + +typedef struct WKGeolocationProviderV0 { + WKGeolocationProviderBase base; + + // Version 0. WKGeolocationProviderStartUpdatingCallback startUpdating; WKGeolocationProviderStopUpdatingCallback stopUpdating; -}; -typedef struct WKGeolocationProvider WKGeolocationProvider; +} WKGeolocationProviderV0; + +typedef struct WKGeolocationProviderV1 { + WKGeolocationProviderBase base; + + // Version 0. + WKGeolocationProviderStartUpdatingCallback startUpdating; + WKGeolocationProviderStopUpdatingCallback stopUpdating; + + // Version 1. + WKGeolocationProviderSetEnableHighAccuracyCallback setEnableHighAccuracy; +} WKGeolocationProviderV1; -enum { kWKGeolocationProviderCurrentVersion = 0 }; WK_EXPORT WKTypeID WKGeolocationManagerGetTypeID(); -WK_EXPORT void WKGeolocationManagerSetProvider(WKGeolocationManagerRef geolocationManager, const WKGeolocationProvider* provider); +WK_EXPORT void WKGeolocationManagerSetProvider(WKGeolocationManagerRef geolocationManager, const WKGeolocationProviderBase* provider); WK_EXPORT void WKGeolocationManagerProviderDidChangePosition(WKGeolocationManagerRef geolocationManager, WKGeolocationPositionRef position); WK_EXPORT void WKGeolocationManagerProviderDidFailToDeterminePosition(WKGeolocationManagerRef geolocationManager); diff --git a/Source/WebKit2/UIProcess/API/C/WKGeolocationPermissionRequest.h b/Source/WebKit2/UIProcess/API/C/WKGeolocationPermissionRequest.h index ee27b66ec..b1391813a 100644 --- a/Source/WebKit2/UIProcess/API/C/WKGeolocationPermissionRequest.h +++ b/Source/WebKit2/UIProcess/API/C/WKGeolocationPermissionRequest.h @@ -26,7 +26,7 @@ #ifndef WKGeolocationPermissionRequest_h #define WKGeolocationPermissionRequest_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKGeolocationPosition.h b/Source/WebKit2/UIProcess/API/C/WKGeolocationPosition.h index 4727e9763..6d67f1d1e 100644 --- a/Source/WebKit2/UIProcess/API/C/WKGeolocationPosition.h +++ b/Source/WebKit2/UIProcess/API/C/WKGeolocationPosition.h @@ -26,7 +26,7 @@ #ifndef WKGeolocationPosition_h #define WKGeolocationPosition_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.cpp b/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.cpp index 9bf8315b3..065f99ba7 100644 --- a/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.cpp @@ -26,8 +26,8 @@ #include "config.h" #include "WKGrammarDetail.h" +#include "APIArray.h" #include "APIObject.h" -#include "ImmutableArray.h" #include "WKAPICast.h" #include "WebGrammarDetail.h" @@ -35,7 +35,7 @@ using namespace WebKit; WKTypeID WKGrammarDetailGetTypeID() { - return toAPI(APIObject::TypeGrammarDetail); + return toAPI(API::Object::Type::GrammarDetail); } WKGrammarDetailRef WKGrammarDetailCreate(int location, int length, WKArrayRef guesses, WKStringRef userDescription) @@ -56,7 +56,7 @@ int WKGrammarDetailGetLength(WKGrammarDetailRef grammarDetailRef) WKArrayRef WKGrammarDetailCopyGuesses(WKGrammarDetailRef grammarDetailRef) { - return toAPI(toImpl(grammarDetailRef)->guesses().leakRef()); + return toAPI(&toImpl(grammarDetailRef)->guesses().leakRef()); } WKStringRef WKGrammarDetailCopyUserDescription(WKGrammarDetailRef grammarDetailRef) diff --git a/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.h b/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.h index c187ce6ad..2493c44d4 100644 --- a/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.h +++ b/Source/WebKit2/UIProcess/API/C/WKGrammarDetail.h @@ -26,7 +26,7 @@ #ifndef WKGrammarDetail_h #define WKGrammarDetail_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKHitTestResult.cpp b/Source/WebKit2/UIProcess/API/C/WKHitTestResult.cpp index 5949091bb..4082002b0 100644 --- a/Source/WebKit2/UIProcess/API/C/WKHitTestResult.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKHitTestResult.cpp @@ -27,14 +27,14 @@ #include "config.h" #include "WKHitTestResult.h" +#include "APIHitTestResult.h" #include "WKAPICast.h" -#include "WebHitTestResult.h" using namespace WebKit; WKTypeID WKHitTestResultGetTypeID() { - return toAPI(WebHitTestResult::APIType); + return toAPI(API::HitTestResult::APIType); } WKURLRef WKHitTestResultCopyAbsoluteImageURL(WKHitTestResultRef hitTestResultRef) @@ -67,7 +67,17 @@ WKStringRef WKHitTestResultCopyLinkTitle(WKHitTestResultRef hitTestResultRef) return toCopiedAPI(toImpl(hitTestResultRef)->linkTitle()); } +WKStringRef WKHitTestResultCopyLookupText(WKHitTestResultRef hitTestResult) +{ + return toCopiedAPI(toImpl(hitTestResult)->lookupText()); +} + bool WKHitTestResultIsContentEditable(WKHitTestResultRef hitTestResultRef) { return toImpl(hitTestResultRef)->isContentEditable(); } + +WKRect WKHitTestResultGetElementBoundingBox(WKHitTestResultRef hitTestResultRef) +{ + return toAPI(toImpl(hitTestResultRef)->elementBoundingBox()); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKHitTestResult.h b/Source/WebKit2/UIProcess/API/C/WKHitTestResult.h index 55fd13768..3c7081362 100644 --- a/Source/WebKit2/UIProcess/API/C/WKHitTestResult.h +++ b/Source/WebKit2/UIProcess/API/C/WKHitTestResult.h @@ -27,7 +27,8 @@ #ifndef WKHitTestResult_h #define WKHitTestResult_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKGeometry.h> #ifdef __cplusplus extern "C" { @@ -42,9 +43,12 @@ WK_EXPORT WKURLRef WKHitTestResultCopyAbsoluteMediaURL(WKHitTestResultRef hitTes WK_EXPORT WKStringRef WKHitTestResultCopyLinkLabel(WKHitTestResultRef hitTestResult); WK_EXPORT WKStringRef WKHitTestResultCopyLinkTitle(WKHitTestResultRef hitTestResult); +WK_EXPORT WKStringRef WKHitTestResultCopyLookupText(WKHitTestResultRef hitTestResult); WK_EXPORT bool WKHitTestResultIsContentEditable(WKHitTestResultRef hitTestResult); +WK_EXPORT WKRect WKHitTestResultGetElementBoundingBox(WKHitTestResultRef hitTestResultRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKIconDatabase.cpp b/Source/WebKit2/UIProcess/API/C/WKIconDatabase.cpp index d667bb752..39006631f 100644 --- a/Source/WebKit2/UIProcess/API/C/WKIconDatabase.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKIconDatabase.cpp @@ -26,6 +26,7 @@ #include "config.h" #include "WKIconDatabase.h" +#include "APIData.h" #include "WKAPICast.h" #include "WebIconDatabase.h" @@ -36,7 +37,7 @@ WKTypeID WKIconDatabaseGetTypeID() return toAPI(WebIconDatabase::APIType); } -void WKIconDatabaseSetIconDatabaseClient(WKIconDatabaseRef iconDatabaseRef, const WKIconDatabaseClient* wkClient) +void WKIconDatabaseSetIconDatabaseClient(WKIconDatabaseRef iconDatabaseRef, const WKIconDatabaseClientBase* wkClient) { toImpl(iconDatabaseRef)->initializeIconDatabaseClient(wkClient); } @@ -51,6 +52,28 @@ void WKIconDatabaseReleaseIconForURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef toImpl(iconDatabaseRef)->releaseIconForPageURL(toWTFString(pageURLRef)); } +void WKIconDatabaseSetIconDataForIconURL(WKIconDatabaseRef iconDatabaseRef, WKDataRef iconDataRef, WKURLRef iconURLRef) +{ + toImpl(iconDatabaseRef)->setIconDataForIconURL(toImpl(iconDataRef)->dataReference(), toWTFString(iconURLRef)); +} + +void WKIconDatabaseSetIconURLForPageURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef iconURLRef, WKURLRef pageURLRef) +{ + toImpl(iconDatabaseRef)->setIconURLForPageURL(toWTFString(iconURLRef), toWTFString(pageURLRef)); +} + +WKURLRef WKIconDatabaseCopyIconURLForPageURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef pageURLRef) +{ + String iconURLString; + toImpl(iconDatabaseRef)->synchronousIconURLForPageURL(toWTFString(pageURLRef), iconURLString); + return toCopiedURLAPI(iconURLString); +} + +WKDataRef WKIconDatabaseCopyIconDataForPageURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef pageURL) +{ + return toAPI(toImpl(iconDatabaseRef)->iconDataForPageURL(toWTFString(pageURL)).leakRef()); +} + void WKIconDatabaseEnableDatabaseCleanup(WKIconDatabaseRef iconDatabaseRef) { toImpl(iconDatabaseRef)->enableDatabaseCleanup(); diff --git a/Source/WebKit2/UIProcess/API/C/WKIconDatabase.h b/Source/WebKit2/UIProcess/API/C/WKIconDatabase.h index eec4ab3af..847414179 100644 --- a/Source/WebKit2/UIProcess/API/C/WKIconDatabase.h +++ b/Source/WebKit2/UIProcess/API/C/WKIconDatabase.h @@ -26,7 +26,7 @@ #ifndef WKIconDatabase_h #define WKIconDatabase_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -37,27 +37,41 @@ typedef void (*WKIconDatabaseDidChangeIconForPageURLCallback)(WKIconDatabaseRef typedef void (*WKIconDatabaseDidRemoveAllIconsCallback)(WKIconDatabaseRef iconDatabase, const void* clientInfo); typedef void (*WKIconDatabaseIconDataReadyForPageURLCallback)(WKIconDatabaseRef iconDatabase, WKURLRef pageURL, const void* clientInfo); -struct WKIconDatabaseClient { +typedef struct WKIconDatabaseClientBase { int version; const void * clientInfo; +} WKIconDatabaseClientBase; - // Version 0 +typedef struct WKIconDatabaseClientV0 { + WKIconDatabaseClientBase base; + + // Version 0. WKIconDatabaseDidChangeIconForPageURLCallback didChangeIconForPageURL; WKIconDatabaseDidRemoveAllIconsCallback didRemoveAllIcons; +} WKIconDatabaseClientV0; - // Version 1 - WKIconDatabaseIconDataReadyForPageURLCallback iconDataReadyForPageURL; -}; -typedef struct WKIconDatabaseClient WKIconDatabaseClient; +typedef struct WKIconDatabaseClientV1 { + WKIconDatabaseClientBase base; -enum { kWKIconDatabaseClientCurrentVersion = 1 }; + // Version 0. + WKIconDatabaseDidChangeIconForPageURLCallback didChangeIconForPageURL; + WKIconDatabaseDidRemoveAllIconsCallback didRemoveAllIcons; + + // Version 1. + WKIconDatabaseIconDataReadyForPageURLCallback iconDataReadyForPageURL; +} WKIconDatabaseClientV1; WK_EXPORT WKTypeID WKIconDatabaseGetTypeID(); -WK_EXPORT void WKIconDatabaseSetIconDatabaseClient(WKIconDatabaseRef iconDatabase, const WKIconDatabaseClient* client); +WK_EXPORT void WKIconDatabaseSetIconDatabaseClient(WKIconDatabaseRef iconDatabase, const WKIconDatabaseClientBase* client); WK_EXPORT void WKIconDatabaseRetainIconForURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL); WK_EXPORT void WKIconDatabaseReleaseIconForURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL); +WK_EXPORT void WKIconDatabaseSetIconDataForIconURL(WKIconDatabaseRef iconDatabase, WKDataRef iconData, WKURLRef iconURL); +WK_EXPORT void WKIconDatabaseSetIconURLForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef iconURL, WKURLRef pageURL); +WK_EXPORT WKURLRef WKIconDatabaseCopyIconURLForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL); +WK_EXPORT WKDataRef WKIconDatabaseCopyIconDataForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL); + WK_EXPORT void WKIconDatabaseEnableDatabaseCleanup(WKIconDatabaseRef iconDatabase); WK_EXPORT void WKIconDatabaseRemoveAllIcons(WKIconDatabaseRef iconDatabase); diff --git a/Source/WebKit2/UIProcess/API/C/WKInspector.cpp b/Source/WebKit2/UIProcess/API/C/WKInspector.cpp index e638609bb..92c641dbb 100644 --- a/Source/WebKit2/UIProcess/API/C/WKInspector.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKInspector.cpp @@ -26,205 +26,98 @@ #include "config.h" #include "WKInspector.h" +#if !PLATFORM(IOS) + #include "WKAPICast.h" #include "WebInspectorProxy.h" +#include "WebPageProxy.h" using namespace WebKit; WKTypeID WKInspectorGetTypeID() { -#if ENABLE(INSPECTOR) return toAPI(WebInspectorProxy::APIType); -#else - return 0; -#endif } WKPageRef WKInspectorGetPage(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) - return toAPI(toImpl(inspectorRef)->page()); -#else - UNUSED_PARAM(inspectorRef); - return 0; -#endif + return toAPI(toImpl(inspectorRef)->inspectedPage()); } 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 } 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 } void WKInspectorClose(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) toImpl(inspectorRef)->close(); -#else - UNUSED_PARAM(inspectorRef); -#endif } void WKInspectorShowConsole(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) toImpl(inspectorRef)->showConsole(); -#else - UNUSED_PARAM(inspectorRef); -#endif } void WKInspectorShowResources(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) toImpl(inspectorRef)->showResources(); -#else - UNUSED_PARAM(inspectorRef); -#endif } void WKInspectorShowMainResourceForFrame(WKInspectorRef inspectorRef, WKFrameRef frameRef) { -#if ENABLE(INSPECTOR) toImpl(inspectorRef)->showMainResourceForFrame(toImpl(frameRef)); -#else - UNUSED_PARAM(inspectorRef); - UNUSED_PARAM(frameRef); -#endif } bool WKInspectorIsAttached(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isAttached(); -#else - UNUSED_PARAM(inspectorRef); - return false; -#endif } void WKInspectorAttach(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) - toImpl(inspectorRef)->attach(); -#else - UNUSED_PARAM(inspectorRef); -#endif + auto inspector = toImpl(inspectorRef); + inspector->attach(inspector->attachmentSide()); } void WKInspectorDetach(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) toImpl(inspectorRef)->detach(); -#else - UNUSED_PARAM(inspectorRef); -#endif -} - -bool WKInspectorIsDebuggingJavaScript(WKInspectorRef inspectorRef) -{ -#if ENABLE(INSPECTOR) - return toImpl(inspectorRef)->isDebuggingJavaScript(); -#else - UNUSED_PARAM(inspectorRef); - return false; -#endif -} - -void WKInspectorToggleJavaScriptDebugging(WKInspectorRef inspectorRef) -{ -#if ENABLE(INSPECTOR) - toImpl(inspectorRef)->toggleJavaScriptDebugging(); -#else - UNUSED_PARAM(inspectorRef); -#endif -} - -bool WKInspectorIsProfilingJavaScript(WKInspectorRef inspectorRef) -{ -#if ENABLE(INSPECTOR) - return toImpl(inspectorRef)->isProfilingJavaScript(); -#else - UNUSED_PARAM(inspectorRef); - return false; -#endif -} - -void WKInspectorToggleJavaScriptProfiling(WKInspectorRef inspectorRef) -{ -#if ENABLE(INSPECTOR) - toImpl(inspectorRef)->toggleJavaScriptProfiling(); -#else - UNUSED_PARAM(inspectorRef); -#endif } bool WKInspectorIsProfilingPage(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) return toImpl(inspectorRef)->isProfilingPage(); -#else - UNUSED_PARAM(inspectorRef); - return false; -#endif } void WKInspectorTogglePageProfiling(WKInspectorRef inspectorRef) { -#if ENABLE(INSPECTOR) toImpl(inspectorRef)->togglePageProfiling(); -#else - UNUSED_PARAM(inspectorRef); -#endif } + +#endif // !PLATFORM(IOS) diff --git a/Source/WebKit2/UIProcess/API/C/WKInspector.h b/Source/WebKit2/UIProcess/API/C/WKInspector.h index 203e1b3cf..14654fcd4 100644 --- a/Source/WebKit2/UIProcess/API/C/WKInspector.h +++ b/Source/WebKit2/UIProcess/API/C/WKInspector.h @@ -26,7 +26,7 @@ #ifndef WKInspector_h #define WKInspector_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifndef __cplusplus #include <stdbool.h> @@ -58,12 +58,6 @@ WK_EXPORT bool WKInspectorIsAttached(WKInspectorRef inspector); WK_EXPORT void WKInspectorAttach(WKInspectorRef inspector); WK_EXPORT void WKInspectorDetach(WKInspectorRef inspector); -WK_EXPORT bool WKInspectorIsDebuggingJavaScript(WKInspectorRef inspector); -WK_EXPORT void WKInspectorToggleJavaScriptDebugging(WKInspectorRef inspector); - -WK_EXPORT bool WKInspectorIsProfilingJavaScript(WKInspectorRef inspector); -WK_EXPORT void WKInspectorToggleJavaScriptProfiling(WKInspectorRef inspector); - WK_EXPORT bool WKInspectorIsProfilingPage(WKInspectorRef inspector); WK_EXPORT void WKInspectorTogglePageProfiling(WKInspectorRef inspector); diff --git a/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp b/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp index d33c056bf..e412511f6 100644 --- a/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.cpp @@ -26,27 +26,106 @@ #include "config.h" #include "WKKeyValueStorageManager.h" +#include "APIDictionary.h" +#include "APIWebsiteDataStore.h" +#include "StorageManager.h" #include "WKAPICast.h" -#include "WebKeyValueStorageManager.h" +#include "WebsiteDataStore.h" +#include <wtf/RunLoop.h> using namespace WebKit; WKTypeID WKKeyValueStorageManagerGetTypeID() { - return toAPI(WebKeyValueStorageManager::APIType); + return toAPI(API::WebsiteDataStore::APIType); } -void WKKeyValueStorageManagerGetKeyValueStorageOrigins(WKKeyValueStorageManagerRef keyValueStorageManagerRef, void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) +WKStringRef WKKeyValueStorageManagerGetOriginKey() { - toImpl(keyValueStorageManagerRef)->getKeyValueStorageOrigins(ArrayCallback::create(context, callback)); + static API::String& key = API::String::create("WebKeyValueStorageManagerStorageDetailsOriginKey").leakRef(); + return toAPI(&key); } -void WKKeyValueStorageManagerDeleteEntriesForOrigin(WKKeyValueStorageManagerRef keyValueStorageManagerRef, WKSecurityOriginRef originRef) +WKStringRef WKKeyValueStorageManagerGetCreationTimeKey() { - toImpl(keyValueStorageManagerRef)->deleteEntriesForOrigin(toImpl(originRef)); + static API::String& key = API::String::create("WebKeyValueStorageManagerStorageDetailsCreationTimeKey").leakRef(); + return toAPI(&key); } -void WKKeyValueStorageManagerDeleteAllEntries(WKKeyValueStorageManagerRef keyValueStorageManagerRef) +WKStringRef WKKeyValueStorageManagerGetModificationTimeKey() { - toImpl(keyValueStorageManagerRef)->deleteAllEntries(); + static API::String& key = API::String::create("WebKeyValueStorageManagerStorageDetailsModificationTimeKey").leakRef(); + return toAPI(&key); +} + +void WKKeyValueStorageManagerGetKeyValueStorageOrigins(WKKeyValueStorageManagerRef keyValueStorageManager, void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) + +{ + StorageManager* storageManager = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(keyValueStorageManager))->websiteDataStore().storageManager(); + if (!storageManager) { + RunLoop::main().dispatch([context, callback] { + callback(toAPI(API::Array::create().ptr()), nullptr, context); + }); + return; + } + + storageManager->getLocalStorageOrigins([context, callback](HashSet<RefPtr<WebCore::SecurityOrigin>>&& securityOrigins) { + Vector<RefPtr<API::Object>> webSecurityOrigins; + webSecurityOrigins.reserveInitialCapacity(securityOrigins.size()); + for (auto& origin : securityOrigins) + webSecurityOrigins.uncheckedAppend(API::SecurityOrigin::create(*origin)); + + callback(toAPI(API::Array::create(WTFMove(webSecurityOrigins)).ptr()), nullptr, context); + }); +} + +void WKKeyValueStorageManagerGetStorageDetailsByOrigin(WKKeyValueStorageManagerRef keyValueStorageManager, void* context, WKKeyValueStorageManagerGetStorageDetailsByOriginFunction callback) +{ + StorageManager* storageManager = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(keyValueStorageManager))->websiteDataStore().storageManager(); + if (!storageManager) { + RunLoop::main().dispatch([context, callback] { + callback(toAPI(API::Array::create().ptr()), nullptr, context); + }); + return; + } + + storageManager->getLocalStorageOriginDetails([context, callback](Vector<LocalStorageDatabaseTracker::OriginDetails> storageDetails) { + HashMap<String, RefPtr<API::Object>> detailsMap; + Vector<RefPtr<API::Object>> result; + result.reserveInitialCapacity(storageDetails.size()); + + for (const auto& originDetails : storageDetails) { + HashMap<String, RefPtr<API::Object>> detailsMap; + + RefPtr<API::Object> origin = API::SecurityOrigin::create(WebCore::SecurityOrigin::createFromDatabaseIdentifier(originDetails.originIdentifier)); + + detailsMap.set(toImpl(WKKeyValueStorageManagerGetOriginKey())->string(), origin); + if (originDetails.creationTime) + detailsMap.set(toImpl(WKKeyValueStorageManagerGetCreationTimeKey())->string(), API::Double::create(originDetails.creationTime.valueOr(0))); + if (originDetails.modificationTime) + detailsMap.set(toImpl(WKKeyValueStorageManagerGetModificationTimeKey())->string(), API::Double::create(originDetails.modificationTime.valueOr(0))); + + result.uncheckedAppend(API::Dictionary::create(WTFMove(detailsMap))); + } + + callback(toAPI(API::Array::create(WTFMove(result)).ptr()), nullptr, context); + }); +} + +void WKKeyValueStorageManagerDeleteEntriesForOrigin(WKKeyValueStorageManagerRef keyValueStorageManager, WKSecurityOriginRef origin) +{ + StorageManager* storageManager = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(keyValueStorageManager))->websiteDataStore().storageManager(); + if (!storageManager) + return; + + storageManager->deleteLocalStorageEntriesForOrigin(toImpl(origin)->securityOrigin()); +} + +void WKKeyValueStorageManagerDeleteAllEntries(WKKeyValueStorageManagerRef keyValueStorageManager) +{ + StorageManager* storageManager = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(keyValueStorageManager))->websiteDataStore().storageManager(); + if (!storageManager) + return; + + storageManager->deleteLocalStorageOriginsModifiedSince(std::chrono::system_clock::time_point::min(), [] { }); } diff --git a/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.h b/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.h index a0ee27825..d92adadad 100644 --- a/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKKeyValueStorageManager.h @@ -26,7 +26,7 @@ #ifndef WKKeyValueStorageManager_h #define WKKeyValueStorageManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -34,9 +34,21 @@ extern "C" { WK_EXPORT WKTypeID WKKeyValueStorageManagerGetTypeID(); +/* Value type: WKSecurityOriginRef */ +WK_EXPORT WKStringRef WKKeyValueStorageManagerGetOriginKey(); + +/* Value type: WKDoubleRef, seconds since January 1st, 1970 UTC */ +WK_EXPORT WKStringRef WKKeyValueStorageManagerGetCreationTimeKey(); + +/* Value type: WKDoubleRef, seconds since January 1st, 1970 UTC */ +WK_EXPORT WKStringRef WKKeyValueStorageManagerGetModificationTimeKey(); + typedef void (*WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction)(WKArrayRef, WKErrorRef, void*); WK_EXPORT void WKKeyValueStorageManagerGetKeyValueStorageOrigins(WKKeyValueStorageManagerRef keyValueStorageManager, void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction function); +typedef void (*WKKeyValueStorageManagerGetStorageDetailsByOriginFunction)(WKArrayRef, WKErrorRef, void*); +WK_EXPORT void WKKeyValueStorageManagerGetStorageDetailsByOrigin(WKKeyValueStorageManagerRef keyValueStorageManager, void* context, WKKeyValueStorageManagerGetStorageDetailsByOriginFunction function); + WK_EXPORT void WKKeyValueStorageManagerDeleteEntriesForOrigin(WKKeyValueStorageManagerRef keyValueStorageManager, WKSecurityOriginRef origin); WK_EXPORT void WKKeyValueStorageManagerDeleteAllEntries(WKKeyValueStorageManagerRef keyValueStorageManager); diff --git a/Source/WebKit2/UIProcess/API/C/WKLayoutMode.h b/Source/WebKit2/UIProcess/API/C/WKLayoutMode.h new file mode 100644 index 000000000..bb75f17f9 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKLayoutMode.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2015 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 WKLayoutMode_h +#define WKLayoutMode_h + +#include <stdint.h> + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + kWKLayoutModeViewSize = 0, + kWKLayoutModeFixedSize = 1, + kWKLayoutModeDynamicSizeComputedFromViewScale = 2, + kWKLayoutModeDynamicSizeComputedFromMinimumDocumentSize = 4 +}; +typedef uint32_t WKLayoutMode; + +#ifdef __cplusplus +} +#endif + +#endif /* WKLayoutMode_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.h b/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.h deleted file mode 100644 index eee1b9291..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WKMediaCacheManager_h -#define WKMediaCacheManager_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -WK_EXPORT WKTypeID WKMediaCacheManagerGetTypeID(); - -typedef void (*WKMediaCacheManagerGetHostnamesWithMediaCacheFunction)(WKArrayRef, WKErrorRef, void*); -WK_EXPORT void WKMediaCacheManagerGetHostnamesWithMediaCache(WKMediaCacheManagerRef mediaCacheManager, void* context, WKMediaCacheManagerGetHostnamesWithMediaCacheFunction function); - -WK_EXPORT void WKMediaCacheManagerClearCacheForHostname(WKMediaCacheManagerRef mediaCacheManager, WKStringRef hostname); -WK_EXPORT void WKMediaCacheManagerClearCacheForAllHostnames(WKMediaCacheManagerRef mediaCacheManager); - -#ifdef __cplusplus -} -#endif - -#endif // WKMediaCacheManager_h diff --git a/Source/WebKit2/UIProcess/API/C/WKMediaSessionFocusManager.cpp b/Source/WebKit2/UIProcess/API/C/WKMediaSessionFocusManager.cpp new file mode 100644 index 000000000..9603bf072 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKMediaSessionFocusManager.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2015 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 "WKMediaSessionFocusManager.h" + +#include "WKAPICast.h" +#include "WebMediaSessionFocusManager.h" + +using namespace WebKit; + +WKTypeID WKMediaSessionFocusManagerGetTypeID() +{ +#if ENABLE(MEDIA_SESSION) + return toAPI(WebMediaSessionFocusManager::APIType); +#else + return toAPI(API::Object::Type::Null); +#endif +} + +void WKMediaSessionFocusManagerSetClient(WKMediaSessionFocusManagerRef manager, const WKMediaSessionFocusManagerClientBase* client) +{ +#if ENABLE(MEDIA_SESSION) + toImpl(manager)->initializeClient(client); +#else + UNUSED_PARAM(manager); + UNUSED_PARAM(client); +#endif +} + +bool WKMediaSessionFocusManagerValueForPlaybackAttribute(WKMediaSessionFocusManagerRef manager, WKMediaSessionFocusManagerPlaybackAttribute attribute) +{ +#if ENABLE(MEDIA_SESSION) + return toImpl(manager)->valueForPlaybackAttribute(attribute); +#else + UNUSED_PARAM(manager); + UNUSED_PARAM(attribute); + return false; +#endif +} + +void WKMediaSessionFocusManagerSetVolumeOfFocusedMediaElement(WKMediaSessionFocusManagerRef manager, double volume) +{ +#if ENABLE(MEDIA_SESSION) + toImpl(manager)->setVolumeOfFocusedMediaElement(volume); +#else + UNUSED_PARAM(manager); + UNUSED_PARAM(volume); +#endif +} diff --git a/Source/WebKit2/UIProcess/API/C/WKMediaSessionFocusManager.h b/Source/WebKit2/UIProcess/API/C/WKMediaSessionFocusManager.h new file mode 100644 index 000000000..ed39e705a --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKMediaSessionFocusManager.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2015 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 WKMediaSessionFocusManager_h +#define WKMediaSessionFocusManager_h + +#include <WebKit/WKBase.h> + +#ifndef __cplusplus +#include <stdbool.h> +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +enum WKMediaSessionFocusManagerPlaybackAttribute { + IsPlaying = 1 << 0, + IsPreviousTrackControlEnabled = 1 << 1, + IsNextTrackControlEnabled = 1 << 2, +}; +typedef uint32_t WKMediaSessionFocusManagerPlaybackAttributes; + +// Media Session Focus Manager Client +typedef void (*WKMediaSessionFocusManagerDidChangePlaybackAttribute)(WKMediaSessionFocusManagerRef manager, WKMediaSessionFocusManagerPlaybackAttribute playbackAttribute, bool value, const void *clientInfo); + +typedef struct WKMediaSessionFocusManagerClientBase { + int version; + const void * clientInfo; +} WKMediaSessionFocusManagerClientBase; + +typedef struct WKMediaSessionFocusManagerClientV0 { + WKMediaSessionFocusManagerClientBase base; + + // Version 0. + WKMediaSessionFocusManagerDidChangePlaybackAttribute didChangePlaybackAttribute; +} WKMediaSessionFocusManagerClientV0; + +WK_EXPORT WKTypeID WKMediaSessionFocusManagerGetTypeID(); + +WK_EXPORT void WKMediaSessionFocusManagerSetClient(WKMediaSessionFocusManagerRef manager, const WKMediaSessionFocusManagerClientBase* client); + +WK_EXPORT bool WKMediaSessionFocusManagerValueForPlaybackAttribute(WKMediaSessionFocusManagerRef, WKMediaSessionFocusManagerPlaybackAttribute); +WK_EXPORT void WKMediaSessionFocusManagerSetVolumeOfFocusedMediaElement(WKMediaSessionFocusManagerRef, double); + +#ifdef __cplusplus +} +#endif + +#endif /* WKMediaSessionFocusManager_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKMediaSessionMetadata.cpp b/Source/WebKit2/UIProcess/API/C/WKMediaSessionMetadata.cpp new file mode 100644 index 000000000..330ca53aa --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKMediaSessionMetadata.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2015 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 "WKMediaSessionMetadata.h" + +#include "WKAPICast.h" +#include "WebMediaSessionMetadata.h" + +using namespace WebKit; + +WKTypeID WKMediaSessionMetadataGetTypeID() +{ +#if ENABLE(MEDIA_SESSION) + return toAPI(WebMediaSessionMetadata::APIType); +#else + return toAPI(API::Object::Type::Null); +#endif +} + +WKStringRef WKMediaSessionMetadataCopyTitle(WKMediaSessionMetadataRef metadata) +{ +#if ENABLE(MEDIA_SESSION) + return toCopiedAPI(toImpl(metadata)->title()); +#else + UNUSED_PARAM(metadata); + return nullptr; +#endif +} + +WKStringRef WKMediaSessionMetadataCopyArtist(WKMediaSessionMetadataRef metadata) +{ +#if ENABLE(MEDIA_SESSION) + return toCopiedAPI(toImpl(metadata)->artist()); +#else + UNUSED_PARAM(metadata); + return nullptr; +#endif +} + +WKStringRef WKMediaSessionMetadataCopyAlbum(WKMediaSessionMetadataRef metadata) +{ +#if ENABLE(MEDIA_SESSION) + return toCopiedAPI(toImpl(metadata)->album()); +#else + UNUSED_PARAM(metadata); + return nullptr; +#endif +} + +WKURLRef WKMediaSessionMetadataCopyArtworkURL(WKMediaSessionMetadataRef metadata) +{ +#if ENABLE(MEDIA_SESSION) + return toCopiedURLAPI(toImpl(metadata)->artworkURL()); +#else + UNUSED_PARAM(metadata); + return nullptr; +#endif +} diff --git a/Source/WebKit2/UIProcess/API/C/WKMediaSessionMetadata.h b/Source/WebKit2/UIProcess/API/C/WKMediaSessionMetadata.h new file mode 100644 index 000000000..b9430f7e4 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKMediaSessionMetadata.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2015 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 WKMediaSessionMetadata_h +#define WKMediaSessionMetadata_h + +#include <WebKit/WKBase.h> + +#ifndef __cplusplus +#include <stdbool.h> +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT WKTypeID WKMediaSessionMetadataGetTypeID(); + +WK_EXPORT WKStringRef WKMediaSessionMetadataCopyTitle(WKMediaSessionMetadataRef metadata); +WK_EXPORT WKStringRef WKMediaSessionMetadataCopyArtist(WKMediaSessionMetadataRef metadata); +WK_EXPORT WKStringRef WKMediaSessionMetadataCopyAlbum(WKMediaSessionMetadataRef metadata); +WK_EXPORT WKURLRef WKMediaSessionMetadataCopyArtworkURL(WKMediaSessionMetadataRef metadata); + +#ifdef __cplusplus +} +#endif + +#endif /* WKMediaSessionMetadata_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKNativeEvent.h b/Source/WebKit2/UIProcess/API/C/WKNativeEvent.h index f0d39fb5a..10bed36ea 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNativeEvent.h +++ b/Source/WebKit2/UIProcess/API/C/WKNativeEvent.h @@ -26,11 +26,15 @@ #ifndef WKNativeEvent_h #define WKNativeEvent_h +#ifdef __APPLE__ +#include <TargetConditionals.h> +#endif + #ifdef __cplusplus extern "C" { #endif -#ifdef __APPLE__ +#if defined(__APPLE__) && !TARGET_OS_IPHONE && !defined(BUILDING_GTK__) #ifdef __OBJC__ @class NSEvent; #elif __cplusplus diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKInspectorClientGtk.cpp b/Source/WebKit2/UIProcess/API/C/WKNavigationActionRef.cpp index c9d777c4d..14a235157 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKInspectorClientGtk.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationActionRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,14 +24,14 @@ */ #include "config.h" -#include "WKInspectorClientGtk.h" +#include "WKNavigationActionRef.h" +#include "APINavigationAction.h" #include "WKAPICast.h" -#include "WebInspectorProxy.h" using namespace WebKit; -void WKInspectorSetInspectorClientGtk(WKInspectorRef inspectorRef, const WKInspectorClientGtk* wkClient) +WKTypeID WKNavigationActionGetTypeID() { - toImpl(inspectorRef)->initializeInspectorClientGtk(wkClient); + return toAPI(API::NavigationAction::APIType); } diff --git a/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.h b/Source/WebKit2/UIProcess/API/C/WKNavigationActionRef.h index ea6231148..5691eabcd 100644 --- a/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.h +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationActionRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2015 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,16 +23,19 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include <WebKit2/WKBase.h> +#ifndef WKNavigationActionRef_h +#define WKNavigationActionRef_h -typedef struct _cairo_surface cairo_surface_t; +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT cairo_surface_t* WKIconDatabaseTryGetCairoSurfaceForURL(WKIconDatabaseRef iconDatabase, WKURLRef url); +WK_EXPORT WKTypeID WKNavigationActionGetTypeID(); #ifdef __cplusplus } #endif + +#endif // WKNavigationActionRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WKNavigationData.cpp b/Source/WebKit2/UIProcess/API/C/WKNavigationDataRef.cpp index e0100bed8..0a815bb82 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNavigationData.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationDataRef.cpp @@ -24,17 +24,17 @@ */ #include "config.h" -#include "WKNavigationData.h" +#include "WKNavigationDataRef.h" +#include "APINavigationData.h" +#include "APIURLRequest.h" #include "WKAPICast.h" -#include "WebNavigationData.h" -#include "WebURLRequest.h" using namespace WebKit; WKTypeID WKNavigationDataGetTypeID() { - return toAPI(WebNavigationData::APIType); + return toAPI(API::NavigationData::APIType); } WKStringRef WKNavigationDataCopyTitle(WKNavigationDataRef navigationDataRef) @@ -55,5 +55,5 @@ WKURLRef WKNavigationDataCopyNavigationDestinationURL(WKNavigationDataRef naviga WKURLRequestRef WKNavigationDataCopyOriginalRequest(WKNavigationDataRef navigationData) { - return toAPI(WebURLRequest::create(toImpl(navigationData)->originalRequest()).leakRef()); + return toAPI(&API::URLRequest::create(toImpl(navigationData)->originalRequest()).leakRef()); } diff --git a/Source/WebKit2/UIProcess/API/C/WKNavigationData.h b/Source/WebKit2/UIProcess/API/C/WKNavigationDataRef.h index e5d3a15f8..b2c5f5b2b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNavigationData.h +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationDataRef.h @@ -23,10 +23,10 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKNavigationData_h -#define WKNavigationData_h +#ifndef WKNavigationDataRef_h +#define WKNavigationDataRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -45,4 +45,4 @@ WK_EXPORT WKURLRef WKNavigationDataCopyURL(WKNavigationDataRef navigationData); } #endif -#endif /* WKNavigationData_h */ +#endif /* WKNavigationDataRef_h */ diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroupPrivate.h b/Source/WebKit2/UIProcess/API/C/WKNavigationRef.cpp index d4f0fc416..591c14660 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroupPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,10 +23,15 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#import <WebKit2/WKBrowsingContextGroup.h> +#include "config.h" +#include "WKNavigationRef.h" -@interface WKBrowsingContextGroup (Private) +#include "APINavigation.h" +#include "WKAPICast.h" -@property(readonly) WKPageGroupRef _pageGroupRef; +using namespace WebKit; -@end +WKTypeID WKNavigationGetTypeID() +{ + return toAPI(API::Navigation::APIType); +} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/InjectedBundle/injected_bundle_sample.cpp b/Source/WebKit2/UIProcess/API/C/WKNavigationRef.h index 55f0f190c..ae9a19074 100644 --- a/Source/WebKit2/UIProcess/API/efl/tests/InjectedBundle/injected_bundle_sample.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2015 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,16 +23,19 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include <WebKit2/WKBundleInitialize.h> +#ifndef WKNavigationRef_h +#define WKNavigationRef_h + +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -void WKBundleInitialize(WKBundleRef bundle, WKTypeRef initializationUserData) -{ -} +WK_EXPORT WKTypeID WKNavigationGetTypeID(); #ifdef __cplusplus } #endif + +#endif // WKNavigationRef_h diff --git a/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.cpp b/Source/WebKit2/UIProcess/API/C/WKNavigationResponseRef.cpp index 118c4d8cb..ed6f21b0f 100644 --- a/Source/WebKit2/UIProcess/API/C/cairo/WKIconDatabaseCairo.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationResponseRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,15 +24,19 @@ */ #include "config.h" -#include "WKIconDatabaseCairo.h" +#include "WKNavigationResponseRef.h" +#include "APINavigationResponse.h" #include "WKAPICast.h" -#include "WebIconDatabase.h" -using namespace WebCore; using namespace WebKit; -cairo_surface_t* WKIconDatabaseTryGetCairoSurfaceForURL(WKIconDatabaseRef iconDatabase, WKURLRef url) +WKTypeID WKNavigationResponseGetTypeID() { - return toImpl(iconDatabase)->nativeImageForPageURL(toWTFString(url)).get(); + return toAPI(API::NavigationResponse::APIType); +} + +bool WKNavigationResponseCanShowMIMEType(WKNavigationResponseRef response) +{ + return toImpl(response)->canShowMIMEType(); } diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.h b/Source/WebKit2/UIProcess/API/C/WKNavigationResponseRef.h index 8357ba56a..c82b14dc3 100644 --- a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.h +++ b/Source/WebKit2/UIProcess/API/C/WKNavigationResponseRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,20 +23,21 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKPagePrivateMac_h -#define WKPagePrivateMac_h +#ifndef WKNavigationResponseRef_h +#define WKNavigationResponseRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT pid_t WKPageGetProcessIdentifier(WKPageRef page); -WK_EXPORT bool WKPageIsURLKnownHSTSHost(WKPageRef page, WKURLRef url); +WK_EXPORT WKTypeID WKNavigationResponseGetTypeID(); + +WK_EXPORT bool WKNavigationResponseCanShowMIMEType(WKNavigationResponseRef); #ifdef __cplusplus } #endif -#endif /* WKPagePrivateMac_h */ +#endif // WKNavigationResponseRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WKNetworkInfoManager.h b/Source/WebKit2/UIProcess/API/C/WKNetworkInfoManager.h deleted file mode 100644 index dd92eb868..000000000 --- a/Source/WebKit2/UIProcess/API/C/WKNetworkInfoManager.h +++ /dev/null @@ -1,63 +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 WKNetworkInfoManager_h -#define WKNetworkInfoManager_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -// Provider. -typedef void (*WKNetworkInfoProviderStartUpdatingCallback)(WKNetworkInfoManagerRef networkInfoManager, const void* clientInfo); -typedef void (*WKNetworkInfoProviderStopUpdatingCallback)(WKNetworkInfoManagerRef networkInfoManager, const void* clientInfo); -typedef double (*WKNetworkInfoProviderGetBandwidthCallback)(WKNetworkInfoManagerRef networkInfoManager, const void* clientInfo); -typedef bool (*WKNetworkInfoProviderIsMeteredCallback)(WKNetworkInfoManagerRef networkInfoManager, const void* clientInfo); - -struct WKNetworkInfoProvider { - int version; - const void * clientInfo; - WKNetworkInfoProviderStartUpdatingCallback startUpdating; - WKNetworkInfoProviderStopUpdatingCallback stopUpdating; - WKNetworkInfoProviderGetBandwidthCallback bandwidth; - WKNetworkInfoProviderIsMeteredCallback isMetered; -}; -typedef struct WKNetworkInfoProvider WKNetworkInfoProvider; - -enum { kWKNetworkInfoProviderCurrentVersion = 0 }; - -WK_EXPORT WKTypeID WKNetworkInfoManagerGetTypeID(); - -WK_EXPORT void WKNetworkInfoManagerSetProvider(WKNetworkInfoManagerRef networkInfoManager, const WKNetworkInfoProvider* provider); - -WK_EXPORT void WKNetworkInfoManagerProviderDidChangeNetworkInformation(WKNetworkInfoManagerRef networkInfoManager, WKStringRef eventType, WKNetworkInfoRef networkInfo); - -#ifdef __cplusplus -} -#endif - -#endif // WKNetworkInfoManager_h diff --git a/Source/WebKit2/UIProcess/API/C/WKNotification.cpp b/Source/WebKit2/UIProcess/API/C/WKNotification.cpp index 78b09e09e..3d1805730 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNotification.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNotification.cpp @@ -26,9 +26,9 @@ #include "config.h" #include "WKNotification.h" +#include "APISecurityOrigin.h" #include "WKAPICast.h" #include "WebNotification.h" -#include "WebSecurityOrigin.h" using namespace WebKit; diff --git a/Source/WebKit2/UIProcess/API/C/WKNotification.h b/Source/WebKit2/UIProcess/API/C/WKNotification.h index 7035ef3f8..d3ae98bf7 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNotification.h +++ b/Source/WebKit2/UIProcess/API/C/WKNotification.h @@ -26,7 +26,7 @@ #ifndef WKNotification_h #define WKNotification_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKNotificationManager.cpp b/Source/WebKit2/UIProcess/API/C/WKNotificationManager.cpp index 60671a7e1..1e050a6e6 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNotificationManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKNotificationManager.cpp @@ -36,7 +36,7 @@ WKTypeID WKNotificationManagerGetTypeID() return toAPI(WebNotificationManagerProxy::APIType); } -void WKNotificationManagerSetProvider(WKNotificationManagerRef managerRef, const WKNotificationProvider* wkProvider) +void WKNotificationManagerSetProvider(WKNotificationManagerRef managerRef, const WKNotificationProviderBase* wkProvider) { toImpl(managerRef)->initializeProvider(wkProvider); } diff --git a/Source/WebKit2/UIProcess/API/C/WKNotificationManager.h b/Source/WebKit2/UIProcess/API/C/WKNotificationManager.h index 7074a2186..cb88036bc 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNotificationManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKNotificationManager.h @@ -27,14 +27,14 @@ #define WKNotificationManager_h #include "WKNotificationProvider.h" -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif WK_EXPORT WKTypeID WKNotificationManagerGetTypeID(); -WK_EXPORT void WKNotificationManagerSetProvider(WKNotificationManagerRef managerRef, const WKNotificationProvider* wkProvider); +WK_EXPORT void WKNotificationManagerSetProvider(WKNotificationManagerRef managerRef, const WKNotificationProviderBase* wkProvider); WK_EXPORT void WKNotificationManagerProviderDidShowNotification(WKNotificationManagerRef managerRef, uint64_t notificationID); WK_EXPORT void WKNotificationManagerProviderDidClickNotification(WKNotificationManagerRef managerRef, uint64_t notificationID); diff --git a/Source/WebKit2/UIProcess/API/C/WKNotificationPermissionRequest.h b/Source/WebKit2/UIProcess/API/C/WKNotificationPermissionRequest.h index 1947a06aa..02be0e63c 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNotificationPermissionRequest.h +++ b/Source/WebKit2/UIProcess/API/C/WKNotificationPermissionRequest.h @@ -26,7 +26,7 @@ #ifndef WKNotificationPermissionRequest_h #define WKNotificationPermissionRequest_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKNotificationProvider.h b/Source/WebKit2/UIProcess/API/C/WKNotificationProvider.h index bc99ec9b0..8a416c57c 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNotificationProvider.h +++ b/Source/WebKit2/UIProcess/API/C/WKNotificationProvider.h @@ -26,7 +26,7 @@ #ifndef WKNotificationProvider_h #define WKNotificationProvider_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -40,9 +40,15 @@ typedef void (*WKNotificationProviderRemoveNotificationManagerCallback)(WKNotifi typedef WKDictionaryRef (*WKNotificationProviderNotificationPermissionsCallback)(const void* clientInfo); typedef void (*WKNotificationProviderClearNotificationsCallback)(WKArrayRef notificationIDs, const void* clientInfo); -struct WKNotificationProvider { +typedef struct WKNotificationProviderBase { int version; const void* clientInfo; +} WKNotificationProviderBase; + +typedef struct WKNotificationProviderV0 { + WKNotificationProviderBase base; + + // Version 0. WKNotificationProviderShowCallback show; WKNotificationProviderCancelCallback cancel; WKNotificationProviderDidDestroyNotificationCallback didDestroyNotification; @@ -50,10 +56,7 @@ struct WKNotificationProvider { WKNotificationProviderRemoveNotificationManagerCallback removeNotificationManager; WKNotificationProviderNotificationPermissionsCallback notificationPermissions; WKNotificationProviderClearNotificationsCallback clearNotifications; -}; -typedef struct WKNotificationProvider WKNotificationProvider; - -enum { kWKNotificationProviderCurrentVersion = 0 }; +} WKNotificationProviderV0; #ifdef __cplusplus } diff --git a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp index 29ecf543b..8370a6ffd 100644 --- a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.cpp @@ -27,7 +27,7 @@ #include "config.h" #include "WKOpenPanelParameters.h" -#include "ImmutableArray.h" +#include "APIArray.h" #include "WKAPICast.h" #include "WebOpenPanelParameters.h" @@ -45,19 +45,26 @@ bool WKOpenPanelParametersGetAllowsMultipleFiles(WKOpenPanelParametersRef parame WKArrayRef WKOpenPanelParametersCopyAcceptedMIMETypes(WKOpenPanelParametersRef parametersRef) { - return toAPI(toImpl(parametersRef)->acceptMIMETypes().leakRef()); + return toAPI(&toImpl(parametersRef)->acceptMIMETypes().leakRef()); } -WKStringRef WKOpenPanelParametersCopyCapture(WKOpenPanelParametersRef parametersRef) +// Deprecated. +WKStringRef WKOpenPanelParametersCopyCapture(WKOpenPanelParametersRef) +{ + return 0; +} + +bool WKOpenPanelParametersGetCaptureEnabled(WKOpenPanelParametersRef parametersRef) { #if ENABLE(MEDIA_CAPTURE) - return toCopiedAPI(toImpl(parametersRef)->capture()); + return toImpl(parametersRef)->capture(); #else - return 0; + UNUSED_PARAM(parametersRef); + return false; #endif } WKArrayRef WKOpenPanelParametersCopySelectedFileNames(WKOpenPanelParametersRef parametersRef) { - return toAPI(toImpl(parametersRef)->selectedFileNames().leakRef()); + 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 3801c2f7b..803bff8b4 100644 --- a/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.h +++ b/Source/WebKit2/UIProcess/API/C/WKOpenPanelParameters.h @@ -27,7 +27,7 @@ #ifndef WKOpenPanelParameters_h #define WKOpenPanelParameters_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifndef __cplusplus #include <stdbool.h> @@ -43,8 +43,11 @@ WK_EXPORT bool WKOpenPanelParametersGetAllowsMultipleFiles(WKOpenPanelParameters WK_EXPORT WKArrayRef WKOpenPanelParametersCopyAcceptedMIMETypes(WKOpenPanelParametersRef parameters); +/* DEPRECATED - Please use WKOpenPanelParametersGetCaptureEnabled() instead. */ WK_EXPORT WKStringRef WKOpenPanelParametersCopyCapture(WKOpenPanelParametersRef parameters); +WK_EXPORT bool WKOpenPanelParametersGetCaptureEnabled(WKOpenPanelParametersRef parametersRef); + WK_EXPORT WKArrayRef WKOpenPanelParametersCopySelectedFileNames(WKOpenPanelParametersRef parametersRef); #ifdef __cplusplus diff --git a/Source/WebKit2/UIProcess/API/C/WKOpenPanelResultListener.h b/Source/WebKit2/UIProcess/API/C/WKOpenPanelResultListener.h index d581738a5..21c92ee24 100644 --- a/Source/WebKit2/UIProcess/API/C/WKOpenPanelResultListener.h +++ b/Source/WebKit2/UIProcess/API/C/WKOpenPanelResultListener.h @@ -26,7 +26,7 @@ #ifndef WKOpenPanelResultListener_h #define WKOpenPanelResultListener_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKPage.cpp b/Source/WebKit2/UIProcess/API/C/WKPage.cpp index 2d9ae5e51..701a4c83b 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPage.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPage.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,14 +27,51 @@ #include "WKPage.h" #include "WKPagePrivate.h" +#include "APIArray.h" +#include "APIContextMenuClient.h" +#include "APIData.h" +#include "APIDictionary.h" +#include "APIFindClient.h" +#include "APIFindMatchesClient.h" +#include "APIFrameInfo.h" +#include "APIGeometry.h" +#include "APIHitTestResult.h" +#include "APILoaderClient.h" +#include "APINavigationAction.h" +#include "APINavigationClient.h" +#include "APINavigationResponse.h" +#include "APIPageConfiguration.h" +#include "APIPolicyClient.h" +#include "APISessionState.h" +#include "APIUIClient.h" +#include "APIWindowFeatures.h" +#include "AuthenticationChallengeProxy.h" +#include "LegacySessionStateCoding.h" +#include "Logging.h" +#include "NativeWebKeyboardEvent.h" +#include "NativeWebWheelEvent.h" +#include "NavigationActionData.h" +#include "PluginInformation.h" #include "PrintInfo.h" #include "WKAPICast.h" +#include "WKPagePolicyClientInternal.h" +#include "WKPageRenderingProgressEventsInternal.h" #include "WKPluginInformation.h" #include "WebBackForwardList.h" -#include "WebData.h" +#include "WebFormClient.h" +#include "WebImage.h" +#include "WebInspectorProxy.h" +#include "WebOpenPanelParameters.h" +#include "WebOpenPanelResultListenerProxy.h" +#include "WebPageGroup.h" +#include "WebPageMessages.h" #include "WebPageProxy.h" +#include "WebProcessPool.h" #include "WebProcessProxy.h" +#include "WebProtectionSpace.h" #include <WebCore/Page.h> +#include <WebCore/SecurityOriginData.h> +#include <WebCore/WindowFeatures.h> #ifdef __BLOCKS__ #include <Block.h> @@ -44,9 +81,51 @@ #include "WebContextMenuItem.h" #endif +#if ENABLE(VIBRATION) +#include "WebVibrationProxy.h" +#endif + +#if ENABLE(MEDIA_SESSION) +#include "WebMediaSessionMetadata.h" +#include <WebCore/MediaSessionEvents.h> +#endif + using namespace WebCore; using namespace WebKit; +namespace API { +template<> struct ClientTraits<WKPageLoaderClientBase> { + typedef std::tuple<WKPageLoaderClientV0, WKPageLoaderClientV1, WKPageLoaderClientV2, WKPageLoaderClientV3, WKPageLoaderClientV4, WKPageLoaderClientV5, WKPageLoaderClientV6> Versions; +}; + +template<> struct ClientTraits<WKPageNavigationClientBase> { + typedef std::tuple<WKPageNavigationClientV0> Versions; +}; + +template<> struct ClientTraits<WKPagePolicyClientBase> { + typedef std::tuple<WKPagePolicyClientV0, WKPagePolicyClientV1, WKPagePolicyClientInternal> Versions; +}; + +template<> struct ClientTraits<WKPageUIClientBase> { + typedef std::tuple<WKPageUIClientV0, WKPageUIClientV1, WKPageUIClientV2, WKPageUIClientV3, WKPageUIClientV4, WKPageUIClientV5, WKPageUIClientV6, WKPageUIClientV7> Versions; +}; + +#if ENABLE(CONTEXT_MENUS) +template<> struct ClientTraits<WKPageContextMenuClientBase> { + typedef std::tuple<WKPageContextMenuClientV0, WKPageContextMenuClientV1, WKPageContextMenuClientV2, WKPageContextMenuClientV3> Versions; +}; +#endif + +template<> struct ClientTraits<WKPageFindClientBase> { + typedef std::tuple<WKPageFindClientV0> Versions; +}; + +template<> struct ClientTraits<WKPageFindMatchesClientBase> { + typedef std::tuple<WKPageFindMatchesClientV0> Versions; +}; + +} + WKTypeID WKPageGetTypeID() { return toAPI(WebPageProxy::APIType); @@ -54,32 +133,43 @@ WKTypeID WKPageGetTypeID() WKContextRef WKPageGetContext(WKPageRef pageRef) { - return toAPI(toImpl(pageRef)->process()->context()); + return toAPI(&toImpl(pageRef)->process().processPool()); } WKPageGroupRef WKPageGetPageGroup(WKPageRef pageRef) { - return toAPI(toImpl(pageRef)->pageGroup()); + return toAPI(&toImpl(pageRef)->pageGroup()); +} + +WKPageConfigurationRef WKPageCopyPageConfiguration(WKPageRef pageRef) +{ + return toAPI(&toImpl(pageRef)->configuration().copy().leakRef()); } void WKPageLoadURL(WKPageRef pageRef, WKURLRef URLRef) { - toImpl(pageRef)->loadURL(toWTFString(URLRef)); + toImpl(pageRef)->loadRequest(URL(URL(), toWTFString(URLRef))); +} + +void WKPageLoadURLWithShouldOpenExternalURLsPolicy(WKPageRef pageRef, WKURLRef URLRef, bool shouldOpenExternalURLs) +{ + ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = shouldOpenExternalURLs ? ShouldOpenExternalURLsPolicy::ShouldAllow : ShouldOpenExternalURLsPolicy::ShouldNotAllow; + toImpl(pageRef)->loadRequest(URL(URL(), toWTFString(URLRef)), shouldOpenExternalURLsPolicy); } void WKPageLoadURLWithUserData(WKPageRef pageRef, WKURLRef URLRef, WKTypeRef userDataRef) { - toImpl(pageRef)->loadURL(toWTFString(URLRef), toImpl(userDataRef)); + toImpl(pageRef)->loadRequest(URL(URL(), toWTFString(URLRef)), ShouldOpenExternalURLsPolicy::ShouldNotAllow, toImpl(userDataRef)); } void WKPageLoadURLRequest(WKPageRef pageRef, WKURLRequestRef urlRequestRef) { - toImpl(pageRef)->loadURLRequest(toImpl(urlRequestRef)); + toImpl(pageRef)->loadRequest(toImpl(urlRequestRef)->resourceRequest()); } void WKPageLoadURLRequestWithUserData(WKPageRef pageRef, WKURLRequestRef urlRequestRef, WKTypeRef userDataRef) { - toImpl(pageRef)->loadURLRequest(toImpl(urlRequestRef), toImpl(userDataRef)); + toImpl(pageRef)->loadRequest(toImpl(urlRequestRef)->resourceRequest(), ShouldOpenExternalURLsPolicy::ShouldNotAllow, toImpl(userDataRef)); } void WKPageLoadFile(WKPageRef pageRef, WKURLRef fileURL, WKURLRef resourceDirectoryURL) @@ -149,12 +239,23 @@ void WKPageStopLoading(WKPageRef pageRef) void WKPageReload(WKPageRef pageRef) { - toImpl(pageRef)->reload(false); + const bool reloadFromOrigin = false; + const bool contentBlockersEnabled = true; + toImpl(pageRef)->reload(reloadFromOrigin, contentBlockersEnabled); +} + +void WKPageReloadWithoutContentBlockers(WKPageRef pageRef) +{ + const bool reloadFromOrigin = false; + const bool contentBlockersEnabled = false; + toImpl(pageRef)->reload(reloadFromOrigin, contentBlockersEnabled); } void WKPageReloadFromOrigin(WKPageRef pageRef) { - toImpl(pageRef)->reload(true); + const bool reloadFromOrigin = true; + const bool contentBlockersEnabled = true; + toImpl(pageRef)->reload(reloadFromOrigin, contentBlockersEnabled); } bool WKPageTryClose(WKPageRef pageRef) @@ -179,7 +280,7 @@ void WKPageGoForward(WKPageRef pageRef) bool WKPageCanGoForward(WKPageRef pageRef) { - return toImpl(pageRef)->canGoForward(); + return toImpl(pageRef)->backForwardList().forwardItem(); } void WKPageGoBack(WKPageRef pageRef) @@ -189,7 +290,7 @@ void WKPageGoBack(WKPageRef pageRef) bool WKPageCanGoBack(WKPageRef pageRef) { - return toImpl(pageRef)->canGoBack(); + return toImpl(pageRef)->backForwardList().backItem(); } void WKPageGoToBackForwardListItem(WKPageRef pageRef, WKBackForwardListItemRef itemRef) @@ -204,7 +305,7 @@ void WKPageTryRestoreScrollPosition(WKPageRef pageRef) WKBackForwardListRef WKPageGetBackForwardList(WKPageRef pageRef) { - return toAPI(toImpl(pageRef)->backForwardList()); + return toAPI(&toImpl(pageRef)->backForwardList()); } bool WKPageWillHandleHorizontalScrollEvents(WKPageRef pageRef) @@ -214,7 +315,7 @@ bool WKPageWillHandleHorizontalScrollEvents(WKPageRef pageRef) WKStringRef WKPageCopyTitle(WKPageRef pageRef) { - return toCopiedAPI(toImpl(pageRef)->pageTitle()); + return toCopiedAPI(toImpl(pageRef)->pageLoadState().title()); } WKFrameRef WKPageGetMainFrame(WKPageRef pageRef) @@ -239,12 +340,7 @@ uint64_t WKPageGetRenderTreeSize(WKPageRef page) WKInspectorRef WKPageGetInspector(WKPageRef pageRef) { -#if defined(ENABLE_INSPECTOR) && ENABLE_INSPECTOR return toAPI(toImpl(pageRef)->inspector()); -#else - UNUSED_PARAM(pageRef); - return 0; -#endif } WKVibrationRef WKPageGetVibration(WKPageRef page) @@ -262,11 +358,6 @@ double WKPageGetEstimatedProgress(WKPageRef pageRef) return toImpl(pageRef)->estimatedProgress(); } -void WKPageSetMemoryCacheClientCallsEnabled(WKPageRef pageRef, bool memoryCacheClientCallsEnabled) -{ - toImpl(pageRef)->setMemoryCacheClientCallsEnabled(memoryCacheClientCallsEnabled); -} - WKStringRef WKPageCopyUserAgent(WKPageRef pageRef) { return toCopiedAPI(toImpl(pageRef)->userAgent()); @@ -292,6 +383,11 @@ void WKPageSetCustomUserAgent(WKPageRef pageRef, WKStringRef userAgentRef) toImpl(pageRef)->setCustomUserAgent(toWTFString(userAgentRef)); } +void WKPageSetUserContentExtensionsEnabled(WKPageRef pageRef, bool enabled) +{ + // FIXME: Remove this function once it is no longer used. +} + bool WKPageSupportsTextEncoding(WKPageRef pageRef) { return toImpl(pageRef)->supportsTextEncoding(); @@ -314,24 +410,55 @@ void WKPageTerminate(WKPageRef pageRef) WKStringRef WKPageGetSessionHistoryURLValueType() { - static WebString* sessionHistoryURLValueType = WebString::create("SessionHistoryURL").leakRef(); - return toAPI(sessionHistoryURLValueType); + static API::String& sessionHistoryURLValueType = API::String::create("SessionHistoryURL").leakRef(); + return toAPI(&sessionHistoryURLValueType); } WKStringRef WKPageGetSessionBackForwardListItemValueType() { - static WebString* sessionBackForwardListValueType = WebString::create("SessionBackForwardListItem").leakRef(); - return toAPI(sessionBackForwardListValueType); + static API::String& sessionBackForwardListValueType = API::String::create("SessionBackForwardListItem").leakRef(); + return toAPI(&sessionBackForwardListValueType); } -WKDataRef WKPageCopySessionState(WKPageRef pageRef, void *context, WKPageSessionStateFilterCallback filter) +WKTypeRef WKPageCopySessionState(WKPageRef pageRef, void* context, WKPageSessionStateFilterCallback filter) { - return toAPI(toImpl(pageRef)->sessionStateData(filter, context).leakRef()); + // FIXME: This is a hack to make sure we return a WKDataRef to maintain compatibility with older versions of Safari. + bool shouldReturnData = !(reinterpret_cast<uintptr_t>(context) & 1); + context = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(context) & ~1); + + auto sessionState = toImpl(pageRef)->sessionState([pageRef, context, filter](WebBackForwardListItem& item) { + if (filter) { + if (!filter(pageRef, WKPageGetSessionBackForwardListItemValueType(), toAPI(&item), context)) + return false; + + if (!filter(pageRef, WKPageGetSessionHistoryURLValueType(), toURLRef(item.originalURL().impl()), context)) + return false; + } + + return true; + }); + + if (shouldReturnData) + return toAPI(encodeLegacySessionState(sessionState).release().leakRef()); + + return toAPI(&API::SessionState::create(WTFMove(sessionState)).leakRef()); } -void WKPageRestoreFromSessionState(WKPageRef pageRef, WKDataRef sessionStateData) +void WKPageRestoreFromSessionState(WKPageRef pageRef, WKTypeRef sessionStateRef) { - toImpl(pageRef)->restoreFromSessionStateData(toImpl(sessionStateData)); + SessionState sessionState; + + // FIXME: This is for backwards compatibility with Safari. Remove it once Safari no longer depends on it. + if (toImpl(sessionStateRef)->type() == API::Object::Type::Data) { + if (!decodeLegacySessionState(toImpl(static_cast<WKDataRef>(sessionStateRef))->bytes(), toImpl(static_cast<WKDataRef>(sessionStateRef))->size(), sessionState)) + return; + } else { + ASSERT(toImpl(sessionStateRef)->type() == API::Object::Type::SessionState); + + sessionState = toImpl(static_cast<WKSessionStateRef>(sessionStateRef))->sessionState(); + } + + toImpl(pageRef)->restoreFromSessionState(WTFMove(sessionState), true); } double WKPageGetTextZoomFactor(WKPageRef pageRef) @@ -409,11 +536,6 @@ void WKPageListenForLayoutMilestones(WKPageRef pageRef, WKLayoutMilestones miles toImpl(pageRef)->listenForLayoutMilestones(toLayoutMilestones(milestones)); } -void WKPageSetVisibilityState(WKPageRef pageRef, WKPageVisibilityState state, bool isInitialState) -{ - toImpl(pageRef)->setVisibilityState(toPageVisibilityState(state), isInitialState); -} - bool WKPageHasHorizontalScrollbar(WKPageRef pageRef) { return toImpl(pageRef)->hasHorizontalScrollbar(); @@ -454,15 +576,24 @@ bool WKPageIsPinnedToBottomSide(WKPageRef pageRef) return toImpl(pageRef)->isPinnedToBottomSide(); } +bool WKPageRubberBandsAtLeft(WKPageRef pageRef) +{ + return toImpl(pageRef)->rubberBandsAtLeft(); +} -bool WKPageRubberBandsAtBottom(WKPageRef pageRef) +void WKPageSetRubberBandsAtLeft(WKPageRef pageRef, bool rubberBandsAtLeft) { - return toImpl(pageRef)->rubberBandsAtBottom(); + toImpl(pageRef)->setRubberBandsAtLeft(rubberBandsAtLeft); } -void WKPageSetRubberBandsAtBottom(WKPageRef pageRef, bool rubberBandsAtBottom) +bool WKPageRubberBandsAtRight(WKPageRef pageRef) { - toImpl(pageRef)->setRubberBandsAtBottom(rubberBandsAtBottom); + return toImpl(pageRef)->rubberBandsAtRight(); +} + +void WKPageSetRubberBandsAtRight(WKPageRef pageRef, bool rubberBandsAtRight) +{ + toImpl(pageRef)->setRubberBandsAtRight(rubberBandsAtRight); } bool WKPageRubberBandsAtTop(WKPageRef pageRef) @@ -475,6 +606,46 @@ void WKPageSetRubberBandsAtTop(WKPageRef pageRef, bool rubberBandsAtTop) toImpl(pageRef)->setRubberBandsAtTop(rubberBandsAtTop); } +bool WKPageRubberBandsAtBottom(WKPageRef pageRef) +{ + return toImpl(pageRef)->rubberBandsAtBottom(); +} + +void WKPageSetRubberBandsAtBottom(WKPageRef pageRef, bool rubberBandsAtBottom) +{ + toImpl(pageRef)->setRubberBandsAtBottom(rubberBandsAtBottom); +} + +bool WKPageVerticalRubberBandingIsEnabled(WKPageRef pageRef) +{ + return toImpl(pageRef)->verticalRubberBandingIsEnabled(); +} + +void WKPageSetEnableVerticalRubberBanding(WKPageRef pageRef, bool enableVerticalRubberBanding) +{ + toImpl(pageRef)->setEnableVerticalRubberBanding(enableVerticalRubberBanding); +} + +bool WKPageHorizontalRubberBandingIsEnabled(WKPageRef pageRef) +{ + return toImpl(pageRef)->horizontalRubberBandingIsEnabled(); +} + +void WKPageSetEnableHorizontalRubberBanding(WKPageRef pageRef, bool enableHorizontalRubberBanding) +{ + toImpl(pageRef)->setEnableHorizontalRubberBanding(enableHorizontalRubberBanding); +} + +void WKPageSetBackgroundExtendsBeyondPage(WKPageRef pageRef, bool backgroundExtendsBeyondPage) +{ + toImpl(pageRef)->setBackgroundExtendsBeyondPage(backgroundExtendsBeyondPage); +} + +bool WKPageBackgroundExtendsBeyondPage(WKPageRef pageRef) +{ + return toImpl(pageRef)->backgroundExtendsBeyondPage(); +} + void WKPageSetPaginationMode(WKPageRef pageRef, WKPaginationMode paginationMode) { Pagination::Mode mode; @@ -549,6 +720,16 @@ double WKPageGetGapBetweenPages(WKPageRef pageRef) return toImpl(pageRef)->gapBetweenPages(); } +void WKPageSetPaginationLineGridEnabled(WKPageRef pageRef, bool lineGridEnabled) +{ + toImpl(pageRef)->setPaginationLineGridEnabled(lineGridEnabled); +} + +bool WKPageGetPaginationLineGridEnabled(WKPageRef pageRef) +{ + return toImpl(pageRef)->paginationLineGridEnabled(); +} + unsigned WKPageGetPageCount(WKPageRef pageRef) { return toImpl(pageRef)->pageCount(); @@ -609,131 +790,1652 @@ void WKPageCountStringMatches(WKPageRef pageRef, WKStringRef string, WKFindOptio toImpl(pageRef)->countStringMatches(toImpl(string)->string(), toFindOptions(options), maxMatchCount); } -void WKPageSetPageContextMenuClient(WKPageRef pageRef, const WKPageContextMenuClient* wkClient) +void WKPageSetPageContextMenuClient(WKPageRef pageRef, const WKPageContextMenuClientBase* wkClient) { #if ENABLE(CONTEXT_MENUS) - toImpl(pageRef)->initializeContextMenuClient(wkClient); + class ContextMenuClient final : public API::Client<WKPageContextMenuClientBase>, public API::ContextMenuClient { + public: + explicit ContextMenuClient(const WKPageContextMenuClientBase* client) + { + initialize(client); + } + + private: + virtual bool getContextMenuFromProposedMenu(WebPageProxy& page, const Vector<RefPtr<WebKit::WebContextMenuItem>>& proposedMenuVector, Vector<RefPtr<WebKit::WebContextMenuItem>>& customMenu, const WebHitTestResultData& hitTestResultData, API::Object* userData) override + { + if (!m_client.getContextMenuFromProposedMenu && !m_client.getContextMenuFromProposedMenu_deprecatedForUseWithV0) + return false; + + if (m_client.base.version >= 2 && !m_client.getContextMenuFromProposedMenu) + return false; + + Vector<RefPtr<API::Object>> proposedMenuItems; + proposedMenuItems.reserveInitialCapacity(proposedMenuVector.size()); + + for (const auto& menuItem : proposedMenuVector) + proposedMenuItems.uncheckedAppend(menuItem); + + WKArrayRef newMenu = nullptr; + if (m_client.base.version >= 2) { + RefPtr<API::HitTestResult> webHitTestResult = API::HitTestResult::create(hitTestResultData); + m_client.getContextMenuFromProposedMenu(toAPI(&page), toAPI(API::Array::create(WTFMove(proposedMenuItems)).ptr()), &newMenu, toAPI(webHitTestResult.get()), toAPI(userData), m_client.base.clientInfo); + } else + m_client.getContextMenuFromProposedMenu_deprecatedForUseWithV0(toAPI(&page), toAPI(API::Array::create(WTFMove(proposedMenuItems)).ptr()), &newMenu, toAPI(userData), m_client.base.clientInfo); + + RefPtr<API::Array> array = adoptRef(toImpl(newMenu)); + + customMenu.clear(); + + size_t newSize = array ? array->size() : 0; + for (size_t i = 0; i < newSize; ++i) { + WebContextMenuItem* item = array->at<WebContextMenuItem>(i); + if (!item) { + LOG(ContextMenu, "New menu entry at index %i is not a WebContextMenuItem", (int)i); + continue; + } + + customMenu.append(item); + } + + return true; + } + + virtual void customContextMenuItemSelected(WebPageProxy& page, const WebContextMenuItemData& itemData) override + { + if (!m_client.customContextMenuItemSelected) + return; + + m_client.customContextMenuItemSelected(toAPI(&page), toAPI(WebContextMenuItem::create(itemData).ptr()), m_client.base.clientInfo); + } + + virtual bool showContextMenu(WebPageProxy& page, const WebCore::IntPoint& menuLocation, const Vector<RefPtr<WebContextMenuItem>>& menuItemsVector) override + { + if (!m_client.showContextMenu) + return false; + + Vector<RefPtr<API::Object>> menuItems; + menuItems.reserveInitialCapacity(menuItemsVector.size()); + + for (const auto& menuItem : menuItemsVector) + menuItems.uncheckedAppend(menuItem); + + m_client.showContextMenu(toAPI(&page), toAPI(menuLocation), toAPI(API::Array::create(WTFMove(menuItems)).ptr()), m_client.base.clientInfo); + + return true; + } + + virtual bool hideContextMenu(WebPageProxy& page) override + { + if (!m_client.hideContextMenu) + return false; + + m_client.hideContextMenu(toAPI(&page), m_client.base.clientInfo); + + return true; + } + }; + + toImpl(pageRef)->setContextMenuClient(std::make_unique<ContextMenuClient>(wkClient)); +#else + UNUSED_PARAM(pageRef); + UNUSED_PARAM(wkClient); #endif } -void WKPageSetPageFindClient(WKPageRef pageRef, const WKPageFindClient* wkClient) +void WKPageSetPageDiagnosticLoggingClient(WKPageRef pageRef, const WKPageDiagnosticLoggingClientBase* wkClient) { - toImpl(pageRef)->initializeFindClient(wkClient); + toImpl(pageRef)->setDiagnosticLoggingClient(std::make_unique<WebPageDiagnosticLoggingClient>(wkClient)); } -void WKPageSetPageFindMatchesClient(WKPageRef pageRef, const WKPageFindMatchesClient* wkClient) +void WKPageSetPageFindClient(WKPageRef pageRef, const WKPageFindClientBase* wkClient) { - toImpl(pageRef)->initializeFindMatchesClient(wkClient); + class FindClient : public API::Client<WKPageFindClientBase>, public API::FindClient { + public: + explicit FindClient(const WKPageFindClientBase* client) + { + initialize(client); + } + + private: + virtual void didFindString(WebPageProxy* page, const String& string, const Vector<WebCore::IntRect>&, uint32_t matchCount, int32_t) override + { + if (!m_client.didFindString) + return; + + m_client.didFindString(toAPI(page), toAPI(string.impl()), matchCount, m_client.base.clientInfo); + } + + virtual void didFailToFindString(WebPageProxy* page, const String& string) override + { + if (!m_client.didFailToFindString) + return; + + m_client.didFailToFindString(toAPI(page), toAPI(string.impl()), m_client.base.clientInfo); + } + + virtual void didCountStringMatches(WebPageProxy* page, const String& string, uint32_t matchCount) override + { + if (!m_client.didCountStringMatches) + return; + + m_client.didCountStringMatches(toAPI(page), toAPI(string.impl()), matchCount, m_client.base.clientInfo); + } + }; + + toImpl(pageRef)->setFindClient(std::make_unique<FindClient>(wkClient)); } -void WKPageSetPageFormClient(WKPageRef pageRef, const WKPageFormClient* wkClient) +void WKPageSetPageFindMatchesClient(WKPageRef pageRef, const WKPageFindMatchesClientBase* wkClient) { - toImpl(pageRef)->initializeFormClient(wkClient); + class FindMatchesClient : public API::Client<WKPageFindMatchesClientBase>, public API::FindMatchesClient { + public: + explicit FindMatchesClient(const WKPageFindMatchesClientBase* client) + { + initialize(client); + } + + private: + virtual void didFindStringMatches(WebPageProxy* page, const String& string, const Vector<Vector<WebCore::IntRect>>& matchRects, int32_t index) override + { + if (!m_client.didFindStringMatches) + return; + + Vector<RefPtr<API::Object>> matches; + matches.reserveInitialCapacity(matchRects.size()); + + for (const auto& rects : matchRects) { + Vector<RefPtr<API::Object>> apiRects; + apiRects.reserveInitialCapacity(rects.size()); + + for (const auto& rect : rects) + apiRects.uncheckedAppend(API::Rect::create(toAPI(rect))); + + matches.uncheckedAppend(API::Array::create(WTFMove(apiRects))); + } + + m_client.didFindStringMatches(toAPI(page), toAPI(string.impl()), toAPI(API::Array::create(WTFMove(matches)).ptr()), index, m_client.base.clientInfo); + } + + virtual void didGetImageForMatchResult(WebPageProxy* page, WebImage* image, int32_t index) override + { + if (!m_client.didGetImageForMatchResult) + return; + + m_client.didGetImageForMatchResult(toAPI(page), toAPI(image), index, m_client.base.clientInfo); + } + }; + + toImpl(pageRef)->setFindMatchesClient(std::make_unique<FindMatchesClient>(wkClient)); } -void WKPageSetPageLoaderClient(WKPageRef pageRef, const WKPageLoaderClient* wkClient) +void WKPageSetPageInjectedBundleClient(WKPageRef pageRef, const WKPageInjectedBundleClientBase* wkClient) { - toImpl(pageRef)->initializeLoaderClient(wkClient); + toImpl(pageRef)->setInjectedBundleClient(wkClient); } -void WKPageSetPagePolicyClient(WKPageRef pageRef, const WKPagePolicyClient* wkClient) +void WKPageSetPageFormClient(WKPageRef pageRef, const WKPageFormClientBase* wkClient) { - toImpl(pageRef)->initializePolicyClient(wkClient); + toImpl(pageRef)->setFormClient(std::make_unique<WebFormClient>(wkClient)); } -void WKPageSetPageUIClient(WKPageRef pageRef, const WKPageUIClient* wkClient) +void WKPageSetPageLoaderClient(WKPageRef pageRef, const WKPageLoaderClientBase* wkClient) { - toImpl(pageRef)->initializeUIClient(wkClient); + class LoaderClient : public API::Client<WKPageLoaderClientBase>, public API::LoaderClient { + public: + explicit LoaderClient(const WKPageLoaderClientBase* client) + { + initialize(client); + } + + private: + virtual void didStartProvisionalLoadForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, API::Object* userData) override + { + if (!m_client.didStartProvisionalLoadForFrame) + return; + + m_client.didStartProvisionalLoadForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didReceiveServerRedirectForProvisionalLoadForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, API::Object* userData) override + { + if (!m_client.didReceiveServerRedirectForProvisionalLoadForFrame) + return; + + m_client.didReceiveServerRedirectForProvisionalLoadForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFailProvisionalLoadWithErrorForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, const ResourceError& error, API::Object* userData) override + { + if (!m_client.didFailProvisionalLoadWithErrorForFrame) + return; + + m_client.didFailProvisionalLoadWithErrorForFrame(toAPI(&page), toAPI(&frame), toAPI(error), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didCommitLoadForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, API::Object* userData) override + { + if (!m_client.didCommitLoadForFrame) + return; + + m_client.didCommitLoadForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFinishDocumentLoadForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, API::Object* userData) override + { + if (!m_client.didFinishDocumentLoadForFrame) + return; + + m_client.didFinishDocumentLoadForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFinishLoadForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, API::Object* userData) override + { + if (!m_client.didFinishLoadForFrame) + return; + + m_client.didFinishLoadForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFailLoadWithErrorForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, const ResourceError& error, API::Object* userData) override + { + if (!m_client.didFailLoadWithErrorForFrame) + return; + + m_client.didFailLoadWithErrorForFrame(toAPI(&page), toAPI(&frame), toAPI(error), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didSameDocumentNavigationForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Navigation*, SameDocumentNavigationType type, API::Object* userData) override + { + if (!m_client.didSameDocumentNavigationForFrame) + return; + + m_client.didSameDocumentNavigationForFrame(toAPI(&page), toAPI(&frame), toAPI(type), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didReceiveTitleForFrame(WebPageProxy& page, const String& title, WebFrameProxy& frame, API::Object* userData) override + { + if (!m_client.didReceiveTitleForFrame) + return; + + m_client.didReceiveTitleForFrame(toAPI(&page), toAPI(title.impl()), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFirstLayoutForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Object* userData) override + { + if (!m_client.didFirstLayoutForFrame) + return; + + m_client.didFirstLayoutForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFirstVisuallyNonEmptyLayoutForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Object* userData) override + { + if (!m_client.didFirstVisuallyNonEmptyLayoutForFrame) + return; + + m_client.didFirstVisuallyNonEmptyLayoutForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didLayout(WebPageProxy& page, LayoutMilestones milestones) override + { + if (!m_client.didLayout) + return; + + m_client.didLayout(toAPI(&page), toWKLayoutMilestones(milestones), nullptr, m_client.base.clientInfo); + } + + virtual void didDisplayInsecureContentForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Object* userData) override + { + if (!m_client.didDisplayInsecureContentForFrame) + return; + + m_client.didDisplayInsecureContentForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didRunInsecureContentForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Object* userData) override + { + if (!m_client.didRunInsecureContentForFrame) + return; + + m_client.didRunInsecureContentForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didDetectXSSForFrame(WebPageProxy& page, WebFrameProxy& frame, API::Object* userData) override + { + if (!m_client.didDetectXSSForFrame) + return; + + m_client.didDetectXSSForFrame(toAPI(&page), toAPI(&frame), toAPI(userData), m_client.base.clientInfo); + } + + virtual bool canAuthenticateAgainstProtectionSpaceInFrame(WebPageProxy& page, WebFrameProxy& frame, WebProtectionSpace* protectionSpace) override + { + if (!m_client.canAuthenticateAgainstProtectionSpaceInFrame) + return false; + + return m_client.canAuthenticateAgainstProtectionSpaceInFrame(toAPI(&page), toAPI(&frame), toAPI(protectionSpace), m_client.base.clientInfo); + } + + virtual void didReceiveAuthenticationChallengeInFrame(WebPageProxy& page, WebFrameProxy& frame, AuthenticationChallengeProxy* authenticationChallenge) override + { + if (!m_client.didReceiveAuthenticationChallengeInFrame) + return; + + m_client.didReceiveAuthenticationChallengeInFrame(toAPI(&page), toAPI(&frame), toAPI(authenticationChallenge), m_client.base.clientInfo); + } + + virtual void didStartProgress(WebPageProxy& page) override + { + if (!m_client.didStartProgress) + return; + + m_client.didStartProgress(toAPI(&page), m_client.base.clientInfo); + } + + virtual void didChangeProgress(WebPageProxy& page) override + { + if (!m_client.didChangeProgress) + return; + + m_client.didChangeProgress(toAPI(&page), m_client.base.clientInfo); + } + + virtual void didFinishProgress(WebPageProxy& page) override + { + if (!m_client.didFinishProgress) + return; + + m_client.didFinishProgress(toAPI(&page), m_client.base.clientInfo); + } + + virtual void processDidBecomeUnresponsive(WebPageProxy& page) override + { + if (!m_client.processDidBecomeUnresponsive) + return; + + m_client.processDidBecomeUnresponsive(toAPI(&page), m_client.base.clientInfo); + } + + virtual void processDidBecomeResponsive(WebPageProxy& page) override + { + if (!m_client.processDidBecomeResponsive) + return; + + m_client.processDidBecomeResponsive(toAPI(&page), m_client.base.clientInfo); + } + + virtual void processDidCrash(WebPageProxy& page) override + { + if (!m_client.processDidCrash) + return; + + m_client.processDidCrash(toAPI(&page), m_client.base.clientInfo); + } + + virtual void didChangeBackForwardList(WebPageProxy& page, WebBackForwardListItem* addedItem, Vector<RefPtr<WebBackForwardListItem>> removedItems) override + { + if (!m_client.didChangeBackForwardList) + return; + + RefPtr<API::Array> removedItemsArray; + if (!removedItems.isEmpty()) { + Vector<RefPtr<API::Object>> removedItemsVector; + removedItemsVector.reserveInitialCapacity(removedItems.size()); + for (auto& removedItem : removedItems) + removedItemsVector.append(WTFMove(removedItem)); + + removedItemsArray = API::Array::create(WTFMove(removedItemsVector)); + } + + m_client.didChangeBackForwardList(toAPI(&page), toAPI(addedItem), toAPI(removedItemsArray.get()), m_client.base.clientInfo); + } + + virtual bool shouldKeepCurrentBackForwardListItemInList(WebKit::WebPageProxy& page, WebKit::WebBackForwardListItem* item) override + { + if (!m_client.shouldKeepCurrentBackForwardListItemInList) + return true; + + return m_client.shouldKeepCurrentBackForwardListItemInList(toAPI(&page), toAPI(item), m_client.base.clientInfo); + } + + virtual void willGoToBackForwardListItem(WebPageProxy& page, WebBackForwardListItem* item, API::Object* userData) override + { + if (m_client.willGoToBackForwardListItem) + m_client.willGoToBackForwardListItem(toAPI(&page), toAPI(item), toAPI(userData), m_client.base.clientInfo); + } + + virtual RefPtr<API::Data> webCryptoMasterKey(WebPageProxy& page) override + { + return page.process().processPool().client().copyWebCryptoMasterKey(&page.process().processPool()); + } + + virtual void navigationGestureDidBegin(WebPageProxy& page) override + { + if (m_client.navigationGestureDidBegin) + m_client.navigationGestureDidBegin(toAPI(&page), m_client.base.clientInfo); + } + + virtual void navigationGestureWillEnd(WebPageProxy& page, bool willNavigate, WebBackForwardListItem& item) override + { + if (m_client.navigationGestureWillEnd) + m_client.navigationGestureWillEnd(toAPI(&page), willNavigate, toAPI(&item), m_client.base.clientInfo); + } + + virtual void navigationGestureDidEnd(WebPageProxy& page, bool willNavigate, WebBackForwardListItem& item) override + { + if (m_client.navigationGestureDidEnd) + m_client.navigationGestureDidEnd(toAPI(&page), willNavigate, toAPI(&item), m_client.base.clientInfo); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + virtual void didFailToInitializePlugin(WebPageProxy& page, API::Dictionary* pluginInformation) override + { + if (m_client.didFailToInitializePlugin_deprecatedForUseWithV0) + m_client.didFailToInitializePlugin_deprecatedForUseWithV0(toAPI(&page), toAPI(pluginInformation->get<API::String>(pluginInformationMIMETypeKey())), m_client.base.clientInfo); + + if (m_client.pluginDidFail_deprecatedForUseWithV1) + m_client.pluginDidFail_deprecatedForUseWithV1(toAPI(&page), kWKErrorCodeCannotLoadPlugIn, toAPI(pluginInformation->get<API::String>(pluginInformationMIMETypeKey())), 0, 0, m_client.base.clientInfo); + + if (m_client.pluginDidFail) + m_client.pluginDidFail(toAPI(&page), kWKErrorCodeCannotLoadPlugIn, toAPI(pluginInformation), m_client.base.clientInfo); + } + + virtual void didBlockInsecurePluginVersion(WebPageProxy& page, API::Dictionary* pluginInformation) override + { + if (m_client.pluginDidFail_deprecatedForUseWithV1) + m_client.pluginDidFail_deprecatedForUseWithV1(toAPI(&page), kWKErrorCodeInsecurePlugInVersion, toAPI(pluginInformation->get<API::String>(pluginInformationMIMETypeKey())), toAPI(pluginInformation->get<API::String>(pluginInformationBundleIdentifierKey())), toAPI(pluginInformation->get<API::String>(pluginInformationBundleVersionKey())), m_client.base.clientInfo); + + if (m_client.pluginDidFail) + m_client.pluginDidFail(toAPI(&page), kWKErrorCodeInsecurePlugInVersion, toAPI(pluginInformation), m_client.base.clientInfo); + } + + virtual PluginModuleLoadPolicy pluginLoadPolicy(WebPageProxy& page, PluginModuleLoadPolicy currentPluginLoadPolicy, API::Dictionary* pluginInformation, String& unavailabilityDescription) override + { + WKStringRef unavailabilityDescriptionOut = 0; + PluginModuleLoadPolicy loadPolicy = currentPluginLoadPolicy; + + if (m_client.pluginLoadPolicy_deprecatedForUseWithV2) + loadPolicy = toPluginModuleLoadPolicy(m_client.pluginLoadPolicy_deprecatedForUseWithV2(toAPI(&page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), m_client.base.clientInfo)); + else if (m_client.pluginLoadPolicy) + loadPolicy = toPluginModuleLoadPolicy(m_client.pluginLoadPolicy(toAPI(&page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), &unavailabilityDescriptionOut, m_client.base.clientInfo)); + + if (unavailabilityDescriptionOut) { + RefPtr<API::String> webUnavailabilityDescription = adoptRef(toImpl(unavailabilityDescriptionOut)); + unavailabilityDescription = webUnavailabilityDescription->string(); + } + + return loadPolicy; + } +#endif // ENABLE(NETSCAPE_PLUGIN_API) + +#if ENABLE(WEBGL) + virtual WebCore::WebGLLoadPolicy webGLLoadPolicy(WebPageProxy& page, const String& url) const override + { + WebCore::WebGLLoadPolicy loadPolicy = WebGLAllowCreation; + + if (m_client.webGLLoadPolicy) + loadPolicy = toWebGLLoadPolicy(m_client.webGLLoadPolicy(toAPI(&page), toAPI(url.impl()), m_client.base.clientInfo)); + + return loadPolicy; + } + + virtual WebCore::WebGLLoadPolicy resolveWebGLLoadPolicy(WebPageProxy& page, const String& url) const override + { + WebCore::WebGLLoadPolicy loadPolicy = WebGLAllowCreation; + + if (m_client.resolveWebGLLoadPolicy) + loadPolicy = toWebGLLoadPolicy(m_client.resolveWebGLLoadPolicy(toAPI(&page), toAPI(url.impl()), m_client.base.clientInfo)); + + return loadPolicy; + } + +#endif // ENABLE(WEBGL) + }; + + WebPageProxy* webPageProxy = toImpl(pageRef); + + auto loaderClient = std::make_unique<LoaderClient>(wkClient); + + // It would be nice to get rid of this code and transition all clients to using didLayout instead of + // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required + // for backwards compatibility. + WebCore::LayoutMilestones milestones = 0; + if (loaderClient->client().didFirstLayoutForFrame) + milestones |= WebCore::DidFirstLayout; + if (loaderClient->client().didFirstVisuallyNonEmptyLayoutForFrame) + milestones |= WebCore::DidFirstVisuallyNonEmptyLayout; + + if (milestones) + webPageProxy->process().send(Messages::WebPage::ListenForLayoutMilestones(milestones), webPageProxy->pageID()); + + webPageProxy->setLoaderClient(WTFMove(loaderClient)); +} + +void WKPageSetPagePolicyClient(WKPageRef pageRef, const WKPagePolicyClientBase* wkClient) +{ + class PolicyClient : public API::Client<WKPagePolicyClientBase>, public API::PolicyClient { + public: + explicit PolicyClient(const WKPagePolicyClientBase* client) + { + initialize(client); + } + + private: + virtual void decidePolicyForNavigationAction(WebPageProxy& page, WebFrameProxy* frame, const NavigationActionData& navigationActionData, WebFrameProxy* originatingFrame, const WebCore::ResourceRequest& originalResourceRequest, const WebCore::ResourceRequest& resourceRequest, Ref<WebFramePolicyListenerProxy>&& listener, API::Object* userData) override + { + if (!m_client.decidePolicyForNavigationAction_deprecatedForUseWithV0 && !m_client.decidePolicyForNavigationAction_deprecatedForUseWithV1 && !m_client.decidePolicyForNavigationAction) { + listener->use(); + return; + } + + Ref<API::URLRequest> originalRequest = API::URLRequest::create(originalResourceRequest); + Ref<API::URLRequest> request = API::URLRequest::create(resourceRequest); + + if (m_client.decidePolicyForNavigationAction_deprecatedForUseWithV0) + m_client.decidePolicyForNavigationAction_deprecatedForUseWithV0(toAPI(&page), toAPI(frame), toAPI(navigationActionData.navigationType), toAPI(navigationActionData.modifiers), toAPI(navigationActionData.mouseButton), toAPI(request.ptr()), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + else if (m_client.decidePolicyForNavigationAction_deprecatedForUseWithV1) + m_client.decidePolicyForNavigationAction_deprecatedForUseWithV1(toAPI(&page), toAPI(frame), toAPI(navigationActionData.navigationType), toAPI(navigationActionData.modifiers), toAPI(navigationActionData.mouseButton), toAPI(originatingFrame), toAPI(request.ptr()), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + else + m_client.decidePolicyForNavigationAction(toAPI(&page), toAPI(frame), toAPI(navigationActionData.navigationType), toAPI(navigationActionData.modifiers), toAPI(navigationActionData.mouseButton), toAPI(originatingFrame), toAPI(originalRequest.ptr()), toAPI(request.ptr()), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + } + + virtual void decidePolicyForNewWindowAction(WebPageProxy& page, WebFrameProxy& frame, const NavigationActionData& navigationActionData, const ResourceRequest& resourceRequest, const String& frameName, Ref<WebFramePolicyListenerProxy>&& listener, API::Object* userData) override + { + if (!m_client.decidePolicyForNewWindowAction) { + listener->use(); + return; + } + + Ref<API::URLRequest> request = API::URLRequest::create(resourceRequest); + + m_client.decidePolicyForNewWindowAction(toAPI(&page), toAPI(&frame), toAPI(navigationActionData.navigationType), toAPI(navigationActionData.modifiers), toAPI(navigationActionData.mouseButton), toAPI(request.ptr()), toAPI(frameName.impl()), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + } + + virtual void decidePolicyForResponse(WebPageProxy& page, WebFrameProxy& frame, const ResourceResponse& resourceResponse, const ResourceRequest& resourceRequest, bool canShowMIMEType, Ref<WebFramePolicyListenerProxy>&& listener, API::Object* userData) override + { + if (!m_client.decidePolicyForResponse_deprecatedForUseWithV0 && !m_client.decidePolicyForResponse) { + listener->use(); + return; + } + + Ref<API::URLResponse> response = API::URLResponse::create(resourceResponse); + Ref<API::URLRequest> request = API::URLRequest::create(resourceRequest); + + if (m_client.decidePolicyForResponse_deprecatedForUseWithV0) + m_client.decidePolicyForResponse_deprecatedForUseWithV0(toAPI(&page), toAPI(&frame), toAPI(response.ptr()), toAPI(request.ptr()), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + else + m_client.decidePolicyForResponse(toAPI(&page), toAPI(&frame), toAPI(response.ptr()), toAPI(request.ptr()), canShowMIMEType, toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + } + + virtual void unableToImplementPolicy(WebPageProxy& page, WebFrameProxy& frame, const ResourceError& error, API::Object* userData) override + { + if (!m_client.unableToImplementPolicy) + return; + + m_client.unableToImplementPolicy(toAPI(&page), toAPI(&frame), toAPI(error), toAPI(userData), m_client.base.clientInfo); + } + }; + + toImpl(pageRef)->setPolicyClient(std::make_unique<PolicyClient>(wkClient)); +} + +#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED <= 101000 +static void fixUpBotchedPageUIClient(WKPageRef pageRef, const WKPageUIClientBase& wkClient) +{ + struct BotchedWKPageUIClientV4 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert_deprecatedForUseWithV0; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm_deprecatedForUseWithV0; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt_deprecatedForUseWithV0; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + + // Version 3. + WKPagePinnedStateDidChangeCallback pinnedStateDidChange; + + // Version 4. + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV5 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV5 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV5 runJavaScriptPrompt; + }; + + const auto& botchedPageUIClient = reinterpret_cast<const BotchedWKPageUIClientV4&>(wkClient); + + WKPageUIClientV5 fixedPageUIClient = { + { 5, botchedPageUIClient.base.clientInfo }, + botchedPageUIClient.createNewPage_deprecatedForUseWithV0, + botchedPageUIClient.showPage, + botchedPageUIClient.close, + botchedPageUIClient.takeFocus, + botchedPageUIClient.focus, + botchedPageUIClient.unfocus, + botchedPageUIClient.runJavaScriptAlert_deprecatedForUseWithV0, + botchedPageUIClient.runJavaScriptConfirm_deprecatedForUseWithV0, + botchedPageUIClient.runJavaScriptPrompt_deprecatedForUseWithV0, + botchedPageUIClient.setStatusText, + botchedPageUIClient.mouseDidMoveOverElement_deprecatedForUseWithV0, + botchedPageUIClient.missingPluginButtonClicked_deprecatedForUseWithV0, + botchedPageUIClient.didNotHandleKeyEvent, + botchedPageUIClient.didNotHandleWheelEvent, + botchedPageUIClient.toolbarsAreVisible, + botchedPageUIClient.setToolbarsAreVisible, + botchedPageUIClient.menuBarIsVisible, + botchedPageUIClient.setMenuBarIsVisible, + botchedPageUIClient.statusBarIsVisible, + botchedPageUIClient.setStatusBarIsVisible, + botchedPageUIClient.isResizable, + botchedPageUIClient.setIsResizable, + botchedPageUIClient.getWindowFrame, + botchedPageUIClient.setWindowFrame, + botchedPageUIClient.runBeforeUnloadConfirmPanel, + botchedPageUIClient.didDraw, + botchedPageUIClient.pageDidScroll, + botchedPageUIClient.exceededDatabaseQuota, + botchedPageUIClient.runOpenPanel, + botchedPageUIClient.decidePolicyForGeolocationPermissionRequest, + botchedPageUIClient.headerHeight, + botchedPageUIClient.footerHeight, + botchedPageUIClient.drawHeader, + botchedPageUIClient.drawFooter, + botchedPageUIClient.printFrame, + botchedPageUIClient.runModal, + botchedPageUIClient.unused1, + botchedPageUIClient.saveDataToFileInDownloadsFolder, + botchedPageUIClient.shouldInterruptJavaScript_unavailable, + botchedPageUIClient.createNewPage, + botchedPageUIClient.mouseDidMoveOverElement, + botchedPageUIClient.decidePolicyForNotificationPermissionRequest, + botchedPageUIClient.unavailablePluginButtonClicked_deprecatedForUseWithV1, + botchedPageUIClient.showColorPicker, + botchedPageUIClient.hideColorPicker, + botchedPageUIClient.unavailablePluginButtonClicked, + botchedPageUIClient.pinnedStateDidChange, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + botchedPageUIClient.runJavaScriptAlert, + botchedPageUIClient.runJavaScriptConfirm, + botchedPageUIClient.runJavaScriptPrompt, + nullptr, + }; + + WKPageSetPageUIClient(pageRef, &fixedPageUIClient.base); } +#endif -void WKPageRunJavaScriptInMainFrame(WKPageRef pageRef, WKStringRef scriptRef, void* context, WKPageRunJavaScriptFunction callback) +namespace WebKit { + +class RunBeforeUnloadConfirmPanelResultListener : public API::ObjectImpl<API::Object::Type::RunBeforeUnloadConfirmPanelResultListener> { +public: + static PassRefPtr<RunBeforeUnloadConfirmPanelResultListener> create(std::function<void (bool)>&& completionHandler) + { + return adoptRef(new RunBeforeUnloadConfirmPanelResultListener(WTFMove(completionHandler))); + } + + virtual ~RunBeforeUnloadConfirmPanelResultListener() + { + } + + void call(bool result) + { + m_completionHandler(result); + } + +private: + explicit RunBeforeUnloadConfirmPanelResultListener(std::function<void (bool)>&& completionHandler) + : m_completionHandler(WTFMove(completionHandler)) + { + } + + std::function<void (bool)> m_completionHandler; +}; + +class RunJavaScriptAlertResultListener : public API::ObjectImpl<API::Object::Type::RunJavaScriptAlertResultListener> { +public: + static PassRefPtr<RunJavaScriptAlertResultListener> create(std::function<void ()>&& completionHandler) + { + return adoptRef(new RunJavaScriptAlertResultListener(WTFMove(completionHandler))); + } + + virtual ~RunJavaScriptAlertResultListener() + { + } + + void call() + { + m_completionHandler(); + } + +private: + explicit RunJavaScriptAlertResultListener(std::function<void ()>&& completionHandler) + : m_completionHandler(WTFMove(completionHandler)) + { + } + + std::function<void ()> m_completionHandler; +}; + +class RunJavaScriptConfirmResultListener : public API::ObjectImpl<API::Object::Type::RunJavaScriptConfirmResultListener> { +public: + static PassRefPtr<RunJavaScriptConfirmResultListener> create(std::function<void (bool)>&& completionHandler) + { + return adoptRef(new RunJavaScriptConfirmResultListener(WTFMove(completionHandler))); + } + + virtual ~RunJavaScriptConfirmResultListener() + { + } + + void call(bool result) + { + m_completionHandler(result); + } + +private: + explicit RunJavaScriptConfirmResultListener(std::function<void (bool)>&& completionHandler) + : m_completionHandler(WTFMove(completionHandler)) + { + } + + std::function<void (bool)> m_completionHandler; +}; + +class RunJavaScriptPromptResultListener : public API::ObjectImpl<API::Object::Type::RunJavaScriptPromptResultListener> { +public: + static PassRefPtr<RunJavaScriptPromptResultListener> create(std::function<void (const String&)>&& completionHandler) + { + return adoptRef(new RunJavaScriptPromptResultListener(WTFMove(completionHandler))); + } + + virtual ~RunJavaScriptPromptResultListener() + { + } + + void call(const String& result) + { + m_completionHandler(result); + } + +private: + explicit RunJavaScriptPromptResultListener(std::function<void (const String&)>&& completionHandler) + : m_completionHandler(WTFMove(completionHandler)) + { + } + + std::function<void (const String&)> m_completionHandler; +}; + +WK_ADD_API_MAPPING(WKPageRunBeforeUnloadConfirmPanelResultListenerRef, RunBeforeUnloadConfirmPanelResultListener) +WK_ADD_API_MAPPING(WKPageRunJavaScriptAlertResultListenerRef, RunJavaScriptAlertResultListener) +WK_ADD_API_MAPPING(WKPageRunJavaScriptConfirmResultListenerRef, RunJavaScriptConfirmResultListener) +WK_ADD_API_MAPPING(WKPageRunJavaScriptPromptResultListenerRef, RunJavaScriptPromptResultListener) + +} + +WKTypeID WKPageRunBeforeUnloadConfirmPanelResultListenerGetTypeID() { - toImpl(pageRef)->runJavaScriptInMainFrame(toImpl(scriptRef)->string(), ScriptValueCallback::create(context, callback)); + return toAPI(RunBeforeUnloadConfirmPanelResultListener::APIType); } -#ifdef __BLOCKS__ -static void callRunJavaScriptBlockAndRelease(WKSerializedScriptValueRef resultValue, WKErrorRef error, void* context) +void WKPageRunBeforeUnloadConfirmPanelResultListenerCall(WKPageRunBeforeUnloadConfirmPanelResultListenerRef listener, bool result) { - WKPageRunJavaScriptBlock block = (WKPageRunJavaScriptBlock)context; - block(resultValue, error); - Block_release(block); + toImpl(listener)->call(result); } -void WKPageRunJavaScriptInMainFrame_b(WKPageRef pageRef, WKStringRef scriptRef, WKPageRunJavaScriptBlock block) +WKTypeID WKPageRunJavaScriptAlertResultListenerGetTypeID() { - WKPageRunJavaScriptInMainFrame(pageRef, scriptRef, Block_copy(block), callRunJavaScriptBlockAndRelease); + return toAPI(RunJavaScriptAlertResultListener::APIType); } -#endif -void WKPageRenderTreeExternalRepresentation(WKPageRef pageRef, void* context, WKPageRenderTreeExternalRepresentationFunction callback) +void WKPageRunJavaScriptAlertResultListenerCall(WKPageRunJavaScriptAlertResultListenerRef listener) { - toImpl(pageRef)->getRenderTreeExternalRepresentation(StringCallback::create(context, callback)); + toImpl(listener)->call(); } -#ifdef __BLOCKS__ -static void callRenderTreeExternalRepresentationBlockAndDispose(WKStringRef resultValue, WKErrorRef error, void* context) +WKTypeID WKPageRunJavaScriptConfirmResultListenerGetTypeID() { - WKPageRenderTreeExternalRepresentationBlock block = (WKPageRenderTreeExternalRepresentationBlock)context; - block(resultValue, error); - Block_release(block); + return toAPI(RunJavaScriptConfirmResultListener::APIType); +} + +void WKPageRunJavaScriptConfirmResultListenerCall(WKPageRunJavaScriptConfirmResultListenerRef listener, bool result) +{ + toImpl(listener)->call(result); } -void WKPageRenderTreeExternalRepresentation_b(WKPageRef pageRef, WKPageRenderTreeExternalRepresentationBlock block) +WKTypeID WKPageRunJavaScriptPromptResultListenerGetTypeID() { - WKPageRenderTreeExternalRepresentation(pageRef, Block_copy(block), callRenderTreeExternalRepresentationBlockAndDispose); + return toAPI(RunJavaScriptPromptResultListener::APIType); } + +void WKPageRunJavaScriptPromptResultListenerCall(WKPageRunJavaScriptPromptResultListenerRef listener, WKStringRef result) +{ + toImpl(listener)->call(toWTFString(result)); +} + +void WKPageSetPageUIClient(WKPageRef pageRef, const WKPageUIClientBase* wkClient) +{ +#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED <= 101000 + if (wkClient && wkClient->version == 4) { + fixUpBotchedPageUIClient(pageRef, *wkClient); + return; + } #endif -void WKPageGetSourceForFrame(WKPageRef pageRef, WKFrameRef frameRef, void* context, WKPageGetSourceForFrameFunction callback) + class UIClient : public API::Client<WKPageUIClientBase>, public API::UIClient { + public: + explicit UIClient(const WKPageUIClientBase* client) + { + initialize(client); + } + + private: + virtual PassRefPtr<WebPageProxy> createNewPage(WebPageProxy* page, WebFrameProxy* initiatingFrame, const SecurityOriginData& securityOriginData, const ResourceRequest& resourceRequest, const WindowFeatures& windowFeatures, const NavigationActionData& navigationActionData) override + { + if (m_client.createNewPage) { + auto configuration = page->configuration().copy(); + configuration->setRelatedPage(page); + + auto sourceFrameInfo = API::FrameInfo::create(*initiatingFrame, securityOriginData.securityOrigin()); + + bool shouldOpenAppLinks = !hostsAreEqual(WebCore::URL(WebCore::ParsedURLString, initiatingFrame->url()), resourceRequest.url()); + auto apiNavigationAction = API::NavigationAction::create(navigationActionData, sourceFrameInfo.ptr(), nullptr, resourceRequest, WebCore::URL(), shouldOpenAppLinks); + + auto apiWindowFeatures = API::WindowFeatures::create(windowFeatures); + + return adoptRef(toImpl(m_client.createNewPage(toAPI(page), toAPI(configuration.ptr()), toAPI(apiNavigationAction.ptr()), toAPI(apiWindowFeatures.ptr()), m_client.base.clientInfo))); + } + + if (m_client.createNewPage_deprecatedForUseWithV1 || m_client.createNewPage_deprecatedForUseWithV0) { + API::Dictionary::MapType map; + if (windowFeatures.x) + map.set("x", API::Double::create(*windowFeatures.x)); + if (windowFeatures.y) + map.set("y", API::Double::create(*windowFeatures.y)); + if (windowFeatures.width) + map.set("width", API::Double::create(*windowFeatures.width)); + if (windowFeatures.height) + map.set("height", API::Double::create(*windowFeatures.height)); + map.set("menuBarVisible", API::Boolean::create(windowFeatures.menuBarVisible)); + map.set("statusBarVisible", API::Boolean::create(windowFeatures.statusBarVisible)); + map.set("toolBarVisible", API::Boolean::create(windowFeatures.toolBarVisible)); + map.set("locationBarVisible", API::Boolean::create(windowFeatures.locationBarVisible)); + map.set("scrollbarsVisible", API::Boolean::create(windowFeatures.scrollbarsVisible)); + map.set("resizable", API::Boolean::create(windowFeatures.resizable)); + map.set("fullscreen", API::Boolean::create(windowFeatures.fullscreen)); + map.set("dialog", API::Boolean::create(windowFeatures.dialog)); + Ref<API::Dictionary> featuresMap = API::Dictionary::create(WTFMove(map)); + + if (m_client.createNewPage_deprecatedForUseWithV1) { + Ref<API::URLRequest> request = API::URLRequest::create(resourceRequest); + return adoptRef(toImpl(m_client.createNewPage_deprecatedForUseWithV1(toAPI(page), toAPI(request.ptr()), toAPI(featuresMap.ptr()), toAPI(navigationActionData.modifiers), toAPI(navigationActionData.mouseButton), m_client.base.clientInfo))); + } + + ASSERT(m_client.createNewPage_deprecatedForUseWithV0); + return adoptRef(toImpl(m_client.createNewPage_deprecatedForUseWithV0(toAPI(page), toAPI(featuresMap.ptr()), toAPI(navigationActionData.modifiers), toAPI(navigationActionData.mouseButton), m_client.base.clientInfo))); + } + + return nullptr; + } + + virtual void showPage(WebPageProxy* page) override + { + if (!m_client.showPage) + return; + + m_client.showPage(toAPI(page), m_client.base.clientInfo); + } + + virtual void close(WebPageProxy* page) override + { + if (!m_client.close) + return; + + m_client.close(toAPI(page), m_client.base.clientInfo); + } + + virtual void takeFocus(WebPageProxy* page, WKFocusDirection direction) override + { + if (!m_client.takeFocus) + return; + + m_client.takeFocus(toAPI(page), direction, m_client.base.clientInfo); + } + + virtual void focus(WebPageProxy* page) override + { + if (!m_client.focus) + return; + + m_client.focus(toAPI(page), m_client.base.clientInfo); + } + + virtual void unfocus(WebPageProxy* page) override + { + if (!m_client.unfocus) + return; + + m_client.unfocus(toAPI(page), m_client.base.clientInfo); + } + + virtual void runJavaScriptAlert(WebPageProxy* page, const String& message, WebFrameProxy* frame, const SecurityOriginData& securityOriginData, std::function<void ()> completionHandler) override + { + if (m_client.runJavaScriptAlert) { + RefPtr<RunJavaScriptAlertResultListener> listener = RunJavaScriptAlertResultListener::create(WTFMove(completionHandler)); + RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(securityOriginData.protocol, securityOriginData.host, securityOriginData.port); + m_client.runJavaScriptAlert(toAPI(page), toAPI(message.impl()), toAPI(frame), toAPI(securityOrigin.get()), toAPI(listener.get()), m_client.base.clientInfo); + return; + } + + if (m_client.runJavaScriptAlert_deprecatedForUseWithV5) { + RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(securityOriginData.protocol, securityOriginData.host, securityOriginData.port); + m_client.runJavaScriptAlert_deprecatedForUseWithV5(toAPI(page), toAPI(message.impl()), toAPI(frame), toAPI(securityOrigin.get()), m_client.base.clientInfo); + completionHandler(); + return; + } + + if (m_client.runJavaScriptAlert_deprecatedForUseWithV0) { + m_client.runJavaScriptAlert_deprecatedForUseWithV0(toAPI(page), toAPI(message.impl()), toAPI(frame), m_client.base.clientInfo); + completionHandler(); + return; + } + + + completionHandler(); + } + + virtual void runJavaScriptConfirm(WebPageProxy* page, const String& message, WebFrameProxy* frame, const SecurityOriginData& securityOriginData, std::function<void (bool)> completionHandler) override + { + if (m_client.runJavaScriptConfirm) { + RefPtr<RunJavaScriptConfirmResultListener> listener = RunJavaScriptConfirmResultListener::create(WTFMove(completionHandler)); + RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(securityOriginData.protocol, securityOriginData.host, securityOriginData.port); + m_client.runJavaScriptConfirm(toAPI(page), toAPI(message.impl()), toAPI(frame), toAPI(securityOrigin.get()), toAPI(listener.get()), m_client.base.clientInfo); + return; + } + + if (m_client.runJavaScriptConfirm_deprecatedForUseWithV5) { + RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(securityOriginData.protocol, securityOriginData.host, securityOriginData.port); + bool result = m_client.runJavaScriptConfirm_deprecatedForUseWithV5(toAPI(page), toAPI(message.impl()), toAPI(frame), toAPI(securityOrigin.get()), m_client.base.clientInfo); + + completionHandler(result); + return; + } + + if (m_client.runJavaScriptConfirm_deprecatedForUseWithV0) { + bool result = m_client.runJavaScriptConfirm_deprecatedForUseWithV0(toAPI(page), toAPI(message.impl()), toAPI(frame), m_client.base.clientInfo); + + completionHandler(result); + return; + } + + completionHandler(false); + } + + virtual void runJavaScriptPrompt(WebPageProxy* page, const String& message, const String& defaultValue, WebFrameProxy* frame, const SecurityOriginData& securityOriginData, std::function<void (const String&)> completionHandler) override + { + if (m_client.runJavaScriptPrompt) { + RefPtr<RunJavaScriptPromptResultListener> listener = RunJavaScriptPromptResultListener::create(WTFMove(completionHandler)); + RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(securityOriginData.protocol, securityOriginData.host, securityOriginData.port); + m_client.runJavaScriptPrompt(toAPI(page), toAPI(message.impl()), toAPI(defaultValue.impl()), toAPI(frame), toAPI(securityOrigin.get()), toAPI(listener.get()), m_client.base.clientInfo); + return; + } + + if (m_client.runJavaScriptPrompt_deprecatedForUseWithV5) { + RefPtr<API::SecurityOrigin> securityOrigin = API::SecurityOrigin::create(securityOriginData.protocol, securityOriginData.host, securityOriginData.port); + RefPtr<API::String> string = adoptRef(toImpl(m_client.runJavaScriptPrompt_deprecatedForUseWithV5(toAPI(page), toAPI(message.impl()), toAPI(defaultValue.impl()), toAPI(frame), toAPI(securityOrigin.get()), m_client.base.clientInfo))); + + if (string) + completionHandler(string->string()); + else + completionHandler(String()); + return; + } + + if (m_client.runJavaScriptPrompt_deprecatedForUseWithV0) { + RefPtr<API::String> string = adoptRef(toImpl(m_client.runJavaScriptPrompt_deprecatedForUseWithV0(toAPI(page), toAPI(message.impl()), toAPI(defaultValue.impl()), toAPI(frame), m_client.base.clientInfo))); + + if (string) + completionHandler(string->string()); + else + completionHandler(String()); + return; + } + + completionHandler(String()); + } + + virtual void setStatusText(WebPageProxy* page, const String& text) override + { + if (!m_client.setStatusText) + return; + + m_client.setStatusText(toAPI(page), toAPI(text.impl()), m_client.base.clientInfo); + } + + virtual void mouseDidMoveOverElement(WebPageProxy* page, const WebHitTestResultData& data, WebEvent::Modifiers modifiers, API::Object* userData) override + { + if (!m_client.mouseDidMoveOverElement && !m_client.mouseDidMoveOverElement_deprecatedForUseWithV0) + return; + + if (m_client.base.version > 0 && !m_client.mouseDidMoveOverElement) + return; + + if (!m_client.base.version) { + m_client.mouseDidMoveOverElement_deprecatedForUseWithV0(toAPI(page), toAPI(modifiers), toAPI(userData), m_client.base.clientInfo); + return; + } + + RefPtr<API::HitTestResult> webHitTestResult = API::HitTestResult::create(data); + m_client.mouseDidMoveOverElement(toAPI(page), toAPI(webHitTestResult.get()), toAPI(modifiers), toAPI(userData), m_client.base.clientInfo); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + virtual void unavailablePluginButtonClicked(WebPageProxy* page, WKPluginUnavailabilityReason pluginUnavailabilityReason, API::Dictionary* pluginInformation) override + { + if (pluginUnavailabilityReason == kWKPluginUnavailabilityReasonPluginMissing) { + if (m_client.missingPluginButtonClicked_deprecatedForUseWithV0) + m_client.missingPluginButtonClicked_deprecatedForUseWithV0( + toAPI(page), + toAPI(pluginInformation->get<API::String>(pluginInformationMIMETypeKey())), + toAPI(pluginInformation->get<API::String>(pluginInformationPluginURLKey())), + toAPI(pluginInformation->get<API::String>(pluginInformationPluginspageAttributeURLKey())), + m_client.base.clientInfo); + } + + if (m_client.unavailablePluginButtonClicked_deprecatedForUseWithV1) + m_client.unavailablePluginButtonClicked_deprecatedForUseWithV1( + toAPI(page), + pluginUnavailabilityReason, + toAPI(pluginInformation->get<API::String>(pluginInformationMIMETypeKey())), + toAPI(pluginInformation->get<API::String>(pluginInformationPluginURLKey())), + toAPI(pluginInformation->get<API::String>(pluginInformationPluginspageAttributeURLKey())), + m_client.base.clientInfo); + + if (m_client.unavailablePluginButtonClicked) + m_client.unavailablePluginButtonClicked( + toAPI(page), + pluginUnavailabilityReason, + toAPI(pluginInformation), + m_client.base.clientInfo); + } +#endif // ENABLE(NETSCAPE_PLUGIN_API) + + virtual bool implementsDidNotHandleKeyEvent() const override + { + return m_client.didNotHandleKeyEvent; + } + + virtual void didNotHandleKeyEvent(WebPageProxy* page, const NativeWebKeyboardEvent& event) override + { + if (!m_client.didNotHandleKeyEvent) + return; + m_client.didNotHandleKeyEvent(toAPI(page), event.nativeEvent(), m_client.base.clientInfo); + } + + virtual bool implementsDidNotHandleWheelEvent() const override + { + return m_client.didNotHandleWheelEvent; + } + + virtual void didNotHandleWheelEvent(WebPageProxy* page, const NativeWebWheelEvent& event) override + { + if (!m_client.didNotHandleWheelEvent) + return; + m_client.didNotHandleWheelEvent(toAPI(page), event.nativeEvent(), m_client.base.clientInfo); + } + + virtual bool toolbarsAreVisible(WebPageProxy* page) override + { + if (!m_client.toolbarsAreVisible) + return true; + return m_client.toolbarsAreVisible(toAPI(page), m_client.base.clientInfo); + } + + virtual void setToolbarsAreVisible(WebPageProxy* page, bool visible) override + { + if (!m_client.setToolbarsAreVisible) + return; + m_client.setToolbarsAreVisible(toAPI(page), visible, m_client.base.clientInfo); + } + + virtual bool menuBarIsVisible(WebPageProxy* page) override + { + if (!m_client.menuBarIsVisible) + return true; + return m_client.menuBarIsVisible(toAPI(page), m_client.base.clientInfo); + } + + virtual void setMenuBarIsVisible(WebPageProxy* page, bool visible) override + { + if (!m_client.setMenuBarIsVisible) + return; + m_client.setMenuBarIsVisible(toAPI(page), visible, m_client.base.clientInfo); + } + + virtual bool statusBarIsVisible(WebPageProxy* page) override + { + if (!m_client.statusBarIsVisible) + return true; + return m_client.statusBarIsVisible(toAPI(page), m_client.base.clientInfo); + } + + virtual void setStatusBarIsVisible(WebPageProxy* page, bool visible) override + { + if (!m_client.setStatusBarIsVisible) + return; + m_client.setStatusBarIsVisible(toAPI(page), visible, m_client.base.clientInfo); + } + + virtual bool isResizable(WebPageProxy* page) override + { + if (!m_client.isResizable) + return true; + return m_client.isResizable(toAPI(page), m_client.base.clientInfo); + } + + virtual void setIsResizable(WebPageProxy* page, bool resizable) override + { + if (!m_client.setIsResizable) + return; + m_client.setIsResizable(toAPI(page), resizable, m_client.base.clientInfo); + } + + virtual void setWindowFrame(WebPageProxy* page, const FloatRect& frame) override + { + if (!m_client.setWindowFrame) + return; + + m_client.setWindowFrame(toAPI(page), toAPI(frame), m_client.base.clientInfo); + } + + virtual FloatRect windowFrame(WebPageProxy* page) override + { + if (!m_client.getWindowFrame) + return FloatRect(); + + return toFloatRect(m_client.getWindowFrame(toAPI(page), m_client.base.clientInfo)); + } + + virtual bool canRunBeforeUnloadConfirmPanel() const override + { + return m_client.runBeforeUnloadConfirmPanel_deprecatedForUseWithV6 || m_client.runBeforeUnloadConfirmPanel; + } + + virtual void runBeforeUnloadConfirmPanel(WebKit::WebPageProxy* page, const WTF::String& message, WebKit::WebFrameProxy* frame, std::function<void (bool)> completionHandler) override + { + if (m_client.runBeforeUnloadConfirmPanel) { + RefPtr<RunBeforeUnloadConfirmPanelResultListener> listener = RunBeforeUnloadConfirmPanelResultListener::create(WTFMove(completionHandler)); + m_client.runBeforeUnloadConfirmPanel(toAPI(page), toAPI(message.impl()), toAPI(frame), toAPI(listener.get()), m_client.base.clientInfo); + return; + } + + if (m_client.runBeforeUnloadConfirmPanel_deprecatedForUseWithV6) { + bool result = m_client.runBeforeUnloadConfirmPanel_deprecatedForUseWithV6(toAPI(page), toAPI(message.impl()), toAPI(frame), m_client.base.clientInfo); + completionHandler(result); + return; + } + + completionHandler(true); + } + + virtual void pageDidScroll(WebPageProxy* page) override + { + if (!m_client.pageDidScroll) + return; + + m_client.pageDidScroll(toAPI(page), m_client.base.clientInfo); + } + + virtual void exceededDatabaseQuota(WebPageProxy* page, WebFrameProxy* frame, API::SecurityOrigin* origin, const String& databaseName, const String& databaseDisplayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, std::function<void (unsigned long long)> completionHandler) override + { + if (!m_client.exceededDatabaseQuota) { + completionHandler(currentQuota); + return; + } + + completionHandler(m_client.exceededDatabaseQuota(toAPI(page), toAPI(frame), toAPI(origin), toAPI(databaseName.impl()), toAPI(databaseDisplayName.impl()), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage, m_client.base.clientInfo)); + } + + virtual bool runOpenPanel(WebPageProxy* page, WebFrameProxy* frame, WebOpenPanelParameters* parameters, WebOpenPanelResultListenerProxy* listener) override + { + if (!m_client.runOpenPanel) + return false; + + m_client.runOpenPanel(toAPI(page), toAPI(frame), toAPI(parameters), toAPI(listener), m_client.base.clientInfo); + return true; + } + + virtual bool decidePolicyForGeolocationPermissionRequest(WebPageProxy* page, WebFrameProxy* frame, API::SecurityOrigin* origin, GeolocationPermissionRequestProxy* permissionRequest) override + { + if (!m_client.decidePolicyForGeolocationPermissionRequest) + return false; + + m_client.decidePolicyForGeolocationPermissionRequest(toAPI(page), toAPI(frame), toAPI(origin), toAPI(permissionRequest), m_client.base.clientInfo); + return true; + } + + virtual bool decidePolicyForUserMediaPermissionRequest(WebPageProxy& page, WebFrameProxy& frame, API::SecurityOrigin& origin, UserMediaPermissionRequestProxy& permissionRequest) override + { + if (!m_client.decidePolicyForUserMediaPermissionRequest) + return false; + + m_client.decidePolicyForUserMediaPermissionRequest(toAPI(&page), toAPI(&frame), toAPI(&origin), toAPI(&permissionRequest), m_client.base.clientInfo); + return true; + } + + virtual bool checkUserMediaPermissionForOrigin(WebPageProxy& page, WebFrameProxy& frame, API::SecurityOrigin& origin, UserMediaPermissionCheckProxy& request) override + { + if (!m_client.checkUserMediaPermissionForOrigin) + return false; + + m_client.checkUserMediaPermissionForOrigin(toAPI(&page), toAPI(&frame), toAPI(&origin), toAPI(&request), m_client.base.clientInfo); + return true; + } + + virtual bool decidePolicyForNotificationPermissionRequest(WebPageProxy* page, API::SecurityOrigin* origin, NotificationPermissionRequest* permissionRequest) override + { + if (!m_client.decidePolicyForNotificationPermissionRequest) + return false; + + m_client.decidePolicyForNotificationPermissionRequest(toAPI(page), toAPI(origin), toAPI(permissionRequest), m_client.base.clientInfo); + return true; + } + + // Printing. + virtual float headerHeight(WebPageProxy* page, WebFrameProxy* frame) override + { + if (!m_client.headerHeight) + return 0; + + return m_client.headerHeight(toAPI(page), toAPI(frame), m_client.base.clientInfo); + } + + virtual float footerHeight(WebPageProxy* page, WebFrameProxy* frame) override + { + if (!m_client.footerHeight) + return 0; + + return m_client.footerHeight(toAPI(page), toAPI(frame), m_client.base.clientInfo); + } + + virtual void drawHeader(WebPageProxy* page, WebFrameProxy* frame, const WebCore::FloatRect& rect) override + { + if (!m_client.drawHeader) + return; + + m_client.drawHeader(toAPI(page), toAPI(frame), toAPI(rect), m_client.base.clientInfo); + } + + virtual void drawFooter(WebPageProxy* page, WebFrameProxy* frame, const WebCore::FloatRect& rect) override + { + if (!m_client.drawFooter) + return; + + m_client.drawFooter(toAPI(page), toAPI(frame), toAPI(rect), m_client.base.clientInfo); + } + + virtual void printFrame(WebPageProxy* page, WebFrameProxy* frame) override + { + if (!m_client.printFrame) + return; + + m_client.printFrame(toAPI(page), toAPI(frame), m_client.base.clientInfo); + } + + virtual bool canRunModal() const override + { + return m_client.runModal; + } + + virtual void runModal(WebPageProxy* page) override + { + if (!m_client.runModal) + return; + + m_client.runModal(toAPI(page), m_client.base.clientInfo); + } + + virtual void saveDataToFileInDownloadsFolder(WebPageProxy* page, const String& suggestedFilename, const String& mimeType, const String& originatingURLString, API::Data* data) override + { + if (!m_client.saveDataToFileInDownloadsFolder) + return; + + m_client.saveDataToFileInDownloadsFolder(toAPI(page), toAPI(suggestedFilename.impl()), toAPI(mimeType.impl()), toURLRef(originatingURLString.impl()), toAPI(data), m_client.base.clientInfo); + } + + virtual void pinnedStateDidChange(WebPageProxy& page) override + { + if (!m_client.pinnedStateDidChange) + return; + + m_client.pinnedStateDidChange(toAPI(&page), m_client.base.clientInfo); + } + + virtual void isPlayingAudioDidChange(WebPageProxy& page) override + { + if (!m_client.isPlayingAudioDidChange) + return; + + m_client.isPlayingAudioDidChange(toAPI(&page), m_client.base.clientInfo); + } + + virtual void didClickAutoFillButton(WebPageProxy& page, API::Object* userInfo) override + { + if (!m_client.didClickAutoFillButton) + return; + + m_client.didClickAutoFillButton(toAPI(&page), toAPI(userInfo), m_client.base.clientInfo); + } + +#if ENABLE(MEDIA_SESSION) + virtual void mediaSessionMetadataDidChange(WebPageProxy& page, WebMediaSessionMetadata* metadata) override + { + if (!m_client.mediaSessionMetadataDidChange) + return; + + m_client.mediaSessionMetadataDidChange(toAPI(&page), toAPI(metadata), m_client.base.clientInfo); + } +#endif + }; + + toImpl(pageRef)->setUIClient(std::make_unique<UIClient>(wkClient)); +} + +void WKPageSetPageNavigationClient(WKPageRef pageRef, const WKPageNavigationClientBase* wkClient) +{ + class NavigationClient : public API::Client<WKPageNavigationClientBase>, public API::NavigationClient { + public: + explicit NavigationClient(const WKPageNavigationClientBase* client) + { + initialize(client); + } + + private: + virtual void decidePolicyForNavigationAction(WebPageProxy& page, API::NavigationAction& navigationAction, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object* userData) override + { + if (!m_client.decidePolicyForNavigationAction) + return; + m_client.decidePolicyForNavigationAction(toAPI(&page), toAPI(&navigationAction), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + } + + virtual void decidePolicyForNavigationResponse(WebPageProxy& page, API::NavigationResponse& navigationResponse, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, API::Object* userData) override + { + if (!m_client.decidePolicyForNavigationResponse) + return; + m_client.decidePolicyForNavigationResponse(toAPI(&page), toAPI(&navigationResponse), toAPI(listener.ptr()), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didStartProvisionalNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object* userData) override + { + if (!m_client.didStartProvisionalNavigation) + return; + m_client.didStartProvisionalNavigation(toAPI(&page), toAPI(navigation), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didReceiveServerRedirectForProvisionalNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object* userData) override + { + if (!m_client.didReceiveServerRedirectForProvisionalNavigation) + return; + m_client.didReceiveServerRedirectForProvisionalNavigation(toAPI(&page), toAPI(navigation), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFailProvisionalNavigationWithError(WebPageProxy& page, WebFrameProxy&, API::Navigation* navigation, const WebCore::ResourceError& error, API::Object* userData) override + { + if (!m_client.didFailProvisionalNavigation) + return; + m_client.didFailProvisionalNavigation(toAPI(&page), toAPI(navigation), toAPI(error), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didCommitNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object* userData) override + { + if (!m_client.didCommitNavigation) + return; + m_client.didCommitNavigation(toAPI(&page), toAPI(navigation), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFinishNavigation(WebPageProxy& page, API::Navigation* navigation, API::Object* userData) override + { + if (!m_client.didFinishNavigation) + return; + m_client.didFinishNavigation(toAPI(&page), toAPI(navigation), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFailNavigationWithError(WebPageProxy& page, WebFrameProxy&, API::Navigation* navigation, const WebCore::ResourceError& error, API::Object* userData) override + { + if (!m_client.didFailNavigation) + return; + m_client.didFailNavigation(toAPI(&page), toAPI(navigation), toAPI(error), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFailProvisionalLoadInSubframeWithError(WebPageProxy& page, WebFrameProxy& subframe, const WebCore::SecurityOriginData& securityOriginData, API::Navigation* navigation, const WebCore::ResourceError& error, API::Object* userData) override + { + if (!m_client.didFailProvisionalLoadInSubframe) + return; + m_client.didFailProvisionalLoadInSubframe(toAPI(&page), toAPI(navigation), toAPI(API::FrameInfo::create(subframe, securityOriginData.securityOrigin()).ptr()), toAPI(error), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didFinishDocumentLoad(WebPageProxy& page, API::Navigation* navigation, API::Object* userData) override + { + if (!m_client.didFinishDocumentLoad) + return; + m_client.didFinishDocumentLoad(toAPI(&page), toAPI(navigation), toAPI(userData), m_client.base.clientInfo); + } + + virtual void didSameDocumentNavigation(WebPageProxy& page, API::Navigation* navigation, WebKit::SameDocumentNavigationType navigationType, API::Object* userData) override + { + if (!m_client.didSameDocumentNavigation) + return; + m_client.didSameDocumentNavigation(toAPI(&page), toAPI(navigation), toAPI(navigationType), toAPI(userData), m_client.base.clientInfo); + } + + virtual void renderingProgressDidChange(WebPageProxy& page, WebCore::LayoutMilestones milestones) override + { + if (!m_client.renderingProgressDidChange) + return; + m_client.renderingProgressDidChange(toAPI(&page), pageRenderingProgressEvents(milestones), nullptr, m_client.base.clientInfo); + } + + virtual bool canAuthenticateAgainstProtectionSpace(WebPageProxy& page, WebProtectionSpace* protectionSpace) override + { + if (!m_client.canAuthenticateAgainstProtectionSpace) + return false; + return m_client.canAuthenticateAgainstProtectionSpace(toAPI(&page), toAPI(protectionSpace), m_client.base.clientInfo); + } + + virtual void didReceiveAuthenticationChallenge(WebPageProxy& page, AuthenticationChallengeProxy* authenticationChallenge) override + { + if (!m_client.didReceiveAuthenticationChallenge) + return; + m_client.didReceiveAuthenticationChallenge(toAPI(&page), toAPI(authenticationChallenge), m_client.base.clientInfo); + } + + virtual void processDidCrash(WebPageProxy& page) override + { + if (!m_client.webProcessDidCrash) + return; + m_client.webProcessDidCrash(toAPI(&page), m_client.base.clientInfo); + } + + virtual RefPtr<API::Data> webCryptoMasterKey(WebPageProxy& page) override + { + if (!m_client.copyWebCryptoMasterKey) + return nullptr; + return adoptRef(toImpl(m_client.copyWebCryptoMasterKey(toAPI(&page), m_client.base.clientInfo))); + } + + virtual void didBeginNavigationGesture(WebPageProxy& page) override + { + if (!m_client.didBeginNavigationGesture) + return; + m_client.didBeginNavigationGesture(toAPI(&page), m_client.base.clientInfo); + } + + virtual void didEndNavigationGesture(WebPageProxy& page, bool willNavigate, WebKit::WebBackForwardListItem& item) override + { + if (!m_client.didEndNavigationGesture) + return; + m_client.didEndNavigationGesture(toAPI(&page), willNavigate ? toAPI(&item) : nullptr, m_client.base.clientInfo); + } + + virtual void willEndNavigationGesture(WebPageProxy& page, bool willNavigate, WebKit::WebBackForwardListItem& item) override + { + if (!m_client.willEndNavigationGesture) + return; + m_client.willEndNavigationGesture(toAPI(&page), willNavigate ? toAPI(&item) : nullptr, m_client.base.clientInfo); + } + + virtual void didRemoveNavigationGestureSnapshot(WebPageProxy& page) override + { + if (!m_client.didRemoveNavigationGestureSnapshot) + return; + m_client.didRemoveNavigationGestureSnapshot(toAPI(&page), m_client.base.clientInfo); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + virtual PluginModuleLoadPolicy decidePolicyForPluginLoad(WebPageProxy& page, PluginModuleLoadPolicy currentPluginLoadPolicy, API::Dictionary* pluginInformation, String& unavailabilityDescription) override + { + WKStringRef unavailabilityDescriptionOut = 0; + PluginModuleLoadPolicy loadPolicy = currentPluginLoadPolicy; + + if (m_client.decidePolicyForPluginLoad) + loadPolicy = toPluginModuleLoadPolicy(m_client.decidePolicyForPluginLoad(toAPI(&page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), &unavailabilityDescriptionOut, m_client.base.clientInfo)); + + if (unavailabilityDescriptionOut) { + RefPtr<API::String> webUnavailabilityDescription = adoptRef(toImpl(unavailabilityDescriptionOut)); + unavailabilityDescription = webUnavailabilityDescription->string(); + } + + return loadPolicy; + } +#endif + }; + + WebPageProxy* webPageProxy = toImpl(pageRef); + + auto navigationClient = std::make_unique<NavigationClient>(wkClient); + webPageProxy->setNavigationClient(WTFMove(navigationClient)); +} + +void WKPageSetSession(WKPageRef pageRef, WKSessionRef session) +{ + toImpl(pageRef)->setSessionID(toImpl(session)->getID()); +} + +void WKPageRunJavaScriptInMainFrame(WKPageRef pageRef, WKStringRef scriptRef, void* context, WKPageRunJavaScriptFunction callback) { - toImpl(pageRef)->getSourceForFrame(toImpl(frameRef), StringCallback::create(context, callback)); + toImpl(pageRef)->runJavaScriptInMainFrame(toImpl(scriptRef)->string(), [context, callback](API::SerializedScriptValue* returnValue, bool, const WebCore::ExceptionDetails&, CallbackBase::Error error) { + callback(toAPI(returnValue), (error != CallbackBase::Error::None) ? toAPI(API::Error::create().ptr()) : 0, context); + }); } #ifdef __BLOCKS__ -static void callGetSourceForFrameBlockBlockAndDispose(WKStringRef resultValue, WKErrorRef error, void* context) +static void callRunJavaScriptBlockAndRelease(WKSerializedScriptValueRef resultValue, WKErrorRef error, void* context) { - WKPageGetSourceForFrameBlock block = (WKPageGetSourceForFrameBlock)context; + WKPageRunJavaScriptBlock block = (WKPageRunJavaScriptBlock)context; block(resultValue, error); Block_release(block); } -void WKPageGetSourceForFrame_b(WKPageRef pageRef, WKFrameRef frameRef, WKPageGetSourceForFrameBlock block) +void WKPageRunJavaScriptInMainFrame_b(WKPageRef pageRef, WKStringRef scriptRef, WKPageRunJavaScriptBlock block) { - WKPageGetSourceForFrame(pageRef, frameRef, Block_copy(block), callGetSourceForFrameBlockBlockAndDispose); + WKPageRunJavaScriptInMainFrame(pageRef, scriptRef, Block_copy(block), callRunJavaScriptBlockAndRelease); } #endif +static std::function<void (const String&, WebKit::CallbackBase::Error)> toGenericCallbackFunction(void* context, void (*callback)(WKStringRef, WKErrorRef, void*)) +{ + return [context, callback](const String& returnValue, WebKit::CallbackBase::Error error) { + callback(toAPI(API::String::create(returnValue).ptr()), error != WebKit::CallbackBase::Error::None ? toAPI(API::Error::create().ptr()) : 0, context); + }; +} + +void WKPageRenderTreeExternalRepresentation(WKPageRef pageRef, void* context, WKPageRenderTreeExternalRepresentationFunction callback) +{ + toImpl(pageRef)->getRenderTreeExternalRepresentation(toGenericCallbackFunction(context, callback)); +} + +void WKPageGetSourceForFrame(WKPageRef pageRef, WKFrameRef frameRef, void* context, WKPageGetSourceForFrameFunction callback) +{ + toImpl(pageRef)->getSourceForFrame(toImpl(frameRef), toGenericCallbackFunction(context, callback)); +} + void WKPageGetContentsAsString(WKPageRef pageRef, void* context, WKPageGetContentsAsStringFunction callback) { - toImpl(pageRef)->getContentsAsString(StringCallback::create(context, callback)); + toImpl(pageRef)->getContentsAsString(toGenericCallbackFunction(context, callback)); } -#ifdef __BLOCKS__ -static void callContentsAsStringBlockBlockAndDispose(WKStringRef resultValue, WKErrorRef error, void* context) +void WKPageGetBytecodeProfile(WKPageRef pageRef, void* context, WKPageGetBytecodeProfileFunction callback) { - WKPageGetContentsAsStringBlock block = (WKPageGetContentsAsStringBlock)context; - block(resultValue, error); - Block_release(block); + toImpl(pageRef)->getBytecodeProfile(toGenericCallbackFunction(context, callback)); } -void WKPageGetContentsAsString_b(WKPageRef pageRef, WKPageGetSourceForFrameBlock block) +void WKPageIsWebProcessResponsive(WKPageRef pageRef, void* context, WKPageIsWebProcessResponsiveFunction callback) { - WKPageGetContentsAsString(pageRef, Block_copy(block), callContentsAsStringBlockBlockAndDispose); + toImpl(pageRef)->isWebProcessResponsive([context, callback](bool isWebProcessResponsive) { + callback(isWebProcessResponsive, context); + }); } -#endif void WKPageGetSelectionAsWebArchiveData(WKPageRef pageRef, void* context, WKPageGetSelectionAsWebArchiveDataFunction callback) { - toImpl(pageRef)->getSelectionAsWebArchiveData(DataCallback::create(context, callback)); + toImpl(pageRef)->getSelectionAsWebArchiveData(toGenericCallbackFunction(context, callback)); } -void WKPageGetContentsAsMHTMLData(WKPageRef pageRef, bool useBinaryEncoding, void* context, WKPageGetContentsAsMHTMLDataFunction callback) +void WKPageGetContentsAsMHTMLData(WKPageRef pageRef, void* context, WKPageGetContentsAsMHTMLDataFunction callback) { #if ENABLE(MHTML) - toImpl(pageRef)->getContentsAsMHTMLData(DataCallback::create(context, callback), useBinaryEncoding); + toImpl(pageRef)->getContentsAsMHTMLData(toGenericCallbackFunction(context, callback)); #else UNUSED_PARAM(pageRef); - UNUSED_PARAM(useBinaryEncoding); UNUSED_PARAM(context); UNUSED_PARAM(callback); #endif @@ -741,39 +2443,34 @@ void WKPageGetContentsAsMHTMLData(WKPageRef pageRef, bool useBinaryEncoding, voi void WKPageForceRepaint(WKPageRef pageRef, void* context, WKPageForceRepaintFunction callback) { - toImpl(pageRef)->forceRepaint(VoidCallback::create(context, callback)); + toImpl(pageRef)->forceRepaint(VoidCallback::create([context, callback](WebKit::CallbackBase::Error error) { + callback(error == WebKit::CallbackBase::Error::None ? nullptr : toAPI(API::Error::create().ptr()), context); + })); } WK_EXPORT WKURLRef WKPageCopyPendingAPIRequestURL(WKPageRef pageRef) { - if (toImpl(pageRef)->pendingAPIRequestURL().isNull()) - return 0; - return toCopiedURLAPI(toImpl(pageRef)->pendingAPIRequestURL()); + const String& pendingAPIRequestURL = toImpl(pageRef)->pageLoadState().pendingAPIRequestURL(); + + if (pendingAPIRequestURL.isNull()) + return nullptr; + + return toCopiedURLAPI(pendingAPIRequestURL); } WKURLRef WKPageCopyActiveURL(WKPageRef pageRef) { - return toCopiedURLAPI(toImpl(pageRef)->activeURL()); + return toCopiedURLAPI(toImpl(pageRef)->pageLoadState().activeURL()); } WKURLRef WKPageCopyProvisionalURL(WKPageRef pageRef) { - return toCopiedURLAPI(toImpl(pageRef)->provisionalURL()); + return toCopiedURLAPI(toImpl(pageRef)->pageLoadState().provisionalURL()); } WKURLRef WKPageCopyCommittedURL(WKPageRef pageRef) { - return toCopiedURLAPI(toImpl(pageRef)->committedURL()); -} - -void WKPageSetDebugPaintFlags(WKPageDebugPaintFlags flags) -{ - WebPageProxy::setDebugPaintFlags(flags); -} - -WKPageDebugPaintFlags WKPageGetDebugPaintFlags() -{ - return WebPageProxy::debugPaintFlags(); + return toCopiedURLAPI(toImpl(pageRef)->pageLoadState().url()); } WKStringRef WKPageCopyStandardUserAgentWithApplicationName(WKStringRef applicationName) @@ -783,7 +2480,9 @@ WKStringRef WKPageCopyStandardUserAgentWithApplicationName(WKStringRef applicati void WKPageValidateCommand(WKPageRef pageRef, WKStringRef command, void* context, WKPageValidateCommandCallback callback) { - toImpl(pageRef)->validateCommand(toImpl(command)->string(), ValidateCommandCallback::create(context, callback)); + toImpl(pageRef)->validateCommand(toImpl(command)->string(), [context, callback](const String& commandName, bool isEnabled, int32_t state, WebKit::CallbackBase::Error error) { + callback(toAPI(API::String::create(commandName).ptr()), isEnabled, state, error != WebKit::CallbackBase::Error::None ? toAPI(API::Error::create().ptr()) : 0, context); + }); } void WKPageExecuteCommand(WKPageRef pageRef, WKStringRef command) @@ -791,26 +2490,7 @@ void WKPageExecuteCommand(WKPageRef pageRef, WKStringRef command) toImpl(pageRef)->executeEditCommand(toImpl(command)->string()); } -#if PLATFORM(MAC) -struct ComputedPagesContext { - ComputedPagesContext(WKPageComputePagesForPrintingFunction callback, void* context) - : callback(callback) - , context(context) - { - } - WKPageComputePagesForPrintingFunction callback; - void* context; -}; - -static void computedPagesCallback(const Vector<WebCore::IntRect>& rects, double scaleFactor, WKErrorRef error, void* untypedContext) -{ - OwnPtr<ComputedPagesContext> context = adoptPtr(static_cast<ComputedPagesContext*>(untypedContext)); - Vector<WKRect> wkRects(rects.size()); - for (size_t i = 0; i < rects.size(); ++i) - wkRects[i] = toAPI(rects[i]); - context->callback(wkRects.data(), wkRects.size(), scaleFactor, error, context->context); -} - +#if PLATFORM(COCOA) static PrintInfo printInfoFromWKPrintInfo(const WKPrintInfo& printInfo) { PrintInfo result; @@ -822,7 +2502,12 @@ static PrintInfo printInfoFromWKPrintInfo(const WKPrintInfo& printInfo) void WKPageComputePagesForPrinting(WKPageRef page, WKFrameRef frame, WKPrintInfo printInfo, WKPageComputePagesForPrintingFunction callback, void* context) { - toImpl(page)->computePagesForPrinting(toImpl(frame), printInfoFromWKPrintInfo(printInfo), ComputedPagesCallback::create(new ComputedPagesContext(callback, context), computedPagesCallback)); + toImpl(page)->computePagesForPrinting(toImpl(frame), printInfoFromWKPrintInfo(printInfo), ComputedPagesCallback::create([context, callback](const Vector<WebCore::IntRect>& rects, double scaleFactor, WebKit::CallbackBase::Error error) { + Vector<WKRect> wkRects(rects.size()); + for (size_t i = 0; i < rects.size(); ++i) + wkRects[i] = toAPI(rects[i]); + callback(wkRects.data(), wkRects.size(), scaleFactor, error != WebKit::CallbackBase::Error::None ? toAPI(API::Error::create().ptr()) : 0, context); + })); } void WKPageBeginPrinting(WKPageRef page, WKFrameRef frame, WKPrintInfo printInfo) @@ -832,7 +2517,7 @@ void WKPageBeginPrinting(WKPageRef page, WKFrameRef frame, WKPrintInfo printInfo void WKPageDrawPagesToPDF(WKPageRef page, WKFrameRef frame, WKPrintInfo printInfo, uint32_t first, uint32_t count, WKPageDrawToPDFFunction callback, void* context) { - toImpl(page)->drawPagesToPDF(toImpl(frame), printInfoFromWKPrintInfo(printInfo), first, count, DataCallback::create(context, callback)); + toImpl(page)->drawPagesToPDF(toImpl(frame), printInfoFromWKPrintInfo(printInfo), first, count, DataCallback::create(toGenericCallbackFunction(context, callback))); } void WKPageEndPrinting(WKPageRef page) @@ -841,14 +2526,24 @@ void WKPageEndPrinting(WKPageRef page) } #endif -WKImageRef WKPageCreateSnapshotOfVisibleContent(WKPageRef) +bool WKPageGetAllowsRemoteInspection(WKPageRef page) { - return 0; +#if ENABLE(REMOTE_INSPECTOR) + return toImpl(page)->allowsRemoteInspection(); +#else + UNUSED_PARAM(page); + return false; +#endif } -void WKPageSetShouldSendEventsSynchronously(WKPageRef page, bool sync) +void WKPageSetAllowsRemoteInspection(WKPageRef page, bool allow) { - toImpl(page)->setShouldSendEventsSynchronously(sync); +#if ENABLE(REMOTE_INSPECTOR) + toImpl(page)->setAllowsRemoteInspection(allow); +#else + UNUSED_PARAM(page); + UNUSED_PARAM(allow); +#endif } void WKPageSetMediaVolume(WKPageRef page, float volume) @@ -856,6 +2551,48 @@ void WKPageSetMediaVolume(WKPageRef page, float volume) toImpl(page)->setMediaVolume(volume); } +void WKPageSetMuted(WKPageRef page, bool muted) +{ + toImpl(page)->setMuted(muted); +} + +bool WKPageHasMediaSessionWithActiveMediaElements(WKPageRef page) +{ +#if ENABLE(MEDIA_SESSION) + return toImpl(page)->hasMediaSessionWithActiveMediaElements(); +#else + UNUSED_PARAM(page); + return false; +#endif +} + +void WKPageHandleMediaEvent(WKPageRef page, WKMediaEventType wkEventType) +{ +#if ENABLE(MEDIA_SESSION) + MediaEventType eventType; + + switch (wkEventType) { + case kWKMediaEventTypePlayPause: + eventType = MediaEventType::PlayPause; + break; + case kWKMediaEventTypeTrackNext: + eventType = MediaEventType::TrackNext; + break; + case kWKMediaEventTypeTrackPrevious: + eventType = MediaEventType::TrackPrevious; + break; + default: + ASSERT_NOT_REACHED(); + return; + } + + toImpl(page)->handleMediaEvent(eventType); +#else + UNUSED_PARAM(page); + UNUSED_PARAM(wkEventType); +#endif +} + void WKPagePostMessageToInjectedBundle(WKPageRef pageRef, WKStringRef messageNameRef, WKTypeRef messageBodyRef) { toImpl(pageRef)->postMessageToInjectedBundle(toImpl(messageNameRef)->string(), toImpl(messageBodyRef)); @@ -863,7 +2600,14 @@ void WKPagePostMessageToInjectedBundle(WKPageRef pageRef, WKStringRef messageNam WKArrayRef WKPageCopyRelatedPages(WKPageRef pageRef) { - return toAPI(toImpl(pageRef)->relatedPages().leakRef()); + Vector<RefPtr<API::Object>> relatedPages; + + for (auto& page : toImpl(pageRef)->process().pages()) { + if (page != toImpl(pageRef)) + relatedPages.append(page); + } + + return toAPI(&API::Array::create(WTFMove(relatedPages)).leakRef()); } void WKPageSetMayStartMediaWhenInWindow(WKPageRef pageRef, bool mayStartMedia) @@ -875,7 +2619,10 @@ void WKPageSetMayStartMediaWhenInWindow(WKPageRef pageRef, bool mayStartMedia) void WKPageSelectContextMenuItem(WKPageRef page, WKContextMenuItemRef item) { #if ENABLE(CONTEXT_MENUS) - toImpl(page)->contextMenuItemSelected(*(toImpl(item)->data())); + toImpl(page)->contextMenuItemSelected((toImpl(item)->data())); +#else + UNUSED_PARAM(page); + UNUSED_PARAM(item); #endif } @@ -884,11 +2631,11 @@ WKScrollPinningBehavior WKPageGetScrollPinningBehavior(WKPageRef page) ScrollPinningBehavior pinning = toImpl(page)->scrollPinningBehavior(); switch (pinning) { - case DoNotPin: + case WebCore::ScrollPinningBehavior::DoNotPin: return kWKScrollPinningBehaviorDoNotPin; - case PinToTop: + case WebCore::ScrollPinningBehavior::PinToTop: return kWKScrollPinningBehaviorPinToTop; - case PinToBottom: + case WebCore::ScrollPinningBehavior::PinToBottom: return kWKScrollPinningBehaviorPinToBottom; } @@ -898,17 +2645,17 @@ WKScrollPinningBehavior WKPageGetScrollPinningBehavior(WKPageRef page) void WKPageSetScrollPinningBehavior(WKPageRef page, WKScrollPinningBehavior pinning) { - ScrollPinningBehavior corePinning = DoNotPin; + ScrollPinningBehavior corePinning = ScrollPinningBehavior::DoNotPin; switch (pinning) { case kWKScrollPinningBehaviorDoNotPin: - corePinning = DoNotPin; + corePinning = ScrollPinningBehavior::DoNotPin; break; case kWKScrollPinningBehaviorPinToTop: - corePinning = PinToTop; + corePinning = ScrollPinningBehavior::PinToTop; break; case kWKScrollPinningBehaviorPinToBottom: - corePinning = PinToBottom; + corePinning = ScrollPinningBehavior::PinToBottom; break; default: ASSERT_NOT_REACHED(); @@ -917,15 +2664,37 @@ void WKPageSetScrollPinningBehavior(WKPageRef page, WKScrollPinningBehavior pinn toImpl(page)->setScrollPinningBehavior(corePinning); } +bool WKPageGetAddsVisitedLinks(WKPageRef page) +{ + return toImpl(page)->addsVisitedLinks(); +} +void WKPageSetAddsVisitedLinks(WKPageRef page, bool addsVisitedLinks) +{ + toImpl(page)->setAddsVisitedLinks(addsVisitedLinks); +} -// -- DEPRECATED -- +bool WKPageIsPlayingAudio(WKPageRef page) +{ + return toImpl(page)->isPlayingAudio(); +} + +void WKPageClearWheelEventTestTrigger(WKPageRef pageRef) +{ + toImpl(pageRef)->clearWheelEventTestTrigger(); +} -void WKPageSetInvalidMessageFunction(WKPageInvalidMessageFunction) +void WKPageCallAfterNextPresentationUpdate(WKPageRef pageRef, void* context, WKPagePostPresentationUpdateFunction callback) { - // FIXME: Remove this function when doing so won't break WebKit nightlies. + toImpl(pageRef)->callAfterNextPresentationUpdate([context, callback](WebKit::CallbackBase::Error error) { + callback(error != WebKit::CallbackBase::Error::None ? toAPI(API::Error::create().ptr()) : 0, context); + }); } +#if ENABLE(NETSCAPE_PLUGIN_API) + +// -- DEPRECATED -- + WKStringRef WKPageGetPluginInformationBundleIdentifierKey() { return WKPluginInformationBundleIdentifierKey(); @@ -968,3 +2737,4 @@ WKStringRef WKPageGetPluginInformationPluginURLKey() // -- DEPRECATED -- +#endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebKit2/UIProcess/API/C/WKPage.h b/Source/WebKit2/UIProcess/API/C/WKPage.h index dc57c523d..59709495d 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPage.h +++ b/Source/WebKit2/UIProcess/API/C/WKPage.h @@ -26,14 +26,25 @@ #ifndef WKPage_h #define WKPage_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKError.h> -#include <WebKit2/WKEvent.h> -#include <WebKit2/WKFindOptions.h> -#include <WebKit2/WKGeometry.h> -#include <WebKit2/WKNativeEvent.h> -#include <WebKit2/WKPageLoadTypes.h> -#include <WebKit2/WKPageVisibilityTypes.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKErrorRef.h> +#include <WebKit/WKEvent.h> +#include <WebKit/WKFindOptions.h> +#include <WebKit/WKGeometry.h> +#include <WebKit/WKNativeEvent.h> +#include <WebKit/WKPageContextMenuClient.h> +#include <WebKit/WKPageDiagnosticLoggingClient.h> +#include <WebKit/WKPageFindClient.h> +#include <WebKit/WKPageFindMatchesClient.h> +#include <WebKit/WKPageFormClient.h> +#include <WebKit/WKPageInjectedBundleClient.h> +#include <WebKit/WKPageLoadTypes.h> +#include <WebKit/WKPageLoaderClient.h> +#include <WebKit/WKPageNavigationClient.h> +#include <WebKit/WKPagePolicyClient.h> +#include <WebKit/WKPageUIClient.h> +#include <WebKit/WKPageVisibilityTypes.h> +#include <WebKit/WKSessionRef.h> #ifndef __cplusplus #include <stdbool.h> @@ -43,324 +54,13 @@ extern "C" { #endif -enum { - kWKFocusDirectionBackward = 0, - kWKFocusDirectionForward = 1 -}; -typedef uint32_t WKFocusDirection; - -enum { - kWKPluginLoadPolicyLoadNormally = 0, - kWKPluginLoadPolicyBlocked, - kWKPluginLoadPolicyInactive, - kWKPluginLoadPolicyLoadUnsandboxed, -}; -typedef uint32_t WKPluginLoadPolicy; - -typedef void (*WKPageCallback)(WKPageRef page, const void* clientInfo); - -// FrameLoad Client -typedef void (*WKPageDidStartProvisionalLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidFailProvisionalLoadWithErrorForFrameCallback)(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidCommitLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidFinishDocumentLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidFinishLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidFailLoadWithErrorForFrameCallback)(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidSameDocumentNavigationForFrameCallback)(WKPageRef page, WKFrameRef frame, WKSameDocumentNavigationType type, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidReceiveTitleForFrameCallback)(WKPageRef page, WKStringRef title, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidFirstLayoutForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidRemoveFrameFromHierarchyCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidDisplayInsecureContentForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidRunInsecureContentForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidDetectXSSForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); -typedef bool (*WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback)(WKPageRef page, WKFrameRef frame, WKProtectionSpaceRef protectionSpace, const void *clientInfo); -typedef void (*WKPageDidReceiveAuthenticationChallengeInFrameCallback)(WKPageRef page, WKFrameRef frame, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo); -typedef void (*WKPageDidChangeBackForwardListCallback)(WKPageRef page, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void *clientInfo); -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 (*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; - const void * clientInfo; - WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; - WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; - WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; - WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; - WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; - WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; - WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; - WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; - WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; - WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; - WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; - WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; - WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; - WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; - WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; - WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; - - // FIXME: Move to progress client. - WKPageCallback didStartProgress; - WKPageCallback didChangeProgress; - WKPageCallback didFinishProgress; - - // FIXME: These three functions should not be part of this client. - WKPageCallback processDidBecomeUnresponsive; - WKPageCallback processDidBecomeResponsive; - WKPageCallback processDidCrash; - WKPageDidChangeBackForwardListCallback didChangeBackForwardList; - WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; - WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; - - // Version 1 - WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; - - // FIXME: didNewFirstVisuallyNonEmptyLayout should be removed. We should consider removing didFirstVisuallyNonEmptyLayoutForFrame - // as well. Their functionality is replaced by didLayout. - WKPageDidNewFirstVisuallyNonEmptyLayoutCallback didNewFirstVisuallyNonEmptyLayout; - - WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; - - WKPageCallback interactionOccurredWhileProcessUnresponsive; - WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; - - // Version 2 - 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 = 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); -typedef void (*WKPageDecidePolicyForNewWindowActionCallback)(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKStringRef frameName, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); -typedef void (*WKPageDecidePolicyForResponseCallback)(WKPageRef page, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); -typedef void (*WKPageUnableToImplementPolicyCallback)(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void* clientInfo); - -struct WKPagePolicyClient { - int version; - const void * clientInfo; - WKPageDecidePolicyForNavigationActionCallback decidePolicyForNavigationAction; - WKPageDecidePolicyForNewWindowActionCallback decidePolicyForNewWindowAction; - WKPageDecidePolicyForResponseCallback decidePolicyForResponse; - WKPageUnableToImplementPolicyCallback unableToImplementPolicy; -}; -typedef struct WKPagePolicyClient WKPagePolicyClient; - -enum { kWKPagePolicyClientCurrentVersion = 0 }; - -// Form Client. -typedef void (*WKPageWillSubmitFormCallback)(WKPageRef page, WKFrameRef frame, WKFrameRef sourceFrame, WKDictionaryRef values, WKTypeRef userData, WKFormSubmissionListenerRef listener, const void* clientInfo); - -struct WKPageFormClient { - int version; - const void * clientInfo; - WKPageWillSubmitFormCallback willSubmitForm; -}; -typedef struct WKPageFormClient WKPageFormClient; - -enum { kWKPageFormClientCurrentVersion = 0 }; - -enum { - kWKPluginUnavailabilityReasonPluginMissing, - kWKPluginUnavailabilityReasonPluginCrashed, - kWKPluginUnavailabilityReasonInsecurePluginVersion -}; -typedef uint32_t WKPluginUnavailabilityReason; - -// UI Client -typedef WKPageRef (*WKPageCreateNewPageCallback)(WKPageRef page, WKURLRequestRef urlRequest, WKDictionaryRef features, WKEventModifiers modifiers, WKEventMouseButton mouseButton, const void *clientInfo); -typedef void (*WKPageRunJavaScriptAlertCallback)(WKPageRef page, WKStringRef alertText, WKFrameRef frame, const void *clientInfo); -typedef bool (*WKPageRunJavaScriptConfirmCallback)(WKPageRef page, WKStringRef message, WKFrameRef frame, const void *clientInfo); -typedef WKStringRef (*WKPageRunJavaScriptPromptCallback)(WKPageRef page, WKStringRef message, WKStringRef defaultValue, WKFrameRef frame, const void *clientInfo); -typedef void (*WKPageTakeFocusCallback)(WKPageRef page, WKFocusDirection direction, const void *clientInfo); -typedef void (*WKPageFocusCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageUnfocusCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageSetStatusTextCallback)(WKPageRef page, WKStringRef text, const void *clientInfo); -typedef void (*WKPageMouseDidMoveOverElementCallback)(WKPageRef page, WKHitTestResultRef hitTestResult, WKEventModifiers modifiers, WKTypeRef userData, const void *clientInfo); -typedef void (*WKPageDidNotHandleKeyEventCallback)(WKPageRef page, WKNativeEventPtr event, const void *clientInfo); -typedef void (*WKPageDidNotHandleWheelEventCallback)(WKPageRef page, WKNativeEventPtr event, const void *clientInfo); -typedef bool (*WKPageGetToolbarsAreVisibleCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageSetToolbarsAreVisibleCallback)(WKPageRef page, bool toolbarsVisible, const void *clientInfo); -typedef bool (*WKPageGetMenuBarIsVisibleCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageSetMenuBarIsVisibleCallback)(WKPageRef page, bool menuBarVisible, const void *clientInfo); -typedef bool (*WKPageGetStatusBarIsVisibleCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageSetStatusBarIsVisibleCallback)(WKPageRef page, bool statusBarVisible, const void *clientInfo); -typedef bool (*WKPageGetIsResizableCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageSetIsResizableCallback)(WKPageRef page, bool resizable, const void *clientInfo); -typedef WKRect (*WKPageGetWindowFrameCallback)(WKPageRef page, const void *clientInfo); -typedef void (*WKPageSetWindowFrameCallback)(WKPageRef page, WKRect frame, const void *clientInfo); -typedef bool (*WKPageRunBeforeUnloadConfirmPanelCallback)(WKPageRef page, WKStringRef message, WKFrameRef frame, const void *clientInfo); -typedef unsigned long long (*WKPageExceededDatabaseQuotaCallback)(WKPageRef page, WKFrameRef frame, WKSecurityOriginRef origin, WKStringRef databaseName, WKStringRef displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void *clientInfo); -typedef void (*WKPageRunOpenPanelCallback)(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void *clientInfo); -typedef void (*WKPageDecidePolicyForGeolocationPermissionRequestCallback)(WKPageRef page, WKFrameRef frame, WKSecurityOriginRef origin, WKGeolocationPermissionRequestRef permissionRequest, const void* clientInfo); -typedef float (*WKPageHeaderHeightCallback)(WKPageRef page, WKFrameRef frame, const void* clientInfo); -typedef float (*WKPageFooterHeightCallback)(WKPageRef page, WKFrameRef frame, const void* clientInfo); -typedef void (*WKPageDrawHeaderCallback)(WKPageRef page, WKFrameRef frame, WKRect rect, const void* clientInfo); -typedef void (*WKPageDrawFooterCallback)(WKPageRef page, WKFrameRef frame, WKRect rect, const void* clientInfo); -typedef void (*WKPagePrintFrameCallback)(WKPageRef page, WKFrameRef frame, const void* clientInfo); -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 (*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; - const void * clientInfo; - - // Version 0 - WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; - WKPageCallback showPage; - WKPageCallback close; - WKPageTakeFocusCallback takeFocus; - WKPageFocusCallback focus; - WKPageUnfocusCallback unfocus; - WKPageRunJavaScriptAlertCallback runJavaScriptAlert; - WKPageRunJavaScriptConfirmCallback runJavaScriptConfirm; - WKPageRunJavaScriptPromptCallback runJavaScriptPrompt; - WKPageSetStatusTextCallback setStatusText; - WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; - WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; - WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; - WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; - WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; - WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; - WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; - WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; - WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; - WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; - WKPageGetIsResizableCallback isResizable; - WKPageSetIsResizableCallback setIsResizable; - WKPageGetWindowFrameCallback getWindowFrame; - WKPageSetWindowFrameCallback setWindowFrame; - WKPageRunBeforeUnloadConfirmPanelCallback runBeforeUnloadConfirmPanel; - WKPageCallback didDraw; - WKPageCallback pageDidScroll; - WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; - WKPageRunOpenPanelCallback runOpenPanel; - WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; - WKPageHeaderHeightCallback headerHeight; - WKPageFooterHeightCallback footerHeight; - WKPageDrawHeaderCallback drawHeader; - WKPageDrawFooterCallback drawFooter; - WKPagePrintFrameCallback printFrame; - WKPageCallback runModal; - void* unused1; // Used to be didCompleteRubberBandForMainFrame - WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; - WKPageShouldInterruptJavaScriptCallback shouldInterruptJavaScript; - - // Version 1 - WKPageCreateNewPageCallback createNewPage; - WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; - WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; - WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; - - // Version 2 - WKPageShowColorPickerCallback showColorPicker; - WKPageHideColorPickerCallback hideColorPicker; - WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; -}; -typedef struct WKPageUIClient WKPageUIClient; - -enum { kWKPageUIClientCurrentVersion = 2 }; - -// Find client. -typedef void (*WKPageDidFindStringCallback)(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo); -typedef void (*WKPageDidFailToFindStringCallback)(WKPageRef page, WKStringRef string, const void* clientInfo); -typedef void (*WKPageDidCountStringMatchesCallback)(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo); - -struct WKPageFindClient { - int version; - const void * clientInfo; - WKPageDidFindStringCallback didFindString; - WKPageDidFailToFindStringCallback didFailToFindString; - WKPageDidCountStringMatchesCallback didCountStringMatches; -}; -typedef struct WKPageFindClient WKPageFindClient; - -enum { kWKPageFindClientCurrentVersion = 0 }; - -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); -struct WKPageContextMenuClient { - int version; - const void * clientInfo; - - // Version 0 - WKPageGetContextMenuFromProposedContextMenuCallback_deprecatedForUseWithV0 getContextMenuFromProposedMenu_deprecatedForUseWithV0; - WKPageCustomContextMenuItemSelectedCallback customContextMenuItemSelected; - - // Version 1 - WKPageContextMenuDismissedCallback contextMenuDismissed; - - // Version 2 - WKPageGetContextMenuFromProposedContextMenuCallback getContextMenuFromProposedMenu; - - // Version 3 - WKPageShowContextMenuCallback showContextMenu; - WKPageHideContextMenuCallback hideContextMenu; -}; -typedef struct WKPageContextMenuClient WKPageContextMenuClient; - -enum { kWKPageContextMenuClientCurrentVersion = 3 }; - WK_EXPORT WKTypeID WKPageGetTypeID(); WK_EXPORT WKContextRef WKPageGetContext(WKPageRef page); WK_EXPORT WKPageGroupRef WKPageGetPageGroup(WKPageRef page); +WK_EXPORT WKPageConfigurationRef WKPageCopyPageConfiguration(WKPageRef page); + // URL Requests WK_EXPORT void WKPageLoadURL(WKPageRef page, WKURLRef url); WK_EXPORT void WKPageLoadURLWithUserData(WKPageRef page, WKURLRef url, WKTypeRef userData); @@ -383,6 +83,7 @@ WK_EXPORT void WKPageLoadWebArchiveDataWithUserData(WKPageRef page, WKDataRef we WK_EXPORT void WKPageStopLoading(WKPageRef page); WK_EXPORT void WKPageReload(WKPageRef page); +WK_EXPORT void WKPageReloadWithoutContentBlockers(WKPageRef page); WK_EXPORT void WKPageReloadFromOrigin(WKPageRef page); WK_EXPORT bool WKPageTryClose(WKPageRef page); @@ -413,8 +114,6 @@ WK_EXPORT double WKPageGetEstimatedProgress(WKPageRef page); WK_EXPORT uint64_t WKPageGetRenderTreeSize(WKPageRef page); -WK_EXPORT void WKPageSetMemoryCacheClientCallsEnabled(WKPageRef page, bool memoryCacheClientCallsEnabled); - WK_EXPORT WKInspectorRef WKPageGetInspector(WKPageRef page); WK_EXPORT WKVibrationRef WKPageGetVibration(WKPageRef page); @@ -427,6 +126,8 @@ WK_EXPORT void WKPageSetApplicationNameForUserAgent(WKPageRef page, WKStringRef WK_EXPORT WKStringRef WKPageCopyCustomUserAgent(WKPageRef page); WK_EXPORT void WKPageSetCustomUserAgent(WKPageRef page, WKStringRef userAgent); +WK_EXPORT void WKPageSetUserContentExtensionsEnabled(WKPageRef, bool); + WK_EXPORT bool WKPageSupportsTextEncoding(WKPageRef page); WK_EXPORT WKStringRef WKPageCopyCustomTextEncodingName(WKPageRef page); WK_EXPORT void WKPageSetCustomTextEncodingName(WKPageRef page, WKStringRef encodingName); @@ -437,11 +138,18 @@ 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); -WK_EXPORT void WKPageRestoreFromSessionState(WKPageRef page, WKDataRef sessionStateData); + +// FIXME: This should return a WKSessionStateRef object, not a WKTypeRef. +// It currently returns a WKTypeRef for backwards compatibility with Safari. +WK_EXPORT WKTypeRef WKPageCopySessionState(WKPageRef page, void* context, WKPageSessionStateFilterCallback urlAllowedCallback); + +// FIXME: This should take a WKSessionStateRef object, not a WKTypeRef. +// It currently takes a WKTypeRef for backwards compatibility with Safari. +WK_EXPORT void WKPageRestoreFromSessionState(WKPageRef page, WKTypeRef sessionState); WK_EXPORT double WKPageGetBackingScaleFactor(WKPageRef page); WK_EXPORT void WKPageSetCustomBackingScaleFactor(WKPageRef page, double customScaleFactor); +WK_EXPORT void WKPageClearWheelEventTestTrigger(WKPageRef page); WK_EXPORT bool WKPageSupportsTextZoom(WKPageRef page); WK_EXPORT double WKPageGetTextZoomFactor(WKPageRef page); @@ -460,8 +168,6 @@ WK_EXPORT WKSize WKPageFixedLayoutSize(WKPageRef page); WK_EXPORT void WKPageListenForLayoutMilestones(WKPageRef page, WKLayoutMilestones milestones); -WK_EXPORT void WKPageSetVisibilityState(WKPageRef page, WKPageVisibilityState state, bool isInitialState); - WK_EXPORT bool WKPageHasHorizontalScrollbar(WKPageRef page); WK_EXPORT bool WKPageHasVerticalScrollbar(WKPageRef page); @@ -472,11 +178,28 @@ WK_EXPORT bool WKPageIsPinnedToLeftSide(WKPageRef page); 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); + +// This API is poorly named. Even when these values are set to false, rubber-banding will +// still be allowed to occur at the end of a momentum scroll. These values are used along +// with pin state to determine if wheel events should be handled in the web process or if +// they should be passed up to the client. +WK_EXPORT bool WKPageRubberBandsAtLeft(WKPageRef); +WK_EXPORT void WKPageSetRubberBandsAtLeft(WKPageRef, bool rubberBandsAtLeft); +WK_EXPORT bool WKPageRubberBandsAtRight(WKPageRef); +WK_EXPORT void WKPageSetRubberBandsAtRight(WKPageRef, bool rubberBandsAtRight); WK_EXPORT bool WKPageRubberBandsAtTop(WKPageRef); WK_EXPORT void WKPageSetRubberBandsAtTop(WKPageRef, bool rubberBandsAtTop); +WK_EXPORT bool WKPageRubberBandsAtBottom(WKPageRef); +WK_EXPORT void WKPageSetRubberBandsAtBottom(WKPageRef, bool rubberBandsAtBottom); + +// Rubber-banding is enabled by default. +WK_EXPORT bool WKPageVerticalRubberBandingIsEnabled(WKPageRef); +WK_EXPORT void WKPageSetEnableVerticalRubberBanding(WKPageRef, bool enableVerticalRubberBanding); +WK_EXPORT bool WKPageHorizontalRubberBandingIsEnabled(WKPageRef); +WK_EXPORT void WKPageSetEnableHorizontalRubberBanding(WKPageRef, bool enableHorizontalRubberBanding); + +WK_EXPORT void WKPageSetBackgroundExtendsBeyondPage(WKPageRef, bool backgroundExtendsBeyondPage); +WK_EXPORT bool WKPageBackgroundExtendsBeyondPage(WKPageRef); WK_EXPORT bool WKPageCanDelete(WKPageRef page); WK_EXPORT bool WKPageHasSelectedRange(WKPageRef page); @@ -492,13 +215,20 @@ WK_EXPORT void WKPageFindStringMatches(WKPageRef page, WKStringRef string, WKFin 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 WKPageSetPageUIClient(WKPageRef page, const WKPageUIClient* client); +WK_EXPORT void WKPageSetPageContextMenuClient(WKPageRef page, const WKPageContextMenuClientBase* client); +WK_EXPORT void WKPageSetPageDiagnosticLoggingClient(WKPageRef page, const WKPageDiagnosticLoggingClientBase* client); +WK_EXPORT void WKPageSetPageFindClient(WKPageRef page, const WKPageFindClientBase* client); +WK_EXPORT void WKPageSetPageFindMatchesClient(WKPageRef page, const WKPageFindMatchesClientBase* client); +WK_EXPORT void WKPageSetPageFormClient(WKPageRef page, const WKPageFormClientBase* client); +WK_EXPORT void WKPageSetPageUIClient(WKPageRef page, const WKPageUIClientBase* client); +WK_EXPORT void WKPageSetPageInjectedBundleClient(WKPageRef page, const WKPageInjectedBundleClientBase* client); + +// A client can implement either a navigation client or loader and policy clients, but never both. +WK_EXPORT void WKPageSetPageLoaderClient(WKPageRef page, const WKPageLoaderClientBase* client); +WK_EXPORT void WKPageSetPagePolicyClient(WKPageRef page, const WKPagePolicyClientBase* client); +WK_EXPORT void WKPageSetPageNavigationClient(WKPageRef page, const WKPageNavigationClientBase* client); + +WK_EXPORT void WKPageSetSession(WKPageRef page, WKSessionRef session); typedef void (*WKPageRunJavaScriptFunction)(WKSerializedScriptValueRef, WKErrorRef, void*); WK_EXPORT void WKPageRunJavaScriptInMainFrame(WKPageRef page, WKStringRef script, void* context, WKPageRunJavaScriptFunction function); @@ -509,20 +239,12 @@ WK_EXPORT void WKPageRunJavaScriptInMainFrame_b(WKPageRef page, WKStringRef scri typedef void (*WKPageGetSourceForFrameFunction)(WKStringRef, WKErrorRef, void*); WK_EXPORT void WKPageGetSourceForFrame(WKPageRef page, WKFrameRef frame, void* context, WKPageGetSourceForFrameFunction function); -#ifdef __BLOCKS__ -typedef void (^WKPageGetSourceForFrameBlock)(WKStringRef, WKErrorRef); -WK_EXPORT void WKPageGetSourceForFrame_b(WKPageRef page, WKFrameRef frame, WKPageGetSourceForFrameBlock block); -#endif typedef void (*WKPageGetContentsAsStringFunction)(WKStringRef, WKErrorRef, void*); WK_EXPORT void WKPageGetContentsAsString(WKPageRef page, void* context, WKPageGetContentsAsStringFunction function); -#ifdef __BLOCKS__ -typedef void (^WKPageGetContentsAsStringBlock)(WKStringRef, WKErrorRef); -WK_EXPORT void WKPageGetContentsAsString_b(WKPageRef page, WKPageGetContentsAsStringBlock block); -#endif typedef void (*WKPageGetContentsAsMHTMLDataFunction)(WKDataRef, WKErrorRef, void*); -WK_EXPORT void WKPageGetContentsAsMHTMLData(WKPageRef page, bool useBinaryEncoding, void* context, WKPageGetContentsAsMHTMLDataFunction function); +WK_EXPORT void WKPageGetContentsAsMHTMLData(WKPageRef page, void* context, WKPageGetContentsAsMHTMLDataFunction function); typedef void (*WKPageGetSelectionAsWebArchiveDataFunction)(WKDataRef, WKErrorRef, void*); WK_EXPORT void WKPageGetSelectionAsWebArchiveData(WKPageRef page, void* context, WKPageGetSelectionAsWebArchiveDataFunction function); diff --git a/Source/WebKit2/UIProcess/API/C/WKPageConfigurationRef.cpp b/Source/WebKit2/UIProcess/API/C/WKPageConfigurationRef.cpp new file mode 100644 index 000000000..ccdd66dca --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageConfigurationRef.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2015 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 "WKPageConfigurationRef.h" + +#include "APIPageConfiguration.h" +#include "WKAPICast.h" +#include "WebPageGroup.h" +#include "WebProcessPool.h" +#include "WebUserContentControllerProxy.h" + +using namespace WebKit; + +WKTypeID WKPageConfigurationGetTypeID() +{ + return toAPI(API::PageConfiguration::APIType); +} + +WKPageConfigurationRef WKPageConfigurationCreate() +{ + return toAPI(&API::PageConfiguration::create().leakRef()); +} + +WKContextRef WKPageConfigurationGetContext(WKPageConfigurationRef configuration) +{ + return toAPI(toImpl(configuration)->processPool()); +} + +void WKPageConfigurationSetContext(WKPageConfigurationRef configuration, WKContextRef context) +{ + toImpl(configuration)->setProcessPool(toImpl(context)); +} + +WKPageGroupRef WKPageConfigurationGetPageGroup(WKPageConfigurationRef configuration) +{ + return toAPI(toImpl(configuration)->pageGroup()); +} + +void WKPageConfigurationSetPageGroup(WKPageConfigurationRef configuration, WKPageGroupRef pageGroup) +{ + toImpl(configuration)->setPageGroup(toImpl(pageGroup)); +} + +WKUserContentControllerRef WKPageConfigurationGetUserContentController(WKPageConfigurationRef configuration) +{ + return toAPI(toImpl(configuration)->userContentController()); +} + +void WKPageConfigurationSetUserContentController(WKPageConfigurationRef configuration, WKUserContentControllerRef userContentController) +{ + toImpl(configuration)->setUserContentController(toImpl(userContentController)); +} + +WKPreferencesRef WKPageConfigurationGetPreferences(WKPageConfigurationRef configuration) +{ + return toAPI(toImpl(configuration)->preferences()); +} + +void WKPageConfigurationSetPreferences(WKPageConfigurationRef configuration, WKPreferencesRef preferences) +{ + toImpl(configuration)->setPreferences(toImpl(preferences)); +} + +WKPageRef WKPageConfigurationGetRelatedPage(WKPageConfigurationRef configuration) +{ + return toAPI(toImpl(configuration)->relatedPage()); +} + +void WKPageConfigurationSetRelatedPage(WKPageConfigurationRef configuration, WKPageRef relatedPage) +{ + toImpl(configuration)->setRelatedPage(toImpl(relatedPage)); +} + +WKWebsiteDataStoreRef WKPageConfigurationGetWebsiteDataStore(WKPageConfigurationRef configuration) +{ + return toAPI(toImpl(configuration)->websiteDataStore()); +} + +void WKPageConfigurationSetWebsiteDataStore(WKPageConfigurationRef configuration, WKWebsiteDataStoreRef websiteDataStore) +{ + toImpl(configuration)->setWebsiteDataStore(toImpl(websiteDataStore)); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKPageConfigurationRef.h b/Source/WebKit2/UIProcess/API/C/WKPageConfigurationRef.h new file mode 100644 index 000000000..e61c70fbc --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageConfigurationRef.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015 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 WKPageConfigurationRef_h +#define WKPageConfigurationRef_h + +#include <WebKit/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT WKTypeID WKPageConfigurationGetTypeID(); + +WK_EXPORT WKPageConfigurationRef WKPageConfigurationCreate(); + +WK_EXPORT WKContextRef WKPageConfigurationGetContext(WKPageConfigurationRef configuration); +WK_EXPORT void WKPageConfigurationSetContext(WKPageConfigurationRef configuration, WKContextRef context); + +WK_EXPORT WKPageGroupRef WKPageConfigurationGetPageGroup(WKPageConfigurationRef configuration); +WK_EXPORT void WKPageConfigurationSetPageGroup(WKPageConfigurationRef configuration, WKPageGroupRef pageGroup); + +WK_EXPORT WKUserContentControllerRef WKPageConfigurationGetUserContentController(WKPageConfigurationRef configuration); +WK_EXPORT void WKPageConfigurationSetUserContentController(WKPageConfigurationRef configuration, WKUserContentControllerRef userContentController); + +WK_EXPORT WKPreferencesRef WKPageConfigurationGetPreferences(WKPageConfigurationRef configuration); +WK_EXPORT void WKPageConfigurationSetPreferences(WKPageConfigurationRef configuration, WKPreferencesRef preferences); + +WK_EXPORT WKPageRef WKPageConfigurationGetRelatedPage(WKPageConfigurationRef configuration); +WK_EXPORT void WKPageConfigurationSetRelatedPage(WKPageConfigurationRef configuration, WKPageRef relatedPage); + +WK_EXPORT WKWebsiteDataStoreRef WKPageConfigurationGetWebsiteDataStore(WKPageConfigurationRef configuration); +WK_EXPORT void WKPageConfigurationSetWebsiteDataStore(WKPageConfigurationRef configuration, WKWebsiteDataStoreRef websiteDataStore); + +#ifdef __cplusplus +} +#endif + +#endif // WKPageConfigurationRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPageContextMenuClient.h b/Source/WebKit2/UIProcess/API/C/WKPageContextMenuClient.h new file mode 100644 index 000000000..ce2e4b07f --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageContextMenuClient.h @@ -0,0 +1,106 @@ +/* + * 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 WKPageContextMenuClient_h +#define WKPageContextMenuClient_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKGeometry.h> + +#ifdef __cplusplus +extern "C" { +#endif + +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); + +typedef struct WKPageContextMenuClientBase { + int version; + const void * clientInfo; +} WKPageContextMenuClientBase; + +typedef struct WKPageContextMenuClientV0 { + WKPageContextMenuClientBase base; + + // Version 0. + WKPageGetContextMenuFromProposedContextMenuCallback_deprecatedForUseWithV0 getContextMenuFromProposedMenu_deprecatedForUseWithV0; + WKPageCustomContextMenuItemSelectedCallback customContextMenuItemSelected; +} WKPageContextMenuClientV0; + +typedef struct WKPageContextMenuClientV1 { + WKPageContextMenuClientBase base; + + // Version 0. + WKPageGetContextMenuFromProposedContextMenuCallback_deprecatedForUseWithV0 getContextMenuFromProposedMenu_deprecatedForUseWithV0; + WKPageCustomContextMenuItemSelectedCallback customContextMenuItemSelected; + + // Version 1. + WKPageContextMenuDismissedCallback contextMenuDismissed; +} WKPageContextMenuClientV1; + +typedef struct WKPageContextMenuClientV2 { + WKPageContextMenuClientBase base; + + // Version 0. + WKPageGetContextMenuFromProposedContextMenuCallback_deprecatedForUseWithV0 getContextMenuFromProposedMenu_deprecatedForUseWithV0; + WKPageCustomContextMenuItemSelectedCallback customContextMenuItemSelected; + + // Version 1. + WKPageContextMenuDismissedCallback contextMenuDismissed; + + // Version 2. + WKPageGetContextMenuFromProposedContextMenuCallback getContextMenuFromProposedMenu; +} WKPageContextMenuClientV2; + +typedef struct WKPageContextMenuClientV3 { + WKPageContextMenuClientBase base; + + // Version 0. + WKPageGetContextMenuFromProposedContextMenuCallback_deprecatedForUseWithV0 getContextMenuFromProposedMenu_deprecatedForUseWithV0; + WKPageCustomContextMenuItemSelectedCallback customContextMenuItemSelected; + + // Version 1. + WKPageContextMenuDismissedCallback contextMenuDismissed; + + // Version 2. + WKPageGetContextMenuFromProposedContextMenuCallback getContextMenuFromProposedMenu; + + // Version 3. + WKPageShowContextMenuCallback showContextMenu; + WKPageHideContextMenuCallback hideContextMenu; +} WKPageContextMenuClientV3; + +#ifdef __cplusplus +} +#endif + + +#endif // WKPageContextMenuClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPageDiagnosticLoggingClient.h b/Source/WebKit2/UIProcess/API/C/WKPageDiagnosticLoggingClient.h new file mode 100644 index 000000000..9bb0b36e9 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageDiagnosticLoggingClient.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2015 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 WKPageDiagnosticLoggingClient_h +#define WKPageDiagnosticLoggingClient_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKDiagnosticLoggingResultType.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*WKPageLogDiagnosticMessageCallback)(WKPageRef page, WKStringRef message, WKStringRef description, const void* clientInfo); +typedef void (*WKPageLogDiagnosticMessageWithResultCallback)(WKPageRef page, WKStringRef message, WKStringRef description, WKDiagnosticLoggingResultType result, const void* clientInfo); +typedef void (*WKPageLogDiagnosticMessageWithValueCallback)(WKPageRef page, WKStringRef message, WKStringRef description, WKStringRef value, const void* clientInfo); + +typedef struct WKPageDiagnosticLoggingClientBase { + int version; + const void * clientInfo; +} WKPageDiagnosticLoggingClientBase; + +typedef struct WKPageDiagnosticLoggingClientV0 { + WKPageDiagnosticLoggingClientBase base; + + // Version 0. + WKPageLogDiagnosticMessageCallback logDiagnosticMessage; + WKPageLogDiagnosticMessageWithResultCallback logDiagnosticMessageWithResult; + WKPageLogDiagnosticMessageWithValueCallback logDiagnosticMessageWithValue; +} WKPageDiagnosticLoggingClientV0; + +#ifdef __cplusplus +} +#endif + +#endif // WKPageDiagnosticLoggingClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPageFindClient.h b/Source/WebKit2/UIProcess/API/C/WKPageFindClient.h new file mode 100644 index 000000000..6c7b1f22c --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageFindClient.h @@ -0,0 +1,58 @@ +/* + * 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 WKPageFindClient_h +#define WKPageFindClient_h + +#include <WebKit/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*WKPageDidFindStringCallback)(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo); +typedef void (*WKPageDidFailToFindStringCallback)(WKPageRef page, WKStringRef string, const void* clientInfo); +typedef void (*WKPageDidCountStringMatchesCallback)(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo); + +typedef struct WKPageFindClientBase { + int version; + const void * clientInfo; +} WKPageFindClientBase; + +typedef struct WKPageFindClientV0 { + WKPageFindClientBase base; + + // Version 0. + WKPageDidFindStringCallback didFindString; + WKPageDidFailToFindStringCallback didFailToFindString; + WKPageDidCountStringMatchesCallback didCountStringMatches; +} WKPageFindClientV0; + +#ifdef __cplusplus +} +#endif + + +#endif // WKPageFindClient_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_touch.h b/Source/WebKit2/UIProcess/API/C/WKPageFindMatchesClient.h index f2971a639..395588c7e 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_touch.h +++ b/Source/WebKit2/UIProcess/API/C/WKPageFindMatchesClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics + * 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,36 +23,39 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ewk_touch_h -#define ewk_touch_h +#ifndef WKPageFindMatchesClient_h +#define WKPageFindMatchesClient_h -#include <Evas.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -/// Represents types of touch event. -typedef enum { - EWK_TOUCH_START, - EWK_TOUCH_MOVE, - EWK_TOUCH_END, - EWK_TOUCH_CANCEL -} Ewk_Touch_Event_Type; - -/// Creates a type name for Ewk_Touch_Point. -typedef struct Ewk_Touch_Point Ewk_Touch_Point; - -/// Represents a touch point. -struct Ewk_Touch_Point { - int id; /**< identifier of the touch event */ - int x; /**< the horizontal position of the touch event */ - int y; /**< the vertical position of the touch event */ - Evas_Touch_Point_State state; /**< state of the touch event */ +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); + +typedef struct WKPageFindMatchesClientBase { + int version; + const void * clientInfo; +} WKPageFindMatchesClientBase; + +typedef struct WKPageFindMatchesClientV0 { + WKPageFindMatchesClientBase base; + + // Version 0. + WKPageDidFindStringMatchesCallback didFindStringMatches; + WKPageDidGetImageForMatchResultCallback didGetImageForMatchResult; +} WKPageFindMatchesClientV0; + #ifdef __cplusplus } #endif -#endif // ewk_touch_h + +#endif // WKPageFindMatchesClient_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_object.h b/Source/WebKit2/UIProcess/API/C/WKPageFormClient.h index 9ad1afe5f..2e6b7aeb1 100644 --- a/Source/WebKit2/UIProcess/API/efl/ewk_object.h +++ b/Source/WebKit2/UIProcess/API/C/WKPageFormClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. 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,43 +23,32 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -/** - * @file ewk_object.h - * @brief Describes the Ewk Ref Counted API. - */ - -#ifndef ewk_object_h -#define ewk_object_h +#ifndef WKPageFormClient_h +#define WKPageFormClient_h -#include <Eina.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -/** Creates a type name for Ewk_Object */ -typedef struct EwkObject Ewk_Object; +// Form Client. +typedef void (*WKPageWillSubmitFormCallback)(WKPageRef page, WKFrameRef frame, WKFrameRef sourceFrame, WKDictionaryRef values, WKTypeRef userData, WKFormSubmissionListenerRef listener, const void* clientInfo); -/** - * Increases the reference count of the given Ewk_Object. - * - * @param object the Ewk_Object instance to increase the reference count - * - * @return a pointer to the object on success, @c NULL otherwise. - */ -EAPI Ewk_Object *ewk_object_ref(Ewk_Object *object); +typedef struct WKPageFormClientBase { + int version; + const void * clientInfo; +} WKPageFormClientBase; -/** - * Decreases the reference count of the given Ewk_Object, possibly freeing it. - * - * When the reference count reaches 0, the item is freed. - * - * @param object the Ewk_Object instance to decrease the reference count - */ -EAPI void ewk_object_unref(Ewk_Object *object); +typedef struct WKPageFormClientV0 { + WKPageFormClientBase base; + // Version 0. + WKPageWillSubmitFormCallback willSubmitForm; +} WKPageFormClientV0; #ifdef __cplusplus } #endif -#endif // ewk_object_h + +#endif // WKPageFormClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPageGroup.cpp b/Source/WebKit2/UIProcess/API/C/WKPageGroup.cpp index 51298cd14..f1641dbbe 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPageGroup.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPageGroup.cpp @@ -26,6 +26,7 @@ #include "config.h" #include "WKPageGroup.h" +#include "APIUserContentExtension.h" #include "WKAPICast.h" #include "WebPageGroup.h" #include "WebPreferences.h" @@ -55,7 +56,7 @@ void WKPageGroupSetPreferences(WKPageGroupRef pageGroupRef, WKPreferencesRef pre WKPreferencesRef WKPageGroupGetPreferences(WKPageGroupRef pageGroupRef) { - return toAPI(toImpl(pageGroupRef)->preferences()); + return toAPI(&toImpl(pageGroupRef)->preferences()); } void WKPageGroupAddUserStyleSheet(WKPageGroupRef pageGroupRef, WKStringRef sourceRef, WKURLRef baseURL, WKArrayRef whitelistedURLPatterns, WKArrayRef blacklistedURLPatterns, WKUserContentInjectedFrames injectedFrames) @@ -68,7 +69,7 @@ void WKPageGroupRemoveAllUserStyleSheets(WKPageGroupRef pageGroupRef) toImpl(pageGroupRef)->removeAllUserStyleSheets(); } -void WKPageGroupAddUserScript(WKPageGroupRef pageGroupRef, WKStringRef sourceRef, WKURLRef baseURL, WKArrayRef whitelistedURLPatterns, WKArrayRef blacklistedURLPatterns, WKUserContentInjectedFrames injectedFrames, WKUserScriptInjectionTime injectionTime) +void WKPageGroupAddUserScript(WKPageGroupRef pageGroupRef, WKStringRef sourceRef, WKURLRef baseURL, WKArrayRef whitelistedURLPatterns, WKArrayRef blacklistedURLPatterns, WKUserContentInjectedFrames injectedFrames, _WKUserScriptInjectionTime injectionTime) { toImpl(pageGroupRef)->addUserScript(toWTFString(sourceRef), toWTFString(baseURL), toImpl(whitelistedURLPatterns), toImpl(blacklistedURLPatterns), toUserContentInjectedFrames(injectedFrames), toUserScriptInjectionTime(injectionTime)); } @@ -77,3 +78,33 @@ void WKPageGroupRemoveAllUserScripts(WKPageGroupRef pageGroupRef) { toImpl(pageGroupRef)->removeAllUserScripts(); } + +void WKPageGroupAddUserContentFilter(WKPageGroupRef pageGroupRef, WKUserContentFilterRef userContentFilterRef) +{ +#if ENABLE(CONTENT_EXTENSIONS) + toImpl(pageGroupRef)->addUserContentExtension(*toImpl(userContentFilterRef)); +#else + UNUSED_PARAM(pageGroupRef); + UNUSED_PARAM(userContentFilterRef); +#endif +} + +void WKPageGroupRemoveUserContentFilter(WKPageGroupRef pageGroupRef, WKStringRef userContentFilterNameRef) +{ +#if ENABLE(CONTENT_EXTENSIONS) + toImpl(pageGroupRef)->removeUserContentExtension(toWTFString(userContentFilterNameRef)); +#else + UNUSED_PARAM(pageGroupRef); + UNUSED_PARAM(userContentFilterNameRef); +#endif +} + + +void WKPageGroupRemoveAllUserContentFilters(WKPageGroupRef pageGroupRef) +{ +#if ENABLE(CONTENT_EXTENSIONS) + toImpl(pageGroupRef)->removeAllUserContentExtensions(); +#else + UNUSED_PARAM(pageGroupRef); +#endif +} diff --git a/Source/WebKit2/UIProcess/API/C/WKPageGroup.h b/Source/WebKit2/UIProcess/API/C/WKPageGroup.h index 01edb51c6..b21455c10 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPageGroup.h +++ b/Source/WebKit2/UIProcess/API/C/WKPageGroup.h @@ -26,7 +26,9 @@ #ifndef WKPageGroup_h #define WKPageGroup_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKUserContentInjectedFrames.h> +#include <WebKit/WKUserScriptInjectionTime.h> #ifdef __cplusplus extern "C" { @@ -44,9 +46,13 @@ WK_EXPORT WKPreferencesRef WKPageGroupGetPreferences(WKPageGroupRef pageGroup); WK_EXPORT void WKPageGroupAddUserStyleSheet(WKPageGroupRef pageGroup, WKStringRef source, WKURLRef baseURL, WKArrayRef whitelistedURLPatterns, WKArrayRef blacklistedURLPatterns, WKUserContentInjectedFrames); WK_EXPORT void WKPageGroupRemoveAllUserStyleSheets(WKPageGroupRef pageGroup); -WK_EXPORT void WKPageGroupAddUserScript(WKPageGroupRef pageGroup, WKStringRef source, WKURLRef baseURL, WKArrayRef whitelistedURLPatterns, WKArrayRef blacklistedURLPatterns, WKUserContentInjectedFrames, WKUserScriptInjectionTime); +WK_EXPORT void WKPageGroupAddUserScript(WKPageGroupRef pageGroup, WKStringRef source, WKURLRef baseURL, WKArrayRef whitelistedURLPatterns, WKArrayRef blacklistedURLPatterns, WKUserContentInjectedFrames, _WKUserScriptInjectionTime); WK_EXPORT void WKPageGroupRemoveAllUserScripts(WKPageGroupRef pageGroup); +WK_EXPORT void WKPageGroupAddUserContentFilter(WKPageGroupRef pageGroup, WKUserContentFilterRef userContentFilter); +WK_EXPORT void WKPageGroupRemoveUserContentFilter(WKPageGroupRef pageGroup, WKStringRef userContentFilterName); +WK_EXPORT void WKPageGroupRemoveAllUserContentFilters(WKPageGroupRef pageGroup); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.cpp b/Source/WebKit2/UIProcess/API/C/WKPageInjectedBundleClient.h index 6e2ecce06..b22c3eb86 100644 --- a/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPageInjectedBundleClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,30 +23,26 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" -#include "WKMediaCacheManager.h" +#ifndef WKPageInjectedBundleClient_h +#define WKPageInjectedBundleClient_h -#include "WKAPICast.h" -#include "WebMediaCacheManagerProxy.h" +#include <WebKit/WKBase.h> -using namespace WebKit; +typedef void (*WKPageDidReceiveMessageFromInjectedBundleCallback)(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, const void *clientInfo); +typedef void (*WKPageDidReceiveSynchronousMessageFromInjectedBundleCallback)(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void *clientInfo); +typedef WKTypeRef (*WKPageGetInjectedBundleInitializationUserDataCallback)(WKPageRef page, const void *clientInfo); -WKTypeID WKMediaCacheManagerGetTypeID() -{ - return toAPI(WebMediaCacheManagerProxy::APIType); -} +typedef struct WKPageInjectedBundleClientBase { + int version; + const void * clientInfo; +} WKPageInjectedBundleClientBase; -void WKMediaCacheManagerGetHostnamesWithMediaCache(WKMediaCacheManagerRef mediaCacheManagerRef, void* context, WKMediaCacheManagerGetHostnamesWithMediaCacheFunction callback) -{ - toImpl(mediaCacheManagerRef)->getHostnamesWithMediaCache(ArrayCallback::create(context, callback)); -} +typedef struct WKPageInjectedBundleClientV0 { + WKPageInjectedBundleClientBase base; -void WKMediaCacheManagerClearCacheForHostname(WKMediaCacheManagerRef mediaCacheManagerRef, WKStringRef hostname) -{ - toImpl(mediaCacheManagerRef)->clearCacheForHostname(toWTFString(hostname)); -} + // Version 0. + WKPageDidReceiveMessageFromInjectedBundleCallback didReceiveMessageFromInjectedBundle; + WKPageDidReceiveSynchronousMessageFromInjectedBundleCallback didReceiveSynchronousMessageFromInjectedBundle; +} WKPageInjectedBundleClientV0; -void WKMediaCacheManagerClearCacheForAllHostnames(WKMediaCacheManagerRef mediaCacheManagerRef) -{ - toImpl(mediaCacheManagerRef)->clearCacheForAllHostnames(); -} +#endif // WKPageInjectedBundleClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPageLoaderClient.h b/Source/WebKit2/UIProcess/API/C/WKPageLoaderClient.h new file mode 100644 index 000000000..c7c1cb011 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageLoaderClient.h @@ -0,0 +1,469 @@ +/* + * 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 WKPageLoaderClient_h +#define WKPageLoaderClient_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKErrorRef.h> +#include <WebKit/WKPageLoadTypes.h> +#include <WebKit/WKPluginLoadPolicy.h> + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + kWKWebGLLoadPolicyBlocked = 0, + kWKWebGLLoadPolicyLoadNormally, + kWKWebGLLoadPolicyPending +}; +typedef uint32_t WKWebGLLoadPolicy; + +typedef void (*WKPageLoaderClientCallback)(WKPageRef page, const void* clientInfo); +typedef void (*WKPageDidStartProvisionalLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidFailProvisionalLoadWithErrorForFrameCallback)(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidCommitLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidFinishDocumentLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidFinishLoadForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidFailLoadWithErrorForFrameCallback)(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidSameDocumentNavigationForFrameCallback)(WKPageRef page, WKFrameRef frame, WKSameDocumentNavigationType type, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidReceiveTitleForFrameCallback)(WKPageRef page, WKStringRef title, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidFirstLayoutForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidRemoveFrameFromHierarchyCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidDisplayInsecureContentForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidRunInsecureContentForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidDetectXSSForFrameCallback)(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void *clientInfo); +typedef bool (*WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback)(WKPageRef page, WKFrameRef frame, WKProtectionSpaceRef protectionSpace, const void *clientInfo); +typedef void (*WKPageDidReceiveAuthenticationChallengeInFrameCallback)(WKPageRef page, WKFrameRef frame, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo); +typedef void (*WKPageDidChangeBackForwardListCallback)(WKPageRef page, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void *clientInfo); +typedef bool (*WKPageShouldGoToBackForwardListItemCallback)(WKPageRef page, WKBackForwardListItemRef item, const void *clientInfo); +typedef bool (*WKPageShouldKeepCurrentBackForwardListItemInListCallback)(WKPageRef page, WKBackForwardListItemRef item, const void *clientInfo); +typedef void (*WKPageWillGoToBackForwardListItemCallback)(WKPageRef page, WKBackForwardListItemRef item, 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, uint32_t errorCode, WKDictionaryRef pluginInfoDictionary, const void* clientInfo); +typedef WKWebGLLoadPolicy (*WKPageWebGLLoadPolicyCallback)(WKPageRef page, WKStringRef url, const void* clientInfo); +typedef void (*WKPageNavigationGestureDidBeginCallback)(WKPageRef page, const void* clientInfo); +typedef void (*WKPageNavigationGestureWillEndCallback)(WKPageRef page, bool willNavigate, WKBackForwardListItemRef item, const void* clientInfo); +typedef void (*WKPageNavigationGestureDidEndCallback)(WKPageRef page, bool willNavigate, WKBackForwardListItemRef item, const void* clientInfo); + +// Deprecated +typedef void (*WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0)(WKPageRef page, WKStringRef mimeType, const void* clientInfo); +typedef void (*WKPagePluginDidFailCallback_deprecatedForUseWithV1)(WKPageRef page, uint32_t errorCode, WKStringRef mimeType, WKStringRef pluginIdentifier, WKStringRef pluginVersion, const void* clientInfo); +typedef WKPluginLoadPolicy (*WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2)(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInfoDictionary, const void* clientInfo); + +typedef struct WKPageLoaderClientBase { + int version; + const void * clientInfo; +} WKPageLoaderClientBase; + +typedef struct WKPageLoaderClientV0 { + WKPageLoaderClientBase base; + + // Version 0. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; +} WKPageLoaderClientV0; + +typedef struct WKPageLoaderClientV1 { + WKPageLoaderClientBase base; + + // Version -. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; + + // Version 1. + WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; + + void* didNewFirstVisuallyNonEmptyLayout_unavailable; + + WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; + + WKPageLoaderClientCallback interactionOccurredWhileProcessUnresponsive; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; +} WKPageLoaderClientV1; + +typedef struct WKPageLoaderClientV2 { + WKPageLoaderClientBase base; + + // Version 0. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; + + // Version 1. + WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; + + void* didNewFirstVisuallyNonEmptyLayout_unavailable; + + WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; + + WKPageLoaderClientCallback interactionOccurredWhileProcessUnresponsive; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; + + // Version 2. + void (*didReceiveIntentForFrame_unavailable)(void); + void (*registerIntentServiceForFrame_unavailable)(void); + + WKPageDidLayoutCallback didLayout; + WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2 pluginLoadPolicy_deprecatedForUseWithV2; + WKPagePluginDidFailCallback pluginDidFail; +} WKPageLoaderClientV2; + +typedef struct WKPageLoaderClientV3 { + WKPageLoaderClientBase base; + + // Version 0. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; + + // Version 1. + WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; + + void* didNewFirstVisuallyNonEmptyLayout_unavailable; + + WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; + + WKPageLoaderClientCallback interactionOccurredWhileProcessUnresponsive; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; + + // Version 2. + void (*didReceiveIntentForFrame_unavailable)(void); + void (*registerIntentServiceForFrame_unavailable)(void); + + WKPageDidLayoutCallback didLayout; + WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2 pluginLoadPolicy_deprecatedForUseWithV2; + WKPagePluginDidFailCallback pluginDidFail; + + // Version 3. + WKPagePluginLoadPolicyCallback pluginLoadPolicy; +} WKPageLoaderClientV3; + +typedef struct WKPageLoaderClientV4 { + WKPageLoaderClientBase base; + + // Version 0. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; + + // Version 1. + WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; + + void* didNewFirstVisuallyNonEmptyLayout_unavailable; + + WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; + + WKPageLoaderClientCallback interactionOccurredWhileProcessUnresponsive; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; + + // Version 2. + void (*didReceiveIntentForFrame_unavailable)(void); + void (*registerIntentServiceForFrame_unavailable)(void); + + WKPageDidLayoutCallback didLayout; + WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2 pluginLoadPolicy_deprecatedForUseWithV2; + WKPagePluginDidFailCallback pluginDidFail; + + // Version 3. + WKPagePluginLoadPolicyCallback pluginLoadPolicy; + + // Version 4 + WKPageWebGLLoadPolicyCallback webGLLoadPolicy; + WKPageWebGLLoadPolicyCallback resolveWebGLLoadPolicy; +} WKPageLoaderClientV4; + +typedef struct WKPageLoaderClientV5 { + WKPageLoaderClientBase base; + + // Version 0. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; + + // Version 1. + WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; + + void* didNewFirstVisuallyNonEmptyLayout_unavailable; + + WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; + + WKPageLoaderClientCallback interactionOccurredWhileProcessUnresponsive; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; + + // Version 2. + void (*didReceiveIntentForFrame_unavailable)(void); + void (*registerIntentServiceForFrame_unavailable)(void); + + WKPageDidLayoutCallback didLayout; + WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2 pluginLoadPolicy_deprecatedForUseWithV2; + WKPagePluginDidFailCallback pluginDidFail; + + // Version 3. + WKPagePluginLoadPolicyCallback pluginLoadPolicy; + + // Version 4. + WKPageWebGLLoadPolicyCallback webGLLoadPolicy; + WKPageWebGLLoadPolicyCallback resolveWebGLLoadPolicy; + + // Version 5. + WKPageShouldKeepCurrentBackForwardListItemInListCallback shouldKeepCurrentBackForwardListItemInList; +} WKPageLoaderClientV5; + +typedef struct WKPageLoaderClientV6 { + WKPageLoaderClientBase base; + + // Version 0. + WKPageDidStartProvisionalLoadForFrameCallback didStartProvisionalLoadForFrame; + WKPageDidReceiveServerRedirectForProvisionalLoadForFrameCallback didReceiveServerRedirectForProvisionalLoadForFrame; + WKPageDidFailProvisionalLoadWithErrorForFrameCallback didFailProvisionalLoadWithErrorForFrame; + WKPageDidCommitLoadForFrameCallback didCommitLoadForFrame; + WKPageDidFinishDocumentLoadForFrameCallback didFinishDocumentLoadForFrame; + WKPageDidFinishLoadForFrameCallback didFinishLoadForFrame; + WKPageDidFailLoadWithErrorForFrameCallback didFailLoadWithErrorForFrame; + WKPageDidSameDocumentNavigationForFrameCallback didSameDocumentNavigationForFrame; + WKPageDidReceiveTitleForFrameCallback didReceiveTitleForFrame; + WKPageDidFirstLayoutForFrameCallback didFirstLayoutForFrame; + WKPageDidFirstVisuallyNonEmptyLayoutForFrameCallback didFirstVisuallyNonEmptyLayoutForFrame; + WKPageDidRemoveFrameFromHierarchyCallback didRemoveFrameFromHierarchy; + WKPageDidDisplayInsecureContentForFrameCallback didDisplayInsecureContentForFrame; + WKPageDidRunInsecureContentForFrameCallback didRunInsecureContentForFrame; + WKPageCanAuthenticateAgainstProtectionSpaceInFrameCallback canAuthenticateAgainstProtectionSpaceInFrame; + WKPageDidReceiveAuthenticationChallengeInFrameCallback didReceiveAuthenticationChallengeInFrame; + + // FIXME: Move to progress client. + WKPageLoaderClientCallback didStartProgress; + WKPageLoaderClientCallback didChangeProgress; + WKPageLoaderClientCallback didFinishProgress; + + // FIXME: These three functions should not be part of this client. + WKPageLoaderClientCallback processDidBecomeUnresponsive; + WKPageLoaderClientCallback processDidBecomeResponsive; + WKPageLoaderClientCallback processDidCrash; + WKPageDidChangeBackForwardListCallback didChangeBackForwardList; + WKPageShouldGoToBackForwardListItemCallback shouldGoToBackForwardListItem; + WKPageDidFailToInitializePluginCallback_deprecatedForUseWithV0 didFailToInitializePlugin_deprecatedForUseWithV0; + + // Version 1. + WKPageDidDetectXSSForFrameCallback didDetectXSSForFrame; + + void* didNewFirstVisuallyNonEmptyLayout_unavailable; + + WKPageWillGoToBackForwardListItemCallback willGoToBackForwardListItem; + + WKPageLoaderClientCallback interactionOccurredWhileProcessUnresponsive; + WKPagePluginDidFailCallback_deprecatedForUseWithV1 pluginDidFail_deprecatedForUseWithV1; + + // Version 2. + void (*didReceiveIntentForFrame_unavailable)(void); + void (*registerIntentServiceForFrame_unavailable)(void); + + WKPageDidLayoutCallback didLayout; + WKPagePluginLoadPolicyCallback_deprecatedForUseWithV2 pluginLoadPolicy_deprecatedForUseWithV2; + WKPagePluginDidFailCallback pluginDidFail; + + // Version 3. + WKPagePluginLoadPolicyCallback pluginLoadPolicy; + + // Version 4. + WKPageWebGLLoadPolicyCallback webGLLoadPolicy; + WKPageWebGLLoadPolicyCallback resolveWebGLLoadPolicy; + + // Version 5. + WKPageShouldKeepCurrentBackForwardListItemInListCallback shouldKeepCurrentBackForwardListItemInList; + + // Version 6. + WKPageNavigationGestureDidBeginCallback navigationGestureDidBegin; + WKPageNavigationGestureWillEndCallback navigationGestureWillEnd; + WKPageNavigationGestureDidEndCallback navigationGestureDidEnd; +} WKPageLoaderClientV6; + +#ifdef __cplusplus +} +#endif + +#endif // WKPageLoaderClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPageNavigationClient.h b/Source/WebKit2/UIProcess/API/C/WKPageNavigationClient.h new file mode 100644 index 000000000..e19cf9741 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageNavigationClient.h @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2015 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 WKPageNavigationClient_h +#define WKPageNavigationClient_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKPageLoadTypes.h> +#include <WebKit/WKPageRenderingProgressEvents.h> +#include <WebKit/WKPluginLoadPolicy.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*WKPageNavigationDecidePolicyForNavigationActionCallback)(WKPageRef page, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDecidePolicyForNavigationResponseCallback)(WKPageRef page, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidStartProvisionalNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidReceiveServerRedirectForProvisionalNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidFailProvisionalNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKErrorRef error, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidCommitNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidFinishNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidFailNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKErrorRef error, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidFailProvisionalLoadInSubframeCallback)(WKPageRef page, WKNavigationRef navigation, WKFrameInfoRef subframe, WKErrorRef error, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidFinishDocumentLoadCallback)(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationDidSameDocumentNavigationCallback)(WKPageRef page, WKNavigationRef navigation, WKSameDocumentNavigationType navigationType, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageNavigationRenderingProgressDidChangeCallback)(WKPageRef page, WKPageRenderingProgressEvents progressEvents, WKTypeRef userData, const void* clientInfo); + +typedef bool (*WKPageNavigationCanAuthenticateAgainstProtectionSpaceCallback)(WKPageRef page, WKProtectionSpaceRef protectionSpace, const void* clientInfo); + +typedef void (*WKPageNavigationDidReceiveAuthenticationChallengeCallback)(WKPageRef page, WKAuthenticationChallengeRef challenge, const void* clientInfo); + +typedef void (*WKPageNavigationWebProcessDidCrashCallback)(WKPageRef page, const void* clientInfo); + +typedef WKDataRef (*WKPageNavigationCopyWebCryptoMasterKeyCallback)(WKPageRef page, const void* clientInfo); + +typedef WKPluginLoadPolicy (*WKPageNavigationDecidePolicyForPluginLoadCallback)(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInfoDictionary, WKStringRef* unavailabilityDescription, const void* clientInfo); + +typedef void (*WKPageNavigationDidBeginNavigationGesture)(WKPageRef page, const void* clientInfo); + +typedef void (*WKPageNavigationWillEndNavigationGesture)(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void* clientInfo); + +typedef void (*WKPageNavigationDidEndNavigationGesture)(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void* clientInfo); + +typedef void (*WKPageNavigationDidRemoveNavigationGestureSnapshot)(WKPageRef page, const void* clientInfo); + + +typedef struct WKPageNavigationClientBase { + int version; + const void* clientInfo; +} WKPageNavigationClientBase; + +typedef struct WKPageNavigationClientV0 { + WKPageNavigationClientBase base; + + // Version 0. + WKPageNavigationDecidePolicyForNavigationActionCallback decidePolicyForNavigationAction; + WKPageNavigationDecidePolicyForNavigationResponseCallback decidePolicyForNavigationResponse; + WKPageNavigationDecidePolicyForPluginLoadCallback decidePolicyForPluginLoad; + WKPageNavigationDidStartProvisionalNavigationCallback didStartProvisionalNavigation; + WKPageNavigationDidReceiveServerRedirectForProvisionalNavigationCallback didReceiveServerRedirectForProvisionalNavigation; + WKPageNavigationDidFailProvisionalNavigationCallback didFailProvisionalNavigation; + WKPageNavigationDidCommitNavigationCallback didCommitNavigation; + WKPageNavigationDidFinishNavigationCallback didFinishNavigation; + WKPageNavigationDidFailNavigationCallback didFailNavigation; + WKPageNavigationDidFailProvisionalLoadInSubframeCallback didFailProvisionalLoadInSubframe; + WKPageNavigationDidFinishDocumentLoadCallback didFinishDocumentLoad; + WKPageNavigationDidSameDocumentNavigationCallback didSameDocumentNavigation; + WKPageNavigationRenderingProgressDidChangeCallback renderingProgressDidChange; + WKPageNavigationCanAuthenticateAgainstProtectionSpaceCallback canAuthenticateAgainstProtectionSpace; + WKPageNavigationDidReceiveAuthenticationChallengeCallback didReceiveAuthenticationChallenge; + WKPageNavigationWebProcessDidCrashCallback webProcessDidCrash; + WKPageNavigationCopyWebCryptoMasterKeyCallback copyWebCryptoMasterKey; + + WKPageNavigationDidBeginNavigationGesture didBeginNavigationGesture; + WKPageNavigationWillEndNavigationGesture willEndNavigationGesture; + WKPageNavigationDidEndNavigationGesture didEndNavigationGesture; + WKPageNavigationDidRemoveNavigationGestureSnapshot didRemoveNavigationGestureSnapshot; +} WKPageNavigationClientV0; + +#ifdef __cplusplus +} +#endif + +#endif // WKPageNavigationClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPagePolicyClient.h b/Source/WebKit2/UIProcess/API/C/WKPagePolicyClient.h new file mode 100644 index 000000000..121c1018a --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPagePolicyClient.h @@ -0,0 +1,78 @@ +/* + * 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 WKPagePolicyClient_h +#define WKPagePolicyClient_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKEvent.h> +#include <WebKit/WKPageLoadTypes.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*WKPageDecidePolicyForNavigationActionCallback)(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKFrameRef originatingFrame, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); +typedef void (*WKPageDecidePolicyForNewWindowActionCallback)(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKStringRef frameName, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); +typedef void (*WKPageDecidePolicyForResponseCallback_deprecatedForUseWithV0)(WKPageRef page, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); +typedef void (*WKPageUnableToImplementPolicyCallback)(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void* clientInfo); + +typedef void (*WKPageDecidePolicyForNavigationActionCallback_deprecatedForUseWithV0)(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); +typedef void (*WKPageDecidePolicyForResponseCallback)(WKPageRef page, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef request, bool canShowMIMEType, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); + +typedef struct WKPagePolicyClientBase { + int version; + const void * clientInfo; +} WKPagePolicyClientBase; + +typedef struct WKPagePolicyClientV0 { + WKPagePolicyClientBase base; + + // Version 0. + WKPageDecidePolicyForNavigationActionCallback_deprecatedForUseWithV0 decidePolicyForNavigationAction_deprecatedForUseWithV0; + WKPageDecidePolicyForNewWindowActionCallback decidePolicyForNewWindowAction; + WKPageDecidePolicyForResponseCallback_deprecatedForUseWithV0 decidePolicyForResponse_deprecatedForUseWithV0; + WKPageUnableToImplementPolicyCallback unableToImplementPolicy; +} WKPagePolicyClientV0; + +typedef struct WKPagePolicyClientV1 { + WKPagePolicyClientBase base; + + // Version 0. + WKPageDecidePolicyForNavigationActionCallback_deprecatedForUseWithV0 decidePolicyForNavigationAction_deprecatedForUseWithV0; + WKPageDecidePolicyForNewWindowActionCallback decidePolicyForNewWindowAction; + WKPageDecidePolicyForResponseCallback_deprecatedForUseWithV0 decidePolicyForResponse_deprecatedForUseWithV0; + WKPageUnableToImplementPolicyCallback unableToImplementPolicy; + + // Version 1. + WKPageDecidePolicyForNavigationActionCallback decidePolicyForNavigationAction; + WKPageDecidePolicyForResponseCallback decidePolicyForResponse; +} WKPagePolicyClientV1; + +#ifdef __cplusplus +} +#endif + +#endif // WKPagePolicyClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPagePolicyClientInternal.h b/Source/WebKit2/UIProcess/API/C/WKPagePolicyClientInternal.h new file mode 100644 index 000000000..a6447a249 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPagePolicyClientInternal.h @@ -0,0 +1,58 @@ +/* + * 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 WKPagePolicyClientInternal_h +#define WKPagePolicyClientInternal_h + +#include "WKPagePolicyClient.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*WKPageDecidePolicyForNavigationActionCallback_internal)(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKFrameRef originatingFrame, WKURLRequestRef originalRequest, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo); + +typedef struct WKPagePolicyClientInternal { + WKPagePolicyClientBase base; + + // Version 0. + WKPageDecidePolicyForNavigationActionCallback_deprecatedForUseWithV0 decidePolicyForNavigationAction_deprecatedForUseWithV0; + WKPageDecidePolicyForNewWindowActionCallback decidePolicyForNewWindowAction; + WKPageDecidePolicyForResponseCallback_deprecatedForUseWithV0 decidePolicyForResponse_deprecatedForUseWithV0; + WKPageUnableToImplementPolicyCallback unableToImplementPolicy; + + // Version 1. + WKPageDecidePolicyForNavigationActionCallback decidePolicyForNavigationAction_deprecatedForUseWithV1; + WKPageDecidePolicyForResponseCallback decidePolicyForResponse; + + // Internal. + WKPageDecidePolicyForNavigationActionCallback_internal decidePolicyForNavigationAction; +} WKPagePolicyClientInternal; + +#ifdef __cplusplus +} +#endif + +#endif // WKPagePolicyClientInternal_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h b/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h index 114990aa3..3c361182e 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKPagePrivate.h @@ -26,8 +26,8 @@ #ifndef WKPagePrivate_h #define WKPagePrivate_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKPage.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKPage.h> #ifdef __cplusplus extern "C" { @@ -36,11 +36,6 @@ extern "C" { typedef void (*WKPageRenderTreeExternalRepresentationFunction)(WKStringRef, WKErrorRef, void*); WK_EXPORT void WKPageRenderTreeExternalRepresentation(WKPageRef page, void *context, WKPageRenderTreeExternalRepresentationFunction function); -#ifdef __BLOCKS__ -typedef void (^WKPageRenderTreeExternalRepresentationBlock)(WKStringRef, WKErrorRef); -WK_EXPORT void WKPageRenderTreeExternalRepresentation_b(WKPageRef page, WKPageRenderTreeExternalRepresentationBlock block); -#endif - enum { kWKDebugFlashViewUpdates = 1 << 0, kWKDebugFlashBackingStoreUpdates = 1 << 1 @@ -69,6 +64,8 @@ WK_EXPORT void WKPageSetPageLength(WKPageRef page, double pageLength); WK_EXPORT double WKPageGetPageLength(WKPageRef page); WK_EXPORT void WKPageSetGapBetweenPages(WKPageRef page, double gap); WK_EXPORT double WKPageGetGapBetweenPages(WKPageRef page); +WK_EXPORT void WKPageSetPaginationLineGridEnabled(WKPageRef page, bool lineGridEnabled); +WK_EXPORT bool WKPageGetPaginationLineGridEnabled(WKPageRef page); WK_EXPORT unsigned WKPageGetPageCount(WKPageRef page); @@ -87,18 +84,19 @@ WK_EXPORT void WKPageBeginPrinting(WKPageRef page, WKFrameRef frame, WKPrintInfo WK_EXPORT void WKPageDrawPagesToPDF(WKPageRef page, WKFrameRef frame, WKPrintInfo printInfo, uint32_t first, uint32_t count, WKPageDrawToPDFFunction callback, void* context); WK_EXPORT void WKPageEndPrinting(WKPageRef page); -// FIXME https://bugs.webkit.org/show_bug.cgi?id=66979: Remove this sync call. -WK_EXPORT WKImageRef WKPageCreateSnapshotOfVisibleContent(WKPageRef page); - -WK_EXPORT void WKPageSetShouldSendEventsSynchronously(WKPageRef page, bool sync); +WK_EXPORT bool WKPageGetAllowsRemoteInspection(WKPageRef page); +WK_EXPORT void WKPageSetAllowsRemoteInspection(WKPageRef page, bool allow); WK_EXPORT void WKPageSetMediaVolume(WKPageRef page, float volume); WK_EXPORT void WKPageSetMayStartMediaWhenInWindow(WKPageRef page, bool mayStartMedia); -WK_EXPORT WKArrayRef WKPageCopyRelatedPages(WKPageRef page); +typedef void (*WKPageGetBytecodeProfileFunction)(WKStringRef, WKErrorRef, void*); +WK_EXPORT void WKPageGetBytecodeProfile(WKPageRef page, void* context, WKPageGetBytecodeProfileFunction function); -typedef void (*WKPageInvalidMessageFunction)(uint32_t messageID); -WK_EXPORT void WKPageSetInvalidMessageFunction(WKPageInvalidMessageFunction function); +typedef void (*WKPageIsWebProcessResponsiveFunction)(bool isWebProcessResponsive, void* context); +WK_EXPORT void WKPageIsWebProcessResponsive(WKPageRef page, void* context, WKPageIsWebProcessResponsiveFunction function); + +WK_EXPORT WKArrayRef WKPageCopyRelatedPages(WKPageRef page); enum { kWKScrollPinningBehaviorDoNotPin, @@ -110,6 +108,27 @@ typedef uint32_t WKScrollPinningBehavior; WK_EXPORT WKScrollPinningBehavior WKPageGetScrollPinningBehavior(WKPageRef page); WK_EXPORT void WKPageSetScrollPinningBehavior(WKPageRef page, WKScrollPinningBehavior pinning); +WK_EXPORT bool WKPageGetAddsVisitedLinks(WKPageRef page); +WK_EXPORT void WKPageSetAddsVisitedLinks(WKPageRef page, bool visitedLinks); + +WK_EXPORT bool WKPageIsPlayingAudio(WKPageRef page); +WK_EXPORT void WKPageSetMuted(WKPageRef page, bool muted); + +enum { + kWKMediaEventTypePlayPause, + kWKMediaEventTypeTrackNext, + kWKMediaEventTypeTrackPrevious +}; +typedef uint32_t WKMediaEventType; + +WK_EXPORT bool WKPageHasMediaSessionWithActiveMediaElements(WKPageRef page); +WK_EXPORT void WKPageHandleMediaEvent(WKPageRef page, WKMediaEventType event); + +WK_EXPORT void WKPageLoadURLWithShouldOpenExternalURLsPolicy(WKPageRef page, WKURLRef url, bool shouldOpenExternalURLs); + +typedef void (*WKPagePostPresentationUpdateFunction)(WKErrorRef, void*); +WK_EXPORT void WKPageCallAfterNextPresentationUpdate(WKPageRef page, void* context, WKPagePostPresentationUpdateFunction function); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h b/Source/WebKit2/UIProcess/API/C/WKPageRenderingProgressEvents.h index 0a7b4ff05..6d258ed15 100644 --- a/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.h +++ b/Source/WebKit2/UIProcess/API/C/WKPageRenderingProgressEvents.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 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,25 +23,25 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKCookieManagerSoup_h -#define WKCookieManagerSoup_h +#ifndef WKPageRenderingProgressEvents_h +#define WKPageRenderingProgressEvents_h -#include <WebKit2/WKBase.h> +#include <stdint.h> #ifdef __cplusplus extern "C" { #endif enum { - kWKCookieStorageTypeText = 0, - kWKCookieStorageTypeSQLite = 1 + WKPageRenderingProgressEventFirstLayout = 1 << 0, + WKPageRenderingProgressEventFirstVisuallyNonEmptyLayout = 1 << 1, + WKPageRenderingProgressEventFirstPaintWithSignificantArea = 1 << 2, + WKPageRenderingProgressEventReachedSessionRestorationRenderTreeSizeThreshold = 1 << 3 }; -typedef uint32_t WKCookieStorageType; - -WK_EXPORT void WKCookieManagerSetCookiePersistentStorage(WKCookieManagerRef cookieManager, WKStringRef storagePath, WKCookieStorageType storageType); +typedef uint32_t WKPageRenderingProgressEvents; #ifdef __cplusplus } #endif -#endif // WKCookieManagerSoup_h +#endif /* WKPageRenderingProgressEvents_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKNetworkInfoManager.cpp b/Source/WebKit2/UIProcess/API/C/WKPageRenderingProgressEventsInternal.h index 85620ad61..ab9274534 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNetworkInfoManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPageRenderingProgressEventsInternal.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,33 +23,25 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" -#include "WKNetworkInfoManager.h" +#include "WKPageRenderingProgressEvents.h" -#include "WKAPICast.h" -#include "WebNetworkInfoManagerProxy.h" +#include <WebCore/LayoutMilestones.h> -using namespace WebKit; - -WKTypeID WKNetworkInfoManagerGetTypeID() -{ -#if ENABLE(NETWORK_INFO) - return toAPI(WebNetworkInfoManagerProxy::APIType); -#else - return 0; -#endif -} - -void WKNetworkInfoManagerSetProvider(WKNetworkInfoManagerRef networkInfoManager, const WKNetworkInfoProvider* provider) -{ -#if ENABLE(NETWORK_INFO) - toImpl(networkInfoManager)->initializeProvider(provider); -#endif -} - -void WKNetworkInfoManagerProviderDidChangeNetworkInformation(WKNetworkInfoManagerRef networkInfoManager, WKStringRef eventType, WKNetworkInfoRef networkInfo) +static inline WKPageRenderingProgressEvents pageRenderingProgressEvents(WebCore::LayoutMilestones milestones) { -#if ENABLE(NETWORK_INFO) - toImpl(networkInfoManager)->providerDidChangeNetworkInformation(AtomicString(toImpl(eventType)->string()), toImpl(networkInfo)); -#endif + WKPageRenderingProgressEvents events = 0; + + if (milestones & WebCore::DidFirstLayout) + events |= WKPageRenderingProgressEventFirstLayout; + + if (milestones & WebCore::DidFirstVisuallyNonEmptyLayout) + events |= WKPageRenderingProgressEventFirstVisuallyNonEmptyLayout; + + if (milestones & WebCore::DidHitRelevantRepaintedObjectsAreaThreshold) + events |= WKPageRenderingProgressEventFirstPaintWithSignificantArea; + + if (milestones & WebCore::ReachedSessionRestorationRenderTreeSizeThreshold) + events |= WKPageRenderingProgressEventReachedSessionRestorationRenderTreeSizeThreshold; + + return events; } diff --git a/Source/WebKit2/UIProcess/API/C/WKPageUIClient.h b/Source/WebKit2/UIProcess/API/C/WKPageUIClient.h new file mode 100644 index 000000000..2ab3595bd --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPageUIClient.h @@ -0,0 +1,641 @@ +/* + * 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 WKPageUIClient_h +#define WKPageUIClient_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKEvent.h> +#include <WebKit/WKGeometry.h> +#include <WebKit/WKNativeEvent.h> + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + kWKFocusDirectionBackward = 0, + kWKFocusDirectionForward = 1 +}; +typedef uint32_t WKFocusDirection; + +enum { + kWKPluginUnavailabilityReasonPluginMissing, + kWKPluginUnavailabilityReasonPluginCrashed, + kWKPluginUnavailabilityReasonInsecurePluginVersion +}; +typedef uint32_t WKPluginUnavailabilityReason; + +WK_EXPORT WKTypeID WKPageRunBeforeUnloadConfirmPanelResultListenerGetTypeID(); +WK_EXPORT void WKPageRunBeforeUnloadConfirmPanelResultListenerCall(WKPageRunBeforeUnloadConfirmPanelResultListenerRef listener, bool result); + +WK_EXPORT WKTypeID WKPageRunJavaScriptAlertResultListenerGetTypeID(); +WK_EXPORT void WKPageRunJavaScriptAlertResultListenerCall(WKPageRunJavaScriptAlertResultListenerRef listener); + +WK_EXPORT WKTypeID WKPageRunJavaScriptConfirmResultListenerGetTypeID(); +WK_EXPORT void WKPageRunJavaScriptConfirmResultListenerCall(WKPageRunJavaScriptConfirmResultListenerRef listener, bool result); + +WK_EXPORT WKTypeID WKPageRunJavaScriptPromptResultListenerGetTypeID(); +WK_EXPORT void WKPageRunJavaScriptPromptResultListenerCall(WKPageRunJavaScriptPromptResultListenerRef listener, WKStringRef result); + +typedef void (*WKPageUIClientCallback)(WKPageRef page, const void* clientInfo); +typedef WKPageRef (*WKPageCreateNewPageCallback)(WKPageRef page, WKPageConfigurationRef configuration, WKNavigationActionRef navigationAction, WKWindowFeaturesRef windowFeatures, const void *clientInfo); +typedef void (*WKPageRunBeforeUnloadConfirmPanelCallback)(WKPageRef page, WKStringRef message, WKFrameRef frame, WKPageRunBeforeUnloadConfirmPanelResultListenerRef listener, const void *clientInfo); +typedef void (*WKPageRunJavaScriptAlertCallback)(WKPageRef page, WKStringRef alertText, WKFrameRef frame, WKSecurityOriginRef securityOrigin, WKPageRunJavaScriptAlertResultListenerRef listener, const void *clientInfo); +typedef void (*WKPageRunJavaScriptConfirmCallback)(WKPageRef page, WKStringRef message, WKFrameRef frame, WKSecurityOriginRef securityOrigin, WKPageRunJavaScriptConfirmResultListenerRef listener, const void *clientInfo); +typedef void (*WKPageRunJavaScriptPromptCallback)(WKPageRef page, WKStringRef message, WKStringRef defaultValue, WKFrameRef frame, WKSecurityOriginRef securityOrigin, WKPageRunJavaScriptPromptResultListenerRef listener, const void *clientInfo); +typedef void (*WKPageTakeFocusCallback)(WKPageRef page, WKFocusDirection direction, const void *clientInfo); +typedef void (*WKPageFocusCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageUnfocusCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageSetStatusTextCallback)(WKPageRef page, WKStringRef text, const void *clientInfo); +typedef void (*WKPageMouseDidMoveOverElementCallback)(WKPageRef page, WKHitTestResultRef hitTestResult, WKEventModifiers modifiers, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageDidNotHandleKeyEventCallback)(WKPageRef page, WKNativeEventPtr event, const void *clientInfo); +typedef void (*WKPageDidNotHandleWheelEventCallback)(WKPageRef page, WKNativeEventPtr event, const void *clientInfo); +typedef bool (*WKPageGetToolbarsAreVisibleCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageSetToolbarsAreVisibleCallback)(WKPageRef page, bool toolbarsVisible, const void *clientInfo); +typedef bool (*WKPageGetMenuBarIsVisibleCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageSetMenuBarIsVisibleCallback)(WKPageRef page, bool menuBarVisible, const void *clientInfo); +typedef bool (*WKPageGetStatusBarIsVisibleCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageSetStatusBarIsVisibleCallback)(WKPageRef page, bool statusBarVisible, const void *clientInfo); +typedef bool (*WKPageGetIsResizableCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageSetIsResizableCallback)(WKPageRef page, bool resizable, const void *clientInfo); +typedef WKRect (*WKPageGetWindowFrameCallback)(WKPageRef page, const void *clientInfo); +typedef void (*WKPageSetWindowFrameCallback)(WKPageRef page, WKRect frame, const void *clientInfo); +typedef unsigned long long (*WKPageExceededDatabaseQuotaCallback)(WKPageRef page, WKFrameRef frame, WKSecurityOriginRef origin, WKStringRef databaseName, WKStringRef displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void *clientInfo); +typedef void (*WKPageRunOpenPanelCallback)(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void *clientInfo); +typedef void (*WKPageDecidePolicyForGeolocationPermissionRequestCallback)(WKPageRef page, WKFrameRef frame, WKSecurityOriginRef origin, WKGeolocationPermissionRequestRef permissionRequest, const void* clientInfo); +typedef float (*WKPageHeaderHeightCallback)(WKPageRef page, WKFrameRef frame, const void* clientInfo); +typedef float (*WKPageFooterHeightCallback)(WKPageRef page, WKFrameRef frame, const void* clientInfo); +typedef void (*WKPageDrawHeaderCallback)(WKPageRef page, WKFrameRef frame, WKRect rect, const void* clientInfo); +typedef void (*WKPageDrawFooterCallback)(WKPageRef page, WKFrameRef frame, WKRect rect, const void* clientInfo); +typedef void (*WKPagePrintFrameCallback)(WKPageRef page, WKFrameRef frame, const void* clientInfo); +typedef void (*WKPageSaveDataToFileInDownloadsFolderCallback)(WKPageRef page, WKStringRef suggestedFilename, WKStringRef mimeType, WKURLRef originatingURL, WKDataRef data, const void* clientInfo); +typedef void (*WKPageDecidePolicyForNotificationPermissionRequestCallback)(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef permissionRequest, 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); +typedef void (*WKPagePinnedStateDidChangeCallback)(WKPageRef page, const void* clientInfo); +typedef void (*WKPageIsPlayingAudioDidChangeCallback)(WKPageRef page, const void* clientInfo); +typedef void (*WKPageDecidePolicyForUserMediaPermissionRequestCallback)(WKPageRef page, WKFrameRef frame, WKSecurityOriginRef origin, WKUserMediaPermissionRequestRef permissionRequest, const void* clientInfo); +typedef void (*WKCheckUserMediaPermissionCallback)(WKPageRef page, WKFrameRef frame, WKSecurityOriginRef origin, WKUserMediaPermissionCheckRef devicesRequest, const void *clientInfo); +typedef void (*WKPageDidClickAutoFillButtonCallback)(WKPageRef page, WKTypeRef userData, const void *clientInfo); +typedef void (*WKPageMediaSessionMetadataDidChangeCallback)(WKPageRef page, WKMediaSessionMetadataRef metadata, 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); +typedef void (*WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0)(WKPageRef page, WKStringRef alertText, WKFrameRef frame, const void *clientInfo); +typedef bool (*WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0)(WKPageRef page, WKStringRef message, WKFrameRef frame, const void *clientInfo); +typedef WKStringRef (*WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0)(WKPageRef page, WKStringRef message, WKStringRef defaultValue, WKFrameRef frame, const void *clientInfo); +typedef WKPageRef (*WKPageCreateNewPageCallback_deprecatedForUseWithV1)(WKPageRef page, WKURLRequestRef urlRequest, WKDictionaryRef features, WKEventModifiers modifiers, WKEventMouseButton mouseButton, const void *clientInfo); +typedef void (*WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV5)(WKPageRef page, WKStringRef alertText, WKFrameRef frame, WKSecurityOriginRef securityOrigin, const void *clientInfo); +typedef bool (*WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV5)(WKPageRef page, WKStringRef message, WKFrameRef frame, WKSecurityOriginRef securityOrigin, const void *clientInfo); +typedef WKStringRef (*WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV5)(WKPageRef page, WKStringRef message, WKStringRef defaultValue, WKFrameRef frame, WKSecurityOriginRef securityOrigin, const void *clientInfo); +typedef bool (*WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6)(WKPageRef page, WKStringRef message, WKFrameRef frame, const void *clientInfo); + +typedef struct WKPageUIClientBase { + int version; + const void * clientInfo; +} WKPageUIClientBase; + +typedef struct WKPageUIClientV0 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; +} WKPageUIClientV0; + +typedef struct WKPageUIClientV1 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; +} WKPageUIClientV1; + +typedef struct WKPageUIClientV2 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; +} WKPageUIClientV2; + +typedef struct WKPageUIClientV3 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + + // Version 3. + WKPagePinnedStateDidChangeCallback pinnedStateDidChange; +} WKPageUIClientV3; + +typedef struct WKPageUIClientV4 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame. + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + + // Version 3. + WKPagePinnedStateDidChangeCallback pinnedStateDidChange; + + // Version 4. + void* unused2; // Used to be didBeginTrackingPotentialLongMousePress. + void* unused3; // Used to be didRecognizeLongMousePress. + void* unused4; // Used to be didCancelTrackingPotentialLongMousePress. + WKPageIsPlayingAudioDidChangeCallback isPlayingAudioDidChange; +} WKPageUIClientV4; + +typedef struct WKPageUIClientV5 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert_deprecatedForUseWithV0; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm_deprecatedForUseWithV0; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt_deprecatedForUseWithV0; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + + // Version 3. + WKPagePinnedStateDidChangeCallback pinnedStateDidChange; + + // Version 4. + void* unused2; // Used to be didBeginTrackingPotentialLongMousePress. + void* unused3; // Used to be didRecognizeLongMousePress. + void* unused4; // Used to be didCancelTrackingPotentialLongMousePress. + WKPageIsPlayingAudioDidChangeCallback isPlayingAudioDidChange; + + // Version 5. + WKPageDecidePolicyForUserMediaPermissionRequestCallback decidePolicyForUserMediaPermissionRequest; + WKPageDidClickAutoFillButtonCallback didClickAutoFillButton; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV5 runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV5 runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV5 runJavaScriptPrompt; + WKPageMediaSessionMetadataDidChangeCallback mediaSessionMetadataDidChange; +} WKPageUIClientV5; + +typedef struct WKPageUIClientV6 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert_deprecatedForUseWithV0; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm_deprecatedForUseWithV0; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt_deprecatedForUseWithV0; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage_deprecatedForUseWithV1; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + + // Version 3. + WKPagePinnedStateDidChangeCallback pinnedStateDidChange; + + // Version 4. + void* unused2; // Used to be didBeginTrackingPotentialLongMousePress. + void* unused3; // Used to be didRecognizeLongMousePress. + void* unused4; // Used to be didCancelTrackingPotentialLongMousePress. + WKPageIsPlayingAudioDidChangeCallback isPlayingAudioDidChange; + + // Version 5. + WKPageDecidePolicyForUserMediaPermissionRequestCallback decidePolicyForUserMediaPermissionRequest; + WKPageDidClickAutoFillButtonCallback didClickAutoFillButton; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV5 runJavaScriptAlert_deprecatedForUseWithV5; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV5 runJavaScriptConfirm_deprecatedForUseWithV5; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV5 runJavaScriptPrompt_deprecatedForUseWithV5; + WKPageMediaSessionMetadataDidChangeCallback mediaSessionMetadataDidChange; + + // Version 6. + WKPageCreateNewPageCallback createNewPage; + WKPageRunJavaScriptAlertCallback runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback runJavaScriptPrompt; + WKCheckUserMediaPermissionCallback checkUserMediaPermissionForOrigin; +} WKPageUIClientV6; + +typedef struct WKPageUIClientV7 { + WKPageUIClientBase base; + + // Version 0. + WKPageCreateNewPageCallback_deprecatedForUseWithV0 createNewPage_deprecatedForUseWithV0; + WKPageUIClientCallback showPage; + WKPageUIClientCallback close; + WKPageTakeFocusCallback takeFocus; + WKPageFocusCallback focus; + WKPageUnfocusCallback unfocus; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV0 runJavaScriptAlert_deprecatedForUseWithV0; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV0 runJavaScriptConfirm_deprecatedForUseWithV0; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV0 runJavaScriptPrompt_deprecatedForUseWithV0; + WKPageSetStatusTextCallback setStatusText; + WKPageMouseDidMoveOverElementCallback_deprecatedForUseWithV0 mouseDidMoveOverElement_deprecatedForUseWithV0; + WKPageMissingPluginButtonClickedCallback_deprecatedForUseWithV0 missingPluginButtonClicked_deprecatedForUseWithV0; + WKPageDidNotHandleKeyEventCallback didNotHandleKeyEvent; + WKPageDidNotHandleWheelEventCallback didNotHandleWheelEvent; + WKPageGetToolbarsAreVisibleCallback toolbarsAreVisible; + WKPageSetToolbarsAreVisibleCallback setToolbarsAreVisible; + WKPageGetMenuBarIsVisibleCallback menuBarIsVisible; + WKPageSetMenuBarIsVisibleCallback setMenuBarIsVisible; + WKPageGetStatusBarIsVisibleCallback statusBarIsVisible; + WKPageSetStatusBarIsVisibleCallback setStatusBarIsVisible; + WKPageGetIsResizableCallback isResizable; + WKPageSetIsResizableCallback setIsResizable; + WKPageGetWindowFrameCallback getWindowFrame; + WKPageSetWindowFrameCallback setWindowFrame; + WKPageRunBeforeUnloadConfirmPanelCallback_deprecatedForUseWithV6 runBeforeUnloadConfirmPanel_deprecatedForUseWithV6; + WKPageUIClientCallback didDraw; + WKPageUIClientCallback pageDidScroll; + WKPageExceededDatabaseQuotaCallback exceededDatabaseQuota; + WKPageRunOpenPanelCallback runOpenPanel; + WKPageDecidePolicyForGeolocationPermissionRequestCallback decidePolicyForGeolocationPermissionRequest; + WKPageHeaderHeightCallback headerHeight; + WKPageFooterHeightCallback footerHeight; + WKPageDrawHeaderCallback drawHeader; + WKPageDrawFooterCallback drawFooter; + WKPagePrintFrameCallback printFrame; + WKPageUIClientCallback runModal; + void* unused1; // Used to be didCompleteRubberBandForMainFrame + WKPageSaveDataToFileInDownloadsFolderCallback saveDataToFileInDownloadsFolder; + void* shouldInterruptJavaScript_unavailable; + + // Version 1. + WKPageCreateNewPageCallback_deprecatedForUseWithV1 createNewPage_deprecatedForUseWithV1; + WKPageMouseDidMoveOverElementCallback mouseDidMoveOverElement; + WKPageDecidePolicyForNotificationPermissionRequestCallback decidePolicyForNotificationPermissionRequest; + WKPageUnavailablePluginButtonClickedCallback_deprecatedForUseWithV1 unavailablePluginButtonClicked_deprecatedForUseWithV1; + + // Version 2. + WKPageShowColorPickerCallback showColorPicker; + WKPageHideColorPickerCallback hideColorPicker; + WKPageUnavailablePluginButtonClickedCallback unavailablePluginButtonClicked; + + // Version 3. + WKPagePinnedStateDidChangeCallback pinnedStateDidChange; + + // Version 4. + void* unused2; // Used to be didBeginTrackingPotentialLongMousePress. + void* unused3; // Used to be didRecognizeLongMousePress. + void* unused4; // Used to be didCancelTrackingPotentialLongMousePress. + WKPageIsPlayingAudioDidChangeCallback isPlayingAudioDidChange; + + // Version 5. + WKPageDecidePolicyForUserMediaPermissionRequestCallback decidePolicyForUserMediaPermissionRequest; + WKPageDidClickAutoFillButtonCallback didClickAutoFillButton; + WKPageRunJavaScriptAlertCallback_deprecatedForUseWithV5 runJavaScriptAlert_deprecatedForUseWithV5; + WKPageRunJavaScriptConfirmCallback_deprecatedForUseWithV5 runJavaScriptConfirm_deprecatedForUseWithV5; + WKPageRunJavaScriptPromptCallback_deprecatedForUseWithV5 runJavaScriptPrompt_deprecatedForUseWithV5; + WKPageMediaSessionMetadataDidChangeCallback mediaSessionMetadataDidChange; + + // Version 6. + WKPageCreateNewPageCallback createNewPage; + WKPageRunJavaScriptAlertCallback runJavaScriptAlert; + WKPageRunJavaScriptConfirmCallback runJavaScriptConfirm; + WKPageRunJavaScriptPromptCallback runJavaScriptPrompt; + WKCheckUserMediaPermissionCallback checkUserMediaPermissionForOrigin; + + // Version 7. + WKPageRunBeforeUnloadConfirmPanelCallback runBeforeUnloadConfirmPanel; +} WKPageUIClientV7; + +#ifdef __cplusplus +} +#endif + +#endif // WKPageUIClient_h diff --git a/Source/WebKit2/UIProcess/API/C/WKPluginLoadPolicy.h b/Source/WebKit2/UIProcess/API/C/WKPluginLoadPolicy.h new file mode 100644 index 000000000..7aaef37ee --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKPluginLoadPolicy.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2015 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 WKPluginLoadPolicy_h +#define WKPluginLoadPolicy_h + +#include <stdint.h> + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + kWKPluginLoadPolicyLoadNormally = 0, + kWKPluginLoadPolicyBlocked, + kWKPluginLoadPolicyInactive, + kWKPluginLoadPolicyLoadUnsandboxed, + kWKPluginLoadPolicyBlockedForCompatibility, +}; +typedef uint32_t WKPluginLoadPolicy; + +enum { + kWKPluginLoadClientPolicyUndefined = 0, + kWKPluginLoadClientPolicyBlock, + kWKPluginLoadClientPolicyAsk, + kWKPluginLoadClientPolicyAllow, + kWKPluginLoadClientPolicyAllowAlways, +}; +typedef uint32_t WKPluginLoadClientPolicy; + +#ifdef __cplusplus +} +#endif + +#endif /* WKPluginLoadPolicy_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp b/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp index 1105ca27a..1015fc4f2 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.cpp @@ -28,68 +28,71 @@ #include "APIObject.h" #include "WKAPICast.h" -#include "WebPluginSiteDataManager.h" - -#if ENABLE(NETSCAPE_PLUGIN_API) -#include <WebCore/npapi.h> -#endif +#include "WebProcessPool.h" +#include "WebsiteDataRecord.h" using namespace WebKit; WKTypeID WKPluginSiteDataManagerGetTypeID() { -#if ENABLE(NETSCAPE_PLUGIN_API) - return toAPI(WebPluginSiteDataManager::APIType); -#else - return APIObject::TypeNull; -#endif + return toAPI(API::WebsiteDataStore::APIType); } -void WKPluginSiteDataManagerGetSitesWithData(WKPluginSiteDataManagerRef managerRef, void* context, WKPluginSiteDataManagerGetSitesWithDataFunction callback) +void WKPluginSiteDataManagerGetSitesWithData(WKPluginSiteDataManagerRef manager, void* context, WKPluginSiteDataManagerGetSitesWithDataFunction callback) { #if ENABLE(NETSCAPE_PLUGIN_API) - toImpl(managerRef)->getSitesWithData(ArrayCallback::create(context, callback)); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(manager))->websiteDataStore(); + websiteDataStore.fetchData(WebsiteDataTypes::WebsiteDataTypePlugInData, [context, callback](Vector<WebsiteDataRecord> dataRecords) { + Vector<String> hostNames; + for (const auto& dataRecord : dataRecords) { + for (const auto& hostName : dataRecord.pluginDataHostNames) + hostNames.append(hostName); + } + + callback(toAPI(API::Array::createStringArray(hostNames).ptr()), nullptr, context); + }); #else - UNUSED_PARAM(managerRef); + UNUSED_PARAM(manager); UNUSED_PARAM(context); UNUSED_PARAM(callback); #endif } -#if ENABLE(NETSCAPE_PLUGIN_API) -static uint64_t toNPClearSiteDataFlags(WKClearSiteDataFlags flags) +void WKPluginSiteDataManagerClearSiteData(WKPluginSiteDataManagerRef manager, WKArrayRef sites, WKClearSiteDataFlags flags, uint64_t maxAgeInSeconds, void* context, WKPluginSiteDataManagerClearSiteDataFunction callback) { - if (flags == kWKClearSiteDataFlagsClearAll) - return NP_CLEAR_ALL; + // These are the only parameters supported. + ASSERT_UNUSED(flags, flags == kWKClearSiteDataFlagsClearAll); + ASSERT_UNUSED(maxAgeInSeconds, maxAgeInSeconds == std::numeric_limits<uint64_t>::max()); - uint64_t result = 0; - if (flags & kWKClearSiteDataFlagsClearCache) - result |= NP_CLEAR_CACHE; - return result; -} -#endif - -void WKPluginSiteDataManagerClearSiteData(WKPluginSiteDataManagerRef managerRef, WKArrayRef sitesRef, WKClearSiteDataFlags flags, uint64_t maxAgeInSeconds, void* context, WKPluginSiteDataManagerClearSiteDataFunction function) -{ #if ENABLE(NETSCAPE_PLUGIN_API) - toImpl(managerRef)->clearSiteData(toImpl(sitesRef), toNPClearSiteDataFlags(flags), maxAgeInSeconds, VoidCallback::create(context, function)); + WebsiteDataRecord dataRecord; + for (const auto& string : toImpl(sites)->elementsOfType<API::String>()) + dataRecord.pluginDataHostNames.add(string->string()); + + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(manager))->websiteDataStore(); + websiteDataStore.removeData(WebsiteDataTypes::WebsiteDataTypePlugInData, { dataRecord }, [context, callback] { + callback(nullptr, context); + }); #else - UNUSED_PARAM(managerRef); - UNUSED_PARAM(sitesRef); + UNUSED_PARAM(manager); + UNUSED_PARAM(sites); UNUSED_PARAM(flags); UNUSED_PARAM(maxAgeInSeconds); UNUSED_PARAM(context); - UNUSED_PARAM(function); + UNUSED_PARAM(callback); #endif } -void WKPluginSiteDataManagerClearAllSiteData(WKPluginSiteDataManagerRef managerRef, void* context, WKPluginSiteDataManagerClearSiteDataFunction function) +void WKPluginSiteDataManagerClearAllSiteData(WKPluginSiteDataManagerRef manager, void* context, WKPluginSiteDataManagerClearSiteDataFunction callback) { #if ENABLE(NETSCAPE_PLUGIN_API) - toImpl(managerRef)->clearSiteData(0, NP_CLEAR_ALL, std::numeric_limits<uint64_t>::max(), VoidCallback::create(context, function)); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(manager))->websiteDataStore(); + websiteDataStore.removeData(WebsiteDataTypes::WebsiteDataTypePlugInData, std::chrono::system_clock::time_point::min(), [context, callback] { + callback(nullptr, context); + }); #else - UNUSED_PARAM(managerRef); + UNUSED_PARAM(manager); UNUSED_PARAM(context); - UNUSED_PARAM(function); + UNUSED_PARAM(callback); #endif } diff --git a/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.h b/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.h index 66e76fbcd..9a772b2b5 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKPluginSiteDataManager.h @@ -26,7 +26,7 @@ #ifndef WKPluginSiteDataManager_h #define WKPluginSiteDataManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp b/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp index b4deaac84..7699c5392 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKPreferences.cpp @@ -24,11 +24,10 @@ */ #include "config.h" -#include "WKPreferences.h" -#include "WKPreferencesPrivate.h" +#include "WKPreferencesRef.h" +#include "WKPreferencesRefPrivate.h" #include "WKAPICast.h" -#include "WebContext.h" #include "WebPreferences.h" #include <WebCore/Settings.h> #include <wtf/PassRefPtr.h> @@ -43,19 +42,19 @@ WKTypeID WKPreferencesGetTypeID() WKPreferencesRef WKPreferencesCreate() { - RefPtr<WebPreferences> preferences = WebPreferences::create(); + RefPtr<WebPreferences> preferences = WebPreferences::createWithLegacyDefaults(String(), "WebKit2.", "WebKit2."); return toAPI(preferences.release().leakRef()); } WKPreferencesRef WKPreferencesCreateWithIdentifier(WKStringRef identifierRef) { - RefPtr<WebPreferences> preferences = WebPreferences::create(toWTFString(identifierRef)); + RefPtr<WebPreferences> preferences = WebPreferences::createWithLegacyDefaults(toWTFString(identifierRef), "WebKit2.", "WebKit2."); return toAPI(preferences.release().leakRef()); } WKPreferencesRef WKPreferencesCreateCopy(WKPreferencesRef preferencesRef) { - RefPtr<WebPreferences> preferences = WebPreferences::create(*toImpl(preferencesRef)); + RefPtr<WebPreferences> preferences = toImpl(preferencesRef)->copy(); return toAPI(preferences.release().leakRef()); } @@ -299,15 +298,6 @@ uint32_t WKPreferencesGetMinimumFontSize(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->minimumFontSize(); } -void WKPreferencesSetScreenFontSubstitutionEnabled(WKPreferencesRef preferencesRef, bool enabled) -{ - toImpl(preferencesRef)->setScreenFontSubstitutionEnabled(enabled); -} - -bool WKPreferencesGetScreenFontSubstitutionEnabled(WKPreferencesRef preferencesRef) -{ - return toImpl(preferencesRef)->screenFontSubstitutionEnabled(); -} void WKPreferencesSetCookieEnabled(WKPreferencesRef preferencesRef, bool enabled) { @@ -359,14 +349,14 @@ bool WKPreferencesGetDeveloperExtrasEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->developerExtrasEnabled(); } -void WKPreferencesSetJavaScriptExperimentsEnabled(WKPreferencesRef preferencesRef, bool enabled) +void WKPreferencesSetJavaScriptRuntimeFlags(WKPreferencesRef preferencesRef, WKJavaScriptRuntimeFlagSet javaScriptRuntimeFlagSet) { - toImpl(preferencesRef)->setJavaScriptExperimentsEnabled(enabled); + toImpl(preferencesRef)->setJavaScriptRuntimeFlags(javaScriptRuntimeFlagSet); } -bool WKPreferencesGetJavaScriptExperimentsEnabled(WKPreferencesRef preferencesRef) +WKJavaScriptRuntimeFlagSet WKPreferencesGetJavaScriptRuntimeFlags(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->javaScriptExperimentsEnabled(); + return toImpl(preferencesRef)->javaScriptRuntimeFlags(); } void WKPreferencesSetTextAreasAreResizable(WKPreferencesRef preferencesRef, bool resizable) @@ -459,24 +449,24 @@ bool WKPreferencesGetTiledScrollingIndicatorVisible(WKPreferencesRef preferences return toImpl(preferencesRef)->tiledScrollingIndicatorVisible(); } -void WKPreferencesSetCSSCustomFilterEnabled(WKPreferencesRef preferencesRef, bool flag) +void WKPreferencesSetWebGLEnabled(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setCSSCustomFilterEnabled(flag); + toImpl(preferencesRef)->setWebGLEnabled(flag); } -bool WKPreferencesGetCSSCustomFilterEnabled(WKPreferencesRef preferencesRef) +bool WKPreferencesGetWebGLEnabled(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->cssCustomFilterEnabled(); + return toImpl(preferencesRef)->webGLEnabled(); } -void WKPreferencesSetWebGLEnabled(WKPreferencesRef preferencesRef, bool flag) +void WKPreferencesSetForceSoftwareWebGLRendering(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setWebGLEnabled(flag); + toImpl(preferencesRef)->setForceSoftwareWebGLRendering(flag); } -bool WKPreferencesGetWebGLEnabled(WKPreferencesRef preferencesRef) +bool WKPreferencesGetForceSoftwareWebGLRendering(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->webGLEnabled(); + return toImpl(preferencesRef)->forceSoftwareWebGLRendering(); } void WKPreferencesSetAccelerated2DCanvasEnabled(WKPreferencesRef preferencesRef, bool flag) @@ -489,34 +479,34 @@ bool WKPreferencesGetAccelerated2DCanvasEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->accelerated2dCanvasEnabled(); } -void WKPreferencesSetCSSRegionsEnabled(WKPreferencesRef preferencesRef, bool flag) +void WKPreferencesSetCSSAnimationTriggersEnabled(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setCSSRegionsEnabled(flag); + toImpl(preferencesRef)->setCSSAnimationTriggersEnabled(flag); } -bool WKPreferencesGetCSSRegionsEnabled(WKPreferencesRef preferencesRef) +bool WKPreferencesGetCSSAnimationTriggersEnabled(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->cssRegionsEnabled(); + return toImpl(preferencesRef)->cssAnimationTriggersEnabled(); } -void WKPreferencesSetCSSGridLayoutEnabled(WKPreferencesRef preferencesRef, bool flag) +void WKPreferencesSetWebAnimationsEnabled(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setCSSGridLayoutEnabled(flag); + toImpl(preferencesRef)->setWebAnimationsEnabled(flag); } -bool WKPreferencesGetCSSGridLayoutEnabled(WKPreferencesRef preferencesRef) +bool WKPreferencesGetWebAnimationsEnabled(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->cssGridLayoutEnabled(); + return toImpl(preferencesRef)->webAnimationsEnabled(); } -void WKPreferencesSetRegionBasedColumnsEnabled(WKPreferencesRef preferencesRef, bool flag) +void WKPreferencesSetCSSRegionsEnabled(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setRegionBasedColumnsEnabled(flag); + toImpl(preferencesRef)->setCSSRegionsEnabled(flag); } -bool WKPreferencesGetRegionBasedColumnsEnabled(WKPreferencesRef preferencesRef) +bool WKPreferencesGetCSSRegionsEnabled(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->regionBasedColumnsEnabled(); + return toImpl(preferencesRef)->cssRegionsEnabled(); } void WKPreferencesSetNeedsSiteSpecificQuirks(WKPreferencesRef preferencesRef, bool flag) @@ -524,6 +514,16 @@ void WKPreferencesSetNeedsSiteSpecificQuirks(WKPreferencesRef preferencesRef, bo toImpl(preferencesRef)->setNeedsSiteSpecificQuirks(flag); } +bool WKPreferencesUseLegacyTextAlignPositionedElementBehavior(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->useLegacyTextAlignPositionedElementBehavior(); +} + +void WKPreferencesSetUseLegacyTextAlignPositionedElementBehavior(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setUseLegacyTextAlignPositionedElementBehavior(flag); +} + bool WKPreferencesGetNeedsSiteSpecificQuirks(WKPreferencesRef preferencesRef) { return toImpl(preferencesRef)->needsSiteSpecificQuirks(); @@ -589,6 +589,16 @@ bool WKPreferencesGetShouldPrintBackgrounds(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->shouldPrintBackgrounds(); } +void WKPreferencesSetDOMTimersThrottlingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setDOMTimersThrottlingEnabled(enabled); +} + +bool WKPreferencesGetDOMTimersThrottlingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->domTimersThrottlingEnabled(); +} + void WKPreferencesSetWebArchiveDebugModeEnabled(WKPreferencesRef preferencesRef, bool enabled) { toImpl(preferencesRef)->setWebArchiveDebugModeEnabled(enabled); @@ -689,6 +699,16 @@ bool WKPreferencesGetAVFoundationEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->isAVFoundationEnabled(); } +void WKPreferencesSetAVFoundationNSURLSessionEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setAVFoundationNSURLSessionEnabled(enabled); +} + +bool WKPreferencesGetAVFoundationNSURLSessionEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->isAVFoundationNSURLSessionEnabled(); +} + void WKPreferencesSetWebSecurityEnabled(WKPreferencesRef preferencesRef, bool enabled) { toImpl(preferencesRef)->setWebSecurityEnabled(enabled); @@ -730,22 +750,52 @@ bool WKPreferencesGetHixie76WebSocketProtocolEnabled(WKPreferencesRef) void WKPreferencesSetMediaPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setMediaPlaybackRequiresUserGesture(flag); + toImpl(preferencesRef)->setRequiresUserGestureForMediaPlayback(flag); } bool WKPreferencesGetMediaPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->mediaPlaybackRequiresUserGesture(); + return toImpl(preferencesRef)->requiresUserGestureForMediaPlayback(); +} + +void WKPreferencesSetAudioPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setRequiresUserGestureForAudioPlayback(flag); +} + +bool WKPreferencesGetAudioPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->requiresUserGestureForAudioPlayback(); } void WKPreferencesSetMediaPlaybackAllowsInline(WKPreferencesRef preferencesRef, bool flag) { - toImpl(preferencesRef)->setMediaPlaybackAllowsInline(flag); + toImpl(preferencesRef)->setAllowsInlineMediaPlayback(flag); } bool WKPreferencesGetMediaPlaybackAllowsInline(WKPreferencesRef preferencesRef) { - return toImpl(preferencesRef)->mediaPlaybackAllowsInline(); + return toImpl(preferencesRef)->allowsInlineMediaPlayback(); +} + +void WKPreferencesSetInlineMediaPlaybackRequiresPlaysInlineAttribute(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setInlineMediaPlaybackRequiresPlaysInlineAttribute(flag); +} + +bool WKPreferencesGetInlineMediaPlaybackRequiresPlaysInlineAttribute(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->inlineMediaPlaybackRequiresPlaysInlineAttribute(); +} + +void WKPreferencesSetMediaControlsScaleWithPageZoom(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setMediaControlsScaleWithPageZoom(flag); +} + +bool WKPreferencesGetMediaControlsScaleWithPageZoom(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->mediaControlsScaleWithPageZoom(); } void WKPreferencesSetShowsToolTipOverTruncatedText(WKPreferencesRef preferencesRef, bool flag) @@ -778,24 +828,26 @@ bool WKPreferencesGetWebAudioEnabled(WKPreferencesRef preferencesRef) return toImpl(preferencesRef)->webAudioEnabled(); } -void WKPreferencesSetApplicationChromeModeEnabled(WKPreferencesRef preferencesRef, bool enabled) +void WKPreferencesSetApplicationChromeModeEnabled(WKPreferencesRef, bool) { - toImpl(preferencesRef)->setApplicationChromeModeEnabled(enabled); + // FIXME: Remove once WebKit nightlies don't need to support Safari 8. } -bool WKPreferencesGetApplicationChromeModeEnabled(WKPreferencesRef preferencesRef) +bool WKPreferencesGetApplicationChromeModeEnabled(WKPreferencesRef) { - return toImpl(preferencesRef)->applicationChromeMode(); + // FIXME: Remove once WebKit nightlies don't need to support Safari 8. + return false; } -void WKPreferencesSetInspectorUsesWebKitUserInterface(WKPreferencesRef preferencesRef, bool enabled) +void WKPreferencesSetInspectorUsesWebKitUserInterface(WKPreferencesRef, bool) { - toImpl(preferencesRef)->setInspectorUsesWebKitUserInterface(enabled); + // FIXME: Remove once WebKit nightlies don't need to support Safari 6 thru 7. } -bool WKPreferencesGetInspectorUsesWebKitUserInterface(WKPreferencesRef preferencesRef) +bool WKPreferencesGetInspectorUsesWebKitUserInterface(WKPreferencesRef) { - return toImpl(preferencesRef)->inspectorUsesWebKitUserInterface(); + // FIXME: Remove once WebKit nightlies don't need to support Safari 6 thru 7. + return false; } void WKPreferencesSetSuppressesIncrementalRendering(WKPreferencesRef preferencesRef, bool enabled) @@ -1145,6 +1197,76 @@ double WKPreferencesGetIncrementalRenderingSuppressionTimeout(WKPreferencesRef p return toAPI(toImpl(preferencesRef)->incrementalRenderingSuppressionTimeout()); } +void WKPreferencesSetThreadedScrollingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setThreadedScrollingEnabled(enabled); +} + +bool WKPreferencesGetThreadedScrollingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->threadedScrollingEnabled(); +} + +void WKPreferencesSetSimpleLineLayoutEnabled(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setSimpleLineLayoutEnabled(flag); +} + +bool WKPreferencesGetSimpleLineLayoutEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->simpleLineLayoutEnabled(); +} + +void WKPreferencesSetSimpleLineLayoutDebugBordersEnabled(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setSimpleLineLayoutDebugBordersEnabled(flag); +} + +bool WKPreferencesGetSimpleLineLayoutDebugBordersEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->simpleLineLayoutDebugBordersEnabled(); +} + +void WKPreferencesSetNewBlockInsideInlineModelEnabled(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setNewBlockInsideInlineModelEnabled(flag); +} + +bool WKPreferencesGetNewBlockInsideInlineModelEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->newBlockInsideInlineModelEnabled(); +} + +void WKPreferencesSetSubpixelCSSOMElementMetricsEnabled(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setSubpixelCSSOMElementMetricsEnabled(flag); +} + +bool WKPreferencesGetSubpixelCSSOMElementMetricsEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->subpixelCSSOMElementMetricsEnabled(); +} + +void WKPreferencesSetUseGiantTiles(WKPreferencesRef preferencesRef, bool flag) +{ + toImpl(preferencesRef)->setUseGiantTiles(flag); +} + +bool WKPreferencesGetUseGiantTiles(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->useGiantTiles(); +} + +void WKPreferencesSetMediaStreamEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setMediaStreamEnabled(enabled); +} + +bool WKPreferencesGetMediaStreamEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->mediaStreamEnabled(); +} + void WKPreferencesSetSpatialNavigationEnabled(WKPreferencesRef preferencesRef, bool enabled) { toImpl(preferencesRef)->setSpatialNavigationEnabled(enabled); @@ -1154,3 +1276,183 @@ bool WKPreferencesGetSpatialNavigationEnabled(WKPreferencesRef preferencesRef) { return toImpl(preferencesRef)->spatialNavigationEnabled(); } + +void WKPreferencesSetMediaSourceEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setMediaSourceEnabled(enabled); +} + +bool WKPreferencesGetMediaSourceEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->mediaSourceEnabled(); +} + +void WKPreferencesSetViewGestureDebuggingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setViewGestureDebuggingEnabled(enabled); +} + +bool WKPreferencesGetViewGestureDebuggingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->viewGestureDebuggingEnabled(); +} + +void WKPreferencesSetShouldConvertPositionStyleOnCopy(WKPreferencesRef preferencesRef, bool convert) +{ + toImpl(preferencesRef)->setShouldConvertPositionStyleOnCopy(convert); +} + +bool WKPreferencesGetShouldConvertPositionStyleOnCopy(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->shouldConvertPositionStyleOnCopy(); +} + +void WKPreferencesSetTelephoneNumberParsingEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setTelephoneNumberParsingEnabled(enabled); +} + +bool WKPreferencesGetTelephoneNumberParsingEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->telephoneNumberParsingEnabled(); +} + +void WKPreferencesSetEnableInheritURIQueryComponent(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setEnableInheritURIQueryComponent(enabled); +} + +bool WKPreferencesGetEnableInheritURIQueryComponent(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->enableInheritURIQueryComponent(); +} + +void WKPreferencesSetServiceControlsEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setServiceControlsEnabled(enabled); +} + +bool WKPreferencesGetServiceControlsEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->serviceControlsEnabled(); +} + +void WKPreferencesSetImageControlsEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setImageControlsEnabled(enabled); +} + +bool WKPreferencesGetImageControlsEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->imageControlsEnabled(); +} + +void WKPreferencesSetGamepadsEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setGamepadsEnabled(enabled); +} + +bool WKPreferencesGetGamepadsEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->gamepadsEnabled(); +} + +// FIXME: Remove these when possible. +void WKPreferencesSetLongMousePressEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ +} + +bool WKPreferencesGetLongMousePressEnabled(WKPreferencesRef preferencesRef) +{ + return false; +} + +void WKPreferencesSetMinimumZoomFontSize(WKPreferencesRef preferencesRef, double size) +{ + toImpl(preferencesRef)->setMinimumZoomFontSize(size); +} + +double WKPreferencesGetMinimumZoomFontSize(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->minimumZoomFontSize(); +} + +void WKPreferencesSetAntialiasedFontDilationEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setAntialiasedFontDilationEnabled(enabled); +} + +bool WKPreferencesGetAntialiasedFontDilationEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->antialiasedFontDilationEnabled(); +} + +void WKPreferencesSetVisibleDebugOverlayRegions(WKPreferencesRef preferencesRef, WKDebugOverlayRegions visibleRegions) +{ + toImpl(preferencesRef)->setVisibleDebugOverlayRegions(visibleRegions); +} + +WKDebugOverlayRegions WKPreferencesGetVisibleDebugOverlayRegions(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->visibleDebugOverlayRegions(); +} + +void WKPreferencesSetIgnoreViewportScalingConstraints(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setIgnoreViewportScalingConstraints(enabled); +} + +bool WKPreferencesGetIgnoreViewportScalingConstraints(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->ignoreViewportScalingConstraints(); +} + +void WKPreferencesSetMetaRefreshEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setHTTPEquivEnabled(enabled); +} + +bool WKPreferencesGetMetaRefreshEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->httpEquivEnabled(); +} + +void WKPreferencesSetHTTPEquivEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setHTTPEquivEnabled(enabled); +} + +bool WKPreferencesGetHTTPEquivEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->httpEquivEnabled(); +} + +void WKPreferencesSetAllowsAirPlayForMediaPlayback(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setAllowsAirPlayForMediaPlayback(enabled); +} + +bool WKPreferencesGetAllowsAirPlayForMediaPlayback(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->allowsAirPlayForMediaPlayback(); +} + +void WKPreferencesSetResourceUsageOverlayVisible(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setResourceUsageOverlayVisible(enabled); +} + +bool WKPreferencesGetResourceUsageOverlayVisible(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->resourceUsageOverlayVisible(); +} + +void WKPreferencesSetMockCaptureDevicesEnabled(WKPreferencesRef preferencesRef, bool enabled) +{ + toImpl(preferencesRef)->setMockCaptureDevicesEnabled(enabled); +} + +bool WKPreferencesGetMockCaptureDevicesEnabled(WKPreferencesRef preferencesRef) +{ + return toImpl(preferencesRef)->mockCaptureDevicesEnabled(); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferences.h b/Source/WebKit2/UIProcess/API/C/WKPreferencesRef.h index a9865d15f..c352038bf 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferences.h +++ b/Source/WebKit2/UIProcess/API/C/WKPreferencesRef.h @@ -23,10 +23,10 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKPreferences_h -#define WKPreferences_h +#ifndef WKPreferencesRef_h +#define WKPreferencesRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifndef __cplusplus #include <stdbool.h> @@ -43,6 +43,12 @@ enum WKStorageBlockingPolicy { }; typedef enum WKStorageBlockingPolicy WKStorageBlockingPolicy; +enum WKDebugOverlayRegionFlags { + kWKNonFastScrollableRegion = 1 << 0, + kWKWheelEventHandlerRegion = 1 << 1 +}; +typedef unsigned WKDebugOverlayRegions; + WK_EXPORT WKTypeID WKPreferencesGetTypeID(); WK_EXPORT WKPreferencesRef WKPreferencesCreate(); @@ -144,10 +150,6 @@ WK_EXPORT bool WKPreferencesGetPrivateBrowsingEnabled(WKPreferencesRef preferenc WK_EXPORT void WKPreferencesSetDeveloperExtrasEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetDeveloperExtrasEnabled(WKPreferencesRef preferencesRef); -// Defaults to false. -WK_EXPORT void WKPreferencesSetJavaScriptExperimentsEnabled(WKPreferencesRef preferencesRef, bool enabled); -WK_EXPORT bool WKPreferencesGetJavaScriptExperimentsEnabled(WKPreferencesRef preferencesRef); - // Defaults to true. WK_EXPORT void WKPreferencesSetTextAreasAreResizable(WKPreferencesRef preferencesRef, bool resizable); WK_EXPORT bool WKPreferencesGetTextAreasAreResizable(WKPreferencesRef preferencesRef); @@ -180,6 +182,10 @@ WK_EXPORT bool WKPreferencesGetFullScreenEnabled(WKPreferencesRef preferencesRef WK_EXPORT void WKPreferencesSetAVFoundationEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetAVFoundationEnabled(WKPreferencesRef preferencesRef); +// Defaults to false. +WK_EXPORT void WKPreferencesSetAVFoundationNSURLSessionEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetAVFoundationNSURLSessionEnabled(WKPreferencesRef preferencesRef); + // Defaults to false WK_EXPORT void WKPreferencesSetWebAudioEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetWebAudioEnabled(WKPreferencesRef preferencesRef); @@ -216,7 +222,7 @@ WK_EXPORT bool WKPreferencesGetNotificationsEnabled(WKPreferencesRef preferences WK_EXPORT void WKPreferencesSetShouldRespectImageOrientation(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetShouldRespectImageOrientation(WKPreferencesRef preferencesRef); -// Defaults to false +// Defaults to kWKAllowAllStorage WK_EXPORT void WKPreferencesSetStorageBlockingPolicy(WKPreferencesRef preferencesRef, WKStorageBlockingPolicy policy); WK_EXPORT WKStorageBlockingPolicy WKPreferencesGetStorageBlockingPolicy(WKPreferencesRef preferencesRef); @@ -240,12 +246,28 @@ WK_EXPORT bool WKPreferencesGetQTKitEnabled(WKPreferencesRef preferencesRef); WK_EXPORT void WKPreferencesSetAsynchronousSpellCheckingEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetAsynchronousSpellCheckingEnabled(WKPreferencesRef preferencesRef); +// Defaults to false +WK_EXPORT void WKPreferencesSetMediaStreamEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetMediaStreamEnabled(WKPreferencesRef preferencesRef); + // Defaults to false. WK_EXPORT void WKPreferencesSetSpatialNavigationEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetSpatialNavigationEnabled(WKPreferencesRef preferencesRef); +// Defaults to 0. +WK_EXPORT void WKPreferencesSetVisibleDebugOverlayRegions(WKPreferencesRef preferencesRef, WKDebugOverlayRegions enabled); +WK_EXPORT WKDebugOverlayRegions WKPreferencesGetVisibleDebugOverlayRegions(WKPreferencesRef preferencesRef); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetIgnoreViewportScalingConstraints(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetIgnoreViewportScalingConstraints(WKPreferencesRef preferencesRef); + +// Defaults to true. +WK_EXPORT void WKPreferencesSetAllowsAirPlayForMediaPlayback(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetAllowsAirPlayForMediaPlayback(WKPreferencesRef preferencesRef); + #ifdef __cplusplus } #endif -#endif /* WKPreferences_h */ +#endif /* WKPreferencesRef_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h b/Source/WebKit2/UIProcess/API/C/WKPreferencesRefPrivate.h index 1c957563f..0c6cc6976 100644 --- a/Source/WebKit2/UIProcess/API/C/WKPreferencesPrivate.h +++ b/Source/WebKit2/UIProcess/API/C/WKPreferencesRefPrivate.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,7 +26,7 @@ #ifndef WKPreferencesPrivate_h #define WKPreferencesPrivate_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -52,6 +52,11 @@ enum WKEditableLinkBehavior { }; typedef enum WKEditableLinkBehavior WKEditableLinkBehavior; +enum WKJavaScriptRuntimeFlags { + kWKJavaScriptRuntimeFlagsAllEnabled = 0 +}; +typedef unsigned WKJavaScriptRuntimeFlagSet; + // Creates a copy with no identifier. WK_EXPORT WKPreferencesRef WKPreferencesCreateCopy(WKPreferencesRef); @@ -92,28 +97,28 @@ WK_EXPORT void WKPreferencesSetTiledScrollingIndicatorVisible(WKPreferencesRef, WK_EXPORT bool WKPreferencesGetTiledScrollingIndicatorVisible(WKPreferencesRef); // Defaults to true. -WK_EXPORT void WKPreferencesSetCSSCustomFilterEnabled(WKPreferencesRef, bool flag); -WK_EXPORT bool WKPreferencesGetCSSCustomFilterEnabled(WKPreferencesRef); - -// Defaults to false. WK_EXPORT void WKPreferencesSetWebGLEnabled(WKPreferencesRef, bool); WK_EXPORT bool WKPreferencesGetWebGLEnabled(WKPreferencesRef); // Defaults to false. +WK_EXPORT void WKPreferencesSetForceSoftwareWebGLRendering(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetForceSoftwareWebGLRendering(WKPreferencesRef); + +// Defaults to false. WK_EXPORT void WKPreferencesSetAccelerated2DCanvasEnabled(WKPreferencesRef, bool); WK_EXPORT bool WKPreferencesGetAccelerated2DCanvasEnabled(WKPreferencesRef); // Defaults to true -WK_EXPORT void WKPreferencesSetCSSRegionsEnabled(WKPreferencesRef, bool flag); -WK_EXPORT bool WKPreferencesGetCSSRegionsEnabled(WKPreferencesRef); +WK_EXPORT void WKPreferencesSetCSSAnimationTriggersEnabled(WKPreferencesRef, bool flag); +WK_EXPORT bool WKPreferencesGetCSSAnimationTriggersEnabled(WKPreferencesRef); // Defaults to false -WK_EXPORT void WKPreferencesSetCSSGridLayoutEnabled(WKPreferencesRef, bool flag); -WK_EXPORT bool WKPreferencesGetCSSGridLayoutEnabled(WKPreferencesRef); +WK_EXPORT void WKPreferencesSetWebAnimationsEnabled(WKPreferencesRef, bool flag); +WK_EXPORT bool WKPreferencesGetWebAnimationsEnabled(WKPreferencesRef); -// Defaults to false -WK_EXPORT void WKPreferencesSetRegionBasedColumnsEnabled(WKPreferencesRef, bool flag); -WK_EXPORT bool WKPreferencesGetRegionBasedColumnsEnabled(WKPreferencesRef); +// Defaults to true +WK_EXPORT void WKPreferencesSetCSSRegionsEnabled(WKPreferencesRef, bool flag); +WK_EXPORT bool WKPreferencesGetCSSRegionsEnabled(WKPreferencesRef); // Defaults to false. WK_EXPORT void WKPreferencesSetNeedsSiteSpecificQuirks(WKPreferencesRef, bool); @@ -127,6 +132,10 @@ WK_EXPORT bool WKPreferencesGetForceFTPDirectoryListings(WKPreferencesRef prefer WK_EXPORT void WKPreferencesSetFTPDirectoryTemplatePath(WKPreferencesRef preferences, WKStringRef path); WK_EXPORT WKStringRef WKPreferencesCopyFTPDirectoryTemplatePath(WKPreferencesRef preferences); +// Defaults to true. +WK_EXPORT void WKPreferencesSetDOMTimersThrottlingEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetDOMTimersThrottlingEnabled(WKPreferencesRef preferences); + // Defaults to false. WK_EXPORT void WKPreferencesSetWebArchiveDebugModeEnabled(WKPreferencesRef preferences, bool enabled); WK_EXPORT bool WKPreferencesGetWebArchiveDebugModeEnabled(WKPreferencesRef preferences); @@ -171,23 +180,35 @@ WK_EXPORT bool WKPreferencesGetHixie76WebSocketProtocolEnabled(WKPreferencesRef WK_EXPORT void WKPreferencesSetMediaPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef, bool flag); WK_EXPORT bool WKPreferencesGetMediaPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef); +// Defaults to false. +WK_EXPORT void WKPreferencesSetAudioPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef, bool flag); +WK_EXPORT bool WKPreferencesGetAudioPlaybackRequiresUserGesture(WKPreferencesRef preferencesRef); + // Defaults to true. WK_EXPORT void WKPreferencesSetMediaPlaybackAllowsInline(WKPreferencesRef preferencesRef, bool flag); WK_EXPORT bool WKPreferencesGetMediaPlaybackAllowsInline(WKPreferencesRef preferencesRef); // Defaults to false. +WK_EXPORT void WKPreferencesSetInlineMediaPlaybackRequiresPlaysInlineAttribute(WKPreferencesRef preferencesRef, bool flag); +WK_EXPORT bool WKPreferencesGetInlineMediaPlaybackRequiresPlaysInlineAttribute(WKPreferencesRef preferencesRef); + +// Defaults to false on iOS, true elsewhere. +WK_EXPORT void WKPreferencesSetMediaControlsScaleWithPageZoom(WKPreferencesRef preferencesRef, bool flag); +WK_EXPORT bool WKPreferencesGetMediaControlsScaleWithPageZoom(WKPreferencesRef preferencesRef); + +// Defaults to false. WK_EXPORT void WKPreferencesSetShowsToolTipOverTruncatedText(WKPreferencesRef preferencesRef, bool flag); WK_EXPORT bool WKPreferencesGetShowsToolTipOverTruncatedText(WKPreferencesRef preferencesRef); // Defaults to false. WK_EXPORT void WKPreferencesSetMockScrollbarsEnabled(WKPreferencesRef preferencesRef, bool flag); WK_EXPORT bool WKPreferencesGetMockScrollbarsEnabled(WKPreferencesRef preferencesRef); - -// Defaults to false. + +// Deprecated. Always returns false. WK_EXPORT void WKPreferencesSetApplicationChromeModeEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetApplicationChromeModeEnabled(WKPreferencesRef preferencesRef); -// Defaults to false. +// Deprecated. Always returns false. WK_EXPORT void WKPreferencesSetInspectorUsesWebKitUserInterface(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetInspectorUsesWebKitUserInterface(WKPreferencesRef preferencesRef); @@ -228,14 +249,10 @@ WK_EXPORT void WKPreferencesSetScrollingPerformanceLoggingEnabled(WKPreferencesR WK_EXPORT bool WKPreferencesGetScrollingPerformanceLoggingEnabled(WKPreferencesRef preferencesRef); // Defaults to true -WK_EXPORT void WKPreferencesSetScreenFontSubstitutionEnabled(WKPreferencesRef preferences, bool enabled); -WK_EXPORT bool WKPreferencesGetScreenFontSubstitutionEnabled(WKPreferencesRef preferences); - -// Defaults to true WK_EXPORT void WKPreferencesSetCookieEnabled(WKPreferencesRef preferences, bool enabled); WK_EXPORT bool WKPreferencesGetCookieEnabled(WKPreferencesRef preferences); -// Defaults to false +// Defaults to true on Mac, false elsewhere WK_EXPORT void WKPreferencesSetPDFPluginEnabled(WKPreferencesRef preferences, bool enabled); WK_EXPORT bool WKPreferencesGetPDFPluginEnabled(WKPreferencesRef preferences); @@ -247,7 +264,7 @@ WK_EXPORT bool WKPreferencesGetAggressiveTileRetentionEnabled(WKPreferencesRef p WK_EXPORT void WKPreferencesSetLogsPageMessagesToSystemConsoleEnabled(WKPreferencesRef preferences, bool enabled); WK_EXPORT bool WKPreferencesGetLogsPageMessagesToSystemConsoleEnabled(WKPreferencesRef preferences); -// Defaults to false +// Defaults to true WK_EXPORT void WKPreferencesSetPageVisibilityBasedProcessSuppressionEnabled(WKPreferencesRef preferences, bool enabled); WK_EXPORT bool WKPreferencesGetPageVisibilityBasedProcessSuppressionEnabled(WKPreferencesRef); @@ -283,12 +300,108 @@ WK_EXPORT bool WKPreferencesGetAutostartOriginPlugInSnapshottingEnabled(WKPrefer WK_EXPORT void WKPreferencesSetPrimaryPlugInSnapshotDetectionEnabled(WKPreferencesRef preferencesRef, bool enabled); WK_EXPORT bool WKPreferencesGetPrimaryPlugInSnapshotDetectionEnabled(WKPreferencesRef preferencesRef); +// Defaults to true +WK_EXPORT void WKPreferencesSetThreadedScrollingEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetThreadedScrollingEnabled(WKPreferencesRef preferencesRef); + // Defaults to 5 seconds. WK_EXPORT void WKPreferencesSetIncrementalRenderingSuppressionTimeout(WKPreferencesRef preferencesRef, double timeout); WK_EXPORT double WKPreferencesGetIncrementalRenderingSuppressionTimeout(WKPreferencesRef preferencesRef); +// Defaults to true. +WK_EXPORT void WKPreferencesSetSimpleLineLayoutEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetSimpleLineLayoutEnabled(WKPreferencesRef); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetSimpleLineLayoutDebugBordersEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetSimpleLineLayoutDebugBordersEnabled(WKPreferencesRef); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetNewBlockInsideInlineModelEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetNewBlockInsideInlineModelEnabled(WKPreferencesRef); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetSubpixelCSSOMElementMetricsEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetSubpixelCSSOMElementMetricsEnabled(WKPreferencesRef); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetUseGiantTiles(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetUseGiantTiles(WKPreferencesRef); + WK_EXPORT void WKPreferencesResetTestRunnerOverrides(WKPreferencesRef preferencesRef); +// Defaults to false. +WK_EXPORT void WKPreferencesSetUseLegacyTextAlignPositionedElementBehavior(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesUseLegacyTextAlignPositionedElementBehavior(WKPreferencesRef preferencesRef); + +// Defaults to true. +WK_EXPORT void WKPreferencesSetMediaSourceEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetMediaSourceEnabled(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetViewGestureDebuggingEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetViewGestureDebuggingEnabled(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetShouldConvertPositionStyleOnCopy(WKPreferencesRef preferencesRef, bool convert); +WK_EXPORT bool WKPreferencesGetShouldConvertPositionStyleOnCopy(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetTelephoneNumberParsingEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetTelephoneNumberParsingEnabled(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetEnableInheritURIQueryComponent(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetEnableInheritURIQueryComponent(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetServiceControlsEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetServiceControlsEnabled(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetImageControlsEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetImageControlsEnabled(WKPreferencesRef preferencesRef); + +// Default to false. +WK_EXPORT void WKPreferencesSetGamepadsEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetGamepadsEnabled(WKPreferencesRef preferencesRef); + +// Not implemented, should be deleted once there are no callers. +WK_EXPORT void WKPreferencesSetLongMousePressEnabled(WKPreferencesRef preferencesRef, bool enabled); +WK_EXPORT bool WKPreferencesGetLongMousePressEnabled(WKPreferencesRef preferencesRef); + +// Defaults to 0. Setting this to 0 disables font autosizing on iOS. +WK_EXPORT void WKPreferencesSetMinimumZoomFontSize(WKPreferencesRef preferencesRef, double); +WK_EXPORT double WKPreferencesGetMinimumZoomFontSize(WKPreferencesRef preferencesRef); + +// Not implemented, should be deleted once Safari no longer uses this function. +WK_EXPORT void WKPreferencesSetScreenFontSubstitutionEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetScreenFontSubstitutionEnabled(WKPreferencesRef preferences); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetAntialiasedFontDilationEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetAntialiasedFontDilationEnabled(WKPreferencesRef preferences); + +// Defaults to 0. +WK_EXPORT void WKPreferencesSetJavaScriptRuntimeFlags(WKPreferencesRef preferences, WKJavaScriptRuntimeFlagSet javascriptRuntimeFlagSet); +WK_EXPORT WKJavaScriptRuntimeFlagSet WKPreferencesGetJavaScriptRuntimeFlags(WKPreferencesRef preferences); + +// Defaults to true. +WK_EXPORT void WKPreferencesSetMetaRefreshEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetMetaRefreshEnabled(WKPreferencesRef preferences); + +// Defaults to true. +WK_EXPORT void WKPreferencesSetHTTPEquivEnabled(WKPreferencesRef preferences, bool enabled); +WK_EXPORT bool WKPreferencesGetHTTPEquivEnabled(WKPreferencesRef preferences); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetResourceUsageOverlayVisible(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetResourceUsageOverlayVisible(WKPreferencesRef); + +// Defaults to false. +WK_EXPORT void WKPreferencesSetMockCaptureDevicesEnabled(WKPreferencesRef, bool); +WK_EXPORT bool WKPreferencesGetMockCaptureDevicesEnabled(WKPreferencesRef); + #ifdef __cplusplus } #endif diff --git a/Source/WebKit2/UIProcess/API/C/WKProtectionSpace.h b/Source/WebKit2/UIProcess/API/C/WKProtectionSpace.h index c77d93ba0..ff7ca8742 100644 --- a/Source/WebKit2/UIProcess/API/C/WKProtectionSpace.h +++ b/Source/WebKit2/UIProcess/API/C/WKProtectionSpace.h @@ -26,8 +26,8 @@ #ifndef WKProtectionSpace_h #define WKProtectionSpace_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKProtectionSpaceTypes.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKProtectionSpaceTypes.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKProtectionSpaceTypes.h b/Source/WebKit2/UIProcess/API/C/WKProtectionSpaceTypes.h index fd1bd09d2..474146049 100644 --- a/Source/WebKit2/UIProcess/API/C/WKProtectionSpaceTypes.h +++ b/Source/WebKit2/UIProcess/API/C/WKProtectionSpaceTypes.h @@ -26,7 +26,7 @@ #ifndef WKProtectionSpaceTypes_h #define WKProtectionSpaceTypes_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.cpp b/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.cpp index a5711e014..0e3c7a2d6 100644 --- a/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.cpp @@ -26,27 +26,68 @@ #include "config.h" #include "WKResourceCacheManager.h" -#include "WebResourceCacheManagerProxy.h" +#include "APIWebsiteDataStore.h" #include "WKAPICast.h" +#include "WebsiteDataRecord.h" using namespace WebKit; WKTypeID WKResourceCacheManagerGetTypeID() { - return toAPI(WebResourceCacheManagerProxy::APIType); + return toAPI(API::WebsiteDataStore::APIType); } -void WKResourceCacheManagerGetCacheOrigins(WKResourceCacheManagerRef cacheManagerRef, void* context, WKResourceCacheManagerGetCacheOriginsFunction callback) +static WebsiteDataTypes toWebsiteDataTypes(WKResourceCachesToClear cachesToClear) { - toImpl(cacheManagerRef)->getCacheOrigins(ArrayCallback::create(context, callback)); + using WebsiteDataTypes = WebKit::WebsiteDataTypes; + + int websiteDataTypes = WebsiteDataTypeMemoryCache; + + if (cachesToClear == WKResourceCachesToClearAll) + websiteDataTypes |= WebsiteDataTypeDiskCache; + + return static_cast<WebsiteDataTypes>(websiteDataTypes); +} + +void WKResourceCacheManagerGetCacheOrigins(WKResourceCacheManagerRef cacheManager, void* context, WKResourceCacheManagerGetCacheOriginsFunction callback) +{ + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(cacheManager))->websiteDataStore(); + websiteDataStore.fetchData(toWebsiteDataTypes(WKResourceCachesToClearAll), [context, callback](Vector<WebsiteDataRecord> dataRecords) { + Vector<RefPtr<API::Object>> securityOrigins; + for (const auto& dataRecord : dataRecords) { + for (const auto& origin : dataRecord.origins) + securityOrigins.append(API::SecurityOrigin::create(*origin)); + } + + callback(toAPI(API::Array::create(WTFMove(securityOrigins)).ptr()), nullptr, context); + }); } -void WKResourceCacheManagerClearCacheForOrigin(WKResourceCacheManagerRef cacheManagerRef, WKSecurityOriginRef originRef, WKResourceCachesToClear cachesToClear) +void WKResourceCacheManagerClearCacheForOrigin(WKResourceCacheManagerRef cacheManager, WKSecurityOriginRef origin, WKResourceCachesToClear cachesToClear) { - toImpl(cacheManagerRef)->clearCacheForOrigin(toImpl(originRef), toResourceCachesToClear(cachesToClear)); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(cacheManager))->websiteDataStore(); + + Vector<WebsiteDataRecord> dataRecords; + + { + WebsiteDataRecord dataRecord; + dataRecord.add(WebsiteDataTypes::WebsiteDataTypeMemoryCache, &toImpl(origin)->securityOrigin()); + + dataRecords.append(dataRecord); + } + + if (cachesToClear == WKResourceCachesToClearAll) { + WebsiteDataRecord dataRecord; + dataRecord.add(WebsiteDataTypes::WebsiteDataTypeDiskCache, &toImpl(origin)->securityOrigin()); + + dataRecords.append(dataRecord); + } + + websiteDataStore.removeData(toWebsiteDataTypes(cachesToClear), dataRecords, [] { }); } -void WKResourceCacheManagerClearCacheForAllOrigins(WKResourceCacheManagerRef cacheManagerRef, WKResourceCachesToClear cachesToClear) +void WKResourceCacheManagerClearCacheForAllOrigins(WKResourceCacheManagerRef cacheManager, WKResourceCachesToClear cachesToClear) { - toImpl(cacheManagerRef)->clearCacheForAllOrigins(toResourceCachesToClear(cachesToClear)); + auto& websiteDataStore = toImpl(reinterpret_cast<WKWebsiteDataStoreRef>(cacheManager))->websiteDataStore(); + websiteDataStore.removeData(toWebsiteDataTypes(cachesToClear), std::chrono::system_clock::time_point::min(), [] { }); } diff --git a/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.h b/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.h index 80c4531ff..7f4bb6c51 100644 --- a/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.h +++ b/Source/WebKit2/UIProcess/API/C/WKResourceCacheManager.h @@ -26,7 +26,7 @@ #ifndef WKResourceCacheManager_h #define WKResourceCacheManager_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKNetworkInfo.cpp b/Source/WebKit2/UIProcess/API/C/WKSessionRef.cpp index a9bfd3cb1..a93579087 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNetworkInfo.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKSessionRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,30 +24,29 @@ */ #include "config.h" -#include "WKNetworkInfo.h" +#include "WKSessionRef.h" -#if ENABLE(NETWORK_INFO) +#include "APISession.h" #include "WKAPICast.h" -#include "WebNetworkInfo.h" using namespace WebKit; -#endif -WKTypeID WKNetworkInfoGetTypeID() +WKSessionRef WKSessionCreate(bool isEphemeral) { -#if ENABLE(NETWORK_INFO) - return toAPI(WebNetworkInfo::APIType); -#else - return 0; -#endif + // The implementation doesn't support non-ephemeral + if (!isEphemeral) + return nullptr; + + RefPtr<API::Session> session = API::Session::createEphemeral(); + return toAPI(session.release().leakRef()); +} + +WKTypeID WKSessionGetTypeID() +{ + return toAPI(API::Session::APIType); } -WKNetworkInfoRef WKNetworkInfoCreate(double bandwidth, bool isMetered) +bool WKSessionIsEphemeral(WKSessionRef sessionRef) { -#if ENABLE(NETWORK_INFO) - RefPtr<WebNetworkInfo> networkInfo = WebNetworkInfo::create(bandwidth, isMetered); - return toAPI(networkInfo.release().leakRef()); -#else - return 0; -#endif + return toAPI(toImpl(sessionRef)->isEphemeral()); } diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.h b/Source/WebKit2/UIProcess/API/C/WKSessionRef.h index d8afdc432..693902677 100644 --- a/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.h +++ b/Source/WebKit2/UIProcess/API/C/WKSessionRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2014 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,27 +23,24 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKViewEfl_h -#define WKViewEfl_h +#ifndef WKSessionRef_h +#define WKSessionRef_h -#include <WebKit2/WKBase.h> - -typedef struct _cairo_surface cairo_surface_t; +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT void WKViewPaintToCairoSurface(WKViewRef, cairo_surface_t*); - -WK_EXPORT WKImageRef WKViewCreateSnapshot(WKViewRef); +/* FIXME: We can create sessions on demand, because we hardcode the fact that all sessions but the default one are ephemeral. We'll need to create them explicitly once sessions have more configuration options. */ +WK_EXPORT WKSessionRef WKSessionCreate(bool isEphemeral); -WK_EXPORT void WKViewSetThemePath(WKViewRef, WKStringRef); +WK_EXPORT WKTypeID WKSessionGetTypeID(); -WK_EXPORT void WKViewSendTouchEvent(WKViewRef, WKTouchEventRef); +WK_EXPORT bool WKSessionIsEphemeral(WKSessionRef session); #ifdef __cplusplus } #endif -#endif /* WKViewEfl_h */ +#endif /* WKSessionRef_h */ diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKView.cpp b/Source/WebKit2/UIProcess/API/C/WKSessionStateRef.cpp index 3e69a9908..98e717519 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKView.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKSessionStateRef.cpp @@ -1,7 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 Igalia S.L. + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,26 +24,29 @@ */ #include "config.h" -#include "WKView.h" +#include "WKSessionStateRef.h" +#include "APIData.h" +#include "APISessionState.h" +#include "LegacySessionStateCoding.h" +#include "SessionState.h" #include "WKAPICast.h" -#include "WKViewPrivate.h" -#include "WebKitWebViewBasePrivate.h" -using namespace WebKit; -using namespace WebCore; - -WKViewRef WKViewCreate(WKContextRef contextRef, WKPageGroupRef pageGroupRef) +WKTypeID WKSessionStateGetTypeID() { - return toAPI(webkitWebViewBaseCreate(toImpl(contextRef), toImpl(pageGroupRef))); + return WebKit::toAPI(API::SessionState::APIType); } -WKPageRef WKViewGetPage(WKViewRef viewRef) +WKSessionStateRef WKSessionStateCreateFromData(WKDataRef data) { - return toAPI(webkitWebViewBaseGetPage(toImpl(viewRef))); + WebKit::SessionState sessionState; + if (!WebKit::decodeLegacySessionState(WebKit::toImpl(data)->bytes(), WebKit::toImpl(data)->size(), sessionState)) + return nullptr; + + return WebKit::toAPI(&API::SessionState::create(WTFMove(sessionState)).leakRef()); } -void WKViewSetFocus(WKViewRef viewRef, bool focused) +WKDataRef WKSessionStateCopyData(WKSessionStateRef sessionState) { - webkitWebViewBaseSetFocus(toImpl(viewRef), focused); + return WebKit::toAPI(WebKit::encodeLegacySessionState(WebKit::toImpl(sessionState)->sessionState()).release().leakRef()); } diff --git a/Source/WebKit2/UIProcess/API/C/WKNetworkInfo.h b/Source/WebKit2/UIProcess/API/C/WKSessionStateRef.h index cff864a75..e46b66414 100644 --- a/Source/WebKit2/UIProcess/API/C/WKNetworkInfo.h +++ b/Source/WebKit2/UIProcess/API/C/WKSessionStateRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2014 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,23 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKNetworkInfo_h -#define WKNetworkInfo_h +#ifndef WKSessionStateRef_h +#define WKSessionStateRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT WKTypeID WKNetworkInfoGetTypeID(); +WK_EXPORT WKTypeID WKSessionStateGetTypeID(); -WK_EXPORT WKNetworkInfoRef WKNetworkInfoCreate(double bandwidth, bool isMetered); +WK_EXPORT WKSessionStateRef WKSessionStateCreateFromData(WKDataRef data); + +WK_EXPORT WKDataRef WKSessionStateCopyData(WKSessionStateRef sessionState); #ifdef __cplusplus } #endif -#endif // WKNetworkInfo_h +#endif // WKSessionStateRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WKTextChecker.cpp b/Source/WebKit2/UIProcess/API/C/WKTextChecker.cpp index 3329da2e6..3279dd7a9 100644 --- a/Source/WebKit2/UIProcess/API/C/WKTextChecker.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKTextChecker.cpp @@ -32,29 +32,29 @@ using namespace WebKit; -void WKTextCheckerSetClient(const WKTextCheckerClient* wkClient) +void WKTextCheckerSetClient(const WKTextCheckerClientBase* wkClient) { if (wkClient && wkClient->version) return; - WebTextChecker::shared()->setClient(wkClient); + WebTextChecker::singleton()->setClient(wkClient); } void WKTextCheckerContinuousSpellCheckingEnabledStateChanged(bool enabled) { - WebTextChecker::shared()->continuousSpellCheckingEnabledStateChanged(enabled); + WebTextChecker::singleton()->continuousSpellCheckingEnabledStateChanged(enabled); } void WKTextCheckerGrammarCheckingEnabledStateChanged(bool enabled) { - WebTextChecker::shared()->grammarCheckingEnabledStateChanged(enabled); + WebTextChecker::singleton()->grammarCheckingEnabledStateChanged(enabled); } void WKTextCheckerCheckSpelling(WKPageRef page, bool startBeforeSelection) { - WebTextChecker::shared()->checkSpelling(toImpl(page), startBeforeSelection); + WebTextChecker::singleton()->checkSpelling(toImpl(page), startBeforeSelection); } void WKTextCheckerChangeSpellingToWord(WKPageRef page, WKStringRef word) { - WebTextChecker::shared()->changeSpellingToWord(toImpl(page), toWTFString(word)); + WebTextChecker::singleton()->changeSpellingToWord(toImpl(page), toWTFString(word)); } diff --git a/Source/WebKit2/UIProcess/API/C/WKTextChecker.h b/Source/WebKit2/UIProcess/API/C/WKTextChecker.h index 6a05ed98a..a32469461 100644 --- a/Source/WebKit2/UIProcess/API/C/WKTextChecker.h +++ b/Source/WebKit2/UIProcess/API/C/WKTextChecker.h @@ -26,7 +26,7 @@ #ifndef WKTextChecker_h #define WKTextChecker_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -50,9 +50,14 @@ typedef WKArrayRef (*WKTextCheckerGuessesForWord)(uint64_t tag, WKStringRef word typedef void (*WKTextCheckerLearnWord)(uint64_t tag, WKStringRef word, const void *clientInfo); typedef void (*WKTextCheckerIgnoreWord)(uint64_t tag, WKStringRef word, const void *clientInfo); -struct WKTextCheckerClient { +typedef struct WKTextCheckerClientBase { int version; const void * clientInfo; +} WKTextCheckerClientBase; + +typedef struct WKTextCheckerClientV0 { + WKTextCheckerClientBase base; + WKTextCheckerContinousSpellCheckingAllowed continuousSpellCheckingAllowed; WKTextCheckerContinousSpellCheckingEnabled continuousSpellCheckingEnabled; WKTextCheckerSetContinousSpellCheckingEnabled setContinuousSpellCheckingEnabled; @@ -69,12 +74,9 @@ struct WKTextCheckerClient { WKTextCheckerGuessesForWord guessesForWord; WKTextCheckerLearnWord learnWord; WKTextCheckerIgnoreWord ignoreWord; -}; -typedef struct WKTextCheckerClient WKTextCheckerClient; - -enum { kWKTextCheckerClientCurrentVersion = 0 }; +} WKTextCheckerClientV0; -WK_EXPORT void WKTextCheckerSetClient(const WKTextCheckerClient* client); +WK_EXPORT void WKTextCheckerSetClient(const WKTextCheckerClientBase* client); WK_EXPORT void WKTextCheckerContinuousSpellCheckingEnabledStateChanged(bool); WK_EXPORT void WKTextCheckerGrammarCheckingEnabledStateChanged(bool); diff --git a/Source/WebKit2/UIProcess/API/C/WKUserContentControllerRef.cpp b/Source/WebKit2/UIProcess/API/C/WKUserContentControllerRef.cpp new file mode 100644 index 000000000..bb73853ba --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKUserContentControllerRef.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2015 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 "WKUserContentControllerRef.h" + +#include "APIUserContentExtension.h" +#include "APIUserScript.h" +#include "WKAPICast.h" +#include "WebUserContentControllerProxy.h" + +using namespace WebKit; + +WKTypeID WKUserContentControllerGetTypeID() +{ + return toAPI(WebUserContentControllerProxy::APIType); +} + +WKUserContentControllerRef WKUserContentControllerCreate() +{ + return toAPI(&WebUserContentControllerProxy::create().leakRef()); +} + +WKArrayRef WKUserContentControllerCopyUserScripts(WKUserContentControllerRef userContentControllerRef) +{ + Ref<API::Array> userScripts = toImpl(userContentControllerRef)->userScripts().copy(); + return toAPI(&userScripts.leakRef()); +} + +void WKUserContentControllerAddUserScript(WKUserContentControllerRef userContentControllerRef, WKUserScriptRef userScriptRef) +{ + toImpl(userContentControllerRef)->addUserScript(*toImpl(userScriptRef)); +} + +void WKUserContentControllerRemoveAllUserScripts(WKUserContentControllerRef userContentControllerRef) +{ + toImpl(userContentControllerRef)->removeAllUserScripts(); +} + +void WKUserContentControllerAddUserContentFilter(WKUserContentControllerRef userContentControllerRef, WKUserContentFilterRef userContentFilterRef) +{ +#if ENABLE(CONTENT_EXTENSIONS) + toImpl(userContentControllerRef)->addUserContentExtension(*toImpl(userContentFilterRef)); +#endif +} + +void WKUserContentControllerRemoveAllUserContentFilters(WKUserContentControllerRef userContentControllerRef) +{ +#if ENABLE(CONTENT_EXTENSIONS) + toImpl(userContentControllerRef)->removeAllUserContentExtensions(); +#endif +} diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKFullScreenClientGtk.h b/Source/WebKit2/UIProcess/API/C/WKUserContentControllerRef.h index a8c92166b..d462e99b1 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKFullScreenClientGtk.h +++ b/Source/WebKit2/UIProcess/API/C/WKUserContentControllerRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 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,32 +23,28 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKFullScreenClientGtk_h -#define WKFullScreenClientGtk_h +#ifndef WKUserContentControllerRef_h +#define WKUserContentControllerRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -typedef bool (*WKFullScreenClientGtkWillEnterFullScreenCallback)(const void* clientInfo); -typedef bool (*WKFullScreenClientGtkWillExitFullScreenCallback)(const void* clientInfo); +WK_EXPORT WKTypeID WKUserContentControllerGetTypeID(); -struct WKFullScreenClientGtk { - int version; - const void* clientInfo; - WKFullScreenClientGtkWillEnterFullScreenCallback willEnterFullScreen; - WKFullScreenClientGtkWillExitFullScreenCallback willExitFullScreen; -}; -typedef struct WKFullScreenClientGtk WKFullScreenClientGtk; +WK_EXPORT WKUserContentControllerRef WKUserContentControllerCreate(); -enum { kWKFullScreenClientGtkCurrentVersion = 0 }; +WK_EXPORT WKArrayRef WKUserContentControllerCopyUserScripts(WKUserContentControllerRef userContentController); +WK_EXPORT void WKUserContentControllerAddUserScript(WKUserContentControllerRef userContentController, WKUserScriptRef userScript); +WK_EXPORT void WKUserContentControllerRemoveAllUserScripts(WKUserContentControllerRef userContentController); -WK_EXPORT void WKViewSetFullScreenClientGtk(WKViewRef viewRef, const WKFullScreenClientGtk* client); +WK_EXPORT void WKUserContentControllerAddUserContentFilter(WKUserContentControllerRef userContentController, WKUserContentFilterRef userContentFilter); +WK_EXPORT void WKUserContentControllerRemoveAllUserContentFilters(WKUserContentControllerRef userContentController); #ifdef __cplusplus } #endif -#endif /* WKFullScreenClientGtk_h */ +#endif /* WKUserContentControllerRef_h */ diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKFullScreenClientGtk.cpp b/Source/WebKit2/UIProcess/API/C/WKUserContentExtensionStoreRef.cpp index 2b29a2b76..6fe872e62 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKFullScreenClientGtk.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKUserContentExtensionStoreRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,14 +24,18 @@ */ #include "config.h" -#include "WKFullScreenClientGtk.h" +#include "WKUserContentExtensionStoreRef.h" +#include "APIUserContentExtensionStore.h" #include "WKAPICast.h" -#include "WebKitWebViewBasePrivate.h" using namespace WebKit; -void WKViewSetFullScreenClientGtk(WKViewRef viewRef, const WKFullScreenClientGtk* wkClient) +WKTypeID WKUserContentExtensionStoreGetTypeID() { - webkitWebViewBaseInitializeFullScreenClient(toImpl(viewRef), wkClient); +#if ENABLE(CONTENT_EXTENSIONS) + return toAPI(API::UserContentExtensionStore::APIType); +#else + return 0; +#endif } diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.h b/Source/WebKit2/UIProcess/API/C/WKUserContentExtensionStoreRef.h index 36954ffe3..53598ec80 100644 --- a/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.h +++ b/Source/WebKit2/UIProcess/API/C/WKUserContentExtensionStoreRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 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,20 +23,19 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKContextSoup_h -#define WKContextSoup_h +#ifndef WKUserContentExtensionStoreRef_h +#define WKUserContentExtensionStoreRef_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKSoupRequestManager.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT WKSoupRequestManagerRef WKContextGetSoupRequestManager(WKContextRef context); +WK_EXPORT WKTypeID WKUserContentExtensionStoreGetTypeID(); #ifdef __cplusplus } #endif -#endif /* WKContextSoup_h */ +#endif /* WKUserContentExtensionStoreRef_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionCheck.cpp b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionCheck.cpp new file mode 100644 index 000000000..371c813c3 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionCheck.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "config.h" +#include "WKUserMediaPermissionCheck.h" + +#include "UserMediaPermissionCheckProxy.h" +#include "WKAPICast.h" +#include "WKArray.h" +#include "WKMutableArray.h" +#include "WKString.h" + +using namespace WebKit; + +WKTypeID WKUserMediaPermissionCheckGetTypeID() +{ + return toAPI(UserMediaPermissionCheckProxy::APIType); +} + +void WKUserMediaPermissionCheckSetHasPersistentPermission(WKUserMediaPermissionCheckRef userMediaPermissionRequestRef, bool allowed) +{ + toImpl(userMediaPermissionRequestRef)->setHasPersistentPermission(allowed); +} + diff --git a/Source/WebKit2/UIProcess/API/mac/WKTextInputWindowController.h b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionCheck.h index d28beaca2..e0cb0a339 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKTextInputWindowController.h +++ b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionCheck.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2009, 2010 Apple Inc. All Rights Reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,7 +10,7 @@ * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR @@ -20,30 +20,25 @@ * 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. + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * */ -#ifndef WKTextInputWindowController_h -#define WKTextInputWindowController_h - -#if USE(APPKIT) - -@class WKTextInputPanel; +#ifndef WKUserMediaPermissionCheck_h +#define WKUserMediaPermissionCheck_h -@interface WKTextInputWindowController : NSObject { - WKTextInputPanel *_panel; -} - -+ (WKTextInputWindowController *)sharedTextInputWindowController; +#include <WebKit/WKBase.h> -- (NSTextInputContext *)inputContext; -- (BOOL)interpretKeyEvent:(NSEvent *)event usingLegacyCocoaTextInput:(BOOL)usingLegacyCocoaTextInput string:(NSString **)string; +#ifdef __cplusplus +extern "C" { +#endif -- (BOOL)hasMarkedText; -- (void)unmarkText; +WK_EXPORT WKTypeID WKUserMediaPermissionCheckGetTypeID(); -@end +WK_EXPORT void WKUserMediaPermissionCheckSetHasPersistentPermission(WKUserMediaPermissionCheckRef, bool); -#endif // USE(APPKIT) +#ifdef __cplusplus +} +#endif -#endif // WKTextInputWindowController_h +#endif /* WKMediaDevicesRequest_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionRequest.cpp b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionRequest.cpp new file mode 100644 index 000000000..c86f86771 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionRequest.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2014 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 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "WKUserMediaPermissionRequest.h" + +#include "UserMediaPermissionRequestProxy.h" +#include "WKAPICast.h" +#include "WKArray.h" +#include "WKMutableArray.h" +#include "WKString.h" + +using namespace WebKit; + +WKTypeID WKUserMediaPermissionRequestGetTypeID() +{ + return toAPI(UserMediaPermissionRequestProxy::APIType); +} + + +void WKUserMediaPermissionRequestAllow(WKUserMediaPermissionRequestRef userMediaPermissionRequestRef, WKStringRef audioDeviceUID, WKStringRef videoDeviceUID) +{ + toImpl(userMediaPermissionRequestRef)->allow(toWTFString(audioDeviceUID), toWTFString(videoDeviceUID)); +} + +void WKUserMediaPermissionRequestDeny(WKUserMediaPermissionRequestRef userMediaPermissionRequestRef) +{ + toImpl(userMediaPermissionRequestRef)->deny(); +} + +WKArrayRef WKUserMediaPermissionRequestVideoDeviceUIDs(WKUserMediaPermissionRequestRef userMediaPermissionRef) +{ + WKMutableArrayRef array = WKMutableArrayCreate(); +#if ENABLE(MEDIA_STREAM) + for (auto& deviceUID : toImpl(userMediaPermissionRef)->videoDeviceUIDs()) + WKArrayAppendItem(array, toAPI(API::String::create(deviceUID).ptr())); +#endif + return array; +} + +WKArrayRef WKUserMediaPermissionRequestAudioDeviceUIDs(WKUserMediaPermissionRequestRef userMediaPermissionRef) +{ + WKMutableArrayRef array = WKMutableArrayCreate(); +#if ENABLE(MEDIA_STREAM) + for (auto& deviceUID : toImpl(userMediaPermissionRef)->audioDeviceUIDs()) + WKArrayAppendItem(array, toAPI(API::String::create(deviceUID).ptr())); +#endif + return array; +} diff --git a/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionRequest.h b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionRequest.h new file mode 100644 index 000000000..764489a25 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKUserMediaPermissionRequest.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2014 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 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef WKUserMediaPermissionRequest_h +#define WKUserMediaPermissionRequest_h + +#include <WebKit/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT WKTypeID WKUserMediaPermissionRequestGetTypeID(); + +WK_EXPORT void WKUserMediaPermissionRequestAllow(WKUserMediaPermissionRequestRef, WKStringRef audioDeviceUID, WKStringRef videoDeviceUID); +WK_EXPORT void WKUserMediaPermissionRequestDeny(WKUserMediaPermissionRequestRef); + +WK_EXPORT WKArrayRef WKUserMediaPermissionRequestVideoDeviceUIDs(WKUserMediaPermissionRequestRef); +WK_EXPORT WKArrayRef WKUserMediaPermissionRequestAudioDeviceUIDs(WKUserMediaPermissionRequestRef); + +#ifdef __cplusplus +} +#endif + +#endif /* WKUserMediaPermissionRequest_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.cpp b/Source/WebKit2/UIProcess/API/C/WKUserScriptRef.cpp index cefa2d358..ad71b017c 100644 --- a/Source/WebKit2/UIProcess/API/C/efl/WKViewEfl.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKUserScriptRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,37 +24,34 @@ */ #include "config.h" -#include "WKViewEfl.h" +#include "WKUserScriptRef.h" -#include "EwkView.h" +#include "APIUserScript.h" #include "WKAPICast.h" -#include "WebViewEfl.h" -#include <WebKit2/WKImageCairo.h> using namespace WebKit; -void WKViewPaintToCairoSurface(WKViewRef viewRef, cairo_surface_t* surface) +WKTypeID WKUserScriptGetTypeID() { - static_cast<WebViewEfl*>(toImpl(viewRef))->paintToCairoSurface(surface); + return toAPI(API::UserScript::APIType); } -WKImageRef WKViewCreateSnapshot(WKViewRef viewRef) +WKUserScriptRef WKUserScriptCreateWithSource(WKStringRef sourceRef, _WKUserScriptInjectionTime injectionTime, bool forMainFrameOnly) { - EwkView* ewkView = static_cast<WebViewEfl*>(toImpl(viewRef))->ewkView(); - return WKImageCreateFromCairoSurface(ewkView->takeSnapshot().get(), 0 /* options */); + return toAPI(&API::UserScript::create(WebCore::UserScript { toWTFString(sourceRef), API::UserScript::generateUniqueURL(), { }, { }, toUserScriptInjectionTime(injectionTime), forMainFrameOnly ? WebCore::InjectInTopFrameOnly : WebCore::InjectInAllFrames }).leakRef()); } -void WKViewSetThemePath(WKViewRef viewRef, WKStringRef theme) +WKStringRef WKUserScriptCopySource(WKUserScriptRef userScriptRef) { - static_cast<WebViewEfl*>(toImpl(viewRef))->setThemePath(toImpl(theme)->string()); + return toCopiedAPI(toImpl(userScriptRef)->userScript().source()); } -void WKViewSendTouchEvent(WKViewRef viewRef, WKTouchEventRef touchEventRef) +_WKUserScriptInjectionTime WKUserScriptGetInjectionTime(WKUserScriptRef userScriptRef) { -#if ENABLE(TOUCH_EVENTS) - static_cast<WebViewEfl*>(toImpl(viewRef))->sendTouchEvent(toImpl(touchEventRef)); -#else - UNUSED_PARAM(viewRef); - UNUSED_PARAM(touchEventRef); -#endif + return toWKUserScriptInjectionTime(toImpl(userScriptRef)->userScript().injectionTime()); +} + +bool WKUserScriptGetMainFrameOnly(WKUserScriptRef userScriptRef) +{ + return toImpl(userScriptRef)->userScript().injectedFrames() == WebCore::InjectInTopFrameOnly; } diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKInspectorPrivateMac.h b/Source/WebKit2/UIProcess/API/C/WKUserScriptRef.h index aef86a5d9..610f9fb58 100644 --- a/Source/WebKit2/UIProcess/API/C/mac/WKInspectorPrivateMac.h +++ b/Source/WebKit2/UIProcess/API/C/WKUserScriptRef.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,27 +23,26 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKInspectorPrivateMac_h -#define WKInspectorPrivateMac_h +#ifndef WKUserScriptRef_h +#define WKUserScriptRef_h + +#include <WebKit/WKBase.h> +#include <WebKit/WKUserScriptInjectionTime.h> #ifdef __cplusplus extern "C" { #endif -const NSInteger WKInspectorViewTag = 1000; - -// This class is the Web Inspector window delegate. It can be used to add interface -// actions that need to work when the Web Inspector window is key. -WK_EXPORT @interface WKWebInspectorProxyObjCAdapter : NSObject <NSWindowDelegate> { - void* _inspectorProxy; -} +WK_EXPORT WKTypeID WKUserScriptGetTypeID(); -@property (readonly) WKInspectorRef inspectorRef; +WK_EXPORT WKUserScriptRef WKUserScriptCreateWithSource(WKStringRef source, _WKUserScriptInjectionTime injectionTime, bool forMainFrameOnly); -@end +WK_EXPORT WKStringRef WKUserScriptCopySource(WKUserScriptRef userScript); +WK_EXPORT _WKUserScriptInjectionTime WKUserScriptGetInjectionTime(WKUserScriptRef userScript); +WK_EXPORT bool WKUserScriptGetMainFrameOnly(WKUserScriptRef userScript); #ifdef __cplusplus } #endif -#endif // WKInspectorPrivateMac_h +#endif /* WKUserScriptRef_h */ diff --git a/Source/WebKit2/UIProcess/API/C/WKVibration.cpp b/Source/WebKit2/UIProcess/API/C/WKVibration.cpp index e9d933ceb..b0aaab430 100644 --- a/Source/WebKit2/UIProcess/API/C/WKVibration.cpp +++ b/Source/WebKit2/UIProcess/API/C/WKVibration.cpp @@ -43,9 +43,12 @@ WKTypeID WKVibrationGetTypeID() #endif } -void WKVibrationSetProvider(WKVibrationRef vibrationRef, const WKVibrationProvider* wkProvider) +void WKVibrationSetProvider(WKVibrationRef vibrationRef, const WKVibrationProviderBase* wkProvider) { #if ENABLE(VIBRATION) toImpl(vibrationRef)->initializeProvider(wkProvider); +#else + UNUSED_PARAM(vibrationRef); + UNUSED_PARAM(wkProvider); #endif } diff --git a/Source/WebKit2/UIProcess/API/C/WKVibration.h b/Source/WebKit2/UIProcess/API/C/WKVibration.h index 4884ecd85..965749c86 100644 --- a/Source/WebKit2/UIProcess/API/C/WKVibration.h +++ b/Source/WebKit2/UIProcess/API/C/WKVibration.h @@ -26,7 +26,7 @@ #ifndef WKVibration_h #define WKVibration_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { @@ -36,19 +36,21 @@ extern "C" { typedef void (*WKVibrationProviderVibrateCallback)(WKVibrationRef vibrationRef, uint32_t vibrationTime, const void* clientInfo); typedef void (*WKVibrationProviderCancelVibrationCallback)(WKVibrationRef vibrationRef, const void* clientInfo); -struct WKVibrationProvider { +typedef struct WKVibrationProviderBase { int version; const void * clientInfo; +} WKVibrationProviderBase; + +typedef struct WKVibrationProviderV0 { + WKVibrationProviderBase base; + WKVibrationProviderVibrateCallback vibrate; WKVibrationProviderCancelVibrationCallback cancelVibration; -}; -typedef struct WKVibrationProvider WKVibrationProvider; - -enum { kWKVibrationProviderCurrentVersion = 0 }; +} WKVibrationProviderV0; WK_EXPORT WKTypeID WKVibrationGetTypeID(); -WK_EXPORT void WKVibrationSetProvider(WKVibrationRef vibrationRef, const WKVibrationProvider* provider); +WK_EXPORT void WKVibrationSetProvider(WKVibrationRef vibrationRef, const WKVibrationProviderBase* provider); #ifdef __cplusplus } diff --git a/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h b/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h index 125b09cc4..8ab84edac 100644 --- a/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h +++ b/Source/WebKit2/UIProcess/API/C/WKViewportAttributes.h @@ -26,8 +26,8 @@ #ifndef WKViewportAttributes_h #define WKViewportAttributes_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKGeometry.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKGeometry.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/C/WKWebsiteDataStoreRef.cpp b/Source/WebKit2/UIProcess/API/C/WKWebsiteDataStoreRef.cpp new file mode 100644 index 000000000..e9e907b63 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKWebsiteDataStoreRef.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2015 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 "WKWebsiteDataStoreRef.h" + +#include "APIWebsiteDataStore.h" +#include "WKAPICast.h" + +WKTypeID WKWebsiteDataStoreGetTypeID() +{ + return WebKit::toAPI(API::WebsiteDataStore::APIType); +} + +WKWebsiteDataStoreRef WKWebsiteDataStoreGetDefaultDataStore() +{ + return WebKit::toAPI(API::WebsiteDataStore::defaultDataStore().get()); +} + +WKWebsiteDataStoreRef WKWebsiteDataStoreCreateNonPersistentDataStore() +{ + return WebKit::toAPI(&API::WebsiteDataStore::createNonPersistentDataStore().leakRef()); +} diff --git a/Source/WebKit2/UIProcess/API/C/gtk/WKView.h b/Source/WebKit2/UIProcess/API/C/WKWebsiteDataStoreRef.h index 291dfe1b6..36990e3d4 100644 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKView.h +++ b/Source/WebKit2/UIProcess/API/C/WKWebsiteDataStoreRef.h @@ -1,7 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 Igalia S.L. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -25,21 +23,22 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKView_h -#define WKView_h +#ifndef WKWebsiteDataStoreRef_h +#define WKWebsiteDataStoreRef_h -#include <WebKit2/WKBase.h> +#include <WebKit/WKBase.h> #ifdef __cplusplus extern "C" { #endif -WK_EXPORT WKViewRef WKViewCreate(WKContextRef context, WKPageGroupRef pageGroup); +WK_EXPORT WKTypeID WKWebsiteDataStoreGetTypeID(); -WK_EXPORT WKPageRef WKViewGetPage(WKViewRef view); +WK_EXPORT WKWebsiteDataStoreRef WKWebsiteDataStoreGetDefaultDataStore(); +WK_EXPORT WKWebsiteDataStoreRef WKWebsiteDataStoreCreateNonPersistentDataStore(); #ifdef __cplusplus } #endif -#endif /* WKView_h */ +#endif /* WKWebsiteDataStoreRef_h */ diff --git a/Source/WebKit2/UIProcess/API/mac/WKConnectionInternal.h b/Source/WebKit2/UIProcess/API/C/WKWindowFeaturesRef.cpp index 684b7fad9..e9338a662 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKConnectionInternal.h +++ b/Source/WebKit2/UIProcess/API/C/WKWindowFeaturesRef.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,10 +23,13 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#import <WebKit2/WKConnection.h> +#include "config.h" +#include "WKWindowFeaturesRef.h" -@interface WKConnection (Internal) +#include "APIWindowFeatures.h" +#include "WKAPICast.h" -- (id)_initWithConnectionRef:(WKConnectionRef)connectionRef; - -@end +WKTypeID WKWindowFeaturesGetTypeID() +{ + return WebKit::toAPI(API::WindowFeatures::APIType); +} diff --git a/Source/WebKit2/UIProcess/API/C/WKWindowFeaturesRef.h b/Source/WebKit2/UIProcess/API/C/WKWindowFeaturesRef.h new file mode 100644 index 000000000..5dc940477 --- /dev/null +++ b/Source/WebKit2/UIProcess/API/C/WKWindowFeaturesRef.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2015 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 WKWindowFeaturesRef_h +#define WKWindowFeaturesRef_h + +#include <WebKit/WKBase.h> + +#ifdef __cplusplus +extern "C" { +#endif + +WK_EXPORT WKTypeID WKWindowFeaturesGetTypeID(); + +#ifdef __cplusplus +} +#endif + +#endif // WKWindowFeaturesRef_h diff --git a/Source/WebKit2/UIProcess/API/C/WebKit2_C.h b/Source/WebKit2/UIProcess/API/C/WebKit2_C.h index 981d52027..bd98fc189 100644 --- a/Source/WebKit2/UIProcess/API/C/WebKit2_C.h +++ b/Source/WebKit2/UIProcess/API/C/WebKit2_C.h @@ -26,43 +26,46 @@ #ifndef WebKit2_C_h #define WebKit2_C_h -#include <WebKit2/WKBase.h> -#include <WebKit2/WKType.h> +#include <WebKit/WKBase.h> +#include <WebKit/WKType.h> -#include <WebKit2/WKArray.h> -#include <WebKit2/WKBackForwardList.h> -#include <WebKit2/WKBackForwardListItem.h> -#include <WebKit2/WKConnectionRef.h> -#include <WebKit2/WKContext.h> -#include <WebKit2/WKData.h> -#include <WebKit2/WKDictionary.h> -#include <WebKit2/WKError.h> -#include <WebKit2/WKFormSubmissionListener.h> -#include <WebKit2/WKFrame.h> -#include <WebKit2/WKFramePolicyListener.h> -#include <WebKit2/WKGeolocationManager.h> -#include <WebKit2/WKGeolocationPermissionRequest.h> -#include <WebKit2/WKGeolocationPosition.h> -#include <WebKit2/WKGraphicsContext.h> -#include <WebKit2/WKHitTestResult.h> -#include <WebKit2/WKMutableArray.h> -#include <WebKit2/WKMutableDictionary.h> -#include <WebKit2/WKNavigationData.h> -#include <WebKit2/WKNumber.h> -#include <WebKit2/WKOpenPanelParameters.h> -#include <WebKit2/WKOpenPanelResultListener.h> -#include <WebKit2/WKPage.h> -#include <WebKit2/WKPageGroup.h> -#include <WebKit2/WKPreferences.h> -#include <WebKit2/WKString.h> -#include <WebKit2/WKURL.h> -#include <WebKit2/WKURLRequest.h> -#include <WebKit2/WKURLResponse.h> +#include <WebKit/WKArray.h> +#include <WebKit/WKBackForwardListRef.h> +#include <WebKit/WKBackForwardListItemRef.h> +#include <WebKit/WKConnectionRef.h> +#include <WebKit/WKContext.h> +#include <WebKit/WKData.h> +#include <WebKit/WKDictionary.h> +#include <WebKit/WKErrorRef.h> +#include <WebKit/WKFormSubmissionListener.h> +#include <WebKit/WKFrame.h> +#include <WebKit/WKFramePolicyListener.h> +#include <WebKit/WKGeolocationManager.h> +#include <WebKit/WKGeolocationPermissionRequest.h> +#include <WebKit/WKGeolocationPosition.h> +#include <WebKit/WKHitTestResult.h> +#include <WebKit/WKMutableArray.h> +#include <WebKit/WKMutableDictionary.h> +#include <WebKit/WKNavigationDataRef.h> +#include <WebKit/WKNumber.h> +#include <WebKit/WKOpenPanelParameters.h> +#include <WebKit/WKOpenPanelResultListener.h> +#include <WebKit/WKPage.h> +#include <WebKit/WKPageConfigurationRef.h> +#include <WebKit/WKPageGroup.h> +#include <WebKit/WKPreferencesRef.h> +#include <WebKit/WKString.h> +#include <WebKit/WKURL.h> +#include <WebKit/WKURLRequest.h> +#include <WebKit/WKURLResponse.h> +#include <WebKit/WKUserContentControllerRef.h> +#include <WebKit/WKUserMediaPermissionRequest.h> +#include <WebKit/WKUserScriptRef.h> #if defined(__OBJC__) && __OBJC__ -#import <WebKit2/WKView.h> +#import <WebKit/WKView.h> #elif !((defined(__APPLE__) && __APPLE__) || defined(BUILDING_QT__)) -#include <WebKit2/WKView.h> +#include <WebKit/WKView.h> #endif #endif /* WebKit2_C_h */ diff --git a/Source/WebKit2/UIProcess/API/C/cg/WKIconDatabaseCG.cpp b/Source/WebKit2/UIProcess/API/C/cg/WKIconDatabaseCG.cpp deleted file mode 100644 index 0f6de7a14..000000000 --- a/Source/WebKit2/UIProcess/API/C/cg/WKIconDatabaseCG.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF 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 "WKIconDatabaseCG.h" - -#include "WebIconDatabase.h" -#include "WKAPICast.h" -#include "WKSharedAPICast.h" -#include <WebCore/Image.h> - -using namespace WebKit; -using namespace WebCore; - -CGImageRef WKIconDatabaseTryGetCGImageForURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef urlRef, WKSize size) -{ - Image* image = toImpl(iconDatabaseRef)->imageForPageURL(toWTFString(urlRef)); - return image ? image->getFirstCGImageRefOfSize(IntSize(static_cast<int>(size.width), static_cast<int>(size.height))) : 0; -} - -CFArrayRef WKIconDatabaseTryCopyCGImageArrayForURL(WKIconDatabaseRef iconDatabaseRef, WKURLRef urlRef) -{ - Image* image = toImpl(iconDatabaseRef)->imageForPageURL(toWTFString(urlRef)); - return image ? image->getCGImageArray().leakRef() : 0; -} - diff --git a/Source/WebKit2/UIProcess/API/C/cg/WKIconDatabaseCG.h b/Source/WebKit2/UIProcess/API/C/cg/WKIconDatabaseCG.h deleted file mode 100644 index af0f2598b..000000000 --- a/Source/WebKit2/UIProcess/API/C/cg/WKIconDatabaseCG.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WKIconDatabaseCG_h -#define WKIconDatabaseCG_h - -#include <CoreFoundation/CFArray.h> -#include <CoreGraphics/CGImage.h> -#include <WebKit2/WKBase.h> -#include <WebKit2/WKGeometry.h> - -#ifdef __cplusplus -extern "C" { -#endif - -WK_EXPORT CGImageRef WKIconDatabaseTryGetCGImageForURL(WKIconDatabaseRef iconDatabase, WKURLRef url, WKSize size); -WK_EXPORT CFArrayRef WKIconDatabaseTryCopyCGImageArrayForURL(WKIconDatabaseRef iconDatabase, WKURLRef url); - -#ifdef __cplusplus -} -#endif - -#endif /* WKIconDatabaseCG_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h b/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h deleted file mode 100644 index 87c5f5efb..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKAPICastEfl.h +++ /dev/null @@ -1,109 +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 WKAPICastEfl_h -#define WKAPICastEfl_h - -#ifndef WKAPICast_h -#error "Please #include \"WKAPICast.h\" instead of this file directly." -#endif - -#include <WebCore/TextDirection.h> -#include <WebKit2/WKPopupItem.h> - -#if ENABLE(TOUCH_EVENTS) -#include "WebEvent.h" -#include <WebKit2/WKEventEfl.h> -#endif - -namespace WebKit { - -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 - -} - -#endif // WKAPICastEfl_h diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.cpp deleted file mode 100644 index 843aeb0dd..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* - * 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 deleted file mode 100644 index b5439219e..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKEventEfl.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2d5ec91b5..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 deleted file mode 100644 index 77b9d140b..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKPageEfl.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7b0ea45ec..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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/efl/WKPopupItem.h b/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.h deleted file mode 100644 index b418ed526..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKPopupItem.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 WKPopupItem_h -#define WKPopupItem_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -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 /* WKPopupItem_h */ diff --git a/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.cpp b/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.cpp deleted file mode 100644 index 34f82b455..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 deleted file mode 100644 index 854991679..000000000 --- a/Source/WebKit2/UIProcess/API/C/efl/WKPopupMenuListener.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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/gtk/WKInspectorClientGtk.h b/Source/WebKit2/UIProcess/API/C/gtk/WKInspectorClientGtk.h deleted file mode 100644 index 865e19ae3..000000000 --- a/Source/WebKit2/UIProcess/API/C/gtk/WKInspectorClientGtk.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef WKInspectorClientGtk_h -#define WKInspectorClientGtk_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef bool (*WKInspectorClientGtkInspectorCallback)(WKInspectorRef inspector, const void* clientInfo); -typedef void (*WKInspectorClientGtkInspectorDidCloseCallback)(WKInspectorRef inspector, const void* clientInfo); -typedef void (*WKInspectorClientGtkInspectedURLChangedCallback)(WKInspectorRef inspector, WKStringRef url, const void* clientInfo); -typedef void (*WKInspectorClientGtkDidChangeAttachedHeightCallback)(WKInspectorRef inspector, unsigned height, const void* clientInfo); - -struct WKInspectorClientGtk { - int version; - const void* clientInfo; - WKInspectorClientGtkInspectorCallback openWindow; - WKInspectorClientGtkInspectorDidCloseCallback didClose; - WKInspectorClientGtkInspectorCallback bringToFront; - WKInspectorClientGtkInspectedURLChangedCallback inspectedURLChanged; - WKInspectorClientGtkInspectorCallback attach; - WKInspectorClientGtkInspectorCallback detach; - WKInspectorClientGtkDidChangeAttachedHeightCallback didChangeAttachedHeight; -}; -typedef struct WKInspectorClientGtk WKInspectorClientGtk; - -enum { kWKInspectorClientGtkCurrentVersion = 0 }; - -WK_EXPORT void WKInspectorSetInspectorClientGtk(WKInspectorRef inspectorRef, const WKInspectorClientGtk* client); - -#ifdef __cplusplus -} -#endif - -#endif /* WKInspectorClientGtk_h */ diff --git a/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.h b/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.h deleted file mode 100644 index 937a4a604..000000000 --- a/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9fb8a2ad8..000000000 --- a/Source/WebKit2/UIProcess/API/C/mac/WKContextPrivateMac.mm +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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 deleted file mode 100644 index 5e45950cb..000000000 --- a/Source/WebKit2/UIProcess/API/C/mac/WKPagePrivateMac.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WKPagePrivateMac.h" - -#include "WKAPICast.h" -#include "WebContext.h" -#include "WebPageGroup.h" -#include "WebPageProxy.h" -#include "WebPreferences.h" - -using namespace WebKit; - -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/soup/WKAPICastSoup.h b/Source/WebKit2/UIProcess/API/C/soup/WKAPICastSoup.h deleted file mode 100644 index c8a954460..000000000 --- a/Source/WebKit2/UIProcess/API/C/soup/WKAPICastSoup.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Portions Copyright (c) 2012 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. - */ - -#ifndef WKAPICastSoup_h -#define WKAPICastSoup_h - -#ifndef WKAPICast_h -#error "Please #include \"WKAPICast.h\" instead of this file directly." -#endif - -namespace WebKit { - -class WebSoupRequestManagerProxy; - -WK_ADD_API_MAPPING(WKSoupRequestManagerRef, WebSoupRequestManagerProxy) - -} - -#endif // WKAPICastSoup_h diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp b/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp deleted file mode 100644 index f7549f003..000000000 --- a/Source/WebKit2/UIProcess/API/C/soup/WKContextSoup.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2012 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 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 "WKContextSoup.h" - -#include "WKAPICast.h" -#include "WebContext.h" - -// Supplements -#include "WebSoupRequestManagerProxy.h" - -using namespace WebKit; - -WKSoupRequestManagerRef WKContextGetSoupRequestManager(WKContextRef contextRef) -{ - return toAPI(toImpl(contextRef)->supplement<WebSoupRequestManagerProxy>()); -} - diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.cpp b/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.cpp deleted file mode 100644 index 86b31aa47..000000000 --- a/Source/WebKit2/UIProcess/API/C/soup/WKCookieManagerSoup.cpp +++ /dev/null @@ -1,51 +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 "WKCookieManagerSoup.h" - -#include "SoupCookiePersistentStorageType.h" -#include "WKAPICast.h" -#include "WebCookieManagerProxy.h" - -using namespace WebKit; - -inline SoupCookiePersistentStorageType toSoupCookiePersistentStorageType(WKCookieStorageType wkCookieStorageType) -{ - switch (wkCookieStorageType) { - case kWKCookieStorageTypeText: - return SoupCookiePersistentStorageText; - case kWKCookieStorageTypeSQLite: - return SoupCookiePersistentStorageSQLite; - } - - ASSERT_NOT_REACHED(); - return SoupCookiePersistentStorageText; -} - -void WKCookieManagerSetCookiePersistentStorage(WKCookieManagerRef cookieManager, WKStringRef storagePath, WKCookieStorageType storageType) -{ - toImpl(cookieManager)->setCookiePersistentStorage(toWTFString(storagePath), storageType); -} diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.cpp b/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.cpp deleted file mode 100644 index 1cbf76554..000000000 --- a/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#include "config.h" -#include "WKSoupRequestManager.h" - -#include "WKAPICast.h" -#include "WebSoupRequestManagerProxy.h" - -using namespace WebKit; - -WKTypeID WKSoupRequestManagerGetTypeID() -{ - return toAPI(WebSoupRequestManagerProxy::APIType); -} - -void WKSoupRequestManagerSetClient(WKSoupRequestManagerRef soupRequestManagerRef, const WKSoupRequestManagerClient* wkClient) -{ - toImpl(soupRequestManagerRef)->initializeClient(wkClient); -} - -void WKSoupRequestManagerRegisterURIScheme(WKSoupRequestManagerRef soupRequestManagerRef, WKStringRef schemeRef) -{ - toImpl(soupRequestManagerRef)->registerURIScheme(toWTFString(schemeRef)); -} - -void WKSoupRequestManagerDidHandleURIRequest(WKSoupRequestManagerRef soupRequestManagerRef, WKDataRef data, uint64_t contentLength, WKStringRef mimeTypeRef, uint64_t requestID) -{ - toImpl(soupRequestManagerRef)->didHandleURIRequest(toImpl(data), contentLength, toWTFString(mimeTypeRef), requestID); -} - -void WKSoupRequestManagerDidReceiveURIRequestData(WKSoupRequestManagerRef soupRequestManagerRef, WKDataRef data, uint64_t requestID) -{ - toImpl(soupRequestManagerRef)->didReceiveURIRequestData(toImpl(data), requestID); -} diff --git a/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h b/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h deleted file mode 100644 index 6892de4bf..000000000 --- a/Source/WebKit2/UIProcess/API/C/soup/WKSoupRequestManager.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef WKSoupRequestManager_h -#define WKSoupRequestManager_h - -#include <WebKit2/WKBase.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*WKSoupRequestManagerDidReceiveURIRequestCallback)(WKSoupRequestManagerRef soupRequestManagerRef, WKURLRef urlRef, WKPageRef pageRef, uint64_t requestID, const void* clientInfo); -typedef void (*WKSoupRequestManagerDidFailToLoadURIRequestCallback)(WKSoupRequestManagerRef soupRequestManagerRef, uint64_t requestID, const void* clientInfo); - -struct WKSoupRequestManagerClient { - int version; - const void* clientInfo; - WKSoupRequestManagerDidReceiveURIRequestCallback didReceiveURIRequest; - WKSoupRequestManagerDidFailToLoadURIRequestCallback didFailToLoadURIRequest; -}; -typedef struct WKSoupRequestManagerClient WKSoupRequestManagerClient; - -enum { kWKSoupRequestManagerClientCurrentVersion = 0 }; - -WK_EXPORT WKTypeID WKSoupRequestManagerGetTypeID(); - -WK_EXPORT void WKSoupRequestManagerSetClient(WKSoupRequestManagerRef, const WKSoupRequestManagerClient* client); -WK_EXPORT void WKSoupRequestManagerRegisterURIScheme(WKSoupRequestManagerRef, WKStringRef schemeRef); -WK_EXPORT void WKSoupRequestManagerDidHandleURIRequest(WKSoupRequestManagerRef, WKDataRef, uint64_t contentLength, WKStringRef mimeTypeRef, uint64_t requestID); -WK_EXPORT void WKSoupRequestManagerDidReceiveURIRequestData(WKSoupRequestManagerRef, WKDataRef, uint64_t requestID); - -#ifdef __cplusplus -} -#endif - -#endif /* WKSoupRequestManager_h */ diff --git a/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp index 5d14f4369..a855116f3 100644 --- a/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp +++ b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.cpp @@ -12,10 +12,10 @@ * 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 + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR @@ -26,15 +26,16 @@ */ #include "config.h" -#if USE(COORDINATED_GRAPHICS) +#if USE(COORDINATED_GRAPHICS) #include "WKCoordinatedScene.h" +#include "CoordinatedGraphicsScene.h" #include "WKCoordinatedSceneAPICast.h" - -#include <WebCore/CoordinatedGraphicsScene.h> #include <WebCore/TextureMapperLayer.h> +using namespace WebKit; + WK_EXPORT WKCoordinatedSceneLayer WKCoordinatedSceneFindScrollableContentsLayerAt(WKCoordinatedScene scene, WKPoint point) { return toAPI(toImpl(scene)->findScrollableContentsLayerAt(WebCore::FloatPoint(point.x, point.y))); diff --git a/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h index c4e88dcdf..061212865 100644 --- a/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h +++ b/Source/WebKit2/UIProcess/API/CoordinatedGraphics/WKCoordinatedScene.h @@ -12,10 +12,10 @@ * 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 + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR @@ -28,7 +28,7 @@ #ifndef WKCoordinatedScene_h #define WKCoordinatedScene_h -#include <WebKit2/WKGeometry.h> +#include <WebKit/WKGeometry.h> #ifdef __cplusplus extern "C" { diff --git a/Source/WebKit2/UIProcess/API/cpp/WKRetainPtr.h b/Source/WebKit2/UIProcess/API/cpp/WKRetainPtr.h index d5dbdf029..24a45afd4 100644 --- a/Source/WebKit2/UIProcess/API/cpp/WKRetainPtr.h +++ b/Source/WebKit2/UIProcess/API/cpp/WKRetainPtr.h @@ -26,8 +26,12 @@ #ifndef WKRetainPtr_h #define WKRetainPtr_h -#include <WebKit2/WKType.h> +#include <WebKit/WKType.h> #include <algorithm> +#include <wtf/GetPtr.h> +#include <wtf/HashFunctions.h> +#include <wtf/HashTraits.h> +#include <wtf/RefPtr.h> namespace WebKit { @@ -68,7 +72,6 @@ public: WKRetain(ptr); } -#if COMPILER_SUPPORTS(CXX_RVALUE_REFERENCES) template<typename U> WKRetainPtr(WKRetainPtr<U>&& o) : m_ptr(o.leakRef()) { @@ -78,7 +81,6 @@ public: : m_ptr(o.leakRef()) { } -#endif ~WKRetainPtr() { @@ -86,6 +88,15 @@ public: WKRelease(ptr); } + // Hash table deleted values, which are only constructed and never copied or destroyed. + WKRetainPtr(WTF::HashTableDeletedValueType) + : m_ptr(hashTableDeletedValue()) + { + } + + bool isHashTableDeletedValue() const { return m_ptr == hashTableDeletedValue(); } + constexpr static T hashTableDeletedValue() { return reinterpret_cast<T>(-1); } + PtrType get() const { return m_ptr; } void clear() @@ -115,10 +126,8 @@ public: WKRetainPtr& operator=(PtrType); template<typename U> WKRetainPtr& operator=(U*); -#if COMPILER_SUPPORTS(CXX_RVALUE_REFERENCES) WKRetainPtr& operator=(WKRetainPtr&&); template<typename U> WKRetainPtr& operator=(WKRetainPtr<U>&&); -#endif void adopt(PtrType); void swap(WKRetainPtr&); @@ -173,7 +182,6 @@ template<typename T> template<typename U> inline WKRetainPtr<T>& WKRetainPtr<T>: return *this; } -#if COMPILER_SUPPORTS(CXX_RVALUE_REFERENCES) template<typename T> inline WKRetainPtr<T>& WKRetainPtr<T>::operator=(WKRetainPtr<T>&& o) { adopt(o.leakRef()); @@ -185,7 +193,6 @@ template<typename T> template<typename U> inline WKRetainPtr<T>& WKRetainPtr<T>: adopt(o.leakRef()); return *this; } -#endif template<typename T> inline void WKRetainPtr<T>::adopt(PtrType optr) { @@ -235,9 +242,8 @@ template<typename T, typename U> inline bool operator!=(T* a, const WKRetainPtr< return a != b.get(); } -template<typename T> inline WKRetainPtr<T> adoptWK(T) WARN_UNUSED_RETURN; - -template<typename T> inline WKRetainPtr<T> adoptWK(T o) +template<typename T> inline WKRetainPtr<T> adoptWK(T) __attribute__((warn_unused_result)); +template<typename T> inline WKRetainPtr<T> adoptWK(T o) { return WKRetainPtr<T>(AdoptWK, o); } @@ -248,4 +254,24 @@ using WebKit::WKRetainPtr; using WebKit::AdoptWK; using WebKit::adoptWK; +namespace WTF { + +template <typename T> struct IsSmartPtr<WKRetainPtr<T>> { + static const bool value = true; +}; + +template<typename P> struct DefaultHash<WKRetainPtr<P>> { + typedef PtrHash<WKRetainPtr<P>> Hash; +}; + +template<typename P> struct HashTraits<WKRetainPtr<P>> : SimpleClassHashTraits<WKRetainPtr<P>> { + static P emptyValue() { return nullptr; } + + typedef P PeekType; + static PeekType peek(const WKRetainPtr<P>& value) { return value.get(); } + static PeekType peek(P value) { return value; } +}; + +} // namespace WTF + #endif // WKRetainPtr_h diff --git a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp b/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp deleted file mode 100644 index ecb7b5f79..000000000 --- a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.cpp +++ /dev/null @@ -1,122 +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 "WKEinaSharedString.h" - -#include <WebKit2/WKAPICast.h> -#include <WebKit2/WKString.h> -#include <WebKit2/WKURL.h> -#include <wtf/text/CString.h> - -using namespace WebKit; - -template <typename WKRefType> -ALWAYS_INLINE const char* fromRefType(WKRefType strRef, bool adopt = false) -{ - const char* res = 0; - if (strRef) { - res = eina_stringshare_add(toImpl(strRef)->string().utf8().data()); - ASSERT(res); - if (adopt) - WKRelease(strRef); - } - - return res; -} - -WKEinaSharedString::WKEinaSharedString(const WKEinaSharedString& other) - : m_string(eina_stringshare_ref(other.m_string)) -{ -} - -WKEinaSharedString::WKEinaSharedString(const char* str) - : m_string(eina_stringshare_add(str)) -{ -} - -WKEinaSharedString::WKEinaSharedString(WKAdoptTag adoptTag, WKStringRef stringRef) - : m_string(fromRefType(stringRef, /*adopt*/ true)) -{ - ASSERT_UNUSED(adoptTag, adoptTag == AdoptWK); // Guard for future enum changes. -} - -WKEinaSharedString::WKEinaSharedString(WKStringRef stringRef) - : m_string(fromRefType(stringRef)) -{ -} - -WKEinaSharedString::WKEinaSharedString(WKAdoptTag adoptTag, WKURLRef urlRef) - : m_string(fromRefType(urlRef, /*adopt*/ true)) -{ - ASSERT_UNUSED(adoptTag, adoptTag == AdoptWK); // Guard for future enum changes. -} - -WKEinaSharedString::WKEinaSharedString(WKURLRef urlRef) - : m_string(fromRefType(urlRef)) -{ -} - -WKEinaSharedString::~WKEinaSharedString() -{ - if (m_string) - eina_stringshare_del(m_string); -} - -WKEinaSharedString& WKEinaSharedString::operator=(const WKEinaSharedString& other) -{ - if (this != &other) { - if (m_string) - eina_stringshare_del(m_string); - m_string = eina_stringshare_ref(other.m_string); - } - return *this; -} - -WKEinaSharedString& WKEinaSharedString::operator=(const char* str) -{ - eina_stringshare_replace(&m_string, str); - return *this; -} - -bool WKEinaSharedString::operator==(const char* str) const -{ - return (!str || !m_string) ? (str == m_string) : !strcmp(m_string, str); -} - -WKEinaSharedString WKEinaSharedString::adopt(Eina_Stringshare* string) -{ - WKEinaSharedString sharedString; - 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 deleted file mode 100644 index dbb5f4788..000000000 --- a/Source/WebKit2/UIProcess/API/cpp/efl/WKEinaSharedString.h +++ /dev/null @@ -1,76 +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 WKEinaSharedString_h -#define WKEinaSharedString_h - -#include <Eina.h> -#include <WebKit2/WKBase.h> -#include <WebKit2/WKRetainPtr.h> - -namespace WebKit { - -class WK_EXPORT WKEinaSharedString { -public: - ALWAYS_INLINE WKEinaSharedString() : m_string(0) { } - WKEinaSharedString(const WKEinaSharedString& other); - WKEinaSharedString(const char* str); - - WKEinaSharedString(WKAdoptTag, WKStringRef); - WKEinaSharedString(WKStringRef); - - WKEinaSharedString(WKAdoptTag, WKURLRef); - WKEinaSharedString(WKURLRef); - - ~WKEinaSharedString(); - - Eina_Stringshare* leakString(); - - WKEinaSharedString& operator=(const WKEinaSharedString& other); - WKEinaSharedString& operator=(const char* str); - - ALWAYS_INLINE bool operator==(const WKEinaSharedString& other) const { return this->m_string == other.m_string; } - ALWAYS_INLINE bool operator!=(const WKEinaSharedString& other) const { return !(*this == other); } - - bool operator==(const char* str) const; - ALWAYS_INLINE bool operator!=(const char* str) const { return !(*this == str); } - - ALWAYS_INLINE operator const char* () const { return m_string; } - - ALWAYS_INLINE bool isNull() const { return !m_string; } - - ALWAYS_INLINE size_t length() const { return m_string ? static_cast<size_t>(eina_stringshare_strlen(m_string)) : 0; } - - static WKEinaSharedString adopt(Eina_Stringshare*); - -private: - const char* m_string; -}; - -} // namespace WebKit - -using WebKit::WKEinaSharedString; - -#endif // WKEinaSharedString_h diff --git a/Source/WebKit2/UIProcess/API/efl/EWebKit2.h b/Source/WebKit2/UIProcess/API/efl/EWebKit2.h deleted file mode 100644 index a9c8a14e7..000000000 --- a/Source/WebKit2/UIProcess/API/efl/EWebKit2.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2012 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 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. - */ - -/** - * @file EWebKit2.h - * @brief Contains the header files that are required by WebKit2-EFL. - * - * It includes the all header files that are exported to public API. - */ - -#ifndef EWebKit2_h -#define EWebKit2_h - -#include "ewk_auth_request.h" -#include "ewk_back_forward_list.h" -#include "ewk_back_forward_list_item.h" -#include "ewk_color_picker.h" -#include "ewk_context.h" -#include "ewk_context_menu.h" -#include "ewk_context_menu_item.h" -#include "ewk_cookie_manager.h" -#include "ewk_database_manager.h" -#include "ewk_download_job.h" -#include "ewk_error.h" -#include "ewk_favicon_database.h" -#include "ewk_file_chooser_request.h" -#include "ewk_form_submission_request.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_security_origin.h" -#include "ewk_settings.h" -#include "ewk_storage_manager.h" -#include "ewk_text_checker.h" -#include "ewk_touch.h" -#include "ewk_url_request.h" -#include "ewk_url_response.h" -#include "ewk_url_scheme_request.h" -#include "ewk_view.h" -#include "ewk_window_features.h" - -#endif // EWebKit2_h diff --git a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h b/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h deleted file mode 100644 index f6fb2b5b0..000000000 --- a/Source/WebKit2/UIProcess/API/efl/EvasGLSurface.h +++ /dev/null @@ -1,69 +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 EvasGLSurface_h -#define EvasGLSurface_h -#if USE(ACCELERATED_COMPOSITING) - -#include <Evas_GL.h> -#include <WebCore/IntSize.h> -#include <wtf/PassOwnPtr.h> - -namespace WebKit { - -class EvasGLSurface { -public: - static PassOwnPtr<EvasGLSurface> create(Evas_GL* evasGL, Evas_GL_Config* cfg, const WebCore::IntSize& size) - { - ASSERT(evasGL); - ASSERT(cfg); - - 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; - - // Ownership of surface is passed to EvasGLSurface. - return adoptPtr(new EvasGLSurface(evasGL, surface)); - } - ~EvasGLSurface(); - - Evas_GL_Surface* surface() { return m_surface; } - -private: - EvasGLSurface(Evas_GL* evasGL, Evas_GL_Surface* passSurface); - - Evas_GL* m_evasGL; - Evas_GL_Surface* m_surface; -}; - -} // 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 deleted file mode 100644 index 457c86163..000000000 --- a/Source/WebKit2/UIProcess/API/efl/EwkView.cpp +++ /dev/null @@ -1,1425 +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 "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/EwkView.h b/Source/WebKit2/UIProcess/API/efl/EwkView.h deleted file mode 100644 index a9f011716..000000000 --- a/Source/WebKit2/UIProcess/API/efl/EwkView.h +++ /dev/null @@ -1,303 +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. -*/ - -#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 "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> -#include <wtf/HashMap.h> -#include <wtf/OwnPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/text/WTFString.h> - -#if ENABLE(TOUCH_EVENTS) -#include "ewk_touch.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 PageLoadClientEfl; -class PagePolicyClientEfl; -class PageUIClientEfl; -class ViewClientEfl; -#if USE(ACCELERATED_COMPOSITING) -class PageViewportController; -class PageViewportControllerClientEfl; -#endif -class WebPageGroup; -class WebPageProxy; - -#if ENABLE(VIBRATION) -class VibrationClientEfl; -#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; - -#if USE(ACCELERATED_COMPOSITING) -typedef struct _Evas_GL_Context Evas_GL_Context; -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 EwkView { -public: - static EwkView* create(WKViewRef, Evas* canvas, Evas_Smart* smart = 0); - - static bool initSmartClassInterface(Ewk_View_Smart_Class&); - - static Evas_Object* toEvasObject(WKPageRef); - - Evas_Object* evasObject() { return m_evasObject; } - - WKViewRef wkView() const { return m_webView.get(); } - WKPageRef wkPage() const; - - 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(); - -#if USE(ACCELERATED_COMPOSITING) - WebKit::PageViewportController* pageViewportController() { return m_pageViewportController.get(); } -#endif - - void setDeviceScaleFactor(float scale); - float deviceScaleFactor() const; - - WebCore::AffineTransform transformToScreen() const; - - const char* url() const { return m_url; } - Evas_Object* createFavicon() const; - const char* title() const; - WebKit::InputMethodContextEfl* inputMethodContext(); - - const char* themePath() const; - void setThemePath(const char* theme); - 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 scheduleUpdateDisplay(); - -#if ENABLE(FULLSCREEN_API) - void enterFullScreen(); - void exitFullScreen(); -#endif - - WKRect windowGeometry() const; - void setWindowGeometry(const WKRect&); -#if USE(ACCELERATED_COMPOSITING) - bool createGLSurface(); - void setNeedsSurfaceResize() { m_pendingSurfaceResize = true; } -#endif - -#if ENABLE(INPUT_TYPE_COLOR) - void requestColorPicker(WKColorPickerResultListenerRef listener, const WebCore::Color&); - void dismissColorPicker(); -#endif - - WKPageRef createNewPage(PassRefPtr<EwkUrlRequest>, WKDictionaryRef windowFeatures); - void close(); - - void requestPopupMenu(WKPopupMenuListenerRef, const WKRect&, WKPopupItemTextDirection, double pageScaleFactor, WKArrayRef items, int32_t selectedIndex); - void closePopupMenu(); - - void customContextMenuItemSelected(WKContextMenuItemRef contextMenuItem); - void showContextMenu(WKPoint position, WKArrayRef items); - void hideContextMenu(); - - void updateTextInputState(); - - void requestJSAlertPopup(const WKEinaSharedString& message); - bool requestJSConfirmPopup(const WKEinaSharedString& message); - WKEinaSharedString requestJSPromptPopup(const WKEinaSharedString& message, const WKEinaSharedString& defaultValue); - - template<EwkViewCallbacks::CallbackType callbackType> - EwkViewCallbacks::CallBack<callbackType> smartCallback() const - { - return EwkViewCallbacks::CallBack<callbackType>(m_evasObject); - } - - 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); - - // FIXME: Remove when possible. - WebKit::WebView* webView(); - - // FIXME: needs refactoring (split callback invoke) - void informURLChange(); - - PassRefPtr<cairo_surface_t> takeSnapshot(); - - void didFindZoomableArea(const WKPoint&, const WKRect&); - -private: - EwkView(WKViewRef, Evas_Object*); - ~EwkView(); - - void setDeviceSize(const WebCore::IntSize&); - Ewk_View_Smart_Data* smartData() const; - - 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); - -#if ENABLE(TOUCH_EVENTS) - void feedTouchEvents(Ewk_Touch_Event_Type type); - 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 handleFaviconChanged(const char* pageURL, void* eventInfo); - -private: - // Note, initialization order matters. - 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 - WebCore::TransformationMatrix m_userViewportTransform; - OwnPtr<WebKit::PageLoadClientEfl> m_pageLoadClient; - OwnPtr<WebKit::PagePolicyClientEfl> m_pagePolicyClient; - OwnPtr<WebKit::PageUIClientEfl> m_pageUIClient; - 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; - OwnPtr<EwkSettings> m_settings; - RefPtr<EwkWindowFeatures> m_windowFeatures; - const void* m_cursorIdentifier; // This is an address, do not free it. - WKEinaSharedString m_url; - mutable WKEinaSharedString m_title; - WKEinaSharedString m_theme; - WKEinaSharedString m_customEncoding; - WKEinaSharedString m_userAgent; - bool m_mouseEventsEnabled; -#if ENABLE(TOUCH_EVENTS) - bool m_touchEventsEnabled; -#endif - 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; -#endif -#if USE(ACCELERATED_COMPOSITING) - OwnPtr<WebKit::PageViewportControllerClientEfl> m_pageViewportControllerClient; - OwnPtr<WebKit::PageViewportController> m_pageViewportController; -#endif - bool m_isAccelerated; - - static Evas_Smart_Class parentSmartClass; -}; - -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 deleted file mode 100644 index 78c304d3f..000000000 --- a/Source/WebKit2/UIProcess/API/efl/EwkViewCallbacks.h +++ /dev/null @@ -1,190 +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 EwkViewCallbacks_h -#define EwkViewCallbacks_h - -#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> - -typedef struct EwkObject Ewk_Auth_Request; -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 EwkError Ewk_Error; - -namespace EwkViewCallbacks { - -enum CallbackType { - AuthenticationRequest, - BackForwardListChange, - CancelVibration, - ContentsSizeChanged, - DownloadJobCancelled, - DownloadJobFailed, - DownloadJobFinished, - DownloadJobRequested, - FileChooserRequest, - NewFormSubmissionRequest, - FaviconChanged, - LoadError, - LoadFinished, - LoadProgress, - MenuBarVisible, - ProvisionalLoadFailed, - ProvisionalLoadRedirect, - ProvisionalLoadStarted, - StatusBarVisible, - NavigationPolicyDecision, - NewWindowPolicyDecision, - TextFound, - TitleChange, - ToolbarVisible, - TooltipTextUnset, - TooltipTextSet, - URLChanged, - Vibrate, - WebProcessCrashed, - WindowResizable -}; - -template <CallbackType> -struct CallBackInfo; - -class EvasObjectHolder { -protected: - explicit EvasObjectHolder(Evas_Object* object) - : m_object(object) - { - ASSERT(m_object); - } - - Evas_Object* m_object; -}; - -template <CallbackType callbackType, typename ArgType = typename CallBackInfo<callbackType>::Type> -struct CallBack: public EvasObjectHolder { - explicit CallBack(Evas_Object* view) : EvasObjectHolder(view) { } - - void call(ArgType argument) - { - evas_object_smart_callback_call(m_object, CallBackInfo<callbackType>::name(), static_cast<void*>(argument)); - } -}; - -template <CallbackType callbackType> -struct CallBack <callbackType, void> : public EvasObjectHolder { - explicit CallBack(Evas_Object* view) : EvasObjectHolder(view) { } - - void call() - { - evas_object_smart_callback_call(m_object, CallBackInfo<callbackType>::name(), 0); - } -}; - -template <CallbackType callbackType> -struct CallBack <callbackType, const char*> : public EvasObjectHolder { - explicit CallBack(Evas_Object* view) : EvasObjectHolder(view) { } - - void call(const char* arg) - { - evas_object_smart_callback_call(m_object, CallBackInfo<callbackType>::name(), const_cast<char*>(arg)); - } - - void call(const String& arg) - { - call(arg.utf8().data()); - } - - void call(const WKEinaSharedString& arg) - { - call(static_cast<const char*>(arg)); - } -}; - -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> { \ - typedef type Type; \ - static inline const char* name() { return string; } \ -} - -// Note: type 'void' means that no arguments are expected. -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(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*); -DECLARE_EWK_VIEW_CALLBACK(ProvisionalLoadFailed, "load,provisional,failed", Ewk_Error*); -DECLARE_EWK_VIEW_CALLBACK(ProvisionalLoadRedirect, "load,provisional,redirect", void); -DECLARE_EWK_VIEW_CALLBACK(ProvisionalLoadStarted, "load,provisional,started", void); -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(StatusBarVisible, "statusbar,visible", bool*); -DECLARE_EWK_VIEW_CALLBACK(TextFound, "text,found", unsigned*); -DECLARE_EWK_VIEW_CALLBACK(TitleChange, "title,changed", const char*); -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", uint32_t*); -DECLARE_EWK_VIEW_CALLBACK(WebProcessCrashed, "webprocess,crashed", bool*); -DECLARE_EWK_VIEW_CALLBACK(WindowResizable, "window,resizable", bool*); - -} - -#endif // #ifndef EwkViewCallbacks_h diff --git a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp b/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp deleted file mode 100644 index 8e0b9d833..000000000 --- a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.cpp +++ /dev/null @@ -1,76 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "SnapshotImageGL.h" - -#if USE(OPENGL_ES_2) -#include <GLES2/gl2.h> -#include <GLES2/gl2ext.h> -#else -#include "OpenGLShims.h" -#endif - -#include <WebCore/CairoUtilitiesEfl.h> - -PassRefPtr<cairo_surface_t> getImageSurfaceFromFrameBuffer(int x, int y, int width, int height) -{ - 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* buf = reinterpret_cast<unsigned*>(data); - - for (int i = 0; i < height / 2; ++i) { - for (int j = 0; j < 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; - } - } - - 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 deleted file mode 100644 index 68c1428ae..000000000 --- a/Source/WebKit2/UIProcess/API/efl/SnapshotImageGL.h +++ /dev/null @@ -1,37 +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 SnapshotImageGL_h -#define SnapshotImageGL_h - -#if USE(ACCELERATED_COMPOSITING) - -#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 deleted file mode 100644 index b9ea77d5e..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.cpp +++ /dev/null @@ -1,174 +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_auth_request.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; - -EwkAuthRequest::EwkAuthRequest(WKAuthenticationChallengeRef authenticationChallenge) - : m_authenticationChallenge(authenticationChallenge) - , m_wasHandled(false) -{ - ASSERT(m_authenticationChallenge); -} - -EwkAuthRequest::~EwkAuthRequest() -{ - if (!m_wasHandled) - continueWithoutCredential(); -} - -const char* EwkAuthRequest::suggestedUsername() const -{ - if (!m_suggestedUsername) { - WKRetainPtr<WKCredentialRef> credential = WKAuthenticationChallengeGetProposedCredential(m_authenticationChallenge.get()); - ASSERT(credential); - - WKRetainPtr<WKStringRef> suggestedUsername(AdoptWK, WKCredentialCopyUser(credential.get())); - if (!suggestedUsername || WKStringIsEmpty(suggestedUsername.get())) - return 0; - - m_suggestedUsername = suggestedUsername.get(); - } - - return m_suggestedUsername; -} - -const char* EwkAuthRequest::realm() const -{ - if (!m_realm) { - WKRetainPtr<WKProtectionSpaceRef> protectionSpace = WKAuthenticationChallengeGetProtectionSpace(m_authenticationChallenge.get()); - ASSERT(protectionSpace); - - WKRetainPtr<WKStringRef> realm(AdoptWK, WKProtectionSpaceCopyRealm(protectionSpace.get())); - if (!realm || WKStringIsEmpty(realm.get())) - return 0; - - m_realm = realm.get(); - } - - return m_realm; -} - -const char* EwkAuthRequest::host() const -{ - if (!m_host) { - WKRetainPtr<WKProtectionSpaceRef> protectionSpace = WKAuthenticationChallengeGetProtectionSpace(m_authenticationChallenge.get()); - ASSERT(protectionSpace); - - WKRetainPtr<WKStringRef> host(AdoptWK, WKProtectionSpaceCopyHost(protectionSpace.get())); - if (!host || WKStringIsEmpty(host.get())) - return 0; - - m_host = host.get(); - } - - return m_host; -} - -bool EwkAuthRequest::continueWithoutCredential() -{ - if (m_wasHandled) - return false; - - m_wasHandled = true; - WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(m_authenticationChallenge.get()); - WKAuthenticationDecisionListenerUseCredential(decisionListener, 0); - - return true; -} - -bool EwkAuthRequest::authenticate(const char* username, const char* password) -{ - if (m_wasHandled) - return false; - - m_wasHandled = true; - 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 WKAuthenticationChallengeGetPreviousFailureCount(m_authenticationChallenge.get()) > 0; -} - -const char* ewk_auth_request_suggested_username_get(const Ewk_Auth_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkAuthRequest, request, impl, 0); - - return impl->suggestedUsername(); -} - -Eina_Bool ewk_auth_request_cancel(Ewk_Auth_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkAuthRequest, request, impl, false); - - return impl->continueWithoutCredential(); -} - -Eina_Bool ewk_auth_request_authenticate(Ewk_Auth_Request* request, const char* username, const char* password) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkAuthRequest, request, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(username, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(password, false); - - return impl->authenticate(username, password); -} - -Eina_Bool ewk_auth_request_retrying_get(const Ewk_Auth_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkAuthRequest, request, impl, false); - - return impl->isRetrying(); -} - -const char* ewk_auth_request_realm_get(const Ewk_Auth_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkAuthRequest, request, impl, 0); - - return impl->realm(); -} - -const char* ewk_auth_request_host_get(const Ewk_Auth_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkAuthRequest, request, impl, 0); - - return impl->host(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.h b/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.h deleted file mode 100644 index 010d44c08..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request.h +++ /dev/null @@ -1,118 +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_auth_request.h - * @brief Describes the Ewk Authentication Request API. - */ - -#ifndef ewk_auth_request_h -#define ewk_auth_request_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Auth_Request as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Auth_Request; - -/** - * Queries the suggested username to be used for authenticating. - * - * @param request request object to query - * - * @return the username 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_auth_request_suggested_username_get(const Ewk_Auth_Request *request); - -/** - * Queries if this an authentication attempt retrying. - * - * @param request request object to query - * - * @return @c EINA_TRUE if this is not the first authentication attempt - * and we are trying, @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_auth_request_retrying_get(const Ewk_Auth_Request *request); - -/** - * Queries the authentication realm. - * - * @param request request object to query - * - * @return the realm 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_auth_request_realm_get(const Ewk_Auth_Request *request); - -/** - * Queries the host requiring the authentication. - * - * @param request request object to query - * - * @return the host 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_auth_request_host_get(const Ewk_Auth_Request *request); - -/** - * Cancels the authentication request. - * - * @param request request object to cancel - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_auth_request_cancel(Ewk_Auth_Request *request); - -/** - * Set credential for the authentication request. - * - * @param request request object to update - * - * @return @c EINA_TRUE if the credential was successfuly sent, @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_auth_request_authenticate(Ewk_Auth_Request *request, const char *username, const char *password); - -#ifdef __cplusplus -} -#endif - -#endif /* ewk_auth_request_h */ diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h deleted file mode 100644 index 7ca9be309..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_auth_request_private.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_auth_request_private_h -#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> - -class EwkAuthRequest : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkAuthRequest) - - static PassRefPtr<EwkAuthRequest> create(WKAuthenticationChallengeRef authenticationChallenge) - { - return adoptRef(new EwkAuthRequest(authenticationChallenge)); - } - ~EwkAuthRequest(); - - const char* suggestedUsername() const; - const char* realm() const; - const char* host() const; - bool isRetrying() const; - - bool continueWithoutCredential(); - bool authenticate(const char* username, const char* password); - -private: - explicit EwkAuthRequest(WKAuthenticationChallengeRef authenticationChallenge); - - WKRetainPtr<WKAuthenticationChallengeRef> m_authenticationChallenge; - bool m_wasHandled; - mutable WKEinaSharedString m_suggestedUsername; - mutable WKEinaSharedString m_realm; - mutable WKEinaSharedString m_host; -}; - -#endif // ewk_auth_request_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp deleted file mode 100644 index 88634373d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.cpp +++ /dev/null @@ -1,187 +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_back_forward_list.h" - -#include "WKAPICast.h" -#include "WKArray.h" -#include "WKBackForwardList.h" -#include "ewk_back_forward_list_private.h" -#include "ewk_object.h" -#include <wtf/text/CString.h> - -using namespace WebKit; - -EwkBackForwardList::EwkBackForwardList(WKBackForwardListRef listRef) - : m_wkList(listRef) -{ } - -EwkBackForwardListItem* EwkBackForwardList::nextItem() const -{ - return getFromCacheOrCreate(WKBackForwardListGetForwardItem(m_wkList.get())); -} - -EwkBackForwardListItem* EwkBackForwardList::previousItem() const -{ - return getFromCacheOrCreate(WKBackForwardListGetBackItem(m_wkList.get())); -} - -EwkBackForwardListItem* EwkBackForwardList::currentItem() const -{ - return getFromCacheOrCreate(WKBackForwardListGetCurrentItem(m_wkList.get())); -} - -EwkBackForwardListItem* EwkBackForwardList::itemAt(int index) const -{ - return getFromCacheOrCreate(WKBackForwardListGetItemAtIndex(m_wkList.get(), index)); -} - -unsigned EwkBackForwardList::size() const -{ - const unsigned currentItem = WKBackForwardListGetCurrentItem(m_wkList.get()) ? 1 : 0; - - return WKBackForwardListGetBackListCount(m_wkList.get()) + WKBackForwardListGetForwardListCount(m_wkList.get()) + currentItem; -} - -WKRetainPtr<WKArrayRef> EwkBackForwardList::backList(int limit) const -{ - if (limit == -1) - limit = WKBackForwardListGetBackListCount(m_wkList.get()); - ASSERT(limit >= 0); - - return adoptWK(WKBackForwardListCopyBackListWithLimit(m_wkList.get(), limit)); -} - -WKRetainPtr<WKArrayRef> EwkBackForwardList::forwardList(int limit) const -{ - if (limit == -1) - limit = WKBackForwardListGetForwardListCount(m_wkList.get()); - ASSERT(limit >= 0); - - return adoptWK(WKBackForwardListCopyForwardListWithLimit(m_wkList.get(), limit)); -} - -EwkBackForwardListItem* EwkBackForwardList::getFromCacheOrCreate(WKBackForwardListItemRef wkItem) const -{ - if (!wkItem) - return 0; - - RefPtr<EwkBackForwardListItem> item = m_wrapperCache.get(wkItem); - if (!item) { - item = EwkBackForwardListItem::create(wkItem); - m_wrapperCache.set(wkItem, item); - } - - return item.get(); -} - -Eina_List* EwkBackForwardList::createEinaList(WKArrayRef wkList) const -{ - if (!wkList) - return 0; - - Eina_List* result = 0; - - const size_t count = WKArrayGetSize(wkList); - for (size_t i = 0; i < count; ++i) { - WKBackForwardListItemRef wkItem = static_cast<WKBackForwardListItemRef>(WKArrayGetItemAtIndex(wkList, i)); - EwkBackForwardListItem* item = getFromCacheOrCreate(wkItem); - result = eina_list_append(result, ewk_object_ref(item)); - } - - return result; -} - -/** - * @internal - * Updates items cache. - */ -void EwkBackForwardList::update(WKBackForwardListItemRef wkAddedItem, WKArrayRef wkRemovedItems) -{ - if (wkAddedItem) // Checking also here to avoid EINA_SAFETY_ON_NULL_RETURN_VAL warnings. - getFromCacheOrCreate(wkAddedItem); // Puts new item to the cache. - - const size_t removedItemsSize = wkRemovedItems ? WKArrayGetSize(wkRemovedItems) : 0; - for (size_t i = 0; i < removedItemsSize; ++i) { - WKBackForwardListItemRef wkItem = static_cast<WKBackForwardListItemRef>(WKArrayGetItemAtIndex(wkRemovedItems, i)); - m_wrapperCache.remove(wkItem); - } -} - -Ewk_Back_Forward_List_Item* ewk_back_forward_list_current_item_get(const Ewk_Back_Forward_List* list) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - - return list->currentItem(); -} - -Ewk_Back_Forward_List_Item* ewk_back_forward_list_previous_item_get(const Ewk_Back_Forward_List* list) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - - return list->previousItem(); -} - -Ewk_Back_Forward_List_Item* ewk_back_forward_list_next_item_get(const Ewk_Back_Forward_List* list) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - - return list->nextItem(); -} - -Ewk_Back_Forward_List_Item* ewk_back_forward_list_item_at_index_get(const Ewk_Back_Forward_List* list, int index) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - - return list->itemAt(index); -} - -unsigned ewk_back_forward_list_count(Ewk_Back_Forward_List* list) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - - return list->size(); -} - -Eina_List* ewk_back_forward_list_n_back_items_copy(const Ewk_Back_Forward_List* list, int limit) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - EINA_SAFETY_ON_FALSE_RETURN_VAL(limit == -1 || limit > 0, 0); - - WKRetainPtr<WKArrayRef> backList = list->backList(limit); - - return list->createEinaList(backList.get()); -} - -Eina_List* ewk_back_forward_list_n_forward_items_copy(const Ewk_Back_Forward_List* list, int limit) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(list, 0); - EINA_SAFETY_ON_FALSE_RETURN_VAL(limit == -1 || limit > 0, 0); - - WKRetainPtr<WKArrayRef> forwardList = list->forwardList(limit); - - return list->createEinaList(forwardList.get()); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.h b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.h deleted file mode 100644 index 93d727698..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list.h +++ /dev/null @@ -1,154 +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_back_forward_list.h - * @brief Describes the Ewk Back Forward List API. - */ - -#ifndef ewk_back_forward_list_h -#define ewk_back_forward_list_h - -#include "ewk_back_forward_list_item.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for Ewk_Back_Forward_List */ -typedef struct EwkBackForwardList Ewk_Back_Forward_List; - -/** - * Returns the current item in the @a list. - * - * @param list the back-forward list instance - * - * @return the current item in the @a list or @c NULL in case of error - */ -EAPI Ewk_Back_Forward_List_Item *ewk_back_forward_list_current_item_get(const Ewk_Back_Forward_List *list); - -/** - * Returns the item that precedes the current item in the @a list. - * - * @param list the back-forward list instance - * - * @return the item that precedes the current item the @a list or @c NULL in case of error - */ -EAPI Ewk_Back_Forward_List_Item *ewk_back_forward_list_previous_item_get(const Ewk_Back_Forward_List *list); - -/** - * Returns the item that follows the current item in the @a list. - * - * @param list the back-forward list instance - * - * @return the item that follows the current item in the @a list or @c NULL in case of error - */ -EAPI Ewk_Back_Forward_List_Item *ewk_back_forward_list_next_item_get(const Ewk_Back_Forward_List *list); - -/** - * Returns the item at a given @a index relative to the current item. - * - * @param list the back-forward list instance - * @param index the index of the item - * - * @return the item at a given @a index relative to the current item or @c NULL in case of error - */ -EAPI Ewk_Back_Forward_List_Item *ewk_back_forward_list_item_at_index_get(const Ewk_Back_Forward_List *list, int index); - -/** - * Returns the length of the back-forward list including current item. - * - * @param list the back-forward list instance - * - * @return the length of the back-forward list including current item or @c 0 in case of error - */ -EAPI unsigned ewk_back_forward_list_count(Ewk_Back_Forward_List *list); - -/** - * Creates the list containing the items preceding the current item limited by @a limit. - * - * The @c Ewk_Back_Forward_List_Item elements are located in the result list starting with the oldest one. - * if @a limit is equal to @c -1 all the items preceding the current item are returned. - * - * @param list the back-forward list instance - * @param limit the number of items to retrieve - * - * @return @c Eina_List containing @c Ewk_Back_Forward_List_Item elements or @c NULL in case of error, - * the Eina_List and its items should be freed after use. Use ewk_object_unref() - * to free the items - */ -EAPI Eina_List *ewk_back_forward_list_n_back_items_copy(const Ewk_Back_Forward_List *list, int limit); - -/** - * Creates the list containing the items following the current item limited by @a limit. - * - * The @c Ewk_Back_Forward_List_Item elements are located in the result list starting with the oldest one. - * if @a limit is equal to @c -1 all the items preceding the current item are returned. - * - * @param list the back-forward list instance - * @param limit the number of items to retrieve - * - * @return @c Eina_List containing @c Ewk_Back_Forward_List_Item elements or @c NULL in case of error, - * the Eina_List and its items should be freed after use. Use ewk_object_unref() - * to free the items - */ -EAPI Eina_List *ewk_back_forward_list_n_forward_items_copy(const Ewk_Back_Forward_List *list, int limit); - -/** - * Creates the list containing the items preceding the current item. - * - * The @c Ewk_Back_Forward_List_Item elements are located in the result list starting with the oldest one. - * - * @param list the back-forward list instance - * - * @return @c Eina_List containing @c Ewk_Back_Forward_List_Item elements or @c NULL in case of error, - * the Eina_List and its items should be freed after use. Use ewk_object_unref() - * to free the items - * - * @see ewk_back_forward_list_n_back_items_copy - */ -#define ewk_back_forward_list_back_items_copy(list) \ - ewk_back_forward_list_n_back_items_copy(list, -1) - -/** - * Creates the list containing the items following the current item. - * - * The @c Ewk_Back_Forward_List_Item elements are located in the result list starting with the oldest one. - * - * @param list the back-forward list instance - * - * @return @c Eina_List containing @c Ewk_Back_Forward_List_Item elements or @c NULL in case of error, - * the Eina_List and its items should be freed after use. Use ewk_object_unref() - * to free the items - * - * @see ewk_back_forward_list_n_forward_items_copy - */ -#define ewk_back_forward_list_forward_items_copy(list) \ - ewk_back_forward_list_n_forward_items_copy(list, -1) - -#ifdef __cplusplus -} -#endif -#endif // ewk_back_forward_list_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item.cpp deleted file mode 100644 index 43f29c96c..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item.cpp +++ /dev/null @@ -1,79 +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 item of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this item 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_back_forward_list_item.h" - -#include "WKAPICast.h" -#include "WKBackForwardListItem.h" -#include "ewk_back_forward_list_item_private.h" - -using namespace WebKit; - -EwkBackForwardListItem::EwkBackForwardListItem(WKBackForwardListItemRef itemRef) - : m_wkItem(itemRef) -{ } - -const char* EwkBackForwardListItem::url() const -{ - m_url = WKEinaSharedString(AdoptWK, WKBackForwardListItemCopyURL(m_wkItem.get())); - - return m_url; -} - -const char* EwkBackForwardListItem::title() const -{ - m_title = WKEinaSharedString(AdoptWK, WKBackForwardListItemCopyTitle(m_wkItem.get())); - - return m_title; -} - -const char* EwkBackForwardListItem::originalURL() const -{ - m_originalURL = WKEinaSharedString(AdoptWK, WKBackForwardListItemCopyOriginalURL(m_wkItem.get())); - - return m_originalURL; -} - -const char* ewk_back_forward_list_item_url_get(const Ewk_Back_Forward_List_Item* item) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkBackForwardListItem, item, impl, 0); - - return impl->url(); -} - -const char* ewk_back_forward_list_item_title_get(const Ewk_Back_Forward_List_Item* item) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkBackForwardListItem, item, impl, 0); - - return impl->title(); -} - -const char* ewk_back_forward_list_item_original_url_get(const Ewk_Back_Forward_List_Item* item) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkBackForwardListItem, item, impl, 0); - - return impl->originalURL(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item.h b/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item.h deleted file mode 100644 index 46c75e340..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item.h +++ /dev/null @@ -1,95 +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_back_forward_list_item.h - * @brief Describes the Ewk Back Forward List Item API. - */ - -#ifndef ewk_back_forward_list_item_h -#define ewk_back_forward_list_item_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Back_Forward_List_Item as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Back_Forward_List_Item; - -/** - * Returns URL of the item. - * - * The returned URL may differ from the original URL (For example if the page was redirected). - * - * @see ewk_back_forward_list_item_original_url_get() - * - * @param item the back-forward list item instance - * - * @return the URL of the @a item or @c NULL in case of error. 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_back_forward_list_item_url_get(const Ewk_Back_Forward_List_Item *item); - -/** - * Returns title of the item. - * - * @param item the back-forward list item instance - * - * @return the title of the @a item or @c NULL in case of error. 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_back_forward_list_item_title_get(const Ewk_Back_Forward_List_Item *item); - -/** - * Returns original URL of the item. - * - * @see ewk_back_forward_list_item_url_get() - * - * @param item the back-forward list item instance - * - * @return the original URL of the @a item or @c NULL in case of error. 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_back_forward_list_item_original_url_get(const Ewk_Back_Forward_List_Item *item); - -#ifdef __cplusplus -} -#endif -#endif // ewk_back_forward_list_item_h 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 deleted file mode 100644 index 7b6d20a48..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_item_private.h +++ /dev/null @@ -1,62 +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 item of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this item 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_back_forward_list_item_private_h -#define ewk_back_forward_list_item_private_h - -#include "WKEinaSharedString.h" -#include "ewk_object_private.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassRefPtr.h> - -/** - * \struct Ewk_Back_Forward_List - * @brief Contains the Back Forward List data. - */ -class EwkBackForwardListItem : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkBackForwardListItem) - - static PassRefPtr<EwkBackForwardListItem> create(WKBackForwardListItemRef itemRef) - { - return adoptRef(new EwkBackForwardListItem(itemRef)); - } - - const char* url() const; - const char* title() const; - const char* originalURL() const; - - WKBackForwardListItemRef wkItem() const { return m_wkItem.get(); } - -private: - explicit EwkBackForwardListItem(WKBackForwardListItemRef itemRef); - - WKRetainPtr<WKBackForwardListItemRef> m_wkItem; - mutable WKEinaSharedString m_url; - mutable WKEinaSharedString m_title; - mutable WKEinaSharedString m_originalURL; -}; - -#endif // ewk_back_forward_list_private_h 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 deleted file mode 100644 index e5c6f0e1d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_back_forward_list_private.h +++ /dev/null @@ -1,65 +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_back_forward_list_private_h -#define ewk_back_forward_list_private_h - -#include "WKRetainPtr.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<EwkBackForwardListItem> > ItemsMap; - -class EwkBackForwardList { -public: - static PassOwnPtr<EwkBackForwardList> create(WKBackForwardListRef listRef) - { - return adoptPtr(new EwkBackForwardList(listRef)); - } - - 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; - unsigned size() const; - - void update(WKBackForwardListItemRef wkAddedItem, WKArrayRef wkRemovedItems); - Eina_List* createEinaList(WKArrayRef wkList) const; - -private: - explicit EwkBackForwardList(WKBackForwardListRef listRef); - - EwkBackForwardListItem* getFromCacheOrCreate(WKBackForwardListItemRef wkItem) const; - - WKRetainPtr<WKBackForwardListRef> m_wkList; - mutable ItemsMap m_wrapperCache; -}; - -#endif // ewk_back_forward_list_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp deleted file mode 100644 index 1141394cb..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.cpp +++ /dev/null @@ -1,93 +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 "ewk_color_picker.h" - -#include "WKColorPickerResultListener.h" -#include "WKString.h" -#include "ewk_color_picker_private.h" -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -using namespace WebCore; - -#if ENABLE(INPUT_TYPE_COLOR) -EwkColorPicker::EwkColorPicker(WKColorPickerResultListenerRef colorPickerListener, const Color& initialColor) - : m_colorPickerListener(colorPickerListener) - , m_color(initialColor) -{ -} - -void EwkColorPicker::setColor(const Color& color) -{ - WKRetainPtr<WKStringRef> colorString(AdoptWK, WKStringCreateWithUTF8CString(color.serialized().utf8().data())); - WKColorPickerResultListenerSetColor(m_colorPickerListener.get(), colorString.get()); -} - -const Color& EwkColorPicker::color() const -{ - return m_color; -} -#endif - -Eina_Bool ewk_color_picker_color_set(Ewk_Color_Picker* colorPicker, int r, int g, int b, int a) -{ -#if ENABLE(INPUT_TYPE_COLOR) - EINA_SAFETY_ON_NULL_RETURN_VAL(colorPicker, false); - - colorPicker->setColor(Color(r, g, b, a)); - - return true; -#else - UNUSED_PARAM(colorPicker); - UNUSED_PARAM(r); - UNUSED_PARAM(g); - UNUSED_PARAM(b); - UNUSED_PARAM(a); - return false; -#endif -} - -Eina_Bool ewk_color_picker_color_get(const Ewk_Color_Picker* colorPicker, int* r, int* g, int* b, int* a) -{ -#if ENABLE(INPUT_TYPE_COLOR) - EINA_SAFETY_ON_NULL_RETURN_VAL(colorPicker, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(r, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(g, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(b, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(a, false); - - const Color& color = colorPicker->color(); - *r = color.red(); - *g = color.green(); - *b = color.blue(); - *a = color.alpha(); - - 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_color_picker.h b/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.h deleted file mode 100644 index 56fb4d08d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker.h +++ /dev/null @@ -1,67 +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. -*/ - -#ifndef ewk_color_picker_h -#define ewk_color_picker_h - -#include <Evas.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for @a Ewk_Color_Picker. */ -typedef struct EwkColorPicker Ewk_Color_Picker; - -/** - * Sets the selected color. - * - * The function should only be called when a color has been requested by the document. - * If called when this is not the case or when the input picker has been dismissed, this - * function will fail and return EINA_FALSE. - * - * @param color_picker color picker object - * @param r red channel value to be set - * @param g green channel value to be set - * @param b blue channel value to be set - * @param a alpha channel value to be set - * - * @return @c EINA_TRUE on success @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_color_picker_color_set(Ewk_Color_Picker *color_picker, int r, int g, int b, int a); - -/** - * Gets the currently selected color. - * - * @param color_picker color picker object - * @param r red channel value to be get - * @param g green channel value to be get - * @param b blue channel value to be get - * @param a alpha channel value to be get - * - * @return @c EINA_TRUE on success @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_color_picker_color_get(const Ewk_Color_Picker *color_picker, int *r, int *g, int *b, int *a); - -#ifdef __cplusplus -} -#endif - -#endif /* ewk_color_picker_h */ diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_color_picker_private.h deleted file mode 100644 index 29d036079..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_color_picker_private.h +++ /dev/null @@ -1,49 +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. -*/ - -#ifndef ewk_color_picker_private_h -#define ewk_color_picker_private_h - -#if ENABLE(INPUT_TYPE_COLOR) - -#include "WKRetainPtr.h" -#include <WebCore/Color.h> -#include <wtf/PassOwnPtr.h> - -class EwkColorPicker { -public: - static PassOwnPtr<EwkColorPicker> create(WKColorPickerResultListenerRef colorPickerListener, const WebCore::Color& initialColor) - { - return adoptPtr(new EwkColorPicker(colorPickerListener, initialColor)); - } - - const WebCore::Color& color() const; - void setColor(const WebCore::Color&); - -private: - EwkColorPicker(WKColorPickerResultListenerRef colorPickerListener, const WebCore::Color& initialColor); - - WKRetainPtr<WKColorPickerResultListenerRef> m_colorPickerListener; - WebCore::Color m_color; -}; - -#endif // ENABLE(INPUT_TYPE_COLOR) - -#endif // ewk_color_picker_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp deleted file mode 100644 index 7189f6d35..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context.cpp +++ /dev/null @@ -1,347 +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 "ewk_context.h" - -#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 "WKString.h" -#include "WebContext.h" -#include "WebIconDatabase.h" -#include "ewk_context_private.h" -#include "ewk_cookie_manager_private.h" -#include "ewk_database_manager_private.h" -#include "ewk_favicon_database_private.h" -#include "ewk_private.h" -#include "ewk_storage_manager_private.h" -#include "ewk_url_scheme_request_private.h" -#include <WebCore/FileSystem.h> -#include <WebCore/IconDatabase.h> -#include <wtf/HashMap.h> -#include <wtf/text/WTFString.h> - -#if ENABLE(SPELLCHECK) -#include "TextCheckerClientEfl.h" -#endif - -using namespace WebCore; -using namespace WebKit; - -typedef HashMap<WKContextRef, EwkContext*> ContextMap; - -static inline ContextMap& contextMap() -{ - DEFINE_STATIC_LOCAL(ContextMap, map, ()); - return map; -} - -EwkContext::EwkContext(WKContextRef context) - : m_context(context) - , m_databaseManager(EwkDatabaseManager::create(WKContextGetDatabaseManager(context))) - , m_storageManager(EwkStorageManager::create(WKContextGetKeyValueStorageManager(context))) -#if ENABLE(BATTERY_STATUS) - , m_batteryProvider(BatteryProvider::create(context)) -#endif -#if ENABLE(NETWORK_INFO) - , m_networkInfoProvider(NetworkInfoProvider::create(context)) -#endif - , m_downloadManager(DownloadManagerEfl::create(context)) - , m_requestManagerClient(RequestManagerClientEfl::create(context)) - , m_historyClient(ContextHistoryClientEfl::create(context)) -{ - ContextMap::AddResult result = contextMap().add(context, this); - ASSERT_UNUSED(result, result.isNewEntry); - -#if ENABLE(MEMORY_SAMPLER) - static bool initializeMemorySampler = false; - static const char environmentVariable[] = "SAMPLE_MEMORY"; - - if (!initializeMemorySampler && getenv(environmentVariable)) { - WKContextStartMemorySampler(context, adoptWK(WKDoubleCreate(0.0)).get()); - initializeMemorySampler = true; - } -#endif - -#if ENABLE(SPELLCHECK) - // Load the default dictionary to show context menu spellchecking items - // independently of checking spelling while typing setting. - TextCheckerClientEfl::instance().ensureSpellCheckingLanguage(); -#endif -} - -EwkContext::~EwkContext() -{ - ASSERT(contextMap().get(m_context.get()) == this); - contextMap().remove(m_context.get()); -} - -PassRefPtr<EwkContext> EwkContext::findOrCreateWrapper(WKContextRef context) -{ - if (contextMap().contains(context)) - return contextMap().get(context); - - return adoptRef(new EwkContext(context)); -} - -PassRefPtr<EwkContext> EwkContext::create() -{ - return adoptRef(new EwkContext(adoptWK(WKContextCreate()).get())); -} - -PassRefPtr<EwkContext> EwkContext::create(const String& injectedBundlePath) -{ - if (!fileExists(injectedBundlePath)) - return 0; - - WKRetainPtr<WKStringRef> path = adoptWK(toCopiedAPI(injectedBundlePath)); - - return adoptRef(new EwkContext(adoptWK(WKContextCreateWithInjectedBundlePath(path.get())).get())); -} - -EwkContext* EwkContext::defaultContext() -{ - static EwkContext* defaultInstance = create().leakRef(); - - return defaultInstance; -} - -EwkCookieManager* EwkContext::cookieManager() -{ - if (!m_cookieManager) - m_cookieManager = EwkCookieManager::create(WKContextGetCookieManager(m_context.get())); - - return m_cookieManager.get(); -} - -EwkDatabaseManager* EwkContext::databaseManager() -{ - return m_databaseManager.get(); -} - -void EwkContext::ensureFaviconDatabase() -{ - if (m_faviconDatabase) - return; - - 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 (iconDatabase->isOpen()) - return false; - - // If databaseDirectory is empty, we use the default database path for the platform. - String databasePath = databaseDirectory.isEmpty() ? toImpl(m_context.get())->iconDatabasePath() : pathByAppendingComponent(databaseDirectory, WebCore::IconDatabase::defaultDatabaseFilename()); - toImpl(m_context.get())->setIconDatabasePath(databasePath); - - return true; -} - -EwkFaviconDatabase* EwkContext::faviconDatabase() -{ - ensureFaviconDatabase(); - ASSERT(m_faviconDatabase); - - return m_faviconDatabase.get(); -} - -EwkStorageManager* EwkContext::storageManager() const -{ - return m_storageManager.get(); -} - -RequestManagerClientEfl* EwkContext::requestManager() -{ - return m_requestManagerClient.get(); -} - -void EwkContext::addVisitedLink(const String& visitedURL) -{ - WKContextAddVisitedLink(m_context.get(), adoptWK(toCopiedAPI(visitedURL)).get()); -} - -void EwkContext::setCacheModel(Ewk_Cache_Model cacheModel) -{ - WKContextSetCacheModel(m_context.get(), static_cast<WebKit::CacheModel>(cacheModel)); -} - -Ewk_Cache_Model EwkContext::cacheModel() const -{ - return static_cast<Ewk_Cache_Model>(WKContextGetCacheModel(m_context.get())); -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -void EwkContext::setAdditionalPluginPath(const String& 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); - - return const_cast<EwkContext*>(impl)->cookieManager(); -} - -Ewk_Database_Manager* ewk_context_database_manager_get(const Ewk_Context* ewkContext) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContext, ewkContext, impl, 0); - - return const_cast<EwkContext*>(impl)->databaseManager(); -} - -Eina_Bool ewk_context_favicon_database_directory_set(Ewk_Context* ewkContext, const char* directoryPath) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl, false); - - return impl->setFaviconDatabaseDirectoryPath(String::fromUTF8(directoryPath)); -} - -Ewk_Favicon_Database* ewk_context_favicon_database_get(const Ewk_Context* ewkContext) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContext, ewkContext, impl, 0); - - return const_cast<EwkContext*>(impl)->faviconDatabase(); -} - -Ewk_Storage_Manager* ewk_context_storage_manager_get(const Ewk_Context* ewkContext) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContext, ewkContext, impl, 0); - - return impl->storageManager(); -} - -DownloadManagerEfl* EwkContext::downloadManager() const -{ - return m_downloadManager.get(); -} - -ContextHistoryClientEfl* EwkContext::historyClient() -{ - return m_historyClient.get(); -} - -Ewk_Context* ewk_context_default_get() -{ - return EwkContext::defaultContext(); -} - -Ewk_Context* ewk_context_new() -{ - return EwkContext::create().leakRef(); -} - -Ewk_Context* ewk_context_new_with_injected_bundle_path(const char* path) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(path, 0); - - return EwkContext::create(String::fromUTF8(path)).leakRef(); -} - -Eina_Bool ewk_context_url_scheme_register(Ewk_Context* ewkContext, const char* scheme, Ewk_Url_Scheme_Request_Cb callback, void* userData) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(scheme, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(callback, false); - - impl->requestManager()->registerURLSchemeHandler(String::fromUTF8(scheme), callback, userData); - - return true; -} - -void ewk_context_history_callbacks_set(Ewk_Context* ewkContext, Ewk_History_Navigation_Cb navigate, Ewk_History_Client_Redirection_Cb clientRedirect, Ewk_History_Server_Redirection_Cb serverRedirect, Ewk_History_Title_Update_Cb titleUpdate, Ewk_History_Populate_Visited_Links_Cb populateVisitedLinks, void* data) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl); - - impl->historyClient()->setCallbacks(navigate, clientRedirect, serverRedirect, titleUpdate, populateVisitedLinks, data); -} - -void ewk_context_visited_link_add(Ewk_Context* ewkContext, const char* visitedURL) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl); - EINA_SAFETY_ON_NULL_RETURN(visitedURL); - - impl->addVisitedLink(visitedURL); -} - -// Ewk_Cache_Model enum validation -COMPILE_ASSERT_MATCHING_ENUM(EWK_CACHE_MODEL_DOCUMENT_VIEWER, kWKCacheModelDocumentViewer); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CACHE_MODEL_DOCUMENT_BROWSER, kWKCacheModelDocumentBrowser); -COMPILE_ASSERT_MATCHING_ENUM(EWK_CACHE_MODEL_PRIMARY_WEBBROWSER, kWKCacheModelPrimaryWebBrowser); - -Eina_Bool ewk_context_cache_model_set(Ewk_Context* ewkContext, Ewk_Cache_Model cacheModel) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContext, ewkContext, impl, false); - - impl->setCacheModel(cacheModel); - - return true; -} - -Ewk_Cache_Model ewk_context_cache_model_get(const Ewk_Context* ewkContext) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContext, ewkContext, impl, EWK_CACHE_MODEL_DOCUMENT_VIEWER); - - return impl->cacheModel(); -} - -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); - - 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 deleted file mode 100644 index 5d440aa94..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context.h +++ /dev/null @@ -1,326 +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. - */ - -/** - * @file ewk_context.h - * @brief Describes the context API. - * - * @note ewk_context encapsulates all pages related to specific use of WebKit. - * - * Applications have the option of creating a context different than the default one - * and use it for a group of pages. All pages in the same context share the same - * preferences, visited link set, local storage, etc. - * - * A process model can be specified per context. The default one is the shared model - * where the web-engine process is shared among the pages in the context. The second - * model allows each page to use a separate web-engine process. This latter model is - * currently not supported by WebKit2/EFL. - * - */ - -#ifndef ewk_context_h -#define ewk_context_h - -#include "ewk_cookie_manager.h" -#include "ewk_database_manager.h" -#include "ewk_favicon_database.h" -#include "ewk_navigation_data.h" -#include "ewk_storage_manager.h" -#include "ewk_url_scheme_request.h" -#include <Evas.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Context as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Context; - -/** - * \enum Ewk_Cache_Model - * - * @brief Contains option for cache model - */ -enum Ewk_Cache_Model { - /// Use the smallest cache capacity. - EWK_CACHE_MODEL_DOCUMENT_VIEWER, - /// Use bigger cache capacity than EWK_CACHE_MODEL_DOCUMENT_VIEWER. - EWK_CACHE_MODEL_DOCUMENT_BROWSER, - /// Use the biggest cache capacity. - EWK_CACHE_MODEL_PRIMARY_WEBBROWSER -}; - -/// Creates a type name for the Ewk_Cache_Model. -typedef enum Ewk_Cache_Model Ewk_Cache_Model; - -/** - * @typedef Ewk_Url_Scheme_Request_Cb Ewk_Url_Scheme_Request_Cb - * @brief Callback type for use with ewk_context_url_scheme_register(). - */ -typedef void (*Ewk_Url_Scheme_Request_Cb) (Ewk_Url_Scheme_Request *request, void *user_data); - -/** - * @typedef Ewk_History_Navigation_Cb Ewk_History_Navigation_Cb - * @brief Type definition for a function that will be called back when @a view did navigation (loaded new URL). - */ -typedef void (*Ewk_History_Navigation_Cb)(const Evas_Object *view, Ewk_Navigation_Data *navigation_data, void *user_data); - -/** - * @typedef Ewk_History_Client_Redirection_Cb Ewk_History_Client_Redirection_Cb - * @brief Type definition for a function that will be called back when @a view performed a client redirect. - */ -typedef void (*Ewk_History_Client_Redirection_Cb)(const Evas_Object *view, const char *source_url, const char *destination_url, void *user_data); - -/** - * @typedef Ewk_History_Server_Redirection_Cb Ewk_History_Server_Redirection_Cb - * @brief Type definition for a function that will be called back when @a view performed a server redirect. - */ -typedef void (*Ewk_History_Server_Redirection_Cb)(const Evas_Object *view, const char *source_url, const char *destination_url, void *user_data); - -/** - * @typedef Ewk_History_Title_Update_Cb Ewk_History_Title_Update_Cb - * @brief Type definition for a function that will be called back when history title is updated. - */ -typedef void (*Ewk_History_Title_Update_Cb)(const Evas_Object *view, const char *title, const char *url, void *user_data); - -/** - * @typedef Ewk_Context_History_Client_Visited_Links_Populate_Cb Ewk_Context_History_Client_Visited_Links_Populate_Cb - * @brief Type definition for a function that will be called back when client is asked to provide visited links from a client-managed storage. - * - * @see ewk_context_visited_link_add - */ -typedef void (*Ewk_History_Populate_Visited_Links_Cb)(void *user_data); - -/** - * Gets default Ewk_Context instance. - * - * The returned Ewk_Context object @b should not be unref'ed if application - * does not call ewk_context_ref() for that. - * - * @return Ewk_Context object. - */ -EAPI Ewk_Context *ewk_context_default_get(void); - -/** - * Creates a new Ewk_Context. - * - * The returned Ewk_Context object @b should be unref'ed after use. - * - * @return Ewk_Context object on success or @c NULL on failure - * - * @see ewk_object_unref - * @see ewk_context_new_with_injected_bundle_path - */ -EAPI Ewk_Context *ewk_context_new(void); - -/** - * Creates a new Ewk_Context. - * - * The returned Ewk_Context object @b should be unref'ed after use. - * - * @param path path of injected bundle library - * - * @return Ewk_Context object on success or @c NULL on failure - * - * @see ewk_object_unref - * @see ewk_context_new - */ -EAPI Ewk_Context *ewk_context_new_with_injected_bundle_path(const char *path); - -/** - * Gets the cookie manager instance for this @a context. - * - * @param context context object to query. - * - * @return Ewk_Cookie_Manager object instance or @c NULL in case of failure. - */ -EAPI Ewk_Cookie_Manager *ewk_context_cookie_manager_get(const Ewk_Context *context); - -/** - * Gets the database manager instance for this @a context. - * - * @param context context object to query - * - * @return Ewk_Database_Manager object instance or @c NULL in case of failure - */ -EAPI Ewk_Database_Manager *ewk_context_database_manager_get(const Ewk_Context *context); - -/** - * Sets the favicon database directory for this @a context. - * - * Sets the directory path to be used to store the favicons database - * for @a context on disk. Passing @c NULL as @a directory_path will - * result in using the default directory for the platform. - * - * Calling this method also means enabling the favicons database for - * its use from the applications, it is therefore expected to be - * called only once. Further calls for the same instance of - * @a context will not have any effect. - * - * @param context context object to update - * @param directory_path database directory path to set - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_context_favicon_database_directory_set(Ewk_Context *context, const char *directory_path); - -/** - * Gets the favicon database instance for this @a context. - * - * @param context context object to query. - * - * @return Ewk_Favicon_Database object instance or @c NULL in case of failure. - */ -EAPI Ewk_Favicon_Database *ewk_context_favicon_database_get(const Ewk_Context *context); - -/** - * Gets the storage manager instance for this @a context. - * - * @param context context object to query. - * - * @return Ewk_Storage_Manager object instance or @c NULL in case of failure. - */ -EAPI Ewk_Storage_Manager *ewk_context_storage_manager_get(const Ewk_Context *context); - -/** - * Register @a scheme in @a context. - * - * When an URL request with @a scheme is made in the #Ewk_Context, the callback - * function provided will be called with a #Ewk_Url_Scheme_Request. - * - * It is possible to handle URL scheme requests asynchronously, by calling ewk_url_scheme_ref() on the - * #Ewk_Url_Scheme_Request and calling ewk_url_scheme_request_finish() later when the data of - * the request is available. - * - * @param context a #Ewk_Context object. - * @param scheme the network scheme to register - * @param callback the function to be called when an URL request with @a scheme is made. - * @param user_data data to pass to callback function - * - * @code - * static void about_url_scheme_request_cb(Ewk_Url_Scheme_Request *request, void *user_data) - * { - * const char *path; - * char *contents_data = NULL; - * unsigned int contents_length = 0; - * - * path = ewk_url_scheme_request_path_get(request); - * if (!strcmp(path, "plugins")) { - * // Initialize contents_data with the contents of plugins about page, and set its length to contents_length - * } else if (!strcmp(path, "memory")) { - * // Initialize contents_data with the contents of memory about page, and set its length to contents_length - * } else if (!strcmp(path, "applications")) { - * // Initialize contents_data with the contents of application about page, and set its length to contents_length - * } else { - * Eina_Strbuf *buf = eina_strbuf_new(); - * eina_strbuf_append_printf(buf, "<html><body><p>Invalid about:%s page</p></body></html>", path); - * contents_data = eina_strbuf_string_steal(buf); - * contents_length = strlen(contents); - * eina_strbuf_free(buf); - * } - * ewk_url_scheme_request_finish(request, contents_data, contents_length, "text/html"); - * free(contents_data); - * } - * @endcode - */ -EAPI Eina_Bool ewk_context_url_scheme_register(Ewk_Context *context, const char *scheme, Ewk_Url_Scheme_Request_Cb callback, void *user_data); - -/** - * Sets history callbacks for the given @a context. - * - * To stop listening for history events, you may call this function with @c - * NULL for the callbacks. - * - * @param context context object to set history callbacks - * @param navigate_func The function to call when @c ewk_view did navigation (may be @c NULL). - * @param client_redirect_func The function to call when @c ewk_view performed a client redirect (may be @c NULL). - * @param server_redirect_func The function to call when @c ewk_view performed a server redirect (may be @c NULL). - * @param title_update_func The function to call when history title is updated (may be @c NULL). - * @param populate_visited_links_func The function is called when client is asked to provide visited links from a - * client-managed storage (may be @c NULL). - * @param data User data (may be @c NULL). - */ -EAPI void ewk_context_history_callbacks_set(Ewk_Context *context, - Ewk_History_Navigation_Cb navigate_func, - Ewk_History_Client_Redirection_Cb client_redirect_func, - Ewk_History_Server_Redirection_Cb server_redirect_func, - Ewk_History_Title_Update_Cb title_update_func, - Ewk_History_Populate_Visited_Links_Cb populate_visited_links_func, - void *data); - -/** - * Registers the given @a visited_url as visited link in @a context visited link cache. - * - * This function shall be invoked as a response to @c populateVisitedLinks callback of the history cient. - * - * @param context context object to add visited link data - * @param visited_url visited url - * - * @see Ewk_Context_History_Client - */ -EAPI void ewk_context_visited_link_add(Ewk_Context *context, const char *visited_url); - -/** - * Set @a cache_model as the cache model for @a context. - * - * By default, it is EWK_CACHE_MODEL_DOCUMENT_VIEWER. - * - * @param context context object to update. - * @param cache_model a #Ewk_Cache_Model. - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_context_cache_model_set(Ewk_Context *context, Ewk_Cache_Model cache_model); - -/** - * Gets the cache model for @a context. - * - * @param context context object to query. - * - * @return the cache model for the @a context. - */ -EAPI Ewk_Cache_Model ewk_context_cache_model_get(const Ewk_Context *context); - -/** - * Sets additional plugin path for @a context. - * - * @param context context object to set additional plugin path - * @param path the path to be used for plugins - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -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 - -#endif // ewk_context_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp deleted file mode 100644 index 5a99e6bf7..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_context_menu.h" - -#include "APIObject.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; - -static WKContextMenuItemTag getWKTagFromEwkAction(Ewk_Context_Menu_Item_Action action); - -EwkContextMenu::EwkContextMenu(EwkView* view, WKArrayRef items) - : m_viewImpl(view) - , m_contextMenuItems(0) -{ - 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(static_cast<WKContextMenuItemRef>(WKArrayGetItemAtIndex(items, i)), this).leakPtr()); -} - -EwkContextMenu::EwkContextMenu() - : m_viewImpl(0) - , m_contextMenuItems(0) -{ -} - -EwkContextMenu::EwkContextMenu(Eina_List* items) - : m_viewImpl(0) - , m_contextMenuItems(0) -{ - Eina_List* l; - void* 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() -{ - void* data; - EINA_LIST_FREE(m_contextMenuItems, data) - delete static_cast<Ewk_Context_Menu_Item*>(data); -} - -void EwkContextMenu::hide() -{ - if (!m_viewImpl) - return; - - m_viewImpl->hideContextMenu(); -} - -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 EwkContextMenu::removeItem(EwkContextMenuItem* item) -{ - m_contextMenuItems = eina_list_remove(m_contextMenuItems, item); -} - -bool EwkContextMenu::contextMenuItemSelected(WKContextMenuItemRef item) -{ - if (!m_viewImpl) - return false; - - WKPageSelectContextMenuItem(m_viewImpl->wkPage(), item); - - return true; -} - -Ewk_Context_Menu* ewk_context_menu_new() -{ - return EwkContextMenu::create().leakRef(); -} - -Ewk_Context_Menu* ewk_context_menu_new_with_items(Eina_List* items) -{ - return EwkContextMenu::create(items).leakRef(); -} - -Eina_Bool ewk_context_menu_item_append(Ewk_Context_Menu* menu, Ewk_Context_Menu_Item* item) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - impl->appendItem(item); - - return true; -} - -Eina_Bool ewk_context_menu_item_remove(Ewk_Context_Menu* menu, Ewk_Context_Menu_Item* item) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); - - impl->removeItem(item); - - return true; -} - -Eina_Bool ewk_context_menu_hide(Ewk_Context_Menu* menu) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); - - impl->hide(); - - return true; -} - -const Eina_List* ewk_context_menu_items_get(const Ewk_Context_Menu* menu) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkContextMenu, menu, impl, 0); - - return impl->items(); -} - -Eina_Bool ewk_context_menu_item_select(Ewk_Context_Menu* menu, Ewk_Context_Menu_Item* item) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkContextMenu, menu, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - WKContextMenuItemRef wkItem; - - 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 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.h b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.h deleted file mode 100644 index ad3561939..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_context_menu.h - * @brief Describes the Ewk Context Menu API. - */ - -#ifndef ewk_context_menu_h -#define ewk_context_menu_h - -#include "ewk_defines.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Creates a new Ewk_Context_Menu to be used as a submenu of an existing - * Ewk_Context_Menu. The context menu is created by the ewk_view and - * passed as an argument of ewk_view smart callback. - * - * @return the pointer to the new context menu - * - * @see ewk_context_menu_new_with_items - */ -EAPI Ewk_Context_Menu *ewk_context_menu_new(void); - -/** - * Creates a new Ewk_Context_Menu to be used as a submenu of an existing - * Ewk_Context_Menu with the given initial items. The context menu is - * created by the ewk_view and passed as an argument of ewk_view smart callback. - * - * @param items the list of initial items - * @return the pointer to the new context menu - * - * @see ewk_context_menu_new - */ -EAPI Ewk_Context_Menu *ewk_context_menu_new_with_items(Eina_List *items); - -/** - * Appends the item of the context menu. - * - * @param menu the context menu - * @param item the item to append - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_context_menu_item_append(Ewk_Context_Menu *menu, Ewk_Context_Menu_Item *item); - -/** - * Removes the item of the context menu. - * - * @param menu the context menu - * @param item the item to remove - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_context_menu_item_remove(Ewk_Context_Menu *menu, Ewk_Context_Menu_Item *item); - -/** - * Hides the context menu. - * - * @param menu the context menu to hide - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_context_menu_hide(Ewk_Context_Menu *menu); - -/** - * Gets the list of items. - * - * @param o the context menu to get list of the items - * @return the list of the items on success or @c NULL on failure - */ -EAPI const Eina_List *ewk_context_menu_items_get(const Ewk_Context_Menu *o); - -/** - * Selects the item from the context menu. - * - * @param menu the context menu - * @param item the item is selected - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_context_menu_item_select(Ewk_Context_Menu *menu, Ewk_Context_Menu_Item *item); - -#ifdef __cplusplus -} -#endif - -#endif /* ewk_context_menu_h */ diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp deleted file mode 100644 index 33d11b469..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "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 WebKit; - -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, PassRefPtr<EwkContextMenu> subMenu, EwkContextMenu* parentMenu) - : m_type(type) - , m_action(action) - , m_title(title) - , m_isChecked(checked) - , m_isEnabled(enabled) - , 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).leakPtr(); -} - -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) -{ - 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) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, EWK_ACTION_TYPE); - - return item->type(); -} - -Eina_Bool ewk_context_menu_item_type_set(Ewk_Context_Menu_Item* item, Ewk_Context_Menu_Item_Type type) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - item->setType(type); - - return true; -} - -Ewk_Context_Menu_Item_Action ewk_context_menu_item_action_get(const Ewk_Context_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION); - - return item->action(); -} - -Eina_Bool ewk_context_menu_item_action_set(Ewk_Context_Menu_Item* item, Ewk_Context_Menu_Item_Action action) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - item->setAction(action); - - return true; -} - -const char* ewk_context_menu_item_title_get(const Ewk_Context_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, 0); - - return item->title(); -} - -Eina_Bool ewk_context_menu_item_title_set(Ewk_Context_Menu_Item* item, const char* title) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - item->setTitle(title); - - return true; -} - -Eina_Bool ewk_context_menu_item_checked_get(const Ewk_Context_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - return item->checked(); -} - -Eina_Bool ewk_context_menu_item_checked_set(Ewk_Context_Menu_Item* item, Eina_Bool checked) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - item->setChecked(checked); - - return true; -} - -Eina_Bool ewk_context_menu_item_enabled_get(const Ewk_Context_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - return item->enabled(); -} - -Eina_Bool ewk_context_menu_item_enabled_set(Ewk_Context_Menu_Item* item, Eina_Bool enabled) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - item->setEnabled(enabled); - - return true; -} - -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 deleted file mode 100644 index d9f74f9af..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item.h +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_context_menu_item.h - * @brief Describes the Ewk Context Menu Item API. - */ - -#ifndef ewk_context_menu_item_h -#define ewk_context_menu_item_h - -#include "ewk_defines.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \enum Ewk_Context_Menu_Item_Type - * @brief Defines the types of the items for the context menu. - * @info Keep this in sync with WKContextMenuItemTypes.h - */ -typedef enum { - EWK_ACTION_TYPE, - EWK_CHECKABLE_ACTION_TYPE, - EWK_SEPARATOR_TYPE, - EWK_SUBMENU_TYPE -} Ewk_Context_Menu_Item_Type; - -/** - * \enum Ewk_Context_Menu_Action - * @brief Provides the actions of items for the context menu. - */ -typedef enum { - EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION, - EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK_IN_NEW_WINDOW, - EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_LINK_TO_DISK, - EWK_CONTEXT_MENU_ITEM_TAG_COPY_LINK_TO_CLIPBOARD, - EWK_CONTEXT_MENU_ITEM_TAG_OPEN_IMAGE_IN_NEW_WINDOW, - EWK_CONTEXT_MENU_ITEM_TAG_DOWNLOAD_IMAGE_TO_DISK, - EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_TO_CLIPBOARD, - EWK_CONTEXT_MENU_ITEM_TAG_COPY_IMAGE_URL_TO_CLIPBOARD, - EWK_CONTEXT_MENU_ITEM_TAG_OPEN_FRAME_IN_NEW_WINDOW, - EWK_CONTEXT_MENU_ITEM_TAG_COPY, - EWK_CONTEXT_MENU_ITEM_TAG_GO_BACK, - EWK_CONTEXT_MENU_ITEM_TAG_GO_FORWARD, - EWK_CONTEXT_MENU_ITEM_TAG_STOP, - EWK_CONTEXT_MENU_ITEM_TAG_RELOAD, - EWK_CONTEXT_MENU_ITEM_TAG_CUT, - EWK_CONTEXT_MENU_ITEM_TAG_PASTE, - EWK_CONTEXT_MENU_ITEM_TAG_SELECT_ALL, - EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_GUESS, - EWK_CONTEXT_MENU_ITEM_TAG_NO_GUESSES_FOUND, - EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_SPELLING, - EWK_CONTEXT_MENU_ITEM_TAG_LEARN_SPELLING, - EWK_CONTEXT_MENU_ITEM_TAG_OTHER, - EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_IN_SPOTLIGHT, - EWK_CONTEXT_MENU_ITEM_TAG_SEARCH_WEB, - EWK_CONTEXT_MENU_ITEM_TAG_LOOK_UP_IN_DICTIONARY, - EWK_CONTEXT_MENU_ITEM_TAG_OPEN_WITH_DEFAULT_APPLICATION, - EWK_CONTEXT_MENU_ITEM_PDFACTUAL_SIZE, - EWK_CONTEXT_MENU_ITEM_PDFZOOM_IN, - EWK_CONTEXT_MENU_ITEM_PDFZOOM_OUT, - EWK_CONTEXT_MENU_ITEM_PDFAUTO_SIZE, - EWK_CONTEXT_MENU_ITEM_PDFSINGLE_PAGE, - EWK_CONTEXT_MENU_ITEM_PDFFACING_PAGES, - EWK_CONTEXT_MENU_ITEM_PDFCONTINUOUS, - EWK_CONTEXT_MENU_ITEM_PDFNEXT_PAGE, - EWK_CONTEXT_MENU_ITEM_PDFPREVIOUS_PAGE, - EWK_CONTEXT_MENU_ITEM_TAG_OPEN_LINK = 2000, - EWK_CONTEXT_MENU_ITEM_TAG_IGNORE_GRAMMAR, - EWK_CONTEXT_MENU_ITEM_TAG_SPELLING_MENU, /**< spelling or spelling/grammar sub-menu */ - EWK_CONTEXT_MENU_ITEM_TAG_SHOW_SPELLING_PANEL, - EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING, - EWK_CONTEXT_MENU_ITEM_TAG_CHECK_SPELLING_WHILE_TYPING, - EWK_CONTEXT_MENU_ITEM_TAG_CHECK_GRAMMAR_WITH_SPELLING, - EWK_CONTEXT_MENU_ITEM_TAG_FONT_MENU, /**< font sub-menu */ - EWK_CONTEXT_MENU_ITEM_TAG_SHOW_FONTS, - EWK_CONTEXT_MENU_ITEM_TAG_BOLD, - EWK_CONTEXT_MENU_ITEM_TAG_ITALIC, - EWK_CONTEXT_MENU_ITEM_TAG_UNDERLINE, - EWK_CONTEXT_MENU_ITEM_TAG_OUTLINE, - EWK_CONTEXT_MENU_ITEM_TAG_STYLES, - EWK_CONTEXT_MENU_ITEM_TAG_SHOW_COLORS, - EWK_CONTEXT_MENU_ITEM_TAG_SPEECH_MENU, /**< speech sub-menu */ - EWK_CONTEXT_MENU_ITEM_TAG_START_SPEAKING, - EWK_CONTEXT_MENU_ITEM_TAG_STOP_SPEAKING, - EWK_CONTEXT_MENU_ITEM_TAG_WRITING_DIRECTION_MENU, /**< writing direction sub-menu */ - EWK_CONTEXT_MENU_ITEM_TAG_DEFAULT_DIRECTION, - EWK_CONTEXT_MENU_ITEM_TAG_LEFT_TO_RIGHT, - EWK_CONTEXT_MENU_ITEM_TAG_RIGHT_TO_LEFT, - EWK_CONTEXT_MENU_ITEM_TAG_PDFSINGLE_PAGE_SCROLLING, - EWK_CONTEXT_MENU_ITEM_TAG_PDFFACING_PAGES_SCROLLING, - EWK_CONTEXT_MENU_ITEM_TAG_INSPECT_ELEMENT, - EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_MENU, /**< text direction sub-menu */ - EWK_CONTEXT_MENU_ITEM_TAG_TEXT_DIRECTION_DEFAULT, - 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_APPLICATION_TAG = 10000 -} Ewk_Context_Menu_Item_Action; - -/** - * Creates a new 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 - * @return the pointer to the new item - * - * @see ewk_context_menu_item_new_with_submenu - */ -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 sub menu type item of the context menu. - * - * @param action specifies a action of the item - * @param title specifies a title of the item - * @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_Action action, const char *title, Eina_Bool enabled, Ewk_Context_Menu *submenu); - -/** - * Gets type of the item. - * - * @param o the item to get the type - * @return type of the item on success or @c EWK_ACTION_TYPE on failure - * - * @see ewk_context_menu_item_type_set - */ -EAPI Ewk_Context_Menu_Item_Type ewk_context_menu_item_type_get(const Ewk_Context_Menu_Item *o); - -/** - * Sets the type of item. - * - * @param o the item to set the type - * @param type a new type for the item object - * @return @c EINA_TRUE on success, or @c EINA_FALSE on failure - * - * @see ewk_context_menu_item_type_get - */ -EAPI Eina_Bool ewk_context_menu_item_type_set(Ewk_Context_Menu_Item *o, Ewk_Context_Menu_Item_Type type); - -/** - * Gets an action of the item. - * - * @param o the item to get the action - * @return an action of the item on success or @c EWK_CONTEXT_MENU_ITEM_TAG_NO_ACTION on failure - * - * @see ewk_context_menu_item_action_set - */ -EAPI Ewk_Context_Menu_Item_Action ewk_context_menu_item_action_get(const Ewk_Context_Menu_Item *o); - -/** - * Sets an action of the item. - * - * @param o the item to set the action - * @param action a new action for the item object - * @return @c EINA_TRUE on success, or @c EINA_FALSE on failure - * - * @see ewk_context_menu_item_action_get - */ -EAPI Eina_Bool ewk_context_menu_item_action_set(Ewk_Context_Menu_Item *o, Ewk_Context_Menu_Item_Action action); - -/** - * Gets a title of the item. - * - * @param o the item to get the title - * @return a title of the item on success, or @c NULL on failure - * - * @see ewk_context_menu_item_title_set - */ -EAPI const char *ewk_context_menu_item_title_get(const Ewk_Context_Menu_Item *o); - -/** - * Sets a title of the item. - * - * @param o the item to set the title - * @param title a new title for the item object - * @return @c EINA_TRUE on success, or @c EINA_FALSE on failure - * - * @see ewk_context_menu_item_title_get - */ -EAPI Eina_Bool ewk_context_menu_item_title_set(Ewk_Context_Menu_Item *o, const char *title); - -/** - * Queries if the item is toggled. - * - * @param o the item to query if the item is toggled - * @return @c EINA_TRUE if the item is toggled or @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_context_menu_item_checked_get(const Ewk_Context_Menu_Item *o); - -/** - * Sets if the item should be toggled. - * - * @param o the item to be toggled - * @param checked @c EINA_TRUE if the item should be toggled or @c EINA_FALSE if not - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_context_menu_item_checked_set(Ewk_Context_Menu_Item *o, Eina_Bool checked); - -/** - * Gets if the item is enabled. - * - * @param o the item to get enabled state - * @return @c EINA_TRUE if it's enabled, @c EINA_FALSE if not or on failure - * - * @see ewk_context_menu_item_enabled_set - */ -EAPI Eina_Bool ewk_context_menu_item_enabled_get(const Ewk_Context_Menu_Item *o); - -/** - * Enables/disables the item. - * - * @param o the item to enable/disable - * @param enabled @c EINA_TRUE to enable the item or @c EINA_FALSE to disable - * @return @c EINA_TRUE on success, or @c EINA_FALSE on failure - * - * @see ewk_context_menu_item_enabled_get - */ -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 - -#endif /* ewk_context_menu_item_h */ 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 deleted file mode 100644 index 22158ec2f..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_item_private.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_context_menu_item_private_h -#define ewk_context_menu_item_private_h - -#include "WKContextMenuItem.h" -#include "WKEinaSharedString.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 - * @brief Contains the context menu item data. - */ -class EwkContextMenuItem { -public: - static PassOwnPtr<EwkContextMenuItem> create(WKContextMenuItemRef item, EwkContextMenu* parentMenu) - { - 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, PassRefPtr<EwkContextMenu> subMenu = 0, EwkContextMenu* parentMenu = 0) - { - return adoptPtr(new EwkContextMenuItem(type, action, title, checked, enabled, subMenu, parentMenu)); - } - - Ewk_Context_Menu_Item_Action action() const { return m_action; } - void setAction(Ewk_Context_Menu_Item_Action action) { m_action = action; } - - const char* title() const { return m_title; } - void setTitle(const char* title) { m_title = title; } - - Ewk_Context_Menu_Item_Type type() const { return m_type; } - void setType(Ewk_Context_Menu_Item_Type type) { m_type = type; } - - bool checked() const { return m_isChecked; } - void setChecked(bool checked) { m_isChecked = checked; } - - 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: - 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; - - WKEinaSharedString m_title; - - bool m_isChecked; - bool m_isEnabled; - - 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 deleted file mode 100644 index 2a3c9a21d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_menu_private.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_context_menu_private_h -#define ewk_context_menu_private_h - -#include "ewk_context_menu_item.h" -#include "ewk_object_private.h" -#include <Eina.h> -#include <wtf/PassRefPtr.h> - -class EwkView; - -class EwkContextMenu : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkContextMenu) - - static PassRefPtr<EwkContextMenu> create(EwkView* viewImpl, WKArrayRef items) - { - return adoptRef(new EwkContextMenu(viewImpl, items)); - } - - static PassRefPtr<EwkContextMenu> create() - { - return adoptRef(new EwkContextMenu()); - } - - static PassRefPtr<EwkContextMenu> create(Eina_List* items) - { - return adoptRef(new EwkContextMenu(items)); - } - - ~EwkContextMenu(); - - void hide(); - void appendItem(EwkContextMenuItem*); - void removeItem(EwkContextMenuItem*); - - const Eina_List* items() const { return m_contextMenuItems; } - bool contextMenuItemSelected(WKContextMenuItemRef item); - - EwkView* ewkView() const { return m_viewImpl; } - void setEwkView(EwkView* ewkView) { m_viewImpl = ewkView; } - -private: - EwkContextMenu(); - EwkContextMenu(Eina_List* items); - EwkContextMenu(EwkView* viewImpl, WKArrayRef items); - - EwkView* m_viewImpl; - Eina_List* m_contextMenuItems; -}; - -#endif // ewk_context_menu_private_h - diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h deleted file mode 100644 index db1980957..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_context_private.h +++ /dev/null @@ -1,112 +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 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 ewk_context_private_h -#define ewk_context_private_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; - -class EwkCookieManager; -class EwkFaviconDatabase; - -namespace WebKit { -class ContextHistoryClientEfl; -class DownloadManagerEfl; -class RequestManagerClientEfl; -#if ENABLE(BATTERY_STATUS) -class BatteryProvider; -#endif -#if ENABLE(NETWORK_INFO) -class NetworkInfoProvider; -#endif -} - -class EwkContext : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkContext) - - static PassRefPtr<EwkContext> findOrCreateWrapper(WKContextRef context); - static PassRefPtr<EwkContext> create(); - static PassRefPtr<EwkContext> create(const String& injectedBundlePath); - - static EwkContext* defaultContext(); - - ~EwkContext(); - - EwkCookieManager* cookieManager(); - - EwkDatabaseManager* databaseManager(); - - bool setFaviconDatabaseDirectoryPath(const String& databaseDirectory); - EwkFaviconDatabase* faviconDatabase(); - - EwkStorageManager* storageManager() const; - - WebKit::RequestManagerClientEfl* requestManager(); - - void addVisitedLink(const String& visitedURL); - - void setCacheModel(Ewk_Cache_Model); - - Ewk_Cache_Model cacheModel() const; - - WKContextRef wkContext() const { return m_context.get(); } - - WebKit::DownloadManagerEfl* downloadManager() const; - - WebKit::ContextHistoryClientEfl* historyClient(); - -#if ENABLE(NETSCAPE_PLUGIN_API) - void setAdditionalPluginPath(const String&); -#endif - - void clearResourceCache(); - -private: - explicit EwkContext(WKContextRef); - - void ensureFaviconDatabase(); - - WKRetainPtr<WKContextRef> m_context; - - 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 -#if ENABLE(NETWORK_INFO) - RefPtr<WebKit::NetworkInfoProvider> m_networkInfoProvider; -#endif - OwnPtr<WebKit::DownloadManagerEfl> m_downloadManager; - OwnPtr<WebKit::RequestManagerClientEfl> m_requestManagerClient; - - OwnPtr<WebKit::ContextHistoryClientEfl> m_historyClient; -}; - -#endif // ewk_context_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp deleted file mode 100644 index 475dca78e..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.cpp +++ /dev/null @@ -1,238 +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_cookie_manager.h" - -#include "WKAPICast.h" -#include "WKArray.h" -#include "WKCookieManagerSoup.h" -#include "WKString.h" -#include "ewk_cookie_manager_private.h" -#include "ewk_error_private.h" -#include "ewk_private.h" -#include <wtf/OwnPtr.h> - -using namespace WebKit; - -EwkCookieManager::EwkCookieManager(WKCookieManagerRef cookieManager) - : m_cookieManager(cookieManager) -{ - ASSERT(m_cookieManager); - - WKCookieManagerClient wkCookieManagerClient = { - kWKCookieManagerClientCurrentVersion, - this, // clientInfo - cookiesDidChange - }; - WKCookieManagerSetClient(m_cookieManager.get(), &wkCookieManagerClient); -} - -EwkCookieManager::~EwkCookieManager() -{ - if (isWatchingForChanges()) - WKCookieManagerStopObservingCookieChanges(m_cookieManager.get()); -} - -void EwkCookieManager::setPersistentStorage(const char* filename, WKCookieStorageType storageType) -{ - bool isWatchingChanges = isWatchingForChanges(); - if (isWatchingChanges) - WKCookieManagerStopObservingCookieChanges(m_cookieManager.get()); - - WKRetainPtr<WKStringRef> wkFilename(AdoptWK, WKStringCreateWithUTF8CString(filename)); - WKCookieManagerSetCookiePersistentStorage(m_cookieManager.get(), wkFilename.get(), storageType); - - if (isWatchingChanges) - WKCookieManagerStartObservingCookieChanges(m_cookieManager.get()); -} - -void EwkCookieManager::setHTTPAcceptPolicy(WKHTTPCookieAcceptPolicy policy) -{ - WKCookieManagerSetHTTPCookieAcceptPolicy(m_cookieManager.get(), policy); -} - -void EwkCookieManager::clearHostnameCookies(const char* hostname) -{ - WKRetainPtr<WKStringRef> wkHostname(AdoptWK, WKStringCreateWithUTF8CString(hostname)); - WKCookieManagerDeleteCookiesForHostname(m_cookieManager.get(), wkHostname.get()); -} - -void EwkCookieManager::clearAllCookies() -{ - WKCookieManagerDeleteAllCookies(m_cookieManager.get()); -} - -void EwkCookieManager::watchChanges(const Cookie_Change_Handler& changeHandler) -{ - m_changeHandler = changeHandler; - - if (changeHandler.callback) - WKCookieManagerStartObservingCookieChanges(m_cookieManager.get()); - else - WKCookieManagerStopObservingCookieChanges(m_cookieManager.get()); -} - -bool EwkCookieManager::isWatchingForChanges() const -{ - return static_cast<bool>(m_changeHandler.callback); -} - -void EwkCookieManager::getHostNamesWithCookies(WKCookieManagerGetCookieHostnamesFunction callback, void* userData) const -{ - WKCookieManagerGetHostnamesWithCookies(m_cookieManager.get(), userData, callback); -} - -void EwkCookieManager::getHTTPAcceptPolicy(WKCookieManagerGetHTTPCookieAcceptPolicyFunction callback, void* userData) const -{ - WKCookieManagerGetHTTPCookieAcceptPolicy(m_cookieManager.get(), userData, callback); -} - -void EwkCookieManager::cookiesDidChange(WKCookieManagerRef, const void* clientInfo) -{ - EwkCookieManager* manager = static_cast<EwkCookieManager*>(const_cast<void*>(clientInfo)); - - if (!manager->isWatchingForChanges()) - return; - - manager->m_changeHandler.callback(manager->m_changeHandler.userData); -} - -// Ewk_Cookie_Persistent_Storage enum validation. -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(filename, static_cast<WKCookieStorageType>(storage)); -} - -// Ewk_Cookie_Accept_Policy enum validation. -COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_ACCEPT_POLICY_ALWAYS, kWKHTTPCookieAcceptPolicyAlways); -COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_ACCEPT_POLICY_NEVER, kWKHTTPCookieAcceptPolicyNever); -COMPILE_ASSERT_MATCHING_ENUM(EWK_COOKIE_ACCEPT_POLICY_NO_THIRD_PARTY, kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain); - -void ewk_cookie_manager_accept_policy_set(Ewk_Cookie_Manager* manager, Ewk_Cookie_Accept_Policy policy) -{ - EINA_SAFETY_ON_NULL_RETURN(manager); - - manager->setHTTPAcceptPolicy(static_cast<WKHTTPCookieAcceptPolicy>(policy)); -} - -struct Get_Policy_Async_Data { - Ewk_Cookie_Manager_Async_Policy_Get_Cb callback; - void* userData; - - Get_Policy_Async_Data(Ewk_Cookie_Manager_Async_Policy_Get_Cb callback, void* userData) - : callback(callback) - , userData(userData) - { } -}; - -static void getAcceptPolicyCallback(WKHTTPCookieAcceptPolicy policy, WKErrorRef wkError, void* data) -{ - Get_Policy_Async_Data* callbackData = static_cast<Get_Policy_Async_Data*>(data); - OwnPtr<EwkError> ewkError = EwkError::create(wkError); - - callbackData->callback(static_cast<Ewk_Cookie_Accept_Policy>(policy), ewkError.get(), callbackData->userData); - - delete callbackData; -} - -void ewk_cookie_manager_async_accept_policy_get(const Ewk_Cookie_Manager* manager, Ewk_Cookie_Manager_Async_Policy_Get_Cb callback, void* data) -{ - EINA_SAFETY_ON_NULL_RETURN(manager); - EINA_SAFETY_ON_NULL_RETURN(callback); - - Get_Policy_Async_Data* callbackData = new Get_Policy_Async_Data(callback, data); - manager->getHTTPAcceptPolicy(getAcceptPolicyCallback, callbackData); -} - -struct Get_Hostnames_Async_Data { - Ewk_Cookie_Manager_Async_Hostnames_Get_Cb callback; - void* userData; - - Get_Hostnames_Async_Data(Ewk_Cookie_Manager_Async_Hostnames_Get_Cb callback, void* userData) - : callback(callback) - , userData(userData) - { } -}; - -static void getHostnamesWithCookiesCallback(WKArrayRef wkHostnames, WKErrorRef wkError, void* context) -{ - Eina_List* hostnames = 0; - Get_Hostnames_Async_Data* callbackData = static_cast<Get_Hostnames_Async_Data*>(context); - 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)); - if (WKStringIsEmpty(wkHostname)) - continue; - hostnames = eina_list_append(hostnames, WKEinaSharedString(wkHostname).leakString()); - } - - callbackData->callback(hostnames, ewkError.get(), callbackData->userData); - - void* item; - EINA_LIST_FREE(hostnames, item) - eina_stringshare_del(static_cast<Eina_Stringshare*>(item)); - - delete callbackData; -} - -void ewk_cookie_manager_async_hostnames_with_cookies_get(const Ewk_Cookie_Manager* manager, Ewk_Cookie_Manager_Async_Hostnames_Get_Cb callback, void* data) -{ - EINA_SAFETY_ON_NULL_RETURN(manager); - EINA_SAFETY_ON_NULL_RETURN(callback); - - Get_Hostnames_Async_Data* callbackData = new Get_Hostnames_Async_Data(callback, data); - manager->getHostNamesWithCookies(getHostnamesWithCookiesCallback, callbackData); -} - -void ewk_cookie_manager_hostname_cookies_clear(Ewk_Cookie_Manager* manager, const char* hostname) -{ - EINA_SAFETY_ON_NULL_RETURN(manager); - EINA_SAFETY_ON_NULL_RETURN(hostname); - - manager->clearHostnameCookies(hostname); -} - -void ewk_cookie_manager_cookies_clear(Ewk_Cookie_Manager* manager) -{ - EINA_SAFETY_ON_NULL_RETURN(manager); - - manager->clearAllCookies(); -} - -void ewk_cookie_manager_changes_watch(Ewk_Cookie_Manager* manager, Ewk_Cookie_Manager_Changes_Watch_Cb callback, void* data) -{ - EINA_SAFETY_ON_NULL_RETURN(manager); - - manager->watchChanges(Cookie_Change_Handler(callback, data)); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.h b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.h deleted file mode 100644 index 5257b75b7..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager.h +++ /dev/null @@ -1,174 +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_cookie_manager.h - * @brief Describes the Ewk Cookie Manager API. - */ - -#ifndef ewk_cookie_manager_h -#define ewk_cookie_manager_h - -#include "ewk_error.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for Ewk_Cookie_Manager */ -typedef struct EwkCookieManager Ewk_Cookie_Manager; - -/** - * \enum Ewk_Cookie_Accept_Policy - * - * @brief Contains accept policies for the cookies. - */ -enum Ewk_Cookie_Accept_Policy { - /// Accepts every cookie sent from any page. - EWK_COOKIE_ACCEPT_POLICY_ALWAYS, - /// Rejects all cookies. - EWK_COOKIE_ACCEPT_POLICY_NEVER, - /// Accepts only cookies set by the main document loaded. - EWK_COOKIE_ACCEPT_POLICY_NO_THIRD_PARTY -}; - -/// Creates a type name for the Ewk_Cookie_Accept_Policy. -typedef enum Ewk_Cookie_Accept_Policy Ewk_Cookie_Accept_Policy; - -/** - * \enum Ewk_Cookie_Persistent_Storage - * - * @brief Enum values to denote cookies persistent storage type. - */ -enum Ewk_Cookie_Persistent_Storage { - /// Cookies are stored in a text file in the Mozilla "cookies.txt" format. - EWK_COOKIE_PERSISTENT_STORAGE_TEXT, - /// Cookies are stored in a SQLite file in the current Mozilla format. - EWK_COOKIE_PERSISTENT_STORAGE_SQLITE -}; - -/// Creates a type name for the Ewk_Cookie_Persistent_Storage. -typedef enum Ewk_Cookie_Persistent_Storage Ewk_Cookie_Persistent_Storage; - -/** - * @typedef Ewk_Cookie_Manager_Async_Policy_Get_Cb Ewk_Cookie_Manager_Async_Policy_Get_Cb - * @brief Callback type for use with ewk_cookie_manager_async_accept_policy_get - */ -typedef void (*Ewk_Cookie_Manager_Async_Policy_Get_Cb)(Ewk_Cookie_Accept_Policy policy, Ewk_Error *error, void *event_info); - -/** - * @typedef Ewk_Cookie_Manager_Async_Hostnames_Get_Cb Ewk_Cookie_Manager_Async_Hostnames_Get_Cb - * @brief Callback type for use with ewk_cookie_manager_async_hostnames_with_cookies_get - * - * @note The @a hostnames list items are guaranteed to be eina_stringshare. Whenever possible - * save yourself some cpu cycles and use eina_stringshare_ref() instead of eina_stringshare_add() - * or strdup(). - */ -typedef void (*Ewk_Cookie_Manager_Async_Hostnames_Get_Cb)(Eina_List *hostnames, Ewk_Error *error, void *event_info); - -/** - * @typedef Ewk_Cookie_Manager_Changes_Watch_Cb Ewk_Cookie_Manager_Changes_Watch_Cb - * @brief Callback type for use with ewk_cookie_manager_changes_watch() - */ -typedef void (*Ewk_Cookie_Manager_Changes_Watch_Cb)(void *event_info); - -/** - * Set the @a filename where non-session cookies are stored persistently using @a storage as the format to read/write the cookies. - * - * Cookies are initially read from @filename to create an initial set of cookies. - * Then, non-session cookies will be written to @filename. - * - * By default, @a manager doesn't store the cookies persistenly, so you need to call this - * method to keep cookies saved across sessions. - * - * @param cookie_manager The cookie manager to update. - * @param filename the filename to read to/write from. - * @param storage the type of storage. - */ -EAPI void ewk_cookie_manager_persistent_storage_set(Ewk_Cookie_Manager *manager, const char *filename, Ewk_Cookie_Persistent_Storage storage); - -/** - * Set @a policy as the cookie acceptance policy for @a manager. - * - * By default, only cookies set by the main document loaded are accepted. - * - * @param manager The cookie manager to update. - * @param policy a #Ewk_Cookie_Accept_Policy - */ - -EAPI void ewk_cookie_manager_accept_policy_set(Ewk_Cookie_Manager *manager, Ewk_Cookie_Accept_Policy policy); - -/** - * Asynchronously get the cookie acceptance policy of @a manager. - * - * By default, only cookies set by the main document loaded are accepted. - * - * @param manager The cookie manager to query. - * @param callback The function to call when the policy is received or an error occured. - * @param data User data (may be @c NULL). - */ -EAPI void ewk_cookie_manager_async_accept_policy_get(const Ewk_Cookie_Manager *manager, Ewk_Cookie_Manager_Async_Policy_Get_Cb callback, void *data); - -/** - * Asynchronously get the list of host names for which @a manager contains cookies. - * - * @param manager The cookie manager to query. - * @param callback The function to call when the host names have been received. - * @param data User data (may be @c NULL). - */ -EAPI void ewk_cookie_manager_async_hostnames_with_cookies_get(const Ewk_Cookie_Manager *manager, Ewk_Cookie_Manager_Async_Hostnames_Get_Cb callback, void *data); - -/** - * Remove all cookies of @a manager for the given @a hostname. - * - * @param manager The cookie manager to update. - * @param hostname A host name. - */ -EAPI void ewk_cookie_manager_hostname_cookies_clear(Ewk_Cookie_Manager *manager, const char *hostname); - -/** - * Watch for cookies changes in @a manager. - * - * Pass @c NULL as value for @a callback to stop watching for changes. - * - * @param manager The cookie manager to watch. - * @param callback function that will be called every time cookies are added, removed or modified. - * @param data User data (may be @c NULL). - */ -EAPI void ewk_cookie_manager_changes_watch(Ewk_Cookie_Manager *manager, Ewk_Cookie_Manager_Changes_Watch_Cb callback, void *data); - -/** - * Delete all cookies of @a manager. - * - * @param manager The cookie manager to update. - */ -EAPI void ewk_cookie_manager_cookies_clear(Ewk_Cookie_Manager *manager); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_cookie_manager_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h deleted file mode 100644 index d478936df..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_cookie_manager_private.h +++ /dev/null @@ -1,82 +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_cookie_manager_private_h -#define ewk_cookie_manager_private_h - -#include "WKCookieManager.h" -#include "WKCookieManagerSoup.h" -#include "WKRetainPtr.h" -#include "ewk_cookie_manager.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -struct Cookie_Change_Handler { - Ewk_Cookie_Manager_Changes_Watch_Cb callback; - void* userData; - - Cookie_Change_Handler() - : callback(0) - , userData(0) - { } - - Cookie_Change_Handler(Ewk_Cookie_Manager_Changes_Watch_Cb _callback, void* _userData) - : callback(_callback) - , userData(_userData) - { } -}; - -class EwkCookieManager { -public: - static PassOwnPtr<EwkCookieManager> create(WKCookieManagerRef cookieManager) - { - return adoptPtr(new EwkCookieManager(cookieManager)); - } - - ~EwkCookieManager(); - - void setPersistentStorage(const char* filename, WKCookieStorageType); - - void getHTTPAcceptPolicy(WKCookieManagerGetHTTPCookieAcceptPolicyFunction callback, void* userData) const; - void setHTTPAcceptPolicy(WKHTTPCookieAcceptPolicy policy); - - 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 cookieManager); - - bool isWatchingForChanges() const; - - static void cookiesDidChange(WKCookieManagerRef, const void* clientInfo); - - WKRetainPtr<WKCookieManagerRef> m_cookieManager; - Cookie_Change_Handler m_changeHandler; -}; - -#endif // ewk_cookie_manager_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp deleted file mode 100644 index 20155415e..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_database_manager.h" - -#include "WKAPICast.h" -#include "WKArray.h" -#include "ewk_database_manager_private.h" -#include "ewk_error_private.h" -#include "ewk_security_origin_private.h" - -using namespace WebKit; - -EwkDatabaseManager::EwkDatabaseManager(WKDatabaseManagerRef databaseManager) - : m_databaseManager(databaseManager) -{ - ASSERT(databaseManager); -} - -void EwkDatabaseManager::getDatabaseOrigins(WKDatabaseManagerGetDatabaseOriginsFunction callback, void* context) const -{ - WKDatabaseManagerGetDatabaseOrigins(m_databaseManager.get(), context, callback); -} - -Eina_List* EwkDatabaseManager::createOriginList(WKArrayRef origins) const -{ - Eina_List* originList = 0; - const size_t length = WKArrayGetSize(origins); - - for (size_t i = 0; i < length; ++i) { - WKSecurityOriginRef wkOriginRef = static_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, i)); - RefPtr<EwkSecurityOrigin> origin = m_wrapperCache.get(wkOriginRef); - if (!origin) { - origin = EwkSecurityOrigin::create(wkOriginRef); - m_wrapperCache.set(wkOriginRef, origin); - } - originList = eina_list_append(originList, origin.release().leakRef()); - } - - return originList; -} - -struct Ewk_Database_Origins_Async_Get_Context { - const Ewk_Database_Manager* manager; - Ewk_Database_Origins_Get_Cb callback; - void* userData; - - Ewk_Database_Origins_Async_Get_Context(const Ewk_Database_Manager* manager, Ewk_Database_Origins_Get_Cb callback, void* userData) - : manager(manager) - , callback(callback) - , userData(userData) - { } -}; - -static void getDatabaseOriginsCallback(WKArrayRef origins, WKErrorRef wkError, void* context) -{ - 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<EwkError> ewkError = EwkError::create(wkError); - webDatabaseContext->callback(originList, ewkError.get(), webDatabaseContext->userData); -} - -Eina_Bool ewk_database_manager_origins_get(const Ewk_Database_Manager* ewkDatabaseManager, Ewk_Database_Origins_Get_Cb callback, void* userData) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(ewkDatabaseManager, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(callback, false); - - Ewk_Database_Origins_Async_Get_Context* context = new Ewk_Database_Origins_Async_Get_Context(ewkDatabaseManager, callback, userData); - ewkDatabaseManager->getDatabaseOrigins(getDatabaseOriginsCallback, context); - - return true; -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h deleted file mode 100644 index 610a736eb..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_database_manager.h - * @brief Describes the Ewk Database Manager API. - * - * Ewk Database Manager manages web database. - */ - -#ifndef ewk_database_manager_h -#define ewk_database_manager_h - -#include "ewk_error.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for Ewk_Database_Manager. */ -typedef struct EwkDatabaseManager Ewk_Database_Manager; - -/** - * @typedef Ewk_Database_Origins_Get_Cb Ewk_Database_Origins_Get_Cb - * @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_object_unref() - * to free the items - */ -typedef void (*Ewk_Database_Origins_Get_Cb)(Eina_List *origins, Ewk_Error *error, void *user_data); - -/** - * Gets list of origins using web database asynchronously. - * - * This function allocates memory for context structure made from callback and user_data. - * - * @param manager Ewk_Database_Manager object - * @param callback callback to get database origins - * @param user_data user_data will be passed when result_callback is called, - * -i.e., user data will be kept until callback is called - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_database_manager_origins_get(const Ewk_Database_Manager *manager, Ewk_Database_Origins_Get_Cb callback, void *user_data); - -#ifdef __cplusplus -} -#endif -#endif // ewk_database_manager_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h deleted file mode 100644 index b76918505..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_database_manager_private.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_database_manager_private_h -#define ewk_database_manager_private_h - -#include "WKDatabaseManager.h" -#include "WKRetainPtr.h" -#include "ewk_security_origin_private.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -using namespace WebKit; - -class EwkDatabaseManager { -public: - static PassOwnPtr<EwkDatabaseManager> create(WKDatabaseManagerRef databaseManager) - { - ASSERT(databaseManager); - return adoptPtr(new EwkDatabaseManager(databaseManager)); - } - - Eina_List* createOriginList(WKArrayRef wkList) const; - void getDatabaseOrigins(WKDatabaseManagerGetDatabaseOriginsFunction callback, void* context) const; - -private: - explicit EwkDatabaseManager(WKDatabaseManagerRef); - - 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 deleted file mode 100644 index bf0177f8b..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_defines.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_defines.h - * @brief Defines the Ewk Structs - */ - -#ifndef ewk_defines_h -#define ewk_defines_h - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * 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; - -#ifdef __cplusplus -} -#endif - -#endif /* ewk_defines_h */ diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp deleted file mode 100644 index 9ae97357c..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_download_job.cpp +++ /dev/null @@ -1,254 +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_download_job.h" - -#include "WKAPICast.h" -#include "WKRetainPtr.h" -#include "WKURLRequest.h" -#include "ewk_download_job_private.h" -#include "ewk_url_response_private.h" -#include <Ecore.h> - -using namespace WebKit; - -EwkDownloadJob::EwkDownloadJob(WKDownloadRef download, EwkView* viewImpl) - : m_download(download) - , m_viewImpl(viewImpl) - , m_state(EWK_DOWNLOAD_JOB_STATE_NOT_STARTED) - , m_startTime(-1) - , m_endTime(-1) - , m_downloaded(0) -{ } - -/** - * @internal - * Queries the identifier for this download - */ -uint64_t EwkDownloadJob::id() const -{ - return WKDownloadGetID(m_download.get()); -} - -/** - * @internal - * Returns the view this download is attached to. - * The view is needed to send notification signals. - */ -EwkView* EwkDownloadJob::view() const -{ - return m_viewImpl; -} - -Ewk_Download_Job_State ewk_download_job_state_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, EWK_DOWNLOAD_JOB_STATE_UNKNOWN); - - return impl->state(); -} - -Ewk_Download_Job_State EwkDownloadJob::state() const -{ - return m_state; -} - -Ewk_Url_Request* ewk_download_job_request_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, 0); - - return impl->request(); -} - -EwkUrlRequest* EwkDownloadJob::request() const -{ - if (!m_request) { - WKRetainPtr<WKURLRequestRef> wkURLRequest(AdoptWK, WKDownloadCopyRequest(m_download.get())); - m_request = EwkUrlRequest::create(wkURLRequest.get()); - } - - return m_request.get(); -} - -Ewk_Url_Response* ewk_download_job_response_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, 0); - - return impl->response(); -} - -EwkUrlResponse* EwkDownloadJob::response() const -{ - return m_response.get(); -} - -const char* ewk_download_job_destination_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, 0); - - return impl->destination(); -} - -const char* EwkDownloadJob::destination() const -{ - return m_destination; -} - -Eina_Bool ewk_download_job_destination_set(Ewk_Download_Job* download, const char* destination) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkDownloadJob, download, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(destination, false); - - impl->setDestination(destination); - - return true; -} - -void EwkDownloadJob::setDestination(const char* destination) -{ - m_destination = destination; -} - -const char* ewk_download_job_suggested_filename_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, 0); - - return impl->suggestedFileName(); -} - -const char* EwkDownloadJob::suggestedFileName() const -{ - return m_suggestedFilename; -} - -Eina_Bool ewk_download_job_cancel(Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkDownloadJob, download, impl, false); - - return impl->cancel(); -} - -bool EwkDownloadJob::cancel() -{ - if (m_state != EWK_DOWNLOAD_JOB_STATE_DOWNLOADING) - return false; - - m_state = EWK_DOWNLOAD_JOB_STATE_CANCELLING; - WKDownloadCancel(m_download.get()); - - return true; -} - -double ewk_download_job_estimated_progress_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, 0); - - return impl->estimatedProgress(); -} - -double EwkDownloadJob::estimatedProgress() const -{ - if (!m_response) - return 0; - - const unsigned long contentLength = m_response->contentLength(); - if (!contentLength) - return 0; - - return static_cast<double>(m_downloaded) / contentLength; -} - -double ewk_download_job_elapsed_time_get(const Ewk_Download_Job* download) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkDownloadJob, download, impl, 0); - - return impl->elapsedTime(); -} - -double EwkDownloadJob::elapsedTime() const -{ - // Download has not started yet. - if (m_startTime < 0) - return 0; - - // Download had ended, return the time elapsed between the - // download start and the end event. - if (m_endTime >= 0) - return m_endTime - m_startTime; - - // Download is still going. - return ecore_time_get() - m_startTime; -} - -/** - * @internal - * Sets the URL @a response for this @a download. - */ -void EwkDownloadJob::setResponse(PassRefPtr<EwkUrlResponse> response) -{ - ASSERT(response); - - m_response = response; -} - -/** - * @internal - * Sets the suggested file name for this @a download. - */ -void EwkDownloadJob::setSuggestedFileName(const char* suggestedFilename) -{ - m_suggestedFilename = suggestedFilename; -} - -/** - * @internal - * Report a given amount of data was received. - */ -void EwkDownloadJob::incrementReceivedData(uint64_t length) -{ - m_downloaded += length; -} - -/** - * @internal - * Sets the state of the download. - */ -void EwkDownloadJob::setState(Ewk_Download_Job_State state) -{ - m_state = state; - - switch (state) { - case EWK_DOWNLOAD_JOB_STATE_DOWNLOADING: - m_startTime = ecore_time_get(); - break; - case EWK_DOWNLOAD_JOB_STATE_FAILED: - case EWK_DOWNLOAD_JOB_STATE_CANCELLED: - case EWK_DOWNLOAD_JOB_STATE_FINISHED: - m_endTime = ecore_time_get(); - break; - default: - break; - } -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_download_job.h b/Source/WebKit2/UIProcess/API/efl/ewk_download_job.h deleted file mode 100644 index 6160904aa..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_download_job.h +++ /dev/null @@ -1,190 +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_download_job.h - * @brief Describes the Download Job API. - * - * @note Ewk_Download_Job encapsulates a WebKit download job in order to provide - * information about it and interact with it (e.g. set the destination - * path, cancel the download, ...). - */ - -#ifndef ewk_download_job_h -#define ewk_download_job_h - -#include "ewk_url_request.h" -#include "ewk_url_response.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Download_Job as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Download_Job; - -/// Defines the possible states of a download. -enum Ewk_Download_Job_State { - /// The download state is unknown - EWK_DOWNLOAD_JOB_STATE_UNKNOWN = -1, - /// The download has not started yet - EWK_DOWNLOAD_JOB_STATE_NOT_STARTED, - /// The download has started - EWK_DOWNLOAD_JOB_STATE_DOWNLOADING, - /// The download stopped because of a failure - EWK_DOWNLOAD_JOB_STATE_FAILED, - /// The download is being cancelled - EWK_DOWNLOAD_JOB_STATE_CANCELLING, - /// The download stopped because it was cancelled - EWK_DOWNLOAD_JOB_STATE_CANCELLED, - /// The download completed successfully. - EWK_DOWNLOAD_JOB_STATE_FINISHED -}; -/// Creates a type name for @a Ewk_Download_Job_State. -typedef enum Ewk_Download_Job_State Ewk_Download_Job_State; - -/** - * Query the state for this download. - * - * @param download a #Ewk_Download_Job to query. - * - * @return the download state. - */ -EAPI Ewk_Download_Job_State ewk_download_job_state_get(const Ewk_Download_Job *download); - -/** - * Query the URL request for this download. - * - * @param download a #Ewk_Download_Job to query. - * - * @return the #Ewk_Url_Request for this download. - */ -EAPI Ewk_Url_Request *ewk_download_job_request_get(const Ewk_Download_Job *download); - -/** - * Query the URL response for this download. - * - * @param download a #Ewk_Download_Job to query. - * - * @return the #Ewk_Url_Response for this download or @c NULL if it was not received yet. - */ -EAPI Ewk_Url_Response *ewk_download_job_response_get(const Ewk_Download_Job *download); - -/** - * Query the URL to which the downloaded file will be written. - * - * @param download a #Ewk_Download_Job to query. - * - * @return the destination 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_download_job_destination_get(const Ewk_Download_Job *download); - -/** - * Sets the destination path for this download. - * - * Sets the path to which the downloaded file will be written. - * - * This method needs to be called before the download transfer - * starts, by connecting to the "download,new" signal on the - * Ewk_View and setting the destination in the callback. To set - * the destination using the filename suggested by the server - * use ewk_download_job_suggested_filename_get(). - * - * @param download #Ewk_Download_Job to update. - * @param destination the destination path. - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise. - * - * @see ewk_download_job_suggested_filename_get - */ -EAPI Eina_Bool ewk_download_job_destination_set(Ewk_Download_Job *download, const char *destination); - -/** - * Queries the suggested file name for this download. - * - * It can be useful to use the value returned by this function to construct - * the destination path to pass to ewk_download_job_destination_set(). - * - * @param download #Ewk_Download_Job to query. - * - * @return The suggested file name for this download. 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(). - * - * @see ewk_download_job_destination_set - */ -EAPI const char *ewk_download_job_suggested_filename_get(const Ewk_Download_Job *download); - -/** - * Cancels the download asynchronously. - * - * When the ongoing download operation is effectively cancelled a "download,cancelled" - * signal will be emitted on the view. - * - * @param download a #Ewk_Download_Job to cancel. - * - * @return @c EINA_TRUE if the cancellation request was taken into account, or - * @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_download_job_cancel(Ewk_Download_Job *download); - -/** - * Query the estimated progress for this download. - * - * @param download a #Ewk_Download_Job to query. - * - * @return an estimate of the of the percent complete for a download - * as a range from 0.0 to 1.0. - */ -EAPI double ewk_download_job_estimated_progress_get(const Ewk_Download_Job *download); - -/** - * Gets the elapsed time in seconds, including any fractional part. - * - * If the download finished, had an error or was cancelled this is - * the time between its start and the event. - * - * @param download a #Ewk_Download_Job - * - * @return seconds since the download was started or 0.0 in case of failure. - */ -EAPI double ewk_download_job_elapsed_time_get(const Ewk_Download_Job *download); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_download_job_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h deleted file mode 100644 index 3e516ef22..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_download_job_private.h +++ /dev/null @@ -1,87 +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_download_job_private_h -#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> - -class EwkView; - -class EwkDownloadJob : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkDownloadJob) - - static PassRefPtr<EwkDownloadJob> create(WKDownloadRef download, EwkView* viewImpl) - { - return adoptRef(new EwkDownloadJob(download, viewImpl)); - } - - uint64_t id() const; - EwkView* view() const; - - Ewk_Download_Job_State state() const; - void setState(Ewk_Download_Job_State); - - EwkUrlRequest* request() const; - EwkUrlResponse* response() const; - void setResponse(PassRefPtr<EwkUrlResponse>); - - const char* destination() const; - void setDestination(const char* destination); - - const char* suggestedFileName() const; - void setSuggestedFileName(const char* fileName); - - bool cancel(); - - double estimatedProgress() const; - double elapsedTime() const; - void incrementReceivedData(uint64_t length); - -private: - EwkDownloadJob(WKDownloadRef download, EwkView* view); - - WKRetainPtr<WKDownloadRef> m_download; - EwkView* m_viewImpl; - Ewk_Download_Job_State m_state; - mutable RefPtr<EwkUrlRequest> m_request; - RefPtr<EwkUrlResponse> m_response; - double m_startTime; - double m_endTime; - uint64_t m_downloaded; // length already downloaded - WKEinaSharedString m_destination; - WKEinaSharedString m_suggestedFilename; -}; - -#endif // ewk_download_job_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp deleted file mode 100644 index 29031fdf4..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_error.cpp +++ /dev/null @@ -1,114 +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_error.h" - -#include "ErrorsEfl.h" -#include "WKError.h" -#include "WKString.h" -#include "WKURL.h" -#include "ewk_error_private.h" - -using namespace WebCore; - -EwkError::EwkError(WKErrorRef errorRef) - : m_wkError(errorRef) - , m_url(AdoptWK, WKErrorCopyFailingURL(errorRef)) - , m_description(AdoptWK, WKErrorCopyLocalizedDescription(errorRef)) -{ } - -const char* EwkError::url() const -{ - return m_url; -} - -const char* EwkError::description() const -{ - return m_description; -} - -WKRetainPtr<WKStringRef> EwkError::domain() const -{ - return adoptWK(WKErrorCopyDomain(m_wkError.get())); -} - -int EwkError::errorCode() const -{ - return WKErrorGetErrorCode(m_wkError.get()); -} - -bool EwkError::isCancellation() const -{ - 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); - - WKRetainPtr<WKStringRef> wkErrorDomain = error->domain(); - - if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainNetwork)) - return EWK_ERROR_TYPE_NETWORK; - if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainPolicy)) - return EWK_ERROR_TYPE_POLICY; - if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainPlugin)) - return EWK_ERROR_TYPE_PLUGIN; - if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainDownload)) - return EWK_ERROR_TYPE_DOWNLOAD; - if (WKStringIsEqualToUTF8CString(wkErrorDomain.get(), errorDomainPrint)) - return EWK_ERROR_TYPE_PRINT; - - return EWK_ERROR_TYPE_INTERNAL; -} - -const char* ewk_error_url_get(const Ewk_Error* error) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(error, 0); - - return error->url(); -} - -int ewk_error_code_get(const Ewk_Error* error) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(error, 0); - - return error->errorCode(); -} - -const char* ewk_error_description_get(const Ewk_Error* error) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(error, 0); - - return error->description(); -} - -Eina_Bool ewk_error_cancellation_get(const Ewk_Error* error) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(error, false); - - return error->isCancellation(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_error.h b/Source/WebKit2/UIProcess/API/efl/ewk_error.h deleted file mode 100644 index b857a30e2..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_error.h +++ /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. - */ - -/** - * @file ewk_error.h - * @brief Describes the Web Error API. - */ - -#ifndef ewk_error_h -#define ewk_error_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for @a Ewk_Error. */ -typedef struct EwkError Ewk_Error; - -/// Creates a type name for Ewk_Error_Type. -typedef enum { - EWK_ERROR_TYPE_NONE, - EWK_ERROR_TYPE_INTERNAL, - EWK_ERROR_TYPE_NETWORK, - EWK_ERROR_TYPE_POLICY, - EWK_ERROR_TYPE_PLUGIN, - EWK_ERROR_TYPE_DOWNLOAD, - EWK_ERROR_TYPE_PRINT -} Ewk_Error_Type; - -/** - * Query type for this error. - * - * @param error error object to query. - * - * @return the error type, 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 Ewk_Error_Type ewk_error_type_get(const Ewk_Error *error); - -/** - * Query failing URL for this error. - * - * URL that failed loading. - * - * @param error error 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_error_url_get(const Ewk_Error *error); - -/** - * Query HTTP error code. - * - * @param error error object to query. - * - * @return the HTTP error code. - */ -EAPI int ewk_error_code_get(const Ewk_Error *error); - -/** - * Query description for this error. - * - * @param error error object to query. - * - * @return the description 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_error_description_get(const Ewk_Error *error); - -/** - * Query if error should be treated as a cancellation. - * - * @param error error object to query. - * - * @return @c EINA_TRUE if this error should be treated as a cancellation, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_error_cancellation_get(const Ewk_Error *error); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_error_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h deleted file mode 100644 index 54682f076..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_error_private.h +++ /dev/null @@ -1,58 +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_error_private_h -#define ewk_error_private_h - -#include "WKEinaSharedString.h" -#include <WKRetainPtr.h> -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkError { -public: - static PassOwnPtr<EwkError> create(WKErrorRef errorRef) - { - if (!errorRef) - return nullptr; - - return adoptPtr(new EwkError(errorRef)); - } - - const char* url() const; - const char* description() const; - WKRetainPtr<WKStringRef> domain() const; - int errorCode() const; - bool isCancellation() const; - -private: - explicit EwkError(WKErrorRef errorRef); - - WKRetainPtr<WKErrorRef> m_wkError; - WKEinaSharedString m_url; - WKEinaSharedString m_description; -}; - -#endif // ewk_error_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp deleted file mode 100644 index 6300ab390..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * 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 - * 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_favicon_database.h" - -#include "WKAPICast.h" -#include "WKIconDatabase.h" -#include "WKIconDatabaseCairo.h" -#include "WKURL.h" -#include "ewk_favicon_database_private.h" -#include <WebCore/CairoUtilitiesEfl.h> -#include <WebCore/RefPtrCairo.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -using namespace WebKit; - -EwkFaviconDatabase::EwkFaviconDatabase(WKIconDatabaseRef iconDatabase) - : m_iconDatabase(iconDatabase) -{ - WKIconDatabaseClient iconDatabaseClient; - memset(&iconDatabaseClient, 0, sizeof(WKIconDatabaseClient)); - iconDatabaseClient.version = kWKIconDatabaseClientCurrentVersion; - iconDatabaseClient.clientInfo = this; - iconDatabaseClient.iconDataReadyForPageURL = iconDataReadyForPageURL; - WKIconDatabaseSetIconDatabaseClient(m_iconDatabase.get(), &iconDatabaseClient); -} - -EwkFaviconDatabase::~EwkFaviconDatabase() -{ - WKIconDatabaseSetIconDatabaseClient(m_iconDatabase.get(), 0); -} - -void EwkFaviconDatabase::watchChanges(const IconChangeCallbackData& callbackData) -{ - ASSERT(callbackData.callback); - if (m_changeListeners.contains(callbackData.callback)) - return; - - m_changeListeners.add(callbackData.callback, callbackData); -} - -void EwkFaviconDatabase::unwatchChanges(Ewk_Favicon_Database_Icon_Change_Cb callback) -{ - ASSERT(callback); - m_changeListeners.remove(callback); -} - -void EwkFaviconDatabase::didChangeIconForPageURL(WKIconDatabaseRef, WKURLRef pageURLRef, const void* clientInfo) -{ - const EwkFaviconDatabase* ewkIconDatabase = static_cast<const EwkFaviconDatabase*>(clientInfo); - - if (ewkIconDatabase->m_changeListeners.isEmpty()) - return; - - CString pageURL = toWTFString(pageURLRef).utf8(); - - ChangeListenerMap::const_iterator it = ewkIconDatabase->m_changeListeners.begin(); - ChangeListenerMap::const_iterator end = ewkIconDatabase->m_changeListeners.end(); - for (; it != end; ++it) - it->value.callback(pageURL.data(), it->value.userData); -} - -PassRefPtr<cairo_surface_t> EwkFaviconDatabase::getIconSurfaceSynchronously(const char* pageURL) const -{ - WKRetainPtr<WKURLRef> wkPageURL(AdoptWK, WKURLCreateWithUTF8CString(pageURL)); - - RefPtr<cairo_surface_t> surface = WKIconDatabaseTryGetCairoSurfaceForURL(m_iconDatabase.get(), wkPageURL.get()); - if (!surface) - return 0; - - return surface.release(); -} - -void EwkFaviconDatabase::iconDataReadyForPageURL(WKIconDatabaseRef, WKURLRef pageURL, const void* clientInfo) -{ - EwkFaviconDatabase* ewkIconDatabase = const_cast<EwkFaviconDatabase*>(static_cast<const EwkFaviconDatabase*>(clientInfo)); - - WKIconDatabaseRetainIconForURL(ewkIconDatabase->m_iconDatabase.get(), pageURL); - - 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); -} - -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); - - RefPtr<cairo_surface_t> surface = ewkIconDatabase->getIconSurfaceSynchronously(pageURL); - if (!surface) - return 0; - - 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) -{ - EINA_SAFETY_ON_NULL_RETURN(ewkIconDatabase); - EINA_SAFETY_ON_NULL_RETURN(callback); - - ewkIconDatabase->watchChanges(IconChangeCallbackData(callback, userData)); -} - -void ewk_favicon_database_icon_change_callback_del(Ewk_Favicon_Database* ewkIconDatabase, Ewk_Favicon_Database_Icon_Change_Cb callback) -{ - EINA_SAFETY_ON_NULL_RETURN(ewkIconDatabase); - EINA_SAFETY_ON_NULL_RETURN(callback); - - ewkIconDatabase->unwatchChanges(callback); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h deleted file mode 100644 index d5cefd2e4..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 - * 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_favicon_database.h - * @brief Describes the Ewk Favicon Database API. - */ - -#ifndef ewk_favicon_database_h -#define ewk_favicon_database_h - -#include <Evas.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for @a Ewk_Favicon_Database. */ -typedef struct EwkFaviconDatabase Ewk_Favicon_Database; - -/** - * @typedef Ewk_Favicon_Database_Icon_Change_Cb Ewk_Favicon_Database_Icon_Change_Cb - * @brief Callback type for use with ewk_favicon_database_icon_change_callback_add and ewk_favicon_database_icon_change_callback_del - */ -typedef void (*Ewk_Favicon_Database_Icon_Change_Cb)(const char *page_url, void *event_info); - -/** - * 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 - * - * @return The favicon as an Evas_Object if successful, @c NULL otherwise. - * The returned Evas_Object needs to be freed after use. - */ -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 - * - * @param database database object to register the callback - * @param callback callback function to be called when an icon changes - * @param data the data pointer that was to be passed to the callback - */ -EAPI void ewk_favicon_database_icon_change_callback_add(Ewk_Favicon_Database *database, Ewk_Favicon_Database_Icon_Change_Cb callback, void *data); - -/** - * Delete (unregister) a callback function registered to a icon change event - * - * @param database database object to unregister the callback. - * @param callback callback function to unregister - */ -EAPI void ewk_favicon_database_icon_change_callback_del(Ewk_Favicon_Database *database, Ewk_Favicon_Database_Icon_Change_Cb callback); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_favicon_database_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h deleted file mode 100644 index 1cc7722d8..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_favicon_database_private.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 - * 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_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> - -struct IconChangeCallbackData { - Ewk_Favicon_Database_Icon_Change_Cb callback; - void* userData; - - IconChangeCallbackData() - : callback(0) - , userData(0) - { } - - IconChangeCallbackData(Ewk_Favicon_Database_Icon_Change_Cb _callback, void* _userData) - : callback(_callback) - , userData(_userData) - { } -}; - -typedef HashMap<Ewk_Favicon_Database_Icon_Change_Cb, IconChangeCallbackData> ChangeListenerMap; - -class EwkFaviconDatabase { -public: - static PassOwnPtr<EwkFaviconDatabase> create(WKIconDatabaseRef iconDatabase) - { - return adoptPtr(new EwkFaviconDatabase(iconDatabase)); - } - ~EwkFaviconDatabase(); - - 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(WKIconDatabaseRef iconDatabase); - - static void didChangeIconForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL, const void* clientInfo); - static void iconDataReadyForPageURL(WKIconDatabaseRef iconDatabase, WKURLRef pageURL, const void* clientInfo); - - WKRetainPtr<WKIconDatabaseRef> m_iconDatabase; - ChangeListenerMap m_changeListeners; -}; - -#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 deleted file mode 100644 index 825fcffec..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.cpp +++ /dev/null @@ -1,152 +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_file_chooser_request.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(WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener) - : m_parameters(parameters) - , m_listener(listener) - , m_wasRequestHandled(false) -{ - ASSERT(parameters); - ASSERT(listener); -} - -EwkFileChooserRequest::~EwkFileChooserRequest() -{ - if (!m_wasRequestHandled) - WKOpenPanelResultListenerCancel(m_listener.get()); -} - -bool EwkFileChooserRequest::allowMultipleFiles() const -{ - return WKOpenPanelParametersGetAllowsMultipleFiles(m_parameters.get()); -} - -WKRetainPtr<WKArrayRef> EwkFileChooserRequest::acceptedMIMETypes() const -{ - return adoptWK(WKOpenPanelParametersCopyAcceptedMIMETypes(m_parameters.get())); -} - -void EwkFileChooserRequest::cancel() -{ - m_wasRequestHandled = true; - - return WKOpenPanelResultListenerCancel(m_listener.get()); -} - -void EwkFileChooserRequest::chooseFiles(WKArrayRef fileURLs) -{ - m_wasRequestHandled = true; - WKOpenPanelResultListenerChooseFiles(m_listener.get(), fileURLs); -} - -Eina_Bool ewk_file_chooser_request_allow_multiple_files_get(const Ewk_File_Chooser_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkFileChooserRequest, request, impl, false); - - return impl->allowMultipleFiles(); -} - -Eina_List* ewk_file_chooser_request_accepted_mimetypes_get(const Ewk_File_Chooser_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkFileChooserRequest, request, impl, 0); - - Eina_List* mimeTypeList = 0; - WKRetainPtr<WKArrayRef> mimeTypes = impl->acceptedMIMETypes(); - - const size_t size = WKArrayGetSize(mimeTypes.get()); - for (size_t i = 0; i < size; ++i) { - WKRetainPtr<WKStringRef> mimeType = static_cast<WKStringRef>(WKArrayGetItemAtIndex(mimeTypes.get(), i)); - if (!mimeType || WKStringIsEmpty(mimeType.get())) - continue; - mimeTypeList = eina_list_append(mimeTypeList, eina_stringshare_add(toWTFString(mimeType.get()).utf8().data())); - } - - return mimeTypeList; -} - -Eina_Bool ewk_file_chooser_request_cancel(Ewk_File_Chooser_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkFileChooserRequest, request, impl, false); - EINA_SAFETY_ON_TRUE_RETURN_VAL(impl->wasHandled(), false); - - impl->cancel(); - - return true; -} - -Eina_Bool ewk_file_chooser_request_files_choose(Ewk_File_Chooser_Request* request, const Eina_List* chosenFiles) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkFileChooserRequest, request, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(chosenFiles, false); - EINA_SAFETY_ON_TRUE_RETURN_VAL(impl->wasHandled(), false); - - 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]); - - 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); - } - - WKRetainPtr<WKArrayRef> wkFileURLs(AdoptWK, WKArrayCreateAdoptingValues(filesURLs.get(), urlCount)); - impl->chooseFiles(wkFileURLs.get()); - - return true; -} - -Eina_Bool ewk_file_chooser_request_file_choose(Ewk_File_Chooser_Request* request, const char* chosenFile) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkFileChooserRequest, request, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(chosenFile, false); - EINA_SAFETY_ON_TRUE_RETURN_VAL(impl->wasHandled(), false); - - String fileURL = ASCIILiteral("file://") + String::fromUTF8(chosenFile); - WKRetainPtr<WKURLRef> wkURL(AdoptWK, toCopiedURLAPI(fileURL)); - - 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.h b/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.h deleted file mode 100644 index d7c2d12b4..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.h +++ /dev/null @@ -1,110 +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_file_chooser_request.h - * @brief Describes the Ewk File Chooser API. - */ - -#ifndef ewk_file_chooser_request_h -#define ewk_file_chooser_request_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_File_Chooser_Request as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_File_Chooser_Request; - -/** - * Queries if it is allowed to select multiple files or not. - * - * @param request request object to query - * - * @return @c EINA_TRUE if it is allowed to select multiple files, - * @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_file_chooser_request_allow_multiple_files_get(const Ewk_File_Chooser_Request *request); - -/** - * Queries the list of accepted MIME types. - * - * Possible MIME types are: - * - "audio\/\*": All sound files are accepted - * - "video\/\*": All video files are accepted - * - "image\/\*": All image files are accepted - * - standard IANA MIME type (see http://www.iana.org/assignments/media-types/ for a complete list) - * - * @param request request object to query - * - * @return The list of accepted MIME types. The list items are guaranteed to be stringshared. - * The caller needs to free the list and its items after use - */ -EAPI Eina_List *ewk_file_chooser_request_accepted_mimetypes_get(const Ewk_File_Chooser_Request *request); - -/** - * Cancels the file chooser request. - * - * @param request request object to cancel - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_file_chooser_request_cancel(Ewk_File_Chooser_Request *request); - -/** - * Sets the files chosen by the user. - * - * @param request request object to update - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise - * - * @see ewk_file_chooser_request_file_choose() - */ -EAPI Eina_Bool ewk_file_chooser_request_files_choose(Ewk_File_Chooser_Request *request, const Eina_List *chosen_files); - -/** - * Sets the file chosen by the user. - * - * This is a convenience function in case only one file needs to be set. - * - * @param request request object to update - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise - * - * @see ewk_file_chooser_request_files_choose() - */ -EAPI Eina_Bool ewk_file_chooser_request_file_choose(Ewk_File_Chooser_Request *request, const char *chosen_file); - -#ifdef __cplusplus -} -#endif - -#endif /* ewk_file_chooser_request_h */ 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 deleted file mode 100644 index 688a39176..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request_private.h +++ /dev/null @@ -1,60 +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_file_chooser_request_private_h -#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> - -class EwkFileChooserRequest : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkFileChooserRequest) - - static PassRefPtr<EwkFileChooserRequest> create(WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener) - { - return adoptRef(new EwkFileChooserRequest(parameters, listener)); - } - - ~EwkFileChooserRequest(); - - bool allowMultipleFiles() const; - WKRetainPtr<WKArrayRef> acceptedMIMETypes() const; - inline bool wasHandled() const { return m_wasRequestHandled; } - void cancel(); - void chooseFiles(WKArrayRef fileURLs); - -private: - EwkFileChooserRequest(WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener); - - WKRetainPtr<WKOpenPanelParametersRef> m_parameters; - WKRetainPtr<WKOpenPanelResultListenerRef> m_listener; - bool m_wasRequestHandled; -}; - -#endif // ewk_file_chooser_request_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp deleted file mode 100644 index 60798eb43..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.cpp +++ /dev/null @@ -1,101 +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_form_submission_request.h" - -#include "WKAPICast.h" -#include "WKArray.h" -#include "WKBase.h" -#include "WKString.h" -#include "ewk_form_submission_request_private.h" - -using namespace WebKit; - -EwkFormSubmissionRequest::EwkFormSubmissionRequest(WKDictionaryRef values, WKFormSubmissionListenerRef listener) - : m_wkValues(values) - , m_wkListener(listener) - , m_handledRequest(false) -{ } - -EwkFormSubmissionRequest::~EwkFormSubmissionRequest() -{ - // Make sure the request is always handled before destroying. - if (!m_handledRequest) - WKFormSubmissionListenerContinue(m_wkListener.get()); -} - -Eina_Stringshare* EwkFormSubmissionRequest::copyFieldValue(const char* fieldName) const -{ - ASSERT(fieldName); - WKRetainPtr<WKStringRef> wkFieldName = adoptWK(WKStringCreateWithUTF8CString(fieldName)); - WKStringRef wkValue = static_cast<WKStringRef>(WKDictionaryGetItemForKey(m_wkValues.get(), wkFieldName.get())); - - return WKEinaSharedString(wkValue).leakString(); -} - -WKRetainPtr<WKArrayRef> EwkFormSubmissionRequest::fieldNames() const -{ - return adoptWK(WKDictionaryCopyKeys(m_wkValues.get())); -} - -void EwkFormSubmissionRequest::submit() -{ - WKFormSubmissionListenerContinue(m_wkListener.get()); - m_handledRequest = true; -} - -Eina_List* ewk_form_submission_request_field_names_get(Ewk_Form_Submission_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkFormSubmissionRequest, request, impl, 0); - - Eina_List* fieldNames = 0; - - WKRetainPtr<WKArrayRef> wkFieldNames = impl->fieldNames(); - const size_t numKeys = WKArrayGetSize(wkFieldNames.get()); - for (size_t i = 0; i < numKeys; ++i) { - WKStringRef wkFieldName = static_cast<WKStringRef>(WKArrayGetItemAtIndex(wkFieldNames.get(), i)); - fieldNames = eina_list_append(fieldNames, WKEinaSharedString(wkFieldName).leakString()); - } - - return fieldNames; -} - -const char* ewk_form_submission_request_field_value_get(Ewk_Form_Submission_Request* request, const char* name) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkFormSubmissionRequest, request, impl, 0); - EINA_SAFETY_ON_NULL_RETURN_VAL(name, 0); - - return impl->copyFieldValue(name); -} - -Eina_Bool ewk_form_submission_request_submit(Ewk_Form_Submission_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkFormSubmissionRequest, request, impl, false); - - impl->submit(); - - return true; -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.h b/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.h deleted file mode 100644 index 58c001f8e..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request.h +++ /dev/null @@ -1,93 +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_form_submission_request.h - * @brief Describes the Ewk Form Submission Request API. - * - * @note Ewk_Form_Submission_Request provides information regarding - * a form about the be submitted, in particular its text fields. - */ - -#ifndef ewk_form_submission_request_h -#define ewk_form_submission_request_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Form_Submission_Request as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Form_Submission_Request; - -/** - * Returns the list of field names contained in the form associated to @a request. - * - * @param request the request object to query. - * - * @return a #Eina_List with the form text fields names, or @c NULL in case of error. - * The items of the list are guaranteed to be stringshared so use eina_stringshare_add() - * instead of strdup() to copy them and free them using eina_stringshare_del(). - * - * @see ewk_form_submission_request_field_value_get() - */ -EAPI Eina_List *ewk_form_submission_request_field_names_get(Ewk_Form_Submission_Request *request); - -/** - * Returns the value of specific field contained in the form associated to @a request. - * - * @param request the request object to query. - * @param name name of the field to query the value for. - * - * @return a #Eina_List with the form text fields names, or @c NULL in case of error. - * The string returned is guaranteed to be stringshared. You need to call - * eina_stringshare_del() on the returned value once you are done with it. - * - * @see ewk_form_submission_request_field_names_get() - */ -EAPI const char *ewk_form_submission_request_field_value_get(Ewk_Form_Submission_Request *request, const char *name); - -/** - * Continues the form request submission. - * - * If you don't call this function explicitly, the form request will be submitted - * upon @a request object destruction. - * - * @param request the request object to submit. - * - * @return @c EINA_TRUE is if successful, @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_form_submission_request_submit(Ewk_Form_Submission_Request *request); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_form_submission_request_h 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 deleted file mode 100644 index b2b8073aa..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_form_submission_request_private.h +++ /dev/null @@ -1,60 +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_form_submission_request_private_h -#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> - -class EwkFormSubmissionRequest : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkFormSubmissionRequest) - - ~EwkFormSubmissionRequest(); - - static PassRefPtr<EwkFormSubmissionRequest> create(WKDictionaryRef values, WKFormSubmissionListenerRef listener) - { - return adoptRef(new EwkFormSubmissionRequest(values, listener)); - } - - WKRetainPtr<WKArrayRef> fieldNames() const; - Eina_Stringshare* copyFieldValue(const char* fieldName) const; - - void submit(); - -private: - EwkFormSubmissionRequest(WKDictionaryRef values, WKFormSubmissionListenerRef listener); - - WKRetainPtr<WKDictionaryRef> m_wkValues; - WKRetainPtr<WKFormSubmissionListenerRef> m_wkListener; - bool m_handledRequest; -}; - -#endif // ewk_form_submission_request_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp deleted file mode 100644 index 7c1925cb8..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_main.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* - Copyright (C) 2009-2010 ProFUSION embedded systems - Copyright (C) 2009-2011 Samsung Electronics - Copyright (C) 2012 Intel Corporation - - 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 "ewk_main.h" - -#include "ewk_private.h" -#include <Ecore.h> -#include <Ecore_Evas.h> -#include <Ecore_IMF.h> -#include <Edje.h> -#include <Eina.h> -#include <Evas.h> -#include <glib-object.h> -#include <glib.h> - -#ifdef HAVE_ECORE_X -#include <Ecore_X.h> -#endif - -static int _ewkInitCount = 0; - -/** - * \var _ewk_log_dom - * @brief the log domain identifier that is used with EINA's macros - */ -int _ewk_log_dom = -1; - -int ewk_init(void) -{ - if (_ewkInitCount) - return ++_ewkInitCount; - - if (!eina_init()) - goto error_eina; - - _ewk_log_dom = eina_log_domain_register("ewebkit2", EINA_COLOR_ORANGE); - if (_ewk_log_dom < 0) { - EINA_LOG_CRIT("could not register log domain 'ewebkit2'"); - goto error_log_domain; - } - - if (!evas_init()) { - CRITICAL("could not init evas."); - goto error_evas; - } - - if (!ecore_init()) { - CRITICAL("could not init ecore."); - goto error_ecore; - } - - if (!ecore_evas_init()) { - CRITICAL("could not init ecore_evas."); - goto error_ecore_evas; - } - - if (!ecore_imf_init()) { - CRITICAL("could not init ecore_imf."); - goto error_ecore_imf; - } - -#ifdef HAVE_ECORE_X - if (!ecore_x_init(0)) { - CRITICAL("could not init ecore_x."); - goto error_ecore_x; - } -#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 " - "work (ie: Adobe Flash)"); - } - - return ++_ewkInitCount; - -error_edje: -#ifdef HAVE_ECORE_X - ecore_x_shutdown(); -error_ecore_x: -#else - ecore_imf_shutdown(); -#endif -error_ecore_imf: - ecore_evas_shutdown(); -error_ecore_evas: - ecore_shutdown(); -error_ecore: - evas_shutdown(); -error_evas: - eina_log_domain_unregister(_ewk_log_dom); - _ewk_log_dom = -1; -error_log_domain: - eina_shutdown(); -error_eina: - return 0; -} - -int ewk_shutdown(void) -{ - if (--_ewkInitCount) - return _ewkInitCount; - - edje_shutdown(); -#ifdef HAVE_ECORE_X - ecore_x_shutdown(); -#endif - ecore_imf_shutdown(); - ecore_evas_shutdown(); - ecore_shutdown(); - evas_shutdown(); - eina_log_domain_unregister(_ewk_log_dom); - _ewk_log_dom = -1; - eina_shutdown(); - - return 0; -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_main.h b/Source/WebKit2/UIProcess/API/efl/ewk_main.h deleted file mode 100644 index 28e93fe23..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_main.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - Copyright (C) 2009-2010 ProFUSION embedded systems - Copyright (C) 2009-2010 Samsung Electronics - Copyright (C) 2012 Intel Corporation - - 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. -*/ - -/** - * @file ewk_main.h - * @brief The general initialization of WebKit2-EFL, not tied to any view object. - */ - -#ifndef ewk_main_h -#define ewk_main_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Initializes WebKit's instance. - * - * - initializes components needed by EFL, - * - increases a reference count of WebKit's instance. - * - * @return a reference count of WebKit's instance on success or 0 on failure - */ -EAPI int ewk_init(void); - -/** - * Decreases a reference count of WebKit's instance, possibly destroying it. - * - * If the reference count reaches 0 WebKit's instance is destroyed. - * - * @return a reference count of WebKit's instance - */ -EAPI int ewk_shutdown(void); - -#ifdef __cplusplus -} -#endif -#endif // ewk_main_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data.h b/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data.h deleted file mode 100644 index 7f62641e7..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data.h +++ /dev/null @@ -1,91 +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_navigation_data.h - * @brief Describes the Ewk navigation data API. - */ - -#ifndef ewk_navigation_data_h -#define ewk_navigation_data_h - -#include "ewk_url_request.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Navigation_Data as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Navigation_Data; - -/** - * Returns title for this navigation data. - * - * The title of the navigated page. - * - * @param data navigation data object to query - * - * @return the title or @c NULL in case of error. 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_navigation_data_title_get(const Ewk_Navigation_Data *data); - -/** - * Returns the original request for this navigation data. - * - * @param data navigation data object to query - * - * @return The URL request pointer or @c NULL in case of error. - */ -EAPI Ewk_Url_Request *ewk_navigation_data_original_request_get(const Ewk_Navigation_Data *data); - -/** - * Returns URL for this navigation data. - * - * The URL of the navigated page. - * - * @param data navigation data object to query - * - * @return the URL of the @a data or @c NULL in case of error. 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_navigation_data_url_get(const Ewk_Navigation_Data *data); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_navigation_data_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data_private.h deleted file mode 100644 index 5ba5a5cb8..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_data_private.h +++ /dev/null @@ -1,63 +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_navigation_data_private_h -#define ewk_navigation_data_private_h - -#include "WKAPICast.h" -#include "WKEinaSharedString.h" -#include "WKNavigationData.h" -#include "WKRetainPtr.h" -#include "ewk_private.h" -#include "ewk_url_request_private.h" -#include <wtf/PassRefPtr.h> - -/** - * \struct EwkNavigationData - * @brief Contains the navigation data details. - */ -class EwkNavigationData : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkNavigationData) - - static PassRefPtr<EwkNavigationData> create(WKNavigationDataRef dataRef) - { - return adoptRef(new EwkNavigationData(dataRef)); - } - - EwkUrlRequest* originalRequest() const; - - const char* title() const; - const char* url() const; - -private: - explicit EwkNavigationData(WKNavigationDataRef dataRef); - - RefPtr<EwkUrlRequest> m_request; - WKEinaSharedString m_title; - WKEinaSharedString m_url; -}; - -#endif // ewk_navigation_data_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision.cpp deleted file mode 100644 index b01d597dd..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision.cpp +++ /dev/null @@ -1,169 +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_navigation_policy_decision.h" - -#include "ewk_navigation_policy_decision_private.h" -#include "ewk_private.h" -#include "ewk_url_request_private.h" - -using namespace WebKit; - -EwkNavigationPolicyDecision::EwkNavigationPolicyDecision(WKFramePolicyListenerRef listener, Ewk_Navigation_Type navigationType, Event_Mouse_Button mouseButton, Event_Modifier_Keys modifiers, PassRefPtr<EwkUrlRequest> request, const char* frameName) - : m_listener(listener) - , m_actedUponByClient(false) - , m_navigationType(navigationType) - , m_mouseButton(mouseButton) - , m_modifiers(modifiers) - , m_request(request) - , m_frameName(frameName) -{ } - -EwkNavigationPolicyDecision::~EwkNavigationPolicyDecision() -{ - // This is the default choice for all policy decisions in WebPageProxy.cpp. - if (!m_actedUponByClient) - WKFramePolicyListenerUse(m_listener.get()); -} - -Ewk_Navigation_Type EwkNavigationPolicyDecision::navigationType() const -{ - return m_navigationType; -} - -Event_Mouse_Button EwkNavigationPolicyDecision::mouseButton() const -{ - return m_mouseButton; -} - -Event_Modifier_Keys EwkNavigationPolicyDecision::modifiers() const -{ - return m_modifiers; -} - -const char* EwkNavigationPolicyDecision::frameName() const -{ - return m_frameName; -} - -EwkUrlRequest* EwkNavigationPolicyDecision::request() const -{ - return m_request.get(); -} - -void EwkNavigationPolicyDecision::accept() -{ - WKFramePolicyListenerUse(m_listener.get()); - m_actedUponByClient = true; -} - -void EwkNavigationPolicyDecision::reject() -{ - WKFramePolicyListenerIgnore(m_listener.get()); - m_actedUponByClient = true; -} - -void EwkNavigationPolicyDecision::download() -{ - WKFramePolicyListenerDownload(m_listener.get()); - m_actedUponByClient = true; -} - -Ewk_Navigation_Type ewk_navigation_policy_navigation_type_get(const Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationPolicyDecision, decision, impl, EWK_NAVIGATION_TYPE_OTHER); - - return impl->navigationType(); -} - -Event_Mouse_Button ewk_navigation_policy_mouse_button_get(const Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationPolicyDecision, decision, impl, EVENT_MOUSE_BUTTON_NONE); - - return impl->mouseButton(); -} - -Event_Modifier_Keys ewk_navigation_policy_modifiers_get(const Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationPolicyDecision, decision, impl, static_cast<Event_Modifier_Keys>(0)); - - return impl->modifiers(); -} - -const char* ewk_navigation_policy_frame_name_get(const Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationPolicyDecision, decision, impl, 0); - - return impl->frameName(); -} - -Ewk_Url_Request* ewk_navigation_policy_request_get(const Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkNavigationPolicyDecision, decision, impl, 0); - - return impl->request(); -} - -void ewk_navigation_policy_decision_accept(Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkNavigationPolicyDecision, decision, impl); - - impl->accept(); -} - -void ewk_navigation_policy_decision_reject(Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkNavigationPolicyDecision, decision, impl); - - impl->reject(); -} - -void ewk_navigation_policy_decision_download(Ewk_Navigation_Policy_Decision* decision) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkNavigationPolicyDecision, decision, impl); - - impl->download(); -} - -// Ewk_Navigation_Type enum validation -COMPILE_ASSERT_MATCHING_ENUM(EWK_NAVIGATION_TYPE_LINK_ACTIVATED, kWKFrameNavigationTypeLinkClicked); -COMPILE_ASSERT_MATCHING_ENUM(EWK_NAVIGATION_TYPE_FORM_SUBMITTED, kWKFrameNavigationTypeFormSubmitted); -COMPILE_ASSERT_MATCHING_ENUM(EWK_NAVIGATION_TYPE_BACK_FORWARD, kWKFrameNavigationTypeBackForward); -COMPILE_ASSERT_MATCHING_ENUM(EWK_NAVIGATION_TYPE_RELOAD, kWKFrameNavigationTypeReload); -COMPILE_ASSERT_MATCHING_ENUM(EWK_NAVIGATION_TYPE_FORM_RESUBMITTED, kWKFrameNavigationTypeFormResubmitted); -COMPILE_ASSERT_MATCHING_ENUM(EWK_NAVIGATION_TYPE_OTHER, kWKFrameNavigationTypeOther); - -// Event_Mouse_Button enum validation -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MOUSE_BUTTON_NONE, kWKEventMouseButtonNoButton); -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MOUSE_BUTTON_LEFT, kWKEventMouseButtonLeftButton); -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MOUSE_BUTTON_MIDDLE, kWKEventMouseButtonMiddleButton); -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MOUSE_BUTTON_RIGHT, kWKEventMouseButtonRightButton); - -// Event_Modifier_Keys validation -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MODIFIER_KEY_SHIFT, kWKEventModifiersShiftKey); -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MODIFIER_KEY_CTRL, kWKEventModifiersControlKey); -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MODIFIER_KEY_ALT, kWKEventModifiersAltKey); -COMPILE_ASSERT_MATCHING_ENUM(EVENT_MODIFIER_KEY_META, kWKEventModifiersMetaKey); diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision.h b/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision.h deleted file mode 100644 index a9fbbefe5..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision.h +++ /dev/null @@ -1,151 +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_navigation_policy_decision.h - * @brief Describes the Ewk navigation policy decision API. - */ - -#ifndef ewk_navigation_policy_decision_h -#define ewk_navigation_policy_decision_h - -#include "ewk_url_request.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Navigation_Policy_Decision as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Navigation_Policy_Decision; - -/// Enum containing navigation types -typedef enum { - EWK_NAVIGATION_TYPE_LINK_ACTIVATED, - EWK_NAVIGATION_TYPE_FORM_SUBMITTED, - EWK_NAVIGATION_TYPE_BACK_FORWARD, - EWK_NAVIGATION_TYPE_RELOAD, - EWK_NAVIGATION_TYPE_FORM_RESUBMITTED, - EWK_NAVIGATION_TYPE_OTHER -} Ewk_Navigation_Type; - -/// Enum containing button types -typedef enum { - EVENT_MOUSE_BUTTON_NONE = -1, - EVENT_MOUSE_BUTTON_LEFT = 0, - EVENT_MOUSE_BUTTON_MIDDLE = 1, - EVENT_MOUSE_BUTTON_RIGHT = 2 -} Event_Mouse_Button; - -typedef enum { - EVENT_MODIFIER_KEY_SHIFT = 1 << 0, - EVENT_MODIFIER_KEY_CTRL = 1 << 1, - EVENT_MODIFIER_KEY_ALT = 1 << 2, - EVENT_MODIFIER_KEY_META = 1 << 3 -} Event_Modifier_Keys; - -/** - * Query type for this navigation policy decision. - * - * @param decision navigation policy decision object to query. - * - * @return the type of navigation. - */ -EAPI Ewk_Navigation_Type ewk_navigation_policy_navigation_type_get(const Ewk_Navigation_Policy_Decision *decision); - -/** - * Query mouse button for this navigation policy decision. - * - * @param decision navigation policy decision object to query. - * - * @return the mouse button clicked to trigger the navigation. - */ -EAPI Event_Mouse_Button ewk_navigation_policy_mouse_button_get(const Ewk_Navigation_Policy_Decision *decision); - -/** - * Query modifier keys for this navigation policy decision. - * - * @param decision navigation policy decision object to query. - * - * @return the modifier keys used when triggering the navigation. - */ -EAPI Event_Modifier_Keys ewk_navigation_policy_modifiers_get(const Ewk_Navigation_Policy_Decision *decision); - -/** - * Query frame name for this navigation policy decision. - * - * The frame name is non-null for new window policy decisions only. - * - * @param decision navigation policy decision object to query. - * - * @return the frame name 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_navigation_policy_frame_name_get(const Ewk_Navigation_Policy_Decision *decision); - -/** - * Query URL request for this navigation policy decision. - * - * @param decision navigation policy decision object to query. - * - * @return The URL request pointer or @c NULL in case of error. - */ -EAPI Ewk_Url_Request *ewk_navigation_policy_request_get(const Ewk_Navigation_Policy_Decision *decision); - -/** - * Accepts the navigation request. - * - * The navigation will be accepted by default. - * - * @param decision navigation policy decision object to query. - */ -EAPI void ewk_navigation_policy_decision_accept(Ewk_Navigation_Policy_Decision *decision); - -/** - * Rejects the navigation request. - * - * @param decision navigation policy decision object to query. - */ -EAPI void ewk_navigation_policy_decision_reject(Ewk_Navigation_Policy_Decision *decision); - -/** - * Triggers a download instead of navigating to the url. - * - * @param decision navigation policy decision object to query. - */ -EAPI void ewk_navigation_policy_decision_download(Ewk_Navigation_Policy_Decision *decision); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_navigation_policy_decision_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision_private.h deleted file mode 100644 index 714dbccbe..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_navigation_policy_decision_private.h +++ /dev/null @@ -1,76 +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_navigation_policy_decision_private_h -#define ewk_navigation_policy_decision_private_h - -#include "WKAPICast.h" -#include "WKBase.h" -#include "WKEinaSharedString.h" -#include "WKEvent.h" -#include "WKFramePolicyListener.h" -#include "WKPageLoadTypes.h" -#include "WKRetainPtr.h" -#include "ewk_url_request_private.h" -#include <wtf/PassRefPtr.h> - -/** - * \struct EwkNavigationPolicyDecision - * @brief Contains the navigation policy decision data. - */ -class EwkNavigationPolicyDecision : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkNavigationPolicyDecision) - - ~EwkNavigationPolicyDecision(); - - static PassRefPtr<EwkNavigationPolicyDecision> create(WKFrameNavigationType navigationType, WKEventMouseButton mouseButton, WKEventModifiers modifiers, WKURLRequestRef requestRef, const char* frameName, WKFramePolicyListenerRef listener) - { - return adoptRef(new EwkNavigationPolicyDecision(listener, static_cast<Ewk_Navigation_Type>(navigationType), static_cast<Event_Mouse_Button>(mouseButton), static_cast<Event_Modifier_Keys>(modifiers), EwkUrlRequest::create(requestRef), frameName)); - } - - void accept(); - void reject(); - void download(); - - Ewk_Navigation_Type navigationType() const; - Event_Mouse_Button mouseButton() const; - Event_Modifier_Keys modifiers() const; - const char* frameName() const; - EwkUrlRequest* request() const; - -private: - EwkNavigationPolicyDecision(WKFramePolicyListenerRef listener, Ewk_Navigation_Type navigationType, Event_Mouse_Button mouseButton, Event_Modifier_Keys modifiers, PassRefPtr<EwkUrlRequest> request, const char* frameName); - - WKRetainPtr<WKFramePolicyListenerRef> m_listener; - bool m_actedUponByClient; - Ewk_Navigation_Type m_navigationType; - Event_Mouse_Button m_mouseButton; - Event_Modifier_Keys m_modifiers; - RefPtr<EwkUrlRequest> m_request; - WKEinaSharedString m_frameName; -}; - -#endif // ewk_navigation_policy_decision_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_object.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_object.cpp deleted file mode 100644 index f25d668d2..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_object.cpp +++ /dev/null @@ -1,44 +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 item of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this item 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_object.h" - -#include "ewk_object_private.h" - -Ewk_Object* ewk_object_ref(Ewk_Object* object) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(object, 0); - object->ref(); - - return object; -} - -void ewk_object_unref(Ewk_Object* object) -{ - EINA_SAFETY_ON_NULL_RETURN(object); - - object->deref(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_object_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_object_private.h deleted file mode 100644 index b67f33820..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_object_private.h +++ /dev/null @@ -1,87 +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_object_private_h -#define ewk_object_private_h - -#include <wtf/RefCounted.h> - -class EwkObject : public RefCounted<EwkObject> { -public: - virtual ~EwkObject() { } - virtual const char* instanceClassName() const = 0; -}; - -template <class T> -inline bool ewk_object_is_of_type(const EwkObject* object) -{ - return (reinterpret_cast<T>(0)->className() == object->instanceClassName()); -} - -template <class T> -inline bool ewk_object_cast_check(const EwkObject* object) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(object, false); - - if (!ewk_object_is_of_type<T>(object)) { - EINA_LOG_CRIT("attempt to convert object of type %s to type %s", - object->instanceClassName(), reinterpret_cast<T>(0)->className()); - ASSERT_NOT_REACHED(); - return false; - } - - return true; -} - -template <class T> -inline const T ewk_object_cast(const EwkObject* object) -{ - return ewk_object_cast_check<T>(object) ? static_cast<T>(object) : 0; -} - -template <class T> -inline T ewk_object_cast(EwkObject* object) -{ - return ewk_object_cast_check<T>(object) ? static_cast<T>(object) : 0; -} - -#define EWK_OBJ_GET_IMPL_OR_RETURN(ImplClass, object, impl, ...) \ - ImplClass* impl = ewk_object_cast<ImplClass*>(object); \ - if (!impl) \ - return __VA_ARGS__ - - -#define EWK_OBJECT_DECLARE(_className) \ -static const char* className() \ -{ \ - static const char* name = #_className; \ - return name; \ -} \ -virtual const char* instanceClassName() const \ -{ \ - return className(); \ -} - -#endif // ewk_object_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_page_group.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_page_group.cpp deleted file mode 100644 index 84cd5678c..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_page_group.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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 deleted file mode 100644 index 615edb039..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_page_group.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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_page_group_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_page_group_private.h deleted file mode 100644 index 3f922017d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_page_group_private.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_page_group_private_h -#define ewk_page_group_private_h - -#include "ewk_object_private.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 EwkView; - -class EwkPageGroup : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkPageGroup) - - static PassRefPtr<EwkPageGroup> findOrCreateWrapper(WKPageGroupRef pageGroupRef); - static PassRefPtr<EwkPageGroup> create(const String& identifier = String()); - - ~EwkPageGroup(); - - WKPageGroupRef wkPageGroup() const { return m_pageGroupRef.get(); } - - void addUserStyleSheet(const String& source, const String& baseURL, Eina_List* whitelist, Eina_List* blacklist, bool mainFrameOnly); - void removeAllUserStyleSheets(); - -private: - explicit EwkPageGroup(WKPageGroupRef pageGroupRef); - - static const char defaultIdentifier[]; - - WKRetainPtr<WKPageGroupRef> m_pageGroupRef; -}; - -#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 deleted file mode 100644 index 1c8c33af1..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_popup_menu.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" - -EwkPopupMenu::EwkPopupMenu(EwkView* view, WKPopupMenuListenerRef popupMenuListener, WKArrayRef items, unsigned selectedIndex) - : m_view(view) - , m_popupMenuListener(popupMenuListener) - , m_popupMenuItems(0) - , m_selectedIndex(selectedIndex) -{ - 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<EwkPopupMenuItem*>(item); -} - -void EwkPopupMenu::close() -{ - // Setting selected item will cause the popup menu to close. - WKPopupMenuListenerSetSelection(m_popupMenuListener.get(), m_selectedIndex); -} - -const Eina_List* EwkPopupMenu::items() const -{ - return m_popupMenuItems; -} - -unsigned EwkPopupMenu::selectedIndex() const -{ - return m_selectedIndex; -} - -bool EwkPopupMenu::setSelectedIndex(unsigned selectedIndex) -{ - if (!m_popupMenuListener) - return false; - - if (selectedIndex >= eina_list_count(m_popupMenuItems)) - return false; - - if (m_selectedIndex == selectedIndex) - return true; - - m_selectedIndex = selectedIndex; - WKPopupMenuListenerSetSelection(m_popupMenuListener.get(), selectedIndex); - - return true; -} - -Eina_Bool ewk_popup_menu_close(Ewk_Popup_Menu* popupMenu) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(popupMenu, false); - - popupMenu->close(); - - return true; -} - -Eina_Bool ewk_popup_menu_selected_index_set(Ewk_Popup_Menu* popupMenu, unsigned selectedIndex) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(popupMenu, false); - - return popupMenu->setSelectedIndex(selectedIndex); -} - -unsigned ewk_popup_menu_selected_index_get(const Ewk_Popup_Menu* popupMenu) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(popupMenu, 0); - - return popupMenu->selectedIndex(); -} - -const Eina_List* ewk_popup_menu_items_get(const Ewk_Popup_Menu* popupMenu) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(popupMenu, 0); - - return popupMenu->items(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.h b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.h deleted file mode 100644 index 0ad0f5fcc..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_popup_menu.h - * @brief Describes the Ewk Popup Menu API. - */ - -#ifndef ewk_popup_menu_h -#define ewk_popup_menu_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for Ewk_Popup_Menu */ -typedef struct EwkPopupMenu Ewk_Popup_Menu; - -/** - * Selects index of current popup menu. - * - * @param popup_menu popup menu object - * @param index index of item to select - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure (e.g. the index is out of range) - */ -EAPI Eina_Bool ewk_popup_menu_selected_index_set(Ewk_Popup_Menu *popup_menu, unsigned index); - -/** - * Returns the index of the currently selected item in the popup menu. - * - * @param popup_menu popup menu object - * - * @return index of the currently selected popup item on success, @c 0 otherwise - */ -EAPI unsigned ewk_popup_menu_selected_index_get(const Ewk_Popup_Menu *popup_menu); - -/** - * Closes current popup menu. - * - * The Ewk_Popup_Menu object becomes invalid after calling this function. - * - * @param popup_menu popup menu object - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_popup_menu_close(Ewk_Popup_Menu *popup_menu); - -/** - * Retrieve the popup menu items - * - * @param popup_menu popup menu object - * - * @return @c list of popup menu items on success, @c NULL otherwise - */ -EAPI const Eina_List *ewk_popup_menu_items_get(const Ewk_Popup_Menu *popup_menu); - -#ifdef __cplusplus -} -#endif - -#endif /* ewk_popup_menu_h */ diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp deleted file mode 100644 index 9c428341d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_popup_menu_item.h" - -#include "WKPopupItem.h" -#include "ewk_popup_menu_item_private.h" -#include "ewk_private.h" - -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 static_cast<Ewk_Popup_Menu_Item_Type>(WKPopupItemGetType(m_wkItem.get())); -} - -Ewk_Text_Direction EwkPopupMenuItem::textDirection() const -{ - 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 WKPopupItemHasTextDirectionOverride(m_wkItem.get()); -} - -bool EwkPopupMenuItem::isEnabled() const -{ - return WKPopupItemIsEnabled(m_wkItem.get()); -} - -bool EwkPopupMenuItem::isLabel() const -{ - return WKPopupItemIsLabel(m_wkItem.get()); -} - -bool EwkPopupMenuItem::isSelected() const -{ - return WKPopupItemIsSelected(m_wkItem.get()); -} - -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); - - return item->type(); -} - -const char* ewk_popup_menu_item_text_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, 0); - - return item->text(); -} - -Ewk_Text_Direction ewk_popup_menu_item_text_direction_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, EWK_TEXT_DIRECTION_LEFT_TO_RIGHT); - - return item->textDirection(); -} - -Eina_Bool ewk_popup_menu_item_text_direction_override_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - return item->hasTextDirectionOverride(); -} - -const char* ewk_popup_menu_item_tooltip_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, 0); - - return item->tooltipText(); -} - -const char* ewk_popup_menu_item_accessibility_text_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, 0); - - return item->accessibilityText(); -} - -Eina_Bool ewk_popup_menu_item_enabled_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - return item->isEnabled(); -} - -Eina_Bool ewk_popup_menu_item_is_label_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - return item->isLabel(); -} - -Eina_Bool ewk_popup_menu_item_selected_get(const Ewk_Popup_Menu_Item* item) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(item, false); - - return item->isSelected(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.h b/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.h deleted file mode 100644 index 1a2eacd0c..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_popup_menu_item.h - * @brief Describes the Ewk Popup Menu Item API. - */ - -#ifndef ewk_popup_menu_item_h -#define ewk_popup_menu_item_h - -#include "ewk_view.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Enum values containing type of popup menu item. */ -typedef enum { - EWK_POPUP_MENU_SEPARATOR, - EWK_POPUP_MENU_ITEM, - EWK_POPUP_MENU_UNKNOWN = -1 -} Ewk_Popup_Menu_Item_Type; - -/** Creates a type name for Ewk_Popup_Menu_Item */ -typedef struct EwkPopupMenuItem Ewk_Popup_Menu_Item; - -/** - * Returns type of the popup menu item. - * - * @param item the popup menu item instance - * - * @return the type of the @a item or @c EWK_POPUP_MENU_UNKNOWN in case of error. - */ -EAPI Ewk_Popup_Menu_Item_Type ewk_popup_menu_item_type_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns text of the popup menu item. - * - * @param item the popup menu item instance - * - * @return the text of the @a item or @c NULL in case of error. 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_popup_menu_item_text_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns text direction of the popup menu item. - * - * @param item the popup menu item instance - * - * @return the text direction of the @a item. - */ -EAPI Ewk_Text_Direction ewk_popup_menu_item_text_direction_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns whether the popup menu item has text direction override. - * - * @param item the popup menu item instance - * - * @return @c EINA_TRUE if the popup menu item has text direction override, - * @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_popup_menu_item_text_direction_override_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns tooltip of the popup menu item. - * - * @param item the popup menu item instance - * - * @return the tooltip of the @a item or @c NULL in case of error. 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_popup_menu_item_tooltip_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns accessibility text of the popup menu item. - * - * @param item the popup menu item instance - * - * @return the accessibility text of the @a item or @c NULL in case of error. - * 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_popup_menu_item_accessibility_text_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns whether the popup menu item is enabled or not. - * - * @param item the popup menu item instance - * - * @return @c EINA_TRUE if ther popup menu item is enabled, @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_popup_menu_item_enabled_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns whether the popup menu item is label or not. - * - * @param item the popup menu item instance - * - * @return @c EINA_TRUE if the popup menu item is label, @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_popup_menu_item_is_label_get(const Ewk_Popup_Menu_Item *item); - -/** - * Returns whether the popup menu item is selected or not. - * - * @param item the popup menu item instance - * - * @return @c EINA_TRUE if the popup menu item is selected, @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_popup_menu_item_selected_get(const Ewk_Popup_Menu_Item *item); - -#ifdef __cplusplus -} -#endif -#endif // ewk_popup_menu_item_h 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 deleted file mode 100644 index d8d2b8cce..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_item_private.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_popup_menu_item_private_h -#define ewk_popup_menu_item_private_h - -#include "WKEinaSharedString.h" -#include "WKRetainPtr.h" -#include "ewk_popup_menu_item.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -/** - * \struct Ewk_Popup_Menu_Item - * @brief Contains the popup menu data. - */ -class EwkPopupMenuItem { -public: - static PassOwnPtr<EwkPopupMenuItem> create(WKPopupItemRef item) - { - return adoptPtr(new EwkPopupMenuItem(item)); - } - - Ewk_Popup_Menu_Item_Type type() const; - Ewk_Text_Direction textDirection() const; - - bool hasTextDirectionOverride() const; - bool isEnabled() const; - bool isLabel() const; - bool isSelected() const; - - const char* text() const; - const char* tooltipText() const; - const char* accessibilityText() const; - -private: - explicit EwkPopupMenuItem(WKPopupItemRef item); - - WKRetainPtr<WKPopupItemRef> m_wkItem; - - // 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 deleted file mode 100644 index 5cd2e3aaf..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_popup_menu_private.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_popup_menu_private_h -#define ewk_popup_menu_private_h - -#include <Eina.h> -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -class EwkPopupMenu { -public: - static PassOwnPtr<EwkPopupMenu> create(EwkView* view, WKPopupMenuListenerRef popupMenuListener, WKArrayRef items, unsigned selectedIndex) - { - return adoptPtr(new EwkPopupMenu(view, popupMenuListener, items, selectedIndex)); - } - ~EwkPopupMenu(); - - void close(); - - const Eina_List* items() const; - - bool setSelectedIndex(unsigned selectedIndex); - unsigned selectedIndex() const; - -private: - EwkPopupMenu(EwkView* viewImpl, WKPopupMenuListenerRef, WKArrayRef items, unsigned selectedIndex); - - EwkView* m_view; - WKRetainPtr<WKPopupMenuListenerRef> m_popupMenuListener; - Eina_List* m_popupMenuItems; - unsigned m_selectedIndex; -}; - -#endif // ewk_popup_menu_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_private.h deleted file mode 100644 index 4bdb25b68..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_private.h +++ /dev/null @@ -1,42 +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_private_h -#define ewk_private_h - -#include <wtf/Assertions.h> - -#define COMPILE_ASSERT_MATCHING_ENUM(ewkName, webcoreName) \ - COMPILE_ASSERT(int(ewkName) == int(webcoreName), mismatchingEnums) - -extern int _ewk_log_dom; - -#define CRITICAL(...) EINA_LOG_DOM_CRIT(_ewk_log_dom, __VA_ARGS__) -#define ERR(...) EINA_LOG_DOM_ERR(_ewk_log_dom, __VA_ARGS__) -#define WARN(...) EINA_LOG_DOM_WARN(_ewk_log_dom, __VA_ARGS__) -#define INFO(...) EINA_LOG_DOM_INFO(_ewk_log_dom, __VA_ARGS__) -#define DBG(...) EINA_LOG_DOM_DBG(_ewk_log_dom, __VA_ARGS__) - -#endif // ewk_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp deleted file mode 100644 index b476f4444..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_security_origin.h" - -#include "WKAPICast.h" -#include "WKSecurityOrigin.h" -#include "WKString.h" -#include "ewk_security_origin_private.h" - -using namespace WebKit; - -EwkSecurityOrigin::EwkSecurityOrigin(WKSecurityOriginRef originRef) - : m_wkOrigin(originRef) - , m_host(AdoptWK, WKSecurityOriginCopyHost(originRef)) - , m_protocol(AdoptWK, WKSecurityOriginCopyProtocol(originRef)) -{ } - -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())) -{ } - -const char* EwkSecurityOrigin::host() const -{ - return m_host; -} - -const char* EwkSecurityOrigin::protocol() const -{ - return m_protocol; -} - -uint32_t EwkSecurityOrigin::port() const -{ - return WKSecurityOriginGetPort(m_wkOrigin.get()); -} - -const char* ewk_security_origin_host_get(const Ewk_Security_Origin* origin) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkSecurityOrigin, origin, impl, 0); - - return impl->host(); -} - -const char* ewk_security_origin_protocol_get(const Ewk_Security_Origin* origin) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkSecurityOrigin, origin, impl, 0); - - return impl->protocol(); -} - -uint32_t ewk_security_origin_port_get(const Ewk_Security_Origin* origin) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkSecurityOrigin, origin, impl, 0); - - return impl->port(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.h b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.h deleted file mode 100644 index 2cfcfe0d1..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_security_origin.h - * @brief Security Origin API. - * - * Security Origin is the mechanism that defines the access limits of a website. - * Based on information such as domain, protocol and port, you can or cannot grant - * authorization for accessing data and performing certain tasks. - */ - -#ifndef ewk_security_origin_h -#define ewk_security_origin_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Security_Origin as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Security_Origin; - -/** - * Returns the host of the security origin. - * - * @param o security origin object - * - * @return the host domain pointer or @c NULL if there is not a host scheme. - * This pointer is guaranteed to be eina_stringshare, so whenever possible - * save yourself from cpu cycles and use eina_stringshare_ref() - * instead of eina_stringshare_add() or strdup(). - */ -EAPI const char *ewk_security_origin_host_get(const Ewk_Security_Origin *o); - -/** - * Returns the port of the security origin. - * - * @param o security origin object - * - * @return the port number or @c 0 if there is not a proper security origin scheme - */ -EAPI uint32_t ewk_security_origin_port_get(const Ewk_Security_Origin *o); - -/** - * Returns the protocol of the security origin. - * - * @param o security origin object - * - * @return the protocol scheme pointer or @c NULL if there is not a protocol scheme. - * This pointer is guaranteed to be eina_stringshare, so whenever possible - * save yourself from cpu cycles and use eina_stringshare_ref() - * instead of eina_stringshare_add() or strdup(). - */ -EAPI const char *ewk_security_origin_protocol_get(const Ewk_Security_Origin *o); - -#ifdef __cplusplus -} -#endif -#endif // ewk_security_origin_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h deleted file mode 100644 index e787ce15d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_security_origin_private.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_security_origin_private_h -#define ewk_security_origin_private_h - -#include "WKEinaSharedString.h" -#include "ewk_object_private.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassRefPtr.h> - -class EwkSecurityOrigin : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkSecurityOrigin) - - static PassRefPtr<EwkSecurityOrigin> create(WKSecurityOriginRef originRef) - { - return adoptRef(new EwkSecurityOrigin(originRef)); - } - - static PassRefPtr<EwkSecurityOrigin> create(const char* url) - { - return adoptRef(new EwkSecurityOrigin(url)); - } - - const char* host() const; - const char* protocol() const; - uint32_t port() const; - -private: - explicit EwkSecurityOrigin(WKSecurityOriginRef originRef); - explicit EwkSecurityOrigin(const char* url); - - WKRetainPtr<WKSecurityOriginRef> m_wkOrigin; - WKEinaSharedString m_host; - WKEinaSharedString m_protocol; -}; - -#endif // ewk_security_origin_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp deleted file mode 100644 index 21b4bba09..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings.cpp +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_settings.h" - -#include "EwkView.h" -#include "ewk_settings_private.h" -#include <WebKit2/WebPageGroup.h> -#include <WebKit2/WebPageProxy.h> -#include <WebKit2/WebPreferences.h> - -using namespace WebKit; - -const WebKit::WebPreferences* EwkSettings::preferences() const -{ - return m_view->page()->pageGroup()->preferences(); -} - -WebKit::WebPreferences* EwkSettings::preferences() -{ - return m_view->page()->pageGroup()->preferences(); -} - -Eina_Bool ewk_settings_fullscreen_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ -#if ENABLE(FULLSCREEN_API) - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setFullScreenEnabled(enable); - return true; -#else - UNUSED_PARAM(settings); - UNUSED_PARAM(enable); - return false; -#endif -} - -Eina_Bool ewk_settings_fullscreen_enabled_get(const Ewk_Settings* settings) -{ -#if ENABLE(FULLSCREEN_API) - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - return settings->preferences()->fullScreenEnabled(); -#else - UNUSED_PARAM(settings); - return false; -#endif -} - -Eina_Bool ewk_settings_javascript_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setJavaScriptEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_javascript_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->javaScriptEnabled(); -} - -Eina_Bool ewk_settings_loads_images_automatically_set(Ewk_Settings* settings, Eina_Bool automatic) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setLoadsImagesAutomatically(automatic); - - return true; -} - -Eina_Bool ewk_settings_loads_images_automatically_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->loadsImagesAutomatically(); -} - -Eina_Bool ewk_settings_developer_extras_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setDeveloperExtrasEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_developer_extras_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->developerExtrasEnabled(); -} - -Eina_Bool ewk_settings_file_access_from_file_urls_allowed_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setAllowFileAccessFromFileURLs(enable); - - return true; -} - -Eina_Bool ewk_settings_file_access_from_file_urls_allowed_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->allowFileAccessFromFileURLs(); -} - -Eina_Bool ewk_settings_frame_flattening_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setFrameFlatteningEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_frame_flattening_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->frameFlatteningEnabled(); -} - -Eina_Bool ewk_settings_dns_prefetching_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setDNSPrefetchingEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_dns_prefetching_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->dnsPrefetchingEnabled(); -} - -Eina_Bool ewk_settings_encoding_detector_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setUsesEncodingDetector(enable); - - return true; -} - -Eina_Bool ewk_settings_encoding_detector_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->usesEncodingDetector(); -} - -Eina_Bool ewk_settings_preferred_minimum_contents_width_set(Ewk_Settings *settings, unsigned width) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setLayoutFallbackWidth(width); - - return true; -} - -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_Bool ewk_settings_offline_web_application_cache_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setOfflineWebApplicationCacheEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_offline_web_application_cache_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->offlineWebApplicationCacheEnabled(); -} - -Eina_Bool ewk_settings_scripts_can_open_windows_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - settings->preferences()->setJavaScriptCanOpenWindowsAutomatically(enable); - - return true; -} - -Eina_Bool ewk_settings_scripts_can_open_windows_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->javaScriptCanOpenWindowsAutomatically(); -} - -Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setLocalStorageEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_local_storage_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->localStorageEnabled(); -} - -Eina_Bool ewk_settings_plugins_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setPluginsEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_plugins_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->pluginsEnabled(); -} - -Eina_Bool ewk_settings_default_font_size_set(Ewk_Settings* settings, int size) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setDefaultFontSize(size); - - return true; -} - -int ewk_settings_default_font_size_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, 0); - - return settings->preferences()->defaultFontSize(); -} - -Eina_Bool ewk_settings_private_browsing_enabled_set(Ewk_Settings* settings, Eina_Bool enable) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - settings->preferences()->setPrivateBrowsingEnabled(enable); - - return true; -} - -Eina_Bool ewk_settings_private_browsing_enabled_get(const Ewk_Settings* settings) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(settings, false); - - return settings->preferences()->privateBrowsingEnabled(); -} - -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()->setTextAutosizingEnabled(enable); - - return true; -#else - UNUSED_PARAM(settings); - UNUSED_PARAM(enable); - return false; -#endif -} - -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()->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 deleted file mode 100644 index 831c515f7..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_settings.h +++ /dev/null @@ -1,450 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_settings.h - * @brief Describes the settings API. - * - * @note The ewk_settings is for setting the preference of specific ewk_view. - * We can get the ewk_settings from ewk_view using ewk_view_settings_get() API. - */ - -#ifndef ewk_settings_h -#define ewk_settings_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for Ewk_Settings */ -typedef struct EwkSettings Ewk_Settings; - - -/** - * Enables/disables the Javascript Fullscreen API. The Javascript API allows - * to request full screen mode, for more information see: - * http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html - * - * Default value for Javascript Fullscreen API setting is @c EINA_TRUE . - * - * @param settings settings object to enable Javascript Fullscreen API - * @param enable @c EINA_TRUE to enable Javascript Fullscreen API or - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_fullscreen_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether the Javascript Fullscreen API is enabled or not. - * - * @param settings settings object to query whether Javascript Fullscreen API is enabled - * - * @return @c EINA_TRUE if the Javascript Fullscreen API is enabled - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_fullscreen_enabled_get(const Ewk_Settings *settings); - -/** - * Enables/disables the javascript executing. - * - * By default, JavaScript execution is enabled. - * - * @param settings settings object to set javascript executing - * @param enable @c EINA_TRUE to enable javascript executing - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_javascript_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether JavaScript execution is enabled. - * - * @param settings settings object to query if the javascript can be executed - * - * @return @c EINA_TRUE if the javascript can be executed - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_javascript_enabled_get(const Ewk_Settings *settings); - -/** - * Enables/disables auto loading of the images. - * - * By default, auto loading of the images is enabled. - * - * @param settings settings object to set auto loading of the images - * @param automatic @c EINA_TRUE to enable auto loading of the images - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_loads_images_automatically_set(Ewk_Settings *settings, Eina_Bool automatic); - -/** - * Returns whether the images can be loaded automatically or not. - * - * @param settings settings object to get auto loading of the images - * - * @return @c EINA_TRUE if the images are loaded automatically - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_loads_images_automatically_get(const Ewk_Settings *settings); - -/** - * Enables/disables developer extensions. - * - * By default, the developer extensions are disabled. - * - * @param settings settings object to set developer extensions - * @param enable @c EINA_TRUE to enable developer extensions - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_developer_extras_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Queries if developer extensions are enabled. - * - * By default, the developer extensions are disabled. - * - * @param settings settings object to set developer extensions - * - * @return @c EINA_TRUE if developer extensions are enabled - @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_developer_extras_enabled_get(const Ewk_Settings *settings); - -/** - * Allow / Disallow file access from file:// URLs. - * - * By default, file access from file:// URLs is not allowed. - * - * @param settings settings object to set file access permission - * @param enable @c EINA_TRUE to enable file access permission - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_file_access_from_file_urls_allowed_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Queries if file access from file:// URLs is allowed. - * - * By default, file access from file:// URLs is not allowed. - * - * @param settings settings object to query file access permission - * - * @return @c EINA_TRUE if file access from file:// URLs is allowed - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_file_access_from_file_urls_allowed_get(const Ewk_Settings *settings); - -/** - * Enables/disables frame flattening. - * - * By default, the frame flattening is disabled. - * - * @param settings settings object to set the frame flattening - * @param enable @c EINA_TRUE to enable the frame flattening - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - * - * @see ewk_settings_enable_frame_flattening_get() - */ -EAPI Eina_Bool ewk_settings_frame_flattening_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether the frame flattening is enabled. - * - * The frame flattening is a feature which expands sub frames until all the frames become - * one scrollable page. - * - * @param settings settings object to get the frame flattening. - * - * @return @c EINA_TRUE if the frame flattening is enabled - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_frame_flattening_enabled_get(const Ewk_Settings *settings); - -/** - * Enables/disables DNS prefetching. - * - * By default, DNS prefetching is disabled. - * - * @param settings settings object to set DNS prefetching - * @param enable @c EINA_TRUE to enable DNS prefetching or - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - * - * @see ewk_settings_DNS_prefetching_enabled_get() - */ -EAPI Eina_Bool ewk_settings_dns_prefetching_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether DNS prefetching is enabled or not. - * - * DNS prefetching is an attempt to resolve domain names before a user tries to follow a link. - * - * @param settings settings object to get DNS prefetching - * - * @return @c EINA_TRUE if DNS prefetching is enabled - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_dns_prefetching_enabled_get(const Ewk_Settings *settings); - -/** - * Enables/disables the encoding detector. - * - * By default, the encoding detector is disabled. - * - * @param settings settings object to set the encoding detector - * @param enable @c EINA_TRUE to enable the encoding detector, - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_encoding_detector_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** -* Returns whether the encoding detector is enabled or not. - * - * @param settings settings object to query whether encoding detector is enabled - * - * @return @c EINA_TRUE if the encoding detector is enabled - * @c EINA_FALSE if not or on failure - */ -EAPI Eina_Bool ewk_settings_encoding_detector_enabled_get(const Ewk_Settings *settings); - -/** - * Sets preferred minimum contents width which is used as default minimum contents width - * for non viewport meta element sites. - * - * By default, preferred minimum contents width is equal to @c 980. - * - * @param settings settings object to set the encoding detector - * @param enable @c EINA_TRUE to enable the encoding detector, - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_preferred_minimum_contents_width_set(Ewk_Settings *settings, unsigned width); - -/** - * Returns preferred minimum contents width or @c 0 on failure. - * - * @param settings settings object to query preferred minimum contents width - * - * @return preferred minimum contents width - * @c 0 on failure - */ -EAPI unsigned ewk_settings_preferred_minimum_contents_width_get(const Ewk_Settings *settings); - -/** - * Enables/disables the offline application cache. - * - * By default, the offline application cache is enabled. - * - * @param settings settings object to set the offline application cache state - * @param enable @c EINA_TRUE to enable the offline application cache, - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_offline_web_application_cache_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether the offline application cache is enabled or not. - * - * @param settings settings object to query whether offline application cache is enabled - * - * @return @c EINA_TRUE if the offline application cache is enabled - * @c EINA_FALSE if disabled or on failure - */ -EAPI Eina_Bool ewk_settings_offline_web_application_cache_enabled_get(const Ewk_Settings *settings); - -/** - * Enables/disables if the scripts can open new windows. - * - * By default, the scripts can open new windows. - * - * @param settings settings object to set if the scripts can open new windows - * @param enable @c EINA_TRUE if the scripts can open new windows - * @c EINA_FALSE if not - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure (scripts are disabled) - */ -EAPI Eina_Bool ewk_settings_scripts_can_open_windows_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether the scripts can open new windows. - * - * @param settings settings object to query whether the scripts can open new windows - * - * @return @c EINA_TRUE if the scripts can open new windows - * @c EINA_FALSE if not or on failure (scripts are disabled) - */ -EAPI Eina_Bool ewk_settings_scripts_can_open_windows_get(const Ewk_Settings *settings); - -/** - * Enables/disables the HTML5 local storage functionality. - * - * Local storage provides simple synchronous storage access. - * HTML5 local storage specification is available at - * http://dev.w3.org/html5/webstorage/. - * - * By default, the HTML5 local storage is enabled. - * - * @param settings settings object to set the HTML5 local storage state - * @param enable @c EINA_TRUE to enable HTML5 local storage, - * @c EINA_FALSE to disable - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_settings_local_storage_enabled_set(Ewk_Settings *settings, Eina_Bool enable); - -/** - * Returns whether the HTML5 local storage functionality is enabled or not. - * - * Local storage provides simple synchronous storage access. - * HTML5 local storage specification is available at - * http://dev.w3.org/html5/webstorage/. - * - * By default, the HTML5 local storage is enabled. - * - * @param settings settings object to query whether HTML5 local storage is enabled - * - * @return @c EINA_TRUE if the HTML5 local storage is enabled - * @c EINA_FALSE if disabled or on failure - */ -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 -#endif // ewk_settings_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp deleted file mode 100644 index fd0eaeb39..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_storage_manager.h" - -#include "WKAPICast.h" -#include "WKArray.h" -#include "ewk_error_private.h" -#include "ewk_security_origin_private.h" -#include "ewk_storage_manager_private.h" - -using namespace WebKit; - -EwkStorageManager::EwkStorageManager(WKKeyValueStorageManagerRef storageManager) - : m_storageManager(storageManager) -{ - ASSERT(storageManager); -} - -void EwkStorageManager::getStorageOrigins(void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) const -{ - WKKeyValueStorageManagerGetKeyValueStorageOrigins(m_storageManager.get(), context, callback); -} - -Eina_List* EwkStorageManager::createOriginList(WKArrayRef origins) const -{ - Eina_List* originList = 0; - const size_t length = WKArrayGetSize(origins); - - for (size_t i = 0; i < length; ++i) { - WKSecurityOriginRef wkOriginRef = static_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, i)); - RefPtr<EwkSecurityOrigin> origin = m_wrapperCache.get(wkOriginRef); - if (!origin) { - origin = EwkSecurityOrigin::create(wkOriginRef); - m_wrapperCache.set(wkOriginRef, origin); - } - originList = eina_list_append(originList, origin.release().leakRef()); - } - - return originList; -} - -struct Ewk_Storage_Origins_Async_Get_Context { - const Ewk_Storage_Manager* manager; - Ewk_Storage_Origins_Get_Cb callback; - void* userData; - - Ewk_Storage_Origins_Async_Get_Context(const Ewk_Storage_Manager* manager, Ewk_Storage_Origins_Get_Cb callback, void* userData) - : manager(manager) - , callback(callback) - , userData(userData) - { } -}; - -static void getStorageOriginsCallback(WKArrayRef origins, WKErrorRef wkError, void* context) -{ - Eina_List* originList = 0; - OwnPtr<Ewk_Storage_Origins_Async_Get_Context*> webStorageContext = adoptPtr(static_cast<Ewk_Storage_Origins_Async_Get_Context*>(context)); - - originList = webStorageContext->manager->createOriginList(origins); - - OwnPtr<EwkError> ewkError = EwkError::create(wkError); - webStorageContext->callback(originList, ewkError.get(), webStorageContext->userData); -} - -Eina_Bool ewk_storage_manager_origins_get(const Ewk_Storage_Manager* ewkStorageManager, Ewk_Storage_Origins_Get_Cb callback, void* userData) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(ewkStorageManager, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(callback, false); - - Ewk_Storage_Origins_Async_Get_Context* context = new Ewk_Storage_Origins_Async_Get_Context(ewkStorageManager, callback, userData); - ewkStorageManager->getStorageOrigins(context, getStorageOriginsCallback); - - return true; -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h deleted file mode 100644 index 4f5c8fb30..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_storage_manager.h - * @brief Describes the Ewk Storage Manager API. - * - * Ewk Storage Manager manages web storage. - */ - -#ifndef ewk_storage_manager_h -#define ewk_storage_manager_h - -#include "ewk_error.h" -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** Creates a type name for Ewk_Storage_Manager. */ -typedef struct EwkStorageManager Ewk_Storage_Manager; - -/** - * @typedef Ewk_Storage_Origins_Get_Cb Ewk_Storage_Origins_Get_Cb - * @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_object_unref() - * to free the items - */ -typedef void (*Ewk_Storage_Origins_Get_Cb)(Eina_List *origins, Ewk_Error *error, void *user_data); - -/** - * Gets list of origins that are stored in storage db asynchronously. - * - * This function allocates memory for context structure made from callback and user_data. - * - * @param manager Ewk_Storage_Manager object - * @param callback callback to get storage origins - * @param user_data user_data will be passed when result_callback is called, - * -i.e., user data will be kept until callback is called - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_storage_manager_origins_get(const Ewk_Storage_Manager *manager, Ewk_Storage_Origins_Get_Cb callback, void *user_data); - -#ifdef __cplusplus -} -#endif -#endif // ewk_storage_manager_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h deleted file mode 100644 index 550cff0f4..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_storage_manager_private.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_storage_manager_private_h -#define ewk_storage_manager_private_h - -#include "WKKeyValueStorageManager.h" -#include "WKRetainPtr.h" -#include "ewk_security_origin_private.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -using namespace WebKit; - -class EwkStorageManager { -public: - static PassOwnPtr<EwkStorageManager> create(WKKeyValueStorageManagerRef storageManager) - { - ASSERT(storageManager); - return adoptPtr(new EwkStorageManager(storageManager)); - } - - Eina_List* createOriginList(WKArrayRef wkList) const; - void getStorageOrigins(void* context, WKKeyValueStorageManagerGetKeyValueStorageOriginsFunction callback) const; - -private: - explicit EwkStorageManager(WKKeyValueStorageManagerRef); - - 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 deleted file mode 100644 index 8f4994b0f..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2012-2013 Samsung Electronics - * Copyright (C) 2012 Intel Corporation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ewk_text_checker.h" - -#if ENABLE(SPELLCHECK) -#include "TextCheckerClientEfl.h" - -using namespace WebKit; - -static Eina_List* convertLanguagesToEinaList(const Vector<String>& languages) -{ - Eina_List* listOflanguages = 0; - size_t numberOfLanguages = languages.size(); - - for (size_t i = 0; i < numberOfLanguages; ++i) - listOflanguages = eina_list_append(listOflanguages, eina_stringshare_add(languages[i].utf8().data())); - - return listOflanguages; -} - -#define EWK_TEXT_CHECKER_CALLBACK_SET(TYPE_NAME, NAME) \ -void ewk_text_checker_##NAME##_cb_set(TYPE_NAME cb) \ -{ \ - TextCheckerClientEfl::instance().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) \ -{ \ -} -#endif // ENABLE(SPELLCHECK) - -Eina_Bool ewk_text_checker_continuous_spell_checking_enabled_get() -{ -#if ENABLE(SPELLCHECK) - return TextCheckerClientEfl::instance().isContinuousSpellCheckingEnabled(); -#else - return false; -#endif -} - -void ewk_text_checker_continuous_spell_checking_enabled_set(Eina_Bool enable) -{ -#if ENABLE(SPELLCHECK) - WKTextCheckerContinuousSpellCheckingEnabledStateChanged(!!enable); -#else - UNUSED_PARAM(enable); -#endif -} - -Eina_List* ewk_text_checker_spell_checking_available_languages_get() -{ - 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; -} - -void ewk_text_checker_spell_checking_languages_set(const char* languages) -{ -#if ENABLE(SPELLCHECK) - Vector<String> newLanguages; - String::fromUTF8(languages).split(',', newLanguages); - - // FIXME: Expose WK2 C API to set spell checking languages. - TextCheckerClientEfl::instance().updateSpellCheckingLanguages(newLanguages); -#else - UNUSED_PARAM(languages); -#endif -} - -Eina_List* ewk_text_checker_spell_checking_languages_get() -{ - 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; -} - -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) -EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_Word_Guesses_Get_Cb, word_guesses_get) -EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_Word_Learn_Cb, word_learn) -EWK_TEXT_CHECKER_CALLBACK_SET(Ewk_Text_Checker_Word_Ignore_Cb, word_ignore) diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h deleted file mode 100644 index b45322591..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker.h +++ /dev/null @@ -1,236 +0,0 @@ -/* - * 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 - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file ewk_text_checker.h - * @brief Provides API to overwrite the default WebKit spellchecker implementation - * and contains API to manipulate spellchecker settings. - * - * 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. - * It doesn't ensure grammar checking. Application is able to overwrite the default - * WebKit spellchecker implementation by defining its own implementation and setting - * appropriate callback functions. - */ - -#ifndef ewk_text_checker_h -#define ewk_text_checker_h - -#include <Evas.h> - -#ifdef __cplusplus -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. - * - * @param o the view object to get unique tag - * - * @return unique tag for the given @a o view object - */ -typedef uint64_t (*Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb)(const Evas_Object *o); - -/** - * Defines a type name for the callback function to close the prviously set tag. - * - * This callback will notify the receiver that the user has finished with the tagged document. - * - * @param tag the tag to be closed - */ -typedef void (*Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb)(uint64_t tag); - -/** - * Defines a type name for the callback function to search for a misspelled words in the given string. - * - * @param tag unique tag to notify the spell checker which document that @a text is associated, - * in most cases not necessarily, just for ignored word, - * @c 0 can be passed in for text not associated with a particular document - * @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 - */ -typedef void (*Ewk_Text_Checker_String_Spelling_Check_Cb)(uint64_t tag, const char *text, int32_t *misspelling_location, int32_t *misspelling_length); - -/** - * Defines a type name for the callback function to get a list of suggested spellings for a misspelled @a word. - * - * @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*), - * 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); - -/** - * Sets a callback function to add the word to the spell checker dictionary. - * - * @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 add - */ -typedef void (*Ewk_Text_Checker_Word_Learn_Cb)(uint64_t tag, const char *word); - -/** - * Sets a callback function to tell the spell checker to ignore a given word. - * - * @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 ignore - */ -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. - * - * @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation - */ -EAPI void ewk_text_checker_unique_spell_document_tag_get_cb_set(Ewk_Text_Checker_Unique_Spell_Document_Tag_Get_Cb cb); - -/** - * Sets a callback function to close a unique spell document tag. - * - * @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation - */ -EAPI void ewk_text_checker_unique_spell_document_tag_close_cb_set(Ewk_Text_Checker_Unique_Spell_Document_Tag_Close_Cb cb); - -/** - * Sets a callback function to search for a misspelled words in the given string. - * - * @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation - */ -EAPI void ewk_text_checker_string_spelling_check_cb_set(Ewk_Text_Checker_String_Spelling_Check_Cb cb); - -/** - * Sets a callback function to get an array of suggested spellings for a misspelled word. - * - * @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation - */ -EAPI void ewk_text_checker_word_guesses_get_cb_set(Ewk_Text_Checker_Word_Guesses_Get_Cb cb); - -/** - * Sets a callback function to add the word to the spell checker dictionary. - * - * @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation - */ -EAPI void ewk_text_checker_word_learn_cb_set(Ewk_Text_Checker_Word_Learn_Cb cb); - -/** - * Sets a callback function to tell the spell checker to ignore a given word. - * - * @param cb a new callback to set or @c NULL to restore the default WebKit callback implementation - */ -EAPI void ewk_text_checker_word_ignore_cb_set(Ewk_Text_Checker_Word_Ignore_Cb cb); - -#ifdef __cplusplus -} -#endif -#endif // ewk_text_checker_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h deleted file mode 100644 index f113cb3c0..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_text_checker_private.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2012-2013 Samsung Electronics - * Copyright (C) 2012 Intel Corporation - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_text_checker_private_h -#define ewk_text_checker_private_h - -#if ENABLE(SPELLCHECK) - -#include "ewk_text_checker.h" - -/** - * @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_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_url_request.cpp deleted file mode 100644 index 879791a59..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_request.cpp +++ /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. - */ - -#include "config.h" -#include "ewk_url_request.h" - -#include "ewk_url_request_private.h" - -using namespace WebKit; - -EwkUrlRequest::EwkUrlRequest(WKURLRequestRef requestRef) - : m_url(AdoptWK, WKURLRequestCopyURL(requestRef)) - , m_firstParty(AdoptWK, WKURLRequestCopyFirstPartyForCookies(requestRef)) - , m_httpMethod(AdoptWK, WKURLRequestCopyHTTPMethod(requestRef)) -{ } - -const char* EwkUrlRequest::url() const -{ - return m_url; -} - -const char* EwkUrlRequest::firstParty() const -{ - return m_firstParty; -} - -const char* EwkUrlRequest::httpMethod() const -{ - return m_httpMethod; -} - -const char* ewk_url_request_url_get(const Ewk_Url_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlRequest, request, impl, 0); - - return impl->url(); -} - -const char* ewk_request_cookies_first_party_get(const Ewk_Url_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlRequest, request, impl, 0); - - return impl->firstParty(); -} - -const char* ewk_url_request_http_method_get(const Ewk_Url_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlRequest, request, impl, 0); - - return impl->httpMethod(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_request.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_request.h deleted file mode 100644 index 96b8b4567..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_request.h +++ /dev/null @@ -1,99 +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_url_request.h - * @brief Describes the Ewk URL request API. - */ - -#ifndef ewk_url_request_h -#define ewk_url_request_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Url_Request as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Url_Request; - -/** - * Query URL for this request. - * - * @param request request 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_url_request_url_get(const Ewk_Url_Request *request); - -/** - * Query first party for cookies for this request. - * - * If set, this first party URL is used to distinguish first party cookies - * from third party ones. This is usually set to the URL of the main document. - * - * @param request request object to query. - * - * @return the first party 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_request_cookies_first_party_get(const Ewk_Url_Request *request); - -/** - * Query HTTP method for this request. - * - * HTTP methods are defined by: - * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - * - * Examples of HTTP methods are "GET", "POST". - * - * @param request request object to query. - * - * @return the HTTP method 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_url_request_http_method_get(const Ewk_Url_Request *request); - - -#ifdef __cplusplus -} -#endif - -#endif // ewk_url_request_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_request_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_request_private.h deleted file mode 100644 index 5ba6677a5..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_request_private.h +++ /dev/null @@ -1,61 +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_url_request_private_h -#define ewk_url_request_private_h - -#include "WKEinaSharedString.h" -#include "WKURL.h" -#include "WKURLRequest.h" -#include "WebURLRequest.h" -#include "ewk_object_private.h" -#include <wtf/PassRefPtr.h> - -/** - * \struct EwkUrlRequest - * @brief Contains the URL request data. - */ -class EwkUrlRequest : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkUrlRequest) - - static PassRefPtr<EwkUrlRequest> create(WKURLRequestRef requestRef) - { - return adoptRef(new EwkUrlRequest(requestRef)); - } - - const char* url() const; - const char* firstParty() const; - const char* httpMethod() const; - -private: - explicit EwkUrlRequest(WKURLRequestRef requestRef); - - WKEinaSharedString m_url; - WKEinaSharedString m_firstParty; - WKEinaSharedString m_httpMethod; -}; - -#endif // ewk_url_request_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp deleted file mode 100644 index 29244fa9f..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_response.cpp +++ /dev/null @@ -1,86 +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_url_response.h" - -#include "ewk_url_response_private.h" -#include <wtf/text/CString.h> - -using namespace WebKit; - -EwkUrlResponse::EwkUrlResponse(WKURLResponseRef response) - : m_response(response) - , m_url(AdoptWK, WKURLResponseCopyURL(response)) - , m_mimeType(AdoptWK, WKURLResponseCopyMIMEType(response)) -{ } - -int EwkUrlResponse::httpStatusCode() const -{ - return WKURLResponseHTTPStatusCode(m_response.get()); -} - -const char* EwkUrlResponse::url() const -{ - return m_url; -} - -const char* EwkUrlResponse::mimeType() const -{ - return m_mimeType; -} - -unsigned long EwkUrlResponse::contentLength() const -{ - return WKURLResponseGetExpectedContentLength(m_response.get()); -} - -const char* ewk_url_response_url_get(const Ewk_Url_Response* response) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlResponse, response, impl, 0); - - return impl->url(); -} - -int ewk_url_response_status_code_get(const Ewk_Url_Response* response) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlResponse, response, impl, 0); - - return impl->httpStatusCode(); -} - -const char* ewk_url_response_mime_type_get(const Ewk_Url_Response* response) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlResponse, response, impl, 0); - - return impl->mimeType(); -} - -unsigned long ewk_url_response_content_length_get(const Ewk_Url_Response* response) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlResponse, response, impl, 0); - - return impl->contentLength(); -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_response.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_response.h deleted file mode 100644 index ecd0796c4..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_response.h +++ /dev/null @@ -1,100 +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_url_response.h - * @brief Describes the Ewk URL response API. - */ - -#ifndef ewk_url_response_h -#define ewk_url_response_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Url_Response as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Url_Response; - -/** - * Query URL for this response. - * - * @param response response 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_url_response_url_get(const Ewk_Url_Response *response); - -/** - * Query HTTP status code for this response. - * - * HTTP status code are defined by: - * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - * - * @param response response object to query. - * - * @return the HTTP status code. - */ -EAPI int ewk_url_response_status_code_get(const Ewk_Url_Response *response); - -/** - * Query MIME type for this response. - * - * @param response response object to query. - * - * @return the MIME 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_url_response_mime_type_get(const Ewk_Url_Response *response); - -/** - * Get the expected content length of the #Ewk_Url_Response. - * - * It can be 0 if the server provided an incorrect or missing Content-Length. - * - * @param response a #Ewk_Url_Response. - * - * @return the expected content length of @a response or 0 in case of failure. - */ -EAPI unsigned long ewk_url_response_content_length_get(const Ewk_Url_Response *response); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_url_response_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h deleted file mode 100644 index 4ea827498..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_response_private.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_url_response_private_h -#define ewk_url_response_private_h - -#include "WKAPICast.h" -#include "WKEinaSharedString.h" -#include "WKURLResponse.h" -#include "ewk_object_private.h" -#include <wtf/PassRefPtr.h> - -/** - * \struct EwkUrlResponse - * @brief Contains the URL response data. - */ -class EwkUrlResponse : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkUrlResponse) - - static PassRefPtr<EwkUrlResponse> create(WKURLResponseRef wkResponse) - { - if (!wkResponse) - return 0; - - return adoptRef(new EwkUrlResponse(wkResponse)); - } - - int httpStatusCode() const; - const char* url() const; - const char* mimeType() const; - unsigned long contentLength() const; - -private: - explicit EwkUrlResponse(WKURLResponseRef response); - - WKRetainPtr<WKURLResponseRef> m_response; - WKEinaSharedString m_url; - WKEinaSharedString m_mimeType; -}; - -#endif // ewk_url_response_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp deleted file mode 100644 index 728ee40fd..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.cpp +++ /dev/null @@ -1,102 +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_url_scheme_request.h" - -#include "WKData.h" -#include "WKString.h" -#include "WKURL.h" -#include "ewk_url_scheme_request_private.h" - -using namespace WebKit; - -EwkUrlSchemeRequest::EwkUrlSchemeRequest(WKSoupRequestManagerRef manager, WKURLRef url, uint64_t requestID) - : m_wkRequestManager(manager) - , m_url(url) - , m_requestID(requestID) - , m_scheme(AdoptWK, WKURLCopyScheme(url)) - , m_path(AdoptWK, WKURLCopyPath(url)) -{ -} - -uint64_t EwkUrlSchemeRequest::id() const -{ - return m_requestID; -} - -const char* EwkUrlSchemeRequest::url() const -{ - return m_url; -} - -const char* EwkUrlSchemeRequest::scheme() const -{ - return m_scheme; -} - -const char* EwkUrlSchemeRequest::path() const -{ - return m_path; -} - -void EwkUrlSchemeRequest::finish(const void* contentData, uint64_t contentLength, const char* mimeType) -{ - WKRetainPtr<WKDataRef> wkData(AdoptWK, WKDataCreate(contentLength ? reinterpret_cast<const unsigned char*>(contentData) : 0, contentLength)); - WKRetainPtr<WKStringRef> wkMimeType = mimeType ? adoptWK(WKStringCreateWithUTF8CString(mimeType)) : 0; - - // In case of empty reply an empty WKDataRef is sent to the WebProcess. - WKSoupRequestManagerDidHandleURIRequest(m_wkRequestManager.get(), wkData.get(), contentLength, wkMimeType.get(), m_requestID); -} - -const char* ewk_url_scheme_request_scheme_get(const Ewk_Url_Scheme_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlSchemeRequest, request, impl, 0); - - return impl->scheme(); -} - -const char* ewk_url_scheme_request_url_get(const Ewk_Url_Scheme_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlSchemeRequest, request, impl, 0); - - return impl->url(); -} - -const char* ewk_url_scheme_request_path_get(const Ewk_Url_Scheme_Request* request) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkUrlSchemeRequest, request, impl, 0); - - return impl->path(); -} - -Eina_Bool ewk_url_scheme_request_finish(Ewk_Url_Scheme_Request* request, const void* contentData, uint64_t contentLength, const char* mimeType) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(EwkUrlSchemeRequest, request, impl, false); - - impl->finish(contentData, contentLength, mimeType); - - return true; -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.h deleted file mode 100644 index 75fabd2e6..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request.h +++ /dev/null @@ -1,100 +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_url_scheme_request.h - * @brief Describes the Ewk URL scheme request API. - */ - -#ifndef ewk_url_scheme_request_h -#define ewk_url_scheme_request_h - -#include <Eina.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Url_Scheme_Request as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Url_Scheme_Request; - -/** - * Query the URL scheme for this request. - * - * @param request request object to query. - * - * @return the URL scheme 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_url_scheme_request_scheme_get(const Ewk_Url_Scheme_Request *request); - -/** - * Query the URL for this request. - * - * @param request request 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_url_scheme_request_url_get(const Ewk_Url_Scheme_Request *request); - -/** - * Query the path part of the URL for this request. - * - * @param request request object to query. - * - * @return the path 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_url_scheme_request_path_get(const Ewk_Url_Scheme_Request *request); - -/** - * Finish a Ewk_Url_Scheme_Request by setting the content of the request and its mime type. - * - * @param request a Ewk_Url_Scheme_Request. - * @param content_data the data content of the request (may be %c NULL if the content is empty). - * @param content_length the length of the @a content_data. - * @param mime_type the content type of the stream or %c NULL if not known - */ -EAPI Eina_Bool ewk_url_scheme_request_finish(Ewk_Url_Scheme_Request *request, const void *content_data, uint64_t content_length, const char *mime_type); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_url_scheme_request_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request_private.h deleted file mode 100644 index 051473867..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_url_scheme_request_private.h +++ /dev/null @@ -1,69 +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_url_scheme_request_private_h -#define ewk_url_scheme_request_private_h - -#include "WKAPICast.h" -#include "WKBase.h" -#include "WKEinaSharedString.h" -#include "WKRetainPtr.h" -#include "WKSoupRequestManager.h" -#include "ewk_object_private.h" - -/** - * \struct EwkUrlSchemeRequest - * @brief Contains the URL scheme request data. - */ -class EwkUrlSchemeRequest : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkUrlSchemeRequest) - - static PassRefPtr<EwkUrlSchemeRequest> create(WKSoupRequestManagerRef manager, WKURLRef url, uint64_t requestID) - { - if (!manager || !url) - return 0; - - return adoptRef(new EwkUrlSchemeRequest(manager, url, requestID)); - } - - uint64_t id() const; - const char* url() const; - const char* scheme() const; - const char* path() const; - - void finish(const void* contentData, uint64_t contentLength, const char* mimeType); - -private: - EwkUrlSchemeRequest(WKSoupRequestManagerRef manager, WKURLRef urlRef, uint64_t requestID); - - WKRetainPtr<WKSoupRequestManagerRef> m_wkRequestManager; - WKEinaSharedString m_url; - uint64_t m_requestID; - WKEinaSharedString m_scheme; - WKEinaSharedString m_path; -}; - -#endif // ewk_url_scheme_request_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp b/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp deleted file mode 100644 index 17c21d537..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_view.cpp +++ /dev/null @@ -1,631 +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 "ewk_view.h" -#include "ewk_view_private.h" - -#include "EwkView.h" -#include "FindClientEfl.h" -#include "FormClientEfl.h" -#include "InputMethodContextEfl.h" -#include "PageLoadClientEfl.h" -#include "PagePolicyClientEfl.h" -#include "PageUIClientEfl.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_page_group.h" -#include "ewk_page_group_private.h" -#include "ewk_private.h" -#include "ewk_settings_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 - -using namespace WebKit; - -static inline EwkView* toEwkViewChecked(const Evas_Object* evasObject) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(evasObject, 0); - if (!isEwkViewEvasObject(evasObject)) - return 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); - - return smartData->priv; -} - -#define EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, ...) \ - EwkView* impl = toEwkViewChecked(ewkView); \ - do { \ - if (!impl) { \ - EINA_LOG_CRIT("no private data for object %p", ewkView); \ - return __VA_ARGS__; \ - } \ - } while (0) - - -Eina_Bool ewk_view_smart_class_set(Ewk_View_Smart_Class* api) -{ - EINA_SAFETY_ON_NULL_RETURN_VAL(api, false); - - return EwkView::initSmartClassInterface(*api); -} - -Evas_Object* EWKViewCreate(WKContextRef context, WKPageGroupRef pageGroup, Evas* canvas, Evas_Smart* smart) -{ - WKRetainPtr<WKViewRef> wkView = adoptWK(WKViewCreate(context, pageGroup)); - WKPageSetUseFixedLayout(WKViewGetPage(wkView.get()), true); - if (EwkView* ewkView = EwkView::create(wkView.get(), canvas, smart)) - return ewkView->evasObject(); - - return 0; -} - -WKViewRef EWKViewGetWKView(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->wkView(); -} - -Evas_Object* ewk_view_smart_add(Evas* canvas, Evas_Smart* smart, Ewk_Context* context, Ewk_Page_Group* pageGroup) -{ - EwkContext* ewkContext = ewk_object_cast<EwkContext*>(context); - EwkPageGroup* ewkPageGroup = ewk_object_cast<EwkPageGroup*>(pageGroup); - - 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 EWKViewCreate(ewkContext->wkContext(), ewkPageGroup->wkPageGroup(), canvas, smart); -} - -Evas_Object* ewk_view_add(Evas* canvas) -{ - return EWKViewCreate(adoptWK(WKContextCreate()).get(), 0, canvas, 0); -} - -Evas_Object* ewk_view_add_with_context(Evas* canvas, Ewk_Context* context) -{ - EwkContext* ewkContext = ewk_object_cast<EwkContext*>(context); - EINA_SAFETY_ON_NULL_RETURN_VAL(ewkContext, 0); - EINA_SAFETY_ON_NULL_RETURN_VAL(ewkContext->wkContext(), 0); - - return EWKViewCreate(ewkContext->wkContext(), 0, canvas, 0); -} - -Ewk_Context* ewk_view_context_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->ewkContext(); -} - -Ewk_Page_Group* ewk_view_page_group_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->ewkPageGroup(); -} - -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); - - WKRetainPtr<WKURLRef> wkUrl = adoptWK(WKURLCreateWithUTF8CString(url)); - WKPageLoadURL(impl->wkPage(), wkUrl.get()); - impl->informURLChange(); - - return true; -} - -const char* ewk_view_url_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->url(); -} - -Evas_Object* ewk_view_favicon_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->createFavicon(); -} - -Eina_Bool ewk_view_reload(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKPageReload(impl->wkPage()); - impl->informURLChange(); - - return true; -} - -Eina_Bool ewk_view_reload_bypass_cache(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKPageReloadFromOrigin(impl->wkPage()); - impl->informURLChange(); - - return true; -} - -Eina_Bool ewk_view_stop(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKPageStopLoading(impl->wkPage()); - - return true; -} - -Ewk_Settings* ewk_view_settings_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->settings(); -} - -const char* ewk_view_title_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->title(); -} - -double ewk_view_load_progress_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, -1.0); - - 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); - - WKPageSetScaleFactor(impl->wkPage(), scaleFactor, WKPointMake(x, y)); - return true; -} - -double ewk_view_scale_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, -1); - - 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->setDeviceScaleFactor(ratio); - - return true; -} - -float ewk_view_device_pixel_ratio_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, -1.0); - - return WKPageGetBackingScaleFactor(impl->wkPage()); -} - -void ewk_view_theme_set(Evas_Object* ewkView, const char* path) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl); - - impl->setThemePath(path); -} - -const char* ewk_view_theme_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->themePath(); -} - -Eina_Bool ewk_view_back(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKPageRef page = impl->wkPage(); - if (WKPageCanGoBack(page)) { - WKPageGoBack(page); - return true; - } - - return false; -} - -Eina_Bool ewk_view_forward(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKPageRef page = impl->wkPage(); - if (WKPageCanGoForward(page)) { - WKPageGoForward(page); - return true; - } - - return false; -} - -Eina_Bool ewk_view_back_possible(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - return WKPageCanGoBack(impl->wkPage()); -} - -Eina_Bool ewk_view_forward_possible(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - return WKPageCanGoForward(impl->wkPage()); -} - -Ewk_Back_Forward_List* ewk_view_back_forward_list_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - 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); - - 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(); - - return true; -} - -const char* ewk_view_custom_encoding_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, 0); - - return impl->customTextEncodingName(); -} - -Eina_Bool ewk_view_custom_encoding_set(Evas_Object* ewkView, const char* encoding) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - 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; -} - -// EwkFindOptions should be matched up orders with WkFindOptions. -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_CASE_INSENSITIVE, kWKFindOptionsCaseInsensitive); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_AT_WORD_STARTS, kWKFindOptionsAtWordStarts); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START, kWKFindOptionsTreatMedialCapitalAsWordStart); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_BACKWARDS, kWKFindOptionsBackwards); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_WRAP_AROUND, kWKFindOptionsWrapAround); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_SHOW_OVERLAY, kWKFindOptionsShowOverlay); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_SHOW_FIND_INDICATOR, kWKFindOptionsShowFindIndicator); -COMPILE_ASSERT_MATCHING_ENUM(EWK_FIND_OPTIONS_SHOW_HIGHLIGHT, kWKFindOptionsShowHighlight); - -Eina_Bool ewk_view_text_find(Evas_Object* ewkView, const char* text, Ewk_Find_Options options, unsigned maxMatchCount) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(text, false); - - WKRetainPtr<WKStringRef> wkText = adoptWK(WKStringCreateWithUTF8CString(text)); - WKPageFindString(impl->wkPage(), wkText.get(), static_cast<WebKit::FindOptions>(options), maxMatchCount); - - return true; -} - -Eina_Bool ewk_view_text_find_highlight_clear(Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKPageHideFindUI(impl->wkPage()); - - return true; -} - -Eina_Bool ewk_view_text_matches_count(Evas_Object* ewkView, const char* text, Ewk_Find_Options options, unsigned maxMatchCount) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - EINA_SAFETY_ON_NULL_RETURN_VAL(text, false); - - WKRetainPtr<WKStringRef> wkText = adoptWK(WKStringCreateWithUTF8CString(text)); - WKPageCountStringMatches(impl->wkPage(), wkText.get(), static_cast<WebKit::FindOptions>(options), maxMatchCount); - - return true; -} - -Eina_Bool ewk_view_mouse_events_enabled_set(Evas_Object* ewkView, Eina_Bool enabled) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - impl->setMouseEventsEnabled(!!enabled); - - return true; -} - -Eina_Bool ewk_view_mouse_events_enabled_get(const Evas_Object* ewkView) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - return impl->mouseEventsEnabled(); -} - -Eina_Bool ewk_view_feed_touch_event(Evas_Object* ewkView, Ewk_Touch_Event_Type type, const Eina_List* points, const Evas_Modifier* modifiers) -{ -#if ENABLE(TOUCH_EVENTS) - EINA_SAFETY_ON_NULL_RETURN_VAL(points, false); - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - impl->feedTouchEvent(type, points, modifiers); - - return true; -#else - UNUSED_PARAM(ewkView); - UNUSED_PARAM(type); - UNUSED_PARAM(points); - UNUSED_PARAM(modifiers); - return false; -#endif -} - -Eina_Bool ewk_view_touch_events_enabled_set(Evas_Object* ewkView, Eina_Bool enabled) -{ -#if ENABLE(TOUCH_EVENTS) - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - impl->setTouchEventsEnabled(!!enabled); - - return true; -#else - UNUSED_PARAM(ewkView); - UNUSED_PARAM(enabled); - return false; -#endif -} - -Eina_Bool ewk_view_touch_events_enabled_get(const Evas_Object* ewkView) -{ -#if ENABLE(TOUCH_EVENTS) - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - return impl->touchEventsEnabled(); -#else - UNUSED_PARAM(ewkView); - return false; -#endif -} - -Eina_Bool ewk_view_inspector_show(Evas_Object* ewkView) -{ -#if ENABLE(INSPECTOR) - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - WKInspectorRef wkInspector = WKPageGetInspector(impl->wkPage()); - if (wkInspector) - WKInspectorShow(wkInspector); - - return true; -#else - UNUSED_PARAM(ewkView); - return false; -#endif -} - -Eina_Bool ewk_view_inspector_close(Evas_Object* ewkView) -{ -#if ENABLE(INSPECTOR) - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - 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 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); - - WKPageSetPaginationMode(impl->wkPage(), static_cast<WKPaginationMode>(mode)); - - return true; -} - -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>(WKPageGetPaginationMode(impl->wkPage())); -} - -Eina_Bool ewk_view_fullscreen_exit(Evas_Object* ewkView) -{ -#if ENABLE(FULLSCREEN_API) - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl, false); - - return WKViewExitFullScreen(impl->wkView()); -#else - UNUSED_PARAM(ewkView); - return false; -#endif -} - -void ewk_view_draws_page_background_set(Evas_Object *ewkView, Eina_Bool enabled) -{ - EWK_VIEW_IMPL_GET_OR_RETURN(ewkView, impl); - - 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 deleted file mode 100644 index e99169233..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_view.h +++ /dev/null @@ -1,890 +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. -*/ - -/** - * @file ewk_view.h - * @brief WebKit main smart object. - * - * This object provides view related APIs of WebKit2 to EFL object. - * - * The following signals (see evas_object_smart_callback_add()) are emitted: - * - * - "authentication,request", Ewk_Auth_Request*: reports that user authentication was requested. Call - * 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. - * - "download,request", Ewk_Download_Job*: reports that a new download has been requested. The client should set the - * destination path by calling ewk_download_job_destination_set() or the download will fail. - * - "file,chooser,request", Ewk_File_Chooser_Request*: reports that a request has been made for the user to choose - * a file (or several) on the file system. Call ewk_file_chooser_request_ref() on the request object to process it - * asynchronously. - * - "form,submission,request", Ewk_Form_Submission_Request*: Reports that a form request is about to be submitted. - * The Ewk_Form_Submission_Request passed contains information about the text fields of the form. This - * is typically used to store login information that can be used later to pre-fill the form. - * The form will not be submitted until ewk_form_submission_request_submit() is called. - * It is possible to handle the form submission request asynchronously, by simply calling - * ewk_form_submission_request_ref() on the request and calling ewk_form_submission_request_submit() - * 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. - * - "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). - * - "load,provisional,failed", const Ewk_Error*: view provisional load failed. - * - "load,provisional,redirect", void: view received redirect for provisional load. - * - "load,provisional,started", void: view started provisional load. - * - "policy,decision,navigation", Ewk_Navigation_Policy_Decision*: a navigation 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(). - * - "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(). - * - "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. - * - "tooltip,text,unset", void: tooltip was unset. - * - "url,changed", const char*: url of the main frame was changed. - * - "vibrate", uint64_t*: request to vibrate. (value is vibration time) - * - "webprocess,crashed", Eina_Bool*: expects a @c EINA_TRUE if web process crash is handled; @c EINA_FALSE, otherwise. - */ - -#ifndef ewk_view_h -#define ewk_view_h - -#include "ewk_back_forward_list.h" -#include "ewk_color_picker.h" -#include "ewk_context.h" -#include "ewk_context_menu.h" -#include "ewk_download_job.h" -#include "ewk_error.h" -#include "ewk_page_group.h" -#include "ewk_popup_menu.h" -#include "ewk_security_origin.h" -#include "ewk_settings.h" -#include "ewk_touch.h" -#include "ewk_url_request.h" -#include "ewk_url_response.h" -#include "ewk_window_features.h" -#include <Evas.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/// Enum values containing text directionality values. -typedef enum { - EWK_TEXT_DIRECTION_RIGHT_TO_LEFT, - 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; - -/// Ewk view's class, to be overridden by sub-classes. -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); - - Eina_Bool (*popup_menu_show)(Ewk_View_Smart_Data *sd, Eina_Rectangle rect, Ewk_Text_Direction text_direction, double page_scale_factor, Ewk_Popup_Menu *menu); - Eina_Bool (*popup_menu_hide)(Ewk_View_Smart_Data *sd); - - // event handling: - // - returns true if handled - // - if overridden, have to call parent method if desired - Eina_Bool (*focus_in)(Ewk_View_Smart_Data *sd); - Eina_Bool (*focus_out)(Ewk_View_Smart_Data *sd); - Eina_Bool (*fullscreen_enter)(Ewk_View_Smart_Data *sd, Ewk_Security_Origin *origin); - Eina_Bool (*fullscreen_exit)(Ewk_View_Smart_Data *sd); - Eina_Bool (*mouse_wheel)(Ewk_View_Smart_Data *sd, const Evas_Event_Mouse_Wheel *ev); - Eina_Bool (*mouse_down)(Ewk_View_Smart_Data *sd, const Evas_Event_Mouse_Down *ev); - Eina_Bool (*mouse_up)(Ewk_View_Smart_Data *sd, const Evas_Event_Mouse_Up *ev); - Eina_Bool (*mouse_move)(Ewk_View_Smart_Data *sd, const Evas_Event_Mouse_Move *ev); - Eina_Bool (*key_down)(Ewk_View_Smart_Data *sd, const Evas_Event_Key_Down *ev); - Eina_Bool (*key_up)(Ewk_View_Smart_Data *sd, const Evas_Event_Key_Up *ev); - Eina_Bool (*window_geometry_set)(Ewk_View_Smart_Data *sd, Evas_Coord x, Evas_Coord y, Evas_Coord width, Evas_Coord height); - Eina_Bool (*window_geometry_get)(Ewk_View_Smart_Data *sd, Evas_Coord *x, Evas_Coord *y, Evas_Coord *width, Evas_Coord *height); - - // javascript popup: - // - All strings should be guaranteed to be stringshared. - void (*run_javascript_alert)(Ewk_View_Smart_Data *sd, const char *message); - Eina_Bool (*run_javascript_confirm)(Ewk_View_Smart_Data *sd, const char *message); - const char *(*run_javascript_prompt)(Ewk_View_Smart_Data *sd, const char *message, const char *default_value); /**< return string should be stringshared. */ - - // color picker: - // - Shows and hides color picker. - Eina_Bool (*input_picker_color_request)(Ewk_View_Smart_Data *sd, Ewk_Color_Picker *color_picker); - Eina_Bool (*input_picker_color_dismiss)(Ewk_View_Smart_Data *sd); - - // storage: - // - Web database. - unsigned long long (*exceeded_database_quota)(Ewk_View_Smart_Data *sd, const char *databaseName, const char *displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage); - - // window creation and closing: - // - Create a new window with specified features and close window. - 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); -}; - -/** - * The version you have to put into the version field - * in the @a Ewk_View_Smart_Class structure. - */ -#define EWK_VIEW_SMART_CLASS_VERSION 8UL - -/** - * Initializer for whole Ewk_View_Smart_Class structure. - * - * @param smart_class_init initializer to use for the "base" field - * (Evas_Smart_Class). - * - * @see EWK_VIEW_SMART_CLASS_INIT_NULL - * @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, 0} - -/** - * Initializer to zero a whole Ewk_View_Smart_Class structure. - * - * @see EWK_VIEW_SMART_CLASS_INIT_VERSION - * @see EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION - * @see EWK_VIEW_SMART_CLASS_INIT - */ -#define EWK_VIEW_SMART_CLASS_INIT_NULL EWK_VIEW_SMART_CLASS_INIT(EVAS_SMART_CLASS_INIT_NULL) - -/** - * Initializer to zero a whole Ewk_View_Smart_Class structure and set - * name and version. - * - * Similar to EWK_VIEW_SMART_CLASS_INIT_NULL, but will set version field of - * Evas_Smart_Class (base field) to latest EVAS_SMART_CLASS_VERSION and name - * to the specific value. - * - * It will keep a reference to name field as a "const char *", that is, - * name must be available while the structure is used (hint: static or global!) - * and will not be modified. - * - * @see EWK_VIEW_SMART_CLASS_INIT_NULL - * @see EWK_VIEW_SMART_CLASS_INIT_VERSION - * @see EWK_VIEW_SMART_CLASS_INIT - */ -#define EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION(name) EWK_VIEW_SMART_CLASS_INIT(EVAS_SMART_CLASS_INIT_NAME_VERSION(name)) - -typedef struct EwkView EwkView; -/** - * @brief Contains an internal View data. - * - * It is to be considered private by users, but may be extended or - * changed by sub-classes (that's why it's in public header file). - */ -struct Ewk_View_Smart_Data { - Evas_Object_Smart_Clipped_Data base; - 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 */ - EwkView* priv; /**< should never be accessed, c++ stuff */ - struct { - Evas_Coord x, y, w, h; /**< last used viewport */ - } view; - struct { /**< what changed since last smart_calculate */ - Eina_Bool any:1; - Eina_Bool size:1; - Eina_Bool position:1; - } changed; -}; - -/// Creates a type name for Ewk_Download_Job_Error. -typedef struct Ewk_Download_Job_Error Ewk_Download_Job_Error; - -/** - * @brief Structure containing details about a download failure. - */ -struct Ewk_Download_Job_Error { - Ewk_Download_Job *download_job; /**< download that failed */ - 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 - * @info Keep this in sync with WKFindOptions.h - */ -enum Ewk_Find_Options { - EWK_FIND_OPTIONS_NONE, /**< no search flags, this means a case sensitive, no wrap, forward only search. */ - EWK_FIND_OPTIONS_CASE_INSENSITIVE = 1 << 0, /**< case insensitive search. */ - EWK_FIND_OPTIONS_AT_WORD_STARTS = 1 << 1, /**< search text only at the beginning of the words. */ - EWK_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START = 1 << 2, /**< treat capital letters in the middle of words as word start. */ - EWK_FIND_OPTIONS_BACKWARDS = 1 << 3, /**< search backwards. */ - EWK_FIND_OPTIONS_WRAP_AROUND = 1 << 4, /**< if not present search will stop at the end of the document. */ - EWK_FIND_OPTIONS_SHOW_OVERLAY = 1 << 5, /**< show overlay */ - EWK_FIND_OPTIONS_SHOW_FIND_INDICATOR = 1 << 6, /**< show indicator */ - EWK_FIND_OPTIONS_SHOW_HIGHLIGHT = 1 << 7 /**< show highlight */ -}; -typedef enum Ewk_Find_Options Ewk_Find_Options; - -/** - * Enum values used to set pagination mode. - */ -typedef enum { - EWK_PAGINATION_MODE_INVALID = -1, /**< invalid pagination mode that will be returned when error occured. */ - EWK_PAGINATION_MODE_UNPAGINATED, /**< default mode for pagination. not paginated */ - EWK_PAGINATION_MODE_LEFT_TO_RIGHT, /**< go to the next page with scrolling left to right horizontally. */ - EWK_PAGINATION_MODE_RIGHT_TO_LEFT, /**< go to the next page with scrolling right to left horizontally. */ - EWK_PAGINATION_MODE_TOP_TO_BOTTOM, /**< go to the next page with scrolling top to bottom vertically. */ - EWK_PAGINATION_MODE_BOTTOM_TO_TOP /**< go to the next page with scrolling bottom to top vertically. */ -} 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 - * exception of @a Evas_Smart_Class->data may be overridden, must - * @b not be @c NULL - * - * @note @a Evas_Smart_Class->data is used to implement type checking and - * is not supposed to be changed/overridden. If you need extra - * data for your smart class to work, just extend - * Ewk_View_Smart_Class instead. - * The Evas_Object which inherits the ewk_view should use - * ewk_view_smart_add() to create Evas_Object instead of - * evas_object_smart_add() because it performs additional initialization - * for the ewk_view. - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure (probably - * version mismatch) - * - * @see ewk_view_smart_add() - */ -EAPI Eina_Bool ewk_view_smart_class_set(Ewk_View_Smart_Class *api); - -/** - * Creates a new EFL WebKit view object with Evas_Smart and Ewk_Context. - * - * @note The Evas_Object which inherits the ewk_view should create its - * Evas_Object using this API instead of evas_object_smart_add() - * because the default initialization for ewk_view is done in this 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, Ewk_Page_Group *pageGroup); - -/** - * Creates a new EFL WebKit view object. - * - * @param e canvas object where to create the view object - * - * @return view object on success or @c NULL on failure - */ -EAPI Evas_Object *ewk_view_add(Evas *e); - -/** - * Creates a new EFL WebKit view object based on specific Ewk_Context. - * - * @param e canvas object where to create the view object - * @param context Ewk_Context object to declare process model - * - * @return view object on success or @c NULL on failure - */ -EAPI Evas_Object *ewk_view_add_with_context(Evas *e, Ewk_Context *context); - -/** - * Gets the Ewk_Context of this view. - * - * @param o the view object to get the Ewk_Context - * - * @return the Ewk_Context of this view or @c NULL on failure - */ -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 - * @param url uniform resource identifier to load - * - * @return @c EINA_TRUE is returned if @a o is valid, irrespective of load, - * or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_view_url_set(Evas_Object *o, const char *url); - -/** - * Returns the current URL string of view object. - * - * It returns an internal string and should not - * be modified. The string is guaranteed to be stringshared. - * - * @param o view object to get current URL - * - * @return current URL on success or @c NULL on failure - */ -EAPI const char *ewk_view_url_get(const Evas_Object *o); - -/** - * Returns the current favicon of view object. - * - * @param o view object to get current icon URL - * - * @return current favicon on success or @c NULL if unavailable or on failure. - * The returned Evas_Object needs to be freed after use. - */ -EAPI Evas_Object *ewk_view_favicon_get(const Evas_Object *o); - -/** - * Asks the main frame to reload the current document. - * - * @param o view object to reload current document - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise - * - * @see ewk_view_reload_bypass_cache() - */ -EAPI Eina_Bool ewk_view_reload(Evas_Object *o); - -/** - * Reloads the current page's document without cache. - * - * @param o view object to reload current document - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_reload_bypass_cache(Evas_Object *o); - -/** - * Asks the main frame to stop loading. - * - * @param o view object to stop loading - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise. - */ -EAPI Eina_Bool ewk_view_stop(Evas_Object *o); - -/** - * Gets the Ewk_Settings of this view. - * - * @param o view object to get Ewk_Settings - * - * @return the Ewk_Settings of this view or @c NULL on failure - */ -EAPI Ewk_Settings *ewk_view_settings_get(const Evas_Object *o); - -/** - * Asks the main frame to navigate back in the history. - * - * @param o view object to navigate back - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise - * - * @see ewk_frame_back() - */ -EAPI Eina_Bool ewk_view_back(Evas_Object *o); - -/** - * Asks the main frame to navigate forward in the history. - * - * @param o view object to navigate forward - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise - * - * @see ewk_frame_forward() - */ -EAPI Eina_Bool ewk_view_forward(Evas_Object *o); - -/** - * Queries if it is possible to navigate backwards one item in the history. - * - * @param o view object to query if backward navigation is possible - * - * @return @c EINA_TRUE if it is possible to navigate backwards in the history, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_back_possible(Evas_Object *o); - -/** - * Queries if it is possible to navigate forwards one item in the history. - * - * @param o view object to query if forward navigation is possible - * - * @return @c EINA_TRUE if it is possible to navigate forwards in the history, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_forward_possible(Evas_Object *o); - -/** - * Gets the back-forward list associated with this view. - * - * The returned instance is unique for this view and thus multiple calls - * to this function with the same view as parameter returns the same - * handle. This handle is alive while view is alive, thus one - * might want to listen for EVAS_CALLBACK_DEL on given view - * (@a o) to know when to stop using returned handle. - * - * @param o view object to get navigation back-forward list - * - * @return the back-forward list instance handle associated with this view - */ -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 - * be modified. The string is guaranteed to be stringshared. - * - * @param o view object to get current title - * - * @return current title on success or @c NULL on failure - */ -EAPI const char *ewk_view_title_get(const Evas_Object *o); - -/** - * Gets the current load progress of page. - * - * The progress estimation from 0.0 to 1.0. - * - * @param o view object to get the current progress - * - * @return the load progress of page, value from 0.0 to 1.0, - * or @c -1.0 on failure - */ -EAPI double ewk_view_load_progress_get(const Evas_Object *o); - -/** - * Loads the specified @a html string as the content of the view. - * - * External objects such as stylesheets or images referenced in the HTML - * document are located relative to @a baseUrl. - * - * If an @a unreachableUrl is passed it is used as the url for the loaded - * content. This is typically used to display error pages for a failed - * load. - * - * @param o view object to load the HTML into - * @param html HTML data to load - * @param baseUrl Base URL used for relative paths to external objects (optional) - * @param unreachableUrl URL that could not be reached (optional) - * - * @return @c EINA_TRUE if it the HTML was successfully loaded, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_html_string_load(Evas_Object *o, const char *html, const char *baseUrl, const char *unreachableUrl); - -/** - * Scales the current page, centered at the given point. - * - * @param o view object to set the zoom level - * @param scale_factor a new level to set - * @param cx x of center coordinate - * @param cy y of center coordinate - * - * @return @c EINA_TRUE on success or @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_scale_set(Evas_Object *o, double scaleFactor, int x, int y); - -/** - * Queries the current scale factor of the page. - * - * It returns previous scale factor after ewk_view_scale_set is called immediately - * until scale factor of page is really changed. - * - * @param o view object to get the scale factor - * - * @return current scale factor in use on success or @c -1.0 on failure - */ -EAPI double ewk_view_scale_get(const Evas_Object *o); - -/** - * Queries the ratio between the CSS units and device pixels when the content is unscaled. - * - * When designing touch-friendly contents, knowing the approximated target size on a device - * is important for contents providers in order to get the intented layout and element - * sizes. - * - * As most first generation touch devices had a PPI of approximately 160, this became a - * de-facto value, when used in conjunction with the viewport meta tag. - * - * Devices with a higher PPI learning towards 240 or 320, applies a pre-scaling on all - * content, of either 1.5 or 2.0, not affecting the CSS scale or pinch zooming. - * - * This value can be set using this property and it is exposed to CSS media queries using - * the -webkit-device-pixel-ratio query. - * - * For instance, if you want to load an image without having it upscaled on a web view - * using a device pixel ratio of 2.0 it can be done by loading an image of say 100x100 - * pixels but showing it at half the size. - * - * @media (-webkit-min-device-pixel-ratio: 1.5) { - * .icon { - * width: 50px; - * height: 50px; - * url: "/images/icon@2x.png"; // This is actually a 100x100 image - * } - * } - * - * If the above is used on a device with device pixel ratio of 1.5, it will be scaled - * down but still provide a better looking image. - * - * @param o view object to get device pixel ratio - * - * @return the ratio between the CSS units and device pixels, - * or @c -1.0 on failure - */ -EAPI float ewk_view_device_pixel_ratio_get(const Evas_Object *o); - -/** - * Sets the ratio between the CSS units and device pixels when the content is unscaled. - * - * @param o view object to set device pixel ratio - * - * @return @c EINA_TRUE if the device pixel ratio was set, @c EINA_FALSE otherwise - * - * @see ewk_view_device_pixel_ratio_get() - */ -EAPI Eina_Bool ewk_view_device_pixel_ratio_set(Evas_Object *o, float ratio); - -/** - * Sets the theme path that will be used by this view. - * - * This also sets the theme on the main frame. As frames inherit theme - * from their parent, this will have all frames with unset theme to - * use this one. - * - * @param o view object to change theme - * @param path theme path - */ -EAPI void ewk_view_theme_set(Evas_Object *o, const char *path); - -/** - * Gets the theme set on this view. - * - * This returns the value set by ewk_view_theme_set(). - * - * @param o view object to get theme path - * - * @return the theme path, may be @c NULL if not set - */ -EAPI const char *ewk_view_theme_get(const Evas_Object *o); - -/** - * Gets the current custom character encoding name. - * - * @param o view object to get the current encoding - * - * @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); - -/** - * Sets the custom character encoding and reloads the page. - * - * @param o view to set the encoding - * @param encoding the new encoding 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_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. - * - * @param o view object to find text - * @param text text to find - * @param options options to find - * @param max_match_count maximum match count to find, unlimited if 0 - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on errors - */ -EAPI Eina_Bool ewk_view_text_find(Evas_Object *o, const char *text, Ewk_Find_Options options, unsigned max_match_count); - -/** - * Clears the highlight of searched text. - * - * @param o view object to find text - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on errors - */ -EAPI Eina_Bool ewk_view_text_find_highlight_clear(Evas_Object *o); - -/** - * Counts the given string in the document. - * - * This does not highlight the matched string and just count the matched string. - * - * As the search is carried out through the whole document, - * only the following EWK_FIND_OPTIONS are valid. - * - EWK_FIND_OPTIONS_NONE - * - EWK_FIND_OPTIONS_CASE_INSENSITIVE - * - EWK_FIND_OPTIONS_AT_WORD_START - * - EWK_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START - * - * The "text,found" callback will be called with the number of matched string. - * - * @param o view object to find text - * @param text text to find - * @param options options to find - * @param max_match_count maximum match count to find, unlimited if 0 - * - * @return @c EINA_TRUE on success, @c EINA_FALSE on errors - */ -EAPI Eina_Bool ewk_view_text_matches_count(Evas_Object *o, const char *text, Ewk_Find_Options options, unsigned max_match_count); - -/** - * Sets whether the ewk_view supports the mouse events or not. - * - * The ewk_view will support the mouse events if EINA_TRUE or not support the - * mouse events otherwise. The default value is EINA_TRUE. - * - * @param o view object to enable/disable the mouse events - * @param enabled a state to set - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_view_mouse_events_enabled_set(Evas_Object *o, Eina_Bool enabled); - -/** - * Queries if the ewk_view supports the mouse events. - * - * @param o view object to query if the mouse events are enabled - * - * @return @c EINA_TRUE if the mouse events are enabled or @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_mouse_events_enabled_get(const Evas_Object *o); - -/** - * Feeds the touch event to the view. - * - * @param o view object to feed touch event - * @param type the type of touch event - * @param points a list of points (Ewk_Touch_Point) to process - * @param modifiers an Evas_Modifier handle to the list of modifier keys - * registered in the Evas. Users can get the Evas_Modifier from the Evas - * using evas_key_modifier_get() and can set each modifier key using - * evas_key_modifier_on() and evas_key_modifier_off() - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_view_feed_touch_event(Evas_Object *o, Ewk_Touch_Event_Type type, const Eina_List *points, const Evas_Modifier *modifiers); - -/** - * Sets whether the ewk_view supports the touch events or not. - * - * The ewk_view will support the touch events if @c EINA_TRUE or not support the - * touch events otherwise. The default value is @c EINA_FALSE. - * - * @param o view object to enable/disable the touch events - * @param enabled a state to set - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_view_touch_events_enabled_set(Evas_Object *o, Eina_Bool enabled); - -/** - * Queries if the ewk_view supports the touch events. - * - * @param o view object to query if the touch events are enabled - * - * @return @c EINA_TRUE if the touch events are enabled or @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_touch_events_enabled_get(const Evas_Object *o); - -/** - * Show the inspector to debug a web page. - * - * @param o The view to show the inspector. - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - * - * @see ewk_settings_developer_extras_enabled_set() - */ -EAPI Eina_Bool ewk_view_inspector_show(Evas_Object *o); - -/** - * Close the inspector - * - * @param o The view to close the inspector. - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_view_inspector_close(Evas_Object *o); - -/** - * Set pagination mode to the current web page. - * - * @param o view object to set the pagenation mode - * @param mode The Ewk_Pagination_Mode to set - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -EAPI Eina_Bool ewk_view_pagination_mode_set(Evas_Object *o, Ewk_Pagination_Mode mode); - -/** - * Get pagination mode of the current web page. - * - * The default value is EWK_PAGINATION_MODE_UNPAGINATED. - * When error occured, EWK_PAGINATION_MODE_INVALID is returned. - * - * @param o view object to get the pagination mode - * - * @return The pagination mode of the current web page - */ -EAPI Ewk_Pagination_Mode ewk_view_pagination_mode_get(const Evas_Object *o); - -/** - * Exit fullscreen mode. - * - * @param o view object where to exit fullscreen - * - * @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_view_fullscreen_exit(Evas_Object *o); - -/** - * Sets whether the ewk_view background matches page background color. - * - * If enabled sets view background color close to page color on page load. - * This helps to reduce flicker on page scrolling and repainting in places - * where page content is not ready for painting. - * View background color can interfere with semi-transparent pages and is - * disabled by default. - * - * @param o view object to enable/disable background matching - * @param enabled a state to set - * - * @return @c EINA_TRUE on success or @c EINA_FALSE on failure - */ -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 -#endif // ewk_view_h diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h b/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h deleted file mode 100644 index 6de35d91e..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_view_private.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_view_private_h -#define ewk_view_private_h - -#include <Evas.h> -#include <WebKit2/WKBase.h> - -#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 deleted file mode 100644 index 8824cafbe..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_window_features.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2012 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_window_features.h" - -#include "EwkView.h" -#include "WKDictionary.h" -#include "WKNumber.h" -#include "WKString.h" -#include "ewk_window_features_private.h" - -using namespace WebKit; - -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)) -{ - 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; - - WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString(featureName)); - return WKDictionaryGetItemForKey(windowFeatures, key.get()); -} - -bool EwkWindowFeatures::getWindowFeatureBoolValue(WKDictionaryRef windowFeatures, const char* featureName, bool defaultValue) -{ - WKBooleanRef value = static_cast<WKBooleanRef>(getWindowFeatureValue(windowFeatures, featureName)); - - return value ? WKBooleanGetValue(value) : defaultValue; -} - -double EwkWindowFeatures::getWindowFeatureDoubleValue(WKDictionaryRef windowFeatures, const char* featureName, double defaultValue) -{ - WKDoubleRef value = static_cast<WKDoubleRef>(getWindowFeatureValue(windowFeatures, featureName)); - - return value ? WKDoubleGetValue(value) : defaultValue; -} - -void EwkWindowFeatures::setToolbarVisible(bool toolbarVisible) -{ - m_toolbarVisible = toolbarVisible; - m_view->smartCallback<EwkViewCallbacks::ToolbarVisible>().call(&toolbarVisible); -} - -void EwkWindowFeatures::setStatusBarVisible(bool statusBarVisible) -{ - m_statusBarVisible = statusBarVisible; - m_view->smartCallback<EwkViewCallbacks::StatusBarVisible>().call(&statusBarVisible); -} - -void EwkWindowFeatures::setMenuBarVisible(bool menuBarVisible) -{ - m_menuBarVisible = menuBarVisible; - m_view->smartCallback<EwkViewCallbacks::MenuBarVisible>().call(&menuBarVisible); -} - -void EwkWindowFeatures::setResizable(bool resizable) -{ - m_resizable = resizable; - m_view->smartCallback<EwkViewCallbacks::WindowResizable>().call(&resizable); -} - -Eina_Bool ewk_window_features_toolbar_visible_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->toolbarVisible(); -} - -Eina_Bool ewk_window_features_statusbar_visible_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->statusBarVisible(); -} - -Eina_Bool ewk_window_features_scrollbars_visible_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->scrollbarsVisible(); -} - -Eina_Bool ewk_window_features_menubar_visible_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->menuBarVisible(); -} - -Eina_Bool ewk_window_features_locationbar_visible_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->locationBarVisible(); -} - -Eina_Bool ewk_window_features_resizable_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->resizable(); -} - -Eina_Bool ewk_window_features_fullscreen_get(const Ewk_Window_Features* window_features) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl, false); - - return impl->fullScreen(); -} - -void ewk_window_features_geometry_get(const Ewk_Window_Features* window_features, Evas_Coord* x, Evas_Coord* y, Evas_Coord* width, Evas_Coord* height) -{ - EWK_OBJ_GET_IMPL_OR_RETURN(const EwkWindowFeatures, window_features, impl); - - const Evas_Coord_Rectangle& geometry = impl->geometry(); - if (x) - *x = geometry.x; - - if (y) - *y = geometry.y; - - if (width) - *width = geometry.w; - - if (height) - *height = geometry.h; -} diff --git a/Source/WebKit2/UIProcess/API/efl/ewk_window_features.h b/Source/WebKit2/UIProcess/API/efl/ewk_window_features.h deleted file mode 100644 index 8e4367506..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_window_features.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2012 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_window_features.h - * @brief Access to the features of window. - */ - -#ifndef ewk_window_features_h -#define ewk_window_features_h - -#include <Eina.h> -#include <Evas.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Declare Ewk_Window_Features as Ewk_Object. - * - * @see Ewk_Object - */ -typedef struct EwkObject Ewk_Window_Features; - -/** - * Queries the toolbar visibility of the window feature. - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the toolbar should be visible, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_toolbar_visible_get(const Ewk_Window_Features *window_features); - -/** - * Queries the statusbar visibility of the window feature. - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the statusbar should be visible, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_statusbar_visible_get(const Ewk_Window_Features *window_features); - -/** - * Queries the scrollbar visibility of the window feature. - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the scrollbars should be visible, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_scrollbars_visible_get(const Ewk_Window_Features *window_features); - -/** - * Queries the menubar visibility of the window feature. - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the menubar should be visible, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_menubar_visible_get(const Ewk_Window_Features *window_features); - -/** - * Queries the locationbar visibility of the window feature. - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the locationbar should be visible, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_locationbar_visible_get(const Ewk_Window_Features *window_features); - -/** - * Queries if the window is resizable. - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the window should be resizable, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_resizable_get(const Ewk_Window_Features *window_features); - -/** - * Queries the the window is fullscreen - * - * @param window_features the object to get properties - * - * @return @c EINA_TRUE is the window should be fullscreen, @c EINA_FALSE otherwise - */ -EAPI Eina_Bool ewk_window_features_fullscreen_get(const Ewk_Window_Features *window_features); - -/** - * Gets geometry properties of an Ewk_Window_Features. - * - * Properties are returned in the respective pointers. Passing @c NULL to any of - * these pointers will cause that property to not be returned. - * - * @param window_features the window's features - * @param x the pointer to store x position - * @param y the pointer to store y position - * @param w the pointer to store width - * @param h the pointer to store height - */ -EAPI void ewk_window_features_geometry_get(const Ewk_Window_Features *window_features, Evas_Coord *x, Evas_Coord *y, Evas_Coord *w, Evas_Coord *h); - -#ifdef __cplusplus -} -#endif - -#endif // ewk_window_features_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 deleted file mode 100644 index 8ae6c90c1..000000000 --- a/Source/WebKit2/UIProcess/API/efl/ewk_window_features_private.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ewk_window_features_private_h -#define ewk_window_features_private_h - -#include "ewk_object_private.h" -#include <Evas.h> -#include <WebKit2/WKBase.h> -#include <wtf/RefCounted.h> - -class EwkView; - -class EwkWindowFeatures : public EwkObject { -public: - EWK_OBJECT_DECLARE(EwkWindowFeatures) - - static PassRefPtr<EwkWindowFeatures> create(WKDictionaryRef windowFeatures, EwkView* viewImpl) - { - return adoptRef(new EwkWindowFeatures(windowFeatures, viewImpl)); - } - - 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); - - bool statusBarVisible() const { return m_statusBarVisible; } - void setStatusBarVisible(bool statusBarVisible); - - bool scrollbarsVisible() const { return m_scrollbarsVisible; } - void setScrollbarsVisible(bool scrollbarsVisible) { m_scrollbarsVisible = scrollbarsVisible; } - - bool menuBarVisible() const { return m_menuBarVisible; } - void setMenuBarVisible(bool menuBarVisible); - - bool locationBarVisible() const { return m_locationBarVisible; } - void setLocationBarVisible(bool locationBarVisible) { m_locationBarVisible = locationBarVisible; } - - bool resizable() const { return m_resizable; } - void setResizable(bool resizable); - - bool fullScreen() const { return m_fullScreen; } - void setFullScreen(bool fullScreen) { m_fullScreen = fullScreen; } - -private: - EwkWindowFeatures(WKDictionaryRef windowFeatures, EwkView* viewImpl); - - static bool getWindowFeatureBoolValue(WKDictionaryRef windowFeatures, const char* featureName, bool defaultValue); - static double getWindowFeatureDoubleValue(WKDictionaryRef windowFeatures, const char* featureName, double defaultValue); - - EwkView* m_view; - - Evas_Coord_Rectangle m_geometry; - bool m_toolbarVisible; - bool m_statusBarVisible; - bool m_scrollbarsVisible; - bool m_menuBarVisible; - bool m_locationBarVisible; - bool m_resizable; - bool m_fullScreen; -}; - -#endif // ewk_window_features_private_h diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp deleted file mode 100644 index c671cb77c..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "config.h" -#include "EWK2UnitTestBase.h" - -#include "EWK2UnitTestEnvironment.h" -#include <Ecore.h> -#include <glib-object.h> - -extern EWK2UnitTest::EWK2UnitTestEnvironment* environment; - -namespace EWK2UnitTest { - -static Ewk_View_Smart_Class ewk2UnitTestBrowserViewSmartClass() -{ - static Ewk_View_Smart_Class ewkViewClass = EWK_VIEW_SMART_CLASS_INIT_NAME_VERSION("Browser_View"); - return ewkViewClass; -} - -EWK2UnitTestBase::EWK2UnitTestBase() - : m_ecoreEvas(0) - , m_webView(0) - , m_ewkViewClass(ewk2UnitTestBrowserViewSmartClass()) -{ - ewk_view_smart_class_set(&m_ewkViewClass); -} - -void EWK2UnitTestBase::SetUp() -{ - unsigned int width = environment->defaultWidth(); - unsigned int height = environment->defaultHeight(); - -#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); - // 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); - - 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); - evas_object_show(m_webView); - evas_object_focus_set(m_webView, true); -} - -void EWK2UnitTestBase::TearDown() -{ - evas_object_del(m_webView); - ecore_evas_free(m_ecoreEvas); -} - -bool EWK2UnitTestBase::loadUrlSync(const char* url, double timeoutSeconds) -{ - ewk_view_url_set(m_webView, url); - return waitUntilLoadFinished(timeoutSeconds); -} - -class CallbackDataTimer { -public: - explicit CallbackDataTimer(double timeoutSeconds) - : m_done(false) - , m_timer(timeoutSeconds >= 0 ? ecore_timer_add(timeoutSeconds, reinterpret_cast<Ecore_Task_Cb>(timeOutCallback), this) : 0) - , m_didTimeOut(false) - { - } - - virtual ~CallbackDataTimer() - { - if (m_timer) - ecore_timer_del(m_timer); - } - - bool isDone() const { return m_done; } - - void setDone() - { - if (m_timer) { - ecore_timer_del(m_timer); - m_timer = 0; - } - m_done = true; - } - - bool didTimeOut() const { return m_didTimeOut; } - -protected: - bool m_done; - Ecore_Timer* m_timer; - bool m_didTimeOut; - -private: - static bool timeOutCallback(void* userData) - { - CallbackDataTimer* data = static_cast<CallbackDataTimer*>(userData); - data->setTimedOut(); - return ECORE_CALLBACK_CANCEL; - } - - void setTimedOut() - { - m_done = true; - m_timer = 0; - m_didTimeOut = true; - } - -}; - -template <class T> -class CallbackDataExpectedValue : public CallbackDataTimer { -public: - CallbackDataExpectedValue(const T& expectedValue, double timeoutSeconds) - : CallbackDataTimer(timeoutSeconds) - , m_expectedValue(expectedValue) - { - } - - const T& expectedValue() const { return m_expectedValue; } - -private: - T m_expectedValue; -}; - -static void onLoadFinished(void* userData, Evas_Object* webView, void* eventInfo) -{ - UNUSED_PARAM(webView); - UNUSED_PARAM(eventInfo); - - CallbackDataTimer* data = static_cast<CallbackDataTimer*>(userData); - data->setDone(); -} - -bool EWK2UnitTestBase::waitUntilLoadFinished(double timeoutSeconds) -{ - CallbackDataTimer data(timeoutSeconds); - - evas_object_smart_callback_add(m_webView, "load,finished", onLoadFinished, &data); - - while (!data.isDone()) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(m_webView, "load,finished", onLoadFinished); - - return !data.didTimeOut(); -} - -static void onTitleChanged(void* userData, Evas_Object* webView, void*) -{ - CallbackDataExpectedValue<CString>* data = static_cast<CallbackDataExpectedValue<CString>*>(userData); - - if (strcmp(ewk_view_title_get(webView), data->expectedValue().data())) - return; - - data->setDone(); -} - -bool EWK2UnitTestBase::waitUntilTitleChangedTo(const char* expectedTitle, double timeoutSeconds) -{ - CallbackDataExpectedValue<CString> data(expectedTitle, timeoutSeconds); - - evas_object_smart_callback_add(m_webView, "title,changed", onTitleChanged, &data); - - while (!data.isDone()) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(m_webView, "title,changed", onTitleChanged); - - return !data.didTimeOut(); -} - -static void onURLChanged(void* userData, Evas_Object* webView, void*) -{ - CallbackDataExpectedValue<CString>* data = static_cast<CallbackDataExpectedValue<CString>*>(userData); - - if (strcmp(ewk_view_url_get(webView), data->expectedValue().data())) - return; - - data->setDone(); -} - -bool EWK2UnitTestBase::waitUntilURLChangedTo(const char* expectedURL, double timeoutSeconds) -{ - CallbackDataExpectedValue<CString> data(expectedURL, timeoutSeconds); - - evas_object_smart_callback_add(m_webView, "url,changed", onURLChanged, &data); - - while (!data.isDone()) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(m_webView, "url,changed", onURLChanged); - - 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); - evas_event_feed_mouse_move(evas, x, y, 0, 0); - evas_event_feed_mouse_down(evas, button, EVAS_BUTTON_NONE, 0, 0); - 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); - evas_event_feed_mouse_move(evas, x, y, 0, 0); - evas_event_feed_mouse_down(evas, button, EVAS_BUTTON_NONE, 0, 0); -} - -void EWK2UnitTestBase::mouseUp(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_up(evas, button, EVAS_BUTTON_NONE, 0, 0); -} - -void EWK2UnitTestBase::mouseMove(int x, int y) -{ - evas_event_feed_mouse_move(evas_object_evas_get(m_webView), x, y, 0, 0); -} - -void EWK2UnitTestBase::multiDown(int id, int x, int y) -{ - evas_event_feed_multi_down(evas_object_evas_get(m_webView), id, x, y, 0, 0, 0, 0, 0, 0, 0, EVAS_BUTTON_NONE, 0, 0); -} - -void EWK2UnitTestBase::multiUp(int id, int x, int y) -{ - evas_event_feed_multi_up(evas_object_evas_get(m_webView), id, x, y, 0, 0, 0, 0, 0, 0, 0, EVAS_BUTTON_NONE, 0, 0); -} - -void EWK2UnitTestBase::multiMove(int id, int x, int y) -{ - evas_event_feed_multi_move(evas_object_evas_get(m_webView), id, x, y, 0, 0, 0, 0, 0, 0, 0, 0, 0); -} - -} // namespace EWK2UnitTest diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h deleted file mode 100644 index 13efa8bee..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestBase.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef EWK2UnitTestBase_h -#define EWK2UnitTestBase_h - -#include "EWK2UnitTestEnvironment.h" -#include <EWebKit2.h> -#include <Ecore.h> -#include <Ecore_Evas.h> -#include <Eina.h> -#include <Evas.h> -#include <gtest/gtest.h> - -namespace EWK2UnitTest { - -class EWK2UnitTestBase : public ::testing::Test { -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: - EWK2UnitTestBase(); - - virtual void SetUp(); - virtual void TearDown(); - - static const double defaultTimeoutSeconds = 10.0; - - bool loadUrlSync(const char* url, double timeoutSeconds = defaultTimeoutSeconds); - 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); - void multiDown(int id, int x, int y); - void multiUp(int id, int x, int y); - void multiMove(int id, int x, int y); - -private: - Evas_Object* m_webView; - Ecore_Evas* m_ecoreEvas; - Ewk_View_Smart_Class m_ewkViewClass; -}; - -} // namespace EWK2UnitTest - -#endif // EWK2UnitTestBase_h diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp deleted file mode 100644 index e626ee745..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "config.h" -#include "EWK2UnitTestEnvironment.h" - -#include <wtf/text/StringBuilder.h> -#include <wtf/text/StringConcatenate.h> -#include <wtf/text/WTFString.h> - -namespace EWK2UnitTest { - -EWK2UnitTestEnvironment::EWK2UnitTestEnvironment() - : m_defaultWidth(800) - , m_defaultHeight(600) -{ -} - -const char* EWK2UnitTestEnvironment::defaultTestPageUrl() const -{ - return "file://"TEST_RESOURCES_DIR"/default_test_page.html"; -} - -const char* EWK2UnitTestEnvironment::defaultTheme() const -{ - return TEST_THEME_DIR"/default.edj"; -} - -const char* EWK2UnitTestEnvironment::injectedBundleSample() const -{ - return TEST_LIB_DIR "/libewk2UnitTestInjectedBundleSample.so"; -} - -CString EWK2UnitTestEnvironment::urlForResource(const char* resource) -{ - return makeString("file://"TEST_RESOURCES_DIR"/", resource).utf8(); -} - -CString EWK2UnitTestEnvironment::pathForResource(const char* resource) -{ - StringBuilder builder; - builder.appendLiteral(TEST_RESOURCES_DIR "/"); - builder.append(resource); - return builder.toString().utf8(); -} - -CString EWK2UnitTestEnvironment::pathForTheme(const char* theme) -{ - StringBuilder builder; - builder.appendLiteral(TEST_THEME_DIR "/"); - builder.append(theme); - return builder.toString().utf8(); -} - -} // namespace EWK2UnitTest diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h deleted file mode 100644 index 888ca0535..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestEnvironment.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef EWK2UnitTestEnvironment_h -#define EWK2UnitTestEnvironment_h - -#include <gtest/gtest.h> -#include <wtf/text/CString.h> - -namespace EWK2UnitTest { - -class EWK2UnitTestEnvironment : public ::testing::Environment { -public: - EWK2UnitTestEnvironment(); - - const char* defaultTestPageUrl() const; - const char* defaultTheme() const; - const char* injectedBundleSample() const; - CString urlForResource(const char* resource); - CString pathForResource(const char* resource); - CString pathForTheme(const char* theme); - - virtual unsigned int defaultWidth() const { return m_defaultWidth; } - virtual unsigned int defaultHeight() const { return m_defaultHeight; } - -private: - unsigned int m_defaultWidth; - unsigned int m_defaultHeight; -}; - -} // namespace EWK2UnitTest - -#endif // EWK2UnitTestEnvironment_h diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestMain.cpp b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestMain.cpp deleted file mode 100644 index 5352212fb..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestMain.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "EWK2UnitTestBase.h" -#include "EWK2UnitTestEnvironment.h" -#include <getopt.h> - -using namespace EWK2UnitTest; - -EWK2UnitTestEnvironment* environment = 0; - -int main(int argc, char** argv) -{ - ewk_init(); - - ::testing::InitGoogleTest(&argc, argv); - - environment = new EWK2UnitTestEnvironment(); - testing::AddGlobalTestEnvironment(environment); - - int result = RUN_ALL_TESTS(); - - ewk_shutdown(); - - return result; -} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestServer.cpp b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestServer.cpp deleted file mode 100644 index 4ef4cf76f..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestServer.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Copyright (C) 2012 Intel Corporation - * - * 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 "EWK2UnitTestServer.h" - -EWK2UnitTestServer::EWK2UnitTestServer() -{ - SoupAddress* address = soup_address_new("127.0.0.1", SOUP_ADDRESS_ANY_PORT); - soup_address_resolve_sync(address, 0); - - m_soupServer = soup_server_new(SOUP_SERVER_INTERFACE, address, static_cast<char*>(0)); - m_baseURL = soup_uri_new("http://127.0.0.1/"); - soup_uri_set_port(m_baseURL, soup_server_get_port(m_soupServer)); - g_object_unref(address); -} - -EWK2UnitTestServer::~EWK2UnitTestServer() -{ - soup_uri_free(m_baseURL); - g_object_unref(m_soupServer); -} - -void EWK2UnitTestServer::run(SoupServerCallback serverCallback) -{ - soup_server_run_async(m_soupServer); - soup_server_add_handler(m_soupServer, 0, serverCallback, 0, 0); -} - -CString EWK2UnitTestServer::getURLForPath(const char* path) const -{ - SoupURI* soupURL = soup_uri_new_with_base(m_baseURL, path); - char* url = soup_uri_to_string(soupURL, false); - CString urlString = url; - free(url); - soup_uri_free(soupURL); - - return urlString; -} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestServer.h b/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestServer.h deleted file mode 100644 index b967ce409..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/UnitTestUtils/EWK2UnitTestServer.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Copyright (C) 2012 Intel Corporation - * - * 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 EWK2UnitTestServer_h -#define EWK2UnitTestServer_h - -#include <libsoup/soup.h> -#include <wtf/text/CString.h> - -class EWK2UnitTestServer { -public: - EWK2UnitTestServer(); - virtual ~EWK2UnitTestServer(); - - CString getURLForPath(const char* path) const; - void run(SoupServerCallback); - -private: - SoupServer* m_soupServer; - SoupURI* m_baseURL; -}; - -#endif // EWK2UnitTestServer_h - diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/blank.ico b/Source/WebKit2/UIProcess/API/efl/tests/resources/blank.ico Binary files differdeleted file mode 100644 index ea848b991..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/blank.ico +++ /dev/null diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/default_test_page.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/default_test_page.html deleted file mode 100644 index 5d1e00856..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/default_test_page.html +++ /dev/null @@ -1,7 +0,0 @@ -<HTML> -<title>Default Testing Web Page</title> -<BODY> -<H2 align="center">EFL Unit Tests</H2> -<H2 align="center">Default Testing Web Page</H2> -</BODY> -</HTML> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/empty_theme.edj b/Source/WebKit2/UIProcess/API/efl/tests/resources/empty_theme.edj Binary files differdeleted file mode 100644 index 2d6cd0485..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/empty_theme.edj +++ /dev/null diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/file_chooser.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/file_chooser.html deleted file mode 100644 index 4418c6477..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/file_chooser.html +++ /dev/null @@ -1,21 +0,0 @@ -<html> -<head> -<title>File chooser test</title> -<script> -function updateTitle() -{ - var myinput = document.getElementById('myInput'); - var title = "" - for (var i = 0; i < myinput.files.length; i++) { - title += myinput.files[i].name; - if (i < (myinput.files.length - 1)) - title += "|"; - } - document.title = title; -} -</script> -</head> -<body> -<input type="file" id="myInput" name="Upload media" accept="image/*,video/*" multiple="multiple" onchange="updateTitle()" style="top: 10; left: 10;"/> -</body> -</html> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/frame_flattening_test.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/frame_flattening_test.html deleted file mode 100644 index 6367992bb..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/frame_flattening_test.html +++ /dev/null @@ -1,4 +0,0 @@ -<!doctype html> -<body onload="document.title=document.getElementById('test').offsetWidth;"> -<iframe id="test" src="./frame_flattening_test_subframe.html" width="200" frameborder="0"></iframe> -</body> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/frame_flattening_test_subframe.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/frame_flattening_test_subframe.html deleted file mode 100644 index 56ef7c9bd..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/frame_flattening_test_subframe.html +++ /dev/null @@ -1,11 +0,0 @@ -<!doctype html> -<head> -<style> -body { -width:600px; -margin:0px; -padding:0px; -} -</style> -</head> -<body></body> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/local_file_access.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/local_file_access.html deleted file mode 100644 index a71fbf976..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/local_file_access.html +++ /dev/null @@ -1,31 +0,0 @@ -<html> -<head> -<script> -function checkFrameLoaded() -{ - var myframe = document.getElementById('myframe'); - var testWindow = myframe.contentWindow; - var state = null; - try { - var state = testWindow.document.readyState; - if (state == "complete") { - document.title = "Frame loaded"; - return; - } - } catch(e) {} - document.title = "Frame NOT loaded"; -} - -function loadFrame() -{ - var myframe = document.getElementById('myframe'); - myframe.src = "default_test_page.html"; - - setTimeout("checkFrameLoaded()", 300); -} -</script> -</head> -<body onload="loadFrame()"> -<iframe id="myframe"></iframe> -</body> -</html> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/redirect_url_to_default.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/redirect_url_to_default.html deleted file mode 100644 index 846fd1113..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/redirect_url_to_default.html +++ /dev/null @@ -1,6 +0,0 @@ -<!doctype html> -<body> -<script> -location.href="./default_test_page.html"; -</script> -</body> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/same_page_navigation.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/same_page_navigation.html deleted file mode 100644 index 7b64b214b..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/same_page_navigation.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> -<body> -<a id="myLink" href="#"><div style="position: absolute; top: 0; left: 0; width: 100px; height: 100px;"></div></a> -</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 deleted file mode 100644 index 635eebd12..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/spelling_selection_tests.html +++ /dev/null @@ -1,46 +0,0 @@ -<!-- - 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/resources/spelling_test.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/spelling_test.html deleted file mode 100644 index bf93820f1..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/spelling_test.html +++ /dev/null @@ -1,23 +0,0 @@ -<!-- - The page contains the input field element which is filled - with the misspelled word to perform spelling. ---> -<HTML> -<HEAD> - <TITLE>Testing Web Page for Spelling</TITLE> - <SCRIPT> - function setInputFieldValue() - { - // The input field has to be focused before typing to it. - document.getElementById("input").focus(); - - // 'Space' notifies WebKit that word has been inserted. - document.getElementById("input").value = "aa "; - } - </SCRIPT> -</HEAD> - -<BODY onload="setInputFieldValue()"> -<INPUT type="text" id="input"> -</BODY> -</HTML> diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/test.pdf b/Source/WebKit2/UIProcess/API/efl/tests/resources/test.pdf Binary files differdeleted file mode 100644 index 2424c19d9..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/test.pdf +++ /dev/null diff --git a/Source/WebKit2/UIProcess/API/efl/tests/resources/window_move_resize.html b/Source/WebKit2/UIProcess/API/efl/tests/resources/window_move_resize.html deleted file mode 100644 index 693ac2ef2..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/resources/window_move_resize.html +++ /dev/null @@ -1,15 +0,0 @@ -<html> -<head> -<title>Window move and resize test</title> -<script> -function test() -{ - window.resizeTo(200, 100); - window.moveTo(150, 200); - document.title = "Moved and resized"; -} -</script> -</head> -<body onload="test()"> -</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 deleted file mode 100644 index 0a7032d0d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_auth_request.cpp +++ /dev/null @@ -1,192 +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" -#include <wtf/PassOwnPtr.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -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>"; - -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); - } - - static void onAuthenticationRequest(void* userData, Evas_Object*, void* eventInfo) - { - Ewk_Auth_Request** returnRequest = static_cast<Ewk_Auth_Request**>(userData); - ASSERT_TRUE(returnRequest); - - Ewk_Auth_Request* request = static_cast<Ewk_Auth_Request*>(eventInfo); - ASSERT_TRUE(request); - - *returnRequest = ewk_object_ref(request); - } - - static void onLoadFinished(void* userData, Evas_Object*, void*) - { - bool* isFinished = static_cast<bool*>(userData); - ASSERT_TRUE(isFinished); - - *isFinished = true; - } -}; - -TEST_F(EWK2AuthRequestTest, ewk_auth_request_success) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - Ewk_Auth_Request* authenticationRequest = 0; - evas_object_smart_callback_add(webView(), "authentication,request", onAuthenticationRequest, &authenticationRequest); - - ewk_view_url_set(webView(), httpServer->getURLForPath("/index.html").data()); - - while (!authenticationRequest) - ecore_main_loop_iterate(); - - ASSERT_TRUE(authenticationRequest); - evas_object_smart_callback_del(webView(), "authentication,request", onAuthenticationRequest); - - EXPECT_STREQ("my realm", ewk_auth_request_realm_get(authenticationRequest)); - 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, testUsername, testPassword)); - - ewk_object_unref(authenticationRequest); - - ASSERT_TRUE(waitUntilTitleChangedTo(expectedSuccessTitle)); -} - -TEST_F(EWK2AuthRequestTest, ewk_auth_request_failure_then_success) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - Ewk_Auth_Request* authenticationRequest = 0; - evas_object_smart_callback_add(webView(), "authentication,request", onAuthenticationRequest, &authenticationRequest); - - ewk_view_url_set(webView(), httpServer->getURLForPath("/index.html").data()); - - while (!authenticationRequest) - ecore_main_loop_iterate(); - - ASSERT_TRUE(authenticationRequest); - - EXPECT_STREQ("my realm", ewk_auth_request_realm_get(authenticationRequest)); - 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, testUsername, "wrongpassword")); - - ewk_object_unref(authenticationRequest); - authenticationRequest = 0; - - // We expect a second authentication request since the first one failed. - while (!authenticationRequest) - ecore_main_loop_iterate(); - evas_object_smart_callback_del(webView(), "authentication,request", onAuthenticationRequest); - - EXPECT_STREQ("my realm", ewk_auth_request_realm_get(authenticationRequest)); - EXPECT_STREQ("127.0.0.1", ewk_auth_request_host_get(authenticationRequest)); - EXPECT_TRUE(ewk_auth_request_retrying_get(authenticationRequest)); - - // Now provide the right password. - ASSERT_TRUE(ewk_auth_request_authenticate(authenticationRequest, testUsername, testPassword)); - - ewk_object_unref(authenticationRequest); - - ASSERT_TRUE(waitUntilTitleChangedTo(expectedSuccessTitle)); -} - -TEST_F(EWK2AuthRequestTest, ewk_auth_request_cancel) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - Ewk_Auth_Request* authenticationRequest = 0; - evas_object_smart_callback_add(webView(), "authentication,request", onAuthenticationRequest, &authenticationRequest); - - ewk_view_url_set(webView(), httpServer->getURLForPath("/index.html").data()); - - while (!authenticationRequest) - ecore_main_loop_iterate(); - - ASSERT_TRUE(authenticationRequest); - evas_object_smart_callback_del(webView(), "authentication,request", onAuthenticationRequest); - - EXPECT_STREQ("my realm", ewk_auth_request_realm_get(authenticationRequest)); - EXPECT_STREQ("127.0.0.1", ewk_auth_request_host_get(authenticationRequest)); - EXPECT_FALSE(ewk_auth_request_retrying_get(authenticationRequest)); - - 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 (!isFinished) - ecore_main_loop_iterate(); - - ASSERT_STRNE(expectedSuccessTitle, ewk_view_title_get(webView())); - - 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 deleted file mode 100644 index 400f5430d..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_back_forward_list.cpp +++ /dev/null @@ -1,271 +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" -#include "WKEinaSharedString.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -using namespace EWK2UnitTest; -using namespace WTF; - -extern EWK2UnitTestEnvironment* environment; - -static const char title1[] = "Page1"; -static const char title2[] = "Page2"; -static const char title3[] = "Page3"; - -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); -} - -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)); - } - - 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; - } - - void freeEinaList(Eina_List* list) - { - void* data = 0; - EINA_LIST_FREE(list, data) - ewk_object_unref(static_cast<Ewk_Object*>(data)); - } -}; - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_current_item_get) -{ - const char* url = environment->defaultTestPageUrl(); - ASSERT_TRUE(loadUrlSync(url)); - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - Ewk_Back_Forward_List_Item* currentItem = ewk_back_forward_list_current_item_get(backForwardList); - checkItem(currentItem, ewk_view_title_get(webView()), url, url); - - Ewk_Back_Forward_List_Item* anotherCurrentItem = ewk_back_forward_list_current_item_get(backForwardList); - ASSERT_EQ(currentItem, anotherCurrentItem); -} - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_previous_item_get) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - WKEinaSharedString url1 = urlFromTitle(httpServer.get(), title1); - ASSERT_TRUE(loadUrlSync(url1)); - ASSERT_STREQ(title1, ewk_view_title_get(webView())); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title2))); - ASSERT_STREQ(title2, ewk_view_title_get(webView())); - - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - Ewk_Back_Forward_List_Item* previousItem = ewk_back_forward_list_previous_item_get(backForwardList); - checkItem(previousItem, title1, url1, url1); - - Ewk_Back_Forward_List_Item* anotherPreviousItem = ewk_back_forward_list_previous_item_get(backForwardList); - ASSERT_EQ(previousItem, anotherPreviousItem); -} - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_next_item_get) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title1))); - ASSERT_STREQ(title1, ewk_view_title_get(webView())); - - WKEinaSharedString url2 = urlFromTitle(httpServer.get(), title2); - ASSERT_TRUE(loadUrlSync(url2)); - ASSERT_STREQ(title2, ewk_view_title_get(webView())); - - // Go back to Page1. - ewk_view_back(webView()); - ASSERT_TRUE(waitUntilTitleChangedTo(title1)); - - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - Ewk_Back_Forward_List_Item* nextItem = ewk_back_forward_list_next_item_get(backForwardList); - checkItem(nextItem, title2, url2, url2); - - Ewk_Back_Forward_List_Item* anotherNextItem = ewk_back_forward_list_next_item_get(backForwardList); - ASSERT_EQ(nextItem, anotherNextItem); -} - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_item_at_index_get) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - WKEinaSharedString url1 = urlFromTitle(httpServer.get(), title1); - ASSERT_TRUE(loadUrlSync(url1)); - ASSERT_STREQ(title1, ewk_view_title_get(webView())); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title2))); - ASSERT_STREQ(title2, ewk_view_title_get(webView())); - - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - Ewk_Back_Forward_List_Item* previousItem = ewk_back_forward_list_item_at_index_get(backForwardList, -1); - checkItem(previousItem, title1, url1, url1); - - Ewk_Back_Forward_List_Item* anotherPreviousItem = ewk_back_forward_list_item_at_index_get(backForwardList, -1); - ASSERT_EQ(previousItem, anotherPreviousItem); - - Ewk_Back_Forward_List_Item* nonExistingItem = ewk_back_forward_list_item_at_index_get(backForwardList, 10); - ASSERT_FALSE(nonExistingItem); -} - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_count) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title1))); - ASSERT_STREQ(title1, ewk_view_title_get(webView())); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title2))); - ASSERT_STREQ(title2, ewk_view_title_get(webView())); - - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - EXPECT_EQ(2, ewk_back_forward_list_count(backForwardList)); -} - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_n_back_items_copy) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - WKEinaSharedString url1 = urlFromTitle(httpServer.get(), title1); - ASSERT_TRUE(loadUrlSync(url1)); - ASSERT_STREQ(title1, ewk_view_title_get(webView())); - - WKEinaSharedString url2 = urlFromTitle(httpServer.get(), title2); - ASSERT_TRUE(loadUrlSync(url2)); - ASSERT_STREQ(title2, ewk_view_title_get(webView())); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title3))); - ASSERT_STREQ(title3, ewk_view_title_get(webView())); - - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - Eina_List* backList = ewk_back_forward_list_n_back_items_copy(backForwardList, 1); - ASSERT_TRUE(backList); - ASSERT_EQ(1, eina_list_count(backList)); - checkItem(static_cast<Ewk_Back_Forward_List_Item*>(eina_list_nth(backList, 0)), title2, url2, url2); - freeEinaList(backList); - - // Check '0' limit. - backList = ewk_back_forward_list_n_back_items_copy(backForwardList, 0); - ASSERT_FALSE(backList); - - backList = ewk_back_forward_list_n_back_items_copy(backForwardList, -1); - ASSERT_TRUE(backList); - ASSERT_EQ(2, eina_list_count(backList)); - checkItem(static_cast<Ewk_Back_Forward_List_Item*>(eina_list_nth(backList, 0)), title1, url1, url1); - checkItem(static_cast<Ewk_Back_Forward_List_Item*>(eina_list_nth(backList, 1)), title2, url2, url2); - freeEinaList(backList); -} - -TEST_F(EWK2BackForwardListTest, ewk_back_forward_list_n_forward_items_copy) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - ASSERT_TRUE(loadUrlSync(urlFromTitle(httpServer.get(), title1))); - ASSERT_STREQ(title1, ewk_view_title_get(webView())); - - WKEinaSharedString url2 = urlFromTitle(httpServer.get(), title2); - ASSERT_TRUE(loadUrlSync(url2)); - ASSERT_STREQ(title2, ewk_view_title_get(webView())); - - WKEinaSharedString url3 = urlFromTitle(httpServer.get(), title3); - ASSERT_TRUE(loadUrlSync(url3)); - ASSERT_STREQ(title3, ewk_view_title_get(webView())); - - // Go back to Page1. - ewk_view_back(webView()); - ASSERT_TRUE(waitUntilTitleChangedTo(title2)); - ewk_view_back(webView()); - ASSERT_TRUE(waitUntilTitleChangedTo(title1)); - - Ewk_Back_Forward_List* backForwardList = ewk_view_back_forward_list_get(webView()); - ASSERT_TRUE(backForwardList); - - Eina_List* forwardList = ewk_back_forward_list_n_forward_items_copy(backForwardList, 1); - ASSERT_TRUE(forwardList); - ASSERT_EQ(1, eina_list_count(forwardList)); - checkItem(static_cast<Ewk_Back_Forward_List_Item*>(eina_list_nth(forwardList, 0)), title2, url2, url2); - freeEinaList(forwardList); - - // Check '0' limit. - forwardList = ewk_back_forward_list_n_forward_items_copy(backForwardList, 0); - ASSERT_FALSE(forwardList); - - forwardList = ewk_back_forward_list_n_forward_items_copy(backForwardList, -1); - ASSERT_TRUE(forwardList); - ASSERT_EQ(2, eina_list_count(forwardList)); - checkItem(static_cast<Ewk_Back_Forward_List_Item*>(eina_list_nth(forwardList, 0)), title2, url2, url2); - checkItem(static_cast<Ewk_Back_Forward_List_Item*>(eina_list_nth(forwardList, 1)), title3, url3, url3); - freeEinaList(forwardList); -} 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 deleted file mode 100644 index f61631e97..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_color_picker.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -#if ENABLE(INPUT_TYPE_COLOR) -static const int initialRed = 0x12; -static const int initialGreen = 0x34; -static const int initialBlue = 0x56; -static const int initialAlpha = 0xff; -static const int changedRed = 0x98; -static const int changedGreen = 0x76; -static const int changedBlue = 0x54; -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); - - *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; - - 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; - } - - 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); - } - -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(EWK2ColorPickerTest, ewk_color_picker_color_set) -{ - Ewk_View_Smart_Class* api = ewkViewClass(); - api->input_picker_color_request = showColorPicker; - api->input_picker_color_dismiss = hideColorPicker; - - const char colorPickerHTML[] = - "<!DOCTYPE html>" - "<html>" - "<head>" - "<script>function removeInputElement(){" - "var parentElement = document.getElementById('parent');" - "var inputElement = document.getElementById('color');" - "parentElement.removeChild(inputElement);" - "}</script>" - "</head>" - "<body>" - "<div id='parent'>" - "<input type='color' value='#123456' id='color'>" - "<button onclick='removeInputElement();'>Remove Element</button>" - "</div>" - "</body>" - "</html>"; - - ewk_view_html_string_load(webView(), colorPickerHTML, 0, 0); - waitUntilLoadFinished(); - - clickButton(ShowColorPickerButton); - - bool handled = false; - evas_object_smart_callback_add(webView(), "input,type,color,request", onColorPickerDone, &handled); - while (!handled) - ecore_main_loop_iterate(); - - clickButton(ShowColorPickerButton); - - handled = false; - while (!handled) - ecore_main_loop_iterate(); - - api->input_picker_color_dismiss = hideColorPickerByRemovingElement; - clickButton(HideColorPickerButton); - - handled = false; - while (!handled) - ecore_main_loop_iterate(); - evas_object_smart_callback_del(webView(), "input,type,color,request", onColorPickerDone); -} -#endif // ENABLE(INPUT_TYPE_COLOR) diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp deleted file mode 100644 index f9db0ef26..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -static const char htmlReply[] = "<html><head><title>Foo</title></head><body>Bar</body></html>"; - -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(EWK2ContextTest, ewk_context_cookie_manager_get) -{ - Ewk_Context* context = ewk_view_context_get(webView()); - Ewk_Cookie_Manager* cookieManager = ewk_context_cookie_manager_get(context); - ASSERT_TRUE(cookieManager); - ASSERT_EQ(cookieManager, ewk_context_cookie_manager_get(context)); -} - -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); - ASSERT_TRUE(databaseManager); - ASSERT_EQ(databaseManager, ewk_context_database_manager_get(context)); -} - -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); - ASSERT_TRUE(faviconDatabase); - ASSERT_EQ(faviconDatabase, ewk_context_favicon_database_get(context)); -} - -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); - ASSERT_TRUE(storageManager); - ASSERT_EQ(storageManager, ewk_context_storage_manager_get(context)); -} - -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(EWK2ContextTest, ewk_context_cache_model) -{ - Ewk_Context* context = ewk_view_context_get(webView()); - - ASSERT_EQ(EWK_CACHE_MODEL_DOCUMENT_VIEWER, ewk_context_cache_model_get(context)); - - ASSERT_TRUE(ewk_context_cache_model_set(context, EWK_CACHE_MODEL_DOCUMENT_BROWSER)); - ASSERT_EQ(EWK_CACHE_MODEL_DOCUMENT_BROWSER, ewk_context_cache_model_get(context)); - - ASSERT_TRUE(ewk_context_cache_model_set(context, EWK_CACHE_MODEL_PRIMARY_WEBBROWSER)); - ASSERT_EQ(EWK_CACHE_MODEL_PRIMARY_WEBBROWSER, ewk_context_cache_model_get(context)); - - ASSERT_TRUE(ewk_context_cache_model_set(context, EWK_CACHE_MODEL_DOCUMENT_VIEWER)); - ASSERT_EQ(EWK_CACHE_MODEL_DOCUMENT_VIEWER, ewk_context_cache_model_get(context)); -} - -TEST_F(EWK2ContextTest, ewk_context_new) -{ - Ewk_Context* context = ewk_context_new(); - ASSERT_TRUE(context); - ewk_object_unref(context); -} - -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(EWK2ContextTest, ewk_context_additional_plugin_path_set) -{ - Ewk_Context* context = ewk_view_context_get(webView()); - - ASSERT_FALSE(ewk_context_additional_plugin_path_set(context, 0)); - - ASSERT_TRUE(ewk_context_additional_plugin_path_set(context, "/plugins")); - - /* FIXME: Get additional plugin path and compare with the path. */ -} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_history_callbacks.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_history_callbacks.cpp deleted file mode 100644 index d08b375dd..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_history_callbacks.cpp +++ /dev/null @@ -1,179 +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 const char defaultTitle[] = "Default Testing Web Page"; - -static const char toBeRedirectedPath[] = "/some_page_to_be_redirected"; -static const char redirectionTargetPath[] = "/redirection_target"; - -static EWK2UnitTestServer* httpServer() -{ - static EWK2UnitTestServer* server = 0; - - if (!server) - server = new EWK2UnitTestServer; - - return server; -} - -#define DECLARE_INVOKE_FLAG(functionName) \ - static bool functionName##Invoked = false; - -#define WAS_INVOKED(functionName) \ - if (functionName##Invoked) \ - return; \ - functionName##Invoked = true - -#define CHECK_WAS_INVOKED(functionName) \ - ASSERT_TRUE(functionName##Invoked) - -DECLARE_INVOKE_FLAG(navigateWithNavigationData) -DECLARE_INVOKE_FLAG(performClientRedirect) -DECLARE_INVOKE_FLAG(performServerRedirect) -DECLARE_INVOKE_FLAG(updateHistoryTitle) -DECLARE_INVOKE_FLAG(populateVisitedLinks) - -static void navigateWithNavigationData(const Evas_Object* view, Ewk_Navigation_Data* navigationData, void* userData) -{ - WAS_INVOKED(navigateWithNavigationData); - - EWK2UnitTestBase* unitTest = static_cast<EWK2UnitTestBase*>(userData); - ASSERT_TRUE(unitTest); - ASSERT_EQ(unitTest->webView(), view); - // FIXME: WebFrameLoaderClient sends empty title. - // ASSERT_STREQ(defaultTitle, ewk_navigation_data_title_get(navigationData)); - ASSERT_STREQ(environment->defaultTestPageUrl(), ewk_navigation_data_url_get(navigationData)); - - Ewk_Url_Request* request = ewk_navigation_data_original_request_get(navigationData); - ASSERT_STREQ("GET", ewk_url_request_http_method_get(request)); - ASSERT_STREQ(environment->defaultTestPageUrl(), ewk_url_request_url_get(request)); - ASSERT_EQ(0, ewk_request_cookies_first_party_get(request)); -} - -static void performClientRedirect(const Evas_Object* view, const char* sourceUrl, const char* destinationUrl, void* userData) -{ - WAS_INVOKED(performClientRedirect); - - EWK2UnitTestBase* unitTest = static_cast<EWK2UnitTestBase*>(userData); - ASSERT_TRUE(unitTest); - ASSERT_EQ(unitTest->webView(), view); - ASSERT_STREQ(environment->urlForResource("redirect_url_to_default.html").data(), sourceUrl); - ASSERT_STREQ(environment->defaultTestPageUrl(), destinationUrl); -} - -static void performServerRedirect(const Evas_Object* view, const char* sourceUrl, const char* destinationUrl, void* userData) -{ - WAS_INVOKED(performServerRedirect); - - EWK2UnitTestBase* unitTest = static_cast<EWK2UnitTestBase*>(userData); - ASSERT_TRUE(unitTest); - ASSERT_EQ(unitTest->webView(), view); - ASSERT_STREQ(httpServer()->getURLForPath(toBeRedirectedPath).data(), sourceUrl); - ASSERT_STREQ(httpServer()->getURLForPath(redirectionTargetPath).data(), destinationUrl); -} - -static void updateHistoryTitle(const Evas_Object* view, const char* title, const char* url, void* userData) -{ - WAS_INVOKED(updateHistoryTitle); - - EWK2UnitTestBase* unitTest = static_cast<EWK2UnitTestBase*>(userData); - ASSERT_TRUE(unitTest); - ASSERT_EQ(unitTest->webView(), view); - ASSERT_STREQ(defaultTitle, title); - ASSERT_STREQ(environment->defaultTestPageUrl(), url); -} - -static void populateVisitedLinks(void* userData) -{ - WAS_INVOKED(populateVisitedLinks); - - EWK2UnitTestBase* unitTest = static_cast<EWK2UnitTestBase*>(userData); - ASSERT_TRUE(unitTest); -} - -static void onLoadFinishedForRedirection(void* userData, Evas_Object*, void*) -{ - int* countLoadFinished = static_cast<int*>(userData); - --(*countLoadFinished); -} - -static void serverCallbackRedirection(SoupServer*, 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, redirectionTargetPath)) { // Redirect if 'path' is not equal to 'redirectionTargetPath'. - soup_message_set_status(message, SOUP_STATUS_TEMPORARY_REDIRECT); - soup_message_headers_append(message->response_headers, "Location", httpServer()->getURLForPath(redirectionTargetPath).data()); - return; - } - - soup_message_set_status(message, SOUP_STATUS_OK); - Eina_Strbuf* body = eina_strbuf_new(); - eina_strbuf_append_printf(body, "<html><title>Redirection Target</title></html>"); - 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_context_history_callbacks_set) -{ - ewk_context_history_callbacks_set(ewk_view_context_get(webView()), navigateWithNavigationData, performClientRedirect, performServerRedirect, updateHistoryTitle, populateVisitedLinks, this); - - // Test navigation. - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - CHECK_WAS_INVOKED(navigateWithNavigationData); - CHECK_WAS_INVOKED(updateHistoryTitle); - CHECK_WAS_INVOKED(populateVisitedLinks); - - // Test client redirect. - int countLoadFinished = 2; - evas_object_smart_callback_add(webView(), "load,finished", onLoadFinishedForRedirection, &countLoadFinished); - ewk_view_url_set(webView(), environment->urlForResource("redirect_url_to_default.html").data()); - while (countLoadFinished) - ecore_main_loop_iterate(); - evas_object_smart_callback_del(webView(), "load,finished", onLoadFinishedForRedirection); - CHECK_WAS_INVOKED(performClientRedirect); - - // Test server redirect. - httpServer()->run(serverCallbackRedirection); - - ASSERT_TRUE(loadUrlSync(httpServer()->getURLForPath(toBeRedirectedPath).data())); - CHECK_WAS_INVOKED(performServerRedirect); -} - 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 deleted file mode 100644 index fba0ee790..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_context_menu.cpp +++ /dev/null @@ -1,227 +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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" -#include "UnitTestUtils/EWK2UnitTestEnvironment.h" -#include <EWebKit2.h> -#include <Ecore.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -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; - } - - /** - * 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 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(EWK2ContextMenuTest, ewk_context_menu_custom_items) -{ - const char* itemSelectHTML = - "<html>" - "<body><a href=http://www.google.com>Test Link</a></body>" - "</html>"; - - ewkViewClass()->custom_item_selected = customItemSelected; - ewkViewClass()->context_menu_show = testContextMenuForRemoveAndAppend; - ewkViewClass()->context_menu_hide = finishTest; - - ewk_view_html_string_load(webView(), itemSelectHTML, "file:///", 0); - 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 deleted file mode 100644 index 881ce174b..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_cookie_manager.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (C) 2012 Igalia S.L. - * Copyright (C) 2012 Intel Corporation - * - * 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 "UnitTestUtils/EWK2UnitTestBase.h" -#include "UnitTestUtils/EWK2UnitTestServer.h" -#include <stdlib.h> -#include <unistd.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -using namespace EWK2UnitTest; -using namespace WTF; - -extern EWK2UnitTestEnvironment* environment; - -static const char FIRST_PARTY_DOMAIN[] = "127.0.0.1"; -static const char THIRD_PARTY_DOMAIN[] = "localhost"; -static const char INDEX_HTML_STRING[] = - "<html><body>" - " <p>EFLWebKit2 Cookie Manager test</p>" - " <img src='http://localhost:%u/image.png' width=5 height=5></img>" - "</body></html>"; - -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); - } - - 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); - - 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 void onCookiesChanged(void *eventInfo) - { - bool* cookiesChanged = static_cast<bool*>(eventInfo); - *cookiesChanged = true; - } - -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; - } - - 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; - } - - 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(EWK2CookieManagerTest, ewk_cookie_manager_accept_policy) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - Ewk_Cookie_Manager* cookieManager = ewk_context_cookie_manager_get(ewk_view_context_get(webView())); - ASSERT_TRUE(cookieManager); - - // Default policy is EWK_COOKIE_ACCEPT_POLICY_NO_THIRD_PARTY. - ASSERT_EQ(EWK_COOKIE_ACCEPT_POLICY_NO_THIRD_PARTY, getAcceptPolicy(cookieManager)); - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - - Eina_List* hostnames = getHostnamesWithCookies(cookieManager); - ASSERT_EQ(1, eina_list_count(hostnames)); - ASSERT_STREQ(FIRST_PARTY_DOMAIN, static_cast<char*>(eina_list_nth(hostnames, 0))); - freeHostNames(hostnames); - ewk_cookie_manager_cookies_clear(cookieManager); - - // Change policy to EWK_COOKIE_ACCEPT_POLICY_ALWAYS - ewk_cookie_manager_accept_policy_set(cookieManager, EWK_COOKIE_ACCEPT_POLICY_ALWAYS); - ASSERT_EQ(EWK_COOKIE_ACCEPT_POLICY_ALWAYS, getAcceptPolicy(cookieManager)); - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - - hostnames = getHostnamesWithCookies(cookieManager); - ASSERT_EQ(2, eina_list_count(hostnames)); - hostnames = eina_list_sort(hostnames, eina_list_count(hostnames), compareHostNames); - ASSERT_STREQ(FIRST_PARTY_DOMAIN, static_cast<char*>(eina_list_nth(hostnames, 0))); - ASSERT_STREQ(THIRD_PARTY_DOMAIN, static_cast<char*>(eina_list_nth(hostnames, 1))); - freeHostNames(hostnames); - ewk_cookie_manager_cookies_clear(cookieManager); - - // Change policy to EWK_COOKIE_ACCEPT_POLICY_NEVER - ewk_cookie_manager_accept_policy_set(cookieManager, EWK_COOKIE_ACCEPT_POLICY_NEVER); - ASSERT_EQ(EWK_COOKIE_ACCEPT_POLICY_NEVER, getAcceptPolicy(cookieManager)); - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); -} - -TEST_F(EWK2CookieManagerTest, ewk_cookie_manager_changes_watch) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - Ewk_Cookie_Manager* cookieManager = ewk_context_cookie_manager_get(ewk_view_context_get(webView())); - ASSERT_TRUE(cookieManager); - - ewk_cookie_manager_accept_policy_set(cookieManager, EWK_COOKIE_ACCEPT_POLICY_ALWAYS); - ASSERT_EQ(EWK_COOKIE_ACCEPT_POLICY_ALWAYS, getAcceptPolicy(cookieManager)); - - // Watch for changes - bool cookiesChanged = false; - ewk_cookie_manager_changes_watch(cookieManager, onCookiesChanged, &cookiesChanged); - - // Check for cookie changes notifications - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - - while (!cookiesChanged) - ecore_main_loop_iterate(); - ASSERT_TRUE(cookiesChanged); - - cookiesChanged = false; - ewk_cookie_manager_cookies_clear(cookieManager); - while (!cookiesChanged) - ecore_main_loop_iterate(); - ASSERT_TRUE(cookiesChanged); - - // Stop watching for notifications - ewk_cookie_manager_changes_watch(cookieManager, 0, 0); - cookiesChanged = false; - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - ASSERT_FALSE(cookiesChanged); - - // Watch again for notifications - ewk_cookie_manager_changes_watch(cookieManager, onCookiesChanged, &cookiesChanged); - - // Make sure we don't get notifications when loading setting an existing persistent storage - char textStorage1[] = "/tmp/txt-cookie.XXXXXX"; - ASSERT_TRUE(mktemp(textStorage1)); - char textStorage2[] = "/tmp/txt-cookie.XXXXXX"; - ASSERT_TRUE(mktemp(textStorage2)); - - ewk_cookie_manager_persistent_storage_set(cookieManager, textStorage1, EWK_COOKIE_PERSISTENT_STORAGE_TEXT); - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - - cookiesChanged = false; - ewk_cookie_manager_persistent_storage_set(cookieManager, textStorage2, EWK_COOKIE_PERSISTENT_STORAGE_TEXT); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); - - ewk_cookie_manager_persistent_storage_set(cookieManager, textStorage1, EWK_COOKIE_PERSISTENT_STORAGE_TEXT); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - - ASSERT_FALSE(cookiesChanged); - - // Final clean up. - ewk_cookie_manager_changes_watch(cookieManager, 0, 0); - unlink(textStorage1); - unlink(textStorage2); -} - -TEST_F(EWK2CookieManagerTest, ewk_cookie_manager_cookies_delete) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - Ewk_Cookie_Manager* cookieManager = ewk_context_cookie_manager_get(ewk_view_context_get(webView())); - ASSERT_TRUE(cookieManager); - - ewk_cookie_manager_accept_policy_set(cookieManager, EWK_COOKIE_ACCEPT_POLICY_ALWAYS); - ASSERT_EQ(EWK_COOKIE_ACCEPT_POLICY_ALWAYS, getAcceptPolicy(cookieManager)); - - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - Eina_List* hostnames = getHostnamesWithCookies(cookieManager); - ASSERT_EQ(2, eina_list_count(hostnames)); - freeHostNames(hostnames); - - // Delete first party cookie - ewk_cookie_manager_hostname_cookies_clear(cookieManager, FIRST_PARTY_DOMAIN); - hostnames = getHostnamesWithCookies(cookieManager); - ASSERT_EQ(1, eina_list_count(hostnames)); - ASSERT_STREQ(THIRD_PARTY_DOMAIN, static_cast<char*>(eina_list_nth(hostnames, 0))); - freeHostNames(hostnames); - - // Delete third party cookie - ewk_cookie_manager_hostname_cookies_clear(cookieManager, THIRD_PARTY_DOMAIN); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); - - // Get all cookies again - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - - // Clear all cookies - ewk_cookie_manager_cookies_clear(cookieManager); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); -} - -TEST_F(EWK2CookieManagerTest, DISABLED_ewk_cookie_manager_permanent_storage) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - // Generate unique names for cookie storages. - char textStorage[] = "/tmp/txt-cookie.XXXXXX"; - ASSERT_TRUE(mktemp(textStorage)); - char sqliteStorage[] = "/tmp/sqlite-cookie.XXXXXX"; - ASSERT_TRUE(mktemp(sqliteStorage)); - - Ewk_Cookie_Manager* cookieManager = ewk_context_cookie_manager_get(ewk_view_context_get(webView())); - ASSERT_TRUE(cookieManager); - - ewk_cookie_manager_accept_policy_set(cookieManager, EWK_COOKIE_ACCEPT_POLICY_ALWAYS); - ASSERT_EQ(EWK_COOKIE_ACCEPT_POLICY_ALWAYS, getAcceptPolicy(cookieManager)); - - // Text storage using a new file. - ewk_cookie_manager_persistent_storage_set(cookieManager, textStorage, EWK_COOKIE_PERSISTENT_STORAGE_TEXT); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); - - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - - // SQLite storage using a new file. - ewk_cookie_manager_persistent_storage_set(cookieManager, sqliteStorage, EWK_COOKIE_PERSISTENT_STORAGE_SQLITE); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); - - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/index.html").data())); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - - // Text storage using an existing file. - ewk_cookie_manager_persistent_storage_set(cookieManager, textStorage, EWK_COOKIE_PERSISTENT_STORAGE_TEXT); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - ewk_cookie_manager_cookies_clear(cookieManager); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); - - // SQLite storage with an existing file. - ewk_cookie_manager_persistent_storage_set(cookieManager, sqliteStorage, EWK_COOKIE_PERSISTENT_STORAGE_SQLITE); - ASSERT_EQ(2, countHostnamesWithCookies(cookieManager)); - ewk_cookie_manager_cookies_clear(cookieManager); - ASSERT_EQ(0, countHostnamesWithCookies(cookieManager)); - - // Final clean up. - 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 deleted file mode 100644 index 513d7b3c3..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_database_manager.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" - -using namespace EWK2UnitTest; - -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 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->didReceiveOriginsCallback) { - originData->didReceiveOriginsCallback = false; - ewk_database_manager_origins_get(originData->manager, databaseOriginsCallback, originData); - } - - return ECORE_CALLBACK_RENEW; - } -}; - -TEST_F(EWK2DatabaseManagerTest, ewk_database_manager_origins_get) -{ - Evas_Object* view = webView(); - const char* databaseHTML = - "<html><head><title>original title</title></head>" - "<body>" - "<script type='text/javascript'>" - " var db = openDatabase(\"DBTest\", \"1.0\", \"HTML5 Database example\", 200000);" - "</script>" - "</body></html>"; - - ASSERT_TRUE(ewk_view_html_string_load(view, databaseHTML, "http://www.databasetest.com", 0)); - ASSERT_TRUE(waitUntilLoadFinished()); - - OriginData originData; - originData.manager = ewk_context_database_manager_get(ewk_view_context_get(view)); - 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) - ecore_timer_del(database_timer); - - ASSERT_TRUE(originData.isSynchronized); - ASSERT_LE(1, eina_list_count(originData.originList)); -} 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 deleted file mode 100644 index 4303bed00..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_download_job.cpp +++ /dev/null @@ -1,177 +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" -#include <sys/stat.h> -#include <sys/types.h> -#include <unistd.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -using namespace EWK2UnitTest; -using namespace WTF; - -extern EWK2UnitTestEnvironment* environment; - -static const char serverSuggestedFilename[] = "webkit-downloaded-file"; -static const char testFilePath[] = "/test.pdf"; - -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); - } - - 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); - - 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)); - - 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)); - - 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)); - } - - 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_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_TRUE(fileExists(testData->destinationPath)); - - ecore_main_loop_quit(); - } -}; - -TEST_F(EWK2DownloadJobTest, ewk_download) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallback); - - // Generate unique name for destination file. - char destinationPath[] = "/tmp/pdf-file.XXXXXX"; - ASSERT_TRUE(mktemp(destinationPath)); - - CString fileUrl = httpServer->getURLForPath(testFilePath); - - DownloadTestData userData = { fileUrl.data(), destinationPath }; - ASSERT_FALSE(fileExists(destinationPath)); - - evas_object_smart_callback_add(webView(), "download,request", on_download_requested, &userData); - evas_object_smart_callback_add(webView(), "download,cancel", on_download_cancelled, &userData); - evas_object_smart_callback_add(webView(), "download,failed", on_download_failed, &userData); - evas_object_smart_callback_add(webView(), "download,finished", on_download_finished, &userData); - - // Download test pdf - ewk_view_url_set(webView(), fileUrl.data()); - ecore_main_loop_begin(); - - // Clean up - unlink(destinationPath); -} 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 deleted file mode 100644 index babc07e67..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_eina_shared_string.cpp +++ /dev/null @@ -1,143 +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 "WKEinaSharedString.h" -#include <WebKit2/WKString.h> -#include <WebKit2/WKURL.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -// Use macro here instead of global variables in order not to have always the same pointers. -#define testString "I'm test string!" -#define anotherTestString "I'm another test string!" -#define testUrl "file:///path/somewhere" - -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(EWK2EinaSharedStringTest, constructFromPlainString) -{ - WKEinaSharedString emptyString(testString); - checkString(emptyString, testString); -} - -TEST_F(EWK2EinaSharedStringTest, constructFromWKString) -{ - WKEinaSharedString string(AdoptWK, WKStringCreateWithUTF8CString(testString)); - checkString(string, testString); -} - -TEST_F(EWK2EinaSharedStringTest, constructFromWKURL) -{ - WKEinaSharedString string(AdoptWK, WKURLCreateWithUTF8CString(testUrl)); - checkString(string, testUrl); -} - -TEST_F(EWK2EinaSharedStringTest, constructFromEinaStringShare) -{ - WKEinaSharedString string(WKEinaSharedString::adopt(eina_stringshare_add(testString))); - checkString(string, testString); - - string = WKEinaSharedString::adopt(eina_stringshare_add(anotherTestString)); - checkString(string, anotherTestString); - - string = string; - checkString(string, anotherTestString); -} - -TEST_F(EWK2EinaSharedStringTest, costructCopy) -{ - WKEinaSharedString string(testString); - WKEinaSharedString copyString(string); - checkString(string, testString); - checkString(copyString, testString); - ASSERT_EQ(string, copyString); // Check '==' operator with two instances of WKEinaSharedString. -} - -TEST_F(EWK2EinaSharedStringTest, comparisonOperators) -{ - WKEinaSharedString string(testString); - WKEinaSharedString sameString(testString); - WKEinaSharedString anotherString(anotherTestString); - - ASSERT_EQ(string, sameString); // Check '==' operator with two instances of WKEinaSharedString. - ASSERT_NE(string, anotherString); // Check '!=' operator with two instances of WKEinaSharedString. - - const char* explicitlySharedString = eina_stringshare_add(testString); - ASSERT_EQ(static_cast<const char*>(string), explicitlySharedString); // Compare pointers. - ASSERT_STREQ(string, explicitlySharedString); // Compare values. - eina_stringshare_del(explicitlySharedString); - - ASSERT_EQ(string, string); // Self-comparison. -} - -TEST_F(EWK2EinaSharedStringTest, assignmentOperators) -{ - WKEinaSharedString string; - - string = testString; - checkString(string, testString); - - WKEinaSharedString anotherString(anotherTestString); - string = anotherString; - checkString(string, anotherTestString); - ASSERT_EQ(string, anotherString); - - 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 deleted file mode 100644 index d0d6cb1b0..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_favicon_database.cpp +++ /dev/null @@ -1,135 +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" -#include "WKEinaSharedString.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -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); - 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; - } - - 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); - - // 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); - - Evas* evas = evas_object_evas_get(data->view); - data->icon = ewk_favicon_database_icon_get(faviconDatabase, ewk_view_url_get(data->view), evas); - } -}; - -TEST_F(EWK2FaviconDatabaseTest, ewk_favicon_database_async_icon_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); - - IconRequestData data = { webView(), 0 }; - 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. - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/").data())); - - while (!data.icon) - ecore_main_loop_iterate(); - - ASSERT_TRUE(data.icon); - 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 deleted file mode 100644 index d79983679..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_file_chooser_request.cpp +++ /dev/null @@ -1,174 +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; - -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); - - return strcmp(static_cast<const char*>(string1), static_cast<const char*>(string2)); - } - -protected: - void freeStringList(Eina_List** list) - { - void* data; - EINA_LIST_FREE(*list, data) { - eina_stringshare_del(static_cast<char*>(data)); - } - } - - 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())); - - clickFileInput(); - - // Wait for the file chooser request. - while (!request) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(webView(), "file,chooser,request", onFileChooserRequest); - ASSERT_TRUE(request); - // Validate file chooser request. - EXPECT_TRUE(ewk_file_chooser_request_allow_multiple_files_get(request)); - Eina_List* mimeTypes = ewk_file_chooser_request_accepted_mimetypes_get(request); - mimeTypes = eina_list_sort(mimeTypes, eina_list_count(mimeTypes), compareStrings); - - ASSERT_EQ(2, eina_list_count(mimeTypes)); - EXPECT_STREQ("image/*", static_cast<char*>(eina_list_nth(mimeTypes, 0))); - EXPECT_STREQ("video/*", static_cast<char*>(eina_list_nth(mimeTypes, 1))); - freeStringList(&mimeTypes); - - ASSERT_FALSE(ewk_file_chooser_request_files_choose(request, 0)); - Eina_List* files = 0; - files = eina_list_append(files, eina_stringshare_add("/tmp/file1.png")); - files = eina_list_append(files, eina_stringshare_add("/tmp/file2.png")); - ASSERT_TRUE(ewk_file_chooser_request_files_choose(request, files)); - ASSERT_FALSE(ewk_file_chooser_request_files_choose(request, files)); - freeStringList(&files); - - ewk_object_unref(request); - - // Check that the JS side received the files. - EXPECT_TRUE(waitUntilTitleChangedTo("file1.png|file2.png")); -} - -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())); - - clickFileInput(); - - // Wait for the file chooser request. - while (!request) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(webView(), "file,chooser,request", onFileChooserRequest); - ASSERT_TRUE(request); - - ASSERT_FALSE(ewk_file_chooser_request_file_choose(request, 0)); - ASSERT_TRUE(ewk_file_chooser_request_file_choose(request, "/tmp/file3.png")); - ASSERT_FALSE(ewk_file_chooser_request_file_choose(request, "/tmp/file3.png")); - - ewk_object_unref(request); - - // Check that the JS side received the file. - EXPECT_TRUE(waitUntilTitleChangedTo("file3.png")); -} - -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())); - - clickFileInput(); - - // Wait for the file chooser request. - while (!request) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(webView(), "file,chooser,request", onFileChooserRequest); - ASSERT_TRUE(request); - - ASSERT_TRUE(ewk_file_chooser_request_cancel(request)); - ASSERT_FALSE(ewk_file_chooser_request_cancel(request)); - - ewk_object_unref(request); - - ecore_main_loop_iterate(); - EXPECT_STREQ("File chooser test", ewk_view_title_get(webView())); - - // 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); - - clickFileInput(); - - // Wait for the file chooser request. - while (!request) - ecore_main_loop_iterate(); - - evas_object_smart_callback_del(webView(), "file,chooser,request", onFileChooserRequest); - ASSERT_TRUE(request); - - ewk_object_unref(request); - - ecore_main_loop_iterate(); - EXPECT_STREQ("File chooser test", ewk_view_title_get(webView())); -} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_object.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_object.cpp deleted file mode 100644 index 70ceea5e5..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_object.cpp +++ /dev/null @@ -1,112 +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" -#include "WKEinaSharedString.h" -#include "ewk_object_private.h" -#include <wtf/PassRefPtr.h> - -using namespace EWK2UnitTest; -using namespace WTF; - -extern EWK2UnitTestEnvironment* environment; - -class TestEwkObject1 : public EwkObject { -public: - EWK_OBJECT_DECLARE(TestEwkObject) - - static PassRefPtr<TestEwkObject1> create() - { - wasDeleted = false; - return adoptRef(new TestEwkObject1()); - } - - static bool wasDeleted; // We always test only one instance of TestEwkObject. - - ~TestEwkObject1() - { - wasDeleted = true; - } -}; - -bool TestEwkObject1::wasDeleted = false; - -class TestEwkObject2 : public EwkObject { -public: - EWK_OBJECT_DECLARE(TestEwkObject2) - - static PassRefPtr<TestEwkObject2> create() - { - return adoptRef(new TestEwkObject2()); - } -}; - -TEST_F(EWK2UnitTestBase, ewk_object_ref) -{ - Ewk_Object* objectRef = 0; - - { - RefPtr<Ewk_Object> object = TestEwkObject1::create(); - ASSERT_FALSE(TestEwkObject1::wasDeleted); - ASSERT_EQ(1, object->refCount()); - - objectRef = object.get(); - ewk_object_ref(objectRef); - ASSERT_EQ(2, objectRef->refCount()); - } - - ASSERT_FALSE(TestEwkObject1::wasDeleted); - ASSERT_EQ(1, objectRef->refCount()); - - ewk_object_unref(objectRef); - ASSERT_TRUE(TestEwkObject1::wasDeleted); -} - -TEST_F(EWK2UnitTestBase, ewk_object_is_of_type) -{ - RefPtr<EwkObject> object1 = TestEwkObject1::create(); - RefPtr<EwkObject> object2 = TestEwkObject2::create(); - - ASSERT_TRUE(ewk_object_is_of_type<TestEwkObject1*>(object1.get())); - ASSERT_TRUE(ewk_object_is_of_type<TestEwkObject2*>(object2.get())); - - ASSERT_FALSE(ewk_object_is_of_type<TestEwkObject1*>(object2.get())); - ASSERT_FALSE(ewk_object_is_of_type<TestEwkObject2*>(object1.get())); -} - -TEST_F(EWK2UnitTestBase, ewk_object_cast) -{ - RefPtr<EwkObject> object1 = TestEwkObject1::create(); - RefPtr<EwkObject> object2 = TestEwkObject2::create(); - - TestEwkObject1* objectRef1 = ewk_object_cast<TestEwkObject1*>(object1.get()); - ASSERT_TRUE(objectRef1); - - TestEwkObject2* objectRef2 = ewk_object_cast<TestEwkObject2*>(object2.get()); - ASSERT_TRUE(objectRef2); -} 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 deleted file mode 100644 index b5ca59771..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_page_group.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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 deleted file mode 100644 index 3ff5d105f..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_popup_menu.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -static Ewk_Popup_Menu* s_popupMenu = 0; - -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;\">" - "<option>first</option><option disabled>second</option><option selected dir=\"rtl\" title=\"tooltip\" aria-label=\"aria\">third</option>" - "<optgroup label=\"label\"><option>forth</option></optgroup>" - "</select></body>"; - - ewkViewClass()->popup_menu_show = showPopupMenu; - - ewk_view_html_string_load(webView(), selectHTML, "file:///", 0); - ASSERT_TRUE(waitUntilLoadFinished()); - mouseClick(30, 20); - ASSERT_TRUE(waitUntilTitleChangedTo("first")); - - ASSERT_TRUE(s_popupMenu); - EXPECT_TRUE(ewk_popup_menu_close(s_popupMenu)); -} diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_refptr_evas_object.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_refptr_evas_object.cpp deleted file mode 100644 index de180e41b..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_refptr_evas_object.cpp +++ /dev/null @@ -1,129 +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 <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/efl/RefPtrEfl.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -TEST_F(EWK2UnitTestBase, construction) -{ - RefPtr<Evas_Object> nullObject = 0; - ASSERT_FALSE(nullObject); - - RefPtr<Evas_Object> object; - ASSERT_FALSE(object); - - object = adoptRef(evas_object_box_add(canvas())); - ASSERT_TRUE(object); - - object = 0; - ASSERT_FALSE(object); - - object = adoptRef(evas_object_box_add(canvas())); - ASSERT_TRUE(object); - - object.clear(); - ASSERT_FALSE(object); -} - -TEST_F(EWK2UnitTestBase, reffing) -{ - RefPtr<Evas_Object> object = adoptRef(evas_object_box_add(canvas())); - ASSERT_TRUE(object); - // Evas_Objec external ref count is not as you would expect. - ASSERT_EQ(0, evas_object_ref_get(object.get())); - - { - RefPtr<Evas_Object> aRef = object; - ASSERT_TRUE(object); - ASSERT_TRUE(aRef); - ASSERT_EQ(1, evas_object_ref_get(object.get())); - ASSERT_EQ(1, evas_object_ref_get(aRef.get())); - - { - RefPtr<Evas_Object> bRef = object; - - ASSERT_TRUE(object); - ASSERT_TRUE(aRef); - ASSERT_TRUE(bRef); - - ASSERT_EQ(2, evas_object_ref_get(object.get())); - ASSERT_EQ(2, evas_object_ref_get(aRef.get())); - - RefPtr<Evas_Object> cRef = bRef; - ASSERT_TRUE(cRef); - - ASSERT_EQ(3, evas_object_ref_get(object.get())); - ASSERT_EQ(3, evas_object_ref_get(aRef.get())); - ASSERT_EQ(3, evas_object_ref_get(bRef.get())); - ASSERT_EQ(3, evas_object_ref_get(cRef.get())); - - bRef.clear(); - ASSERT_EQ(2, evas_object_ref_get(object.get())); - ASSERT_EQ(2, evas_object_ref_get(aRef.get())); - ASSERT_EQ(2, evas_object_ref_get(cRef.get())); - } - ASSERT_EQ(1, evas_object_ref_get(object.get())); - ASSERT_EQ(1, evas_object_ref_get(aRef.get())); - } - ASSERT_EQ(0, evas_object_ref_get(object.get())); -} - -TEST_F(EWK2UnitTestBase, destruction) -{ - RefPtr<Evas_Object> object = adoptRef(evas_object_box_add(canvas())); - ASSERT_TRUE(object); - ASSERT_EQ(0, evas_object_ref_get(object.get())); - - RefPtr<Evas_Object> aRef = object; - ASSERT_TRUE(object); - ASSERT_TRUE(aRef); - ASSERT_EQ(1, evas_object_ref_get(object.get())); - ASSERT_EQ(1, evas_object_ref_get(aRef.get())); - - object = nullptr; - ASSERT_EQ(0, evas_object_ref_get(object.get())); - ASSERT_EQ(0, evas_object_ref_get(aRef.get())); - - object = aRef; - ASSERT_EQ(1, evas_object_ref_get(object.get())); - ASSERT_EQ(1, evas_object_ref_get(aRef.get())); - - object = 0; - ASSERT_EQ(0, evas_object_ref_get(object.get())); - ASSERT_EQ(0, evas_object_ref_get(aRef.get())); - - aRef.clear(); - ASSERT_FALSE(aRef); - ASSERT_FALSE(object); -} - diff --git a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp b/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp deleted file mode 100644 index caf6af413..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_settings.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -TEST_F(EWK2UnitTestBase, ewk_settings_fullscreen_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - -#if ENABLE(FULLSCREEN_API) - ASSERT_TRUE(ewk_settings_fullscreen_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_fullscreen_enabled_set(settings, EINA_TRUE)); - ASSERT_TRUE(ewk_settings_fullscreen_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_fullscreen_enabled_set(settings, EINA_FALSE)); - ASSERT_FALSE(ewk_settings_fullscreen_enabled_get(settings)); -#else - ASSERT_FALSE(ewk_settings_fullscreen_enabled_get(settings)); - - ASSERT_FALSE(ewk_settings_fullscreen_enabled_set(settings, EINA_TRUE)); - ASSERT_FALSE(ewk_settings_fullscreen_enabled_get(settings)); - - ASSERT_FALSE(ewk_settings_fullscreen_enabled_set(settings, EINA_FALSE)); - ASSERT_FALSE(ewk_settings_fullscreen_enabled_get(settings)); -#endif -} - -TEST_F(EWK2UnitTestBase, ewk_settings_javascript_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - ASSERT_TRUE(ewk_settings_javascript_enabled_set(settings, EINA_TRUE)); - ASSERT_TRUE(ewk_settings_javascript_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_javascript_enabled_set(settings, 2)); - ASSERT_TRUE(ewk_settings_javascript_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_javascript_enabled_set(settings, EINA_FALSE)); - ASSERT_FALSE(ewk_settings_javascript_enabled_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_loads_images_automatically) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - ASSERT_TRUE(ewk_settings_loads_images_automatically_set(settings, EINA_TRUE)); - ASSERT_TRUE(ewk_settings_loads_images_automatically_get(settings)); - - ASSERT_TRUE(ewk_settings_loads_images_automatically_set(settings, 2)); - ASSERT_TRUE(ewk_settings_loads_images_automatically_get(settings)); - - ASSERT_TRUE(ewk_settings_loads_images_automatically_set(settings, EINA_FALSE)); - ASSERT_FALSE(ewk_settings_loads_images_automatically_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_developer_extras_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - ASSERT_TRUE(ewk_settings_developer_extras_enabled_set(settings, EINA_TRUE)); - ASSERT_TRUE(ewk_settings_developer_extras_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_developer_extras_enabled_set(settings, 2)); - ASSERT_TRUE(ewk_settings_developer_extras_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_developer_extras_enabled_set(settings, EINA_FALSE)); - ASSERT_FALSE(ewk_settings_developer_extras_enabled_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_file_access_from_file_urls_allowed) -{ - CString testURL = environment->urlForResource("local_file_access.html"); - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - ASSERT_FALSE(ewk_settings_file_access_from_file_urls_allowed_get(settings)); - - ASSERT_TRUE(ewk_settings_file_access_from_file_urls_allowed_set(settings, true)); - ASSERT_TRUE(ewk_settings_file_access_from_file_urls_allowed_get(settings)); - - // Check that file access from file:// URLs is allowed. - ewk_view_url_set(webView(), testURL.data()); - ASSERT_TRUE(waitUntilTitleChangedTo("Frame loaded")); - - ASSERT_TRUE(ewk_settings_file_access_from_file_urls_allowed_set(settings, false)); - ASSERT_FALSE(ewk_settings_file_access_from_file_urls_allowed_get(settings)); - - // Check that file access from file:// URLs is NOT allowed. - ewk_view_url_set(webView(), testURL.data()); - ASSERT_TRUE(waitUntilTitleChangedTo("Frame NOT loaded")); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_frame_flattening_enabled_set) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - ASSERT_TRUE(settings); - - // The frame flattening is disabled by default. - ASSERT_FALSE(ewk_settings_frame_flattening_enabled_get(settings)); - ewk_view_url_set(webView(), environment->urlForResource("frame_flattening_test.html").data()); - waitUntilTitleChangedTo("200"); // width of iframe tag. - ASSERT_STREQ("200", ewk_view_title_get(webView())); - - ASSERT_TRUE(ewk_settings_frame_flattening_enabled_set(settings, true)); - ASSERT_TRUE(ewk_settings_frame_flattening_enabled_get(settings)); - ewk_view_url_set(webView(), environment->urlForResource("frame_flattening_test.html").data()); - waitUntilTitleChangedTo("600"); // width of frame_flattening_test_subframe.html - ASSERT_STREQ("600", ewk_view_title_get(webView())); - - ASSERT_TRUE(ewk_settings_frame_flattening_enabled_set(settings, false)); - ASSERT_FALSE(ewk_settings_frame_flattening_enabled_get(settings)); - ewk_view_url_set(webView(), environment->urlForResource("frame_flattening_test.html").data()); - waitUntilTitleChangedTo("200"); // width of iframe tag. - ASSERT_STREQ("200", ewk_view_title_get(webView())); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_dns_prefetching_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - // DNS prefeching is disabled by default. - ASSERT_FALSE(ewk_settings_dns_prefetching_enabled_get(settings)); - ASSERT_TRUE(ewk_settings_dns_prefetching_enabled_set(settings, true)); - ASSERT_TRUE(ewk_settings_dns_prefetching_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_dns_prefetching_enabled_set(settings, false)); - ASSERT_FALSE(ewk_settings_dns_prefetching_enabled_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_encoding_detector_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - // The encoding detector is disabled by default. - ASSERT_FALSE(ewk_settings_encoding_detector_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_encoding_detector_enabled_set(settings, true)); - ASSERT_TRUE(ewk_settings_encoding_detector_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_encoding_detector_enabled_set(settings, false)); - ASSERT_FALSE(ewk_settings_encoding_detector_enabled_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_preferred_minimum_contents_width) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - // 980 by default. - ASSERT_EQ(980, ewk_settings_preferred_minimum_contents_width_get(settings)); - - ASSERT_TRUE(ewk_settings_preferred_minimum_contents_width_set(settings, 0)); - ASSERT_EQ(0, ewk_settings_preferred_minimum_contents_width_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_offline_web_application_cache_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - // The offline web application cache is enabled by default. - ASSERT_TRUE(ewk_settings_offline_web_application_cache_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_offline_web_application_cache_enabled_set(settings, true)); - ASSERT_TRUE(ewk_settings_offline_web_application_cache_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_offline_web_application_cache_enabled_set(settings, false)); - ASSERT_FALSE(ewk_settings_offline_web_application_cache_enabled_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_scripts_can_open_windows) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - // The scripts can open new windows by default. - ASSERT_TRUE(ewk_settings_scripts_can_open_windows_get(settings)); - - ASSERT_TRUE(ewk_settings_scripts_can_open_windows_set(settings, true)); - ASSERT_TRUE(ewk_settings_scripts_can_open_windows_get(settings)); - - ASSERT_TRUE(ewk_settings_scripts_can_open_windows_set(settings, false)); - ASSERT_FALSE(ewk_settings_scripts_can_open_windows_get(settings)); -} - -TEST_F(EWK2UnitTestBase, ewk_settings_local_storage_enabled) -{ - Ewk_Settings* settings = ewk_view_settings_get(webView()); - - // HTML5 local storage should be enabled by default. - ASSERT_TRUE(ewk_settings_local_storage_enabled_get(settings)); - - ASSERT_TRUE(ewk_settings_local_storage_enabled_set(settings, false)); - ASSERT_FALSE(ewk_settings_local_storage_enabled_get(settings)); - - 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 deleted file mode 100644 index 0c6d336e0..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_storage_manager.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" - -using namespace EWK2UnitTest; - -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); - - 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); - } - - 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; - } - - return false; - } -}; - -TEST_F(EWK2StorageManagerTest, ewk_storage_manager_origins_get) -{ - Evas_Object* view = webView(); - const char* storageHTML = - "<html><head><title>original title</title></head>" - "<body>" - "<script type='text/javascript'>" - " localStorage.setItem('item', 'storage');" - "</script>" - "</body></html>"; - - ewk_view_html_string_load(view, storageHTML, "http://www.storagetest.com", 0); - - OriginData originData; - originData.manager = ewk_context_storage_manager_get(ewk_view_context_get(view)); - ASSERT_TRUE(ewk_storage_manager_origins_get(originData.manager, getStorageOriginsCallback, &originData)); - Ecore_Timer* storage_timer = ecore_timer_add(1, reinterpret_cast<Ecore_Task_Cb>(timerCallback), &originData); - - ecore_main_loop_begin(); - if (storage_timer) - ecore_timer_del(storage_timer); - - ASSERT_TRUE(originData.isSynchronized); - ASSERT_LE(1, eina_list_count(originData.originList)); - - Ewk_Security_Origin* origin = 0; - EXPECT_TRUE(checkOrigin(originData.originList, &origin)); - - EXPECT_EQ(origin, ewk_object_ref(origin)); - ewk_object_unref(origin); -} 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 deleted file mode 100644 index 6dcb870c8..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_text_checker.cpp +++ /dev/null @@ -1,906 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @brief covers API from ewk_text_checker.h - * @file test_ewk2_text_checker.cpp - */ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" -#include <wtf/text/CString.h> -#include <wtf/text/StringBuilder.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -static const uint64_t defaultDocumentTag = 123; -static const char expectedMisspelledWord[] = "aa"; -static const Evas_Object* defaultView = 0; -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 settingChange; - bool spellDocumentTag; - bool spellDocumentTagClose; - bool spellingCheck; - bool wordGuesses; - bool wordLearn; - bool wordIgnore; -} callbacksExecutionStats; - -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; - } - - /** - * 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; - } - - /** - * 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; - } - - /** - * 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. - * - * @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; - } - - /** - * 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; - } - } -}; - -/** - * Test whether there are spelling suggestions when misspelled word is directly context clicked. - */ -TEST_F(EWK2TextCheckerTest, spelling_suggestion_for_context_click) -{ - 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(waitUntilTrue(wasContextMenuShown)); - unsigned numberItemsWithoutSpellCheck = contextMenuItemsNumber; - - wasContextMenuShown = false; - - // 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); -} - -/** - * Test whether there are no spelling suggestions when multiple words are selected (that are not a single misspelling). - */ -TEST_F(EWK2TextCheckerTest, no_spelling_suggestion_for_multiword_selection) -{ - 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 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); -} - -/** - * Test whether there are no spelling suggestions when part of misspelled word are selected. - */ -TEST_F(EWK2TextCheckerTest, no_spelling_suggestion_for_subword_selection) -{ - 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); -} - -/** - * Test whether context menu spelling items are available when misspelled word has selection as the double click. - */ -TEST_F(EWK2TextCheckerTest, spelling_suggestion_for_double_clicked_word) -{ - 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 whether the default language is loaded independently of - * continuous spell checking setting. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_spell_checking_languages_get) -{ - 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_text_checker_spell_checking_languages_get(); - // No dictionary is available/installed. - if (!loadedLanguages) - return; - - EXPECT_EQ(1, eina_list_count(loadedLanguages)); - - void* data; - EINA_LIST_FREE(loadedLanguages, data) - 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)); - - EINA_LIST_FREE(loadedLanguages, data) - eina_stringshare_del(static_cast<Eina_Stringshare*>(data)); -} - -/** - * Test whether the context menu spelling items (suggestions, learn and ignore spelling) - * are available when continuous spell checking is off. - */ -TEST_F(EWK2TextCheckerTest, context_menu_spelling_items_availability) -{ - ewk_text_checker_continuous_spell_checking_enabled_set(false); - ewkViewClass()->context_menu_show = checkCorrectnessOfSpellingItems; - - ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - showContextMenu(FirstLine); - - 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_TRUE(ewk_text_checker_continuous_spell_checking_enabled_get()); -#else - EXPECT_FALSE(ewk_text_checker_continuous_spell_checking_enabled_get()); -#endif - - ewk_text_checker_continuous_spell_checking_enabled_set(false); - EXPECT_FALSE(ewk_text_checker_continuous_spell_checking_enabled_get()); -} - -/** - * 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)); - - resetCallbacksExecutionStats(); - - // Test case, when "Check Spelling While Typing" is in reverse to the previous one. - isSettingEnabled = !isSettingEnabled; - - 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; - - ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - - showContextMenu(FirstLine); - ASSERT_FALSE(waitUntilTrue(callbacksExecutionStats.settingChange, /*Timeout*/ 0)); -} - -/** - * This unit test sets all available/installed dictionaries and verifies them - * if they are in use. - * All the dictionaries from the list can be set to perform spellchecking. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_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; - - // Helper to create one string with comma separated languages. - void* actual = 0; - WTF::StringBuilder languages; - Eina_List* listIterator = 0; - unsigned lastIndex = eina_list_count(availableLanguages) - 1; - unsigned i = 0; - EINA_LIST_FOREACH(availableLanguages, listIterator, actual) { - languages.append(static_cast<const char*>(actual)); - // Add the comma after all but the last language IDs. - if (i++ != lastIndex) - languages.append(','); - } - - // Set all available languages. - 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_text_checker_spell_checking_languages_get(); - ASSERT_EQ(eina_list_count(loadedLanguages), eina_list_count(availableLanguages)); - - i = 0; - void* expected = 0; - // Verify whether the loaded languages list is equal to the available languages list. - EINA_LIST_FOREACH(loadedLanguages, listIterator, actual) { - expected = eina_list_nth(availableLanguages, i++); - EXPECT_STREQ(static_cast<const char*>(expected), static_cast<const char*>(actual)); - } - - // Delete the lists. - EINA_LIST_FREE(availableLanguages, actual) - eina_stringshare_del(static_cast<const char*>(actual)); - - EINA_LIST_FREE(loadedLanguages, actual) - eina_stringshare_del(static_cast<const char*>(actual)); -} - -/** - * Here we test the following scenarios: - * - setting the default language, - * - if two arbitrarily selected dictionaries are set correctly. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_spell_checking_languages) -{ - // Set the default language. - 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_text_checker_spell_checking_languages_get(); - // No dictionary is available/installed or the SPELLCHECK macro is disabled. - if (!loadedLanguages) - return; - - ASSERT_EQ(1, eina_list_count(loadedLanguages)); - - // Delete the list. - void* actual = 0; - EINA_LIST_FREE(loadedLanguages, actual) - eina_stringshare_del(static_cast<const char*>(actual)); - - // Get the first and last language from installed dictionaries. - 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) - return; - - const char* firstExpected = static_cast<const char*>(eina_list_nth(availableLanguages, 0)); - const char* lastExpected = static_cast<const char*>(eina_list_data_get(eina_list_last(availableLanguages))); - - // Case sensitivity of dictionaries doesn't affect on loading the dictionaries, - // the Enchant library will 'normalize' them. - WTF::StringBuilder languages; - languages.append(String(firstExpected).upper()); - languages.append(','); - languages.append(String(lastExpected).lower()); - - // Set both languages (the first and the last) from the list. - ewk_text_checker_spell_checking_languages_set(languages.toString().utf8().data()); - - timeoutTimer = ecore_timer_add(defaultTimeoutInSeconds, onTimeout, 0); - ecore_main_loop_begin(); - - 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))); - EXPECT_STREQ(lastExpected, static_cast<const char*>(eina_list_nth(loadedLanguages, 1))); - - // Delete the lists. - EINA_LIST_FREE(availableLanguages, actual) - eina_stringshare_del(static_cast<const char*>(actual)); - - EINA_LIST_FREE(loadedLanguages, actual) - eina_stringshare_del(static_cast<const char*>(actual)); -} - -/** - * Test whether the client's callbacks aren't called (if not specified). - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker) -{ - resetCallbacksExecutionStats(); - ewk_text_checker_continuous_spell_checking_enabled_set(true); - - ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - - // If user doesn't specify callback functions responsible for spelling - // the default WebKit implementation (based on the Enchant library) will be used. - ASSERT_FALSE(callbacksExecutionStats.spellDocumentTag); - ASSERT_FALSE(callbacksExecutionStats.spellDocumentTagClose); - ASSERT_FALSE(callbacksExecutionStats.spellingCheck); - - // It doesn't make sense to verify others callbacks (onWordGuesses, - // onWordLearn, onWordIgnore) as they need the context menu feature - // which is not implemented for WK2-EFL. -} - -/** - * Test whether the client's callbacks (onSpellDocumentTag, onSpellDocumentTagClose) are called. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_unique_spell_document_tag) -{ - resetCallbacksExecutionStats(); - defaultView = webView(); - 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); - - ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - - // Check whether the callback was called. - ASSERT_TRUE(callbacksExecutionStats.spellDocumentTag); - // It's not possible to check whether onSpellDocumentTagClose was called here, because - // it's invoked when WebPage is being destroyed. - // It should be verified for example when view is freed. -} - -/** - * Test whether the client's callback (onSpellingCheck) is called when - * the word to input field was put. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_string_spelling_check_cb_set) -{ - resetCallbacksExecutionStats(); - defaultView = webView(); - ewk_text_checker_continuous_spell_checking_enabled_set(true); - - ewk_text_checker_string_spelling_check_cb_set(onSpellingCheck); - - ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - - // Check whether the callback was called. - ASSERT_TRUE(callbacksExecutionStats.spellingCheck); -} - -/** - * Test whether the client's callback (onWordGuesses) is called when - * the context menu was shown on the misspelled word. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_word_guesses_get_cb_set) -{ - resetCallbacksExecutionStats(); - wasContextMenuShown = false; - defaultView = webView(); - ewkViewClass()->context_menu_show = checkClientSuggestionsForWord; - ewk_text_checker_word_guesses_get_cb_set(onWordGuesses); - - ASSERT_TRUE(loadUrlSync(environment->urlForResource("spelling_test.html").data())); - - 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 chosen. In the next step, - * check whether the learned word is treated as spelled correctly while spell checking. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_word_learn_cb_set) -{ - resetCallbacksExecutionStats(); - knownWord = emptyString(); - defaultView = webView(); - 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())); - - 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 chosen. In the next step, - * check whether the ignored word is treated as spelled correctly while spell checking. - */ -TEST_F(EWK2TextCheckerTest, ewk_text_checker_word_ignore_cb_set) -{ - resetCallbacksExecutionStats(); - knownWord = emptyString(); - defaultView = webView(); - 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())); - - 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 deleted file mode 100644 index b65240007..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_view.cpp +++ /dev/null @@ -1,1043 +0,0 @@ -/* - Copyright (C) 2012 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 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this library; if not, write to the Free Software Foundation, - Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "config.h" - -#include "UnitTestUtils/EWK2UnitTestBase.h" -#include "UnitTestUtils/EWK2UnitTestServer.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -using namespace EWK2UnitTest; - -extern EWK2UnitTestEnvironment* environment; - -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)); - - Evas_Object* rectangle = evas_object_rectangle_add(canvas()); - ASSERT_FALSE(ewk_view_url_set(rectangle, 0)); -} - -TEST_F(EWK2ViewTest, ewk_view_url_get) -{ - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - EXPECT_STREQ(environment->defaultTestPageUrl(), ewk_view_url_get(webView())); - - int countLoadFinished = 2; - evas_object_smart_callback_add(webView(), "load,finished", onLoadFinishedForRedirection, &countLoadFinished); - ewk_view_url_set(webView(), environment->urlForResource("redirect_url_to_default.html").data()); - while (countLoadFinished) - ecore_main_loop_iterate(); - evas_object_smart_callback_del(webView(), "load,finished", onLoadFinishedForRedirection); - EXPECT_STREQ(environment->defaultTestPageUrl(), ewk_view_url_get(webView())); -} - -TEST_F(EWK2ViewTest, ewk_view_device_pixel_ratio) -{ - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - - // Default pixel ratio is 1.0 - ASSERT_FLOAT_EQ(1, ewk_view_device_pixel_ratio_get(webView())); - - ASSERT_TRUE(ewk_view_device_pixel_ratio_set(webView(), 1.2)); - ASSERT_FLOAT_EQ(1.2, ewk_view_device_pixel_ratio_get(webView())); - - ASSERT_TRUE(ewk_view_device_pixel_ratio_set(webView(), 1)); - ASSERT_FLOAT_EQ(1, ewk_view_device_pixel_ratio_get(webView())); -} - -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")); - ASSERT_STREQ("Foo", ewk_view_title_get(webView())); - ewk_view_html_string_load(webView(), "<html><head><title>Bar</title></head><body>Foo</body></html>", 0, 0); - ASSERT_TRUE(waitUntilTitleChangedTo("Bar")); - ASSERT_STREQ("Bar", ewk_view_title_get(webView())); -} - -TEST_F(EWK2ViewTest, ewk_view_navigation) -{ - OwnPtr<EWK2UnitTestServer> httpServer = adoptPtr(new EWK2UnitTestServer); - httpServer->run(serverCallbackNavigation); - - // Visit Page1 - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/Page1").data())); - ASSERT_STREQ("Page1", ewk_view_title_get(webView())); - ASSERT_FALSE(ewk_view_back_possible(webView())); - ASSERT_FALSE(ewk_view_forward_possible(webView())); - - // Visit Page2 - ASSERT_TRUE(loadUrlSync(httpServer->getURLForPath("/Page2").data())); - ASSERT_STREQ("Page2", ewk_view_title_get(webView())); - ASSERT_TRUE(ewk_view_back_possible(webView())); - ASSERT_FALSE(ewk_view_forward_possible(webView())); - - // Go back to Page1 - ewk_view_back(webView()); - ASSERT_TRUE(waitUntilTitleChangedTo("Page1")); - ASSERT_STREQ("Page1", ewk_view_title_get(webView())); - ASSERT_FALSE(ewk_view_back_possible(webView())); - ASSERT_TRUE(ewk_view_forward_possible(webView())); - - // Go forward to Page2 - ewk_view_forward(webView()); - ASSERT_TRUE(waitUntilTitleChangedTo("Page2")); - 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(EWK2ViewTest, ewk_view_custom_encoding) -{ - ASSERT_FALSE(ewk_view_custom_encoding_get(webView())); - ASSERT_TRUE(ewk_view_custom_encoding_set(webView(), "UTF-8")); - ASSERT_STREQ("UTF-8", ewk_view_custom_encoding_get(webView())); - // Set the default charset. - ASSERT_TRUE(ewk_view_custom_encoding_set(webView(), 0)); - ASSERT_FALSE(ewk_view_custom_encoding_get(webView())); -} - -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>" - "<body onload='submitForm()'>" - " <form id='myform' action='#'>" - " <input type='text' name='text1' value='value1'>" - " <input type='text' name='text2' value='value2'>" - " <input type='password' name='password' value='secret'>" - " <textarea cols='5' rows='5' name='textarea'>Text</textarea>" - " <input type='hidden' name='hidden1' value='hidden1'>" - " <input type='submit' value='Submit'>" - " </form>" - "</body></html>"; - - ewk_view_html_string_load(webView(), formHTML, "file:///", 0); - bool handled = false; - evas_object_smart_callback_add(webView(), "form,submission,request", onFormAboutToBeSubmitted, &handled); - while (!handled) - ecore_main_loop_iterate(); - ASSERT_TRUE(handled); - evas_object_smart_callback_del(webView(), "form,submission,request", onFormAboutToBeSubmitted); -} - -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(EWK2ViewTest, ewk_view_theme_set) -{ - const char* buttonHTML = "<html><body><input type='button' id='btn'>" - "<script>document.title=document.getElementById('btn').clientWidth;</script>" - "</body></html>"; - - ewk_view_html_string_load(webView(), buttonHTML, "file:///", 0); - EXPECT_TRUE(waitUntilTitleChangedTo("30")); // button of default theme has 30px as padding (15 to -16) - - ewk_view_theme_set(webView(), environment->pathForResource("it_does_not_exist.edj").data()); - ewk_view_html_string_load(webView(), buttonHTML, "file:///", 0); - EXPECT_TRUE(waitUntilTitleChangedTo("30")); // the result should be same as default theme - - ewk_view_theme_set(webView(), environment->pathForResource("empty_theme.edj").data()); - ewk_view_html_string_load(webView(), buttonHTML, "file:///", 0); - EXPECT_TRUE(waitUntilTitleChangedTo("30")); // the result should be same as default theme - - ewk_view_theme_set(webView(), environment->pathForTheme("big_button_theme.edj").data()); - ewk_view_html_string_load(webView(), buttonHTML, "file:///", 0); - EXPECT_TRUE(waitUntilTitleChangedTo("299")); // button of big button theme has 299px as padding (15 to -285) -} - -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())); - - ASSERT_TRUE(ewk_view_mouse_events_enabled_set(webView(), 2)); - ASSERT_TRUE(ewk_view_mouse_events_enabled_get(webView())); - - ASSERT_TRUE(ewk_view_mouse_events_enabled_set(webView(), EINA_FALSE)); - ASSERT_FALSE(ewk_view_mouse_events_enabled_get(webView())); -} - -TEST_F(EWK2ViewTest, ewk_view_full_screen_enter) -{ - const char fullscreenHTML[] = - "<!doctype html><head><script>function makeFullScreen(){" - "var div = document.getElementById(\"fullscreen\");" - "div.webkitRequestFullScreen();" - "document.title = \"fullscreen entered\";" - "}</script></head>" - "<body><div id=\"fullscreen\" style=\"width:100px; height:100px\" onclick=\"makeFullScreen()\"></div></body>"; - - ewkViewClass()->fullscreen_enter = fullScreenCallback; - - ewk_view_html_string_load(webView(), fullscreenHTML, "file:///", 0); - ASSERT_TRUE(waitUntilLoadFinished()); - mouseClick(50, 50); - ASSERT_TRUE(waitUntilTitleChangedTo("fullscreen entered")); - ASSERT_TRUE(fullScreenCallbackCalled); -} - -TEST_F(EWK2ViewTest, ewk_view_full_screen_exit) -{ - const char fullscreenHTML[] = - "<!doctype html><head><script>function makeFullScreenAndExit(){" - "var div = document.getElementById(\"fullscreen\");" - "div.webkitRequestFullScreen();" - "document.webkitCancelFullScreen();" - "document.title = \"fullscreen exited\";" - "}</script></head>" - "<body><div id=\"fullscreen\" style=\"width:100px; height:100px\" onclick=\"makeFullScreenAndExit()\"></div></body>"; - - ewkViewClass()->fullscreen_exit = fullScreenExitCallback; - - ewk_view_html_string_load(webView(), fullscreenHTML, "file:///", 0); - ASSERT_TRUE(waitUntilLoadFinished()); - mouseClick(50, 50); - ASSERT_TRUE(waitUntilTitleChangedTo("fullscreen exited")); - ASSERT_TRUE(fullScreenCallbackCalled); -} - -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(); - ASSERT_TRUE(loadUrlSync(testUrl.utf8().data())); - ASSERT_STREQ(testUrl.utf8().data(), ewk_view_url_get(webView())); - mouseClick(50, 50); - testUrl = testUrl + '#'; - ASSERT_TRUE(waitUntilURLChangedTo(testUrl.utf8().data())); -} - -TEST_F(EWK2ViewTest, ewk_view_title_changed) -{ - const char* titleChangedHTML = - "<!doctype html><head><title>Title before changed</title></head>" - "<body onload=\"document.title='Title after changed';\"></body>"; - ewk_view_html_string_load(webView(), titleChangedHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("Title after changed")); - EXPECT_STREQ("Title after changed", ewk_view_title_get(webView())); - - titleChangedHTML = - "<!doctype html><head><title>Title before changed</title></head>" - "<body onload=\"document.title='';\"></body>"; - ewk_view_html_string_load(webView(), titleChangedHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("")); - EXPECT_STREQ("", ewk_view_title_get(webView())); - - titleChangedHTML = - "<!doctype html><head><title>Title before changed</title></head>" - "<body onload=\"document.title=null;\"></body>"; - ewk_view_html_string_load(webView(), titleChangedHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("")); - EXPECT_STREQ("", ewk_view_title_get(webView())); -} - -TEST_F(EWK2ViewTest, ewk_view_run_javascript_alert) -{ - ewkViewClass()->run_javascript_alert = checkAlert; - - const char* alertHTML = "<!doctype html><body onload=\"alert('Alert message');\"></body>"; - alertCallbackData.expectedMessage = "Alert message"; - alertCallbackData.called = false; - ewk_view_html_string_load(webView(), alertHTML, 0, 0); - EXPECT_TRUE(waitUntilLoadFinished()); - EXPECT_TRUE(alertCallbackData.called); - - alertHTML = "<!doctype html><body onload=\"alert('');\"></body>"; - alertCallbackData.expectedMessage = ""; - alertCallbackData.called = false; - ewk_view_html_string_load(webView(), alertHTML, 0, 0); - EXPECT_TRUE(waitUntilLoadFinished()); - EXPECT_TRUE(alertCallbackData.called); - - alertHTML = "<!doctype html><body onload=\"alert(null);\"></body>"; - alertCallbackData.expectedMessage = "null"; - alertCallbackData.called = false; - ewk_view_html_string_load(webView(), alertHTML, 0, 0); - EXPECT_TRUE(waitUntilLoadFinished()); - EXPECT_TRUE(alertCallbackData.called); - - alertHTML = "<!doctype html><body onload=\"alert();\"></body>"; - alertCallbackData.expectedMessage = "undefined"; - alertCallbackData.called = false; - ewk_view_html_string_load(webView(), alertHTML, 0, 0); - EXPECT_TRUE(waitUntilLoadFinished()); - EXPECT_TRUE(alertCallbackData.called); - - ewkViewClass()->run_javascript_alert = 0; - - alertCallbackData.called = false; - ewk_view_html_string_load(webView(), alertHTML, 0, 0); - EXPECT_TRUE(waitUntilLoadFinished()); - EXPECT_FALSE(alertCallbackData.called); -} - -TEST_F(EWK2ViewTest, ewk_view_run_javascript_confirm) -{ - ewkViewClass()->run_javascript_confirm = checkConfirm; - - const char* confirmHTML = "<!doctype html><body onload=\"document.title = confirm('Confirm message');\"></body>"; - confirmCallbackData.expectedMessage = "Confirm message"; - confirmCallbackData.result = true; - confirmCallbackData.called = false; - ewk_view_html_string_load(webView(), confirmHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("true")); - EXPECT_STREQ("true", ewk_view_title_get(webView())); - EXPECT_TRUE(confirmCallbackData.called); - - confirmCallbackData.expectedMessage = "Confirm message"; - confirmCallbackData.result = false; - confirmCallbackData.called = false; - ewk_view_html_string_load(webView(), confirmHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("false")); - EXPECT_STREQ("false", ewk_view_title_get(webView())); - EXPECT_TRUE(confirmCallbackData.called); - - confirmHTML = "<!doctype html><body onload=\"document.title = confirm('');\"></body>"; - confirmCallbackData.expectedMessage = ""; - confirmCallbackData.result = true; - confirmCallbackData.called = false; - ewk_view_html_string_load(webView(), confirmHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("true")); - EXPECT_STREQ("true", ewk_view_title_get(webView())); - EXPECT_TRUE(confirmCallbackData.called); - - confirmHTML = "<!doctype html><body onload=\"document.title = confirm(null);\"></body>"; - confirmCallbackData.expectedMessage = "null"; - confirmCallbackData.result = true; - confirmCallbackData.called = false; - ewk_view_html_string_load(webView(), confirmHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("true")); - EXPECT_STREQ("true", ewk_view_title_get(webView())); - EXPECT_TRUE(confirmCallbackData.called); - - confirmHTML = "<!doctype html><body onload=\"document.title = confirm();\"></body>"; - confirmCallbackData.expectedMessage = "undefined"; - confirmCallbackData.result = true; - confirmCallbackData.called = false; - ewk_view_html_string_load(webView(), confirmHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("true")); - EXPECT_STREQ("true", ewk_view_title_get(webView())); - EXPECT_TRUE(confirmCallbackData.called); - - ewkViewClass()->run_javascript_confirm = 0; - - confirmCallbackData.called = false; - ewk_view_html_string_load(webView(), confirmHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("false")); - EXPECT_STREQ("false", ewk_view_title_get(webView())); - EXPECT_FALSE(confirmCallbackData.called); -} - -TEST_F(EWK2ViewTest, ewk_view_run_javascript_prompt) -{ - static const char promptMessage[] = "Prompt message"; - static const char promptResult[] = "Prompt result"; - - ewkViewClass()->run_javascript_prompt = checkPrompt; - - const char* promptHTML = "<!doctype html><body onload=\"document.title = prompt('Prompt message', 'Prompt default value');\"></body>"; - promptCallbackData.expectedMessage = promptMessage; - promptCallbackData.expectedDefaultValue = "Prompt default value"; - promptCallbackData.result = promptResult; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo(promptResult)); - EXPECT_STREQ(promptResult, ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - promptHTML = "<!doctype html><body onload=\"document.title = prompt('Prompt message', '');\"></body>"; - promptCallbackData.expectedMessage = promptMessage; - promptCallbackData.expectedDefaultValue = ""; - promptCallbackData.result = promptResult; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo(promptResult)); - EXPECT_STREQ(promptResult, ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - promptHTML = "<!doctype html><body onload=\"document.title = prompt('Prompt message');\"></body>"; - promptCallbackData.expectedMessage = promptMessage; - promptCallbackData.expectedDefaultValue = ""; - promptCallbackData.result = promptResult; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo(promptResult)); - EXPECT_STREQ(promptResult, ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - promptHTML = "<!doctype html><body onload=\"document.title = prompt('');\"></body>"; - promptCallbackData.expectedMessage = ""; - promptCallbackData.expectedDefaultValue = ""; - promptCallbackData.result = promptResult; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo(promptResult)); - EXPECT_STREQ(promptResult, ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - promptHTML = "<!doctype html><body onload=\"document.title = prompt();\"></body>"; - promptCallbackData.expectedMessage = "undefined"; - promptCallbackData.expectedDefaultValue = ""; - promptCallbackData.result = promptResult; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo(promptResult)); - EXPECT_STREQ(promptResult, ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - promptHTML = "<html><head><title>Default title</title></head>" - "<body onload=\"var promptResult = prompt('Prompt message');" - "if (promptResult == null) document.title='null';" - "else document.title = promptResult;\"></body></html>"; - promptCallbackData.expectedMessage = promptMessage; - promptCallbackData.expectedDefaultValue = ""; - promptCallbackData.result = ""; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("")); - EXPECT_STREQ("", ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - promptCallbackData.expectedMessage = promptMessage; - promptCallbackData.expectedDefaultValue = ""; - promptCallbackData.result = 0; - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("null")); - EXPECT_STREQ("null", ewk_view_title_get(webView())); - EXPECT_TRUE(promptCallbackData.called); - - ewkViewClass()->run_javascript_prompt = 0; - - promptCallbackData.called = false; - ewk_view_html_string_load(webView(), promptHTML, 0, 0); - EXPECT_TRUE(waitUntilTitleChangedTo("null")); - EXPECT_STREQ("null", ewk_view_title_get(webView())); - EXPECT_FALSE(promptCallbackData.called); -} - -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(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 }; - Ewk_Touch_Point point2 = { 1, 0, 0, EVAS_TOUCH_POINT_DOWN }; - points = eina_list_append(points, &point1); - points = eina_list_append(points, &point2); - ASSERT_TRUE(ewk_view_feed_touch_event(webView(), EWK_TOUCH_START, points, evas_key_modifier_get(evas_object_evas_get(webView())))); - - point1.state = EVAS_TOUCH_POINT_STILL; - point2.x = 100; - point2.y = 100; - point2.state = EVAS_TOUCH_POINT_MOVE; - ASSERT_TRUE(ewk_view_feed_touch_event(webView(), EWK_TOUCH_MOVE, points, evas_key_modifier_get(evas_object_evas_get(webView())))); - - point2.state = EVAS_TOUCH_POINT_UP; - ASSERT_TRUE(ewk_view_feed_touch_event(webView(), EWK_TOUCH_END, points, evas_key_modifier_get(evas_object_evas_get(webView())))); - points = eina_list_remove(points, &point2); - - point1.state = EVAS_TOUCH_POINT_CANCEL; - ASSERT_TRUE(ewk_view_feed_touch_event(webView(), EWK_TOUCH_CANCEL, points, evas_key_modifier_get(evas_object_evas_get(webView())))); - points = eina_list_remove(points, &point1); - - eina_list_free(points); -} - -TEST_F(EWK2ViewTest, ewk_view_text_find) -{ - const char textFindHTML[] = - "<!DOCTYPE html>" - "<body>" - "apple apple apple banana banana coconut" - "</body>"; - ewk_view_html_string_load(webView(), textFindHTML, 0, 0); - waitUntilLoadFinished(); - - int matchCount = -1; - evas_object_smart_callback_add(webView(), "text,found", onTextFound, &matchCount); - - ewk_view_text_find(webView(), "apple", EWK_FIND_OPTIONS_SHOW_OVERLAY, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(3, matchCount); - - matchCount = -1; - ewk_view_text_find(webView(), "mango", EWK_FIND_OPTIONS_SHOW_OVERLAY, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(0, matchCount); - - evas_object_smart_callback_del(webView(), "text,found", onTextFound); -} - -TEST_F(EWK2ViewTest, ewk_view_text_matches_count) -{ - const char textFindHTML[] = - "<!DOCTYPE html>" - "<body>" - "apple Apple apple apple banana bananaApple banana coconut" - "</body>"; - ewk_view_html_string_load(webView(), textFindHTML, 0, 0); - waitUntilLoadFinished(); - - int matchCount = -1; - evas_object_smart_callback_add(webView(), "text,found", onTextFound, &matchCount); - - ewk_view_text_matches_count(webView(), "apple", EWK_FIND_OPTIONS_NONE, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(3, matchCount); - - matchCount = -1; - ewk_view_text_matches_count(webView(), "apple", EWK_FIND_OPTIONS_CASE_INSENSITIVE, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(5, matchCount); - - matchCount = -1; - ewk_view_text_matches_count(webView(), "Apple", EWK_FIND_OPTIONS_AT_WORD_STARTS, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(1, matchCount); - - matchCount = -1; - ewk_view_text_matches_count(webView(), "Apple", EWK_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(2, matchCount); - - matchCount = -1; - ewk_view_text_matches_count(webView(), "mango", EWK_FIND_OPTIONS_NONE, 100); - while (matchCount < 0) - ecore_main_loop_iterate(); - EXPECT_EQ(0, matchCount); - - // If we have more matches than allowed, -1 is returned as a matched count. - matchCount = -2; - ewk_view_text_matches_count(webView(), "apple", EWK_FIND_OPTIONS_NONE, 2); - while (matchCount < -1) - ecore_main_loop_iterate(); - EXPECT_EQ(-1, matchCount); - - evas_object_smart_callback_del(webView(), "text,found", onTextFound); -} - -TEST_F(EWK2ViewTest, ewk_view_touch_events_enabled) -{ - ASSERT_FALSE(ewk_view_touch_events_enabled_get(webView())); - - ASSERT_TRUE(ewk_view_touch_events_enabled_set(webView(), true)); - ASSERT_TRUE(ewk_view_touch_events_enabled_get(webView())); - - ASSERT_TRUE(ewk_view_touch_events_enabled_set(webView(), 2)); - ASSERT_TRUE(ewk_view_touch_events_enabled_get(webView())); - - const char* touchHTML = - "<!doctype html><body><div style=\"width:100px; height:100px;\" " - "ontouchstart=\"document.title='touchstarted' + event.touches.length;\" " - "ontouchmove=\"document.title='touchmoved' + event.touches.length;\" " - "ontouchend=\"document.title='touchended' + event.touches.length;\">" - "</div></body>"; - - ewk_view_html_string_load(webView(), touchHTML, "file:///", 0); - ASSERT_TRUE(waitUntilLoadFinished()); - - mouseDown(10, 10); - ASSERT_TRUE(waitUntilTitleChangedTo("touchstarted1")); - - multiDown(1, 30, 30); - ASSERT_TRUE(waitUntilTitleChangedTo("touchstarted2")); - - multiMove(1, 40, 40); - ASSERT_TRUE(waitUntilTitleChangedTo("touchmoved2")); - - multiUp(1, 40, 40); - ASSERT_TRUE(waitUntilTitleChangedTo("touchended1")); - - mouseMove(20, 20); - ASSERT_TRUE(waitUntilTitleChangedTo("touchmoved1")); - - mouseUp(20, 20); - ASSERT_TRUE(waitUntilTitleChangedTo("touchended0")); - - ASSERT_TRUE(ewk_view_touch_events_enabled_set(webView(), false)); - ASSERT_FALSE(ewk_view_touch_events_enabled_get(webView())); -} - -TEST_F(EWK2ViewTest, window_move_resize) -{ - int x, y, width, height; - Ecore_Evas* ee = ecore_evas_ecore_evas_get(evas_object_evas_get(webView())); - ecore_evas_geometry_get(ee, 0, 0, &width, &height); - - EXPECT_EQ(800, width); - EXPECT_EQ(600, height); - - ewk_view_url_set(webView(), environment->urlForResource("window_move_resize.html").data()); - ASSERT_TRUE(waitUntilTitleChangedTo("Moved and resized")); - - // Check that the window has been moved and resized. - ecore_evas_request_geometry_get(ee, &x, &y, &width, &height); - EXPECT_EQ(150, x); - EXPECT_EQ(200, y); - EXPECT_EQ(200, width); - EXPECT_EQ(100, height); -} - -TEST_F(EWK2ViewTest, ewk_view_inspector) -{ -#if ENABLE(INSPECTOR) - ASSERT_TRUE(ewk_view_inspector_show(webView())); - ASSERT_TRUE(ewk_view_inspector_close(webView())); -#else - ASSERT_FALSE(ewk_view_inspector_show(webView())); - ASSERT_FALSE(ewk_view_inspector_close(webView())); -#endif -} - -TEST_F(EWK2ViewTest, DISABLED_ewk_view_scale) -{ - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - - // Default scale value is 1.0. - ASSERT_FLOAT_EQ(1, ewk_view_scale_get(webView())); - - ASSERT_TRUE(ewk_view_scale_set(webView(), 1.2, 0, 0)); - // Reload page to check the page scale value. - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_FLOAT_EQ(1.2, ewk_view_scale_get(webView())); - - ASSERT_TRUE(ewk_view_scale_set(webView(), 1.5, 0, 0)); - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_FLOAT_EQ(1.5, ewk_view_scale_get(webView())); - - ASSERT_TRUE(ewk_view_scale_set(webView(), 1, 0, 0)); - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_FLOAT_EQ(1, ewk_view_scale_get(webView())); -} - -TEST_F(EWK2ViewTest, ewk_view_pagination) -{ - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - - // Default pagination value is EWK_PAGINATION_MODE_UNPAGINATED - ASSERT_EQ(EWK_PAGINATION_MODE_UNPAGINATED, ewk_view_pagination_mode_get(webView())); - - ASSERT_TRUE(ewk_view_pagination_mode_set(webView(), EWK_PAGINATION_MODE_LEFT_TO_RIGHT)); - // Reload page to check the pagination mode. - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_EQ(EWK_PAGINATION_MODE_LEFT_TO_RIGHT, ewk_view_pagination_mode_get(webView())); - - ASSERT_TRUE(ewk_view_pagination_mode_set(webView(), EWK_PAGINATION_MODE_RIGHT_TO_LEFT)); - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_EQ(EWK_PAGINATION_MODE_RIGHT_TO_LEFT, ewk_view_pagination_mode_get(webView())); - - ASSERT_TRUE(ewk_view_pagination_mode_set(webView(), EWK_PAGINATION_MODE_TOP_TO_BOTTOM)); - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_EQ(EWK_PAGINATION_MODE_TOP_TO_BOTTOM, ewk_view_pagination_mode_get(webView())); - - ASSERT_TRUE(ewk_view_pagination_mode_set(webView(), EWK_PAGINATION_MODE_BOTTOM_TO_TOP)); - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_EQ(EWK_PAGINATION_MODE_BOTTOM_TO_TOP, ewk_view_pagination_mode_get(webView())); - - ASSERT_TRUE(ewk_view_pagination_mode_set(webView(), EWK_PAGINATION_MODE_UNPAGINATED)); - ASSERT_TRUE(loadUrlSync(environment->defaultTestPageUrl())); - ASSERT_EQ(EWK_PAGINATION_MODE_UNPAGINATED, ewk_view_pagination_mode_get(webView())); -} - -TEST_F(EWK2ViewTest, ewk_context_vibration_client_callbacks_set) -{ - VibrationCbData data = { false, false, 0, 5000 }; - evas_object_smart_callback_add(webView(), "vibrate", onVibrate, &data); - evas_object_smart_callback_add(webView(), "cancel,vibration", onCancelVibration, &data); - - // Vibrate for 5 seconds. - loadVibrationHTMLString(webView(), "5000", true, &data); - ASSERT_TRUE(data.didReceiveVibrate); - - // Cancel any existing vibrations. - loadVibrationHTMLString(webView(), "0", true, &data); - ASSERT_TRUE(data.didReceiveCancelVibration); - - // This case the pattern will cause the device to vibrate for 200 ms, be still for 100 ms, and then vibrate for 5000 ms. - loadVibrationHTMLString(webView(), "[200, 100, 5000]", true, &data); - ASSERT_EQ(2, data.vibrateCalledCount); - ASSERT_TRUE(data.didReceiveVibrate); - - // Cancel outstanding vibration pattern. - loadVibrationHTMLString(webView(), "[0]", true, &data); - ASSERT_TRUE(data.didReceiveCancelVibration); - - // Stop listening for vibration events, by calling the function with null for the callbacks. - evas_object_smart_callback_del(webView(), "vibrate", onVibrate); - evas_object_smart_callback_del(webView(), "cancel,vibration", onCancelVibration); - - // Make sure we don't receive vibration event. - loadVibrationHTMLString(webView(), "[5000]", false, &data); - ASSERT_TRUE(waitUntilTitleChangedTo("Loaded")); - ASSERT_STREQ("Loaded", ewk_view_title_get(webView())); - ASSERT_FALSE(data.didReceiveVibrate); - - // Make sure we don't receive cancel vibration event. - loadVibrationHTMLString(webView(), "0", false, &data); - ASSERT_TRUE(waitUntilTitleChangedTo("Loaded")); - ASSERT_STREQ("Loaded", ewk_view_title_get(webView())); - 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 deleted file mode 100644 index 24ca9a4ae..000000000 --- a/Source/WebKit2/UIProcess/API/efl/tests/test_ewk2_window_features.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2012 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" -#include <EWebKit2.h> -#include <Ecore.h> -#include <WebCore/IntRect.h> - -using namespace EWK2UnitTest; -using namespace WebCore; - -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(); - - const char windowHTML[] = "<html><body onLoad=\"window.open('', '');\"></body></html>"; - - ewkViewClass()->window_create = createDefaultWindow; - - ewk_view_html_string_load(view, windowHTML, 0, 0); - ASSERT_TRUE(waitUntilLoadFinished()); -} - -TEST_F(EWK2WindowFeaturesTest, ewk_window_features_property_get) -{ - Evas_Object* view = webView(); - - const char windowHTML[] = "<html><body onLoad=\"window.open('', '', 'left=100,top=150,width=400,height=400,location=no,menubar=no,status=yes,toolbar=no,scrollbars=yes,resizable=yes,fullscreen=no');\"></body></html>"; - - ewkViewClass()->window_create = createWindow; - - ewk_view_html_string_load(view, windowHTML, 0, 0); - ASSERT_TRUE(waitUntilLoadFinished()); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp b/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp deleted file mode 100644 index bd214f3b6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 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. - */ - -#include "config.h" -#include "PageClientImpl.h" - -#include "DrawingAreaProxyImpl.h" -#include "NativeWebKeyboardEvent.h" -#include "NativeWebMouseEvent.h" -#include "NotImplemented.h" -#include "WebContext.h" -#include "WebContextMenuProxyGtk.h" -#include "WebEventFactory.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebPageProxy.h" -#include "WebPopupMenuProxyGtk.h" -#include <WebCore/Cursor.h> -#include <WebCore/EventNames.h> -#include <WebCore/GtkUtilities.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -using namespace WebCore; - -namespace WebKit { - -PageClientImpl::PageClientImpl(GtkWidget* viewWidget) - : m_viewWidget(viewWidget) -{ -} - -PageClientImpl::~PageClientImpl() -{ -} - -void PageClientImpl::getEditorCommandsForKeyEvent(const NativeWebKeyboardEvent& event, const AtomicString& eventType, Vector<WTF::String>& commandList) -{ - ASSERT(eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent); - - KeyBindingTranslator::EventType type = eventType == eventNames().keydownEvent ? - KeyBindingTranslator::KeyDown : KeyBindingTranslator::KeyPress; - m_keyBindingTranslator.getEditorCommandsForKeyEvent(const_cast<GdkEventKey*>(&event.nativeEvent()->key), type, commandList); -} - -// PageClient's pure virtual functions -PassOwnPtr<DrawingAreaProxy> PageClientImpl::createDrawingAreaProxy() -{ - return DrawingAreaProxyImpl::create(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_viewWidget))); -} - -void PageClientImpl::setViewNeedsDisplay(const WebCore::IntRect& rect) -{ - gtk_widget_queue_draw_area(m_viewWidget, rect.x(), rect.y(), rect.width(), rect.height()); -} - -void PageClientImpl::displayView() -{ - notImplemented(); -} - -void PageClientImpl::scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset) -{ - setViewNeedsDisplay(scrollRect); -} - -WebCore::IntSize PageClientImpl::viewSize() -{ - if (!gtk_widget_get_realized(m_viewWidget)) - return IntSize(); - GtkAllocation allocation; - gtk_widget_get_allocation(m_viewWidget, &allocation); - return IntSize(allocation.width, allocation.height); -} - -bool PageClientImpl::isViewWindowActive() -{ - return webkitWebViewBaseIsInWindowActive(WEBKIT_WEB_VIEW_BASE(m_viewWidget)); -} - -bool PageClientImpl::isViewFocused() -{ - return webkitWebViewBaseIsFocused(WEBKIT_WEB_VIEW_BASE(m_viewWidget)); -} - -bool PageClientImpl::isViewVisible() -{ - return webkitWebViewBaseIsVisible(WEBKIT_WEB_VIEW_BASE(m_viewWidget)); -} - -bool PageClientImpl::isViewInWindow() -{ - return webkitWebViewBaseIsInWindow(WEBKIT_WEB_VIEW_BASE(m_viewWidget)); -} - -void PageClientImpl::PageClientImpl::processDidCrash() -{ - notImplemented(); -} - -void PageClientImpl::didRelaunchProcess() -{ - notImplemented(); -} - -void PageClientImpl::takeFocus(bool) -{ - notImplemented(); -} - -void PageClientImpl::toolTipChanged(const String&, const String& newToolTip) -{ - webkitWebViewBaseSetTooltipText(WEBKIT_WEB_VIEW_BASE(m_viewWidget), newToolTip.utf8().data()); -} - -void PageClientImpl::setCursor(const Cursor& cursor) -{ - if (!gtk_widget_get_realized(m_viewWidget)) - return; - - // [GTK] Widget::setCursor() gets called frequently - // http://bugs.webkit.org/show_bug.cgi?id=16388 - // Setting the cursor may be an expensive operation in some backends, - // so don't re-set the cursor if it's already set to the target value. - GdkWindow* window = gtk_widget_get_window(m_viewWidget); - GdkCursor* currentCursor = gdk_window_get_cursor(window); - GdkCursor* newCursor = cursor.platformCursor().get(); - if (currentCursor != newCursor) - gdk_window_set_cursor(window, newCursor); -} - -void PageClientImpl::setCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves) -{ - notImplemented(); -} - -void PageClientImpl::didChangeViewportProperties(const WebCore::ViewportAttributes&) -{ - notImplemented(); -} - -void PageClientImpl::registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo) -{ - notImplemented(); -} - -void PageClientImpl::clearAllEditCommands() -{ - notImplemented(); -} - -bool PageClientImpl::canUndoRedo(WebPageProxy::UndoOrRedo) -{ - notImplemented(); - return false; -} - -void PageClientImpl::executeUndoRedo(WebPageProxy::UndoOrRedo) -{ - notImplemented(); -} - -FloatRect PageClientImpl::convertToDeviceSpace(const FloatRect& viewRect) -{ - notImplemented(); - return viewRect; -} - -FloatRect PageClientImpl::convertToUserSpace(const FloatRect& viewRect) -{ - notImplemented(); - return viewRect; -} - -IntPoint PageClientImpl::screenToWindow(const IntPoint& point) -{ - IntPoint widgetPositionOnScreen = convertWidgetPointToScreenPoint(m_viewWidget, IntPoint()); - IntPoint result(point); - result.move(-widgetPositionOnScreen.x(), -widgetPositionOnScreen.y()); - return result; -} - -IntRect PageClientImpl::windowToScreen(const IntRect& rect) -{ - return IntRect(convertWidgetPointToScreenPoint(m_viewWidget, rect.location()), rect.size()); -} - -void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool wasEventHandled) -{ - if (wasEventHandled) - return; - if (event.isFakeEventForComposition()) - return; - - WebKitWebViewBase* webkitWebViewBase = WEBKIT_WEB_VIEW_BASE(m_viewWidget); - webkitWebViewBaseForwardNextKeyEvent(webkitWebViewBase); - gtk_main_do_event(event.nativeEvent()); -} - -PassRefPtr<WebPopupMenuProxy> PageClientImpl::createPopupMenuProxy(WebPageProxy* page) -{ - return WebPopupMenuProxyGtk::create(m_viewWidget, page); -} - -PassRefPtr<WebContextMenuProxy> PageClientImpl::createContextMenuProxy(WebPageProxy* page) -{ - return WebContextMenuProxyGtk::create(m_viewWidget, page); -} - -#if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorPicker> PageClientImpl::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) -{ - notImplemented(); - return 0; -} -#endif - -void PageClientImpl::setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate) -{ - notImplemented(); -} - -#if USE(ACCELERATED_COMPOSITING) -void PageClientImpl::enterAcceleratedCompositingMode(const LayerTreeContext&) -{ - notImplemented(); -} - -void PageClientImpl::exitAcceleratedCompositingMode() -{ - notImplemented(); -} - -void PageClientImpl::updateAcceleratedCompositingMode(const LayerTreeContext&) -{ - notImplemented(); -} -#endif // USE(ACCELERATED_COMPOSITING) - -void PageClientImpl::pageClosed() -{ - notImplemented(); -} - -void PageClientImpl::preferencesDidChange() -{ - notImplemented(); -} - -void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&) -{ - notImplemented(); -} - -void PageClientImpl::updateTextInputState() -{ - webkitWebViewBaseUpdateTextInputState(WEBKIT_WEB_VIEW_BASE(m_viewWidget)); -} - -void PageClientImpl::startDrag(const WebCore::DragData& dragData, PassRefPtr<ShareableBitmap> dragImage) -{ - webkitWebViewBaseStartDrag(WEBKIT_WEB_VIEW_BASE(m_viewWidget), dragData, dragImage); -} - -void PageClientImpl::handleDownloadRequest(DownloadProxy* download) -{ - webkitWebViewBaseHandleDownloadRequest(WEBKIT_WEB_VIEW_BASE(m_viewWidget), download); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h b/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h deleted file mode 100644 index a7469cdbf..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/PageClientImpl.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 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. - */ - -#ifndef PageClientImpl_h -#define PageClientImpl_h - -#include "KeyBindingTranslator.h" -#include "PageClient.h" -#include "WebPageProxy.h" -#include "WindowsKeyboardCodes.h" -#include <WebCore/IntSize.h> -#include <gtk/gtk.h> - -namespace WebKit { - -class DrawingAreaProxy; -class WebPageNamespace; - -class PageClientImpl : public PageClient { -public: - ~PageClientImpl(); - static PassOwnPtr<PageClientImpl> create(GtkWidget* viewWidget) - { - return adoptPtr(new PageClientImpl(viewWidget)); - } - - GtkWidget* viewWidget() { return m_viewWidget; } - -private: - explicit PageClientImpl(GtkWidget*); - - 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(); - virtual bool isViewFocused(); - virtual bool isViewVisible(); - virtual bool isViewInWindow(); - 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&); - virtual void setCursorHiddenUntilMouseMoves(bool); - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); - virtual void registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo); - virtual void clearAllEditCommands(); - virtual bool canUndoRedo(WebPageProxy::UndoOrRedo); - virtual void executeUndoRedo(WebPageProxy::UndoOrRedo); - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&); - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&); - virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&); - virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&); - virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool wasEventHandled); - virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*); - virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); -#if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& intialColor, const WebCore::IntRect&); -#endif - virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate); - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); - virtual void getEditorCommandsForKeyEvent(const NativeWebKeyboardEvent&, const AtomicString&, Vector<WTF::String>&); - virtual void updateTextInputState(); - virtual void startDrag(const WebCore::DragData&, PassRefPtr<ShareableBitmap> dragImage); - -#if USE(ACCELERATED_COMPOSITING) - virtual void enterAcceleratedCompositingMode(const LayerTreeContext&); - virtual void exitAcceleratedCompositingMode(); - virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); -#endif - - virtual void handleDownloadRequest(DownloadProxy*); - - // Members of PageClientImpl class - GtkWidget* m_viewWidget; - WebCore::KeyBindingTranslator m_keyBindingTranslator; -}; - -} // namespace WebKit - -#endif // PageClientImpl_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.cpp deleted file mode 100644 index 0699da7ee..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.cpp +++ /dev/null @@ -1,147 +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 "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 deleted file mode 100644 index 7d4de2a6d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitAuthenticationDialog.h +++ /dev/null @@ -1,55 +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. - */ - -#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 deleted file mode 100644 index 47aaa4cc8..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitBackForwardList.h" - -#include "WebKitBackForwardListPrivate.h" -#include "WebKitMarshal.h" -#include "WebKitPrivate.h" -#include <wtf/gobject/GRefPtr.h> - -/** - * SECTION: WebKitBackForwardList - * @Short_description: List of visited pages - * @Title: WebKitBackForwardList - * @See_also: #WebKitWebView, #WebKitBackForwardListItem - * - * WebKitBackForwardList maintains a list of visited pages used to - * navigate to recent pages. Items are inserted in the list in the - * order they are visited. - * - * WebKitBackForwardList also maintains the notion of the current item - * (which is always at index 0), the preceding item (which is at index -1), - * and the following item (which is at index 1). - * Methods webkit_web_view_go_back() and webkit_web_view_go_forward() move - * the current item backward or forward by one. Method - * webkit_web_view_go_to_back_forward_list_item() sets the current item to the - * specified item. All other methods returning #WebKitBackForwardListItem<!-- -->s - * do not change the value of the current item, they just return the requested - * item or items. - */ - -using namespace WebKit; - -enum { - CHANGED, - - LAST_SIGNAL -}; - -typedef HashMap<WebBackForwardListItem*, GRefPtr<WebKitBackForwardListItem> > BackForwardListItemsMap; - -struct _WebKitBackForwardListPrivate { - WebBackForwardList* backForwardItems; - BackForwardListItemsMap itemsMap; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitBackForwardList, webkit_back_forward_list, G_TYPE_OBJECT) - -static void webkit_back_forward_list_class_init(WebKitBackForwardListClass* listClass) -{ - /** - * WebKitBackForwardList::changed: - * @back_forward_list: the #WebKitBackForwardList on which the signal was emitted - * @item_added: (allow-none): the #WebKitBackForwardListItem added or %NULL - * @items_removed: a #GList of #WebKitBackForwardListItem<!-- -->s - * - * This signal is emitted when @back_forward_list changes. This happens - * when the current item is updated, a new item is added or one or more - * items are removed. Note that both @item_added and @items_removed can - * %NULL when only the current item is updated. Items are only removed - * when the list is cleared or the maximum items limit is reached. - */ - signals[CHANGED] = - g_signal_new("changed", - G_TYPE_FROM_CLASS(listClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - webkit_marshal_VOID__OBJECT_POINTER, - G_TYPE_NONE, 2, - WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM, - G_TYPE_POINTER); -} - -static WebKitBackForwardListItem* webkitBackForwardListGetOrCreateItem(WebKitBackForwardList* list, WebBackForwardListItem* webListItem) -{ - if (!webListItem) - return 0; - - WebKitBackForwardListPrivate* priv = list->priv; - GRefPtr<WebKitBackForwardListItem> listItem = priv->itemsMap.get(webListItem); - if (listItem) - return listItem.get(); - - listItem = webkitBackForwardListItemGetOrCreate(webListItem); - priv->itemsMap.set(webListItem, listItem); - - return listItem.get(); -} - -static GList* webkitBackForwardListCreateList(WebKitBackForwardList* list, ImmutableArray* backForwardItems) -{ - if (!backForwardItems) - return 0; - - GList* returnValue = 0; - for (size_t i = 0; i < backForwardItems->size(); ++i) { - WebBackForwardListItem* webItem = static_cast<WebBackForwardListItem*>(backForwardItems->at(i)); - returnValue = g_list_prepend(returnValue, webkitBackForwardListGetOrCreateItem(list, webItem)); - } - - return returnValue; -} - -WebKitBackForwardList* webkitBackForwardListCreate(WebBackForwardList* backForwardItems) -{ - WebKitBackForwardList* list = WEBKIT_BACK_FORWARD_LIST(g_object_new(WEBKIT_TYPE_BACK_FORWARD_LIST, NULL)); - list->priv->backForwardItems = backForwardItems; - - return list; -} - -void webkitBackForwardListChanged(WebKitBackForwardList* backForwardList, WebBackForwardListItem* webAddedItem, ImmutableArray* webRemovedItems) -{ - WebKitBackForwardListItem* addedItem = webkitBackForwardListGetOrCreateItem(backForwardList, webAddedItem); - GList* removedItems = 0; - - size_t removedItemsSize = webRemovedItems ? webRemovedItems->size() : 0; - WebKitBackForwardListPrivate* priv = backForwardList->priv; - for (size_t i = 0; i < removedItemsSize; ++i) { - WebBackForwardListItem* webItem = static_cast<WebBackForwardListItem*>(webRemovedItems->at(i)); - removedItems = g_list_prepend(removedItems, g_object_ref(G_OBJECT(priv->itemsMap.get(webItem).get()))); - priv->itemsMap.remove(webItem); - } - - g_signal_emit(backForwardList, signals[CHANGED], 0, addedItem, removedItems, NULL); - g_list_free_full(removedItems, static_cast<GDestroyNotify>(g_object_unref)); -} - -/** - * webkit_back_forward_list_get_current_item: - * @back_forward_list: a #WebKitBackForwardList - * - * Returns the current item in @back_forward_list. - * - * Returns: (transfer none): a #WebKitBackForwardListItem - * or %NULL if @back_forward_list is empty. - */ -WebKitBackForwardListItem* webkit_back_forward_list_get_current_item(WebKitBackForwardList* backForwardList) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - return webkitBackForwardListGetOrCreateItem(backForwardList, backForwardList->priv->backForwardItems->currentItem()); -} - -/** - * webkit_back_forward_list_get_back_item: - * @back_forward_list: a #WebKitBackForwardList - * - * Returns the item that precedes the current item. - * - * Returns: (transfer none): the #WebKitBackForwardListItem - * preceding the current item or %NULL. - */ -WebKitBackForwardListItem* webkit_back_forward_list_get_back_item(WebKitBackForwardList* backForwardList) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - return webkitBackForwardListGetOrCreateItem(backForwardList, backForwardList->priv->backForwardItems->backItem()); -} - -/** - * webkit_back_forward_list_get_forward_item: - * @back_forward_list: a #WebKitBackForwardList - * - * Returns the item that follows the current item. - * - * Returns: (transfer none): the #WebKitBackForwardListItem - * following the current item or %NULL. - */ -WebKitBackForwardListItem* webkit_back_forward_list_get_forward_item(WebKitBackForwardList* backForwardList) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - return webkitBackForwardListGetOrCreateItem(backForwardList, backForwardList->priv->backForwardItems->forwardItem()); -} - -/** - * webkit_back_forward_list_get_nth_item: - * @back_forward_list: a #WebKitBackForwardList - * @index: the index of the item - * - * Returns the item at a given index relative to the current item. - * - * Returns: (transfer none): the #WebKitBackForwardListItem - * located at the specified index relative to the current item. - */ -WebKitBackForwardListItem* webkit_back_forward_list_get_nth_item(WebKitBackForwardList* backForwardList, gint index) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - return webkitBackForwardListGetOrCreateItem(backForwardList, backForwardList->priv->backForwardItems->itemAtIndex(index)); -} - -/** - * webkit_back_forward_list_get_length: - * @back_forward_list: a #WebKitBackForwardList - * - * Returns: the length of @back_forward_list. - */ -guint webkit_back_forward_list_get_length(WebKitBackForwardList* backForwardList) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - WebKitBackForwardListPrivate* priv = backForwardList->priv; - guint currentItem = webkit_back_forward_list_get_current_item(backForwardList) ? 1 : 0; - return priv->backForwardItems->backListCount() + priv->backForwardItems->forwardListCount() + currentItem; -} - -/** - * webkit_back_forward_list_get_back_list: - * @back_forward_list: a #WebKitBackForwardList - * - * Returns: (element-type WebKit2.BackForwardListItem) (transfer container): a #GList of - * items preceding the current item. - */ -GList* webkit_back_forward_list_get_back_list(WebKitBackForwardList* backForwardList) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - return webkit_back_forward_list_get_back_list_with_limit(backForwardList, backForwardList->priv->backForwardItems->backListCount()); -} - -/** - * webkit_back_forward_list_get_back_list_with_limit: - * @back_forward_list: a #WebKitBackForwardList - * @limit: the number of items to retrieve - * - * Returns: (element-type WebKit2.BackForwardListItem) (transfer container): a #GList of - * items preceding the current item limited by @limit. - */ -GList* webkit_back_forward_list_get_back_list_with_limit(WebKitBackForwardList* backForwardList, guint limit) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - WebKitBackForwardListPrivate* priv = backForwardList->priv; - RefPtr<ImmutableArray> immutableArray = priv->backForwardItems->backListAsImmutableArrayWithLimit(limit); - return webkitBackForwardListCreateList(backForwardList, immutableArray.get()); -} - -/** - * webkit_back_forward_list_get_forward_list: - * @back_forward_list: a #WebKitBackForwardList - * - * Returns: (element-type WebKit2.BackForwardListItem) (transfer container): a #GList of - * items following the current item. - */ -GList* webkit_back_forward_list_get_forward_list(WebKitBackForwardList* backForwardList) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - return webkit_back_forward_list_get_forward_list_with_limit(backForwardList, backForwardList->priv->backForwardItems->forwardListCount()); -} - -/** - * webkit_back_forward_list_get_forward_list_with_limit: - * @back_forward_list: a #WebKitBackForwardList - * @limit: the number of items to retrieve - * - * Returns: (element-type WebKit2.BackForwardListItem) (transfer container): a #GList of - * items following the current item limited by @limit. - */ -GList* webkit_back_forward_list_get_forward_list_with_limit(WebKitBackForwardList* backForwardList, guint limit) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST(backForwardList), 0); - - WebKitBackForwardListPrivate* priv = backForwardList->priv; - 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 deleted file mode 100644 index 6fbd42ab0..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardList.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitBackForwardList_h -#define WebKitBackForwardList_h - -#include <glib-object.h> -#include <webkit2/WebKitBackForwardListItem.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_BACK_FORWARD_LIST (webkit_back_forward_list_get_type()) -#define WEBKIT_BACK_FORWARD_LIST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_BACK_FORWARD_LIST, WebKitBackForwardList)) -#define WEBKIT_BACK_FORWARD_LIST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_BACK_FORWARD_LIST, WebKitBackForwardListClass)) -#define WEBKIT_IS_BACK_FORWARD_LIST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_BACK_FORWARD_LIST)) -#define WEBKIT_IS_BACK_FORWARD_LIST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_BACK_FORWARD_LIST)) -#define WEBKIT_BACK_FORWARD_LIST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_BACK_FORWARD_LIST, WebKitBackForwardListClass)) - -typedef struct _WebKitBackForwardList WebKitBackForwardList; -typedef struct _WebKitBackForwardListClass WebKitBackForwardListClass; -typedef struct _WebKitBackForwardListPrivate WebKitBackForwardListPrivate; - -struct _WebKitBackForwardList { - GObject parent; - - WebKitBackForwardListPrivate *priv; -}; - -struct _WebKitBackForwardListClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_back_forward_list_get_type (void); - -WEBKIT_API WebKitBackForwardListItem * -webkit_back_forward_list_get_current_item (WebKitBackForwardList *back_forward_list); - -WEBKIT_API WebKitBackForwardListItem * -webkit_back_forward_list_get_back_item (WebKitBackForwardList *back_forward_list); - -WEBKIT_API WebKitBackForwardListItem * -webkit_back_forward_list_get_forward_item (WebKitBackForwardList *back_forward_list); - -WEBKIT_API WebKitBackForwardListItem * -webkit_back_forward_list_get_nth_item (WebKitBackForwardList *back_forward_list, - gint index); -WEBKIT_API guint -webkit_back_forward_list_get_length (WebKitBackForwardList *back_forward_list); - -WEBKIT_API GList * -webkit_back_forward_list_get_back_list (WebKitBackForwardList *back_forward_list); - -WEBKIT_API GList * -webkit_back_forward_list_get_back_list_with_limit (WebKitBackForwardList *back_forward_list, - guint limit); - -WEBKIT_API GList * -webkit_back_forward_list_get_forward_list (WebKitBackForwardList *back_forward_list); - -WEBKIT_API GList * -webkit_back_forward_list_get_forward_list_with_limit (WebKitBackForwardList *back_forward_list, - guint limit); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp deleted file mode 100644 index ae18b05ec..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitBackForwardListItem.h" - -#include "WebKitBackForwardListPrivate.h" -#include "WebKitPrivate.h" -#include <wtf/HashMap.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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; - CString title; - CString originalURI; -}; - -WEBKIT_DEFINE_TYPE(WebKitBackForwardListItem, webkit_back_forward_list_item, G_TYPE_INITIALLY_UNOWNED) - -static void webkit_back_forward_list_item_class_init(WebKitBackForwardListItemClass* listItemClass) -{ -} - -typedef HashMap<WebBackForwardListItem*, WebKitBackForwardListItem*> HistoryItemsMap; - -static HistoryItemsMap& historyItemsMap() -{ - DEFINE_STATIC_LOCAL(HistoryItemsMap, itemsMap, ()); - return itemsMap; -} - -static void webkitBackForwardListItemFinalized(gpointer webListItem, GObject* finalizedListItem) -{ - ASSERT(G_OBJECT(historyItemsMap().get(static_cast<WebBackForwardListItem*>(webListItem))) == finalizedListItem); - historyItemsMap().remove(static_cast<WebBackForwardListItem*>(webListItem)); -} - -WebKitBackForwardListItem* webkitBackForwardListItemGetOrCreate(WebBackForwardListItem* webListItem) -{ - if (!webListItem) - return 0; - - WebKitBackForwardListItem* listItem = historyItemsMap().get(webListItem); - if (listItem) - return listItem; - - listItem = WEBKIT_BACK_FORWARD_LIST_ITEM(g_object_new(WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM, NULL)); - listItem->priv->webListItem = webListItem; - - g_object_weak_ref(G_OBJECT(listItem), webkitBackForwardListItemFinalized, webListItem); - historyItemsMap().set(webListItem, listItem); - - return listItem; -} - -WebBackForwardListItem* webkitBackForwardListItemGetItem(WebKitBackForwardListItem* listItem) -{ - return listItem->priv->webListItem.get(); -} - -/** - * webkit_back_forward_list_item_get_uri: - * @list_item: a #WebKitBackForwardListItem - * - * This URI may differ from the original URI if the page was, - * for example, redirected to a new location. - * See also webkit_back_forward_list_item_get_original_uri(). - * - * Returns: the URI of @list_item or %NULL - * when the URI is empty. - */ -const gchar* webkit_back_forward_list_item_get_uri(WebKitBackForwardListItem* listItem) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(listItem), 0); - - WebKitBackForwardListItemPrivate* priv = listItem->priv; - String url = priv->webListItem->url(); - if (url.isEmpty()) - return 0; - - priv->uri = url.utf8(); - return priv->uri.data(); -} - -/** - * webkit_back_forward_list_item_get_title: - * @list_item: a #WebKitBackForwardListItem - * - * Returns: the page title of @list_item or %NULL - * when the title is empty. - */ -const gchar* webkit_back_forward_list_item_get_title(WebKitBackForwardListItem* listItem) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(listItem), 0); - - WebKitBackForwardListItemPrivate* priv = listItem->priv; - String title = priv->webListItem->title(); - if (title.isEmpty()) - return 0; - - priv->title = title.utf8(); - return priv->title.data(); -} - -/** - * webkit_back_forward_list_item_get_original_uri: - * @list_item: a #WebKitBackForwardListItem - * - * See also webkit_back_forward_list_item_get_uri(). - * - * Returns: the original URI of @list_item or %NULL - * when the original URI is empty. - */ -const gchar* webkit_back_forward_list_item_get_original_uri(WebKitBackForwardListItem* listItem) -{ - g_return_val_if_fail(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(listItem), 0); - - WebKitBackForwardListItemPrivate* priv = listItem->priv; - String originalURL = priv->webListItem->originalURL(); - if (originalURL.isEmpty()) - return 0; - - priv->originalURI = originalURL.utf8(); - return priv->originalURI.data(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h deleted file mode 100644 index 5090e516c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListItem.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitBackForwardListItem_h -#define WebKitBackForwardListItem_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM (webkit_back_forward_list_item_get_type()) -#define WEBKIT_BACK_FORWARD_LIST_ITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM, WebKitBackForwardListItem)) -#define WEBKIT_BACK_FORWARD_LIST_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM, WebKitBackForwardListItemClass)) -#define WEBKIT_IS_BACK_FORWARD_LIST_ITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM)) -#define WEBKIT_IS_BACK_FORWARD_LIST_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM)) -#define WEBKIT_BACK_FORWARD_LIST_ITEM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM, WebKitBackForwardListItemClass)) - -typedef struct _WebKitBackForwardListItem WebKitBackForwardListItem; -typedef struct _WebKitBackForwardListItemClass WebKitBackForwardListItemClass; -typedef struct _WebKitBackForwardListItemPrivate WebKitBackForwardListItemPrivate; - -struct _WebKitBackForwardListItem { - GInitiallyUnowned parent; - - WebKitBackForwardListItemPrivate *priv; -}; - -struct _WebKitBackForwardListItemClass { - GInitiallyUnownedClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_back_forward_list_item_get_type (void); - -WEBKIT_API const gchar * -webkit_back_forward_list_item_get_uri (WebKitBackForwardListItem* list_item); - -WEBKIT_API const gchar * -webkit_back_forward_list_item_get_title (WebKitBackForwardListItem* list_item); - -WEBKIT_API const gchar * -webkit_back_forward_list_item_get_original_uri (WebKitBackForwardListItem* list_item); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListPrivate.h deleted file mode 100644 index 540f66594..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitBackForwardListPrivate.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef WebKitBackForwardListPrivate_h -#define WebKitBackForwardListPrivate_h - -#include "WebBackForwardList.h" -#include "WebKitBackForwardList.h" - -WebKitBackForwardList* webkitBackForwardListCreate(WebKit::WebBackForwardList*); -WebKitBackForwardListItem* webkitBackForwardListItemGetOrCreate(WebKit::WebBackForwardListItem*); -WebKit::WebBackForwardListItem* webkitBackForwardListItemGetItem(WebKitBackForwardListItem*); -void webkitBackForwardListChanged(WebKitBackForwardList*, WebKit::WebBackForwardListItem* webAddedItem, WebKit::ImmutableArray* webRemovedItems); - -#endif // WebKitBackForwardListPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp deleted file mode 100644 index 0ab6edba6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.cpp +++ /dev/null @@ -1,318 +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 "WebKitContextMenu.h" - -#include "ImmutableArray.h" -#include "WebContextMenuItem.h" -#include "WebKitContextMenuItemPrivate.h" -#include "WebKitContextMenuPrivate.h" - -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; -}; - -WEBKIT_DEFINE_TYPE(WebKitContextMenu, webkit_context_menu, G_TYPE_OBJECT) - -static void webkitContextMenuDispose(GObject* object) -{ - webkit_context_menu_remove_all(WEBKIT_CONTEXT_MENU(object)); - G_OBJECT_CLASS(webkit_context_menu_parent_class)->dispose(object); -} - -static void webkit_context_menu_class_init(WebKitContextMenuClass* listClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(listClass); - gObjectClass->dispose = webkitContextMenuDispose; -} - -void webkitContextMenuPopulate(WebKitContextMenu* menu, Vector<ContextMenuItem>& contextMenuItems) -{ - for (GList* item = menu->priv->items; item; item = g_list_next(item)) { - WebKitContextMenuItem* menuItem = WEBKIT_CONTEXT_MENU_ITEM(item->data); - contextMenuItems.append(ContextMenuItem(webkitContextMenuItemRelease(menuItem))); - } -} - -WebKitContextMenu* webkitContextMenuCreate(ImmutableArray* items) -{ - WebKitContextMenu* menu = webkit_context_menu_new(); - for (size_t i = 0; i < items->size(); ++i) { - WebContextMenuItem* item = static_cast<WebContextMenuItem*>(items->at(i)); - webkit_context_menu_prepend(menu, webkitContextMenuItemCreate(item)); - } - menu->priv->items = g_list_reverse(menu->priv->items); - - return menu; -} - -void webkitContextMenuSetParentItem(WebKitContextMenu* menu, WebKitContextMenuItem* item) -{ - menu->priv->parentItem = item; -} - -WebKitContextMenuItem* webkitContextMenuGetParentItem(WebKitContextMenu* menu) -{ - return menu->priv->parentItem; -} - -/** - * webkit_context_menu_new: - * - * Creates a new #WebKitContextMenu object to be used as a submenu of an existing - * #WebKitContextMenu. The context menu of a #WebKitWebView is created by the view - * and passed as an argument of #WebKitWebView::context-menu signal. - * To add items to the menu use webkit_context_menu_prepend(), - * webkit_context_menu_append() or webkit_context_menu_insert(). - * See also webkit_context_menu_new_with_items() to create a #WebKitContextMenu with - * a list of initial items. - * - * Returns: The newly created #WebKitContextMenu object - */ -WebKitContextMenu* webkit_context_menu_new() -{ - return WEBKIT_CONTEXT_MENU(g_object_new(WEBKIT_TYPE_CONTEXT_MENU, NULL)); -} - -/** - * webkit_context_menu_new_with_items: - * @items: (element-type WebKitContextMenuItem): a #GList of #WebKitContextMenuItem - * - * Creates a new #WebKitContextMenu object to be used as a submenu of an existing - * #WebKitContextMenu with the given initial items. - * See also webkit_context_menu_new() - * - * Returns: The newly created #WebKitContextMenu object - */ -WebKitContextMenu* webkit_context_menu_new_with_items(GList* items) -{ - WebKitContextMenu* menu = webkit_context_menu_new(); - g_list_foreach(items, reinterpret_cast<GFunc>(g_object_ref_sink), 0); - menu->priv->items = g_list_copy(items); - - return menu; -} - -/** - * webkit_context_menu_prepend: - * @menu: a #WebKitContextMenu - * @item: the #WebKitContextMenuItem to add - * - * Adds @item at the beginning of the @menu. - */ -void webkit_context_menu_prepend(WebKitContextMenu* menu, WebKitContextMenuItem* item) -{ - webkit_context_menu_insert(menu, item, 0); -} - -/** - * webkit_context_menu_append: - * @menu: a #WebKitContextMenu - * @item: the #WebKitContextMenuItem to add - * - * Adds @item at the end of the @menu. - */ -void webkit_context_menu_append(WebKitContextMenu* menu, WebKitContextMenuItem* item) -{ - webkit_context_menu_insert(menu, item, -1); -} - -/** - * webkit_context_menu_insert: - * @menu: a #WebKitContextMenu - * @item: the #WebKitContextMenuItem to add - * @position: the position to insert the item - * - * Inserts @item into the @menu at the given position. - * If @position is negative, or is larger than the number of items - * in the #WebKitContextMenu, the item is added on to the end of - * the @menu. The first position is 0. - */ -void webkit_context_menu_insert(WebKitContextMenu* menu, WebKitContextMenuItem* item, int position) -{ - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU(menu)); - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item)); - - g_object_ref_sink(item); - menu->priv->items = g_list_insert(menu->priv->items, item, position); -} - -/** - * webkit_context_menu_move_item: - * @menu: a #WebKitContextMenu - * @item: the #WebKitContextMenuItem to add - * @position: the new position to move the item - * - * Moves @item to the given position in the @menu. - * If @position is negative, or is larger than the number of items - * in the #WebKitContextMenu, the item is added on to the end of - * the @menu. - * The first position is 0. - */ -void webkit_context_menu_move_item(WebKitContextMenu* menu, WebKitContextMenuItem* item, int position) -{ - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU(menu)); - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item)); - - if (!g_list_find(menu->priv->items, item)) - return; - - menu->priv->items = g_list_remove(menu->priv->items, item); - menu->priv->items = g_list_insert(menu->priv->items, item, position); -} - -/** - * webkit_context_menu_get_items: - * @menu: a #WebKitContextMenu - * - * Returns the item list of @menu. - * - * Returns: (element-type WebKitContextMenuItem) (transfer none): a #GList of - * #WebKitContextMenuItem<!-- -->s - */ -GList* webkit_context_menu_get_items(WebKitContextMenu* menu) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU(menu), 0); - - return menu->priv->items; -} - -/** - * webkit_context_menu_get_n_items: - * @menu: a #WebKitContextMenu - * - * Gets the length of the @menu. - * - * Returns: the number of #WebKitContextMenuItem<!-- -->s in @menu - */ -guint webkit_context_menu_get_n_items(WebKitContextMenu* menu) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU(menu), 0); - - return g_list_length(menu->priv->items); -} - -/** - * webkit_context_menu_first: - * @menu: a #WebKitContextMenu - * - * Gets the first item in the @menu. - * - * Returns: (transfer none): the first #WebKitContextMenuItem of @menu, - * or %NULL if the #WebKitContextMenu is empty. - */ -WebKitContextMenuItem* webkit_context_menu_first(WebKitContextMenu* menu) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU(menu), 0); - - return menu->priv->items ? WEBKIT_CONTEXT_MENU_ITEM(menu->priv->items->data) : 0; -} - -/** - * webkit_context_menu_last: - * @menu: a #WebKitContextMenu - * - * Gets the last item in the @menu. - * - * Returns: (transfer none): the last #WebKitContextMenuItem of @menu, - * or %NULL if the #WebKitContextMenu is empty. - */ -WebKitContextMenuItem* webkit_context_menu_last(WebKitContextMenu* menu) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU(menu), 0); - - GList* last = g_list_last(menu->priv->items); - return last ? WEBKIT_CONTEXT_MENU_ITEM(last->data) : 0; -} - -/** - * webkit_context_menu_get_item_at_position: - * @menu: a #WebKitContextMenu - * @position: the position of the item, counting from 0 - * - * Gets the item at the given position in the @menu. - * - * Returns: (transfer none): the #WebKitContextMenuItem at position @position in @menu, - * or %NULL if the position is off the end of the @menu. - */ -WebKitContextMenuItem* webkit_context_menu_get_item_at_position(WebKitContextMenu* menu, unsigned position) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU(menu), 0); - - gpointer item = g_list_nth_data(menu->priv->items, position); - return item ? WEBKIT_CONTEXT_MENU_ITEM(item) : 0; -} - -/** - * webkit_context_menu_remove: - * @menu: a #WebKitContextMenu - * @item: the #WebKitContextMenuItem to remove - * - * Removes @item from the @menu. - * See also webkit_context_menu_remove_all() to remove all items. - */ -void webkit_context_menu_remove(WebKitContextMenu* menu, WebKitContextMenuItem* item) -{ - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU(menu)); - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item)); - - if (!g_list_find(menu->priv->items, item)) - return; - - menu->priv->items = g_list_remove(menu->priv->items, item); - g_object_unref(item); -} - -/** - * webkit_context_menu_remove_all: - * @menu: a #WebKitContextMenu - * - * Removes all items of the @menu. - */ -void webkit_context_menu_remove_all(WebKitContextMenu* menu) -{ - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU(menu)); - - g_list_free_full(menu->priv->items, reinterpret_cast<GDestroyNotify>(g_object_unref)); - menu->priv->items = 0; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h deleted file mode 100644 index 22f4bef29..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenu.h +++ /dev/null @@ -1,110 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitContextMenu_h -#define WebKitContextMenu_h - -#include <glib-object.h> -#include <webkit2/WebKitContextMenuItem.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitForwardDeclarations.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_CONTEXT_MENU (webkit_context_menu_get_type()) -#define WEBKIT_CONTEXT_MENU(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_CONTEXT_MENU, WebKitContextMenu)) -#define WEBKIT_IS_CONTEXT_MENU(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_CONTEXT_MENU)) -#define WEBKIT_CONTEXT_MENU_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_CONTEXT_MENU, WebKitContextMenuClass)) -#define WEBKIT_IS_CONTEXT_MENU_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_CONTEXT_MENU)) -#define WEBKIT_CONTEXT_MENU_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_CONTEXT_MENU, WebKitContextMenuClass)) - -typedef struct _WebKitContextMenuClass WebKitContextMenuClass; -typedef struct _WebKitContextMenuPrivate WebKitContextMenuPrivate; - -struct _WebKitContextMenu { - GObject parent; - - WebKitContextMenuPrivate *priv; -}; - -struct _WebKitContextMenuClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_context_menu_get_type (void); - -WEBKIT_API WebKitContextMenu * -webkit_context_menu_new (void); - -WEBKIT_API WebKitContextMenu * -webkit_context_menu_new_with_items (GList *items); - -WEBKIT_API void -webkit_context_menu_prepend (WebKitContextMenu *menu, - WebKitContextMenuItem *item); - -WEBKIT_API void -webkit_context_menu_append (WebKitContextMenu *menu, - WebKitContextMenuItem *item); - -WEBKIT_API void -webkit_context_menu_insert (WebKitContextMenu *menu, - WebKitContextMenuItem *item, - gint position); - -WEBKIT_API void -webkit_context_menu_move_item (WebKitContextMenu *menu, - WebKitContextMenuItem *item, - gint position); -WEBKIT_API GList * -webkit_context_menu_get_items (WebKitContextMenu *menu); - -WEBKIT_API guint -webkit_context_menu_get_n_items (WebKitContextMenu *menu); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_first (WebKitContextMenu *menu); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_last (WebKitContextMenu *menu); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_get_item_at_position (WebKitContextMenu *menu, - guint position); - -WEBKIT_API void -webkit_context_menu_remove (WebKitContextMenu *menu, - WebKitContextMenuItem *item); - -WEBKIT_API void -webkit_context_menu_remove_all (WebKitContextMenu *menu); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActions.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActions.cpp deleted file mode 100644 index 3793d7c0f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActions.cpp +++ /dev/null @@ -1,318 +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 "WebKitContextMenuActions.h" - -#include "WebKitContextMenuActionsPrivate.h" -#include <WebCore/LocalizedStrings.h> - -using namespace WebCore; - -bool webkitContextMenuActionIsCheckable(WebKitContextMenuAction action) -{ - switch (action) { - case WEBKIT_CONTEXT_MENU_ACTION_BOLD: - case WEBKIT_CONTEXT_MENU_ACTION_ITALIC: - case WEBKIT_CONTEXT_MENU_ACTION_UNDERLINE: - case WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS: - case WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP: - return true; - default: - return false; - } -} - -ContextMenuAction webkitContextMenuActionGetActionTag(WebKitContextMenuAction action) -{ - switch (action) { - case WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION: - return ContextMenuItemTagNoAction; - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK: - return ContextMenuItemTagOpenLink; - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW: - return ContextMenuItemTagOpenLinkInNewWindow; - case WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK: - return ContextMenuItemTagDownloadLinkToDisk; - case WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD: - return ContextMenuItemTagCopyLinkToClipboard; - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW: - return ContextMenuItemTagOpenImageInNewWindow; - case WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK: - return ContextMenuItemTagDownloadImageToDisk; - case WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD: - return ContextMenuItemTagCopyImageToClipboard; - case WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD: - return ContextMenuItemTagCopyImageUrlToClipboard; - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_FRAME_IN_NEW_WINDOW: - return ContextMenuItemTagOpenFrameInNewWindow; - case WEBKIT_CONTEXT_MENU_ACTION_GO_BACK: - return ContextMenuItemTagGoBack; - case WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD: - return ContextMenuItemTagGoForward; - case WEBKIT_CONTEXT_MENU_ACTION_STOP: - return ContextMenuItemTagStop; - case WEBKIT_CONTEXT_MENU_ACTION_RELOAD: - return ContextMenuItemTagReload; - case WEBKIT_CONTEXT_MENU_ACTION_COPY: - return ContextMenuItemTagCopy; - case WEBKIT_CONTEXT_MENU_ACTION_CUT: - return ContextMenuItemTagCut; - case WEBKIT_CONTEXT_MENU_ACTION_PASTE: - return ContextMenuItemTagPaste; - case WEBKIT_CONTEXT_MENU_ACTION_DELETE: - return ContextMenuItemTagDelete; - case WEBKIT_CONTEXT_MENU_ACTION_SELECT_ALL: - return ContextMenuItemTagSelectAll; - case WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS: - return ContextMenuItemTagInputMethods; - case WEBKIT_CONTEXT_MENU_ACTION_UNICODE: - return ContextMenuItemTagUnicode; - case WEBKIT_CONTEXT_MENU_ACTION_SPELLING_GUESS: - return ContextMenuItemTagSpellingGuess; - case WEBKIT_CONTEXT_MENU_ACTION_NO_GUESSES_FOUND: - return ContextMenuItemTagNoGuessesFound; - case WEBKIT_CONTEXT_MENU_ACTION_IGNORE_SPELLING: - return ContextMenuItemTagIgnoreSpelling; - case WEBKIT_CONTEXT_MENU_ACTION_LEARN_SPELLING: - return ContextMenuItemTagLearnSpelling; - case WEBKIT_CONTEXT_MENU_ACTION_IGNORE_GRAMMAR: - return ContextMenuItemTagIgnoreGrammar; - case WEBKIT_CONTEXT_MENU_ACTION_FONT_MENU: - return ContextMenuItemTagFontMenu; - case WEBKIT_CONTEXT_MENU_ACTION_BOLD: - return ContextMenuItemTagBold; - case WEBKIT_CONTEXT_MENU_ACTION_ITALIC: - return ContextMenuItemTagItalic; - case WEBKIT_CONTEXT_MENU_ACTION_UNDERLINE: - return ContextMenuItemTagUnderline; - case WEBKIT_CONTEXT_MENU_ACTION_OUTLINE: - return ContextMenuItemTagOutline; - case WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT: - return ContextMenuItemTagInspectElement; - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_VIDEO_IN_NEW_WINDOW: - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_AUDIO_IN_NEW_WINDOW: - return ContextMenuItemTagOpenMediaInNewWindow; - case WEBKIT_CONTEXT_MENU_ACTION_COPY_VIDEO_LINK_TO_CLIPBOARD: - case WEBKIT_CONTEXT_MENU_ACTION_COPY_AUDIO_LINK_TO_CLIPBOARD: - return ContextMenuItemTagCopyMediaLinkToClipboard; - case WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS: - return ContextMenuItemTagToggleMediaControls; - case WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP: - return ContextMenuItemTagToggleMediaLoop; - case WEBKIT_CONTEXT_MENU_ACTION_ENTER_VIDEO_FULLSCREEN: - return ContextMenuItemTagEnterVideoFullscreen; - case WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PLAY: - case WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PAUSE: - return ContextMenuItemTagMediaPlayPause; - case WEBKIT_CONTEXT_MENU_ACTION_MEDIA_MUTE: - return ContextMenuItemTagMediaMute; - case WEBKIT_CONTEXT_MENU_ACTION_CUSTOM: - return ContextMenuItemBaseApplicationTag; - default: - ASSERT_NOT_REACHED(); - } - - return ContextMenuItemBaseApplicationTag; -} - -WebKitContextMenuAction webkitContextMenuActionGetForContextMenuItem(ContextMenuItem* menuItem) -{ - switch (menuItem->action()) { - case ContextMenuItemTagNoAction: - return WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION; - case ContextMenuItemTagOpenLink: - return WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK; - case ContextMenuItemTagOpenLinkInNewWindow: - return WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW; - case ContextMenuItemTagDownloadLinkToDisk: - return WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK; - case ContextMenuItemTagCopyLinkToClipboard: - return WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD; - case ContextMenuItemTagOpenImageInNewWindow: - return WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW; - case ContextMenuItemTagDownloadImageToDisk: - return WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK; - case ContextMenuItemTagCopyImageToClipboard: - return WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD; - case ContextMenuItemTagCopyImageUrlToClipboard: - return WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD; - case ContextMenuItemTagOpenFrameInNewWindow: - return WEBKIT_CONTEXT_MENU_ACTION_OPEN_FRAME_IN_NEW_WINDOW; - case ContextMenuItemTagGoBack: - return WEBKIT_CONTEXT_MENU_ACTION_GO_BACK; - case ContextMenuItemTagGoForward: - return WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD; - case ContextMenuItemTagStop: - return WEBKIT_CONTEXT_MENU_ACTION_STOP; - case ContextMenuItemTagReload: - return WEBKIT_CONTEXT_MENU_ACTION_RELOAD; - case ContextMenuItemTagCopy: - return WEBKIT_CONTEXT_MENU_ACTION_COPY; - case ContextMenuItemTagCut: - return WEBKIT_CONTEXT_MENU_ACTION_CUT; - case ContextMenuItemTagPaste: - return WEBKIT_CONTEXT_MENU_ACTION_PASTE; - case ContextMenuItemTagDelete: - return WEBKIT_CONTEXT_MENU_ACTION_DELETE; - case ContextMenuItemTagSelectAll: - return WEBKIT_CONTEXT_MENU_ACTION_SELECT_ALL; - case ContextMenuItemTagInputMethods: - return WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS; - case ContextMenuItemTagUnicode: - return WEBKIT_CONTEXT_MENU_ACTION_UNICODE; - case ContextMenuItemTagSpellingGuess: - return WEBKIT_CONTEXT_MENU_ACTION_SPELLING_GUESS; - case ContextMenuItemTagIgnoreSpelling: - return WEBKIT_CONTEXT_MENU_ACTION_IGNORE_SPELLING; - case ContextMenuItemTagLearnSpelling: - return WEBKIT_CONTEXT_MENU_ACTION_LEARN_SPELLING; - case ContextMenuItemTagIgnoreGrammar: - return WEBKIT_CONTEXT_MENU_ACTION_IGNORE_GRAMMAR; - case ContextMenuItemTagFontMenu: - return WEBKIT_CONTEXT_MENU_ACTION_FONT_MENU; - case ContextMenuItemTagBold: - return WEBKIT_CONTEXT_MENU_ACTION_BOLD; - case ContextMenuItemTagItalic: - return WEBKIT_CONTEXT_MENU_ACTION_ITALIC; - case ContextMenuItemTagUnderline: - return WEBKIT_CONTEXT_MENU_ACTION_UNDERLINE; - case ContextMenuItemTagOutline: - return WEBKIT_CONTEXT_MENU_ACTION_OUTLINE; - case ContextMenuItemTagInspectElement: - return WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT; - case ContextMenuItemTagOpenMediaInNewWindow: - return menuItem->title() == contextMenuItemTagOpenVideoInNewWindow() ? - WEBKIT_CONTEXT_MENU_ACTION_OPEN_VIDEO_IN_NEW_WINDOW : WEBKIT_CONTEXT_MENU_ACTION_OPEN_AUDIO_IN_NEW_WINDOW; - case ContextMenuItemTagCopyMediaLinkToClipboard: - return menuItem->title() == contextMenuItemTagCopyVideoLinkToClipboard() ? - WEBKIT_CONTEXT_MENU_ACTION_COPY_VIDEO_LINK_TO_CLIPBOARD : WEBKIT_CONTEXT_MENU_ACTION_COPY_AUDIO_LINK_TO_CLIPBOARD; - case ContextMenuItemTagToggleMediaControls: - return WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS; - case ContextMenuItemTagToggleMediaLoop: - return WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP; - case ContextMenuItemTagEnterVideoFullscreen: - return WEBKIT_CONTEXT_MENU_ACTION_ENTER_VIDEO_FULLSCREEN; - case ContextMenuItemTagMediaPlayPause: - return menuItem->title() == contextMenuItemTagMediaPlay() ? - WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PLAY : WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PAUSE; - case ContextMenuItemTagMediaMute: - return WEBKIT_CONTEXT_MENU_ACTION_MEDIA_MUTE; - case ContextMenuItemBaseApplicationTag: - return WEBKIT_CONTEXT_MENU_ACTION_CUSTOM; - default: - ASSERT_NOT_REACHED(); - } - - return WEBKIT_CONTEXT_MENU_ACTION_CUSTOM; -} - -String webkitContextMenuActionGetLabel(WebKitContextMenuAction action) -{ - switch (action) { - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK: - return contextMenuItemTagOpenLink(); - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW: - return contextMenuItemTagOpenLinkInNewWindow(); - case WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK: - return contextMenuItemTagDownloadLinkToDisk(); - case WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD: - return contextMenuItemTagCopyLinkToClipboard(); - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW: - return contextMenuItemTagOpenImageInNewWindow(); - case WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK: - return contextMenuItemTagDownloadImageToDisk(); - case WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD: - return contextMenuItemTagCopyImageToClipboard(); - case WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD: - return contextMenuItemTagCopyImageUrlToClipboard(); - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_FRAME_IN_NEW_WINDOW: - return contextMenuItemTagOpenFrameInNewWindow(); - case WEBKIT_CONTEXT_MENU_ACTION_GO_BACK: - return contextMenuItemTagGoBack(); - case WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD: - return contextMenuItemTagGoForward(); - case WEBKIT_CONTEXT_MENU_ACTION_STOP: - return contextMenuItemTagStop(); - case WEBKIT_CONTEXT_MENU_ACTION_RELOAD: - return contextMenuItemTagReload(); - case WEBKIT_CONTEXT_MENU_ACTION_COPY: - return contextMenuItemTagCopy(); - case WEBKIT_CONTEXT_MENU_ACTION_CUT: - return contextMenuItemTagCut(); - case WEBKIT_CONTEXT_MENU_ACTION_PASTE: - return contextMenuItemTagPaste(); - case WEBKIT_CONTEXT_MENU_ACTION_DELETE: - return contextMenuItemTagDelete(); - case WEBKIT_CONTEXT_MENU_ACTION_SELECT_ALL: - return contextMenuItemTagSelectAll(); - case WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS: - return contextMenuItemTagInputMethods(); - case WEBKIT_CONTEXT_MENU_ACTION_UNICODE: - return contextMenuItemTagUnicode(); - case WEBKIT_CONTEXT_MENU_ACTION_NO_GUESSES_FOUND: - return contextMenuItemTagNoGuessesFound(); - case WEBKIT_CONTEXT_MENU_ACTION_IGNORE_SPELLING: - return contextMenuItemTagIgnoreSpelling(); - case WEBKIT_CONTEXT_MENU_ACTION_LEARN_SPELLING: - return contextMenuItemTagLearnSpelling(); - case WEBKIT_CONTEXT_MENU_ACTION_IGNORE_GRAMMAR: - return contextMenuItemTagIgnoreGrammar(); - case WEBKIT_CONTEXT_MENU_ACTION_FONT_MENU: - return contextMenuItemTagFontMenu(); - case WEBKIT_CONTEXT_MENU_ACTION_BOLD: - return contextMenuItemTagBold(); - case WEBKIT_CONTEXT_MENU_ACTION_ITALIC: - return contextMenuItemTagItalic(); - case WEBKIT_CONTEXT_MENU_ACTION_UNDERLINE: - return contextMenuItemTagUnderline(); - case WEBKIT_CONTEXT_MENU_ACTION_OUTLINE: - return contextMenuItemTagOutline(); - case WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT: - return contextMenuItemTagInspectElement(); - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_VIDEO_IN_NEW_WINDOW: - return contextMenuItemTagOpenVideoInNewWindow(); - case WEBKIT_CONTEXT_MENU_ACTION_OPEN_AUDIO_IN_NEW_WINDOW: - return contextMenuItemTagOpenAudioInNewWindow(); - case WEBKIT_CONTEXT_MENU_ACTION_COPY_VIDEO_LINK_TO_CLIPBOARD: - return contextMenuItemTagCopyVideoLinkToClipboard(); - case WEBKIT_CONTEXT_MENU_ACTION_COPY_AUDIO_LINK_TO_CLIPBOARD: - return contextMenuItemTagCopyAudioLinkToClipboard(); - case WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS: - return contextMenuItemTagToggleMediaControls(); - case WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP: - return contextMenuItemTagToggleMediaLoop(); - case WEBKIT_CONTEXT_MENU_ACTION_ENTER_VIDEO_FULLSCREEN: - return contextMenuItemTagEnterVideoFullscreen(); - case WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PLAY: - return contextMenuItemTagMediaPlay(); - case WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PAUSE: - return contextMenuItemTagMediaPause(); - case WEBKIT_CONTEXT_MENU_ACTION_MEDIA_MUTE: - return contextMenuItemTagMediaMute(); - case WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION: - case WEBKIT_CONTEXT_MENU_ACTION_CUSTOM: - case WEBKIT_CONTEXT_MENU_ACTION_SPELLING_GUESS: - return String(); - default: - ASSERT_NOT_REACHED(); - } - - return String(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActions.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActions.h deleted file mode 100644 index 185bd251f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActions.h +++ /dev/null @@ -1,130 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#include <glib.h> - -#ifndef WebKitContextMenuActions_h -#define WebKitContextMenuActions_h - -G_BEGIN_DECLS - -/** - * WebKitContextMenuAction: - * @WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION: No action, used by separator menu items. - * @WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK: Open current link. - * @WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW: Open current link in a new window. - * @WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK: Download link destination. - * @WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD: Copy link location to the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW: Open current image in a new window. - * @WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK: Download current image. - * @WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD: Copy current image to the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD: Copy curent image location to the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_OPEN_FRAME_IN_NEW_WINDOW: Open current frame in a new window. - * @WEBKIT_CONTEXT_MENU_ACTION_GO_BACK: Load the previous history item. - * @WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD: Load the next history item. - * @WEBKIT_CONTEXT_MENU_ACTION_STOP: Stop any ongoing loading operation. - * @WEBKIT_CONTEXT_MENU_ACTION_RELOAD: Reload the conents of current view. - * @WEBKIT_CONTEXT_MENU_ACTION_COPY: Copy current selection the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_CUT: Cut current selection to the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_PASTE: Paste clipboard contents. - * @WEBKIT_CONTEXT_MENU_ACTION_DELETE: Delete current selection. - * @WEBKIT_CONTEXT_MENU_ACTION_SELECT_ALL: Select all text. - * @WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS: Input methods menu. - * @WEBKIT_CONTEXT_MENU_ACTION_UNICODE: Unicode menu. - * @WEBKIT_CONTEXT_MENU_ACTION_SPELLING_GUESS: A proposed replacement for a misspelled word. - * @WEBKIT_CONTEXT_MENU_ACTION_NO_GUESSES_FOUND: An indicator that spellchecking found no proposed replacements. - * @WEBKIT_CONTEXT_MENU_ACTION_IGNORE_SPELLING: Causes the spellchecker to ignore the word for this session. - * @WEBKIT_CONTEXT_MENU_ACTION_LEARN_SPELLING: Causes the spellchecker to add the word to the dictionary. - * @WEBKIT_CONTEXT_MENU_ACTION_IGNORE_GRAMMAR: Ignore grammar. - * @WEBKIT_CONTEXT_MENU_ACTION_FONT_MENU: Font options menu. - * @WEBKIT_CONTEXT_MENU_ACTION_BOLD: Bold. - * @WEBKIT_CONTEXT_MENU_ACTION_ITALIC: Italic. - * @WEBKIT_CONTEXT_MENU_ACTION_UNDERLINE: Underline. - * @WEBKIT_CONTEXT_MENU_ACTION_OUTLINE: Outline. - * @WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT: Open current element in the inspector. - * @WEBKIT_CONTEXT_MENU_ACTION_OPEN_VIDEO_IN_NEW_WINDOW: Open current video element in a new window. - * @WEBKIT_CONTEXT_MENU_ACTION_OPEN_AUDIO_IN_NEW_WINDOW: Open current audio element in a new window. - * @WEBKIT_CONTEXT_MENU_ACTION_COPY_VIDEO_LINK_TO_CLIPBOARD: Copy video link location in to the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_COPY_AUDIO_LINK_TO_CLIPBOARD: Copy audio link location in to the clipboard. - * @WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS: Enable or disable media controls. - * @WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP: Enable or disable media loop. - * @WEBKIT_CONTEXT_MENU_ACTION_ENTER_VIDEO_FULLSCREEN: Show current video element in fullscreen mode. - * @WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PLAY: Play current media element. - * @WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PAUSE: Pause current media element. - * @WEBKIT_CONTEXT_MENU_ACTION_MEDIA_MUTE: Mute current media element. - * @WEBKIT_CONTEXT_MENU_ACTION_CUSTOM: Custom action defined by applications. - * - * Enum values used to denote the stock actions for - * #WebKitContextMenuItem<!-- -->s - */ -typedef enum { - WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION = 0, - - WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK, - WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW, - WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK, - WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD, - WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW, - WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK, - WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD, - WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD, - WEBKIT_CONTEXT_MENU_ACTION_OPEN_FRAME_IN_NEW_WINDOW, - WEBKIT_CONTEXT_MENU_ACTION_GO_BACK, - WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD, - WEBKIT_CONTEXT_MENU_ACTION_STOP, - WEBKIT_CONTEXT_MENU_ACTION_RELOAD, - WEBKIT_CONTEXT_MENU_ACTION_COPY, - WEBKIT_CONTEXT_MENU_ACTION_CUT, - WEBKIT_CONTEXT_MENU_ACTION_PASTE, - WEBKIT_CONTEXT_MENU_ACTION_DELETE, - WEBKIT_CONTEXT_MENU_ACTION_SELECT_ALL, - WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS, - WEBKIT_CONTEXT_MENU_ACTION_UNICODE, - WEBKIT_CONTEXT_MENU_ACTION_SPELLING_GUESS, - WEBKIT_CONTEXT_MENU_ACTION_NO_GUESSES_FOUND, - WEBKIT_CONTEXT_MENU_ACTION_IGNORE_SPELLING, - WEBKIT_CONTEXT_MENU_ACTION_LEARN_SPELLING, - WEBKIT_CONTEXT_MENU_ACTION_IGNORE_GRAMMAR, - WEBKIT_CONTEXT_MENU_ACTION_FONT_MENU, - WEBKIT_CONTEXT_MENU_ACTION_BOLD, - WEBKIT_CONTEXT_MENU_ACTION_ITALIC, - WEBKIT_CONTEXT_MENU_ACTION_UNDERLINE, - WEBKIT_CONTEXT_MENU_ACTION_OUTLINE, - WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT, - WEBKIT_CONTEXT_MENU_ACTION_OPEN_VIDEO_IN_NEW_WINDOW, - WEBKIT_CONTEXT_MENU_ACTION_OPEN_AUDIO_IN_NEW_WINDOW, - WEBKIT_CONTEXT_MENU_ACTION_COPY_VIDEO_LINK_TO_CLIPBOARD, - WEBKIT_CONTEXT_MENU_ACTION_COPY_AUDIO_LINK_TO_CLIPBOARD, - WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS, - WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP, - WEBKIT_CONTEXT_MENU_ACTION_ENTER_VIDEO_FULLSCREEN, - WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PLAY, - WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PAUSE, - WEBKIT_CONTEXT_MENU_ACTION_MEDIA_MUTE, - - WEBKIT_CONTEXT_MENU_ACTION_CUSTOM = 10000 -} WebKitContextMenuAction; - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActionsPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActionsPrivate.h deleted file mode 100644 index f753bb97c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuActionsPrivate.h +++ /dev/null @@ -1,31 +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. - */ - -#ifndef WebKitContextMenuActionsPrivate_h -#define WebKitContextMenuActionsPrivate_h - -#include "WebKitContextMenuActions.h" -#include <WebCore/ContextMenuItem.h> - -bool webkitContextMenuActionIsCheckable(WebKitContextMenuAction); -WebCore::ContextMenuAction webkitContextMenuActionGetActionTag(WebKitContextMenuAction); -WebKitContextMenuAction webkitContextMenuActionGetForContextMenuItem(WebCore::ContextMenuItem*); -String webkitContextMenuActionGetLabel(WebKitContextMenuAction); - -#endif // WebKitPrintOperationPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp deleted file mode 100644 index f50c52aea..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.cpp +++ /dev/null @@ -1,49 +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 "WebKitContextMenuClient.h" - -#include "WebKitPrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" - -using namespace WebKit; - -static void getContextMenuFromProposedMenu(WKPageRef, WKArrayRef proposedMenu, WKArrayRef*, WKHitTestResultRef hitTestResult, WKTypeRef userData, const void* clientInfo) -{ - webkitWebViewPopulateContextMenu(WEBKIT_WEB_VIEW(clientInfo), toImpl(proposedMenu), toImpl(hitTestResult)); -} - -void attachContextMenuClientToView(WebKitWebView* webView) -{ - WKPageContextMenuClient wkContextMenuClient = { - kWKPageContextMenuClientCurrentVersion, - webView, // clientInfo - 0, // getContextMenuFromProposedMenu_deprecatedForUseWithV0 - 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/WebKitContextMenuClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.h deleted file mode 100644 index 9b28bf998..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuClient.h +++ /dev/null @@ -1,27 +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. - */ - -#ifndef WebKitContextMenuClient_h -#define WebKitContextMenuClient_h - -#include "WebKitWebView.h" - -void attachContextMenuClientToView(WebKitWebView*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp deleted file mode 100644 index d98cc548e..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.cpp +++ /dev/null @@ -1,345 +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 "WebKitContextMenuItem.h" - -#include "MutableArray.h" -#include "WebContextMenuItem.h" -#include "WebContextMenuItemData.h" -#include "WebKitContextMenuActionsPrivate.h" -#include "WebKitContextMenuItemPrivate.h" -#include "WebKitContextMenuPrivate.h" -#include <WebCore/ContextMenu.h> -#include <WebCore/ContextMenuItem.h> -#include <gtk/gtk.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> - -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() - { - if (subMenu) - webkitContextMenuSetParentItem(subMenu.get(), 0); - } - - OwnPtr<ContextMenuItem> menuItem; - GRefPtr<WebKitContextMenu> subMenu; -}; - -WEBKIT_DEFINE_TYPE(WebKitContextMenuItem, webkit_context_menu_item, G_TYPE_INITIALLY_UNOWNED) - -static void webkit_context_menu_item_class_init(WebKitContextMenuItemClass* itemClass) -{ -} - -static bool checkAndWarnIfMenuHasParentItem(WebKitContextMenu* menu) -{ - if (menu && webkitContextMenuGetParentItem(menu)) { - g_warning("Attempting to set a WebKitContextMenu as submenu of " - "a WebKitContextMenuItem, but the menu is already " - "a submenu of a WebKitContextMenuItem"); - return true; - } - - return false; -} - -static void webkitContextMenuItemSetSubMenu(WebKitContextMenuItem* item, GRefPtr<WebKitContextMenu> subMenu) -{ - if (checkAndWarnIfMenuHasParentItem(subMenu.get())) - return; - - if (item->priv->subMenu) - webkitContextMenuSetParentItem(item->priv->subMenu.get(), 0); - item->priv->subMenu = subMenu; - if (subMenu) - webkitContextMenuSetParentItem(subMenu.get(), item); -} - -WebKitContextMenuItem* webkitContextMenuItemCreate(WebContextMenuItem* webItem) -{ - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - WebContextMenuItemData* itemData = webItem->data(); - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(itemData->type(), itemData->action(), itemData->title(), itemData->enabled(), itemData->checked())); - const Vector<WebContextMenuItemData>& subMenu = itemData->submenu(); - if (!subMenu.size()) - return item; - - RefPtr<MutableArray> subMenuItems = MutableArray::create(); - subMenuItems->reserveCapacity(subMenu.size()); - for (size_t i = 0; i < subMenu.size(); ++i) - subMenuItems->append(WebContextMenuItem::create(subMenu[i]).get()); - webkitContextMenuItemSetSubMenu(item, adoptGRef(webkitContextMenuCreate(subMenuItems.get()))); - - return item; -} - -static WebKitContextMenuItem* webkitContextMenuItemCreateForGtkItem(GtkMenuItem* menuItem) -{ - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(menuItem)); - webkitContextMenuItemSetSubMenuFromGtkMenu(item, GTK_MENU(gtk_menu_item_get_submenu(menuItem))); - - return item; -} - -void webkitContextMenuItemSetSubMenuFromGtkMenu(WebKitContextMenuItem* item, GtkMenu* subMenu) -{ - if (!subMenu) - return; - - GOwnPtr<GList> children(gtk_container_get_children(GTK_CONTAINER(subMenu))); - if (!g_list_length(children.get())) - return; - - webkitContextMenuItemSetSubMenu(item, adoptGRef(webkit_context_menu_new())); - for (GList* listItem = children.get(); listItem; listItem = g_list_next(listItem)) { - GRefPtr<GtkWidget> widget = GTK_WIDGET(listItem->data); - if (!GTK_IS_MENU_ITEM(widget.get())) - continue; - - gtk_container_remove(GTK_CONTAINER(subMenu), widget.get()); - GtkMenuItem* menuItem = GTK_MENU_ITEM(widget.leakRef()); - g_object_force_floating(G_OBJECT(menuItem)); - webkit_context_menu_append(item->priv->subMenu.get(), webkitContextMenuItemCreateForGtkItem(menuItem)); - } -} - -GtkMenuItem* webkitContextMenuItemRelease(WebKitContextMenuItem* item) -{ - if (item->priv->subMenu) { - Vector<ContextMenuItem> subMenuItems; - webkitContextMenuPopulate(item->priv->subMenu.get(), subMenuItems); - ContextMenu subMenu(platformMenuDescription(subMenuItems)); - item->priv->menuItem->setSubMenu(&subMenu); - } - - return item->priv->menuItem->releasePlatformDescription(); -} - -/** - * webkit_context_menu_item_new: - * @action: a #GtkAction - * - * Creates a new #WebKitContextMenuItem for the given @action. - * - * Returns: the newly created #WebKitContextMenuItem object. - */ -WebKitContextMenuItem* webkit_context_menu_item_new(GtkAction* action) -{ - g_return_val_if_fail(GTK_IS_ACTION(action), 0); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(GTK_MENU_ITEM(gtk_action_create_menu_item(action)))); - item->priv->menuItem->setAction(ContextMenuItemBaseApplicationTag); - - return item; -} - -/** - * webkit_context_menu_item_new_from_stock_action: - * @action: a #WebKitContextMenuAction stock action - * - * Creates a new #WebKitContextMenuItem for the given stock action. - * Stock actions are handled automatically by WebKit so that, for example, - * when a menu item created with a %WEBKIT_CONTEXT_MENU_ACTION_STOP is - * activated the action associated will be handled by WebKit and the current - * load operation will be stopped. You can get the #GtkAction of a - * #WebKitContextMenuItem created with a #WebKitContextMenuAction with - * webkit_context_menu_item_get_action() and connect to #GtkAction::activate signal - * to be notified when the item is activated. But you can't prevent the asociated - * action from being performed. - * - * Returns: the newly created #WebKitContextMenuItem object. - */ -WebKitContextMenuItem* webkit_context_menu_item_new_from_stock_action(WebKitContextMenuAction action) -{ - g_return_val_if_fail(action > WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION && action < WEBKIT_CONTEXT_MENU_ACTION_CUSTOM, 0); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - ContextMenuItemType type = webkitContextMenuActionIsCheckable(action) ? CheckableActionType : ActionType; - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(type, webkitContextMenuActionGetActionTag(action), webkitContextMenuActionGetLabel(action))); - - return item; -} - -/** - * webkit_context_menu_item_new_from_stock_action_with_label: - * @action: a #WebKitContextMenuAction stock action - * @label: a custom label text to use instead of the predefined one - * - * Creates a new #WebKitContextMenuItem for the given stock action using the given @label. - * Stock actions have a predefined label, this method can be used to create a - * #WebKitContextMenuItem for a #WebKitContextMenuAction but using a custom label. - * - * Returns: the newly created #WebKitContextMenuItem object. - */ -WebKitContextMenuItem* webkit_context_menu_item_new_from_stock_action_with_label(WebKitContextMenuAction action, const gchar* label) -{ - g_return_val_if_fail(action > WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION && action < WEBKIT_CONTEXT_MENU_ACTION_CUSTOM, 0); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - ContextMenuItemType type = webkitContextMenuActionIsCheckable(action) ? CheckableActionType : ActionType; - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(type, webkitContextMenuActionGetActionTag(action), String::fromUTF8(label))); - - return item; -} - -/** - * webkit_context_menu_item_new_with_submenu: - * @label: the menu item label text - * @submenu: a #WebKitContextMenu to set - * - * Creates a new #WebKitContextMenuItem using the given @label with a submenu. - * - * Returns: the newly created #WebKitContextMenuItem object. - */ -WebKitContextMenuItem* webkit_context_menu_item_new_with_submenu(const gchar* label, WebKitContextMenu* submenu) -{ - g_return_val_if_fail(label, 0); - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU(submenu), 0); - - if (checkAndWarnIfMenuHasParentItem(submenu)) - return 0; - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(SubmenuType, ContextMenuItemBaseApplicationTag, String::fromUTF8(label))); - item->priv->subMenu = submenu; - webkitContextMenuSetParentItem(submenu, item); - - return item; -} - -/** - * webkit_context_menu_item_new_separator: - * - * Creates a new #WebKitContextMenuItem representing a separator. - * - * Returns: the newly created #WebKitContextMenuItem object. - */ -WebKitContextMenuItem* webkit_context_menu_item_new_separator(void) -{ - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(g_object_new(WEBKIT_TYPE_CONTEXT_MENU_ITEM, NULL)); - item->priv->menuItem = WTF::adoptPtr(new ContextMenuItem(SeparatorType, ContextMenuItemTagNoAction, String())); - - return item; -} - -/** - * webkit_context_menu_item_get_action: - * @item: a #WebKitContextMenuItem - * - * Gets the action associated to @item. - * - * Returns: (transfer none): the #GtkAction associated to the #WebKitContextMenuItem, - * or %NULL if @item is a separator. - */ -GtkAction* webkit_context_menu_item_get_action(WebKitContextMenuItem* item) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item), 0); - - return item->priv->menuItem->gtkAction(); -} - -/** - * webkit_context_menu_item_get_stock_action: - * @item: a #WebKitContextMenuItem - * - * Gets the #WebKitContextMenuAction of @item. If the #WebKitContextMenuItem was not - * created for a stock action %WEBKIT_CONTEXT_MENU_ACTION_CUSTOM will be - * returned. If the #WebKitContextMenuItem is a separator %WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION - * will be returned. - * - * Returns: the #WebKitContextMenuAction of @item - */ -WebKitContextMenuAction webkit_context_menu_item_get_stock_action(WebKitContextMenuItem* item) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item), WEBKIT_CONTEXT_MENU_ACTION_NO_ACTION); - - return webkitContextMenuActionGetForContextMenuItem(item->priv->menuItem.get()); -} - -/** - * webkit_context_menu_item_is_separator: - * @item: a #WebKitContextMenuItem - * - * Checks whether @item is a separator. - * - * Returns: %TRUE is @item is a separator or %FALSE otherwise - */ -gboolean webkit_context_menu_item_is_separator(WebKitContextMenuItem* item) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item), FALSE); - - return item->priv->menuItem->type() == SeparatorType; -} - -/** - * webkit_context_menu_item_set_submenu: - * @item: a #WebKitContextMenuItem - * @submenu: (allow-none): a #WebKitContextMenu - * - * Sets or replaces the @item submenu. If @submenu is %NULL the current - * submenu of @item is removed. - */ -void webkit_context_menu_item_set_submenu(WebKitContextMenuItem* item, WebKitContextMenu* submenu) -{ - g_return_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item)); - - if (item->priv->subMenu == submenu) - return; - - webkitContextMenuItemSetSubMenu(item, submenu); -} - -/** - * webkit_context_menu_item_get_submenu: - * @item: a #WebKitContextMenuItem - * - * Gets the submenu of @item. - * - * Returns: (transfer none): the #WebKitContextMenu representing the submenu of - * @item or %NULL if @item doesn't have a submenu. - */ -WebKitContextMenu* webkit_context_menu_item_get_submenu(WebKitContextMenuItem* item) -{ - g_return_val_if_fail(WEBKIT_IS_CONTEXT_MENU_ITEM(item), 0); - - return item->priv->subMenu.get(); -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h deleted file mode 100644 index 75d60d7d6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItem.h +++ /dev/null @@ -1,98 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitContextMenuItem_h -#define WebKitContextMenuItem_h - -#include <gtk/gtk.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitContextMenu.h> -#include <webkit2/WebKitContextMenuActions.h> -#include <webkit2/WebKitForwardDeclarations.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_CONTEXT_MENU_ITEM (webkit_context_menu_item_get_type()) -#define WEBKIT_CONTEXT_MENU_ITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_CONTEXT_MENU_ITEM, WebKitContextMenuItem)) -#define WEBKIT_IS_CONTEXT_MENU_ITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_CONTEXT_MENU_ITEM)) -#define WEBKIT_CONTEXT_MENU_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_CONTEXT_MENU_ITEM, WebKitContextMenuItemClass)) -#define WEBKIT_IS_CONTEXT_MENU_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_CONTEXT_MENU_ITEM)) -#define WEBKIT_CONTEXT_MENU_ITEM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_CONTEXT_MENU_ITEM, WebKitContextMenuItemClass)) - -typedef struct _WebKitContextMenuItemClass WebKitContextMenuItemClass; -typedef struct _WebKitContextMenuItemPrivate WebKitContextMenuItemPrivate; - -struct _WebKitContextMenuItem { - GInitiallyUnowned parent; - - WebKitContextMenuItemPrivate *priv; -}; - -struct _WebKitContextMenuItemClass { - GInitiallyUnownedClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_context_menu_item_get_type (void); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_item_new (GtkAction *action); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_item_new_from_stock_action (WebKitContextMenuAction action); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_item_new_from_stock_action_with_label (WebKitContextMenuAction action, - const gchar *label); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_item_new_with_submenu (const gchar *label, - WebKitContextMenu *submenu); - -WEBKIT_API WebKitContextMenuItem * -webkit_context_menu_item_new_separator (void); - -WEBKIT_API GtkAction * -webkit_context_menu_item_get_action (WebKitContextMenuItem *item); - -WEBKIT_API WebKitContextMenuAction -webkit_context_menu_item_get_stock_action (WebKitContextMenuItem *item); - -WEBKIT_API gboolean -webkit_context_menu_item_is_separator (WebKitContextMenuItem *item); - -WEBKIT_API void -webkit_context_menu_item_set_submenu (WebKitContextMenuItem *item, - WebKitContextMenu *submenu); - -WEBKIT_API WebKitContextMenu * -webkit_context_menu_item_get_submenu (WebKitContextMenuItem *item); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItemPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItemPrivate.h deleted file mode 100644 index 18f8c1a87..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuItemPrivate.h +++ /dev/null @@ -1,30 +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. - */ - -#ifndef WebKitContextMenuItemPrivate_h -#define WebKitContextMenuItemPrivate_h - -#include "WebKitContextMenuItem.h" -#include "WebKitPrivate.h" - -WebKitContextMenuItem* webkitContextMenuItemCreate(WebKit::WebContextMenuItem*); -GtkMenuItem* webkitContextMenuItemRelease(WebKitContextMenuItem*); -void webkitContextMenuItemSetSubMenuFromGtkMenu(WebKitContextMenuItem*, GtkMenu*); - -#endif // WebKitContextMenuItemPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuPrivate.h deleted file mode 100644 index 5556e9f72..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitContextMenuPrivate.h +++ /dev/null @@ -1,31 +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. - */ - -#ifndef WebKitContextMenuPrivate_h -#define WebKitContextMenuPrivate_h - -#include "WebKitContextMenu.h" -#include "WebKitPrivate.h" - -WebKitContextMenu* webkitContextMenuCreate(WebKit::ImmutableArray* items); -void webkitContextMenuPopulate(WebKitContextMenu*, Vector<WebCore::ContextMenuItem>&); -void webkitContextMenuSetParentItem(WebKitContextMenu*, WebKitContextMenuItem*); -WebKitContextMenuItem* webkitContextMenuGetParentItem(WebKitContextMenu*); - -#endif // WebKitContextMenuPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp deleted file mode 100644 index daf79fe3b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.cpp +++ /dev/null @@ -1,283 +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 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 "WebKitCookieManager.h" - -#include "SoupCookiePersistentStorageType.h" -#include "WebCookieManagerProxy.h" -#include "WebKitCookieManagerPrivate.h" -#include "WebKitEnumTypes.h" -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - - LAST_SIGNAL -}; - -struct _WebKitCookieManagerPrivate { - ~_WebKitCookieManagerPrivate() - { - webCookieManager->stopObservingCookieChanges(); - } - - RefPtr<WebCookieManagerProxy> webCookieManager; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitCookieManager, webkit_cookie_manager, G_TYPE_OBJECT) - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT, SoupCookiePersistentStorageText); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE, SoupCookiePersistentStorageSQLite); - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS, HTTPCookieAcceptPolicyAlways); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_COOKIE_POLICY_ACCEPT_NEVER, HTTPCookieAcceptPolicyNever); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY, HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain); - -static void webkit_cookie_manager_class_init(WebKitCookieManagerClass* findClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(findClass); - - /** - * WebKitCookieManager::changed: - * @cookie_manager: the #WebKitCookieManager - * - * This signal is emitted when cookies are added, removed or modified. - */ - signals[CHANGED] = - g_signal_new("changed", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); -} - -static void cookiesDidChange(WKCookieManagerRef, const void* clientInfo) -{ - g_signal_emit(WEBKIT_COOKIE_MANAGER(clientInfo), signals[CHANGED], 0); -} - -WebKitCookieManager* webkitCookieManagerCreate(WebCookieManagerProxy* webCookieManager) -{ - WebKitCookieManager* manager = WEBKIT_COOKIE_MANAGER(g_object_new(WEBKIT_TYPE_COOKIE_MANAGER, NULL)); - manager->priv->webCookieManager = webCookieManager; - - WKCookieManagerClient wkCookieManagerClient = { - kWKCookieManagerClientCurrentVersion, - manager, // clientInfo - cookiesDidChange - }; - WKCookieManagerSetClient(toAPI(webCookieManager), &wkCookieManagerClient); - manager->priv->webCookieManager->startObservingCookieChanges(); - - return manager; -} - -/** - * webkit_cookie_manager_set_persistent_storage: - * @cookie_manager: a #WebKitCookieManager - * @filename: the filename to read to/write from - * @storage: a #WebKitCookiePersistentStorage - * - * Set the @filename where non-session cookies are stored persistently using - * @storage as the format to read/write the cookies. - * Cookies are initially read from @filename to create an initial set of cookies. - * Then, non-session cookies will be written to @filename when the WebKitCookieManager::changed - * signal is emitted. - * By default, @cookie_manager doesn't store the cookies persistenly, so you need to call this - * method to keep cookies saved across sessions. - */ -void webkit_cookie_manager_set_persistent_storage(WebKitCookieManager* manager, const char* filename, WebKitCookiePersistentStorage storage) -{ - g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - g_return_if_fail(filename); - - manager->priv->webCookieManager->stopObservingCookieChanges(); - manager->priv->webCookieManager->setCookiePersistentStorage(String::fromUTF8(filename), storage); - manager->priv->webCookieManager->startObservingCookieChanges(); -} - -/** - * webkit_cookie_manager_set_accept_policy: - * @cookie_manager: a #WebKitCookieManager - * @policy: a #WebKitCookieAcceptPolicy - * - * Set the cookie acceptance policy of @cookie_manager as @policy. - */ -void webkit_cookie_manager_set_accept_policy(WebKitCookieManager* manager, WebKitCookieAcceptPolicy policy) -{ - g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - - manager->priv->webCookieManager->setHTTPCookieAcceptPolicy(policy); -} - -static void webkitCookieManagerGetAcceptPolicyCallback(WKHTTPCookieAcceptPolicy policy, WKErrorRef, void* context) -{ - GRefPtr<GTask> task = adoptGRef(G_TASK(context)); - g_task_return_int(task.get(), policy); -} - -/** - * webkit_cookie_manager_get_accept_policy: - * @cookie_manager: a #WebKitCookieManager - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously get the cookie acceptance policy of @cookie_manager. - * - * When the operation is finished, @callback will be called. You can then call - * webkit_cookie_manager_get_accept_policy_finish() to get the result of the operation. - */ -void webkit_cookie_manager_get_accept_policy(WebKitCookieManager* manager, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - - GTask* task = g_task_new(manager, cancellable, callback, userData); - manager->priv->webCookieManager->getHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyCallback::create(task, webkitCookieManagerGetAcceptPolicyCallback)); -} - -/** - * webkit_cookie_manager_get_accept_policy_finish: - * @cookie_manager: a #WebKitCookieManager - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_cookie_manager_get_accept_policy(). - * - * Returns: the cookie acceptance policy of @cookie_manager as a #WebKitCookieAcceptPolicy. - */ -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_task_is_valid(result, manager), WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY); - - gssize returnValue = g_task_propagate_int(G_TASK(result), error); - return returnValue == -1 ? WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY : static_cast<WebKitCookieAcceptPolicy>(returnValue); -} - -static void webkitCookieManagerGetDomainsWithCookiesCallback(WKArrayRef wkDomains, WKErrorRef, void* context) -{ - 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_ptr_array_add(returnValue, 0); - g_task_return_pointer(task.get(), g_ptr_array_free(returnValue, FALSE), reinterpret_cast<GDestroyNotify>(g_strfreev)); -} - -/** - * webkit_cookie_manager_get_domains_with_cookies: - * @cookie_manager: a #WebKitCookieManager - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously get the list of domains for which @cookie_manager contains cookies. - * - * When the operation is finished, @callback will be called. You can then call - * webkit_cookie_manager_get_domains_with_cookies_finish() to get the result of the operation. - */ -void webkit_cookie_manager_get_domains_with_cookies(WebKitCookieManager* manager, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - - GTask* task = g_task_new(manager, cancellable, callback, userData); - manager->priv->webCookieManager->getHostnamesWithCookies(ArrayCallback::create(task, webkitCookieManagerGetDomainsWithCookiesCallback)); -} - -/** - * webkit_cookie_manager_get_domains_with_cookies_finish: - * @cookie_manager: a #WebKitCookieManager - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_cookie_manager_get_domains_with_cookies(). - * The return value is a %NULL terminated list of strings which should - * be released with g_strfreev(). - * - * Returns: (transfer full) (array zero-terminated=1): A %NULL terminated array of domain names - * or %NULL in case of error. - */ -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_task_is_valid(result, manager), 0); - - return reinterpret_cast<char**>(g_task_propagate_pointer(G_TASK(result), error)); -} - -/** - * webkit_cookie_manager_delete_cookies_for_domain: - * @cookie_manager: a #WebKitCookieManager - * @domain: a domain name - * - * Remove all cookies of @cookie_manager for the given @domain. - */ -void webkit_cookie_manager_delete_cookies_for_domain(WebKitCookieManager* manager, const gchar* domain) -{ - g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - g_return_if_fail(domain); - - manager->priv->webCookieManager->deleteCookiesForHostname(String::fromUTF8(domain)); -} - -/** - * webkit_cookie_manager_delete_all_cookies: - * @cookie_manager: a #WebKitCookieManager - * - * Delete all cookies of @cookie_manager - */ -void webkit_cookie_manager_delete_all_cookies(WebKitCookieManager* manager) -{ - g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager)); - - manager->priv->webCookieManager->deleteAllCookies(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h deleted file mode 100644 index f25f1a2b0..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManager.h +++ /dev/null @@ -1,130 +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 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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitCookieManager_h -#define WebKitCookieManager_h - -#include <gio/gio.h> -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_COOKIE_MANAGER (webkit_cookie_manager_get_type()) -#define WEBKIT_COOKIE_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_COOKIE_MANAGER, WebKitCookieManager)) -#define WEBKIT_IS_COOKIE_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_COOKIE_MANAGER)) -#define WEBKIT_COOKIE_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_COOKIE_MANAGER, WebKitCookieManagerClass)) -#define WEBKIT_IS_COOKIE_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_COOKIE_MANAGER)) -#define WEBKIT_COOKIE_MANAGER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_COOKIE_MANAGER, WebKitCookieManagerClass)) - -typedef struct _WebKitCookieManager WebKitCookieManager; -typedef struct _WebKitCookieManagerClass WebKitCookieManagerClass; -typedef struct _WebKitCookieManagerPrivate WebKitCookieManagerPrivate; - -/** - * WebKitCookiePersistentStorage: - * @WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT: Cookies are stored in a text - * file in the Mozilla "cookies.txt" format. - * @WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE: Cookies are stored in a SQLite - * file in the current Mozilla format. - * - * Enum values used to denote the cookie persistent storage types. - */ -typedef enum { - WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT, - WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE -} WebKitCookiePersistentStorage; - -/** - * WebKitCookieAcceptPolicy: - * @WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS: Accept all cookies unconditionally. - * @WEBKIT_COOKIE_POLICY_ACCEPT_NEVER: Reject all cookies unconditionally. - * @WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY: Accept only cookies set by the main document loaded. - * - * Enum values used to denote the cookie acceptance policies. - */ -typedef enum { - WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS, - WEBKIT_COOKIE_POLICY_ACCEPT_NEVER, - WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY -} WebKitCookieAcceptPolicy; - -struct _WebKitCookieManager { - GObject parent; - - WebKitCookieManagerPrivate *priv; -}; - -struct _WebKitCookieManagerClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_cookie_manager_get_type (void); - -WEBKIT_API void -webkit_cookie_manager_set_persistent_storage (WebKitCookieManager *cookie_manager, - const gchar *filename, - WebKitCookiePersistentStorage storage); - -WEBKIT_API void -webkit_cookie_manager_set_accept_policy (WebKitCookieManager *cookie_manager, - WebKitCookieAcceptPolicy policy); - -WEBKIT_API void -webkit_cookie_manager_get_accept_policy (WebKitCookieManager *cookie_manager, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API WebKitCookieAcceptPolicy -webkit_cookie_manager_get_accept_policy_finish (WebKitCookieManager *cookie_manager, - GAsyncResult *result, - GError **error); - -WEBKIT_API void -webkit_cookie_manager_get_domains_with_cookies (WebKitCookieManager *cookie_manager, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API gchar ** -webkit_cookie_manager_get_domains_with_cookies_finish (WebKitCookieManager *cookie_manager, - GAsyncResult *result, - GError **error); - -WEBKIT_API void -webkit_cookie_manager_delete_cookies_for_domain (WebKitCookieManager *cookie_manager, - const gchar *domain); - -WEBKIT_API void -webkit_cookie_manager_delete_all_cookies (WebKitCookieManager *cookie_manager); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManagerPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManagerPrivate.h deleted file mode 100644 index 6be84afae..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitCookieManagerPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitCookieManagerPrivate_h -#define WebKitCookieManagerPrivate_h - -#include "WebKitCookieManager.h" -#include "WebKitPrivate.h" - -WebKitCookieManager* webkitCookieManagerCreate(WebKit::WebCookieManagerProxy*); - -#endif // WebKitCookieManagerPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h b/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h deleted file mode 100644 index 8b637652b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDefines.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2011 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) && !defined(__WEBKIT_WEB_EXTENSION_H_INSIDE__) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitDefines_h -#define WebKitDefines_h - -#include <glib.h> - -#ifdef G_OS_WIN32 -# ifdef BUILDING_WEBKIT -# define WEBKIT_API __declspec(dllexport) -# else -# define WEBKIT_API __declspec(dllimport) -# endif -# define WEBKIT_OBSOLETE_API WEBKIT_API -#else -# define WEBKIT_API __attribute__((visibility("default"))) -# define WEBKIT_OBSOLETE_API WEBKIT_API __attribute__((deprecated)) -#endif - -#endif // WebKitDefines_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp deleted file mode 100644 index e9524c209..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.cpp +++ /dev/null @@ -1,570 +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 "WebKitDownload.h" - -#include "DownloadProxy.h" -#include "WebKitDownloadPrivate.h" -#include "WebKitMarshal.h" -#include "WebKitURIRequestPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include <WebCore/ErrorsGtk.h> -#include <WebCore/ResourceResponse.h> -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> - -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, - FAILED, - DECIDE_DESTINATION, - CREATED_DESTINATION, - - LAST_SIGNAL -}; - -enum { - PROP_0, - - PROP_DESTINATION, - PROP_RESPONSE, - PROP_ESTIMATED_PROGRESS -}; - -struct _WebKitDownloadPrivate { - ~_WebKitDownloadPrivate() - { - if (webView) - g_object_remove_weak_pointer(G_OBJECT(webView), reinterpret_cast<void**>(&webView)); - } - - RefPtr<DownloadProxy> download; - - GRefPtr<WebKitURIRequest> request; - GRefPtr<WebKitURIResponse> response; - WebKitWebView* webView; - CString destinationURI; - guint64 currentSize; - bool isCancelled; - GOwnPtr<GTimer> timer; - gdouble lastProgress; - gdouble lastElapsed; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitDownload, webkit_download, G_TYPE_OBJECT) - -static void webkitDownloadGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitDownload* download = WEBKIT_DOWNLOAD(object); - - switch (propId) { - case PROP_DESTINATION: - g_value_set_string(value, webkit_download_get_destination(download)); - break; - case PROP_RESPONSE: - g_value_set_object(value, webkit_download_get_response(download)); - break; - case PROP_ESTIMATED_PROGRESS: - g_value_set_double(value, webkit_download_get_estimated_progress(download)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static gboolean webkitDownloadDecideDestination(WebKitDownload* download, const gchar* suggestedFilename) -{ - if (!download->priv->destinationURI.isNull()) - return FALSE; - - GOwnPtr<char> filename(g_strdelimit(g_strdup(suggestedFilename), G_DIR_SEPARATOR_S, '_')); - 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"); - return TRUE; -} - -static void webkit_download_class_init(WebKitDownloadClass* downloadClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(downloadClass); - objectClass->get_property = webkitDownloadGetProperty; - - downloadClass->decide_destination = webkitDownloadDecideDestination; - - /** - * WebKitDownload:destination: - * - * The local URI to where the download will be saved. - */ - g_object_class_install_property(objectClass, - PROP_DESTINATION, - g_param_spec_string("destination", - _("Destination"), - _("The local URI to where the download will be saved"), - 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitDownload:response: - * - * The #WebKitURIResponse associated with this download. - */ - g_object_class_install_property(objectClass, - PROP_RESPONSE, - g_param_spec_object("response", - _("Response"), - _("The response of the download"), - WEBKIT_TYPE_URI_RESPONSE, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitDownload:estimated-progress: - * - * An estimate of the percent completion for the download operation. - * This value will range from 0.0 to 1.0. The value is an estimate - * based on the total number of bytes expected to be received for - * a download. - * If you need a more accurate progress information you can connect to - * #WebKitDownload::received-data signal to track the progress. - */ - g_object_class_install_property(objectClass, - PROP_ESTIMATED_PROGRESS, - g_param_spec_double("estimated-progress", - _("Estimated Progress"), - _("Determines the current progress of the download"), - 0.0, 1.0, 1.0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitDownload::received-data: - * @download: the #WebKitDownload - * @data_length: the length of data received in bytes - * - * This signal is emitted after response is received, - * every time new data has been written to the destination. It's - * useful to know the progress of the download operation. - */ - signals[RECEIVED_DATA] = - g_signal_new("received-data", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - webkit_marshal_VOID__UINT64, - G_TYPE_NONE, 1, - G_TYPE_UINT64); - - /** - * WebKitDownload::finished: - * @download: the #WebKitDownload - * - * This signal is emitted when download finishes successfully or due to an error. - * In case of errors #WebKitDownload::failed signal is emitted before this one. - */ - signals[FINISHED] = - g_signal_new("finished", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitDownload::failed: - * @download: the #WebKitDownload - * @error: the #GError that was triggered - * - * This signal is emitted when an error occurs during the download - * operation. The given @error, of the domain %WEBKIT_DOWNLOAD_ERROR, - * contains further details of the failure. If the download is cancelled - * with webkit_download_cancel(), this signal is emitted with error - * %WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER. The download operation finishes - * after an error and #WebKitDownload::finished signal is emitted after this one. - */ - signals[FAILED] = - g_signal_new("failed", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__POINTER, - G_TYPE_NONE, 1, - G_TYPE_POINTER); - - /** - * WebKitDownload::decide-destination: - * @download: the #WebKitDownload - * @suggested_filename: the filename suggested for the download - * - * This signal is emitted after response is received to - * decide a destination URI for the download. If this signal is not - * handled the file will be downloaded to %G_USER_DIRECTORY_DOWNLOAD - * directory using @suggested_filename. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[DECIDE_DESTINATION] = - g_signal_new("decide-destination", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitDownloadClass, decide_destination), - g_signal_accumulator_true_handled, NULL, - webkit_marshal_BOOLEAN__STRING, - G_TYPE_BOOLEAN, 1, - G_TYPE_STRING); - - /** - * WebKitDownload::created-destination: - * @download: the #WebKitDownload - * @destination: the destination URI - * - * This signal is emitted after #WebKitDownload::decide-destination and before - * #WebKitDownload::received-data to notify that destination file has been - * created successfully at @destination. - */ - signals[CREATED_DESTINATION] = - g_signal_new("created-destination", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__STRING, - G_TYPE_BOOLEAN, 1, - G_TYPE_STRING); -} - -WebKitDownload* webkitDownloadCreate(DownloadProxy* downloadProxy) -{ - ASSERT(downloadProxy); - WebKitDownload* download = WEBKIT_DOWNLOAD(g_object_new(WEBKIT_TYPE_DOWNLOAD, NULL)); - download->priv->download = 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; - g_object_notify(G_OBJECT(download), "response"); -} - -void webkitDownloadSetWebView(WebKitDownload* download, WebKitWebView* webView) -{ - download->priv->webView = webView; - g_object_add_weak_pointer(G_OBJECT(webView), reinterpret_cast<void**>(&download->priv->webView)); -} - -bool webkitDownloadIsCancelled(WebKitDownload* download) -{ - return download->priv->isCancelled; -} - -void webkitDownloadNotifyProgress(WebKitDownload* download, guint64 bytesReceived) -{ - WebKitDownloadPrivate* priv = download->priv; - if (priv->isCancelled) - return; - - if (!download->priv->timer) - download->priv->timer.set(g_timer_new()); - - priv->currentSize += bytesReceived; - g_signal_emit(download, signals[RECEIVED_DATA], 0, bytesReceived); - - // Throttle progress notification to not consume high amounts of - // CPU on fast links, except when the last notification occured - // more than 0.016 secs ago (60 FPS), or the last notified progress - // is passed in 1% or we reached the end. - gdouble currentElapsed = g_timer_elapsed(priv->timer.get(), 0); - gdouble currentProgress = webkit_download_get_estimated_progress(download); - - if (priv->lastElapsed - && priv->lastProgress - && (currentElapsed - priv->lastElapsed) < 0.016 - && (currentProgress - priv->lastProgress) < 0.01 - && currentProgress < 1.0) { - return; - } - priv->lastElapsed = currentElapsed; - priv->lastProgress = currentProgress; - g_object_notify(G_OBJECT(download), "estimated-progress"); -} - -void webkitDownloadFailed(WebKitDownload* download, const ResourceError& resourceError) -{ - GOwnPtr<GError> webError(g_error_new_literal(g_quark_from_string(resourceError.domain().utf8().data()), - resourceError.errorCode(), - resourceError.localizedDescription().utf8().data())); - if (download->priv->timer) - g_timer_stop(download->priv->timer.get()); - - g_signal_emit(download, signals[FAILED], 0, webError.get()); - g_signal_emit(download, signals[FINISHED], 0, NULL); -} - -void webkitDownloadCancelled(WebKitDownload* download) -{ - WebKitDownloadPrivate* priv = download->priv; - webkitDownloadFailed(download, downloadCancelledByUserError(priv->response ? webkitURIResponseGetResourceResponse(priv->response.get()) : ResourceResponse())); -} - -void webkitDownloadFinished(WebKitDownload* download) -{ - if (download->priv->isCancelled) { - // Since cancellation is asynchronous, didFinish might be called even - // if the download was cancelled. User cancelled the download, - // so we should fail with cancelled error even if the download - // actually finished successfully. - webkitDownloadCancelled(download); - return; - } - if (download->priv->timer) - g_timer_stop(download->priv->timer.get()); - g_signal_emit(download, signals[FINISHED], 0, NULL); -} - -CString webkitDownloadDecideDestinationWithSuggestedFilename(WebKitDownload* download, const CString& suggestedFilename) -{ - if (download->priv->isCancelled) - return ""; - gboolean returnValue; - g_signal_emit(download, signals[DECIDE_DESTINATION], 0, suggestedFilename.data(), &returnValue); - return download->priv->destinationURI; -} - -void webkitDownloadDestinationCreated(WebKitDownload* download, const CString& destinationURI) -{ - if (download->priv->isCancelled) - return; - gboolean returnValue; - g_signal_emit(download, signals[CREATED_DESTINATION], 0, destinationURI.data(), &returnValue); -} - -/** - * webkit_download_get_request: - * @download: a #WebKitDownload - * - * Retrieves the #WebKitURIRequest object that backs the download - * process. - * - * Returns: (transfer none): the #WebKitURIRequest of @download - */ -WebKitURIRequest* webkit_download_get_request(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - WebKitDownloadPrivate* priv = download->priv; - if (!priv->request) - priv->request = adoptGRef(webkitURIRequestCreateForResourceRequest(priv->download->request())); - return priv->request.get(); -} - -/** - * webkit_download_get_destination: - * @download: a #WebKitDownload - * - * Obtains the URI to which the downloaded file will be written. You - * can connect to #WebKitDownload::created-destination to make - * sure this method returns a valid destination. - * - * Returns: the destination URI or %NULL - */ -const gchar* webkit_download_get_destination(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - return download->priv->destinationURI.data(); -} - -/** - * webkit_download_set_destination: - * @download: a #WebKitDownload - * @uri: the destination URI - * - * Sets the URI to which the downloaded file will be written. - * This method should be called before the download transfer - * starts or it will not have any effect on the ongoing download - * operation. To set the destination using the filename suggested - * by the server connect to #WebKitDownload::decide-destination - * signal and call webkit_download_set_destination(). If you want to - * set a fixed destination URI that doesn't depend on the suggested - * filename you can connect to notify::response signal and call - * webkit_download_set_destination(). - * If #WebKitDownload::decide-destination signal is not handled - * and destination URI is not set when the download tranfer starts, - * the file will be saved with the filename suggested by the server in - * %G_USER_DIRECTORY_DOWNLOAD directory. - */ -void webkit_download_set_destination(WebKitDownload* download, const gchar* uri) -{ - g_return_if_fail(WEBKIT_IS_DOWNLOAD(download)); - g_return_if_fail(uri); - - WebKitDownloadPrivate* priv = download->priv; - if (priv->destinationURI == uri) - return; - - priv->destinationURI = uri; - g_object_notify(G_OBJECT(download), "destination"); -} - -/** - * webkit_download_get_response: - * @download: a #WebKitDownload - * - * Retrieves the #WebKitURIResponse object that backs the download - * process. This method returns %NULL if called before the response - * is received from the server. You can connect to notify::response - * signal to be notified when the response is received. - * - * Returns: (transfer none): the #WebKitURIResponse, or %NULL if - * the response hasn't been received yet. - */ -WebKitURIResponse* webkit_download_get_response(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - return download->priv->response.get(); -} - -/** - * webkit_download_cancel: - * @download: a #WebKitDownload - * - * Cancels the download. When the ongoing download - * operation is effectively cancelled the signal - * #WebKitDownload::failed is emitted with - * %WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER error. - */ -void webkit_download_cancel(WebKitDownload* download) -{ - g_return_if_fail(WEBKIT_IS_DOWNLOAD(download)); - - download->priv->isCancelled = true; - download->priv->download->cancel(); -} - -/** - * webkit_download_get_estimated_progress: - * @download: a #WebKitDownload - * - * Gets the value of the #WebKitDownload:estimated-progress property. - * You can monitor the estimated progress of the download operation by - * connecting to the notify::estimated-progress signal of @download. - * - * Returns: an estimate of the of the percent complete for a download - * as a range from 0.0 to 1.0. - */ -gdouble webkit_download_get_estimated_progress(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - WebKitDownloadPrivate* priv = download->priv; - if (!priv->response) - return 0; - - guint64 contentLength = webkit_uri_response_get_content_length(priv->response.get()); - if (!contentLength) - return 0; - - return static_cast<gdouble>(priv->currentSize) / static_cast<gdouble>(contentLength); -} - -/** - * webkit_download_get_elapsed_time: - * @download: a #WebKitDownload - * - * Gets the elapsed time in seconds, including any fractional part. - * If the download finished, had an error or was cancelled this is - * the time between its start and the event. - * - * Returns: seconds since the download was started - */ -gdouble webkit_download_get_elapsed_time(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - WebKitDownloadPrivate* priv = download->priv; - if (!priv->timer) - return 0; - - return g_timer_elapsed(priv->timer.get(), 0); -} - -/** - * webkit_download_get_received_data_length: - * @download: a #WebKitDownload - * - * Gets the length of the data already downloaded for @download - * in bytes. - * - * Returns: the amount of bytes already downloaded. - */ -guint64 webkit_download_get_received_data_length(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - return download->priv->currentSize; -} - -/** - * webkit_download_get_web_view: - * @download: a #WebKitDownload - * - * Get the #WebKitWebView that initiated the download. - * - * Returns: (transfer none): the #WebKitWebView that initiated @download, - * or %NULL if @download was not initiated by a #WebKitWebView. - */ -WebKitWebView* webkit_download_get_web_view(WebKitDownload* download) -{ - g_return_val_if_fail(WEBKIT_IS_DOWNLOAD(download), 0); - - return download->priv->webView; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h b/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h deleted file mode 100644 index 493bfea40..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownload.h +++ /dev/null @@ -1,97 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitDownload_h -#define WebKitDownload_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitForwardDeclarations.h> -#include <webkit2/WebKitURIRequest.h> -#include <webkit2/WebKitURIResponse.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_DOWNLOAD (webkit_download_get_type()) -#define WEBKIT_DOWNLOAD(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_DOWNLOAD, WebKitDownload)) -#define WEBKIT_IS_DOWNLOAD(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_DOWNLOAD)) -#define WEBKIT_DOWNLOAD_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_DOWNLOAD, WebKitDownloadClass)) -#define WEBKIT_IS_DOWNLOAD_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_DOWNLOAD)) -#define WEBKIT_DOWNLOAD_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_DOWNLOAD, WebKitDownloadClass)) - -typedef struct _WebKitDownload WebKitDownload; -typedef struct _WebKitDownloadClass WebKitDownloadClass; -typedef struct _WebKitDownloadPrivate WebKitDownloadPrivate; - -struct _WebKitDownload { - GObject parent; - - WebKitDownloadPrivate *priv; -}; - -struct _WebKitDownloadClass { - GObjectClass parent_class; - - 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 -webkit_download_get_type (void); - -WEBKIT_API WebKitURIRequest * -webkit_download_get_request (WebKitDownload *download); - -WEBKIT_API const gchar * -webkit_download_get_destination (WebKitDownload *download); - -WEBKIT_API void -webkit_download_set_destination (WebKitDownload *download, - const gchar *uri); - -WEBKIT_API WebKitURIResponse* -webkit_download_get_response (WebKitDownload *download); - -WEBKIT_API void -webkit_download_cancel (WebKitDownload *download); - -WEBKIT_API gdouble -webkit_download_get_estimated_progress (WebKitDownload *download); - -WEBKIT_API gdouble -webkit_download_get_elapsed_time (WebKitDownload *download); - -WEBKIT_API guint64 -webkit_download_get_received_data_length (WebKitDownload *download); - -WEBKIT_API WebKitWebView * -webkit_download_get_web_view (WebKitDownload *download); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadClient.cpp deleted file mode 100644 index 79c1c3e2a..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadClient.cpp +++ /dev/null @@ -1,115 +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 "WebKitDownloadClient.h" - -#include "WebContext.h" -#include "WebKitDownloadPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include "WebKitWebContextPrivate.h" -#include "WebURLResponse.h" -#include <WebKit2/WKString.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -using namespace WebCore; -using namespace WebKit; - -static void didStart(WKContextRef, WKDownloadRef wkDownload, const void* clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - webkitWebContextDownloadStarted(WEBKIT_WEB_CONTEXT(clientInfo), download.get()); -} - -static void didReceiveResponse(WKContextRef, WKDownloadRef wkDownload, WKURLResponseRef wkResponse, const void* clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - if (webkitDownloadIsCancelled(download.get())) - return; - - GRefPtr<WebKitURIResponse> response = adoptGRef(webkitURIResponseCreateForResourceResponse(toImpl(wkResponse)->resourceResponse())); - webkitDownloadSetResponse(download.get(), response.get()); -} - -static void didReceiveData(WKContextRef, WKDownloadRef wkDownload, uint64_t length, const void* clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - webkitDownloadNotifyProgress(download.get(), length); -} - -static WKStringRef decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef wkDownload, WKStringRef filename, bool* allowOverwrite, const void* clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - CString destinationURI = webkitDownloadDecideDestinationWithSuggestedFilename(download.get(), - toImpl(filename)->string().utf8()); - return WKStringCreateWithUTF8CString(destinationURI.data()); -} - -static void didCreateDestination(WKContextRef, WKDownloadRef wkDownload, WKStringRef path, const void* clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - webkitDownloadDestinationCreated(download.get(), toImpl(path)->string().utf8()); -} - -static void didFail(WKContextRef, WKDownloadRef wkDownload, WKErrorRef error, const void *clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - if (webkitDownloadIsCancelled(download.get())) { - // Cancellation takes precedence over other errors. - webkitDownloadCancelled(download.get()); - } else - webkitDownloadFailed(download.get(), toImpl(error)->platformError()); - webkitWebContextRemoveDownload(toImpl(wkDownload)); -} - -static void didCancel(WKContextRef, WKDownloadRef wkDownload, const void *clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - webkitDownloadCancelled(download.get()); - webkitWebContextRemoveDownload(toImpl(wkDownload)); -} - -static void didFinish(WKContextRef wkContext, WKDownloadRef wkDownload, const void *clientInfo) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(toImpl(wkDownload)); - webkitDownloadFinished(download.get()); - webkitWebContextRemoveDownload(toImpl(wkDownload)); -} - -void attachDownloadClientToContext(WebKitWebContext* webContext) -{ - WKContextDownloadClient wkDownloadClient = { - kWKContextDownloadClientCurrentVersion, - webContext, // ClientInfo - didStart, - 0, // didReceiveAuthenticationChallenge - didReceiveResponse, - didReceiveData, - 0, // shouldDecodeSourceDataOfMIMEType - decideDestinationWithSuggestedFilename, - didCreateDestination, - didFinish, - didFail, - didCancel, - 0, // processDidCrash - }; - WKContextSetDownloadClient(toAPI(webkitWebContextGetContext(webContext)), &wkDownloadClient); -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h deleted file mode 100644 index 980ad732b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitDownloadPrivate.h +++ /dev/null @@ -1,41 +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. - */ - -#ifndef WebKitDownloadPrivate_h -#define WebKitDownloadPrivate_h - -#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*); -void webkitDownloadNotifyProgress(WebKitDownload*, guint64 bytesReceived); -void webkitDownloadFailed(WebKitDownload*, const WebCore::ResourceError&); -void webkitDownloadCancelled(WebKitDownload*); -void webkitDownloadFinished(WebKitDownload*); -CString webkitDownloadDecideDestinationWithSuggestedFilename(WebKitDownload*, const CString& suggestedFilename); -void webkitDownloadDestinationCreated(WebKitDownload*, const CString& destinationURI); - -#endif // WebKitDownloadPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitEditingCommands.h b/Source/WebKit2/UIProcess/API/gtk/WebKitEditingCommands.h deleted file mode 100644 index 437395710..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitEditingCommands.h +++ /dev/null @@ -1,99 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitEditingCommands_h -#define WebKitEditingCommands_h - -G_BEGIN_DECLS - -/** - * WEBKIT_EDITING_COMMAND_CUT: - * - * The cut clipboard command. Copies the current selection inside - * a #WebKitWebView to the clipboard and deletes the selected content. - * You can check whether it's possible to execute the command with - * webkit_web_view_can_execute_editing_command(). In general it's - * possible to cut to the clipboard when the #WebKitWebView content is - * editable and there is an active selection. - */ -#define WEBKIT_EDITING_COMMAND_CUT "Cut" - -/** - * WEBKIT_EDITING_COMMAND_COPY: - * - * The copy clipboard command. Copies the current selection inside - * a #WebKitWebView to the clipboard. - * You can check whether it's possible to execute the command with - * webkit_web_view_can_execute_editing_command(). In general it's - * possible to copy to the clipboard when there is an active selection - * inside the #WebKitWebView. - */ -#define WEBKIT_EDITING_COMMAND_COPY "Copy" - -/** - * WEBKIT_EDITING_COMMAND_PASTE: - * - * The paste clipboard command. Pastes the contents of the clipboard to - * a #WebKitWebView. - * You can check whether it's possible to execute the command with - * webkit_web_view_can_execute_editing_command(). In general it's possible - * to paste from the clipboard when the #WebKitWebView content is editable - * and clipboard is not empty. - */ -#define WEBKIT_EDITING_COMMAND_PASTE "Paste" - -/** - * WEBKIT_EDITING_COMMAND_SELECT_ALL: - * - * The select all command. Selects all the content of the current text field in - * a #WebKitWebView. - * It is always possible to select all text, no matter whether the - * #WebKitWebView content is editable or not. You can still check it - * with webkit_web_view_can_execute_editing_command(). - */ -#define WEBKIT_EDITING_COMMAND_SELECT_ALL "SelectAll" - -/** - * WEBKIT_EDITING_COMMAND_UNDO: - * - * The undo command. Undoes the last editing command in a #WebKitWebView. - * You can check whether it's possible to execute the command with - * webkit_web_view_can_execute_editing_command(). It's only possible - * to undo a command after a previously executed editing operation. - */ -#define WEBKIT_EDITING_COMMAND_UNDO "Undo" - -/** - * WEBKIT_EDITING_COMMAND_REDO: - * - * The redo command. Redoes a previously undone editing command in - * a #WebKitWebView. - * You can check whether it's possible to execute the command with - * webkit_web_view_can_execute_editing_command(). It's only possible - * to redo a command when it has been previously undone. - */ -#define WEBKIT_EDITING_COMMAND_REDO "Redo" - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.cpp.template b/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.cpp.template deleted file mode 100644 index 292e1e556..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.cpp.template +++ /dev/null @@ -1,62 +0,0 @@ -/*** 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 deleted file mode 100644 index 1283e0bbd..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitEnumTypes.h.template +++ /dev/null @@ -1,54 +0,0 @@ -/*** 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 deleted file mode 100644 index c06dc61a5..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitError.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Copyright (C) 2008 Luca Bruno <lethalman88@gmail.com> - * - * 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 "WebKitError.h" - -#include "WebKitPrivate.h" -#include <WebCore/ErrorsGtk.h> - -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); -} - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NETWORK_ERROR_FAILED, NetworkErrorFailed); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NETWORK_ERROR_TRANSPORT, NetworkErrorTransport); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NETWORK_ERROR_UNKNOWN_PROTOCOL, NetworkErrorUnknownProtocol); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NETWORK_ERROR_CANCELLED, NetworkErrorCancelled); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NETWORK_ERROR_FILE_DOES_NOT_EXIST, NetworkErrorFileDoesNotExist); - -GQuark webkit_policy_error_quark() -{ - return g_quark_from_static_string(WebCore::errorDomainPolicy); -} - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_POLICY_ERROR_FAILED, PolicyErrorFailed); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_POLICY_ERROR_CANNOT_SHOW_MIME_TYPE, PolicyErrorCannotShowMimeType); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_POLICY_ERROR_CANNOT_SHOW_URI, PolicyErrorCannotShowURL); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE, PolicyErrorFrameLoadInterruptedByPolicyChange); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_POLICY_ERROR_CANNOT_USE_RESTRICTED_PORT, PolicyErrorCannotUseRestrictedPort); - -GQuark webkit_plugin_error_quark() -{ - return g_quark_from_static_string(WebCore::errorDomainPlugin); -} - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PLUGIN_ERROR_FAILED, PluginErrorFailed); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PLUGIN_ERROR_CANNOT_FIND_PLUGIN, PluginErrorCannotFindPlugin); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PLUGIN_ERROR_CANNOT_LOAD_PLUGIN, PluginErrorCannotLoadPlugin); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PLUGIN_ERROR_JAVA_UNAVAILABLE, PluginErrorJavaUnavailable); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PLUGIN_ERROR_CONNECTION_CANCELLED, PluginErrorConnectionCancelled); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD, PluginErrorWillHandleLoad); - -GQuark webkit_download_error_quark() -{ - return g_quark_from_static_string(WebCore::errorDomainDownload); -} - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_DOWNLOAD_ERROR_NETWORK, DownloadErrorNetwork); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER, DownloadErrorCancelledByUser); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_DOWNLOAD_ERROR_DESTINATION, DownloadErrorDestination); - -GQuark webkit_print_error_quark() -{ - return g_quark_from_static_string(WebCore::errorDomainPrint); -} - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PRINT_ERROR_GENERAL, PrintErrorGeneral); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PRINT_ERROR_PRINTER_NOT_FOUND, PrintErrorPrinterNotFound); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_PRINT_ERROR_INVALID_PAGE_RANGE, PrintErrorInvalidPageRange); - -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 deleted file mode 100644 index e7de93bc2..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitError.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Copyright (C) 2008 Luca Bruno <lethalman88@gmail.com> - * - * 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 WebKitError_h -#define WebKitError_h - -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_NETWORK_ERROR webkit_network_error_quark () -#define WEBKIT_POLICY_ERROR webkit_policy_error_quark () -#define WEBKIT_PLUGIN_ERROR webkit_plugin_error_quark () -#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: - * @WEBKIT_NETWORK_ERROR_FAILED: Generic load failure - * @WEBKIT_NETWORK_ERROR_TRANSPORT: Load failure due to transport error - * @WEBKIT_NETWORK_ERROR_UNKNOWN_PROTOCOL: Load failure due to unknown protocol - * @WEBKIT_NETWORK_ERROR_CANCELLED: Load failure due to cancellation - * @WEBKIT_NETWORK_ERROR_FILE_DOES_NOT_EXIST: Load failure due to missing file - * - * Enum values used to denote the various network errors. - **/ -typedef enum { - WEBKIT_NETWORK_ERROR_FAILED = 399, - WEBKIT_NETWORK_ERROR_TRANSPORT = 300, - WEBKIT_NETWORK_ERROR_UNKNOWN_PROTOCOL = 301, - WEBKIT_NETWORK_ERROR_CANCELLED = 302, - WEBKIT_NETWORK_ERROR_FILE_DOES_NOT_EXIST = 303 -} WebKitNetworkError; - -/** - * WebKitPolicyError: - * @WEBKIT_POLICY_ERROR_FAILED: Generic load failure due to policy error - * @WEBKIT_POLICY_ERROR_CANNOT_SHOW_MIME_TYPE: Load failure due to unsupported mime type - * @WEBKIT_POLICY_ERROR_CANNOT_SHOW_URI: Load failure due to URI that can not be shown - * @WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE: Load failure due to frame load interruption by policy change - * @WEBKIT_POLICY_ERROR_CANNOT_USE_RESTRICTED_PORT: Load failure due to port restriction - * - * Enum values used to denote the various policy errors. - **/ -typedef enum { - WEBKIT_POLICY_ERROR_FAILED = 199, - WEBKIT_POLICY_ERROR_CANNOT_SHOW_MIME_TYPE = 100, - WEBKIT_POLICY_ERROR_CANNOT_SHOW_URI = 101, - WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE = 102, - WEBKIT_POLICY_ERROR_CANNOT_USE_RESTRICTED_PORT = 103 -} WebKitPolicyError; - -/** - * WebKitPluginError: - * @WEBKIT_PLUGIN_ERROR_FAILED: Generic plugin load failure - * @WEBKIT_PLUGIN_ERROR_CANNOT_FIND_PLUGIN: Load failure due to missing plugin - * @WEBKIT_PLUGIN_ERROR_CANNOT_LOAD_PLUGIN: Load failure due to inability to load plugin - * @WEBKIT_PLUGIN_ERROR_JAVA_UNAVAILABLE: Load failue due to missing Java support that is required to load plugin - * @WEBKIT_PLUGIN_ERROR_CONNECTION_CANCELLED: Load failure due to connection cancellation - * @WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD: Load failure since plugin handles the load - * - * Enum values used to denote the various plugin errors. - **/ -typedef enum { - WEBKIT_PLUGIN_ERROR_FAILED = 299, - WEBKIT_PLUGIN_ERROR_CANNOT_FIND_PLUGIN = 200, - WEBKIT_PLUGIN_ERROR_CANNOT_LOAD_PLUGIN = 201, - WEBKIT_PLUGIN_ERROR_JAVA_UNAVAILABLE = 202, - WEBKIT_PLUGIN_ERROR_CONNECTION_CANCELLED = 203, - WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD = 204, -} WebKitPluginError; - -/** - * WebKitDownloadError: - * @WEBKIT_DOWNLOAD_ERROR_NETWORK: Download failure due to network error - * @WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER: Download was cancelled by user - * @WEBKIT_DOWNLOAD_ERROR_DESTINATION: Download failure due to destination error - * - * Enum values used to denote the various download errors. - */ -typedef enum { - WEBKIT_DOWNLOAD_ERROR_NETWORK = 499, - WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER = 400, - WEBKIT_DOWNLOAD_ERROR_DESTINATION = 401 -} WebKitDownloadError; - -/** - * WebKitPrintError: - * @WEBKIT_PRINT_ERROR_GENERAL: Unspecified error during a print operation - * @WEBKIT_PRINT_ERROR_PRINTER_NOT_FOUND: Selected printer cannot be found - * @WEBKIT_PRINT_ERROR_INVALID_PAGE_RANGE: Invalid page range - * - * Enum values used to denote the various print errors. - */ -typedef enum { - WEBKIT_PRINT_ERROR_GENERAL = 599, - WEBKIT_PRINT_ERROR_PRINTER_NOT_FOUND = 500, - WEBKIT_PRINT_ERROR_INVALID_PAGE_RANGE = 501 -} WebKitPrintError; - -/** - * WebKitJavascriptError: - * @WEBKIT_JAVASCRIPT_ERROR_SCRIPT_FAILED: An exception was raised in Javascript execution - * - * Enum values used to denote errors happending when executing Javascript - */ -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); - -WEBKIT_API GQuark -webkit_policy_error_quark (void); - -WEBKIT_API GQuark -webkit_plugin_error_quark (void); - -WEBKIT_API GQuark -webkit_download_error_quark (void); - -WEBKIT_API GQuark -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 deleted file mode 100644 index af274b97d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.cpp +++ /dev/null @@ -1,381 +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 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 "WebKitFaviconDatabase.h" - -#include "WebKitFaviconDatabasePrivate.h" -#include "WebKitMarshal.h" -#include "WebKitPrivate.h" -#include <WebCore/FileSystem.h> -#include <WebCore/Image.h> -#include <WebCore/IntSize.h> -#include <WebCore/RefPtrCairo.h> -#include <glib/gi18n-lib.h> -#include <wtf/MainThread.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - - LAST_SIGNAL -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -typedef Vector<GRefPtr<GTask> > PendingIconRequestVector; -typedef HashMap<String, PendingIconRequestVector*> PendingIconRequestMap; - -struct _WebKitFaviconDatabasePrivate { - RefPtr<WebIconDatabase> iconDatabase; - PendingIconRequestMap pendingIconRequests; - HashMap<String, String> pageURLToIconURLMap; -}; - -WEBKIT_DEFINE_TYPE(WebKitFaviconDatabase, webkit_favicon_database, G_TYPE_OBJECT) - -static void webkitFaviconDatabaseDispose(GObject* object) -{ - WebKitFaviconDatabase* database = WEBKIT_FAVICON_DATABASE(object); - - WebKitFaviconDatabasePrivate* priv = database->priv; - if (priv->iconDatabase->isOpen()) - priv->iconDatabase->close(); - - G_OBJECT_CLASS(webkit_favicon_database_parent_class)->dispose(object); -} - -static void webkit_favicon_database_class_init(WebKitFaviconDatabaseClass* faviconDatabaseClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(faviconDatabaseClass); - gObjectClass->dispose = webkitFaviconDatabaseDispose; - - /** - * WebKitFaviconDatabase::favicon-changed: - * @database: the object on which the signal is emitted - * @page_uri: the URI of the Web page containing the icon - * @favicon_uri: the URI of the favicon - * - * This signal is emitted when the favicon URI of @page_uri has - * been changed to @favicon_uri in the database. You can connect - * to this signal and call webkit_favicon_database_get_favicon() - * to get the favicon. If you are interested in the favicon of a - * #WebKitWebView it's easier to use the #WebKitWebView:favicon - * property. See webkit_web_view_get_favicon() for more details. - */ - signals[FAVICON_CHANGED] = - g_signal_new( - "favicon-changed", - G_TYPE_FROM_CLASS(faviconDatabaseClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - webkit_marshal_VOID__STRING_STRING, - G_TYPE_NONE, 2, - G_TYPE_STRING, - G_TYPE_STRING); -} - -struct GetFaviconSurfaceAsyncData { - ~GetFaviconSurfaceAsyncData() - { - if (shouldReleaseIconForPageURL) - faviconDatabase->priv->iconDatabase->releaseIconForPageURL(pageURL); - } - - GRefPtr<WebKitFaviconDatabase> faviconDatabase; - String pageURL; - RefPtr<cairo_surface_t> icon; - GRefPtr<GCancellable> cancellable; - bool shouldReleaseIconForPageURL; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(GetFaviconSurfaceAsyncData) - -static PassRefPtr<cairo_surface_t> getIconSurfaceSynchronously(WebKitFaviconDatabase* database, const String& pageURL, GError** error) -{ - ASSERT(isMainThread()); - - // The exact size we pass is irrelevant to the iconDatabase code. - // We must pass something greater than 0x0 to get an icon. - WebCore::Image* iconImage = database->priv->iconDatabase->imageForPageURL(pageURL, WebCore::IntSize(1, 1)); - if (!iconImage) { - g_set_error(error, WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN, _("Unknown favicon for page %s"), pageURL.utf8().data()); - return 0; - } - - 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 surface.release(); -} - -static void deletePendingIconRequests(WebKitFaviconDatabase* database, PendingIconRequestVector* requests, const String& pageURL) -{ - database->priv->pendingIconRequests.remove(pageURL); - delete requests; -} - -static void processPendingIconsForPageURL(WebKitFaviconDatabase* database, const String& pageURL) -{ - PendingIconRequestVector* pendingIconRequests = database->priv->pendingIconRequests.get(pageURL); - if (!pendingIconRequests) - return; - - GOwnPtr<GError> error; - RefPtr<cairo_surface_t> icon = getIconSurfaceSynchronously(database, pageURL, &error.outPtr()); - - for (size_t i = 0; i < pendingIconRequests->size(); ++i) { - 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); - } - } - deletePendingIconRequests(database, pendingIconRequests, pageURL); -} - -static void didChangeIconForPageURLCallback(WKIconDatabaseRef wkIconDatabase, WKURLRef wkPageURL, const void* clientInfo) -{ - WebKitFaviconDatabase* database = WEBKIT_FAVICON_DATABASE(clientInfo); - if (!database->priv->iconDatabase->isUrlImportCompleted()) - return; - - // Wait until there's an icon record in the database for this page URL. - String pageURL = toImpl(wkPageURL)->string(); - WebCore::Image* iconImage = database->priv->iconDatabase->imageForPageURL(pageURL, WebCore::IntSize(1, 1)); - if (!iconImage || iconImage->isNull()) - return; - - String currentIconURL; - database->priv->iconDatabase->synchronousIconURLForPageURL(pageURL, currentIconURL); - const String& iconURL = database->priv->pageURLToIconURLMap.get(pageURL); - if (iconURL == currentIconURL) - return; - - database->priv->pageURLToIconURLMap.set(pageURL, currentIconURL); - g_signal_emit(database, signals[FAVICON_CHANGED], 0, pageURL.utf8().data(), currentIconURL.utf8().data()); -} - -static void iconDataReadyForPageURLCallback(WKIconDatabaseRef wkIconDatabase, WKURLRef wkPageURL, const void* clientInfo) -{ - ASSERT(isMainThread()); - processPendingIconsForPageURL(WEBKIT_FAVICON_DATABASE(clientInfo), toImpl(wkPageURL)->string()); -} - -WebKitFaviconDatabase* webkitFaviconDatabaseCreate(WebIconDatabase* iconDatabase) -{ - WebKitFaviconDatabase* faviconDatabase = WEBKIT_FAVICON_DATABASE(g_object_new(WEBKIT_TYPE_FAVICON_DATABASE, NULL)); - faviconDatabase->priv->iconDatabase = iconDatabase; - - WKIconDatabaseClient wkIconDatabaseClient = { - kWKIconDatabaseClientCurrentVersion, - faviconDatabase, // clientInfo - didChangeIconForPageURLCallback, - 0, // didRemoveAllIconsCallback - iconDataReadyForPageURLCallback, - }; - WKIconDatabaseSetIconDatabaseClient(toAPI(iconDatabase), &wkIconDatabaseClient); - return faviconDatabase; -} - -static PendingIconRequestVector* getOrCreatePendingIconRequests(WebKitFaviconDatabase* database, const String& pageURL) -{ - PendingIconRequestVector* icons = database->priv->pendingIconRequests.get(pageURL); - if (!icons) { - icons = new PendingIconRequestVector; - database->priv->pendingIconRequests.set(pageURL, icons); - } - - return icons; -} - -GQuark webkit_favicon_database_error_quark(void) -{ - return g_quark_from_static_string("WebKitFaviconDatabaseError"); -} - -/** - * webkit_favicon_database_get_favicon: - * @database: a #WebKitFaviconDatabase - * @page_uri: URI of the page for which we want to retrieve the favicon - * @cancellable: (allow-none): A #GCancellable or %NULL. - * @callback: (scope async): A #GAsyncReadyCallback to call when the request is - * satisfied or %NULL if you don't care about the result. - * @user_data: (closure): The data to pass to @callback. - * - * Asynchronously obtains a #cairo_surface_t of the favicon for the - * given page URI. It returns the cached icon if it's in the database - * asynchronously waiting for the icon to be read from the database. - * - * This is an asynchronous method. When the operation is finished, callback will - * be invoked. You can then call webkit_favicon_database_get_favicon_finish() - * to get the result of the operation. - */ -void webkit_favicon_database_get_favicon(WebKitFaviconDatabase* database, const gchar* pageURI, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_FAVICON_DATABASE(database)); - g_return_if_fail(pageURI); - - WebKitFaviconDatabasePrivate* priv = database->priv; - WebIconDatabase* iconDatabaseImpl = priv->iconDatabase.get(); - if (!iconDatabaseImpl->isOpen()) { - 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 (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, - // we'll be notified later (even if the database is still importing icons). - GOwnPtr<GError> error; - data->icon = getIconSurfaceSynchronously(database, data->pageURL, &error.outPtr()); - if (data->icon) { - g_task_return_boolean(task.get(), TRUE); - return; - } - - // At this point we still don't know whether we will get a valid icon for pageURL. - data->shouldReleaseIconForPageURL = true; - - if (g_error_matches(error.get(), WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND)) { - g_task_return_error(task.get(), error.release()); - return; - } - - // If there's not a 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 iconDataReadyForPage to be - // called before making and informed decision. - String iconURLForPageURL; - iconDatabaseImpl->synchronousIconURLForPageURL(data->pageURL, iconURLForPageURL); - if (!iconURLForPageURL.isEmpty() || !iconDatabaseImpl->isUrlImportCompleted()) { - PendingIconRequestVector* iconRequests = getOrCreatePendingIconRequests(database, data->pageURL); - ASSERT(iconRequests); - iconRequests->append(task); - return; - } - - g_task_return_new_error(task.get(), WEBKIT_FAVICON_DATABASE_ERROR, WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN, - _("Unknown favicon for page %s"), pageURI); -} - -/** - * webkit_favicon_database_get_favicon_finish: - * @database: a #WebKitFaviconDatabase - * @result: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to webkit_favicon_database_get_favicon() - * @error: (allow-none): Return location for error or %NULL. - * - * Finishes an operation started with webkit_favicon_database_get_favicon(). - * - * Returns: (transfer full): a new reference to a #cairo_surface_t, or - * %NULL in case of error. - */ -cairo_surface_t* webkit_favicon_database_get_favicon_finish(WebKitFaviconDatabase* database, GAsyncResult* result, GError** error) -{ - g_return_val_if_fail(WEBKIT_IS_FAVICON_DATABASE(database), 0); - g_return_val_if_fail(g_task_is_valid(result, database), 0); - - GTask* task = G_TASK(result); - if (!g_task_propagate_boolean(task, error)) - return 0; - - GetFaviconSurfaceAsyncData* data = static_cast<GetFaviconSurfaceAsyncData*>(g_task_get_task_data(task)); - return cairo_surface_reference(data->icon.get()); -} - -/** - * webkit_favicon_database_get_favicon_uri: - * @database: a #WebKitFaviconDatabase - * @page_uri: URI of the page containing the icon - * - * Obtains the URI of the favicon for the given @page_uri. - * - * Returns: a newly allocated URI for the favicon, or %NULL if the - * database doesn't have a favicon for @page_uri. - */ -gchar* webkit_favicon_database_get_favicon_uri(WebKitFaviconDatabase* database, const gchar* pageURL) -{ - g_return_val_if_fail(WEBKIT_IS_FAVICON_DATABASE(database), 0); - g_return_val_if_fail(pageURL, 0); - ASSERT(isMainThread()); - - String iconURLForPageURL; - database->priv->iconDatabase->synchronousIconURLForPageURL(String::fromUTF8(pageURL), iconURLForPageURL); - if (iconURLForPageURL.isEmpty()) - return 0; - - return g_strdup(iconURLForPageURL.utf8().data()); -} - -/** - * webkit_favicon_database_clear: - * @database: a #WebKitFaviconDatabase - * - * Clears all icons from the database. - */ -void webkit_favicon_database_clear(WebKitFaviconDatabase* database) -{ - g_return_if_fail(WEBKIT_IS_FAVICON_DATABASE(database)); - - database->priv->iconDatabase->removeAllIcons(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h deleted file mode 100644 index 45fbb5d88..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabase.h +++ /dev/null @@ -1,99 +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 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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitFaviconDatabase_h -#define WebKitFaviconDatabase_h - -#include <cairo.h> -#include <gio/gio.h> -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_FAVICON_DATABASE (webkit_favicon_database_get_type()) -#define WEBKIT_FAVICON_DATABASE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_FAVICON_DATABASE, WebKitFaviconDatabase)) -#define WEBKIT_IS_FAVICON_DATABASE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_FAVICON_DATABASE)) -#define WEBKIT_FAVICON_DATABASE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_FAVICON_DATABASE, WebKitFaviconDatabaseClass)) -#define WEBKIT_IS_FAVICON_DATABASE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_FAVICON_DATABASE)) -#define WEBKIT_FAVICON_DATABASE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_FAVICON_DATABASE, WebKitFaviconDatabaseClass)) -#define WEBKIT_FAVICON_DATABASE_ERROR (webkit_favicon_database_error_quark()) - -typedef struct _WebKitFaviconDatabase WebKitFaviconDatabase; -typedef struct _WebKitFaviconDatabaseClass WebKitFaviconDatabaseClass; -typedef struct _WebKitFaviconDatabasePrivate WebKitFaviconDatabasePrivate; - -struct _WebKitFaviconDatabase { - GObject parent; - - WebKitFaviconDatabasePrivate *priv; -}; - -struct _WebKitFaviconDatabaseClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -/** - * WebKitFaviconDatabaseError: - * @WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED: The #WebKitFaviconDatabase has not been initialized yet - * @WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND: There is not an icon available for the requested URL - * @WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN: There might be an icon for the requested URL, but its data is unknown at the moment - * - * Enum values used to denote the various errors related to the #WebKitFaviconDatabase. - **/ -typedef enum { - WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED, - WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_NOT_FOUND, - WEBKIT_FAVICON_DATABASE_ERROR_FAVICON_UNKNOWN -} WebKitFaviconDatabaseError; - -WEBKIT_API GQuark -webkit_favicon_database_error_quark (void); - -WEBKIT_API GType -webkit_favicon_database_get_type (void); - -WEBKIT_API void -webkit_favicon_database_get_favicon (WebKitFaviconDatabase *database, - const gchar *page_uri, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); -WEBKIT_API cairo_surface_t * -webkit_favicon_database_get_favicon_finish (WebKitFaviconDatabase *database, - GAsyncResult *result, - GError **error); -WEBKIT_API gchar * -webkit_favicon_database_get_favicon_uri (WebKitFaviconDatabase *database, - const gchar *page_uri); -WEBKIT_API void -webkit_favicon_database_clear (WebKitFaviconDatabase *database); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabasePrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabasePrivate.h deleted file mode 100644 index 0a99321a1..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFaviconDatabasePrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitFaviconDatabasePrivate_h -#define WebKitFaviconDatabasePrivate_h - -#include "WebIconDatabase.h" -#include "WebKitFaviconDatabase.h" - -WebKitFaviconDatabase* webkitFaviconDatabaseCreate(WebKit::WebIconDatabase*); - -#endif // WebKitFaviconDatabasePrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp deleted file mode 100644 index 217d06961..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.cpp +++ /dev/null @@ -1,380 +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 "WebKitFileChooserRequest.h" - -#include "ImmutableArray.h" -#include "WebKitFileChooserRequestPrivate.h" -#include "WebOpenPanelParameters.h" -#include "WebOpenPanelResultListenerProxy.h" -#include <WebCore/FileSystem.h> -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -using namespace WebKit; -using namespace WebCore; - -/** - * SECTION: WebKitFileChooserRequest - * @Short_description: A request to open a file chooser - * @Title: WebKitFileChooserRequest - * @See_also: #WebKitWebView - * - * Whenever the user interacts with an <input type='file' /> - * HTML element, WebKit will need to show a dialog to choose one or - * more files to be uploaded to the server along with the rest of the - * form data. For that to happen in a general way, instead of just - * opening a #GtkFileChooserDialog (which might be not desirable in - * some cases, which could prefer to use their own file chooser - * dialog), WebKit will fire the #WebKitWebView::run-file-chooser - * signal with a #WebKitFileChooserRequest object, which will allow - * the client application to specify the files to be selected, to - * inspect the details of the request (e.g. if multiple selection - * should be allowed) and to cancel the request, in case nothing was - * selected. - * - * In case the client application does not wish to handle this signal, - * WebKit will provide a default handler which will asynchronously run - * a regular #GtkFileChooserDialog for the user to interact with. - */ - -struct _WebKitFileChooserRequestPrivate { - RefPtr<WebOpenPanelParameters> parameters; - RefPtr<WebOpenPanelResultListenerProxy> listener; - GRefPtr<GtkFileFilter> filter; - GRefPtr<GPtrArray> mimeTypes; - GRefPtr<GPtrArray> selectedFiles; - bool handledRequest; -}; - -WEBKIT_DEFINE_TYPE(WebKitFileChooserRequest, webkit_file_chooser_request, G_TYPE_OBJECT) - -enum { - PROP_0, - PROP_FILTER, - PROP_MIME_TYPES, - PROP_SELECT_MULTIPLE, - PROP_SELECTED_FILES, -}; - -static void webkitFileChooserRequestDispose(GObject* object) -{ - WebKitFileChooserRequest* request = WEBKIT_FILE_CHOOSER_REQUEST(object); - - // Make sure the request is always handled before finalizing. - if (!request->priv->handledRequest) - webkit_file_chooser_request_cancel(request); - - G_OBJECT_CLASS(webkit_file_chooser_request_parent_class)->dispose(object); -} - -static void webkitFileChooserRequestGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitFileChooserRequest* request = WEBKIT_FILE_CHOOSER_REQUEST(object); - switch (propId) { - case PROP_FILTER: - g_value_set_object(value, webkit_file_chooser_request_get_mime_types_filter(request)); - break; - case PROP_MIME_TYPES: - g_value_set_boxed(value, webkit_file_chooser_request_get_mime_types(request)); - break; - case PROP_SELECT_MULTIPLE: - g_value_set_boolean(value, webkit_file_chooser_request_get_select_multiple(request)); - break; - case PROP_SELECTED_FILES: - g_value_set_boxed(value, webkit_file_chooser_request_get_selected_files(request)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - break; - } -} - -static void webkit_file_chooser_request_class_init(WebKitFileChooserRequestClass* requestClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(requestClass); - objectClass->dispose = webkitFileChooserRequestDispose; - objectClass->get_property = webkitFileChooserRequestGetProperty; - - /** - * WebKitFileChooserRequest:filter: - * - * The filter currently associated with the request. See - * webkit_file_chooser_request_get_mime_types_filter() for more - * details. - */ - g_object_class_install_property(objectClass, - PROP_FILTER, - g_param_spec_object("filter", - _("MIME types filter"), - _("The filter currently associated with the request"), - GTK_TYPE_FILE_FILTER, - WEBKIT_PARAM_READABLE)); - /** - * WebKitFileChooserRequest:mime-types: - * - * A %NULL-terminated array of strings containing the list of MIME - * types the file chooser dialog should handle. See - * webkit_file_chooser_request_get_mime_types() for more details. - */ - g_object_class_install_property(objectClass, - PROP_MIME_TYPES, - g_param_spec_boxed("mime-types", - _("MIME types"), - _("The list of MIME types associated with the request"), - G_TYPE_STRV, - WEBKIT_PARAM_READABLE)); - /** - * WebKitFileChooserRequest:select-multiple: - * - * Whether the file chooser should allow selecting multiple - * files. See - * webkit_file_chooser_request_get_select_multiple() for - * more details. - */ - g_object_class_install_property(objectClass, - PROP_SELECT_MULTIPLE, - g_param_spec_boolean("select-multiple", - _("Select multiple files"), - _("Whether the file chooser should allow selecting multiple files"), - FALSE, - WEBKIT_PARAM_READABLE)); - /** - * WebKitFileChooserRequest:selected-files: - * - * A %NULL-terminated array of strings containing the list of - * selected files associated to the current request. See - * webkit_file_chooser_request_get_selected_files() for more details. - */ - g_object_class_install_property(objectClass, - PROP_SELECTED_FILES, - g_param_spec_boxed("selected-files", - _("Selected files"), - _("The list of selected files associated with the request"), - G_TYPE_STRV, - WEBKIT_PARAM_READABLE)); -} - -WebKitFileChooserRequest* webkitFileChooserRequestCreate(WebOpenPanelParameters* parameters, WebOpenPanelResultListenerProxy* listener) -{ - WebKitFileChooserRequest* request = WEBKIT_FILE_CHOOSER_REQUEST(g_object_new(WEBKIT_TYPE_FILE_CHOOSER_REQUEST, NULL)); - request->priv->parameters = parameters; - request->priv->listener = listener; - return request; -} - -/** - * webkit_file_chooser_request_get_mime_types: - * @request: a #WebKitFileChooserRequest - * - * Get the list of MIME types the file chooser dialog should handle, - * in the format specified in RFC 2046 for "media types". Its contents - * depend on the value of the 'accept' attribute for HTML input - * elements. This function should normally be called before presenting - * the file chooser dialog to the user, to decide whether to allow the - * user to select multiple files at once or only one. - * - * Returns: (array zero-terminated=1) (transfer none): a - * %NULL-terminated array of strings if a list of accepted MIME types - * is defined or %NULL otherwise, meaning that any MIME type should be - * accepted. This array and its contents are owned by WebKitGTK+ and - * should not be modified or freed. - */ -const gchar* const* webkit_file_chooser_request_get_mime_types(WebKitFileChooserRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_FILE_CHOOSER_REQUEST(request), 0); - if (request->priv->mimeTypes) - return reinterpret_cast<gchar**>(request->priv->mimeTypes->pdata); - - RefPtr<ImmutableArray> mimeTypes = request->priv->parameters->acceptMIMETypes(); - size_t numOfMimeTypes = mimeTypes->size(); - if (!numOfMimeTypes) - return 0; - - request->priv->mimeTypes = adoptGRef(g_ptr_array_new_with_free_func(g_free)); - for (size_t i = 0; i < numOfMimeTypes; ++i) { - WebString* webMimeType = static_cast<WebString*>(mimeTypes->at(i)); - String mimeTypeString = webMimeType->string(); - if (mimeTypeString.isEmpty()) - continue; - g_ptr_array_add(request->priv->mimeTypes.get(), g_strdup(mimeTypeString.utf8().data())); - } - g_ptr_array_add(request->priv->mimeTypes.get(), 0); - - return reinterpret_cast<gchar**>(request->priv->mimeTypes->pdata); -} - -/** - * webkit_file_chooser_request_get_mime_types_filter: - * @request: a #WebKitFileChooserRequest - * - * Get the filter currently associated with the request, ready to be - * used by #GtkFileChooser. This function should normally be called - * before presenting the file chooser dialog to the user, to decide - * whether to apply a filter so the user would not be allowed to - * select files with other MIME types. - * - * See webkit_file_chooser_request_get_mime_types() if you are - * interested in getting the list of accepted MIME types. - * - * Returns: (transfer none): a #GtkFileFilter if a list of accepted - * MIME types is defined or %NULL otherwise. The returned object is - * owned by WebKitGTK+ should not be modified or freed. - */ -GtkFileFilter* webkit_file_chooser_request_get_mime_types_filter(WebKitFileChooserRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_FILE_CHOOSER_REQUEST(request), 0); - if (request->priv->filter) - return request->priv->filter.get(); - - RefPtr<ImmutableArray> mimeTypes = request->priv->parameters->acceptMIMETypes(); - size_t numOfMimeTypes = mimeTypes->size(); - if (!numOfMimeTypes) - return 0; - - // Do not use adoptGRef here, since we want to sink the floating - // reference for the new instance of GtkFileFilter, so we make - // sure we keep the ownership during the lifetime of the request. - request->priv->filter = gtk_file_filter_new(); - for (size_t i = 0; i < numOfMimeTypes; ++i) { - WebString* webMimeType = static_cast<WebString*>(mimeTypes->at(i)); - String mimeTypeString = webMimeType->string(); - if (mimeTypeString.isEmpty()) - continue; - gtk_file_filter_add_mime_type(request->priv->filter.get(), mimeTypeString.utf8().data()); - } - - return request->priv->filter.get(); -} - -/** - * webkit_file_chooser_request_get_select_multiple: - * @request: a #WebKitFileChooserRequest - * - * Determine whether the file chooser associated to this - * #WebKitFileChooserRequest should allow selecting multiple files, - * which depends on the HTML input element having a 'multiple' - * attribute defined. - * - * Returns: %TRUE if the file chooser should allow selecting multiple files or %FALSE otherwise. - */ -gboolean webkit_file_chooser_request_get_select_multiple(WebKitFileChooserRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_FILE_CHOOSER_REQUEST(request), FALSE); - return request->priv->parameters->allowMultipleFiles(); -} - -/** - * webkit_file_chooser_request_select_files: - * @request: a #WebKitFileChooserRequest - * @files: (array zero-terminated=1) (transfer none): a - * %NULL-terminated array of strings, containing paths to local files. - * - * Ask WebKit to select local files for upload and complete the - * request. - */ -void webkit_file_chooser_request_select_files(WebKitFileChooserRequest* request, const gchar* const* files) -{ - g_return_if_fail(WEBKIT_IS_FILE_CHOOSER_REQUEST(request)); - g_return_if_fail(files); - - GRefPtr<GPtrArray> selectedFiles = adoptGRef(g_ptr_array_new_with_free_func(g_free)); - Vector<RefPtr<APIObject> > choosenFiles; - for (int i = 0; files[i]; i++) { - GRefPtr<GFile> filename = adoptGRef(g_file_new_for_path(files[i])); - - // Make sure the file path is presented as an URI (escaped - // string, with the 'file://' prefix) to WebCore otherwise the - // FileChooser won't actually choose it. - GOwnPtr<char> uri(g_file_get_uri(filename.get())); - choosenFiles.append(WebURL::create(String::fromUTF8(uri.get()))); - - // Do not use the URI here because this won't reach WebCore. - g_ptr_array_add(selectedFiles.get(), g_strdup(files[i])); - } - g_ptr_array_add(selectedFiles.get(), 0); - - // Select the files in WebCore and update local private attributes. - request->priv->listener->chooseFiles(ImmutableArray::adopt(choosenFiles).get()); - request->priv->selectedFiles = selectedFiles; - request->priv->handledRequest = true; -} - -/** - * webkit_file_chooser_request_get_selected_files: - * @request: a #WebKitFileChooserRequest - * - * Get the list of selected files currently associated to the - * request. Initially, the return value of this method contains any - * files selected in previous file chooser requests for this HTML - * input element. Once webkit_file_chooser_request_select_files, the - * value will reflect whatever files are given. - * - * This function should normally be called only before presenting the - * file chooser dialog to the user, to decide whether to perform some - * extra action, like pre-selecting the files from a previous request. - * - * Returns: (array zero-terminated=1) (transfer none): a - * %NULL-terminated array of strings if there are selected files - * associated with the request or %NULL otherwise. This array and its - * contents are owned by WebKitGTK+ and should not be modified or - * freed. - */ -const gchar* const* webkit_file_chooser_request_get_selected_files(WebKitFileChooserRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_FILE_CHOOSER_REQUEST(request), 0); - if (request->priv->selectedFiles) - return reinterpret_cast<gchar**>(request->priv->selectedFiles->pdata); - - 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) { - WebString* webFileName = static_cast<WebString*>(selectedFileNames->at(i)); - if (webFileName->isEmpty()) - continue; - 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); - - return reinterpret_cast<gchar**>(request->priv->selectedFiles->pdata); -} - -/** - * webkit_file_chooser_request_cancel: - * @request: a #WebKitFileChooserRequest - * - * Ask WebKit to cancel the request. It's important to do this in case - * no selection has been made in the client, otherwise the request - * won't be properly completed and the browser will keep the request - * pending forever, which might cause the browser to hang. - */ -void webkit_file_chooser_request_cancel(WebKitFileChooserRequest* request) -{ - g_return_if_fail(WEBKIT_IS_FILE_CHOOSER_REQUEST(request)); - request->priv->listener->cancel(); - request->priv->handledRequest = true; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h deleted file mode 100644 index 2b0069024..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequest.h +++ /dev/null @@ -1,83 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitFileChooserRequest_h -#define WebKitFileChooserRequest_h - -#include <gtk/gtk.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_FILE_CHOOSER_REQUEST (webkit_file_chooser_request_get_type()) -#define WEBKIT_FILE_CHOOSER_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_FILE_CHOOSER_REQUEST, WebKitFileChooserRequest)) -#define WEBKIT_FILE_CHOOSER_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_FILE_CHOOSER_REQUEST, WebKitFileChooserRequestClass)) -#define WEBKIT_IS_FILE_CHOOSER_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_FILE_CHOOSER_REQUEST)) -#define WEBKIT_IS_FILE_CHOOSER_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_FILE_CHOOSER_REQUEST)) -#define WEBKIT_FILE_CHOOSER_REQUEST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_FILE_CHOOSER_REQUEST, WebKitFileChooserRequestClass)) - -typedef struct _WebKitFileChooserRequest WebKitFileChooserRequest; -typedef struct _WebKitFileChooserRequestClass WebKitFileChooserRequestClass; -typedef struct _WebKitFileChooserRequestPrivate WebKitFileChooserRequestPrivate; - -struct _WebKitFileChooserRequest { - GObject parent; - - /*< private >*/ - WebKitFileChooserRequestPrivate *priv; -}; - -struct _WebKitFileChooserRequestClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_file_chooser_request_get_type (void); - -WEBKIT_API const gchar * const * -webkit_file_chooser_request_get_mime_types (WebKitFileChooserRequest *request); - -WEBKIT_API GtkFileFilter * -webkit_file_chooser_request_get_mime_types_filter (WebKitFileChooserRequest *request); - -WEBKIT_API gboolean -webkit_file_chooser_request_get_select_multiple (WebKitFileChooserRequest *request); - -WEBKIT_API void -webkit_file_chooser_request_select_files (WebKitFileChooserRequest *request, - const gchar * const *files); - -WEBKIT_API const gchar * const * -webkit_file_chooser_request_get_selected_files (WebKitFileChooserRequest *request); - -WEBKIT_API void -webkit_file_chooser_request_cancel (WebKitFileChooserRequest *request); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequestPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequestPrivate.h deleted file mode 100644 index 45d133e5b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFileChooserRequestPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitFileChooserRequestPrivate_h -#define WebKitFileChooserRequestPrivate_h - -#include "WebKitFileChooserRequest.h" -#include "WebKitPrivate.h" - -WebKitFileChooserRequest* webkitFileChooserRequestCreate(WebKit::WebOpenPanelParameters*, WebKit::WebOpenPanelResultListenerProxy*); - -#endif // WebKitFileChooserRequestPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp deleted file mode 100644 index 516c58237..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.cpp +++ /dev/null @@ -1,485 +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 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 "WebKitFindController.h" - -#include "WebKitEnumTypes.h" -#include "WebKitPrivate.h" -#include "WebKitWebView.h" -#include "WebKitWebViewBasePrivate.h" -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - COUNTED_MATCHES, - - LAST_SIGNAL -}; - -enum { - PROP_0, - - PROP_TEXT, - PROP_OPTIONS, - PROP_MAX_MATCH_COUNT, - PROP_WEB_VIEW -}; - -typedef enum { - FindOperation, - FindNextPrevOperation, - CountOperation -} WebKitFindControllerOperation; - -struct _WebKitFindControllerPrivate { - CString searchText; - uint32_t findOptions; - unsigned maxMatchCount; - WebKitWebView* webView; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitFindController, webkit_find_controller, G_TYPE_OBJECT) - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE, FindOptionsCaseInsensitive); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_FIND_OPTIONS_AT_WORD_STARTS, FindOptionsAtWordStarts); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START, FindOptionsTreatMedialCapitalAsWordStart); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_FIND_OPTIONS_BACKWARDS, FindOptionsBackwards); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_FIND_OPTIONS_WRAP_AROUND, FindOptionsWrapAround); - -static void didFindString(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo) -{ - g_signal_emit(WEBKIT_FIND_CONTROLLER(clientInfo), signals[FOUND_TEXT], 0, matchCount); -} - -static void didFailToFindString(WKPageRef page, WKStringRef string, const void* clientInfo) -{ - g_signal_emit(WEBKIT_FIND_CONTROLLER(clientInfo), signals[FAILED_TO_FIND_TEXT], 0); -} - -static void didCountStringMatches(WKPageRef page, WKStringRef string, unsigned matchCount, const void* clientInfo) -{ - g_signal_emit(WEBKIT_FIND_CONTROLLER(clientInfo), signals[COUNTED_MATCHES], 0, matchCount); -} - -static inline WebPageProxy* getPage(WebKitFindController* findController) -{ - return webkitWebViewBaseGetPage(reinterpret_cast<WebKitWebViewBase*>(findController->priv->webView)); -} - -static void webkitFindControllerConstructed(GObject* object) -{ - WebKitFindController* findController = WEBKIT_FIND_CONTROLLER(object); - WKPageFindClient wkFindClient = { - kWKPageFindClientCurrentVersion, - findController, // clientInfo - didFindString, - didFailToFindString, - didCountStringMatches - }; - - WKPageSetPageFindClient(toAPI(getPage(findController)), &wkFindClient); -} - -static void webkitFindControllerGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitFindController* findController = WEBKIT_FIND_CONTROLLER(object); - - switch (propId) { - case PROP_TEXT: - g_value_set_string(value, webkit_find_controller_get_search_text(findController)); - break; - case PROP_OPTIONS: - g_value_set_uint(value, webkit_find_controller_get_options(findController)); - break; - case PROP_MAX_MATCH_COUNT: - g_value_set_uint(value, webkit_find_controller_get_max_match_count(findController)); - break; - case PROP_WEB_VIEW: - g_value_set_object(value, webkit_find_controller_get_web_view(findController)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkitFindControllerSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) -{ - WebKitFindController* findController = WEBKIT_FIND_CONTROLLER(object); - - switch (propId) { - case PROP_WEB_VIEW: - findController->priv->webView = WEBKIT_WEB_VIEW(g_value_get_object(value)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_find_controller_class_init(WebKitFindControllerClass* findClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(findClass); - gObjectClass->constructed = webkitFindControllerConstructed; - gObjectClass->get_property = webkitFindControllerGetProperty; - gObjectClass->set_property = webkitFindControllerSetProperty; - - /** - * WebKitFindController:text: - * - * The current search text for this #WebKitFindController. - */ - g_object_class_install_property(gObjectClass, - PROP_TEXT, - g_param_spec_string("text", - _("Search text"), - _("Text to search for in the view"), - 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitFindController:options: - * - * The options to be used in the search operation. - */ - g_object_class_install_property(gObjectClass, - PROP_OPTIONS, - g_param_spec_flags("options", - _("Search Options"), - _("Search options to be used in the search operation"), - WEBKIT_TYPE_FIND_OPTIONS, - WEBKIT_FIND_OPTIONS_NONE, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitFindController:max-match-count: - * - * The maximum number of matches to report for a given search. - */ - g_object_class_install_property(gObjectClass, - PROP_MAX_MATCH_COUNT, - g_param_spec_uint("max-match-count", - _("Maximum matches count"), - _("The maximum number of matches in a given text to report"), - 0, G_MAXUINT, 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitFindController:web-view: - * - * The #WebKitWebView this controller is associated to. - */ - g_object_class_install_property(gObjectClass, - PROP_WEB_VIEW, - g_param_spec_object("web-view", - _("WebView"), - _("The WebView associated with this find controller"), - WEBKIT_TYPE_WEB_VIEW, - static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); - - /** - * WebKitFindController::found-text: - * @find_controller: the #WebKitFindController - * @match_count: the number of matches found of the search text - * - * This signal is emitted when a given text is found in the web - * page text. It will be issued if the text is found - * asynchronously after a call to webkit_find_controller_search(), - * webkit_find_controller_search_next() or - * webkit_find_controller_search_previous(). - */ - signals[FOUND_TEXT] = - g_signal_new("found-text", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__UINT, - G_TYPE_NONE, 1, G_TYPE_UINT); - - /** - * WebKitFindController::failed-to-find-text: - * @find_controller: the #WebKitFindController - * - * This signal is emitted when a search operation does not find - * any result for the given text. It will be issued if the text - * is not found asynchronously after a call to - * webkit_find_controller_search(), webkit_find_controller_search_next() - * or webkit_find_controller_search_previous(). - */ - signals[FAILED_TO_FIND_TEXT] = - g_signal_new("failed-to-find-text", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitFindController::counted-matches: - * @find_controller: the #WebKitFindController - * @match_count: the number of matches of the search text - * - * This signal is emitted when the #WebKitFindController has - * counted the number of matches for a given text after a call - * to webkit_find_controller_count_matches(). - */ - signals[COUNTED_MATCHES] = - g_signal_new("counted-matches", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__UINT, - G_TYPE_NONE, 1, G_TYPE_UINT); -} - -/** - * webkit_find_controller_get_search_text: - * @find_controller: the #WebKitFindController - * - * Gets the text that @find_controller is currently searching - * for. This text is passed to either - * webkit_find_controller_search() or - * webkit_find_controller_count_matches(). - * - * Returns: the text to look for in the #WebKitWebView. - */ -const char* webkit_find_controller_get_search_text(WebKitFindController* findController) -{ - g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), 0); - - return findController->priv->searchText.data(); -} - -/** - * webkit_find_controller_get_options: - * @find_controller: the #WebKitFindController - * - * Gets a bitmask containing the #WebKitFindOptions associated with - * the current search. - * - * Returns: a bitmask containing the #WebKitFindOptions associated - * with the current search. - */ -guint32 webkit_find_controller_get_options(WebKitFindController* findController) -{ - g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), WEBKIT_FIND_OPTIONS_NONE); - - return findController->priv->findOptions; -} - -/** - * webkit_find_controller_get_max_match_count: - * @find_controller: the #WebKitFindController - * - * Gets the maximum number of matches to report during a text - * lookup. This number is passed as the last argument of - * webkit_find_controller_search() or - * webkit_find_controller_count_matches(). - * - * Returns: the maximum number of matches to report. - */ -guint webkit_find_controller_get_max_match_count(WebKitFindController* findController) -{ - g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), 0); - - return findController->priv->maxMatchCount; -} - -/** - * webkit_find_controller_get_web_view: - * @find_controller: the #WebKitFindController - * - * Gets the #WebKitWebView this find controller is associated to. Do - * not unref the returned instance as it belongs to the - * #WebKitFindController. - * - * Returns: (transfer none): the #WebKitWebView. - */ -WebKitWebView* webkit_find_controller_get_web_view(WebKitFindController* findController) -{ - g_return_val_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController), 0); - - return findController->priv->webView; -} - -static void webKitFindControllerPerform(WebKitFindController* findController, WebKitFindControllerOperation operation) -{ - WebKitFindControllerPrivate* priv = findController->priv; - if (operation == CountOperation) { - getPage(findController)->countStringMatches(String::fromUTF8(priv->searchText.data()), - static_cast<WebKit::FindOptions>(priv->findOptions), priv->maxMatchCount); - return; - } - - uint32_t findOptions = priv->findOptions; - if (operation == FindOperation) - // Unconditionally highlight text matches when the search - // starts. WK1 API was forcing clients to enable/disable - // highlighting. Since most of them (all?) where using that - // feature we decided to simplify the WK2 API and - // unconditionally show highlights. Both search_next() and - // search_prev() should not enable highlighting to avoid an - // extra unmarkAllTextMatches() + markAllTextMatches() - findOptions |= FindOptionsShowHighlight; - - getPage(findController)->findString(String::fromUTF8(priv->searchText.data()), static_cast<WebKit::FindOptions>(findOptions), - priv->maxMatchCount); -} - -static inline void webKitFindControllerSetSearchData(WebKitFindController* findController, const gchar* searchText, guint32 findOptions, guint maxMatchCount) -{ - findController->priv->searchText = searchText; - findController->priv->findOptions = findOptions; - findController->priv->maxMatchCount = maxMatchCount; -} - -/** - * webkit_find_controller_search: - * @find_controller: the #WebKitFindController - * @search_text: the text to look for - * @find_options: a bitmask with the #WebKitFindOptions used in the search - * @max_match_count: the maximum number of matches allowed in the search - * - * Looks for @search_text in the #WebKitWebView associated with - * @find_controller since the beginning of the document highlighting - * up to @max_match_count matches. The outcome of the search will be - * asynchronously provided by the #WebKitFindController::found-text - * and #WebKitFindController::failed-to-find-text signals. - * - * To look for the next or previous occurrences of the same text - * with the same find options use webkit_find_controller_search_next() - * and/or webkit_find_controller_search_previous(). The - * #WebKitFindController will use the same text and options for the - * following searches unless they are modified by another call to this - * method. - * - * Note that if the number of matches is higher than @max_match_count - * then #WebKitFindController::found-text will report %G_MAXUINT matches - * instead of the actual number. - * - * Callers should call webkit_find_controller_search_finish() to - * finish the current search operation. - */ -void webkit_find_controller_search(WebKitFindController* findController, const gchar* searchText, guint findOptions, guint maxMatchCount) -{ - g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController)); - g_return_if_fail(searchText); - - webKitFindControllerSetSearchData(findController, searchText, findOptions, maxMatchCount); - webKitFindControllerPerform(findController, FindOperation); -} - -/** - * webkit_find_controller_search_next: - * @find_controller: the #WebKitFindController - * - * Looks for the next occurrence of the search text. - * - * Calling this method before webkit_find_controller_search() or - * webkit_find_controller_count_matches() is a programming error. - */ -void webkit_find_controller_search_next(WebKitFindController* findController) -{ - g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController)); - - findController->priv->findOptions &= ~WEBKIT_FIND_OPTIONS_BACKWARDS; - findController->priv->findOptions &= ~FindOptionsShowHighlight; - webKitFindControllerPerform(findController, FindNextPrevOperation); -} - -/** - * webkit_find_controller_search_previous: - * @find_controller: the #WebKitFindController - * - * Looks for the previous occurrence of the search text. - * - * Calling this method before webkit_find_controller_search() or - * webkit_find_controller_count_matches() is a programming error. - */ -void webkit_find_controller_search_previous(WebKitFindController* findController) -{ - g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController)); - - findController->priv->findOptions |= WEBKIT_FIND_OPTIONS_BACKWARDS; - findController->priv->findOptions &= ~FindOptionsShowHighlight; - webKitFindControllerPerform(findController, FindNextPrevOperation); -} - -/** - * webkit_find_controller_count_matches: - * @find_controller: the #WebKitFindController - * @search_text: the text to look for - * @find_options: a bitmask with the #WebKitFindOptions used in the search - * @max_match_count: the maximum number of matches allowed in the search - * - * Counts the number of matches for @search_text found in the - * #WebKitWebView with the provided @find_options. The number of - * matches will be provided by the - * #WebKitFindController::counted-matches signal. - */ -void webkit_find_controller_count_matches(WebKitFindController* findController, const gchar* searchText, guint32 findOptions, guint maxMatchCount) -{ - g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController)); - g_return_if_fail(searchText); - - webKitFindControllerSetSearchData(findController, searchText, findOptions, maxMatchCount); - webKitFindControllerPerform(findController, CountOperation); -} - -/** - * webkit_find_controller_search_finish: - * @find_controller: a #WebKitFindController - * - * Finishes a find operation started by - * webkit_find_controller_search(). It will basically unhighlight - * every text match found. - * - * This method will be typically called when the search UI is - * closed/hidden by the client application. - */ -void webkit_find_controller_search_finish(WebKitFindController* findController) -{ - g_return_if_fail(WEBKIT_IS_FIND_CONTROLLER(findController)); - - getPage(findController)->hideFindUI(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h deleted file mode 100644 index 7bad1d051..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFindController.h +++ /dev/null @@ -1,122 +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 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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitFindController_h -#define WebKitFindController_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitForwardDeclarations.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_FIND_CONTROLLER (webkit_find_controller_get_type()) -#define WEBKIT_FIND_CONTROLLER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_FIND_CONTROLLER, WebKitFindController)) -#define WEBKIT_FIND_CONTROLLER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_FIND_CONTROLLER, WebKitFindControllerClass)) -#define WEBKIT_IS_FIND_CONTROLLER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_FIND_CONTROLLER)) -#define WEBKIT_IS_FIND_CONTROLLER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_FIND_CONTROLLER)) -#define WEBKIT_FIND_CONTROLLER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_FIND_CONTROLLER, WebKitFindControllerClass)) - -typedef struct _WebKitFindControllerPrivate WebKitFindControllerPrivate; -typedef struct _WebKitFindControllerClass WebKitFindControllerClass; - -/** - * WebKitFindOptions: - * @WEBKIT_FIND_OPTIONS_NONE: no search flags, this means a case - * sensitive, no wrap, forward only search. - * @WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE: case insensitive search. - * @WEBKIT_FIND_OPTIONS_AT_WORD_STARTS: search text only at the - * begining of the words. - * @WEBKIT_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START: treat - * capital letters in the middle of words as word start. - * @WEBKIT_FIND_OPTIONS_BACKWARDS: search backwards. - * @WEBKIT_FIND_OPTIONS_WRAP_AROUND: if not present search will stop - * at the end of the document. - * - * Enum values used to specify search options. - */ -typedef enum { - WEBKIT_FIND_OPTIONS_NONE, - - WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE = 1 << 0, - WEBKIT_FIND_OPTIONS_AT_WORD_STARTS = 1 << 1, - WEBKIT_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START = 1 << 2, - WEBKIT_FIND_OPTIONS_BACKWARDS = 1 << 3, - WEBKIT_FIND_OPTIONS_WRAP_AROUND = 1 << 4, -} WebKitFindOptions; - -struct _WebKitFindController { - GObject parent; - - /*< private >*/ - WebKitFindControllerPrivate *priv; -}; - -struct _WebKitFindControllerClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_find_controller_get_type (void); - -WEBKIT_API void -webkit_find_controller_search (WebKitFindController *find_controller, - const gchar *search_text, - guint32 find_options, - guint max_match_count); - -WEBKIT_API void -webkit_find_controller_search_finish (WebKitFindController *find_controller); - -WEBKIT_API void -webkit_find_controller_search_next (WebKitFindController *find_controller); - -WEBKIT_API void -webkit_find_controller_search_previous (WebKitFindController *find_controller); - -WEBKIT_API void -webkit_find_controller_count_matches (WebKitFindController *find_controller, - const gchar *search_text, - guint32 find_options, - guint max_match_count); - -WEBKIT_API const gchar * -webkit_find_controller_get_search_text (WebKitFindController *find_controller); - -WEBKIT_API guint32 -webkit_find_controller_get_options (WebKitFindController *find_controller); - -WEBKIT_API guint -webkit_find_controller_get_max_match_count (WebKitFindController *find_controller); - -WEBKIT_API WebKitWebView * -webkit_find_controller_get_web_view (WebKitFindController *find_controller); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFormClient.cpp deleted file mode 100644 index 75978cf13..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormClient.cpp +++ /dev/null @@ -1,46 +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 "WebKitFormClient.h" - -#include "WebKitFormSubmissionRequestPrivate.h" -#include "WebKitPrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" -#include <wtf/gobject/GRefPtr.h> - -using namespace WebKit; - -static void willSubmitForm(WKPageRef page, WKFrameRef frame, WKFrameRef sourceFrame, WKDictionaryRef values, WKTypeRef userData, WKFormSubmissionListenerRef listener, const void* clientInfo) -{ - GRefPtr<WebKitFormSubmissionRequest> request = adoptGRef(webkitFormSubmissionRequestCreate(toImpl(values), toImpl(listener))); - webkitWebViewSubmitFormRequest(WEBKIT_WEB_VIEW(clientInfo), request.get()); -} - -void attachFormClientToView(WebKitWebView* webView) -{ - WKPageFormClient wkFormClient = { - kWKPageFormClientCurrentVersion, - webView, // clientInfo - willSubmitForm - }; - WKPageRef wkPage = toAPI(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView))); - WKPageSetPageFormClient(wkPage, &wkFormClient); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFormClient.h deleted file mode 100644 index a37022731..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormClient.h +++ /dev/null @@ -1,27 +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. - */ - -#ifndef WebKitFormClient_h -#define WebKitFormClient_h - -#include "WebKitWebView.h" - -void attachFormClientToView(WebKitWebView*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp deleted file mode 100644 index 92ee4586c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.cpp +++ /dev/null @@ -1,126 +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 "WebKitFormSubmissionRequest.h" - -#include "ImmutableDictionary.h" -#include "WebFormSubmissionListenerProxy.h" -#include "WebKitFormSubmissionRequestPrivate.h" -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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; - GRefPtr<GHashTable> values; - bool handledRequest; -}; - -WEBKIT_DEFINE_TYPE(WebKitFormSubmissionRequest, webkit_form_submission_request, G_TYPE_OBJECT) - -static void webkitFormSubmissionRequestDispose(GObject* object) -{ - WebKitFormSubmissionRequest* request = WEBKIT_FORM_SUBMISSION_REQUEST(object); - - // Make sure the request is always handled before finalizing. - if (!request->priv->handledRequest) - webkit_form_submission_request_submit(request); - - G_OBJECT_CLASS(webkit_form_submission_request_parent_class)->dispose(object); -} - -static void webkit_form_submission_request_class_init(WebKitFormSubmissionRequestClass* requestClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(requestClass); - objectClass->dispose = webkitFormSubmissionRequestDispose; -} - -WebKitFormSubmissionRequest* webkitFormSubmissionRequestCreate(ImmutableDictionary* values, WebFormSubmissionListenerProxy* listener) -{ - WebKitFormSubmissionRequest* request = WEBKIT_FORM_SUBMISSION_REQUEST(g_object_new(WEBKIT_TYPE_FORM_SUBMISSION_REQUEST, NULL)); - request->priv->webValues = values; - request->priv->listener = listener; - return request; -} - -/** - * webkit_form_submission_request_get_text_fields: - * @request: a #WebKitFormSubmissionRequest - * - * Get a #GHashTable with the values of the text fields contained in the form - * associated to @request. - * - * Returns: (transfer none): a #GHashTable with the form text fields, or %NULL if the - * form doesn't contain text fields. - */ -GHashTable* webkit_form_submission_request_get_text_fields(WebKitFormSubmissionRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_FORM_SUBMISSION_REQUEST(request), 0); - - if (request->priv->values) - return request->priv->values.get(); - - if (!request->priv->webValues->size()) - return 0; - - request->priv->values = adoptGRef(g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free)); - - const ImmutableDictionary::MapType& map = request->priv->webValues->map(); - ImmutableDictionary::MapType::const_iterator end = map.end(); - for (ImmutableDictionary::MapType::const_iterator it = map.begin(); it != end; ++it) { - WebString* value = static_cast<WebString*>(it->value.get()); - g_hash_table_insert(request->priv->values.get(), g_strdup(it->key.utf8().data()), g_strdup(value->string().utf8().data())); - } - - request->priv->webValues = 0; - - return request->priv->values.get(); -} - -/** - * webkit_form_submission_request_submit: - * @request: a #WebKitFormSubmissionRequest - * - * Continue the form submission. - */ -void webkit_form_submission_request_submit(WebKitFormSubmissionRequest* request) -{ - g_return_if_fail(WEBKIT_IS_FORM_SUBMISSION_REQUEST(request)); - - request->priv->listener->continueSubmission(); - request->priv->handledRequest = true; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h deleted file mode 100644 index e27779b34..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequest.h +++ /dev/null @@ -1,70 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitFormSubmissionRequest_h -#define WebKitFormSubmissionRequest_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_FORM_SUBMISSION_REQUEST (webkit_form_submission_request_get_type()) -#define WEBKIT_FORM_SUBMISSION_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_FORM_SUBMISSION_REQUEST, WebKitFormSubmissionRequest)) -#define WEBKIT_IS_FORM_SUBMISSION_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_FORM_SUBMISSION_REQUEST)) -#define WEBKIT_FORM_SUBMISSION_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_FORM_SUBMISSION_REQUEST, WebKitFormSubmissionRequestClass)) -#define WEBKIT_IS_FORM_SUBMISSION_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_FORM_SUBMISSION_REQUEST)) -#define WEBKIT_FORM_SUBMISSION_REQUEST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_FORM_SUBMISSION_REQUEST, WebKitFormSubmissionRequestClass)) - -typedef struct _WebKitFormSubmissionRequest WebKitFormSubmissionRequest; -typedef struct _WebKitFormSubmissionRequestClass WebKitFormSubmissionRequestClass; -typedef struct _WebKitFormSubmissionRequestPrivate WebKitFormSubmissionRequestPrivate; - -struct _WebKitFormSubmissionRequest { - GObject parent; - - /*< private >*/ - WebKitFormSubmissionRequestPrivate *priv; -}; - -struct _WebKitFormSubmissionRequestClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_form_submission_request_get_type (void); - -WEBKIT_API GHashTable * -webkit_form_submission_request_get_text_fields (WebKitFormSubmissionRequest *request); - -WEBKIT_API void -webkit_form_submission_request_submit (WebKitFormSubmissionRequest *request); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequestPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequestPrivate.h deleted file mode 100644 index 9fe4751d2..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFormSubmissionRequestPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitFormSubmissionRequestPrivate_h -#define WebKitFormSubmissionRequestPrivate_h - -#include "WebKitFormSubmissionRequest.h" -#include "WebKitPrivate.h" - -WebKitFormSubmissionRequest* webkitFormSubmissionRequestCreate(WebKit::ImmutableDictionary* values, WebKit::WebFormSubmissionListenerProxy*); - -#endif // WebKitFormSubmissionRequestPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitForwardDeclarations.h b/Source/WebKit2/UIProcess/API/gtk/WebKitForwardDeclarations.h deleted file mode 100644 index a9898de48..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitForwardDeclarations.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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/WebKitFullscreenClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitFullscreenClient.cpp deleted file mode 100644 index 75b51e25d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFullscreenClient.cpp +++ /dev/null @@ -1,48 +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 "WebKitFullscreenClient.h" - -#include "WebKitPrivate.h" -#include "WebKitWebViewPrivate.h" - -using namespace WebKit; - -static bool willEnterFullScreen(const void* clientInfo) -{ - return webkitWebViewEnterFullScreen(WEBKIT_WEB_VIEW(clientInfo)); -} - -static bool willExitFullScreen(const void* clientInfo) -{ - return webkitWebViewLeaveFullScreen(WEBKIT_WEB_VIEW(clientInfo)); -} - -void attachFullScreenClientToView(WebKitWebView* webView) -{ - WKFullScreenClientGtk wkFullScreenClient = { - kWKFullScreenClientGtkCurrentVersion, - webView, // clientInfo - willEnterFullScreen, - willExitFullScreen - }; - WKViewSetFullScreenClientGtk(toAPI(WEBKIT_WEB_VIEW_BASE(webView)), &wkFullScreenClient); -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitFullscreenClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitFullscreenClient.h deleted file mode 100644 index 187c067af..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitFullscreenClient.h +++ /dev/null @@ -1,27 +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. - */ - -#ifndef WebKitFullscreenClient_h -#define WebKitFullscreenClient_h - -#include "WebKitWebView.h" - -void attachFullScreenClientToView(WebKitWebView*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.cpp deleted file mode 100644 index f780dafb2..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.cpp +++ /dev/null @@ -1,103 +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 "WebKitGeolocationPermissionRequest.h" - -#include "GeolocationPermissionRequestProxy.h" -#include "WebKitGeolocationPermissionRequestPrivate.h" -#include "WebKitPermissionRequest.h" - -using namespace WebKit; - -/** - * SECTION: WebKitGeolocationPermissionRequest - * @Short_description: A permission request for sharing user's location - * @Title: WebKitGeolocationPermissionRequest - * @See_also: #WebKitPermissionRequest, #WebKitWebView - * - * WebKitGeolocationPermissionRequest represents a request for - * permission to decide whether WebKit should provide the user's - * location to a website when requested throught the Geolocation API. - */ - -static void webkit_permission_request_interface_init(WebKitPermissionRequestIface*); - -struct _WebKitGeolocationPermissionRequestPrivate { - RefPtr<GeolocationPermissionRequestProxy> request; - bool madeDecision; -}; - -WEBKIT_DEFINE_TYPE_WITH_CODE( - WebKitGeolocationPermissionRequest, webkit_geolocation_permission_request, G_TYPE_OBJECT, - G_IMPLEMENT_INTERFACE(WEBKIT_TYPE_PERMISSION_REQUEST, webkit_permission_request_interface_init)) - -static void webkitGeolocationPermissionRequestAllow(WebKitPermissionRequest* request) -{ - ASSERT(WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(request)); - - WebKitGeolocationPermissionRequestPrivate* priv = WEBKIT_GEOLOCATION_PERMISSION_REQUEST(request)->priv; - - // Only one decision at a time. - if (priv->madeDecision) - return; - - priv->request->allow(); - priv->madeDecision = true; -} - -static void webkitGeolocationPermissionRequestDeny(WebKitPermissionRequest* request) -{ - ASSERT(WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(request)); - - WebKitGeolocationPermissionRequestPrivate* priv = WEBKIT_GEOLOCATION_PERMISSION_REQUEST(request)->priv; - - // Only one decision at a time. - if (priv->madeDecision) - return; - - priv->request->deny(); - priv->madeDecision = true; -} - -static void webkit_permission_request_interface_init(WebKitPermissionRequestIface* iface) -{ - iface->allow = webkitGeolocationPermissionRequestAllow; - iface->deny = webkitGeolocationPermissionRequestDeny; -} - -static void webkitGeolocationPermissionRequestDispose(GObject* object) -{ - // Default behaviour when no decision has been made is denying the request. - webkitGeolocationPermissionRequestDeny(WEBKIT_PERMISSION_REQUEST(object)); - G_OBJECT_CLASS(webkit_geolocation_permission_request_parent_class)->dispose(object); -} - -static void webkit_geolocation_permission_request_class_init(WebKitGeolocationPermissionRequestClass* klass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(klass); - objectClass->dispose = webkitGeolocationPermissionRequestDispose; -} - -WebKitGeolocationPermissionRequest* webkitGeolocationPermissionRequestCreate(GeolocationPermissionRequestProxy* request) -{ - WebKitGeolocationPermissionRequest* geolocationPermissionRequest = WEBKIT_GEOLOCATION_PERMISSION_REQUEST(g_object_new(WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST, NULL)); - geolocationPermissionRequest->priv->request = request; - return geolocationPermissionRequest; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h deleted file mode 100644 index 4b44af09f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequest.h +++ /dev/null @@ -1,64 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitGeolocationPermissionRequest_h -#define WebKitGeolocationPermissionRequest_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST (webkit_geolocation_permission_request_get_type()) -#define WEBKIT_GEOLOCATION_PERMISSION_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST, WebKitGeolocationPermissionRequest)) -#define WEBKIT_GEOLOCATION_PERMISSION_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST, WebKitGeolocationPermissionRequestClass)) -#define WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST)) -#define WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST)) -#define WEBKIT_GEOLOCATION_PERMISSION_REQUEST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST, WebKitGeolocationPermissionRequestClass)) - -typedef struct _WebKitGeolocationPermissionRequest WebKitGeolocationPermissionRequest; -typedef struct _WebKitGeolocationPermissionRequestClass WebKitGeolocationPermissionRequestClass; -typedef struct _WebKitGeolocationPermissionRequestPrivate WebKitGeolocationPermissionRequestPrivate; - -struct _WebKitGeolocationPermissionRequest { - GObject parent; - - /*< private >*/ - WebKitGeolocationPermissionRequestPrivate *priv; -}; - -struct _WebKitGeolocationPermissionRequestClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_geolocation_permission_request_get_type (void); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequestPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequestPrivate.h deleted file mode 100644 index dd0e95821..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationPermissionRequestPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitGeolocationPermissionRequestPrivate_h -#define WebKitGeolocationPermissionRequestPrivate_h - -#include "WebKitGeolocationPermissionRequest.h" -#include "WebKitPrivate.h" - -WebKitGeolocationPermissionRequest* webkitGeolocationPermissionRequestCreate(WebKit::GeolocationPermissionRequestProxy*); - -#endif // WebKitGeolocationPermissionRequestPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationProvider.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationProvider.cpp deleted file mode 100644 index cdeac917d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationProvider.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#include "config.h" -#include "WebKitGeolocationProvider.h" - -#include "WebGeolocationManagerProxy.h" -#include "WebGeolocationPosition.h" - -using namespace WebKit; - -#if ENABLE(GEOLOCATION) - -static inline WebKitGeolocationProvider* toGeolocationProvider(const void* clientInfo) -{ - return static_cast<WebKitGeolocationProvider*>(const_cast<void*>(clientInfo)); -} - -static void startUpdatingCallback(WKGeolocationManagerRef geolocationManager, const void* clientInfo) -{ - toGeolocationProvider(clientInfo)->startUpdating(); -} - -static void stopUpdatingCallback(WKGeolocationManagerRef geolocationManager, const void* clientInfo) -{ - toGeolocationProvider(clientInfo)->stopUpdating(); -} - -WebKitGeolocationProvider::~WebKitGeolocationProvider() -{ - m_provider.stopUpdating(); -} - -PassRefPtr<WebKitGeolocationProvider> WebKitGeolocationProvider::create(WebGeolocationManagerProxy* geolocationManager) -{ - return adoptRef(new WebKitGeolocationProvider(geolocationManager)); -} - -WebKitGeolocationProvider::WebKitGeolocationProvider(WebGeolocationManagerProxy* geolocationManager) - : m_geolocationManager(geolocationManager) - , m_provider(this) -{ - ASSERT(geolocationManager); - - WKGeolocationProvider wkGeolocationProvider = { - kWKGeolocationProviderCurrentVersion, - this, // clientInfo - startUpdatingCallback, - stopUpdatingCallback - }; - WKGeolocationManagerSetProvider(toAPI(geolocationManager), &wkGeolocationProvider); -} - -void WebKitGeolocationProvider::startUpdating() -{ - m_provider.startUpdating(); -} - -void WebKitGeolocationProvider::stopUpdating() -{ - m_provider.stopUpdating(); -} - -void WebKitGeolocationProvider::notifyPositionChanged(int timestamp, double latitude, double longitude, double altitude, double accuracy, double altitudeAccuracy) -{ - RefPtr<WebGeolocationPosition> position = WebGeolocationPosition::create(timestamp, latitude, longitude, accuracy, true, altitude, true, altitudeAccuracy, false, 0, false, 0); - m_geolocationManager->providerDidChangePosition(position.get()); -} - -void WebKitGeolocationProvider::notifyErrorOccurred(const char* message) -{ - m_geolocationManager->providerDidFailToDeterminePosition(); -} - -#endif // ENABLE(GEOLOCATION) diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationProvider.h b/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationProvider.h deleted file mode 100644 index e6be3eac2..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitGeolocationProvider.h +++ /dev/null @@ -1,56 +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. - */ - -#ifndef WebKitGeolocationProvider_h -#define WebKitGeolocationProvider_h - -#if ENABLE(GEOLOCATION) - -#include "WebKitPrivate.h" -#include <WebCore/GeolocationProviderGeoclue.h> -#include <WebCore/GeolocationProviderGeoclueClient.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> - -namespace WebKit { - -class WebKitGeolocationProvider : public RefCounted<WebKitGeolocationProvider>, public WebCore::GeolocationProviderGeoclueClient { -public: - virtual ~WebKitGeolocationProvider(); - static PassRefPtr<WebKitGeolocationProvider> create(WebGeolocationManagerProxy*); - - void startUpdating(); - void stopUpdating(); - -private: - WebKitGeolocationProvider(WebGeolocationManagerProxy*); - - // GeolocationProviderGeoclueClient interface. - virtual void notifyPositionChanged(int, double, double, double, double, double); - virtual void notifyErrorOccurred(const char*); - - RefPtr<WebGeolocationManagerProxy> m_geolocationManager; - WebCore::GeolocationProviderGeoclue m_provider; -}; - -} // namespace WebKit - -#endif // ENABLE(GEOLOCATION) - -#endif // WebKitGeolocationProvider_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp deleted file mode 100644 index 918d316c0..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.cpp +++ /dev/null @@ -1,456 +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 "WebKitHitTestResult.h" - -#include "WebHitTestResult.h" -#include "WebKitHitTestResultPrivate.h" -#include <glib/gi18n-lib.h> -#include <wtf/text/CString.h> - -using namespace WebKit; - -/** - * SECTION: WebKitHitTestResult - * @Short_description: Result of a Hit Test - * @Title: WebKitHitTestResult - * @See_also: #WebKitWebView - * - * A Hit Test is an operation to get context information about a given - * point in a #WebKitWebView. #WebKitHitTestResult represents the - * result of a Hit Test. It provides context information about what is - * at the coordinates of the Hit Test, such as if there's a link, - * an image or a media. - * - * You can get the context of the HitTestResult with - * webkit_hit_test_result_get_context() that returns a bitmask of - * #WebKitHitTestResultContext flags. You can also use - * webkit_hit_test_result_context_is_link(), webkit_hit_test_result_context_is_image() and - * webkit_hit_test_result_context_is_media() to determine whether there's - * a link, image or a media element at the coordinates of the Hit Test. - * Note that it's possible that several #WebKitHitTestResultContext flags - * are active at the same time, for example if there's a link containing an image. - * - * When the mouse is moved over a #WebKitWebView a Hit Test is performed - * for the mouse coordinates and #WebKitWebView::mouse-target-changed - * signal is emitted with a #WebKitHitTestResult. - * - */ - -enum { - PROP_0, - - PROP_CONTEXT, - PROP_LINK_URI, - PROP_LINK_TITLE, - PROP_LINK_LABEL, - PROP_IMAGE_URI, - PROP_MEDIA_URI -}; - -struct _WebKitHitTestResultPrivate { - unsigned int context; - CString linkURI; - CString linkTitle; - CString linkLabel; - CString imageURI; - CString mediaURI; -}; - -WEBKIT_DEFINE_TYPE(WebKitHitTestResult, webkit_hit_test_result, G_TYPE_OBJECT) - -static void webkitHitTestResultGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitHitTestResult* hitTestResult = WEBKIT_HIT_TEST_RESULT(object); - - switch (propId) { - case PROP_CONTEXT: - g_value_set_uint(value, webkit_hit_test_result_get_context(hitTestResult)); - break; - case PROP_LINK_URI: - g_value_set_string(value, webkit_hit_test_result_get_link_uri(hitTestResult)); - break; - case PROP_LINK_TITLE: - g_value_set_string(value, webkit_hit_test_result_get_link_title(hitTestResult)); - break; - case PROP_LINK_LABEL: - g_value_set_string(value, webkit_hit_test_result_get_link_label(hitTestResult)); - break; - case PROP_IMAGE_URI: - g_value_set_string(value, webkit_hit_test_result_get_image_uri(hitTestResult)); - break; - case PROP_MEDIA_URI: - g_value_set_string(value, webkit_hit_test_result_get_media_uri(hitTestResult)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkitHitTestResultSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) -{ - WebKitHitTestResult* hitTestResult = WEBKIT_HIT_TEST_RESULT(object); - - switch (propId) { - case PROP_CONTEXT: - hitTestResult->priv->context = g_value_get_uint(value); - break; - case PROP_LINK_URI: - hitTestResult->priv->linkURI = g_value_get_string(value); - break; - case PROP_LINK_TITLE: - hitTestResult->priv->linkTitle = g_value_get_string(value); - break; - case PROP_LINK_LABEL: - hitTestResult->priv->linkLabel = g_value_get_string(value); - break; - case PROP_IMAGE_URI: - hitTestResult->priv->imageURI = g_value_get_string(value); - break; - case PROP_MEDIA_URI: - hitTestResult->priv->mediaURI = g_value_get_string(value); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_hit_test_result_class_init(WebKitHitTestResultClass* hitTestResultClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(hitTestResultClass); - objectClass->get_property = webkitHitTestResultGetProperty; - objectClass->set_property = webkitHitTestResultSetProperty; - - GParamFlags paramFlags = static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY); - - /** - * WebKitHitTestResult:context: - * - * Bitmask of #WebKitHitTestResultContext flags representing - * the context of the #WebKitHitTestResult. - */ - g_object_class_install_property(objectClass, - PROP_CONTEXT, - g_param_spec_uint("context", - _("Context"), - _("Flags with the context of the WebKitHitTestResult"), - 0, G_MAXUINT, 0, - paramFlags)); - - /** - * WebKitHitTestResult:link-uri: - * - * The URI of the link if flag %WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK - * is present in #WebKitHitTestResult:context - */ - g_object_class_install_property(objectClass, - PROP_LINK_URI, - g_param_spec_string("link-uri", - _("Link URI"), - _("The link URI"), - 0, - paramFlags)); - /** - * WebKitHitTestResult:link-title: - * - * The title of the link if flag %WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK - * is present in #WebKitHitTestResult:context - */ - g_object_class_install_property(objectClass, - PROP_LINK_TITLE, - g_param_spec_string("link-title", - _("Link Title"), - _("The link title"), - 0, - paramFlags)); - /** - * WebKitHitTestResult:link-label: - * - * The label of the link if flag %WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK - * is present in #WebKitHitTestResult:context - */ - g_object_class_install_property(objectClass, - PROP_LINK_LABEL, - g_param_spec_string("link-label", - _("Link Label"), - _("The link label"), - 0, - paramFlags)); - /** - * WebKitHitTestResult:image-uri: - * - * The URI of the image if flag %WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE - * is present in #WebKitHitTestResult:context - */ - g_object_class_install_property(objectClass, - PROP_IMAGE_URI, - g_param_spec_string("image-uri", - _("Image URI"), - _("The image URI"), - 0, - paramFlags)); - /** - * WebKitHitTestResult:media-uri: - * - * The URI of the media if flag %WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA - * is present in #WebKitHitTestResult:context - */ - g_object_class_install_property(objectClass, - PROP_MEDIA_URI, - g_param_spec_string("media-uri", - _("Media URI"), - _("The media URI"), - 0, - paramFlags)); -} - -WebKitHitTestResult* webkitHitTestResultCreate(WebHitTestResult* hitTestResult) -{ - unsigned context = WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT; - - const String& linkURL = hitTestResult->absoluteLinkURL(); - if (!linkURL.isEmpty()) - context |= WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK; - - const String& imageURL = hitTestResult->absoluteImageURL(); - if (!imageURL.isEmpty()) - context |= WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE; - - const String& mediaURL = hitTestResult->absoluteMediaURL(); - if (!mediaURL.isEmpty()) - context |= WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA; - - 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(); - - return WEBKIT_HIT_TEST_RESULT(g_object_new(WEBKIT_TYPE_HIT_TEST_RESULT, - "context", context, - "link-uri", !linkURL.isEmpty() ? linkURL.utf8().data() : 0, - "image-uri", !imageURL.isEmpty() ? imageURL.utf8().data() : 0, - "media-uri", !mediaURL.isEmpty() ? mediaURL.utf8().data() : 0, - "link-title", !linkTitle.isEmpty() ? linkTitle.utf8().data() : 0, - "link-label", !linkLabel.isEmpty() ? linkLabel.utf8().data() : 0, - NULL)); -} - -static bool stringIsEqualToCString(const String& string, const CString& cString) -{ - return ((string.isEmpty() && cString.isNull()) || (string.utf8() == cString)); -} - -bool webkitHitTestResultCompare(WebKitHitTestResult* hitTestResult, WebHitTestResult* webHitTestResult) -{ - 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) - && stringIsEqualToCString(webHitTestResult->absoluteImageURL(), priv->imageURI) - && stringIsEqualToCString(webHitTestResult->absoluteMediaURL(), priv->mediaURI); -} - -/** - * webkit_hit_test_result_get_context: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets the value of the #WebKitHitTestResult:context property. - * - * Returns: a bitmask of #WebKitHitTestResultContext flags - */ -guint webkit_hit_test_result_get_context(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), 0); - - return hitTestResult->priv->context; -} - -/** - * webkit_hit_test_result_context_is_link: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets whether %WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK flag is present in - * #WebKitHitTestResult:context. - * - * Returns: %TRUE if there's a link element in the coordinates of the Hit Test, - * or %FALSE otherwise - */ -gboolean webkit_hit_test_result_context_is_link(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), FALSE); - - return hitTestResult->priv->context & WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK; -} - -/** - * webkit_hit_test_result_context_is_image: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets whether %WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE flag is present in - * #WebKitHitTestResult:context. - * - * Returns: %TRUE if there's an image element in the coordinates of the Hit Test, - * or %FALSE otherwise - */ -gboolean webkit_hit_test_result_context_is_image(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), FALSE); - - return hitTestResult->priv->context & WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE; -} - -/** - * webkit_hit_test_result_context_is_media: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets whether %WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA flag is present in - * #WebKitHitTestResult:context. - * - * Returns: %TRUE if there's a media element in the coordinates of the Hit Test, - * or %FALSE otherwise - */ -gboolean webkit_hit_test_result_context_is_media(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), FALSE); - - return hitTestResult->priv->context & WEBKIT_HIT_TEST_RESULT_CONTEXT_MEDIA; -} - -/** - * webkit_hit_test_result_context_is_editable: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets whether %WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE flag is present in - * #WebKitHitTestResult:context. - * - * Returns: %TRUE if there's an editable element at the coordinates of the @hit_test_result, - * or %FALSE otherwise - */ -gboolean webkit_hit_test_result_context_is_editable(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), FALSE); - - return hitTestResult->priv->context & WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE; -} - -/** - * webkit_hit_test_result_get_link_uri: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets the value of the #WebKitHitTestResult:link-uri property. - * - * Returns: the URI of the link element in the coordinates of the Hit Test, - * or %NULL if there ins't a link element in @hit_test_result context - */ -const gchar* webkit_hit_test_result_get_link_uri(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), 0); - - return hitTestResult->priv->linkURI.data(); -} - -/** - * webkit_hit_test_result_get_link_title: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets the value of the #WebKitHitTestResult:link-title property. - * - * Returns: the title of the link element in the coordinates of the Hit Test, - * or %NULL if there ins't a link element in @hit_test_result context or the - * link element doesn't have a title - */ -const gchar* webkit_hit_test_result_get_link_title(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), 0); - - return hitTestResult->priv->linkTitle.data(); -} - -/** - * webkit_hit_test_result_get_link_label: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets the value of the #WebKitHitTestResult:link-label property. - * - * Returns: the label of the link element in the coordinates of the Hit Test, - * or %NULL if there ins't a link element in @hit_test_result context or the - * link element doesn't have a label - */ -const gchar* webkit_hit_test_result_get_link_label(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), 0); - - return hitTestResult->priv->linkLabel.data(); -} - -/** - * webkit_hit_test_result_get_image_uri: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets the value of the #WebKitHitTestResult:image-uri property. - * - * Returns: the URI of the image element in the coordinates of the Hit Test, - * or %NULL if there ins't an image element in @hit_test_result context - */ -const gchar* webkit_hit_test_result_get_image_uri(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), 0); - - return hitTestResult->priv->imageURI.data(); -} - -/** - * webkit_hit_test_result_get_media_uri: - * @hit_test_result: a #WebKitHitTestResult - * - * Gets the value of the #WebKitHitTestResult:media-uri property. - * - * Returns: the URI of the media element in the coordinates of the Hit Test, - * or %NULL if there ins't a media element in @hit_test_result context - */ -const gchar* webkit_hit_test_result_get_media_uri(WebKitHitTestResult* hitTestResult) -{ - g_return_val_if_fail(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult), 0); - - 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 deleted file mode 100644 index 54611ba92..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResult.h +++ /dev/null @@ -1,117 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitHitTestResult_h -#define WebKitHitTestResult_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_HIT_TEST_RESULT (webkit_hit_test_result_get_type()) -#define WEBKIT_HIT_TEST_RESULT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_HIT_TEST_RESULT, WebKitHitTestResult)) -#define WEBKIT_IS_HIT_TEST_RESULT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_HIT_TEST_RESULT)) -#define WEBKIT_HIT_TEST_RESULT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_HIT_TEST_RESULT, WebKitHitTestResultClass)) -#define WEBKIT_IS_HIT_TEST_RESULT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_HIT_TEST_RESULT)) -#define WEBKIT_HIT_TEST_RESULT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_HIT_TEST_RESULT, WebKitHitTestResultClass)) - -typedef struct _WebKitHitTestResult WebKitHitTestResult; -typedef struct _WebKitHitTestResultClass WebKitHitTestResultClass; -typedef struct _WebKitHitTestResultPrivate WebKitHitTestResultPrivate; - -/** - * WebKitHitTestResultContext: - * @WEBKIT_HIT_TEST_RESULT_CONTEXT_DOCUMENT: anywhere in the document. - * @WEBKIT_HIT_TEST_RESULT_CONTEXT_LINK: a hyperlink element. - * @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_SCROLLBAR = 1 << 6 -} WebKitHitTestResultContext; - -struct _WebKitHitTestResult { - GObject parent; - - WebKitHitTestResultPrivate *priv; -}; - -struct _WebKitHitTestResultClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_hit_test_result_get_type (void); - -WEBKIT_API guint -webkit_hit_test_result_get_context (WebKitHitTestResult *hit_test_result); - -WEBKIT_API gboolean -webkit_hit_test_result_context_is_link (WebKitHitTestResult *hit_test_result); - -WEBKIT_API gboolean -webkit_hit_test_result_context_is_image (WebKitHitTestResult *hit_test_result); - -WEBKIT_API gboolean -webkit_hit_test_result_context_is_media (WebKitHitTestResult *hit_test_result); - -WEBKIT_API gboolean -webkit_hit_test_result_context_is_editable (WebKitHitTestResult *hit_test_result); - -WEBKIT_API const gchar * -webkit_hit_test_result_get_link_uri (WebKitHitTestResult *hit_test_result); - -WEBKIT_API const gchar * -webkit_hit_test_result_get_link_title (WebKitHitTestResult *hit_test_result); - -WEBKIT_API const gchar * -webkit_hit_test_result_get_link_label (WebKitHitTestResult *hit_test_result); - -WEBKIT_API const gchar * -webkit_hit_test_result_get_image_uri (WebKitHitTestResult *hit_test_result); - -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/WebKitHitTestResultPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResultPrivate.h deleted file mode 100644 index 7ba2c3871..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitHitTestResultPrivate.h +++ /dev/null @@ -1,29 +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. - */ - -#ifndef WebKitHitTestResultPrivate_h -#define WebKitHitTestResultPrivate_h - -#include "WebKitHitTestResult.h" -#include "WebKitPrivate.h" - -WebKitHitTestResult* webkitHitTestResultCreate(WebKit::WebHitTestResult*); -bool webkitHitTestResultCompare(WebKitHitTestResult*, WebKit::WebHitTestResult*); - -#endif // WebKitHitTestResultPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.cpp deleted file mode 100644 index 26a6f8f10..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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/WebKitInjectedBundleClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.h deleted file mode 100644 index 7f7c79179..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitInjectedBundleClient.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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 WebKitInjectedBundleClient_h -#define WebKitInjectedBundleClient_h - -#include "WebKitWebContext.h" - -void attachInjectedBundleClientToContext(WebKitWebContext*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResult.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResult.cpp deleted file mode 100644 index 9bbd3f4ed..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResult.cpp +++ /dev/null @@ -1,110 +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 "WebKitJavascriptResult.h" - -#include "WebKitJavascriptResultPrivate.h" -#include "WebSerializedScriptValue.h" -#include <wtf/gobject/GRefPtr.h> - -using namespace WebKit; - -struct _WebKitJavascriptResult { - _WebKitJavascriptResult(WebKitWebView* view, WebSerializedScriptValue* serializedScriptValue) - : webView(view) - , referenceCount(1) - { - value = serializedScriptValue->deserialize(webkit_web_view_get_javascript_global_context(view), 0); - } - - GRefPtr<WebKitWebView> webView; - JSValueRef value; - - int referenceCount; -}; - -G_DEFINE_BOXED_TYPE(WebKitJavascriptResult, webkit_javascript_result, webkit_javascript_result_ref, webkit_javascript_result_unref) - -WebKitJavascriptResult* webkitJavascriptResultCreate(WebKitWebView* webView, WebSerializedScriptValue* serializedScriptValue) -{ - WebKitJavascriptResult* result = g_slice_new(WebKitJavascriptResult); - new (result) WebKitJavascriptResult(webView, serializedScriptValue); - return result; -} - -/** - * webkit_javascript_result_ref: - * @js_result: a #WebKitJavascriptResult - * - * Atomically increments the reference count of @js_result by one. This - * function is MT-safe and may be called from any thread. - * - * Returns: The passed in #WebKitJavascriptResult - */ -WebKitJavascriptResult* webkit_javascript_result_ref(WebKitJavascriptResult* javascriptResult) -{ - g_atomic_int_inc(&javascriptResult->referenceCount); - return javascriptResult; -} - -/** - * webkit_javascript_result_unref: - * @js_result: a #WebKitJavascriptResult - * - * Atomically decrements the reference count of @js_result by one. If the - * reference count drops to 0, all memory allocated by the #WebKitJavascriptResult is - * released. This function is MT-safe and may be called from any - * thread. - */ -void webkit_javascript_result_unref(WebKitJavascriptResult* javascriptResult) -{ - if (g_atomic_int_dec_and_test(&javascriptResult->referenceCount)) { - javascriptResult->~WebKitJavascriptResult(); - g_slice_free(WebKitJavascriptResult, javascriptResult); - } -} - -/** - * webkit_javascript_result_get_global_context: - * @js_result: a #WebKitJavascriptResult - * - * Get the global Javascript context that should be used with the - * <function>JSValueRef</function> returned by webkit_javascript_result_get_value(). - * - * Returns: the <function>JSGlobalContextRef</function> for the #WebKitJavascriptResult - */ -JSGlobalContextRef webkit_javascript_result_get_global_context(WebKitJavascriptResult* javascriptResult) -{ - return webkit_web_view_get_javascript_global_context(javascriptResult->webView.get()); -} - -/** - * webkit_javascript_result_get_value: - * @js_result: a #WebKitJavascriptResult - * - * Get the value of @js_result. You should use the <function>JSGlobalContextRef</function> - * returned by webkit_javascript_result_get_global_context() to use the <function>JSValueRef</function>. - * - * Returns: the <function>JSValueRef</function> of the #WebKitJavascriptResult - */ -JSValueRef webkit_javascript_result_get_value(WebKitJavascriptResult* javascriptResult) -{ - return javascriptResult->value; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResult.h b/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResult.h deleted file mode 100644 index 5a9f7389f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResult.h +++ /dev/null @@ -1,55 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitJavascriptResult_h -#define WebKitJavascriptResult_h - -#include <JavaScriptCore/JSBase.h> -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_JAVASCRIPT_RESULT (webkit_javascript_result_get_type()) - -typedef struct _WebKitJavascriptResult WebKitJavascriptResult; - - -WEBKIT_API GType -webkit_javascript_result_get_type (void); - -WEBKIT_API WebKitJavascriptResult * -webkit_javascript_result_ref (WebKitJavascriptResult *js_result); - -WEBKIT_API void -webkit_javascript_result_unref (WebKitJavascriptResult *js_result); - -WEBKIT_API JSGlobalContextRef -webkit_javascript_result_get_global_context (WebKitJavascriptResult *js_result); - -WEBKIT_API JSValueRef -webkit_javascript_result_get_value (WebKitJavascriptResult *js_result); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResultPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResultPrivate.h deleted file mode 100644 index e47e94c1b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitJavascriptResultPrivate.h +++ /dev/null @@ -1,29 +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. - */ - -#ifndef WebKitJavascriptResultPrivate_h -#define WebKitJavascriptResultPrivate_h - -#include "WebKitJavascriptResult.h" -#include "WebKitPrivate.h" -#include "WebKitWebView.h" - -WebKitJavascriptResult* webkitJavascriptResultCreate(WebKitWebView*, WebKit::WebSerializedScriptValue*); - -#endif // WebKitJavascriptResultPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp deleted file mode 100644 index 36cd6c0e6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 "WebKitLoaderClient.h" - -#include "WebKitBackForwardListPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> - -using namespace WebKit; -using namespace WebCore; - -static void didStartProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - webkitWebViewLoadChanged(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_LOAD_STARTED); -} - -static void didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - webkitWebViewLoadChanged(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_LOAD_REDIRECTED); -} - -static void didFailProvisionalLoadWithErrorForFrame(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - const ResourceError& resourceError = toImpl(error)->platformError(); - GOwnPtr<GError> webError(g_error_new_literal(g_quark_from_string(resourceError.domain().utf8().data()), - resourceError.errorCode(), - resourceError.localizedDescription().utf8().data())); - 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) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - webkitWebViewLoadChanged(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_LOAD_COMMITTED); -} - -static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - webkitWebViewLoadChanged(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_LOAD_FINISHED); -} - -static void didFailLoadWithErrorForFrame(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - const ResourceError& resourceError = toImpl(error)->platformError(); - 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_COMMITTED, - resourceError.failingURL().utf8().data(), webError.get()); -} - -static void didSameDocumentNavigationForFrame(WKPageRef page, WKFrameRef frame, WKSameDocumentNavigationType, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - webkitWebViewUpdateURI(WEBKIT_WEB_VIEW(clientInfo)); -} - -static void didReceiveTitleForFrame(WKPageRef page, WKStringRef titleRef, WKFrameRef frameRef, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frameRef)) - return; - - 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)); -} - -static void didChangeBackForwardList(WKPageRef page, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void* clientInfo) -{ - webkitBackForwardListChanged(webkit_web_view_get_back_forward_list(WEBKIT_WEB_VIEW(clientInfo)), toImpl(addedItem), toImpl(removedItems)); -} - -static void didReceiveAuthenticationChallengeInFrame(WKPageRef page, WKFrameRef frame, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo) -{ - 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 = { - kWKPageLoaderClientCurrentVersion, - webView, // clientInfo - didStartProvisionalLoadForFrame, - didReceiveServerRedirectForProvisionalLoadForFrame, - didFailProvisionalLoadWithErrorForFrame, - didCommitLoadForFrame, - 0, // didFinishDocumentLoadForFrame - didFinishLoadForFrame, - didFailLoadWithErrorForFrame, - didSameDocumentNavigationForFrame, - didReceiveTitleForFrame, - 0, // didFirstLayoutForFrame - 0, // didFirstVisuallyNonEmptyLayoutForFrame - 0, // didRemoveFrameFromHierarchy - didDisplayInsecureContentForFrame, - didRunInsecureContentForFrame, - 0, // canAuthenticateAgainstProtectionSpaceInFrame - didReceiveAuthenticationChallengeInFrame, - didChangeProgress, // didStartProgress - didChangeProgress, - didChangeProgress, // didFinishProgress - 0, // didBecomeUnresponsive - 0, // didBecomeResponsive - processDidCrash, - didChangeBackForwardList, - 0, // shouldGoToBackForwardListItem - 0, // didFailToInitializePlugin - 0, // didDetectXSSForFrame - 0, // didFirstVisuallyNonEmptyLayoutForFrame - 0, // willGoToBackForwardListItem - 0, // interactionOccurredWhileProcessUnresponsive - 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/WebKitLoaderClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.h deleted file mode 100644 index dfac3c86f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitLoaderClient.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitLoaderClient_h -#define WebKitLoaderClient_h - -#include "WebKitWebView.h" - -void attachLoaderClientToView(WebKitWebView*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfo.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfo.cpp deleted file mode 100644 index 2282ede37..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfo.cpp +++ /dev/null @@ -1,145 +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 "WebKitMimeInfo.h" - -#include "WebKitMimeInfoPrivate.h" -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -struct _WebKitMimeInfo { - _WebKitMimeInfo(const WebCore::MimeClassInfo& mimeInfo) - : mimeInfo(mimeInfo) - { - } - - WebCore::MimeClassInfo mimeInfo; - CString mimeType; - CString description; - GRefPtr<GPtrArray> extensions; - - int referenceCount; -}; - -G_DEFINE_BOXED_TYPE(WebKitMimeInfo, webkit_mime_info, webkit_mime_info_ref, webkit_mime_info_unref) - -WebKitMimeInfo* webkitMimeInfoCreate(const WebCore::MimeClassInfo& mimeInfo) -{ - WebKitMimeInfo* info = g_slice_new(WebKitMimeInfo); - new (info) WebKitMimeInfo(mimeInfo); - return info; -} - -/** - * webkit_mime_info_ref: - * @info: a #WebKitMimeInfo - * - * Atomically increments the reference count of @info by one. This - * function is MT-safe and may be called from any thread. - * - * Returns: The passed in #WebKitMimeInfo - */ -WebKitMimeInfo* webkit_mime_info_ref(WebKitMimeInfo* info) -{ - g_atomic_int_inc(&info->referenceCount); - return info; -} - -/** - * webkit_mime_info_unref: - * @info: a #WebKitMimeInfo - * - * Atomically decrements the reference count of @info by one. If the - * reference count drops to 0, all memory allocated by the #WebKitMimeInfo is - * released. This function is MT-safe and may be called from any - * thread. - */ -void webkit_mime_info_unref(WebKitMimeInfo* info) -{ - if (g_atomic_int_dec_and_test(&info->referenceCount)) { - info->~WebKitMimeInfo(); - g_slice_free(WebKitMimeInfo, info); - } -} - -/** - * webkit_mime_info_get_mime_type: - * @info: a #WebKitMimeInfo - * - * Returns: the MIME type of @info - */ -const char* webkit_mime_info_get_mime_type(WebKitMimeInfo* info) -{ - if (!info->mimeType.isNull()) - return info->mimeType.data(); - - if (info->mimeInfo.type.isEmpty()) - return 0; - - info->mimeType = info->mimeInfo.type.utf8(); - return info->mimeType.data(); -} - -/** - * webkit_mime_info_get_description: - * @info: a #WebKitMimeInfo - * - * Returns: the description of the MIME type of @info - */ -const char* webkit_mime_info_get_description(WebKitMimeInfo* info) -{ - if (!info->description.isNull()) - return info->description.data(); - - if (info->mimeInfo.desc.isEmpty()) - return 0; - - info->description = info->mimeInfo.desc.utf8(); - return info->description.data(); -} - -/** - * webkit_mime_info_get_extensions: - * @info: a #WebKitMimeInfo - * - * Get the list of file extensions associated to the - * MIME type of @info - * - * Returns: (array zero-terminated=1) (transfer none): a - * %NULL-terminated array of strings - */ -const char* const* webkit_mime_info_get_extensions(WebKitMimeInfo* info) -{ - if (info->extensions) - return reinterpret_cast<gchar**>(info->extensions->pdata); - - if (info->mimeInfo.extensions.isEmpty()) - return 0; - - info->extensions = adoptGRef(g_ptr_array_new_with_free_func(g_free)); - for (size_t i = 0; i < info->mimeInfo.extensions.size(); ++i) { - if (info->mimeInfo.extensions[i].isEmpty()) - continue; - g_ptr_array_add(info->extensions.get(), g_strdup(info->mimeInfo.extensions[i].utf8().data())); - } - g_ptr_array_add(info->extensions.get(), 0); - - return reinterpret_cast<gchar**>(info->extensions->pdata); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfo.h b/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfo.h deleted file mode 100644 index 7ec8e69c5..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfo.h +++ /dev/null @@ -1,57 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitMimeInfo_h -#define WebKitMimeInfo_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_MIME_INFO (webkit_mime_info_get_type()) - -typedef struct _WebKitMimeInfo WebKitMimeInfo; - - -WEBKIT_API GType -webkit_mime_info_get_type (void); - -WEBKIT_API WebKitMimeInfo * -webkit_mime_info_ref (WebKitMimeInfo *info); - -WEBKIT_API void -webkit_mime_info_unref (WebKitMimeInfo *info); - -WEBKIT_API const gchar * -webkit_mime_info_get_mime_type (WebKitMimeInfo *info); - -WEBKIT_API const gchar * -webkit_mime_info_get_description (WebKitMimeInfo *info); - -WEBKIT_API const gchar * const * -webkit_mime_info_get_extensions (WebKitMimeInfo *info); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfoPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfoPrivate.h deleted file mode 100644 index 0ccc007b3..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitMimeInfoPrivate.h +++ /dev/null @@ -1,29 +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. - */ - -#ifndef WebKitMimeInfoPrivate_h -#define WebKitMimeInfoPrivate_h - -#include "WebKitMimeInfo.h" -#include "WebKitPrivate.h" -#include <WebCore/PluginData.h> - -WebKitMimeInfo* webkitMimeInfoCreate(const WebCore::MimeClassInfo&); - -#endif // WebKitMimeInfoPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.cpp deleted file mode 100644 index deef50c55..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.cpp +++ /dev/null @@ -1,263 +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 "WebKitNavigationPolicyDecision.h" - -#include "WebEvent.h" -#include "WebKitEnumTypes.h" -#include "WebKitPolicyDecisionPrivate.h" -#include "WebKitURIRequestPrivate.h" -#include "WebURLRequest.h" -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -using namespace WebKit; -using namespace WebCore; - -/** - * SECTION: WebKitNavigationPolicyDecision - * @Short_description: A policy decision for navigation actions - * @Title: WebKitNavigationPolicyDecision - * @See_also: #WebKitPolicyDecision, #WebKitWebView - * - * WebKitNavigationPolicyDecision represents a policy decision for events associated with - * navigations. If the value of #WebKitNavigationPolicyDecision:mouse-button is not 0, then - * the navigation was triggered by a mouse event. - */ - -struct _WebKitNavigationPolicyDecisionPrivate { - WebKitNavigationType navigationType; - unsigned modifiers; - unsigned mouseButton; - GRefPtr<WebKitURIRequest> request; - CString frameName; -}; - -WEBKIT_DEFINE_TYPE(WebKitNavigationPolicyDecision, webkit_navigation_policy_decision, WEBKIT_TYPE_POLICY_DECISION) - -enum { - PROP_0, - PROP_NAVIGATION_TYPE, - PROP_MOUSE_BUTTON, - PROP_MODIFIERS, - PROP_REQUEST, - PROP_FRAME_NAME, -}; - -static void webkitNavigationPolicyDecisionGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitNavigationPolicyDecision* decision = WEBKIT_NAVIGATION_POLICY_DECISION(object); - switch (propId) { - case PROP_NAVIGATION_TYPE: - g_value_set_enum(value, webkit_navigation_policy_decision_get_navigation_type(decision)); - break; - case PROP_MOUSE_BUTTON: - g_value_set_enum(value, webkit_navigation_policy_decision_get_mouse_button(decision)); - break; - case PROP_MODIFIERS: - g_value_set_uint(value, webkit_navigation_policy_decision_get_modifiers(decision)); - break; - case PROP_REQUEST: - g_value_set_object(value, webkit_navigation_policy_decision_get_request(decision)); - break; - case PROP_FRAME_NAME: - g_value_set_string(value, webkit_navigation_policy_decision_get_frame_name(decision)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - break; - } -} - -static void webkit_navigation_policy_decision_class_init(WebKitNavigationPolicyDecisionClass* decisionClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(decisionClass); - objectClass->get_property = webkitNavigationPolicyDecisionGetProperty; - - /** - * WebKitNavigationPolicyDecision:navigation-type: - * - * The type of navigation that triggered this policy decision. This is - * useful for enacting different policies depending on what type of user - * action caused the navigation. - */ - g_object_class_install_property(objectClass, - PROP_NAVIGATION_TYPE, - g_param_spec_enum("navigation-type", - _("Navigation type"), - _("The type of navigation triggering this decision"), - WEBKIT_TYPE_NAVIGATION_TYPE, - WEBKIT_NAVIGATION_TYPE_LINK_CLICKED, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitNavigationPolicyDecision:mouse-button: - * - * If the navigation associated with this policy decision was originally - * triggered by a mouse event, this property contains non-zero button number - * of the button triggering that event. The button numbers match those from GDK. - * If the navigation was not triggered by a mouse event, the value of this - * property will be 0. - */ - g_object_class_install_property(objectClass, - PROP_MOUSE_BUTTON, - g_param_spec_uint("mouse-button", - _("Mouse button"), - _("The mouse button used if this decision was triggered by a mouse event"), - 0, G_MAXUINT, 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitNavigationPolicyDecision:modifiers: - * - * If the navigation associated with this policy decision was originally - * triggered by a mouse event, this property contains a bitmask of various - * #GdkModifierType values describing the modifiers used for that click. - * If the navigation was not triggered by a mouse event or no modifiers - * were active, the value of this property will be zero. - */ - g_object_class_install_property(objectClass, - PROP_MODIFIERS, - g_param_spec_uint("modifiers", - _("Mouse event modifiers"), - _("The modifiers active if this decision was triggered by a mouse event"), - 0, G_MAXUINT, 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitNavigationPolicyDecision:request: - * - * This property contains the #WebKitURIRequest associated with this - * navigation. - */ - g_object_class_install_property(objectClass, - PROP_REQUEST, - g_param_spec_object("request", - _("Navigation URI request"), - _("The URI request that is associated with this navigation"), - WEBKIT_TYPE_URI_REQUEST, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitNavigationPolicyDecision:frame-name: - * - * If this navigation request targets a new frame, this property contains - * the name of that frame. For example if the decision was triggered by clicking a - * link with a target attribute equal to "_blank", this property will contain the - * value of that attribute. In all other cases, this value will be %NULL. - */ - g_object_class_install_property(objectClass, - PROP_FRAME_NAME, - g_param_spec_string("frame-name", - _("Frame name"), - _("The name of the new frame this navigation action targets"), - 0, - WEBKIT_PARAM_READABLE)); -} - -/** - * webkit_navigation_policy_decision_get_navigation_type: - * @decision: a #WebKitNavigationPolicyDecision - * - * Gets the value of the #WebKitNavigationPolicyDecision:navigation-type property. - * - * Returns: The type of navigation triggering this policy decision. - */ -WebKitNavigationType webkit_navigation_policy_decision_get_navigation_type(WebKitNavigationPolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_NAVIGATION_POLICY_DECISION(decision), WEBKIT_NAVIGATION_TYPE_OTHER); - return decision->priv->navigationType; -} - -/** - * webkit_navigation_policy_decision_get_mouse_button: - * @decision: a #WebKitNavigationPolicyDecision - * - * Gets the value of the #WebKitNavigationPolicyDecision:mouse-button property. - * - * Returns: The mouse button used if this decision was triggered by a mouse event or 0 otherwise - */ -guint webkit_navigation_policy_decision_get_mouse_button(WebKitNavigationPolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_NAVIGATION_POLICY_DECISION(decision), 0); - return decision->priv->mouseButton; -} - -/** - * webkit_navigation_policy_decision_get_modifiers: - * @decision: a #WebKitNavigationPolicyDecision - * - * Gets the value of the #WebKitNavigationPolicyDecision:modifiers property. - * - * Returns: The modifiers active if this decision was triggered by a mouse event - */ -unsigned webkit_navigation_policy_decision_get_modifiers(WebKitNavigationPolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_NAVIGATION_POLICY_DECISION(decision), 0); - return decision->priv->modifiers; -} - -/** - * webkit_navigation_policy_decision_get_request: - * @decision: a #WebKitNavigationPolicyDecision - * - * Gets the value of the #WebKitNavigationPolicyDecision:request property. - * - * Returns: (transfer none): The URI request that is associated with this navigation - */ -WebKitURIRequest* webkit_navigation_policy_decision_get_request(WebKitNavigationPolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_NAVIGATION_POLICY_DECISION(decision), 0); - return decision->priv->request.get(); -} - -/** - * webkit_navigation_policy_decision_get_frame_name: - * @decision: a #WebKitNavigationPolicyDecision - * - * Gets the value of the #WebKitNavigationPolicyDecision:frame-name property. - * - * Returns: The name of the new frame this navigation action targets or %NULL - */ -const char* webkit_navigation_policy_decision_get_frame_name(WebKitNavigationPolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_NAVIGATION_POLICY_DECISION(decision), 0); - return decision->priv->frameName.data(); -} - -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NAVIGATION_TYPE_LINK_CLICKED, NavigationTypeLinkClicked); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED, NavigationTypeFormSubmitted); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NAVIGATION_TYPE_BACK_FORWARD, NavigationTypeBackForward); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NAVIGATION_TYPE_RELOAD, NavigationTypeReload); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED, NavigationTypeFormResubmitted); -COMPILE_ASSERT_MATCHING_ENUM(WEBKIT_NAVIGATION_TYPE_OTHER, NavigationTypeOther); - -WebKitNavigationPolicyDecision* webkitNavigationPolicyDecisionCreate(WebKitNavigationType navigationType, unsigned mouseButton, unsigned modifiers, WebURLRequest* request, const char* frameName, WebFramePolicyListenerProxy* listener) -{ - WebKitNavigationPolicyDecision* decision = WEBKIT_NAVIGATION_POLICY_DECISION(g_object_new(WEBKIT_TYPE_NAVIGATION_POLICY_DECISION, NULL)); - decision->priv->navigationType = navigationType; - decision->priv->mouseButton = mouseButton; - decision->priv->modifiers = modifiers; - decision->priv->request = adoptGRef(webkitURIRequestCreateForResourceRequest(request->resourceRequest())); - decision->priv->frameName = frameName; - webkitPolicyDecisionSetListener(WEBKIT_POLICY_DECISION(decision), listener); - return decision; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h b/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h deleted file mode 100644 index 751397731..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecision.h +++ /dev/null @@ -1,96 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitNavigationPolicyDecision_h -#define WebKitNavigationPolicyDecision_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitPolicyDecision.h> -#include <webkit2/WebKitURIRequest.h> - -G_BEGIN_DECLS - -/** - * WebKitNavigationType: - * @WEBKIT_NAVIGATION_TYPE_LINK_CLICKED: The navigation was triggered by clicking a link. - * @WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED: The navigation was triggered by submitting a form. - * @WEBKIT_NAVIGATION_TYPE_BACK_FORWARD: The navigation was triggered by navigating forward or backward. - * @WEBKIT_NAVIGATION_TYPE_RELOAD: The navigation was triggered by reloading. - * @WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED: The navigation was triggered by resubmitting a form. - * @WEBKIT_NAVIGATION_TYPE_OTHER: The navigation was triggered by some other action. - * - * Enum values used to denote the various navigation types. - */ -typedef enum { - WEBKIT_NAVIGATION_TYPE_LINK_CLICKED, - WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED, - WEBKIT_NAVIGATION_TYPE_BACK_FORWARD, - WEBKIT_NAVIGATION_TYPE_RELOAD, - WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED, - WEBKIT_NAVIGATION_TYPE_OTHER, -} WebKitNavigationType; - -#define WEBKIT_TYPE_NAVIGATION_POLICY_DECISION (webkit_navigation_policy_decision_get_type()) -#define WEBKIT_NAVIGATION_POLICY_DECISION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_NAVIGATION_POLICY_DECISION, WebKitNavigationPolicyDecision)) -#define WEBKIT_NAVIGATION_POLICY_DECISION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_NAVIGATION_POLICY_DECISION, WebKitNavigationPolicyDecisionClass)) -#define WEBKIT_IS_NAVIGATION_POLICY_DECISION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_NAVIGATION_POLICY_DECISION)) -#define WEBKIT_IS_NAVIGATION_POLICY_DECISION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_NAVIGATION_POLICY_DECISION)) -#define WEBKIT_NAVIGATION_POLICY_DECISION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_NAVIGATION_POLICY_DECISION, WebKitNavigationPolicyDecisionClass)) - -typedef struct _WebKitNavigationPolicyDecision WebKitNavigationPolicyDecision; -typedef struct _WebKitNavigationPolicyDecisionClass WebKitNavigationPolicyDecisionClass; -typedef struct _WebKitNavigationPolicyDecisionPrivate WebKitNavigationPolicyDecisionPrivate; - -struct _WebKitNavigationPolicyDecision { - WebKitPolicyDecision parent; - - /*< private >*/ - WebKitNavigationPolicyDecisionPrivate *priv; -}; - -struct _WebKitNavigationPolicyDecisionClass { - WebKitPolicyDecisionClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_navigation_policy_decision_get_type (void); - -WEBKIT_API WebKitNavigationType -webkit_navigation_policy_decision_get_navigation_type (WebKitNavigationPolicyDecision *decision); -WEBKIT_API guint -webkit_navigation_policy_decision_get_mouse_button (WebKitNavigationPolicyDecision *decision); -WEBKIT_API guint -webkit_navigation_policy_decision_get_modifiers (WebKitNavigationPolicyDecision *decision); -WEBKIT_API WebKitURIRequest * -webkit_navigation_policy_decision_get_request (WebKitNavigationPolicyDecision *decision); -WEBKIT_API const gchar * -webkit_navigation_policy_decision_get_frame_name (WebKitNavigationPolicyDecision *decision); -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecisionPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecisionPrivate.h deleted file mode 100644 index d90f1c6c8..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitNavigationPolicyDecisionPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitNavigationPolicyDecisionPrivate_h -#define WebKitNavigationPolicyDecisionPrivate_h - -#include "WebKitNavigationPolicyDecision.h" -#include "WebKitPrivate.h" - -WebKitNavigationPolicyDecision* webkitNavigationPolicyDecisionCreate(WebKitNavigationType, unsigned mouseButton, unsigned modifiers, WebKit::WebURLRequest*, const char* frameName, WebKit::WebFramePolicyListenerProxy*); - -#endif // WebKitNavigationPolicyDecisionPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPermissionRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPermissionRequest.cpp deleted file mode 100644 index 92235cef1..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPermissionRequest.cpp +++ /dev/null @@ -1,72 +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 "WebKitPermissionRequest.h" - -/** - * SECTION: WebKitPermissionRequest - * @Short_description: A permission request - * @Title: WebKitPermissionRequest - * @See_also: #WebKitWebView - * - * There are situations where an embedder would need to ask the user - * for permission to do certain types of operations, such as switching - * to fullscreen mode or reporting the user's location through the - * standard Geolocation API. In those cases, WebKit will emit a - * #WebKitWebView::permission-request signal with a - * #WebKitPermissionRequest object attached to it. - */ - -typedef WebKitPermissionRequestIface WebKitPermissionRequestInterface; -G_DEFINE_INTERFACE(WebKitPermissionRequest, webkit_permission_request, G_TYPE_OBJECT) - -static void webkit_permission_request_default_init(WebKitPermissionRequestIface*) -{ -} - -/** - * webkit_permission_request_allow: - * @request: a #WebKitPermissionRequest - * - * Allow the action which triggered this request. - */ -void webkit_permission_request_allow(WebKitPermissionRequest* request) -{ - g_return_if_fail(WEBKIT_IS_PERMISSION_REQUEST(request)); - - WebKitPermissionRequestIface* iface = WEBKIT_PERMISSION_REQUEST_GET_IFACE(request); - if (iface->allow) - iface->allow(request); -} - -/** - * webkit_permission_request_deny: - * @request: a #WebKitPermissionRequest - * - * Deny the action which triggered this request. - */ -void webkit_permission_request_deny(WebKitPermissionRequest* request) -{ - g_return_if_fail(WEBKIT_IS_PERMISSION_REQUEST(request)); - - WebKitPermissionRequestIface* iface = WEBKIT_PERMISSION_REQUEST_GET_IFACE(request); - if (iface->deny) - iface->deny(request); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPermissionRequest.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPermissionRequest.h deleted file mode 100644 index a62f1f1a5..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPermissionRequest.h +++ /dev/null @@ -1,58 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitPermissionRequest_h -#define WebKitPermissionRequest_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_PERMISSION_REQUEST (webkit_permission_request_get_type()) -#define WEBKIT_PERMISSION_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_PERMISSION_REQUEST, WebKitPermissionRequest)) -#define WEBKIT_IS_PERMISSION_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_PERMISSION_REQUEST)) -#define WEBKIT_PERMISSION_REQUEST_GET_IFACE(obj) (G_TYPE_INSTANCE_GET_INTERFACE((obj), WEBKIT_TYPE_PERMISSION_REQUEST, WebKitPermissionRequestIface)) - -typedef struct _WebKitPermissionRequest WebKitPermissionRequest; -typedef struct _WebKitPermissionRequestIface WebKitPermissionRequestIface; - -struct _WebKitPermissionRequestIface { - GTypeInterface parent_interface; - - void (* allow) (WebKitPermissionRequest *request); - void (* deny) (WebKitPermissionRequest *request); -}; - -WEBKIT_API GType -webkit_permission_request_get_type (void); - -WEBKIT_API void -webkit_permission_request_allow (WebKitPermissionRequest *request); - -WEBKIT_API void -webkit_permission_request_deny (WebKitPermissionRequest *request); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp deleted file mode 100644 index 977afa450..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.cpp +++ /dev/null @@ -1,151 +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 "WebKitPlugin.h" - -#include "WebKitMimeInfoPrivate.h" -#include "WebKitPluginPrivate.h" -#include <wtf/text/CString.h> - -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() - { - g_list_free_full(mimeInfoList, reinterpret_cast<GDestroyNotify>(webkit_mime_info_unref)); - } - - PluginModuleInfo pluginInfo; - CString name; - CString description; - CString path; - GList* mimeInfoList; -}; - -WEBKIT_DEFINE_TYPE(WebKitPlugin, webkit_plugin, G_TYPE_OBJECT) - -static void webkit_plugin_class_init(WebKitPluginClass* pluginClass) -{ -} - -WebKitPlugin* webkitPluginCreate(const PluginModuleInfo& pluginInfo) -{ - WebKitPlugin* plugin = WEBKIT_PLUGIN(g_object_new(WEBKIT_TYPE_PLUGIN, NULL)); - plugin->priv->pluginInfo = pluginInfo; - return plugin; -} - -/** - * webkit_plugin_get_name: - * @plugin: a #WebKitPlugin - * - * Returns: the name of the plugin. - */ -const char* webkit_plugin_get_name(WebKitPlugin* plugin) -{ - g_return_val_if_fail(WEBKIT_IS_PLUGIN(plugin), 0); - - if (!plugin->priv->name.isNull()) - return plugin->priv->name.data(); - - if (plugin->priv->pluginInfo.info.name.isEmpty()) - return 0; - - plugin->priv->name = plugin->priv->pluginInfo.info.name.utf8(); - return plugin->priv->name.data(); -} - -/** - * webkit_plugin_get_description: - * @plugin: a #WebKitPlugin - * - * Returns: the description of the plugin. - */ -const char* webkit_plugin_get_description(WebKitPlugin* plugin) -{ - g_return_val_if_fail(WEBKIT_IS_PLUGIN(plugin), 0); - - if (!plugin->priv->description.isNull()) - plugin->priv->description.data(); - - if (plugin->priv->pluginInfo.info.desc.isEmpty()) - return 0; - - plugin->priv->description = plugin->priv->pluginInfo.info.desc.utf8(); - return plugin->priv->description.data(); -} - -/** - * webkit_plugin_get_path: - * @plugin: a #WebKitPlugin - * - * Returns: the absolute path where the plugin is installed. - */ -const char* webkit_plugin_get_path(WebKitPlugin* plugin) -{ - g_return_val_if_fail(WEBKIT_IS_PLUGIN(plugin), 0); - - if (!plugin->priv->path.isNull()) - return plugin->priv->path.data(); - - if (plugin->priv->pluginInfo.path.isEmpty()) - return 0; - - plugin->priv->path = plugin->priv->pluginInfo.path.utf8(); - return plugin->priv->path.data(); -} - -/** - * webkit_plugin_get_mime_info_list: - * @plugin: a #WebKitPlugin - * - * Get information about MIME types handled by the plugin, - * as a list of #WebKitMimeInfo. - * - * Returns: (element-type WebKitMimeInfo) (transfer none): a #GList of #WebKitMimeInfo. - */ -GList* webkit_plugin_get_mime_info_list(WebKitPlugin* plugin) -{ - g_return_val_if_fail(WEBKIT_IS_PLUGIN(plugin), 0); - - if (plugin->priv->mimeInfoList) - return plugin->priv->mimeInfoList; - - if (plugin->priv->pluginInfo.info.mimes.isEmpty()) - return 0; - - for (size_t i = 0; i < plugin->priv->pluginInfo.info.mimes.size(); ++i) - plugin->priv->mimeInfoList = g_list_prepend(plugin->priv->mimeInfoList, webkitMimeInfoCreate(plugin->priv->pluginInfo.info.mimes[i])); - return plugin->priv->mimeInfoList; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h deleted file mode 100644 index d7533c920..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPlugin.h +++ /dev/null @@ -1,75 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitPlugin_h -#define WebKitPlugin_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_PLUGIN (webkit_plugin_get_type()) -#define WEBKIT_PLUGIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_PLUGIN, WebKitPlugin)) -#define WEBKIT_IS_PLUGIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_PLUGIN)) -#define WEBKIT_PLUGIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_PLUGIN, WebKitPluginClass)) -#define WEBKIT_IS_PLUGIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_PLUGIN)) -#define WEBKIT_PLUGIN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_PLUGIN, WebKitPluginClass)) - -typedef struct _WebKitPlugin WebKitPlugin; -typedef struct _WebKitPluginClass WebKitPluginClass; -typedef struct _WebKitPluginPrivate WebKitPluginPrivate; - -struct _WebKitPlugin { - GObject parent; - - WebKitPluginPrivate *priv; -}; - -struct _WebKitPluginClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_plugin_get_type (void); - -WEBKIT_API const gchar * -webkit_plugin_get_name (WebKitPlugin *plugin); - -WEBKIT_API const gchar * -webkit_plugin_get_description (WebKitPlugin *plugin); - -WEBKIT_API const gchar * -webkit_plugin_get_path (WebKitPlugin *plugin); - -WEBKIT_API GList * -webkit_plugin_get_mime_info_list (WebKitPlugin *plugin); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPluginPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPluginPrivate.h deleted file mode 100644 index 3fe2ac0bf..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPluginPrivate.h +++ /dev/null @@ -1,29 +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. - */ - -#ifndef WebKitPluginPrivate_h -#define WebKitPluginPrivate_h - -#include "PluginModuleInfo.h" -#include "WebKitPlugin.h" -#include "WebKitPrivate.h" - -WebKitPlugin* webkitPluginCreate(const WebKit::PluginModuleInfo&); - -#endif // WebKitPluginPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyClient.cpp deleted file mode 100644 index 72a5266cc..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyClient.cpp +++ /dev/null @@ -1,80 +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 "WebKitPolicyClient.h" - -#include "WebKitNavigationPolicyDecisionPrivate.h" -#include "WebKitResponsePolicyDecisionPrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -using namespace WebKit; - -static void decidePolicyForNavigationActionCallback(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo) -{ - GRefPtr<WebKitNavigationPolicyDecision> decision = - adoptGRef(webkitNavigationPolicyDecisionCreate(static_cast<WebKitNavigationType>(navigationType), - wkEventMouseButtonToWebKitMouseButton(mouseButton), - wkEventModifiersToGdkModifiers(modifiers), - toImpl(request), - 0, /* frame name */ - toImpl(listener))); - webkitWebViewMakePolicyDecision(WEBKIT_WEB_VIEW(clientInfo), - WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION, - WEBKIT_POLICY_DECISION(decision.get())); -} - -static void decidePolicyForNewWindowActionCallback(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKStringRef frameName, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo) -{ - GRefPtr<WebKitNavigationPolicyDecision> decision = - adoptGRef(webkitNavigationPolicyDecisionCreate(static_cast<WebKitNavigationType>(navigationType), - wkEventMouseButtonToWebKitMouseButton(mouseButton), - wkEventModifiersToGdkModifiers(modifiers), - toImpl(request), - toImpl(frameName)->string().utf8().data(), - toImpl(listener))); - webkitWebViewMakePolicyDecision(WEBKIT_WEB_VIEW(clientInfo), - WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION, - WEBKIT_POLICY_DECISION(decision.get())); -} - -static void decidePolicyForResponseCallback(WKPageRef page, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo) -{ - GRefPtr<WebKitResponsePolicyDecision> decision = - adoptGRef(webkitResponsePolicyDecisionCreate(toImpl(request), toImpl(response), toImpl(listener))); - webkitWebViewMakePolicyDecision(WEBKIT_WEB_VIEW(clientInfo), - WEBKIT_POLICY_DECISION_TYPE_RESPONSE, - WEBKIT_POLICY_DECISION(decision.get())); -} - -void attachPolicyClientToView(WebKitWebView* webView) -{ - WKPagePolicyClient policyClient = { - kWKPagePolicyClientCurrentVersion, - webView, // clientInfo - decidePolicyForNavigationActionCallback, - decidePolicyForNewWindowActionCallback, - decidePolicyForResponseCallback, - 0, // unableToImplementPolicy - }; - WKPageSetPagePolicyClient(toAPI(webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView))), &policyClient); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyClient.h deleted file mode 100644 index 23dfcbb52..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyClient.h +++ /dev/null @@ -1,27 +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. - */ - -#ifndef WebKitPolicyClient_h -#define WebKitPolicyClient_h - -#include "WebKitWebView.h" - -void attachPolicyClientToView(WebKitWebView*); - -#endif // WebKitPolicyClient_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.cpp deleted file mode 100644 index ee44eaebb..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.cpp +++ /dev/null @@ -1,119 +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 "WebKitPolicyDecision.h" - -#include "WebFramePolicyListenerProxy.h" -#include "WebKitPolicyDecisionPrivate.h" - -using namespace WebKit; - -/** - * SECTION: WebKitPolicyDecision - * @Short_description: A pending policy decision - * @Title: WebKitPolicyDecision - * @See_also: #WebKitWebView - * - * Often WebKit allows the client to decide the policy for certain - * operations. For instance, a client may want to open a link in a new - * tab, block a navigation entirely, query the user or trigger a download - * instead of a navigation. In these cases WebKit will fire the - * #WebKitWebView::decide-policy signal with a #WebKitPolicyDecision - * object. If the signal handler does nothing, WebKit will act as if - * webkit_policy_decision_use() was called as soon as signal handling - * completes. To make a policy decision asynchronously, simply increment - * the reference count of the #WebKitPolicyDecision object. - */ - -struct _WebKitPolicyDecisionPrivate { - RefPtr<WebFramePolicyListenerProxy> listener; - bool madePolicyDecision; -}; - -WEBKIT_DEFINE_ABSTRACT_TYPE(WebKitPolicyDecision, webkit_policy_decision, G_TYPE_OBJECT) - -static void webkitPolicyDecisionDispose(GObject* object) -{ - webkit_policy_decision_use(WEBKIT_POLICY_DECISION(object)); - G_OBJECT_CLASS(webkit_policy_decision_parent_class)->dispose(object); -} - -void webkitPolicyDecisionSetListener(WebKitPolicyDecision* decision, WebFramePolicyListenerProxy* listener) -{ - decision->priv->listener = listener; -} - -static void webkit_policy_decision_class_init(WebKitPolicyDecisionClass* decisionClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(decisionClass); - objectClass->dispose = webkitPolicyDecisionDispose; -} - -/** - * webkit_policy_decision_use: - * @decision: a #WebKitPolicyDecision - * - * Accept the action which triggerd this decision. - */ -void webkit_policy_decision_use(WebKitPolicyDecision* decision) -{ - g_return_if_fail(WEBKIT_IS_POLICY_DECISION(decision)); - - if (decision->priv->madePolicyDecision) - return; - - decision->priv->listener->use(); - decision->priv->madePolicyDecision = true; -} - -/** - * webkit_policy_decision_ignore: - * @decision: a #WebKitPolicyDecision - * - * Ignore the action which triggerd this decision. For instance, for a - * #WebKitResponsePolicyDecision, this would cancel the request. - */ -void webkit_policy_decision_ignore(WebKitPolicyDecision* decision) -{ - g_return_if_fail(WEBKIT_IS_POLICY_DECISION(decision)); - - if (decision->priv->madePolicyDecision) - return; - - decision->priv->listener->ignore(); - decision->priv->madePolicyDecision = true; -} - -/** - * webkit_policy_decision_download: - * @decision: a #WebKitPolicyDecision - * - * Spawn a download from this decision. - */ -void webkit_policy_decision_download(WebKitPolicyDecision* decision) -{ - g_return_if_fail(WEBKIT_IS_POLICY_DECISION(decision)); - - if (decision->priv->madePolicyDecision) - return; - - decision->priv->listener->download(); - decision->priv->madePolicyDecision = true; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h deleted file mode 100644 index f192a1d37..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecision.h +++ /dev/null @@ -1,73 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitPolicyDecision_h -#define WebKitPolicyDecision_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_POLICY_DECISION (webkit_policy_decision_get_type()) -#define WEBKIT_POLICY_DECISION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_POLICY_DECISION, WebKitPolicyDecision)) -#define WEBKIT_POLICY_DECISION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_POLICY_DECISION, WebKitPolicyDecisionClass)) -#define WEBKIT_IS_POLICY_DECISION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_POLICY_DECISION)) -#define WEBKIT_IS_POLICY_DECISION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_POLICY_DECISION)) -#define WEBKIT_POLICY_DECISION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_POLICY_DECISION, WebKitPolicyDecisionClass)) - -typedef struct _WebKitPolicyDecision WebKitPolicyDecision; -typedef struct _WebKitPolicyDecisionClass WebKitPolicyDecisionClass; -typedef struct _WebKitPolicyDecisionPrivate WebKitPolicyDecisionPrivate; - -struct _WebKitPolicyDecision { - GObject parent; - - /*< private >*/ - WebKitPolicyDecisionPrivate *priv; -}; - -struct _WebKitPolicyDecisionClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_policy_decision_get_type (void); - -WEBKIT_API void -webkit_policy_decision_use (WebKitPolicyDecision *decision); - -WEBKIT_API void -webkit_policy_decision_ignore (WebKitPolicyDecision *decision); - -WEBKIT_API void -webkit_policy_decision_download (WebKitPolicyDecision *decision); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecisionPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecisionPrivate.h deleted file mode 100644 index 0af6081ed..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPolicyDecisionPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitPolicyDecisionPrivate_h -#define WebKitPolicyDecisionPrivate_h - -#include "WebKitPolicyDecision.h" -#include "WebKitPrivate.h" - -void webkitPolicyDecisionSetListener(WebKitPolicyDecision*, WebKit::WebFramePolicyListenerProxy*); - -#endif // WebKitResponsePolicyDecisionPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp deleted file mode 100644 index 068a28cdd..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.cpp +++ /dev/null @@ -1,439 +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 "WebKitPrintOperation.h" - -#include "PrintInfo.h" -#include "WebKitPrintOperationPrivate.h" -#include "WebKitPrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebPageProxy.h" -#include <WebCore/GtkUtilities.h> -#include <WebCore/NotImplemented.h> -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -#ifdef HAVE_GTK_UNIX_PRINTING -#include <gtk/gtkunixprint.h> -#endif - -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, - - PROP_WEB_VIEW, - PROP_PRINT_SETTINGS, - PROP_PAGE_SETUP -}; - -enum { - FINISHED, - FAILED, - - LAST_SIGNAL -}; - -struct _WebKitPrintOperationPrivate { - ~_WebKitPrintOperationPrivate() - { - g_signal_handler_disconnect(webView, webViewDestroyedId); - } - - WebKitWebView* webView; - gulong webViewDestroyedId; - - GRefPtr<GtkPrintSettings> printSettings; - GRefPtr<GtkPageSetup> pageSetup; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitPrintOperation, webkit_print_operation, G_TYPE_OBJECT) - -static void webViewDestroyed(GtkWidget* webView, GObject* printOperation) -{ - g_object_unref(printOperation); -} - -static void webkitPrintOperationConstructed(GObject* object) -{ - WebKitPrintOperation* printOperation = WEBKIT_PRINT_OPERATION(object); - WebKitPrintOperationPrivate* priv = printOperation->priv; - - if (G_OBJECT_CLASS(webkit_print_operation_parent_class)->constructed) - G_OBJECT_CLASS(webkit_print_operation_parent_class)->constructed(object); - - priv->webViewDestroyedId = g_signal_connect(priv->webView, "destroy", G_CALLBACK(webViewDestroyed), printOperation); -} - -static void webkitPrintOperationGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitPrintOperation* printOperation = WEBKIT_PRINT_OPERATION(object); - - switch (propId) { - case PROP_WEB_VIEW: - g_value_take_object(value, printOperation->priv->webView); - break; - case PROP_PRINT_SETTINGS: - g_value_set_object(value, printOperation->priv->printSettings.get()); - break; - case PROP_PAGE_SETUP: - g_value_set_object(value, printOperation->priv->pageSetup.get()); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkitPrintOperationSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) -{ - WebKitPrintOperation* printOperation = WEBKIT_PRINT_OPERATION(object); - - switch (propId) { - case PROP_WEB_VIEW: - printOperation->priv->webView = WEBKIT_WEB_VIEW(g_value_get_object(value)); - break; - case PROP_PRINT_SETTINGS: - webkit_print_operation_set_print_settings(printOperation, GTK_PRINT_SETTINGS(g_value_get_object(value))); - break; - case PROP_PAGE_SETUP: - webkit_print_operation_set_page_setup(printOperation, GTK_PAGE_SETUP(g_value_get_object(value))); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_print_operation_class_init(WebKitPrintOperationClass* printOperationClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(printOperationClass); - gObjectClass->constructed = webkitPrintOperationConstructed; - gObjectClass->get_property = webkitPrintOperationGetProperty; - gObjectClass->set_property = webkitPrintOperationSetProperty; - - /** - * WebKitPrintOperation:web-view: - * - * The #WebKitWebView that will be printed. - */ - g_object_class_install_property(gObjectClass, - PROP_WEB_VIEW, - g_param_spec_object("web-view", - _("Web View"), - _("The web view that will be printed"), - WEBKIT_TYPE_WEB_VIEW, - static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY))); - - /** - * WebKitPrintOperation:print-settings: - * - * The initial #GtkPrintSettings for the print operation. - */ - g_object_class_install_property(gObjectClass, - PROP_PRINT_SETTINGS, - g_param_spec_object("print-settings", - _("Print Settings"), - _("The initial print settings for the print operation"), - GTK_TYPE_PRINT_SETTINGS, - WEBKIT_PARAM_READWRITE)); - /** - * WebKitPrintOperation:page-setup: - * - * The initial #GtkPageSetup for the print operation. - */ - g_object_class_install_property(gObjectClass, - PROP_PAGE_SETUP, - g_param_spec_object("page-setup", - _("Page Setup"), - _("The initial page setup for the print operation"), - GTK_TYPE_PAGE_SETUP, - WEBKIT_PARAM_READWRITE)); - - /** - * WebKitPrintOperation::finished: - * @print_operation: the #WebKitPrintOperation on which the signal was emitted - * - * Emitted when the print operation has finished doing everything - * required for printing. - */ - signals[FINISHED] = - g_signal_new("finished", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitPrintOperation::failed: - * @print_operation: the #WebKitPrintOperation on which the signal was emitted - * @error: the #GError that was triggered - * - * Emitted when an error occurs while printing. The given @error, of the domain - * %WEBKIT_PRINT_ERROR, contains further details of the failure. - * The #WebKitPrintOperation::finished signal is emitted after this one. - */ - signals[FAILED] = - g_signal_new("failed", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__POINTER, - G_TYPE_NONE, 1, - G_TYPE_POINTER); -} - -#ifdef HAVE_GTK_UNIX_PRINTING -static WebKitPrintOperationResponse webkitPrintOperationRunDialog(WebKitPrintOperation* printOperation, GtkWindow* parent) -{ - GtkPrintUnixDialog* printDialog = GTK_PRINT_UNIX_DIALOG(gtk_print_unix_dialog_new(0, parent)); - gtk_print_unix_dialog_set_manual_capabilities(printDialog, static_cast<GtkPrintCapabilities>(GTK_PRINT_CAPABILITY_NUMBER_UP - | GTK_PRINT_CAPABILITY_NUMBER_UP_LAYOUT - | GTK_PRINT_CAPABILITY_PAGE_SET - | GTK_PRINT_CAPABILITY_REVERSE - | GTK_PRINT_CAPABILITY_COPIES - | GTK_PRINT_CAPABILITY_COLLATE - | GTK_PRINT_CAPABILITY_SCALE)); - - WebKitPrintOperationPrivate* priv = printOperation->priv; - if (priv->printSettings) - gtk_print_unix_dialog_set_settings(printDialog, priv->printSettings.get()); - - if (priv->pageSetup) - gtk_print_unix_dialog_set_page_setup(printDialog, priv->pageSetup.get()); - - gtk_print_unix_dialog_set_embed_page_setup(printDialog, TRUE); - - WebKitPrintOperationResponse returnValue = WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL; - if (gtk_dialog_run(GTK_DIALOG(printDialog)) == GTK_RESPONSE_OK) { - priv->printSettings = adoptGRef(gtk_print_unix_dialog_get_settings(printDialog)); - priv->pageSetup = gtk_print_unix_dialog_get_page_setup(printDialog); - returnValue = WEBKIT_PRINT_OPERATION_RESPONSE_PRINT; - } - - gtk_widget_destroy(GTK_WIDGET(printDialog)); - - return returnValue; -} -#else -// TODO: We need to add an implementation for Windows. -static WebKitPrintOperationResponse webkitPrintOperationRunDialog(WebKitPrintOperation*, GtkWindow*) -{ - notImplemented(); - return WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL; -} -#endif - -static void drawPagesForPrintingCompleted(WKErrorRef wkPrintError, WKErrorRef, void* context) -{ - GRefPtr<WebKitPrintOperation> printOperation = adoptGRef(WEBKIT_PRINT_OPERATION(context)); - WebPageProxy* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(printOperation->priv->webView)); - page->endPrinting(); - - const WebCore::ResourceError& resourceError = toImpl(wkPrintError)->platformError(); - if (!resourceError.isNull()) { - GOwnPtr<GError> printError(g_error_new_literal(g_quark_from_string(resourceError.domain().utf8().data()), - resourceError.errorCode(), - resourceError.localizedDescription().utf8().data())); - g_signal_emit(printOperation.get(), signals[FAILED], 0, printError.get()); - } - g_signal_emit(printOperation.get(), signals[FINISHED], 0, NULL); -} - -static void webkitPrintOperationPrintPagesForFrame(WebKitPrintOperation* printOperation, WebFrameProxy* webFrame, GtkPrintSettings* printSettings, GtkPageSetup* pageSetup) -{ - PrintInfo printInfo(printSettings, pageSetup); - WebPageProxy* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(printOperation->priv->webView)); - page->drawPagesForPrinting(webFrame, printInfo, PrintFinishedCallback::create(g_object_ref(printOperation), &drawPagesForPrintingCompleted)); -} - -WebKitPrintOperationResponse webkitPrintOperationRunDialogForFrame(WebKitPrintOperation* printOperation, GtkWindow* parent, WebFrameProxy* webFrame) -{ - WebKitPrintOperationPrivate* priv = printOperation->priv; - if (!parent) { - GtkWidget* toplevel = gtk_widget_get_toplevel(GTK_WIDGET(priv->webView)); - if (WebCore::widgetIsOnscreenToplevelWindow(toplevel)) - parent = GTK_WINDOW(toplevel); - } - - WebKitPrintOperationResponse response = webkitPrintOperationRunDialog(printOperation, parent); - if (response == WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL) - return response; - - webkitPrintOperationPrintPagesForFrame(printOperation, webFrame, priv->printSettings.get(), priv->pageSetup.get()); - return response; -} - -/** - * webkit_print_operation_new: - * @web_view: a #WebKitWebView - * - * Create a new #WebKitPrintOperation to print @web_view contents. - * - * Returns: (transfer full): a new #WebKitPrintOperation. - */ -WebKitPrintOperation* webkit_print_operation_new(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return WEBKIT_PRINT_OPERATION(g_object_new(WEBKIT_TYPE_PRINT_OPERATION, "web-view", webView, NULL)); -} - -/** - * webkit_print_operation_get_print_settings: - * @print_operation: a #WebKitPrintOperation - * - * Return the current print settings of @print_operation. It returns %NULL until - * either webkit_print_operation_set_print_settings() or webkit_print_operation_run_dialog() - * have been called. - * - * Returns: (transfer none): the current #GtkPrintSettings of @print_operation. - */ -GtkPrintSettings* webkit_print_operation_get_print_settings(WebKitPrintOperation* printOperation) -{ - g_return_val_if_fail(WEBKIT_IS_PRINT_OPERATION(printOperation), 0); - - return printOperation->priv->printSettings.get(); -} - -/** - * webkit_print_operation_set_print_settings: - * @print_operation: a #WebKitPrintOperation - * @print_settings: a #GtkPrintSettings to set - * - * Set the current print settings of @print_operation. Current print settings are used for - * the initial values of the print dialog when webkit_print_operation_run_dialog() is called. - */ -void webkit_print_operation_set_print_settings(WebKitPrintOperation* printOperation, GtkPrintSettings* printSettings) -{ - g_return_if_fail(WEBKIT_IS_PRINT_OPERATION(printOperation)); - g_return_if_fail(GTK_IS_PRINT_SETTINGS(printSettings)); - - if (printOperation->priv->printSettings.get() == printSettings) - return; - - printOperation->priv->printSettings = printSettings; - g_object_notify(G_OBJECT(printOperation), "print-settings"); -} - -/** - * webkit_print_operation_get_page_setup: - * @print_operation: a #WebKitPrintOperation - * - * Return the current page setup of @print_operation. It returns %NULL until - * either webkit_print_operation_set_print_settings() or webkit_print_operation_run_dialog() - * have been called. - * - * Returns: (transfer none): the current #GtkPageSetup of @print_operation. - */ -GtkPageSetup* webkit_print_operation_get_page_setup(WebKitPrintOperation* printOperation) -{ - g_return_val_if_fail(WEBKIT_IS_PRINT_OPERATION(printOperation), 0); - - return printOperation->priv->pageSetup.get(); -} - -/** - * webkit_print_operation_set_page_setup: - * @print_operation: a #WebKitPrintOperation - * @page_setup: a #GtkPageSetup to set - * - * Set the current page setup of @print_operation. Current page setup is used for the - * initial values of the print dialog when webkit_print_operation_run_dialog() is called. - */ -void webkit_print_operation_set_page_setup(WebKitPrintOperation* printOperation, GtkPageSetup* pageSetup) -{ - g_return_if_fail(WEBKIT_IS_PRINT_OPERATION(printOperation)); - g_return_if_fail(GTK_IS_PAGE_SETUP(pageSetup)); - - if (printOperation->priv->pageSetup.get() == pageSetup) - return; - - printOperation->priv->pageSetup = pageSetup; - g_object_notify(G_OBJECT(printOperation), "page-setup"); -} - -/** - * webkit_print_operation_run_dialog: - * @print_operation: a #WebKitPrintOperation - * @parent: (allow-none): transient parent of the print dialog - * - * Run the print dialog and start printing using the options selected by - * the user. This method returns when the print dialog is closed. - * If the print dialog is cancelled %WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL - * is returned. If the user clicks on the print button, %WEBKIT_PRINT_OPERATION_RESPONSE_PRINT - * is returned and the print operation starts. In this case, the #WebKitPrintOperation::finished - * signal is emitted when the operation finishes. If an error occurs while printing, the signal - * #WebKitPrintOperation::failed is emitted before #WebKitPrintOperation::finished. - * If the print dialog is not cancelled current print settings and page setup of @print_operation - * are updated with options selected by the user when Print button is pressed in print dialog. - * You can get the updated print settings and page setup by calling - * webkit_print_operation_get_print_settings() and webkit_print_operation_get_page_setup() - * after this method. - * - * Returns: the #WebKitPrintOperationResponse of the print dialog - */ -WebKitPrintOperationResponse webkit_print_operation_run_dialog(WebKitPrintOperation* printOperation, GtkWindow* parent) -{ - g_return_val_if_fail(WEBKIT_IS_PRINT_OPERATION(printOperation), WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL); - - WebPageProxy* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(printOperation->priv->webView)); - return webkitPrintOperationRunDialogForFrame(printOperation, parent, page->mainFrame()); -} - -/** - * webkit_print_operation_print: - * @print_operation: a #WebKitPrintOperation - * - * Start a print operation using current print settings and page setup - * without showing the print dialog. If either print settings or page setup - * are not set with webkit_print_operation_set_print_settings() and - * webkit_print_operation_set_page_setup(), the default options will be used - * and the print job will be sent to the default printer. - * The #WebKitPrintOperation::finished signal is emitted when the printing - * operation finishes. If an error occurs while printing the signal - * #WebKitPrintOperation::failed is emitted before #WebKitPrintOperation::finished. - */ -void webkit_print_operation_print(WebKitPrintOperation* printOperation) -{ - g_return_if_fail(WEBKIT_IS_PRINT_OPERATION(printOperation)); - - WebKitPrintOperationPrivate* priv = printOperation->priv; - GRefPtr<GtkPrintSettings> printSettings = priv->printSettings ? priv->printSettings : adoptGRef(gtk_print_settings_new()); - GRefPtr<GtkPageSetup> pageSetup = priv->pageSetup ? priv->pageSetup : adoptGRef(gtk_page_setup_new()); - - WebPageProxy* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(printOperation->priv->webView)); - webkitPrintOperationPrintPagesForFrame(printOperation, page->mainFrame(), printSettings.get(), pageSetup.get()); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h deleted file mode 100644 index b7159b8c6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperation.h +++ /dev/null @@ -1,101 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitPrintOperation_h -#define WebKitPrintOperation_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitForwardDeclarations.h> -#include <webkit2/WebKitWebView.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_PRINT_OPERATION (webkit_print_operation_get_type()) -#define WEBKIT_PRINT_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_PRINT_OPERATION, WebKitPrintOperation)) -#define WEBKIT_IS_PRINT_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_PRINT_OPERATION)) -#define WEBKIT_PRINT_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_PRINT_OPERATION, WebKitPrintOperationClass)) -#define WEBKIT_IS_PRINT_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_PRINT_OPERATION)) -#define WEBKIT_PRINT_OPERATION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_PRINT_OPERATION, WebKitPrintOperationClass)) - -typedef struct _WebKitPrintOperationClass WebKitPrintOperationClass; -typedef struct _WebKitPrintOperationPrivate WebKitPrintOperationPrivate; - -/** - * WebKitPrintOperationResponse: - * @WEBKIT_PRINT_OPERATION_RESPONSE_PRINT: Print button was cliked in print dialog - * @WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL: Print dialog was cancelled - * - * Enum values representing the response of the print dialog shown with - * webkit_print_operation_run_dialog(). - */ -typedef enum { - WEBKIT_PRINT_OPERATION_RESPONSE_PRINT, - WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL -} WebKitPrintOperationResponse; - -struct _WebKitPrintOperation { - GObject parent; - - WebKitPrintOperationPrivate *priv; -}; - -struct _WebKitPrintOperationClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_print_operation_get_type (void); - -WEBKIT_API WebKitPrintOperation * -webkit_print_operation_new (WebKitWebView *web_view); - -WEBKIT_API GtkPrintSettings * -webkit_print_operation_get_print_settings (WebKitPrintOperation *print_operation); - -WEBKIT_API void -webkit_print_operation_set_print_settings (WebKitPrintOperation *print_operation, - GtkPrintSettings *print_settings); - -WEBKIT_API GtkPageSetup * -webkit_print_operation_get_page_setup (WebKitPrintOperation *print_operation); - -WEBKIT_API void -webkit_print_operation_set_page_setup (WebKitPrintOperation *print_operation, - GtkPageSetup *page_setup); - -WEBKIT_API WebKitPrintOperationResponse -webkit_print_operation_run_dialog (WebKitPrintOperation *print_operation, - GtkWindow *parent); - -WEBKIT_API void -webkit_print_operation_print (WebKitPrintOperation *print_operation); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperationPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperationPrivate.h deleted file mode 100644 index 7a4fb4e43..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrintOperationPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitPrintOperationPrivate_h -#define WebKitPrintOperationPrivate_h - -#include "WebFrameProxy.h" -#include "WebKitPrintOperation.h" - -WebKitPrintOperationResponse webkitPrintOperationRunDialogForFrame(WebKitPrintOperation*, GtkWindow* parent, WebKit::WebFrameProxy*); - -#endif // WebKitPrintOperationPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.cpp deleted file mode 100644 index d34b9c471..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.cpp +++ /dev/null @@ -1,53 +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 "WebKitPrivate.h" - -#include <gdk/gdk.h> - -unsigned wkEventModifiersToGdkModifiers(WKEventModifiers wkModifiers) -{ - unsigned modifiers = 0; - if (wkModifiers & kWKEventModifiersShiftKey) - modifiers |= GDK_SHIFT_MASK; - if (wkModifiers & kWKEventModifiersControlKey) - modifiers |= GDK_CONTROL_MASK; - if (wkModifiers & kWKEventModifiersAltKey) - modifiers |= GDK_MOD1_MASK; - if (wkModifiers & kWKEventModifiersMetaKey) - modifiers |= GDK_META_MASK; - return modifiers; -} - -unsigned wkEventMouseButtonToWebKitMouseButton(WKEventMouseButton wkButton) -{ - switch (wkButton) { - case kWKEventMouseButtonNoButton: - return 0; - case kWKEventMouseButtonLeftButton: - return 1; - case kWKEventMouseButtonMiddleButton: - return 2; - case kWKEventMouseButtonRightButton: - return 3; - } - ASSERT_NOT_REACHED(); - return 0; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h deleted file mode 100644 index 83904ad9a..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitPrivate.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef WebKitPrivate_h -#define WebKitPrivate_h - -#include <WebKit2/WKAPICast.h> -#include <WebKit2/WKContextSoup.h> -#include <WebKit2/WKDownload.h> -#include <WebKit2/WKFindOptions.h> -#include <WebKit2/WKFullScreenClientGtk.h> -#include <WebKit2/WKGeolocationManager.h> -#include <WebKit2/WKGeolocationPermissionRequest.h> -#include <WebKit2/WKGeolocationPosition.h> -#include <WebKit2/WKIconDatabase.h> -#include <WebKit2/WKInspector.h> -#include <WebKit2/WKInspectorClientGtk.h> -#include <WebKit2/WKRetainPtr.h> -#include <WebKit2/WKSerializedScriptValue.h> -#include <WebKit2/WKSoupRequestManager.h> -#include <WebKit2/WKString.h> -#include <WebKit2/WKTextChecker.h> -#include <WebKit2/WebKit2_C.h> -#include <glib.h> -#include <wtf/Assertions.h> - -#define WEBKIT_PARAM_READABLE (static_cast<GParamFlags>(G_PARAM_READABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)) -#define WEBKIT_PARAM_WRITABLE (static_cast<GParamFlags>(G_PARAM_WRITABLE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)) -#define WEBKIT_PARAM_READWRITE (static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)) - -#define COMPILE_ASSERT_MATCHING_ENUM(webkitName, webcoreName) \ - COMPILE_ASSERT(int(webkitName) == int(webcoreName), mismatchingEnums) - -#define WEBKIT_DEFINE_ASYNC_DATA_STRUCT(structName) \ -static structName* create##structName() \ -{ \ - structName* data = g_slice_new0(structName); \ - new (data) structName(); \ - return data; \ -} \ -static void destroy##structName(structName* data) \ -{ \ - data->~structName(); \ - g_slice_free(structName, data); \ -} - -#define WEBKIT_DEFINE_TYPE(TypeName, type_name, TYPE_PARENT) _WEBKIT_DEFINE_TYPE_EXTENDED(TypeName, type_name, TYPE_PARENT, 0, { }) -#define WEBKIT_DEFINE_ABSTRACT_TYPE(TypeName, type_name, TYPE_PARENT) _WEBKIT_DEFINE_TYPE_EXTENDED(TypeName, type_name, TYPE_PARENT, G_TYPE_FLAG_ABSTRACT, { }) -#define WEBKIT_DEFINE_TYPE_WITH_CODE(TypeName, type_name, TYPE_PARENT, Code) _WEBKIT_DEFINE_TYPE_EXTENDED_BEGIN(TypeName, type_name, TYPE_PARENT, 0) {Code;} _WEBKIT_DEFINE_TYPE_EXTENDED_END() - -#define _WEBKIT_DEFINE_TYPE_EXTENDED(TypeName, type_name, TYPE_PARENT, flags, Code) _WEBKIT_DEFINE_TYPE_EXTENDED_BEGIN(TypeName, type_name, TYPE_PARENT, flags) {Code;} _WEBKIT_DEFINE_TYPE_EXTENDED_END() -#define _WEBKIT_DEFINE_TYPE_EXTENDED_BEGIN(TypeName, type_name, TYPE_PARENT, flags) \ -\ -static void type_name##_class_init(TypeName##Class* klass); \ -static gpointer type_name##_parent_class = 0; \ -static void type_name##_finalize(GObject* object) \ -{ \ - TypeName* self = (TypeName*)object; \ - self->priv->~TypeName##Private(); \ - G_OBJECT_CLASS(type_name##_parent_class)->finalize(object); \ -} \ -\ -static void type_name##_class_intern_init(gpointer klass) \ -{ \ - GObjectClass* gObjectClass = G_OBJECT_CLASS(klass); \ - g_type_class_add_private(klass, sizeof(TypeName##Private)); \ - type_name##_parent_class = g_type_class_peek_parent(klass); \ - type_name##_class_init((TypeName##Class*)klass); \ - gObjectClass->finalize = type_name##_finalize; \ -} \ -\ -static void type_name##_init(TypeName* self) \ -{ \ - TypeName##Private* priv = G_TYPE_INSTANCE_GET_PRIVATE(self, type_name##_get_type(), TypeName##Private); \ - self->priv = priv; \ - new (priv) TypeName##Private(); \ -}\ -GType type_name##_get_type(void) \ -{ \ - static volatile gsize g_define_type_id__volatile = 0; \ - if (g_once_init_enter(&g_define_type_id__volatile)) { \ - GType g_define_type_id = \ - g_type_register_static_simple( \ - TYPE_PARENT, \ - g_intern_static_string(#TypeName), \ - sizeof(TypeName##Class), \ - (GClassInitFunc)type_name##_class_intern_init, \ - sizeof(TypeName), \ - (GInstanceInitFunc)type_name##_init, \ - (GTypeFlags)flags); \ - // Custom code follows. -#define _WEBKIT_DEFINE_TYPE_EXTENDED_END() \ - g_once_init_leave(&g_define_type_id__volatile, g_define_type_id); \ - } \ - return g_define_type_id__volatile; \ -} // Closes type_name##_get_type(). - -unsigned wkEventModifiersToGdkModifiers(WKEventModifiers); -unsigned wkEventMouseButtonToWebKitMouseButton(WKEventMouseButton); - -enum SnapshotRegion { - SnapshotRegionVisible, - SnapshotRegionFullDocument -}; - -#endif // WebKitPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitRequestManagerClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitRequestManagerClient.cpp deleted file mode 100644 index 3bb2434ce..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitRequestManagerClient.cpp +++ /dev/null @@ -1,51 +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 "WebKitRequestManagerClient.h" - -#include "WebKitURISchemeRequestPrivate.h" -#include "WebKitWebContextPrivate.h" -#include <wtf/gobject/GRefPtr.h> - -using namespace WebKit; - -static void didReceiveURIRequest(WKSoupRequestManagerRef soupRequestManagerRef, WKURLRef urlRef, WKPageRef initiatingPageRef, uint64_t requestID, const void* clientInfo) -{ - WebKitWebContext* webContext = WEBKIT_WEB_CONTEXT(clientInfo); - GRefPtr<WebKitURISchemeRequest> request = adoptGRef(webkitURISchemeRequestCreate(webContext, toImpl(soupRequestManagerRef), toImpl(urlRef), toImpl(initiatingPageRef), requestID)); - webkitWebContextReceivedURIRequest(webContext, request.get()); -} - -static void didFailToLoadURIRequest(WKSoupRequestManagerRef, uint64_t requestID, const void* clientInfo) -{ - webkitWebContextDidFailToLoadURIRequest(WEBKIT_WEB_CONTEXT(clientInfo), requestID); -} - -void attachRequestManagerClientToContext(WebKitWebContext* webContext) -{ - WKSoupRequestManagerClient wkRequestManagerClient = { - kWKSoupRequestManagerClientCurrentVersion, - webContext, // clientInfo - didReceiveURIRequest, - didFailToLoadURIRequest - }; - WKSoupRequestManagerSetClient(toAPI(webkitWebContextGetRequestManager(webContext)), &wkRequestManagerClient); -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitRequestManagerClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitRequestManagerClient.h deleted file mode 100644 index a365594f8..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitRequestManagerClient.h +++ /dev/null @@ -1,27 +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. - */ - -#ifndef WebKitRequestManagerClient_h -#define WebKitRequestManagerClient_h - -#include "WebKitWebContext.h" - -void attachRequestManagerClientToContext(WebKitWebContext*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.cpp deleted file mode 100644 index 3a75e38c9..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.cpp +++ /dev/null @@ -1,147 +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 "WebKitResponsePolicyDecision.h" - -#include "WebKitPolicyDecisionPrivate.h" -#include "WebKitPrivate.h" -#include "WebKitURIRequestPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include "WebURLRequest.h" -#include "WebURLResponse.h" -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -using namespace WebKit; - -/** - * SECTION: WebKitResponsePolicyDecision - * @Short_description: A policy decision for resource responses - * @Title: WebKitResponsePolicyDecision - * @See_also: #WebKitPolicyDecision, #WebKitWebView - * - * WebKitResponsePolicyDecision represents a policy decision for a - * resource response, whether from the network or the local system. - * A very common usecase for these types of decision is deciding - * whether or not to download a particular resource or to load it - * normally. - */ - -struct _WebKitResponsePolicyDecisionPrivate { - GRefPtr<WebKitURIRequest> request; - GRefPtr<WebKitURIResponse> response; -}; - -WEBKIT_DEFINE_TYPE(WebKitResponsePolicyDecision, webkit_response_policy_decision, WEBKIT_TYPE_POLICY_DECISION) - -enum { - PROP_0, - PROP_REQUEST, - PROP_RESPONSE, -}; - -static void webkitResponsePolicyDecisionGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitResponsePolicyDecision* decision = WEBKIT_RESPONSE_POLICY_DECISION(object); - switch (propId) { - case PROP_REQUEST: - g_value_set_object(value, webkit_response_policy_decision_get_request(decision)); - break; - case PROP_RESPONSE: - g_value_set_object(value, webkit_response_policy_decision_get_response(decision)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - break; - } -} - -static void webkit_response_policy_decision_class_init(WebKitResponsePolicyDecisionClass* decisionClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(decisionClass); - objectClass->get_property = webkitResponsePolicyDecisionGetProperty; - - /** - * WebKitResponsePolicyDecision:request: - * - * This property contains the #WebKitURIRequest associated with this - * policy decision. - */ - g_object_class_install_property(objectClass, - PROP_REQUEST, - g_param_spec_object("request", - _("Response URI request"), - _("The URI request that is associated with this policy decision"), - WEBKIT_TYPE_URI_REQUEST, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitResponsePolicyDecision:response: - * - * This property contains the #WebKitURIResponse associated with this - * policy decision. - */ - g_object_class_install_property(objectClass, - PROP_REQUEST, - g_param_spec_object("response", - _("URI response"), - _("The URI response that is associated with this policy decision"), - WEBKIT_TYPE_URI_REQUEST, - WEBKIT_PARAM_READABLE)); - -} - -/** - * webkit_response_policy_decision_get_request: - * @decision: a #WebKitResponsePolicyDecision - * - * Gets the value of the #WebKitResponsePolicyDecision:request property. - * - * Returns: (transfer none): The URI request that is associated with this policy decision. - */ -WebKitURIRequest* webkit_response_policy_decision_get_request(WebKitResponsePolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_RESPONSE_POLICY_DECISION(decision), 0); - return decision->priv->request.get(); -} - -/** - * webkit_response_policy_decision_get_response: - * @decision: a #WebKitResponsePolicyDecision - * - * Gets the value of the #WebKitResponsePolicyDecision:response property. - * - * Returns: (transfer none): The URI response that is associated with this policy decision. - */ -WebKitURIResponse* webkit_response_policy_decision_get_response(WebKitResponsePolicyDecision* decision) -{ - g_return_val_if_fail(WEBKIT_IS_RESPONSE_POLICY_DECISION(decision), 0); - return decision->priv->response.get(); -} - -WebKitResponsePolicyDecision* webkitResponsePolicyDecisionCreate(WebURLRequest* request, WebURLResponse* response, WebFramePolicyListenerProxy* listener) -{ - WebKitResponsePolicyDecision* decision = WEBKIT_RESPONSE_POLICY_DECISION(g_object_new(WEBKIT_TYPE_RESPONSE_POLICY_DECISION, NULL)); - decision->priv->request = adoptGRef(webkitURIRequestCreateForResourceRequest(request->resourceRequest())); - decision->priv->response = adoptGRef(webkitURIResponseCreateForResourceResponse(response->resourceResponse())); - webkitPolicyDecisionSetListener(WEBKIT_POLICY_DECISION(decision), listener); - return decision; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h b/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h deleted file mode 100644 index 4a689fbc7..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecision.h +++ /dev/null @@ -1,73 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitResponsePolicyDecision_h -#define WebKitResponsePolicyDecision_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitPolicyDecision.h> -#include <webkit2/WebKitURIResponse.h> -#include <webkit2/WebKitURIRequest.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_RESPONSE_POLICY_DECISION (webkit_response_policy_decision_get_type()) -#define WEBKIT_RESPONSE_POLICY_DECISION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_RESPONSE_POLICY_DECISION, WebKitResponsePolicyDecision)) -#define WEBKIT_RESPONSE_POLICY_DECISION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_RESPONSE_POLICY_DECISION, WebKitResponsePolicyDecisionClass)) -#define WEBKIT_IS_RESPONSE_POLICY_DECISION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_RESPONSE_POLICY_DECISION)) -#define WEBKIT_IS_RESPONSE_POLICY_DECISION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_RESPONSE_POLICY_DECISION)) -#define WEBKIT_RESPONSE_POLICY_DECISION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_RESPONSE_POLICY_DECISION, WebKitResponsePolicyDecisionClass)) - -typedef struct _WebKitResponsePolicyDecision WebKitResponsePolicyDecision; -typedef struct _WebKitResponsePolicyDecisionClass WebKitResponsePolicyDecisionClass; -typedef struct _WebKitResponsePolicyDecisionPrivate WebKitResponsePolicyDecisionPrivate; - -struct _WebKitResponsePolicyDecision { - WebKitPolicyDecision parent; - - /*< private >*/ - WebKitResponsePolicyDecisionPrivate *priv; -}; - -struct _WebKitResponsePolicyDecisionClass { - WebKitPolicyDecisionClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_response_policy_decision_get_type (void); - -WEBKIT_API WebKitURIRequest * -webkit_response_policy_decision_get_request (WebKitResponsePolicyDecision *decision); - -WEBKIT_API WebKitURIResponse * -webkit_response_policy_decision_get_response (WebKitResponsePolicyDecision *decision); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecisionPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecisionPrivate.h deleted file mode 100644 index 3e7e59e65..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitResponsePolicyDecisionPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitResponsePolicyDecisionPrivate_h -#define WebKitResponsePolicyDecisionPrivate_h - -#include "WebKitPrivate.h" -#include "WebKitResponsePolicyDecision.h" - -WebKitResponsePolicyDecision* webkitResponsePolicyDecisionCreate(WebKit::WebURLRequest*, WebKit::WebURLResponse*, WebKit::WebFramePolicyListenerProxy*); - -#endif // WebKitResponsePolicyDecisionPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialog.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialog.cpp deleted file mode 100644 index 863665d71..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialog.cpp +++ /dev/null @@ -1,126 +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 "WebKitScriptDialog.h" - -#include "WebKitScriptDialogPrivate.h" - -static WebKitScriptDialog* webkitScriptDialogCopy(WebKitScriptDialog* dialog) -{ - WebKitScriptDialog* copy = g_slice_new0(WebKitScriptDialog); - new (copy) WebKitScriptDialog(dialog); - return copy; -} - -static void webkitScriptDialogFree(WebKitScriptDialog* dialog) -{ - dialog->~WebKitScriptDialog(); - g_slice_free(WebKitScriptDialog, dialog); -} - -G_DEFINE_BOXED_TYPE(WebKitScriptDialog, webkit_script_dialog, webkitScriptDialogCopy, webkitScriptDialogFree) - -/** - * webkit_script_dialog_get_dialog_type: - * @dialog: a #WebKitScriptDialog - * - * Get the dialog type of a #WebKitScriptDialog. - * - * Returns: the #WebKitScriptDialogType of @dialog - */ -WebKitScriptDialogType webkit_script_dialog_get_dialog_type(WebKitScriptDialog* dialog) -{ - g_return_val_if_fail(dialog, WEBKIT_SCRIPT_DIALOG_ALERT); - - return static_cast<WebKitScriptDialogType>(dialog->type); -} - -/** - * webkit_script_dialog_get_message: - * @dialog: a #WebKitScriptDialog - * - * Get the message of a #WebKitScriptDialog. - * - * Returns: the message of @dialog. - */ -const char* webkit_script_dialog_get_message(WebKitScriptDialog* dialog) -{ - g_return_val_if_fail(dialog, 0); - - return dialog->message.data(); -} - -/** - * webkit_script_dialog_confirm_set_confirmed: - * @dialog: a #WebKitScriptDialog - * @confirmed: whether user confirmed the dialog - * - * This method is used for %WEBKIT_SCRIPT_DIALOG_CONFIRM dialogs when - * #WebKitWebView::script-dialog signal is emitted to set whether the user - * confirmed the dialog or not. The default implementation of #WebKitWebView::script-dialog - * signal sets %TRUE when the OK button is clicked and %FALSE otherwise. - * It's an error to use this method with a #WebKitScriptDialog that is not of type - * %WEBKIT_SCRIPT_DIALOG_CONFIRM. - */ -void webkit_script_dialog_confirm_set_confirmed(WebKitScriptDialog* dialog, gboolean confirmed) -{ - g_return_if_fail(dialog); - g_return_if_fail(dialog->type == WEBKIT_SCRIPT_DIALOG_CONFIRM); - - dialog->confirmed = confirmed; -} - -/** - * webkit_script_dialog_prompt_get_default_text: - * @dialog: a #WebKitScriptDialog - * - * Get the default text of a #WebKitScriptDialog of type %WEBKIT_SCRIPT_DIALOG_PROMPT. - * It's an error to use this method with a #WebKitScriptDialog that is not of type - * %WEBKIT_SCRIPT_DIALOG_PROMPT. - * - * Returns: the default text of @dialog - */ -const char* webkit_script_dialog_prompt_get_default_text(WebKitScriptDialog* dialog) -{ - g_return_val_if_fail(dialog, 0); - g_return_val_if_fail(dialog->type == WEBKIT_SCRIPT_DIALOG_PROMPT, 0); - - return dialog->defaultText.data(); -} - -/** - * webkit_script_dialog_prompt_set_text: - * @dialog: a #WebKitScriptDialog - * @text: the text to set - * - * This method is used for %WEBKIT_SCRIPT_DIALOG_PROMPT dialogs when - * #WebKitWebView::script-dialog signal is emitted to set the text - * entered by the user. The default implementation of #WebKitWebView::script-dialog - * signal sets the text of the entry form when OK button is clicked, otherwise %NULL is set. - * It's an error to use this method with a #WebKitScriptDialog that is not of type - * %WEBKIT_SCRIPT_DIALOG_PROMPT. - */ -void webkit_script_dialog_prompt_set_text(WebKitScriptDialog* dialog, const char* text) -{ - g_return_if_fail(dialog); - g_return_if_fail(dialog->type == WEBKIT_SCRIPT_DIALOG_PROMPT); - - dialog->text = text; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialog.h b/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialog.h deleted file mode 100644 index cf88535ad..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialog.h +++ /dev/null @@ -1,75 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitScriptDialog_h -#define WebKitScriptDialog_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_SCRIPT_DIALOG (webkit_script_dialog_get_type()) - -typedef struct _WebKitScriptDialog WebKitScriptDialog; - -/** - * WebKitScriptDialogType: - * @WEBKIT_SCRIPT_DIALOG_ALERT: Alert script dialog, used to show a - * message to the user. - * @WEBKIT_SCRIPT_DIALOG_CONFIRM: Confirm script dialog, used to ask - * confirmation to the user. - * @WEBKIT_SCRIPT_DIALOG_PROMPT: Prompt script dialog, used to ask - * information to the user. - * - * Enum values used for determining the type of #WebKitScriptDialog - */ -typedef enum { - WEBKIT_SCRIPT_DIALOG_ALERT, - WEBKIT_SCRIPT_DIALOG_CONFIRM, - WEBKIT_SCRIPT_DIALOG_PROMPT -} WebKitScriptDialogType; - -WEBKIT_API GType -webkit_script_dialog_get_type (void); - -WEBKIT_API WebKitScriptDialogType -webkit_script_dialog_get_dialog_type (WebKitScriptDialog *dialog); - -WEBKIT_API const gchar * -webkit_script_dialog_get_message (WebKitScriptDialog *dialog); - -WEBKIT_API void -webkit_script_dialog_confirm_set_confirmed (WebKitScriptDialog *dialog, - gboolean confirmed); - -WEBKIT_API const gchar * -webkit_script_dialog_prompt_get_default_text (WebKitScriptDialog *dialog); - -WEBKIT_API void -webkit_script_dialog_prompt_set_text (WebKitScriptDialog *dialog, - const gchar *text); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialogPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialogPrivate.h deleted file mode 100644 index 5f1a43d94..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitScriptDialogPrivate.h +++ /dev/null @@ -1,60 +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. - */ - -#ifndef WebKitScriptDialogPrivate_h -#define WebKitScriptDialogPrivate_h - -#include "WebKitScriptDialog.h" -#include <wtf/text/CString.h> - -struct _WebKitScriptDialog { - _WebKitScriptDialog(unsigned type, const CString& message) - : type(type) - , message(message) - , confirmed(false) - { - } - - _WebKitScriptDialog(unsigned type, const CString& message, const CString& defaultText) - : type(type) - , message(message) - , defaultText(defaultText) - , confirmed(false) - { - ASSERT(type == WEBKIT_SCRIPT_DIALOG_PROMPT); - } - - _WebKitScriptDialog(WebKitScriptDialog* dialog) - : type(dialog->type) - , message(dialog->message) - , defaultText(dialog->defaultText) - , confirmed(dialog->confirmed) - , text(dialog->text) - { - } - - unsigned type; - CString message; - CString defaultText; - - bool confirmed; - CString text; -}; - -#endif // WebKitScriptDialogPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp deleted file mode 100644 index e8c36d72c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.cpp +++ /dev/null @@ -1,331 +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 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 "WebKitSecurityManager.h" - -#include "WebContext.h" -#include "WebKitSecurityManagerPrivate.h" -#include "WebKitWebContextPrivate.h" -#include <WebCore/SchemeRegistry.h> - -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, - SecurityPolicyDisplayIsolated, - SecurityPolicySecure, - SecurityPolicyCORSEnabled, - SecurityPolicyEmptyDocument -} SecurityPolicy; - -struct _WebKitSecurityManagerPrivate { - WebKitWebContext* webContext; -}; - -WEBKIT_DEFINE_TYPE(WebKitSecurityManager, webkit_security_manager, G_TYPE_OBJECT) - -static void webkit_security_manager_class_init(WebKitSecurityManagerClass* klass) -{ -} - -WebKitSecurityManager* webkitSecurityManagerCreate(WebKitWebContext* webContext) -{ - WebKitSecurityManager* manager = WEBKIT_SECURITY_MANAGER(g_object_new(WEBKIT_TYPE_SECURITY_MANAGER, NULL)); - manager->priv->webContext = webContext; - return manager; -} - -static void registerSecurityPolicyForURIScheme(WebKitSecurityManager* manager, const char* scheme, SecurityPolicy policy) -{ - String urlScheme = String::fromUTF8(scheme); - WebContext* webContext = webkitWebContextGetContext(manager->priv->webContext); - - // We keep the WebCore::SchemeRegistry of the UI process in sync with the - // web process one, so that we can return the SecurityPolicy for - // a given URI scheme synchronously without blocking. - switch (policy) { - case SecurityPolicyLocal: - WebCore::SchemeRegistry::registerURLSchemeAsLocal(urlScheme); - webContext->registerURLSchemeAsLocal(urlScheme); - break; - case SecurityPolicyNoAccess: - WebCore::SchemeRegistry::registerURLSchemeAsNoAccess(urlScheme); - webContext->registerURLSchemeAsNoAccess(urlScheme); - break; - case SecurityPolicyDisplayIsolated: - WebCore::SchemeRegistry::registerURLSchemeAsDisplayIsolated(urlScheme); - webContext->registerURLSchemeAsDisplayIsolated(urlScheme); - break; - case SecurityPolicySecure: - WebCore::SchemeRegistry::registerURLSchemeAsSecure(urlScheme); - webContext->registerURLSchemeAsSecure(urlScheme); - break; - case SecurityPolicyCORSEnabled: - WebCore::SchemeRegistry::registerURLSchemeAsCORSEnabled(urlScheme); - webContext->registerURLSchemeAsCORSEnabled(urlScheme); - break; - case SecurityPolicyEmptyDocument: - WebCore::SchemeRegistry::registerURLSchemeAsEmptyDocument(urlScheme); - webContext->registerURLSchemeAsEmptyDocument(urlScheme); - break; - } -} - -static bool checkSecurityPolicyForURIScheme(const char* scheme, SecurityPolicy policy) -{ - String urlScheme = String::fromUTF8(scheme); - - switch (policy) { - case SecurityPolicyLocal: - return WebCore::SchemeRegistry::shouldTreatURLSchemeAsLocal(urlScheme); - case SecurityPolicyNoAccess: - return WebCore::SchemeRegistry::shouldTreatURLSchemeAsNoAccess(urlScheme); - case SecurityPolicyDisplayIsolated: - return WebCore::SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated(urlScheme); - case SecurityPolicySecure: - return WebCore::SchemeRegistry::shouldTreatURLSchemeAsSecure(urlScheme); - case SecurityPolicyCORSEnabled: - return WebCore::SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(urlScheme); - case SecurityPolicyEmptyDocument: - return WebCore::SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(urlScheme); - } - - return false; -} - -/** - * webkit_security_manager_register_uri_scheme_as_local: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Register @scheme as a local scheme. This means that other non-local pages - * cannot link to or access URIs of this scheme. - */ -void webkit_security_manager_register_uri_scheme_as_local(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager)); - g_return_if_fail(scheme); - - registerSecurityPolicyForURIScheme(manager, scheme, SecurityPolicyLocal); -} - -/** - * webkit_security_manager_uri_scheme_is_local: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Whether @scheme is considered as a local scheme. - * See also webkit_security_manager_register_uri_scheme_as_local(). - * - * Returns: %TRUE if @scheme is a local scheme or %FALSE otherwise. - */ -gboolean webkit_security_manager_uri_scheme_is_local(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_val_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager), FALSE); - g_return_val_if_fail(scheme, FALSE); - - return checkSecurityPolicyForURIScheme(scheme, SecurityPolicyLocal); -} - -/** - * webkit_security_manager_register_uri_scheme_as_no_access: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Register @scheme as a no-access scheme. This means that pages loaded - * with this URI scheme cannot access pages loaded with any other URI scheme. - */ -void webkit_security_manager_register_uri_scheme_as_no_access(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager)); - g_return_if_fail(scheme); - - registerSecurityPolicyForURIScheme(manager, scheme, SecurityPolicyNoAccess); -} - -/** - * webkit_security_manager_uri_scheme_is_no_access: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Whether @scheme is considered as a no-access scheme. - * See also webkit_security_manager_register_uri_scheme_as_no_access(). - * - * Returns: %TRUE if @scheme is a no-access scheme or %FALSE otherwise. - */ -gboolean webkit_security_manager_uri_scheme_is_no_access(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_val_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager), FALSE); - g_return_val_if_fail(scheme, FALSE); - - return checkSecurityPolicyForURIScheme(scheme, SecurityPolicyNoAccess); -} - -/** - * webkit_security_manager_register_uri_scheme_as_display_isolated: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Register @scheme as a display isolated scheme. This means that pages cannot - * display these URIs unless they are from the same scheme. - */ -void webkit_security_manager_register_uri_scheme_as_display_isolated(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager)); - g_return_if_fail(scheme); - - registerSecurityPolicyForURIScheme(manager, scheme, SecurityPolicyDisplayIsolated); -} - -/** - * webkit_security_manager_uri_scheme_is_display_isolated: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Whether @scheme is considered as a display isolated scheme. - * See also webkit_security_manager_register_uri_scheme_as_display_isolated(). - * - * Returns: %TRUE if @scheme is a display isolated scheme or %FALSE otherwise. - */ -gboolean webkit_security_manager_uri_scheme_is_display_isolated(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_val_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager), FALSE); - g_return_val_if_fail(scheme, FALSE); - - return checkSecurityPolicyForURIScheme(scheme, SecurityPolicyDisplayIsolated); -} - -/** - * webkit_security_manager_register_uri_scheme_as_secure: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Register @scheme as a secure scheme. This means that mixed - * content warnings won't be generated for this scheme when - * included by an HTTPS page. - */ -void webkit_security_manager_register_uri_scheme_as_secure(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager)); - g_return_if_fail(scheme); - - registerSecurityPolicyForURIScheme(manager, scheme, SecurityPolicySecure); -} - -/** - * webkit_security_manager_uri_scheme_is_secure: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Whether @scheme is considered as a secure scheme. - * See also webkit_security_manager_register_uri_scheme_as_secure(). - * - * Returns: %TRUE if @scheme is a secure scheme or %FALSE otherwise. - */ -gboolean webkit_security_manager_uri_scheme_is_secure(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_val_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager), FALSE); - g_return_val_if_fail(scheme, FALSE); - - return checkSecurityPolicyForURIScheme(scheme, SecurityPolicySecure); -} - -/** - * webkit_security_manager_register_uri_scheme_as_cors_enabled: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Register @scheme as a CORS (Cross-origin resource sharing) enabled scheme. - * This means that CORS requests are allowed. See W3C CORS specification - * http://www.w3.org/TR/cors/. - */ -void webkit_security_manager_register_uri_scheme_as_cors_enabled(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager)); - g_return_if_fail(scheme); - - registerSecurityPolicyForURIScheme(manager, scheme, SecurityPolicyCORSEnabled); -} - -/** - * webkit_security_manager_uri_scheme_is_cors_enabled: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Whether @scheme is considered as a CORS enabled scheme. - * See also webkit_security_manager_register_uri_scheme_as_cors_enabled(). - * - * Returns: %TRUE if @scheme is a CORS enabled scheme or %FALSE otherwise. - */ -gboolean webkit_security_manager_uri_scheme_is_cors_enabled(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_val_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager), FALSE); - g_return_val_if_fail(scheme, FALSE); - - return checkSecurityPolicyForURIScheme(scheme, SecurityPolicyCORSEnabled); -} - -/** - * webkit_security_manager_register_uri_scheme_as_empty_document: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Register @scheme as an empty document scheme. This means that - * they are allowd to commit synchronously. - */ -void webkit_security_manager_register_uri_scheme_as_empty_document(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager)); - g_return_if_fail(scheme); - - registerSecurityPolicyForURIScheme(manager, scheme, SecurityPolicyEmptyDocument); -} - -/** - * webkit_security_manager_uri_scheme_is_empty_document: - * @security_manager: a #WebKitSecurityManager - * @scheme: a URI scheme - * - * Whether @scheme is considered as an empty document scheme. - * See also webkit_security_manager_register_uri_scheme_as_empty_document(). - * - * Returns: %TRUE if @scheme is a an empty document scheme or %FALSE otherwise. - */ -gboolean webkit_security_manager_uri_scheme_is_empty_document(WebKitSecurityManager* manager, const char* scheme) -{ - g_return_val_if_fail(WEBKIT_IS_SECURITY_MANAGER(manager), FALSE); - g_return_val_if_fail(scheme, FALSE); - - return checkSecurityPolicyForURIScheme(scheme, SecurityPolicyEmptyDocument); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h deleted file mode 100644 index e8cf9e7cd..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManager.h +++ /dev/null @@ -1,111 +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 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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitSecurityManager_h -#define WebKitSecurityManager_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_SECURITY_MANAGER (webkit_security_manager_get_type()) -#define WEBKIT_SECURITY_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_SECURITY_MANAGER, WebKitSecurityManager)) -#define WEBKIT_IS_SECURITY_MANAGER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_SECURITY_MANAGER)) -#define WEBKIT_SECURITY_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_SECURITY_MANAGER, WebKitSecurityManagerClass)) -#define WEBKIT_IS_SECURITY_MANAGER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_SECURITY_MANAGER)) -#define WEBKIT_SECURITY_MANAGER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_SECURITY_MANAGER, WebKitSecurityManagerClass)) - -typedef struct _WebKitSecurityManager WebKitSecurityManager; -typedef struct _WebKitSecurityManagerClass WebKitSecurityManagerClass; -typedef struct _WebKitSecurityManagerPrivate WebKitSecurityManagerPrivate; - -struct _WebKitSecurityManager { - GObject parent; - - WebKitSecurityManagerPrivate *priv; -}; - -struct _WebKitSecurityManagerClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_security_manager_get_type (void); - -WEBKIT_API void -webkit_security_manager_register_uri_scheme_as_local (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API gboolean -webkit_security_manager_uri_scheme_is_local (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API void -webkit_security_manager_register_uri_scheme_as_no_access (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API gboolean -webkit_security_manager_uri_scheme_is_no_access (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API void -webkit_security_manager_register_uri_scheme_as_display_isolated (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API gboolean -webkit_security_manager_uri_scheme_is_display_isolated (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API void -webkit_security_manager_register_uri_scheme_as_secure (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API gboolean -webkit_security_manager_uri_scheme_is_secure (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API void -webkit_security_manager_register_uri_scheme_as_cors_enabled (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API gboolean -webkit_security_manager_uri_scheme_is_cors_enabled (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API void -webkit_security_manager_register_uri_scheme_as_empty_document (WebKitSecurityManager *security_manager, - const gchar *scheme); - -WEBKIT_API gboolean -webkit_security_manager_uri_scheme_is_empty_document (WebKitSecurityManager *security_manager, - const gchar *scheme); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManagerPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManagerPrivate.h deleted file mode 100644 index feabdced6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSecurityManagerPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitSecurityManagerPrivate_h -#define WebKitSecurityManagerPrivate_h - -#include "WebKitSecurityManager.h" -#include "WebKitWebContext.h" - -WebKitSecurityManager* webkitSecurityManagerCreate(WebKitWebContext*); - -#endif // WebKitSecurityManagerPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp deleted file mode 100644 index 53a547a1f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.cpp +++ /dev/null @@ -1,2798 +0,0 @@ -/* - * Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * Neither the name of Motorola Mobility, Inc. nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebKitSettings.h" - -#include "ExperimentalFeatures.h" -#include "WebKitPrivate.h" -#include "WebKitSettingsPrivate.h" -#include <WebCore/UserAgentGtk.h> -#include <glib/gi18n-lib.h> -#include <wtf/text/CString.h> - -using namespace WebKit; - -struct _WebKitSettingsPrivate { - _WebKitSettingsPrivate() - : preferences(WebPreferences::create()) - { - defaultFontFamily = preferences->standardFontFamily().utf8(); - monospaceFontFamily = preferences->fixedFontFamily().utf8(); - serifFontFamily = preferences->serifFontFamily().utf8(); - sansSerifFontFamily = preferences->sansSerifFontFamily().utf8(); - cursiveFontFamily = preferences->cursiveFontFamily().utf8(); - fantasyFontFamily = preferences->fantasyFontFamily().utf8(); - pictographFontFamily = preferences->pictographFontFamily().utf8(); - defaultCharset = preferences->defaultTextEncodingName().utf8(); - } - - RefPtr<WebPreferences> preferences; - CString defaultFontFamily; - CString monospaceFontFamily; - CString serifFontFamily; - CString sansSerifFontFamily; - CString cursiveFontFamily; - CString fantasyFontFamily; - CString pictographFontFamily; - CString defaultCharset; - CString userAgent; - bool allowModalDialogs; - bool zoomTextOnly; -}; - -/** - * SECTION:WebKitSettings - * @short_description: Control the behaviour of #WebKitWebView<!-- -->s - * @see_also: #WebKitWebViewGroup, #WebKitWebView - * - * #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> - * /<!-- -->* Disable JavaScript. *<!-- -->/ - * WebKitSettings *settings = webkit_web_view_group_get_settings (my_view_group); - * webkit_settings_set_enable_javascript (settings, FALSE); - * - * </programlisting></informalexample> - */ - -WEBKIT_DEFINE_TYPE(WebKitSettings, webkit_settings, G_TYPE_OBJECT) - -enum { - PROP_0, - - PROP_ENABLE_JAVASCRIPT, - PROP_AUTO_LOAD_IMAGES, - PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING, - PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE, - PROP_ENABLE_HTML5_LOCAL_STORAGE, - PROP_ENABLE_HTML5_DATABASE, - PROP_ENABLE_XSS_AUDITOR, - PROP_ENABLE_FRAME_FLATTENING, - PROP_ENABLE_PLUGINS, - PROP_ENABLE_JAVA, - PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY, - PROP_ENABLE_HYPERLINK_AUDITING, - PROP_DEFAULT_FONT_FAMILY, - PROP_MONOSPACE_FONT_FAMILY, - PROP_SERIF_FONT_FAMILY, - PROP_SANS_SERIF_FONT_FAMILY, - PROP_CURSIVE_FONT_FAMILY, - PROP_FANTASY_FONT_FAMILY, - PROP_PICTOGRAPH_FONT_FAMILY, - PROP_DEFAULT_FONT_SIZE, - PROP_DEFAULT_MONOSPACE_FONT_SIZE, - PROP_MINIMUM_FONT_SIZE, - PROP_DEFAULT_CHARSET, - PROP_ENABLE_PRIVATE_BROWSING, - PROP_ENABLE_DEVELOPER_EXTRAS, - PROP_ENABLE_RESIZABLE_TEXT_AREAS, - PROP_ENABLE_TABS_TO_LINKS, - PROP_ENABLE_DNS_PREFETCHING, - PROP_ENABLE_CARET_BROWSING, - PROP_ENABLE_FULLSCREEN, - PROP_PRINT_BACKGROUNDS, - PROP_ENABLE_WEBAUDIO, - PROP_ENABLE_WEBGL, - PROP_ALLOW_MODAL_DIALOGS, - PROP_ZOOM_TEXT_ONLY, - PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD, - PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE, - PROP_MEDIA_PLAYBACK_ALLOWS_INLINE, - PROP_DRAW_COMPOSITING_INDICATORS, - PROP_ENABLE_SITE_SPECIFIC_QUIRKS, - PROP_ENABLE_PAGE_CACHE, - PROP_USER_AGENT, - 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); - - switch (propId) { - case PROP_ENABLE_JAVASCRIPT: - webkit_settings_set_enable_javascript(settings, g_value_get_boolean(value)); - break; - case PROP_AUTO_LOAD_IMAGES: - webkit_settings_set_auto_load_images(settings, g_value_get_boolean(value)); - break; - case PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING: - webkit_settings_set_load_icons_ignoring_image_load_setting(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE: - webkit_settings_set_enable_offline_web_application_cache(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_HTML5_LOCAL_STORAGE: - webkit_settings_set_enable_html5_local_storage(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_HTML5_DATABASE: - webkit_settings_set_enable_html5_database(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_XSS_AUDITOR: - webkit_settings_set_enable_xss_auditor(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_FRAME_FLATTENING: - webkit_settings_set_enable_frame_flattening(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_PLUGINS: - webkit_settings_set_enable_plugins(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_JAVA: - webkit_settings_set_enable_java(settings, g_value_get_boolean(value)); - break; - case PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY: - webkit_settings_set_javascript_can_open_windows_automatically(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_HYPERLINK_AUDITING: - webkit_settings_set_enable_hyperlink_auditing(settings, g_value_get_boolean(value)); - break; - case PROP_DEFAULT_FONT_FAMILY: - webkit_settings_set_default_font_family(settings, g_value_get_string(value)); - break; - case PROP_MONOSPACE_FONT_FAMILY: - webkit_settings_set_monospace_font_family(settings, g_value_get_string(value)); - break; - case PROP_SERIF_FONT_FAMILY: - webkit_settings_set_serif_font_family(settings, g_value_get_string(value)); - break; - case PROP_SANS_SERIF_FONT_FAMILY: - webkit_settings_set_sans_serif_font_family(settings, g_value_get_string(value)); - break; - case PROP_CURSIVE_FONT_FAMILY: - webkit_settings_set_cursive_font_family(settings, g_value_get_string(value)); - break; - case PROP_FANTASY_FONT_FAMILY: - webkit_settings_set_fantasy_font_family(settings, g_value_get_string(value)); - break; - case PROP_PICTOGRAPH_FONT_FAMILY: - webkit_settings_set_pictograph_font_family(settings, g_value_get_string(value)); - break; - case PROP_DEFAULT_FONT_SIZE: - webkit_settings_set_default_font_size(settings, g_value_get_uint(value)); - break; - case PROP_DEFAULT_MONOSPACE_FONT_SIZE: - webkit_settings_set_default_monospace_font_size(settings, g_value_get_uint(value)); - break; - case PROP_MINIMUM_FONT_SIZE: - webkit_settings_set_minimum_font_size(settings, g_value_get_uint(value)); - break; - case PROP_DEFAULT_CHARSET: - webkit_settings_set_default_charset(settings, g_value_get_string(value)); - break; - case PROP_ENABLE_PRIVATE_BROWSING: - webkit_settings_set_enable_private_browsing(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_DEVELOPER_EXTRAS: - webkit_settings_set_enable_developer_extras(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_RESIZABLE_TEXT_AREAS: - webkit_settings_set_enable_resizable_text_areas(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_TABS_TO_LINKS: - webkit_settings_set_enable_tabs_to_links(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_DNS_PREFETCHING: - webkit_settings_set_enable_dns_prefetching(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_CARET_BROWSING: - webkit_settings_set_enable_caret_browsing(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_FULLSCREEN: - webkit_settings_set_enable_fullscreen(settings, g_value_get_boolean(value)); - break; - case PROP_PRINT_BACKGROUNDS: - webkit_settings_set_print_backgrounds(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_WEBAUDIO: - webkit_settings_set_enable_webaudio(settings, g_value_get_boolean(value)); - break; - case PROP_ENABLE_WEBGL: - webkit_settings_set_enable_webgl(settings, g_value_get_boolean(value)); - break; - case PROP_ALLOW_MODAL_DIALOGS: - webkit_settings_set_allow_modal_dialogs(settings, g_value_get_boolean(value)); - break; - case PROP_ZOOM_TEXT_ONLY: - webkit_settings_set_zoom_text_only(settings, g_value_get_boolean(value)); - break; - case PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD: - webkit_settings_set_javascript_can_access_clipboard(settings, g_value_get_boolean(value)); - break; - case PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE: - webkit_settings_set_media_playback_requires_user_gesture(settings, g_value_get_boolean(value)); - break; - case PROP_MEDIA_PLAYBACK_ALLOWS_INLINE: - webkit_settings_set_media_playback_allows_inline(settings, g_value_get_boolean(value)); - break; - case PROP_DRAW_COMPOSITING_INDICATORS: - 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)); - break; - case PROP_ENABLE_PAGE_CACHE: - webkit_settings_set_enable_page_cache(settings, g_value_get_boolean(value)); - break; - case PROP_USER_AGENT: - webkit_settings_set_user_agent(settings, g_value_get_string(value)); - break; - 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; - } -} - -static void webKitSettingsGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitSettings* settings = WEBKIT_SETTINGS(object); - - switch (propId) { - case PROP_ENABLE_JAVASCRIPT: - g_value_set_boolean(value, webkit_settings_get_enable_javascript(settings)); - break; - case PROP_AUTO_LOAD_IMAGES: - g_value_set_boolean(value, webkit_settings_get_auto_load_images(settings)); - break; - case PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING: - g_value_set_boolean(value, webkit_settings_get_load_icons_ignoring_image_load_setting(settings)); - break; - case PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE: - g_value_set_boolean(value, webkit_settings_get_enable_offline_web_application_cache(settings)); - break; - case PROP_ENABLE_HTML5_LOCAL_STORAGE: - g_value_set_boolean(value, webkit_settings_get_enable_html5_local_storage(settings)); - break; - case PROP_ENABLE_HTML5_DATABASE: - g_value_set_boolean(value, webkit_settings_get_enable_html5_database(settings)); - break; - case PROP_ENABLE_XSS_AUDITOR: - g_value_set_boolean(value, webkit_settings_get_enable_xss_auditor(settings)); - break; - case PROP_ENABLE_FRAME_FLATTENING: - g_value_set_boolean(value, webkit_settings_get_enable_frame_flattening(settings)); - break; - case PROP_ENABLE_PLUGINS: - g_value_set_boolean(value, webkit_settings_get_enable_plugins(settings)); - break; - case PROP_ENABLE_JAVA: - g_value_set_boolean(value, webkit_settings_get_enable_java(settings)); - break; - case PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY: - g_value_set_boolean(value, webkit_settings_get_javascript_can_open_windows_automatically(settings)); - break; - case PROP_ENABLE_HYPERLINK_AUDITING: - g_value_set_boolean(value, webkit_settings_get_enable_hyperlink_auditing(settings)); - break; - case PROP_DEFAULT_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_default_font_family(settings)); - break; - case PROP_MONOSPACE_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_monospace_font_family(settings)); - break; - case PROP_SERIF_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_serif_font_family(settings)); - break; - case PROP_SANS_SERIF_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_sans_serif_font_family(settings)); - break; - case PROP_CURSIVE_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_cursive_font_family(settings)); - break; - case PROP_FANTASY_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_fantasy_font_family(settings)); - break; - case PROP_PICTOGRAPH_FONT_FAMILY: - g_value_set_string(value, webkit_settings_get_pictograph_font_family(settings)); - break; - case PROP_DEFAULT_FONT_SIZE: - g_value_set_uint(value, webkit_settings_get_default_font_size(settings)); - break; - case PROP_DEFAULT_MONOSPACE_FONT_SIZE: - g_value_set_uint(value, webkit_settings_get_default_monospace_font_size(settings)); - break; - case PROP_MINIMUM_FONT_SIZE: - g_value_set_uint(value, webkit_settings_get_minimum_font_size(settings)); - break; - case PROP_DEFAULT_CHARSET: - g_value_set_string(value, webkit_settings_get_default_charset(settings)); - break; - case PROP_ENABLE_PRIVATE_BROWSING: - g_value_set_boolean(value, webkit_settings_get_enable_private_browsing(settings)); - break; - case PROP_ENABLE_DEVELOPER_EXTRAS: - g_value_set_boolean(value, webkit_settings_get_enable_developer_extras(settings)); - break; - case PROP_ENABLE_RESIZABLE_TEXT_AREAS: - g_value_set_boolean(value, webkit_settings_get_enable_resizable_text_areas(settings)); - break; - case PROP_ENABLE_TABS_TO_LINKS: - g_value_set_boolean(value, webkit_settings_get_enable_tabs_to_links(settings)); - break; - case PROP_ENABLE_DNS_PREFETCHING: - g_value_set_boolean(value, webkit_settings_get_enable_dns_prefetching(settings)); - break; - case PROP_ENABLE_CARET_BROWSING: - g_value_set_boolean(value, webkit_settings_get_enable_caret_browsing(settings)); - break; - case PROP_ENABLE_FULLSCREEN: - g_value_set_boolean(value, webkit_settings_get_enable_fullscreen(settings)); - break; - case PROP_PRINT_BACKGROUNDS: - g_value_set_boolean(value, webkit_settings_get_print_backgrounds(settings)); - break; - case PROP_ENABLE_WEBAUDIO: - g_value_set_boolean(value, webkit_settings_get_enable_webaudio(settings)); - break; - case PROP_ENABLE_WEBGL: - g_value_set_boolean(value, webkit_settings_get_enable_webgl(settings)); - break; - case PROP_ALLOW_MODAL_DIALOGS: - g_value_set_boolean(value, webkit_settings_get_allow_modal_dialogs(settings)); - break; - case PROP_ZOOM_TEXT_ONLY: - g_value_set_boolean(value, webkit_settings_get_zoom_text_only(settings)); - break; - case PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD: - g_value_set_boolean(value, webkit_settings_get_javascript_can_access_clipboard(settings)); - break; - case PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE: - g_value_set_boolean(value, webkit_settings_get_media_playback_requires_user_gesture(settings)); - break; - case PROP_MEDIA_PLAYBACK_ALLOWS_INLINE: - g_value_set_boolean(value, webkit_settings_get_media_playback_allows_inline(settings)); - break; - case PROP_DRAW_COMPOSITING_INDICATORS: - g_value_set_boolean(value, webkit_settings_get_draw_compositing_indicators(settings)); - break; - case PROP_ENABLE_SITE_SPECIFIC_QUIRKS: - g_value_set_boolean(value, webkit_settings_get_enable_site_specific_quirks(settings)); - break; - case PROP_ENABLE_PAGE_CACHE: - g_value_set_boolean(value, webkit_settings_get_enable_page_cache(settings)); - break; - case PROP_USER_AGENT: - g_value_set_string(value, webkit_settings_get_user_agent(settings)); - break; - 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; - } -} - -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; - - GParamFlags readWriteConstructParamFlags = static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT); - - /** - * WebKitSettings:enable-javascript: - * - * Determines whether or not JavaScript executes within a page. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_JAVASCRIPT, - g_param_spec_boolean("enable-javascript", - _("Enable JavaScript"), - _("Enable JavaScript."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:auto-load-images: - * - * Determines whether images should be automatically loaded or not. - * On devices where network bandwidth is of concern, it might be - * useful to turn this property off. - */ - g_object_class_install_property(gObjectClass, - PROP_AUTO_LOAD_IMAGES, - g_param_spec_boolean("auto-load-images", - _("Auto load images"), - _("Load images automatically."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:load-icons-ignoring-image-load-setting: - * - * Determines whether a site can load favicons irrespective - * of the value of #WebKitSettings:auto-load-images. - */ - g_object_class_install_property(gObjectClass, - PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING, - g_param_spec_boolean("load-icons-ignoring-image-load-setting", - _("Load icons ignoring image load setting"), - _("Whether to load site icons ignoring image load setting."), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-offline-web-application-cache: - * - * Whether to enable HTML5 offline web application cache support. Offline - * web application cache allows web applications to run even when - * the user is not connected to the network. - * - * HTML5 offline web application specification is available at - * http://dev.w3.org/html5/spec/offline.html. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE, - g_param_spec_boolean("enable-offline-web-application-cache", - _("Enable offline web application cache"), - _("Whether to enable offline web application cache."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-html5-local-storage: - * - * Whether to enable HTML5 local storage support. Local storage provides - * simple synchronous storage access. - * - * HTML5 local storage specification is available at - * http://dev.w3.org/html5/webstorage/. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_HTML5_LOCAL_STORAGE, - g_param_spec_boolean("enable-html5-local-storage", - _("Enable HTML5 local storage"), - _("Whether to enable HTML5 Local Storage support."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-html5-database: - * - * Whether to enable HTML5 client-side SQL database support. Client-side - * SQL database allows web pages to store structured data and be able to - * use SQL to manipulate that data asynchronously. - * - * HTML5 database specification is available at - * http://www.w3.org/TR/webdatabase/. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_HTML5_DATABASE, - g_param_spec_boolean("enable-html5-database", - _("Enable HTML5 database"), - _("Whether to enable HTML5 database support."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-xss-auditor: - * - * Whether to enable the XSS auditor. This feature filters some kinds of - * reflective XSS attacks on vulnerable web sites. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_XSS_AUDITOR, - g_param_spec_boolean("enable-xss-auditor", - _("Enable XSS auditor"), - _("Whether to enable the XSS auditor."), - TRUE, - readWriteConstructParamFlags)); - - - /** - * WebKitSettings:enable-frame-flattening: - * - * Whether to enable the frame flattening. With this setting each subframe is expanded - * to its contents, which will flatten all the frames to become one scrollable page. - * On touch devices scrollable subframes on a page can result in a confusing user experience. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_FRAME_FLATTENING, - g_param_spec_boolean("enable-frame-flattening", - _("Enable frame flattening"), - _("Whether to enable frame flattening."), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-plugins: - * - * Determines whether or not plugins on the page are enabled. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_PLUGINS, - g_param_spec_boolean("enable-plugins", - _("Enable plugins"), - _("Enable embedded plugin objects."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-java: - * - * Determines whether or not Java is enabled on the page. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_JAVA, - g_param_spec_boolean("enable-java", - _("Enable Java"), - _("Whether Java support should be enabled."), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:javascript-can-open-windows-automatically: - * - * Whether JavaScript can open popup windows automatically without user - * intervention. - */ - g_object_class_install_property(gObjectClass, - PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY, - g_param_spec_boolean("javascript-can-open-windows-automatically", - _("JavaScript can open windows automatically"), - _("Whether JavaScript can open windows automatically."), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-hyperlink-auditing: - * - * Determines whether or not hyperlink auditing is enabled. - * - * The hyperlink auditing specification is available at - * http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_HYPERLINK_AUDITING, - g_param_spec_boolean("enable-hyperlink-auditing", - _("Enable hyperlink auditing"), - _("Whether <a ping> should be able to send pings."), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:default-font-family: - * - * The font family to use as the default for content that does not specify a font. - */ - g_object_class_install_property(gObjectClass, - PROP_DEFAULT_FONT_FAMILY, - g_param_spec_string("default-font-family", - _("Default font family"), - _("The font family to use as the default for content that does not specify a font."), - "sans-serif", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:monospace-font-family: - * - * The font family used as the default for content using a monospace font. - * - */ - g_object_class_install_property(gObjectClass, - PROP_MONOSPACE_FONT_FAMILY, - g_param_spec_string("monospace-font-family", - _("Monospace font family"), - _("The font family used as the default for content using monospace font."), - "monospace", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:serif-font-family: - * - * The font family used as the default for content using a serif font. - */ - g_object_class_install_property(gObjectClass, - PROP_SERIF_FONT_FAMILY, - g_param_spec_string("serif-font-family", - _("Serif font family"), - _("The font family used as the default for content using serif font."), - "serif", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:sans-serif-font-family: - * - * The font family used as the default for content using a sans-serif font. - */ - g_object_class_install_property(gObjectClass, - PROP_SANS_SERIF_FONT_FAMILY, - g_param_spec_string("sans-serif-font-family", - _("Sans-serif font family"), - _("The font family used as the default for content using sans-serif font."), - "sans-serif", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:cursive-font-family: - * - * The font family used as the default for content using a cursive font. - */ - g_object_class_install_property(gObjectClass, - PROP_CURSIVE_FONT_FAMILY, - g_param_spec_string("cursive-font-family", - _("Cursive font family"), - _("The font family used as the default for content using cursive font."), - "serif", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:fantasy-font-family: - * - * The font family used as the default for content using a fantasy font. - */ - g_object_class_install_property(gObjectClass, - PROP_FANTASY_FONT_FAMILY, - g_param_spec_string("fantasy-font-family", - _("Fantasy font family"), - _("The font family used as the default for content using fantasy font."), - "serif", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:pictograph-font-family: - * - * The font family used as the default for content using a pictograph font. - */ - g_object_class_install_property(gObjectClass, - PROP_PICTOGRAPH_FONT_FAMILY, - g_param_spec_string("pictograph-font-family", - _("Pictograph font family"), - _("The font family used as the default for content using pictograph font."), - "serif", - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:default-font-size: - * - * The default font size in pixels to use for content displayed if - * no font size is specified. - */ - g_object_class_install_property(gObjectClass, - PROP_DEFAULT_FONT_SIZE, - g_param_spec_uint("default-font-size", - _("Default font size"), - _("The default font size used to display text."), - 0, G_MAXUINT, 16, - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:default-monospace-font-size: - * - * The default font size in pixels to use for content displayed in - * monospace font if no font size is specified. - */ - g_object_class_install_property(gObjectClass, - PROP_DEFAULT_MONOSPACE_FONT_SIZE, - g_param_spec_uint("default-monospace-font-size", - _("Default monospace font size"), - _("The default font size used to display monospace text."), - 0, G_MAXUINT, 13, - readWriteConstructParamFlags)); - - /** - * WebKitWebSettings:minimum-font-size: - * - * The minimum font size in points used to display text. This setting - * controls the absolute smallest size. Values other than 0 can - * potentially break page layouts. - */ - g_object_class_install_property(gObjectClass, - PROP_MINIMUM_FONT_SIZE, - g_param_spec_uint("minimum-font-size", - _("Minimum font size"), - _("The minimum font size used to display text."), - 0, G_MAXUINT, 0, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:default-charset: - * - * The default text charset used when interpreting content with an unspecified charset. - */ - g_object_class_install_property(gObjectClass, - PROP_DEFAULT_CHARSET, - g_param_spec_string("default-charset", - _("Default charset"), - _("The default text charset used when interpreting content with unspecified charset."), - "iso-8859-1", - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-private-browsing: - * - * Determines whether or not private browsing is enabled. Private browsing - * will disable history, cache and form auto-fill for any pages visited. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_PRIVATE_BROWSING, - g_param_spec_boolean("enable-private-browsing", - _("Enable private browsing"), - _("Whether to enable private browsing"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-developer-extras: - * - * Determines whether or not developer tools, such as the Web Inspector, are enabled. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_DEVELOPER_EXTRAS, - g_param_spec_boolean("enable-developer-extras", - _("Enable developer extras"), - _("Whether to enable developer extras"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-resizable-text-areas: - * - * Determines whether or not text areas can be resized. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_RESIZABLE_TEXT_AREAS, - g_param_spec_boolean("enable-resizable-text-areas", - _("Enable resizable text areas"), - _("Whether to enable resizable text areas"), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-tabs-to-links: - * - * Determines whether the tab key cycles through the elements on the page. - * When this setting is enabled, users will be able to focus the next element - * in the page by pressing the tab key. If the selected element is editable, - * then pressing tab key will insert the tab character. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_TABS_TO_LINKS, - g_param_spec_boolean("enable-tabs-to-links", - _("Enable tabs to links"), - _("Whether to enable tabs to links"), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-dns-prefetching: - * - * Determines whether or not to prefetch domain names. DNS prefetching attempts - * to resolve domain names before a user tries to follow a link. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_DNS_PREFETCHING, - g_param_spec_boolean("enable-dns-prefetching", - _("Enable DNS prefetching"), - _("Whether to enable DNS prefetching"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-caret-browsing: - * - * Whether to enable accessibility enhanced keyboard navigation. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_CARET_BROWSING, - g_param_spec_boolean("enable-caret-browsing", - _("Enable Caret Browsing"), - _("Whether to enable accessibility enhanced keyboard navigation"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-fullscreen: - * - * Whether to enable the Javascript Fullscreen API. The API - * allows any HTML element to request fullscreen display. See also - * the current draft of the spec: - * http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_FULLSCREEN, - g_param_spec_boolean("enable-fullscreen", - _("Enable Fullscreen"), - _("Whether to enable the Javascriipt Fullscreen API"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:print-backgrounds: - * - * Whether background images should be drawn during printing. - */ - g_object_class_install_property(gObjectClass, - PROP_PRINT_BACKGROUNDS, - g_param_spec_boolean("print-backgrounds", - _("Print Backgrounds"), - _("Whether background images should be drawn during printing"), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-webaudio: - * - * - * Enable or disable support for WebAudio on pages. WebAudio is an - * experimental proposal for allowing web pages to generate Audio - * WAVE data from JavaScript. The standard is currently a - * work-in-progress by the W3C Audio Working Group. - * - * See also https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_WEBAUDIO, - g_param_spec_boolean("enable-webaudio", - _("Enable WebAudio"), - _("Whether WebAudio content should be handled"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-webgl: - * - * Enable or disable support for WebGL on pages. WebGL is an experimental - * proposal for allowing web pages to use OpenGL ES-like calls directly. The - * standard is currently a work-in-progress by the Khronos Group. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_WEBGL, - g_param_spec_boolean("enable-webgl", - _("Enable WebGL"), - _("Whether WebGL content should be rendered"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:allow-modal-dialogs: - * - * Determine whether it's allowed to create and run modal dialogs - * from a #WebKitWebView through JavaScript with - * <function>window.showModalDialog</function>. If it's set to - * %FALSE, the associated #WebKitWebView won't be able to create - * new modal dialogs, so not even the #WebKitWebView::create - * signal will be emitted. - */ - g_object_class_install_property(gObjectClass, - PROP_ALLOW_MODAL_DIALOGS, - g_param_spec_boolean("allow-modal-dialogs", - _("Allow modal dialogs"), - _("Whether it is possible to create modal dialogs"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:zoom-text-only: - * - * Whether #WebKitWebView:zoom-level affects only the - * text of the page or all the contents. Other contents containing text - * like form controls will be also affected by zoom factor when - * this property is enabled. - */ - g_object_class_install_property(gObjectClass, - PROP_ZOOM_TEXT_ONLY, - g_param_spec_boolean("zoom-text-only", - _("Zoom Text Only"), - _("Whether zoom level of web view changes only the text size"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:javascript-can-access-clipboard: - * - * Whether JavaScript can access the clipboard. The default value is %FALSE. If - * set to %TRUE, document.execCommand() allows cut, copy and paste commands. - * - */ - g_object_class_install_property(gObjectClass, - PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD, - g_param_spec_boolean("javascript-can-access-clipboard", - _("JavaScript can access clipboard"), - _("Whether JavaScript can access Clipboard"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:media-playback-requires-user-gesture: - * - * Whether a user gesture (such as clicking the play button) - * would be required to start media playback or load media. This is off - * by default, so media playback could start automatically. - * Setting it on requires a gesture by the user to start playback, or to - * load the media. - */ - g_object_class_install_property(gObjectClass, - PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE, - g_param_spec_boolean("media-playback-requires-user-gesture", - _("Media playback requires user gesture"), - _("Whether media playback requires user gesture"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:media-playback-allows-inline: - * - * Whether media playback is full-screen only or inline playback is allowed. - * This is %TRUE by default, so media playback can be inline. Setting it to - * %FALSE allows specifying that media playback should be always fullscreen. - */ - g_object_class_install_property(gObjectClass, - PROP_MEDIA_PLAYBACK_ALLOWS_INLINE, - g_param_spec_boolean("media-playback-allows-inline", - _("Media playback allows inline"), - _("Whether media playback allows inline"), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:draw-compositing-indicators: - * - * Whether to draw compositing borders and repaint counters on layers drawn - * with accelerated compositing. This is useful for debugging issues related - * to web content that is composited with the GPU. - */ - g_object_class_install_property(gObjectClass, - PROP_DRAW_COMPOSITING_INDICATORS, - g_param_spec_boolean("draw-compositing-indicators", - _("Draw compositing indicators"), - _("Whether to draw compositing borders and repaint counters"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-site-specific-quirks: - * - * Whether to turn on site-specific quirks. Turning this on will - * tell WebKit to use some site-specific workarounds for - * better web compatibility. For example, older versions of - * MediaWiki will incorrectly send to WebKit a css file with KHTML - * workarounds. By turning on site-specific quirks, WebKit will - * special-case this and other cases to make some specific sites work. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_SITE_SPECIFIC_QUIRKS, - g_param_spec_boolean("enable-site-specific-quirks", - _("Enable Site Specific Quirks"), - _("Enables the site-specific compatibility workarounds"), - FALSE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-page-cache: - * - * Enable or disable the page cache. Disabling the page cache is - * generally only useful for special circumstances like low-memory - * scenarios or special purpose applications like static HTML - * viewers. This setting only controls the Page Cache, this cache - * is different than the disk-based or memory-based traditional - * resource caches, its point is to make going back and forth - * between pages much faster. For details about the different types - * of caches and their purposes see: - * http://webkit.org/blog/427/webkit-page-cache-i-the-basics/ - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_PAGE_CACHE, - g_param_spec_boolean("enable-page-cache", - _("Enable page cache"), - _("Whether the page cache should be used"), - TRUE, - readWriteConstructParamFlags)); - - /** - * WebKitSettings:user-agent: - * - * The user-agent string used by WebKit. Unusual user-agent strings may cause web - * content to render incorrectly or fail to run, as many web pages are written to - * parse the user-agent strings of only the most popular browsers. Therefore, it's - * typically better to not completely override the standard user-agent, but to use - * webkit_settings_set_user_agent_with_application_details() instead. - * - * If this property is set to the empty string or %NULL, it will revert to the standard - * user-agent. - */ - g_object_class_install_property(gObjectClass, - PROP_USER_AGENT, - g_param_spec_string("user-agent", - _("User agent string"), - _("The user agent string"), - 0, // A null string forces the standard user agent. - readWriteConstructParamFlags)); - - /** - * WebKitSettings:enable-smooth-scrolling: - * - * Enable or disable smooth scrolling. - */ - g_object_class_install_property(gObjectClass, - PROP_ENABLE_SMOOTH_SCROLLING, - g_param_spec_boolean("enable-smooth-scrolling", - _("Enable smooth scrolling"), - _("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)); - -} - -WebPreferences* webkitSettingsGetPreferences(WebKitSettings* settings) -{ - return settings->priv->preferences.get(); -} - -/** - * webkit_settings_new: - * - * Creates a new #WebKitSettings instance with default values. It must - * be manually attached to a #WebKitWebViewGroup. - * See also webkit_settings_new_with_settings(). - * - * Returns: a new #WebKitSettings instance. - */ -WebKitSettings* webkit_settings_new() -{ - return WEBKIT_SETTINGS(g_object_new(WEBKIT_TYPE_SETTINGS, NULL)); -} - -/** - * webkit_settings_new_with_settings: - * @first_setting_name: name of first setting to set - * @...: value of first setting, followed by more settings, - * %NULL-terminated - * - * Creates a new #WebKitSettings instance with the given settings. It must - * be manually attached to a #WebKitWebViewGroup. - * - * Returns: a new #WebKitSettings instance. - */ -WebKitSettings* webkit_settings_new_with_settings(const gchar* firstSettingName, ...) -{ - va_list args; - va_start(args, firstSettingName); - WebKitSettings* settings = WEBKIT_SETTINGS(g_object_new_valist(WEBKIT_TYPE_SETTINGS, firstSettingName, args)); - va_end(args); - return settings; -} - -/** - * webkit_settings_get_enable_javascript: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-javascript property. - * - * Returns: %TRUE If JavaScript is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_javascript(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->javaScriptEnabled(); -} - -/** - * webkit_settings_set_enable_javascript: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-javascript property. - */ -void webkit_settings_set_enable_javascript(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->javaScriptEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setJavaScriptEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-javascript"); -} - -/** - * webkit_settings_get_auto_load_images: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:auto-load-images property. - * - * Returns: %TRUE If auto loading of images is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_auto_load_images(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->loadsImagesAutomatically(); -} - -/** - * webkit_settings_set_auto_load_images: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:auto-load-images property. - */ -void webkit_settings_set_auto_load_images(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->loadsImagesAutomatically(); - if (currentValue == enabled) - return; - - priv->preferences->setLoadsImagesAutomatically(enabled); - g_object_notify(G_OBJECT(settings), "auto-load-images"); -} - -/** - * webkit_settings_get_load_icons_ignoring_image_load_setting: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:load-icons-ignoring-image-load-setting property. - * - * Returns: %TRUE If site icon can be loaded irrespective of image loading preference or %FALSE otherwise. - */ -gboolean webkit_settings_get_load_icons_ignoring_image_load_setting(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->loadsSiteIconsIgnoringImageLoadingPreference(); -} - -/** - * webkit_settings_set_load_icons_ignoring_image_load_setting: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:load-icons-ignoring-image-load-setting property. - */ -void webkit_settings_set_load_icons_ignoring_image_load_setting(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->loadsSiteIconsIgnoringImageLoadingPreference(); - if (currentValue == enabled) - return; - - priv->preferences->setLoadsSiteIconsIgnoringImageLoadingPreference(enabled); - g_object_notify(G_OBJECT(settings), "load-icons-ignoring-image-load-setting"); -} - -/** - * webkit_settings_get_enable_offline_web_application_cache: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-offline-web-application-cache property. - * - * Returns: %TRUE If HTML5 offline web application cache support is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_offline_web_application_cache(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->offlineWebApplicationCacheEnabled(); -} - -/** - * webkit_settings_set_enable_offline_web_application_cache: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-offline-web-application-cache property. - */ -void webkit_settings_set_enable_offline_web_application_cache(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->offlineWebApplicationCacheEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setOfflineWebApplicationCacheEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-offline-web-application-cache"); -} - -/** - * webkit_settings_get_enable_html5_local_storage: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-html5-local-storage property. - * - * Returns: %TRUE If HTML5 local storage support is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_html5_local_storage(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->localStorageEnabled(); -} - -/** - * webkit_settings_set_enable_html5_local_storage: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-html5-local-storage property. - */ -void webkit_settings_set_enable_html5_local_storage(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->localStorageEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setLocalStorageEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-html5-local-storage"); -} - -/** - * webkit_settings_get_enable_html5_database: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-html5-database property. - * - * Returns: %TRUE If HTML5 database support is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_html5_database(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->databasesEnabled(); -} - -/** - * webkit_settings_set_enable_html5_database: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-html5-database property. - */ -void webkit_settings_set_enable_html5_database(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->databasesEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setDatabasesEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-html5-database"); -} - -/** - * webkit_settings_get_enable_xss_auditor: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-xss-auditor property. - * - * Returns: %TRUE If XSS auditing is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_xss_auditor(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->xssAuditorEnabled(); -} - -/** - * webkit_settings_set_enable_xss_auditor: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-xss-auditor property. - */ -void webkit_settings_set_enable_xss_auditor(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->xssAuditorEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setXSSAuditorEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-xss-auditor"); -} - -/** - * webkit_settings_get_enable_frame_flattening: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-frame-flattening property. - * - * Returns: %TRUE If frame flattening is enabled or %FALSE otherwise. - * - **/ -gboolean webkit_settings_get_enable_frame_flattening(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->frameFlatteningEnabled(); -} - -/** - * webkit_settings_set_enable_frame_flattening: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-frame-flattening property. - */ -void webkit_settings_set_enable_frame_flattening(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->frameFlatteningEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setFrameFlatteningEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-frame-flattening"); -} - -/** - * webkit_settings_get_enable_plugins: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-plugins property. - * - * Returns: %TRUE If plugins are enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_plugins(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->pluginsEnabled(); -} - -/** - * webkit_settings_set_enable_plugins: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-plugins property. - */ -void webkit_settings_set_enable_plugins(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->pluginsEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setPluginsEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-plugins"); -} - -/** - * webkit_settings_get_enable_java: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-java property. - * - * Returns: %TRUE If Java is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_java(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->javaEnabled(); -} - -/** - * webkit_settings_set_enable_java: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-java property. - */ -void webkit_settings_set_enable_java(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->javaEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setJavaEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-java"); -} - -/** - * webkit_settings_get_javascript_can_open_windows_automatically: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:javascript-can-open-windows-automatically property. - * - * Returns: %TRUE If JavaScript can open window automatically or %FALSE otherwise. - */ -gboolean webkit_settings_get_javascript_can_open_windows_automatically(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->javaScriptCanOpenWindowsAutomatically(); -} - -/** - * webkit_settings_set_javascript_can_open_windows_automatically: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:javascript-can-open-windows-automatically property. - */ -void webkit_settings_set_javascript_can_open_windows_automatically(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->javaScriptCanOpenWindowsAutomatically(); - if (currentValue == enabled) - return; - - priv->preferences->setJavaScriptCanOpenWindowsAutomatically(enabled); - g_object_notify(G_OBJECT(settings), "javascript-can-open-windows-automatically"); -} - -/** - * webkit_settings_get_enable_hyperlink_auditing: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-hyperlink-auditing property. - * - * Returns: %TRUE If hyper link auditing is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_hyperlink_auditing(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->hyperlinkAuditingEnabled(); -} - -/** - * webkit_settings_set_enable_hyperlink_auditing: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-hyperlink-auditing property. - */ -void webkit_settings_set_enable_hyperlink_auditing(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->hyperlinkAuditingEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setHyperlinkAuditingEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-hyperlink-auditing"); -} - -/** - * webkit_web_settings_get_default_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:default-font-family property. - * - * Returns: The default font family used to display content that does not specify a font. - */ -const gchar* webkit_settings_get_default_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->defaultFontFamily.data(); -} - -/** - * webkit_settings_set_default_font_family: - * @settings: a #WebKitSettings - * @default_font_family: the new default font family - * - * Set the #WebKitSettings:default-font-family property. - */ -void webkit_settings_set_default_font_family(WebKitSettings* settings, const gchar* defaultFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(defaultFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->defaultFontFamily.data(), defaultFontFamily)) - return; - - String standardFontFamily = String::fromUTF8(defaultFontFamily); - priv->preferences->setStandardFontFamily(standardFontFamily); - priv->defaultFontFamily = standardFontFamily.utf8(); - g_object_notify(G_OBJECT(settings), "default-font-family"); -} - -/** - * webkit_settings_get_monospace_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:monospace-font-family property. - * - * Returns: Default font family used to display content marked with monospace font. - */ -const gchar* webkit_settings_get_monospace_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->monospaceFontFamily.data(); -} - -/** - * webkit_settings_set_monospace_font_family: - * @settings: a #WebKitSettings - * @monospace_font_family: the new default monospace font family - * - * Set the #WebKitSettings:monospace-font-family property. - */ -void webkit_settings_set_monospace_font_family(WebKitSettings* settings, const gchar* monospaceFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(monospaceFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->monospaceFontFamily.data(), monospaceFontFamily)) - return; - - String fixedFontFamily = String::fromUTF8(monospaceFontFamily); - priv->preferences->setFixedFontFamily(fixedFontFamily); - priv->monospaceFontFamily = fixedFontFamily.utf8(); - g_object_notify(G_OBJECT(settings), "monospace-font-family"); -} - -/** - * webkit_settings_get_serif_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:serif-font-family property. - * - * Returns: The default font family used to display content marked with serif font. - */ -const gchar* webkit_settings_get_serif_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->serifFontFamily.data(); -} - -/** - * webkit_settings_set_serif_font_family: - * @settings: a #WebKitSettings - * @serif_font_family: the new default serif font family - * - * Set the #WebKitSettings:serif-font-family property. - */ -void webkit_settings_set_serif_font_family(WebKitSettings* settings, const gchar* serifFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(serifFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->serifFontFamily.data(), serifFontFamily)) - return; - - String serifFontFamilyString = String::fromUTF8(serifFontFamily); - priv->preferences->setSerifFontFamily(serifFontFamilyString); - priv->serifFontFamily = serifFontFamilyString.utf8(); - g_object_notify(G_OBJECT(settings), "serif-font-family"); -} - -/** - * webkit_settings_get_sans_serif_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:sans-serif-font-family property. - * - * Returns: The default font family used to display content marked with sans-serif font. - */ -const gchar* webkit_settings_get_sans_serif_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->sansSerifFontFamily.data(); -} - -/** - * webkit_settings_set_sans_serif_font_family: - * @settings: a #WebKitSettings - * @sans_serif_font_family: the new default sans-serif font family - * - * Set the #WebKitSettings:sans-serif-font-family property. - */ -void webkit_settings_set_sans_serif_font_family(WebKitSettings* settings, const gchar* sansSerifFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(sansSerifFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->sansSerifFontFamily.data(), sansSerifFontFamily)) - return; - - String sansSerifFontFamilyString = String::fromUTF8(sansSerifFontFamily); - priv->preferences->setSansSerifFontFamily(sansSerifFontFamilyString); - priv->sansSerifFontFamily = sansSerifFontFamilyString.utf8(); - g_object_notify(G_OBJECT(settings), "sans-serif-font-family"); -} - -/** - * webkit_settings_get_cursive_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:cursive-font-family property. - * - * Returns: The default font family used to display content marked with cursive font. - */ -const gchar* webkit_settings_get_cursive_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->cursiveFontFamily.data(); -} - -/** - * webkit_settings_set_cursive_font_family: - * @settings: a #WebKitSettings - * @cursive_font_family: the new default cursive font family - * - * Set the #WebKitSettings:cursive-font-family property. - */ -void webkit_settings_set_cursive_font_family(WebKitSettings* settings, const gchar* cursiveFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(cursiveFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->cursiveFontFamily.data(), cursiveFontFamily)) - return; - - String cursiveFontFamilyString = String::fromUTF8(cursiveFontFamily); - priv->preferences->setCursiveFontFamily(cursiveFontFamilyString); - priv->cursiveFontFamily = cursiveFontFamilyString.utf8(); - g_object_notify(G_OBJECT(settings), "cursive-font-family"); -} - -/** - * webkit_settings_get_fantasy_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:fantasy-font-family property. - * - * Returns: The default font family used to display content marked with fantasy font. - */ -const gchar* webkit_settings_get_fantasy_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->fantasyFontFamily.data(); -} - -/** - * webkit_settings_set_fantasy_font_family: - * @settings: a #WebKitSettings - * @fantasy_font_family: the new default fantasy font family - * - * Set the #WebKitSettings:fantasy-font-family property. - */ -void webkit_settings_set_fantasy_font_family(WebKitSettings* settings, const gchar* fantasyFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(fantasyFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->fantasyFontFamily.data(), fantasyFontFamily)) - return; - - String fantasyFontFamilyString = String::fromUTF8(fantasyFontFamily); - priv->preferences->setFantasyFontFamily(fantasyFontFamilyString); - priv->fantasyFontFamily = fantasyFontFamilyString.utf8(); - g_object_notify(G_OBJECT(settings), "fantasy-font-family"); -} - -/** - * webkit_settings_get_pictograph_font_family: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:pictograph-font-family property. - * - * Returns: The default font family used to display content marked with pictograph font. - */ -const gchar* webkit_settings_get_pictograph_font_family(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->pictographFontFamily.data(); -} - -/** - * webkit_settings_set_pictograph_font_family: - * @settings: a #WebKitSettings - * @pictograph_font_family: the new default pictograph font family - * - * Set the #WebKitSettings:pictograph-font-family property. - */ -void webkit_settings_set_pictograph_font_family(WebKitSettings* settings, const gchar* pictographFontFamily) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(pictographFontFamily); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->pictographFontFamily.data(), pictographFontFamily)) - return; - - String pictographFontFamilyString = String::fromUTF8(pictographFontFamily); - priv->preferences->setPictographFontFamily(pictographFontFamilyString); - priv->pictographFontFamily = pictographFontFamilyString.utf8(); - g_object_notify(G_OBJECT(settings), "pictograph-font-family"); -} - -/** - * webkit_settings_get_default_font_size: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:default-font-size property. - * - * Returns: The default font size. - */ -guint32 webkit_settings_get_default_font_size(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->preferences->defaultFontSize(); -} - -/** - * webkit_settings_set_default_font_size: - * @settings: a #WebKitSettings - * @font_size: default font size to be set in pixels - * - * Set the #WebKitSettings:default-font-size property. - */ -void webkit_settings_set_default_font_size(WebKitSettings* settings, guint32 fontSize) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - uint32_t currentSize = priv->preferences->defaultFontSize(); - if (currentSize == fontSize) - return; - - priv->preferences->setDefaultFontSize(fontSize); - g_object_notify(G_OBJECT(settings), "default-font-size"); -} - -/** - * webkit_settings_get_default_monospace_font_size: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:default-monospace-font-size property. - * - * Returns: Default monospace font size. - */ -guint32 webkit_settings_get_default_monospace_font_size(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->preferences->defaultFixedFontSize(); -} - -/** - * webkit_settings_set_default_monospace_font_size: - * @settings: a #WebKitSettings - * @font_size: default monospace font size to be set in pixels - * - * Set the #WebKitSettings:default-monospace-font-size property. - */ -void webkit_settings_set_default_monospace_font_size(WebKitSettings* settings, guint32 fontSize) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - uint32_t currentSize = priv->preferences->defaultFixedFontSize(); - if (currentSize == fontSize) - return; - - priv->preferences->setDefaultFixedFontSize(fontSize); - g_object_notify(G_OBJECT(settings), "default-monospace-font-size"); -} - -/** - * webkit_settings_get_minimum_font_size: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:minimum-font-size property. - * - * Returns: Minimum font size. - */ -guint32 webkit_settings_get_minimum_font_size(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->preferences->minimumFontSize(); -} - -/** - * webkit_settings_set_minimum_font_size: - * @settings: a #WebKitSettings - * @font_size: minimum font size to be set in points - * - * Set the #WebKitSettings:minimum-font-size property. - */ -void webkit_settings_set_minimum_font_size(WebKitSettings* settings, guint32 fontSize) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - uint32_t currentSize = priv->preferences->minimumFontSize(); - if (currentSize == fontSize) - return; - - priv->preferences->setMinimumFontSize(fontSize); - g_object_notify(G_OBJECT(settings), "minimum-font-size"); -} - -/** - * webkit_settings_get_default_charset: - * @settings: a #WebKitSettings - * - * Gets the #WebKitSettings:default-charset property. - * - * Returns: Default charset. - */ -const gchar* webkit_settings_get_default_charset(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - return settings->priv->defaultCharset.data(); -} - -/** - * webkit_settings_set_default_charset: - * @settings: a #WebKitSettings - * @default_charset: default charset to be set - * - * Set the #WebKitSettings:default-charset property. - */ -void webkit_settings_set_default_charset(WebKitSettings* settings, const gchar* defaultCharset) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - g_return_if_fail(defaultCharset); - - WebKitSettingsPrivate* priv = settings->priv; - if (!g_strcmp0(priv->defaultCharset.data(), defaultCharset)) - return; - - String defaultCharsetString = String::fromUTF8(defaultCharset); - priv->preferences->setDefaultTextEncodingName(defaultCharsetString); - priv->defaultCharset = defaultCharsetString.utf8(); - g_object_notify(G_OBJECT(settings), "default-charset"); -} - -/** - * webkit_settings_get_enable_private_browsing: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-private-browsing property. - * - * Returns: %TRUE If private browsing is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_private_browsing(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->privateBrowsingEnabled(); -} - -/** - * webkit_settings_set_private_caret_browsing: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-private-browsing property. - */ -void webkit_settings_set_enable_private_browsing(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->privateBrowsingEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setPrivateBrowsingEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-private-browsing"); -} - -/** - * webkit_settings_get_enable_developer_extras: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-developer-extras property. - * - * Returns: %TRUE If developer extras is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_developer_extras(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->developerExtrasEnabled(); -} - -/** - * webkit_settings_set_enable_developer_extras: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-developer-extras property. - */ -void webkit_settings_set_enable_developer_extras(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->developerExtrasEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setDeveloperExtrasEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-developer-extras"); -} - -/** - * webkit_settings_get_enable_resizable_text_areas: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-resizable-text-areas property. - * - * Returns: %TRUE If text areas can be resized or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_resizable_text_areas(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->textAreasAreResizable(); -} - -/** - * webkit_settings_set_enable_resizable_text_areas: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-resizable-text-areas property. - */ -void webkit_settings_set_enable_resizable_text_areas(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->textAreasAreResizable(); - if (currentValue == enabled) - return; - - priv->preferences->setTextAreasAreResizable(enabled); - g_object_notify(G_OBJECT(settings), "enable-resizable-text-areas"); -} - -/** - * webkit_settings_get_enable_tabs_to_links: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-tabs-to-links property. - * - * Returns: %TRUE If tabs to link is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_tabs_to_links(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->tabsToLinks(); -} - -/** - * webkit_settings_set_enable_tabs_to_links: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-tabs-to-links property. - */ -void webkit_settings_set_enable_tabs_to_links(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->tabsToLinks(); - if (currentValue == enabled) - return; - - priv->preferences->setTabsToLinks(enabled); - g_object_notify(G_OBJECT(settings), "enable-tabs-to-links"); -} - -/** - * webkit_settings_get_enable_dns_prefetching: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-dns-prefetching property. - * - * Returns: %TRUE If DNS prefetching is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_dns_prefetching(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->dnsPrefetchingEnabled(); -} - -/** - * webkit_settings_set_enable_dns_prefetching: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-dns-prefetching property. - */ -void webkit_settings_set_enable_dns_prefetching(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->dnsPrefetchingEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setDNSPrefetchingEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-dns-prefetching"); -} - -/** - * webkit_settings_get_enable_caret_browsing: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-caret-browsing property. - * - * Returns: %TRUE If caret browsing is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_caret_browsing(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->caretBrowsingEnabled(); -} - -/** - * webkit_settings_set_enable_caret_browsing: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-caret-browsing property. - */ -void webkit_settings_set_enable_caret_browsing(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->caretBrowsingEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setCaretBrowsingEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-caret-browsing"); -} - -/** - * webkit_settings_get_enable_fullscreen: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-fullscreen property. - * - * Returns: %TRUE If fullscreen support is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_fullscreen(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->fullScreenEnabled(); -} - -/** - * webkit_settings_set_enable_fullscreen: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-fullscreen property. - */ -void webkit_settings_set_enable_fullscreen(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->fullScreenEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setFullScreenEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-fullscreen"); -} - -/** - * webkit_settings_get_print_backgrounds: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:print-backgrounds property. - * - * Returns: %TRUE If background images should be printed or %FALSE otherwise. - */ -gboolean webkit_settings_get_print_backgrounds(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->shouldPrintBackgrounds(); -} - -/** - * webkit_settings_set_print_backgrounds: - * @settings: a #WebKitSettings - * @print_backgrounds: Value to be set - * - * Set the #WebKitSettings:print-backgrounds property. - */ -void webkit_settings_set_print_backgrounds(WebKitSettings* settings, gboolean printBackgrounds) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->shouldPrintBackgrounds(); - if (currentValue == printBackgrounds) - return; - - priv->preferences->setShouldPrintBackgrounds(printBackgrounds); - g_object_notify(G_OBJECT(settings), "print-backgrounds"); -} - -/** - * webkit_settings_get_enable_webaudio: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-webaudio property. - * - * Returns: %TRUE If webaudio support is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_webaudio(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->webAudioEnabled(); -} - -/** - * webkit_settings_set_enable_webaudio: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-webaudio property. - */ -void webkit_settings_set_enable_webaudio(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->webAudioEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setWebAudioEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-webaudio"); -} - -/** - * webkit_settings_get_enable_webgl: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-webgl property. - * - * Returns: %TRUE If webgl support is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_webgl(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->webGLEnabled(); -} - -/** - * webkit_settings_set_enable_webgl: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-webgl property. - */ -void webkit_settings_set_enable_webgl(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->webGLEnabled(); - if (currentValue == enabled) - return; - - priv->preferences->setWebGLEnabled(enabled); - g_object_notify(G_OBJECT(settings), "enable-webgl"); -} - -/** - * webkit_settings_get_allow_modal_dialogs: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:allow-modal-dialogs property. - * - * Returns: %TRUE if it's allowed to create and run modal dialogs or %FALSE otherwise. - */ -gboolean webkit_settings_get_allow_modal_dialogs(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - return settings->priv->allowModalDialogs; -} - -/** - * webkit_settings_set_allow_modal_dialogs: - * @settings: a #WebKitSettings - * @allowed: Value to be set - * - * Set the #WebKitSettings:allow-modal-dialogs property. - */ -void webkit_settings_set_allow_modal_dialogs(WebKitSettings* settings, gboolean allowed) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - if (priv->allowModalDialogs == allowed) - return; - - priv->allowModalDialogs = allowed; - g_object_notify(G_OBJECT(settings), "allow-modal-dialogs"); -} - -/** - * webkit_settings_get_zoom_text_only: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:zoom-text-only property. - * - * Returns: %TRUE If zoom level of the view should only affect the text - * or %FALSE if all view contents should be scaled. - */ -gboolean webkit_settings_get_zoom_text_only(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->zoomTextOnly; -} - -/** - * webkit_settings_set_zoom_text_only: - * @settings: a #WebKitSettings - * @zoom_text_only: Value to be set - * - * Set the #WebKitSettings:zoom-text-only property. - */ -void webkit_settings_set_zoom_text_only(WebKitSettings* settings, gboolean zoomTextOnly) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - if (priv->zoomTextOnly == zoomTextOnly) - return; - - priv->zoomTextOnly = zoomTextOnly; - g_object_notify(G_OBJECT(settings), "zoom-text-only"); -} - -/** - * webkit_settings_get_javascript_can_access_clipboard: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:javascript-can-access-clipboard property. - * - * Returns: %TRUE If javascript-can-access-clipboard is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_javascript_can_access_clipboard(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->javaScriptCanAccessClipboard() - && settings->priv->preferences->domPasteAllowed(); -} - -/** - * webkit_settings_set_javascript_can_access_clipboard: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:javascript-can-access-clipboard property. - */ -void webkit_settings_set_javascript_can_access_clipboard(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->javaScriptCanAccessClipboard() && priv->preferences->domPasteAllowed(); - if (currentValue == enabled) - return; - - priv->preferences->setJavaScriptCanAccessClipboard(enabled); - priv->preferences->setDOMPasteAllowed(enabled); - g_object_notify(G_OBJECT(settings), "javascript-can-access-clipboard"); -} - -/** - * webkit_settings_get_media_playback_requires_user_gesture: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:media-playback-requires-user-gesture property. - * - * Returns: %TRUE If an user gesture is needed to play or load media - * or %FALSE if no user gesture is needed. - */ -gboolean webkit_settings_get_media_playback_requires_user_gesture(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->mediaPlaybackRequiresUserGesture(); -} - -/** - * webkit_settings_set_media_playback_requires_user_gesture: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:media-playback-requires-user-gesture property. - */ -void webkit_settings_set_media_playback_requires_user_gesture(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->mediaPlaybackRequiresUserGesture(); - if (currentValue == enabled) - return; - - priv->preferences->setMediaPlaybackRequiresUserGesture(enabled); - g_object_notify(G_OBJECT(settings), "media-playback-requires-user-gesture"); -} - -/** - * webkit_settings_get_media_playback_allows_inline: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:media-playback-allows-inline property. - * - * Returns: %TRUE If inline playback is allowed for media - * or %FALSE if only fullscreen playback is allowed. - */ -gboolean webkit_settings_get_media_playback_allows_inline(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), TRUE); - - return settings->priv->preferences->mediaPlaybackAllowsInline(); -} - -/** - * webkit_settings_set_media_playback_allows_inline: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:media-playback-allows-inline property. - */ -void webkit_settings_set_media_playback_allows_inline(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->mediaPlaybackAllowsInline(); - if (currentValue == enabled) - return; - - priv->preferences->setMediaPlaybackAllowsInline(enabled); - g_object_notify(G_OBJECT(settings), "media-playback-allows-inline"); -} - -/** - * webkit_settings_get_draw_compositing_indicators: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:draw-compositing-indicators property. - * - * Returns: %TRUE If compositing borders are drawn or %FALSE otherwise. - */ -gboolean webkit_settings_get_draw_compositing_indicators(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - return settings->priv->preferences->compositingBordersVisible() - && settings->priv->preferences->compositingRepaintCountersVisible(); -} - -/** - * webkit_settings_set_draw_compositing_indicators: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:draw-compositing-indicators property. - */ -void webkit_settings_set_draw_compositing_indicators(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - if (priv->preferences->compositingBordersVisible() == enabled - && priv->preferences->compositingRepaintCountersVisible() == enabled) - return; - - priv->preferences->setCompositingBordersVisible(enabled); - priv->preferences->setCompositingRepaintCountersVisible(enabled); - g_object_notify(G_OBJECT(settings), "draw-compositing-indicators"); -} - -/** - * webkit_settings_get_enable_site_specific_quirks: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-site-specific-quirks property. - * - * Returns: %TRUE if site specific quirks are enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_site_specific_quirks(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->needsSiteSpecificQuirks(); -} - -/** - * webkit_settings_set_enable_site_specific_quirks: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-site-specific-quirks property. - */ -void webkit_settings_set_enable_site_specific_quirks(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->needsSiteSpecificQuirks(); - if (currentValue == enabled) - return; - - priv->preferences->setNeedsSiteSpecificQuirks(enabled); - g_object_notify(G_OBJECT(settings), "enable-site-specific-quirks"); -} - -/** - * webkit_settings_get_enable_page_cache: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-page-cache property. - * - * Returns: %TRUE if page cache enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_page_cache(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->usesPageCache(); -} - -/** - * webkit_settings_set_enable_page_cache: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-page-cache property. - */ -void webkit_settings_set_enable_page_cache(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->usesPageCache(); - if (currentValue == enabled) - return; - - priv->preferences->setUsesPageCache(enabled); - g_object_notify(G_OBJECT(settings), "enable-page-cache"); -} - -/** - * webkit_settings_get_user_agent: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:user-agent property. - * - * Returns: The current value of the user-agent property. - */ -const char* webkit_settings_get_user_agent(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0); - - WebKitSettingsPrivate* priv = settings->priv; - ASSERT(!priv->userAgent.isNull()); - return priv->userAgent.data(); -} - -/** - * webkit_settings_set_user_agent: - * @settings: a #WebKitSettings - * @user_agent: (allow-none): The new custom user agent string or %NULL to use the default user agent - * - * Set the #WebKitSettings:user-agent property. - */ -void webkit_settings_set_user_agent(WebKitSettings* settings, const char* userAgent) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - CString newUserAgent = (!userAgent || !strlen(userAgent)) ? WebCore::standardUserAgent("").utf8() : userAgent; - if (newUserAgent == priv->userAgent) - return; - - priv->userAgent = newUserAgent; - g_object_notify(G_OBJECT(settings), "user-agent"); -} - -/** - * webkit_settings_set_user_agent_with_application_details: - * @settings: a #WebKitSettings - * @application_name: (allow-none): The application name used for the user agent or %NULL to use the default user agent. - * @application_version: (allow-none): The application version for the user agent or %NULL to user the default version. - * - * Set the #WebKitSettings:user-agent property by appending the application details to the default user - * agent. If no application name or version is given, the default user agent used will be used. If only - * the version is given, the default engine version is used with the given application name. - */ -void webkit_settings_set_user_agent_with_application_details(WebKitSettings* settings, const char* applicationName, const char* applicationVersion) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - CString newUserAgent = WebCore::standardUserAgent(String::fromUTF8(applicationName), String::fromUTF8(applicationVersion)).utf8(); - webkit_settings_set_user_agent(settings, newUserAgent.data()); -} - -/** - * webkit_settings_get_enable_smooth_scrolling: - * @settings: a #WebKitSettings - * - * Get the #WebKitSettings:enable-smooth-scrolling property. - * - * Returns: %TRUE if smooth scrolling is enabled or %FALSE otherwise. - */ -gboolean webkit_settings_get_enable_smooth_scrolling(WebKitSettings* settings) -{ - g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE); - - return settings->priv->preferences->scrollAnimatorEnabled(); -} - -/** - * webkit_settings_set_enable_smooth_scrolling: - * @settings: a #WebKitSettings - * @enabled: Value to be set - * - * Set the #WebKitSettings:enable-smooth-scrolling property. - */ -void webkit_settings_set_enable_smooth_scrolling(WebKitSettings* settings, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_SETTINGS(settings)); - - WebKitSettingsPrivate* priv = settings->priv; - bool currentValue = priv->preferences->scrollAnimatorEnabled(); - if (currentValue == enabled) - return; - - 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 deleted file mode 100644 index a904d0eb6..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSettings.h +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * Neither the name of Motorola Mobility, Inc. nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitSettings_h -#define WebKitSettings_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_SETTINGS (webkit_settings_get_type()) -#define WEBKIT_SETTINGS(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_SETTINGS, WebKitSettings)) -#define WEBKIT_SETTINGS_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_SETTINGS, WebKitSettingsClass)) -#define WEBKIT_IS_SETTINGS(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_SETTINGS)) -#define WEBKIT_IS_SETTINGS_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_SETTINGS)) -#define WEBKIT_SETTINGS_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_SETTINGS, WebKitSettingsClass)) - -typedef struct _WebKitSettings WebKitSettings; -typedef struct _WebKitSettingsClass WebKitSettingsClass; -typedef struct _WebKitSettingsPrivate WebKitSettingsPrivate; - -struct _WebKitSettings { - GObject parent_instance; - - WebKitSettingsPrivate *priv; -}; - -struct _WebKitSettingsClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_settings_get_type(void); - -WEBKIT_API WebKitSettings * -webkit_settings_new (void); - -WEBKIT_API WebKitSettings * -webkit_settings_new_with_settings (const gchar *first_setting_name, - ...); - -WEBKIT_API gboolean -webkit_settings_get_enable_javascript (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_javascript (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_auto_load_images (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_auto_load_images (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_load_icons_ignoring_image_load_setting (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_load_icons_ignoring_image_load_setting (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_offline_web_application_cache (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_offline_web_application_cache (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_html5_local_storage (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_html5_local_storage (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_html5_database (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_html5_database (WebKitSettings *settings, - gboolean enabled); -WEBKIT_API gboolean -webkit_settings_get_enable_xss_auditor (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_xss_auditor (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_frame_flattening (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_frame_flattening (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_plugins (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_plugins (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_java (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_java (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_javascript_can_open_windows_automatically (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_javascript_can_open_windows_automatically (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_hyperlink_auditing (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_hyperlink_auditing (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API const gchar * -webkit_settings_get_default_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_default_font_family (WebKitSettings *settings, - const gchar *default_font_family); - -WEBKIT_API const gchar * -webkit_settings_get_monospace_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_monospace_font_family (WebKitSettings *settings, - const gchar *monospace_font_family); - -WEBKIT_API const gchar * -webkit_settings_get_serif_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_serif_font_family (WebKitSettings *settings, - const gchar *serif_font_family); - -WEBKIT_API const gchar * -webkit_settings_get_sans_serif_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_sans_serif_font_family (WebKitSettings *settings, - const gchar *sans_serif_font_family); - -WEBKIT_API const gchar * -webkit_settings_get_cursive_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_cursive_font_family (WebKitSettings *settings, - const gchar *cursive_font_family); - -WEBKIT_API const gchar * -webkit_settings_get_fantasy_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_fantasy_font_family (WebKitSettings *settings, - const gchar *fantasy_font_family); - -WEBKIT_API const gchar * -webkit_settings_get_pictograph_font_family (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_pictograph_font_family (WebKitSettings *settings, - const gchar *pictograph_font_family); - -WEBKIT_API guint32 -webkit_settings_get_default_font_size (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_default_font_size (WebKitSettings *settings, - guint32 font_size); - -WEBKIT_API guint32 -webkit_settings_get_default_monospace_font_size (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_default_monospace_font_size (WebKitSettings *settings, - guint32 font_size); - -WEBKIT_API guint32 -webkit_settings_get_minimum_font_size (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_minimum_font_size (WebKitSettings *settings, - guint32 font_size); - -WEBKIT_API const gchar * -webkit_settings_get_default_charset (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_default_charset (WebKitSettings *settings, - const gchar *default_charset); - -WEBKIT_API gboolean -webkit_settings_get_enable_private_browsing (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_private_browsing (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_developer_extras (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_developer_extras (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_resizable_text_areas (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_resizable_text_areas (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_tabs_to_links (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_tabs_to_links (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_dns_prefetching (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_dns_prefetching (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_caret_browsing (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_caret_browsing (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_fullscreen (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_fullscreen (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_print_backgrounds (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_print_backgrounds (WebKitSettings *settings, - gboolean print_backgrounds); - -WEBKIT_API gboolean -webkit_settings_get_enable_webaudio (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_webaudio (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_webgl (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_webgl (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API void -webkit_settings_set_allow_modal_dialogs (WebKitSettings *settings, - gboolean allowed); - -WEBKIT_API gboolean -webkit_settings_get_allow_modal_dialogs (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_zoom_text_only (WebKitSettings *settings, - gboolean zoom_text_only); - -WEBKIT_API gboolean -webkit_settings_get_zoom_text_only (WebKitSettings *settings); - -WEBKIT_API gboolean -webkit_settings_get_javascript_can_access_clipboard (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_javascript_can_access_clipboard (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_media_playback_requires_user_gesture (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_media_playback_requires_user_gesture (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_media_playback_allows_inline (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_media_playback_allows_inline (WebKitSettings *settings, - gboolean enabled); -WEBKIT_API gboolean -webkit_settings_get_draw_compositing_indicators (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_draw_compositing_indicators (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_site_specific_quirks (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_site_specific_quirks (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API gboolean -webkit_settings_get_enable_page_cache (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_enable_page_cache (WebKitSettings *settings, - gboolean enabled); - -WEBKIT_API const gchar * -webkit_settings_get_user_agent (WebKitSettings *settings); - -WEBKIT_API void -webkit_settings_set_user_agent (WebKitSettings *settings, - const gchar *user_agent); -WEBKIT_API void -webkit_settings_set_user_agent_with_application_details (WebKitSettings *settings, - const gchar *application_name, - const gchar *application_version); - -WEBKIT_API gboolean -webkit_settings_get_enable_smooth_scrolling (WebKitSettings *settings); - -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 deleted file mode 100644 index c23a8cd1f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitSettingsPrivate.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef WebKitSettingsPrivate_h -#define WebKitSettingsPrivate_h - -#include "WebKitSettings.h" -#include "WebPreferences.h" - -WebKit::WebPreferences* webkitSettingsGetPreferences(WebKitSettings*); - -#endif // WebKitSettingsPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitTextChecker.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitTextChecker.cpp deleted file mode 100644 index 89e746d47..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitTextChecker.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#include "config.h" -#include "WebKitTextChecker.h" - -#if ENABLE(SPELLCHECK) - -#include "WebKitPrivate.h" - -using namespace WebKit; - -static inline WebKitTextChecker* toTextChecker(const void* clientInfo) -{ - return static_cast<WebKitTextChecker*>(const_cast<void*>(clientInfo)); -} - -static bool continuousSpellCheckingEnabledCallback(const void* clientInfo) -{ - return toTextChecker(clientInfo)->isSpellCheckingEnabled(); -} - -static void setContinuousSpellCheckingEnabledCallback(bool enabled, const void* clientInfo) -{ - toTextChecker(clientInfo)->setSpellCheckingEnabled(enabled); -} - -static void checkSpellingOfStringCallback(uint64_t tag, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void* clientInfo) -{ - toTextChecker(clientInfo)->checkSpellingOfString(toImpl(text)->string(), *misspellingLocation, *misspellingLength); -} - -static WKArrayRef guessesForWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) -{ - Vector<String> guesses = toTextChecker(clientInfo)->getGuessesForWord(toImpl(word)->string()); - if (guesses.isEmpty()) - return 0; - - WKMutableArrayRef wkSuggestions = WKMutableArrayCreate(); - for (Vector<String>::const_iterator iter = guesses.begin(); iter != guesses.end(); ++iter) { - WKRetainPtr<WKStringRef> wkSuggestion(AdoptWK, WKStringCreateWithUTF8CString(iter->utf8().data())); - WKArrayAppendItem(wkSuggestions, wkSuggestion.get()); - } - - return wkSuggestions; -} - -static void learnWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) -{ - toTextChecker(clientInfo)->learnWord(toImpl(word)->string()); -} - -static void ignoreWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) -{ - toTextChecker(clientInfo)->ignoreWord(toImpl(word)->string()); -} - -WebKitTextChecker::~WebKitTextChecker() -{ -} - -WebKitTextChecker::WebKitTextChecker() - : m_textChecker(WebCore::TextCheckerEnchant::create()) - , m_spellCheckingEnabled(false) -{ - WKTextCheckerClient wkTextCheckerClient = { - kWKTextCheckerClientCurrentVersion, - this, // clientInfo - 0, // continuousSpellCheckingAllowed - continuousSpellCheckingEnabledCallback, - setContinuousSpellCheckingEnabledCallback, - 0, // grammarCheckingEnabled - 0, // setGrammarCheckingEnabled - 0, // uniqueSpellDocumentTag - 0, // closeSpellDocumentWithTag - checkSpellingOfStringCallback, - 0, // checkGrammarOfString - 0, // spellingUIIsShowing - 0, // toggleSpellingUIIsShowing - 0, // updateSpellingUIWithMisspelledWord - 0, // updateSpellingUIWithGrammarString - guessesForWordCallback, - learnWordCallback, - ignoreWordCallback, - }; - WKTextCheckerSetClient(&wkTextCheckerClient); -} - -void WebKitTextChecker::checkSpellingOfString(const String& string, int& misspellingLocation, int& misspellingLength) -{ - m_textChecker->checkSpellingOfString(string, misspellingLocation, misspellingLength); -} - -Vector<String> WebKitTextChecker::getGuessesForWord(const String& word) -{ - return m_textChecker->getGuessesForWord(word); -} - -void WebKitTextChecker::learnWord(const String& word) -{ - m_textChecker->learnWord(word); -} - -void WebKitTextChecker::ignoreWord(const String& word) -{ - m_textChecker->ignoreWord(word); -} - -void WebKitTextChecker::setSpellCheckingEnabled(bool enabled) -{ - if (m_spellCheckingEnabled == enabled) - return; - m_spellCheckingEnabled = enabled; - - // We need to notify the Web process that this has changed. - WKTextCheckerContinuousSpellCheckingEnabledStateChanged(enabled); -} - -const char* const* WebKitTextChecker::getSpellCheckingLanguages() -{ - Vector<String> spellCheckingLanguages = m_textChecker->loadedSpellCheckingLanguages(); - if (spellCheckingLanguages.isEmpty()) - return 0; - - m_spellCheckingLanguages = adoptGRef(g_ptr_array_new_with_free_func(g_free)); - for (size_t i = 0; i < spellCheckingLanguages.size(); ++i) - g_ptr_array_add(m_spellCheckingLanguages.get(), g_strdup(spellCheckingLanguages[i].utf8().data())); - g_ptr_array_add(m_spellCheckingLanguages.get(), 0); - - return reinterpret_cast<char**>(m_spellCheckingLanguages->pdata); -} - -void WebKitTextChecker::setSpellCheckingLanguages(const char* const* languages) -{ - Vector<String> spellCheckingLanguages; - for (size_t i = 0; languages[i]; ++i) - spellCheckingLanguages.append(String::fromUTF8(languages[i])); - m_textChecker->updateSpellCheckingLanguages(spellCheckingLanguages); -} -#endif // ENABLE(SPELLCHECK) diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitTextChecker.h b/Source/WebKit2/UIProcess/API/gtk/WebKitTextChecker.h deleted file mode 100644 index 15f764f61..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitTextChecker.h +++ /dev/null @@ -1,61 +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. - */ - -#ifndef WebKitTextChecker_h -#define WebKitTextChecker_h - -#if ENABLE(SPELLCHECK) - -#include <WebCore/TextCheckerEnchant.h> -#include <wtf/FastAllocBase.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -class WebKitTextChecker { - WTF_MAKE_FAST_ALLOCATED; - -public: - static PassOwnPtr<WebKitTextChecker> create() { return adoptPtr(new WebKitTextChecker()); } - virtual ~WebKitTextChecker(); - - // For implementing TextCheckerClient. - bool isSpellCheckingEnabled() { return m_spellCheckingEnabled; } - void setSpellCheckingEnabled(bool enabled); - void checkSpellingOfString(const String& string, int& misspellingLocation, int& misspellingLength); - Vector<String> getGuessesForWord(const String& word); - void learnWord(const String& word); - void ignoreWord(const String& word); - - // To be called from WebKitWebContext only. - const char* const* getSpellCheckingLanguages(); - void setSpellCheckingLanguages(const char* const* spellCheckingLanguages); - -private: - WebKitTextChecker(); - - OwnPtr<WebCore::TextCheckerEnchant> m_textChecker; - GRefPtr<GPtrArray> m_spellCheckingLanguages; - bool m_spellCheckingEnabled; -}; - -#endif // ENABLE(SPELLCHECK) - -#endif // WebKitTextChecker_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp deleted file mode 100644 index 0899b8563..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (C) 2011, 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 "WebKitUIClient.h" - -#include "WebKitFileChooserRequestPrivate.h" -#include "WebKitGeolocationPermissionRequestPrivate.h" -#include "WebKitPrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewPrivate.h" -#include "WebKitWindowPropertiesPrivate.h" -#include "WebPageProxy.h" -#include <WebCore/GtkUtilities.h> -#include <wtf/gobject/GRefPtr.h> - -using namespace WebKit; - -static WKPageRef createNewPage(WKPageRef page, WKURLRequestRef, WKDictionaryRef wkWindowFeatures, WKEventModifiers, WKEventMouseButton, const void* clientInfo) -{ - return static_cast<WKPageRef>(toAPI(webkitWebViewCreateNewPage(WEBKIT_WEB_VIEW(clientInfo), toImpl(wkWindowFeatures)))); -} - -static void showPage(WKPageRef page, const void* clientInfo) -{ - webkitWebViewReadyToShowPage(WEBKIT_WEB_VIEW(clientInfo)); -} - -static void closePage(WKPageRef page, const void* clientInfo) -{ - webkitWebViewClosePage(WEBKIT_WEB_VIEW(clientInfo)); -} - -static void runJavaScriptAlert(WKPageRef page, WKStringRef message, WKFrameRef, const void* clientInfo) -{ - webkitWebViewRunJavaScriptAlert(WEBKIT_WEB_VIEW(clientInfo), toImpl(message)->string().utf8()); -} - -static bool runJavaScriptConfirm(WKPageRef page, WKStringRef message, WKFrameRef, const void* clientInfo) -{ - return webkitWebViewRunJavaScriptConfirm(WEBKIT_WEB_VIEW(clientInfo), toImpl(message)->string().utf8()); -} - -static WKStringRef runJavaScriptPrompt(WKPageRef page, WKStringRef message, WKStringRef defaultValue, WKFrameRef, const void* clientInfo) -{ - CString result = webkitWebViewRunJavaScriptPrompt(WEBKIT_WEB_VIEW(clientInfo), toImpl(message)->string().utf8(), - toImpl(defaultValue)->string().utf8()); - return WKStringCreateWithUTF8CString(result.data()); -} - -static bool toolbarsAreVisible(WKPageRef page, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - return webkit_window_properties_get_toolbar_visible(windowProperties); -} - -static void setToolbarsAreVisible(WKPageRef page, bool toolbarsVisible, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - webkitWindowPropertiesSetToolbarVisible(windowProperties, toolbarsVisible); -} - -static bool menuBarIsVisible(WKPageRef page, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - return webkit_window_properties_get_menubar_visible(windowProperties); -} - -static void setMenuBarIsVisible(WKPageRef page, bool menuBarVisible, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - webkitWindowPropertiesSetMenubarVisible(windowProperties, menuBarVisible); -} - -static bool statusBarIsVisible(WKPageRef page, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - return webkit_window_properties_get_statusbar_visible(windowProperties); -} - -static void setStatusBarIsVisible(WKPageRef page, bool statusBarVisible, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - webkitWindowPropertiesSetStatusbarVisible(windowProperties, statusBarVisible); -} - -static bool isResizable(WKPageRef page, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - return webkit_window_properties_get_resizable(windowProperties); -} - -static void setIsResizable(WKPageRef page, bool resizable, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - webkitWindowPropertiesSetResizable(windowProperties, resizable); -} - -static WKRect getWindowFrame(WKPageRef page, const void* clientInfo) -{ - GdkRectangle geometry = { 0, 0, 0, 0 }; - GtkWidget* window = gtk_widget_get_toplevel(GTK_WIDGET(clientInfo)); - if (WebCore::widgetIsOnscreenToplevelWindow(window) && gtk_widget_get_visible(window)) { - gtk_window_get_position(GTK_WINDOW(window), &geometry.x, &geometry.y); - gtk_window_get_size(GTK_WINDOW(window), &geometry.width, &geometry.height); - } - return WKRectMake(geometry.x, geometry.y, geometry.width, geometry.height); -} - -static void setWindowFrame(WKPageRef page, WKRect frame, const void* clientInfo) -{ - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(clientInfo)); - 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); -} - -static void mouseDidMoveOverElement(WKPageRef page, WKHitTestResultRef hitTestResult, WKEventModifiers modifiers, WKTypeRef userData, const void* clientInfo) -{ - webkitWebViewMouseTargetChanged(WEBKIT_WEB_VIEW(clientInfo), toImpl(hitTestResult), wkEventModifiersToGdkModifiers(modifiers)); -} - -static void printFrame(WKPageRef page, WKFrameRef frame, const void*) -{ - webkitWebViewPrintFrame(WEBKIT_WEB_VIEW(toImpl(page)->viewWidget()), toImpl(frame)); -} - -static void runOpenPanel(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void *clientInfo) -{ - GRefPtr<WebKitFileChooserRequest> request = adoptGRef(webkitFileChooserRequestCreate(toImpl(parameters), toImpl(listener))); - webkitWebViewRunFileChooserRequest(WEBKIT_WEB_VIEW(clientInfo), request.get()); -} - -static void decidePolicyForGeolocationPermissionRequest(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKGeolocationPermissionRequestRef request, const void* clientInfo) -{ - GRefPtr<WebKitGeolocationPermissionRequest> geolocationPermissionRequest = adoptGRef(webkitGeolocationPermissionRequestCreate(toImpl(request))); - webkitWebViewMakePermissionRequest(WEBKIT_WEB_VIEW(clientInfo), WEBKIT_PERMISSION_REQUEST(geolocationPermissionRequest.get())); -} - -static void runModal(WKPageRef page, const void* clientInfo) -{ - webkitWebViewRunAsModal(WEBKIT_WEB_VIEW(clientInfo)); -} - -void attachUIClientToView(WebKitWebView* webView) -{ - WKPageUIClient wkUIClient = { - kWKPageUIClientCurrentVersion, - webView, // clientInfo - 0, // createNewPage_deprecatedForUseWithV0 - showPage, - closePage, - 0, // takeFocus - 0, // focus - 0, // unfocus - runJavaScriptAlert, - runJavaScriptConfirm, - runJavaScriptPrompt, - 0, // setStatusText - 0, // mouseDidMoveOverElement_deprecatedForUseWithV0 - 0, // missingPluginButtonClicked - 0, // didNotHandleKeyEvent - 0, // didNotHandleWheelEvent - toolbarsAreVisible, - setToolbarsAreVisible, - menuBarIsVisible, - setMenuBarIsVisible, - statusBarIsVisible, - setStatusBarIsVisible, - isResizable, - setIsResizable, - getWindowFrame, - setWindowFrame, - 0, // runBeforeUnloadConfirmPanel - 0, // didDraw - 0, // pageDidScroll - 0, // exceededDatabaseQuota - runOpenPanel, - decidePolicyForGeolocationPermissionRequest, - 0, // headerHeight - 0, // footerHeight - 0, // drawHeader - 0, // drawFooter - printFrame, - runModal, - 0, // didCompleteRubberBandForMainFrame - 0, // saveDataToFileInDownloadsFolder - 0, // shouldInterruptJavaScript - createNewPage, - mouseDidMoveOverElement, - 0, // decidePolicyForNotificationPermissionRequest - 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/WebKitUIClient.h b/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.h deleted file mode 100644 index e5a1a3e0f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitUIClient.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitUIClient_h -#define WebKitUIClient_h - -#include "WebKitWebView.h" - -void attachUIClientToView(WebKitWebView*); - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp deleted file mode 100644 index 50c6eea5d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitURIRequest.h" - -#include "WebKitPrivate.h" -#include "WebKitURIRequestPrivate.h" -#include <WebCore/GOwnPtrSoup.h> -#include <glib/gi18n-lib.h> -#include <wtf/text/CString.h> - -enum { - PROP_0, - - PROP_URI -}; - -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) - -static void webkitURIRequestGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitURIRequest* request = WEBKIT_URI_REQUEST(object); - - switch (propId) { - case PROP_URI: - g_value_set_string(value, webkit_uri_request_get_uri(request)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkitURIRequestSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) -{ - WebKitURIRequest* request = WEBKIT_URI_REQUEST(object); - - switch (propId) { - case PROP_URI: - webkit_uri_request_set_uri(request, g_value_get_string(value)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_uri_request_class_init(WebKitURIRequestClass* requestClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(requestClass); - objectClass->get_property = webkitURIRequestGetProperty; - objectClass->set_property = webkitURIRequestSetProperty; - - /** - * WebKitURIRequest:uri: - * - * The URI to which the request will be made. - */ - g_object_class_install_property(objectClass, PROP_URI, - g_param_spec_string("uri", - _("URI"), - _("The URI to which the request will be made."), - "about:blank", - static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT))); -} - -/** - * webkit_uri_request_new: - * @uri: an URI - * - * Creates a new #WebKitURIRequest for the given URI. - * - * Returns: a new #WebKitURIRequest - */ -WebKitURIRequest* webkit_uri_request_new(const gchar* uri) -{ - g_return_val_if_fail(uri, 0); - - return WEBKIT_URI_REQUEST(g_object_new(WEBKIT_TYPE_URI_REQUEST, "uri", uri, NULL)); -} - -/** - * webkit_uri_request_get_uri: - * @request: a #WebKitURIRequest - * - * Returns: the uri of the #WebKitURIRequest - */ -const gchar* webkit_uri_request_get_uri(WebKitURIRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_URI_REQUEST(request), 0); - - request->priv->uri = request->priv->resourceRequest.url().string().utf8(); - return request->priv->uri.data(); -} - -/** - * 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; -} - -void webkitURIRequestGetResourceRequest(WebKitURIRequest* request, ResourceRequest& 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 deleted file mode 100644 index cac3b332b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIRequest.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2011 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) && !defined(__WEBKIT_WEB_EXTENSION_H_INSIDE__) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitURIRequest_h -#define WebKitURIRequest_h - -#include <glib-object.h> -#include <libsoup/soup.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_URI_REQUEST (webkit_uri_request_get_type()) -#define WEBKIT_URI_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_URI_REQUEST, WebKitURIRequest)) -#define WEBKIT_IS_URI_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_URI_REQUEST)) -#define WEBKIT_URI_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_URI_REQUEST, WebKitURIRequestClass)) -#define WEBKIT_IS_URI_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_URI_REQUEST)) -#define WEBKIT_URI_REQUEST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_URI_REQUEST, WebKitURIRequestClass)) - -typedef struct _WebKitURIRequest WebKitURIRequest; -typedef struct _WebKitURIRequestClass WebKitURIRequestClass; -typedef struct _WebKitURIRequestPrivate WebKitURIRequestPrivate; - -struct _WebKitURIRequest { - GObject parent; - - /*< private >*/ - WebKitURIRequestPrivate *priv; -}; - -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_API WebKitURIRequest * -webkit_uri_request_new (const gchar *uri); - -WEBKIT_API const gchar * -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 - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp deleted file mode 100644 index 20ab248a5..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitURIResponse.h" - -#include "WebKitPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include <glib/gi18n-lib.h> -#include <wtf/text/CString.h> - -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, - - PROP_URI, - PROP_STATUS_CODE, - PROP_CONTENT_LENGTH, - PROP_MIME_TYPE, - PROP_SUGGESTED_FILENAME -}; - -struct _WebKitURIResponsePrivate { - ResourceResponse resourceResponse; - CString uri; - CString mimeType; - CString suggestedFilename; -}; - -WEBKIT_DEFINE_TYPE(WebKitURIResponse, webkit_uri_response, G_TYPE_OBJECT) - -static void webkitURIResponseGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitURIResponse* response = WEBKIT_URI_RESPONSE(object); - - switch (propId) { - case PROP_URI: - g_value_set_string(value, webkit_uri_response_get_uri(response)); - break; - case PROP_STATUS_CODE: - g_value_set_uint(value, webkit_uri_response_get_status_code(response)); - break; - case PROP_CONTENT_LENGTH: - g_value_set_uint64(value, webkit_uri_response_get_content_length(response)); - break; - case PROP_MIME_TYPE: - g_value_set_string(value, webkit_uri_response_get_mime_type(response)); - break; - case PROP_SUGGESTED_FILENAME: - g_value_set_string(value, webkit_uri_response_get_suggested_filename(response)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_uri_response_class_init(WebKitURIResponseClass* responseClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(responseClass); - objectClass->get_property = webkitURIResponseGetProperty; - - /** - * WebKitURIResponse:uri: - * - * The URI for which the response was made. - */ - g_object_class_install_property(objectClass, - PROP_URI, - g_param_spec_string("uri", - _("URI"), - _("The URI for which the response was made."), - 0, - WEBKIT_PARAM_READABLE)); - /** - * WebKitURIResponse:status-code: - * - * The status code of the response as returned by the server. - */ - g_object_class_install_property(objectClass, - PROP_STATUS_CODE, - g_param_spec_uint("status-code", - _("Status Code"), - _("The status code of the response as returned by the server."), - 0, G_MAXUINT, SOUP_STATUS_NONE, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitURIResponse:content-length: - * - * The expected content length of the response. - */ - g_object_class_install_property(objectClass, - PROP_CONTENT_LENGTH, - g_param_spec_uint64("content-length", - _("Content Length"), - _("The expected content length of the response."), - 0, G_MAXUINT64, 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitURIResponse:mime-type: - * - * The MIME type of the response. - */ - g_object_class_install_property(objectClass, - PROP_MIME_TYPE, - g_param_spec_string("mime-type", - _("MIME Type"), - _("The MIME type of the response"), - 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitURIResponse:suggested-filename: - * - * The suggested filename for the URI response. - */ - g_object_class_install_property(objectClass, - PROP_SUGGESTED_FILENAME, - g_param_spec_string("suggested-filename", - _("Suggested Filename"), - _("The suggested filename for the URI response"), - 0, - WEBKIT_PARAM_READABLE)); -} - -/** - * webkit_uri_response_get_uri: - * @response: a #WebKitURIResponse - * - * Returns: the uri of the #WebKitURIResponse - */ -const gchar* webkit_uri_response_get_uri(WebKitURIResponse* response) -{ - g_return_val_if_fail(WEBKIT_IS_URI_RESPONSE(response), 0); - - response->priv->uri = response->priv->resourceResponse.url().string().utf8(); - return response->priv->uri.data(); -} - -/** - * webkit_uri_response_get_status_code: - * @response: a #WebKitURIResponse - * - * Get the status code of the #WebKitURIResponse as returned by - * the server. It will normally be a #SoupKnownStatusCode, for - * example %SOUP_STATUS_OK, though the server can respond with any - * unsigned integer. - * - * Returns: the status code of @response - */ -guint webkit_uri_response_get_status_code(WebKitURIResponse* response) -{ - g_return_val_if_fail(WEBKIT_IS_URI_RESPONSE(response), SOUP_STATUS_NONE); - - return response->priv->resourceResponse.httpStatusCode(); -} - -/** - * webkit_uri_response_get_content_length: - * @response: a #WebKitURIResponse - * - * Get the expected content length of the #WebKitURIResponse. It can - * be 0 if the server provided an incorrect or missing Content-Length. - * - * Returns: the expected content length of @response. - */ -guint64 webkit_uri_response_get_content_length(WebKitURIResponse* response) -{ - g_return_val_if_fail(WEBKIT_IS_URI_RESPONSE(response), 0); - - return response->priv->resourceResponse.expectedContentLength(); -} - -/** - * webkit_uri_response_get_mime_type: - * @response: a #WebKitURIResponse - * - * Returns: the MIME type of the #WebKitURIResponse - */ -const gchar* webkit_uri_response_get_mime_type(WebKitURIResponse* response) -{ - g_return_val_if_fail(WEBKIT_IS_URI_RESPONSE(response), 0); - - response->priv->mimeType = response->priv->resourceResponse.mimeType().utf8(); - return response->priv->mimeType.data(); -} - -/** - * webkit_uri_response_get_suggested_filename: - * @response: a #WebKitURIResponse - * - * Get the suggested filename for @response, as specified by - * the 'Content-Disposition' HTTP header, or %NULL if it's not - * present. - * - * Returns: (transfer none): the suggested filename or %NULL if - * the 'Content-Disposition' HTTP header is not present. - */ -const gchar* webkit_uri_response_get_suggested_filename(WebKitURIResponse* response) -{ - g_return_val_if_fail(WEBKIT_IS_URI_RESPONSE(response), 0); - - if (response->priv->resourceResponse.suggestedFilename().isEmpty()) - return 0; - - response->priv->suggestedFilename = response->priv->resourceResponse.suggestedFilename().utf8(); - return response->priv->suggestedFilename.data(); -} - -WebKitURIResponse* webkitURIResponseCreateForResourceResponse(const WebCore::ResourceResponse& resourceResponse) -{ - WebKitURIResponse* uriResponse = WEBKIT_URI_RESPONSE(g_object_new(WEBKIT_TYPE_URI_RESPONSE, NULL)); - uriResponse->priv->resourceResponse = resourceResponse; - return uriResponse; -} - -const WebCore::ResourceResponse& webkitURIResponseGetResourceResponse(WebKitURIResponse* uriResponse) -{ - return uriResponse->priv->resourceResponse; -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h deleted file mode 100644 index d43eca13f..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponse.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2011 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) && !defined(__WEBKIT_WEB_EXTENSION_H_INSIDE__) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitURIResponse_h -#define WebKitURIResponse_h - -#include <gio/gio.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_URI_RESPONSE (webkit_uri_response_get_type()) -#define WEBKIT_URI_RESPONSE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_URI_RESPONSE, WebKitURIResponse)) -#define WEBKIT_IS_URI_RESPONSE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_URI_RESPONSE)) -#define WEBKIT_URI_RESPONSE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_URI_RESPONSE, WebKitURIResponseClass)) -#define WEBKIT_IS_URI_RESPONSE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_URI_RESPONSE)) -#define WEBKIT_URI_RESPONSE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_URI_RESPONSE, WebKitURIResponseClass)) - -typedef struct _WebKitURIResponse WebKitURIResponse; -typedef struct _WebKitURIResponseClass WebKitURIResponseClass; -typedef struct _WebKitURIResponsePrivate WebKitURIResponsePrivate; - -struct _WebKitURIResponse { - GObject parent; - - /*< private >*/ - WebKitURIResponsePrivate *priv; -}; - -struct _WebKitURIResponseClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_uri_response_get_type (void); - -WEBKIT_API const gchar * -webkit_uri_response_get_uri (WebKitURIResponse *response); - -WEBKIT_API guint -webkit_uri_response_get_status_code (WebKitURIResponse *response); - -WEBKIT_API guint64 -webkit_uri_response_get_content_length (WebKitURIResponse *response); - -WEBKIT_API const gchar * -webkit_uri_response_get_mime_type (WebKitURIResponse *response); - -WEBKIT_API const gchar * -webkit_uri_response_get_suggested_filename (WebKitURIResponse *response); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h deleted file mode 100644 index c2dc49c17..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURIResponsePrivate.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef WebKitURIResponsePrivate_h -#define WebKitURIResponsePrivate_h - -#include "WebKitURIResponse.h" -#include <WebCore/ResourceResponse.h> - -WebKitURIResponse* webkitURIResponseCreateForResourceResponse(const WebCore::ResourceResponse&); -const WebCore::ResourceResponse& webkitURIResponseGetResourceResponse(WebKitURIResponse*); - -#endif // WebKitURIResponsePrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp deleted file mode 100644 index 0e5218129..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.cpp +++ /dev/null @@ -1,238 +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 "WebKitURISchemeRequest.h" - -#include "WebData.h" -#include "WebKitURISchemeRequestPrivate.h" -#include "WebKitWebContextPrivate.h" -#include "WebKitWebView.h" -#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 { - WebKitWebContext* webContext; - RefPtr<WebSoupRequestManagerProxy> webRequestManager; - RefPtr<WebPageProxy> initiatingPage; - uint64_t requestID; - CString uri; - GOwnPtr<SoupURI> soupURI; - - GRefPtr<GInputStream> stream; - uint64_t streamLength; - GRefPtr<GCancellable> cancellable; - char readBuffer[gReadBufferSize]; - uint64_t bytesRead; - CString mimeType; -}; - -WEBKIT_DEFINE_TYPE(WebKitURISchemeRequest, webkit_uri_scheme_request, G_TYPE_OBJECT) - -static void webkit_uri_scheme_request_class_init(WebKitURISchemeRequestClass* requestClass) -{ -} - -WebKitURISchemeRequest* webkitURISchemeRequestCreate(WebKitWebContext* webContext, WebSoupRequestManagerProxy* webRequestManager, WebURL* webURL, WebPageProxy* initiatingPage, uint64_t requestID) -{ - WebKitURISchemeRequest* request = WEBKIT_URI_SCHEME_REQUEST(g_object_new(WEBKIT_TYPE_URI_SCHEME_REQUEST, NULL)); - request->priv->webContext = webContext; - request->priv->webRequestManager = webRequestManager; - request->priv->uri = webURL->string().utf8(); - request->priv->initiatingPage = initiatingPage; - request->priv->requestID = requestID; - return request; -} - -uint64_t webkitURISchemeRequestGetID(WebKitURISchemeRequest* request) -{ - return request->priv->requestID; -} - -void webkitURISchemeRequestCancel(WebKitURISchemeRequest* request) -{ - if (request->priv->cancellable.get()) - g_cancellable_cancel(request->priv->cancellable.get()); -} - -/** - * webkit_uri_scheme_request_get_scheme: - * @request: a #WebKitURISchemeRequest - * - * Get the URI scheme of @request - * - * Returns: the URI scheme of @request - */ -const char* webkit_uri_scheme_request_get_scheme(WebKitURISchemeRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_URI_SCHEME_REQUEST(request), 0); - - if (!request->priv->soupURI) - request->priv->soupURI.set(soup_uri_new(request->priv->uri.data())); - return request->priv->soupURI->scheme; -} - -/** - * webkit_uri_scheme_request_get_uri: - * @request: a #WebKitURISchemeRequest - * - * Get the URI of @request - * - * Returns: the full URI of @request - */ -const char* webkit_uri_scheme_request_get_uri(WebKitURISchemeRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_URI_SCHEME_REQUEST(request), 0); - - return request->priv->uri.data(); -} - -/** - * webkit_uri_scheme_request_get_path: - * @request: a #WebKitURISchemeRequest - * - * Get the URI path of @request - * - * Returns: the URI path of @request - */ -const char* webkit_uri_scheme_request_get_path(WebKitURISchemeRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_URI_SCHEME_REQUEST(request), 0); - - if (!request->priv->soupURI) - request->priv->soupURI.set(soup_uri_new(request->priv->uri.data())); - return request->priv->soupURI->path; -} - -/** - * webkit_uri_scheme_request_get_web_view: - * @request: a #WebKitURISchemeRequest - * - * Get the #WebKitWebView that initiated the request. - * - * Returns: (transfer none): the #WebKitWebView that initiated @request. - */ -WebKitWebView* webkit_uri_scheme_request_get_web_view(WebKitURISchemeRequest* request) -{ - g_return_val_if_fail(WEBKIT_IS_URI_SCHEME_REQUEST(request), 0); - - return WEBKIT_WEB_VIEW(request->priv->initiatingPage->viewWidget()); -} - -static void webkitURISchemeRequestReadCallback(GInputStream* inputStream, GAsyncResult* result, WebKitURISchemeRequest* schemeRequest) -{ - GRefPtr<WebKitURISchemeRequest> request = adoptGRef(schemeRequest); - GOwnPtr<GError> error; - gssize bytesRead = g_input_stream_read_finish(inputStream, result, &error.outPtr()); - if (bytesRead == -1) { - webkit_uri_scheme_request_finish_error(request.get(), error.get()); - return; - } - - WebKitURISchemeRequestPrivate* priv = request->priv; - RefPtr<WebData> webData = WebData::create(reinterpret_cast<const unsigned char*>(priv->readBuffer), bytesRead); - if (!priv->bytesRead) { - // First chunk read. In case of empty reply an empty WebData is sent to the WebProcess. - priv->webRequestManager->didHandleURIRequest(webData.get(), priv->streamLength, String::fromUTF8(priv->mimeType.data()), priv->requestID); - } else if (bytesRead || (!bytesRead && !priv->streamLength)) { - // Subsequent chunk read. We only send an empty WebData to the WebProcess when stream length is unknown. - priv->webRequestManager->didReceiveURIRequestData(webData.get(), priv->requestID); - } - - if (!bytesRead) { - webkitWebContextDidFinishURIRequest(request->priv->webContext, request->priv->requestID); - return; - } - - priv->bytesRead += bytesRead; - g_input_stream_read_async(inputStream, priv->readBuffer, gReadBufferSize, G_PRIORITY_DEFAULT, priv->cancellable.get(), - reinterpret_cast<GAsyncReadyCallback>(webkitURISchemeRequestReadCallback), g_object_ref(request.get())); -} - -/** - * webkit_uri_scheme_request_finish: - * @request: a #WebKitURISchemeRequest - * @stream: a #GInputStream to read the contents of the request - * @stream_length: the length of the stream or -1 if not known - * @mime_type: (allow-none): the content type of the stream or %NULL if not known - * - * Finish a #WebKitURISchemeRequest by setting the contents of the request and its mime type. - */ -void webkit_uri_scheme_request_finish(WebKitURISchemeRequest* request, GInputStream* inputStream, gint64 streamLength, const gchar* mimeType) -{ - g_return_if_fail(WEBKIT_IS_URI_SCHEME_REQUEST(request)); - g_return_if_fail(G_IS_INPUT_STREAM(inputStream)); - g_return_if_fail(streamLength == -1 || streamLength >= 0); - - request->priv->stream = inputStream; - // We use -1 in the API for consistency with soup when the content length is not known, but 0 internally. - request->priv->streamLength = streamLength == -1 ? 0 : streamLength; - request->priv->cancellable = adoptGRef(g_cancellable_new()); - request->priv->bytesRead = 0; - request->priv->mimeType = mimeType; - 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 deleted file mode 100644 index 71895da51..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequest.h +++ /dev/null @@ -1,86 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitURISchemeRequest_h -#define WebKitURISchemeRequest_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitForwardDeclarations.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_URI_SCHEME_REQUEST (webkit_uri_scheme_request_get_type()) -#define WEBKIT_URI_SCHEME_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_URI_SCHEME_REQUEST, WebKitURISchemeRequest)) -#define WEBKIT_IS_URI_SCHEME_REQUEST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_URI_SCHEME_REQUEST)) -#define WEBKIT_URI_SCHEME_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_URI_SCHEME_REQUEST, WebKitURISchemeRequestClass)) -#define WEBKIT_IS_URI_SCHEME_REQUEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_URI_SCHEME_REQUEST)) -#define WEBKIT_URI_SCHEME_REQUEST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_URI_SCHEME_REQUEST, WebKitURISchemeRequestClass)) - -typedef struct _WebKitURISchemeRequest WebKitURISchemeRequest; -typedef struct _WebKitURISchemeRequestClass WebKitURISchemeRequestClass; -typedef struct _WebKitURISchemeRequestPrivate WebKitURISchemeRequestPrivate; - -struct _WebKitURISchemeRequest { - GObject parent; - - WebKitURISchemeRequestPrivate *priv; -}; - -struct _WebKitURISchemeRequestClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_uri_scheme_request_get_type (void); - -WEBKIT_API const gchar * -webkit_uri_scheme_request_get_scheme (WebKitURISchemeRequest *request); - -WEBKIT_API const gchar * -webkit_uri_scheme_request_get_uri (WebKitURISchemeRequest *request); - -WEBKIT_API const gchar * -webkit_uri_scheme_request_get_path (WebKitURISchemeRequest *request); - -WEBKIT_API WebKitWebView * -webkit_uri_scheme_request_get_web_view (WebKitURISchemeRequest *request); - -WEBKIT_API void -webkit_uri_scheme_request_finish (WebKitURISchemeRequest *request, - GInputStream *stream, - 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/WebKitURISchemeRequestPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequestPrivate.h deleted file mode 100644 index 3baebd1fe..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitURISchemeRequestPrivate.h +++ /dev/null @@ -1,31 +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. - */ - -#ifndef WebKitURISchemeRequestPrivate_h -#define WebKitURISchemeRequestPrivate_h - -#include "WebKitPrivate.h" -#include "WebKitURISchemeRequest.h" -#include "WebKitWebContext.h" - -WebKitURISchemeRequest* webkitURISchemeRequestCreate(WebKitWebContext*, WebKit::WebSoupRequestManagerProxy*, WebKit::WebURL*, WebKit::WebPageProxy*, uint64_t requestID); -uint64_t webkitURISchemeRequestGetID(WebKitURISchemeRequest*); -void webkitURISchemeRequestCancel(WebKitURISchemeRequest*); - -#endif // WebKitURISchemeRequestPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp deleted file mode 100644 index 54dacc4f7..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.cpp +++ /dev/null @@ -1,89 +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 "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. - * (e.g. in WebKit version 1.8.3 this is 1.) - * - * This function is in the library, so it represents the WebKit library - * your code is running against. Contrast with the #WEBKIT_MAJOR_VERSION - * macro, which represents the major version of the WebKit headers you - * have included when compiling your code. - * - * Returns: the major version number of the WebKit library - */ -guint webkit_get_major_version(void) -{ - return WEBKIT_MAJOR_VERSION; -} - -/** - * webkit_get_minor_version: - * - * Returns the minor version number of the WebKit library. - * (e.g. in WebKit version 1.8.3 this is 8.) - * - * This function is in the library, so it represents the WebKit library - * your code is running against. Contrast with the #WEBKIT_MINOR_VERSION - * macro, which represents the minor version of the WebKit headers you - * have included when compiling your code. - * - * Returns: the minor version number of the WebKit library - */ -guint webkit_get_minor_version(void) -{ - return WEBKIT_MINOR_VERSION; -} - -/** - * webkit_get_micro_version: - * - * Returns the micro version number of the WebKit library. - * (e.g. in WebKit version 1.8.3 this is 3.) - * - * This function is in the library, so it represents the WebKit library - * your code is running against. Contrast with the #WEBKIT_MICRO_VERSION - * macro, which represents the micro version of the WebKit headers you - * have included when compiling your code. - * - * Returns: the micro version number of the WebKit library - */ -guint webkit_get_micro_version(void) -{ - return WEBKIT_MICRO_VERSION; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.h.in b/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.h.in deleted file mode 100644 index 81ef5179a..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitVersion.h.in +++ /dev/null @@ -1,84 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitVersion_h -#define WebKitVersion_h - -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -/** - * WEBKIT_MAJOR_VERSION: - * - * Like webkit_get_major_version(), but from the headers used at - * application compile time, rather than from the library linked - * against at application run time. - */ -#define WEBKIT_MAJOR_VERSION (@WEBKIT_MAJOR_VERSION@) - -/** - * WEBKIT_MINOR_VERSION: - * - * Like webkit_get_minor_version(), but from the headers used at - * application compile time, rather than from the library linked - * against at application run time. - */ -#define WEBKIT_MINOR_VERSION (@WEBKIT_MINOR_VERSION@) - -/** - * WEBKIT_MICRO_VERSION: - * - * Like webkit_get_micro_version(), but from the headers used at - * application compile time, rather than from the library linked - * against at application run time. - */ -#define WEBKIT_MICRO_VERSION (@WEBKIT_MICRO_VERSION@) - -/** - * WEBKIT_CHECK_VERSION: - * @major: major version (e.g. 1 for version 1.2.5) - * @minor: minor version (e.g. 2 for version 1.2.5) - * @micro: micro version (e.g. 5 for version 1.2.5) - * - * Returns: %TRUE if the version of the WebKit header files - * is the same as or newer than the passed-in version. - */ -#define WEBKIT_CHECK_VERSION(major, minor, micro) \ - (WEBKIT_MAJOR_VERSION > (major) || \ - (WEBKIT_MAJOR_VERSION == (major) && WEBKIT_MINOR_VERSION > (minor)) || \ - (WEBKIT_MAJOR_VERSION == (major) && WEBKIT_MINOR_VERSION == (minor) && \ - WEBKIT_MICRO_VERSION >= (micro))) - -WEBKIT_API guint -webkit_get_major_version (void); - -WEBKIT_API guint -webkit_get_minor_version (void); - -WEBKIT_API guint -webkit_get_micro_version (void); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp deleted file mode 100644 index d2c8bbdf9..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.cpp +++ /dev/null @@ -1,904 +0,0 @@ -/* - * Copyright (C) 2011 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 "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" -#include "WebKitSecurityManagerPrivate.h" -#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> -#include <WebCore/Language.h> -#include <wtf/HashMap.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - - LAST_SIGNAL -}; - -class WebKitURISchemeHandler: public RefCounted<WebKitURISchemeHandler> { -public: - WebKitURISchemeHandler() - : m_callback(0) - , m_userData(0) - , m_destroyNotify(0) - { - } - WebKitURISchemeHandler(WebKitURISchemeRequestCallback callback, void* userData, GDestroyNotify destroyNotify) - : m_callback(callback) - , m_userData(userData) - , m_destroyNotify(destroyNotify) - { - } - - ~WebKitURISchemeHandler() - { - if (m_destroyNotify) - m_destroyNotify(m_userData); - } - - bool hasCallback() - { - return m_callback; - } - - void performCallback(WebKitURISchemeRequest* request) - { - ASSERT(m_callback); - - m_callback(request, m_userData); - } - -private: - WebKitURISchemeRequestCallback m_callback; - void* m_userData; - GDestroyNotify m_destroyNotify; -}; - -typedef HashMap<String, RefPtr<WebKitURISchemeHandler> > URISchemeHandlerMap; -typedef HashMap<uint64_t, GRefPtr<WebKitURISchemeRequest> > URISchemeRequestMap; - -struct _WebKitWebContextPrivate { - RefPtr<WebContext> context; - - GRefPtr<WebKitCookieManager> cookieManager; - GRefPtr<WebKitFaviconDatabase> faviconDatabase; - GRefPtr<WebKitSecurityManager> securityManager; - RefPtr<WebSoupRequestManagerProxy> requestManager; - URISchemeHandlerMap uriSchemeHandlers; - URISchemeRequestMap uriSchemeRequests; -#if ENABLE(GEOLOCATION) - RefPtr<WebKitGeolocationProvider> geolocationProvider; -#endif -#if ENABLE(SPELLCHECK) - OwnPtr<WebKitTextChecker> textChecker; -#endif - CString faviconDatabaseDirectory; - WebKitTLSErrorsPolicy tlsErrorsPolicy; - - HashMap<uint64_t, WebKitWebView*> webViews; - GRefPtr<WebKitWebViewGroup> defaultWebViewGroup; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitWebContext, webkit_web_context, G_TYPE_OBJECT) - -static void webkit_web_context_class_init(WebKitWebContextClass* webContextClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(webContextClass); - - /** - * WebKitWebContext::download-started: - * @context: the #WebKitWebContext - * @download: the #WebKitDownload associated with this event - * - * This signal is emitted when a new download request is made. - */ - signals[DOWNLOAD_STARTED] = - g_signal_new("download-started", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__OBJECT, - G_TYPE_NONE, 1, - 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(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->supplement<WebGeolocationManagerProxy>()); -#endif -#if ENABLE(SPELLCHECK) - priv->textChecker = WebKitTextChecker::create(); -#endif - return webContext.get(); -} - -/** - * webkit_web_context_get_default: - * - * Gets the default web context - * - * Returns: (transfer none): a #WebKitWebContext - */ -WebKitWebContext* webkit_web_context_get_default(void) -{ - static GOnce onceInit = G_ONCE_INIT; - return WEBKIT_WEB_CONTEXT(g_once(&onceInit, createDefaultWebContext, 0)); -} - -/** - * webkit_web_context_set_cache_model: - * @context: the #WebKitWebContext - * @cache_model: a #WebKitCacheModel - * - * Specifies a usage model for WebViews, which WebKit will use to - * determine its caching behavior. All web views follow the cache - * model. This cache model determines the RAM and disk space to use - * for caching previously viewed content . - * - * Research indicates that users tend to browse within clusters of - * documents that hold resources in common, and to revisit previously - * visited documents. WebKit and the frameworks below it include - * built-in caches that take advantage of these patterns, - * substantially improving document load speed in browsing - * situations. The WebKit cache model controls the behaviors of all of - * these caches, including various WebCore caches. - * - * Browsers can improve document load speed substantially by - * specifying %WEBKIT_CACHE_MODEL_WEB_BROWSER. Applications without a - * browsing interface can reduce memory usage substantially by - * specifying %WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER. The default value is - * %WEBKIT_CACHE_MODEL_WEB_BROWSER. - */ -void webkit_web_context_set_cache_model(WebKitWebContext* context, WebKitCacheModel model) -{ - CacheModel cacheModel; - - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - - switch (model) { - case WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER: - cacheModel = CacheModelDocumentViewer; - break; - case WEBKIT_CACHE_MODEL_WEB_BROWSER: - cacheModel = CacheModelPrimaryWebBrowser; - break; - case WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER: - cacheModel = CacheModelDocumentBrowser; - break; - default: - g_assert_not_reached(); - } - - if (cacheModel != context->priv->context->cacheModel()) - context->priv->context->setCacheModel(cacheModel); -} - -/** - * webkit_web_context_get_cache_model: - * @context: the #WebKitWebContext - * - * Returns the current cache model. For more information about this - * value check the documentation of the function - * webkit_web_context_set_cache_model(). - * - * Returns: the current #WebKitCacheModel - */ -WebKitCacheModel webkit_web_context_get_cache_model(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), WEBKIT_CACHE_MODEL_WEB_BROWSER); - - switch (context->priv->context->cacheModel()) { - case CacheModelDocumentViewer: - return WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER; - case CacheModelPrimaryWebBrowser: - return WEBKIT_CACHE_MODEL_WEB_BROWSER; - case CacheModelDocumentBrowser: - return WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER; - default: - g_assert_not_reached(); - } - - return WEBKIT_CACHE_MODEL_WEB_BROWSER; -} - -/** - * webkit_web_context_clear_cache: - * @context: a #WebKitWebContext - * - * Clears all resources currently cached. - * See also webkit_web_context_set_cache_model(). - */ -void webkit_web_context_clear_cache(WebKitWebContext* context) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - - context->priv->context->supplement<WebResourceCacheManagerProxy>()->clearCacheForAllOrigins(AllResourceCaches); -} - -typedef HashMap<DownloadProxy*, GRefPtr<WebKitDownload> > DownloadsMap; - -static DownloadsMap& downloadsMap() -{ - DEFINE_STATIC_LOCAL(DownloadsMap, downloads, ()); - return downloads; -} - -/** - * webkit_web_context_download_uri: - * @context: a #WebKitWebContext - * @uri: the URI to download - * - * Requests downloading of the specified URI string. The download operation - * will not be associated to any #WebKitWebView, if you are interested in - * starting a download from a particular #WebKitWebView use - * webkit_web_view_download_uri() instead. - * - * Returns: (transfer full): a new #WebKitDownload representing the - * the download operation. - */ -WebKitDownload* webkit_web_context_download_uri(WebKitWebContext* context, const gchar* uri) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - g_return_val_if_fail(uri, 0); - - return webkitWebContextStartDownload(context, uri, 0); -} - -/** - * webkit_web_context_get_cookie_manager: - * @context: a #WebKitWebContext - * - * Get the #WebKitCookieManager of @context. - * - * Returns: (transfer none): the #WebKitCookieManager of @context. - */ -WebKitCookieManager* webkit_web_context_get_cookie_manager(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - - WebKitWebContextPrivate* priv = context->priv; - if (!priv->cookieManager) - priv->cookieManager = adoptGRef(webkitCookieManagerCreate(priv->context->supplement<WebCookieManagerProxy>())); - - return priv->cookieManager.get(); -} - -static void ensureFaviconDatabase(WebKitWebContext* context) -{ - WebKitWebContextPrivate* priv = context->priv; - if (priv->faviconDatabase) - return; - - priv->faviconDatabase = adoptGRef(webkitFaviconDatabaseCreate(priv->context->iconDatabase())); -} - -/** - * webkit_web_context_set_favicon_database_directory: - * @context: a #WebKitWebContext - * @path: (allow-none): an absolute path to the icon database - * directory or %NULL to use the defaults - * - * Set the directory path to be used to store the favicons database - * for @context on disk. Passing %NULL as @path means using the - * default directory for the platform (see g_get_user_data_dir()). - * - * Calling this method also means enabling the favicons database for - * its use from the applications, so that's why it's expected to be - * called only once. Further calls for the same instance of - * #WebKitWebContext won't cause any effect. - */ -void webkit_web_context_set_favicon_database_directory(WebKitWebContext* context, const gchar* path) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - - WebKitWebContextPrivate* priv = context->priv; - WebIconDatabase* iconDatabase = priv->context->iconDatabase(); - if (iconDatabase->isOpen()) - return; - - ensureFaviconDatabase(context); - - // Use default if 0 is passed as parameter. - String directoryPath = WebCore::filenameToString(path); - priv->faviconDatabaseDirectory = directoryPath.isEmpty() - ? priv->context->iconDatabasePath().utf8() - : directoryPath.utf8(); - - // Build the full path to the icon database file on disk. - GOwnPtr<gchar> faviconDatabasePath(g_build_filename(priv->faviconDatabaseDirectory.data(), - WebCore::IconDatabase::defaultDatabaseFilename().utf8().data(), - NULL)); - - // Setting the path will cause the icon database to be opened. - priv->context->setIconDatabasePath(WebCore::filenameToString(faviconDatabasePath.get())); -} - -/** - * webkit_web_context_get_favicon_database_directory: - * @context: a #WebKitWebContext - * - * Get the directory path being used to store the favicons database - * for @context, or %NULL if - * webkit_web_context_set_favicon_database_directory() hasn't been - * called yet. - * - * This function will always return the same path after having called - * webkit_web_context_set_favicon_database_directory() for the first - * time. - * - * Returns: (transfer none): the path of the directory of the favicons - * database associated with @context, or %NULL. - */ -const gchar* webkit_web_context_get_favicon_database_directory(WebKitWebContext *context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - - WebKitWebContextPrivate* priv = context->priv; - if (priv->faviconDatabaseDirectory.isNull()) - return 0; - - return priv->faviconDatabaseDirectory.data(); -} - -/** - * webkit_web_context_get_favicon_database: - * @context: a #WebKitWebContext - * - * Get the #WebKitFaviconDatabase associated with @context. - * - * To initialize the database you need to call - * webkit_web_context_set_favicon_database_directory(). - * - * Returns: (transfer none): the #WebKitFaviconDatabase of @context. - */ -WebKitFaviconDatabase* webkit_web_context_get_favicon_database(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - - ensureFaviconDatabase(context); - return context->priv->faviconDatabase.get(); -} - -/** - * webkit_web_context_get_security_manager: - * @context: a #WebKitWebContext - * - * Get the #WebKitSecurityManager of @context. - * - * Returns: (transfer none): the #WebKitSecurityManager of @context. - */ -WebKitSecurityManager* webkit_web_context_get_security_manager(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - - WebKitWebContextPrivate* priv = context->priv; - if (!priv->securityManager) - priv->securityManager = adoptGRef(webkitSecurityManagerCreate(context)); - - return priv->securityManager.get(); -} - -/** - * webkit_web_context_set_additional_plugins_directory: - * @context: a #WebKitWebContext - * @directory: the directory to add - * - * Set an additional directory where WebKit will look for plugins. - */ -void webkit_web_context_set_additional_plugins_directory(WebKitWebContext* context, const char* directory) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - g_return_if_fail(directory); - - context->priv->context->setAdditionalPluginsDirectory(WebCore::filenameToString(directory)); -} - -static void destroyPluginList(GList* plugins) -{ - g_list_free_full(plugins, g_object_unref); -} - -static void webkitWebContextGetPluginThread(GTask* task, gpointer object, gpointer taskData, GCancellable*) -{ - 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)); -} - -/** - * webkit_web_context_get_plugins: - * @context: a #WebKitWebContext - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously get the list of installed plugins. - * - * When the operation is finished, @callback will be called. You can then call - * webkit_web_context_get_plugins_finish() to get the result of the operation. - */ -void webkit_web_context_get_plugins(WebKitWebContext* context, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - - GRefPtr<GTask> task = adoptGRef(g_task_new(context, cancellable, callback, userData)); - g_task_run_in_thread(task.get(), webkitWebContextGetPluginThread); -} - -/** - * webkit_web_context_get_plugins_finish: - * @context: a #WebKitWebContext - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_context_get_plugins. - * - * Returns: (element-type WebKitPlugin) (transfer full): a #GList of #WebKitPlugin. You must free the #GList with - * g_list_free() and unref the #WebKitPlugin<!-- -->s with g_object_unref() when you're done with them. - */ -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_task_is_valid(result, context), 0); - - return static_cast<GList*>(g_task_propagate_pointer(G_TASK(result), error)); -} - -/** - * webkit_web_context_register_uri_scheme: - * @context: a #WebKitWebContext - * @scheme: the network scheme to register - * @callback: (scope async): a #WebKitURISchemeRequestCallback - * @user_data: data to pass to callback function - * @user_data_destroy_func: destroy notify for @user_data - * - * Register @scheme in @context, so that when an URI request with @scheme is made in the - * #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 or - * webkit_uri_scheme_request_finish_error() in case of error. - * - * <informalexample><programlisting> - * static void - * about_uri_scheme_request_cb (WebKitURISchemeRequest *request, - * gpointer user_data) - * { - * GInputStream *stream; - * gsize stream_length; - * const gchar *path; - * - * path = webkit_uri_scheme_request_get_path (request); - * if (!g_strcmp0 (path, "plugins")) { - * /<!-- -->* Create a GInputStream with the contents of plugins about page, and set its length to stream_length *<!-- -->/ - * } else if (!g_strcmp0 (path, "memory")) { - * /<!-- -->* 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 if (!g_strcmp0 (path, "example")) { - * gchar *contents; - * - * 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); - * } - * </programlisting></informalexample> - */ -void webkit_web_context_register_uri_scheme(WebKitWebContext* context, const char* scheme, WebKitURISchemeRequestCallback callback, gpointer userData, GDestroyNotify destroyNotify) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - g_return_if_fail(scheme); - g_return_if_fail(callback); - - RefPtr<WebKitURISchemeHandler> handler = adoptRef(new WebKitURISchemeHandler(callback, userData, destroyNotify)); - context->priv->uriSchemeHandlers.set(String::fromUTF8(scheme), handler.get()); - context->priv->requestManager->registerURIScheme(String::fromUTF8(scheme)); -} - -/** - * webkit_web_context_get_spell_checking_enabled: - * @context: a #WebKitWebContext - * - * Get whether spell checking feature is currently enabled. - * - * Returns: %TRUE If spell checking is enabled, or %FALSE otherwise. - */ -gboolean webkit_web_context_get_spell_checking_enabled(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), FALSE); - -#if ENABLE(SPELLCHECK) - return context->priv->textChecker->isSpellCheckingEnabled(); -#else - return false; -#endif -} - -/** - * webkit_web_context_set_spell_checking_enabled: - * @context: a #WebKitWebContext - * @enabled: Value to be set - * - * Enable or disable the spell checking feature. - */ -void webkit_web_context_set_spell_checking_enabled(WebKitWebContext* context, gboolean enabled) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - -#if ENABLE(SPELLCHECK) - context->priv->textChecker->setSpellCheckingEnabled(enabled); -#endif -} - -/** - * webkit_web_context_get_spell_checking_languages: - * @context: a #WebKitWebContext - * - * Get the the list of spell checking languages associated with - * @context, or %NULL if no languages have been previously set. - * - * See webkit_web_context_set_spell_checking_languages() for more - * details on the format of the languages in the list. - * - * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): A %NULL-terminated - * array of languages if available, or %NULL otherwise. - */ -const gchar* const* webkit_web_context_get_spell_checking_languages(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - -#if ENABLE(SPELLCHECK) - return context->priv->textChecker->getSpellCheckingLanguages(); -#else - return 0; -#endif -} - -/** - * webkit_web_context_set_spell_checking_languages: - * @context: a #WebKitWebContext - * @languages: (array zero-terminated=1) (transfer none): a %NULL-terminated list of spell checking languages - * - * Set the list of spell checking languages to be used for spell - * checking. - * - * The locale string typically is in the form lang_COUNTRY, where lang - * is an ISO-639 language code, and COUNTRY is an ISO-3166 country code. - * For instance, sv_FI for Swedish as written in Finland or pt_BR - * for Portuguese as written in Brazil. - * - * You need to call this function with a valid list of languages at - * least once in order to properly enable the spell checking feature - * in WebKit. - */ -void webkit_web_context_set_spell_checking_languages(WebKitWebContext* context, const gchar* const* languages) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - g_return_if_fail(languages); - -#if ENABLE(SPELLCHECK) - context->priv->textChecker->setSpellCheckingLanguages(languages); -#endif -} - -/** - * webkit_web_context_set_preferred_languages: - * @context: a #WebKitWebContext - * @languages: (allow-none) (array zero-terminated=1) (element-type utf8) (transfer none): a %NULL-terminated list of language identifiers - * - * Set the list of preferred languages, sorted from most desirable - * to least desirable. The list will be used to build the "Accept-Language" - * header that will be included in the network requests started by - * the #WebKitWebContext. - */ -void webkit_web_context_set_preferred_languages(WebKitWebContext* context, const gchar* const* languageList) -{ - g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context)); - - if (!languageList || !g_strv_length(const_cast<char**>(languageList))) - return; - - Vector<String> languages; - for (size_t i = 0; languageList[i]; ++i) - languages.append(String::fromUTF8(languageList[i]).lower().replace("_", "-")); - - WebCore::overrideUserPreferredLanguages(languages); - 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); - if (download) - return download.get(); - - download = adoptGRef(webkitDownloadCreate(downloadProxy)); - downloadsMap().set(downloadProxy, download.get()); - return download.get(); -} - -WebKitDownload* webkitWebContextStartDownload(WebKitWebContext* context, const char* uri, WebPageProxy* initiatingPage) -{ - 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; -} - -void webkitWebContextRemoveDownload(DownloadProxy* downloadProxy) -{ - downloadsMap().remove(downloadProxy); -} - -void webkitWebContextDownloadStarted(WebKitWebContext* context, WebKitDownload* download) -{ - g_signal_emit(context, signals[DOWNLOAD_STARTED], 0, download); -} - -WebContext* webkitWebContextGetContext(WebKitWebContext* context) -{ - g_assert(WEBKIT_IS_WEB_CONTEXT(context)); - - return context->priv->context.get(); -} - -WebSoupRequestManagerProxy* webkitWebContextGetRequestManager(WebKitWebContext* context) -{ - return context->priv->requestManager.get(); -} - -void webkitWebContextReceivedURIRequest(WebKitWebContext* context, WebKitURISchemeRequest* request) -{ - String scheme(String::fromUTF8(webkit_uri_scheme_request_get_scheme(request))); - RefPtr<WebKitURISchemeHandler> handler = context->priv->uriSchemeHandlers.get(scheme); - ASSERT(handler.get()); - if (!handler->hasCallback()) - return; - - context->priv->uriSchemeRequests.set(webkitURISchemeRequestGetID(request), request); - handler->performCallback(request); -} - -void webkitWebContextDidFailToLoadURIRequest(WebKitWebContext* context, uint64_t requestID) -{ - GRefPtr<WebKitURISchemeRequest> request = context->priv->uriSchemeRequests.get(requestID); - if (!request.get()) - return; - webkitURISchemeRequestCancel(request.get()); -} - -void webkitWebContextDidFinishURIRequest(WebKitWebContext* context, uint64_t requestID) -{ - 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 deleted file mode 100644 index dd38c1d37..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContext.h +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitWebContext_h -#define WebKitWebContext_h - -#include <glib-object.h> -#include <webkit2/WebKitCookieManager.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitDownload.h> -#include <webkit2/WebKitFaviconDatabase.h> -#include <webkit2/WebKitSecurityManager.h> -#include <webkit2/WebKitURISchemeRequest.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WEB_CONTEXT (webkit_web_context_get_type()) -#define WEBKIT_WEB_CONTEXT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_WEB_CONTEXT, WebKitWebContext)) -#define WEBKIT_WEB_CONTEXT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_CONTEXT, WebKitWebContextClass)) -#define WEBKIT_IS_WEB_CONTEXT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_WEB_CONTEXT)) -#define WEBKIT_IS_WEB_CONTEXT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_CONTEXT)) -#define WEBKIT_WEB_CONTEXT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_WEB_CONTEXT, WebKitWebContextClass)) - -/** - * WebKitCacheModel: - * @WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER: Disable the cache completely, which - * substantially reduces memory usage. Useful for applications that only - * access a single local file, with no navigation to other pages. No remote - * resources will be cached. - * @WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER: A cache model optimized for viewing - * a series of local files -- for example, a documentation viewer or a website - * designer. WebKit will cache a moderate number of resources. - * @WEBKIT_CACHE_MODEL_WEB_BROWSER: Improve document load speed substantially - * by caching a very large number of resources and previously viewed content. - * - * Enum values used for determining the #WebKitWebContext cache model. - */ -typedef enum { - WEBKIT_CACHE_MODEL_DOCUMENT_VIEWER, - WEBKIT_CACHE_MODEL_WEB_BROWSER, - WEBKIT_CACHE_MODEL_DOCUMENT_BROWSER -} 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 - * - * Type definition for a function that will be called back when an URI request is - * made for a user registered URI scheme. - */ -typedef void (* WebKitURISchemeRequestCallback) (WebKitURISchemeRequest *request, - gpointer user_data); - -typedef struct _WebKitWebContext WebKitWebContext; -typedef struct _WebKitWebContextClass WebKitWebContextClass; -typedef struct _WebKitWebContextPrivate WebKitWebContextPrivate; - -struct _WebKitWebContext { - GObject parent; - - /*< private >*/ - WebKitWebContextPrivate *priv; -}; - -struct _WebKitWebContextClass { - GObjectClass parent; - - 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 -webkit_web_context_get_type (void); - -WEBKIT_API WebKitWebContext * -webkit_web_context_get_default (void); - -WEBKIT_API void -webkit_web_context_set_cache_model (WebKitWebContext *context, - WebKitCacheModel cache_model); -WEBKIT_API WebKitCacheModel -webkit_web_context_get_cache_model (WebKitWebContext *context); - -WEBKIT_API void -webkit_web_context_clear_cache (WebKitWebContext *context); - -WEBKIT_API WebKitDownload * -webkit_web_context_download_uri (WebKitWebContext *context, - const gchar *uri); - -WEBKIT_API WebKitCookieManager * -webkit_web_context_get_cookie_manager (WebKitWebContext *context); - -WEBKIT_API WebKitFaviconDatabase * -webkit_web_context_get_favicon_database (WebKitWebContext *context); - -WEBKIT_API void -webkit_web_context_set_favicon_database_directory (WebKitWebContext *context, - const gchar *path); -WEBKIT_API const gchar * -webkit_web_context_get_favicon_database_directory (WebKitWebContext *context); - -WEBKIT_API WebKitSecurityManager * -webkit_web_context_get_security_manager (WebKitWebContext *context); - -WEBKIT_API void -webkit_web_context_set_additional_plugins_directory (WebKitWebContext *context, - const gchar *directory); - -WEBKIT_API void -webkit_web_context_get_plugins (WebKitWebContext *context, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API GList * -webkit_web_context_get_plugins_finish (WebKitWebContext *context, - GAsyncResult *result, - GError **error); -WEBKIT_API void -webkit_web_context_register_uri_scheme (WebKitWebContext *context, - const gchar *scheme, - WebKitURISchemeRequestCallback callback, - gpointer user_data, - GDestroyNotify user_data_destroy_func); - -WEBKIT_API gboolean -webkit_web_context_get_spell_checking_enabled (WebKitWebContext *context); - -WEBKIT_API void -webkit_web_context_set_spell_checking_enabled (WebKitWebContext *context, - gboolean enabled); -WEBKIT_API const gchar * const * -webkit_web_context_get_spell_checking_languages (WebKitWebContext *context); - -WEBKIT_API void -webkit_web_context_set_spell_checking_languages (WebKitWebContext *context, - const gchar * const *languages); - -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 deleted file mode 100644 index 81c473c56..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebContextPrivate.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef WebKitWebContextPrivate_h -#define WebKitWebContextPrivate_h - -#include "DownloadProxy.h" -#include "WebContext.h" -#include "WebKitPrivate.h" -#include "WebKitURISchemeRequest.h" -#include "WebKitWebContext.h" -#include "WebKitWebViewGroup.h" -#include "WebSoupRequestManagerProxy.h" - -WebKit::WebContext* webkitWebContextGetContext(WebKitWebContext*); -WebKitDownload* webkitWebContextGetOrCreateDownload(WebKit::DownloadProxy*); -WebKitDownload* webkitWebContextStartDownload(WebKitWebContext*, const char* uri, WebKit::WebPageProxy*); -void webkitWebContextRemoveDownload(WebKit::DownloadProxy*); -void webkitWebContextDownloadStarted(WebKitWebContext*, WebKitDownload*); -WebKit::WebSoupRequestManagerProxy* webkitWebContextGetRequestManager(WebKitWebContext*); -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 deleted file mode 100644 index 3839ad3e2..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.cpp +++ /dev/null @@ -1,461 +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 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 "WebKitWebInspector.h" - -#include "WebInspectorProxy.h" -#include "WebKitMarshal.h" -#include "WebKitWebInspectorPrivate.h" -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - CLOSED, - ATTACH, - DETACH, - - LAST_SIGNAL -}; - -enum { - PROP_0, - - PROP_INSPECTED_URI, - PROP_ATTACHED_HEIGHT -}; - -struct _WebKitWebInspectorPrivate { - ~_WebKitWebInspectorPrivate() - { - WKInspectorSetInspectorClientGtk(toAPI(webInspector.get()), 0); - } - - RefPtr<WebInspectorProxy> webInspector; - CString inspectedURI; - unsigned attachedHeight; -}; - -WEBKIT_DEFINE_TYPE(WebKitWebInspector, webkit_web_inspector, G_TYPE_OBJECT) - -static guint signals[LAST_SIGNAL] = { 0, }; - -static void webkitWebInspectorGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitWebInspector* inspector = WEBKIT_WEB_INSPECTOR(object); - - switch (propId) { - case PROP_INSPECTED_URI: - g_value_set_string(value, webkit_web_inspector_get_inspected_uri(inspector)); - break; - case PROP_ATTACHED_HEIGHT: - g_value_set_uint(value, webkit_web_inspector_get_attached_height(inspector)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_web_inspector_class_init(WebKitWebInspectorClass* findClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(findClass); - gObjectClass->get_property = webkitWebInspectorGetProperty; - - /** - * WebKitWebInspector:inspected-uri: - * - * The URI that is currently being inspected. - */ - g_object_class_install_property(gObjectClass, - PROP_INSPECTED_URI, - g_param_spec_string("inspected-uri", - _("Inspected URI"), - _("The URI that is currently being inspected"), - 0, - WEBKIT_PARAM_READABLE)); - /** - * WebKitWebInspector:attached-height: - * - * The height that the inspector view should have when it is attached. - */ - g_object_class_install_property(gObjectClass, - PROP_ATTACHED_HEIGHT, - g_param_spec_uint("attached-height", - _("Attached Height"), - _("The height that the inspector view should have when it is attached"), - 0, G_MAXUINT, 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitWebInspector::open-window: - * @inspector: the #WebKitWebInspector on which the signal is emitted - * - * Emitted when the inspector is requested to open in a separate window. - * If this signal is not handled, a #GtkWindow with the inspector will be - * created and shown, so you only need to handle this signal if you want - * to use your own window. - * This signal is emitted after #WebKitWebInspector::detach to show - * the inspector in a separate window after being detached. - * - * To prevent the inspector from being shown you can connect to this - * signal and simply return %TRUE - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[OPEN_WINDOW] = - g_signal_new("open-window", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__VOID, - G_TYPE_BOOLEAN, 0); - - /** - * WebKitWebInspector::bring-to-front: - * @inspector: the #WebKitWebInspector on which the signal is emitted - * - * Emitted when the inspector should be shown. - * - * If the inspector is not attached the inspector window should be shown - * on top of any other windows. - * If the inspector is attached the inspector view should be made visible. - * For example, if the inspector view is attached using a tab in a browser - * window, the browser window should be raised and the tab containing the - * inspector view should be the active one. - * In both cases, if this signal is not handled, the default implementation - * calls gtk_window_present() on the current toplevel #GtkWindow of the - * inspector view. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[BRING_TO_FRONT] = - g_signal_new("bring-to-front", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__VOID, - G_TYPE_BOOLEAN, 0); - - /** - * WebKitWebInspector::closed: - * @inspector: the #WebKitWebInspector on which the signal is emitted - * - * Emitted when the inspector page is closed. If you are using your own - * inspector window, you should connect to this signal and destroy your - * window. - */ - signals[CLOSED] = - g_signal_new("closed", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitWebInspector::attach: - * @inspector: the #WebKitWebInspector on which the signal is emitted - * - * Emitted when the inspector is requested to be attached to the window - * where the inspected web view is. - * If this signal is not handled the inspector view will be automatically - * attached to the inspected view, so you only need to handle this signal - * if you want to attach the inspector view yourself (for example, to add - * the inspector view to a browser tab). - * - * To prevent the inspector vew from being attached you can connect to this - * signal and simply return %TRUE. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[ATTACH] = - g_signal_new("attach", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__VOID, - G_TYPE_BOOLEAN, 0); - - /** - * WebKitWebInspector::detach: - * @inspector: the #WebKitWebInspector on which the signal is emitted - * - * Emitted when the inspector is requested to be detached from the window - * it is currently attached to. The inspector is detached when the inspector page - * is about to be closed, and this signal is emitted right before - * #WebKitWebInspector::closed, or when the user clicks on the detach button - * in the inspector view to show the inspector in a separate window. In this case - * the signal #WebKitWebInspector::open-window is emitted after this one. - * - * To prevent the inspector vew from being detached you can connect to this - * signal and simply return %TRUE. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[DETACH] = - g_signal_new("detach", - G_TYPE_FROM_CLASS(gObjectClass), - G_SIGNAL_RUN_LAST, - 0, - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__VOID, - G_TYPE_BOOLEAN, 0); -} - -static bool openWindow(WKInspectorRef, const void* clientInfo) -{ - gboolean returnValue; - g_signal_emit(WEBKIT_WEB_INSPECTOR(clientInfo), signals[OPEN_WINDOW], 0, &returnValue); - return returnValue; -} - -static void didClose(WKInspectorRef, const void* clientInfo) -{ - g_signal_emit(WEBKIT_WEB_INSPECTOR(clientInfo), signals[CLOSED], 0); -} - -static bool bringToFront(WKInspectorRef, const void* clientInfo) -{ - gboolean returnValue; - g_signal_emit(WEBKIT_WEB_INSPECTOR(clientInfo), signals[BRING_TO_FRONT], 0, &returnValue); - return returnValue; -} - -static void inspectedURLChanged(WKInspectorRef, WKStringRef url, const void* clientInfo) -{ - WebKitWebInspector* inspector = WEBKIT_WEB_INSPECTOR(clientInfo); - CString uri = toImpl(url)->string().utf8(); - if (uri == inspector->priv->inspectedURI) - return; - inspector->priv->inspectedURI = uri; - g_object_notify(G_OBJECT(inspector), "inspected-uri"); -} - -static bool attach(WKInspectorRef, const void* clientInfo) -{ - gboolean returnValue; - g_signal_emit(WEBKIT_WEB_INSPECTOR(clientInfo), signals[ATTACH], 0, &returnValue); - return returnValue; -} - -static bool detach(WKInspectorRef inspector, const void* clientInfo) -{ - gboolean returnValue; - g_signal_emit(WEBKIT_WEB_INSPECTOR(clientInfo), signals[DETACH], 0, &returnValue); - return returnValue; -} - -static void didChangeAttachedHeight(WKInspectorRef, unsigned height, const void* clientInfo) -{ - WebKitWebInspector* inspector = WEBKIT_WEB_INSPECTOR(clientInfo); - if (inspector->priv->attachedHeight == height) - return; - inspector->priv->attachedHeight = height; - g_object_notify(G_OBJECT(inspector), "attached-height"); -} - -WebKitWebInspector* webkitWebInspectorCreate(WebInspectorProxy* webInspector) -{ - WebKitWebInspector* inspector = WEBKIT_WEB_INSPECTOR(g_object_new(WEBKIT_TYPE_WEB_INSPECTOR, NULL)); - inspector->priv->webInspector = webInspector; - - WKInspectorClientGtk wkInspectorClientGtk = { - kWKInspectorClientGtkCurrentVersion, - inspector, // clientInfo - openWindow, - didClose, - bringToFront, - inspectedURLChanged, - attach, - detach, - didChangeAttachedHeight - }; - WKInspectorSetInspectorClientGtk(toAPI(webInspector), &wkInspectorClientGtk); - - return inspector; -} - -/** - * webkit_web_inspector_get_web_view: - * @inspector: a #WebKitWebInspector - * - * Get the #WebKitWebViewBase used to display the inspector. - * This might be %NULL if the inspector hasn't been loaded yet, - * or it has been closed. - * - * Returns: (transfer none): the #WebKitWebViewBase used to display the inspector or %NULL - */ -WebKitWebViewBase* webkit_web_inspector_get_web_view(WebKitWebInspector* inspector) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector), 0); - - return WEBKIT_WEB_VIEW_BASE(inspector->priv->webInspector->inspectorView()); -} - -/** - * webkit_web_inspector_get_inspected_uri: - * @inspector: a #WebKitWebInspector - * - * Get the URI that is currently being inspected. This can be %NULL if - * nothing has been loaded yet in the inspected view, if the inspector - * has been closed or when inspected view was loaded from a HTML string - * instead of a URI. - * - * Returns: the URI that is currently being inspected or %NULL - */ -const char* webkit_web_inspector_get_inspected_uri(WebKitWebInspector* inspector) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector), 0); - - return inspector->priv->inspectedURI.data(); -} - -/** - * webkit_web_inspector_is_attached: - * @inspector: a #WebKitWebInspector - * - * Whether the @inspector view is currently attached to the same window that contains - * the inspected view. - * - * Returns: %TRUE if @inspector is currently attached or %FALSE otherwise - */ -gboolean webkit_web_inspector_is_attached(WebKitWebInspector* inspector) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector), FALSE); - - return inspector->priv->webInspector->isAttached(); -} - -/** - * webkit_web_inspector_attach: - * @inspector: a #WebKitWebInspector - * - * Request @inspector to be attached. The signal #WebKitWebInspector::attach - * will be emitted. If the inspector is already attached it does nothing. - */ -void webkit_web_inspector_attach(WebKitWebInspector* inspector) -{ - g_return_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector)); - - if (inspector->priv->webInspector->isAttached()) - return; - inspector->priv->webInspector->attach(); -} - -/** - * webkit_web_inspector_detach: - * @inspector: a #WebKitWebInspector - * - * Request @inspector to be detached. The signal #WebKitWebInspector::detach - * will be emitted. If the inspector is already detached it does nothing. - */ -void webkit_web_inspector_detach(WebKitWebInspector* inspector) -{ - g_return_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector)); - - if (!inspector->priv->webInspector->isAttached()) - return; - inspector->priv->webInspector->detach(); -} - -/** - * webkit_web_inspector_show: - * @inspector: a #WebKitWebInspector - * - * Request @inspector to be shown. - */ -void webkit_web_inspector_show(WebKitWebInspector* inspector) -{ - g_return_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector)); - - inspector->priv->webInspector->show(); -} - -/** - * webkit_web_inspector_close: - * @inspector: a #WebKitWebInspector - * - * Request @inspector to be closed. - */ -void webkit_web_inspector_close(WebKitWebInspector* inspector) -{ - g_return_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector)); - - inspector->priv->webInspector->close(); -} - -/** - * webkit_web_inspector_get_attached_height: - * @inspector: a #WebKitWebInspector - * - * Get the height that the inspector view should have when - * it's attached. If the inspector view is not attached this - * returns 0. - * - * Returns: the height of the inspector view when attached - */ -guint webkit_web_inspector_get_attached_height(WebKitWebInspector* inspector) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_INSPECTOR(inspector), 0); - - if (!inspector->priv->webInspector->isAttached()) - return 0; - return inspector->priv->attachedHeight; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h deleted file mode 100644 index 67f0f4957..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspector.h +++ /dev/null @@ -1,88 +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 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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitWebInspector_h -#define WebKitWebInspector_h - -#include <glib-object.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitWebViewBase.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WEB_INSPECTOR (webkit_web_inspector_get_type()) -#define WEBKIT_WEB_INSPECTOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_WEB_INSPECTOR, WebKitWebInspector)) -#define WEBKIT_IS_WEB_INSPECTOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_WEB_INSPECTOR)) -#define WEBKIT_WEB_INSPECTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_INSPECTOR, WebKitWebInspectorClass)) -#define WEBKIT_IS_WEB_INSPECTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_INSPECTOR)) -#define WEBKIT_WEB_INSPECTOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_WEB_INSPECTOR, WebKitWebInspectorClass)) - -typedef struct _WebKitWebInspector WebKitWebInspector; -typedef struct _WebKitWebInspectorClass WebKitWebInspectorClass; -typedef struct _WebKitWebInspectorPrivate WebKitWebInspectorPrivate; - -struct _WebKitWebInspector { - GObject parent; - - WebKitWebInspectorPrivate *priv; -}; - -struct _WebKitWebInspectorClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_web_inspector_get_type (void); - -WEBKIT_API WebKitWebViewBase * -webkit_web_inspector_get_web_view (WebKitWebInspector *inspector); - -WEBKIT_API const char * -webkit_web_inspector_get_inspected_uri (WebKitWebInspector *inspector); - -WEBKIT_API gboolean -webkit_web_inspector_is_attached (WebKitWebInspector *inspector); - -WEBKIT_API void -webkit_web_inspector_attach (WebKitWebInspector *inspector); - -WEBKIT_API void -webkit_web_inspector_detach (WebKitWebInspector *inspector); - -WEBKIT_API void -webkit_web_inspector_show (WebKitWebInspector *inspector); - -WEBKIT_API void -webkit_web_inspector_close (WebKitWebInspector *inspector); - -WEBKIT_API guint -webkit_web_inspector_get_attached_height (WebKitWebInspector *inspector); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspectorPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspectorPrivate.h deleted file mode 100644 index 2f5e99f8e..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebInspectorPrivate.h +++ /dev/null @@ -1,28 +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. - */ - -#ifndef WebKitWebInspectorPrivate_h -#define WebKitWebInspectorPrivate_h - -#include "WebKitPrivate.h" -#include "WebKitWebInspector.h" - -WebKitWebInspector* webkitWebInspectorCreate(WebKit::WebInspectorProxy*); - -#endif // WebKitWebInspectorPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp deleted file mode 100644 index f81cd2b17..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.cpp +++ /dev/null @@ -1,376 +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 "WebKitWebResource.h" - -#include "WebData.h" -#include "WebFrameProxy.h" -#include "WebKitMarshal.h" -#include "WebKitURIRequest.h" -#include "WebKitWebResourcePrivate.h" -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - FINISHED, - FAILED, - - LAST_SIGNAL -}; - -enum { - PROP_0, - - PROP_URI, - PROP_RESPONSE -}; - - -struct _WebKitWebResourcePrivate { - RefPtr<WebFrameProxy> frame; - CString uri; - GRefPtr<WebKitURIResponse> response; - bool isMainResource; -}; - -WEBKIT_DEFINE_TYPE(WebKitWebResource, webkit_web_resource, G_TYPE_OBJECT) - -static guint signals[LAST_SIGNAL] = { 0, }; - -static void webkitWebResourceGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(object); - - switch (propId) { - case PROP_URI: - g_value_set_string(value, webkit_web_resource_get_uri(resource)); - break; - case PROP_RESPONSE: - g_value_set_object(value, webkit_web_resource_get_response(resource)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_web_resource_class_init(WebKitWebResourceClass* resourceClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(resourceClass); - objectClass->get_property = webkitWebResourceGetProperty; - - /** - * WebKitWebResource:uri: - * - * The current active URI of the #WebKitWebResource. - * See webkit_web_resource_get_uri() for more details. - */ - g_object_class_install_property(objectClass, - PROP_URI, - g_param_spec_string("uri", - _("URI"), - _("The current active URI of the resource"), - 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitWebResource:response: - * - * The #WebKitURIResponse associated with this resource. - */ - g_object_class_install_property(objectClass, - PROP_RESPONSE, - g_param_spec_object("response", - _("Response"), - _("The response of the resource"), - WEBKIT_TYPE_URI_RESPONSE, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitWebResource::sent-request: - * @resource: the #WebKitWebResource - * @request: a #WebKitURIRequest - * @redirected_response: a #WebKitURIResponse, or %NULL - * - * This signal is emitted when @request has been sent to the - * server. In case of a server redirection this signal is - * emitted again with the @request argument containing the new - * request sent to the server due to the redirection and the - * @redirected_response parameter containing the response - * received by the server for the initial request. - */ - signals[SENT_REQUEST] = - g_signal_new("sent-request", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - webkit_marshal_VOID__OBJECT_OBJECT, - G_TYPE_NONE, 2, - WEBKIT_TYPE_URI_REQUEST, - WEBKIT_TYPE_URI_RESPONSE); - - /** - * WebKitWebResource::received-data: - * @resource: the #WebKitWebResource - * @data_length: the length of data received in bytes - * - * This signal is emitted after response is received, - * every time new data has been received. It's - * useful to know the progress of the resource load operation. - */ - signals[RECEIVED_DATA] = - g_signal_new("received-data", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - webkit_marshal_VOID__UINT64, - G_TYPE_NONE, 1, - G_TYPE_UINT64); - - /** - * WebKitWebResource::finished: - * @resource: the #WebKitWebResource - * - * This signal is emitted when the resource load finishes successfully - * or due to an error. In case of errors #WebKitWebResource::failed signal - * is emitted before this one. - */ - signals[FINISHED] = - g_signal_new("finished", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitWebResource::failed: - * @resource: the #WebKitWebResource - * @error: the #GError that was triggered - * - * This signal is emitted when an error occurs during the resource - * load operation. - */ - signals[FAILED] = - g_signal_new("failed", - G_TYPE_FROM_CLASS(objectClass), - G_SIGNAL_RUN_LAST, - 0, 0, 0, - g_cclosure_marshal_VOID__POINTER, - G_TYPE_NONE, 1, - G_TYPE_POINTER); -} - -static void webkitWebResourceUpdateURI(WebKitWebResource* resource, const CString& requestURI) -{ - if (resource->priv->uri == requestURI) - return; - - resource->priv->uri = requestURI; - g_object_notify(G_OBJECT(resource), "uri"); -} - -WebKitWebResource* webkitWebResourceCreate(WebFrameProxy* frame, WebKitURIRequest* request, bool isMainResource) -{ - ASSERT(frame); - WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(g_object_new(WEBKIT_TYPE_WEB_RESOURCE, NULL)); - resource->priv->frame = frame; - resource->priv->uri = webkit_uri_request_get_uri(request); - resource->priv->isMainResource = isMainResource; - return resource; -} - -void webkitWebResourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) -{ - webkitWebResourceUpdateURI(resource, webkit_uri_request_get_uri(request)); - g_signal_emit(resource, signals[SENT_REQUEST], 0, request, redirectResponse); -} - -void webkitWebResourceSetResponse(WebKitWebResource* resource, WebKitURIResponse* response) -{ - resource->priv->response = response; - g_object_notify(G_OBJECT(resource), "response"); -} - -void webkitWebResourceNotifyProgress(WebKitWebResource* resource, guint64 bytesReceived) -{ - g_signal_emit(resource, signals[RECEIVED_DATA], 0, bytesReceived); -} - -void webkitWebResourceFinished(WebKitWebResource* resource) -{ - g_signal_emit(resource, signals[FINISHED], 0, NULL); -} - -void webkitWebResourceFailed(WebKitWebResource* resource, GError* error) -{ - g_signal_emit(resource, signals[FAILED], 0, error); - g_signal_emit(resource, signals[FINISHED], 0, NULL); -} - -WebFrameProxy* webkitWebResourceGetFrame(WebKitWebResource* resource) -{ - return resource->priv->frame.get(); -} - -/** - * webkit_web_resource_get_uri: - * @resource: a #WebKitWebResource - * - * Returns the current active URI of @resource. The active URI might change during - * a load operation: - * - * <orderedlist> - * <listitem><para> - * When the resource load starts, the active URI is the requested URI - * </para></listitem> - * <listitem><para> - * When the initial request is sent to the server, #WebKitWebResource::sent-request - * signal is emitted without a redirected response, the active URI is the URI of - * the request sent to the server. - * </para></listitem> - * <listitem><para> - * In case of a server redirection, #WebKitWebResource::sent-request signal - * is emitted again with a redirected response, the active URI is the URI the request - * was redirected to. - * </para></listitem> - * <listitem><para> - * When the response is received from the server, the active URI is the final - * one and it will not change again. - * </para></listitem> - * </orderedlist> - * - * You can monitor the active URI by connecting to the notify::uri - * signal of @resource. - * - * Returns: the current active URI of @resource - */ -const char* webkit_web_resource_get_uri(WebKitWebResource* resource) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); - - return resource->priv->uri.data(); -} - -/** - * webkit_web_resource_get_response: - * @resource: a #WebKitWebResource - * - * Retrieves the #WebKitURIResponse of the resource load operation. - * This method returns %NULL if called before the response - * is received from the server. You can connect to notify::response - * signal to be notified when the response is received. - * - * Returns: (transfer none): the #WebKitURIResponse, or %NULL if - * the response hasn't been received yet. - */ -WebKitURIResponse* webkit_web_resource_get_response(WebKitWebResource* resource) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); - - return resource->priv->response.get(); -} - -struct ResourceGetDataAsyncData { - RefPtr<WebData> webData; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ResourceGetDataAsyncData) - -static void resourceDataCallback(WKDataRef wkData, WKErrorRef, void* context) -{ - 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); -} - -/** - * webkit_web_resource_get_data: - * @resource: a #WebKitWebResource - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously get the raw data for @resource. - * - * When the operation is finished, @callback will be called. You can then call - * webkit_web_resource_get_data_finish() to get the result of the operation. - */ -void webkit_web_resource_get_data(WebKitWebResource* resource, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_RESOURCE(resource)); - - 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(task, resourceDataCallback)); - else { - String url = String::fromUTF8(resource->priv->uri.data()); - resource->priv->frame->getResourceData(WebURL::create(url).get(), DataCallback::create(task, resourceDataCallback)); - } -} - -/** - * webkit_web_resource_get_data_finish: - * @resource: a #WebKitWebResource - * @result: a #GAsyncResult - * @length: (out): return location for the length of the resource data - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_resource_get_data(). - * - * Returns: (transfer full): a string with the data of @resource, or %NULL in case - * of error. if @length is not %NULL, the size of the data will be assigned to it. - */ -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_task_is_valid(result, resource), 0); - - GTask* task = G_TASK(result); - if (!g_task_propagate_boolean(task, error)) - return 0; - - 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 deleted file mode 100644 index 7463686ab..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResource.h +++ /dev/null @@ -1,83 +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. - */ - -#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION) -#error "Only <webkit2/webkit2.h> can be included directly." -#endif - -#ifndef WebKitWebResource_h -#define WebKitWebResource_h - -#include <glib-object.h> -#include <gio/gio.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitURIResponse.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WEB_RESOURCE (webkit_web_resource_get_type()) -#define WEBKIT_WEB_RESOURCE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_WEB_RESOURCE, WebKitWebResource)) -#define WEBKIT_IS_WEB_RESOURCE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_WEB_RESOURCE)) -#define WEBKIT_WEB_RESOURCE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_RESOURCE, WebKitWebResourceClass)) -#define WEBKIT_IS_WEB_RESOURCE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_RESOURCE)) -#define WEBKIT_WEB_RESOURCE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_WEB_RESOURCE, WebKitWebResourceClass)) - -typedef struct _WebKitWebResource WebKitWebResource; -typedef struct _WebKitWebResourceClass WebKitWebResourceClass; -typedef struct _WebKitWebResourcePrivate WebKitWebResourcePrivate; - -struct _WebKitWebResource { - GObject parent; - - WebKitWebResourcePrivate *priv; -}; - -struct _WebKitWebResourceClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_web_resource_get_type (void); - -WEBKIT_API const gchar * -webkit_web_resource_get_uri (WebKitWebResource *resource); - -WEBKIT_API WebKitURIResponse * -webkit_web_resource_get_response (WebKitWebResource *resource); - -WEBKIT_API void -webkit_web_resource_get_data (WebKitWebResource *resource, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API guchar * -webkit_web_resource_get_data_finish (WebKitWebResource *resource, - GAsyncResult *result, - gsize *length, - GError **error); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResourcePrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebResourcePrivate.h deleted file mode 100644 index 82e2d8f5a..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebResourcePrivate.h +++ /dev/null @@ -1,35 +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. - */ - -#ifndef WebKitWebResourcePrivate_h -#define WebKitWebResourcePrivate_h - -#include "WebKitPrivate.h" -#include "WebKitWebResource.h" - -WebKitWebResource* webkitWebResourceCreate(WebKit::WebFrameProxy*, WebKitURIRequest*, bool isMainResource); -void webkitWebResourceSentRequest(WebKitWebResource*, WebKitURIRequest*, WebKitURIResponse*); -void webkitWebResourceSetResponse(WebKitWebResource*, WebKitURIResponse*); -void webkitWebResourceNotifyProgress(WebKitWebResource*, guint64 bytesReceived); -void webkitWebResourceFinished(WebKitWebResource*); -void webkitWebResourceFailed(WebKitWebResource*, GError*); -WebKit::WebFrameProxy* webkitWebResourceGetFrame(WebKitWebResource*); - - -#endif // WebKitWebResourcePrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp deleted file mode 100644 index 29497090d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.cpp +++ /dev/null @@ -1,3032 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 "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" -#include "WebKitContextMenuPrivate.h" -#include "WebKitDownloadPrivate.h" -#include "WebKitEnumTypes.h" -#include "WebKitError.h" -#include "WebKitFaviconDatabasePrivate.h" -#include "WebKitFormClient.h" -#include "WebKitFullscreenClient.h" -#include "WebKitHitTestResultPrivate.h" -#include "WebKitJavascriptResultPrivate.h" -#include "WebKitLoaderClient.h" -#include "WebKitMarshal.h" -#include "WebKitPolicyClient.h" -#include "WebKitPrintOperationPrivate.h" -#include "WebKitPrivate.h" -#include "WebKitResponsePolicyDecision.h" -#include "WebKitScriptDialogPrivate.h" -#include "WebKitUIClient.h" -#include "WebKitURIRequestPrivate.h" -#include "WebKitURIResponsePrivate.h" -#include "WebKitWebContextPrivate.h" -#include "WebKitWebInspectorPrivate.h" -#include "WebKitWebResourcePrivate.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebKitWebViewGroupPrivate.h" -#include "WebKitWebViewPrivate.h" -#include "WebKitWindowPropertiesPrivate.h" -#include <JavaScriptCore/APICast.h> -#include <WebCore/DragIcon.h> -#include <WebCore/GOwnPtrGtk.h> -#include <WebCore/GtkUtilities.h> -#include <WebCore/RefPtrCairo.h> -#include <glib/gi18n-lib.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -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, - - CREATE, - READY_TO_SHOW, - RUN_AS_MODAL, - CLOSE, - - SCRIPT_DIALOG, - - DECIDE_POLICY, - PERMISSION_REQUEST, - - MOUSE_TARGET_CHANGED, - - PRINT, - - RESOURCE_LOAD_STARTED, - - ENTER_FULLSCREEN, - LEAVE_FULLSCREEN, - - RUN_FILE_CHOOSER, - - CONTEXT_MENU, - CONTEXT_MENU_DISMISSED, - - SUBMIT_FORM, - - INSECURE_CONTENT_DETECTED, - - WEB_PROCESS_CRASHED, - - LAST_SIGNAL -}; - -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_VIEW_MODE -}; - -typedef HashMap<uint64_t, GRefPtr<WebKitWebResource> > LoadingResourcesMap; -typedef HashMap<uint64_t, GRefPtr<GTask> > SnapshotResultsMap; - -struct _WebKitWebViewPrivate { - ~_WebKitWebViewPrivate() - { - if (javascriptGlobalContext) - JSGlobalContextRelease(javascriptGlobalContext); - - // For modal dialogs, make sure the main loop is stopped when finalizing the webView. - if (modalLoop && g_main_loop_is_running(modalLoop.get())) - g_main_loop_quit(modalLoop.get()); - } - - WebKitWebContext* context; - CString title; - CString customTextEncoding; - double estimatedLoadProgress; - CString activeURI; - bool isLoading; - WebKitViewMode viewMode; - - bool waitingForMainResource; - unsigned long mainResourceResponseHandlerID; - WebKitLoadEvent lastDelayedEvent; - - GRefPtr<WebKitBackForwardList> backForwardList; - GRefPtr<WebKitSettings> settings; - unsigned long settingsChangedHandlerID; - GRefPtr<WebKitWebViewGroup> group; - GRefPtr<WebKitWindowProperties> windowProperties; - - GRefPtr<GMainLoop> modalLoop; - - GRefPtr<WebKitHitTestResult> mouseTargetHitTestResult; - unsigned mouseTargetModifiers; - - GRefPtr<WebKitFindController> findController; - JSGlobalContextRef javascriptGlobalContext; - - GRefPtr<WebKitWebResource> mainResource; - LoadingResourcesMap loadingResourcesMap; - - GRefPtr<WebKitWebInspector> inspector; - - RefPtr<cairo_surface_t> favicon; - GRefPtr<GCancellable> faviconCancellable; - CString faviconURI; - unsigned long faviconChangedHandlerID; - - SnapshotResultsMap snapshotResultsMap; -}; - -static guint signals[LAST_SIGNAL] = { 0, }; - -WEBKIT_DEFINE_TYPE(WebKitWebView, webkit_web_view, WEBKIT_TYPE_WEB_VIEW_BASE) - -static inline WebPageProxy* getPage(WebKitWebView* webView) -{ - return webkitWebViewBaseGetPage(reinterpret_cast<WebKitWebViewBase*>(webView)); -} - -static gboolean webkitWebViewLoadFail(WebKitWebView* webView, WebKitLoadEvent, const char* failingURI, GError* error) -{ - if (g_error_matches(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED) - || g_error_matches(error, WEBKIT_POLICY_ERROR, WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE) - || g_error_matches(error, WEBKIT_PLUGIN_ERROR, WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD)) - return FALSE; - - GOwnPtr<char> htmlString(g_strdup_printf("<html><body>%s</body></html>", error->message)); - webkit_web_view_load_alternate_html(webView, htmlString.get(), failingURI, 0); - - return TRUE; -} - -static GtkWidget* webkitWebViewCreate(WebKitWebView*) -{ - return 0; -} - -static GtkWidget* webkitWebViewCreateJavaScriptDialog(WebKitWebView* webView, GtkMessageType type, GtkButtonsType buttons, int defaultResponse, const char* message) -{ - GtkWidget* parent = gtk_widget_get_toplevel(GTK_WIDGET(webView)); - GtkWidget* dialog = gtk_message_dialog_new(widgetIsOnscreenToplevelWindow(parent) ? GTK_WINDOW(parent) : 0, - GTK_DIALOG_DESTROY_WITH_PARENT, type, buttons, "%s", message); - GOwnPtr<char> title(g_strdup_printf("JavaScript - %s", webkit_web_view_get_uri(webView))); - gtk_window_set_title(GTK_WINDOW(dialog), title.get()); - gtk_dialog_set_default_response(GTK_DIALOG(dialog), defaultResponse); - - return dialog; -} - -static gboolean webkitWebViewScriptDialog(WebKitWebView* webView, WebKitScriptDialog* scriptDialog) -{ - GtkWidget* dialog = 0; - - switch (scriptDialog->type) { - case WEBKIT_SCRIPT_DIALOG_ALERT: - dialog = webkitWebViewCreateJavaScriptDialog(webView, GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, GTK_RESPONSE_CLOSE, scriptDialog->message.data()); - gtk_dialog_run(GTK_DIALOG(dialog)); - break; - case WEBKIT_SCRIPT_DIALOG_CONFIRM: - dialog = webkitWebViewCreateJavaScriptDialog(webView, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, GTK_RESPONSE_OK, scriptDialog->message.data()); - scriptDialog->confirmed = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK; - break; - case WEBKIT_SCRIPT_DIALOG_PROMPT: - dialog = webkitWebViewCreateJavaScriptDialog(webView, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, GTK_RESPONSE_OK, scriptDialog->message.data()); - GtkWidget* entry = gtk_entry_new(); - gtk_entry_set_text(GTK_ENTRY(entry), scriptDialog->defaultText.data()); - gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), entry); - gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE); - gtk_widget_show(entry); - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) - scriptDialog->text = gtk_entry_get_text(GTK_ENTRY(entry)); - break; - } - - gtk_widget_destroy(dialog); - - return TRUE; -} - -static gboolean webkitWebViewDecidePolicy(WebKitWebView* webView, WebKitPolicyDecision* decision, WebKitPolicyDecisionType decisionType) -{ - if (decisionType != WEBKIT_POLICY_DECISION_TYPE_RESPONSE) { - webkit_policy_decision_use(decision); - return TRUE; - } - - WebKitURIResponse* response = webkit_response_policy_decision_get_response(WEBKIT_RESPONSE_POLICY_DECISION(decision)); - const ResourceResponse resourceResponse = webkitURIResponseGetResourceResponse(response); - if (resourceResponse.isAttachment()) { - webkit_policy_decision_download(decision); - return TRUE; - } - - if (webkit_web_view_can_show_mime_type(webView, webkit_uri_response_get_mime_type(response))) - webkit_policy_decision_use(decision); - else - webkit_policy_decision_ignore(decision); - - return TRUE; -} - -static gboolean webkitWebViewPermissionRequest(WebKitWebView*, WebKitPermissionRequest* request) -{ - webkit_permission_request_deny(request); - return TRUE; -} - -static void allowModalDialogsChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView) -{ - WebPageProxy* page = webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(webView)); - if (!page) - return; - getPage(webView)->setCanRunModal(webkit_settings_get_allow_modal_dialogs(settings)); -} - -static void zoomTextOnlyChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView) -{ - WebPageProxy* page = getPage(webView); - gboolean zoomTextOnly = webkit_settings_get_zoom_text_only(settings); - gdouble pageZoomLevel = zoomTextOnly ? 1 : page->textZoomFactor(); - gdouble textZoomLevel = zoomTextOnly ? page->pageZoomFactor() : 1; - page->setPageAndTextZoomFactors(pageZoomLevel, textZoomLevel); -} - -static void userAgentChanged(WebKitSettings* settings, GParamSpec*, WebKitWebView* webView) -{ - getPage(webView)->setCustomUserAgent(String::fromUTF8(webkit_settings_get_user_agent(settings))); -} - -static void webkitWebViewUpdateFavicon(WebKitWebView* webView, cairo_surface_t* favicon) -{ - WebKitWebViewPrivate* priv = webView->priv; - if (priv->favicon.get() == favicon) - return; - - priv->favicon = favicon; - g_object_notify(G_OBJECT(webView), "favicon"); -} - -static void webkitWebViewCancelFaviconRequest(WebKitWebView* webView) -{ - if (!webView->priv->faviconCancellable) - return; - - g_cancellable_cancel(webView->priv->faviconCancellable.get()); - webView->priv->faviconCancellable = 0; -} - -static void gotFaviconCallback(GObject* object, GAsyncResult* result, gpointer userData) -{ - GOwnPtr<GError> error; - RefPtr<cairo_surface_t> favicon = adoptRef(webkit_favicon_database_get_favicon_finish(WEBKIT_FAVICON_DATABASE(object), result, &error.outPtr())); - if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_CANCELLED)) - return; - - WebKitWebView* webView = WEBKIT_WEB_VIEW(userData); - webkitWebViewUpdateFavicon(webView, favicon.get()); - webView->priv->faviconCancellable = 0; -} - -static void webkitWebViewRequestFavicon(WebKitWebView* webView) -{ - webkitWebViewCancelFaviconRequest(webView); - - WebKitWebViewPrivate* priv = webView->priv; - priv->faviconCancellable = adoptGRef(g_cancellable_new()); - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(priv->context); - webkit_favicon_database_get_favicon(database, priv->activeURI.data(), priv->faviconCancellable.get(), gotFaviconCallback, webView); -} - -static void webkitWebViewUpdateFaviconURI(WebKitWebView* webView, const char* faviconURI) -{ - if (webView->priv->faviconURI == faviconURI) - return; - - webView->priv->faviconURI = faviconURI; - webkitWebViewRequestFavicon(webView); -} - -static void faviconChangedCallback(WebKitFaviconDatabase* database, const char* pageURI, const char* faviconURI, WebKitWebView* webView) -{ - if (webView->priv->activeURI != pageURI) - return; - - webkitWebViewUpdateFaviconURI(webView, faviconURI); -} - -static void webkitWebViewUpdateSettings(WebKitWebView* 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); -} - -static void webkitWebViewDisconnectSettingsSignalHandlers(WebKitWebView* webView) -{ - WebKitSettings* settings = webView->priv->settings.get(); - g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(allowModalDialogsChanged), webView); - g_signal_handlers_disconnect_by_func(settings, reinterpret_cast<gpointer>(zoomTextOnlyChanged), 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; - if (priv->mainResourceResponseHandlerID) - g_signal_handler_disconnect(priv->mainResource.get(), priv->mainResourceResponseHandlerID); - priv->mainResourceResponseHandlerID = 0; -} - -static void webkitWebViewWatchForChangesInFavicon(WebKitWebView* webView) -{ - WebKitWebViewPrivate* priv = webView->priv; - if (priv->faviconChangedHandlerID) - return; - - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(priv->context); - priv->faviconChangedHandlerID = g_signal_connect(database, "favicon-changed", G_CALLBACK(faviconChangedCallback), webView); -} - -static void webkitWebViewDisconnectFaviconDatabaseSignalHandlers(WebKitWebView* webView) -{ - WebKitWebViewPrivate* priv = webView->priv; - if (priv->faviconChangedHandlerID) - g_signal_handler_disconnect(webkit_web_context_get_favicon_database(priv->context), priv->faviconChangedHandlerID); - priv->faviconChangedHandlerID = 0; -} - -static void fileChooserDialogResponseCallback(GtkDialog* dialog, gint responseID, WebKitFileChooserRequest* request) -{ - GRefPtr<WebKitFileChooserRequest> adoptedRequest = adoptGRef(request); - if (responseID == GTK_RESPONSE_ACCEPT) { - GOwnPtr<GSList> filesList(gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog))); - GRefPtr<GPtrArray> filesArray = adoptGRef(g_ptr_array_new()); - for (GSList* file = filesList.get(); file; file = g_slist_next(file)) - g_ptr_array_add(filesArray.get(), file->data); - g_ptr_array_add(filesArray.get(), 0); - webkit_file_chooser_request_select_files(adoptedRequest.get(), reinterpret_cast<const gchar* const*>(filesArray->pdata)); - } else - webkit_file_chooser_request_cancel(adoptedRequest.get()); - - gtk_widget_destroy(GTK_WIDGET(dialog)); -} - -static gboolean webkitWebViewRunFileChooser(WebKitWebView* webView, WebKitFileChooserRequest* request) -{ - GtkWidget* toplevel = gtk_widget_get_toplevel(GTK_WIDGET(webView)); - if (!widgetIsOnscreenToplevelWindow(toplevel)) - toplevel = 0; - - gboolean allowsMultipleSelection = webkit_file_chooser_request_get_select_multiple(request); - GtkWidget* dialog = gtk_file_chooser_dialog_new(allowsMultipleSelection ? _("Select Files") : _("Select File"), - toplevel ? GTK_WINDOW(toplevel) : 0, - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - - if (GtkFileFilter* filter = webkit_file_chooser_request_get_mime_types_filter(request)) - gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); - gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), allowsMultipleSelection); - - if (const gchar* const* selectedFiles = webkit_file_chooser_request_get_selected_files(request)) - gtk_file_chooser_select_filename(GTK_FILE_CHOOSER(dialog), selectedFiles[0]); - - g_signal_connect(dialog, "response", G_CALLBACK(fileChooserDialogResponseCallback), g_object_ref(request)); - gtk_widget_show(dialog); - - return TRUE; -} - -static void webkitWebViewHandleDownloadRequest(WebKitWebViewBase* webViewBase, DownloadProxy* downloadProxy) -{ - GRefPtr<WebKitDownload> download = webkitWebContextGetOrCreateDownload(downloadProxy); - webkitDownloadSetWebView(download.get(), WEBKIT_WEB_VIEW(webViewBase)); -} - -static void webkitWebViewConstructed(GObject* object) -{ - if (G_OBJECT_CLASS(webkit_web_view_parent_class)->constructed) - G_OBJECT_CLASS(webkit_web_view_parent_class)->constructed(object); - - WebKitWebView* webView = WEBKIT_WEB_VIEW(object); - WebKitWebViewPrivate* priv = webView->priv; - webkitWebContextCreatePageForWebView(priv->context, webView, priv->group.get()); - - webkitWebViewBaseSetDownloadRequestHandler(WEBKIT_WEB_VIEW_BASE(webView), webkitWebViewHandleDownloadRequest); - - attachLoaderClientToView(webView); - attachUIClientToView(webView); - attachPolicyClientToView(webView); - attachFullScreenClientToView(webView); - attachContextMenuClientToView(webView); - attachFormClientToView(webView); - - priv->backForwardList = adoptGRef(webkitBackForwardListCreate(getPage(webView)->backForwardList())); - priv->windowProperties = adoptGRef(webkitWindowPropertiesCreate()); - - 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) -{ - WebKitWebView* webView = WEBKIT_WEB_VIEW(object); - - switch (propId) { - case PROP_WEB_CONTEXT: { - gpointer webContext = g_value_get_object(value); - 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); - } -} - -static void webkitWebViewGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitWebView* webView = WEBKIT_WEB_VIEW(object); - - switch (propId) { - 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; - case PROP_ESTIMATED_LOAD_PROGRESS: - g_value_set_double(value, webkit_web_view_get_estimated_load_progress(webView)); - break; - case PROP_FAVICON: - g_value_set_pointer(value, webkit_web_view_get_favicon(webView)); - break; - case PROP_URI: - g_value_set_string(value, webkit_web_view_get_uri(webView)); - break; - case PROP_ZOOM_LEVEL: - g_value_set_double(value, webkit_web_view_get_zoom_level(webView)); - break; - 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); - } -} - -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); -} - -static gboolean webkitWebViewAccumulatorObjectHandled(GSignalInvocationHint*, GValue* returnValue, const GValue* handlerReturn, gpointer) -{ - void* object = g_value_get_object(handlerReturn); - if (object) - g_value_set_object(returnValue, object); - - return !object; -} - -static void webkit_web_view_class_init(WebKitWebViewClass* webViewClass) -{ - GObjectClass* gObjectClass = G_OBJECT_CLASS(webViewClass); - - gObjectClass->constructed = webkitWebViewConstructed; - gObjectClass->set_property = webkitWebViewSetProperty; - gObjectClass->get_property = webkitWebViewGetProperty; - gObjectClass->dispose = webkitWebViewDispose; - - webViewClass->load_failed = webkitWebViewLoadFail; - webViewClass->create = webkitWebViewCreate; - webViewClass->script_dialog = webkitWebViewScriptDialog; - webViewClass->decide_policy = webkitWebViewDecidePolicy; - webViewClass->permission_request = webkitWebViewPermissionRequest; - webViewClass->run_file_chooser = webkitWebViewRunFileChooser; - - /** - * WebKitWebView:web-context: - * - * The #WebKitWebContext of the view. - */ - g_object_class_install_property(gObjectClass, - PROP_WEB_CONTEXT, - g_param_spec_object("web-context", - _("Web Context"), - _("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: - * - * The main frame document title of this #WebKitWebView. If - * the title has not been received yet, it will be %NULL. - */ - g_object_class_install_property(gObjectClass, - PROP_TITLE, - g_param_spec_string("title", - _("Title"), - _("Main frame document title"), - 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitWebView:estimated-load-progress: - * - * An estimate of the percent completion for the current loading operation. - * This value will range from 0.0 to 1.0 and, once a load completes, - * will remain at 1.0 until a new load starts, at which point it - * will be reset to 0.0. - * The value is an estimate based on the total number of bytes expected - * to be received for a document, including all its possible subresources - * and child documents. - */ - g_object_class_install_property(gObjectClass, - PROP_ESTIMATED_LOAD_PROGRESS, - g_param_spec_double("estimated-load-progress", - _("Estimated Load Progress"), - _("An estimate of the percent completion for a document load"), - 0.0, 1.0, 0.0, - WEBKIT_PARAM_READABLE)); - /** - * WebKitWebView:favicon: - * - * The favicon currently associated to the #WebKitWebView. - * See webkit_web_view_get_favicon() for more details. - */ - g_object_class_install_property(gObjectClass, - PROP_FAVICON, - g_param_spec_pointer("favicon", - _("Favicon"), - _("The favicon associated to the view, if any"), - WEBKIT_PARAM_READABLE)); - /** - * WebKitWebView:uri: - * - * The current active URI of the #WebKitWebView. - * See webkit_web_view_get_uri() for more details. - */ - g_object_class_install_property(gObjectClass, - PROP_URI, - g_param_spec_string("uri", - _("URI"), - _("The current active URI of the view"), - 0, - WEBKIT_PARAM_READABLE)); - - /** - * WebKitWebView:zoom-level: - * - * The zoom level of the #WebKitWebView content. - * See webkit_web_view_set_zoom_level() for more details. - */ - g_object_class_install_property(gObjectClass, - PROP_ZOOM_LEVEL, - g_param_spec_double("zoom-level", - "Zoom level", - _("The zoom level of the view content"), - 0, G_MAXDOUBLE, 1, - WEBKIT_PARAM_READWRITE)); - - /** - * WebKitWebView:is-loading: - * - * Whether the #WebKitWebView is currently loading a page. This property becomes - * %TRUE as soon as a new load operation is requested and before the - * #WebKitWebView::load-changed signal is emitted with %WEBKIT_LOAD_STARTED and - * at that point the active URI is the requested one. - * When the load operation finishes the property is set to %FALSE before - * #WebKitWebView::load-changed is emitted with %WEBKIT_LOAD_FINISHED. - */ - g_object_class_install_property(gObjectClass, - PROP_IS_LOADING, - g_param_spec_boolean("is-loading", - "Is Loading", - _("Whether the view is loading a page"), - FALSE, - 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 - * - * Emitted when the a load operation in @web_view changes. - * The signal is always emitted with %WEBKIT_LOAD_STARTED when a - * new load request is made and %WEBKIT_LOAD_FINISHED when the load - * finishes successfully or due to an error. When the ongoing load - * operation fails #WebKitWebView::load-failed signal is emitted - * before #WebKitWebView::load-changed is emitted with - * %WEBKIT_LOAD_FINISHED. - * If a redirection is received from the server, this signal is emitted - * with %WEBKIT_LOAD_REDIRECTED after the initial emission with - * %WEBKIT_LOAD_STARTED and before %WEBKIT_LOAD_COMMITTED. - * When the page content starts arriving the signal is emitted with - * %WEBKIT_LOAD_COMMITTED event. - * - * You can handle this signal and use a switch to track any ongoing - * load operation. - * - * <informalexample><programlisting> - * static void web_view_load_changed (WebKitWebView *web_view, - * WebKitLoadEvent load_event, - * gpointer user_data) - * { - * switch (load_event) { - * case WEBKIT_LOAD_STARTED: - * /<!-- -->* New load, we have now a provisional URI *<!-- -->/ - * provisional_uri = webkit_web_view_get_uri (web_view); - * /<!-- -->* Here we could start a spinner or update the - * <!-- -->* location bar with the provisional URI *<!-- -->/ - * break; - * case WEBKIT_LOAD_REDIRECTED: - * redirected_uri = webkit_web_view_get_uri (web_view); - * break; - * case WEBKIT_LOAD_COMMITTED: - * /<!-- -->* The load is being performed. Current URI is - * <!-- -->* the final one and it won't change unless a new - * <!-- -->* load is requested or a navigation within the - * <!-- -->* same page is performed *<!-- -->/ - * uri = webkit_web_view_get_uri (web_view); - * break; - * case WEBKIT_LOAD_FINISHED: - * /<!-- -->* Load finished, we can now stop the spinner *<!-- -->/ - * break; - * } - * } - * </programlisting></informalexample> - */ - signals[LOAD_CHANGED] = - g_signal_new("load-changed", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, load_changed), - 0, 0, - g_cclosure_marshal_VOID__ENUM, - G_TYPE_NONE, 1, - WEBKIT_TYPE_LOAD_EVENT); - - /** - * WebKitWebView::load-failed: - * @web_view: the #WebKitWebView on which the signal is emitted - * @load_event: the #WebKitLoadEvent of the load operation - * @failing_uri: the URI that failed to load - * @error: the #GError that was triggered - * - * Emitted when an error occurs during a load operation. - * If the error happened when starting to load data for a page - * @load_event will be %WEBKIT_LOAD_STARTED. If it happened while - * loading a committed data source @load_event will be %WEBKIT_LOAD_COMMITTED. - * Since a load error causes the load operation to finish, the signal - * WebKitWebView::load-changed will always be emitted with - * %WEBKIT_LOAD_FINISHED event right after this one. - * - * By default, if the signal is not handled, a stock error page will be displayed. - * You need to handle the signal if you want to provide your own error page. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[LOAD_FAILED] = - g_signal_new("load-failed", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, load_failed), - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__ENUM_STRING_POINTER, - G_TYPE_BOOLEAN, 3, - WEBKIT_TYPE_LOAD_EVENT, - G_TYPE_STRING, - G_TYPE_POINTER); - - /** - * WebKitWebView::create: - * @web_view: the #WebKitWebView on which the signal is emitted - * - * Emitted when the creation of a new #WebKitWebView is requested. - * If this signal is handled the signal handler should return the - * newly created #WebKitWebView. - * - * The new #WebKitWebView should not be displayed to the user - * until the #WebKitWebView::ready-to-show signal is emitted. - * - * Returns: (transfer full): a newly allocated #WebKitWebView widget - * or %NULL to propagate the event further. - */ - signals[CREATE] = - g_signal_new("create", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, create), - webkitWebViewAccumulatorObjectHandled, 0, - webkit_marshal_OBJECT__VOID, - GTK_TYPE_WIDGET, 0); - - /** - * WebKitWebView::ready-to-show: - * @web_view: the #WebKitWebView on which the signal is emitted - * - * Emitted after #WebKitWebView::create on the newly created #WebKitWebView - * when it should be displayed to the user. When this signal is emitted - * all the information about how the window should look, including - * size, position, whether the location, status and scrollbars - * should be displayed, is already set on the #WebKitWindowProperties - * of @web_view. See also webkit_web_view_get_window_properties(). - */ - signals[READY_TO_SHOW] = - g_signal_new("ready-to-show", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, ready_to_show), - 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitWebView::run-as-modal: - * @web_view: the #WebKitWebView on which the signal is emitted - * - * Emitted after #WebKitWebView::ready-to-show on the newly - * created #WebKitWebView when JavaScript code calls - * <function>window.showModalDialog</function>. The purpose of - * this signal is to allow the client application to prepare the - * new view to behave as modal. Once the signal is emitted a new - * mainloop will be run to block user interaction in the parent - * #WebKitWebView until the new dialog is closed. - */ - signals[RUN_AS_MODAL] = - g_signal_new("run-as-modal", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, run_as_modal), - 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitWebView::close: - * @webView: the #WebKitWebView on which the signal is emitted - * - * Emitted when closing a #WebKitWebView is requested. This occurs when a - * call is made from JavaScript's <function>window.close</function> function. - * It is the owner's responsibility to handle this signal to hide or - * destroy the #WebKitWebView, if necessary. - */ - signals[CLOSE] = - g_signal_new("close", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, close), - 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitWebView::script-dialog: - * @web_view: the #WebKitWebView on which the signal is emitted - * @dialog: the #WebKitScriptDialog to show - * - * Emitted when JavaScript code calls <function>window.alert</function>, - * <function>window.confirm</function> or <function>window.prompt</function>. - * The @dialog parameter should be used to build the dialog. - * If the signal is not handled a different dialog will be built and shown depending - * on the dialog type: - * <itemizedlist> - * <listitem><para> - * %WEBKIT_SCRIPT_DIALOG_ALERT: message dialog with a single Close button. - * </para></listitem> - * <listitem><para> - * %WEBKIT_SCRIPT_DIALOG_CONFIRM: message dialog with OK and Cancel buttons. - * </para></listitem> - * <listitem><para> - * %WEBKIT_SCRIPT_DIALOG_PROMPT: message dialog with OK and Cancel buttons and - * a text entry with the default text. - * </para></listitem> - * </itemizedlist> - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[SCRIPT_DIALOG] = - g_signal_new("script-dialog", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, script_dialog), - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__BOXED, - G_TYPE_BOOLEAN, 1, - WEBKIT_TYPE_SCRIPT_DIALOG | G_SIGNAL_TYPE_STATIC_SCOPE); - - /** - * WebKitWebView::decide-policy: - * @web_view: the #WebKitWebView on which the signal is emitted - * @decision: the #WebKitPolicyDecision - * @decision_type: a #WebKitPolicyDecisionType denoting the type of @decision - * - * This signal is emitted when WebKit is requesting the client to decide a policy - * decision, such as whether to navigate to a page, open a new window or whether or - * not to download a resource. The #WebKitNavigationPolicyDecision passed in the - * @decision argument is a generic type, but should be casted to a more - * specific type when making the decision. For example: - * - * <informalexample><programlisting> - * static gboolean - * decide_policy_cb (WebKitWebView *web_view, - * WebKitPolicyDecision *decision, - * WebKitPolicyDecisionType type) - * { - * switch (type) { - * case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION: - * WebKitNavigationPolicyDecision *navigation_decision = WEBKIT_NAVIGATION_POLICY_DECISION (decision); - * /<!-- -->* Make a policy decision here. *<!-- -->/ - * break; - * case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION: - * WebKitNavigationPolicyDecision *navigation_decision = WEBKIT_NAVIGATION_POLICY_DECISION (decision); - * /<!-- -->* Make a policy decision here. *<!-- -->/ - * break; - * case WEBKIT_POLICY_DECISION_TYPE_RESPONSE: - * WebKitResponsePolicyDecision *response = WEBKIT_RESPONSE_POLICY_DECISION (decision); - * /<!-- -->* Make a policy decision here. *<!-- -->/ - * break; - * default: - * /<!-- -->* Making no decision results in webkit_policy_decision_use(). *<!-- -->/ - * return FALSE; - * } - * return TRUE; - * } - * </programlisting></informalexample> - * - * It is possible to make policy decision asynchronously, by simply calling g_object_ref() - * on the @decision argument and returning %TRUE to block the default signal handler. - * If the last reference is removed on a #WebKitPolicyDecision and no decision has been - * made explicitly, webkit_policy_decision_use() will be the default policy decision. The - * default signal handler will simply call webkit_policy_decision_use(). Only the first - * policy decision chosen for a given #WebKitPolicyDecision will have any affect. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - * - */ - signals[DECIDE_POLICY] = - g_signal_new("decide-policy", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, decide_policy), - g_signal_accumulator_true_handled, 0 /* accumulator data */, - webkit_marshal_BOOLEAN__OBJECT_ENUM, - G_TYPE_BOOLEAN, 2, /* number of parameters */ - WEBKIT_TYPE_POLICY_DECISION, - WEBKIT_TYPE_POLICY_DECISION_TYPE); - - /** - * WebKitWebView::permission-request: - * @web_view: the #WebKitWebView on which the signal is emitted - * @request: the #WebKitPermissionRequest - * - * This signal is emitted when WebKit is requesting the client to - * decide about a permission request, such as allowing the browser - * to switch to fullscreen mode, sharing its location or similar - * operations. - * - * A possible way to use this signal could be through a dialog - * allowing the user decide what to do with the request: - * - * <informalexample><programlisting> - * static gboolean permission_request_cb (WebKitWebView *web_view, - * WebKitPermissionRequest *request, - * GtkWindow *parent_window) - * { - * GtkWidget *dialog = gtk_message_dialog_new (parent_window, - * GTK_DIALOG_MODAL, - * GTK_MESSAGE_QUESTION, - * GTK_BUTTONS_YES_NO, - * "Allow Permission Request?"); - * gtk_widget_show (dialog); - * gint result = gtk_dialog_run (GTK_DIALOG (dialog)); - * - * switch (result) { - * case GTK_RESPONSE_YES: - * webkit_permission_request_allow (request); - * break; - * default: - * webkit_permission_request_deny (request); - * break; - * } - * gtk_widget_destroy (dialog); - * - * return TRUE; - * } - * </programlisting></informalexample> - * - * It is possible to handle permission requests asynchronously, by - * simply calling g_object_ref() on the @request argument and - * returning %TRUE to block the default signal handler. If the - * last reference is removed on a #WebKitPermissionRequest and the - * request has not been handled, webkit_permission_request_deny() - * will be the default action. - * - * By default, if the signal is not handled, - * webkit_permission_request_deny() will be called over the - * #WebKitPermissionRequest. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - * - */ - signals[PERMISSION_REQUEST] = - g_signal_new("permission-request", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, permission_request), - g_signal_accumulator_true_handled, 0 /* accumulator data */, - webkit_marshal_BOOLEAN__OBJECT, - G_TYPE_BOOLEAN, 1, /* number of parameters */ - WEBKIT_TYPE_PERMISSION_REQUEST); - /** - * WebKitWebView::mouse-target-changed: - * @web_view: the #WebKitWebView on which the signal is emitted - * @hit_test_result: a #WebKitHitTestResult - * @modifiers: a bitmask of #GdkModifierType - * - * This signal is emitted when the mouse cursor moves over an - * element such as a link, image or a media element. To determine - * what type of element the mouse cursor is over, a Hit Test is performed - * on the current mouse coordinates and the result is passed in the - * @hit_test_result argument. The @modifiers argument is a bitmask of - * #GdkModifierType flags indicating the state of modifier keys. - * The signal is emitted again when the mouse is moved out of the - * current element with a new @hit_test_result. - */ - signals[MOUSE_TARGET_CHANGED] = - g_signal_new("mouse-target-changed", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, mouse_target_changed), - 0, 0, - webkit_marshal_VOID__OBJECT_UINT, - G_TYPE_NONE, 2, - WEBKIT_TYPE_HIT_TEST_RESULT, - G_TYPE_UINT); - /** - * WebKitWebView::print: - * @web_view: the #WebKitWebView on which the signal is emitted - * @print_operation: the #WebKitPrintOperation that will handle the print request - * - * Emitted when printing is requested on @web_view, usually by a javascript call, - * before the print dialog is shown. This signal can be used to set the initial - * print settings and page setup of @print_operation to be used as default values in - * the print dialog. You can call webkit_print_operation_set_print_settings() and - * webkit_print_operation_set_page_setup() and then return %FALSE to propagate the - * event so that the print dialog is shown. - * - * You can connect to this signal and return %TRUE to cancel the print operation - * or implement your own print dialog. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[PRINT] = - g_signal_new("print", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, print), - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__OBJECT, - G_TYPE_BOOLEAN, 1, - WEBKIT_TYPE_PRINT_OPERATION); - - /** - * WebKitWebView::resource-load-started: - * @web_view: the #WebKitWebView on which the signal is emitted - * @resource: a #WebKitWebResource - * @request: a #WebKitURIRequest - * - * Emitted when a new resource is going to be loaded. The @request parameter - * contains the #WebKitURIRequest that will be sent to the server. - * You can monitor the load operation by connecting to the different signals - * of @resource. - */ - signals[RESOURCE_LOAD_STARTED] = - g_signal_new("resource-load-started", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, resource_load_started), - 0, 0, - webkit_marshal_VOID__OBJECT_OBJECT, - G_TYPE_NONE, 2, - WEBKIT_TYPE_WEB_RESOURCE, - WEBKIT_TYPE_URI_REQUEST); - - /** - * WebKitWebView::enter-fullscreen: - * @web_view: the #WebKitWebView on which the signal is emitted. - * - * Emitted when JavaScript code calls - * <function>element.webkitRequestFullScreen</function>. If the - * signal is not handled the #WebKitWebView will proceed to full screen - * its top level window. This signal can be used by client code to - * request permission to the user prior doing the full screen - * transition and eventually prepare the top-level window - * (e.g. hide some widgets that would otherwise be part of the - * full screen window). - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to continue emission of the event. - */ - signals[ENTER_FULLSCREEN] = - g_signal_new("enter-fullscreen", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, enter_fullscreen), - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__VOID, - G_TYPE_BOOLEAN, 0); - - /** - * WebKitWebView::leave-fullscreen: - * @web_view: the #WebKitWebView on which the signal is emitted. - * - * Emitted when the #WebKitWebView is about to restore its top level - * window out of its full screen state. This signal can be used by - * client code to restore widgets hidden during the - * #WebKitWebView::enter-fullscreen stage for instance. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to continue emission of the event. - */ - signals[LEAVE_FULLSCREEN] = - g_signal_new("leave-fullscreen", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, leave_fullscreen), - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__VOID, - G_TYPE_BOOLEAN, 0); - /** - * WebKitWebView::run-file-chooser: - * @web_view: the #WebKitWebView on which the signal is emitted - * @request: a #WebKitFileChooserRequest - * - * This signal is emitted when the user interacts with a <input - * type='file' /> HTML element, requesting from WebKit to show - * a dialog to select one or more files to be uploaded. To let the - * application know the details of the file chooser, as well as to - * allow the client application to either cancel the request or - * perform an actual selection of files, the signal will pass an - * instance of the #WebKitFileChooserRequest in the @request - * argument. - * - * The default signal handler will asynchronously run a regular - * #GtkFileChooserDialog for the user to interact with. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - * - */ - signals[RUN_FILE_CHOOSER] = - g_signal_new("run-file-chooser", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, run_file_chooser), - g_signal_accumulator_true_handled, 0 /* accumulator data */, - webkit_marshal_BOOLEAN__OBJECT, - G_TYPE_BOOLEAN, 1, /* number of parameters */ - WEBKIT_TYPE_FILE_CHOOSER_REQUEST); - - /** - * WebKitWebView::context-menu: - * @web_view: the #WebKitWebView on which the signal is emitted - * @context_menu: the proposed #WebKitContextMenu - * @event: the #GdkEvent that triggered the context menu - * @hit_test_result: a #WebKitHitTestResult - * - * Emmited when a context menu is about to be displayed to give the application - * a chance to customize the proposed menu, prevent the menu from being displayed - * or build its own context menu. - * <itemizedlist> - * <listitem><para> - * To customize the proposed menu you can use webkit_context_menu_prepend(), - * webkit_context_menu_append() or webkit_context_menu_insert() to add new - * #WebKitContextMenuItem<!-- -->s to @context_menu, webkit_context_menu_move_item() - * to reorder existing items, or webkit_context_menu_remove() to remove an - * existing item. The signal handler should return %FALSE, and the menu represented - * by @context_menu will be shown. - * </para></listitem> - * <listitem><para> - * To prevent the menu from being displayed you can just connect to this signal - * and return %TRUE so that the proposed menu will not be shown. - * </para></listitem> - * <listitem><para> - * To build your own menu, you can remove all items from the proposed menu with - * webkit_context_menu_remove_all(), add your own items and return %FALSE so - * that the menu will be shown. You can also ignore the proposed #WebKitContextMenu, - * build your own #GtkMenu and return %TRUE to prevent the proposed menu from being shown. - * </para></listitem> - * <listitem><para> - * If you just want the default menu to be shown always, simply don't connect to this - * signal because showing the proposed context menu is the default behaviour. - * </para></listitem> - * </itemizedlist> - * - * If the signal handler returns %FALSE the context menu represented by @context_menu - * will be shown, if it return %TRUE the context menu will not be shown. - * - * The proposed #WebKitContextMenu passed in @context_menu argument is only valid - * during the signal emission. - * - * Returns: %TRUE to stop other handlers from being invoked for the event. - * %FALSE to propagate the event further. - */ - signals[CONTEXT_MENU] = - g_signal_new("context-menu", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, context_menu), - g_signal_accumulator_true_handled, 0, - webkit_marshal_BOOLEAN__OBJECT_BOXED_OBJECT, - G_TYPE_BOOLEAN, 3, - WEBKIT_TYPE_CONTEXT_MENU, - GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE, - WEBKIT_TYPE_HIT_TEST_RESULT); - - /** - * WebKitWebView::context-menu-dismissed: - * @web_view: the #WebKitWebView on which the signal is emitted - * - * Emitted after #WebKitWebView::context-menu signal, if the context menu is shown, - * to notify that the context menu is dismissed. - */ - signals[CONTEXT_MENU_DISMISSED] = - g_signal_new("context-menu-dismissed", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, context_menu_dismissed), - 0, 0, - g_cclosure_marshal_VOID__VOID, - G_TYPE_NONE, 0); - - /** - * WebKitWebView::submit-form: - * @web_view: the #WebKitWebView on which the signal is emitted - * @request: a #WebKitFormSubmissionRequest - * - * This signal is emitted when a form is about to be submitted. The @request - * argument passed contains information about the text fields of the form. This - * is typically used to store login information that can be used later to - * pre-fill the form. - * The form will not be submitted until webkit_form_submission_request_submit() is called. - * - * It is possible to handle the form submission request asynchronously, by - * simply calling g_object_ref() on the @request argument and calling - * webkit_form_submission_request_submit() when done to continue with the form submission. - * If the last reference is removed on a #WebKitFormSubmissionRequest and the - * form has not been submitted, webkit_form_submission_request_submit() will be called. - */ - signals[SUBMIT_FORM] = - g_signal_new("submit-form", - G_TYPE_FROM_CLASS(webViewClass), - G_SIGNAL_RUN_LAST, - G_STRUCT_OFFSET(WebKitWebViewClass, submit_form), - 0, 0, - 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) -{ - if (webView->priv->isLoading == isLoading) - return; - - webView->priv->isLoading = isLoading; - g_object_freeze_notify(G_OBJECT(webView)); - g_object_notify(G_OBJECT(webView), "is-loading"); - - // Update the URI if a new load has started. - if (webView->priv->isLoading) - webkitWebViewUpdateURI(webView); - g_object_thaw_notify(G_OBJECT(webView)); -} - -static void webkitWebViewEmitLoadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent) -{ - if (loadEvent == WEBKIT_LOAD_STARTED) { - webkitWebViewSetIsLoading(webView, true); - webkitWebViewWatchForChangesInFavicon(webView); - webkitWebViewBaseCancelAuthenticationDialog(WEBKIT_WEB_VIEW_BASE(webView)); - } else if (loadEvent == WEBKIT_LOAD_FINISHED) { - webkitWebViewSetIsLoading(webView, false); - webView->priv->waitingForMainResource = false; - webkitWebViewDisconnectMainResourceResponseChangedSignalHandler(webView); - } else - webkitWebViewUpdateURI(webView); - g_signal_emit(webView, signals[LOAD_CHANGED], 0, loadEvent); -} - -static void webkitWebViewEmitDelayedLoadEvents(WebKitWebView* webView) -{ - WebKitWebViewPrivate* priv = webView->priv; - if (!priv->waitingForMainResource) - return; - ASSERT(priv->lastDelayedEvent == WEBKIT_LOAD_COMMITTED || priv->lastDelayedEvent == WEBKIT_LOAD_FINISHED); - - if (priv->lastDelayedEvent == WEBKIT_LOAD_FINISHED) - webkitWebViewEmitLoadChanged(webView, WEBKIT_LOAD_COMMITTED); - webkitWebViewEmitLoadChanged(webView, priv->lastDelayedEvent); - priv->waitingForMainResource = false; -} - -void webkitWebViewLoadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent) -{ - WebKitWebViewPrivate* priv = webView->priv; - if (loadEvent == WEBKIT_LOAD_STARTED) { - // Finish a possible previous load waiting for main resource. - webkitWebViewEmitDelayedLoadEvents(webView); - - webkitWebViewCancelFaviconRequest(webView); - priv->loadingResourcesMap.clear(); - priv->mainResource = 0; - priv->waitingForMainResource = false; - } else if (loadEvent == WEBKIT_LOAD_COMMITTED) { - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(priv->context); - GOwnPtr<char> faviconURI(webkit_favicon_database_get_favicon_uri(database, priv->activeURI.data())); - webkitWebViewUpdateFaviconURI(webView, faviconURI.get()); - - 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; - } - } - - if (priv->waitingForMainResource) - priv->lastDelayedEvent = loadEvent; - else - webkitWebViewEmitLoadChanged(webView, loadEvent); -} - -void webkitWebViewLoadFailed(WebKitWebView* webView, WebKitLoadEvent loadEvent, const char* failingURI, GError *error) -{ - webkitWebViewSetIsLoading(webView, false); - gboolean returnValue; - g_signal_emit(webView, signals[LOAD_FAILED], 0, loadEvent, failingURI, error, &returnValue); - 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; - if (priv->title == title) - return; - - priv->title = title; - g_object_notify(G_OBJECT(webView), "title"); -} - -void webkitWebViewSetEstimatedLoadProgress(WebKitWebView* webView, double estimatedLoadProgress) -{ - if (webView->priv->estimatedLoadProgress == estimatedLoadProgress) - return; - - webView->priv->estimatedLoadProgress = estimatedLoadProgress; - g_object_notify(G_OBJECT(webView), "estimated-load-progress"); -} - -void webkitWebViewUpdateURI(WebKitWebView* webView) -{ - CString activeURI = getPage(webView)->activeURL().utf8(); - if (webView->priv->activeURI == activeURI) - return; - - webView->priv->activeURI = activeURI; - g_object_notify(G_OBJECT(webView), "uri"); -} - -WebPageProxy* webkitWebViewCreateNewPage(WebKitWebView* webView, ImmutableDictionary* windowFeatures) -{ - WebKitWebView* newWebView; - g_signal_emit(webView, signals[CREATE], 0, &newWebView); - if (!newWebView) - return 0; - - webkitWindowPropertiesUpdateFromWebWindowFeatures(newWebView->priv->windowProperties.get(), windowFeatures); - - RefPtr<WebPageProxy> newPage = getPage(newWebView); - return newPage.release().leakRef(); -} - -void webkitWebViewReadyToShowPage(WebKitWebView* webView) -{ - g_signal_emit(webView, signals[READY_TO_SHOW], 0, NULL); -} - -void webkitWebViewRunAsModal(WebKitWebView* webView) -{ - g_signal_emit(webView, signals[RUN_AS_MODAL], 0, NULL); - - webView->priv->modalLoop = adoptGRef(g_main_loop_new(0, FALSE)); - gdk_threads_leave(); - g_main_loop_run(webView->priv->modalLoop.get()); - gdk_threads_enter(); -} - -void webkitWebViewClosePage(WebKitWebView* webView) -{ - g_signal_emit(webView, signals[CLOSE], 0, NULL); -} - -void webkitWebViewRunJavaScriptAlert(WebKitWebView* webView, const CString& message) -{ - WebKitScriptDialog dialog(WEBKIT_SCRIPT_DIALOG_ALERT, message); - gboolean returnValue; - g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, &dialog, &returnValue); -} - -bool webkitWebViewRunJavaScriptConfirm(WebKitWebView* webView, const CString& message) -{ - WebKitScriptDialog dialog(WEBKIT_SCRIPT_DIALOG_CONFIRM, message); - gboolean returnValue; - g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, &dialog, &returnValue); - return dialog.confirmed; -} - -CString webkitWebViewRunJavaScriptPrompt(WebKitWebView* webView, const CString& message, const CString& defaultText) -{ - WebKitScriptDialog dialog(WEBKIT_SCRIPT_DIALOG_PROMPT, message, defaultText); - gboolean returnValue; - g_signal_emit(webView, signals[SCRIPT_DIALOG], 0, &dialog, &returnValue); - return dialog.text; -} - -void webkitWebViewMakePolicyDecision(WebKitWebView* webView, WebKitPolicyDecisionType type, WebKitPolicyDecision* decision) -{ - gboolean returnValue; - g_signal_emit(webView, signals[DECIDE_POLICY], 0, decision, type, &returnValue); -} - -void webkitWebViewMakePermissionRequest(WebKitWebView* webView, WebKitPermissionRequest* request) -{ - gboolean returnValue; - g_signal_emit(webView, signals[PERMISSION_REQUEST], 0, request, &returnValue); -} - -void webkitWebViewMouseTargetChanged(WebKitWebView* webView, WebHitTestResult* hitTestResult, unsigned modifiers) -{ - webkitWebViewBaseSetTooltipArea(WEBKIT_WEB_VIEW_BASE(webView), hitTestResult->elementBoundingBox()); - - WebKitWebViewPrivate* priv = webView->priv; - if (priv->mouseTargetHitTestResult - && priv->mouseTargetModifiers == modifiers - && webkitHitTestResultCompare(priv->mouseTargetHitTestResult.get(), hitTestResult)) - return; - - priv->mouseTargetModifiers = modifiers; - priv->mouseTargetHitTestResult = adoptGRef(webkitHitTestResultCreate(hitTestResult)); - g_signal_emit(webView, signals[MOUSE_TARGET_CHANGED], 0, priv->mouseTargetHitTestResult.get(), modifiers); -} - -void webkitWebViewPrintFrame(WebKitWebView* webView, WebFrameProxy* frame) -{ - GRefPtr<WebKitPrintOperation> printOperation = adoptGRef(webkit_print_operation_new(webView)); - gboolean returnValue; - g_signal_emit(webView, signals[PRINT], 0, printOperation.get(), &returnValue); - if (returnValue) - return; - - WebKitPrintOperationResponse response = webkitPrintOperationRunDialogForFrame(printOperation.get(), 0, frame); - if (response == WEBKIT_PRINT_OPERATION_RESPONSE_CANCEL) - return; - g_signal_connect(printOperation.leakRef(), "finished", G_CALLBACK(g_object_unref), 0); -} - -static void mainResourceResponseChangedCallback(WebKitWebResource*, GParamSpec*, WebKitWebView* webView) -{ - webkitWebViewDisconnectMainResourceResponseChangedSignalHandler(webView); - webkitWebViewEmitDelayedLoadEvents(webView); -} - -static void waitForMainResourceResponseIfWaitingForResource(WebKitWebView* webView) -{ - WebKitWebViewPrivate* priv = webView->priv; - if (!priv->waitingForMainResource) - return; - - webkitWebViewDisconnectMainResourceResponseChangedSignalHandler(webView); - priv->mainResourceResponseHandlerID = - g_signal_connect(priv->mainResource.get(), "notify::response", G_CALLBACK(mainResourceResponseChangedCallback), webView); -} - -void webkitWebViewResourceLoadStarted(WebKitWebView* webView, WebFrameProxy* frame, uint64_t resourceIdentifier, WebKitURIRequest* request) -{ - WebKitWebViewPrivate* priv = webView->priv; - bool isMainResource = frame->isMainFrame() && !priv->mainResource; - WebKitWebResource* resource = webkitWebResourceCreate(frame, request, isMainResource); - if (isMainResource) { - priv->mainResource = resource; - waitForMainResourceResponseIfWaitingForResource(webView); - } - priv->loadingResourcesMap.set(resourceIdentifier, adoptGRef(resource)); - g_signal_emit(webView, signals[RESOURCE_LOAD_STARTED], 0, resource, request); -} - -WebKitWebResource* webkitWebViewGetLoadingWebResource(WebKitWebView* webView, uint64_t resourceIdentifier) -{ - GRefPtr<WebKitWebResource> resource = webView->priv->loadingResourcesMap.get(resourceIdentifier); - return resource.get(); -} - -void webkitWebViewRemoveLoadingWebResource(WebKitWebView* webView, uint64_t resourceIdentifier) -{ - WebKitWebViewPrivate* priv = webView->priv; - ASSERT(priv->loadingResourcesMap.contains(resourceIdentifier)); - priv->loadingResourcesMap.remove(resourceIdentifier); -} - -bool webkitWebViewEnterFullScreen(WebKitWebView* webView) -{ - gboolean returnValue; - g_signal_emit(webView, signals[ENTER_FULLSCREEN], 0, &returnValue); - return !returnValue; -} - -bool webkitWebViewLeaveFullScreen(WebKitWebView* webView) -{ - gboolean returnValue; - g_signal_emit(webView, signals[LEAVE_FULLSCREEN], 0, &returnValue); - return !returnValue; -} - -void webkitWebViewRunFileChooserRequest(WebKitWebView* webView, WebKitFileChooserRequest* request) -{ - gboolean returnValue; - g_signal_emit(webView, signals[RUN_FILE_CHOOSER], 0, request, &returnValue); -} - -static bool webkitWebViewShouldShowInputMethodsMenu(WebKitWebView* webView) -{ - GtkSettings* settings = gtk_widget_get_settings(GTK_WIDGET(webView)); - if (!settings) - return true; - - gboolean showInputMethodMenu; - g_object_get(settings, "gtk-show-input-method-menu", &showInputMethodMenu, NULL); - return showInputMethodMenu; -} - -static int getUnicodeMenuItemPosition(WebKitContextMenu* contextMenu) -{ - GList* items = webkit_context_menu_get_items(contextMenu); - GList* iter; - int i = 0; - for (iter = items, i = 0; iter; iter = g_list_next(iter), ++i) { - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(iter->data); - - if (webkit_context_menu_item_is_separator(item)) - continue; - if (webkit_context_menu_item_get_stock_action(item) == WEBKIT_CONTEXT_MENU_ACTION_UNICODE) - return i; - } - return -1; -} - -static void webkitWebViewCreateAndAppendInputMethodsMenuItem(WebKitWebView* webView, WebKitContextMenu* contextMenu) -{ - if (!webkitWebViewShouldShowInputMethodsMenu(webView)) - return; - - // Place the im context menu item right before the unicode menu item - // if it's present. - int unicodeMenuItemPosition = getUnicodeMenuItemPosition(contextMenu); - if (unicodeMenuItemPosition == -1) - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - - GtkIMContext* imContext = webkitWebViewBaseGetIMContext(WEBKIT_WEB_VIEW_BASE(webView)); - GtkMenu* imContextMenu = GTK_MENU(gtk_menu_new()); - gtk_im_multicontext_append_menuitems(GTK_IM_MULTICONTEXT(imContext), GTK_MENU_SHELL(imContextMenu)); - WebKitContextMenuItem* menuItem = webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS); - webkitContextMenuItemSetSubMenuFromGtkMenu(menuItem, imContextMenu); - webkit_context_menu_insert(contextMenu, menuItem, unicodeMenuItemPosition); -} - -static void contextMenuDismissed(GtkMenuShell*, WebKitWebView* webView) -{ - g_signal_emit(webView, signals[CONTEXT_MENU_DISMISSED], 0, NULL); -} - -void webkitWebViewPopulateContextMenu(WebKitWebView* webView, ImmutableArray* proposedMenu, WebHitTestResult* webHitTestResult) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(webView); - WebContextMenuProxyGtk* contextMenuProxy = webkitWebViewBaseGetActiveContextMenuProxy(webViewBase); - ASSERT(contextMenuProxy); - - GRefPtr<WebKitContextMenu> contextMenu = adoptGRef(webkitContextMenuCreate(proposedMenu)); - if (webHitTestResult->isContentEditable()) - webkitWebViewCreateAndAppendInputMethodsMenuItem(webView, contextMenu.get()); - - GRefPtr<WebKitHitTestResult> hitTestResult = adoptGRef(webkitHitTestResultCreate(webHitTestResult)); - GOwnPtr<GdkEvent> contextMenuEvent(webkitWebViewBaseTakeContextMenuEvent(webViewBase)); - - gboolean returnValue; - g_signal_emit(webView, signals[CONTEXT_MENU], 0, contextMenu.get(), contextMenuEvent.get(), hitTestResult.get(), &returnValue); - if (returnValue) - return; - - Vector<ContextMenuItem> contextMenuItems; - webkitContextMenuPopulate(contextMenu.get(), contextMenuItems); - contextMenuProxy->populate(contextMenuItems); - - g_signal_connect(contextMenuProxy->gtkMenu(), "deactivate", G_CALLBACK(contextMenuDismissed), webView); - - // Clear the menu to make sure it's useless after signal emission. - webkit_context_menu_remove_all(contextMenu.get()); -} - -void webkitWebViewSubmitFormRequest(WebKitWebView* webView, WebKitFormSubmissionRequest* request) -{ - g_signal_emit(webView, signals[SUBMIT_FORM], 0, request); -} - -void webkitWebViewHandleAuthenticationChallenge(WebKitWebView* webView, AuthenticationChallengeProxy* authenticationChallenge) -{ - 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 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 - */ -GtkWidget* webkit_web_view_new() -{ - return webkit_web_view_new_with_context(webkit_web_context_get_default()); -} - -/** - * webkit_web_view_new_with_context: - * @context: the #WebKitWebContext to be used by the #WebKitWebView - * - * 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 - */ -GtkWidget* webkit_web_view_new_with_context(WebKitWebContext* context) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_CONTEXT(context), 0); - - return GTK_WIDGET(g_object_new(WEBKIT_TYPE_WEB_VIEW, "web-context", context, NULL)); -} - -/** - * 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 - * - * Gets the web context of @web_view. - * - * Returns: (transfer none): the #WebKitWebContext of the view - */ -WebKitWebContext* webkit_web_view_get_context(WebKitWebView *webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->context; -} - -/** - * 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 - * - * Requests loading of the specified URI string. - * You can monitor the load operation by connecting to - * #WebKitWebView::load-changed signal. - */ -void webkit_web_view_load_uri(WebKitWebView* webView, const gchar* uri) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(uri); - - getPage(webView)->loadURL(String::fromUTF8(uri)); -} - -/** - * webkit_web_view_load_html: - * @web_view: a #WebKitWebView - * @content: The HTML string to load - * @base_uri: (allow-none): The base URI for relative locations or %NULL - * - * Load the given @content string with the specified @base_uri. - * If @base_uri is not %NULL, relative URLs in the @content will be - * resolved against @base_uri and absolute local paths must be children of the @base_uri. - * For security reasons absolute local paths that are not children of @base_uri - * will cause the web process to terminate. - * If you need to include URLs in @content that are local paths in a different - * directory than @base_uri you can build a data URI for them. When @base_uri is %NULL, - * it defaults to "about:blank". The mime type of the document will be "text/html". - * You can monitor the load operation by connecting to #WebKitWebView::load-changed signal. - */ -void webkit_web_view_load_html(WebKitWebView* webView, const gchar* content, const gchar* baseURI) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(content); - - getPage(webView)->loadHTMLString(String::fromUTF8(content), String::fromUTF8(baseURI)); -} - -/** - * webkit_web_view_load_alternate_html: - * @web_view: a #WebKitWebView - * @content: the new content to display as the main page of the @web_view - * @content_uri: the URI for the alternate page content - * @base_uri: (allow-none): the base URI for relative locations or %NULL - * - * Load the given @content string for the URI @content_uri. - * This allows clients to display page-loading errors in the #WebKitWebView itself. - * When this method is called from #WebKitWebView::load-failed signal to show an - * error page, the the back-forward list is maintained appropriately. - * For everything else this method works the same way as webkit_web_view_load_html(). - */ -void webkit_web_view_load_alternate_html(WebKitWebView* webView, const gchar* content, const gchar* contentURI, const gchar* baseURI) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(content); - g_return_if_fail(contentURI); - - getPage(webView)->loadAlternateHTMLString(String::fromUTF8(content), String::fromUTF8(baseURI), String::fromUTF8(contentURI)); -} - -/** - * webkit_web_view_load_plain_text: - * @web_view: a #WebKitWebView - * @plain_text: The plain text to load - * - * Load the specified @plain_text string into @web_view. The mime type of - * document will be "text/plain". You can monitor the load - * operation by connecting to #WebKitWebView::load-changed signal. - */ -void webkit_web_view_load_plain_text(WebKitWebView* webView, const gchar* plainText) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(plainText); - - getPage(webView)->loadPlainTextString(String::fromUTF8(plainText)); -} - -/** - * webkit_web_view_load_request: - * @web_view: a #WebKitWebView - * @request: a #WebKitURIRequest to load - * - * Requests loading of the specified #WebKitURIRequest. - * You can monitor the load operation by connecting to - * #WebKitWebView::load-changed signal. - */ -void webkit_web_view_load_request(WebKitWebView* webView, WebKitURIRequest* request) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(WEBKIT_IS_URI_REQUEST(request)); - - 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(); -} - -/** - * webkit_web_view_get_title: - * @web_view: a #WebKitWebView - * - * Gets the value of the #WebKitWebView:title property. - * You can connect to notify::title signal of @web_view to - * be notified when the title has been received. - * - * Returns: The main frame document title of @web_view. - */ -const gchar* webkit_web_view_get_title(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->title.data(); -} - -/** - * webkit_web_view_reload: - * @web_view: a #WebKitWebView - * - * Reloads the current contents of @web_view. - * See also webkit_web_view_reload_bypass_cache(). - */ -void webkit_web_view_reload(WebKitWebView* webView) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - getPage(webView)->reload(false); -} - -/** - * webkit_web_view_reload_bypass_cache: - * @web_view: a #WebKitWebView - * - * Reloads the current contents of @web_view without - * using any cached data. - */ -void webkit_web_view_reload_bypass_cache(WebKitWebView* webView) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - getPage(webView)->reload(true); -} - -/** - * webkit_web_view_stop_loading: - * @web_view: a #WebKitWebView - * - * Stops any ongoing loading operation in @web_view. - * This method does nothing if no content is being loaded. - * If there is a loading operation in progress, it will be cancelled and - * #WebKitWebView::load-failed signal will be emitted with - * %WEBKIT_NETWORK_ERROR_CANCELLED error. - */ -void webkit_web_view_stop_loading(WebKitWebView* webView) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - getPage(webView)->stopLoading(); -} - -/** - * webkit_web_view_is_loading: - * @web_view: a #WebKitWebView - * - * Gets the value of the #WebKitWebView:is-loading property. - * You can monitor when a #WebKitWebView is loading a page by connecting to - * notify::is-loading signal of @web_view. This is useful when you are - * interesting in knowing when the view is loding something but not in the - * details about the status of the load operation, for example to start a spinner - * when the view is loading a page and stop it when it finishes. - * - * Returns: %TRUE if @web_view is loading a page or %FALSE otherwise. - */ -gboolean webkit_web_view_is_loading(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); - - return webView->priv->isLoading; -} - -/** - * webkit_web_view_go_back: - * @web_view: a #WebKitWebView - * - * Loads the previous history item. - * You can monitor the load operation by connecting to - * #WebKitWebView::load-changed signal. - */ -void webkit_web_view_go_back(WebKitWebView* webView) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - getPage(webView)->goBack(); -} - -/** - * webkit_web_view_can_go_back: - * @web_view: a #WebKitWebView - * - * Determines whether @web_view has a previous history item. - * - * Returns: %TRUE if able to move back or %FALSE otherwise. - */ -gboolean webkit_web_view_can_go_back(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); - - return getPage(webView)->canGoBack(); -} - -/** - * webkit_web_view_go_forward: - * @web_view: a #WebKitWebView - * - * Loads the next history item. - * You can monitor the load operation by connecting to - * #WebKitWebView::load-changed signal. - */ -void webkit_web_view_go_forward(WebKitWebView* webView) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - getPage(webView)->goForward(); -} - -/** - * webkit_web_view_can_go_forward: - * @web_view: a #WebKitWebView - * - * Determines whether @web_view has a next history item. - * - * Returns: %TRUE if able to move forward or %FALSE otherwise. - */ -gboolean webkit_web_view_can_go_forward(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); - - return getPage(webView)->canGoForward(); -} - -/** - * webkit_web_view_get_uri: - * @web_view: a #WebKitWebView - * - * Returns the current active URI of @web_view. The active URI might change during - * a load operation: - * - * <orderedlist> - * <listitem><para> - * When nothing has been loaded yet on @web_view the active URI is %NULL. - * </para></listitem> - * <listitem><para> - * When a new load operation starts the active URI is the requested URI: - * <itemizedlist> - * <listitem><para> - * If the load operation was started by webkit_web_view_load_uri(), - * the requested URI is the given one. - * </para></listitem> - * <listitem><para> - * If the load operation was started by webkit_web_view_load_html(), - * the requested URI is "about:blank". - * </para></listitem> - * <listitem><para> - * If the load operation was started by webkit_web_view_load_alternate_html(), - * the requested URI is content URI provided. - * </para></listitem> - * <listitem><para> - * If the load operation was started by webkit_web_view_go_back() or - * webkit_web_view_go_forward(), the requested URI is the original URI - * of the previous/next item in the #WebKitBackForwardList of @web_view. - * </para></listitem> - * <listitem><para> - * If the load operation was started by - * webkit_web_view_go_to_back_forward_list_item(), the requested URI - * is the opriginal URI of the given #WebKitBackForwardListItem. - * </para></listitem> - * </itemizedlist> - * </para></listitem> - * <listitem><para> - * If there is a server redirection during the load operation, - * the active URI is the redirected URI. When the signal - * #WebKitWebView::load-changed is emitted with %WEBKIT_LOAD_REDIRECTED - * event, the active URI is already updated to the redirected URI. - * </para></listitem> - * <listitem><para> - * When the signal #WebKitWebView::load-changed is emitted - * with %WEBKIT_LOAD_COMMITTED event, the active URI is the final - * one and it will not change unless a new load operation is started - * or a navigation action within the same page is performed. - * </para></listitem> - * </orderedlist> - * - * You can monitor the active URI by connecting to the notify::uri - * signal of @web_view. - * - * Returns: the current active URI of @web_view or %NULL - * if nothing has been loaded yet. - */ -const gchar* webkit_web_view_get_uri(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->activeURI.data(); -} - -/** - * webkit_web_view_get_favicon: - * @web_view: a #WebKitWebView - * - * Returns favicon currently associated to @web_view, if any. You can - * connect to notify::favicon signal of @web_view to be notified when - * the favicon is available. - * - * Returns: (transfer none): a pointer to a #cairo_surface_t with the - * favicon or %NULL if there's no icon associated with @web_view. - */ -cairo_surface_t* webkit_web_view_get_favicon(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - if (webView->priv->activeURI.isNull()) - return 0; - - return webView->priv->favicon.get(); -} - -/** - * webkit_web_view_get_custom_charset: - * @web_view: a #WebKitWebView - * - * Returns the current custom character encoding name of @web_view. - * - * Returns: the current custom character encoding name or %NULL if no - * custom character encoding has been set. - */ -const gchar* webkit_web_view_get_custom_charset(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - String customTextEncoding = getPage(webView)->customTextEncodingName(); - if (customTextEncoding.isEmpty()) - return 0; - - webView->priv->customTextEncoding = customTextEncoding.utf8(); - return webView->priv->customTextEncoding.data(); -} - -/** - * webkit_web_view_set_custom_charset: - * @web_view: a #WebKitWebView - * @charset: (allow-none): a character encoding name or %NULL - * - * Sets the current custom character encoding override of @web_view. The custom - * character encoding will override any text encoding detected via HTTP headers or - * META tags. Calling this method will stop any current load operation and reload the - * current page. Setting the custom character encoding to %NULL removes the character - * encoding override. - */ -void webkit_web_view_set_custom_charset(WebKitWebView* webView, const gchar* charset) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - getPage(webView)->setCustomTextEncodingName(String::fromUTF8(charset)); -} - -/** - * webkit_web_view_get_estimated_load_progress: - * @web_view: a #WebKitWebView - * - * Gets the value of the #WebKitWebView:estimated-load-progress property. - * You can monitor the estimated progress of a load operation by - * connecting to the notify::estimated-load-progress signal of @web_view. - * - * Returns: an estimate of the of the percent complete for a document - * load as a range from 0.0 to 1.0. - */ -gdouble webkit_web_view_get_estimated_load_progress(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - return webView->priv->estimatedLoadProgress; -} - -/** - * webkit_web_view_get_back_forward_list: - * @web_view: a #WebKitWebView - * - * Obtains the #WebKitBackForwardList associated with the given #WebKitWebView. The - * #WebKitBackForwardList is owned by the #WebKitWebView. - * - * Returns: (transfer none): the #WebKitBackForwardList - */ -WebKitBackForwardList* webkit_web_view_get_back_forward_list(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->backForwardList.get(); -} - -/** - * webkit_web_view_go_to_back_forward_list_item: - * @web_view: a #WebKitWebView - * @list_item: a #WebKitBackForwardListItem - * - * Loads the specific history item @list_item. - * You can monitor the load operation by connecting to - * #WebKitWebView::load-changed signal. - */ -void webkit_web_view_go_to_back_forward_list_item(WebKitWebView* webView, WebKitBackForwardListItem* listItem) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(listItem)); - - getPage(webView)->goToBackForwardItem(webkitBackForwardListItemGetItem(listItem)); -} - -/** - * webkit_web_view_set_settings: - * @web_view: a #WebKitWebView - * @settings: a #WebKitSettings - * - * 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) -{ - webkit_web_view_group_set_settings(webkit_web_view_get_group(webView), settings); -} - -/** - * webkit_web_view_get_settings: - * @web_view: a #WebKitWebView - * - * Gets the #WebKitSettings currently applied to @web_view. - * 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 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) -{ - return webkit_web_view_group_get_settings(webkit_web_view_get_group(webView)); -} - -/** - * webkit_web_view_get_window_properties: - * @web_view: a #WebKitWebView - * - * Get the #WebKitWindowProperties object containing the properties - * that the window containing @web_view should have. - * - * Returns: (transfer none): the #WebKitWindowProperties of @web_view - */ -WebKitWindowProperties* webkit_web_view_get_window_properties(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->windowProperties.get(); -} - -/** - * webkit_web_view_set_zoom_level: - * @web_view: a #WebKitWebView - * @zoom_level: the zoom level - * - * Set the zoom level of @web_view, i.e. the factor by which the - * view contents are scaled with respect to their original size. - */ -void webkit_web_view_set_zoom_level(WebKitWebView* webView, gdouble zoomLevel) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - if (webkit_web_view_get_zoom_level(webView) == zoomLevel) - return; - - WebPageProxy* page = getPage(webView); - if (webkit_settings_get_zoom_text_only(webkit_web_view_get_settings(webView))) - page->setTextZoomFactor(zoomLevel); - else - page->setPageZoomFactor(zoomLevel); - g_object_notify(G_OBJECT(webView), "zoom-level"); -} - -/** - * webkit_web_view_get_zoom_level: - * @web_view: a #WebKitWebView - * - * Get the zoom level of @web_view, i.e. the factor by which the - * view contents are scaled with respect to their original size. - * - * Returns: the current zoom level of @web_view - */ -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(webkit_web_view_get_settings(webView)); - return zoomTextOnly ? page->textZoomFactor() : page->pageZoomFactor(); -} - -static void didValidateCommand(WKStringRef command, bool isEnabled, int32_t state, WKErrorRef, void* context) -{ - GRefPtr<GTask> task = adoptGRef(G_TASK(context)); - g_task_return_boolean(task.get(), isEnabled); -} - -/** - * webkit_web_view_can_execute_editing_command: - * @web_view: a #WebKitWebView - * @command: the command to check - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously execute the given editing command. - * - * When the operation is finished, @callback will be called. You can then call - * webkit_web_view_can_execute_editing_command_finish() to get the result of the operation. - */ -void webkit_web_view_can_execute_editing_command(WebKitWebView* webView, const char* command, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(command); - - GTask* task = g_task_new(webView, cancellable, callback, userData); - getPage(webView)->validateCommand(String::fromUTF8(command), ValidateCommandCallback::create(task, didValidateCommand)); -} - -/** - * webkit_web_view_can_execute_editing_command_finish: - * @web_view: a #WebKitWebView - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_view_can_execute_editing_command(). - * - * Returns: %TRUE if the editing command can be executed or %FALSE otherwise - */ -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_task_is_valid(result, webView), FALSE); - - return g_task_propagate_boolean(G_TASK(result), error); -} - -/** - * webkit_web_view_execute_editing_command: - * @web_view: a #WebKitWebView - * @command: the command to execute - * - * Request to execute the given @command for @web_view. You can use - * webkit_web_view_can_execute_editing_command() to check whether - * it's possible to execute the command. - */ -void webkit_web_view_execute_editing_command(WebKitWebView* webView, const char* command) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(command); - - getPage(webView)->executeEditCommand(String::fromUTF8(command)); -} - -/** - * webkit_web_view_get_find_controller: - * @web_view: the #WebKitWebView - * - * Gets the #WebKitFindController that will allow the caller to query - * the #WebKitWebView for the text to look for. - * - * Returns: (transfer none): the #WebKitFindController associated to - * this particular #WebKitWebView. - */ -WebKitFindController* webkit_web_view_get_find_controller(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - if (!webView->priv->findController) - webView->priv->findController = adoptGRef(WEBKIT_FIND_CONTROLLER(g_object_new(WEBKIT_TYPE_FIND_CONTROLLER, "web-view", webView, NULL))); - - return webView->priv->findController.get(); -} - -/** - * webkit_web_view_get_javascript_global_context: - * @web_view: a #WebKitWebView - * - * Get the global JavaScript context used by @web_view to deserialize the - * result values of scripts executed with webkit_web_view_run_javascript(). - * - * Returns: the <function>JSGlobalContextRef</function> used by @web_view to deserialize - * the result values of scripts. - */ -JSGlobalContextRef webkit_web_view_get_javascript_global_context(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - if (!webView->priv->javascriptGlobalContext) - webView->priv->javascriptGlobalContext = JSGlobalContextCreate(0); - return webView->priv->javascriptGlobalContext; -} - -static void webkitWebViewRunJavaScriptCallback(WKSerializedScriptValueRef wkSerializedScriptValue, WKErrorRef, void* context) -{ - 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; - } - - 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)); -} - -/** - * webkit_web_view_run_javascript: - * @web_view: a #WebKitWebView - * @script: the script to run - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @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. 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. - */ -void webkit_web_view_run_javascript(WebKitWebView* webView, const gchar* script, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(script); - - GTask* task = g_task_new(webView, cancellable, callback, userData); - getPage(webView)->runJavaScriptInMainFrame(String::fromUTF8(script), ScriptValueCallback::create(task, webkitWebViewRunJavaScriptCallback)); -} - -/** - * webkit_web_view_run_javascript_finish: - * @web_view: a #WebKitWebView - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_view_run_javascript(). - * - * This is an example of using webkit_web_view_run_javascript() with a script returning - * a string: - * - * <informalexample><programlisting> - * static void - * web_view_javascript_finished (GObject *object, - * GAsyncResult *result, - * gpointer user_data) - * { - * WebKitJavascriptResult *js_result; - * JSValueRef value; - * JSGlobalContextRef context; - * GError *error = NULL; - * - * js_result = webkit_web_view_run_javascript_finish (WEBKIT_WEB_VIEW (object), result, &error); - * if (!js_result) { - * g_warning ("Error running javascript: %s", error->message); - * g_error_free (error); - * return; - * } - * - * context = webkit_javascript_result_get_global_context (js_result); - * value = webkit_javascript_result_get_value (js_result); - * if (JSValueIsString (context, value)) { - * JSStringRef js_str_value; - * gchar *str_value; - * gsize str_length; - * - * js_str_value = JSValueToStringCopy (context, value, NULL); - * str_length = JSStringGetMaximumUTF8CStringSize (js_str_value); - * str_value = (gchar *)g_malloc (str_length); - * JSStringGetUTF8CString (js_str_value, str_value, str_length); - * JSStringRelease (js_str_value); - * g_print ("Script result: %s\n", str_value); - * g_free (str_value); - * } else { - * g_warning ("Error running javascript: unexpected return value"); - * } - * webkit_javascript_result_unref (js_result); - * } - * - * static void - * web_view_get_link_url (WebKitWebView *web_view, - * const gchar *link_id) - * { - * gchar *script; - * - * script = g_strdup_printf ("window.document.getElementById('%s').href;", link_id); - * webkit_web_view_run_javascript (web_view, script, NULL, web_view_javascript_finished, NULL); - * g_free (script); - * } - * </programlisting></informalexample> - * - * Returns: (transfer full): a #WebKitJavascriptResult with the result of the last executed statement in @script - * or %NULL in case of error - */ -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_task_is_valid(result, webView), 0); - - return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error)); -} - -static void resourcesStreamReadCallback(GObject* object, GAsyncResult* result, gpointer userData) -{ - GRefPtr<GTask> task = adoptGRef(G_TASK(userData)); - - GError* error = 0; - g_output_stream_splice_finish(G_OUTPUT_STREAM(object), result, &error); - if (error) { - g_task_return_error(task.get(), error); - return; - } - - 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)); -} - -/** - * webkit_web_view_run_javascript_from_gresource: - * @web_view: a #WebKitWebView - * @resource: the location of the resource to load - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the script finished - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously run the script from @resource in the context of the - * current page in @web_view. - * - * When the operation is finished, @callback will be called. You can - * then call webkit_web_view_run_javascript_from_gresource_finish() to get the result - * of the operation. - */ -void webkit_web_view_run_javascript_from_gresource(WebKitWebView* webView, const gchar* resource, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(resource); - - GError* error = 0; - GRefPtr<GInputStream> inputStream = adoptGRef(g_resources_open_stream(resource, G_RESOURCE_LOOKUP_FLAGS_NONE, &error)); - if (error) { - 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, task); -} - -/** - * webkit_web_view_run_javascript_from_gresource_finish: - * @web_view: a #WebKitWebView - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_view_run_javascript_from_gresource(). - * - * Check webkit_web_view_run_javascript_finish() for a usage example. - * - * Returns: (transfer full): a #WebKitJavascriptResult with the result of the last executed statement in @script - * or %NULL in case of error - */ -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_task_is_valid(result, webView), 0); - - return static_cast<WebKitJavascriptResult*>(g_task_propagate_pointer(G_TASK(result), error)); -} - -/** - * webkit_web_view_get_main_resource: - * @web_view: a #WebKitWebView - * - * Return the main resource of @web_view. - * - * Returns: (transfer none): the main #WebKitWebResource of the view - * or %NULL if nothing has been loaded. - */ -WebKitWebResource* webkit_web_view_get_main_resource(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - return webView->priv->mainResource.get(); -} - -/** - * webkit_web_view_get_inspector: - * @web_view: a #WebKitWebView - * - * Get the #WebKitWebInspector associated to @web_view - * - * Returns: (transfer none): the #WebKitWebInspector of @web_view - */ -WebKitWebInspector* webkit_web_view_get_inspector(WebKitWebView* webView) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - - if (!webView->priv->inspector) - webView->priv->inspector = adoptGRef(webkitWebInspectorCreate(getPage(webView)->inspector())); - - return webView->priv->inspector.get(); -} - -/** - * webkit_web_view_can_show_mime_type: - * @web_view: a #WebKitWebView - * @mime_type: a MIME type - * - * Whether or not a MIME type can be displayed in @web_view. - * - * Returns: %TRUE if the MIME type @mime_type can be displayed or %FALSE otherwise - */ -gboolean webkit_web_view_can_show_mime_type(WebKitWebView* webView, const char* mimeType) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), FALSE); - g_return_val_if_fail(mimeType, FALSE); - - return getPage(webView)->canShowMIMEType(String::fromUTF8(mimeType)); -} - -struct ViewSaveAsyncData { - RefPtr<WebData> webData; - GRefPtr<GFile> file; -}; -WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ViewSaveAsyncData) - -static void fileReplaceContentsCallback(GObject* object, GAsyncResult* result, gpointer data) -{ - GRefPtr<GTask> task = adoptGRef(G_TASK(data)); - GError* error = 0; - if (!g_file_replace_contents_finish(G_FILE(object), result, 0, &error)) { - g_task_return_error(task.get(), error); - return; - } - - g_task_return_boolean(task.get(), TRUE); -} - -static void getContentsAsMHTMLDataCallback(WKDataRef wkData, WKErrorRef, void* context) -{ - GRefPtr<GTask> task = adoptGRef(G_TASK(context)); - if (g_task_return_error_if_cancelled(task.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_task_return_boolean(task.get(), TRUE); -} - -/** - * webkit_web_view_save: - * @web_view: a #WebKitWebView - * @save_mode: the #WebKitSaveMode specifying how the web page should be saved. - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously save the current web page associated to the - * #WebKitWebView into a self-contained format using the mode - * specified in @save_mode. - * - * When the operation is finished, @callback will be called. You can - * then call webkit_web_view_save_finish() to get the result of the - * operation. - */ -void webkit_web_view_save(WebKitWebView* webView, WebKitSaveMode saveMode, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - - // We only support MHTML at the moment. - g_return_if_fail(saveMode == WEBKIT_SAVE_MODE_MHTML); - - 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); -} - -/** - * webkit_web_view_save_finish: - * @web_view: a #WebKitWebView - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_view_save(). - * - * Returns: (transfer full): a #GInputStream with the result of saving - * the current web page or %NULL in case of error. - */ -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_task_is_valid(result, webView), 0); - - 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_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); - - return dataStream; -} - -/** - * webkit_web_view_save_to_file: - * @web_view: a #WebKitWebView - * @file: the #GFile where the current web page should be saved to. - * @save_mode: the #WebKitSaveMode specifying how the web page should be saved. - * @cancellable: (allow-none): a #GCancellable or %NULL to ignore - * @callback: (scope async): a #GAsyncReadyCallback to call when the request is satisfied - * @user_data: (closure): the data to pass to callback function - * - * Asynchronously save the current web page associated to the - * #WebKitWebView into a self-contained format using the mode - * specified in @save_mode and writing it to @file. - * - * When the operation is finished, @callback will be called. You can - * then call webkit_web_view_save_to_file_finish() to get the result of the - * operation. - */ -void webkit_web_view_save_to_file(WebKitWebView* webView, GFile* file, WebKitSaveMode saveMode, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) -{ - g_return_if_fail(WEBKIT_IS_WEB_VIEW(webView)); - g_return_if_fail(G_IS_FILE(file)); - - // We only support MHTML at the moment. - g_return_if_fail(saveMode == WEBKIT_SAVE_MODE_MHTML); - - 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; - g_task_set_task_data(task, data, reinterpret_cast<GDestroyNotify>(destroyViewSaveAsyncData)); - - getPage(webView)->getContentsAsMHTMLData(DataCallback::create(task, getContentsAsMHTMLDataCallback), false); -} - -/** - * webkit_web_view_save_to_file_finish: - * @web_view: a #WebKitWebView - * @result: a #GAsyncResult - * @error: return location for error or %NULL to ignore - * - * Finish an asynchronous operation started with webkit_web_view_save_to_file(). - * - * Returns: %TRUE if the web page was successfully saved to a file or %FALSE otherwise. - */ -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_task_is_valid(result, webView), FALSE); - - return g_task_propagate_boolean(G_TASK(result), error); -} - -/** - * webkit_web_view_download_uri: - * @web_view: a #WebKitWebView - * @uri: the URI to download - * - * Requests downloading of the specified URI string for @web_view. - * - * Returns: (transfer full): a new #WebKitDownload representing the - * the download operation. - */ -WebKitDownload* webkit_web_view_download_uri(WebKitWebView* webView, const char* uri) -{ - g_return_val_if_fail(WEBKIT_IS_WEB_VIEW(webView), 0); - g_return_val_if_fail(uri, 0); - - WebKitDownload* download = webkitWebContextStartDownload(webView->priv->context, uri, getPage(webView)); - webkitDownloadSetWebView(download, webView); - - 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 deleted file mode 100644 index b23d7ffb1..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebView.h +++ /dev/null @@ -1,471 +0,0 @@ -/* - * Copyright (C) 2007 Holger Hans Peter Freyther - * Copyright (C) 2007, 2008 Alp Toker <alp@atoker.com> - * Copyright (C) 2008 Collabora Ltd. - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 WebKitWebView_h -#define WebKitWebView_h - -#include <JavaScriptCore/JSBase.h> -#include <webkit2/WebKitBackForwardList.h> -#include <webkit2/WebKitDefines.h> -#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> -#include <webkit2/WebKitPolicyDecision.h> -#include <webkit2/WebKitScriptDialog.h> -#include <webkit2/WebKitSettings.h> -#include <webkit2/WebKitURIRequest.h> -#include <webkit2/WebKitWebContext.h> -#include <webkit2/WebKitWebInspector.h> -#include <webkit2/WebKitWebResource.h> -#include <webkit2/WebKitWebViewBase.h> -#include <webkit2/WebKitWebViewGroup.h> -#include <webkit2/WebKitWindowProperties.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WEB_VIEW (webkit_web_view_get_type()) -#define WEBKIT_WEB_VIEW(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_WEB_VIEW, WebKitWebView)) -#define WEBKIT_IS_WEB_VIEW(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_WEB_VIEW)) -#define WEBKIT_WEB_VIEW_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_VIEW, WebKitWebViewClass)) -#define WEBKIT_IS_WEB_VIEW_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_VIEW)) -#define WEBKIT_WEB_VIEW_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_WEB_VIEW, WebKitWebViewClass)) - -typedef struct _WebKitWebViewClass WebKitWebViewClass; -typedef struct _WebKitWebViewPrivate WebKitWebViewPrivate; - -/** - * WebKitPolicyDecisionType: - * @WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION: This type of policy decision - * is requested when WebKit is about to navigate to a new page in either the - * main frame or a subframe. Acceptable policy decisions are either - * webkit_policy_decision_use() or webkit_policy_decision_ignore(). This - * type of policy decision is always a #WebKitNavigationPolicyDecision. - * @WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION: This type of policy decision - * is requested when WebKit is about to create a new window. Acceptable policy - * decisions are either webkit_policy_decision_use() or - * webkit_policy_decision_ignore(). This type of policy decision is always - * a #WebKitNavigationPolicyDecision. These decisions are useful for implementing - * special actions for new windows, such as forcing the new window to open - * in a tab when a keyboard modifier is active or handling a special - * target attribute on <a> elements. - * @WEBKIT_POLICY_DECISION_TYPE_RESPONSE: This type of decision is used when WebKit has - * received a response for a network resource and is about to start the load. - * Note that these resources include all subresources of a page such as images - * and stylesheets as well as main documents. Appropriate policy responses to - * this decision are webkit_policy_decision_use(), webkit_policy_decision_ignore(), - * or webkit_policy_decision_download(). This type of policy decision is always - * a #WebKitResponsePolicyDecision. This decision is useful for forcing - * some types of resources to be downloaded rather than rendered in the WebView - * or to block the transfer of resources entirely. - * - * Enum values used for determining the type of a policy decision during - * #WebKitWebView::decide-policy. - */ -typedef enum { - WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION, - WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION, - WEBKIT_POLICY_DECISION_TYPE_RESPONSE, -} WebKitPolicyDecisionType; - -/** - * WebKitLoadEvent: - * @WEBKIT_LOAD_STARTED: A new load request has been made. - * No data has been received yet, empty structures have - * been allocated to perform the load; the load may still - * fail due to transport issues such as not being able to - * resolve a name, or connect to a port. - * @WEBKIT_LOAD_REDIRECTED: A provisional data source received - * a server redirect. - * @WEBKIT_LOAD_COMMITTED: The content started arriving for a page load. - * The necessary transport requirements are stabilished, and the - * load is being performed. - * @WEBKIT_LOAD_FINISHED: Load completed. All resources are done loading - * or there was an error during the load operation. - * - * Enum values used to denote the different events that happen during a - * #WebKitWebView load operation. - */ -typedef enum { - WEBKIT_LOAD_STARTED, - WEBKIT_LOAD_REDIRECTED, - WEBKIT_LOAD_COMMITTED, - WEBKIT_LOAD_FINISHED -} WebKitLoadEvent; - -/** - * WebKitSaveMode: - * @WEBKIT_SAVE_MODE_MHTML: Save the current page using the MHTML format. - * - * Enum values to specify the different ways in which a #WebKitWebView - * can save its current web page into a self-contained file. - */ -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; - - /*< private >*/ - WebKitWebViewPrivate *priv; -}; - -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); - 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); - void (*_webkit_reserved3) (void); - void (*_webkit_reserved4) (void); - void (*_webkit_reserved5) (void); - void (*_webkit_reserved6) (void); - void (*_webkit_reserved7) (void); -}; - -WEBKIT_API GType -webkit_web_view_get_type (void); - -WEBKIT_API GtkWidget * -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); - -WEBKIT_API void -webkit_web_view_load_html (WebKitWebView *web_view, - const gchar *content, - const gchar *base_uri); -WEBKIT_API void -webkit_web_view_load_alternate_html (WebKitWebView *web_view, - const gchar *content, - const gchar *content_uri, - const gchar *base_uri); -WEBKIT_API void -webkit_web_view_load_plain_text (WebKitWebView *web_view, - const gchar *plain_text); - -WEBKIT_API void -webkit_web_view_load_request (WebKitWebView *web_view, - WebKitURIRequest *request); - -WEBKIT_API void -webkit_web_view_stop_loading (WebKitWebView *web_view); - -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); - -WEBKIT_API void -webkit_web_view_reload (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_reload_bypass_cache (WebKitWebView *web_view); - -WEBKIT_API gdouble -webkit_web_view_get_estimated_load_progress (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_go_back (WebKitWebView *web_view); - -WEBKIT_API gboolean -webkit_web_view_can_go_back (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_go_forward (WebKitWebView *web_view); - -WEBKIT_API gboolean -webkit_web_view_can_go_forward (WebKitWebView *web_view); - -WEBKIT_API WebKitBackForwardList * -webkit_web_view_get_back_forward_list (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_go_to_back_forward_list_item (WebKitWebView *web_view, - WebKitBackForwardListItem *list_item); -WEBKIT_API const gchar * -webkit_web_view_get_uri (WebKitWebView *web_view); - -WEBKIT_API cairo_surface_t * -webkit_web_view_get_favicon (WebKitWebView *web_view); - -WEBKIT_API const gchar * -webkit_web_view_get_custom_charset (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_set_custom_charset (WebKitWebView *web_view, - const gchar *charset); - -WEBKIT_API void -webkit_web_view_set_settings (WebKitWebView *web_view, - WebKitSettings *settings); - -WEBKIT_API WebKitSettings * -webkit_web_view_get_settings (WebKitWebView *web_view); - -WEBKIT_API WebKitWindowProperties * -webkit_web_view_get_window_properties (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_set_zoom_level (WebKitWebView *web_view, - gdouble zoom_level); -WEBKIT_API gdouble -webkit_web_view_get_zoom_level (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_can_execute_editing_command (WebKitWebView *web_view, - const gchar *command, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API gboolean -webkit_web_view_can_execute_editing_command_finish (WebKitWebView *web_view, - GAsyncResult *result, - GError **error); - -WEBKIT_API void -webkit_web_view_execute_editing_command (WebKitWebView *web_view, - const gchar *command); - -WEBKIT_API WebKitFindController * -webkit_web_view_get_find_controller (WebKitWebView *web_view); - -WEBKIT_API JSGlobalContextRef -webkit_web_view_get_javascript_global_context (WebKitWebView *web_view); - -WEBKIT_API void -webkit_web_view_run_javascript (WebKitWebView *web_view, - const gchar *script, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); -WEBKIT_API WebKitJavascriptResult * -webkit_web_view_run_javascript_finish (WebKitWebView *web_view, - GAsyncResult *result, - GError **error); - -WEBKIT_API void -webkit_web_view_run_javascript_from_gresource (WebKitWebView *web_view, - const gchar *resource, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API WebKitJavascriptResult * -webkit_web_view_run_javascript_from_gresource_finish (WebKitWebView *web_view, - GAsyncResult *result, - GError **error); - -WEBKIT_API WebKitWebResource * -webkit_web_view_get_main_resource (WebKitWebView *web_view); - -WEBKIT_API WebKitWebInspector * -webkit_web_view_get_inspector (WebKitWebView *web_view); - -WEBKIT_API gboolean -webkit_web_view_can_show_mime_type (WebKitWebView *web_view, - const gchar *mime_type); - -WEBKIT_API void -webkit_web_view_save (WebKitWebView *web_view, - WebKitSaveMode save_mode, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API GInputStream * -webkit_web_view_save_finish (WebKitWebView *web_view, - GAsyncResult *result, - GError **error); - -WEBKIT_API void -webkit_web_view_save_to_file (WebKitWebView *web_view, - GFile *file, - WebKitSaveMode save_mode, - GCancellable *cancellable, - GAsyncReadyCallback callback, - gpointer user_data); - -WEBKIT_API gboolean -webkit_web_view_save_to_file_finish (WebKitWebView *web_view, - GAsyncResult *result, - GError **error); - -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 deleted file mode 100644 index a414920b1..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.cpp +++ /dev/null @@ -1,1105 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 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. - */ - -#include "config.h" -#include "WebKitWebViewBase.h" - -#include "DrawingAreaProxyImpl.h" -#include "NativeWebMouseEvent.h" -#include "NativeWebWheelEvent.h" -#include "PageClientImpl.h" -#include "WebContext.h" -#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 "WebViewBaseInputMethodFilter.h" -#include <WebCore/ClipboardUtilitiesGtk.h> -#include <WebCore/DataObjectGtk.h> -#include <WebCore/DragData.h> -#include <WebCore/DragIcon.h> -#include <WebCore/GOwnPtrGtk.h> -#include <WebCore/GtkClickCounter.h> -#include <WebCore/GtkDragAndDropHelper.h> -#include <WebCore/GtkUtilities.h> -#include <WebCore/GtkVersioning.h> -#include <WebCore/NotImplemented.h> -#include <WebCore/PasteboardHelper.h> -#include <WebCore/RefPtrCairo.h> -#include <WebCore/Region.h> -#include <gdk/gdk.h> -#include <gdk/gdkkeysyms.h> -#include <wtf/HashMap.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -#if ENABLE(FULLSCREEN_API) -#include "WebFullScreenManagerProxy.h" -#endif - -#if USE(TEXTURE_MAPPER_GL) && defined(GDK_WINDOWING_X11) -#include <WebCore/RedirectedXCompositeWindow.h> -#endif - -using namespace WebKit; -using namespace WebCore; - -typedef HashMap<GtkWidget*, IntRect> WebKitWebViewChildrenMap; - -#if USE(TEXTURE_MAPPER_GL) -void redirectedWindowDamagedCallback(void* data); -#endif - -struct _WebKitWebViewBasePrivate { - _WebKitWebViewBasePrivate() -#if USE(TEXTURE_MAPPER_GL) - : redirectedWindow(RedirectedXCompositeWindow::create(IntSize(1, 1), RedirectedXCompositeWindow::DoNotCreateGLContext)) -#endif - { - } - - ~_WebKitWebViewBasePrivate() - { - pageProxy->close(); - } - - WebKitWebViewChildrenMap children; - OwnPtr<PageClientImpl> pageClient; - RefPtr<WebPageProxy> pageProxy; - bool shouldForwardNextKeyEvent; - GtkClickCounter clickCounter; - CString tooltipText; - IntRect tooltipArea; - GtkDragAndDropHelper dragAndDropHelper; - DragIcon dragIcon; - IntSize resizerSize; - GRefPtr<AtkObject> accessible; - bool needsResizeOnMap; - GtkWidget* authenticationDialog; - GtkWidget* inspectorView; - unsigned inspectorViewHeight; - GOwnPtr<GdkEvent> contextMenuEvent; - WebContextMenuProxyGtk* activeContextMenuProxy; - WebViewBaseInputMethodFilter inputMethodFilter; - - GtkWindow* toplevelOnScreenWindow; - unsigned long toplevelResizeGripVisibilityID; - unsigned long toplevelFocusInEventID; - unsigned long toplevelFocusOutEventID; - - // View State. - bool isInWindowActive : 1; - bool isFocused : 1; - bool isVisible : 1; - - WebKitWebViewBaseDownloadRequestHandler downloadHandler; - -#if ENABLE(FULLSCREEN_API) - bool fullScreenModeActive; - WebFullScreenClientGtk fullScreenClient; -#endif - -#if USE(TEXTURE_MAPPER_GL) - OwnPtr<RedirectedXCompositeWindow> redirectedWindow; -#endif -}; - -WEBKIT_DEFINE_TYPE(WebKitWebViewBase, webkit_web_view_base, GTK_TYPE_CONTAINER) - -static void webkitWebViewBaseNotifyResizerSize(WebKitWebViewBase* webViewBase) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (!priv->toplevelOnScreenWindow) - return; - - gboolean resizerVisible; - g_object_get(G_OBJECT(priv->toplevelOnScreenWindow), "resize-grip-visible", &resizerVisible, NULL); - - IntSize resizerSize; - if (resizerVisible) { - GdkRectangle resizerRect; - gtk_window_get_resize_grip_area(priv->toplevelOnScreenWindow, &resizerRect); - GdkRectangle allocation; - gtk_widget_get_allocation(GTK_WIDGET(webViewBase), &allocation); - if (gdk_rectangle_intersect(&resizerRect, &allocation, 0)) - resizerSize = IntSize(resizerRect.width, resizerRect.height); - } - - if (resizerSize != priv->resizerSize) { - priv->resizerSize = resizerSize; - priv->pageProxy->setWindowResizerSize(resizerSize); - } -} - -static void toplevelWindowResizeGripVisibilityChanged(GObject*, GParamSpec*, WebKitWebViewBase* webViewBase) -{ - webkitWebViewBaseNotifyResizerSize(webViewBase); -} - -static gboolean toplevelWindowFocusInEvent(GtkWidget* widget, GdkEventFocus*, WebKitWebViewBase* webViewBase) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (!priv->isInWindowActive) { - priv->isInWindowActive = true; - priv->pageProxy->viewStateDidChange(WebPageProxy::ViewWindowIsActive); - } - - return FALSE; -} - -static gboolean toplevelWindowFocusOutEvent(GtkWidget* widget, GdkEventFocus*, WebKitWebViewBase* webViewBase) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (priv->isInWindowActive) { - priv->isInWindowActive = false; - priv->pageProxy->viewStateDidChange(WebPageProxy::ViewWindowIsActive); - } - - return FALSE; -} - -static void webkitWebViewBaseSetToplevelOnScreenWindow(WebKitWebViewBase* webViewBase, GtkWindow* window) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (priv->toplevelOnScreenWindow == window) - return; - - if (priv->toplevelResizeGripVisibilityID) { - g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelResizeGripVisibilityID); - priv->toplevelResizeGripVisibilityID = 0; - } - if (priv->toplevelFocusInEventID) { - g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelFocusInEventID); - priv->toplevelFocusInEventID = 0; - } - if (priv->toplevelFocusOutEventID) { - g_signal_handler_disconnect(priv->toplevelOnScreenWindow, priv->toplevelFocusOutEventID); - priv->toplevelFocusOutEventID = 0; - } - - priv->toplevelOnScreenWindow = window; - priv->pageProxy->viewStateDidChange(WebPageProxy::ViewIsInWindow); - if (!priv->toplevelOnScreenWindow) - return; - - webkitWebViewBaseNotifyResizerSize(webViewBase); - - priv->toplevelResizeGripVisibilityID = - g_signal_connect(priv->toplevelOnScreenWindow, "notify::resize-grip-visible", - G_CALLBACK(toplevelWindowResizeGripVisibilityChanged), webViewBase); - priv->toplevelFocusInEventID = - g_signal_connect(priv->toplevelOnScreenWindow, "focus-in-event", - G_CALLBACK(toplevelWindowFocusInEvent), webViewBase); - priv->toplevelFocusOutEventID = - g_signal_connect(priv->toplevelOnScreenWindow, "focus-out-event", - G_CALLBACK(toplevelWindowFocusOutEvent), webViewBase); -} - -static void webkitWebViewBaseRealize(GtkWidget* widget) -{ - gtk_widget_set_realized(widget, TRUE); - - GtkAllocation allocation; - gtk_widget_get_allocation(widget, &allocation); - - GdkWindowAttr attributes; - attributes.window_type = GDK_WINDOW_CHILD; - attributes.x = allocation.x; - attributes.y = allocation.y; - attributes.width = allocation.width; - attributes.height = allocation.height; - attributes.wclass = GDK_INPUT_OUTPUT; - attributes.visual = gtk_widget_get_visual(widget); - attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK - | GDK_EXPOSURE_MASK - | GDK_BUTTON_PRESS_MASK - | GDK_BUTTON_RELEASE_MASK - | GDK_SCROLL_MASK - | GDK_SMOOTH_SCROLL_MASK - | GDK_POINTER_MOTION_MASK - | GDK_KEY_PRESS_MASK - | GDK_KEY_RELEASE_MASK - | GDK_BUTTON_MOTION_MASK - | GDK_BUTTON1_MOTION_MASK - | GDK_BUTTON2_MOTION_MASK - | GDK_BUTTON3_MOTION_MASK; - - gint attributesMask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL; - - GdkWindow* window = gdk_window_new(gtk_widget_get_parent_window(widget), &attributes, attributesMask); - gtk_widget_set_window(widget, window); - gdk_window_set_user_data(window, widget); - - gtk_style_context_set_background(gtk_widget_get_style_context(widget), window); - - WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(widget); - GtkWidget* toplevel = gtk_widget_get_toplevel(widget); - if (widgetIsOnscreenToplevelWindow(toplevel)) - webkitWebViewBaseSetToplevelOnScreenWindow(webView, GTK_WINDOW(toplevel)); -} - -static bool webkitWebViewChildIsInternalWidget(WebKitWebViewBase* webViewBase, GtkWidget* widget) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - return widget == priv->inspectorView || widget == priv->authenticationDialog; -} - -static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget) -{ - WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container); - WebKitWebViewBasePrivate* priv = webView->priv; - - // Internal widgets like the web inspector and authentication dialog have custom - // allocations so we don't need to add them to our list of children. - if (!webkitWebViewChildIsInternalWidget(webView, widget)) { - GtkAllocation childAllocation; - gtk_widget_get_allocation(widget, &childAllocation); - priv->children.set(widget, childAllocation); - } - - gtk_widget_set_parent(widget, GTK_WIDGET(container)); -} - -void webkitWebViewBaseAddAuthenticationDialog(WebKitWebViewBase* webViewBase, GtkWidget* dialog) -{ - 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) - gtk_widget_destroy(priv->authenticationDialog); -} - -void webkitWebViewBaseAddWebInspector(WebKitWebViewBase* webViewBase, GtkWidget* inspector) -{ - webViewBase->priv->inspectorView = inspector; - gtk_container_add(GTK_CONTAINER(webViewBase), inspector); -} - -static void webkitWebViewBaseContainerRemove(GtkContainer* container, GtkWidget* widget) -{ - WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container); - WebKitWebViewBasePrivate* priv = webView->priv; - GtkWidget* widgetContainer = GTK_WIDGET(container); - - gboolean wasVisible = gtk_widget_get_visible(widget); - gtk_widget_unparent(widget); - - if (priv->inspectorView == widget) { - priv->inspectorView = 0; - priv->inspectorViewHeight = 0; - } else if (priv->authenticationDialog == widget) { - priv->authenticationDialog = 0; - } else { - ASSERT(priv->children.contains(widget)); - priv->children.remove(widget); - } - if (wasVisible && gtk_widget_get_visible(widgetContainer)) - gtk_widget_queue_resize(widgetContainer); -} - -static void webkitWebViewBaseContainerForall(GtkContainer* container, gboolean includeInternals, GtkCallback callback, gpointer callbackData) -{ - WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container); - WebKitWebViewBasePrivate* priv = webView->priv; - - WebKitWebViewChildrenMap children = priv->children; - WebKitWebViewChildrenMap::const_iterator end = children.end(); - for (WebKitWebViewChildrenMap::const_iterator current = children.begin(); current != end; ++current) - (*callback)(current->key, callbackData); - - if (includeInternals && priv->inspectorView) - (*callback)(priv->inspectorView, callbackData); - - if (includeInternals && priv->authenticationDialog) - (*callback)(priv->authenticationDialog, callbackData); -} - -void webkitWebViewBaseChildMoveResize(WebKitWebViewBase* webView, GtkWidget* child, const IntRect& childRect) -{ - const IntRect& geometry = webView->priv->children.get(child); - if (geometry == childRect) - return; - - webView->priv->children.set(child, childRect); - gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webView)); -} - -static void webkitWebViewBaseDispose(GObject* gobject) -{ - webkitWebViewBaseSetToplevelOnScreenWindow(WEBKIT_WEB_VIEW_BASE(gobject), 0); - G_OBJECT_CLASS(webkit_web_view_base_parent_class)->dispose(gobject); -} - -static void webkitWebViewBaseConstructed(GObject* object) -{ - G_OBJECT_CLASS(webkit_web_view_base_parent_class)->constructed(object); - - GtkWidget* viewWidget = GTK_WIDGET(object); - gtk_widget_set_can_focus(viewWidget, TRUE); - gtk_drag_dest_set(viewWidget, static_cast<GtkDestDefaults>(0), 0, 0, - static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK | GDK_ACTION_PRIVATE)); - gtk_drag_dest_set_target_list(viewWidget, PasteboardHelper::defaultPasteboardHelper()->targetList()); - - WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(object)->priv; - priv->pageClient = PageClientImpl::create(viewWidget); - priv->dragAndDropHelper.setWidget(viewWidget); - -#if USE(TEXTURE_MAPPER_GL) - if (priv->redirectedWindow) - priv->redirectedWindow->setDamageNotifyCallback(redirectedWindowDamagedCallback, object); -#endif - - priv->authenticationDialog = 0; -} - -#if USE(TEXTURE_MAPPER_GL) -static bool webkitWebViewRenderAcceleratedCompositingResults(WebKitWebViewBase* webViewBase, DrawingAreaProxyImpl* drawingArea, cairo_t* cr, GdkRectangle* clipRect) -{ - if (!drawingArea->isInAcceleratedCompositingMode()) - return false; - - // To avoid flashes when initializing accelerated compositing for the first - // time, we wait until we know there's a frame ready before rendering. - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (!priv->redirectedWindow) - return false; - - cairo_rectangle(cr, clipRect->x, clipRect->y, clipRect->width, clipRect->height); - cairo_surface_t* surface = priv->redirectedWindow->cairoSurfaceForWidget(GTK_WIDGET(webViewBase)); - cairo_set_source_surface(cr, surface, 0, 0); - cairo_fill(cr); - return true; -} -#endif - -static gboolean webkitWebViewBaseDraw(GtkWidget* widget, cairo_t* cr) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(webViewBase->priv->pageProxy->drawingArea()); - if (!drawingArea) - return FALSE; - - GdkRectangle clipRect; - if (!gdk_cairo_get_clip_rectangle(cr, &clipRect)) - return FALSE; - -#if USE(TEXTURE_MAPPER_GL) - if (webkitWebViewRenderAcceleratedCompositingResults(webViewBase, drawingArea, cr, &clipRect)) - return FALSE; -#endif - - WebCore::Region unpaintedRegion; // This is simply unused. - drawingArea->paint(cr, clipRect, unpaintedRegion); - - if (webViewBase->priv->authenticationDialog) { - cairo_set_operator(cr, CAIRO_OPERATOR_OVER); - cairo_set_source_rgba(cr, 0, 0, 0, 0.5); - cairo_paint(cr); - } - - GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->draw(widget, cr); - - return FALSE; -} - -static void webkitWebViewBaseChildAllocate(GtkWidget* child, gpointer userData) -{ - if (!gtk_widget_get_visible(child)) - return; - - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(userData); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - const IntRect& geometry = priv->children.get(child); - if (geometry.isEmpty()) - return; - - GtkAllocation childAllocation = geometry; - gtk_widget_size_allocate(child, &childAllocation); - priv->children.set(child, IntRect()); -} - -static void resizeWebKitWebViewBaseFromAllocation(WebKitWebViewBase* webViewBase, GtkAllocation* allocation, bool sizeChanged) -{ - gtk_container_foreach(GTK_CONTAINER(webViewBase), webkitWebViewBaseChildAllocate, 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 - inspectorViewHeight; - childAllocation.height = inspectorViewHeight; - gtk_widget_size_allocate(priv->inspectorView, &childAllocation); - - viewRect.setHeight(std::max(allocation->height - inspectorViewHeight, 1)); - } - - // The authentication dialog is centered in the view rect, which means that it - // never overlaps the web inspector. Thus, we need to calculate the allocation here - // after calculating the inspector allocation. - if (priv->authenticationDialog) { - GtkRequisition naturalSize; - gtk_widget_get_preferred_size(priv->authenticationDialog, 0, &naturalSize); - - GtkAllocation childAllocation = { - (viewRect.width() - naturalSize.width) / 2, - (viewRect.height() - naturalSize.height) / 2, - naturalSize.width, - naturalSize.height - }; - gtk_widget_size_allocate(priv->authenticationDialog, &childAllocation); - } - -#if USE(TEXTURE_MAPPER_GL) - if (sizeChanged && webViewBase->priv->redirectedWindow) - webViewBase->priv->redirectedWindow->resize(viewRect.size()); -#endif - - if (priv->pageProxy->drawingArea()) - priv->pageProxy->drawingArea()->setSize(viewRect.size(), IntSize(), IntSize()); - - webkitWebViewBaseNotifyResizerSize(webViewBase); -} - -static void webkitWebViewBaseSizeAllocate(GtkWidget* widget, GtkAllocation* allocation) -{ - bool sizeChanged = gtk_widget_get_allocated_width(widget) != allocation->width - || gtk_widget_get_allocated_height(widget) != allocation->height; - - 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->needsResizeOnMap = true; - return; - } - - resizeWebKitWebViewBaseFromAllocation(webViewBase, allocation, sizeChanged); -} - -static void webkitWebViewBaseMap(GtkWidget* widget) -{ - GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->map(widget); - - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (!priv->isVisible) { - priv->isVisible = true; - priv->pageProxy->viewStateDidChange(WebPageProxy::ViewIsVisible); - } - - if (!priv->needsResizeOnMap) - return; - - GtkAllocation allocation; - gtk_widget_get_allocation(widget, &allocation); - resizeWebKitWebViewBaseFromAllocation(webViewBase, &allocation, true /* sizeChanged */); - priv->needsResizeOnMap = false; -} - -static void webkitWebViewBaseUnmap(GtkWidget* widget) -{ - GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->unmap(widget); - - WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv; - if (priv->isVisible) { - priv->isVisible = false; - priv->pageProxy->viewStateDidChange(WebPageProxy::ViewIsVisible); - } -} - -static gboolean webkitWebViewBaseFocusInEvent(GtkWidget* widget, GdkEventFocus* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - webkitWebViewBaseSetFocus(webViewBase, true); - webViewBase->priv->inputMethodFilter.notifyFocusedIn(); - - return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus_in_event(widget, event); -} - -static gboolean webkitWebViewBaseFocusOutEvent(GtkWidget* widget, GdkEventFocus* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - webkitWebViewBaseSetFocus(webViewBase, false); - webViewBase->priv->inputMethodFilter.notifyFocusedOut(); - - return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->focus_out_event(widget, event); -} - -static gboolean webkitWebViewBaseKeyPressEvent(GtkWidget* widget, GdkEventKey* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - if (priv->authenticationDialog) - return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_press_event(widget, event); - -#if ENABLE(FULLSCREEN_API) - if (priv->fullScreenModeActive) { - switch (event->keyval) { - case GDK_KEY_Escape: - case GDK_KEY_f: - case GDK_KEY_F: - webkitWebViewBaseExitFullScreen(webViewBase); - return TRUE; - default: - break; - } - } -#endif - - // Since WebProcess key event handling is not synchronous, handle the event in two passes. - // When WebProcess processes the input event, it will call PageClientImpl::doneWithKeyEvent - // with event handled status which determines whether to pass the input event to parent or not - // using gtk_main_do_event(). - if (priv->shouldForwardNextKeyEvent) { - priv->shouldForwardNextKeyEvent = FALSE; - return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_press_event(widget, event); - } - priv->inputMethodFilter.filterKeyEvent(event); - return TRUE; -} - -static gboolean webkitWebViewBaseKeyReleaseEvent(GtkWidget* widget, GdkEventKey* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - if (priv->shouldForwardNextKeyEvent) { - priv->shouldForwardNextKeyEvent = FALSE; - return GTK_WIDGET_CLASS(webkit_web_view_base_parent_class)->key_release_event(widget, event); - } - priv->inputMethodFilter.filterKeyEvent(event); - return TRUE; -} - -static gboolean webkitWebViewBaseButtonPressEvent(GtkWidget* widget, GdkEventButton* buttonEvent) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - if (priv->authenticationDialog) - return TRUE; - - gtk_widget_grab_focus(widget); - - priv->inputMethodFilter.notifyMouseButtonPress(); - - if (!priv->clickCounter.shouldProcessButtonEvent(buttonEvent)) - return TRUE; - - // If it's a right click event save it as a possible context menu event. - if (buttonEvent->button == 3) - priv->contextMenuEvent.set(gdk_event_copy(reinterpret_cast<GdkEvent*>(buttonEvent))); - priv->pageProxy->handleMouseEvent(NativeWebMouseEvent(reinterpret_cast<GdkEvent*>(buttonEvent), - priv->clickCounter.clickCountForGdkButtonEvent(widget, buttonEvent))); - return TRUE; -} - -static gboolean webkitWebViewBaseButtonReleaseEvent(GtkWidget* widget, GdkEventButton* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - if (priv->authenticationDialog) - return TRUE; - - gtk_widget_grab_focus(widget); - priv->pageProxy->handleMouseEvent(NativeWebMouseEvent(reinterpret_cast<GdkEvent*>(event), 0 /* currentClickCount */)); - - return TRUE; -} - -static gboolean webkitWebViewBaseScrollEvent(GtkWidget* widget, GdkEventScroll* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - if (priv->authenticationDialog) - return TRUE; - - priv->pageProxy->handleWheelEvent(NativeWebWheelEvent(reinterpret_cast<GdkEvent*>(event))); - - return TRUE; -} - -static gboolean webkitWebViewBaseMotionNotifyEvent(GtkWidget* widget, GdkEventMotion* event) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - if (priv->authenticationDialog) - return TRUE; - - priv->pageProxy->handleMouseEvent(NativeWebMouseEvent(reinterpret_cast<GdkEvent*>(event), 0 /* currentClickCount */)); - - return TRUE; -} - -static gboolean webkitWebViewBaseQueryTooltip(GtkWidget* widget, gint x, gint y, gboolean keyboardMode, GtkTooltip* tooltip) -{ - WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv; - - if (keyboardMode) { - // TODO: https://bugs.webkit.org/show_bug.cgi?id=61732. - notImplemented(); - return FALSE; - } - - if (priv->tooltipText.length() <= 0) - return FALSE; - - if (!priv->tooltipArea.isEmpty()) { - GdkRectangle area = priv->tooltipArea; - gtk_tooltip_set_tip_area(tooltip, &area); - } else - gtk_tooltip_set_tip_area(tooltip, 0); - gtk_tooltip_set_text(tooltip, priv->tooltipText.data()); - - return TRUE; -} - -static void webkitWebViewBaseDragDataGet(GtkWidget* widget, GdkDragContext* context, GtkSelectionData* selectionData, guint info, guint time) -{ - WEBKIT_WEB_VIEW_BASE(widget)->priv->dragAndDropHelper.handleGetDragData(context, selectionData, info); -} - -static void webkitWebViewBaseDragEnd(GtkWidget* widget, GdkDragContext* context) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - if (!webViewBase->priv->dragAndDropHelper.handleDragEnd(context)) - return; - - GdkDevice* device = gdk_drag_context_get_device(context); - int x = 0, y = 0; - gdk_device_get_window_at_position(device, &x, &y); - int xRoot = 0, yRoot = 0; - gdk_device_get_position(device, 0, &xRoot, &yRoot); - webViewBase->priv->pageProxy->dragEnded(IntPoint(x, y), IntPoint(xRoot, yRoot), - gdkDragActionToDragOperation(gdk_drag_context_get_selected_action(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); - 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); - DragOperation operation = webViewBase->priv->pageProxy->dragSession().operation; - gdk_drag_status(context, dragOperationToSingleGdkDragAction(operation), time); -} - -static AtkObject* webkitWebViewBaseGetAccessible(GtkWidget* widget) -{ - // If the socket has already been created and embedded a plug ID, return it. - WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv; - if (priv->accessible && atk_socket_is_occupied(ATK_SOCKET(priv->accessible.get()))) - return priv->accessible.get(); - - // Create the accessible object and associate it to the widget. - if (!priv->accessible) { - priv->accessible = adoptGRef(ATK_OBJECT(webkitWebViewBaseAccessibleNew(widget))); - - // Set the parent not to break bottom-up navigation. - GtkWidget* parentWidget = gtk_widget_get_parent(widget); - AtkObject* axParent = parentWidget ? gtk_widget_get_accessible(parentWidget) : 0; - if (axParent) - atk_object_set_parent(priv->accessible.get(), axParent); - } - - // Try to embed the plug in the socket, if posssible. - String plugID = priv->pageProxy->accessibilityPlugID(); - if (plugID.isNull()) - return priv->accessible.get(); - - atk_socket_embed(ATK_SOCKET(priv->accessible.get()), const_cast<gchar*>(plugID.utf8().data())); - - return priv->accessible.get(); -} - -static gboolean webkitWebViewBaseDragMotion(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - IntPoint position(x, y); - DataObjectGtk* dataObject = webViewBase->priv->dragAndDropHelper.handleDragMotion(context, position, time); - if (!dataObject) - return TRUE; - - 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; -} - -static void dragExitedCallback(GtkWidget* widget, DragData* dragData, bool dropHappened) -{ - // Don't call dragExited if we have just received a drag-drop signal. This - // happens in the case of a successful drop onto the view. - if (dropHappened) - return; - - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - webViewBase->priv->pageProxy->dragExited(dragData); - webViewBase->priv->pageProxy->resetDragOperation(); -} - -static void webkitWebViewBaseDragLeave(GtkWidget* widget, GdkDragContext* context, guint time) -{ - WEBKIT_WEB_VIEW_BASE(widget)->priv->dragAndDropHelper.handleDragLeave(context, dragExitedCallback); -} - -static gboolean webkitWebViewBaseDragDrop(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time) -{ - WebKitWebViewBase* webViewBase = WEBKIT_WEB_VIEW_BASE(widget); - 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, String(), handle, sandboxExtensionForUpload); - gtk_drag_finish(context, TRUE, FALSE, time); - return TRUE; -} - -static void webkitWebViewBaseParentSet(GtkWidget* widget, GtkWidget* oldParent) -{ - if (!gtk_widget_get_parent(widget)) - webkitWebViewBaseSetToplevelOnScreenWindow(WEBKIT_WEB_VIEW_BASE(widget), 0); -} - -static gboolean webkitWebViewBaseFocus(GtkWidget* widget, GtkDirectionType direction) -{ - // If the authentication dialog is active, we need to forward focus events there. This - // ensures that you can tab between elements in the box. - WebKitWebViewBasePrivate* priv = WEBKIT_WEB_VIEW_BASE(widget)->priv; - if (priv->authenticationDialog) { - gboolean 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); - widgetClass->realize = webkitWebViewBaseRealize; - widgetClass->draw = webkitWebViewBaseDraw; - widgetClass->size_allocate = webkitWebViewBaseSizeAllocate; - widgetClass->map = webkitWebViewBaseMap; - widgetClass->unmap = webkitWebViewBaseUnmap; - widgetClass->focus = webkitWebViewBaseFocus; - widgetClass->focus_in_event = webkitWebViewBaseFocusInEvent; - widgetClass->focus_out_event = webkitWebViewBaseFocusOutEvent; - widgetClass->key_press_event = webkitWebViewBaseKeyPressEvent; - widgetClass->key_release_event = webkitWebViewBaseKeyReleaseEvent; - widgetClass->button_press_event = webkitWebViewBaseButtonPressEvent; - widgetClass->button_release_event = webkitWebViewBaseButtonReleaseEvent; - widgetClass->scroll_event = webkitWebViewBaseScrollEvent; - widgetClass->motion_notify_event = webkitWebViewBaseMotionNotifyEvent; - widgetClass->query_tooltip = webkitWebViewBaseQueryTooltip; - widgetClass->drag_end = webkitWebViewBaseDragEnd; - widgetClass->drag_data_get = webkitWebViewBaseDragDataGet; - widgetClass->drag_motion = webkitWebViewBaseDragMotion; - widgetClass->drag_leave = webkitWebViewBaseDragLeave; - widgetClass->drag_drop = webkitWebViewBaseDragDrop; - 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; - gobjectClass->dispose = webkitWebViewBaseDispose; - - GtkContainerClass* containerClass = GTK_CONTAINER_CLASS(webkitWebViewBaseClass); - containerClass->add = webkitWebViewBaseContainerAdd; - containerClass->remove = webkitWebViewBaseContainerRemove; - containerClass->forall = webkitWebViewBaseContainerForall; -} - -WebKitWebViewBase* webkitWebViewBaseCreate(WebContext* context, WebPageGroup* pageGroup) -{ - WebKitWebViewBase* webkitWebViewBase = WEBKIT_WEB_VIEW_BASE(g_object_new(WEBKIT_TYPE_WEB_VIEW_BASE, NULL)); - webkitWebViewBaseCreateWebPage(webkitWebViewBase, context, pageGroup); - return webkitWebViewBase; -} - -GtkIMContext* webkitWebViewBaseGetIMContext(WebKitWebViewBase* webkitWebViewBase) -{ - return webkitWebViewBase->priv->inputMethodFilter.context(); -} - -WebPageProxy* webkitWebViewBaseGetPage(WebKitWebViewBase* webkitWebViewBase) -{ - return webkitWebViewBase->priv->pageProxy.get(); -} - -void webkitWebViewBaseCreateWebPage(WebKitWebViewBase* webkitWebViewBase, WebContext* context, WebPageGroup* pageGroup) -{ - WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv; - - priv->pageProxy = context->createWebPage(priv->pageClient.get(), pageGroup); - priv->pageProxy->initializeWebPage(); - -#if ENABLE(FULLSCREEN_API) - priv->pageProxy->fullScreenManager()->setWebView(webkitWebViewBase); -#endif - -#if USE(TEXTURE_MAPPER_GL) - 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) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (tooltip && tooltip[0] != '\0') { - priv->tooltipText = tooltip; - gtk_widget_set_has_tooltip(GTK_WIDGET(webViewBase), TRUE); - } else { - priv->tooltipText = ""; - gtk_widget_set_has_tooltip(GTK_WIDGET(webViewBase), FALSE); - } - - gtk_widget_trigger_tooltip_query(GTK_WIDGET(webViewBase)); -} - -void webkitWebViewBaseSetTooltipArea(WebKitWebViewBase* webViewBase, const IntRect& tooltipArea) -{ - webViewBase->priv->tooltipArea = tooltipArea; -} - -void webkitWebViewBaseStartDrag(WebKitWebViewBase* webViewBase, const DragData& dragData, PassRefPtr<ShareableBitmap> dragImage) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - - RefPtr<DataObjectGtk> dataObject = adoptRef(dragData.platformData()); - GRefPtr<GtkTargetList> targetList = adoptGRef(PasteboardHelper::defaultPasteboardHelper()->targetListForDataObject(dataObject.get())); - GOwnPtr<GdkEvent> currentEvent(gtk_get_current_event()); - GdkDragContext* context = gtk_drag_begin(GTK_WIDGET(webViewBase), - targetList.get(), - dragOperationToGdkDragActions(dragData.draggingSourceOperationMask()), - 1, /* button */ - currentEvent.get()); - priv->dragAndDropHelper.startedDrag(context, dataObject.get()); - - - // A drag starting should prevent a double-click from happening. This might - // happen if a drag is followed very quickly by another click (like in the DRT). - priv->clickCounter.reset(); - - if (dragImage) { - RefPtr<cairo_surface_t> image(dragImage->createCairoSurface()); - priv->dragIcon.setImage(image.get()); - priv->dragIcon.useForDrag(context); - } else - gtk_drag_set_icon_default(context); -} - -void webkitWebViewBaseForwardNextKeyEvent(WebKitWebViewBase* webkitWebViewBase) -{ - webkitWebViewBase->priv->shouldForwardNextKeyEvent = TRUE; -} - -void webkitWebViewBaseEnterFullScreen(WebKitWebViewBase* webkitWebViewBase) -{ -#if ENABLE(FULLSCREEN_API) - WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv; - if (priv->fullScreenModeActive) - return; - - if (!priv->fullScreenClient.willEnterFullScreen()) - return; - - WebFullScreenManagerProxy* fullScreenManagerProxy = priv->pageProxy->fullScreenManager(); - fullScreenManagerProxy->willEnterFullScreen(); - - GtkWidget* topLevelWindow = gtk_widget_get_toplevel(GTK_WIDGET(webkitWebViewBase)); - if (gtk_widget_is_toplevel(topLevelWindow)) - gtk_window_fullscreen(GTK_WINDOW(topLevelWindow)); - fullScreenManagerProxy->didEnterFullScreen(); - priv->fullScreenModeActive = true; -#endif -} - -void webkitWebViewBaseExitFullScreen(WebKitWebViewBase* webkitWebViewBase) -{ -#if ENABLE(FULLSCREEN_API) - WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv; - if (!priv->fullScreenModeActive) - return; - - if (!priv->fullScreenClient.willExitFullScreen()) - return; - - WebFullScreenManagerProxy* fullScreenManagerProxy = priv->pageProxy->fullScreenManager(); - fullScreenManagerProxy->willExitFullScreen(); - - GtkWidget* topLevelWindow = gtk_widget_get_toplevel(GTK_WIDGET(webkitWebViewBase)); - if (gtk_widget_is_toplevel(topLevelWindow)) - gtk_window_unfullscreen(GTK_WINDOW(topLevelWindow)); - fullScreenManagerProxy->didExitFullScreen(); - priv->fullScreenModeActive = false; -#endif -} - -void webkitWebViewBaseInitializeFullScreenClient(WebKitWebViewBase* webkitWebViewBase, const WKFullScreenClientGtk* wkClient) -{ - webkitWebViewBase->priv->fullScreenClient.initialize(wkClient); -} - -void webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase* webkitWebViewBase, unsigned height) -{ - if (webkitWebViewBase->priv->inspectorViewHeight == height) - return; - webkitWebViewBase->priv->inspectorViewHeight = height; - if (webkitWebViewBase->priv->inspectorView) - gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase)); -} - -void webkitWebViewBaseSetActiveContextMenuProxy(WebKitWebViewBase* webkitWebViewBase, WebContextMenuProxyGtk* contextMenuProxy) -{ - webkitWebViewBase->priv->activeContextMenuProxy = contextMenuProxy; -} - -WebContextMenuProxyGtk* webkitWebViewBaseGetActiveContextMenuProxy(WebKitWebViewBase* webkitWebViewBase) -{ - return webkitWebViewBase->priv->activeContextMenuProxy; -} - -GdkEvent* webkitWebViewBaseTakeContextMenuEvent(WebKitWebViewBase* webkitWebViewBase) -{ - return webkitWebViewBase->priv->contextMenuEvent.release(); -} - -#if USE(TEXTURE_MAPPER_GL) -void redirectedWindowDamagedCallback(void* data) -{ - gtk_widget_queue_draw(GTK_WIDGET(data)); -} -#endif - -void webkitWebViewBaseSetFocus(WebKitWebViewBase* webViewBase, bool focused) -{ - WebKitWebViewBasePrivate* priv = webViewBase->priv; - if (priv->isFocused == focused) - return; - - unsigned viewStateFlags = WebPageProxy::ViewIsFocused; - priv->isFocused = focused; - - // If the view has received the focus and the window is not active - // mark the current window as active now. This can happen if the - // toplevel window is a GTK_WINDOW_POPUP and the focus has been - // set programatically like WebKitTestRunner does, because POPUP - // can't be focused. - if (priv->isFocused && !priv->isInWindowActive) { - priv->isInWindowActive = true; - viewStateFlags |= WebPageProxy::ViewWindowIsActive; - } - priv->pageProxy->viewStateDidChange(viewStateFlags); -} - -bool webkitWebViewBaseIsInWindowActive(WebKitWebViewBase* webViewBase) -{ - return webViewBase->priv->isInWindowActive; -} - -bool webkitWebViewBaseIsFocused(WebKitWebViewBase* webViewBase) -{ - return webViewBase->priv->isFocused; -} - -bool webkitWebViewBaseIsVisible(WebKitWebViewBase* webViewBase) -{ - return webViewBase->priv->isVisible; -} - -bool webkitWebViewBaseIsInWindow(WebKitWebViewBase* webViewBase) -{ - return webViewBase->priv->toplevelOnScreenWindow; -} - -void webkitWebViewBaseSetDownloadRequestHandler(WebKitWebViewBase* webViewBase, WebKitWebViewBaseDownloadRequestHandler downloadHandler) -{ - webViewBase->priv->downloadHandler = downloadHandler; -} - -void webkitWebViewBaseHandleDownloadRequest(WebKitWebViewBase* webViewBase, DownloadProxy* download) -{ - 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 deleted file mode 100644 index f24457f57..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBase.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 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 WebKitWebViewBase_h -#define WebKitWebViewBase_h - -#include <gtk/gtk.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WEB_VIEW_BASE (webkit_web_view_base_get_type()) -#define WEBKIT_WEB_VIEW_BASE(object) (G_TYPE_CHECK_INSTANCE_CAST((object), WEBKIT_TYPE_WEB_VIEW_BASE, WebKitWebViewBase)) -#define WEBKIT_WEB_VIEW_BASE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_VIEW_BASE, WebKitWebViewBaseClass)) -#define WEBKIT_IS_WEB_VIEW_BASE(object) (G_TYPE_CHECK_INSTANCE_TYPE((object), WEBKIT_TYPE_WEB_VIEW_BASE)) -#define WEBKIT_IS_WEB_VIEW_BASE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_VIEW_BASE)) -#define WEBKIT_WEB_VIEW_BASE_GET_CLASS(object) (G_TYPE_INSTANCE_GET_CLASS((object), WEBKIT_TYPE_WEB_VIEW_BASE, WebKitWebViewBaseClass)) - -typedef struct _WebKitWebViewBase WebKitWebViewBase; -typedef struct _WebKitWebViewBaseClass WebKitWebViewBaseClass; -typedef struct _WebKitWebViewBasePrivate WebKitWebViewBasePrivate; - -struct _WebKitWebViewBase { - GtkContainer parentInstance; - /*< private >*/ - WebKitWebViewBasePrivate* priv; -}; - -struct _WebKitWebViewBaseClass { - GtkContainerClass parentClass; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_web_view_base_get_type (void); - -G_END_DECLS - -#endif // WebKitWebViewBase_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBaseAccessible.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBaseAccessible.cpp deleted file mode 100644 index 7b069dd94..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBaseAccessible.cpp +++ /dev/null @@ -1,107 +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 "WebKitWebViewBaseAccessible.h" - -#include "WebKitPrivate.h" -#include <gtk/gtk.h> - -struct _WebKitWebViewBaseAccessiblePrivate { - GtkWidget* widget; -}; - -WEBKIT_DEFINE_TYPE(WebKitWebViewBaseAccessible, webkit_web_view_base_accessible, ATK_TYPE_SOCKET) - -static void webkitWebViewBaseAccessibleWidgetDestroyed(GtkWidget* widget, WebKitWebViewBaseAccessible* accessible) -{ - accessible->priv->widget = 0; - atk_object_notify_state_change(ATK_OBJECT(accessible), ATK_STATE_DEFUNCT, TRUE); -} - -static void webkitWebViewBaseAccessibleInitialize(AtkObject* atkObject, gpointer data) -{ - if (ATK_OBJECT_CLASS(webkit_web_view_base_accessible_parent_class)->initialize) - ATK_OBJECT_CLASS(webkit_web_view_base_accessible_parent_class)->initialize(atkObject, data); - - if (data && GTK_IS_WIDGET(data)) { - WebKitWebViewBaseAccessible* accessible = WEBKIT_WEB_VIEW_BASE_ACCESSIBLE(atkObject); - accessible->priv->widget = GTK_WIDGET(data); - - g_signal_connect_after(accessible->priv->widget, "destroy", - G_CALLBACK(webkitWebViewBaseAccessibleWidgetDestroyed), atkObject); - } - - atk_object_set_role(atkObject, ATK_ROLE_FILLER); -} - -static AtkStateSet* webkitWebViewBaseAccessibleRefStateSet(AtkObject* atkObject) -{ - WebKitWebViewBaseAccessible* accessible = WEBKIT_WEB_VIEW_BASE_ACCESSIBLE(atkObject); - - AtkStateSet* stateSet; - if (accessible->priv->widget) { - // Use the implementation of AtkSocket if the widget is still alive. - stateSet = ATK_OBJECT_CLASS(webkit_web_view_base_accessible_parent_class)->ref_state_set(atkObject); - } else { - // If the widget is no longer alive, save some remote calls - // (because of AtkSocket's implementation of ref_state_set()) - // and just return that this AtkObject is defunct. - stateSet = atk_state_set_new(); - atk_state_set_add_state(stateSet, ATK_STATE_DEFUNCT); - } - - return stateSet; -} - -static gint webkitWebViewBaseAccessibleGetIndexInParent(AtkObject* atkObject) -{ - AtkObject* atkParent = atk_object_get_parent(atkObject); - if (!atkParent) - return -1; - - guint count = atk_object_get_n_accessible_children(atkParent); - for (guint i = 0; i < count; ++i) { - AtkObject* child = atk_object_ref_accessible_child(atkParent, i); - bool childIsObject = child == atkObject; - g_object_unref(child); - if (childIsObject) - return i; - } - - return -1; -} - -static void webkit_web_view_base_accessible_class_init(WebKitWebViewBaseAccessibleClass* klass) -{ - // No need to implement get_n_children() and ref_child() here - // since this is a subclass of AtkSocket and all the logic related - // to those functions will be implemented by the ATK bridge. - AtkObjectClass* atkObjectClass = ATK_OBJECT_CLASS(klass); - atkObjectClass->initialize = webkitWebViewBaseAccessibleInitialize; - atkObjectClass->ref_state_set = webkitWebViewBaseAccessibleRefStateSet; - atkObjectClass->get_index_in_parent = webkitWebViewBaseAccessibleGetIndexInParent; -} - -WebKitWebViewBaseAccessible* webkitWebViewBaseAccessibleNew(GtkWidget* widget) -{ - AtkObject* object = ATK_OBJECT(g_object_new(WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE, NULL)); - atk_object_initialize(object, widget); - return WEBKIT_WEB_VIEW_BASE_ACCESSIBLE(object); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBaseAccessible.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBaseAccessible.h deleted file mode 100644 index 3e932c3cd..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBaseAccessible.h +++ /dev/null @@ -1,55 +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. - */ - -#ifndef WebKitWebViewBaseAccessible_h -#define WebKitWebViewBaseAccessible_h - -#include <atk/atk.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE (webkit_web_view_base_accessible_get_type()) -#define WEBKIT_WEB_VIEW_BASE_ACCESSIBLE(object) (G_TYPE_CHECK_INSTANCE_CAST((object), WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE, WebKitWebViewBaseAccessible)) -#define WEBKIT_WEB_VIEW_BASE_ACCESSIBLE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE, WebKitWebViewBaseAccessibleClass)) -#define WEBKIT_IS_WEB_VIEW_BASE_ACCESSIBLE(object) (G_TYPE_CHECK_INSTANCE_TYPE((object), WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE)) -#define WEBKIT_IS_WEB_VIEW_BASE_ACCESSIBLE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE)) -#define WEBKIT_WEB_VIEW_BASE_ACCESSIBLE_GET_CLASS(object) (G_TYPE_INSTANCE_GET_CLASS((object), WEBKIT_TYPE_WEB_VIEW_BASE_ACCESSIBLE, WebKitWebViewBaseAccessibleClass)) - -typedef struct _WebKitWebViewBaseAccessible WebKitWebViewBaseAccessible; -typedef struct _WebKitWebViewBaseAccessibleClass WebKitWebViewBaseAccessibleClass; -typedef struct _WebKitWebViewBaseAccessiblePrivate WebKitWebViewBaseAccessiblePrivate; - - -struct _WebKitWebViewBaseAccessible { - AtkSocket parent; - /*< private >*/ - WebKitWebViewBaseAccessiblePrivate* priv; -}; - -struct _WebKitWebViewBaseAccessibleClass { - AtkSocketClass parentClass; -}; - -GType webkit_web_view_base_accessible_get_type(); - -WebKitWebViewBaseAccessible* webkitWebViewBaseAccessibleNew(GtkWidget*); - -G_END_DECLS - -#endif // WebKitWebViewBaseAccessible_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h deleted file mode 100644 index e30fd949e..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewBasePrivate.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011 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. - */ - -#ifndef WebKitWebViewBasePrivate_h -#define WebKitWebViewBasePrivate_h - -#include "WebContextMenuProxyGtk.h" -#include "WebKitPrivate.h" -#include "WebKitWebViewBase.h" -#include "WebPageProxy.h" - -WebKitWebViewBase* webkitWebViewBaseCreate(WebKit::WebContext*, WebKit::WebPageGroup*); -GtkIMContext* webkitWebViewBaseGetIMContext(WebKitWebViewBase*); -WebKit::WebPageProxy* webkitWebViewBaseGetPage(WebKitWebViewBase*); -void webkitWebViewBaseCreateWebPage(WebKitWebViewBase*, WebKit::WebContext*, WebKit::WebPageGroup*); -void webkitWebViewBaseSetTooltipText(WebKitWebViewBase*, const char*); -void webkitWebViewBaseSetTooltipArea(WebKitWebViewBase*, const WebCore::IntRect&); -void webkitWebViewBaseForwardNextKeyEvent(WebKitWebViewBase*); -void webkitWebViewBaseStartDrag(WebKitWebViewBase*, const WebCore::DragData&, PassRefPtr<WebKit::ShareableBitmap> dragImage); -void webkitWebViewBaseChildMoveResize(WebKitWebViewBase*, GtkWidget*, const WebCore::IntRect&); -void webkitWebViewBaseEnterFullScreen(WebKitWebViewBase*); -void webkitWebViewBaseExitFullScreen(WebKitWebViewBase*); -void webkitWebViewBaseInitializeFullScreenClient(WebKitWebViewBase*, const WKFullScreenClientGtk*); -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*); -#endif - -void webkitWebViewBaseSetFocus(WebKitWebViewBase*, bool focused); -bool webkitWebViewBaseIsInWindowActive(WebKitWebViewBase*); -bool webkitWebViewBaseIsFocused(WebKitWebViewBase*); -bool webkitWebViewBaseIsVisible(WebKitWebViewBase*); -bool webkitWebViewBaseIsInWindow(WebKitWebViewBase*); - -typedef void (*WebKitWebViewBaseDownloadRequestHandler) (WebKitWebViewBase*, WebKit::DownloadProxy*); -void webkitWebViewBaseSetDownloadRequestHandler(WebKitWebViewBase*, WebKitWebViewBaseDownloadRequestHandler); -void webkitWebViewBaseHandleDownloadRequest(WebKitWebViewBase*, WebKit::DownloadProxy*); - -void webkitWebViewBaseAddAuthenticationDialog(WebKitWebViewBase*, GtkWidget* authDialog); -void webkitWebViewBaseCancelAuthenticationDialog(WebKitWebViewBase*); -void webkitWebViewBaseAddWebInspector(WebKitWebViewBase*, GtkWidget* inspector); - -#endif // WebKitWebViewBasePrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.cpp deleted file mode 100644 index 998c5c0c1..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* - * 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 deleted file mode 100644 index 685f19904..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroup.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * 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 deleted file mode 100644 index 5fd865610..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewGroupPrivate.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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 deleted file mode 100644 index eb1f27db2..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWebViewPrivate.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, 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 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*); -WebKit::WebPageProxy* webkitWebViewCreateNewPage(WebKitWebView*, WebKit::ImmutableDictionary* windowFeatures); -void webkitWebViewReadyToShowPage(WebKitWebView*); -void webkitWebViewRunAsModal(WebKitWebView*); -void webkitWebViewClosePage(WebKitWebView*); -void webkitWebViewRunJavaScriptAlert(WebKitWebView*, const CString& message); -bool webkitWebViewRunJavaScriptConfirm(WebKitWebView*, const CString& message); -CString webkitWebViewRunJavaScriptPrompt(WebKitWebView*, const CString& message, const CString& defaultText); -void webkitWebViewMakePermissionRequest(WebKitWebView*, WebKitPermissionRequest*); -void webkitWebViewMakePolicyDecision(WebKitWebView*, WebKitPolicyDecisionType, WebKitPolicyDecision*); -void webkitWebViewMouseTargetChanged(WebKitWebView*, WebKit::WebHitTestResult*, unsigned modifiers); -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); -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.cpp b/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.cpp deleted file mode 100644 index bdfc72589..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.cpp +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitWindowProperties.h" - -#include "ImmutableDictionary.h" -#include "WebKitPrivate.h" -#include "WebKitWindowPropertiesPrivate.h" -#include "WebNumber.h" -#include "WebURLRequest.h" -#include <WebCore/IntRect.h> -#include <glib/gi18n-lib.h> - -using namespace WebKit; -using namespace WebCore; - -/** - * SECTION: WebKitWindowProperties - * @short_description: Window properties of a #WebKitWebView - * @title: WebKitWindowProperties - * @see_also: #WebKitWebView::ready-to-show - * - * The content of a #WebKitWebView can request to change certain - * properties of the window containing the view. This can include the x, y position - * of the window, the width and height but also if a toolbar, - * scrollbar, statusbar, locationbar should be visible to the user, - * and the request to show the #WebKitWebView fullscreen. - * - * The #WebKitWebView::ready-to-show signal handler is the proper place - * to apply the initial window properties. Then you can monitor the - * #WebKitWindowProperties by connecting to ::notify signal. - * - * <informalexample><programlisting> - * static void ready_to_show_cb (WebKitWebView *web_view, gpointer user_data) - * { - * GtkWidget *window; - * WebKitWindowProperties *window_properties; - * gboolean visible; - * - * /<!-- -->* Create the window to contain the WebKitWebView *<!-- -->/ - * window = browser_window_new (); - * gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (web_view)); - * gtk_widget_show (GTK_WIDGET (web_view)); - * - * /<!-- -->* Get the WebKitWindowProperties of the web view and monitor it *<!-- -->/ - * window_properties = webkit_web_view_get_window_properties (web_view); - * g_signal_connect (window_properties, "notify::geometry", - * G_CALLBACK (window_geometry_changed), window); - * g_signal_connect (window_properties, "notify::toolbar-visible", - * G_CALLBACK (window_toolbar_visibility_changed), window); - * g_signal_connect (window_properties, "notify::menubar-visible", - * G_CALLBACK (window_menubar_visibility_changed), window); - * .... - * - * /<!-- -->* Apply the window properties before showing the window *<!-- -->/ - * visible = webkit_window_properties_get_toolbar_visible (window_properties); - * browser_window_set_toolbar_visible (BROWSER_WINDOW (window), visible); - * visible = webkit_window_properties_get_menubar_visible (window_properties); - * browser_window_set_menubar_visible (BROWSER_WINDOW (window), visible); - * .... - * - * if (webkit_window_properties_get_fullscreen (window_properties)) { - * gtk_window_fullscreen (GTK_WINDOW (window)); - * } else { - * GdkRectangle geometry; - * - * gtk_window_set_resizable (GTK_WINDOW (window), - * webkit_window_properties_get_resizable (window_properties)); - * webkit_window_properties_get_geometry (window_properties, &geometry); - * gtk_window_move (GTK_WINDOW (window), geometry.x, geometry.y); - * gtk_window_resize (GTK_WINDOW (window), geometry.width, geometry.height); - * } - * - * gtk_widget_show (window); - * } - * </programlisting></informalexample> - */ - -enum { - PROP_0, - - PROP_GEOMETRY, - PROP_TOOLBAR_VISIBLE, - PROP_STATUSBAR_VISIBLE, - PROP_SCROLLBARS_VISIBLE, - PROP_MENUBAR_VISIBLE, - PROP_LOCATIONBAR_VISIBLE, - PROP_RESIZABLE, - PROP_FULLSCREEN -}; - -struct _WebKitWindowPropertiesPrivate { - GdkRectangle geometry; - - bool toolbarVisible : 1; - bool statusbarVisible : 1; - bool scrollbarsVisible : 1; - bool menubarVisible : 1; - bool locationbarVisible : 1; - - bool resizable : 1; - bool fullscreen : 1; -}; - -WEBKIT_DEFINE_TYPE(WebKitWindowProperties, webkit_window_properties, G_TYPE_OBJECT) - -static void webkitWindowPropertiesGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) -{ - WebKitWindowProperties* windowProperties = WEBKIT_WINDOW_PROPERTIES(object); - - switch (propId) { - case PROP_GEOMETRY: - g_value_set_boxed(value, &windowProperties->priv->geometry); - break; - case PROP_TOOLBAR_VISIBLE: - g_value_set_boolean(value, webkit_window_properties_get_toolbar_visible(windowProperties)); - break; - case PROP_STATUSBAR_VISIBLE: - g_value_set_boolean(value, webkit_window_properties_get_statusbar_visible(windowProperties)); - break; - case PROP_SCROLLBARS_VISIBLE: - g_value_set_boolean(value, webkit_window_properties_get_scrollbars_visible(windowProperties)); - break; - case PROP_MENUBAR_VISIBLE: - g_value_set_boolean(value, webkit_window_properties_get_menubar_visible(windowProperties)); - break; - case PROP_LOCATIONBAR_VISIBLE: - g_value_set_boolean(value, webkit_window_properties_get_locationbar_visible(windowProperties)); - break; - case PROP_RESIZABLE: - g_value_set_boolean(value, webkit_window_properties_get_resizable(windowProperties)); - break; - case PROP_FULLSCREEN: - g_value_set_boolean(value, webkit_window_properties_get_fullscreen(windowProperties)); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkitWindowPropertiesSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec) -{ - WebKitWindowProperties* windowProperties = WEBKIT_WINDOW_PROPERTIES(object); - - switch (propId) { - case PROP_GEOMETRY: - if (GdkRectangle* geometry = static_cast<GdkRectangle*>(g_value_get_boxed(value))) - windowProperties->priv->geometry = *geometry; - break; - case PROP_TOOLBAR_VISIBLE: - windowProperties->priv->toolbarVisible = g_value_get_boolean(value); - break; - case PROP_STATUSBAR_VISIBLE: - windowProperties->priv->statusbarVisible = g_value_get_boolean(value); - break; - case PROP_SCROLLBARS_VISIBLE: - windowProperties->priv->scrollbarsVisible = g_value_get_boolean(value); - break; - case PROP_MENUBAR_VISIBLE: - windowProperties->priv->menubarVisible = g_value_get_boolean(value); - break; - case PROP_LOCATIONBAR_VISIBLE: - windowProperties->priv->locationbarVisible = g_value_get_boolean(value); - break; - case PROP_RESIZABLE: - windowProperties->priv->resizable = g_value_get_boolean(value); - break; - case PROP_FULLSCREEN: - windowProperties->priv->fullscreen = g_value_get_boolean(value); - break; - default: - G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); - } -} - -static void webkit_window_properties_class_init(WebKitWindowPropertiesClass* requestClass) -{ - GObjectClass* objectClass = G_OBJECT_CLASS(requestClass); - objectClass->get_property = webkitWindowPropertiesGetProperty; - objectClass->set_property = webkitWindowPropertiesSetProperty; - - GParamFlags paramFlags = static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY); - - /** - * WebKitWebWindowProperties:geometry: - * - * The size and position of the window on the screen. - */ - g_object_class_install_property(objectClass, - PROP_GEOMETRY, - g_param_spec_boxed("geometry", - _("Geometry"), - _("The size and position of the window on the screen."), - GDK_TYPE_RECTANGLE, - paramFlags)); - - /** - * WebKitWebWindowProperties:toolbar-visible: - * - * Whether the toolbar should be visible for the window. - */ - g_object_class_install_property(objectClass, - PROP_TOOLBAR_VISIBLE, - g_param_spec_boolean("toolbar-visible", - _("Toolbar Visible"), - _("Whether the toolbar should be visible for the window."), - TRUE, - paramFlags)); - - /** - * WebKitWebWindowProperties:statusbar-visible: - * - * Whether the statusbar should be visible for the window. - */ - g_object_class_install_property(objectClass, - PROP_STATUSBAR_VISIBLE, - g_param_spec_boolean("statusbar-visible", - _("Statusbar Visible"), - _("Whether the statusbar should be visible for the window."), - TRUE, - paramFlags)); - - /** - * WebKitWebWindowProperties:scrollbars-visible: - * - * Whether the scrollbars should be visible for the window. - */ - g_object_class_install_property(objectClass, - PROP_SCROLLBARS_VISIBLE, - g_param_spec_boolean("scrollbars-visible", - _("Scrollbars Visible"), - _("Whether the scrollbars should be visible for the window."), - TRUE, - paramFlags)); - - /** - * WebKitWebWindowProperties:menubar-visible: - * - * Whether the menubar should be visible for the window. - */ - g_object_class_install_property(objectClass, - PROP_MENUBAR_VISIBLE, - g_param_spec_boolean("menubar-visible", - _("Menubar Visible"), - _("Whether the menubar should be visible for the window."), - TRUE, - paramFlags)); - - /** - * WebKitWebWindowProperties:locationbar-visible: - * - * Whether the locationbar should be visible for the window. - */ - g_object_class_install_property(objectClass, - PROP_LOCATIONBAR_VISIBLE, - g_param_spec_boolean("locationbar-visible", - _("Locationbar Visible"), - _("Whether the locationbar should be visible for the window."), - TRUE, - paramFlags)); - /** - * WebKitWebWindowProperties:resizable: - * - * Whether the window can be resized. - */ - g_object_class_install_property(objectClass, - PROP_RESIZABLE, - g_param_spec_boolean("resizable", - _("Resizable"), - _("Whether the window can be resized."), - TRUE, - paramFlags)); - - /** - * WebKitWebWindowProperties:fullscreen: - * - * Whether window will be displayed fullscreen. - */ - g_object_class_install_property(objectClass, - PROP_FULLSCREEN, - g_param_spec_boolean("fullscreen", - _("Fullscreen"), - _("Whether window will be displayed fullscreen."), - FALSE, - paramFlags)); -} - -WebKitWindowProperties* webkitWindowPropertiesCreate() -{ - return WEBKIT_WINDOW_PROPERTIES(g_object_new(WEBKIT_TYPE_WINDOW_PROPERTIES, NULL)); -} - -void webkitWindowPropertiesSetGeometry(WebKitWindowProperties* windowProperties, GdkRectangle* geometry) -{ - if (windowProperties->priv->geometry.x == geometry->x - && windowProperties->priv->geometry.y == geometry->y - && windowProperties->priv->geometry.width == geometry->width - && windowProperties->priv->geometry.height == geometry->height) - return; - windowProperties->priv->geometry = *geometry; - g_object_notify(G_OBJECT(windowProperties), "geometry"); -} - -void webkitWindowPropertiesSetToolbarVisible(WebKitWindowProperties* windowProperties, bool toolbarsVisible) -{ - if (windowProperties->priv->toolbarVisible == toolbarsVisible) - return; - windowProperties->priv->toolbarVisible = toolbarsVisible; - g_object_notify(G_OBJECT(windowProperties), "toolbar-visible"); -} - -void webkitWindowPropertiesSetMenubarVisible(WebKitWindowProperties* windowProperties, bool menuBarVisible) -{ - if (windowProperties->priv->menubarVisible == menuBarVisible) - return; - windowProperties->priv->menubarVisible = menuBarVisible; - g_object_notify(G_OBJECT(windowProperties), "menubar-visible"); -} - -void webkitWindowPropertiesSetStatusbarVisible(WebKitWindowProperties* windowProperties, bool statusBarVisible) -{ - if (windowProperties->priv->statusbarVisible == statusBarVisible) - return; - windowProperties->priv->statusbarVisible = statusBarVisible; - g_object_notify(G_OBJECT(windowProperties), "statusbar-visible"); -} - -void webkitWindowPropertiesSetLocationbarVisible(WebKitWindowProperties* windowProperties, bool locationBarVisible) -{ - if (windowProperties->priv->locationbarVisible == locationBarVisible) - return; - windowProperties->priv->locationbarVisible = locationBarVisible; - g_object_notify(G_OBJECT(windowProperties), "locationbar-visible"); -} - -void webkitWindowPropertiesSetScrollbarsVisible(WebKitWindowProperties* windowProperties, bool scrollBarsVisible) -{ - if (windowProperties->priv->scrollbarsVisible == scrollBarsVisible) - return; - windowProperties->priv->scrollbarsVisible = scrollBarsVisible; - g_object_notify(G_OBJECT(windowProperties), "scrollbars-visible"); -} - -void webkitWindowPropertiesSetResizable(WebKitWindowProperties* windowProperties, bool resizable) -{ - if (windowProperties->priv->resizable == resizable) - return; - windowProperties->priv->resizable = resizable; - g_object_notify(G_OBJECT(windowProperties), "resizable"); -} - -void webkitWindowPropertiesSetFullscreen(WebKitWindowProperties* windowProperties, bool fullscreen) -{ - if (windowProperties->priv->fullscreen == fullscreen) - return; - windowProperties->priv->fullscreen = fullscreen; - g_object_notify(G_OBJECT(windowProperties), "fullscreen"); -} - -void webkitWindowPropertiesUpdateFromWebWindowFeatures(WebKitWindowProperties* windowProperties, ImmutableDictionary* features) -{ - GdkRectangle geometry = windowProperties->priv->geometry; - - WebDouble* doubleValue = static_cast<WebDouble*>(features->get("x")); - if (doubleValue) - geometry.x = doubleValue->value(); - - doubleValue = static_cast<WebDouble*>(features->get("y")); - if (doubleValue) - geometry.y = doubleValue->value(); - - doubleValue = static_cast<WebDouble*>(features->get("width")); - if (doubleValue) - geometry.width = doubleValue->value(); - - doubleValue = static_cast<WebDouble*>(features->get("height")); - if (doubleValue) - geometry.height = doubleValue->value(); - webkitWindowPropertiesSetGeometry(windowProperties, &geometry); - - WebBoolean* booleanValue = static_cast<WebBoolean*>(features->get("menuBarVisible")); - if (booleanValue) - webkitWindowPropertiesSetMenubarVisible(windowProperties, booleanValue->value()); - - booleanValue = static_cast<WebBoolean*>(features->get("statusBarVisible")); - if (booleanValue) - webkitWindowPropertiesSetStatusbarVisible(windowProperties, booleanValue->value()); - - booleanValue = static_cast<WebBoolean*>(features->get("toolBarVisible")); - if (booleanValue) - webkitWindowPropertiesSetToolbarVisible(windowProperties, booleanValue->value()); - - booleanValue = static_cast<WebBoolean*>(features->get("locationBarVisible")); - if (booleanValue) - webkitWindowPropertiesSetLocationbarVisible(windowProperties, booleanValue->value()); - - booleanValue = static_cast<WebBoolean*>(features->get("scrollbarsVisible")); - if (booleanValue) - webkitWindowPropertiesSetScrollbarsVisible(windowProperties, booleanValue->value()); - - booleanValue = static_cast<WebBoolean*>(features->get("resizable")); - if (booleanValue) - webkitWindowPropertiesSetResizable(windowProperties, booleanValue->value()); - - booleanValue = static_cast<WebBoolean*>(features->get("fullscreen")); - if (booleanValue) - webkitWindowPropertiesSetFullscreen(windowProperties, booleanValue->value()); -} - -/** - * webkit_window_properties_get_geometry: - * @window_properties: a #WebKitWindowProperties - * @geometry: (out): return location for the window geometry - * - * Get the geometry the window should have on the screen when shown. - */ -void webkit_window_properties_get_geometry(WebKitWindowProperties* windowProperties, GdkRectangle* geometry) -{ - g_return_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties)); - g_return_if_fail(geometry); - - *geometry = windowProperties->priv->geometry; -} - -/** - * webkit_window_properties_get_toolbar_visible: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should have the toolbar visible or not. - * - * Returns: %TRUE if toolbar should be visible or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_toolbar_visible(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), TRUE); - - return windowProperties->priv->toolbarVisible; -} - -/** - * webkit_window_properties_get_statusbar_visible: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should have the statusbar visible or not. - * - * Returns: %TRUE if statusbar should be visible or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_statusbar_visible(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), TRUE); - - return windowProperties->priv->statusbarVisible; -} - -/** - * webkit_window_properties_get_scrollbars_visible: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should have the scrollbars visible or not. - * - * Returns: %TRUE if scrollbars should be visible or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_scrollbars_visible(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), TRUE); - - return windowProperties->priv->scrollbarsVisible; -} - -/** - * webkit_window_properties_get_menubar_visible: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should have the menubar visible or not. - * - * Returns: %TRUE if menubar should be visible or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_menubar_visible(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), TRUE); - - return windowProperties->priv->menubarVisible; -} - -/** - * webkit_window_properties_get_locationbar_visible: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should have the locationbar visible or not. - * - * Returns: %TRUE if locationbar should be visible or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_locationbar_visible(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), TRUE); - - return windowProperties->priv->locationbarVisible; -} - -/** - * webkit_window_properties_get_resizable: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should be resizable by the user or not. - * - * Returns: %TRUE if the window should be resizable or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_resizable(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), TRUE); - - return windowProperties->priv->resizable; -} - -/** - * webkit_window_properties_get_fullscreen: - * @window_properties: a #WebKitWindowProperties - * - * Get whether the window should be shown in fullscreen state or not. - * - * Returns: %TRUE if the window should be fullscreen or %FALSE otherwise. - */ -gboolean webkit_window_properties_get_fullscreen(WebKitWindowProperties* windowProperties) -{ - g_return_val_if_fail(WEBKIT_IS_WINDOW_PROPERTIES(windowProperties), FALSE); - - return windowProperties->priv->fullscreen; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h deleted file mode 100644 index edbcee98d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowProperties.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitWindowProperties_h -#define WebKitWindowProperties_h - -#include <glib-object.h> -#include <gtk/gtk.h> -#include <webkit2/WebKitDefines.h> - -G_BEGIN_DECLS - -#define WEBKIT_TYPE_WINDOW_PROPERTIES (webkit_window_properties_get_type()) -#define WEBKIT_WINDOW_PROPERTIES(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_WINDOW_PROPERTIES, WebKitWindowProperties)) -#define WEBKIT_IS_WINDOW_PROPERTIES(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_WINDOW_PROPERTIES)) -#define WEBKIT_WINDOW_PROPERTIES_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_WINDOW_PROPERTIES, WebKitWindowPropertiesClass)) -#define WEBKIT_IS_WINDOW_PROPERTIES_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_WINDOW_PROPERTIES)) -#define WEBKIT_WINDOW_PROPERTIES_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_WINDOW_PROPERTIES, WebKitWindowPropertiesClass)) - -typedef struct _WebKitWindowProperties WebKitWindowProperties; -typedef struct _WebKitWindowPropertiesClass WebKitWindowPropertiesClass; -typedef struct _WebKitWindowPropertiesPrivate WebKitWindowPropertiesPrivate; - -struct _WebKitWindowProperties { - GObject parent; - - /*< private >*/ - WebKitWindowPropertiesPrivate *priv; -}; - -struct _WebKitWindowPropertiesClass { - GObjectClass parent_class; - - void (*_webkit_reserved0) (void); - void (*_webkit_reserved1) (void); - void (*_webkit_reserved2) (void); - void (*_webkit_reserved3) (void); -}; - -WEBKIT_API GType -webkit_window_properties_get_type (void); - -WEBKIT_API void -webkit_window_properties_get_geometry (WebKitWindowProperties *window_properties, - GdkRectangle *geometry); -WEBKIT_API gboolean -webkit_window_properties_get_toolbar_visible (WebKitWindowProperties *window_properties); - -WEBKIT_API gboolean -webkit_window_properties_get_statusbar_visible (WebKitWindowProperties *window_properties); - -WEBKIT_API gboolean -webkit_window_properties_get_scrollbars_visible (WebKitWindowProperties *window_properties); - -WEBKIT_API gboolean -webkit_window_properties_get_menubar_visible (WebKitWindowProperties *window_properties); - -WEBKIT_API gboolean -webkit_window_properties_get_locationbar_visible (WebKitWindowProperties *window_properties); - -WEBKIT_API gboolean -webkit_window_properties_get_resizable (WebKitWindowProperties *window_properties); - -WEBKIT_API gboolean -webkit_window_properties_get_fullscreen (WebKitWindowProperties *window_properties); - -G_END_DECLS - -#endif diff --git a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowPropertiesPrivate.h b/Source/WebKit2/UIProcess/API/gtk/WebKitWindowPropertiesPrivate.h deleted file mode 100644 index 8ec17b4ea..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebKitWindowPropertiesPrivate.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, 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 WebKitWindowPropertiesPrivate_h -#define WebKitWindowPropertiesPrivate_h - -#include "WebKitPrivate.h" -#include "WebKitWindowProperties.h" - -WebKitWindowProperties* webkitWindowPropertiesCreate(); -void webkitWindowPropertiesUpdateFromWebWindowFeatures(WebKitWindowProperties*, WebKit::ImmutableDictionary* features); -void webkitWindowPropertiesSetGeometry(WebKitWindowProperties*, GdkRectangle*); -void webkitWindowPropertiesSetToolbarVisible(WebKitWindowProperties*, bool toolbarsVisible); -void webkitWindowPropertiesSetMenubarVisible(WebKitWindowProperties*, bool menuBarVisible); -void webkitWindowPropertiesSetStatusbarVisible(WebKitWindowProperties*, bool statusBarVisible); -void webkitWindowPropertiesSetScrollbarsVisible(WebKitWindowProperties*, bool scrollBarsVisible); -void webkitWindowPropertiesSetResizable(WebKitWindowProperties*, bool resizable); -void webkitWindowPropertiesSetFullscreen(WebKitWindowProperties*, bool fullscreen); - -#endif // WebKitWindowPropertiesPrivate_h diff --git a/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.cpp b/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.cpp deleted file mode 100644 index 8b87c1522..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.cpp +++ /dev/null @@ -1,100 +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 "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 deleted file mode 100644 index 9cde8b12d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/WebViewBaseInputMethodFilter.h +++ /dev/null @@ -1,49 +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. - */ - -#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 deleted file mode 100644 index 2fa7ebacf..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-docs.sgml +++ /dev/null @@ -1,57 +0,0 @@ -<?xml version="1.0"?> -<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" - "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [ -<!ENTITY version SYSTEM "version.xml"> -]> -<book id="index" xmlns:xi="http://www.w3.org/2003/XInclude"> - <bookinfo> - <title>WebKit2GTK+ Reference Manual</title> - <releaseinfo>for WebKit2GTK+ &version;</releaseinfo> - </bookinfo> - - <chapter> - <title>Class Overview</title> - <xi:include href="xml/WebKitWebContext.xml"/> - <xi:include href="xml/WebKitWebView.xml"/> - <xi:include href="xml/WebKitBackForwardList.xml"/> - <xi:include href="xml/WebKitBackForwardListItem.xml"/> - <xi:include href="xml/WebKitSettings.xml"/> - <xi:include href="xml/WebKitURIRequest.xml"/> - <xi:include href="xml/WebKitURIResponse.xml"/> - <xi:include href="xml/WebKitWindowProperties.xml"/> - <xi:include href="xml/WebKitDownload.xml"/> - <xi:include href="xml/WebKitPermissionRequest.xml"/> - <xi:include href="xml/WebKitGeolocationPermissionRequest.xml"/> - <xi:include href="xml/WebKitPolicyDecision.xml"/> - <xi:include href="xml/WebKitNavigationPolicyDecision.xml"/> - <xi:include href="xml/WebKitResponsePolicyDecision.xml"/> - <xi:include href="xml/WebKitHitTestResult.xml"/> - <xi:include href="xml/WebKitPrintOperation.xml"/> - <xi:include href="xml/WebKitWebResource.xml"/> - <xi:include href="xml/WebKitError.xml"/> - <xi:include href="xml/WebKitFaviconDatabase.xml"/> - <xi:include href="xml/WebKitFileChooserRequest.xml"/> - <xi:include href="xml/WebKitFindController.xml"/> - <xi:include href="xml/WebKitCookieManager.xml"/> - <xi:include href="xml/WebKitPlugin.xml"/> - <xi:include href="xml/WebKitWebInspector.xml"/> - <xi:include href="xml/WebKitURISchemeRequest.xml"/> - <xi:include href="xml/WebKitVersion.xml"/> - <xi:include href="xml/WebKitContextMenu.xml"/> - <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"> - <title>Index</title> - </index> - <xi:include href="xml/annotation-glossary.xml"><xi:fallback /></xi:include> -</book> diff --git a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt b/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt deleted file mode 100644 index f280c62df..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk-sections.txt +++ /dev/null @@ -1,1014 +0,0 @@ -<SECTION> -<FILE>WebKitWebViewBase</FILE> -<TITLE>WebKitWebViewBase</TITLE> -WebKitWebViewBase - -<SUBSECTION Standard> -WebKitWebViewBaseClass -WEBKIT_WEB_VIEW_BASE -WEBKIT_IS_WEB_VIEW_BASE -WEBKIT_TYPE_WEB_VIEW_BASE -WEBKIT_WEB_VIEW_BASE_CLASS -WEBKIT_IS_WEB_VIEW_BASE_CLASS -WEBKIT_WEB_VIEW_BASE_GET_CLASS - -<SUBSECTION Private> -webkit_web_view_base_get_type -WebKitWebViewBasePrivate -WEBKIT_API -WEBKIT_OBSOLETE_API -</SECTION> - -<SECTION> -<FILE>WebKitWebContext</FILE> -<TITLE>WebKitWebContext</TITLE> -WebKitWebContext -WebKitCacheModel -WebKitTLSErrorsPolicy -webkit_web_context_get_default -webkit_web_context_get_cache_model -webkit_web_context_set_cache_model -webkit_web_context_clear_cache -webkit_web_context_download_uri -webkit_web_context_get_cookie_manager -webkit_web_context_get_favicon_database -webkit_web_context_set_favicon_database_directory -webkit_web_context_get_favicon_database_directory -webkit_web_context_get_security_manager -webkit_web_context_set_additional_plugins_directory -webkit_web_context_get_plugins -webkit_web_context_get_plugins_finish -webkit_web_context_get_spell_checking_enabled -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 -webkit_web_context_register_uri_scheme - -<SUBSECTION Standard> -WebKitWebContextClass -WEBKIT_WEB_CONTEXT -WEBKIT_IS_WEB_CONTEXT -WEBKIT_TYPE_WEB_CONTEXT -WEBKIT_WEB_CONTEXT_CLASS -WEBKIT_IS_WEB_CONTEXT_CLASS -WEBKIT_WEB_CONTEXT_GET_CLASS - -<SUBSECTION Private> -WebKitWebContextPrivate -webkit_web_context_get_type -</SECTION> - -<SECTION> -<FILE>WebKitWebView</FILE> -<TITLE>WebKitWebView</TITLE> -WebKitWebView -WebKitLoadEvent -WebKitPolicyDecisionType -WebKitSaveMode -WebKitViewMode -WebKitInsecureContentEvent -WebKitSnapshotOptions -WebKitSnapshotRegion - -<SUBSECTION Editing Commands> -WEBKIT_EDITING_COMMAND_CUT -WEBKIT_EDITING_COMMAND_COPY -WEBKIT_EDITING_COMMAND_PASTE -WEBKIT_EDITING_COMMAND_SELECT_ALL -WEBKIT_EDITING_COMMAND_UNDO -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 -webkit_web_view_load_plain_text -webkit_web_view_load_request -webkit_web_view_can_go_back -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 -webkit_web_view_is_loading -webkit_web_view_get_estimated_load_progress -webkit_web_view_get_custom_charset -webkit_web_view_set_custom_charset -webkit_web_view_get_back_forward_list -webkit_web_view_go_to_back_forward_list_item -webkit_web_view_get_uri -webkit_web_view_get_favicon -webkit_web_view_set_settings -webkit_web_view_get_settings -webkit_web_view_get_window_properties -webkit_web_view_set_zoom_level -webkit_web_view_get_zoom_level -webkit_web_view_can_execute_editing_command -webkit_web_view_can_execute_editing_command_finish -webkit_web_view_execute_editing_command -webkit_web_view_get_find_controller -webkit_web_view_get_inspector -webkit_web_view_get_javascript_global_context -webkit_web_view_run_javascript -webkit_web_view_run_javascript_finish -webkit_web_view_run_javascript_from_gresource -webkit_web_view_run_javascript_from_gresource_finish -webkit_web_view_can_show_mime_type -webkit_web_view_save -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 -webkit_javascript_result_ref -webkit_javascript_result_unref -webkit_javascript_result_get_global_context -webkit_javascript_result_get_value - -<SUBSECTION WebKitScriptDialog> -WebKitScriptDialog -WebKitScriptDialogType -webkit_script_dialog_get_dialog_type -webkit_script_dialog_get_message -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 - -<SUBSECTION Standard> -WebKitWebViewClass -WEBKIT_WEB_VIEW -WEBKIT_IS_WEB_VIEW -WEBKIT_TYPE_WEB_VIEW -WEBKIT_WEB_VIEW_CLASS -WEBKIT_IS_WEB_VIEW_CLASS -WEBKIT_WEB_VIEW_GET_CLASS -WEBKIT_TYPE_JAVASCRIPT_RESULT -WEBKIT_TYPE_SCRIPT_DIALOG - -<SUBSECTION Private> -webkit_web_view_get_type -webkit_javascript_result_get_type -webkit_script_dialog_get_type -WebKitWebViewPrivate -</SECTION> - -<SECTION> -<FILE>WebKitBackForwardList</FILE> -WebKitBackForwardList -webkit_back_forward_list_get_length -webkit_back_forward_list_get_current_item -webkit_back_forward_list_get_back_item -webkit_back_forward_list_get_forward_item -webkit_back_forward_list_get_nth_item -webkit_back_forward_list_get_back_list -webkit_back_forward_list_get_back_list_with_limit -webkit_back_forward_list_get_forward_list -webkit_back_forward_list_get_forward_list_with_limit - -<SUBSECTION Standard> -WebKitBackForwardListClass -WEBKIT_TYPE_BACK_FORWARD_LIST -WEBKIT_BACK_FORWARD_LIST -WEBKIT_IS_BACK_FORWARD_LIST -WEBKIT_BACK_FORWARD_LIST_CLASS -WEBKIT_IS_BACK_FORWARD_LIST_CLASS -WEBKIT_BACK_FORWARD_LIST_GET_CLASS - -<SUBSECTION Private> -WebKitBackForwardListPrivate -webkit_back_forward_list_get_type -</SECTION> - -<SECTION> -<FILE>WebKitBackForwardListItem</FILE> -WebKitBackForwardListItem -webkit_back_forward_list_item_get_title -webkit_back_forward_list_item_get_uri -webkit_back_forward_list_item_get_original_uri - -<SUBSECTION Standard> -WebKitBackForwardListItemClass -WEBKIT_TYPE_BACK_FORWARD_LIST_ITEM -WEBKIT_BACK_FORWARD_LIST_ITEM -WEBKIT_IS_BACK_FORWARD_LIST_ITEM -WEBKIT_BACK_FORWARD_LIST_ITEM_CLASS -WEBKIT_IS_BACK_FORWARD_LIST_ITEM_CLASS -WEBKIT_BACK_FORWARD_LIST_ITEM_GET_CLASS - -<SUBSECTION Private> -WebKitBackForwardListItemPrivate -webkit_back_forward_list_item_get_type -</SECTION> - -<SECTION> -<FILE>WebKitSettings</FILE> -WebKitSettings -webkit_settings_new -webkit_settings_new_with_settings -webkit_settings_get_auto_load_images -webkit_settings_set_auto_load_images -webkit_settings_get_enable_frame_flattening -webkit_settings_set_enable_frame_flattening -webkit_settings_get_enable_html5_database -webkit_settings_set_enable_html5_database -webkit_settings_get_enable_html5_local_storage -webkit_settings_set_enable_html5_local_storage -webkit_settings_get_enable_hyperlink_auditing -webkit_settings_set_enable_hyperlink_auditing -webkit_settings_get_enable_java -webkit_settings_set_enable_java -webkit_settings_get_enable_javascript -webkit_settings_set_enable_javascript -webkit_settings_get_enable_offline_web_application_cache -webkit_settings_set_enable_offline_web_application_cache -webkit_settings_get_enable_plugins -webkit_settings_set_enable_plugins -webkit_settings_get_enable_xss_auditor -webkit_settings_set_enable_xss_auditor -webkit_settings_get_javascript_can_open_windows_automatically -webkit_settings_set_javascript_can_open_windows_automatically -webkit_settings_get_load_icons_ignoring_image_load_setting -webkit_settings_set_load_icons_ignoring_image_load_setting -webkit_settings_get_default_font_family -webkit_settings_set_default_font_family -webkit_settings_get_monospace_font_family -webkit_settings_set_monospace_font_family -webkit_settings_get_serif_font_family -webkit_settings_set_serif_font_family -webkit_settings_get_sans_serif_font_family -webkit_settings_set_sans_serif_font_family -webkit_settings_get_cursive_font_family -webkit_settings_set_cursive_font_family -webkit_settings_get_fantasy_font_family -webkit_settings_set_fantasy_font_family -webkit_settings_get_pictograph_font_family -webkit_settings_set_pictograph_font_family -webkit_settings_get_default_font_size -webkit_settings_set_default_font_size -webkit_settings_get_default_monospace_font_size -webkit_settings_set_default_monospace_font_size -webkit_settings_get_minimum_font_size -webkit_settings_set_minimum_font_size -webkit_settings_get_default_charset -webkit_settings_set_default_charset -webkit_settings_get_enable_private_browsing -webkit_settings_set_enable_private_browsing -webkit_settings_get_enable_developer_extras -webkit_settings_set_enable_developer_extras -webkit_settings_get_enable_resizable_text_areas -webkit_settings_set_enable_resizable_text_areas -webkit_settings_get_enable_tabs_to_links -webkit_settings_set_enable_tabs_to_links -webkit_settings_get_enable_dns_prefetching -webkit_settings_set_enable_dns_prefetching -webkit_settings_get_enable_caret_browsing -webkit_settings_set_enable_caret_browsing -webkit_settings_get_enable_fullscreen -webkit_settings_set_enable_fullscreen -webkit_settings_get_print_backgrounds -webkit_settings_set_print_backgrounds -webkit_settings_get_enable_webaudio -webkit_settings_set_enable_webaudio -webkit_settings_get_enable_webgl -webkit_settings_set_enable_webgl -webkit_settings_set_allow_modal_dialogs -webkit_settings_get_allow_modal_dialogs -webkit_settings_get_zoom_text_only -webkit_settings_set_zoom_text_only -webkit_settings_get_javascript_can_access_clipboard -webkit_settings_set_javascript_can_access_clipboard -webkit_settings_get_media_playback_requires_user_gesture -webkit_settings_set_media_playback_requires_user_gesture -webkit_settings_get_media_playback_allows_inline -webkit_settings_set_media_playback_allows_inline -webkit_settings_get_draw_compositing_indicators -webkit_settings_set_draw_compositing_indicators -webkit_settings_get_enable_site_specific_quirks -webkit_settings_set_enable_site_specific_quirks -webkit_settings_get_enable_page_cache -webkit_settings_set_enable_page_cache -webkit_settings_get_user_agent -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 -WEBKIT_TYPE_SETTINGS -WEBKIT_SETTINGS -WEBKIT_IS_SETTINGS -WEBKIT_SETTINGS_CLASS -WEBKIT_IS_SETTINGS_CLASS -WEBKIT_SETTINGS_GET_CLASS - -<SUBSECTION Private> -WebKitSettingsPrivate -webkit_settings_get_type -</SECTION> - -<SECTION> -<FILE>WebKitURIRequest</FILE> -WebKitURIRequest -webkit_uri_request_new -webkit_uri_request_get_uri -webkit_uri_request_set_uri -webkit_uri_request_get_http_headers - -<SUBSECTION Standard> -WebKitURIRequestClass -WEBKIT_TYPE_URI_REQUEST -WEBKIT_URI_REQUEST -WEBKIT_IS_URI_REQUEST -WEBKIT_URI_REQUEST_CLASS -WEBKIT_IS_URI_REQUEST_CLASS -WEBKIT_URI_REQUEST_GET_CLASS - -<SUBSECTION Private> -WebKitURIRequestPrivate -webkit_uri_request_get_type -</SECTION> - -<SECTION> -<FILE>WebKitURIResponse</FILE> -WebKitURIResponse -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_suggested_filename - -<SUBSECTION Standard> -WebKitURIResponseClass -WEBKIT_TYPE_URI_RESPONSE -WEBKIT_URI_RESPONSE -WEBKIT_IS_URI_RESPONSE -WEBKIT_URI_RESPONSE_CLASS -WEBKIT_IS_URI_RESPONSE_CLASS -WEBKIT_URI_RESPONSE_GET_CLASS - -<SUBSECTION Private> -WebKitURIResponsePrivate -webkit_uri_response_get_type -</SECTION> - -<SECTION> -<FILE>WebKitWindowProperties</FILE> -WebKitWindowProperties -webkit_window_properties_get_geometry -webkit_window_properties_get_toolbar_visible -webkit_window_properties_get_statusbar_visible -webkit_window_properties_get_scrollbars_visible -webkit_window_properties_get_menubar_visible -webkit_window_properties_get_locationbar_visible -webkit_window_properties_get_resizable -webkit_window_properties_get_fullscreen - -<SUBSECTION Standard> -WebKitWindowPropertiesClass -WEBKIT_TYPE_WINDOW_PROPERTIES -WEBKIT_WINDOW_PROPERTIES -WEBKIT_IS_WINDOW_PROPERTIES -WEBKIT_WINDOW_PROPERTIES_CLASS -WEBKIT_IS_WINDOW_PROPERTIES_CLASS -WEBKIT_WINDOW_PROPERTIES_GET_CLASS - -<SUBSECTION Private> -WebKitWindowPropertiesPrivate -webkit_window_properties_get_type -</SECTION> - -<SECTION> -<FILE>WebKitDownload</FILE> -WebKitDownload -webkit_download_get_request -webkit_download_get_destination -webkit_download_set_destination -webkit_download_get_response -webkit_download_cancel -webkit_download_get_estimated_progress -webkit_download_get_elapsed_time -webkit_download_get_received_data_length -webkit_download_get_web_view - -<SUBSECTION Standard> -WebKitDownloadClass -WEBKIT_TYPE_DOWNLOAD -WEBKIT_DOWNLOAD -WEBKIT_IS_DOWNLOAD -WEBKIT_DOWNLOAD_CLASS -WEBKIT_IS_DOWNLOAD_CLASS -WEBKIT_DOWNLOAD_GET_CLASS - -<SUBSECTION Private> -WebKitDownloadPrivate -webkit_download_get_type -</SECTION> - -<SECTION> -<FILE>WebKitPermissionRequest</FILE> -WebKitPermissionRequest -webkit_permission_request_allow -webkit_permission_request_deny - -<SUBSECTION Standard> -WebKitPermissionRequestIface -WEBKIT_TYPE_PERMISSION_REQUEST -WEBKIT_PERMISSION_REQUEST -WEBKIT_IS_PERMISSION_REQUEST -WEBKIT_PERMISSION_REQUEST_GET_IFACE - -<SUBSECTION Private> -webkit_permission_request_get_type -</SECTION> - -<SECTION> -<FILE>WebKitGeolocationPermissionRequest</FILE> -WebKitGeolocationPermissionRequest - -<SUBSECTION Standard> -WebKitGeolocationPermissionRequestClass -WEBKIT_TYPE_GEOLOCATION_PERMISSION_REQUEST -WEBKIT_GEOLOCATION_PERMISSION_REQUEST -WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST -WEBKIT_GEOLOCATION_PERMISSION_REQUEST_CLASS -WEBKIT_IS_GEOLOCATION_PERMISSION_REQUEST_CLASS -WEBKIT_GEOLOCATION_PERMISSION_REQUEST_GET_CLASS - -<SUBSECTION Private> -WebKitGeolocationPermissionRequestPrivate -webkit_geolocation_permission_request_get_type -</SECTION> - -<SECTION> -<FILE>WebKitPolicyDecision</FILE> -WebKitPolicyDecision -webkit_policy_decision_download -webkit_policy_decision_ignore -webkit_policy_decision_use - -<SUBSECTION Standard> -WebKitPolicyDecisionClass -WEBKIT_TYPE_POLICY_DECISION -WEBKIT_POLICY_DECISION -WEBKIT_IS_POLICY_DECISION -WEBKIT_POLICY_DECISION_CLASS -WEBKIT_IS_POLICY_DECISION_CLASS -WEBKIT_POLICY_DECISION_GET_CLASS - -<SUBSECTION Private> -WebKitPolicyDecisionPrivate -webkit_policy_decision_get_type -</SECTION> - -<SECTION> -<FILE>WebKitNavigationPolicyDecision</FILE> -WebKitNavigationPolicyDecision -WebKitNavigationType -webkit_navigation_policy_decision_get_frame_name -webkit_navigation_policy_decision_get_modifiers -webkit_navigation_policy_decision_get_mouse_button -webkit_navigation_policy_decision_get_navigation_type -webkit_navigation_policy_decision_get_request - -<SUBSECTION Standard> -WebKitNavigationPolicyDecisionClass -WEBKIT_TYPE_NAVIGATION_POLICY_DECISION -WEBKIT_NAVIGATION_POLICY_DECISION -WEBKIT_IS_NAVIGATION_POLICY_DECISION -WEBKIT_NAVIGATION_POLICY_DECISION_CLASS -WEBKIT_IS_NAVIGATION_POLICY_DECISION_CLASS -WEBKIT_NAVIGATION_POLICY_DECISION_GET_CLASS - -<SUBSECTION Private> -WebKitNavigationPolicyDecisionPrivate -webkit_navigation_policy_decision_get_type -</SECTION> - -<SECTION> -<FILE>WebKitResponsePolicyDecision</FILE> -WebKitResponsePolicyDecision -webkit_response_policy_decision_get_request -webkit_response_policy_decision_get_response - -<SUBSECTION Standard> -WebKitResponsePolicyDecisionClass -WEBKIT_TYPE_RESPONSE_POLICY_DECISION -WEBKIT_RESPONSE_POLICY_DECISION -WEBKIT_IS_RESPONSE_POLICY_DECISION -WEBKIT_RESPONSE_POLICY_DECISION_CLASS -WEBKIT_IS_RESPONSE_POLICY_DECISION_CLASS -WEBKIT_RESPONSE_POLICY_DECISION_GET_CLASS - -<SUBSECTION Private> -WebKitResponsePolicyDecisionPrivate -webkit_response_policy_decision_get_type -</SECTION> - -<SECTION> -<FILE>WebKitHitTestResult</FILE> -WebKitHitTestResult -WebKitHitTestResultContext -webkit_hit_test_result_get_context -webkit_hit_test_result_context_is_link -webkit_hit_test_result_context_is_image -webkit_hit_test_result_context_is_media -webkit_hit_test_result_context_is_editable -webkit_hit_test_result_get_link_uri -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 -WEBKIT_TYPE_HIT_TEST_RESULT -WEBKIT_HIT_TEST_RESULT -WEBKIT_IS_HIT_TEST_RESULT -WEBKIT_HIT_TEST_RESULT_CLASS -WEBKIT_IS_HIT_TEST_RESULT_CLASS -WEBKIT_HIT_TEST_RESULT_GET_CLASS - -<SUBSECTION Private> -WebKitHitTestResultPrivate -webkit_hit_test_result_get_type -</SECTION> - -<SECTION> -<FILE>WebKitPrintOperation</FILE> -WebKitPrintOperation -WebKitPrintOperationResponse -webkit_print_operation_new -webkit_print_operation_get_print_settings -webkit_print_operation_set_print_settings -webkit_print_operation_get_page_setup -webkit_print_operation_set_page_setup -webkit_print_operation_run_dialog -webkit_print_operation_print - -<SUBSECTION Standard> -WebKitPrintOperationClass -WEBKIT_TYPE_PRINT_OPERATION -WEBKIT_PRINT_OPERATION -WEBKIT_IS_PRINT_OPERATION -WEBKIT_PRINT_OPERATION_CLASS -WEBKIT_IS_PRINT_OPERATION_CLASS -WEBKIT_PRINT_OPERATION_GET_CLASS - -<SUBSECTION Private> -WebKitPrintOperationPrivate -webkit_print_operation_get_type -</SECTION> - -<SECTION> -<FILE>WebKitWebResource</FILE> -WebKitWebResource -webkit_web_resource_get_uri -webkit_web_resource_get_response -webkit_web_resource_get_data -webkit_web_resource_get_data_finish - -<SUBSECTION Standard> -WebKitWebResourceClass -WEBKIT_TYPE_WEB_RESOURCE -WEBKIT_WEB_RESOURCE -WEBKIT_IS_WEB_RESOURCE -WEBKIT_WEB_RESOURCE_CLASS -WEBKIT_IS_WEB_RESOURCE_CLASS -WEBKIT_WEB_RESOURCE_GET_CLASS - -<SUBSECTION Private> -WebKitWebResourcePrivate -webkit_web_resource_get_type -</SECTION> - -<SECTION> -<FILE>WebKitError</FILE> -WEBKIT_NETWORK_ERROR -WEBKIT_PLUGIN_ERROR -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> -<FILE>WebKitFaviconDatabase</FILE> -WebKitFaviconDatabase -WEBKIT_FAVICON_DATABASE_ERROR -WebKitFaviconDatabaseError -webkit_favicon_database_get_favicon -webkit_favicon_database_get_favicon_finish -webkit_favicon_database_get_favicon_uri -webkit_favicon_database_clear - -<SUBSECTION Standard> -WebKitFaviconDatabaseClass -WEBKIT_TYPE_FAVICON_DATABASE -WEBKIT_FAVICON_DATABASE -WEBKIT_IS_FAVICON_DATABASE -WEBKIT_FAVICON_DATABASE_CLASS -WEBKIT_IS_FAVICON_DATABASE_CLASS -WEBKIT_FAVICON_DATABASE_GET_CLASS - -<SUBSECTION Private> -WebKitFaviconDatabasePrivate -webkit_favicon_database_get_type -webkit_favicon_database_error_quark -</SECTION> - -<SECTION> -<FILE>WebKitFileChooserRequest</FILE> -WebKitFileChooserRequest -webkit_file_chooser_request_get_mime_types -webkit_file_chooser_request_get_mime_types_filter -webkit_file_chooser_request_get_select_multiple -webkit_file_chooser_request_select_files -webkit_file_chooser_request_get_selected_files -webkit_file_chooser_request_cancel - -<SUBSECTION Standard> -WebKitFileChooserRequestClass -WEBKIT_TYPE_FILE_CHOOSER_REQUEST -WEBKIT_FILE_CHOOSER_REQUEST -WEBKIT_IS_FILE_CHOOSER_REQUEST -WEBKIT_FILE_CHOOSER_REQUEST_CLASS -WEBKIT_IS_FILE_CHOOSER_REQUEST_CLASS -WEBKIT_FILE_CHOOSER_REQUEST_GET_CLASS - -<SUBSECTION Private> -WebKitFileChooserRequestPrivate -webkit_file_chooser_request_get_type -</SECTION> - -<SECTION> -<FILE>WebKitFindController</FILE> -WebKitFindController -WebKitFindOptions -webkit_find_controller_search -webkit_find_controller_search_finish -webkit_find_controller_search_next -webkit_find_controller_search_previous -webkit_find_controller_get_search_text -webkit_find_controller_count_matches -webkit_find_controller_get_options -webkit_find_controller_get_max_match_count -webkit_find_controller_get_web_view - -<SUBSECTION Standard> -WebKitFindControllerClass -WEBKIT_TYPE_FIND_CONTROLLER -WEBKIT_FIND_CONTROLLER -WEBKIT_IS_FIND_CONTROLLER -WEBKIT_FIND_CONTROLLER_CLASS -WEBKIT_IS_FIND_CONTROLLER_CLASS -WEBKIT_FIND_CONTROLLER_GET_CLASS - -<SUBSECTION Private> -WebKitFindControllerPrivate -webkit_find_controller_get_type -</SECTION> - -<SECTION> -<FILE>WebKitCookieManager</FILE> -WebKitCookieManager -WebKitCookiePersistentStorage -WebKitCookieAcceptPolicy -webkit_cookie_manager_set_persistent_storage -webkit_cookie_manager_set_accept_policy -webkit_cookie_manager_get_accept_policy -webkit_cookie_manager_get_accept_policy_finish -webkit_cookie_manager_get_domains_with_cookies -webkit_cookie_manager_get_domains_with_cookies_finish -webkit_cookie_manager_delete_cookies_for_domain -webkit_cookie_manager_delete_all_cookies - -<SUBSECTION Standard> -WebKitCookieManagerClass -WEBKIT_TYPE_COOKIE_MANAGER -WEBKIT_COOKIE_MANAGER -WEBKIT_IS_COOKIE_MANAGER -WEBKIT_COOKIE_MANAGER_CLASS -WEBKIT_IS_COOKIE_MANAGER_CLASS -WEBKIT_COOKIE_MANAGER_GET_CLASS - -<SUBSECTION Private> -WebKitCookieManagerPrivate -webkit_cookie_manager_get_type -</SECTION> - -<SECTION> -<FILE>WebKitPlugin</FILE> -WebKitPlugin -webkit_plugin_get_name -webkit_plugin_get_description -webkit_plugin_get_path -webkit_plugin_get_mime_info_list - -<SUBSECTION WebKitMimeInfo> -WebKitMimeInfo -webkit_mime_info_ref -webkit_mime_info_unref -webkit_mime_info_get_mime_type -webkit_mime_info_get_description -webkit_mime_info_get_extensions - -<SUBSECTION Standard> -WebKitPluginClass -WEBKIT_TYPE_PLUGIN -WEBKIT_PLUGIN -WEBKIT_IS_PLUGIN -WEBKIT_PLUGIN_CLASS -WEBKIT_IS_PLUGIN_CLASS -WEBKIT_PLUGIN_GET_CLASS -WEBKIT_TYPE_MIME_INFO - -<SUBSECTION Private> -webkit_plugin_get_type -webkit_mime_info_get_type -WebKitPluginPrivate -</SECTION> - -<SECTION> -<FILE>WebKitWebInspector</FILE> -WebKitWebInspector -webkit_web_inspector_get_web_view -webkit_web_inspector_get_inspected_uri -webkit_web_inspector_is_attached -webkit_web_inspector_attach -webkit_web_inspector_detach -webkit_web_inspector_show -webkit_web_inspector_close -webkit_web_inspector_get_attached_height - -<SUBSECTION Standard> -WebKitWebInspectorClass -WEBKIT_TYPE_WEB_INSPECTOR -WEBKIT_WEB_INSPECTOR -WEBKIT_IS_WEB_INSPECTOR -WEBKIT_WEB_INSPECTOR_CLASS -WEBKIT_IS_WEB_INSPECTOR_CLASS -WEBKIT_WEB_INSPECTOR_GET_CLASS - -<SUBSECTION Private> -webkit_web_inspector_get_type -WebKitWebInspectorPrivate -</SECTION> - -<SECTION> -<FILE>WebKitURISchemeRequest</FILE> -WebKitURISchemeRequest -webkit_uri_scheme_request_get_scheme -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 -WEBKIT_TYPE_URI_SCHEME_REQUEST -WEBKIT_URI_SCHEME_REQUEST -WEBKIT_IS_URI_SCHEME_REQUEST -WEBKIT_URI_SCHEME_REQUEST_CLASS -WEBKIT_IS_URI_SCHEME_REQUEST_CLASS -WEBKIT_URI_SCHEME_REQUEST_GET_CLASS - -<SUBSECTION Private> -WebKitURISchemeRequestPrivate -webkit_uri_scheme_request_get_type -</SECTION> - -<SECTION> -<FILE>WebKitVersion</FILE> -webkit_get_major_version -webkit_get_minor_version -webkit_get_micro_version - -<SUBSECTION> -WEBKIT_MAJOR_VERSION -WEBKIT_MINOR_VERSION -WEBKIT_MICRO_VERSION -WEBKIT_CHECK_VERSION -</SECTION> - -<SECTION> -<FILE>WebKitContextMenu</FILE> -WebKitContextMenu -webkit_context_menu_new -webkit_context_menu_new_with_items -webkit_context_menu_prepend -webkit_context_menu_append -webkit_context_menu_insert -webkit_context_menu_move_item -webkit_context_menu_get_items -webkit_context_menu_get_n_items -webkit_context_menu_first -webkit_context_menu_last -webkit_context_menu_get_item_at_position -webkit_context_menu_remove -webkit_context_menu_remove_all - -<SUBSECTION Standard> -WebKitContextMenuClass -WEBKIT_TYPE_CONTEXT_MENU -WEBKIT_CONTEXT_MENU -WEBKIT_IS_CONTEXT_MENU -WEBKIT_CONTEXT_MENU_CLASS -WEBKIT_IS_CONTEXT_MENU_CLASS -WEBKIT_CONTEXT_MENU_GET_CLASS - -<SUBSECTION Private> -WebKitContextMenuPrivate -webkit_context_menu_get_type -</SECTION> - -<SECTION> -<FILE>WebKitContextMenuItem</FILE> -WebKitContextMenuItem -WebKitContextMenuAction -webkit_context_menu_item_new -webkit_context_menu_item_new_from_stock_action -webkit_context_menu_item_new_from_stock_action_with_label -webkit_context_menu_item_new_with_submenu -webkit_context_menu_item_new_separator -webkit_context_menu_item_get_action -webkit_context_menu_item_get_stock_action -webkit_context_menu_item_is_separator -webkit_context_menu_item_set_submenu -webkit_context_menu_item_get_submenu - -<SUBSECTION Standard> -WebKitContextMenuItemClass -WEBKIT_TYPE_CONTEXT_MENU_ITEM -WEBKIT_CONTEXT_MENU_ITEM -WEBKIT_IS_CONTEXT_MENU_ITEM -WEBKIT_CONTEXT_MENU_ITEM_CLASS -WEBKIT_IS_CONTEXT_MENU_ITEM_CLASS -WEBKIT_CONTEXT_MENU_ITEM_GET_CLASS - -<SUBSECTION Private> -WebKitContextMenuItemPrivate -webkit_context_menu_item_get_type -</SECTION> - -<SECTION> -<FILE>WebKitFormSubmissionRequest</FILE> -WebKitFormSubmissionRequest -webkit_form_submission_request_get_text_fields -webkit_form_submission_request_submit - -<SUBSECTION Standard> -WebKitFormSubmissionRequestClass -WEBKIT_TYPE_FORM_SUBMISSION_REQUEST -WEBKIT_FORM_SUBMISSION_REQUEST -WEBKIT_IS_FORM_SUBMISSION_REQUEST -WEBKIT_FORM_SUBMISSION_REQUEST_CLASS -WEBKIT_IS_FORM_SUBMISSION_REQUEST_CLASS -WEBKIT_FORM_SUBMISSION_REQUEST_GET_CLASS - -<SUBSECTION Private> -WebKitFormSubmissionRequestPrivate -webkit_form_submission_request_get_type -</SECTION> - -<SECTION> -<FILE>WebKitSecurityManager</FILE> -WebKitSecurityManager -webkit_security_manager_register_uri_scheme_as_local -webkit_security_manager_uri_scheme_is_local -webkit_security_manager_register_uri_scheme_as_no_access -webkit_security_manager_uri_scheme_is_no_access -webkit_security_manager_register_uri_scheme_as_display_isolated -webkit_security_manager_uri_scheme_is_display_isolated -webkit_security_manager_register_uri_scheme_as_secure -webkit_security_manager_uri_scheme_is_secure -webkit_security_manager_register_uri_scheme_as_cors_enabled -webkit_security_manager_uri_scheme_is_cors_enabled -webkit_security_manager_register_uri_scheme_as_empty_document -webkit_security_manager_uri_scheme_is_empty_document - -<SUBSECTION Standard> -WebKitSecurityManagerClass -WEBKIT_TYPE_SECURITY_MANAGER -WEBKIT_SECURITY_MANAGER -WEBKIT_IS_SECURITY_MANAGER -WEBKIT_SECURITY_MANAGER_CLASS -WEBKIT_IS_SECURITY_MANAGER_CLASS -WEBKIT_SECURITY_MANAGER_GET_CLASS - -<SUBSECTION Private> -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 deleted file mode 100644 index 5d97f69be..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/docs/webkit2gtk.types +++ /dev/null @@ -1,26 +0,0 @@ -#include <webkit2/webkit2.h> -webkit_web_view_get_type -webkit_web_view_base_get_type -webkit_web_context_get_type -webkit_back_forward_list_get_type -webkit_back_forward_list_item_get_type -webkit_settings_get_type -webkit_uri_response_get_type -webkit_uri_request_get_type -webkit_window_properties_get_type -webkit_download_get_type -webkit_file_chooser_request_get_type -webkit_find_controller_get_type -webkit_script_dialog_get_type -webkit_javascript_result_get_type -webkit_web_resource_get_type -webkit_cookie_manager_get_type -webkit_plugin_get_type -webkit_mime_info_get_type -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/AccessibilityTestServer.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/AccessibilityTestServer.cpp deleted file mode 100644 index a8bbbc3fa..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/AccessibilityTestServer.cpp +++ /dev/null @@ -1,58 +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 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 <gtk/gtk.h> -#include <webkit2/webkit2.h> - -static void loadChangedCallback(WebKitWebView*, WebKitLoadEvent loadEvent, gpointer) -{ - // Send a message to the parent process when we're ready. - if (loadEvent == WEBKIT_LOAD_FINISHED) - g_print("OK"); -} - -int main(int argc, char** argv) -{ - // Make sure that both GAIL and the ATK bridge are loaded. - g_setenv("GTK_MODULES", "gail:atk-bridge", TRUE); - - gtk_init(&argc, &argv); - - WebKitWebView* webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); - webkit_web_view_load_html(webView, - "<html>" - " <body>" - " <h1>This is a test</h1>" - " <p>This is a paragraph with some plain text.</p>" - " <p>This paragraph contains <a href=\"http://www.webkitgtk.org\">a link</a> in the middle.</p>" - " </body>" - "</html>", - 0); - - GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(webView)); - gtk_widget_show_all(window); - - g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), 0); - g_signal_connect(webView, "load-changed", G_CALLBACK(loadChangedCallback), 0); - - gtk_main(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am b/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am deleted file mode 100644 index 7510b617c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/GNUmakefile.am +++ /dev/null @@ -1,271 +0,0 @@ -if ENABLE_WEBKIT2 - -TEST_PROGS += \ - Programs/WebKit2APITests/InspectorTestServer \ - Programs/WebKit2APITests/TestBackForwardList \ - Programs/WebKit2APITests/TestContextMenu \ - Programs/WebKit2APITests/TestCookieManager \ - Programs/WebKit2APITests/TestDownloads \ - Programs/WebKit2APITests/TestInspector \ - Programs/WebKit2APITests/TestInspectorServer \ - Programs/WebKit2APITests/TestLoaderClient \ - Programs/WebKit2APITests/TestPrinting \ - Programs/WebKit2APITests/TestResources \ - Programs/WebKit2APITests/TestSSL \ - Programs/WebKit2APITests/TestWebExtensions \ - Programs/WebKit2APITests/TestWebKitVersion \ - Programs/WebKit2APITests/TestWebKitFaviconDatabase \ - Programs/WebKit2APITests/TestWebKitFindController \ - Programs/WebKit2APITests/TestWebKitPolicyClient \ - Programs/WebKit2APITests/TestWebKitSettings \ - Programs/WebKit2APITests/TestWebKitWebContext \ - Programs/WebKit2APITests/TestWebKitWebView \ - Programs/WebKit2APITests/TestWebKitWebViewGroup \ - Programs/WebKit2APITests/TestWebViewEditor - -noinst_PROGRAMS += $(TEST_PROGS) - -if HAVE_ATSPI2 -TEST_PROGS += Programs/WebKit2APITests/TestWebKitAccessibility - -noinst_PROGRAMS += Programs/WebKit2APITests/AccessibilityTestServer -endif - -webkit2_tests_cppflags = \ - -DWEBKIT_EXEC_PATH=\"${shell pwd}/$(top_builddir)/Programs\" \ - -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 \ - -I$(srcdir)/Source/WebKit2 \ - -I$(top_builddir)/DerivedSources/WebKit2/include \ - -I$(top_builddir)/DerivedSources/WebKit2/webkit2gtk \ - -I$(top_builddir)/DerivedSources/WebKit2/webkit2gtk/include \ - -I$(srcdir)/Source/WebKit2/UIProcess/API/gtk \ - $(global_cppflags) \ - $(FREETYPE_CFLAGS) \ - $(GLIB_CFLAGS) \ - $(GTK_CFLAGS) \ - $(LIBSOUP_CFLAGS) - -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) \ - $(LIBSOUP_LIBS) - -webkit2_tests_ldflags = \ - -no-install \ - -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) $< - -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 \ - Source/WebKit2/UIProcess/API/gtk/tests/TestMain.h \ - Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp \ - 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 \ - Source/WebKit2/UIProcess/API/gtk/tests/resources/webkit2gtk-tests.gresource.xml \ - Source/WebKit2/UIProcess/API/gtk/tests/resources/link-title.js - -Programs_WebKit2APITests_TestWebKitWebContext_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp -Programs_WebKit2APITests_TestWebKitWebContext_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitWebContext_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitWebContext_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitWebView_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp -Programs_WebKit2APITests_TestWebKitWebView_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitWebView_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitWebView_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestLoaderClient_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp -Programs_WebKit2APITests_TestLoaderClient_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestLoaderClient_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestLoaderClient_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitSettings_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp -Programs_WebKit2APITests_TestWebKitSettings_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitSettings_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitSettings_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_InspectorTestServer_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/InspectorTestServer.cpp -Programs_WebKit2APITests_InspectorTestServer_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_InspectorTestServer_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_InspectorTestServer_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestBackForwardList_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestBackForwardList.cpp -Programs_WebKit2APITests_TestBackForwardList_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestBackForwardList_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestBackForwardList_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitPolicyClient_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitPolicyClient.cpp -Programs_WebKit2APITests_TestWebKitPolicyClient_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitPolicyClient_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitPolicyClient_LDFLAGS = $(webkit2_tests_ldflags) - -if HAVE_ATSPI2 -Programs_WebKit2APITests_AccessibilityTestServer_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/AccessibilityTestServer.cpp -Programs_WebKit2APITests_AccessibilityTestServer_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_AccessibilityTestServer_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_AccessibilityTestServer_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitAccessibility_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitAccessibility.cpp -Programs_WebKit2APITests_TestWebKitAccessibility_CPPFLAGS = $(webkit2_tests_cppflags) $(ATSPI2_CFLAGS) -Programs_WebKit2APITests_TestWebKitAccessibility_LDADD = $(webkit2_tests_ldadd) $(ATSPI2_LIBS) -Programs_WebKit2APITests_TestWebKitAccessibility_LDFLAGS = $(webkit2_tests_ldflags) -endif - -Programs_WebKit2APITests_TestDownloads_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp -Programs_WebKit2APITests_TestDownloads_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestDownloads_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestDownloads_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebViewEditor_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebViewEditor.cpp -Programs_WebKit2APITests_TestWebViewEditor_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebViewEditor_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebViewEditor_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestPrinting_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp -Programs_WebKit2APITests_TestPrinting_CPPFLAGS = $(webkit2_tests_cppflags) $(GTK_UNIX_PRINTING_CFLAGS) -Programs_WebKit2APITests_TestPrinting_LDADD = $(webkit2_tests_ldadd) $(GTK_UNIX_PRINTING_LIBS) -Programs_WebKit2APITests_TestPrinting_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitFaviconDatabase_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp -Programs_WebKit2APITests_TestWebKitFaviconDatabase_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitFaviconDatabase_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitFaviconDatabase_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitFindController_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp -Programs_WebKit2APITests_TestWebKitFindController_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitFindController_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitFindController_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestResources_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp -Programs_WebKit2APITests_TestResources_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestResources_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestResources_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestCookieManager_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestCookieManager.cpp -Programs_WebKit2APITests_TestCookieManager_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestCookieManager_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestCookieManager_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestInspector_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp -Programs_WebKit2APITests_TestInspector_CPPFLAGS = \ - -DWEBKIT_INSPECTOR_PATH=\"${shell pwd}/${top_builddir}/resources/inspector\" \ - $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestInspector_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestInspector_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestInspectorServer_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp -Programs_WebKit2APITests_TestInspectorServer_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestInspectorServer_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestInspectorServer_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestWebKitVersion_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitVersion.cpp -Programs_WebKit2APITests_TestWebKitVersion_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestWebKitVersion_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestWebKitVersion_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestContextMenu_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp -Programs_WebKit2APITests_TestContextMenu_CPPFLAGS = $(webkit2_tests_cppflags) -Programs_WebKit2APITests_TestContextMenu_LDADD = $(webkit2_tests_ldadd) -Programs_WebKit2APITests_TestContextMenu_LDFLAGS = $(webkit2_tests_ldflags) - -Programs_WebKit2APITests_TestSSL_SOURCES = \ - Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp -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 deleted file mode 100644 index 7c9dc900c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/InspectorTestServer.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics Ltd. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include <gtk/gtk.h> -#include <webkit2/webkit2.h> - -static void loadChangedCallback(WebKitWebView*, WebKitLoadEvent loadEvent, gpointer) -{ - // Send a message to the parent process when we're ready. - if (loadEvent == WEBKIT_LOAD_FINISHED) - g_print("OK"); -} - -int main(int argc, char** argv) -{ - gtk_init(&argc, &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); - webkit_web_view_load_html(webView, - "<html><body><p>WebKitGTK+ Inspector Test Server</p></body></html>", - "http://127.0.0.1:2999/"); - - GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(webView)); - gtk_widget_show_all(window); - - g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), 0); - g_signal_connect(webView, "load-changed", G_CALLBACK(loadChangedCallback), 0); - - gtk_main(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp deleted file mode 100644 index df3420492..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2011 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 "LoadTrackingTest.h" - -#include <webkit2/webkit2.h> - -static void loadChangedCallback(WebKitWebView* webView, WebKitLoadEvent loadEvent, LoadTrackingTest* test) -{ - switch (loadEvent) { - case WEBKIT_LOAD_STARTED: - g_assert(webkit_web_view_is_loading(webView)); - g_assert_cmpstr(test->m_activeURI.data(), ==, webkit_web_view_get_uri(webView)); - test->provisionalLoadStarted(); - break; - case WEBKIT_LOAD_REDIRECTED: - g_assert(webkit_web_view_is_loading(webView)); - test->m_activeURI = webkit_web_view_get_uri(webView); - if (!test->m_redirectURI.isNull()) - g_assert_cmpstr(test->m_redirectURI.data(), ==, test->m_activeURI.data()); - test->provisionalLoadReceivedServerRedirect(); - break; - case WEBKIT_LOAD_COMMITTED: { - g_assert(webkit_web_view_is_loading(webView)); - g_assert_cmpstr(test->m_activeURI.data(), ==, webkit_web_view_get_uri(webView)); - - // Check that on committed we always have a main resource with a response. - WebKitWebResource* resource = webkit_web_view_get_main_resource(webView); - g_assert(resource); - g_assert(webkit_web_resource_get_response(resource)); - - test->loadCommitted(); - break; - } - case WEBKIT_LOAD_FINISHED: - g_assert(!webkit_web_view_is_loading(webView)); - if (!test->m_loadFailed) - g_assert_cmpstr(test->m_activeURI.data(), ==, webkit_web_view_get_uri(webView)); - test->loadFinished(); - break; - default: - g_assert_not_reached(); - } -} - -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: - g_assert(!webkit_web_view_is_loading(webView)); - g_assert_cmpstr(test->m_activeURI.data(), ==, webkit_web_view_get_uri(webView)); - g_assert(error); - test->provisionalLoadFailed(failingURI, error); - break; - case WEBKIT_LOAD_COMMITTED: - g_assert(!webkit_web_view_is_loading(webView)); - g_assert_cmpstr(test->m_activeURI.data(), ==, webkit_web_view_get_uri(webView)); - g_assert(error); - test->loadFailed(failingURI, error); - break; - default: - g_assert_not_reached(); - } -} - -static void estimatedProgressChangedCallback(GObject*, GParamSpec*, LoadTrackingTest* test) -{ - test->estimatedProgressChanged(); -} - -LoadTrackingTest::LoadTrackingTest() - : m_runLoadUntilCompletion(false) - , m_loadFailed(false) -{ - g_signal_connect(m_webView, "load-changed", G_CALLBACK(loadChangedCallback), this); - g_signal_connect(m_webView, "load-failed", G_CALLBACK(loadFailedCallback), this); - g_signal_connect(m_webView, "notify::estimated-load-progress", G_CALLBACK(estimatedProgressChangedCallback), this); - - g_assert(!webkit_web_view_get_uri(m_webView)); -} - -LoadTrackingTest::~LoadTrackingTest() -{ - g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); -} - -void LoadTrackingTest::waitUntilLoadFinished() -{ - m_estimatedProgress = 0; - m_runLoadUntilCompletion = true; - g_main_loop_run(m_mainLoop); -} - -void LoadTrackingTest::provisionalLoadStarted() -{ - m_loadEvents.append(ProvisionalLoadStarted); -} - -void LoadTrackingTest::provisionalLoadReceivedServerRedirect() -{ - m_loadEvents.append(ProvisionalLoadReceivedServerRedirect); -} - -void LoadTrackingTest::provisionalLoadFailed(const gchar* failingURI, GError* error) -{ - m_loadEvents.append(ProvisionalLoadFailed); -} - -void LoadTrackingTest::loadCommitted() -{ - m_loadEvents.append(LoadCommitted); -} - -void LoadTrackingTest::loadFinished() -{ - m_loadEvents.append(LoadFinished); - if (m_runLoadUntilCompletion) - g_main_loop_quit(m_mainLoop); -} - -void LoadTrackingTest::loadFailed(const gchar* failingURI, GError* error) -{ - m_loadEvents.append(LoadFailed); -} - -void LoadTrackingTest::estimatedProgressChanged() -{ - double progress = webkit_web_view_get_estimated_load_progress(m_webView); - g_assert_cmpfloat(m_estimatedProgress, <, progress); - m_estimatedProgress = progress; -} - -void LoadTrackingTest::loadURI(const char* uri) -{ - m_loadEvents.clear(); - m_estimatedProgress = 0; - m_error.clear(); - WebViewTest::loadURI(uri); -} - -void LoadTrackingTest::loadHtml(const char* html, const char* baseURI) -{ - m_loadEvents.clear(); - m_estimatedProgress = 0; - m_error.clear(); - WebViewTest::loadHtml(html, baseURI); -} - -void LoadTrackingTest::loadPlainText(const char* plainText) -{ - m_loadEvents.clear(); - m_estimatedProgress = 0; - m_error.clear(); - WebViewTest::loadPlainText(plainText); -} - -void LoadTrackingTest::loadRequest(WebKitURIRequest* request) -{ - m_loadEvents.clear(); - m_estimatedProgress = 0; - m_error.clear(); - WebViewTest::loadRequest(request); -} - -void LoadTrackingTest::reload() -{ - m_loadEvents.clear(); - m_estimatedProgress = 0; - m_error.clear(); - webkit_web_view_reload(m_webView); -} - -void LoadTrackingTest::goBack() -{ - m_loadEvents.clear(); - m_estimatedProgress = 0; - m_error.clear(); - WebViewTest::goBack(); -} - -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 deleted file mode 100644 index a3cf7843d..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/LoadTrackingTest.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2011 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 LoadTrackingTest_h -#define LoadTrackingTest_h - -#include "TestMain.h" -#include "WebViewTest.h" -#include <wtf/Vector.h> - -class LoadTrackingTest : public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(LoadTrackingTest); - LoadTrackingTest(); - virtual ~LoadTrackingTest(); - void waitUntilLoadFinished(); - - virtual void provisionalLoadStarted(); - virtual void provisionalLoadReceivedServerRedirect(); - virtual void provisionalLoadFailed(const gchar* failingURI, GError*); - virtual void loadCommitted(); - virtual void loadFinished(); - virtual void loadFailed(const char* failingURI, GError*); - virtual void estimatedProgressChanged(); - - void loadURI(const char* uri); - void loadHtml(const char* html, const char* baseURI); - void loadPlainText(const char* plainText); - void loadRequest(WebKitURIRequest*); - void reload(); - void goBack(); - void goForward(); - - void setRedirectURI(const char* uri) { m_redirectURI = uri; } - - enum LoadEvents { - ProvisionalLoadStarted, - ProvisionalLoadReceivedServerRedirect, - ProvisionalLoadFailed, - LoadCommitted, - LoadFinished, - LoadFailed - }; - bool m_runLoadUntilCompletion; - bool m_loadFailed; - GOwnPtr<GError> m_error; - Vector<LoadEvents> m_loadEvents; - float m_estimatedProgress; - CString m_redirectURI; -}; - -#endif // LoadTrackingTest_h diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestBackForwardList.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestBackForwardList.cpp deleted file mode 100644 index b479366a4..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestBackForwardList.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitTestServer.h" -#include "WebViewTest.h" -#include <gtk/gtk.h> -#include <libsoup/soup.h> -#include <string.h> -#include <webkit2/webkit2.h> - -// Back forward list limit is 100 by default. -static const int kBackForwardListLimit = 100; - -static WebKitTestServer* kServer; - -static void serverCallback(SoupServer* server, SoupMessage* msg, const char* path, GHashTable* query, SoupClientContext* context, gpointer data) -{ - if (msg->method != SOUP_METHOD_GET) { - soup_message_set_status(msg, SOUP_STATUS_NOT_IMPLEMENTED); - return; - } - - if (g_str_has_suffix(path, "favicon.ico")) { - soup_message_set_status(msg, SOUP_STATUS_NOT_FOUND); - return; - } - - soup_message_set_status(msg, SOUP_STATUS_OK); - - char* body = g_strdup_printf("<html><title>%s</title><body>%s</body></html>", path + 1, path + 1); - soup_message_body_append(msg->response_body, SOUP_MEMORY_TAKE, body, strlen(body)); - - soup_message_body_complete(msg->response_body); -} - -class BackForwardListTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(BackForwardListTest); - - enum { - Backward, - Forward - }; - - enum { - CurrentItem = 1 << 0, - AddedItem = 1 << 1, - RemovedItems = 1 << 2 - }; - - static void checkItem(WebKitBackForwardListItem* item, const char* title, const char* uri, const char* originalURI) - { - g_assert(item); - g_assert_cmpstr(webkit_back_forward_list_item_get_uri(item), ==, uri); - g_assert_cmpstr(webkit_back_forward_list_item_get_title(item), == , title); - g_assert_cmpstr(webkit_back_forward_list_item_get_original_uri(item), ==, originalURI); - } - - static void checkItemIndex(WebKitBackForwardList* list) - { - g_assert(webkit_back_forward_list_get_nth_item(list, -1) == webkit_back_forward_list_get_back_item(list)); - g_assert(webkit_back_forward_list_get_nth_item(list, 0) == webkit_back_forward_list_get_current_item(list)); - g_assert(webkit_back_forward_list_get_nth_item(list, 1) == webkit_back_forward_list_get_forward_item(list)); - } - - static void checkList(WebKitBackForwardList* list, unsigned type, WebKitBackForwardListItem** items, unsigned nItems) - { - GList* listItems = type == BackForwardListTest::Backward ? webkit_back_forward_list_get_back_list(list) : - webkit_back_forward_list_get_forward_list(list); - g_assert(listItems); - - unsigned i = 0; - for (GList* listItem = listItems; listItem; listItem = g_list_next(listItem), i++) { - g_assert_cmpuint(i, <, nItems); - g_assert(listItem->data == items[i]); - } - g_list_free(listItems); - } - - static void backForwardListChanged(WebKitBackForwardList* list, WebKitBackForwardListItem* addedItem, GList* removedItems, BackForwardListTest* test) - { - test->m_hasChanged = true; - - if (test->m_changedFlags & BackForwardListTest::AddedItem) { - g_assert(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(addedItem)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(addedItem)); - } else - g_assert(!addedItem); - - if (test->m_changedFlags & BackForwardListTest::RemovedItems) { - g_assert(removedItems); - for (GList* iter = removedItems; iter; iter = iter->next) { - g_assert(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(iter->data)); - if (test->m_expectedRemovedItems) - g_assert(g_list_find(test->m_expectedRemovedItems, iter->data)); - } - - } else - g_assert(!removedItems); - } - - BackForwardListTest() - : m_list(webkit_web_view_get_back_forward_list(m_webView)) - , m_changedFlags(0) - , m_hasChanged(false) - , m_expectedRemovedItems(0) - { - g_signal_connect(m_list, "changed", G_CALLBACK(backForwardListChanged), this); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_list)); - } - - ~BackForwardListTest() - { - g_signal_handlers_disconnect_matched(m_list, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void waitUntilLoadFinished() - { - m_hasChanged = false; - WebViewTest::waitUntilLoadFinished(); - g_assert(m_hasChanged); - } - - void waitUntilLoadFinishedAndCheckRemovedItems(GList* removedItems) - { - m_expectedRemovedItems = removedItems; - waitUntilLoadFinished(); - m_expectedRemovedItems = 0; - } - - WebKitBackForwardList* m_list; - unsigned long m_changedFlags; - bool m_hasChanged; - GList* m_expectedRemovedItems; -}; - -static void testBackForwardListNavigation(BackForwardListTest* test, gconstpointer) -{ - WebKitBackForwardListItem* items[1]; - - g_assert(!webkit_web_view_can_go_back(test->m_webView)); - g_assert(!webkit_web_view_can_go_forward(test->m_webView)); - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 0); - g_assert(!webkit_back_forward_list_get_current_item(test->m_list)); - g_assert(!webkit_back_forward_list_get_back_item(test->m_list)); - g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); - BackForwardListTest::checkItemIndex(test->m_list); - g_assert(!webkit_back_forward_list_get_back_list(test->m_list)); - g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); - - CString uriPage1 = kServer->getURIForPath("/Page1"); - test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem; - test->loadURI(uriPage1.data()); - test->waitUntilLoadFinished(); - - g_assert(!webkit_web_view_can_go_back(test->m_webView)); - g_assert(!webkit_web_view_can_go_forward(test->m_webView)); - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 1); - WebKitBackForwardListItem* itemPage1 = webkit_back_forward_list_get_current_item(test->m_list); - BackForwardListTest::checkItem(itemPage1, "Page1", uriPage1.data(), uriPage1.data()); - g_assert(!webkit_back_forward_list_get_back_item(test->m_list)); - g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); - BackForwardListTest::checkItemIndex(test->m_list); - g_assert(!webkit_back_forward_list_get_back_list(test->m_list)); - g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); - - CString uriPage2 = kServer->getURIForPath("/Page2"); - test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem; - test->loadURI(uriPage2.data()); - test->waitUntilLoadFinished(); - - g_assert(webkit_web_view_can_go_back(test->m_webView)); - g_assert(!webkit_web_view_can_go_forward(test->m_webView)); - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 2); - WebKitBackForwardListItem* itemPage2 = webkit_back_forward_list_get_current_item(test->m_list); - BackForwardListTest::checkItem(itemPage2, "Page2", uriPage2.data(), uriPage2.data()); - g_assert(webkit_back_forward_list_get_back_item(test->m_list) == itemPage1); - g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); - BackForwardListTest::checkItemIndex(test->m_list); - items[0] = itemPage1; - BackForwardListTest::checkList(test->m_list, BackForwardListTest::Backward, items, 1); - g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); - - test->m_changedFlags = BackForwardListTest::CurrentItem; - test->goBack(); - test->waitUntilLoadFinished(); - - g_assert(!webkit_web_view_can_go_back(test->m_webView)); - g_assert(webkit_web_view_can_go_forward(test->m_webView)); - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 2); - g_assert(itemPage1 == webkit_back_forward_list_get_current_item(test->m_list)); - BackForwardListTest::checkItem(webkit_back_forward_list_get_current_item(test->m_list), "Page1", uriPage1.data(), uriPage1.data()); - g_assert(!webkit_back_forward_list_get_back_item(test->m_list)); - g_assert(webkit_back_forward_list_get_forward_item(test->m_list) == itemPage2); - BackForwardListTest::checkItemIndex(test->m_list); - g_assert(!webkit_back_forward_list_get_back_list(test->m_list)); - items[0] = itemPage2; - BackForwardListTest::checkList(test->m_list, BackForwardListTest::Forward, items, 1); - - test->m_changedFlags = BackForwardListTest::CurrentItem; - test->goForward(); - test->waitUntilLoadFinished(); - - g_assert(webkit_web_view_can_go_back(test->m_webView)); - g_assert(!webkit_web_view_can_go_forward(test->m_webView)); - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 2); - g_assert(itemPage2 == webkit_back_forward_list_get_current_item(test->m_list)); - BackForwardListTest::checkItem(webkit_back_forward_list_get_current_item(test->m_list), "Page2", uriPage2.data(), uriPage2.data()); - g_assert(webkit_back_forward_list_get_back_item(test->m_list) == itemPage1); - g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); - BackForwardListTest::checkItemIndex(test->m_list); - items[0] = itemPage1; - BackForwardListTest::checkList(test->m_list, BackForwardListTest::Backward, items, 1); - g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); - - test->m_changedFlags = BackForwardListTest::CurrentItem; - test->goToBackForwardListItem(itemPage1); - test->waitUntilLoadFinished(); - - g_assert(itemPage1 == webkit_back_forward_list_get_current_item(test->m_list)); -} - -static void testBackForwardListLimitAndCache(BackForwardListTest* test, gconstpointer) -{ - for (int i = 0; i < kBackForwardListLimit; i++) { - GOwnPtr<char> path(g_strdup_printf("/Page%d", i)); - test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem; - test->loadURI(kServer->getURIForPath(path.get()).data()); - test->waitUntilLoadFinished(); - } - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, kBackForwardListLimit); - WebKitBackForwardListItem* itemPageFirst = webkit_back_forward_list_get_nth_item(test->m_list, -(kBackForwardListLimit - 1)); - GOwnPtr<GList> removedItems(g_list_prepend(0, itemPageFirst)); - - GOwnPtr<char> path(g_strdup_printf("/Page%d", kBackForwardListLimit)); - test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem | BackForwardListTest::RemovedItems; - test->loadURI(kServer->getURIForPath(path.get()).data()); - test->waitUntilLoadFinishedAndCheckRemovedItems(removedItems.get()); - - g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, kBackForwardListLimit); -} - -void beforeAll() -{ - kServer = new WebKitTestServer(); - kServer->run(serverCallback); - - BackForwardListTest::add("BackForwardList", "navigation", testBackForwardListNavigation); - BackForwardListTest::add("BackForwardList", "list-limit-and-cache", testBackForwardListLimitAndCache); -} - -void afterAll() -{ - delete kServer; -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp deleted file mode 100644 index c361f8baf..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestContextMenu.cpp +++ /dev/null @@ -1,846 +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 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 "WebViewTest.h" -#include <wtf/gobject/GRefPtr.h> - -class ContextMenuTest: public WebViewTest { -public: - enum ContextMenuItemStateFlags { - Visible = 1 << 0, - Enabled = 1 << 1, - Checked = 1 << 2 - }; - - void checkContextMenuEvent(GdkEvent* event) - { - g_assert(event); - g_assert_cmpint(event->type, ==, GDK_BUTTON_PRESS); - g_assert_cmpint(event->button.button, ==, 3); - g_assert_cmpint(event->button.x, ==, m_menuPositionX); - g_assert_cmpint(event->button.y, ==, m_menuPositionY); - } - - static gboolean contextMenuCallback(WebKitWebView* webView, WebKitContextMenu* contextMenu, GdkEvent* event, WebKitHitTestResult* hitTestResult, ContextMenuTest* test) - { - g_assert(WEBKIT_IS_CONTEXT_MENU(contextMenu)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(contextMenu)); - test->checkContextMenuEvent(event); - g_assert(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(hitTestResult)); - - return test->contextMenu(contextMenu, event, hitTestResult); - } - - static void contextMenuDismissedCallback(WebKitWebView*, ContextMenuTest* test) - { - test->contextMenuDismissed(); - } - - ContextMenuTest() - : m_menuPositionX(0) - , m_menuPositionY(0) - { - g_signal_connect(m_webView, "context-menu", G_CALLBACK(contextMenuCallback), this); - g_signal_connect(m_webView, "context-menu-dismissed", G_CALLBACK(contextMenuDismissedCallback), this); - } - - ~ContextMenuTest() - { - g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - virtual bool contextMenu(WebKitContextMenu*, GdkEvent*, WebKitHitTestResult*) = 0; - - virtual void contextMenuDismissed() - { - quitMainLoop(); - } - - GtkMenu* getPopupMenu() - { - GOwnPtr<GList> toplevels(gtk_window_list_toplevels()); - for (GList* iter = toplevels.get(); iter; iter = g_list_next(iter)) { - if (!GTK_IS_WINDOW(iter->data)) - continue; - - GtkWidget* child = gtk_bin_get_child(GTK_BIN(iter->data)); - if (!GTK_IS_MENU(child)) - continue; - - if (gtk_menu_get_attach_widget(GTK_MENU(child)) == GTK_WIDGET(m_webView)) - return GTK_MENU(child); - } - g_assert_not_reached(); - return 0; - } - - bool shouldShowInputMethodsMenu() - { - GtkSettings* settings = gtk_widget_get_settings(GTK_WIDGET(m_webView)); - if (!settings) - return true; - - gboolean showInputMethodMenu; - g_object_get(settings, "gtk-show-input-method-menu", &showInputMethodMenu, NULL); - return showInputMethodMenu; - } - - void checkActionState(GtkAction* action, unsigned state) - { - if (state & Visible) - g_assert(gtk_action_get_visible(action)); - else - g_assert(!gtk_action_get_visible(action)); - - if (state & Enabled) - g_assert(gtk_action_get_sensitive(action)); - else - g_assert(!gtk_action_get_sensitive(action)); - - if (GTK_IS_TOGGLE_ACTION(action)) { - if (state & Checked) - g_assert(gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action))); - else - g_assert(!gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action))); - } - } - - GList* checkCurrentItemIsStockActionAndGetNext(GList* items, WebKitContextMenuAction stockAction, unsigned state) - { - g_assert(items); - g_assert(WEBKIT_IS_CONTEXT_MENU_ITEM(items->data)); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(items->data); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(item)); - - GtkAction* action = webkit_context_menu_item_get_action(item); - g_assert(GTK_IS_ACTION(action)); - - g_assert_cmpint(webkit_context_menu_item_get_stock_action(item), ==, stockAction); - - checkActionState(action, state); - - return g_list_next(items); - } - - GList* checkCurrentItemIsCustomActionAndGetNext(GList* items, const char* label, unsigned state) - { - g_assert(items); - g_assert(WEBKIT_IS_CONTEXT_MENU_ITEM(items->data)); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(items->data); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(item)); - - GtkAction* action = webkit_context_menu_item_get_action(item); - g_assert(GTK_IS_ACTION(action)); - - g_assert_cmpint(webkit_context_menu_item_get_stock_action(item), ==, WEBKIT_CONTEXT_MENU_ACTION_CUSTOM); - g_assert_cmpstr(gtk_action_get_label(action), ==, label); - - checkActionState(action, state); - - return g_list_next(items); - } - - GList* checkCurrentItemIsSubMenuAndGetNext(GList* items, const char* label, unsigned state, GList** subMenuIter) - { - g_assert(items); - g_assert(WEBKIT_IS_CONTEXT_MENU_ITEM(items->data)); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(items->data); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(item)); - - GtkAction* action = webkit_context_menu_item_get_action(item); - g_assert(GTK_IS_ACTION(action)); - - g_assert_cmpstr(gtk_action_get_label(action), ==, label); - checkActionState(action, state); - - WebKitContextMenu* subMenu = webkit_context_menu_item_get_submenu(item); - g_assert(WEBKIT_IS_CONTEXT_MENU(subMenu)); - if (subMenuIter) - *subMenuIter = webkit_context_menu_get_items(subMenu); - - return g_list_next(items); - } - - GList* checkCurrentItemIsSeparatorAndGetNext(GList* items) - { - g_assert(items); - g_assert(WEBKIT_IS_CONTEXT_MENU_ITEM(items->data)); - - WebKitContextMenuItem* item = WEBKIT_CONTEXT_MENU_ITEM(items->data); - g_assert(webkit_context_menu_item_is_separator(item)); - - return g_list_next(items); - } - - static gboolean doRightClickIdleCallback(ContextMenuTest* test) - { - test->clickMouseButton(test->m_menuPositionX, test->m_menuPositionY, 3); - return FALSE; - } - - void showContextMenuAtPositionAndWaitUntilFinished(int x, int y) - { - m_menuPositionX = x; - m_menuPositionY = y; - g_idle_add(reinterpret_cast<GSourceFunc>(doRightClickIdleCallback), this); - g_main_loop_run(m_mainLoop); - } - - void showContextMenuAndWaitUntilFinished() - { - showContextMenuAtPositionAndWaitUntilFinished(0, 0); - } - - static gboolean simulateEscKeyIdleCallback(ContextMenuTest* test) - { - test->keyStroke(GDK_KEY_Escape); - return FALSE; - } - - void dismissContextMenuAndWaitUntilFinished() - { - g_idle_add(reinterpret_cast<GSourceFunc>(simulateEscKeyIdleCallback), this); - g_main_loop_run(m_mainLoop); - } - - double m_menuPositionX; - double m_menuPositionY; -}; - -class ContextMenuDefaultTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuDefaultTest); - - enum DefaultMenuType { - Navigation, - Link, - Image, - LinkImage, - Video, - Editable - }; - - ContextMenuDefaultTest() - : m_expectedMenuType(Navigation) - { - } - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent* event, WebKitHitTestResult* hitTestResult) - { - GList* iter = webkit_context_menu_get_items(contextMenu); - - switch (m_expectedMenuType) { - case Navigation: - 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)); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_GO_BACK, Visible); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD, Visible); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_STOP, Visible); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_RELOAD, Visible | Enabled); - break; - case Link: - 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)); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD, Visible | Enabled); - break; - case Image: - 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)); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD, Visible | Enabled); - break; - case LinkImage: - 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)); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK_IN_NEW_WINDOW, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_LINK_TO_DISK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_LINK_TO_CLIPBOARD, Visible | Enabled); - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_IMAGE_IN_NEW_WINDOW, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_DOWNLOAD_IMAGE_TO_DISK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_TO_CLIPBOARD, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_IMAGE_URL_TO_CLIPBOARD, Visible | Enabled); - break; - case Video: - 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)); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_MEDIA_PLAY, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_MEDIA_MUTE, Visible); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_CONTROLS, Visible | Enabled | Checked); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_TOGGLE_MEDIA_LOOP, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_ENTER_VIDEO_FULLSCREEN, Visible); - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY_VIDEO_LINK_TO_CLIPBOARD, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_OPEN_VIDEO_IN_NEW_WINDOW, Visible | Enabled); - break; - case Editable: - 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)); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_CUT, Visible); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_COPY, Visible); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_PASTE, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_DELETE, Visible); - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_SELECT_ALL, Visible | Enabled); - if (shouldShowInputMethodsMenu()) { - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_INPUT_METHODS, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_UNICODE, Visible | Enabled); - } - break; - default: - g_assert_not_reached(); - } - - if (webkit_settings_get_enable_developer_extras(webkit_web_view_get_settings(m_webView))) { - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT, Visible | Enabled); - } - g_assert(!iter); - - quitMainLoop(); - - return true; - } - - DefaultMenuType m_expectedMenuType; -}; - -static void testContextMenuDefaultMenu(ContextMenuDefaultTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - const char* linksHTML = - "<html><body>" - " <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>" - " <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(); - - // Context menu for document. - test->m_expectedMenuType = ContextMenuDefaultTest::Navigation; - test->showContextMenuAtPositionAndWaitUntilFinished(0, 0); - - // Context menu for link. - test->m_expectedMenuType = ContextMenuDefaultTest::Link; - test->showContextMenuAtPositionAndWaitUntilFinished(1, 1); - - // Context menu for image. - test->m_expectedMenuType = ContextMenuDefaultTest::Image; - test->showContextMenuAtPositionAndWaitUntilFinished(1, 10); - - // Enable developer extras now, so that inspector element - // will be shown in the default context menu. - webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(test->m_webView), TRUE); - - // Context menu for image link. - test->m_expectedMenuType = ContextMenuDefaultTest::LinkImage; - test->showContextMenuAtPositionAndWaitUntilFinished(1, 20); - - // Context menu for image video. - test->m_expectedMenuType = ContextMenuDefaultTest::Video; - test->showContextMenuAtPositionAndWaitUntilFinished(1, 50); - - // Context menu for editable. - test->m_expectedMenuType = ContextMenuDefaultTest::Editable; - test->showContextMenuAtPositionAndWaitUntilFinished(5, 35); -} - -class ContextMenuCustomTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuCustomTest); - - ContextMenuCustomTest() - : m_itemToActivateLabel(0) - , m_activated(false) - , m_toggled(false) - { - } - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent*, WebKitHitTestResult* hitTestResult) - { - // Append our custom item to the default menu. - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new(m_action.get())); - quitMainLoop(); - - return false; - } - - GtkMenuItem* getMenuItem(GtkMenu* menu, const gchar* itemLabel) - { - GOwnPtr<GList> items(gtk_container_get_children(GTK_CONTAINER(menu))); - for (GList* iter = items.get(); iter; iter = g_list_next(iter)) { - GtkMenuItem* child = GTK_MENU_ITEM(iter->data); - if (g_str_equal(itemLabel, gtk_menu_item_get_label(child))) - return child; - } - g_assert_not_reached(); - return 0; - } - - void activateMenuItem() - { - g_assert(m_itemToActivateLabel); - GtkMenu* menu = getPopupMenu(); - GtkMenuItem* item = getMenuItem(menu, m_itemToActivateLabel); - gtk_menu_shell_activate_item(GTK_MENU_SHELL(menu), GTK_WIDGET(item), TRUE); - m_itemToActivateLabel = 0; - } - - static gboolean activateMenuItemIdleCallback(gpointer userData) - { - ContextMenuCustomTest* test = static_cast<ContextMenuCustomTest*>(userData); - test->activateMenuItem(); - return FALSE; - } - - void activateCustomMenuItemAndWaitUntilActivated(const char* actionLabel) - { - m_activated = m_toggled = false; - m_itemToActivateLabel = actionLabel; - g_idle_add(activateMenuItemIdleCallback, this); - g_main_loop_run(m_mainLoop); - } - - void toggleCustomMenuItemAndWaitUntilToggled(const char* actionLabel) - { - activateCustomMenuItemAndWaitUntilActivated(actionLabel); - } - - static void actionActivatedCallback(GtkAction*, ContextMenuCustomTest* test) - { - test->m_activated = true; - } - - static void actionToggledCallback(GtkAction*, ContextMenuCustomTest* test) - { - test->m_toggled = true; - } - - void setAction(GtkAction* action) - { - m_action = action; - if (GTK_IS_TOGGLE_ACTION(action)) - g_signal_connect(action, "toggled", G_CALLBACK(actionToggledCallback), this); - else - g_signal_connect(action, "activate", G_CALLBACK(actionActivatedCallback), this); - } - - GRefPtr<GtkAction> m_action; - const char* m_itemToActivateLabel; - bool m_activated; - bool m_toggled; -}; - -static void testContextMenuPopulateMenu(ContextMenuCustomTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - test->loadHtml("<html><body>WebKitGTK+ Context menu tests</body></html>", "file:///"); - test->waitUntilLoadFinished(); - - // Create a custom menu item. - GRefPtr<GtkAction> action = adoptGRef(gtk_action_new("WebKitGTK+CustomAction", "Custom _Action", 0, 0)); - test->setAction(action.get()); - test->showContextMenuAndWaitUntilFinished(); - test->activateCustomMenuItemAndWaitUntilActivated(gtk_action_get_label(action.get())); - g_assert(test->m_activated); - g_assert(!test->m_toggled); - - // Create a custom toggle menu item. - GRefPtr<GtkAction> toggleAction = adoptGRef(GTK_ACTION(gtk_toggle_action_new("WebKitGTK+CustomToggleAction", "Custom _Toggle Action", 0, 0))); - test->setAction(toggleAction.get()); - test->showContextMenuAndWaitUntilFinished(); - test->toggleCustomMenuItemAndWaitUntilToggled(gtk_action_get_label(toggleAction.get())); - g_assert(!test->m_activated); - g_assert(test->m_toggled); -} - -class ContextMenuCustomFullTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuCustomFullTest); - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent*, WebKitHitTestResult*) - { - // Clear proposed menu and build our own. - webkit_context_menu_remove_all(contextMenu); - g_assert_cmpint(webkit_context_menu_get_n_items(contextMenu), ==, 0); - - // Add actions from stock. - webkit_context_menu_prepend(contextMenu, webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_GO_BACK)); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD)); - webkit_context_menu_insert(contextMenu, webkit_context_menu_item_new_separator(), 2); - - // Add custom actions. - GRefPtr<GtkAction> action = adoptGRef(gtk_action_new("WebKitGTK+CustomAction", "Custom _Action", 0, 0)); - gtk_action_set_sensitive(action.get(), FALSE); - webkit_context_menu_insert(contextMenu, webkit_context_menu_item_new(action.get()), -1); - GRefPtr<GtkAction> toggleAction = adoptGRef(GTK_ACTION(gtk_toggle_action_new("WebKitGTK+CustomToggleAction", "Custom _Toggle Action", 0, 0))); - gtk_toggle_action_set_active(GTK_TOGGLE_ACTION(toggleAction.get()), TRUE); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new(toggleAction.get())); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - - // Add a submenu. - GRefPtr<WebKitContextMenu> subMenu = adoptGRef(webkit_context_menu_new()); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(subMenu.get())); - webkit_context_menu_insert(subMenu.get(), webkit_context_menu_item_new_from_stock_action_with_label(WEBKIT_CONTEXT_MENU_ACTION_STOP, "Stop Load"), 0); - webkit_context_menu_insert(subMenu.get(), webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_RELOAD), -1); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_with_submenu("Load options", subMenu.get())); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - - // Move Load submenu before custom actions. - webkit_context_menu_move_item(contextMenu, webkit_context_menu_last(contextMenu), 3); - webkit_context_menu_move_item(contextMenu, webkit_context_menu_last(contextMenu), 3); - - // If last item is a separator, remove it. - if (webkit_context_menu_item_is_separator(webkit_context_menu_last(contextMenu))) - webkit_context_menu_remove(contextMenu, webkit_context_menu_last(contextMenu)); - - // Check the menu. - GList* iter = webkit_context_menu_get_items(contextMenu); - - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_GO_BACK, Visible | Enabled); - iter = checkCurrentItemIsStockActionAndGetNext(iter, WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD, Visible | Enabled); - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - - GList* subMenuIter = 0; - iter = checkCurrentItemIsSubMenuAndGetNext(iter, "Load options", Visible | Enabled, &subMenuIter); - subMenuIter = checkCurrentItemIsStockActionAndGetNext(subMenuIter, WEBKIT_CONTEXT_MENU_ACTION_STOP, Visible | Enabled); - subMenuIter = checkCurrentItemIsStockActionAndGetNext(subMenuIter, WEBKIT_CONTEXT_MENU_ACTION_RELOAD, Visible | Enabled); - iter = checkCurrentItemIsSeparatorAndGetNext(iter); - - iter = checkCurrentItemIsCustomActionAndGetNext(iter, "Custom _Action", Visible); - iter = checkCurrentItemIsCustomActionAndGetNext(iter, "Custom _Toggle Action", Visible | Enabled | Checked); - g_assert(!iter); - - quitMainLoop(); - - return true; - } -}; - -static void testContextMenuCustomMenu(ContextMenuCustomFullTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - test->loadHtml("<html><body>WebKitGTK+ Context menu tests</body></html>", "file:///"); - test->waitUntilLoadFinished(); - - test->showContextMenuAndWaitUntilFinished(); -} - -class ContextMenuDisabledTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuDisabledTest); - - enum DisableMode { - IgnoreClicks, - IgnoreDefaultMenu - }; - - static gboolean buttonPressEventCallback(GtkWidget*, GdkEvent* event, ContextMenuDisabledTest* test) - { - if (event->button.button != 3) - return FALSE; - return test->rightButtonPressed(); - } - - ContextMenuDisabledTest() - : m_disableMode(IgnoreClicks) - { - g_signal_connect(m_webView, "button-press-event", G_CALLBACK(buttonPressEventCallback), this); - } - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent*, WebKitHitTestResult*) - { - if (m_disableMode == IgnoreClicks) - g_assert_not_reached(); - else - quitMainLoop(); - - return true; - } - - bool rightButtonPressed() - { - if (m_disableMode == IgnoreClicks) { - quitMainLoopAfterProcessingPendingEvents(); - return true; - } - return false; - } - - DisableMode m_disableMode; -}; - -static void testContextMenuDisableMenu(ContextMenuDisabledTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - test->loadHtml("<html><body>WebKitGTK+ Context menu tests</body></html>", "file:///"); - test->waitUntilLoadFinished(); - - test->m_disableMode = ContextMenuDisabledTest::IgnoreDefaultMenu; - test->showContextMenuAndWaitUntilFinished(); - - test->m_disableMode = ContextMenuDisabledTest::IgnoreClicks; - test->showContextMenuAndWaitUntilFinished(); -} - -class ContextMenuSubmenuTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuSubmenuTest); - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent*, WebKitHitTestResult*) - { - size_t menuSize = webkit_context_menu_get_n_items(contextMenu); - GRefPtr<WebKitContextMenu> subMenu = adoptGRef(webkit_context_menu_new()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_with_submenu("SubMenuItem", subMenu.get())); - g_assert_cmpuint(webkit_context_menu_get_n_items(contextMenu), ==, menuSize + 1); - - GRefPtr<WebKitContextMenu> subMenu2 = adoptGRef(webkit_context_menu_new()); - GRefPtr<WebKitContextMenuItem> item = webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_OPEN_LINK); - - // Add submenu to newly created item. - g_assert(!webkit_context_menu_item_get_submenu(item.get())); - webkit_context_menu_item_set_submenu(item.get(), subMenu2.get()); - g_assert(webkit_context_menu_item_get_submenu(item.get()) == subMenu2.get()); - - // Replace the submenu. - webkit_context_menu_item_set_submenu(item.get(), 0); - g_assert(!webkit_context_menu_item_get_submenu(item.get())); - - // Try to add a submenu already added to another item. - removeLogFatalFlag(G_LOG_LEVEL_WARNING); - webkit_context_menu_item_set_submenu(item.get(), subMenu.get()); - addLogFatalFlag(G_LOG_LEVEL_WARNING); - g_assert(!webkit_context_menu_item_get_submenu(item.get())); - - // A removed submenu shouldn't have a parent. - webkit_context_menu_item_set_submenu(item.get(), subMenu2.get()); - g_assert(webkit_context_menu_item_get_submenu(item.get()) == subMenu2.get()); - - quitMainLoop(); - - return true; - } -}; - -static void testContextMenuSubMenu(ContextMenuSubmenuTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - test->loadHtml("<html><body>WebKitGTK+ Context menu tests</body></html>", "file:///"); - test->waitUntilLoadFinished(); - - test->showContextMenuAndWaitUntilFinished(); -} - -class ContextMenuDismissedTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuDismissedTest); - - ContextMenuDismissedTest() - : m_dismissed(false) - { - } - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent*, WebKitHitTestResult*) - { - quitMainLoop(); - // Show the default context menu. - return false; - } - - void contextMenuDismissed() - { - m_dismissed = true; - ContextMenuTest::contextMenuDismissed(); - } - - void showContextMenuAndWaitUntilDismissed() - { - showContextMenuAndWaitUntilFinished(); - dismissContextMenuAndWaitUntilFinished(); - } - - bool m_dismissed; -}; - -static void testContextMenuDismissed(ContextMenuDismissedTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - test->loadHtml("<html><body>WebKitGTK+ Context menu tests</body></html>", "file:///"); - test->waitUntilLoadFinished(); - - test->showContextMenuAndWaitUntilDismissed(); - g_assert(test->m_dismissed); -} - -class ContextMenuSmartSeparatorsTest: public ContextMenuTest { -public: - MAKE_GLIB_TEST_FIXTURE(ContextMenuSmartSeparatorsTest); - - bool contextMenu(WebKitContextMenu* contextMenu, GdkEvent*, WebKitHitTestResult*) - { - webkit_context_menu_remove_all(contextMenu); - - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_GO_BACK)); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD)); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_COPY)); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_from_stock_action(WEBKIT_CONTEXT_MENU_ACTION_INSPECT_ELEMENT)); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - webkit_context_menu_append(contextMenu, webkit_context_menu_item_new_separator()); - - quitMainLoop(); - - return false; - } - - GtkMenu* showContextMenuAndGetGtkMenu() - { - showContextMenuAndWaitUntilFinished(); - return getPopupMenu(); - } -}; - -static void testContextMenuSmartSeparators(ContextMenuSmartSeparatorsTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - test->loadHtml("<html><body>WebKitGTK+ Context menu tests</body></html>", "file:///"); - test->waitUntilLoadFinished(); - - GtkMenu* menu = test->showContextMenuAndGetGtkMenu(); - g_assert(menu); - - // Leading and trailing separators are not added to the context menu. - GOwnPtr<GList> menuItems(gtk_container_get_children(GTK_CONTAINER(menu))); - g_assert_cmpuint(g_list_length(menuItems.get()), ==, 6); - GtkWidget* item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 0)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 1)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 2)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 3)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 4)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 5)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - - // Hiding a menu item between two separators hides the following separator. - GtkAction* action = gtk_activatable_get_related_action(GTK_ACTIVATABLE(g_list_nth_data(menuItems.get(), 3))); - gtk_action_set_visible(action, FALSE); - menuItems.set(gtk_container_get_children(GTK_CONTAINER(menu))); - g_assert_cmpuint(g_list_length(menuItems.get()), ==, 6); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 0)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 1)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 2)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 3)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && !gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 4)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && !gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 5)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - gtk_action_set_visible(action, TRUE); - - // Showing an action between two separators shows the hidden separator. - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 0)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 1)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 2)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 3)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 4)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 5)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - - // Trailing separators are hidden too. - action = gtk_activatable_get_related_action(GTK_ACTIVATABLE(g_list_nth_data(menuItems.get(), 5))); - gtk_action_set_visible(action, FALSE); - menuItems.set(gtk_container_get_children(GTK_CONTAINER(menu))); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 0)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 1)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 2)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 3)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 4)); - g_assert(GTK_IS_SEPARATOR_MENU_ITEM(item) && !gtk_widget_get_visible(item)); - item = GTK_WIDGET(g_list_nth_data(menuItems.get(), 5)); - g_assert(!GTK_IS_SEPARATOR_MENU_ITEM(item) && !gtk_widget_get_visible(item)); -} - -void beforeAll() -{ - ContextMenuDefaultTest::add("WebKitWebView", "default-menu", testContextMenuDefaultMenu); - ContextMenuCustomTest::add("WebKitWebView", "populate-menu", testContextMenuPopulateMenu); - ContextMenuCustomFullTest::add("WebKitWebView", "custom-menu", testContextMenuCustomMenu); - ContextMenuDisabledTest::add("WebKitWebView", "disable-menu", testContextMenuDisableMenu); - ContextMenuSubmenuTest::add("WebKitWebView", "submenu", testContextMenuSubMenu); - ContextMenuDismissedTest::add("WebKitWebView", "menu-dismissed", testContextMenuDismissed); - ContextMenuSmartSeparatorsTest::add("WebKitWebView", "smart-separators", testContextMenuSmartSeparators); -} - -void afterAll() -{ -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestCookieManager.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestCookieManager.cpp deleted file mode 100644 index adc6b5b9b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestCookieManager.cpp +++ /dev/null @@ -1,331 +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 "WebKitTestServer.h" -#include "WebViewTest.h" -#include <glib/gstdio.h> - -static WebKitTestServer* kServer; -static char* kTempDirectory; - -static const char* kFirstPartyDomain = "127.0.0.1"; -static const char* kThirdPartyDomain = "localhost"; -static const char* kIndexHtmlFormat = - "<html><body>" - " <p>WebKitGTK+ Cookie Manager test</p>" - " <img src='http://localhost:%u/image.png' width=5 height=5></img>" - "</body></html>"; - -class CookieManagerTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(CookieManagerTest); - - static void cookiesChangedCallback(WebKitCookieManager*, CookieManagerTest* test) - { - test->m_cookiesChanged = true; - if (test->m_finishLoopWhenCookiesChange) - g_main_loop_quit(test->m_mainLoop); - } - - CookieManagerTest() - : WebViewTest() - , m_cookieManager(webkit_web_context_get_cookie_manager(webkit_web_view_get_context(m_webView))) - , m_acceptPolicy(WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY) - , m_domains(0) - , m_cookiesChanged(false) - , m_finishLoopWhenCookiesChange(false) - { - g_signal_connect(m_cookieManager, "changed", G_CALLBACK(cookiesChangedCallback), this); - } - - ~CookieManagerTest() - { - g_strfreev(m_domains); - g_signal_handlers_disconnect_matched(m_cookieManager, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - if (m_cookiesTextFile) - g_unlink(m_cookiesTextFile.get()); - if (m_cookiesSQLiteFile) - g_unlink(m_cookiesSQLiteFile.get()); - } - - void setPersistentStorage(WebKitCookiePersistentStorage storage) - { - const char* filename = 0; - switch (storage) { - case WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT: - if (!m_cookiesTextFile) - m_cookiesTextFile.set(g_build_filename(kTempDirectory, "cookies.txt", NULL)); - filename = m_cookiesTextFile.get(); - break; - case WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE: - if (!m_cookiesSQLiteFile) - m_cookiesSQLiteFile.set(g_build_filename(kTempDirectory, "cookies.db", NULL)); - filename = m_cookiesSQLiteFile.get(); - break; - default: - g_assert_not_reached(); - } - webkit_cookie_manager_set_persistent_storage(m_cookieManager, filename, storage); - } - - static void getAcceptPolicyReadyCallback(GObject* object, GAsyncResult* result, gpointer userData) - { - GOwnPtr<GError> error; - WebKitCookieAcceptPolicy policy = webkit_cookie_manager_get_accept_policy_finish(WEBKIT_COOKIE_MANAGER(object), result, &error.outPtr()); - g_assert(!error.get()); - - CookieManagerTest* test = static_cast<CookieManagerTest*>(userData); - test->m_acceptPolicy = policy; - g_main_loop_quit(test->m_mainLoop); - } - - WebKitCookieAcceptPolicy getAcceptPolicy() - { - m_acceptPolicy = WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY; - webkit_cookie_manager_get_accept_policy(m_cookieManager, 0, getAcceptPolicyReadyCallback, this); - g_main_loop_run(m_mainLoop); - - return m_acceptPolicy; - } - - void setAcceptPolicy(WebKitCookieAcceptPolicy policy) - { - webkit_cookie_manager_set_accept_policy(m_cookieManager, policy); - } - - static void getDomainsReadyCallback(GObject* object, GAsyncResult* result, gpointer userData) - { - GOwnPtr<GError> error; - char** domains = webkit_cookie_manager_get_domains_with_cookies_finish(WEBKIT_COOKIE_MANAGER(object), result, &error.outPtr()); - g_assert(!error.get()); - - CookieManagerTest* test = static_cast<CookieManagerTest*>(userData); - test->m_domains = domains; - g_main_loop_quit(test->m_mainLoop); - } - - char** getDomains() - { - g_strfreev(m_domains); - m_domains = 0; - webkit_cookie_manager_get_domains_with_cookies(m_cookieManager, 0, getDomainsReadyCallback, this); - g_main_loop_run(m_mainLoop); - - return m_domains; - } - - bool hasDomain(const char* domain) - { - if (!m_domains) - return false; - - for (size_t i = 0; m_domains[i]; ++i) - if (g_str_equal(m_domains[i], domain)) - return true; - return false; - } - - void deleteCookiesForDomain(const char* domain) - { - webkit_cookie_manager_delete_cookies_for_domain(m_cookieManager, domain); - } - - void deleteAllCookies() - { - webkit_cookie_manager_delete_all_cookies(m_cookieManager); - } - - void waitUntilCookiesChanged() - { - m_cookiesChanged = false; - m_finishLoopWhenCookiesChange = true; - g_main_loop_run(m_mainLoop); - m_finishLoopWhenCookiesChange = false; - } - - WebKitCookieManager* m_cookieManager; - WebKitCookieAcceptPolicy m_acceptPolicy; - char** m_domains; - bool m_cookiesChanged; - bool m_finishLoopWhenCookiesChange; - GOwnPtr<char> m_cookiesTextFile; - GOwnPtr<char> m_cookiesSQLiteFile; -}; - -static void testCookieManagerAcceptPolicy(CookieManagerTest* test, gconstpointer) -{ - // Default policy is NO_THIRD_PARTY. - g_assert_cmpint(test->getAcceptPolicy(), ==, WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY); - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - char** domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 1); - g_assert_cmpstr(domains[0], ==, kFirstPartyDomain); - test->deleteAllCookies(); - - test->setAcceptPolicy(WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS); - g_assert_cmpint(test->getAcceptPolicy(), ==, WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS); - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 2); - g_assert(test->hasDomain(kFirstPartyDomain)); - g_assert(test->hasDomain(kThirdPartyDomain)); - test->deleteAllCookies(); - - test->setAcceptPolicy(WEBKIT_COOKIE_POLICY_ACCEPT_NEVER); - g_assert_cmpint(test->getAcceptPolicy(), ==, WEBKIT_COOKIE_POLICY_ACCEPT_NEVER); - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 0); -} - -static void testCookieManagerDeleteCookies(CookieManagerTest* test, gconstpointer) -{ - test->setAcceptPolicy(WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS); - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 2); - - // Delete first party cookies. - test->deleteCookiesForDomain(kFirstPartyDomain); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 1); - - // Delete third party cookies. - test->deleteCookiesForDomain(kThirdPartyDomain); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 0); - - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 2); - - // Delete all cookies. - test->deleteAllCookies(); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 0); -} - -static void testCookieManagerCookiesChanged(CookieManagerTest* test, gconstpointer) -{ - g_assert(!test->m_cookiesChanged); - test->setAcceptPolicy(WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS); - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - g_assert(test->m_cookiesChanged); - - test->deleteCookiesForDomain(kFirstPartyDomain); - test->waitUntilCookiesChanged(); - g_assert(test->m_cookiesChanged); - - test->deleteAllCookies(); - test->waitUntilCookiesChanged(); - g_assert(test->m_cookiesChanged); -} - -static void testCookieManagerPersistentStorage(CookieManagerTest* test, gconstpointer) -{ - test->setAcceptPolicy(WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS); - - // Text storage using a new file. - test->setPersistentStorage(WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT); - char** domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 0); - - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - g_assert(test->m_cookiesChanged); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 2); - - - // SQLite storage using a new file. - test->setPersistentStorage(WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 0); - - test->loadURI(kServer->getURIForPath("/index.html").data()); - test->waitUntilLoadFinished(); - g_assert(test->m_cookiesChanged); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 2); - - // Text storage using an existing file. - test->setPersistentStorage(WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 2); - test->deleteAllCookies(); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 0); - - // SQLite storage with an existing file. - test->setPersistentStorage(WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE); - domains = test->getDomains(); - g_assert(domains); - g_assert_cmpint(g_strv_length(domains), ==, 2); - test->deleteAllCookies(); - g_assert_cmpint(g_strv_length(test->getDomains()), ==, 0); -} - -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 (g_str_equal(path, "/index.html")) { - char* indexHtml = g_strdup_printf(kIndexHtmlFormat, 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, indexHtml, strlen(indexHtml)); - } else if (g_str_equal(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); -} - -void beforeAll() -{ - kServer = new WebKitTestServer(); - kServer->run(serverCallback); - - kTempDirectory = g_dir_make_tmp("WebKit2Tests-XXXXXX", 0); - g_assert(kTempDirectory); - - CookieManagerTest::add("WebKitCookieManager", "accept-policy", testCookieManagerAcceptPolicy); - CookieManagerTest::add("WebKitCookieManager", "delete-cookies", testCookieManagerDeleteCookies); - CookieManagerTest::add("WebKitCookieManager", "cookies-changed", testCookieManagerCookiesChanged); - CookieManagerTest::add("WebKitCookieManager", "persistent-storage", testCookieManagerPersistentStorage); -} - -void afterAll() -{ - delete kServer; - g_rmdir(kTempDirectory); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp deleted file mode 100644 index ce159906c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestDownloads.cpp +++ /dev/null @@ -1,522 +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 "WebKitTestServer.h" -#include "WebViewTest.h" -#include <glib/gstdio.h> -#include <gtk/gtk.h> -#include <libsoup/soup.h> -#include <string.h> -#include <webkit2/webkit2.h> -#include <wtf/Vector.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -static char* kTempDirectory; - -class DownloadTest: public Test { -public: - MAKE_GLIB_TEST_FIXTURE(DownloadTest); - - enum DownloadEvent { - Started, - ReceivedResponse, - CreatedDestination, - ReceivedData, - Failed, - Finished - }; - - static void receivedResponseCallback(WebKitDownload* download, GParamSpec*, DownloadTest* test) - { - g_assert(webkit_download_get_response(download)); - test->receivedResponse(download); - } - - static gboolean createdDestinationCallback(WebKitDownload* download, const gchar* destination, DownloadTest* test) - { - g_assert(webkit_download_get_destination(download)); - g_assert_cmpstr(webkit_download_get_destination(download), ==, destination); - test->createdDestination(download, destination); - return TRUE; - } - - static gboolean receivedDataCallback(WebKitDownload* download, guint64 dataLength, DownloadTest* test) - { - test->receivedData(download, dataLength); - return TRUE; - } - - static gboolean finishedCallback(WebKitDownload* download, DownloadTest* test) - { - test->finished(download); - return TRUE; - } - - static gboolean failedCallback(WebKitDownload* download, GError* error, DownloadTest* test) - { - g_assert(error); - test->failed(download, error); - return TRUE; - } - - static gboolean decideDestinationCallback(WebKitDownload* download, const gchar* suggestedFilename, DownloadTest* test) - { - g_assert(suggestedFilename); - test->decideDestination(download, suggestedFilename); - return TRUE; - } - - static void downloadStartedCallback(WebKitWebContext* context, WebKitDownload* download, DownloadTest* test) - { - g_assert(webkit_download_get_request(download)); - test->started(download); - g_signal_connect(download, "notify::response", G_CALLBACK(receivedResponseCallback), test); - g_signal_connect(download, "created-destination", G_CALLBACK(createdDestinationCallback), test); - g_signal_connect(download, "received-data", G_CALLBACK(receivedDataCallback), test); - g_signal_connect(download, "finished", G_CALLBACK(finishedCallback), test); - g_signal_connect(download, "failed", G_CALLBACK(failedCallback), test); - g_signal_connect(download, "decide-destination", G_CALLBACK(decideDestinationCallback), test); - } - - DownloadTest() - : m_webContext(webkit_web_context_get_default()) - , m_mainLoop(g_main_loop_new(0, TRUE)) - , m_downloadSize(0) - { - g_signal_connect(m_webContext, "download-started", G_CALLBACK(downloadStartedCallback), this); - } - - ~DownloadTest() - { - g_signal_handlers_disconnect_matched(m_webContext, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - g_main_loop_unref(m_mainLoop); - } - - virtual void started(WebKitDownload* download) - { - m_downloadEvents.append(Started); - } - - virtual void receivedResponse(WebKitDownload* download) - { - m_downloadEvents.append(ReceivedResponse); - } - - virtual void createdDestination(WebKitDownload* download, const char* destination) - { - m_downloadEvents.append(CreatedDestination); - } - - virtual void receivedData(WebKitDownload* download, guint64 dataLength) - { - m_downloadSize += dataLength; - if (!m_downloadEvents.contains(ReceivedData)) - m_downloadEvents.append(ReceivedData); - } - - virtual void finished(WebKitDownload* download) - { - g_assert_cmpuint(m_downloadSize, ==, webkit_download_get_received_data_length(download)); - m_downloadEvents.append(Finished); - g_main_loop_quit(m_mainLoop); - } - - virtual void failed(WebKitDownload* download, GError* error) - { - m_downloadEvents.append(Failed); - } - - virtual void decideDestination(WebKitDownload* download, const gchar* suggestedFilename) - { - GOwnPtr<char> destination(g_build_filename(kTempDirectory, suggestedFilename, NULL)); - GOwnPtr<char> destinationURI(g_filename_to_uri(destination.get(), 0, 0)); - webkit_download_set_destination(download, destinationURI.get()); - } - - 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) - { - if (!webkit_download_get_destination(download)) - return; - GRefPtr<GFile> destFile = adoptGRef(g_file_new_for_uri(webkit_download_get_destination(download))); - GOwnPtr<char> destBasename(g_file_get_basename(destFile.get())); - g_assert_cmpstr(destBasename.get(), ==, expectedName); - - g_file_delete(destFile.get(), 0, 0); - } - - WebKitWebContext* m_webContext; - GMainLoop* m_mainLoop; - Vector<DownloadEvent> m_downloadEvents; - guint64 m_downloadSize; -}; - -static void testDownloadLocalFile(DownloadTest* test, gconstpointer) -{ - GOwnPtr<char> sourcePath(g_build_filename(Test::getWebKit1TestResoucesDir().data(), "test.pdf", NULL)); - 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(test->downloadURIAndWaitUntilFinishes(sourceURI.get())); - g_assert(!webkit_download_get_web_view(download.get())); - - Vector<DownloadTest::DownloadEvent>& events = test->m_downloadEvents; - g_assert_cmpint(events.size(), ==, 5); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::CreatedDestination); - g_assert_cmpint(events[3], ==, DownloadTest::ReceivedData); - g_assert_cmpint(events[4], ==, DownloadTest::Finished); - - WebKitURIRequest* request = webkit_download_get_request(download.get()); - g_assert(request); - g_assert_cmpstr(webkit_uri_request_get_uri(request), ==, sourceURI.get()); - - g_assert_cmpint(test->m_downloadSize, ==, g_file_info_get_size(sourceInfo.get())); - g_assert(webkit_download_get_destination(download.get())); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), ==, 1); - test->checkDestinationAndDeleteFile(download.get(), "test.pdf"); -} - -class DownloadErrorTest: public DownloadTest { -public: - MAKE_GLIB_TEST_FIXTURE(DownloadErrorTest); - - DownloadErrorTest() - : m_expectedError(WEBKIT_DOWNLOAD_ERROR_NETWORK) - { - } - - void receivedResponse(WebKitDownload* download) - { - DownloadTest::receivedResponse(download); - if (m_expectedError == WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER) - webkit_download_cancel(download); - } - - void createdDestination(WebKitDownload* download, const char* destination) - { - g_assert_not_reached(); - } - - void failed(WebKitDownload* download, GError* error) - { - g_assert(g_error_matches(error, WEBKIT_DOWNLOAD_ERROR, m_expectedError)); - DownloadTest::failed(download, error); - } - - void decideDestination(WebKitDownload* download, const gchar* suggestedFilename) - { - if (m_expectedError != WEBKIT_DOWNLOAD_ERROR_DESTINATION) { - DownloadTest::decideDestination(download, suggestedFilename); - return; - } - webkit_download_set_destination(download, "file:///foo/bar"); - } - - WebKitDownloadError m_expectedError; -}; - -static void testDownloadLocalFileError(DownloadErrorTest* test, gconstpointer) -{ - test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_NETWORK; - 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; - g_assert_cmpint(events.size(), ==, 3); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::Failed); - g_assert_cmpint(events[2], ==, DownloadTest::Finished); - events.clear(); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); - - test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_DESTINATION; - 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(test->downloadURIAndWaitUntilFinishes(uri.get())); - g_assert(!webkit_download_get_web_view(download.get())); - - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::Failed); - g_assert_cmpint(events[3], ==, DownloadTest::Finished); - events.clear(); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); - test->checkDestinationAndDeleteFile(download.get(), "bar"); - - test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER; - download = adoptGRef(test->downloadURIAndWaitUntilFinishes(uri.get())); - g_assert(!webkit_download_get_web_view(download.get())); - - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::Failed); - g_assert_cmpint(events[3], ==, DownloadTest::Finished); - events.clear(); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); - test->checkDestinationAndDeleteFile(download.get(), "test.pdf"); -} - -static WebKitTestServer* kServer; -static const char* kServerSuggestedFilename = "webkit-downloaded-file"; - -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; - } - - GOwnPtr<char> filePath(g_build_filename(Test::getWebKit1TestResoucesDir().data(), path, NULL)); - char* contents; - gsize contentsLength; - if (!g_file_get_contents(filePath.get(), &contents, &contentsLength, 0)) { - 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); - - GOwnPtr<char> contentDisposition(g_strdup_printf("filename=%s", kServerSuggestedFilename)); - soup_message_headers_append(message->response_headers, "Content-Disposition", contentDisposition.get()); - soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, contents, contentsLength); - - soup_message_body_complete(message->response_body); -} - -static void testDownloadRemoteFile(DownloadTest* test, gconstpointer) -{ - 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; - g_assert_cmpint(events.size(), ==, 5); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::CreatedDestination); - g_assert_cmpint(events[3], ==, DownloadTest::ReceivedData); - g_assert_cmpint(events[4], ==, DownloadTest::Finished); - events.clear(); - - WebKitURIRequest* request = webkit_download_get_request(download.get()); - g_assert(request); - 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); - test->checkDestinationAndDeleteFile(download.get(), kServerSuggestedFilename); -} - -static void testDownloadRemoteFileError(DownloadErrorTest* test, gconstpointer) -{ - test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_NETWORK; - 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; - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::Failed); - g_assert_cmpint(events[3], ==, DownloadTest::Finished); - events.clear(); - WebKitURIResponse* response = webkit_download_get_response(download.get()); - g_assert_cmpuint(webkit_uri_response_get_status_code(response), ==, 404); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); - - test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_DESTINATION; - download = adoptGRef(test->downloadURIAndWaitUntilFinishes(kServer->getURIForPath("/test.pdf"))); - g_assert(!webkit_download_get_web_view(download.get())); - - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::Failed); - g_assert_cmpint(events[3], ==, DownloadTest::Finished); - events.clear(); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); - test->checkDestinationAndDeleteFile(download.get(), "bar"); - - test->m_expectedError = WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER; - download = adoptGRef(test->downloadURIAndWaitUntilFinishes(kServer->getURIForPath("/test.pdf"))); - g_assert(!webkit_download_get_web_view(download.get())); - - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, DownloadTest::Started); - g_assert_cmpint(events[1], ==, DownloadTest::ReceivedResponse); - g_assert_cmpint(events[2], ==, DownloadTest::Failed); - g_assert_cmpint(events[3], ==, DownloadTest::Finished); - events.clear(); - g_assert_cmpfloat(webkit_download_get_estimated_progress(download.get()), <, 1); - test->checkDestinationAndDeleteFile(download.get(), kServerSuggestedFilename); -} - -class WebViewDownloadTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(WebViewDownloadTest); - - static void downloadStartedCallback(WebKitWebContext* context, WebKitDownload* download, WebViewDownloadTest* test) - { - test->m_download = download; - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(download)); - test->quitMainLoop(); - } - - WebViewDownloadTest() - { - g_signal_connect(webkit_web_view_get_context(m_webView), "download-started", G_CALLBACK(downloadStartedCallback), this); - } - - ~WebViewDownloadTest() - { - g_signal_handlers_disconnect_matched(webkit_web_view_get_context(m_webView), G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void waitUntilDownloadStarted() - { - m_download = 0; - g_main_loop_run(m_mainLoop); - g_assert(m_download.get()); - } - - static gboolean downloadDecideDestinationCallback(WebKitDownload* download, const gchar* suggestedFilename, WebViewDownloadTest* test) - { - GOwnPtr<char> destination(g_build_filename(kTempDirectory, suggestedFilename, NULL)); - GOwnPtr<char> destinationURI(g_filename_to_uri(destination.get(), 0, 0)); - webkit_download_set_destination(download, destinationURI.get()); - return TRUE; - } - - static void downloadFinishedCallback(WebKitDownload* download, WebViewDownloadTest* test) - { - test->quitMainLoop(); - } - - void waitUntilDownloadFinished() - { - g_signal_connect(m_download.get(), "decide-destination", G_CALLBACK(downloadDecideDestinationCallback), this); - g_signal_connect(m_download.get(), "finished", G_CALLBACK(downloadFinishedCallback), this); - g_main_loop_run(m_mainLoop); - } - - GRefPtr<WebKitDownload> m_download; -}; - -static void testWebViewDownloadURI(WebViewDownloadTest* test, gconstpointer) -{ - GRefPtr<WebKitDownload> download = adoptGRef(webkit_web_view_download_uri(test->m_webView, kServer->getURIForPath("/test.pdf").data())); - test->waitUntilDownloadStarted(); - g_assert(test->m_webView == webkit_download_get_web_view(download.get())); - test->waitUntilDownloadFinished(); - - GRefPtr<GFile> downloadFile = adoptGRef(g_file_new_for_uri(webkit_download_get_destination(download.get()))); - GRefPtr<GFileInfo> downloadFileInfo = adoptGRef(g_file_query_info(downloadFile.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE, static_cast<GFileQueryInfoFlags>(0), 0, 0)); - g_assert_cmpint(g_file_info_get_size(downloadFileInfo.get()), >, 0); - g_file_delete(downloadFile.get(), 0, 0); -} - -class PolicyResponseDownloadTest: public WebViewDownloadTest { -public: - MAKE_GLIB_TEST_FIXTURE(PolicyResponseDownloadTest); - - static gboolean decidePolicyCallback(WebKitWebView* webView, WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, PolicyResponseDownloadTest* test) - { - if (type != WEBKIT_POLICY_DECISION_TYPE_RESPONSE) - return FALSE; - - webkit_policy_decision_download(decision); - return TRUE; - } - - PolicyResponseDownloadTest() - { - g_signal_connect(m_webView, "decide-policy", G_CALLBACK(decidePolicyCallback), this); - } - - ~PolicyResponseDownloadTest() - { - g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void cancelDownloadAndWaitUntilFinished() - { - webkit_download_cancel(m_download.get()); - waitUntilDownloadFinished(); - m_download = 0; - } -}; - -static void testPolicyResponseDownload(PolicyResponseDownloadTest* test, gconstpointer) -{ - // Test that a download started by the the policy checker contains the web view. - 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(); -} - -void beforeAll() -{ - kServer = new WebKitTestServer(); - kServer->run(serverCallback); - - kTempDirectory = g_dir_make_tmp("WebKit2Tests-XXXXXX", 0); - g_assert(kTempDirectory); - - DownloadTest::add("Downloads", "local-file", testDownloadLocalFile); - DownloadErrorTest::add("Downloads", "local-file-error", testDownloadLocalFileError); - DownloadTest::add("Downloads", "remote-file", testDownloadRemoteFile); - DownloadErrorTest::add("Downloads", "remote-file-error", testDownloadRemoteFileError); - WebViewDownloadTest::add("WebKitWebView", "download-uri", testWebViewDownloadURI); - PolicyResponseDownloadTest::add("Downloads", "policy-decision-download", testPolicyResponseDownload); -} - -void afterAll() -{ - delete kServer; - g_rmdir(kTempDirectory); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp deleted file mode 100644 index aa80888b3..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspector.cpp +++ /dev/null @@ -1,356 +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 "WebViewTest.h" -#include <wtf/gobject/GRefPtr.h> - -class InspectorTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(InspectorTest); - - enum InspectorEvents { - OpenWindow, - BringToFront, - Closed, - Attach, - Detach - }; - - static gboolean openWindowCallback(WebKitWebInspector*, InspectorTest* test) - { - return test->openWindow(); - } - - static gboolean bringToFrontCallback(WebKitWebInspector*, InspectorTest* test) - { - return test->bringToFront(); - } - - static void closedCallback(WebKitWebInspector*, InspectorTest* test) - { - return test->closed(); - } - - static gboolean attachCallback(WebKitWebInspector*, InspectorTest* test) - { - return test->attach(); - } - - static gboolean detachCallback(WebKitWebInspector*, InspectorTest* test) - { - return test->detach(); - } - - static const unsigned gMinimumAttachedInspectorWidth = 750; - static const unsigned gMinimumAttachedInspectorHeight = 250; - - InspectorTest() - : WebViewTest() - , m_inspector(webkit_web_view_get_inspector(m_webView)) - { - webkit_settings_set_enable_developer_extras(webkit_web_view_get_settings(m_webView), TRUE); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_inspector)); - g_signal_connect(m_inspector, "open-window", G_CALLBACK(openWindowCallback), this); - g_signal_connect(m_inspector, "bring-to-front", G_CALLBACK(bringToFrontCallback), this); - g_signal_connect(m_inspector, "closed", G_CALLBACK(closedCallback), this); - g_signal_connect(m_inspector, "attach", G_CALLBACK(attachCallback), this); - g_signal_connect(m_inspector, "detach", G_CALLBACK(detachCallback), this); - } - - ~InspectorTest() - { - g_signal_handlers_disconnect_matched(m_inspector, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - virtual bool openWindow() - { - m_events.append(OpenWindow); - g_main_loop_quit(m_mainLoop); - return TRUE; - } - - virtual bool bringToFront() - { - m_events.append(BringToFront); - g_main_loop_quit(m_mainLoop); - return FALSE; - } - - virtual void closed() - { - m_events.append(Closed); - } - - virtual bool attach() - { - m_events.append(Attach); - return TRUE; - } - - virtual bool detach() - { - m_events.append(Detach); - return TRUE; - } - - - static gboolean showIdle(InspectorTest* test) - { - 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); - } - - void resizeViewAndAttach() - { - // Resize the view to make room for the inspector. - resizeView(gMinimumAttachedInspectorWidth, (gMinimumAttachedInspectorHeight + 1) * 4 / 3); - webkit_web_inspector_attach(m_inspector); - } - - static gboolean detachIdle(InspectorTest* test) - { - webkit_web_inspector_detach(test->m_inspector); - return FALSE; - } - - void detachAndWaitUntilWindowOpened() - { - g_idle_add(reinterpret_cast<GSourceFunc>(detachIdle), this); - g_main_loop_run(m_mainLoop); - } - - void close() - { - webkit_web_inspector_close(m_inspector); - } - - WebKitWebInspector* m_inspector; - Vector<InspectorEvents> m_events; -}; - -static void testInspectorDefault(InspectorTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - test->resizeView(200, 200); - test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); - test->waitUntilLoadFinished(); - - 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()); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); - 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(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::OpenWindow); - test->m_events.clear(); - - test->show(); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); - test->m_events.clear(); - - test->resizeViewAndAttach(); - g_assert(webkit_web_inspector_is_attached(test->m_inspector)); - g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), >=, InspectorTest::gMinimumAttachedInspectorHeight); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::Attach); - test->m_events.clear(); - - test->detachAndWaitUntilWindowOpened(); - g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 2); - g_assert_cmpint(events[0], ==, InspectorTest::Detach); - g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); - test->m_events.clear(); - - test->close(); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::Closed); - test->m_events.clear(); -} - -class CustomInspectorTest: public InspectorTest { -public: - MAKE_GLIB_TEST_FIXTURE(CustomInspectorTest); - - CustomInspectorTest() - : InspectorTest() - , m_inspectorWindow(0) - { - } - - ~CustomInspectorTest() - { - if (m_inspectorWindow) - gtk_widget_destroy(m_inspectorWindow); - } - - bool openWindow() - { - g_assert(!m_inspectorWindow); - m_inspectorWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); - WebKitWebViewBase* inspectorView = webkit_web_inspector_get_web_view(m_inspector); - g_assert(inspectorView); - gtk_container_add(GTK_CONTAINER(m_inspectorWindow), GTK_WIDGET(inspectorView)); - gtk_widget_show_all(m_inspectorWindow); - - return InspectorTest::openWindow(); - } - - void closed() - { - if (m_inspectorWindow) { - gtk_widget_destroy(m_inspectorWindow); - m_inspectorWindow = 0; - } - - return InspectorTest::closed(); - } - - bool attach() - { - GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(m_inspector); - if (m_inspectorWindow) { - gtk_container_remove(GTK_CONTAINER(m_inspectorWindow), GTK_WIDGET(inspectorView.get())); - gtk_widget_destroy(m_inspectorWindow); - m_inspectorWindow = 0; - } - - GtkWidget* pane; - if (gtk_bin_get_child(GTK_BIN(m_parentWindow)) == GTK_WIDGET(m_webView)) { - GRefPtr<WebKitWebView> inspectedView = m_webView; - gtk_container_remove(GTK_CONTAINER(m_parentWindow), GTK_WIDGET(m_webView)); - pane = gtk_paned_new(GTK_ORIENTATION_VERTICAL); - gtk_paned_add1(GTK_PANED(pane), GTK_WIDGET(m_webView)); - gtk_container_add(GTK_CONTAINER(m_parentWindow), pane); - gtk_widget_show_all(pane); - } else - pane = gtk_bin_get_child(GTK_BIN(m_parentWindow)); - gtk_paned_set_position(GTK_PANED(pane), webkit_web_inspector_get_attached_height(m_inspector)); - gtk_paned_add2(GTK_PANED(pane), GTK_WIDGET(inspectorView.get())); - - return InspectorTest::attach(); - } - - bool detach() - { - GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(m_inspector); - GtkWidget* pane = gtk_bin_get_child(GTK_BIN(m_parentWindow)); - g_assert(GTK_IS_PANED(pane)); - gtk_container_remove(GTK_CONTAINER(pane), GTK_WIDGET(inspectorView.get())); - return InspectorTest::detach(); - } - - void destroyWindow() - { - g_assert(m_inspectorWindow); - gtk_widget_destroy(m_inspectorWindow); - m_inspectorWindow = 0; - } - - GtkWidget* m_inspectorWindow; -}; - -static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - test->resizeView(200, 200); - test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); - test->waitUntilLoadFinished(); - - 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(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::OpenWindow); - test->m_events.clear(); - - test->resizeViewAndAttach(); - g_assert(webkit_web_inspector_is_attached(test->m_inspector)); - g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), >=, InspectorTest::gMinimumAttachedInspectorHeight); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::Attach); - test->m_events.clear(); - - test->detachAndWaitUntilWindowOpened(); - g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 2); - g_assert_cmpint(events[0], ==, InspectorTest::Detach); - g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); - test->m_events.clear(); - - test->resizeViewAndAttach(); - g_assert(webkit_web_inspector_is_attached(test->m_inspector)); - test->m_events.clear(); - test->close(); - events = test->m_events; - g_assert_cmpint(events.size(), ==, 2); - g_assert_cmpint(events[0], ==, InspectorTest::Detach); - g_assert_cmpint(events[1], ==, InspectorTest::Closed); - test->m_events.clear(); -} - -static void testInspectorCustomContainerDestroyed(CustomInspectorTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - test->resizeView(200, 200); - test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); - test->waitUntilLoadFinished(); - - 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->destroyWindow(); - Vector<InspectorTest::InspectorEvents>& events = test->m_events; - g_assert_cmpint(events.size(), ==, 1); - g_assert_cmpint(events[0], ==, InspectorTest::Closed); - test->m_events.clear(); -} - -void beforeAll() -{ - g_setenv("WEBKIT_INSPECTOR_PATH", WEBKIT_INSPECTOR_PATH, FALSE); - InspectorTest::add("WebKitWebInspector", "default", testInspectorDefault); - CustomInspectorTest::add("WebKitWebInspector", "manual-attach-detach", testInspectorManualAttachDetach); - CustomInspectorTest::add("WebKitWebInspector", "custom-container-destroyed", testInspectorCustomContainerDestroyed); -} - -void afterAll() -{ -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp deleted file mode 100644 index 35fb3fcdc..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestInspectorServer.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics Ltd. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "WebViewTest.h" -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/WTFString.h> - -// Name of the test server application creating the webView object. -static const char* gTestServerAppName = "InspectorTestServer"; - -// Max seconds to wait for the test server before inspecting it. -static const int gMaxWaitForChild = 5; - -// The PID for the test server running, so we can kill it if needed. -static GPid gChildProcessPid = 0; - -// Whether the child has replied and it's ready. -static bool gChildIsReady = false; - -static void stopTestServer() -{ - // Do nothing if there's no server running. - if (!gChildProcessPid) - return; - - g_spawn_close_pid(gChildProcessPid); - kill(gChildProcessPid, SIGTERM); - gChildProcessPid = 0; -} - -static void sigAbortHandler(int sigNum) -{ - // Just stop the test server if SIGABRT was received. - stopTestServer(); -} - -static gpointer testServerMonitorThreadFunc(gpointer) -{ - // Wait for the specified timeout to happen. - g_usleep(gMaxWaitForChild * G_USEC_PER_SEC); - - // Kill the child process if not ready yet. - if (!gChildIsReady) - stopTestServer(); - - g_thread_exit(0); - return 0; -} - -static void startTestServerMonitor() -{ - gChildIsReady = false; - g_thread_new("TestServerMonitor", testServerMonitorThreadFunc, 0); -} - -static void startTestServer() -{ - // Prepare argv[] for spawning the server process. - GOwnPtr<char> testServerPath(g_build_filename(WEBKIT_EXEC_PATH, "WebKit2APITests", gTestServerAppName, NULL)); - - // We install a handler to ensure that we kill the child process - // if the parent dies because of whatever the reason is. - signal(SIGABRT, sigAbortHandler); - - char* testServerArgv[2]; - testServerArgv[0] = testServerPath.get(); - testServerArgv[1] = 0; - - // Spawn the server, getting its stdout file descriptor to set a - // communication channel, so we know when it's ready. - int childStdout = 0; - g_assert(g_spawn_async_with_pipes(0, testServerArgv, 0, static_cast<GSpawnFlags>(0), 0, 0, - &gChildProcessPid, 0, &childStdout, 0, 0)); - - // Start monitoring the test server (in a separate thread) to - // ensure we don't block on the child process more than a timeout. - startTestServerMonitor(); - - char msg[2]; - GIOChannel* ioChannel = g_io_channel_unix_new(childStdout); - if (g_io_channel_read_chars(ioChannel, msg, 2, 0, 0) == G_IO_STATUS_NORMAL) { - // Check whether the server sent a message saying it's ready - // and store the result globally, so the monitor can see it. - gChildIsReady = msg[0] == 'O' && msg[1] == 'K'; - } - g_io_channel_unref(ioChannel); - close(childStdout); - - // The timeout was reached and the server is not ready yet, so - // stop it inmediately, and let the unit tests fail. - if (!gChildIsReady) - stopTestServer(); -} - -class InspectorServerTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(InspectorServerTest); - - InspectorServerTest() - : WebViewTest() - { - } - - bool getPageList() - { - loadHtml("<script type=\"text/javascript\">\n" - "var pages;\n" - "var xhr = new XMLHttpRequest;\n" - "xhr.open(\"GET\", \"/pagelist.json\");\n" - "xhr.onload = function(e) {\n" - "if (xhr.status == 200) {\n" - "pages = JSON.parse(xhr.responseText);\n" - "document.title = \"OK\";\n" - "} else \n" - "document.title = \"FAIL\";\n" - "}\n" - "xhr.send();\n" - "</script>\n", - "http://127.0.0.1:2999/"); - - waitUntilTitleChanged(); - - if (!strcmp(webkit_web_view_get_title(m_webView), "OK")) - return true; - - return false; - } - - ~InspectorServerTest() - { - } -}; - -// Test to get inspector server page list from the test server. -// Should contain only one entry pointing to http://127.0.0.1:2999/webinspector/inspector.html?page=1 -static void testInspectorServerPageList(InspectorServerTest* test, gconstpointer) -{ - GOwnPtr<GError> error; - - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - g_assert(test->getPageList()); - - WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished("pages.length;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert_cmpint(WebViewTest::javascriptResultToNumber(javascriptResult), ==, 1); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("pages[0].id;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - int pageId = WebViewTest::javascriptResultToNumber(javascriptResult); - - GOwnPtr<char> valueString; - javascriptResult = test->runJavaScriptAndWaitUntilFinished("pages[0].url;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); - g_assert_cmpstr(valueString.get(), ==, "http://127.0.0.1:2999/"); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("pages[0].inspectorUrl;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); - 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. -// For this specific message see: http://code.google.com/chrome/devtools/docs/protocol/tot/runtime.html#command-evaluate -static void testRemoteDebuggingMessage(InspectorServerTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - - test->loadHtml("<script type=\"text/javascript\">\n" - "var socket = new WebSocket('ws://127.0.0.1:2999/devtools/page/1');\n" - "socket.onmessage = function(message) {\n" - "var response = JSON.parse(message.data);\n" - "if (response.id === 1)\n" - "document.title = response.result.result.value;\n" - "else\n" - "document.title = \"FAIL\";\n" - "}\n" - "socket.onopen = function() {\n" - "socket.send('{\"id\": 1, \"method\": \"Runtime.evaluate\", \"params\": {\"expression\": \"2 + 2\" } }');\n" - "}\n" - "</script>", - "http://127.0.0.1:2999/"); - test->waitUntilTitleChanged(); - - g_assert_cmpstr(webkit_web_view_get_title(test->m_webView), ==, "4"); -} - -static void openRemoteDebuggingSession(InspectorServerTest* test, gconstpointer) -{ - // To test the whole pipeline this exploits a behavior of the inspector front-end which won't provide any title unless the - // debugging session was established correctly through web socket. It should be something like "Web Inspector - <Page URL>". - // In our case page URL should be http://127.0.0.1:2999/ - // So this test case will fail if: - // - The page list didn't return a valid inspector URL - // - Or the front-end couldn't be loaded through the inspector HTTP server - // - Or the web socket connection couldn't be established between the front-end and the page through the inspector server - // Let's see if this test isn't raising too many false positives, in which case we should use a better predicate if available. - - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - - g_assert(test->getPageList()); - - GOwnPtr<GError> error; - WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished("pages[0].inspectorUrl;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - - String resolvedURL = String("http://127.0.0.1:2999/") + String::fromUTF8(WebViewTest::javascriptResultToCString(javascriptResult)); - test->loadURI(resolvedURL.utf8().data()); - test->waitUntilTitleChanged(); - - g_assert_cmpstr(webkit_web_view_get_title(test->m_webView), ==, "Web Inspector - http://127.0.0.1:2999/"); -} - - -void beforeAll() -{ - // Overwrite WEBKIT_INSPECTOR_SERVER variable with default IP address but different port to avoid conflict with the test inspector server page. - g_setenv("WEBKIT_INSPECTOR_SERVER", "127.0.0.1:2998", TRUE); - - startTestServer(); - InspectorServerTest::add("WebKitWebInspectorServer", "test-page-list", testInspectorServerPageList); - InspectorServerTest::add("WebKitWebInspectorServer", "test-remote-debugging-message", testRemoteDebuggingMessage); - InspectorServerTest::add("WebKitWebInspectorServer", "test-open-debugging-session", openRemoteDebuggingSession); - -} - -void afterAll() -{ - stopTestServer(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp deleted file mode 100644 index 331915e00..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestLoaderClient.cpp +++ /dev/null @@ -1,465 +0,0 @@ -/* - * Copyright (C) 2009, 2010 Gustavo Noronha Silva - * Copyright (C) 2009, 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 "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()); - test->loadURI(kServer->getURIForPath("/redirect").data()); - test->waitUntilLoadFinished(); - - Vector<LoadTrackingTest::LoadEvents>& events = test->m_loadEvents; - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(events[1], ==, LoadTrackingTest::ProvisionalLoadReceivedServerRedirect); - g_assert_cmpint(events[2], ==, LoadTrackingTest::LoadCommitted); - g_assert_cmpint(events[3], ==, LoadTrackingTest::LoadFinished); -} - -static void testLoadingError(LoadTrackingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/error").data()); - test->waitUntilLoadFinished(); - - Vector<LoadTrackingTest::LoadEvents>& events = test->m_loadEvents; - g_assert_cmpint(events.size(), ==, 3); - g_assert_cmpint(events[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(events[1], ==, LoadTrackingTest::ProvisionalLoadFailed); - g_assert_cmpint(events[2], ==, LoadTrackingTest::LoadFinished); -} - -static void assertNormalLoadHappened(Vector<LoadTrackingTest::LoadEvents>& events) -{ - g_assert_cmpint(events.size(), ==, 3); - g_assert_cmpint(events[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(events[1], ==, LoadTrackingTest::LoadCommitted); - g_assert_cmpint(events[2], ==, LoadTrackingTest::LoadFinished); -} - -static void testLoadHtml(LoadTrackingTest* test, gconstpointer) -{ - test->loadHtml("<html><body>Hello WebKit-GTK+</body></html>", 0); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); -} - -static void testLoadAlternateHTML(LoadTrackingTest* test, gconstpointer) -{ - test->loadAlternateHTML("<html><body>Alternate page</body></html>", "http://error-page.foo/", 0); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); -} - -static void testLoadPlainText(LoadTrackingTest* test, gconstpointer) -{ - test->loadPlainText("Hello WebKit-GTK+"); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); -} - -static void testLoadRequest(LoadTrackingTest* test, gconstpointer) -{ - GRefPtr<WebKitURIRequest> request(webkit_uri_request_new(kServer->getURIForPath("/normal").data())); - test->loadRequest(request.get()); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); -} - -class LoadStopTrackingTest : public LoadTrackingTest { -public: - MAKE_GLIB_TEST_FIXTURE(LoadStopTrackingTest); - - virtual void loadCommitted() - { - LoadTrackingTest::loadCommitted(); - webkit_web_view_stop_loading(m_webView); - } - virtual void loadFailed(const gchar* failingURI, GError* error) - { - g_assert(g_error_matches(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED)); - LoadTrackingTest::loadFailed(failingURI, error); - } -}; - -static void testLoadCancelled(LoadStopTrackingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/cancelled").data()); - test->waitUntilLoadFinished(); - - Vector<LoadTrackingTest::LoadEvents>& events = test->m_loadEvents; - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(events[1], ==, LoadTrackingTest::LoadCommitted); - g_assert_cmpint(events[2], ==, LoadTrackingTest::LoadFailed); - g_assert_cmpint(events[3], ==, LoadTrackingTest::LoadFinished); -} - -static void testWebViewTitle(LoadTrackingTest* test, gconstpointer) -{ - g_assert(!webkit_web_view_get_title(test->m_webView)); - test->loadHtml("<html><head><title>Welcome to WebKit-GTK+!</title></head></html>", 0); - test->waitUntilLoadFinished(); - g_assert_cmpstr(webkit_web_view_get_title(test->m_webView), ==, "Welcome to WebKit-GTK+!"); -} - -static void testWebViewReload(LoadTrackingTest* test, gconstpointer) -{ - // Check that nothing happens when there's nothing to reload. - test->reload(); - test->wait(0.25); // Wait for a quarter of a second. - - test->loadURI(kServer->getURIForPath("/normal").data()); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); - - test->reload(); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); -} - -static void testLoadProgress(LoadTrackingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/normal").data()); - test->waitUntilLoadFinished(); - g_assert_cmpfloat(test->m_estimatedProgress, ==, 1); -} - -static void testWebViewHistoryLoad(LoadTrackingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/normal").data()); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); - - test->loadURI(kServer->getURIForPath("/normal2").data()); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); - - // Check that load process is the same for pages loaded from history cache. - test->goBack(); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); - - test->goForward(); - test->waitUntilLoadFinished(); - assertNormalLoadHappened(test->m_loadEvents); -} - -class ViewURITrackingTest: public LoadTrackingTest { -public: - MAKE_GLIB_TEST_FIXTURE(ViewURITrackingTest); - - static void uriChanged(GObject*, GParamSpec*, ViewURITrackingTest* test) - { - g_assert_cmpstr(test->m_activeURI.data(), !=, webkit_web_view_get_uri(test->m_webView)); - test->m_activeURI = webkit_web_view_get_uri(test->m_webView); - } - - ViewURITrackingTest() - : m_activeURI(webkit_web_view_get_uri(m_webView)) - { - g_assert(m_activeURI.isNull()); - g_signal_connect(m_webView, "notify::uri", G_CALLBACK(uriChanged), this); - } - - void provisionalLoadStarted() - { - checkActiveURI("/redirect"); - } - - void provisionalLoadReceivedServerRedirect() - { - checkActiveURI("/normal"); - } - - void loadCommitted() - { - checkActiveURI("/normal"); - } - - void loadFinished() - { - checkActiveURI("/normal"); - LoadTrackingTest::loadFinished(); - } - - CString m_activeURI; - -private: - void checkActiveURI(const char* uri) - { - ASSERT_CMP_CSTRING(m_activeURI, ==, kServer->getURIForPath(uri)); - } -}; - -static void testWebViewActiveURI(ViewURITrackingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/redirect").data()); - test->waitUntilLoadFinished(); -} - -class ViewIsLoadingTest: public LoadTrackingTest { -public: - MAKE_GLIB_TEST_FIXTURE(ViewIsLoadingTest); - - static void isLoadingChanged(GObject*, GParamSpec*, ViewIsLoadingTest* test) - { - if (webkit_web_view_is_loading(test->m_webView)) - test->beginLoad(); - else - test->endLoad(); - } - - ViewIsLoadingTest() - { - g_signal_connect(m_webView, "notify::is-loading", G_CALLBACK(isLoadingChanged), this); - } - - void beginLoad() - { - // New load, load-started hasn't been emitted yet. - g_assert(m_loadEvents.isEmpty()); - g_assert_cmpstr(webkit_web_view_get_uri(m_webView), ==, m_activeURI.data()); - } - - void endLoad() - { - // Load finish, load-finished and load-failed haven't been emitted yet. - g_assert(!m_loadEvents.isEmpty()); - g_assert(!m_loadEvents.contains(LoadTrackingTest::LoadFinished)); - g_assert(!m_loadEvents.contains(LoadTrackingTest::LoadFailed)); - } -}; - -static void testWebViewIsLoading(ViewIsLoadingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/normal").data()); - test->waitUntilLoadFinished(); - - test->reload(); - test->waitUntilLoadFinished(); - - test->loadURI(kServer->getURIForPath("/error").data()); - test->waitUntilLoadFinished(); - - test->loadURI(kServer->getURIForPath("/normal").data()); - test->waitUntilLoadFinished(); - test->loadURI(kServer->getURIForPath("/normal2").data()); - test->waitUntilLoadFinished(); - - test->goBack(); - test->waitUntilLoadFinished(); - - test->goForward(); - 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!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!" - "Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!Testing!</body></html>"; - - 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 (g_str_has_prefix(path, "/normal")) - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, responseString, strlen(responseString)); - else if (g_str_equal(path, "/error")) - soup_message_set_status(message, SOUP_STATUS_CANT_CONNECT); - else if (g_str_equal(path, "/redirect")) { - soup_message_set_status(message, SOUP_STATUS_MOVED_PERMANENTLY); - soup_message_headers_append(message->response_headers, "Location", "/normal"); - } else if (g_str_equal(path, "/cancelled")) { - soup_message_headers_set_encoding(message->response_headers, SOUP_ENCODING_CHUNKED); - 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); - - soup_message_body_complete(message->response_body); -} - -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); - - LoadTrackingTest::add("WebKitWebView", "loading-status", testLoadingStatus); - LoadTrackingTest::add("WebKitWebView", "loading-error", testLoadingError); - LoadTrackingTest::add("WebKitWebView", "load-html", testLoadHtml); - LoadTrackingTest::add("WebKitWebView", "load-alternate-html", testLoadAlternateHTML); - LoadTrackingTest::add("WebKitWebView", "load-plain-text", testLoadPlainText); - LoadTrackingTest::add("WebKitWebView", "load-request", testLoadRequest); - LoadStopTrackingTest::add("WebKitWebView", "stop-loading", testLoadCancelled); - LoadTrackingTest::add("WebKitWebView", "title", testWebViewTitle); - LoadTrackingTest::add("WebKitWebView", "progress", testLoadProgress); - LoadTrackingTest::add("WebKitWebView", "reload", testWebViewReload); - LoadTrackingTest::add("WebKitWebView", "history-load", testWebViewHistoryLoad); - - // This test checks that web view notify::uri signal is correctly emitted - // and the uri is already updated when loader client signals are emitted. - 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 deleted file mode 100644 index 6ac35f8ca..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2011 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 "TestMain.h" - -#include <glib/gstdio.h> -#include <gtk/gtk.h> -#include <webkit2/webkit2.h> -#include <wtf/gobject/GOwnPtr.h> - -void beforeAll(); -void afterAll(); - -static void registerGResource(void) -{ - GOwnPtr<char> resourcesPath(g_build_filename(WEBKIT_EXEC_PATH, "resources", "webkit2gtk-tests-resources.gresource", NULL)); - GResource* resource = g_resource_load(resourcesPath.get(), 0); - g_assert(resource); - - g_resources_register(resource); - 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 deleted file mode 100644 index 02c90709c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestMain.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2011 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 TestMain_h -#define TestMain_h - -#include <cairo.h> -#include <glib-object.h> -#include <wtf/HashSet.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> - -#define MAKE_GLIB_TEST_FIXTURE(ClassName) \ - static void setUp(ClassName* fixture, gconstpointer data) \ - { \ - new (fixture) ClassName; \ - } \ - static void tearDown(ClassName* fixture, gconstpointer data) \ - { \ - fixture->~ClassName(); \ - } \ - static void add(const char* suiteName, const char* testName, void (*testFunc)(ClassName*, const void*)) \ - { \ - GOwnPtr<gchar> testPath(g_strdup_printf("/webkit2/%s/%s", suiteName, testName)); \ - 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); - - ~Test() - { - if (m_watchedObjects.isEmpty()) - return; - - g_print("Leaked objects:"); - HashSet<GObject*>::const_iterator end = m_watchedObjects.end(); - for (HashSet<GObject*>::const_iterator it = m_watchedObjects.begin(); it != end; ++it) - g_print(" %s(%p)", g_type_name_from_instance(reinterpret_cast<GTypeInstance*>(*it)), *it); - g_print("\n"); - - g_assert(m_watchedObjects.isEmpty()); - } - - static void objectFinalized(Test* test, GObject* finalizedObject) - { - test->m_watchedObjects.remove(finalizedObject); - } - - void assertObjectIsDeletedWhenTestFinishes(GObject* object) - { - m_watchedObjects.add(object); - g_object_weak_ref(object, reinterpret_cast<GWeakNotify>(objectFinalized), this); - } - - static CString getWebKit1TestResoucesDir() - { - GOwnPtr<char> resourcesDir(g_build_filename(WEBKIT_SRC_DIR, "Source", "WebKit", "gtk", "tests", "resources", NULL)); - return resourcesDir.get(); - } - - static CString getResourcesDir() - { - GOwnPtr<char> resourcesDir(g_build_filename(WEBKIT_SRC_DIR, "Source", "WebKit2", "UIProcess", "API", "gtk", "tests", "resources", NULL)); - return resourcesDir.get(); - } - - void addLogFatalFlag(unsigned flag) - { - unsigned fatalMask = g_log_set_always_fatal(static_cast<GLogLevelFlags>(G_LOG_FATAL_MASK)); - fatalMask |= flag; - g_log_set_always_fatal(static_cast<GLogLevelFlags>(fatalMask)); - } - - void removeLogFatalFlag(unsigned flag) - { - unsigned fatalMask = g_log_set_always_fatal(static_cast<GLogLevelFlags>(G_LOG_FATAL_MASK)); - fatalMask &= ~flag; - 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; -}; - -#endif // TestMain_h diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp deleted file mode 100644 index 72c2cfbbd..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestPrinting.cpp +++ /dev/null @@ -1,209 +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 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 "WebViewTest.h" -#include <glib/gstdio.h> -#include <wtf/gobject/GRefPtr.h> - -#ifdef HAVE_GTK_UNIX_PRINTING -#include <gtk/gtkunixprint.h> -#endif - -static char* kTempDirectory; - -static void testPrintOperationPrintSettings(WebViewTest* test, gconstpointer) -{ - GRefPtr<WebKitPrintOperation> printOperation = adoptGRef(webkit_print_operation_new(test->m_webView)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(printOperation.get())); - - g_assert(!webkit_print_operation_get_print_settings(printOperation.get())); - g_assert(!webkit_print_operation_get_page_setup(printOperation.get())); - - GRefPtr<GtkPrintSettings> printSettings = adoptGRef(gtk_print_settings_new()); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(printSettings.get())); - - GRefPtr<GtkPageSetup> pageSetup = adoptGRef(gtk_page_setup_new()); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(pageSetup.get())); - - webkit_print_operation_set_print_settings(printOperation.get(), printSettings.get()); - webkit_print_operation_set_page_setup(printOperation.get(), pageSetup.get()); - - g_assert(webkit_print_operation_get_print_settings(printOperation.get()) == printSettings.get()); - g_assert(webkit_print_operation_get_page_setup(printOperation.get()) == pageSetup.get()); -} - -static gboolean webViewPrintCallback(WebKitWebView* webView, WebKitPrintOperation* printOperation, WebViewTest* test) -{ - g_assert(webView == test->m_webView); - - g_assert(WEBKIT_IS_PRINT_OPERATION(printOperation)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(printOperation)); - - g_assert(!webkit_print_operation_get_print_settings(printOperation)); - g_assert(!webkit_print_operation_get_page_setup(printOperation)); - - g_main_loop_quit(test->m_mainLoop); - - return TRUE; -} - -static void testWebViewPrint(WebViewTest* test, gconstpointer) -{ - g_signal_connect(test->m_webView, "print", G_CALLBACK(webViewPrintCallback), test); - test->loadHtml("<html><body onLoad=\"print();\">WebKitGTK+ printing test</body></html>", 0); - g_main_loop_run(test->m_mainLoop); -} - -#ifdef HAVE_GTK_UNIX_PRINTING -class PrintTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(PrintTest); - - static void printFinishedCallback(WebKitPrintOperation*, PrintTest* test) - { - g_main_loop_quit(test->m_mainLoop); - } - - static void printFailedCallback(WebKitPrintOperation*, GError* error, PrintTest* test) - { - g_assert(test->m_expectedError); - g_assert(error); - g_assert(g_error_matches(error, WEBKIT_PRINT_ERROR, test->m_expectedError)); - } - - PrintTest() - : m_expectedError(0) - { - m_printOperation = adoptGRef(webkit_print_operation_new(m_webView)); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_printOperation.get())); - g_signal_connect(m_printOperation.get(), "finished", G_CALLBACK(printFinishedCallback), this); - g_signal_connect(m_printOperation.get(), "failed", G_CALLBACK(printFailedCallback), this); - } - - static gboolean testPrintOperationPrintPrinter(GtkPrinter* printer, gpointer userData) - { - if (strcmp(gtk_printer_get_name(printer), "Print to File")) - return FALSE; - - GtkPrinter** foundPrinter = static_cast<GtkPrinter**>(userData); - *foundPrinter = static_cast<GtkPrinter*>(g_object_ref(printer)); - return TRUE; - } - - GtkPrinter* findPrintToFilePrinter() - { - GtkPrinter* printer = 0; - gtk_enumerate_printers(testPrintOperationPrintPrinter, &printer, 0, TRUE); - return printer; - } - - void waitUntilPrintFinished() - { - g_main_loop_run(m_mainLoop); - } - - GRefPtr<WebKitPrintOperation> m_printOperation; - unsigned int m_expectedError; -}; - -static void testPrintOperationPrint(PrintTest* test, gconstpointer) -{ - test->loadHtml("<html><body>WebKitGTK+ printing test</body></html>", 0); - test->waitUntilLoadFinished(); - - GRefPtr<GtkPrinter> printer = adoptGRef(test->findPrintToFilePrinter()); - if (!printer) { - g_message("%s", "Cannot test WebKitPrintOperation/print: no suitable printer found"); - return; - } - - GOwnPtr<char> outputFilename(g_build_filename(kTempDirectory, "webkit-print.pdf", NULL)); - GRefPtr<GFile> outputFile = adoptGRef(g_file_new_for_path(outputFilename.get())); - GOwnPtr<char> outputURI(g_file_get_uri(outputFile.get())); - - GRefPtr<GtkPrintSettings> printSettings = adoptGRef(gtk_print_settings_new()); - gtk_print_settings_set_printer(printSettings.get(), gtk_printer_get_name(printer.get())); - gtk_print_settings_set(printSettings.get(), GTK_PRINT_SETTINGS_OUTPUT_URI, outputURI.get()); - - webkit_print_operation_set_print_settings(test->m_printOperation.get(), printSettings.get()); - 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, - static_cast<GFileQueryInfoFlags>(0), 0, 0)); - g_assert(fileInfo.get()); - g_assert_cmpint(g_file_info_get_size(fileInfo.get()), >, 0); - g_assert_cmpstr(g_file_info_get_content_type(fileInfo.get()), ==, "application/pdf"); - - g_file_delete(outputFile.get(), 0, 0); -} - -static void testPrintOperationErrors(PrintTest* test, gconstpointer) -{ - test->loadHtml("<html><body>WebKitGTK+ printing errors test</body></html>", 0); - test->waitUntilLoadFinished(); - - GRefPtr<GtkPrinter> printer = adoptGRef(test->findPrintToFilePrinter()); - if (!printer) { - g_message("%s", "Cannot test WebKitPrintOperation/print: no suitable printer found"); - return; - } - - // General Error: invalid filename. - test->m_expectedError = WEBKIT_PRINT_ERROR_GENERAL; - GRefPtr<GtkPrintSettings> printSettings = adoptGRef(gtk_print_settings_new()); - gtk_print_settings_set_printer(printSettings.get(), gtk_printer_get_name(printer.get())); - gtk_print_settings_set(printSettings.get(), GTK_PRINT_SETTINGS_OUTPUT_URI, "file:///foo/bar"); - webkit_print_operation_set_print_settings(test->m_printOperation.get(), printSettings.get()); - webkit_print_operation_print(test->m_printOperation.get()); - test->waitUntilPrintFinished(); - - // Printer not found error. - test->m_expectedError = WEBKIT_PRINT_ERROR_PRINTER_NOT_FOUND; - gtk_print_settings_set_printer(printSettings.get(), "The fake WebKit printer"); - webkit_print_operation_print(test->m_printOperation.get()); - test->waitUntilPrintFinished(); - - // No pages to print: print even pages for a single page document. - test->m_expectedError = WEBKIT_PRINT_ERROR_INVALID_PAGE_RANGE; - gtk_print_settings_set_printer(printSettings.get(), gtk_printer_get_name(printer.get())); - gtk_print_settings_set_page_set(printSettings.get(), GTK_PAGE_SET_EVEN); - webkit_print_operation_print(test->m_printOperation.get()); - test->waitUntilPrintFinished(); -} -#endif // HAVE_GTK_UNIX_PRINTING - -void beforeAll() -{ - kTempDirectory = g_dir_make_tmp("WebKit2Tests-XXXXXX", 0); - g_assert(kTempDirectory); - - WebViewTest::add("WebKitPrintOperation", "printing-settings", testPrintOperationPrintSettings); - WebViewTest::add("WebKitWebView", "print", testWebViewPrint); -#ifdef HAVE_GTK_UNIX_PRINTING - PrintTest::add("WebKitPrintOperation", "print", testPrintOperationPrint); - PrintTest::add("WebKitPrintOperation", "print-errors", testPrintOperationErrors); -#endif -} - -void afterAll() -{ - g_rmdir(kTempDirectory); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp deleted file mode 100644 index a24b6fdff..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestResources.cpp +++ /dev/null @@ -1,735 +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 "WebKitTestServer.h" -#include "WebViewTest.h" -#include <wtf/gobject/GRefPtr.h> - -static WebKitTestServer* kServer; - -static const char* kIndexHtml = - "<html><head>" - " <link rel='stylesheet' href='/style.css' type='text/css'>" - " <script language='javascript' src='/javascript.js'></script>" - "</head><body>WebKitGTK+ resources test</body></html>"; - -static const char* kStyleCSS = - "body {" - " margin: 0px;" - " padding: 0px;" - " font-family: sans-serif;" - " background: url(/blank.ico) 0 0 no-repeat;" - " color: black;" - "}"; - -static const char* kJavascript = "function foo () { var a = 1; }"; - -class ResourcesTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(ResourcesTest); - - static void resourceSentRequestCallback(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse, ResourcesTest* test) - { - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request)); - if (redirectResponse) - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(redirectResponse)); - test->resourceSentRequest(resource, request, redirectResponse); - } - - static void resourceReceivedResponseCallback(WebKitWebResource* resource, GParamSpec*, ResourcesTest* test) - { - g_assert(webkit_web_resource_get_response(resource)); - test->resourceReceivedResponse(resource); - } - - static void resourceReceivedDataCallback(WebKitWebResource* resource, guint64 bytesReceived, ResourcesTest* test) - { - test->resourceReceivedData(resource, bytesReceived); - } - - static void resourceFinishedCallback(WebKitWebResource* resource, ResourcesTest* test) - { - test->resourceFinished(resource); - } - - static void resourceFailedCallback(WebKitWebResource* resource, GError* error, ResourcesTest* test) - { - g_assert(error); - test->resourceFailed(resource, error); - } - - static void resourceLoadStartedCallback(WebKitWebView* webView, WebKitWebResource* resource, WebKitURIRequest* request, ResourcesTest* test) - { - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(resource)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request)); - - // Ignore favicons. - if (g_str_has_suffix(webkit_uri_request_get_uri(request), "favicon.ico")) - return; - - test->resourceLoadStarted(resource, request); - g_signal_connect(resource, "sent-request", G_CALLBACK(resourceSentRequestCallback), test); - g_signal_connect(resource, "notify::response", G_CALLBACK(resourceReceivedResponseCallback), test); - g_signal_connect(resource, "received-data", G_CALLBACK(resourceReceivedDataCallback), test); - g_signal_connect(resource, "finished", G_CALLBACK(resourceFinishedCallback), test); - 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) - { - } - - virtual void resourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) - { - } - - virtual void resourceReceivedResponse(WebKitWebResource* resource) - { - } - - virtual void resourceReceivedData(WebKitWebResource* resource, guint64 bytesReceived) - { - } - - 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); - } - - virtual void resourceFailed(WebKitWebResource* resource, GError* error) - { - g_assert_not_reached(); - } - - void waitUntilResourcesLoaded(size_t resourcesCount) - { - 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; - GOwnPtr<GError> error; - unsigned char* data = webkit_web_resource_get_data_finish(WEBKIT_WEB_RESOURCE(object), result, &dataSize, &error.outPtr()); - g_assert(!error.get()); - g_assert(data); - g_assert_cmpint(dataSize, >, 0); - - ResourcesTest* test = static_cast<ResourcesTest*>(userData); - test->m_resourceData.set(reinterpret_cast<char*>(data)); - test->m_resourceDataSize = dataSize; - g_main_loop_quit(test->m_mainLoop); - } - - void checkResourceData(WebKitWebResource* resource) - { - m_resourceDataSize = 0; - webkit_web_resource_get_data(resource, 0, resourceGetDataCallback, this); - g_main_loop_run(m_mainLoop); - - const char* uri = webkit_web_resource_get_uri(resource); - if (uri == kServer->getURIForPath("/")) { - g_assert_cmpint(m_resourceDataSize, ==, strlen(kIndexHtml)); - g_assert(!strncmp(m_resourceData.get(), kIndexHtml, m_resourceDataSize)); - } else if (uri == kServer->getURIForPath("/style.css")) { - g_assert_cmpint(m_resourceDataSize, ==, strlen(kStyleCSS)); - g_assert(!strncmp(m_resourceData.get(), kStyleCSS, m_resourceDataSize)); - } else if (uri == kServer->getURIForPath("/javascript.js")) { - g_assert_cmpint(m_resourceDataSize, ==, strlen(kJavascript)); - g_assert(!strncmp(m_resourceData.get(), kJavascript, m_resourceDataSize)); - } else - g_assert_not_reached(); - m_resourceData.clear(); - } - - size_t m_resourcesLoaded; - 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(!test->subresources()); - - // Load simple page without subresources. - test->loadHtml("<html><body>Testing WebKitGTK+</body></html>", 0); - test->waitUntilLoadFinished(); - 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(!test->subresources()); - - // Load simple page with subresources. - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilResourcesLoaded(4); - - 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)); - GList* subresources = test->subresources(); - g_assert(subresources); - g_assert_cmpint(g_list_length(subresources), ==, 3); - -#if 0 - // Load the same URI again. - // FIXME: we need a workaround for bug https://bugs.webkit.org/show_bug.cgi?id=78510. - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilResourcesLoaded(4); -#endif - - // Reload. - webkit_web_view_reload_bypass_cache(test->m_webView); - test->waitUntilResourcesLoaded(4); -} - -class SingleResourceLoadTest: public ResourcesTest { -public: - MAKE_GLIB_TEST_FIXTURE(SingleResourceLoadTest); - - enum LoadEvents { - Started, - SentRequest, - Redirected, - ReceivedResponse, - ReceivedData, - Finished, - Failed - }; - - SingleResourceLoadTest() - : ResourcesTest() - , m_resourceDataReceived(0) - { - m_resourcesToLoad = 2; - } - - void resourceLoadStarted(WebKitWebResource* resource, WebKitURIRequest* request) - { - if (resource == webkit_web_view_get_main_resource(m_webView)) - return; - - m_resourceDataReceived = 0; - m_resource = resource; - m_loadEvents.append(Started); - } - - void resourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) - { - if (resource != m_resource) - return; - - if (redirectResponse) - m_loadEvents.append(Redirected); - else - m_loadEvents.append(SentRequest); - } - - void resourceReceivedResponse(WebKitWebResource* resource) - { - if (resource != m_resource) - return; - - m_loadEvents.append(ReceivedResponse); - } - - void resourceReceivedData(WebKitWebResource* resource, guint64 bytesReceived) - { - if (resource != m_resource) - return; - - m_resourceDataReceived += bytesReceived; - if (!m_loadEvents.contains(ReceivedData)) - m_loadEvents.append(ReceivedData); - } - - void resourceFinished(WebKitWebResource* resource) - { - if (resource != m_resource) { - ResourcesTest::resourceFinished(resource); - return; - } - - if (!m_loadEvents.contains(Failed)) { - WebKitURIResponse* response = webkit_web_resource_get_response(m_resource.get()); - g_assert(response); - g_assert_cmpint(webkit_uri_response_get_content_length(response), ==, m_resourceDataReceived); - } - m_loadEvents.append(Finished); - ResourcesTest::resourceFinished(resource); - } - - void resourceFailed(WebKitWebResource* resource, GError* error) - { - if (resource == m_resource) - m_loadEvents.append(Failed); - } - - void waitUntilResourceLoadFinished() - { - m_resource = 0; - m_resourcesLoaded = 0; - g_main_loop_run(m_mainLoop); - } - - WebKitURIResponse* waitUntilResourceLoadFinishedAndReturnURIResponse() - { - waitUntilResourceLoadFinished(); - g_assert(m_resource); - return webkit_web_resource_get_response(m_resource.get()); - } - - GRefPtr<WebKitWebResource> m_resource; - Vector<LoadEvents> m_loadEvents; - guint64 m_resourceDataReceived; -}; - -static void testWebResourceLoading(SingleResourceLoadTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/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(); - - test->loadURI(kServer->getURIForPath("/redirected-css.html").data()); - test->waitUntilResourceLoadFinished(); - g_assert(test->m_resource); - g_assert_cmpint(events.size(), ==, 6); - g_assert_cmpint(events[0], ==, SingleResourceLoadTest::Started); - g_assert_cmpint(events[1], ==, SingleResourceLoadTest::SentRequest); - g_assert_cmpint(events[2], ==, SingleResourceLoadTest::Redirected); - g_assert_cmpint(events[3], ==, SingleResourceLoadTest::ReceivedResponse); - g_assert_cmpint(events[4], ==, SingleResourceLoadTest::ReceivedData); - g_assert_cmpint(events[5], ==, SingleResourceLoadTest::Finished); - events.clear(); - - test->loadURI(kServer->getURIForPath("/invalid-css.html").data()); - test->waitUntilResourceLoadFinished(); - g_assert(test->m_resource); - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, SingleResourceLoadTest::Started); - g_assert_cmpint(events[1], ==, SingleResourceLoadTest::SentRequest); - g_assert_cmpint(events[2], ==, SingleResourceLoadTest::Failed); - g_assert_cmpint(events[3], ==, SingleResourceLoadTest::Finished); - events.clear(); -} - -static void testWebResourceResponse(SingleResourceLoadTest* test, gconstpointer) -{ - // No cached resource: First load. - test->loadURI(kServer->getURIForPath("/javascript.html").data()); - WebKitURIResponse* response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpint(webkit_uri_response_get_status_code(response), ==, SOUP_STATUS_OK); - - // No cached resource: Second load. - test->loadURI(kServer->getURIForPath("/javascript.html").data()); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpint(webkit_uri_response_get_status_code(response), ==, SOUP_STATUS_OK); - - // No cached resource: Reload. - webkit_web_view_reload(test->m_webView); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpint(webkit_uri_response_get_status_code(response), ==, SOUP_STATUS_OK); - - // Cached resource: First load. - test->loadURI(kServer->getURIForPath("/image.html").data()); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpint(webkit_uri_response_get_status_code(response), ==, SOUP_STATUS_OK); - - // Cached resource: Second load. - test->loadURI(kServer->getURIForPath("/image.html").data()); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpint(webkit_uri_response_get_status_code(response), ==, SOUP_STATUS_OK); - - // Cached resource: Reload. - webkit_web_view_reload(test->m_webView); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpint(webkit_uri_response_get_status_code(response), ==, SOUP_STATUS_NOT_MODIFIED); -} - -static void testWebResourceMimeType(SingleResourceLoadTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/javascript.html").data()); - WebKitURIResponse* response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpstr(webkit_uri_response_get_mime_type(response), ==, "text/javascript"); - - test->loadURI(kServer->getURIForPath("/image.html").data()); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpstr(webkit_uri_response_get_mime_type(response), ==, "image/vnd.microsoft.icon"); - - test->loadURI(kServer->getURIForPath("/redirected-css.html").data()); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpstr(webkit_uri_response_get_mime_type(response), ==, "text/css"); -} - -static void testWebResourceSuggestedFilename(SingleResourceLoadTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/javascript.html").data()); - WebKitURIResponse* response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert_cmpstr(webkit_uri_response_get_suggested_filename(response), ==, "JavaScript.js"); - - test->loadURI(kServer->getURIForPath("/image.html").data()); - response = test->waitUntilResourceLoadFinishedAndReturnURIResponse(); - g_assert(!webkit_uri_response_get_suggested_filename(response)); -} - -class ResourceURITrackingTest: public SingleResourceLoadTest { -public: - MAKE_GLIB_TEST_FIXTURE(ResourceURITrackingTest); - - ResourceURITrackingTest() - : SingleResourceLoadTest() - { - } - - static void uriChanged(WebKitWebResource* resource, GParamSpec*, ResourceURITrackingTest* test) - { - g_assert(resource == test->m_resource.get()); - g_assert_cmpstr(test->m_activeURI.data(), !=, webkit_web_resource_get_uri(test->m_resource.get())); - test->m_activeURI = webkit_web_resource_get_uri(test->m_resource.get()); - } - - void resourceLoadStarted(WebKitWebResource* resource, WebKitURIRequest* request) - { - if (resource == webkit_web_view_get_main_resource(m_webView)) - return; - - m_resource = resource; - m_activeURI = webkit_web_resource_get_uri(resource); - checkActiveURI("/redirected.css"); - g_assert_cmpstr(m_activeURI.data(), ==, webkit_uri_request_get_uri(request)); - g_signal_connect(resource, "notify::uri", G_CALLBACK(uriChanged), this); - } - - void resourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) - { - if (resource != m_resource) - return; - - if (redirectResponse) - checkActiveURI("/simple-style.css"); - else - checkActiveURI("/redirected.css"); - g_assert_cmpstr(m_activeURI.data(), ==, webkit_uri_request_get_uri(request)); - } - - void resourceReceivedResponse(WebKitWebResource* resource) - { - if (resource != m_resource) - return; - - checkActiveURI("/simple-style.css"); - } - - void resourceReceivedData(WebKitWebResource* resource, guint64 bytesReceived) - { - } - - void resourceFinished(WebKitWebResource* resource) - { - if (resource == m_resource) - checkActiveURI("/simple-style.css"); - ResourcesTest::resourceFinished(resource); - } - - void resourceFailed(WebKitWebResource*, GError*) - { - g_assert_not_reached(); - } - - CString m_activeURI; - -private: - void checkActiveURI(const char* uri) - { - ASSERT_CMP_CSTRING(m_activeURI, ==, kServer->getURIForPath(uri)); - } -}; - -static void testWebResourceActiveURI(ResourceURITrackingTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/redirected-css.html").data()); - test->waitUntilResourceLoadFinished(); -} - -static void testWebResourceGetData(ResourcesTest* test, gconstpointer) -{ - test->loadURI(kServer->getURIForPath("/").data()); - // FIXME: this should be 4 instead of 3, but we don't get the css image resource - // due to bug https://bugs.webkit.org/show_bug.cgi?id=78510. - test->waitUntilResourcesLoaded(3); - - WebKitWebResource* resource = webkit_web_view_get_main_resource(test->m_webView); - g_assert(resource); - test->checkResourceData(resource); - - GList* subresources = test->subresources(); - for (GList* item = subresources; item; item = g_list_next(item)) - test->checkResourceData(WEBKIT_WEB_RESOURCE(item->data)); -} - -static void testWebViewResourcesHistoryCache(SingleResourceLoadTest* test, gconstpointer) -{ - CString javascriptURI = kServer->getURIForPath("/javascript.html"); - test->loadURI(javascriptURI.data()); - test->waitUntilResourceLoadFinished(); - WebKitWebResource* resource = webkit_web_view_get_main_resource(test->m_webView); - g_assert(resource); - g_assert_cmpstr(webkit_web_resource_get_uri(resource), ==, javascriptURI.data()); - - CString simpleStyleCSSURI = kServer->getURIForPath("/simple-style-css.html"); - test->loadURI(simpleStyleCSSURI.data()); - test->waitUntilResourceLoadFinished(); - resource = webkit_web_view_get_main_resource(test->m_webView); - g_assert(resource); - g_assert_cmpstr(webkit_web_resource_get_uri(resource), ==, simpleStyleCSSURI.data()); - - test->goBack(); - test->waitUntilResourceLoadFinished(); - resource = webkit_web_view_get_main_resource(test->m_webView); - g_assert(resource); - g_assert_cmpstr(webkit_web_resource_get_uri(resource), ==, javascriptURI.data()); - - test->goForward(); - test->waitUntilResourceLoadFinished(); - resource = webkit_web_view_get_main_resource(test->m_webView); - g_assert(resource); - 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. - SoupDate* soupDate = soup_date_new_from_now(0); - GOwnPtr<char> date(soup_date_to_string(soupDate, SOUP_DATE_HTTP)); - soup_message_headers_append(message->response_headers, "Last-Modified", date.get()); - soup_date_free(soupDate); - soup_message_headers_append(message->response_headers, "Cache-control", "public, max-age=31536000"); - soupDate = soup_date_new_from_now(3600); - date.set(soup_date_to_string(soupDate, SOUP_DATE_HTTP)); - soup_message_headers_append(message->response_headers, "Expires", date.get()); - soup_date_free(soupDate); -} - -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 (soup_message_headers_get_one(message->request_headers, "If-Modified-Since")) { - soup_message_set_status(message, SOUP_STATUS_NOT_MODIFIED); - soup_message_body_complete(message->response_body); - return; - } - - if (g_str_equal(path, "/")) { - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, kIndexHtml, strlen(kIndexHtml)); - } else if (g_str_equal(path, "/javascript.html")) { - static const char* javascriptHtml = "<html><head><script language='javascript' src='/javascript.js'></script></head><body></body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, javascriptHtml, strlen(javascriptHtml)); - } else if (g_str_equal(path, "/image.html")) { - static const char* imageHTML = "<html><body><img src='/blank.ico'></img></body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, imageHTML, strlen(imageHTML)); - } else if (g_str_equal(path, "/redirected-css.html")) { - static const char* redirectedCSSHtml = "<html><head><link rel='stylesheet' href='/redirected.css' type='text/css'></head><body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, redirectedCSSHtml, strlen(redirectedCSSHtml)); - } else if (g_str_equal(path, "/invalid-css.html")) { - static const char* invalidCSSHtml = "<html><head><link rel='stylesheet' href='/invalid.css' type='text/css'></head><body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, invalidCSSHtml, strlen(invalidCSSHtml)); - } else if (g_str_equal(path, "/simple-style-css.html")) { - static const char* simpleStyleCSSHtml = "<html><head><link rel='stylesheet' href='/simple-style.css' type='text/css'></head><body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, simpleStyleCSSHtml, strlen(simpleStyleCSSHtml)); - } else if (g_str_equal(path, "/style.css")) { - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, kStyleCSS, strlen(kStyleCSS)); - addCacheHTTPHeadersToResponse(message); - } else if (g_str_equal(path, "/javascript.js")) { - 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; - gsize contentsLength; - g_file_get_contents(filePath.get(), &contents, &contentsLength, 0); - soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, contents, contentsLength); - addCacheHTTPHeadersToResponse(message); - } else if (g_str_equal(path, "/simple-style.css")) { - static const char* simpleCSS = - "body {" - " margin: 0px;" - " padding: 0px;" - "}"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, simpleCSS, strlen(simpleCSS)); - soup_message_headers_append(message->response_headers, "Content-Type", "text/css"); - } else if (g_str_equal(path, "/redirected.css")) { - soup_message_set_status(message, SOUP_STATUS_MOVED_PERMANENTLY); - soup_message_headers_append(message->response_headers, "Location", "/simple-style.css"); - } else if (g_str_equal(path, "/invalid.css")) - soup_message_set_status(message, SOUP_STATUS_CANT_CONNECT); - else - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); - soup_message_body_complete(message->response_body); -} - -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); - SingleResourceLoadTest::add("WebKitWebResource", "mime-type", testWebResourceMimeType); - SingleResourceLoadTest::add("WebKitWebResource", "suggested-filename", testWebResourceSuggestedFilename); - 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() -{ - delete kServer; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp deleted file mode 100644 index db6ccc852..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestSSL.cpp +++ /dev/null @@ -1,201 +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 "LoadTrackingTest.h" -#include "WebKitTestServer.h" -#include <gtk/gtk.h> - -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: - MAKE_GLIB_TEST_FIXTURE(SSLTest); - - SSLTest() - : m_tlsErrors(static_cast<GTlsCertificateFlags>(0)) - { - } - - virtual void provisionalLoadFailed(const gchar* failingURI, GError* error) - { - g_assert_error(error, SOUP_HTTP_ERROR, SOUP_STATUS_SSL_FAILED); - LoadTrackingTest::provisionalLoadFailed(failingURI, error); - } - - virtual void loadCommitted() - { - GTlsCertificate* certificate = 0; - webkit_web_view_get_tls_info(m_webView, &certificate, &m_tlsErrors); - m_certificate = certificate; - LoadTrackingTest::loadCommitted(); - } - - void waitUntilLoadFinished() - { - m_certificate = 0; - m_tlsErrors = static_cast<GTlsCertificateFlags>(0); - LoadTrackingTest::waitUntilLoadFinished(); - } - - GRefPtr<GTlsCertificate> m_certificate; - GTlsCertificateFlags m_tlsErrors; -}; - -static void testSSL(SSLTest* test, gconstpointer) -{ - test->loadURI(kHttpsServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - g_assert(test->m_certificate); - // We always expect errors because we are using a self-signed certificate, - // but only G_TLS_CERTIFICATE_UNKNOWN_CA flags should be present. - g_assert(test->m_tlsErrors); - g_assert_cmpuint(test->m_tlsErrors, ==, G_TLS_CERTIFICATE_UNKNOWN_CA); - - // Non HTTPS loads shouldn't have a certificate nor errors. - test->loadHtml(indexHTML, 0); - test->waitUntilLoadFinished(); - g_assert(!test->m_certificate); - g_assert(!test->m_tlsErrors); -} - -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); - return; - } - - if (g_str_equal(path, "/")) { - 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() -{ - 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 kHttpsServer; - delete kHttpServer; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp deleted file mode 100644 index 527cc936c..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebExtensions.cpp +++ /dev/null @@ -1,118 +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 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 deleted file mode 100644 index d3750c005..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitAccessibility.cpp +++ /dev/null @@ -1,225 +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 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 "TestMain.h" -#include "WebViewTest.h" - -// The libatspi headers don't use G_BEGIN_DECLS -extern "C" { -#include <atspi/atspi.h> -} - -#include <errno.h> -#include <fcntl.h> -#include <glib.h> -#include <signal.h> -#include <unistd.h> -#include <wtf/PassRefPtr.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> - -// Name of the test server application creating the webView object. -static const char* kTestServerAppName = "AccessibilityTestServer"; - -// Max seconds to wait for the test server before inspecting it. -static const int kMaxWaitForChild = 5; - -// The PID for the test server running, so we can kill it if needed. -static GPid kChildProcessPid = 0; - -// Whether the child has replied and it's ready. -static bool kChildIsReady = false; - -static void stopTestServer() -{ - // Do nothing if there's no server running. - if (!kChildProcessPid) - return; - - g_spawn_close_pid(kChildProcessPid); - kill(kChildProcessPid, SIGTERM); - kChildProcessPid = 0; -} - -static void sigAbortHandler(int sigNum) -{ - // Just stop the test server if SIGABRT was received. - stopTestServer(); -} - -static gpointer testServerMonitorThreadFunc(gpointer) -{ - // Wait for the specified timeout to happen. - g_usleep(kMaxWaitForChild * G_USEC_PER_SEC); - - // Kill the child process if not ready yet. - if (!kChildIsReady) - stopTestServer(); - - g_thread_exit(0); - return 0; -} - -static void startTestServerMonitor() -{ - kChildIsReady = false; - g_thread_new("TestServerMonitor", testServerMonitorThreadFunc, 0); -} - -static void startTestServer() -{ - // Prepare argv[] for spawning the server process. - GOwnPtr<char> testServerPath(g_build_filename(WEBKIT_EXEC_PATH, "WebKit2APITests", kTestServerAppName, NULL)); - - char* testServerArgv[2]; - testServerArgv[0] = testServerPath.get(); - testServerArgv[1] = 0; - - // Spawn the server, getting its stdout file descriptor to set a - // communication channel, so we know when it's ready. - int childStdout = 0; - if (!g_spawn_async_with_pipes(0, testServerArgv, 0, static_cast<GSpawnFlags>(0), 0, 0, - &kChildProcessPid, 0, &childStdout, 0, 0)) { - close(childStdout); - return; - } - - // Start monitoring the test server (in a separate thread) to - // ensure we don't block on the child process more than a timeout. - startTestServerMonitor(); - - char msg[2]; - GIOChannel* ioChannel = g_io_channel_unix_new(childStdout); - if (g_io_channel_read_chars(ioChannel, msg, 2, 0, 0) == G_IO_STATUS_NORMAL) { - // Check whether the server sent a message saying it's ready - // and store the result globally, so the monitor can see it. - kChildIsReady = msg[0] == 'O' && msg[1] == 'K'; - } - g_io_channel_unref(ioChannel); - close(childStdout); - - // The timeout was reached and the server is not ready yet, so - // stop it inmediately, and let the unit tests fail. - if (!kChildIsReady) - stopTestServer(); -} - -static void checkAtspiAccessible(AtspiAccessible* accessible, const char* targetName, AtspiRole targetRole) -{ - g_assert(ATSPI_IS_ACCESSIBLE(accessible)); - - GOwnPtr<char> name(atspi_accessible_get_name(accessible, 0)); - g_assert_cmpstr(targetName, ==, name.get()); - g_assert_cmpint(targetRole, ==, atspi_accessible_get_role(accessible, 0)); -} - -static GRefPtr<AtspiAccessible> findTestServerApplication() -{ - // Only one desktop is supported by ATSPI at the moment. - GRefPtr<AtspiAccessible> desktop = adoptGRef(atspi_get_desktop(0)); - - // Look for the server application in the list of apps. - GRefPtr<AtspiAccessible> current; - int childCount = atspi_accessible_get_child_count(desktop.get(), 0); - for (int i = 0; i < childCount; i++) { - current = adoptGRef(atspi_accessible_get_child_at_index(desktop.get(), i, 0)); - if (!g_strcmp0(atspi_accessible_get_name(current.get(), 0), kTestServerAppName)) - return current; - } - - return 0; -} - -static void testAtspiBasicHierarchy(WebViewTest* test, gconstpointer) -{ - // The test server's accessibility object (UI Process). - GRefPtr<AtspiAccessible> testServerApp = findTestServerApplication(); - g_assert(ATSPI_IS_ACCESSIBLE(testServerApp.get())); - checkAtspiAccessible(testServerApp.get(), "AccessibilityTestServer", ATSPI_ROLE_APPLICATION); - - // The main window's accessibility object (UI Process). - GRefPtr<AtspiAccessible> currentParent = testServerApp; - GRefPtr<AtspiAccessible> currentChild = adoptGRef(atspi_accessible_get_child_at_index(currentParent.get(), 0, 0)); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "", ATSPI_ROLE_FRAME); - - // The WebView's accessibility object (UI Process). - currentParent = currentChild; - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 0, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "", ATSPI_ROLE_FILLER); - - // The WebPage's accessibility object (Web Process). - currentParent = currentChild; - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 0, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "", ATSPI_ROLE_FILLER); - - // HTML root element's accessible element (Web Process). - currentParent = currentChild; - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 0, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - - // HTML body's accessible element (Web Process). - currentParent = currentChild; - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 0, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "", ATSPI_ROLE_DOCUMENT_FRAME); - - // HTML H1's accessible element (Web Process). - currentParent = currentChild; - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 0, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "This is a test", ATSPI_ROLE_HEADING); - - // HTML first paragraph's accessible element (Web Process). - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 1, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "", ATSPI_ROLE_PARAGRAPH); - - // HTML second paragraph's accessible element (Web Process). - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 2, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "", ATSPI_ROLE_PARAGRAPH); - - // HTML link's accessible element (Web Process). - currentParent = currentChild; - currentChild = atspi_accessible_get_child_at_index(currentParent.get(), 0, 0); - g_assert(ATSPI_IS_ACCESSIBLE(currentChild.get())); - checkAtspiAccessible(currentChild.get(), "a link", ATSPI_ROLE_LINK); -} - -void beforeAll() -{ - // We install a handler to ensure that we kill the child process - // if the parent dies because of whatever the reason is. - signal(SIGABRT, sigAbortHandler); - - // Start the accessibility test server and load the tests. - startTestServer(); - WebViewTest::add("WebKitAccessibility", "atspi-basic-hierarchy", testAtspiBasicHierarchy); -} - -void afterAll() -{ - // Ensure we stop the server. - stopTestServer(); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp deleted file mode 100644 index 1a06f7496..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFaviconDatabase.cpp +++ /dev/null @@ -1,274 +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 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 <glib/gstdio.h> -#include <libsoup/soup.h> -#include <wtf/gobject/GOwnPtr.h> - -static WebKitTestServer* kServer; -static char* kTempDirectory; - -class FaviconDatabaseTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(FaviconDatabaseTest); - - FaviconDatabaseTest() - : m_webContext(webkit_web_context_get_default()) - , m_favicon(0) - , m_error(0) - , m_faviconNotificationReceived(false) - { - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(m_webContext); - g_signal_connect(database, "favicon-changed", G_CALLBACK(faviconChangedCallback), this); - } - - ~FaviconDatabaseTest() - { - if (m_favicon) - cairo_surface_destroy(m_favicon); - - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(m_webContext); - g_signal_handlers_disconnect_matched(database, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - static void faviconChangedCallback(WebKitFaviconDatabase* database, const char* pageURI, const char* faviconURI, FaviconDatabaseTest* test) - { - if (!g_strcmp0(webkit_web_view_get_uri(test->m_webView), pageURI)) - test->m_faviconURI = faviconURI; - } - - static void viewFaviconChangedCallback(WebKitWebView* webView, GParamSpec* pspec, gpointer data) - { - FaviconDatabaseTest* test = static_cast<FaviconDatabaseTest*>(data); - g_assert(test->m_webView == webView); - test->m_faviconNotificationReceived = true; - test->quitMainLoop(); - } - - static void getFaviconCallback(GObject* sourceObject, GAsyncResult* result, void* data) - { - FaviconDatabaseTest* test = static_cast<FaviconDatabaseTest*>(data); - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(test->m_webContext); - test->m_favicon = webkit_favicon_database_get_favicon_finish(database, result, &test->m_error.outPtr()); - test->quitMainLoop(); - } - - void waitUntilFaviconChanged() - { - m_faviconNotificationReceived = false; - unsigned long handlerID = g_signal_connect(m_webView, "notify::favicon", G_CALLBACK(viewFaviconChangedCallback), this); - g_main_loop_run(m_mainLoop); - g_signal_handler_disconnect(m_webView, handlerID); - } - - void getFaviconForPageURIAndWaitUntilReady(const char* pageURI) - { - m_error.clear(); - if (m_favicon) { - cairo_surface_destroy(m_favicon); - m_favicon = 0; - } - - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(m_webContext); - webkit_favicon_database_get_favicon(database, pageURI, 0, getFaviconCallback, this); - g_main_loop_run(m_mainLoop); - } - - WebKitWebContext* m_webContext; - cairo_surface_t* m_favicon; - CString m_faviconURI; - GOwnPtr<GError> m_error; - bool m_faviconNotificationReceived; -}; - -static void -serverCallback(SoupServer* server, SoupMessage* message, const char* path, GHashTable* query, SoupClientContext* context, void* data) -{ - if (message->method != SOUP_METHOD_GET) { - soup_message_set_status(message, SOUP_STATUS_NOT_IMPLEMENTED); - return; - } - - if (g_str_equal(path, "/favicon.ico")) { - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); - soup_message_body_complete(message->response_body); - return; - } - - char* contents; - gsize length; - if (g_str_equal(path, "/icon/favicon.ico")) { - GOwnPtr<char> pathToFavicon(g_build_filename(Test::getWebKit1TestResoucesDir().data(), "blank.ico", NULL)); - g_file_get_contents(pathToFavicon.get(), &contents, &length, 0); - soup_message_body_append(message->response_body, SOUP_MEMORY_TAKE, contents, length); - } else if (g_str_equal(path, "/nofavicon")) { - static const char* noFaviconHTML = "<html><head><body>test</body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, noFaviconHTML, strlen(noFaviconHTML)); - } else { - static const char* contentsHTML = "<html><head><link rel='icon' href='/icon/favicon.ico' type='image/x-ico; charset=binary'></head><body>test</body></html>"; - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, contentsHTML, strlen(contentsHTML)); - } - - soup_message_set_status(message, SOUP_STATUS_OK); - soup_message_body_complete(message->response_body); -} - -static void testNotInitialized(FaviconDatabaseTest* test) -{ - // Try to retrieve a valid favicon from a not initialized database. - test->getFaviconForPageURIAndWaitUntilReady(kServer->getURIForPath("/foo").data()); - g_assert(!test->m_favicon); - g_assert(test->m_error); - g_assert_cmpint(test->m_error->code, ==, WEBKIT_FAVICON_DATABASE_ERROR_NOT_INITIALIZED); -} - -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) -{ - 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("/foo").data())); - g_assert(!iconURI); -} - -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. - test->loadURI(kServer->getURIForPath("/foo").data()); - test->waitUntilFaviconChanged(); - CString faviconURI = kServer->getURIForPath("/icon/favicon.ico"); - - // Check the API retrieving a valid favicon. - test->getFaviconForPageURIAndWaitUntilReady(kServer->getURIForPath("/foo").data()); - g_assert(test->m_favicon); - g_assert_cmpstr(test->m_faviconURI.data(), ==, faviconURI.data()); - g_assert(!test->m_error); - - // Check that width and height match those from blank.ico (16x16 favicon). - g_assert_cmpint(cairo_image_surface_get_width(test->m_favicon), ==, 16); - g_assert_cmpint(cairo_image_surface_get_height(test->m_favicon), ==, 16); - - // Check that another page with the same favicon return the same icon. - cairo_surface_t* favicon = cairo_surface_reference(test->m_favicon); - test->loadURI(kServer->getURIForPath("/bar").data()); - // It's a new page in the database, so favicon will change twice, first to reset it - // and then when the icon is loaded. - test->waitUntilFaviconChanged(); - test->waitUntilFaviconChanged(); - test->getFaviconForPageURIAndWaitUntilReady(kServer->getURIForPath("/bar").data()); - g_assert(test->m_favicon); - g_assert_cmpstr(test->m_faviconURI.data(), ==, faviconURI.data()); - g_assert(test->m_favicon == favicon); - g_assert(!test->m_error); - cairo_surface_destroy(favicon); - - // Check the API retrieving an invalid favicon. - test->loadURI(kServer->getURIForPath("/nofavicon").data()); - test->waitUntilFaviconChanged(); - - test->getFaviconForPageURIAndWaitUntilReady(kServer->getURIForPath("/nofavicon").data()); - g_assert(!test->m_favicon); - g_assert(test->m_error); -} - -static void testGetFaviconURI(FaviconDatabaseTest* test) -{ - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(test->m_webContext); - - 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) -{ - test->m_faviconURI = CString(); - - cairo_surface_t* iconFromWebView = webkit_web_view_get_favicon(test->m_webView); - g_assert(!iconFromWebView); - - test->loadURI(kServer->getURIForPath("/foo").data()); - test->waitUntilFaviconChanged(); - g_assert(test->m_faviconNotificationReceived); - // The icon is known and hasn't changed in the database, so notify::favicon is emitted - // but WebKitFaviconDatabase::icon-changed isn't. - g_assert(test->m_faviconURI.isNull()); - - iconFromWebView = webkit_web_view_get_favicon(test->m_webView); - g_assert(iconFromWebView); - g_assert_cmpuint(cairo_image_surface_get_width(iconFromWebView), ==, 16); - 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. - kServer = new WebKitTestServer(); - kServer->run(serverCallback); - - kTempDirectory = g_dir_make_tmp("WebKit2Tests-XXXXXX", 0); - g_assert(kTempDirectory); - - // Add tests to the suite. - FaviconDatabaseTest::add("WebKitFaviconDatabase", "favicon-database-test", testFaviconDatabase); -} - -static void webkitFaviconDatabaseFinalizedCallback(gpointer, GObject*) -{ - if (!g_file_test(kTempDirectory, G_FILE_TEST_IS_DIR)) - return; - - GOwnPtr<char> filename(g_build_filename(kTempDirectory, "WebpageIcons.db", NULL)); - g_unlink(filename.get()); - - g_rmdir(kTempDirectory); -} - -void afterAll() -{ - delete kServer; - - // Delete the temporary files after the IconDatabase has been - // closed, that is, once WebKitFaviconDatabase is being destroyed. - WebKitFaviconDatabase* database = webkit_web_context_get_favicon_database(webkit_web_context_get_default()); - g_object_weak_ref(G_OBJECT(database), webkitFaviconDatabaseFinalizedCallback, 0); -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp deleted file mode 100644 index d2eef4ca4..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitFindController.cpp +++ /dev/null @@ -1,335 +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 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 "LoadTrackingTest.h" -#include <gtk/gtk.h> -#include <webkit2/webkit2.h> -#include <wtf/gobject/GRefPtr.h> - -static const char* testString = "<html><body>first testing second testing secondHalf</body></html>"; - -class FindControllerTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(FindControllerTest); - - FindControllerTest() - : m_findController(webkit_web_view_get_find_controller(m_webView)) - , m_runFindUntilCompletion(false) - { - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_findController.get())); - } - - ~FindControllerTest() - { - if (m_findController) - g_signal_handlers_disconnect_matched(m_findController.get(), G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void find(const char* searchText, guint32 findOptions, guint maxMatchCount) - { - g_signal_connect(m_findController.get(), "found-text", G_CALLBACK(foundTextCallback), this); - g_signal_connect(m_findController.get(), "failed-to-find-text", G_CALLBACK(failedToFindTextCallback), this); - webkit_find_controller_search(m_findController.get(), searchText, findOptions, maxMatchCount); - } - - void count(const char* searchText, guint32 findOptions, guint maxMatchCount) - { - g_signal_connect(m_findController.get(), "counted-matches", G_CALLBACK(countedMatchesCallback), this); - webkit_find_controller_count_matches(m_findController.get(), searchText, findOptions, maxMatchCount); - } - - void waitUntilFindFinished() - { - m_runFindUntilCompletion = true; - g_main_loop_run(m_mainLoop); - } - - GRefPtr<WebKitFindController> m_findController; - bool m_textFound; - unsigned m_matchCount; - -private: - bool m_runFindUntilCompletion; - - static void foundTextCallback(WebKitFindController*, guint matchCount, FindControllerTest* test) - { - test->m_textFound = true; - test->m_matchCount = matchCount; - if (test->m_runFindUntilCompletion) - g_main_loop_quit(test->m_mainLoop); - } - - static void failedToFindTextCallback(WebKitFindController*, FindControllerTest* test) - { - test->m_textFound = false; - if (test->m_runFindUntilCompletion) - g_main_loop_quit(test->m_mainLoop); - } - - static void countedMatchesCallback(WebKitFindController*, guint matchCount, FindControllerTest* test) - { - test->m_matchCount = matchCount; - if (test->m_runFindUntilCompletion) - g_main_loop_quit(test->m_mainLoop); - } -}; - -static void testFindControllerTextFound(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("testing", WEBKIT_FIND_OPTIONS_NONE, 1); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); -} - -static void testFindControllerTextNotFound(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("notFound", WEBKIT_FIND_OPTIONS_NONE, 1); - test->waitUntilFindFinished(); - - g_assert(!test->m_textFound); -} - -static void testFindControllerMatchCount(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("testing", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_matchCount == 2); - g_assert(test->m_textFound); -} - -static void testFindControllerMaxMatchCount(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("testing", WEBKIT_FIND_OPTIONS_NONE, 1); - test->waitUntilFindFinished(); - - g_assert(test->m_matchCount == G_MAXUINT); - g_assert(test->m_textFound); -} - -static void testFindControllerNext(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("testing", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - g_assert(test->m_matchCount == 2); - - webkit_find_controller_search_next(test->m_findController.get()); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - g_assert(test->m_matchCount == 1); - g_assert(!(webkit_find_controller_get_options(test->m_findController.get()) & WEBKIT_FIND_OPTIONS_BACKWARDS)); - - webkit_find_controller_search_next(test->m_findController.get()); - test->waitUntilFindFinished(); - - g_assert(!test->m_textFound); - g_assert(test->m_matchCount == 1); - g_assert(!(webkit_find_controller_get_options(test->m_findController.get()) & WEBKIT_FIND_OPTIONS_BACKWARDS)); -} - -static void testFindControllerPrevious(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("testing", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_matchCount == 2); - g_assert(test->m_textFound); - - webkit_find_controller_search_next(test->m_findController.get()); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - g_assert(test->m_matchCount == 1); - g_assert(!(webkit_find_controller_get_options(test->m_findController.get()) & WEBKIT_FIND_OPTIONS_BACKWARDS)); - - webkit_find_controller_search_previous(test->m_findController.get()); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - g_assert(test->m_matchCount == 1); - g_assert(webkit_find_controller_get_options(test->m_findController.get()) & WEBKIT_FIND_OPTIONS_BACKWARDS); -} - -static void testFindControllerCountedMatches(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->count("testing", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_matchCount == 2); - - test->count("first", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_matchCount == 1); - - test->count("notFound", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(!test->m_matchCount); -} - -static void testFindControllerOptions(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->find("Testing", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(!test->m_textFound); - - test->find("Testing", WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - - test->find("esting", WEBKIT_FIND_OPTIONS_NONE, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - - test->find("esting", WEBKIT_FIND_OPTIONS_AT_WORD_STARTS, 2); - test->waitUntilFindFinished(); - - g_assert(!test->m_textFound); - - test->find("Half", WEBKIT_FIND_OPTIONS_AT_WORD_STARTS, 2); - test->waitUntilFindFinished(); - - g_assert(!test->m_textFound); - - test->find("Half", WEBKIT_FIND_OPTIONS_AT_WORD_STARTS | WEBKIT_FIND_OPTIONS_TREAT_MEDIAL_CAPITAL_AS_WORD_START, 2); - test->waitUntilFindFinished(); - - g_assert(test->m_textFound); - - test->find("testing", WEBKIT_FIND_OPTIONS_WRAP_AROUND, 3); - test->waitUntilFindFinished(); - g_assert(test->m_textFound); - - webkit_find_controller_search_next(test->m_findController.get()); - test->waitUntilFindFinished(); - g_assert(test->m_textFound); - - webkit_find_controller_search_next(test->m_findController.get()); - test->waitUntilFindFinished(); - g_assert(test->m_textFound); -} - -static void testFindControllerHide(FindControllerTest* test, gconstpointer) -{ - test->loadHtml(testString, 0); - test->waitUntilLoadFinished(); - - test->showInWindowAndWaitUntilMapped(); - - 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); - - 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"); - - 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) -{ - WebKitFindController* findController1 = webkit_web_view_get_find_controller(test->m_webView); - WebKitFindController* findController2 = webkit_web_view_get_find_controller(test->m_webView); - - g_assert(findController1 == findController2); -} - -static void testFindControllerGetters(FindControllerTest* test, gconstpointer) -{ - const char* searchText = "testing"; - guint maxMatchCount = 1; - guint32 findOptions = WEBKIT_FIND_OPTIONS_WRAP_AROUND | WEBKIT_FIND_OPTIONS_AT_WORD_STARTS; - WebKitFindController* findController = webkit_web_view_get_find_controller(test->m_webView); - - webkit_find_controller_search(findController, searchText, findOptions, maxMatchCount); - g_assert(webkit_find_controller_get_web_view(findController) == test->m_webView); - g_assert(!g_strcmp0(webkit_find_controller_get_search_text(findController), searchText)); - g_assert(webkit_find_controller_get_max_match_count(findController) == maxMatchCount); - g_assert(webkit_find_controller_get_options(findController) == findOptions); -} - -void beforeAll() -{ - FindControllerTest::add("WebKitFindController", "getters", testFindControllerGetters); - FindControllerTest::add("WebKitFindController", "instance", testFindControllerInstance); - FindControllerTest::add("WebKitFindController", "text-found", testFindControllerTextFound); - FindControllerTest::add("WebKitFindController", "text-not-found", testFindControllerTextNotFound); - FindControllerTest::add("WebKitFindController", "match-count", testFindControllerMatchCount); - FindControllerTest::add("WebKitFindController", "max-match-count", testFindControllerMaxMatchCount); - FindControllerTest::add("WebKitFindController", "next", testFindControllerNext); - FindControllerTest::add("WebKitFindController", "previous", testFindControllerPrevious); - FindControllerTest::add("WebKitFindController", "counted-matches", testFindControllerCountedMatches); - FindControllerTest::add("WebKitFindController", "options", testFindControllerOptions); - FindControllerTest::add("WebKitFindController", "hide", testFindControllerHide); -} - -void afterAll() -{ -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitPolicyClient.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitPolicyClient.cpp deleted file mode 100644 index abbfd652a..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitPolicyClient.cpp +++ /dev/null @@ -1,257 +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 "LoadTrackingTest.h" -#include "WebKitTestServer.h" -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -static WebKitTestServer* kServer; - -class PolicyClientTest: public LoadTrackingTest { -public: - MAKE_GLIB_TEST_FIXTURE(PolicyClientTest); - - enum PolicyDecisionResponse { - Use, - Ignore, - Download, - None - }; - - PolicyClientTest() - : LoadTrackingTest() - , m_policyDecisionResponse(None) - , m_policyDecisionTypeFilter(0) - , m_respondToPolicyDecisionAsynchronously(false) - , m_haltMainLoopAfterMakingDecision(false) - { - g_signal_connect(m_webView, "decide-policy", G_CALLBACK(decidePolicyCallback), this); - } - - static gboolean quitMainLoopLater(GMainLoop* loop) - { - g_main_loop_quit(loop); - return FALSE; - } - - static void respondToPolicyDecision(PolicyClientTest* test, WebKitPolicyDecision* decision) - { - switch (test->m_policyDecisionResponse) { - case Use: - webkit_policy_decision_use(decision); - break; - case Ignore: - webkit_policy_decision_ignore(decision); - break; - case Download: - webkit_policy_decision_download(decision); - break; - case None: - break; - } - - if (test->m_haltMainLoopAfterMakingDecision) - g_idle_add(reinterpret_cast<GSourceFunc>(quitMainLoopLater), test->m_mainLoop); - } - - static gboolean respondToPolicyDecisionLater(PolicyClientTest* test) - { - respondToPolicyDecision(test, test->m_previousPolicyDecision.get()); - test->m_previousPolicyDecision = 0; - return FALSE; - } - - static gboolean decidePolicyCallback(WebKitWebView* webView, WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, PolicyClientTest* test) - { - if (test->m_policyDecisionTypeFilter != type) - return FALSE; - - test->m_previousPolicyDecision = decision; - if (test->m_respondToPolicyDecisionAsynchronously) { - g_idle_add(reinterpret_cast<GSourceFunc>(respondToPolicyDecisionLater), test); - return TRUE; - } - - respondToPolicyDecision(test, decision); - - // We return FALSE here to ensure that the default policy decision - // handler doesn't override whatever we use here. - return FALSE; - } - - PolicyDecisionResponse m_policyDecisionResponse; - int m_policyDecisionTypeFilter; - bool m_respondToPolicyDecisionAsynchronously; - bool m_haltMainLoopAfterMakingDecision; - GRefPtr<WebKitPolicyDecision> m_previousPolicyDecision; -}; - -static void testNavigationPolicy(PolicyClientTest* test, gconstpointer) -{ - test->m_policyDecisionTypeFilter = WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION; - - test->m_policyDecisionResponse = PolicyClientTest::Use; - test->loadHtml("<html/>", "http://webkitgtk.org/"); - test->waitUntilLoadFinished(); - g_assert_cmpint(test->m_loadEvents.size(), ==, 3); - - // Ideally we'd like to have a more intensive test here, but it's still pretty tricky - // to trigger different types of navigations with the GTK+ WebKit2 API. - WebKitNavigationPolicyDecision* decision = WEBKIT_NAVIGATION_POLICY_DECISION(test->m_previousPolicyDecision.get()); - g_assert_cmpint(webkit_navigation_policy_decision_get_navigation_type(decision), ==, WEBKIT_NAVIGATION_TYPE_OTHER); - g_assert_cmpint(webkit_navigation_policy_decision_get_mouse_button(decision), ==, 0); - g_assert_cmpint(webkit_navigation_policy_decision_get_modifiers(decision), ==, 0); - g_assert_cmpstr(webkit_navigation_policy_decision_get_frame_name(decision), ==, 0); - WebKitURIRequest* request = webkit_navigation_policy_decision_get_request(decision); - g_assert_cmpstr(webkit_uri_request_get_uri(request), ==, "http://webkitgtk.org/"); - - test->m_policyDecisionResponse = PolicyClientTest::Use; - test->m_respondToPolicyDecisionAsynchronously = true; - test->loadHtml("<html/>", "http://webkitgtk.org/"); - test->waitUntilLoadFinished(); - g_assert_cmpint(test->m_loadEvents.size(), ==, 3); - - // If we are waiting until load completion, it will never complete if we ignore the - // navigation. So we tell the main loop to quit sometime later. - test->m_policyDecisionResponse = PolicyClientTest::Ignore; - test->m_respondToPolicyDecisionAsynchronously = false; - test->m_haltMainLoopAfterMakingDecision = true; - test->loadHtml("<html/>", "http://webkitgtk.org/"); - test->waitUntilLoadFinished(); - g_assert_cmpint(test->m_loadEvents.size(), ==, 0); - - test->m_policyDecisionResponse = PolicyClientTest::Ignore; - test->loadHtml("<html/>", "http://webkitgtk.org/"); - test->waitUntilLoadFinished(); - g_assert_cmpint(test->m_loadEvents.size(), ==, 0); -} - -static void testResponsePolicy(PolicyClientTest* test, gconstpointer) -{ - test->m_policyDecisionTypeFilter = WEBKIT_POLICY_DECISION_TYPE_RESPONSE; - - test->m_policyDecisionResponse = PolicyClientTest::Use; - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - g_assert_cmpint(test->m_loadEvents.size(), ==, 3); - g_assert_cmpint(test->m_loadEvents[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(test->m_loadEvents[1], ==, LoadTrackingTest::LoadCommitted); - g_assert_cmpint(test->m_loadEvents[2], ==, LoadTrackingTest::LoadFinished); - - test->m_respondToPolicyDecisionAsynchronously = true; - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - g_assert_cmpint(test->m_loadEvents.size(), ==, 3); - g_assert_cmpint(test->m_loadEvents[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(test->m_loadEvents[1], ==, LoadTrackingTest::LoadCommitted); - g_assert_cmpint(test->m_loadEvents[2], ==, LoadTrackingTest::LoadFinished); - - test->m_respondToPolicyDecisionAsynchronously = false; - test->m_policyDecisionResponse = PolicyClientTest::Ignore; - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - - g_assert_cmpint(test->m_loadEvents.size(), ==, 3); - g_assert_cmpint(test->m_loadEvents[0], ==, LoadTrackingTest::ProvisionalLoadStarted); - g_assert_cmpint(test->m_loadEvents[1], ==, LoadTrackingTest::ProvisionalLoadFailed); - g_assert_cmpint(test->m_loadEvents[2], ==, LoadTrackingTest::LoadFinished); -} - -struct CreateCallbackData { - bool triedToOpenWindow; - GMainLoop* mainLoop; -}; - -static WebKitWebView* createCallback(WebKitWebView* webView, CreateCallbackData* data) -{ - data->triedToOpenWindow = true; - g_main_loop_quit(data->mainLoop); - return 0; -} - -static void testNewWindowPolicy(PolicyClientTest* test, gconstpointer) -{ - static const char* windowOpeningHTML = - "<html><body>" - " <a id=\"link\" href=\"http://www.google.com\" target=\"_blank\">Link</a>" - " <script>" - " var event = document.createEvent('MouseEvents');" - " event.initEvent('click', true, false);" - " document.getElementById('link').dispatchEvent(event);" - " </script>" - "</body></html>"; - test->m_policyDecisionTypeFilter = WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION; - webkit_settings_set_javascript_can_open_windows_automatically(webkit_web_view_get_settings(test->m_webView), TRUE); - - CreateCallbackData data; - data.triedToOpenWindow = false; - data.mainLoop = test->m_mainLoop; - - g_signal_connect(test->m_webView, "create", G_CALLBACK(createCallback), &data); - test->m_policyDecisionResponse = PolicyClientTest::Use; - test->loadHtml(windowOpeningHTML, "http://webkitgtk.org/"); - test->wait(1); - g_assert(data.triedToOpenWindow); - - WebKitNavigationPolicyDecision* decision = WEBKIT_NAVIGATION_POLICY_DECISION(test->m_previousPolicyDecision.get()); - g_assert_cmpstr(webkit_navigation_policy_decision_get_frame_name(decision), ==, "_blank"); - - // Using a short timeout is a bit ugly here, but it's hard to get around because if we block - // the new window signal we cannot halt the main loop in the create callback. If we - // halt the main loop in the policy decision, the create callback never executes. - data.triedToOpenWindow = false; - test->m_policyDecisionResponse = PolicyClientTest::Ignore; - test->loadHtml(windowOpeningHTML, "http://webkitgtk.org/"); - test->wait(.2); - g_assert(!data.triedToOpenWindow); -} - -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; - } - - if (g_str_equal(path, "/")) { - static const char* responseString = "<html><body>Testing!</body></html>"; - soup_message_set_status(message, SOUP_STATUS_OK); - soup_message_body_append(message->response_body, SOUP_MEMORY_STATIC, responseString, strlen(responseString)); - soup_message_body_complete(message->response_body); - } else - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); -} - -void beforeAll() -{ - kServer = new WebKitTestServer(); - kServer->run(serverCallback); - - PolicyClientTest::add("WebKitPolicyClient", "navigation-policy", testNavigationPolicy); - PolicyClientTest::add("WebKitPolicyClient", "response-policy", testResponsePolicy); - PolicyClientTest::add("WebKitPolicyClient", "new-window-policy", testNewWindowPolicy); -} - -void afterAll() -{ - delete kServer; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp deleted file mode 100644 index 1ee3843f9..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitSettings.cpp +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * - * Neither the name of Motorola Mobility, Inc. nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "TestMain.h" -#include "WebViewTest.h" -#include "WebKitTestServer.h" -#include <gtk/gtk.h> -#include <webkit2/webkit2.h> -#include <wtf/gobject/GRefPtr.h> - -static WebKitTestServer* gServer; - -static void testWebKitSettings(Test*, gconstpointer) -{ - WebKitSettings* settings = webkit_settings_new(); - - // JavaScript is enabled by default. - g_assert(webkit_settings_get_enable_javascript(settings)); - webkit_settings_set_enable_javascript(settings, FALSE); - g_assert(!webkit_settings_get_enable_javascript(settings)); - - // By default auto-load-image is true. - g_assert(webkit_settings_get_auto_load_images(settings)); - webkit_settings_set_auto_load_images(settings, FALSE); - g_assert(!webkit_settings_get_auto_load_images(settings)); - - // load-icons-ignoring-image-load-setting is false by default. - g_assert(!webkit_settings_get_load_icons_ignoring_image_load_setting(settings)); - webkit_settings_set_load_icons_ignoring_image_load_setting(settings, TRUE); - g_assert(webkit_settings_get_load_icons_ignoring_image_load_setting(settings)); - - // Offline application cache is true by default. - g_assert(webkit_settings_get_enable_offline_web_application_cache(settings)); - webkit_settings_set_enable_offline_web_application_cache(settings, FALSE); - g_assert(!webkit_settings_get_enable_offline_web_application_cache(settings)); - - // Local storage is enable by default. - g_assert(webkit_settings_get_enable_html5_local_storage(settings)); - webkit_settings_set_enable_html5_local_storage(settings, FALSE); - g_assert(!webkit_settings_get_enable_html5_local_storage(settings)); - - // HTML5 database is enabled by default. - g_assert(webkit_settings_get_enable_html5_database(settings)); - webkit_settings_set_enable_html5_database(settings, FALSE); - g_assert(!webkit_settings_get_enable_html5_database(settings)); - - // XSS Auditor is enabled by default. - g_assert(webkit_settings_get_enable_xss_auditor(settings)); - webkit_settings_set_enable_xss_auditor(settings, FALSE); - g_assert(!webkit_settings_get_enable_xss_auditor(settings)); - - // Frame flattening is disabled by default. - g_assert(!webkit_settings_get_enable_frame_flattening(settings)); - webkit_settings_set_enable_frame_flattening(settings, TRUE); - g_assert(webkit_settings_get_enable_frame_flattening(settings)); - - // Plugins are enabled by default. - g_assert(webkit_settings_get_enable_plugins(settings)); - webkit_settings_set_enable_plugins(settings, FALSE); - g_assert(!webkit_settings_get_enable_plugins(settings)); - - // Java is enabled by default. - g_assert(webkit_settings_get_enable_java(settings)); - webkit_settings_set_enable_java(settings, FALSE); - g_assert(!webkit_settings_get_enable_java(settings)); - - // By default, JavaScript can open windows automatically is disabled. - g_assert(!webkit_settings_get_javascript_can_open_windows_automatically(settings)); - webkit_settings_set_javascript_can_open_windows_automatically(settings, TRUE); - g_assert(webkit_settings_get_javascript_can_open_windows_automatically(settings)); - - // By default hyper link auditing is disabled. - g_assert(!webkit_settings_get_enable_hyperlink_auditing(settings)); - webkit_settings_set_enable_hyperlink_auditing(settings, TRUE); - g_assert(webkit_settings_get_enable_hyperlink_auditing(settings)); - - // Default font family is "sans-serif". - g_assert_cmpstr(webkit_settings_get_default_font_family(settings), ==, "sans-serif"); - webkit_settings_set_default_font_family(settings, "monospace"); - g_assert_cmpstr(webkit_settings_get_default_font_family(settings), ==, "monospace"); - - // Default monospace font family font family is "monospace". - g_assert_cmpstr(webkit_settings_get_monospace_font_family(settings), ==, "monospace"); - webkit_settings_set_monospace_font_family(settings, "sans-serif"); - g_assert_cmpstr(webkit_settings_get_monospace_font_family(settings), ==, "sans-serif"); - - // Default serif font family is "serif". - g_assert_cmpstr(webkit_settings_get_serif_font_family(settings), ==, "serif"); - webkit_settings_set_serif_font_family(settings, "sans-serif"); - g_assert_cmpstr(webkit_settings_get_serif_font_family(settings), ==, "sans-serif"); - - // Default sans serif font family is "sans-serif". - g_assert_cmpstr(webkit_settings_get_sans_serif_font_family(settings), ==, "sans-serif"); - webkit_settings_set_sans_serif_font_family(settings, "serif"); - g_assert_cmpstr(webkit_settings_get_sans_serif_font_family(settings), ==, "serif"); - - // Default cursive font family "serif". - g_assert_cmpstr(webkit_settings_get_cursive_font_family(settings), ==, "serif"); - webkit_settings_set_cursive_font_family(settings, "sans-serif"); - g_assert_cmpstr(webkit_settings_get_cursive_font_family(settings), ==, "sans-serif"); - - // Default fantasy font family is "serif". - g_assert_cmpstr(webkit_settings_get_fantasy_font_family(settings), ==, "serif"); - webkit_settings_set_fantasy_font_family(settings, "sans-serif"); - g_assert_cmpstr(webkit_settings_get_fantasy_font_family(settings), ==, "sans-serif"); - - // Default pictograph font family is "serif". - g_assert_cmpstr(webkit_settings_get_pictograph_font_family(settings), ==, "serif"); - webkit_settings_set_pictograph_font_family(settings, "sans-serif"); - g_assert_cmpstr(webkit_settings_get_pictograph_font_family(settings), ==, "sans-serif"); - - // Default font size is 16. - g_assert_cmpuint(webkit_settings_get_default_font_size(settings), ==, 16); - webkit_settings_set_default_font_size(settings, 14); - g_assert_cmpuint(webkit_settings_get_default_font_size(settings), ==, 14); - - // Default monospace font size is 13. - g_assert_cmpuint(webkit_settings_get_default_monospace_font_size(settings), ==, 13); - webkit_settings_set_default_monospace_font_size(settings, 10); - g_assert_cmpuint(webkit_settings_get_default_monospace_font_size(settings), ==, 10); - - // Default minimum font size is 0. - g_assert_cmpuint(webkit_settings_get_minimum_font_size(settings), ==, 0); - webkit_settings_set_minimum_font_size(settings, 7); - g_assert_cmpuint(webkit_settings_get_minimum_font_size(settings), ==, 7); - - // Default charset is "iso-8859-1". - g_assert_cmpstr(webkit_settings_get_default_charset(settings), ==, "iso-8859-1"); - webkit_settings_set_default_charset(settings, "utf8"); - g_assert_cmpstr(webkit_settings_get_default_charset(settings), ==, "utf8"); - - g_assert(!webkit_settings_get_enable_private_browsing(settings)); - webkit_settings_set_enable_private_browsing(settings, TRUE); - g_assert(webkit_settings_get_enable_private_browsing(settings)); - - g_assert(!webkit_settings_get_enable_developer_extras(settings)); - webkit_settings_set_enable_developer_extras(settings, TRUE); - g_assert(webkit_settings_get_enable_developer_extras(settings)); - - g_assert(webkit_settings_get_enable_resizable_text_areas(settings)); - webkit_settings_set_enable_resizable_text_areas(settings, FALSE); - g_assert(!webkit_settings_get_enable_resizable_text_areas(settings)); - - g_assert(webkit_settings_get_enable_tabs_to_links(settings)); - webkit_settings_set_enable_tabs_to_links(settings, FALSE); - g_assert(!webkit_settings_get_enable_tabs_to_links(settings)); - - g_assert(!webkit_settings_get_enable_dns_prefetching(settings)); - webkit_settings_set_enable_dns_prefetching(settings, TRUE); - g_assert(webkit_settings_get_enable_dns_prefetching(settings)); - - // Caret browsing is disabled by default. - g_assert(!webkit_settings_get_enable_caret_browsing(settings)); - webkit_settings_set_enable_caret_browsing(settings, TRUE); - g_assert(webkit_settings_get_enable_caret_browsing(settings)); - - // Fullscreen JavaScript API is disabled by default. - g_assert(!webkit_settings_get_enable_fullscreen(settings)); - webkit_settings_set_enable_fullscreen(settings, TRUE); - g_assert(webkit_settings_get_enable_fullscreen(settings)); - - // Print backgrounds is enabled by default - g_assert(webkit_settings_get_print_backgrounds(settings)); - webkit_settings_set_print_backgrounds(settings, FALSE); - g_assert(!webkit_settings_get_print_backgrounds(settings)); - - // WebAudio is disabled by default. - g_assert(!webkit_settings_get_enable_webaudio(settings)); - webkit_settings_set_enable_webaudio(settings, TRUE); - g_assert(webkit_settings_get_enable_webaudio(settings)); - - // WebGL is disabled by default. - g_assert(!webkit_settings_get_enable_webgl(settings)); - webkit_settings_set_enable_webgl(settings, TRUE); - g_assert(webkit_settings_get_enable_webgl(settings)); - - // Allow Modal Dialogs is disabled by default. - g_assert(!webkit_settings_get_allow_modal_dialogs(settings)); - webkit_settings_set_allow_modal_dialogs(settings, TRUE); - g_assert(webkit_settings_get_allow_modal_dialogs(settings)); - - // Zoom text only is disabled by default. - g_assert(!webkit_settings_get_zoom_text_only(settings)); - webkit_settings_set_zoom_text_only(settings, TRUE); - g_assert(webkit_settings_get_zoom_text_only(settings)); - - // By default, JavaScript cannot access the clipboard. - g_assert(!webkit_settings_get_javascript_can_access_clipboard(settings)); - webkit_settings_set_javascript_can_access_clipboard(settings, TRUE); - g_assert(webkit_settings_get_javascript_can_access_clipboard(settings)); - - // By default, media playback doesn't require user gestures. - g_assert(!webkit_settings_get_media_playback_requires_user_gesture(settings)); - webkit_settings_set_media_playback_requires_user_gesture(settings, TRUE); - g_assert(webkit_settings_get_media_playback_requires_user_gesture(settings)); - - // By default, inline media playback is allowed - g_assert(webkit_settings_get_media_playback_allows_inline(settings)); - webkit_settings_set_media_playback_allows_inline(settings, FALSE); - g_assert(!webkit_settings_get_media_playback_allows_inline(settings)); - - // By default, debug indicators are disabled. - g_assert(!webkit_settings_get_draw_compositing_indicators(settings)); - webkit_settings_set_draw_compositing_indicators(settings, TRUE); - g_assert(webkit_settings_get_draw_compositing_indicators(settings)); - - // By default, site specific quirks are disabled. - g_assert(!webkit_settings_get_enable_site_specific_quirks(settings)); - webkit_settings_set_enable_site_specific_quirks(settings, TRUE); - g_assert(webkit_settings_get_enable_site_specific_quirks(settings)); - - // By default, page cache is enabled. - g_assert(webkit_settings_get_enable_page_cache(settings)); - webkit_settings_set_enable_page_cache(settings, FALSE); - g_assert(!webkit_settings_get_enable_page_cache(settings)); - - // By default, smooth scrolling is disabled. - g_assert(!webkit_settings_get_enable_smooth_scrolling(settings)); - 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)); -} - -void testWebKitSettingsNewWithSettings(Test* test, gconstpointer) -{ - GRefPtr<WebKitSettings> settings = adoptGRef(webkit_settings_new_with_settings("enable-javascript", FALSE, - "auto-load-images", FALSE, - "load-icons-ignoring-image-load-setting", TRUE, - NULL)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(settings.get())); - g_assert(!webkit_settings_get_enable_javascript(settings.get())); - g_assert(!webkit_settings_get_auto_load_images(settings.get())); - g_assert(webkit_settings_get_load_icons_ignoring_image_load_setting(settings.get())); -} - -static CString convertWebViewMainResourceDataToCString(WebViewTest* test) -{ - size_t mainResourceDataSize = 0; - const char* mainResourceData = test->mainResourceData(mainResourceDataSize); - return CString(mainResourceData, mainResourceDataSize); -} - -static void assertThatUserAgentIsSentInHeaders(WebViewTest* test, const CString& userAgent) -{ - test->loadURI(gServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - ASSERT_CMP_CSTRING(convertWebViewMainResourceDataToCString(test), ==, userAgent); -} - -static void testWebKitSettingsUserAgent(WebViewTest* test, gconstpointer) -{ - GRefPtr<WebKitSettings> settings = adoptGRef(webkit_settings_new()); - CString defaultUserAgent = webkit_settings_get_user_agent(settings.get()); - webkit_web_view_set_settings(test->m_webView, settings.get()); - - g_assert(g_strstr_len(defaultUserAgent.data(), -1, "Safari")); - g_assert(g_strstr_len(defaultUserAgent.data(), -1, "Chromium")); - g_assert(g_strstr_len(defaultUserAgent.data(), -1, "Chrome")); - - webkit_settings_set_user_agent(settings.get(), 0); - g_assert_cmpstr(defaultUserAgent.data(), ==, webkit_settings_get_user_agent(settings.get())); - assertThatUserAgentIsSentInHeaders(test, defaultUserAgent.data()); - - webkit_settings_set_user_agent(settings.get(), ""); - g_assert_cmpstr(defaultUserAgent.data(), ==, webkit_settings_get_user_agent(settings.get())); - - const char* funkyUserAgent = "Funky!"; - webkit_settings_set_user_agent(settings.get(), funkyUserAgent); - g_assert_cmpstr(funkyUserAgent, ==, webkit_settings_get_user_agent(settings.get())); - assertThatUserAgentIsSentInHeaders(test, funkyUserAgent); - - webkit_settings_set_user_agent_with_application_details(settings.get(), "WebKitGTK+", 0); - 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); - - webkit_settings_set_user_agent_with_application_details(settings.get(), "WebCatGTK+", "3.4.5"); - const char* newUserAgent = webkit_settings_get_user_agent(settings.get()); - g_assert(g_strstr_len(newUserAgent, -1, "3.4.5")); - g_assert(g_strstr_len(newUserAgent, -1, "WebCatGTK+")); -} - -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; - } - - if (g_str_equal(path, "/")) { - const char* userAgent = soup_message_headers_get_one(message->request_headers, "User-Agent"); - soup_message_set_status(message, SOUP_STATUS_OK); - soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, userAgent, strlen(userAgent)); - soup_message_body_complete(message->response_body); - } else - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); -} - -void beforeAll() -{ - gServer = new WebKitTestServer(); - gServer->run(serverCallback); - - Test::add("WebKitSettings", "webkit-settings", testWebKitSettings); - Test::add("WebKitSettings", "new-with-settings", testWebKitSettingsNewWithSettings); - WebViewTest::add("WebKitSettings", "user-agent", testWebKitSettingsUserAgent); -} - -void afterAll() -{ - delete gServer; -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitVersion.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitVersion.cpp deleted file mode 100644 index e747ff962..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitVersion.cpp +++ /dev/null @@ -1,50 +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 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 "TestMain.h" -#include <gtk/gtk.h> -#include <webkit2/webkit2.h> - - -static void testWebKitVersion(Test*, gconstpointer) -{ - g_assert_cmpuint(webkit_get_major_version(), ==, WEBKIT_MAJOR_VERSION); - g_assert_cmpuint(webkit_get_minor_version(), ==, WEBKIT_MINOR_VERSION); - g_assert_cmpuint(webkit_get_micro_version(), ==, WEBKIT_MICRO_VERSION); -} - -static void testWebKitCheckVersion(Test*, gconstpointer) -{ - g_assert(WEBKIT_CHECK_VERSION(WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION, WEBKIT_MICRO_VERSION)); - g_assert(!WEBKIT_CHECK_VERSION(WEBKIT_MAJOR_VERSION + 1, WEBKIT_MINOR_VERSION, WEBKIT_MICRO_VERSION)); - g_assert(!WEBKIT_CHECK_VERSION(WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION + 1, WEBKIT_MICRO_VERSION)); - g_assert(!WEBKIT_CHECK_VERSION(WEBKIT_MAJOR_VERSION, WEBKIT_MINOR_VERSION, WEBKIT_MICRO_VERSION + 1)); -} - -void beforeAll() -{ - Test::add("WebKitVersion", "version", testWebKitVersion); - Test::add("WebKitVersion", "check-version", testWebKitCheckVersion); -} - -void afterAll() -{ -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp deleted file mode 100644 index 54e44d682..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebContext.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Copyright (C) 2011 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 "LoadTrackingTest.h" -#include "WebKitTestServer.h" -#include <gtk/gtk.h> -#include <webkit2/webkit2.h> -#include <wtf/HashMap.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/StringHash.h> - -static WebKitTestServer* kServer; - -static void testWebContextDefault(Test* test, gconstpointer) -{ - // Check there's a single instance of the default web context. - g_assert(webkit_web_context_get_default() == webkit_web_context_get_default()); -} - -class PluginsTest: public Test { -public: - MAKE_GLIB_TEST_FIXTURE(PluginsTest); - - PluginsTest() - : m_context(webkit_web_context_get_default()) - , m_mainLoop(g_main_loop_new(0, TRUE)) - , m_plugins(0) - { - webkit_web_context_set_additional_plugins_directory(m_context, WEBKIT_TEST_PLUGIN_DIR); - } - - ~PluginsTest() - { - g_main_loop_unref(m_mainLoop); - g_list_free_full(m_plugins, g_object_unref); - } - - static void getPluginsAsyncReadyCallback(GObject*, GAsyncResult* result, PluginsTest* test) - { - test->m_plugins = webkit_web_context_get_plugins_finish(test->m_context, result, 0); - g_main_loop_quit(test->m_mainLoop); - } - - GList* getPlugins() - { - g_list_free_full(m_plugins, g_object_unref); - webkit_web_context_get_plugins(m_context, 0, reinterpret_cast<GAsyncReadyCallback>(getPluginsAsyncReadyCallback), this); - g_main_loop_run(m_mainLoop); - return m_plugins; - } - - WebKitWebContext* m_context; - GMainLoop* m_mainLoop; - GList* m_plugins; -}; - -static void testWebContextGetPlugins(PluginsTest* test, gconstpointer) -{ - GList* plugins = test->getPlugins(); - g_assert(plugins); - - GRefPtr<WebKitPlugin> testPlugin; - for (GList* item = plugins; item; item = g_list_next(item)) { - WebKitPlugin* plugin = WEBKIT_PLUGIN(item->data); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(plugin)); - if (!g_strcmp0(webkit_plugin_get_name(plugin), "WebKit Test PlugIn")) { - testPlugin = plugin; - break; - } - } - g_assert(WEBKIT_IS_PLUGIN(testPlugin.get())); - - GOwnPtr<char> pluginPath(g_build_filename(WEBKIT_TEST_PLUGIN_DIR, "libtestnetscapeplugin.so", NULL)); - g_assert_cmpstr(webkit_plugin_get_path(testPlugin.get()), ==, pluginPath.get()); - g_assert_cmpstr(webkit_plugin_get_description(testPlugin.get()), ==, "Simple Netscape® plug-in that handles test content for WebKit"); - GList* mimeInfoList = webkit_plugin_get_mime_info_list(testPlugin.get()); - g_assert(mimeInfoList); - g_assert_cmpuint(g_list_length(mimeInfoList), ==, 2); - - WebKitMimeInfo* mimeInfo = static_cast<WebKitMimeInfo*>(mimeInfoList->data); - g_assert_cmpstr(webkit_mime_info_get_mime_type(mimeInfo), ==, "image/png"); - g_assert_cmpstr(webkit_mime_info_get_description(mimeInfo), ==, "png image"); - const gchar* const* extensions = webkit_mime_info_get_extensions(mimeInfo); - g_assert(extensions); - g_assert_cmpstr(extensions[0], ==, "png"); - - mimeInfoList = g_list_next(mimeInfoList); - mimeInfo = static_cast<WebKitMimeInfo*>(mimeInfoList->data); - g_assert_cmpstr(webkit_mime_info_get_mime_type(mimeInfo), ==, "application/x-webkit-test-netscape"); - g_assert_cmpstr(webkit_mime_info_get_description(mimeInfo), ==, "test netscape content"); - extensions = webkit_mime_info_get_extensions(mimeInfo); - g_assert(extensions); - g_assert_cmpstr(extensions[0], ==, "testnetscape"); -} - -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: - MAKE_GLIB_TEST_FIXTURE(URISchemeTest); - - struct URISchemeHandler { - URISchemeHandler() - : replyLength(0) - { - } - - URISchemeHandler(const char* reply, int replyLength, const char* mimeType) - : reply(reply) - , replyLength(replyLength) - , mimeType(mimeType) - { - } - - CString reply; - int replyLength; - CString mimeType; - }; - - static void uriSchemeRequestCallback(WebKitURISchemeRequest* request, gpointer userData) - { - URISchemeTest* test = static_cast<URISchemeTest*>(userData); - test->m_uriSchemeRequest = request; - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request)); - - g_assert(webkit_uri_scheme_request_get_web_view(request) == test->m_webView); - - GRefPtr<GInputStream> inputStream = adoptGRef(g_memory_input_stream_new()); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inputStream.get())); - - const char* scheme = webkit_uri_scheme_request_get_scheme(request); - g_assert(scheme); - g_assert(test->m_handlersMap.contains(String::fromUTF8(scheme))); - - 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 (!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) - { - 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); - } - - GRefPtr<WebKitURISchemeRequest> m_uriSchemeRequest; - HashMap<String, URISchemeHandler> m_handlersMap; -}; - -static void testWebContextURIScheme(URISchemeTest* test, gconstpointer) -{ - test->registerURISchemeHandler("foo", kBarHTML, strlen(kBarHTML), "text/html"); - test->loadURI("foo:blank"); - test->waitUntilLoadFinished(); - size_t mainResourceDataSize = 0; - const char* mainResourceData = test->mainResourceData(mainResourceDataSize); - g_assert_cmpint(mainResourceDataSize, ==, strlen(kBarHTML)); - g_assert(!strncmp(mainResourceData, kBarHTML, mainResourceDataSize)); - - 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()))); - mainResourceDataSize = 0; - mainResourceData = test->mainResourceData(mainResourceDataSize); - g_assert_cmpint(mainResourceDataSize, ==, strlen(echoHTML.get())); - g_assert(!strncmp(mainResourceData, echoHTML.get(), mainResourceDataSize)); - - test->registerURISchemeHandler("nomime", kBarHTML, -1, 0); - test->m_loadEvents.clear(); - test->loadURI("nomime:foo bar"); - test->waitUntilLoadFinished(); - g_assert(test->m_loadEvents.contains(LoadTrackingTest::ProvisionalLoadFailed)); - - test->registerURISchemeHandler("empty", 0, 0, "text/html"); - test->m_loadEvents.clear(); - test->loadURI("empty:nothing"); - 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) -{ - WebKitWebContext* webContext = webkit_web_context_get_default(); - - // Check what happens if no spell checking language has been set. - const gchar* const* currentLanguage = webkit_web_context_get_spell_checking_languages(webContext); - g_assert(!currentLanguage); - - // Set the language to a specific one. - GRefPtr<GPtrArray> languages = adoptGRef(g_ptr_array_new()); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("en_US"))); - g_ptr_array_add(languages.get(), 0); - webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata)); - currentLanguage = webkit_web_context_get_spell_checking_languages(webContext); - g_assert_cmpuint(g_strv_length(const_cast<char**>(currentLanguage)), ==, 1); - g_assert_cmpstr(currentLanguage[0], ==, "en_US"); - - // Set the language string to list of valid languages. - g_ptr_array_remove_index_fast(languages.get(), languages->len - 1); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("en_GB"))); - g_ptr_array_add(languages.get(), 0); - webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata)); - currentLanguage = webkit_web_context_get_spell_checking_languages(webContext); - g_assert_cmpuint(g_strv_length(const_cast<char**>(currentLanguage)), ==, 2); - g_assert_cmpstr(currentLanguage[0], ==, "en_US"); - g_assert_cmpstr(currentLanguage[1], ==, "en_GB"); - - // Try passing a wrong language along with good ones. - g_ptr_array_remove_index_fast(languages.get(), languages->len - 1); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("bd_WR"))); - g_ptr_array_add(languages.get(), 0); - webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata)); - currentLanguage = webkit_web_context_get_spell_checking_languages(webContext); - g_assert_cmpuint(g_strv_length(const_cast<char**>(currentLanguage)), ==, 2); - g_assert_cmpstr(currentLanguage[0], ==, "en_US"); - g_assert_cmpstr(currentLanguage[1], ==, "en_GB"); - - // Try passing a list with only wrong languages. - languages = adoptGRef(g_ptr_array_new()); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("bd_WR"))); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("wr_BD"))); - g_ptr_array_add(languages.get(), 0); - webkit_web_context_set_spell_checking_languages(webContext, reinterpret_cast<const char* const*>(languages->pdata)); - currentLanguage = webkit_web_context_get_spell_checking_languages(webContext); - g_assert(!currentLanguage); - - // Check disabling and re-enabling spell checking. - webkit_web_context_set_spell_checking_enabled(webContext, FALSE); - g_assert(!webkit_web_context_get_spell_checking_enabled(webContext)); - webkit_web_context_set_spell_checking_enabled(webContext, TRUE); - g_assert(webkit_web_context_get_spell_checking_enabled(webContext)); -} - -static void testWebContextLanguages(WebViewTest* test, gconstpointer) -{ - static const char* expectedDefaultLanguage = "en"; - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - size_t mainResourceDataSize = 0; - const char* mainResourceData = test->mainResourceData(mainResourceDataSize); - g_assert_cmpuint(mainResourceDataSize, ==, strlen(expectedDefaultLanguage)); - g_assert(!strncmp(mainResourceData, expectedDefaultLanguage, mainResourceDataSize)); - - GRefPtr<GPtrArray> languages = adoptGRef(g_ptr_array_new()); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("en"))); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("ES_es"))); - g_ptr_array_add(languages.get(), const_cast<gpointer>(static_cast<const void*>("dE"))); - g_ptr_array_add(languages.get(), 0); - webkit_web_context_set_preferred_languages(webkit_web_context_get_default(), reinterpret_cast<const char* const*>(languages->pdata)); - - static const char* expectedLanguages = "en, es-es;q=0.90, de;q=0.80"; - test->loadURI(kServer->getURIForPath("/").data()); - test->waitUntilLoadFinished(); - mainResourceDataSize = 0; - mainResourceData = test->mainResourceData(mainResourceDataSize); - g_assert_cmpuint(mainResourceDataSize, ==, strlen(expectedLanguages)); - g_assert(!strncmp(mainResourceData, expectedLanguages, mainResourceDataSize)); -} - -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; - } - - if (g_str_equal(path, "/")) { - const char* acceptLanguage = soup_message_headers_get_one(message->request_headers, "Accept-Language"); - soup_message_set_status(message, SOUP_STATUS_OK); - soup_message_body_append(message->response_body, SOUP_MEMORY_COPY, acceptLanguage, strlen(acceptLanguage)); - soup_message_body_complete(message->response_body); - } else - soup_message_set_status(message, SOUP_STATUS_NOT_FOUND); -} - -class SecurityPolicyTest: public Test { -public: - MAKE_GLIB_TEST_FIXTURE(SecurityPolicyTest); - - enum SecurityPolicy { - Local = 1 << 1, - NoAccess = 1 << 2, - DisplayIsolated = 1 << 3, - Secure = 1 << 4, - CORSEnabled = 1 << 5, - EmptyDocument = 1 << 6 - }; - - SecurityPolicyTest() - : m_manager(webkit_web_context_get_security_manager(webkit_web_context_get_default())) - { - } - - void verifyThatSchemeMatchesPolicy(const char* scheme, unsigned policy) - { - if (policy & Local) - g_assert(webkit_security_manager_uri_scheme_is_local(m_manager, scheme)); - else - g_assert(!webkit_security_manager_uri_scheme_is_local(m_manager, scheme)); - if (policy & NoAccess) - g_assert(webkit_security_manager_uri_scheme_is_no_access(m_manager, scheme)); - else - g_assert(!webkit_security_manager_uri_scheme_is_no_access(m_manager, scheme)); - if (policy & DisplayIsolated) - g_assert(webkit_security_manager_uri_scheme_is_display_isolated(m_manager, scheme)); - else - g_assert(!webkit_security_manager_uri_scheme_is_display_isolated(m_manager, scheme)); - if (policy & Secure) - g_assert(webkit_security_manager_uri_scheme_is_secure(m_manager, scheme)); - else - g_assert(!webkit_security_manager_uri_scheme_is_secure(m_manager, scheme)); - if (policy & CORSEnabled) - g_assert(webkit_security_manager_uri_scheme_is_cors_enabled(m_manager, scheme)); - else - g_assert(!webkit_security_manager_uri_scheme_is_cors_enabled(m_manager, scheme)); - if (policy & EmptyDocument) - g_assert(webkit_security_manager_uri_scheme_is_empty_document(m_manager, scheme)); - else - g_assert(!webkit_security_manager_uri_scheme_is_empty_document(m_manager, scheme)); - } - - WebKitSecurityManager* m_manager; -}; - -static void testWebContextSecurityPolicy(SecurityPolicyTest* test, gconstpointer) -{ - // VerifyThatSchemeMatchesPolicy default policy for well known schemes. - test->verifyThatSchemeMatchesPolicy("http", SecurityPolicyTest::CORSEnabled); - test->verifyThatSchemeMatchesPolicy("https", SecurityPolicyTest::CORSEnabled | SecurityPolicyTest::Secure); - test->verifyThatSchemeMatchesPolicy("file", SecurityPolicyTest::Local); - test->verifyThatSchemeMatchesPolicy("data", SecurityPolicyTest::NoAccess | SecurityPolicyTest::Secure); - test->verifyThatSchemeMatchesPolicy("about", SecurityPolicyTest::NoAccess | SecurityPolicyTest::Secure | SecurityPolicyTest::EmptyDocument); - - // Custom scheme. - test->verifyThatSchemeMatchesPolicy("foo", 0); - - webkit_security_manager_register_uri_scheme_as_local(test->m_manager, "foo"); - test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local); - webkit_security_manager_register_uri_scheme_as_no_access(test->m_manager, "foo"); - test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess); - webkit_security_manager_register_uri_scheme_as_display_isolated(test->m_manager, "foo"); - test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated); - webkit_security_manager_register_uri_scheme_as_secure(test->m_manager, "foo"); - test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated | SecurityPolicyTest::Secure); - webkit_security_manager_register_uri_scheme_as_cors_enabled(test->m_manager, "foo"); - test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated | SecurityPolicyTest::Secure - | SecurityPolicyTest::CORSEnabled); - webkit_security_manager_register_uri_scheme_as_empty_document(test->m_manager, "foo"); - test->verifyThatSchemeMatchesPolicy("foo", SecurityPolicyTest::Local | SecurityPolicyTest::NoAccess | SecurityPolicyTest::DisplayIsolated | SecurityPolicyTest::Secure - | SecurityPolicyTest::CORSEnabled | SecurityPolicyTest::EmptyDocument); -} - -void beforeAll() -{ - kServer = new WebKitTestServer(); - kServer->run(serverCallback); - - Test::add("WebKitWebContext", "default-context", testWebContextDefault); - PluginsTest::add("WebKitWebContext", "get-plugins", testWebContextGetPlugins); - URISchemeTest::add("WebKitWebContext", "uri-scheme", testWebContextURIScheme); - Test::add("WebKitWebContext", "spell-checker", testWebContextSpellChecker); - WebViewTest::add("WebKitWebContext", "languages", testWebContextLanguages); - SecurityPolicyTest::add("WebKitSecurityManager", "security-policy", testWebContextSecurityPolicy); -} - -void afterAll() -{ - delete kServer; -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp deleted file mode 100644 index 88d77f286..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebView.cpp +++ /dev/null @@ -1,1258 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebViewTest.h" -#include <JavaScriptCore/JSStringRef.h> -#include <JavaScriptCore/JSValueRef.h> -#include <glib/gstdio.h> -#include <wtf/HashSet.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/StringHash.h> - -static void testWebViewDefaultContext(WebViewTest* test, gconstpointer) -{ - g_assert(webkit_web_view_get_context(test->m_webView) == webkit_web_context_get_default()); - - // Check that a web view created with g_object_new has the default context. - GRefPtr<WebKitWebView> webView = WEBKIT_WEB_VIEW(g_object_new(WEBKIT_TYPE_WEB_VIEW, NULL)); - g_assert(webkit_web_view_get_context(webView.get()) == webkit_web_context_get_default()); -} - -static void testWebViewCustomCharset(WebViewTest* test, gconstpointer) -{ - g_assert(!webkit_web_view_get_custom_charset(test->m_webView)); - webkit_web_view_set_custom_charset(test->m_webView, "utf8"); - g_assert_cmpstr(webkit_web_view_get_custom_charset(test->m_webView), ==, "utf8"); - // Go back to the default charset. - webkit_web_view_set_custom_charset(test->m_webView, 0); - g_assert(!webkit_web_view_get_custom_charset(test->m_webView)); -} - -static void testWebViewSettings(WebViewTest* test, gconstpointer) -{ - WebKitSettings* defaultSettings = webkit_web_view_get_settings(test->m_webView); - g_assert(defaultSettings); - g_assert(webkit_settings_get_enable_javascript(defaultSettings)); - - GRefPtr<WebKitSettings> newSettings = adoptGRef(webkit_settings_new()); - g_object_set(G_OBJECT(newSettings.get()), "enable-javascript", FALSE, NULL); - webkit_web_view_set_settings(test->m_webView, newSettings.get()); - - WebKitSettings* settings = webkit_web_view_get_settings(test->m_webView); - g_assert(settings != defaultSettings); - g_assert(!webkit_settings_get_enable_javascript(settings)); - - GRefPtr<GtkWidget> webView2 = webkit_web_view_new(); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webView2.get())); - webkit_web_view_set_settings(WEBKIT_WEB_VIEW(webView2.get()), settings); - g_assert(webkit_web_view_get_settings(WEBKIT_WEB_VIEW(webView2.get())) == settings); - - GRefPtr<WebKitSettings> newSettings2 = adoptGRef(webkit_settings_new()); - 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()); - g_assert(webkit_settings_get_enable_javascript(settings)); -} - -static const char* kAlertDialogMessage = "WebKitGTK+ alert dialog message"; -static const char* kConfirmDialogMessage = "WebKitGTK+ confirm dialog message"; -static const char* kPromptDialogMessage = "WebKitGTK+ prompt dialog message"; -static const char* kPromptDialogReturnedText = "WebKitGTK+ prompt dialog returned text"; - -class UIClientTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(UIClientTest); - - enum WebViewEvents { - Create, - ReadyToShow, - RunAsModal, - Close - }; - - class WindowProperties { - public: - WindowProperties() - : m_isNull(true) - , m_toolbarVisible(true) - , m_statusbarVisible(true) - , m_scrollbarsVisible(true) - , m_menubarVisible(true) - , m_locationbarVisible(true) - , m_resizable(true) - , m_fullscreen(false) - { - memset(&m_geometry, 0, sizeof(GdkRectangle)); - } - - WindowProperties(WebKitWindowProperties* windowProperties) - : m_isNull(false) - , m_toolbarVisible(webkit_window_properties_get_toolbar_visible(windowProperties)) - , m_statusbarVisible(webkit_window_properties_get_statusbar_visible(windowProperties)) - , m_scrollbarsVisible(webkit_window_properties_get_scrollbars_visible(windowProperties)) - , m_menubarVisible(webkit_window_properties_get_menubar_visible(windowProperties)) - , m_locationbarVisible(webkit_window_properties_get_locationbar_visible(windowProperties)) - , m_resizable(webkit_window_properties_get_resizable(windowProperties)) - , m_fullscreen(webkit_window_properties_get_fullscreen(windowProperties)) - { - webkit_window_properties_get_geometry(windowProperties, &m_geometry); - } - - WindowProperties(GdkRectangle* geometry, bool toolbarVisible, bool statusbarVisible, bool scrollbarsVisible, bool menubarVisible, - bool locationbarVisible, bool resizable, bool fullscreen) - : m_isNull(false) - , m_geometry(*geometry) - , m_toolbarVisible(toolbarVisible) - , m_statusbarVisible(statusbarVisible) - , m_scrollbarsVisible(scrollbarsVisible) - , m_menubarVisible(menubarVisible) - , m_locationbarVisible(locationbarVisible) - , m_resizable(resizable) - , m_fullscreen(fullscreen) - { - } - - bool isNull() const { return m_isNull; } - - void assertEqual(const WindowProperties& other) const - { - g_assert_cmpint(m_geometry.x, ==, other.m_geometry.x); - g_assert_cmpint(m_geometry.y, ==, other.m_geometry.y); - g_assert_cmpint(m_geometry.width, ==, other.m_geometry.width); - g_assert_cmpint(m_geometry.height, ==, other.m_geometry.height); - g_assert_cmpint(static_cast<int>(m_toolbarVisible), ==, static_cast<int>(other.m_toolbarVisible)); - g_assert_cmpint(static_cast<int>(m_statusbarVisible), ==, static_cast<int>(other.m_statusbarVisible)); - g_assert_cmpint(static_cast<int>(m_scrollbarsVisible), ==, static_cast<int>(other.m_scrollbarsVisible)); - g_assert_cmpint(static_cast<int>(m_menubarVisible), ==, static_cast<int>(other.m_menubarVisible)); - g_assert_cmpint(static_cast<int>(m_locationbarVisible), ==, static_cast<int>(other.m_locationbarVisible)); - g_assert_cmpint(static_cast<int>(m_resizable), ==, static_cast<int>(other.m_resizable)); - g_assert_cmpint(static_cast<int>(m_fullscreen), ==, static_cast<int>(other.m_fullscreen)); - } - - private: - bool m_isNull; - - GdkRectangle m_geometry; - - bool m_toolbarVisible; - bool m_statusbarVisible; - bool m_scrollbarsVisible; - bool m_menubarVisible; - bool m_locationbarVisible; - - bool m_resizable; - bool m_fullscreen; - }; - - static void windowPropertiesNotifyCallback(GObject*, GParamSpec* paramSpec, UIClientTest* test) - { - test->m_windowPropertiesChanged.add(g_param_spec_get_name(paramSpec)); - } - - static GtkWidget* viewCreateCallback(WebKitWebView* webView, UIClientTest* test) - { - return test->viewCreate(webView); - } - - static void viewReadyToShowCallback(WebKitWebView* webView, UIClientTest* test) - { - test->viewReadyToShow(webView); - } - - static void viewCloseCallback(WebKitWebView* webView, UIClientTest* test) - { - test->viewClose(webView); - } - - void scriptAlert(WebKitScriptDialog* dialog) - { - switch (m_scriptDialogType) { - case WEBKIT_SCRIPT_DIALOG_ALERT: - g_assert_cmpstr(webkit_script_dialog_get_message(dialog), ==, kAlertDialogMessage); - break; - case WEBKIT_SCRIPT_DIALOG_CONFIRM: - g_assert(m_scriptDialogConfirmed); - g_assert_cmpstr(webkit_script_dialog_get_message(dialog), ==, "confirmed"); - - break; - case WEBKIT_SCRIPT_DIALOG_PROMPT: - g_assert_cmpstr(webkit_script_dialog_get_message(dialog), ==, kPromptDialogReturnedText); - break; - } - - g_main_loop_quit(m_mainLoop); - } - - void scriptConfirm(WebKitScriptDialog* dialog) - { - g_assert_cmpstr(webkit_script_dialog_get_message(dialog), ==, kConfirmDialogMessage); - m_scriptDialogConfirmed = !m_scriptDialogConfirmed; - webkit_script_dialog_confirm_set_confirmed(dialog, m_scriptDialogConfirmed); - } - - void scriptPrompt(WebKitScriptDialog* dialog) - { - g_assert_cmpstr(webkit_script_dialog_get_message(dialog), ==, kPromptDialogMessage); - g_assert_cmpstr(webkit_script_dialog_prompt_get_default_text(dialog), ==, "default"); - webkit_script_dialog_prompt_set_text(dialog, kPromptDialogReturnedText); - } - - static gboolean scriptDialog(WebKitWebView*, WebKitScriptDialog* dialog, UIClientTest* test) - { - switch (webkit_script_dialog_get_dialog_type(dialog)) { - case WEBKIT_SCRIPT_DIALOG_ALERT: - test->scriptAlert(dialog); - break; - case WEBKIT_SCRIPT_DIALOG_CONFIRM: - test->scriptConfirm(dialog); - break; - case WEBKIT_SCRIPT_DIALOG_PROMPT: - test->scriptPrompt(dialog); - break; - } - - return TRUE; - } - - static void mouseTargetChanged(WebKitWebView*, WebKitHitTestResult* hitTestResult, guint modifiers, UIClientTest* test) - { - g_assert(WEBKIT_IS_HIT_TEST_RESULT(hitTestResult)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(hitTestResult)); - - test->m_mouseTargetHitTestResult = hitTestResult; - test->m_mouseTargetModifiers = modifiers; - g_main_loop_quit(test->m_mainLoop); - } - - static gboolean permissionRequested(WebKitWebView*, WebKitPermissionRequest* request, UIClientTest* test) - { - g_assert(WEBKIT_IS_PERMISSION_REQUEST(request)); - test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request)); - - if (test->m_allowPermissionRequests) - webkit_permission_request_allow(request); - else - webkit_permission_request_deny(request); - - return TRUE; - } - - UIClientTest() - : m_scriptDialogType(WEBKIT_SCRIPT_DIALOG_ALERT) - , m_scriptDialogConfirmed(true) - , m_allowPermissionRequests(false) - , m_mouseTargetModifiers(0) - { - webkit_settings_set_javascript_can_open_windows_automatically(webkit_web_view_get_settings(m_webView), TRUE); - g_signal_connect(m_webView, "create", G_CALLBACK(viewCreateCallback), this); - g_signal_connect(m_webView, "script-dialog", G_CALLBACK(scriptDialog), this); - g_signal_connect(m_webView, "mouse-target-changed", G_CALLBACK(mouseTargetChanged), this); - g_signal_connect(m_webView, "permission-request", G_CALLBACK(permissionRequested), this); - } - - ~UIClientTest() - { - g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void waitUntilMainLoopFinishes() - { - g_main_loop_run(m_mainLoop); - } - - void setExpectedWindowProperties(const WindowProperties& windowProperties) - { - m_windowProperties = windowProperties; - } - - WebKitHitTestResult* moveMouseAndWaitUntilMouseTargetChanged(int x, int y, unsigned int mouseModifiers = 0) - { - mouseMoveTo(x, y, mouseModifiers); - g_main_loop_run(m_mainLoop); - return m_mouseTargetHitTestResult.get(); - } - - virtual GtkWidget* viewCreate(WebKitWebView* webView) - { - g_assert(webView == m_webView); - - GtkWidget* newWebView = webkit_web_view_new_with_context(webkit_web_view_get_context(webView)); - g_object_ref_sink(newWebView); - - m_webViewEvents.append(Create); - - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(WEBKIT_WEB_VIEW(newWebView)); - g_assert(windowProperties); - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(windowProperties)); - m_windowPropertiesChanged.clear(); - - g_signal_connect(windowProperties, "notify", G_CALLBACK(windowPropertiesNotifyCallback), this); - g_signal_connect(newWebView, "ready-to-show", G_CALLBACK(viewReadyToShowCallback), this); - g_signal_connect(newWebView, "close", G_CALLBACK(viewCloseCallback), this); - - return newWebView; - } - - virtual void viewReadyToShow(WebKitWebView* webView) - { - g_assert(webView != m_webView); - - WebKitWindowProperties* windowProperties = webkit_web_view_get_window_properties(webView); - g_assert(windowProperties); - if (!m_windowProperties.isNull()) - WindowProperties(windowProperties).assertEqual(m_windowProperties); - - m_webViewEvents.append(ReadyToShow); - } - - virtual void viewClose(WebKitWebView* webView) - { - g_assert(webView != m_webView); - - m_webViewEvents.append(Close); - g_object_unref(webView); - - g_main_loop_quit(m_mainLoop); - } - - Vector<WebViewEvents> m_webViewEvents; - WebKitScriptDialogType m_scriptDialogType; - bool m_scriptDialogConfirmed; - bool m_allowPermissionRequests; - WindowProperties m_windowProperties; - HashSet<WTF::String> m_windowPropertiesChanged; - GRefPtr<WebKitHitTestResult> m_mouseTargetHitTestResult; - unsigned int m_mouseTargetModifiers; -}; - -static void testWebViewCreateReadyClose(UIClientTest* test, gconstpointer) -{ - test->loadHtml("<html><body onLoad=\"window.open().close();\"></html>", 0); - test->waitUntilMainLoopFinishes(); - - Vector<UIClientTest::WebViewEvents>& events = test->m_webViewEvents; - g_assert_cmpint(events.size(), ==, 3); - g_assert_cmpint(events[0], ==, UIClientTest::Create); - g_assert_cmpint(events[1], ==, UIClientTest::ReadyToShow); - g_assert_cmpint(events[2], ==, UIClientTest::Close); -} - -static gboolean checkMimeTypeForFilter(GtkFileFilter* filter, const gchar* mimeType) -{ - GtkFileFilterInfo filterInfo; - filterInfo.contains = GTK_FILE_FILTER_MIME_TYPE; - filterInfo.mime_type = mimeType; - return gtk_file_filter_filter(filter, &filterInfo); -} - -class ModalDialogsTest: public UIClientTest { -public: - MAKE_GLIB_TEST_FIXTURE(ModalDialogsTest); - - static void dialogRunAsModalCallback(WebKitWebView* webView, ModalDialogsTest* test) - { - g_assert(webView != test->m_webView); - test->m_webViewEvents.append(RunAsModal); - } - - GtkWidget* viewCreate(WebKitWebView* webView) - { - g_assert(webView == m_webView); - - GtkWidget* newWebView = UIClientTest::viewCreate(webView); - g_signal_connect(newWebView, "run-as-modal", G_CALLBACK(dialogRunAsModalCallback), this); - return newWebView; - } - - void viewReadyToShow(WebKitWebView* webView) - { - g_assert(webView != m_webView); - m_webViewEvents.append(ReadyToShow); - } -}; - -static void testWebViewAllowModalDialogs(ModalDialogsTest* test, gconstpointer) -{ - WebKitSettings* settings = webkit_web_view_get_settings(test->m_webView); - webkit_settings_set_allow_modal_dialogs(settings, TRUE); - - test->loadHtml("<html><body onload=\"window.showModalDialog('data:text/html,<html><body/><script>window.close();</script></html>')\"></body></html>", 0); - test->waitUntilMainLoopFinishes(); - - Vector<UIClientTest::WebViewEvents>& events = test->m_webViewEvents; - g_assert_cmpint(events.size(), ==, 4); - g_assert_cmpint(events[0], ==, UIClientTest::Create); - g_assert_cmpint(events[1], ==, UIClientTest::ReadyToShow); - g_assert_cmpint(events[2], ==, UIClientTest::RunAsModal); - g_assert_cmpint(events[3], ==, UIClientTest::Close); -} - -static void testWebViewDisallowModalDialogs(ModalDialogsTest* test, gconstpointer) -{ - WebKitSettings* settings = webkit_web_view_get_settings(test->m_webView); - webkit_settings_set_allow_modal_dialogs(settings, FALSE); - - test->loadHtml("<html><body onload=\"window.showModalDialog('data:text/html,<html><body/><script>window.close();</script></html>')\"></body></html>", 0); - // We need to use a timeout here because the viewClose() function - // won't ever be called as the dialog won't be created. - test->wait(1); - - Vector<UIClientTest::WebViewEvents>& events = test->m_webViewEvents; - g_assert_cmpint(events.size(), ==, 0); -} - -static void testWebViewJavaScriptDialogs(UIClientTest* test, gconstpointer) -{ - static const char* htmlOnLoadFormat = "<html><body onLoad=\"%s\"></body></html>"; - static const char* jsAlertFormat = "alert('%s')"; - static const char* jsConfirmFormat = "do { confirmed = confirm('%s'); } while (!confirmed); alert('confirmed');"; - static const char* jsPromptFormat = "alert(prompt('%s', 'default'));"; - - test->m_scriptDialogType = WEBKIT_SCRIPT_DIALOG_ALERT; - GOwnPtr<char> alertDialogMessage(g_strdup_printf(jsAlertFormat, kAlertDialogMessage)); - GOwnPtr<char> alertHTML(g_strdup_printf(htmlOnLoadFormat, alertDialogMessage.get())); - test->loadHtml(alertHTML.get(), 0); - test->waitUntilMainLoopFinishes(); - - test->m_scriptDialogType = WEBKIT_SCRIPT_DIALOG_CONFIRM; - GOwnPtr<char> confirmDialogMessage(g_strdup_printf(jsConfirmFormat, kConfirmDialogMessage)); - GOwnPtr<char> confirmHTML(g_strdup_printf(htmlOnLoadFormat, confirmDialogMessage.get())); - test->loadHtml(confirmHTML.get(), 0); - test->waitUntilMainLoopFinishes(); - - test->m_scriptDialogType = WEBKIT_SCRIPT_DIALOG_PROMPT; - GOwnPtr<char> promptDialogMessage(g_strdup_printf(jsPromptFormat, kPromptDialogMessage)); - GOwnPtr<char> promptHTML(g_strdup_printf(htmlOnLoadFormat, promptDialogMessage.get())); - test->loadHtml(promptHTML.get(), 0); - test->waitUntilMainLoopFinishes(); -} - -static void testWebViewWindowProperties(UIClientTest* test, gconstpointer) -{ - static const char* windowProrpertiesString = "left=100,top=150,width=400,height=400,location=no,menubar=no,status=no,toolbar=no,scrollbars=no"; - GdkRectangle geometry = { 100, 150, 400, 400 }; - test->setExpectedWindowProperties(UIClientTest::WindowProperties(&geometry, false, false, false, false, false, true, false)); - - GOwnPtr<char> htmlString(g_strdup_printf("<html><body onLoad=\"window.open('', '', '%s').close();\"></body></html>", windowProrpertiesString)); - test->loadHtml(htmlString.get(), 0); - test->waitUntilMainLoopFinishes(); - - static const char* propertiesChanged[] = { - "geometry", "locationbar-visible", "menubar-visible", "statusbar-visible", "toolbar-visible", "scrollbars-visible" - }; - for (size_t i = 0; i < G_N_ELEMENTS(propertiesChanged); ++i) - g_assert(test->m_windowPropertiesChanged.contains(propertiesChanged[i])); - - Vector<UIClientTest::WebViewEvents>& events = test->m_webViewEvents; - g_assert_cmpint(events.size(), ==, 3); - g_assert_cmpint(events[0], ==, UIClientTest::Create); - g_assert_cmpint(events[1], ==, UIClientTest::ReadyToShow); - g_assert_cmpint(events[2], ==, UIClientTest::Close); -} - -static void testWebViewMouseTarget(UIClientTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); - - const char* linksHoveredHTML = - "<html><body>" - " <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>" - " <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:///"); - test->waitUntilLoadFinished(); - - // Move over link. - WebKitHitTestResult* hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(1, 1); - 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_cmpstr(webkit_hit_test_result_get_link_uri(hitTestResult), ==, "http://www.webkitgtk.org/"); - g_assert_cmpstr(webkit_hit_test_result_get_link_title(hitTestResult), ==, "WebKitGTK+ Title"); - g_assert_cmpstr(webkit_hit_test_result_get_link_label(hitTestResult), ==, "WebKitGTK+ Website"); - g_assert(!test->m_mouseTargetModifiers); - - // Move out of the link. - hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(0, 0); - 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(!test->m_mouseTargetModifiers); - - // Move over image with GDK_CONTROL_MASK. - hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(1, 10, GDK_CONTROL_MASK); - 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_image_uri(hitTestResult), ==, "file:///0xdeadbeef"); - g_assert(test->m_mouseTargetModifiers & GDK_CONTROL_MASK); - - // Move over image link. - hitTestResult = test->moveMouseAndWaitUntilMouseTargetChanged(1, 20); - 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_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"); - g_assert(!webkit_hit_test_result_get_link_label(hitTestResult)); - g_assert(!test->m_mouseTargetModifiers); - - // Move over media. - 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, 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) -{ - // Some versions of geoclue give a runtime warning because it tries - // to register the error quark twice. See https://bugs.webkit.org/show_bug.cgi?id=89858. - // Make warnings non-fatal for this test to make it pass. - test->removeLogFatalFlag(G_LOG_LEVEL_WARNING); - test->showInWindowAndWaitUntilMapped(); - static const char* geolocationRequestHTML = - "<html>" - " <script>" - " function runTest()" - " {" - " navigator.geolocation.getCurrentPosition(function(p) { document.title = \"OK\" }," - " function(e) { document.title = e.code });" - " }" - " </script>" - " <body onload='runTest();'></body>" - "</html>"; - - // Test denying a permission request. - test->m_allowPermissionRequests = false; - test->loadHtml(geolocationRequestHTML, 0); - test->waitUntilTitleChanged(); - - // According to the Geolocation API specification, '1' is the - // error code returned for the PERMISSION_DENIED error. - // http://dev.w3.org/geo/api/spec-source.html#position_error_interface - const gchar* result = webkit_web_view_get_title(test->m_webView); - g_assert_cmpstr(result, ==, "1"); - - // Test allowing a permission request. - test->m_allowPermissionRequests = true; - test->loadHtml(geolocationRequestHTML, 0); - test->waitUntilTitleChanged(); - - // Check that we did not get the PERMISSION_DENIED error now. - result = webkit_web_view_get_title(test->m_webView); - g_assert_cmpstr(result, !=, "1"); - test->addLogFatalFlag(G_LOG_LEVEL_WARNING); -} - -static void testWebViewZoomLevel(WebViewTest* test, gconstpointer) -{ - g_assert_cmpfloat(webkit_web_view_get_zoom_level(test->m_webView), ==, 1); - webkit_web_view_set_zoom_level(test->m_webView, 2.5); - g_assert_cmpfloat(webkit_web_view_get_zoom_level(test->m_webView), ==, 2.5); - - webkit_settings_set_zoom_text_only(webkit_web_view_get_settings(test->m_webView), TRUE); - // The zoom level shouldn't change when zoom-text-only setting changes. - g_assert_cmpfloat(webkit_web_view_get_zoom_level(test->m_webView), ==, 2.5); -} - -static void testWebViewRunJavaScript(WebViewTest* test, gconstpointer) -{ - static const char* html = "<html><body><a id='WebKitLink' href='http://www.webkitgtk.org/' title='WebKitGTK+ Title'>WebKitGTK+ Website</a></body></html>"; - test->loadHtml(html, 0); - test->waitUntilLoadFinished(); - - GOwnPtr<GError> error; - WebKitJavascriptResult* javascriptResult = test->runJavaScriptAndWaitUntilFinished("window.document.getElementById('WebKitLink').title;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - GOwnPtr<char> valueString(WebViewTest::javascriptResultToCString(javascriptResult)); - g_assert_cmpstr(valueString.get(), ==, "WebKitGTK+ Title"); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("window.document.getElementById('WebKitLink').href;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); - g_assert_cmpstr(valueString.get(), ==, "http://www.webkitgtk.org/"); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("window.document.getElementById('WebKitLink').textContent", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); - g_assert_cmpstr(valueString.get(), ==, "WebKitGTK+ Website"); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("a = 25;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert_cmpfloat(WebViewTest::javascriptResultToNumber(javascriptResult), ==, 25); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("a = 2.5;", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert_cmpfloat(WebViewTest::javascriptResultToNumber(javascriptResult), ==, 2.5); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("a = true", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert(WebViewTest::javascriptResultToBoolean(javascriptResult)); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("a = false", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert(!WebViewTest::javascriptResultToBoolean(javascriptResult)); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("a = null", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert(WebViewTest::javascriptResultIsNull(javascriptResult)); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("function Foo() { a = 25; } Foo();", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - g_assert(WebViewTest::javascriptResultIsUndefined(javascriptResult)); - - javascriptResult = test->runJavaScriptFromGResourceAndWaitUntilFinished("/org/webkit/webkit2gtk/tests/link-title.js", &error.outPtr()); - g_assert(javascriptResult); - g_assert(!error.get()); - valueString.set(WebViewTest::javascriptResultToCString(javascriptResult)); - g_assert_cmpstr(valueString.get(), ==, "WebKitGTK+ Title"); - - javascriptResult = test->runJavaScriptFromGResourceAndWaitUntilFinished("/wrong/path/to/resource.js", &error.outPtr()); - g_assert(!javascriptResult); - g_assert_error(error.get(), G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND); - error.clear(); - - javascriptResult = test->runJavaScriptAndWaitUntilFinished("foo();", &error.outPtr()); - g_assert(!javascriptResult); - g_assert_error(error.get(), WEBKIT_JAVASCRIPT_ERROR, WEBKIT_JAVASCRIPT_ERROR_SCRIPT_FAILED); -} - -class FileChooserTest: public UIClientTest { -public: - MAKE_GLIB_TEST_FIXTURE(FileChooserTest); - - FileChooserTest() - { - g_signal_connect(m_webView, "run-file-chooser", G_CALLBACK(runFileChooserCallback), this); - } - - static gboolean runFileChooserCallback(WebKitWebView*, WebKitFileChooserRequest* request, FileChooserTest* test) - { - test->runFileChooser(request); - return TRUE; - } - - void runFileChooser(WebKitFileChooserRequest* request) - { - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request)); - m_fileChooserRequest = request; - g_main_loop_quit(m_mainLoop); - } - - WebKitFileChooserRequest* clickMouseButtonAndWaitForFileChooserRequest(int x, int y) - { - clickMouseButton(x, y); - g_main_loop_run(m_mainLoop); - return m_fileChooserRequest.get(); - } - -private: - GRefPtr<WebKitFileChooserRequest> m_fileChooserRequest; -}; - -static void testWebViewFileChooserRequest(FileChooserTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - static const char* fileChooserHTMLFormat = "<html><body><input style='position:absolute;left:0;top:0;margin:0;padding:0' type='file' %s/></body></html>"; - - // Multiple selections not allowed, no MIME filtering. - GOwnPtr<char> simpleFileUploadHTML(g_strdup_printf(fileChooserHTMLFormat, "")); - test->loadHtml(simpleFileUploadHTML.get(), 0); - test->waitUntilLoadFinished(); - WebKitFileChooserRequest* fileChooserRequest = test->clickMouseButtonAndWaitForFileChooserRequest(5, 5); - g_assert(!webkit_file_chooser_request_get_select_multiple(fileChooserRequest)); - - const gchar* const* mimeTypes = webkit_file_chooser_request_get_mime_types(fileChooserRequest); - g_assert(!mimeTypes); - GtkFileFilter* filter = webkit_file_chooser_request_get_mime_types_filter(fileChooserRequest); - g_assert(!filter); - const gchar* const* selectedFiles = webkit_file_chooser_request_get_selected_files(fileChooserRequest); - g_assert(!selectedFiles); - webkit_file_chooser_request_cancel(fileChooserRequest); - - // Multiple selections allowed, no MIME filtering, some pre-selected files. - GOwnPtr<char> multipleSelectionFileUploadHTML(g_strdup_printf(fileChooserHTMLFormat, "multiple")); - test->loadHtml(multipleSelectionFileUploadHTML.get(), 0); - test->waitUntilLoadFinished(); - fileChooserRequest = test->clickMouseButtonAndWaitForFileChooserRequest(5, 5); - g_assert(webkit_file_chooser_request_get_select_multiple(fileChooserRequest)); - - mimeTypes = webkit_file_chooser_request_get_mime_types(fileChooserRequest); - g_assert(!mimeTypes); - filter = webkit_file_chooser_request_get_mime_types_filter(fileChooserRequest); - g_assert(!filter); - selectedFiles = webkit_file_chooser_request_get_selected_files(fileChooserRequest); - g_assert(!selectedFiles); - - // Select some files. - const gchar* filesToSelect[4] = { "/foo", "/foo/bar", "/foo/bar/baz", 0 }; - webkit_file_chooser_request_select_files(fileChooserRequest, filesToSelect); - - // Check the files that have been just selected. - selectedFiles = webkit_file_chooser_request_get_selected_files(fileChooserRequest); - g_assert(selectedFiles); - g_assert_cmpstr(selectedFiles[0], ==, "/foo"); - g_assert_cmpstr(selectedFiles[1], ==, "/foo/bar"); - g_assert_cmpstr(selectedFiles[2], ==, "/foo/bar/baz"); - g_assert(!selectedFiles[3]); - - // Perform another request to check if the list of files selected - // in the previous step appears now as part of the new request. - fileChooserRequest = test->clickMouseButtonAndWaitForFileChooserRequest(5, 5); - selectedFiles = webkit_file_chooser_request_get_selected_files(fileChooserRequest); - g_assert(selectedFiles); - g_assert_cmpstr(selectedFiles[0], ==, "/foo"); - g_assert_cmpstr(selectedFiles[1], ==, "/foo/bar"); - g_assert_cmpstr(selectedFiles[2], ==, "/foo/bar/baz"); - g_assert(!selectedFiles[3]); - webkit_file_chooser_request_cancel(fileChooserRequest); - - // Multiple selections not allowed, only accept images, audio and video files.. - GOwnPtr<char> mimeFilteredFileUploadHTML(g_strdup_printf(fileChooserHTMLFormat, "accept='audio/*,video/*,image/*'")); - test->loadHtml(mimeFilteredFileUploadHTML.get(), 0); - test->waitUntilLoadFinished(); - fileChooserRequest = test->clickMouseButtonAndWaitForFileChooserRequest(5, 5); - g_assert(!webkit_file_chooser_request_get_select_multiple(fileChooserRequest)); - - mimeTypes = webkit_file_chooser_request_get_mime_types(fileChooserRequest); - g_assert(mimeTypes); - g_assert_cmpstr(mimeTypes[0], ==, "audio/*"); - g_assert_cmpstr(mimeTypes[1], ==, "video/*"); - g_assert_cmpstr(mimeTypes[2], ==, "image/*"); - g_assert(!mimeTypes[3]); - - filter = webkit_file_chooser_request_get_mime_types_filter(fileChooserRequest); - g_assert(GTK_IS_FILE_FILTER(filter)); - g_assert(checkMimeTypeForFilter(filter, "audio/*")); - g_assert(checkMimeTypeForFilter(filter, "video/*")); - g_assert(checkMimeTypeForFilter(filter, "image/*")); - - selectedFiles = webkit_file_chooser_request_get_selected_files(fileChooserRequest); - g_assert(!selectedFiles); - webkit_file_chooser_request_cancel(fileChooserRequest); -} - -class FullScreenClientTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(FullScreenClientTest); - - enum FullScreenEvent { - None, - Enter, - Leave - }; - - static gboolean viewEnterFullScreenCallback(WebKitWebView*, FullScreenClientTest* test) - { - test->m_event = Enter; - g_main_loop_quit(test->m_mainLoop); - return FALSE; - } - - static gboolean viewLeaveFullScreenCallback(WebKitWebView*, FullScreenClientTest* test) - { - test->m_event = Leave; - g_main_loop_quit(test->m_mainLoop); - return FALSE; - } - - FullScreenClientTest() - : m_event(None) - { - webkit_settings_set_enable_fullscreen(webkit_web_view_get_settings(m_webView), TRUE); - g_signal_connect(m_webView, "enter-fullscreen", G_CALLBACK(viewEnterFullScreenCallback), this); - g_signal_connect(m_webView, "leave-fullscreen", G_CALLBACK(viewLeaveFullScreenCallback), this); - } - - ~FullScreenClientTest() - { - g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void requestFullScreenAndWaitUntilEnteredFullScreen() - { - m_event = None; - webkit_web_view_run_javascript(m_webView, "document.documentElement.webkitRequestFullScreen();", 0, 0, 0); - g_main_loop_run(m_mainLoop); - } - - static gboolean leaveFullScreenIdle(FullScreenClientTest* test) - { - test->keyStroke(GDK_KEY_Escape); - return FALSE; - } - - void leaveFullScreenAndWaitUntilLeftFullScreen() - { - m_event = None; - g_idle_add(reinterpret_cast<GSourceFunc>(leaveFullScreenIdle), this); - g_main_loop_run(m_mainLoop); - } - - FullScreenEvent m_event; -}; - -static void testWebViewFullScreen(FullScreenClientTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - test->loadHtml("<html><body>FullScreen test</body></html>", 0); - test->waitUntilLoadFinished(); - test->requestFullScreenAndWaitUntilEnteredFullScreen(); - g_assert_cmpint(test->m_event, ==, FullScreenClientTest::Enter); - test->leaveFullScreenAndWaitUntilLeftFullScreen(); - g_assert_cmpint(test->m_event, ==, FullScreenClientTest::Leave); -} - -static void testWebViewCanShowMIMEType(WebViewTest* test, gconstpointer) -{ - // Supported MIME types. - g_assert(webkit_web_view_can_show_mime_type(test->m_webView, "text/html")); - g_assert(webkit_web_view_can_show_mime_type(test->m_webView, "text/plain")); - g_assert(webkit_web_view_can_show_mime_type(test->m_webView, "image/jpeg")); - - // Unsupported MIME types. - g_assert(!webkit_web_view_can_show_mime_type(test->m_webView, "text/vcard")); - g_assert(!webkit_web_view_can_show_mime_type(test->m_webView, "application/pdf")); - g_assert(!webkit_web_view_can_show_mime_type(test->m_webView, "application/zip")); - g_assert(!webkit_web_view_can_show_mime_type(test->m_webView, "application/octet-stream")); - - // Plugins are only supported when enabled. - webkit_web_context_set_additional_plugins_directory(webkit_web_view_get_context(test->m_webView), WEBKIT_TEST_PLUGIN_DIR); - g_assert(webkit_web_view_can_show_mime_type(test->m_webView, "application/x-webkit-test-netscape")); - webkit_settings_set_enable_plugins(webkit_web_view_get_settings(test->m_webView), FALSE); - g_assert(!webkit_web_view_can_show_mime_type(test->m_webView, "application/x-webkit-test-netscape")); -} - -class FormClientTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(FormClientTest); - - static void submitFormCallback(WebKitWebView*, WebKitFormSubmissionRequest* request, FormClientTest* test) - { - test->submitForm(request); - } - - FormClientTest() - : m_submitPositionX(0) - , m_submitPositionY(0) - { - g_signal_connect(m_webView, "submit-form", G_CALLBACK(submitFormCallback), this); - } - - ~FormClientTest() - { - g_signal_handlers_disconnect_matched(m_webView, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - } - - void submitForm(WebKitFormSubmissionRequest* request) - { - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(request)); - m_request = request; - webkit_form_submission_request_submit(request); - quitMainLoop(); - } - - GHashTable* waitUntilFormSubmittedAndGetTextFields() - { - g_main_loop_run(m_mainLoop); - return webkit_form_submission_request_get_text_fields(m_request.get()); - } - - static gboolean doClickIdleCallback(FormClientTest* test) - { - test->clickMouseButton(test->m_submitPositionX, test->m_submitPositionY, 1); - return FALSE; - } - - void submitFormAtPosition(int x, int y) - { - m_submitPositionX = x; - m_submitPositionY = y; - g_idle_add(reinterpret_cast<GSourceFunc>(doClickIdleCallback), this); - } - - int m_submitPositionX; - int m_submitPositionY; - GRefPtr<WebKitFormSubmissionRequest> m_request; -}; - -static void testWebViewSubmitForm(FormClientTest* test, gconstpointer) -{ - test->showInWindowAndWaitUntilMapped(); - - const char* formHTML = - "<html><body>" - " <form action='#'>" - " <input type='text' name='text1' value='value1'>" - " <input type='text' name='text2' value='value2'>" - " <input type='password' name='password' value='secret'>" - " <textarea cols='5' rows='5' name='textarea'>Text</textarea>" - " <input type='hidden' name='hidden1' value='hidden1'>" - " <input type='submit' value='Submit' style='position:absolute; left:1; top:1' size='10'>" - " </form>" - "</body></html>"; - - test->loadHtml(formHTML, "file:///"); - test->waitUntilLoadFinished(); - - test->submitFormAtPosition(5, 5); - GHashTable* values = test->waitUntilFormSubmittedAndGetTextFields(); - g_assert(values); - g_assert_cmpuint(g_hash_table_size(values), ==, 3); - g_assert_cmpstr(static_cast<char*>(g_hash_table_lookup(values, "text1")), ==, "value1"); - g_assert_cmpstr(static_cast<char*>(g_hash_table_lookup(values, "text2")), ==, "value2"); - g_assert_cmpstr(static_cast<char*>(g_hash_table_lookup(values, "password")), ==, "secret"); -} - -class SaveWebViewTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(SaveWebViewTest); - - SaveWebViewTest() - : m_tempDirectory(g_dir_make_tmp("WebKit2SaveViewTest-XXXXXX", 0)) - { - } - - ~SaveWebViewTest() - { - if (G_IS_FILE(m_file.get())) - g_file_delete(m_file.get(), 0, 0); - - if (G_IS_INPUT_STREAM(m_inputStream.get())) - g_input_stream_close(m_inputStream.get(), 0, 0); - - if (m_tempDirectory) - g_rmdir(m_tempDirectory.get()); - } - - static void webViewSavedToStreamCallback(GObject* object, GAsyncResult* result, SaveWebViewTest* test) - { - GOwnPtr<GError> error; - test->m_inputStream = adoptGRef(webkit_web_view_save_finish(test->m_webView, result, &error.outPtr())); - g_assert(G_IS_INPUT_STREAM(test->m_inputStream.get())); - g_assert(!error); - - test->quitMainLoop(); - } - - static void webViewSavedToFileCallback(GObject* object, GAsyncResult* result, SaveWebViewTest* test) - { - GOwnPtr<GError> error; - g_assert(webkit_web_view_save_to_file_finish(test->m_webView, result, &error.outPtr())); - g_assert(!error); - - test->quitMainLoop(); - } - - void saveAndWaitForStream() - { - webkit_web_view_save(m_webView, WEBKIT_SAVE_MODE_MHTML, 0, reinterpret_cast<GAsyncReadyCallback>(webViewSavedToStreamCallback), this); - g_main_loop_run(m_mainLoop); - } - - void saveAndWaitForFile() - { - m_saveDestinationFilePath.set(g_build_filename(m_tempDirectory.get(), "testWebViewSaveResult.mht", NULL)); - m_file = adoptGRef(g_file_new_for_path(m_saveDestinationFilePath.get())); - webkit_web_view_save_to_file(m_webView, m_file.get(), WEBKIT_SAVE_MODE_MHTML, 0, reinterpret_cast<GAsyncReadyCallback>(webViewSavedToFileCallback), this); - g_main_loop_run(m_mainLoop); - } - - GOwnPtr<char> m_tempDirectory; - GOwnPtr<char> m_saveDestinationFilePath; - GRefPtr<GInputStream> m_inputStream; - GRefPtr<GFile> m_file; -}; - -static void testWebViewSave(SaveWebViewTest* test, gconstpointer) -{ - test->loadHtml("<html>" - "<body>" - " <p>A paragraph with plain text</p>" - " <p>" - " A red box: <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AYWDTMVwnSZnwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFklEQVQI12P8z8DAwMDAxMDAwMDAAAANHQEDK+mmyAAAAABJRU5ErkJggg=='></br>" - " A blue box: <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AYWDTMvBHhALQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFklEQVQI12Nk4PnPwMDAxMDAwMDAAAALrwEPPIs1pgAAAABJRU5ErkJggg=='>" - " </p>" - "</body>" - "</html>", 0); - test->waitUntilLoadFinished(); - - // Write to a file and to an input stream. - test->saveAndWaitForFile(); - test->saveAndWaitForStream(); - - // We should have exactly the same amount of bytes in the file - // than those coming from the GInputStream. We don't compare the - // strings read since the 'Date' field and the boundaries will be - // different on each case. MHTML functionality will be tested by - // Layout tests, so checking the amount of bytes is enough. - GOwnPtr<GError> error; - gchar buffer[512] = { 0 }; - gssize readBytes = 0; - gssize totalBytesFromStream = 0; - while (readBytes = g_input_stream_read(test->m_inputStream.get(), &buffer, 512, 0, &error.outPtr())) { - g_assert(!error); - totalBytesFromStream += readBytes; - } - - // Check that the file exists and that it contains the same amount of bytes. - GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(test->m_file.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE, static_cast<GFileQueryInfoFlags>(0), 0, 0)); - 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); - WebViewTest::add("WebKitWebView", "custom-charset", testWebViewCustomCharset); - WebViewTest::add("WebKitWebView", "settings", testWebViewSettings); - UIClientTest::add("WebKitWebView", "create-ready-close", testWebViewCreateReadyClose); - ModalDialogsTest::add("WebKitWebView", "allow-modal-dialogs", testWebViewAllowModalDialogs); - ModalDialogsTest::add("WebKitWebView", "disallow-modal-dialogs", testWebViewDisallowModalDialogs); - UIClientTest::add("WebKitWebView", "javascript-dialogs", testWebViewJavaScriptDialogs); - UIClientTest::add("WebKitWebView", "window-properties", testWebViewWindowProperties); - UIClientTest::add("WebKitWebView", "mouse-target", testWebViewMouseTarget); - UIClientTest::add("WebKitWebView", "permission-requests", testWebViewPermissionRequests); - WebViewTest::add("WebKitWebView", "zoom-level", testWebViewZoomLevel); - WebViewTest::add("WebKitWebView", "run-javascript", testWebViewRunJavaScript); - FileChooserTest::add("WebKitWebView", "file-chooser-request", testWebViewFileChooserRequest); - FullScreenClientTest::add("WebKitWebView", "fullscreen", testWebViewFullScreen); - 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 deleted file mode 100644 index 026c5c5b9..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebKitWebViewGroup.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * 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/TestWebViewEditor.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/TestWebViewEditor.cpp deleted file mode 100644 index 93315db68..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/TestWebViewEditor.cpp +++ /dev/null @@ -1,202 +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 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 "WebViewTest.h" -#include <wtf/gobject/GRefPtr.h> - -class EditorTest: public WebViewTest { -public: - MAKE_GLIB_TEST_FIXTURE(EditorTest); - - static const unsigned int kClipboardWaitTimeout = 50; - static const unsigned int kClipboardWaitMaxTries = 2; - - EditorTest() - : m_clipboard(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD)) - , m_canExecuteEditingCommand(false) - , m_triesCount(0) - { - gtk_clipboard_clear(m_clipboard); - } - - static void canExecuteEditingCommandReadyCallback(GObject*, GAsyncResult* result, EditorTest* test) - { - GOwnPtr<GError> error; - test->m_canExecuteEditingCommand = webkit_web_view_can_execute_editing_command_finish(test->m_webView, result, &error.outPtr()); - g_assert(!error.get()); - g_main_loop_quit(test->m_mainLoop); - } - - bool canExecuteEditingCommand(const char* command) - { - m_canExecuteEditingCommand = false; - webkit_web_view_can_execute_editing_command(m_webView, command, 0, reinterpret_cast<GAsyncReadyCallback>(canExecuteEditingCommandReadyCallback), this); - g_main_loop_run(m_mainLoop); - return m_canExecuteEditingCommand; - } - - static gboolean waitForClipboardText(EditorTest* test) - { - test->m_triesCount++; - if (gtk_clipboard_wait_is_text_available(test->m_clipboard) || test->m_triesCount > kClipboardWaitMaxTries) { - g_main_loop_quit(test->m_mainLoop); - return FALSE; - } - - return TRUE; - } - - void copyClipboard() - { - webkit_web_view_execute_editing_command(m_webView, WEBKIT_EDITING_COMMAND_COPY); - // There's no way to know when the selection has been copied to - // the clipboard, so use a timeout source to query the clipboard. - m_triesCount = 0; - g_timeout_add(kClipboardWaitTimeout, reinterpret_cast<GSourceFunc>(waitForClipboardText), this); - g_main_loop_run(m_mainLoop); - } - - GtkClipboard* m_clipboard; - bool m_canExecuteEditingCommand; - size_t m_triesCount; -}; - -static void testWebViewEditorCutCopyPasteNonEditable(EditorTest* test, gconstpointer) -{ - static const char* selectedSpanHTML = "<html><body contentEditable=\"false\">" - "<span id=\"mainspan\">All work and no play <span id=\"subspan\">make Jack a dull</span> boy.</span>" - "<script>document.getSelection().collapse();\n" - "document.getSelection().selectAllChildren(document.getElementById('subspan'));\n" - "</script></body></html>"; - - // Nothing loaded yet. - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_CUT)); - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_COPY)); - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_PASTE)); - - test->loadHtml(selectedSpanHTML, 0); - test->waitUntilLoadFinished(); - - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_COPY)); - // It's not possible to cut and paste when content is not editable - // even if there's a selection. - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_CUT)); - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_PASTE)); - - test->copyClipboard(); - GOwnPtr<char> clipboardText(gtk_clipboard_wait_for_text(test->m_clipboard)); - g_assert_cmpstr(clipboardText.get(), ==, "make Jack a dull"); -} - -static void testWebViewEditorCutCopyPasteEditable(EditorTest* test, gconstpointer) -{ - static const char* selectedSpanHTML = "<html><body contentEditable=\"true\">" - "<span id=\"mainspan\">All work and no play <span>make Jack a dull</span> boy.</span>" - "<script>document.getSelection().collapse();\n" - "document.getSelection().selectAllChildren(document.getElementById('mainspan'));\n" - "</script></body></html>"; - - // Nothing loaded yet. - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_CUT)); - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_COPY)); - g_assert(!test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_PASTE)); - - test->loadHtml(selectedSpanHTML, 0); - test->waitUntilLoadFinished(); - - // There's a selection. - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_CUT)); - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_COPY)); - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_PASTE)); - - test->copyClipboard(); - GOwnPtr<char> clipboardText(gtk_clipboard_wait_for_text(test->m_clipboard)); - g_assert_cmpstr(clipboardText.get(), ==, "All work and no play make Jack a dull boy."); -} - -static void testWebViewEditorSelectAllNonEditable(EditorTest* test, gconstpointer) -{ - static const char* selectedSpanHTML = "<html><body contentEditable=\"false\">" - "<span id=\"mainspan\">All work and no play <span id=\"subspan\">make Jack a dull</span> boy.</span>" - "<script>document.getSelection().collapse();\n" - "document.getSelection().selectAllChildren(document.getElementById('subspan'));\n" - "</script></body></html>"; - - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_SELECT_ALL)); - - test->loadHtml(selectedSpanHTML, 0); - test->waitUntilLoadFinished(); - - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_SELECT_ALL)); - - test->copyClipboard(); - GOwnPtr<char> clipboardText(gtk_clipboard_wait_for_text(test->m_clipboard)); - - // Initially only the subspan is selected. - g_assert_cmpstr(clipboardText.get(), ==, "make Jack a dull"); - - webkit_web_view_execute_editing_command(test->m_webView, WEBKIT_EDITING_COMMAND_SELECT_ALL); - test->copyClipboard(); - clipboardText.set(gtk_clipboard_wait_for_text(test->m_clipboard)); - - // The mainspan should be selected after calling SELECT_ALL. - g_assert_cmpstr(clipboardText.get(), ==, "All work and no play make Jack a dull boy."); -} - -static void testWebViewEditorSelectAllEditable(EditorTest* test, gconstpointer) -{ - static const char* selectedSpanHTML = "<html><body contentEditable=\"true\">" - "<span id=\"mainspan\">All work and no play <span id=\"subspan\">make Jack a dull</span> boy.</span>" - "<script>document.getSelection().collapse();\n" - "document.getSelection().selectAllChildren(document.getElementById('subspan'));\n" - "</script></body></html>"; - - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_SELECT_ALL)); - - test->loadHtml(selectedSpanHTML, 0); - test->waitUntilLoadFinished(); - - g_assert(test->canExecuteEditingCommand(WEBKIT_EDITING_COMMAND_SELECT_ALL)); - - test->copyClipboard(); - GOwnPtr<char> clipboardText(gtk_clipboard_wait_for_text(test->m_clipboard)); - - // Initially only the subspan is selected. - g_assert_cmpstr(clipboardText.get(), ==, "make Jack a dull"); - - webkit_web_view_execute_editing_command(test->m_webView, WEBKIT_EDITING_COMMAND_SELECT_ALL); - test->copyClipboard(); - clipboardText.set(gtk_clipboard_wait_for_text(test->m_clipboard)); - - // The mainspan should be selected after calling SELECT_ALL. - g_assert_cmpstr(clipboardText.get(), ==, "All work and no play make Jack a dull boy."); -} - -void beforeAll() -{ - EditorTest::add("WebKitWebView", "cut-copy-paste/non-editable", testWebViewEditorCutCopyPasteNonEditable); - EditorTest::add("WebKitWebView", "cut-copy-paste/editable", testWebViewEditorCutCopyPasteEditable); - EditorTest::add("WebKitWebView", "select-all/non-editable", testWebViewEditorSelectAllNonEditable); - EditorTest::add("WebKitWebView", "select-all/editable", testWebViewEditorSelectAllEditable); -} - -void afterAll() -{ -} diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp deleted file mode 100644 index 692663e33..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebExtensionTest.cpp +++ /dev/null @@ -1,158 +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 <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 deleted file mode 100644 index 8c2d3f638..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.cpp +++ /dev/null @@ -1,106 +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 "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/tests/WebKitTestBus.h b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.h deleted file mode 100644 index b9f856b27..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestBus.h +++ /dev/null @@ -1,44 +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. - */ - -#ifndef WebKitTestBus_h -#define WebKitTestBus_h - -#include <gio/gio.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -class WebKitTestBus { -public: - WebKitTestBus(); - virtual ~WebKitTestBus(); - - bool run(); - GDBusProxy* createProxy(const char* serviceName, const char* objectPath, const char* interfaceName, GMainLoop*); - GDBusConnection* connection() const { return m_connection.get(); } - -private: - GDBusConnection* getOrCreateConnection(); - - pid_t m_pid; - CString m_address; - GRefPtr<GDBusConnection> m_connection; -}; - -#endif // WebKitTestBus_h diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.cpp deleted file mode 100644 index 98b4a9a2b..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebKitTestServer.h" - -#include "TestMain.h" -#include <wtf/gobject/GOwnPtr.h> - -WebKitTestServer::WebKitTestServer(ServerType type) -{ - GOwnPtr<char> sslCertificateFile; - GOwnPtr<char> sslKeyFile; - if (type == ServerHTTPS) { - CString resourcesDir = Test::getResourcesDir(); - sslCertificateFile.set(g_build_filename(resourcesDir.data(), "test-cert.pem", NULL)); - sslKeyFile.set(g_build_filename(resourcesDir.data(), "test-key.pem", NULL)); - } - - GRefPtr<SoupAddress> address = adoptGRef(soup_address_new("127.0.0.1", SOUP_ADDRESS_ANY_PORT)); - soup_address_resolve_sync(address.get(), 0); - - m_soupServer = adoptGRef(soup_server_new(SOUP_SERVER_INTERFACE, address.get(), - SOUP_SERVER_SSL_CERT_FILE, sslCertificateFile.get(), - SOUP_SERVER_SSL_KEY_FILE, sslKeyFile.get(), NULL)); - m_baseURI = type == ServerHTTPS ? soup_uri_new("https://127.0.0.1/") : soup_uri_new("http://127.0.0.1/"); - soup_uri_set_port(m_baseURI, soup_server_get_port(m_soupServer.get())); -} - -WebKitTestServer::~WebKitTestServer() -{ - soup_uri_free(m_baseURI); -} - -void WebKitTestServer::run(SoupServerCallback serverCallback) -{ - soup_server_run_async(m_soupServer.get()); - soup_server_add_handler(m_soupServer.get(), 0, serverCallback, 0, 0); -} - -CString WebKitTestServer::getURIForPath(const char* path) -{ - SoupURI* uri = soup_uri_new_with_base(m_baseURI, path); - GOwnPtr<gchar> uriString(soup_uri_to_string(uri, FALSE)); - soup_uri_free(uri); - return uriString.get(); -} - diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.h b/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.h deleted file mode 100644 index d4626f6b1..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebKitTestServer.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2011 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 WebKitTestServer_h -#define WebKitTestServer_h - -#include <libsoup/soup.h> -#include <webkit2/webkit2.h> -#include <wtf/gobject/GRefPtr.h> -#include <wtf/text/CString.h> - -class WebKitTestServer { -public: - - enum ServerType { - ServerHTTP, - ServerHTTPS - }; - - WebKitTestServer(ServerType type = ServerHTTP); - virtual ~WebKitTestServer(); - - SoupURI* baseURI() { return m_baseURI; } - - CString getURIForPath(const char* path); - void run(SoupServerCallback); - -private: - GRefPtr<SoupServer> m_soupServer; - SoupURI* m_baseURI; -}; - -#endif // WebKitTestServer_h diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp b/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp deleted file mode 100644 index e6c843456..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.cpp +++ /dev/null @@ -1,444 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 "WebViewTest.h" - -#include <JavaScriptCore/JSRetainPtr.h> -#include <WebCore/GOwnPtrGtk.h> - -WebViewTest::WebViewTest() - : m_webView(WEBKIT_WEB_VIEW(g_object_ref_sink(webkit_web_view_new()))) - , m_mainLoop(g_main_loop_new(0, TRUE)) - , m_parentWindow(0) - , m_javascriptResult(0) - , m_resourceDataSize(0) - , m_surface(0) -{ - assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_webView)); -} - -WebViewTest::~WebViewTest() -{ - if (m_parentWindow) - 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); -} - -void WebViewTest::loadURI(const char* uri) -{ - m_activeURI = uri; - webkit_web_view_load_uri(m_webView, uri); -} - -void WebViewTest::loadHtml(const char* html, const char* baseURI) -{ - if (!baseURI) - m_activeURI = "about:blank"; - else - m_activeURI = baseURI; - webkit_web_view_load_html(m_webView, html, baseURI); -} - -void WebViewTest::loadPlainText(const char* plainText) -{ - m_activeURI = "about:blank"; - webkit_web_view_load_plain_text(m_webView, plainText); -} - -void WebViewTest::loadRequest(WebKitURIRequest* request) -{ - m_activeURI = webkit_uri_request_get_uri(request); - webkit_web_view_load_request(m_webView, request); -} - -void WebViewTest::loadAlternateHTML(const char* html, const char* contentURI, const char* baseURI) -{ - m_activeURI = contentURI; - webkit_web_view_load_alternate_html(m_webView, html, contentURI, baseURI); -} - -void WebViewTest::goBack() -{ - if (webkit_web_view_can_go_back(m_webView)) { - WebKitBackForwardList* list = webkit_web_view_get_back_forward_list(m_webView); - WebKitBackForwardListItem* item = webkit_back_forward_list_get_nth_item(list, -1); - m_activeURI = webkit_back_forward_list_item_get_original_uri(item); - } - - // Call go_back even when can_go_back returns FALSE to check nothing happens. - webkit_web_view_go_back(m_webView); -} - -void WebViewTest::goForward() -{ - if (webkit_web_view_can_go_forward(m_webView)) { - WebKitBackForwardList* list = webkit_web_view_get_back_forward_list(m_webView); - WebKitBackForwardListItem* item = webkit_back_forward_list_get_nth_item(list, 1); - m_activeURI = webkit_back_forward_list_item_get_original_uri(item); - } - - // Call go_forward even when can_go_forward returns FALSE to check nothing happens. - webkit_web_view_go_forward(m_webView); -} - -void WebViewTest::goToBackForwardListItem(WebKitBackForwardListItem* item) -{ - m_activeURI = webkit_back_forward_list_item_get_original_uri(item); - webkit_web_view_go_to_back_forward_list_item(m_webView, item); -} - -void WebViewTest::quitMainLoop() -{ - g_main_loop_quit(m_mainLoop); -} - -void WebViewTest::quitMainLoopAfterProcessingPendingEvents() -{ - while (gtk_events_pending()) - gtk_main_iteration(); - quitMainLoop(); -} - -static gboolean quitMainLoopIdleCallback(WebViewTest* test) -{ - test->quitMainLoop(); - return FALSE; -} - -void WebViewTest::wait(double seconds) -{ - g_timeout_add_seconds(seconds, reinterpret_cast<GSourceFunc>(quitMainLoopIdleCallback), this); - g_main_loop_run(m_mainLoop); -} - -static void loadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent, WebViewTest* test) -{ - if (loadEvent != WEBKIT_LOAD_FINISHED) - return; - g_signal_handlers_disconnect_by_func(webView, reinterpret_cast<void*>(loadChanged), test); - g_main_loop_quit(test->m_mainLoop); -} - -void WebViewTest::waitUntilLoadFinished() -{ - g_signal_connect(m_webView, "load-changed", G_CALLBACK(loadChanged), this); - g_main_loop_run(m_mainLoop); -} - -static void titleChanged(WebKitWebView* webView, GParamSpec*, WebViewTest* test) -{ - if (!test->m_expectedTitle.isNull() && test->m_expectedTitle != webkit_web_view_get_title(webView)) - return; - - g_signal_handlers_disconnect_by_func(webView, reinterpret_cast<void*>(titleChanged), test); - g_main_loop_quit(test->m_mainLoop); -} - -void WebViewTest::waitUntilTitleChangedTo(const char* expectedTitle) -{ - m_expectedTitle = expectedTitle; - g_signal_connect(m_webView, "notify::title", G_CALLBACK(titleChanged), this); - g_main_loop_run(m_mainLoop); - m_expectedTitle = CString(); -} - -void WebViewTest::waitUntilTitleChanged() -{ - waitUntilTitleChangedTo(0); -} - -static gboolean parentWindowMapped(GtkWidget* widget, GdkEvent*, WebViewTest* test) -{ - g_signal_handlers_disconnect_by_func(widget, reinterpret_cast<void*>(parentWindowMapped), test); - g_main_loop_quit(test->m_mainLoop); - - 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); - m_parentWindow = gtk_window_new(windowType); - gtk_container_add(GTK_CONTAINER(m_parentWindow), GTK_WIDGET(m_webView)); - gtk_widget_show(GTK_WIDGET(m_webView)); - - g_signal_connect(m_parentWindow, "map-event", G_CALLBACK(parentWindowMapped), this); - gtk_widget_show(m_parentWindow); - g_main_loop_run(m_mainLoop); -} - -void WebViewTest::resizeView(int width, int height) -{ - GtkAllocation allocation; - gtk_widget_get_allocation(GTK_WIDGET(m_webView), &allocation); - if (width != -1) - allocation.width = width; - if (height != -1) - allocation.height = 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; - GOwnPtr<GError> error; - unsigned char* data = webkit_web_resource_get_data_finish(WEBKIT_WEB_RESOURCE(object), result, &dataSize, &error.outPtr()); - g_assert(data); - - WebViewTest* test = static_cast<WebViewTest*>(userData); - test->m_resourceData.set(reinterpret_cast<char*>(data)); - test->m_resourceDataSize = dataSize; - g_main_loop_quit(test->m_mainLoop); -} - -const char* WebViewTest::mainResourceData(size_t& mainResourceDataSize) -{ - m_resourceDataSize = 0; - m_resourceData.clear(); - WebKitWebResource* resource = webkit_web_view_get_main_resource(m_webView); - g_assert(resource); - - webkit_web_resource_get_data(resource, 0, resourceGetDataCallback, this); - g_main_loop_run(m_mainLoop); - - mainResourceDataSize = m_resourceDataSize; - return m_resourceData.get(); -} - -void WebViewTest::mouseMoveTo(int x, int y, unsigned int mouseModifiers) -{ - g_assert(m_parentWindow); - GtkWidget* viewWidget = GTK_WIDGET(m_webView); - g_assert(gtk_widget_get_realized(viewWidget)); - - GOwnPtr<GdkEvent> event(gdk_event_new(GDK_MOTION_NOTIFY)); - event->motion.x = x; - event->motion.y = y; - - event->motion.time = GDK_CURRENT_TIME; - event->motion.window = gtk_widget_get_window(viewWidget); - g_object_ref(event->motion.window); - event->motion.device = gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gtk_widget_get_display(viewWidget))); - event->motion.state = mouseModifiers; - event->motion.axes = 0; - - int xRoot, yRoot; - gdk_window_get_root_coords(gtk_widget_get_window(viewWidget), x, y, &xRoot, &yRoot); - event->motion.x_root = xRoot; - event->motion.y_root = yRoot; - gtk_main_do_event(event.get()); -} - -void WebViewTest::clickMouseButton(int x, int y, unsigned int button, unsigned int mouseModifiers) -{ - doMouseButtonEvent(GDK_BUTTON_PRESS, x, y, button, mouseModifiers); - doMouseButtonEvent(GDK_BUTTON_RELEASE, x, y, button, mouseModifiers); -} - -void WebViewTest::keyStroke(unsigned int keyVal, unsigned int keyModifiers) -{ - g_assert(m_parentWindow); - GtkWidget* viewWidget = GTK_WIDGET(m_webView); - g_assert(gtk_widget_get_realized(viewWidget)); - - GOwnPtr<GdkEvent> event(gdk_event_new(GDK_KEY_PRESS)); - event->key.keyval = keyVal; - - event->key.time = GDK_CURRENT_TIME; - event->key.window = gtk_widget_get_window(viewWidget); - g_object_ref(event->key.window); - gdk_event_set_device(event.get(), gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gtk_widget_get_display(viewWidget)))); - event->key.state = keyModifiers; - - // When synthesizing an event, an invalid hardware_keycode value can cause it to be badly processed by GTK+. - GOwnPtr<GdkKeymapKey> keys; - int keysCount; - if (gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), keyVal, &keys.outPtr(), &keysCount)) - event->key.hardware_keycode = keys.get()[0].keycode; - - gtk_main_do_event(event.get()); - event->key.type = GDK_KEY_RELEASE; - gtk_main_do_event(event.get()); -} - -void WebViewTest::doMouseButtonEvent(GdkEventType eventType, int x, int y, unsigned int button, unsigned int mouseModifiers) -{ - g_assert(m_parentWindow); - GtkWidget* viewWidget = GTK_WIDGET(m_webView); - g_assert(gtk_widget_get_realized(viewWidget)); - - GOwnPtr<GdkEvent> event(gdk_event_new(eventType)); - event->button.window = gtk_widget_get_window(viewWidget); - g_object_ref(event->button.window); - - event->button.time = GDK_CURRENT_TIME; - event->button.x = x; - event->button.y = y; - event->button.axes = 0; - event->button.state = mouseModifiers; - event->button.button = button; - - event->button.device = gdk_device_manager_get_client_pointer(gdk_display_get_device_manager(gtk_widget_get_display(viewWidget))); - - int xRoot, yRoot; - gdk_window_get_root_coords(gtk_widget_get_window(viewWidget), x, y, &xRoot, &yRoot); - event->button.x_root = xRoot; - event->button.y_root = yRoot; - gtk_main_do_event(event.get()); -} - -static void runJavaScriptReadyCallback(GObject*, GAsyncResult* result, WebViewTest* test) -{ - test->m_javascriptResult = webkit_web_view_run_javascript_finish(test->m_webView, result, test->m_javascriptError); - g_main_loop_quit(test->m_mainLoop); -} - -static void runJavaScriptFromGResourceReadyCallback(GObject*, GAsyncResult* result, WebViewTest* test) -{ - test->m_javascriptResult = webkit_web_view_run_javascript_from_gresource_finish(test->m_webView, result, test->m_javascriptError); - g_main_loop_quit(test->m_mainLoop); -} - -WebKitJavascriptResult* WebViewTest::runJavaScriptAndWaitUntilFinished(const char* javascript, GError** error) -{ - if (m_javascriptResult) - webkit_javascript_result_unref(m_javascriptResult); - m_javascriptResult = 0; - m_javascriptError = error; - webkit_web_view_run_javascript(m_webView, javascript, 0, reinterpret_cast<GAsyncReadyCallback>(runJavaScriptReadyCallback), this); - g_main_loop_run(m_mainLoop); - - return m_javascriptResult; -} - -WebKitJavascriptResult* WebViewTest::runJavaScriptFromGResourceAndWaitUntilFinished(const char* resource, GError** error) -{ - if (m_javascriptResult) - webkit_javascript_result_unref(m_javascriptResult); - m_javascriptResult = 0; - m_javascriptError = error; - webkit_web_view_run_javascript_from_gresource(m_webView, resource, 0, reinterpret_cast<GAsyncReadyCallback>(runJavaScriptFromGResourceReadyCallback), this); - g_main_loop_run(m_mainLoop); - - return m_javascriptResult; -} - -static char* jsValueToCString(JSGlobalContextRef context, JSValueRef value) -{ - g_assert(value); - g_assert(JSValueIsString(context, value)); - - JSRetainPtr<JSStringRef> stringValue(Adopt, JSValueToStringCopy(context, value, 0)); - g_assert(stringValue); - - size_t cStringLength = JSStringGetMaximumUTF8CStringSize(stringValue.get()); - char* cString = static_cast<char*>(g_malloc(cStringLength)); - JSStringGetUTF8CString(stringValue.get(), cString, cStringLength); - return cString; -} - -char* WebViewTest::javascriptResultToCString(WebKitJavascriptResult* javascriptResult) -{ - JSGlobalContextRef context = webkit_javascript_result_get_global_context(javascriptResult); - g_assert(context); - return jsValueToCString(context, webkit_javascript_result_get_value(javascriptResult)); -} - -double WebViewTest::javascriptResultToNumber(WebKitJavascriptResult* javascriptResult) -{ - JSGlobalContextRef context = webkit_javascript_result_get_global_context(javascriptResult); - g_assert(context); - JSValueRef value = webkit_javascript_result_get_value(javascriptResult); - g_assert(value); - g_assert(JSValueIsNumber(context, value)); - - return JSValueToNumber(context, value, 0); -} - -bool WebViewTest::javascriptResultToBoolean(WebKitJavascriptResult* javascriptResult) -{ - JSGlobalContextRef context = webkit_javascript_result_get_global_context(javascriptResult); - g_assert(context); - JSValueRef value = webkit_javascript_result_get_value(javascriptResult); - g_assert(value); - g_assert(JSValueIsBoolean(context, value)); - - return JSValueToBoolean(context, value); -} - -bool WebViewTest::javascriptResultIsNull(WebKitJavascriptResult* javascriptResult) -{ - JSGlobalContextRef context = webkit_javascript_result_get_global_context(javascriptResult); - g_assert(context); - JSValueRef value = webkit_javascript_result_get_value(javascriptResult); - g_assert(value); - - return JSValueIsNull(context, value); -} - -bool WebViewTest::javascriptResultIsUndefined(WebKitJavascriptResult* javascriptResult) -{ - JSGlobalContextRef context = webkit_javascript_result_get_global_context(javascriptResult); - g_assert(context); - JSValueRef value = webkit_javascript_result_get_value(javascriptResult); - g_assert(value); - - 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 deleted file mode 100644 index a460e22b4..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 WebViewTest_h -#define WebViewTest_h - -#include "TestMain.h" -#include <webkit2/webkit2.h> -#include <wtf/text/CString.h> - -class WebViewTest: public Test { -public: - MAKE_GLIB_TEST_FIXTURE(WebViewTest); - WebViewTest(); - virtual ~WebViewTest(); - - virtual void loadURI(const char* uri); - virtual void loadHtml(const char* html, const char* baseURI); - virtual void loadPlainText(const char* plainText); - virtual void loadRequest(WebKitURIRequest*); - void loadAlternateHTML(const char* html, const char* contentURI, const char* baseURI); - void goBack(); - void goForward(); - void goToBackForwardListItem(WebKitBackForwardListItem*); - - void quitMainLoop(); - void quitMainLoopAfterProcessingPendingEvents(); - void wait(double seconds); - 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); - void clickMouseButton(int x, int y, unsigned int button = 1, unsigned int mouseModifiers = 0); - void keyStroke(unsigned int keyVal, unsigned int keyModifiers = 0); - - WebKitJavascriptResult* runJavaScriptAndWaitUntilFinished(const char* javascript, GError**); - WebKitJavascriptResult* runJavaScriptFromGResourceAndWaitUntilFinished(const char* resource, GError**); - - // Javascript result helpers. - static char* javascriptResultToCString(WebKitJavascriptResult*); - static double javascriptResultToNumber(WebKitJavascriptResult*); - static bool javascriptResultToBoolean(WebKitJavascriptResult*); - static bool javascriptResultIsNull(WebKitJavascriptResult*); - static bool javascriptResultIsUndefined(WebKitJavascriptResult*); - - cairo_surface_t* getSnapshotAndWaitUntilReady(WebKitSnapshotRegion, WebKitSnapshotOptions); - - WebKitWebView* m_webView; - GMainLoop* m_mainLoop; - CString m_activeURI; - GtkWidget* m_parentWindow; - CString m_expectedTitle; - WebKitJavascriptResult* m_javascriptResult; - 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); -}; - -#endif // WebViewTest_h diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/resources/link-title.js b/Source/WebKit2/UIProcess/API/gtk/tests/resources/link-title.js deleted file mode 100644 index 2c824da38..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/resources/link-title.js +++ /dev/null @@ -1 +0,0 @@ -window.document.getElementById('WebKitLink').title; diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/resources/test-cert.pem b/Source/WebKit2/UIProcess/API/gtk/tests/resources/test-cert.pem deleted file mode 100644 index b34301f25..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/resources/test-cert.pem +++ /dev/null @@ -1,13 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIB9jCCAV+gAwIBAgIJALeuXBo+vwz9MA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV -BAMMCTEyNy4wLjAuMTAeFw0xMjA3MTIxMjQ4MjRaFw0yMjA3MTAxMjQ4MjRaMBQx -EjAQBgNVBAMMCTEyNy4wLjAuMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA -0TUzOQxHBIKDD2mkuq+tU92mQvDZg73B0G+Nhr2T2G6MbcLqIwjg1QYtBZWJ83tZ -xMMEfiweHLF85Z9ohavAgxJlKG7YmvZO79KkFpmjV2W5CVRm0eYMPnzmxNCoaYqo -DLl0zsH6KZOLPKu/fX4eDX9XpAP1f83hWB1UFBmHKN8CAwEAAaNQME4wHQYDVR0O -BBYEFDHv5ZQ1BdmhzTsDUEoY55EXyUdKMB8GA1UdIwQYMBaAFDHv5ZQ1BdmhzTsD -UEoY55EXyUdKMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAh3qMBx7v -jSodMf3OyTqTLE7deLnmnCeBVpgzxRZEoizcGqYcjiqO27i5N5Z6KVQsnITnLiyC -mUtuR5KnF69uTKUw4m/ugZe5whjig5Mq2l410KVK6EeG4tdLlfXR+wi4U5K4KjP6 -p4nchQUXLa2zcbJn+VBexJn6/9wdhr+DUGY= ------END CERTIFICATE----- diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/resources/test-key.pem b/Source/WebKit2/UIProcess/API/gtk/tests/resources/test-key.pem deleted file mode 100644 index 9036222ce..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/resources/test-key.pem +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANE1MzkMRwSCgw9p -pLqvrVPdpkLw2YO9wdBvjYa9k9hujG3C6iMI4NUGLQWVifN7WcTDBH4sHhyxfOWf -aIWrwIMSZShu2Jr2Tu/SpBaZo1dluQlUZtHmDD585sTQqGmKqAy5dM7B+imTizyr -v31+Hg1/V6QD9X/N4VgdVBQZhyjfAgMBAAECgYB2QwOUsRsIMprRwJ9tJNfvO7G7 -z5i1/zOrlxPC4jHMPBnIBlICwgcOhLI4oOLdr5H8R12n0VqoT7DRwP396iwlJipF -iO1heDMn/8z8LPGwkCK/+ck04rMDksxWIdMwYKBXt9ahnJ/xRLzQ1/3AJiAGnoe5 -/QLXQweofd4mmfsjKQJBAO2CwT7uMP6nMjXgtVMJq5QP8UbeCS1sEOPJJbHuDxJB -/HePQHBjq4kzG6CL4oO7T+5fDv4g+fIIHzuXerZ0imsCQQDhfmiTIc9OucEIfg6/ -ms0JiKSmWc+qoiOCtrILuQvFoNwJRciQANqeJs6wpaDvevSUvBLGfG/7b3HvaE5X -iqBdAkBEQIvp2qcHtuJN60oQF7pPrRknxUyb2e8sljQX4pJAK+gyL19ULMAxiBdL -Vod8VYqNtJFpY+6Pp9fZ1xjzb6ALAkEA4JzrDAw0lQXA+3WduUw4ixOadr2ldyG0 -36KebcDwsfZO18m0Q4UmPz0Gy7zgN0wxzuochaw0W6+iPUiYKOlEXQJBAMWQrPlu -rrinoZS2f8doJ9BNNUa+RNpMug6UXc55qoUJlyiXEh+tu4AaMOtxuGIyC0sAcuw6 -XdAPVPXKd7Mne70= ------END PRIVATE KEY----- diff --git a/Source/WebKit2/UIProcess/API/gtk/tests/resources/webkit2gtk-tests.gresource.xml b/Source/WebKit2/UIProcess/API/gtk/tests/resources/webkit2gtk-tests.gresource.xml deleted file mode 100644 index 4f1e5a654..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/tests/resources/webkit2gtk-tests.gresource.xml +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<gresources> - <gresource prefix="/org/webkit/webkit2gtk/tests/"> - <file alias="link-title.js">Source/WebKit2/UIProcess/API/gtk/tests/resources/link-title.js</file> - </gresource> -</gresources> diff --git a/Source/WebKit2/UIProcess/API/gtk/webkit2.h b/Source/WebKit2/UIProcess/API/gtk/webkit2.h deleted file mode 100644 index d18431528..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/webkit2.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2011 Igalia S.L. - * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 __WEBKIT2_H__ -#define __WEBKIT2_H__ - -#define __WEBKIT2_H_INSIDE__ - -#include <webkit2/WebKitBackForwardList.h> -#include <webkit2/WebKitBackForwardListItem.h> -#include <webkit2/WebKitContextMenu.h> -#include <webkit2/WebKitContextMenuActions.h> -#include <webkit2/WebKitContextMenuItem.h> -#include <webkit2/WebKitCookieManager.h> -#include <webkit2/WebKitDefines.h> -#include <webkit2/WebKitDownload.h> -#include <webkit2/WebKitEditingCommands.h> -#include <webkit2/WebKitEnumTypes.h> -#include <webkit2/WebKitError.h> -#include <webkit2/WebKitFaviconDatabase.h> -#include <webkit2/WebKitFileChooserRequest.h> -#include <webkit2/WebKitFindController.h> -#include <webkit2/WebKitFormSubmissionRequest.h> -#include <webkit2/WebKitGeolocationPermissionRequest.h> -#include <webkit2/WebKitHitTestResult.h> -#include <webkit2/WebKitJavascriptResult.h> -#include <webkit2/WebKitMimeInfo.h> -#include <webkit2/WebKitNavigationPolicyDecision.h> -#include <webkit2/WebKitPermissionRequest.h> -#include <webkit2/WebKitPlugin.h> -#include <webkit2/WebKitPrintOperation.h> -#include <webkit2/WebKitResponsePolicyDecision.h> -#include <webkit2/WebKitScriptDialog.h> -#include <webkit2/WebKitSecurityManager.h> -#include <webkit2/WebKitSettings.h> -#include <webkit2/WebKitURIRequest.h> -#include <webkit2/WebKitURIResponse.h> -#include <webkit2/WebKitURISchemeRequest.h> -#include <webkit2/WebKitVersion.h> -#include <webkit2/WebKitWebContext.h> -#include <webkit2/WebKitWebInspector.h> -#include <webkit2/WebKitWebResource.h> -#include <webkit2/WebKitWebView.h> -#include <webkit2/WebKitWebViewBase.h> -#include <webkit2/WebKitWebViewGroup.h> -#include <webkit2/WebKitWindowProperties.h> - -#undef __WEBKIT2_H_INSIDE__ - -#endif /* __WEBKIT2_H__ */ diff --git a/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list b/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list deleted file mode 100644 index 420766ea7..000000000 --- a/Source/WebKit2/UIProcess/API/gtk/webkit2marshal.list +++ /dev/null @@ -1,15 +0,0 @@ -BOOLEAN:BOXED -BOOLEAN:ENUM,STRING,POINTER -BOOLEAN:OBJECT -BOOLEAN:OBJECT,BOXED,OBJECT -BOOLEAN:OBJECT,ENUM -BOOLEAN:OBJECT,OBJECT -BOOLEAN:STRING -BOOLEAN:VOID -OBJECT:VOID -VOID:OBJECT,UINT -VOID:OBJECT,OBJECT -VOID:OBJECT,POINTER -VOID:STRING,STRING -VOID:UINT64 - diff --git a/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.h b/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.h deleted file mode 100644 index cbe34a1a9..000000000 --- a/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.h +++ /dev/null @@ -1,77 +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 FindIndicatorWindow_h -#define FindIndicatorWindow_h - -#import "WebKitSystemInterface.h" -#import <WebCore/RunLoop.h> -#import <wtf/Noncopyable.h> -#import <wtf/PassOwnPtr.h> -#import <wtf/RefPtr.h> -#import <wtf/RetainPtr.h> - -@class WKFindIndicatorWindowAnimation; -@class WKView; - -namespace WebKit { - -class FindIndicator; - -class FindIndicatorWindow { - WTF_MAKE_NONCOPYABLE(FindIndicatorWindow); - -public: - static PassOwnPtr<FindIndicatorWindow> create(WKView *); - ~FindIndicatorWindow(); - - void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate); - -private: - explicit FindIndicatorWindow(WKView *); - void closeWindow(); - - void startFadeOutTimerFired(); - - void fadeOutAnimationCallback(double); - void fadeOutAnimationDidEnd(); - - void bounceAnimationCallback(double); - void bounceAnimationDidEnd(); - - WKView* m_wkView; - RefPtr<FindIndicator> m_findIndicator; - RetainPtr<NSWindow> m_findIndicatorWindow; - - WKWindowBounceAnimationContextRef m_bounceAnimationContext; - RetainPtr<WKFindIndicatorWindowAnimation> m_bounceAnimation; - - WebCore::RunLoop::Timer<FindIndicatorWindow> m_startFadeOutTimer; - RetainPtr<WKFindIndicatorWindowAnimation> m_fadeOutAnimation; -}; - -} // namespace WebKit - -#endif // FindIndicatorWindow_h diff --git a/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm b/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm deleted file mode 100644 index 19d696670..000000000 --- a/Source/WebKit2/UIProcess/API/mac/FindIndicatorWindow.mm +++ /dev/null @@ -1,249 +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. - */ - -#import "config.h" -#import "FindIndicatorWindow.h" - -#import "FindIndicator.h" -#import "WKView.h" -#import <WebCore/GraphicsContext.h> - -static const double bounceAnimationDuration = 0.12; -static const double timeBeforeFadeStarts = bounceAnimationDuration + 0.2; -static const double fadeOutAnimationDuration = 0.3; - -using namespace WebCore; - -@interface WKFindIndicatorView : NSView { - RefPtr<WebKit::FindIndicator> _findIndicator; -} - -- (id)_initWithFindIndicator:(PassRefPtr<WebKit::FindIndicator>)findIndicator; -@end - -@implementation WKFindIndicatorView - -- (id)_initWithFindIndicator:(PassRefPtr<WebKit::FindIndicator>)findIndicator -{ - if ((self = [super initWithFrame:NSZeroRect])) - _findIndicator = findIndicator; - - return self; -} - -- (void)drawRect:(NSRect)rect -{ - GraphicsContext graphicsContext(static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort])); - - _findIndicator->draw(graphicsContext, enclosingIntRect(rect)); -} - -- (BOOL)isFlipped -{ - return YES; -} - -@end - -@interface WKFindIndicatorWindowAnimation : NSAnimation<NSAnimationDelegate> { - WebKit::FindIndicatorWindow* _findIndicatorWindow; - void (WebKit::FindIndicatorWindow::*_animationProgressCallback)(double progress); - void (WebKit::FindIndicatorWindow::*_animationDidEndCallback)(); -} - -- (id)_initWithFindIndicatorWindow:(WebKit::FindIndicatorWindow *)findIndicatorWindow - animationDuration:(CFTimeInterval)duration - animationProgressCallback:(void (WebKit::FindIndicatorWindow::*)(double progress))animationProgressCallback - animationDidEndCallback:(void (WebKit::FindIndicatorWindow::*)())animationDidEndCallback; -@end - -@implementation WKFindIndicatorWindowAnimation - -- (id)_initWithFindIndicatorWindow:(WebKit::FindIndicatorWindow *)findIndicatorWindow - animationDuration:(CFTimeInterval)animationDuration - animationProgressCallback:(void (WebKit::FindIndicatorWindow::*)(double progress))animationProgressCallback - animationDidEndCallback:(void (WebKit::FindIndicatorWindow::*)())animationDidEndCallback -{ - if ((self = [super initWithDuration:animationDuration animationCurve:NSAnimationEaseInOut])) { - _findIndicatorWindow = findIndicatorWindow; - _animationProgressCallback = animationProgressCallback; - _animationDidEndCallback = animationDidEndCallback; - [self setDelegate:self]; - [self setAnimationBlockingMode:NSAnimationNonblocking]; - } - return self; -} - -- (void)setCurrentProgress:(NSAnimationProgress)progress -{ - (_findIndicatorWindow->*_animationProgressCallback)(progress); -} - -- (void)animationDidEnd:(NSAnimation *)animation -{ - ASSERT(animation == self); - - (_findIndicatorWindow->*_animationDidEndCallback)(); -} - -@end - -namespace WebKit { - -PassOwnPtr<FindIndicatorWindow> FindIndicatorWindow::create(WKView *wkView) -{ - return adoptPtr(new FindIndicatorWindow(wkView)); -} - -FindIndicatorWindow::FindIndicatorWindow(WKView *wkView) - : m_wkView(wkView) - , m_bounceAnimationContext(0) - , m_startFadeOutTimer(RunLoop::main(), this, &FindIndicatorWindow::startFadeOutTimerFired) -{ -} - -FindIndicatorWindow::~FindIndicatorWindow() -{ - closeWindow(); -} - -void FindIndicatorWindow::setFindIndicator(PassRefPtr<FindIndicator> findIndicator, bool fadeOut, bool animate) -{ - if (m_findIndicator == findIndicator) - return; - - m_findIndicator = findIndicator; - - // Get rid of the old window. - closeWindow(); - - if (!m_findIndicator) - return; - - NSRect contentRect = m_findIndicator->frameRect(); - NSRect windowFrameRect = NSIntegralRect([m_wkView convertRect:contentRect toView:nil]); - windowFrameRect.origin = [[m_wkView window] convertBaseToScreen:windowFrameRect.origin]; - - NSRect windowContentRect = [NSWindow contentRectForFrameRect:windowFrameRect styleMask:NSBorderlessWindowMask]; - - m_findIndicatorWindow = adoptNS([[NSWindow alloc] initWithContentRect:windowContentRect - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - - [m_findIndicatorWindow.get() setBackgroundColor:[NSColor clearColor]]; - [m_findIndicatorWindow.get() setOpaque:NO]; - [m_findIndicatorWindow.get() setIgnoresMouseEvents:YES]; - - RetainPtr<WKFindIndicatorView> findIndicatorView = adoptNS([[WKFindIndicatorView alloc] _initWithFindIndicator:m_findIndicator]); - [m_findIndicatorWindow.get() setContentView:findIndicatorView.get()]; - - [[m_wkView window] addChildWindow:m_findIndicatorWindow.get() ordered:NSWindowAbove]; - [m_findIndicatorWindow.get() setReleasedWhenClosed:NO]; - - if (animate) { - // Start the bounce animation. - m_bounceAnimationContext = WKWindowBounceAnimationContextCreate(m_findIndicatorWindow.get()); - m_bounceAnimation = adoptNS([[WKFindIndicatorWindowAnimation alloc] _initWithFindIndicatorWindow:this - animationDuration:bounceAnimationDuration - animationProgressCallback:&FindIndicatorWindow::bounceAnimationCallback - animationDidEndCallback:&FindIndicatorWindow::bounceAnimationDidEnd]); - [m_bounceAnimation.get() startAnimation]; - } - - if (fadeOut) - m_startFadeOutTimer.startOneShot(timeBeforeFadeStarts); -} - -void FindIndicatorWindow::closeWindow() -{ - if (!m_findIndicatorWindow) - return; - - m_startFadeOutTimer.stop(); - - if (m_fadeOutAnimation) { - [m_fadeOutAnimation.get() stopAnimation]; - m_fadeOutAnimation = nullptr; - } - - if (m_bounceAnimation) { - [m_bounceAnimation.get() stopAnimation]; - m_bounceAnimation = nullptr; - } - - if (m_bounceAnimationContext) - WKWindowBounceAnimationContextDestroy(m_bounceAnimationContext); - - [[m_findIndicatorWindow.get() parentWindow] removeChildWindow:m_findIndicatorWindow.get()]; - [m_findIndicatorWindow.get() close]; - m_findIndicatorWindow = nullptr; -} - -void FindIndicatorWindow::startFadeOutTimerFired() -{ - ASSERT(!m_fadeOutAnimation); - - m_fadeOutAnimation = adoptNS([[WKFindIndicatorWindowAnimation alloc] _initWithFindIndicatorWindow:this - animationDuration:fadeOutAnimationDuration - animationProgressCallback:&FindIndicatorWindow::fadeOutAnimationCallback - animationDidEndCallback:&FindIndicatorWindow::fadeOutAnimationDidEnd]); - [m_fadeOutAnimation.get() startAnimation]; -} - -void FindIndicatorWindow::fadeOutAnimationCallback(double progress) -{ - ASSERT(m_fadeOutAnimation); - - [m_findIndicatorWindow.get() setAlphaValue:1.0 - progress]; -} - -void FindIndicatorWindow::fadeOutAnimationDidEnd() -{ - ASSERT(m_fadeOutAnimation); - ASSERT(m_findIndicatorWindow); - - closeWindow(); -} - -void FindIndicatorWindow::bounceAnimationCallback(double progress) -{ - ASSERT(m_bounceAnimation); - ASSERT(m_bounceAnimationContext); - - WKWindowBounceAnimationSetAnimationProgress(m_bounceAnimationContext, progress); -} - -void FindIndicatorWindow::bounceAnimationDidEnd() -{ - ASSERT(m_bounceAnimation); - ASSERT(m_bounceAnimationContext); - ASSERT(m_findIndicatorWindow); - - WKWindowBounceAnimationContextDestroy(m_bounceAnimationContext); - m_bounceAnimationContext = 0; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/mac/PDFViewController.h b/Source/WebKit2/UIProcess/API/mac/PDFViewController.h deleted file mode 100644 index 265d7d692..000000000 --- a/Source/WebKit2/UIProcess/API/mac/PDFViewController.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PDFViewController_h -#define PDFViewController_h - -#include "WebFindOptions.h" -#include <wtf/Forward.h> -#include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/RetainPtr.h> -#include <wtf/text/WTFString.h> - -@class PDFView; -@class WKView; -@class WKPDFView; - -namespace CoreIPC { - class DataReference; -} - -namespace WebKit { - -class WebPageProxy; - -class PDFViewController { - WTF_MAKE_NONCOPYABLE(PDFViewController); - -public: - static PassOwnPtr<PDFViewController> create(WKView *); - ~PDFViewController(); - - WKView* wkView() const { return m_wkView; } - WebPageProxy* page() const; - NSView* pdfView() const; - - void setPDFDocumentData(const String& mimeType, const String& suggestedFilename, const CoreIPC::DataReference&); - - double zoomFactor() const; - void setZoomFactor(double); - - static Class pdfPreviewViewClass(); - - bool forwardScrollWheelEvent(NSEvent *); - - NSPrintOperation *makePrintOperation(NSPrintInfo *); - void openPDFInFinder(); - void savePDFToDownloadsFolder(); - void linkClicked(const String& url); - void print(); - - void findString(const String&, FindOptions, unsigned maxMatchCount); - void countStringMatches(const String&, FindOptions, unsigned maxMatchCount); - -private: - explicit PDFViewController(WKView *wkView); - - static Class pdfDocumentClass(); - static NSBundle* pdfKitBundle(); - - WKView* m_wkView; - - RetainPtr<WKPDFView> m_wkPDFView; - PDFView* m_pdfView; - - RetainPtr<NSString> m_suggestedFilename; - RetainPtr<CFDataRef> m_pdfData; - - String m_temporaryPDFUUID; -}; - -} // namespace WebKit - -#endif // PDFViewController_h diff --git a/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm b/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm deleted file mode 100644 index 8436c5dc8..000000000 --- a/Source/WebKit2/UIProcess/API/mac/PDFViewController.mm +++ /dev/null @@ -1,678 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "PDFViewController.h" - -#import "DataReference.h" -#import "WKAPICast.h" -#import "WKViewPrivate.h" -#import "WebData.h" -#import "WebEventFactory.h" -#import "WebPageGroup.h" -#import "WebPageProxy.h" -#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> - -// Redeclarations of PDFKit notifications. We can't use the API since we use a weak link to the framework. -#define _webkit_PDFViewDisplayModeChangedNotification @"PDFViewDisplayModeChanged" -#define _webkit_PDFViewScaleChangedNotification @"PDFViewScaleChanged" -#define _webkit_PDFViewPageChangedNotification @"PDFViewChangedPage" - -using namespace WebCore; -using namespace WebKit; - -@class PDFDocument; -@class PDFView; - -@interface PDFDocument (PDFDocumentDetails) -- (NSPrintOperation *)getPrintOperationForPrintInfo:(NSPrintInfo *)printInfo autoRotate:(BOOL)doRotate; -@end - -extern "C" NSString *_NSPathForSystemFramework(NSString *framework); - -// MARK: C UTILITY FUNCTIONS - -static void _applicationInfoForMIMEType(NSString *type, NSString **name, NSImage **image) -{ - ASSERT(name); - ASSERT(image); - - CFURLRef appURL = 0; - - OSStatus error = LSCopyApplicationForMIMEType((CFStringRef)type, kLSRolesAll, &appURL); - if (error != noErr) - return; - - NSString *appPath = [(NSURL *)appURL path]; - if (appURL) - CFRelease(appURL); - - *image = [[NSWorkspace sharedWorkspace] iconForFile:appPath]; - [*image setSize:NSMakeSize(16, 16)]; - - *name = [[NSFileManager defaultManager] displayNameAtPath:appPath]; -} - -// FIXME 4182876: We can eliminate this function in favor if -isEqual: if [PDFSelection isEqual:] is overridden -// to compare contents. -static BOOL _PDFSelectionsAreEqual(PDFSelection *selectionA, PDFSelection *selectionB) -{ - NSArray *aPages = [selectionA pages]; - NSArray *bPages = [selectionB pages]; - - if (![aPages isEqual:bPages]) - return NO; - - NSUInteger count = [aPages count]; - for (NSUInteger i = 0; i < count; ++i) { - NSRect aBounds = [selectionA boundsForPage:[aPages objectAtIndex:i]]; - NSRect bBounds = [selectionB boundsForPage:[bPages objectAtIndex:i]]; - if (!NSEqualRects(aBounds, bBounds)) - return NO; - } - - return YES; -} - -@interface WKPDFView : NSView -{ - PDFViewController* _pdfViewController; - - RetainPtr<NSView> _pdfPreviewView; - PDFView *_pdfView; - BOOL _ignoreScaleAndDisplayModeAndPageNotifications; - BOOL _willUpdatePreferencesSoon; -} - -- (id)initWithFrame:(NSRect)frame PDFViewController:(PDFViewController*)pdfViewController; -- (void)invalidate; -- (PDFView *)pdfView; -- (void)setDocument:(PDFDocument *)pdfDocument; - -- (BOOL)forwardScrollWheelEvent:(NSEvent *)wheelEvent; -- (void)_applyPDFPreferences; -- (PDFSelection *)_nextMatchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag fromSelection:(PDFSelection *)initialSelection startInSelection:(BOOL)startInSelection; -@end - -@implementation WKPDFView - -- (id)initWithFrame:(NSRect)frame PDFViewController:(PDFViewController*)pdfViewController -{ - if ((self = [super initWithFrame:frame])) { - _pdfViewController = pdfViewController; - - [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; - - Class previewViewClass = PDFViewController::pdfPreviewViewClass(); - ASSERT(previewViewClass); - - _pdfPreviewView = adoptNS([[previewViewClass alloc] initWithFrame:frame]); - [_pdfPreviewView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; - [self addSubview:_pdfPreviewView.get()]; - - _pdfView = [_pdfPreviewView.get() performSelector:@selector(pdfView)]; - [_pdfView setDelegate:self]; - } - - return self; -} - -- (void)invalidate -{ - _pdfViewController = 0; -} - -- (PDFView *)pdfView -{ - return _pdfView; -} - -- (void)setDocument:(PDFDocument *)pdfDocument -{ - _ignoreScaleAndDisplayModeAndPageNotifications = YES; - [_pdfView setDocument:pdfDocument]; - [self _applyPDFPreferences]; - _ignoreScaleAndDisplayModeAndPageNotifications = NO; -} - -- (void)_applyPDFPreferences -{ - if (!_pdfViewController) - return; - - WebPreferences *preferences = _pdfViewController->page()->pageGroup()->preferences(); - - CGFloat scaleFactor = preferences->pdfScaleFactor(); - if (!scaleFactor) - [_pdfView setAutoScales:YES]; - else { - [_pdfView setAutoScales:NO]; - [_pdfView setScaleFactor:scaleFactor]; - } - [_pdfView setDisplayMode:preferences->pdfDisplayMode()]; -} - -- (void)_updatePreferences:(id)ignored -{ - _willUpdatePreferencesSoon = NO; - - if (!_pdfViewController) - return; - - WebPreferences* preferences = _pdfViewController->page()->pageGroup()->preferences(); - - CGFloat scaleFactor = [_pdfView autoScales] ? 0 : [_pdfView scaleFactor]; - preferences->setPDFScaleFactor(scaleFactor); - preferences->setPDFDisplayMode([_pdfView displayMode]); -} - -- (void)_updatePreferencesSoon -{ - if (_willUpdatePreferencesSoon) - return; - - [self performSelector:@selector(_updatePreferences:) withObject:nil afterDelay:0]; - _willUpdatePreferencesSoon = YES; -} - -- (void)_scaleOrDisplayModeOrPageChanged:(NSNotification *)notification -{ - ASSERT_ARG(notification, [notification object] == _pdfView); - if (!_ignoreScaleAndDisplayModeAndPageNotifications) - [self _updatePreferencesSoon]; -} - -- (void)_openWithFinder:(id)sender -{ - _pdfViewController->openPDFInFinder(); -} - -- (PDFSelection *)_nextMatchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag fromSelection:(PDFSelection *)initialSelection startInSelection:(BOOL)startInSelection -{ - if (![string length]) - return nil; - - int options = 0; - if (!forward) - options |= NSBackwardsSearch; - - if (!caseFlag) - options |= NSCaseInsensitiveSearch; - - PDFDocument *document = [_pdfView document]; - - PDFSelection *selectionForInitialSearch = [initialSelection copy]; - if (startInSelection) { - // Initially we want to include the selected text in the search. So we must modify the starting search - // selection to fit PDFDocument's search requirements: selection must have a length >= 1, begin before - // the current selection (if searching forwards) or after (if searching backwards). - int initialSelectionLength = [[initialSelection string] length]; - if (forward) { - [selectionForInitialSearch extendSelectionAtStart:1]; - [selectionForInitialSearch extendSelectionAtEnd:-initialSelectionLength]; - } else { - [selectionForInitialSearch extendSelectionAtEnd:1]; - [selectionForInitialSearch extendSelectionAtStart:-initialSelectionLength]; - } - } - PDFSelection *foundSelection = [document findString:string fromSelection:selectionForInitialSearch withOptions:options]; - [selectionForInitialSearch release]; - - // If we first searched in the selection, and we found the selection, search again from just past the selection - if (startInSelection && _PDFSelectionsAreEqual(foundSelection, initialSelection)) - foundSelection = [document findString:string fromSelection:initialSelection withOptions:options]; - - if (!foundSelection && wrapFlag) - foundSelection = [document findString:string fromSelection:nil withOptions:options]; - - return foundSelection; -} - -- (NSUInteger)_countMatches:(NSString *)string caseSensitive:(BOOL)caseFlag -{ - if (![string length]) - return 0; - - int options = caseFlag ? 0 : NSCaseInsensitiveSearch; - - return [[[_pdfView document] findString:string withOptions:options] count]; -} - -// MARK: NSView overrides - -- (void)viewDidMoveToWindow -{ - if (![self window]) - return; - - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter addObserver:self selector:@selector(_scaleOrDisplayModeOrPageChanged:) name:_webkit_PDFViewScaleChangedNotification object:_pdfView]; - [notificationCenter addObserver:self selector:@selector(_scaleOrDisplayModeOrPageChanged:) name:_webkit_PDFViewDisplayModeChangedNotification object:_pdfView]; - [notificationCenter addObserver:self selector:@selector(_scaleOrDisplayModeOrPageChanged:) name:_webkit_PDFViewPageChangedNotification object:_pdfView]; -} - -- (void)viewWillMoveToWindow:(NSWindow *)newWindow -{ - if (![self window]) - return; - - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter removeObserver:self name:_webkit_PDFViewScaleChangedNotification object:_pdfView]; - [notificationCenter removeObserver:self name:_webkit_PDFViewDisplayModeChangedNotification object:_pdfView]; - [notificationCenter removeObserver:self name:_webkit_PDFViewPageChangedNotification object:_pdfView]; -} - -- (NSView *)hitTest:(NSPoint)point -{ - // Override hitTest so we can override menuForEvent. - NSEvent *event = [NSApp currentEvent]; - NSEventType type = [event type]; - if (type == NSRightMouseDown || (type == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask))) - return self; - - return [super hitTest:point]; -} - -static void insertOpenWithDefaultPDFMenuItem(NSMenu *menu, NSUInteger index) -{ - // Add in an "Open with <default PDF viewer>" item - NSString *appName = nil; - NSImage *appIcon = nil; - - _applicationInfoForMIMEType(@"application/pdf", &appName, &appIcon); - if (!appName) - appName = WEB_UI_STRING("Finder", "Default application name for Open With context menu"); - - // To match the PDFKit style, we'll add Open with Preview even when there's no document yet to view, and - // disable it using validateUserInterfaceItem. - NSString *title = [NSString stringWithFormat:WEB_UI_STRING("Open with %@", "context menu item for PDF"), appName]; - - NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title action:@selector(_openWithFinder:) keyEquivalent:@""]; - if (appIcon) - [item setImage:appIcon]; - [menu insertItem:item atIndex:index]; - [item release]; -} - -- (NSMenu *)menuForEvent:(NSEvent *)theEvent -{ - NSMenu *menu = [[NSMenu alloc] initWithTitle:@""]; - - bool insertedOpenWithItem = false; - - NSEnumerator *menuItemEnumerator = [[[_pdfView menuForEvent:theEvent] itemArray] objectEnumerator]; - while (NSMenuItem *item = [menuItemEnumerator nextObject]) { - NSMenuItem *itemCopy = [item copy]; - [menu addItem:itemCopy]; - [itemCopy release]; - - if (insertedOpenWithItem) - continue; - - // If a "Copy" item is present, place the "Open With" item just after it, with an intervening separator. - if ([item action] != @selector(copy:)) - continue; - - [menu addItem:[NSMenuItem separatorItem]]; - insertOpenWithDefaultPDFMenuItem(menu, [menu numberOfItems]); - insertedOpenWithItem = true; - } - - if (!insertedOpenWithItem) { - // No "Copy" item was found; place the "Open With" item at the top of the menu, with a trailing separator. - insertOpenWithDefaultPDFMenuItem(menu, 0); - [menu insertItem:[NSMenuItem separatorItem] atIndex:1]; - } - - return [menu autorelease]; -} - -// MARK: NSUserInterfaceValidations PROTOCOL IMPLEMENTATION - -- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item -{ - SEL action = [item action]; - if (action == @selector(_openWithFinder:)) - return [_pdfView document] != nil; - return YES; -} - -// MARK: PDFView delegate methods - -- (void)PDFViewWillClickOnLink:(PDFView *)sender withURL:(NSURL *)URL -{ - _pdfViewController->linkClicked([URL absoluteString]); -} - -- (void)PDFViewOpenPDFInNativeApplication:(PDFView *)sender -{ - _pdfViewController->openPDFInFinder(); -} - -- (void)PDFViewSavePDFToDownloadFolder:(PDFView *)sender -{ - _pdfViewController->savePDFToDownloadsFolder(); -} - -- (void)PDFViewPerformPrint:(PDFView *)sender -{ - _pdfViewController->print(); -} - -- (BOOL)forwardScrollWheelEvent:(NSEvent *)wheelEvent -{ - return _pdfViewController->forwardScrollWheelEvent(wheelEvent); -} - -@end - -namespace WebKit { - -PassOwnPtr<PDFViewController> PDFViewController::create(WKView *wkView) -{ - return adoptPtr(new PDFViewController(wkView)); -} - -PDFViewController::PDFViewController(WKView *wkView) - : m_wkView(wkView) - , m_wkPDFView(adoptNS([[WKPDFView alloc] initWithFrame:[m_wkView bounds] PDFViewController:this])) - , m_pdfView([m_wkPDFView.get() pdfView]) -{ - [m_wkView addSubview:m_wkPDFView.get()]; -} - -PDFViewController::~PDFViewController() -{ - [m_wkPDFView.get() removeFromSuperview]; - [m_wkPDFView.get() invalidate]; - m_wkPDFView = nullptr; -} - -WebPageProxy* PDFViewController::page() const -{ - return toImpl([m_wkView pageRef]); -} - -NSView* PDFViewController::pdfView() const -{ - return m_wkPDFView.get(); -} - -static RetainPtr<CFDataRef> convertPostScriptDataSourceToPDF(const CoreIPC::DataReference& dataReference) -{ - // Convert PostScript to PDF using Quartz 2D API - // 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)); - ASSERT(converter); - - 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())); - ASSERT(provider); - - RetainPtr<CFMutableDataRef> result = adoptCF(CFDataCreateMutable(kCFAllocatorDefault, 0)); - ASSERT(result); - - RetainPtr<CGDataConsumerRef> consumer = adoptCF(CGDataConsumerCreateWithCFData(result.get())); - ASSERT(consumer); - - CGPSConverterConvert(converter.get(), provider.get(), consumer.get(), 0); - - if (!result) - return 0; - - return result; -} - -void PDFViewController::setPDFDocumentData(const String& mimeType, const String& suggestedFilename, const CoreIPC::DataReference& dataReference) -{ - if (equalIgnoringCase(mimeType, "application/postscript")) { - m_pdfData = convertPostScriptDataSourceToPDF(dataReference); - if (!m_pdfData) - return; - m_suggestedFilename = String(suggestedFilename + ".pdf"); - } else { - // Make sure to copy the data. - m_pdfData = adoptCF(CFDataCreate(0, dataReference.data(), dataReference.size())); - m_suggestedFilename = suggestedFilename; - } - - RetainPtr<PDFDocument> pdfDocument = adoptNS([[pdfDocumentClass() alloc] initWithData:(NSData *)m_pdfData.get()]); - [m_wkPDFView.get() setDocument:pdfDocument.get()]; -} - -double PDFViewController::zoomFactor() const -{ - return [m_pdfView scaleFactor]; -} - -void PDFViewController::setZoomFactor(double zoomFactor) -{ - [m_pdfView setScaleFactor:zoomFactor]; -} - -Class PDFViewController::pdfDocumentClass() -{ - static Class pdfDocumentClass = [pdfKitBundle() classNamed:@"PDFDocument"]; - - return pdfDocumentClass; -} - -Class PDFViewController::pdfPreviewViewClass() -{ - static Class pdfPreviewViewClass = [pdfKitBundle() classNamed:@"PDFPreviewView"]; - - return pdfPreviewViewClass; -} - -bool PDFViewController::forwardScrollWheelEvent(NSEvent *wheelEvent) -{ - CGFloat deltaX = [wheelEvent deltaX]; - if ((deltaX > 0 && !page()->canGoBack()) || (deltaX < 0 && !page()->canGoForward())) - return false; - - [m_wkView scrollWheel:wheelEvent]; - return true; -} - -static IMP oldPDFViewScrollView_scrollWheel; - -static WKPDFView *findEnclosingWKPDFView(NSView *view) -{ - for (NSView *superview = [view superview]; superview; superview = [superview superview]) { - if ([superview isKindOfClass:[WKPDFView class]]) - return static_cast<WKPDFView *>(superview); - } - - return nil; -} - -static void PDFViewScrollView_scrollWheel(NSScrollView* self, SEL _cmd, NSEvent *wheelEvent) -{ - CGFloat deltaX = [wheelEvent deltaX]; - CGFloat deltaY = [wheelEvent deltaY]; - - NSSize contentsSize = [[self documentView] bounds].size; - NSRect visibleRect = [self documentVisibleRect]; - - // We only want to forward the wheel events if the horizontal delta is non-zero, - // and only if we're pinned to either the left or right side. - // We also never want to forward momentum scroll events. - if ([wheelEvent momentumPhase] == NSEventPhaseNone && deltaX && fabsf(deltaY) < fabsf(deltaX) - && ((deltaX > 0 && visibleRect.origin.x <= 0) || (deltaX < 0 && contentsSize.width <= NSMaxX(visibleRect)))) { - - if (WKPDFView *pdfView = findEnclosingWKPDFView(self)) { - if ([pdfView forwardScrollWheelEvent:wheelEvent]) - return; - } - } - - wtfCallIMP<void>(oldPDFViewScrollView_scrollWheel, self, _cmd, wheelEvent); -} - -NSBundle* PDFViewController::pdfKitBundle() -{ - static NSBundle *pdfKitBundle; - if (pdfKitBundle) - return pdfKitBundle; - - NSString *pdfKitPath = [_NSPathForSystemFramework(@"Quartz.framework") stringByAppendingString:@"/Frameworks/PDFKit.framework"]; - if (!pdfKitPath) { - LOG_ERROR("Couldn't find PDFKit.framework"); - return nil; - } - - pdfKitBundle = [NSBundle bundleWithPath:pdfKitPath]; - if (![pdfKitBundle load]) - LOG_ERROR("Couldn't load PDFKit.framework"); - - if (Class pdfViewScrollViewClass = [pdfKitBundle classNamed:@"PDFViewScrollView"]) { - if (Method scrollWheel = class_getInstanceMethod(pdfViewScrollViewClass, @selector(scrollWheel:))) - oldPDFViewScrollView_scrollWheel = method_setImplementation(scrollWheel, reinterpret_cast<IMP>(PDFViewScrollView_scrollWheel)); - } - - return pdfKitBundle; -} - -NSPrintOperation *PDFViewController::makePrintOperation(NSPrintInfo *printInfo) -{ - return [[m_pdfView document] getPrintOperationForPrintInfo:printInfo autoRotate:YES]; -} - -void PDFViewController::openPDFInFinder() -{ - // We don't want to open the PDF until we have a document to write. (see 4892525). - if (![m_pdfView document]) { - NSBeep(); - return; - } - - 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; - } - - page()->openPDFFromTemporaryFolderWithNativeApplication(m_temporaryPDFUUID); -} - -static void releaseCFData(unsigned char*, const void* data) -{ - ASSERT(CFGetTypeID(data) == CFDataGetTypeID()); - - // Balanced by CFRetain in savePDFToDownloadsFolder. - CFRelease(data); -} - -void PDFViewController::savePDFToDownloadsFolder() -{ - // We don't want to write the file until we have a document to write. (see 5267607). - if (![m_pdfView document]) { - NSBeep(); - return; - } - - ASSERT(m_pdfData); - - // Balanced by CFRelease in releaseCFData. - CFRetain(m_pdfData.get()); - - RefPtr<WebData> data = WebData::createWithoutCopying(CFDataGetBytePtr(m_pdfData.get()), CFDataGetLength(m_pdfData.get()), releaseCFData, m_pdfData.get()); - - page()->saveDataToFileInDownloadsFolder(m_suggestedFilename.get(), page()->mainFrame()->mimeType(), page()->mainFrame()->url(), data.get()); -} - -void PDFViewController::linkClicked(const String& url) -{ - NSEvent* nsEvent = [NSApp currentEvent]; - WebMouseEvent event; - switch ([nsEvent type]) { - case NSLeftMouseUp: - case NSRightMouseUp: - case NSOtherMouseUp: - event = WebEventFactory::createWebMouseEvent(nsEvent, m_pdfView); - default: - // For non mouse-clicks or for keyboard events, pass an empty WebMouseEvent - // through. The event is only used by the WebFrameLoaderClient to determine - // the modifier keys and which mouse button is down. These queries will be - // valid with an empty event. - break; - } - - page()->linkClicked(url, event); -} - -void PDFViewController::print() -{ - page()->printMainFrame(); -} - -void PDFViewController::findString(const String& string, FindOptions options, unsigned maxMatchCount) -{ - BOOL forward = !(options & FindOptionsBackwards); - BOOL caseFlag = !(options & FindOptionsCaseInsensitive); - BOOL wrapFlag = options & FindOptionsWrapAround; - - PDFSelection *selection = [m_wkPDFView.get() _nextMatchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag fromSelection:[m_pdfView currentSelection] startInSelection:NO]; - if (!selection) { - page()->didFailToFindString(string); - return; - } - - NSUInteger matchCount; - if (!maxMatchCount) { - // If the max was zero, any result means we exceeded the max. We can skip computing the actual count. - matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount); - } else { - matchCount = [m_wkPDFView.get() _countMatches:string caseSensitive:caseFlag]; - if (matchCount > maxMatchCount) - matchCount = static_cast<unsigned>(kWKMoreThanMaximumMatchCount); - } - - [m_pdfView setCurrentSelection:selection]; - [m_pdfView scrollSelectionToVisible:nil]; - page()->didFindString(string, matchCount); -} - -void PDFViewController::countStringMatches(const String& string, FindOptions options, unsigned maxMatchCount) -{ - BOOL caseFlag = !(options & FindOptionsCaseInsensitive); - - NSUInteger matchCount = [m_wkPDFView.get() _countMatches:string caseSensitive:caseFlag]; - if (matchCount > maxMatchCount) - matchCount = maxMatchCount; - page()->didCountStringMatches(string, matchCount); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h deleted file mode 100644 index 5f747c0c5..000000000 --- a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PageClientImpl_h -#define PageClientImpl_h - -#include "CorrectionPanel.h" -#include "PageClient.h" -#include <wtf/RetainPtr.h> - -@class WKEditorUndoTargetObjC; -@class WKView; - -namespace WebCore { -class AlternativeTextUIController; -} - -namespace WebKit { -class FindIndicatorWindow; - -class PageClientImpl FINAL : public PageClient { -public: - static PassOwnPtr<PageClientImpl> create(WKView*); - virtual ~PageClientImpl(); - - void viewWillMoveToAnotherWindow(); - -private: - explicit PageClientImpl(WKView*); - - 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(); - virtual bool isViewWindowActive(); - virtual bool isViewFocused(); - virtual bool isViewVisible(); - virtual bool isViewInWindow(); - virtual LayerHostingMode viewLayerHostingMode() OVERRIDE; - virtual ColorSpaceData colorSpace() OVERRIDE; - virtual void setAcceleratedCompositingRootLayer(CALayer *) OVERRIDE; - - 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); - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); - - virtual void registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo); - virtual void clearAllEditCommands(); - virtual bool canUndoRedo(WebPageProxy::UndoOrRedo); - virtual void executeUndoRedo(WebPageProxy::UndoOrRedo); - virtual bool interpretKeyEvent(const NativeWebKeyboardEvent&, Vector<WebCore::KeypressCommand>&); - virtual bool executeSavedCommandBySelector(const String& selector); - 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 updateSecureInputState() OVERRIDE; - virtual void resetSecureInputState() OVERRIDE; - virtual void notifyInputContextAboutDiscardedComposition() OVERRIDE; - - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&); - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&); - virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&); - virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&); - -#if ENABLE(GESTURE_EVENTS) - virtual void doneWithGestureEvent(const WebGestureEvent&, bool wasEventHandled); -#endif - virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool wasEventHandled); - - virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*); - virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*); - -#if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&); -#endif - - void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate); - - virtual void enterAcceleratedCompositingMode(const LayerTreeContext&); - virtual void exitAcceleratedCompositingMode(); - virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); - - virtual void accessibilityWebProcessTokenReceived(const CoreIPC::DataReference&); - - virtual void pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus); - virtual void setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, PluginComplexTextInputState); - - virtual void makeFirstResponder(); - - virtual CGContextRef containingWindowGraphicsContext(); - - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); - - virtual void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&); - virtual void dismissDictionaryLookupPanel(); - - virtual void showCorrectionPanel(WebCore::AlternativeTextType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings); - virtual void dismissCorrectionPanel(WebCore::ReasonForDismissingAlternativeText); - virtual String dismissCorrectionPanelSoon(WebCore::ReasonForDismissingAlternativeText); - virtual void recordAutocorrectionResponse(WebCore::AutocorrectionResponseType, const String& replacedString, const String& replacementString); - - virtual void recommendedScrollbarStyleDidChange(int32_t newStyle); - - virtual WKView* wkView() const { return m_wkView; } - virtual void intrinsicContentSizeDidChange(const WebCore::IntSize& intrinsicContentSize) OVERRIDE; - -#if USE(DICTATION_ALTERNATIVES) - virtual uint64_t addDictationAlternatives(const RetainPtr<NSTextAlternatives>&); - virtual void removeDictationAlternatives(uint64_t dictationContext); - virtual void showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext); - virtual Vector<String> dictationAlternatives(uint64_t dictationContext); -#endif - - WKView* m_wkView; - RetainPtr<WKEditorUndoTargetObjC> m_undoTarget; -#if USE(AUTOCORRECTION_PANEL) - CorrectionPanel m_correctionPanel; -#endif -#if USE(DICTATION_ALTERNATIVES) - OwnPtr<WebCore::AlternativeTextUIController> m_alternativeTextUIController; -#endif -}; - -} // namespace WebKit - -#endif // PageClientImpl_h diff --git a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm b/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm deleted file mode 100644 index 3d93314e6..000000000 --- a/Source/WebKit2/UIProcess/API/mac/PageClientImpl.mm +++ /dev/null @@ -1,575 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "PageClientImpl.h" - -#if USE(DICTATION_ALTERNATIVES) -#import <AppKit/NSTextAlternatives.h> -#endif -#import "AttributedString.h" -#import "ColorSpaceData.h" -#import "DataReference.h" -#import "DictionaryPopupInfo.h" -#import "FindIndicator.h" -#import "NativeWebKeyboardEvent.h" -#import "WKAPICast.h" -#import "WKStringCF.h" -#import "WKViewInternal.h" -#import "StringUtilities.h" -#import "WebContextMenuProxyMac.h" -#import "WebEditCommandProxy.h" -#import "WebPopupMenuProxyMac.h" -#import <WebCore/AlternativeTextUIController.h> -#import <WebCore/BitmapImage.h> -#import <WebCore/Cursor.h> -#import <WebCore/FloatRect.h> -#import <WebCore/FoundationExtras.h> -#import <WebCore/GraphicsContext.h> -#import <WebCore/Image.h> -#import <WebCore/KeyboardEvent.h> -#import <WebCore/NotImplemented.h> -#import <WebCore/SharedBuffer.h> -#import <wtf/PassOwnPtr.h> -#import <wtf/text/CString.h> -#import <wtf/text/WTFString.h> -#import <WebKitSystemInterface.h> - -@interface NSApplication (WebNSApplicationDetails) -- (NSCursor *)_cursorRectCursor; -@end - -#if HAVE(LAYER_HOSTING_IN_WINDOW_SERVER) -@interface NSWindow (WebNSWindowDetails) -- (BOOL)_hostsLayersInWindowServer; -@end -#endif - -using namespace WebCore; -using namespace WebKit; - -@interface WKEditCommandObjC : NSObject -{ - RefPtr<WebEditCommandProxy> m_command; -} -- (id)initWithWebEditCommandProxy:(PassRefPtr<WebEditCommandProxy>)command; -- (WebEditCommandProxy*)command; -@end - -@interface WKEditorUndoTargetObjC : NSObject -- (void)undoEditing:(id)sender; -- (void)redoEditing:(id)sender; -@end - -@implementation WKEditCommandObjC - -- (id)initWithWebEditCommandProxy:(PassRefPtr<WebEditCommandProxy>)command -{ - self = [super init]; - if (!self) - return nil; - - m_command = command; - return self; -} - -- (WebEditCommandProxy*)command -{ - return m_command.get(); -} - -@end - -@implementation WKEditorUndoTargetObjC - -- (void)undoEditing:(id)sender -{ - ASSERT([sender isKindOfClass:[WKEditCommandObjC class]]); - [sender command]->unapply(); -} - -- (void)redoEditing:(id)sender -{ - ASSERT([sender isKindOfClass:[WKEditCommandObjC class]]); - [sender command]->reapply(); -} - -@end - -namespace WebKit { - -PassOwnPtr<PageClientImpl> PageClientImpl::create(WKView* wkView) -{ - return adoptPtr(new PageClientImpl(wkView)); -} - -PageClientImpl::PageClientImpl(WKView* wkView) - : m_wkView(wkView) - , m_undoTarget(adoptNS([[WKEditorUndoTargetObjC alloc] init])) -#if USE(DICTATION_ALTERNATIVES) - , m_alternativeTextUIController(adoptPtr(new AlternativeTextUIController)) -#endif -{ -} - -PageClientImpl::~PageClientImpl() -{ -} - -PassOwnPtr<DrawingAreaProxy> PageClientImpl::createDrawingAreaProxy() -{ - return [m_wkView _createDrawingAreaProxy]; -} - -void PageClientImpl::setViewNeedsDisplay(const WebCore::IntRect& rect) -{ - [m_wkView setNeedsDisplayInRect:rect]; -} - -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())); - - [m_wkView _cacheWindowBottomCornerRect]; - - [m_wkView translateRectsNeedingDisplayInRect:clippedScrollRect by:scrollOffset]; - [m_wkView scrollRect:clippedScrollRect by:scrollOffset]; -} - -IntSize PageClientImpl::viewSize() -{ - return IntSize([m_wkView bounds].size); -} - -bool PageClientImpl::isViewWindowActive() -{ - return [[m_wkView window] isKeyWindow] || [NSApp keyWindow] == [m_wkView window]; -} - -bool PageClientImpl::isViewFocused() -{ - return [m_wkView _isFocused]; -} - -void PageClientImpl::makeFirstResponder() -{ - [[m_wkView window] makeFirstResponder:m_wkView]; -} - -bool PageClientImpl::isViewVisible() -{ - if (![m_wkView window]) - return false; - - 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; -} - -bool PageClientImpl::isViewInWindow() -{ - return [m_wkView window]; -} - -void PageClientImpl::viewWillMoveToAnotherWindow() -{ - clearAllEditCommands(); -} - -LayerHostingMode PageClientImpl::viewLayerHostingMode() -{ -#if HAVE(LAYER_HOSTING_IN_WINDOW_SERVER) - if (![m_wkView window]) - return LayerHostingModeDefault; - - return [[m_wkView window] _hostsLayersInWindowServer] ? LayerHostingModeInWindowServer : LayerHostingModeDefault; -#else - return LayerHostingModeDefault; -#endif -} - -ColorSpaceData PageClientImpl::colorSpace() -{ - return [m_wkView _colorSpace]; -} - -void PageClientImpl::processDidCrash() -{ - [m_wkView _processDidCrash]; -} - -void PageClientImpl::pageClosed() -{ - [m_wkView _pageClosed]; -#if USE(DICTATION_ALTERNATIVES) - m_alternativeTextUIController->clear(); -#endif -} - -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)]; -} - -void PageClientImpl::setCursor(const WebCore::Cursor& cursor) -{ - if (![NSApp _cursorRectCursor]) - [m_wkView _setCursor:cursor.platformCursor()]; -} - -void PageClientImpl::setCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves) -{ - [NSCursor setHiddenUntilMouseMoves:hiddenUntilMouseMoves]; -} - -void PageClientImpl::didChangeViewportProperties(const WebCore::ViewportAttributes&) -{ -} - -void PageClientImpl::registerEditCommand(PassRefPtr<WebEditCommandProxy> prpCommand, WebPageProxy::UndoOrRedo undoOrRedo) -{ - RefPtr<WebEditCommandProxy> command = prpCommand; - - RetainPtr<WKEditCommandObjC> commandObjC = adoptNS([[WKEditCommandObjC alloc] initWithWebEditCommandProxy:command]); - String actionName = WebEditCommandProxy::nameForEditAction(command->editAction()); - - NSUndoManager *undoManager = [m_wkView undoManager]; - [undoManager registerUndoWithTarget:m_undoTarget.get() selector:((undoOrRedo == WebPageProxy::Undo) ? @selector(undoEditing:) : @selector(redoEditing:)) object:commandObjC.get()]; - if (!actionName.isEmpty()) - [undoManager setActionName:(NSString *)actionName]; -} - -void PageClientImpl::clearAllEditCommands() -{ - [[m_wkView undoManager] removeAllActionsWithTarget:m_undoTarget.get()]; -} - -bool PageClientImpl::canUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - return (undoOrRedo == WebPageProxy::Undo) ? [[m_wkView undoManager] canUndo] : [[m_wkView undoManager] canRedo]; -} - -void PageClientImpl::executeUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - return (undoOrRedo == WebPageProxy::Undo) ? [[m_wkView undoManager] undo] : [[m_wkView undoManager] redo]; -} - -bool PageClientImpl::interpretKeyEvent(const NativeWebKeyboardEvent& event, Vector<WebCore::KeypressCommand>& commands) -{ - return [m_wkView _interpretKeyEvent:event.nativeEvent() savingCommandsTo:commands]; -} - -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()]); - - [m_wkView _setDragImage:dragNSImage.get() at:clientPosition linkDrag:isLinkDrag]; -} - -void PageClientImpl::setPromisedData(const String& pasteboardName, PassRefPtr<SharedBuffer> imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleUrl, PassRefPtr<SharedBuffer> archiveBuffer) -{ - RefPtr<Image> image = BitmapImage::create(); - image->setData(imageBuffer.get(), true); - [m_wkView _setPromisedData:image.get() withFileName:filename withExtension:extension withTitle:title withURL:url withVisibleURL:visibleUrl withArchive:archiveBuffer.get() forPasteboard:pasteboardName]; -} - -void PageClientImpl::updateSecureInputState() -{ - [m_wkView _updateSecureInputState]; -} - -void PageClientImpl::resetSecureInputState() -{ - [m_wkView _resetSecureInputState]; -} - -void PageClientImpl::notifyInputContextAboutDiscardedComposition() -{ - [m_wkView _notifyInputContextAboutDiscardedComposition]; -} - -FloatRect PageClientImpl::convertToDeviceSpace(const FloatRect& rect) -{ - return [m_wkView _convertToDeviceSpace:rect]; -} - -FloatRect PageClientImpl::convertToUserSpace(const FloatRect& rect) -{ - return [m_wkView _convertToUserSpace:rect]; -} - -IntPoint PageClientImpl::screenToWindow(const IntPoint& point) -{ - NSPoint windowCoord = [[m_wkView window] convertScreenToBase:point]; - return IntPoint([m_wkView convertPoint:windowCoord fromView:nil]); -} - -IntRect PageClientImpl::windowToScreen(const IntRect& rect) -{ - NSRect tempRect = rect; - tempRect = [m_wkView convertRect:tempRect toView:nil]; - tempRect.origin = [[m_wkView window] convertBaseToScreen:tempRect.origin]; - return enclosingIntRect(tempRect); -} - -#if ENABLE(GESTURE_EVENTS) -void PageClientImpl::doneWithGestureEvent(const WebGestureEvent&, bool wasEventHandled) -{ - notImplemented(); -} -#endif - -void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool eventWasHandled) -{ - [m_wkView _doneWithKeyEvent:event.nativeEvent() eventWasHandled:eventWasHandled]; -} - -PassRefPtr<WebPopupMenuProxy> PageClientImpl::createPopupMenuProxy(WebPageProxy* page) -{ - return WebPopupMenuProxyMac::create(m_wkView, page); -} - -PassRefPtr<WebContextMenuProxy> PageClientImpl::createContextMenuProxy(WebPageProxy* page) -{ - return WebContextMenuProxyMac::create(m_wkView, page); -} - -#if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorPicker> PageClientImpl::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) -{ - notImplemented(); - return 0; -} -#endif - -void PageClientImpl::setFindIndicator(PassRefPtr<FindIndicator> findIndicator, bool fadeOut, bool animate) -{ - [m_wkView _setFindIndicator:findIndicator fadeOut:fadeOut animate:animate]; -} - -void PageClientImpl::accessibilityWebProcessTokenReceived(const CoreIPC::DataReference& data) -{ - NSData* remoteToken = [NSData dataWithBytes:data.data() length:data.size()]; - [m_wkView _setAccessibilityWebProcessToken:remoteToken]; -} - -void PageClientImpl::enterAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) -{ - ASSERT(!layerTreeContext.isEmpty()); - - CALayer *renderLayer = WKMakeRenderLayer(layerTreeContext.contextID); - [m_wkView _setAcceleratedCompositingModeRootLayer:renderLayer]; -} - -void PageClientImpl::exitAcceleratedCompositingMode() -{ - [m_wkView _setAcceleratedCompositingModeRootLayer:nil]; -} - -void PageClientImpl::updateAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) -{ - ASSERT(!layerTreeContext.isEmpty()); - - CALayer *renderLayer = WKMakeRenderLayer(layerTreeContext.contextID); - [m_wkView _setAcceleratedCompositingModeRootLayer:renderLayer]; -} - -void PageClientImpl::setAcceleratedCompositingRootLayer(CALayer *rootLayer) -{ - [m_wkView _setAcceleratedCompositingModeRootLayer:rootLayer]; -} - -void PageClientImpl::pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus) -{ - [m_wkView _pluginFocusOrWindowFocusChanged:pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:pluginComplexTextInputIdentifier]; -} - -void PageClientImpl::setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, PluginComplexTextInputState pluginComplexTextInputState) -{ - [m_wkView _setPluginComplexTextInputState:pluginComplexTextInputState pluginComplexTextInputIdentifier:pluginComplexTextInputIdentifier]; -} - -CGContextRef PageClientImpl::containingWindowGraphicsContext() -{ - NSWindow *window = [m_wkView window]; - - // Don't try to get the graphics context if the NSWindow doesn't have a window device. - if ([window windowNumber] <= 0) - return 0; - - return static_cast<CGContextRef>([[window graphicsContext] graphicsPort]); -} - -void PageClientImpl::flashBackingStoreUpdates(const Vector<IntRect>&) -{ - notImplemented(); -} - -void PageClientImpl::didPerformDictionaryLookup(const AttributedString& text, const DictionaryPopupInfo& dictionaryPopupInfo) -{ - RetainPtr<NSAttributedString> attributedString = text.string; - NSPoint textBaselineOrigin = dictionaryPopupInfo.origin; - - // 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()); -} - -void PageClientImpl::dismissDictionaryLookupPanel() -{ - // FIXME: We don't know which panel we are dismissing, it may not even be in the current page (see <rdar://problem/13875766>). - WKHideWordDefinitionWindow(); -} - -void PageClientImpl::showCorrectionPanel(AlternativeTextType type, const FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) -{ -#if USE(AUTOCORRECTION_PANEL) - if (!isViewVisible() || !isViewInWindow()) - return; - m_correctionPanel.show(m_wkView, type, boundingBoxOfReplacedString, replacedString, replacementString, alternativeReplacementStrings); -#endif -} - -void PageClientImpl::dismissCorrectionPanel(ReasonForDismissingAlternativeText reason) -{ -#if USE(AUTOCORRECTION_PANEL) - m_correctionPanel.dismiss(reason); -#endif -} - -String PageClientImpl::dismissCorrectionPanelSoon(WebCore::ReasonForDismissingAlternativeText reason) -{ -#if USE(AUTOCORRECTION_PANEL) - return m_correctionPanel.dismiss(reason); -#else - return String(); -#endif -} - -void PageClientImpl::recordAutocorrectionResponse(AutocorrectionResponseType responseType, const String& replacedString, const String& replacementString) -{ - NSCorrectionResponse response = responseType == AutocorrectionReverted ? NSCorrectionResponseReverted : NSCorrectionResponseEdited; - CorrectionPanel::recordAutocorrectionResponse(m_wkView, response, replacedString, replacementString); -} - -void PageClientImpl::recommendedScrollbarStyleDidChange(int32_t newStyle) -{ - NSArray *trackingAreas = [m_wkView trackingAreas]; - NSUInteger count = [trackingAreas count]; - ASSERT(count == 1); - - for (NSUInteger i = 0; i < count; ++i) - [m_wkView removeTrackingArea:[trackingAreas objectAtIndex:i]]; - - // Now re-create a tracking area with the appropriate options given the new scrollbar style - NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect; - if (newStyle == NSScrollerStyleLegacy) - options |= NSTrackingActiveAlways; - else - options |= NSTrackingActiveInKeyWindow; - - NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:[m_wkView frame] - options:options - owner:m_wkView - userInfo:nil]; - [m_wkView addTrackingArea:trackingArea]; - [trackingArea release]; -} - -void PageClientImpl::intrinsicContentSizeDidChange(const IntSize& intrinsicContentSize) -{ - [m_wkView _setIntrinsicContentSize:intrinsicContentSize]; -} - -bool PageClientImpl::executeSavedCommandBySelector(const String& selectorString) -{ - return [m_wkView _executeSavedCommandBySelector:NSSelectorFromString(selectorString)]; -} - -#if USE(DICTATION_ALTERNATIVES) -uint64_t PageClientImpl::addDictationAlternatives(const RetainPtr<NSTextAlternatives>& alternatives) -{ - return m_alternativeTextUIController->addAlternatives(alternatives); -} - -void PageClientImpl::removeDictationAlternatives(uint64_t dictationContext) -{ - m_alternativeTextUIController->removeAlternatives(dictationContext); -} - -void PageClientImpl::showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext) -{ - if (!isViewVisible() || !isViewInWindow()) - return; - m_alternativeTextUIController->showAlternatives(m_wkView, boundingBoxOfDictatedText, dictationContext, ^(NSString* acceptedAlternative){ - [m_wkView handleAcceptedAlternativeText:acceptedAlternative]; - }); -} - -Vector<String> PageClientImpl::dictationAlternatives(uint64_t dictationContext) -{ - return m_alternativeTextUIController->alternativesForContext(dictationContext); -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h deleted file mode 100644 index 6aa81c438..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <Foundation/Foundation.h> -#import <WebKit2/WKBase.h> - -@class WKBrowsingContextControllerData; -@protocol WKBrowsingContextLoadDelegate; - -WK_EXPORT -@interface WKBrowsingContextController : NSObject { -@private - WKBrowsingContextControllerData *_data; -} - -#pragma mark Delegates - -@property(assign) id<WKBrowsingContextLoadDelegate> loadDelegate; - - -#pragma mark Loading - -+ (void)registerSchemeForCustomProtocol:(NSString *)scheme; -+ (void)unregisterSchemeForCustomProtocol:(NSString *)scheme; - -/* 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 yield an exception. - - Passing nil as the allowedDirectory will open the entire file-system for - 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; - -/* Reload the currently active URL. */ -- (void)reload; - -/* Reload the currently active URL, bypassing caches. */ -- (void)reloadFromOrigin; - - -#pragma mark Back/Forward - -/* Go to the next page in the back/forward list. */ -- (void)goForward; - -/* Whether there is a next page in the back/forward list. */ -@property(readonly) BOOL canGoForward; - -/* Go to the previous page in the back/forward list. */ -- (void)goBack; - -/* Whether there is a previous page in the back/forward list. */ -@property(readonly) BOOL canGoBack; - - -#pragma mark Active Load Introspection - -/* URL for the active load. This is the URL that should be shown in user interface. */ -@property(readonly) NSURL *activeURL; - -/* URL for a request that has been sent, but no response has been recieved yet. */ -@property(readonly) NSURL *provisionalURL; - -/* URL for a request that has been recieved, and is now being used. */ -@property(readonly) NSURL *committedURL; - - -#pragma mark Active Document Introspection - -/* Title of the document associated with the active load. */ -@property(readonly) NSString *title; - - -#pragma mark Zoom - -/* Sets the text zoom for the active URL. */ -@property CGFloat textZoom; - -/* Sets the text zoom for the active URL. */ -@property CGFloat pageZoom; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm deleted file mode 100644 index f7120af2e..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextController.mm +++ /dev/null @@ -1,500 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKBrowsingContextController.h" -#import "WKBrowsingContextControllerPrivate.h" -#import "WKBrowsingContextControllerInternal.h" - -#import "ObjCObjectGraph.h" -#import "WKErrorCF.h" -#import "WKFrame.h" -#import "WKPagePrivate.h" -#import "WKRetainPtr.h" -#import "WKStringCF.h" -#import "WKURLCF.h" -#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); - return [(NSString *)WKStringCopyCFString(kCFAllocatorDefault, wkString.get()) autorelease]; -} - -static inline NSURL *autoreleased(WKURLRef url) -{ - WKRetainPtr<WKURLRef> wkURL = adoptWK(url); - return [(NSURL *)WKURLCopyCFURL(kCFAllocatorDefault, wkURL.get()) autorelease]; -} - -@interface WKBrowsingContextControllerData : NSObject { -@public - // Underlying WKPageRef. - WKRetainPtr<WKPageRef> _pageRef; - - // Delegate for load callbacks. - id<WKBrowsingContextLoadDelegate> _loadDelegate; -} -@end - -@implementation WKBrowsingContextControllerData -@end - - -@implementation WKBrowsingContextController - -- (void)dealloc -{ - WKPageSetPageLoaderClient(_data->_pageRef.get(), 0); - - [_data release]; - [super dealloc]; -} - -- (WKPageRef)_pageRef -{ - return _data->_pageRef.get(); -} - -#pragma mark Delegates - -- (id<WKBrowsingContextLoadDelegate>)loadDelegate -{ - return _data->_loadDelegate; -} - -- (void)setLoadDelegate:(id<WKBrowsingContextLoadDelegate>)loadDelegate -{ - _data->_loadDelegate = loadDelegate; -} - -#pragma mark Loading - -+ (void)registerSchemeForCustomProtocol:(NSString *)scheme -{ - if (!scheme) - return; - - NSString *lowercaseScheme = [scheme lowercaseString]; - [[WKBrowsingContextController customSchemes] addObject: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: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)); - - RefPtr<ObjCObjectGraph> wkUserData; - if (userData) - wkUserData = ObjCObjectGraph::create(userData); - - WKPageLoadURLRequestWithUserData(self._pageRef, wkRequest.get(), (WKTypeRef)wkUserData.get()); -} - -- (void)loadFileURL:(NSURL *)URL restrictToFilesWithin:(NSURL *)allowedDirectory -{ - [self loadFileURL:URL restrictToFilesWithin:allowedDirectory userData:nil]; -} - -- (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)); - 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)); - - WKRetainPtr<WKURLRef> wkBaseURL; - if (baseURL) - wkBaseURL = adoptWK(WKURLCreateWithCFURL((CFURLRef)baseURL)); - - 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 -{ - WKPageStopLoading(self._pageRef); -} - -- (void)reload -{ - WKPageReload(self._pageRef); -} - -- (void)reloadFromOrigin -{ - WKPageReloadFromOrigin(self._pageRef); -} - -#pragma mark Back/Forward - -- (void)goForward -{ - WKPageGoForward(self._pageRef); -} - -- (BOOL)canGoForward -{ - return WKPageCanGoForward(self._pageRef); -} - -- (void)goBack -{ - WKPageGoBack(self._pageRef); -} - -- (BOOL)canGoBack -{ - return WKPageCanGoBack(self._pageRef); -} - - -#pragma mark Active Load Introspection - -- (NSURL *)activeURL -{ - return autoreleased(WKPageCopyActiveURL(self._pageRef)); -} - -- (NSURL *)provisionalURL -{ - return autoreleased(WKPageCopyProvisionalURL(self._pageRef)); -} - -- (NSURL *)committedURL -{ - return autoreleased(WKPageCopyCommittedURL(self._pageRef)); -} - -#pragma mark Active Document Introspection - -- (NSString *)title -{ - return autoreleased(WKPageCopyTitle(self._pageRef)); -} - -#pragma mark Zoom - -- (CGFloat)textZoom -{ - return WKPageGetTextZoomFactor(self._pageRef); -} - -- (void)setTextZoom:(CGFloat)textZoom -{ - return WKPageSetTextZoomFactor(self._pageRef, textZoom); -} - -- (CGFloat)pageZoom -{ - return WKPageGetPageZoomFactor(self._pageRef); -} - -- (void)setPageZoom:(CGFloat)pageZoom -{ - return WKPageSetPageZoomFactor(self._pageRef, pageZoom); -} - -@end - -@implementation WKBrowsingContextController (Private) - -- (void)setPaginationMode:(WKBrowsingContextPaginationMode)paginationMode -{ - WKPaginationMode mode; - switch (paginationMode) { - case WKPaginationModeUnpaginated: - mode = kWKPaginationModeUnpaginated; - break; - case WKPaginationModeLeftToRight: - mode = kWKPaginationModeLeftToRight; - break; - case WKPaginationModeRightToLeft: - mode = kWKPaginationModeRightToLeft; - break; - case WKPaginationModeTopToBottom: - mode = kWKPaginationModeTopToBottom; - break; - case WKPaginationModeBottomToTop: - mode = kWKPaginationModeBottomToTop; - break; - default: - return; - } - - WKPageSetPaginationMode(self._pageRef, mode); -} - -- (WKBrowsingContextPaginationMode)paginationMode -{ - switch (WKPageGetPaginationMode(self._pageRef)) { - case kWKPaginationModeUnpaginated: - return WKPaginationModeUnpaginated; - case kWKPaginationModeLeftToRight: - return WKPaginationModeLeftToRight; - case kWKPaginationModeRightToLeft: - return WKPaginationModeRightToLeft; - case kWKPaginationModeTopToBottom: - return WKPaginationModeTopToBottom; - case kWKPaginationModeBottomToTop: - return WKPaginationModeBottomToTop; - } - - ASSERT_NOT_REACHED(); - return WKPaginationModeUnpaginated; -} - -- (void)setPaginationBehavesLikeColumns:(BOOL)behavesLikeColumns -{ - WKPageSetPaginationBehavesLikeColumns(self._pageRef, behavesLikeColumns); -} - -- (BOOL)paginationBehavesLikeColumns -{ - return WKPageGetPaginationBehavesLikeColumns(self._pageRef); -} - -- (void)setPageLength:(CGFloat)pageLength -{ - WKPageSetPageLength(self._pageRef, pageLength); -} - -- (CGFloat)pageLength -{ - return WKPageGetPageLength(self._pageRef); -} - -- (void)setGapBetweenPages:(CGFloat)gapBetweenPages -{ - WKPageSetGapBetweenPages(self._pageRef, gapBetweenPages); -} - -- (CGFloat)gapBetweenPages -{ - return WKPageGetGapBetweenPages(self._pageRef); -} - -- (NSUInteger)pageCount -{ - return WKPageGetPageCount(self._pageRef); -} - -@end - -@implementation WKBrowsingContextController (Internal) - -static void didStartProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; - if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidStartProvisionalLoad:)]) - [browsingContext.loadDelegate browsingContextControllerDidStartProvisionalLoad:browsingContext]; -} - -static void didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; - if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidReceiveServerRedirectForProvisionalLoad:)]) - [browsingContext.loadDelegate browsingContextControllerDidReceiveServerRedirectForProvisionalLoad:browsingContext]; -} - -static void didFailProvisionalLoadWithErrorForFrame(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; - if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidFailProvisionalLoad:withError:)]) { - RetainPtr<CFErrorRef> cfError = adoptCF(WKErrorCopyCFError(kCFAllocatorDefault, error)); - [browsingContext.loadDelegate browsingContextControllerDidFailProvisionalLoad:browsingContext withError:(NSError *)cfError.get()]; - } -} - -static void didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; - if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidCommitLoad:)]) - [browsingContext.loadDelegate browsingContextControllerDidCommitLoad:browsingContext]; -} - -static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; - if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidFinishLoad:)]) - [browsingContext.loadDelegate browsingContextControllerDidFinishLoad:browsingContext]; -} - -static void didFailLoadWithErrorForFrame(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - WKBrowsingContextController *browsingContext = (WKBrowsingContextController *)clientInfo; - if ([browsingContext.loadDelegate respondsToSelector:@selector(browsingContextControllerDidFailLoad:withError:)]) { - RetainPtr<CFErrorRef> cfError = adoptCF(WKErrorCopyCFError(kCFAllocatorDefault, error)); - [browsingContext.loadDelegate browsingContextControllerDidFailLoad:browsingContext withError:(NSError *)cfError.get()]; - } -} - -static void setUpPageLoaderClient(WKBrowsingContextController *browsingContext, WKPageRef pageRef) -{ - WKPageLoaderClient loaderClient; - memset(&loaderClient, 0, sizeof(loaderClient)); - - loaderClient.version = kWKPageLoaderClientCurrentVersion; - loaderClient.clientInfo = browsingContext; - loaderClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; - loaderClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame; - loaderClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame; - loaderClient.didCommitLoadForFrame = didCommitLoadForFrame; - loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; - loaderClient.didFailLoadWithErrorForFrame = didFailLoadWithErrorForFrame; - - WKPageSetPageLoaderClient(pageRef, &loaderClient); -} - - -/* This should only be called from associate view. */ - -- (id)_initWithPageRef:(WKPageRef)pageRef -{ - self = [super init]; - if (!self) - return nil; - - _data = [[WKBrowsingContextControllerData alloc] init]; - _data->_pageRef = pageRef; - - setUpPageLoaderClient(self, pageRef); - - return self; -} - -+ (WKBrowsingContextController *)_browsingContextControllerForPageRef:(WKPageRef)pageRef -{ - return (WKBrowsingContextController *)WebKit::toImpl(pageRef)->loaderClient().client().clientInfo; -} - -+ (NSMutableSet *)customSchemes -{ - static NSMutableSet *customSchemes = [[NSMutableSet alloc] init]; - return customSchemes; -} - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h deleted file mode 100644 index 1ec4b515c..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerInternal.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <WebKit2/WKBrowsingContextController.h> - -@interface WKBrowsingContextController (Internal) - -/* This should only be called from associate view. */ -- (id)_initWithPageRef:(WKPageRef)pageRef; - -/* Returns a WKBrowsingContextController associated with the WKPageRef. */ -+ (WKBrowsingContextController *)_browsingContextControllerForPageRef:(WKPageRef)pageRef; - -+ (NSMutableSet *)customSchemes; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h deleted file mode 100644 index 6c8cb49b2..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextControllerPrivate.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <WebKit2/WKBrowsingContextController.h> - -enum { - WKPaginationModeUnpaginated, - WKPaginationModeLeftToRight, - WKPaginationModeRightToLeft, - WKPaginationModeTopToBottom, - WKPaginationModeBottomToTop, -}; -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. -@property BOOL paginationBehavesLikeColumns; -// Set to 0 to have the page length equal the view length. -@property CGFloat pageLength; -@property CGFloat gapBetweenPages; - -@property(readonly) NSUInteger pageCount; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.h deleted file mode 100644 index e8d2bdab9..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <Foundation/Foundation.h> -#import <WebKit2/WKBase.h> - -@class WKBrowsingContextGroupData; - -WK_EXPORT -@interface WKBrowsingContextGroup : NSObject { -@private - WKBrowsingContextGroupData *_data; -} - -- (id)initWithIdentifier:(NSString *)identifier; - -/* User Content */ - -- (void)addUserStyleSheet:(NSString *)source baseURL:(NSURL *)baseURL whitelistedURLPatterns:(NSArray *)whitelist blacklistedURLPatterns:(NSArray *)blacklist mainFrameOnly:(BOOL)mainFrameOnly; -- (void)removeAllUserStyleSheets; - -- (void)addUserScript:(NSString *)source baseURL:(NSURL *)baseURL whitelistedURLPatterns:(NSArray *)whitelist blacklistedURLPatterns:(NSArray *)blacklist injectionTime:(WKUserScriptInjectionTime)injectionTime mainFrameOnly:(BOOL)mainFrameOnly; -- (void)removeAllUserScripts; - - -/* Settings */ - -/* Setting to control whether JavaScript referenced by a page is enabled. - Default: YES -*/ -@property BOOL allowsJavaScript; - -/* Setting to control whether plug-ins are enabled. - Default: YES -*/ -@property BOOL allowsPlugIns; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm deleted file mode 100644 index a24b015c9..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextGroup.mm +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKBrowsingContextGroup.h" -#import "WKBrowsingContextGroupPrivate.h" - -#import "WKArray.h" -#import "WKPageGroup.h" -#import "WKPreferences.h" -#import "WKRetainPtr.h" -#import "WKStringCF.h" -#import "WKURL.h" -#import "WKURLCF.h" -#import <wtf/Vector.h> - -@interface WKBrowsingContextGroupData : NSObject { -@public - WKRetainPtr<WKPageGroupRef> _pageGroupRef; -} -@end - -@implementation WKBrowsingContextGroupData -@end - -@implementation WKBrowsingContextGroup - -- (id)initWithIdentifier:(NSString *)identifier -{ - self = [super init]; - if (!self) - return nil; - - _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; -} - -- (void)dealloc -{ - [_data release]; - [super dealloc]; -} - -- (BOOL)allowsJavaScript -{ - return WKPreferencesGetJavaScriptEnabled(WKPageGroupGetPreferences(self._pageGroupRef)); -} - -- (void)setAllowsJavaScript:(BOOL)allowsJavaScript -{ - 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)); -} - -- (void)setAllowsPlugIns:(BOOL)allowsPlugIns -{ - WKPreferencesSetPluginsEnabled(WKPageGroupGetPreferences(self._pageGroupRef), allowsPlugIns); -} - -static WKArrayRef createWKArray(NSArray *array) -{ - NSUInteger count = [array count]; - if (count == 0) - return WKArrayRef(); - - Vector<WKTypeRef> stringVector; - stringVector.reserveInitialCapacity(count); - for (NSUInteger i = 0; i < count; ++i) { - id entry = [array objectAtIndex:i]; - if ([entry isKindOfClass:[NSString class]]) - stringVector.uncheckedAppend(WKStringCreateWithCFString((CFStringRef)entry)); - - } - - return WKArrayCreateAdoptingValues(stringVector.data(), stringVector.size()); -} - --(void)addUserStyleSheet:(NSString *)source baseURL:(NSURL *)baseURL whitelistedURLPatterns:(NSArray *)whitelist blacklistedURLPatterns:(NSArray *)blacklist mainFrameOnly:(BOOL)mainFrameOnly -{ - if (!source) - CRASH(); - - WKRetainPtr<WKStringRef> wkSource = adoptWK(WKStringCreateWithCFString((CFStringRef)source)); - WKRetainPtr<WKURLRef> wkBaseURL = adoptWK(WKURLCreateWithCFURL((CFURLRef)baseURL)); - WKRetainPtr<WKArrayRef> wkWhitelist = adoptWK(createWKArray(whitelist)); - WKRetainPtr<WKArrayRef> wkBlacklist = adoptWK(createWKArray(blacklist)); - WKUserContentInjectedFrames injectedFrames = mainFrameOnly ? kWKInjectInTopFrameOnly : kWKInjectInAllFrames; - - WKPageGroupAddUserStyleSheet(self._pageGroupRef, wkSource.get(), wkBaseURL.get(), wkWhitelist.get(), wkBlacklist.get(), injectedFrames); -} - -- (void)removeAllUserStyleSheets -{ - WKPageGroupRemoveAllUserStyleSheets(self._pageGroupRef); -} - -- (void)addUserScript:(NSString *)source baseURL:(NSURL *)baseURL whitelistedURLPatterns:(NSArray *)whitelist blacklistedURLPatterns:(NSArray *)blacklist injectionTime:(WKUserScriptInjectionTime)injectionTime mainFrameOnly:(BOOL)mainFrameOnly -{ - if (!source) - CRASH(); - - WKRetainPtr<WKStringRef> wkSource = adoptWK(WKStringCreateWithCFString((CFStringRef)source)); - WKRetainPtr<WKURLRef> wkBaseURL = adoptWK(WKURLCreateWithCFURL((CFURLRef)baseURL)); - WKRetainPtr<WKArrayRef> wkWhitelist = adoptWK(createWKArray(whitelist)); - WKRetainPtr<WKArrayRef> wkBlacklist = adoptWK(createWKArray(blacklist)); - WKUserContentInjectedFrames injectedFrames = mainFrameOnly ? kWKInjectInTopFrameOnly : kWKInjectInAllFrames; - - WKPageGroupAddUserScript(self._pageGroupRef, wkSource.get(), wkBaseURL.get(), wkWhitelist.get(), wkBlacklist.get(), injectedFrames, injectionTime); -} - -- (void)removeAllUserScripts -{ - WKPageGroupRemoveAllUserScripts(self._pageGroupRef); -} - -@end - -@implementation WKBrowsingContextGroup (Private) - -- (WKPageGroupRef)_pageGroupRef -{ - return _data->_pageGroupRef.get(); -} - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextLoadDelegate.h b/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextLoadDelegate.h deleted file mode 100644 index 3cd3a51d9..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKBrowsingContextLoadDelegate.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <Foundation/Foundation.h> -#import <WebKit2/WKBase.h> - -@class WKBrowsingContextController; - -@protocol WKBrowsingContextLoadDelegate <NSObject> -@optional - -/* Sent when the provisional load begins. */ -- (void)browsingContextControllerDidStartProvisionalLoad:(WKBrowsingContextController *)sender; - -/* Sent if a server-side redirect was recieved. */ -- (void)browsingContextControllerDidReceiveServerRedirectForProvisionalLoad:(WKBrowsingContextController *)sender; - -/* Sent if the provional load fails. */ -- (void)browsingContextControllerDidFailProvisionalLoad:(WKBrowsingContextController *)sender withError:(NSError *)error; - -/* Sent when the load gets committed. */ -- (void)browsingContextControllerDidCommitLoad:(WKBrowsingContextController *)sender; - -/* Sent when the load completes. */ -- (void)browsingContextControllerDidFinishLoad:(WKBrowsingContextController *)sender; - -/* Sent if the commited load fails. */ -- (void)browsingContextControllerDidFailLoad:(WKBrowsingContextController *)sender withError:(NSError *)error; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKConnection.h b/Source/WebKit2/UIProcess/API/mac/WKConnection.h deleted file mode 100644 index 52bd85c66..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKConnection.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <Foundation/Foundation.h> -#import <WebKit2/WKBase.h> - -@class WKConnection, WKConnectionData; - -@protocol WKConnectionDelegate <NSObject> - -- (void)connection:(WKConnection *)connection didReceiveMessageWithName:(NSString *)messageName body:(id)messageBody; -- (void)connectionDidClose:(WKConnection *)connection; - -@end - -WK_EXPORT -@interface WKConnection : NSObject { -@private - WKConnectionData *_data; -} - -- (void)sendMessageWithName:(NSString *)messageName body:(id)messageBody; - -#pragma mark Delegates - -@property(assign) id<WKConnectionDelegate> delegate; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKConnection.mm b/Source/WebKit2/UIProcess/API/mac/WKConnection.mm deleted file mode 100644 index 3830e740f..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKConnection.mm +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKConnection.h" -#import "WKConnectionInternal.h" - -#import "ObjCObjectGraph.h" -#import "WKConnectionRef.h" -#import "WKData.h" -#import "WKRetainPtr.h" -#import "WKString.h" -#import "WKStringCF.h" -#import <wtf/RetainPtr.h> - -using namespace WebKit; - -@interface WKConnectionData : NSObject { -@public - // Underlying connection object. - WKRetainPtr<WKConnectionRef> _connectionRef; - - // Delegate for callbacks. - id<WKConnectionDelegate> _delegate; -} -@end - -@implementation WKConnectionData -@end - -@implementation WKConnection - -- (void)dealloc -{ - WKConnectionSetConnectionClient(_data->_connectionRef.get(), 0); - - [_data release]; - [super dealloc]; -} - -- (void)sendMessageWithName:(NSString *)messageName body:(id)messageBody -{ - WKRetainPtr<WKStringRef> wkMessageName = adoptWK(WKStringCreateWithCFString((CFStringRef)messageName)); - RefPtr<ObjCObjectGraph> wkMessageBody = ObjCObjectGraph::create(messageBody); - - WKConnectionPostMessage(_data->_connectionRef.get(), wkMessageName.get(), (WKTypeRef)wkMessageBody.get()); -} - -#pragma mark Delegates - -- (id<WKConnectionDelegate>)delegate -{ - return _data->_delegate; -} - -- (void)setDelegate:(id<WKConnectionDelegate>)delegate -{ - _data->_delegate = delegate; -} - -@end - -@implementation WKConnection (Internal) - -static void didReceiveMessage(WKConnectionRef, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo) -{ - WKConnection *connection = (WKConnection *)clientInfo; - if ([connection.delegate respondsToSelector:@selector(connection:didReceiveMessageWithName:body:)]) { - RetainPtr<CFStringRef> nsMessageName = adoptCF(WKStringCopyCFString(kCFAllocatorDefault, messageName)); - RetainPtr<id> nsMessageBody = ((ObjCObjectGraph*)messageBody)->rootObject(); - - [connection.delegate connection:connection didReceiveMessageWithName:(NSString *)nsMessageName.get() body:nsMessageBody.get()]; - } -} - -static void didClose(WKConnectionRef, const void* clientInfo) -{ - WKConnection *connection = (WKConnection *)clientInfo; - if ([connection.delegate respondsToSelector:@selector(connectionDidClose:)]) { - [connection.delegate connectionDidClose:connection]; - } -} - -static void setUpClient(WKConnection *connection, WKConnectionRef connectionRef) -{ - WKConnectionClient client; - memset(&client, 0, sizeof(client)); - - client.version = WKConnectionClientCurrentVersion; - client.clientInfo = connection; - client.didReceiveMessage = didReceiveMessage; - client.didClose = didClose; - - WKConnectionSetConnectionClient(connectionRef, &client); -} - -- (id)_initWithConnectionRef:(WKConnectionRef)connectionRef -{ - self = [super init]; - if (!self) - return nil; - - _data = [[WKConnectionData alloc] init]; - _data->_connectionRef = connectionRef; - - setUpClient(self, _data->_connectionRef.get()); - - return self; -} - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h b/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h deleted file mode 100644 index b45f635b3..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <WebCore/IntRectHash.h> -#import <wtf/RetainPtr.h> - -@class WKPrintingViewData; -@class PDFDocument; - -namespace WebKit { - class ShareableBitmap; - class WebFrameProxy; -} - -@interface WKPrintingView : NSView { -@public - NSPrintOperation *_printOperation; // WKPrintingView is owned by the operation. - RetainPtr<NSView> _wkView; - - RefPtr<WebKit::WebFrameProxy> _webFrame; - Vector<WebCore::IntRect> _printingPageRects; - double _totalScaleFactorForPrinting; - HashMap<WebCore::IntRect, RefPtr<WebKit::ShareableBitmap>> _pagePreviews; - - Vector<uint8_t> _printedPagesData; - RetainPtr<PDFDocument> _printedPagesPDFDocument; - - uint64_t _expectedComputedPagesCallback; - HashMap<uint64_t, WebCore::IntRect> _expectedPreviewCallbacks; - uint64_t _latestExpectedPreviewCallback; - uint64_t _expectedPrintCallback; - - BOOL _isPrintingFromSecondaryThread; - Mutex _printingCallbackMutex; - ThreadCondition _printingCallbackCondition; - - NSTimer *_autodisplayResumeTimer; -} - -- (id)initWithFrameProxy:(WebKit::WebFrameProxy*)frame view:(NSView *)wkView; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm b/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm deleted file mode 100644 index 350ad542e..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKPrintingView.mm +++ /dev/null @@ -1,677 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKPrintingView.h" - -#import "Logging.h" -#import "PDFKitImports.h" -#import "PrintInfo.h" -#import "ShareableBitmap.h" -#import "WebData.h" -#import "WebPageProxy.h" -#import <PDFKit/PDFKit.h> -#import <WebCore/GraphicsContext.h> -#import <WebCore/WebCoreObjCExtras.h> -#import <wtf/MainThread.h> - -using namespace WebKit; -using namespace WebCore; - -NSString * const WebKitOriginalTopPrintingMarginKey = @"WebKitOriginalTopMargin"; -NSString * const WebKitOriginalBottomPrintingMarginKey = @"WebKitOriginalBottomMargin"; - -NSString * const NSPrintInfoDidChangeNotification = @"NSPrintInfoDidChange"; - -static BOOL isForcingPreviewUpdate; - -@implementation WKPrintingView - -- (id)initWithFrameProxy:(WebKit::WebFrameProxy*)frame view:(NSView *)wkView -{ - self = [super init]; // No frame rect to pass to NSView. - if (!self) - return nil; - - _webFrame = frame; - _wkView = wkView; - - return self; -} - -- (void)dealloc -{ - if (WebCoreObjCScheduleDeallocateOnMainThread([WKPrintingView class], self)) - return; - - [super dealloc]; -} - -- (BOOL)isFlipped -{ - return YES; -} - -- (void)_setAutodisplay:(BOOL)newState -{ - if (!newState && [[_wkView.get() window] isAutodisplay]) - [_wkView.get() displayIfNeeded]; - - [[_wkView.get() window] setAutodisplay:newState]; - - // For some reason, painting doesn't happen for a long time without this call, <rdar://problem/8975229>. - if (newState) - [_wkView.get() displayIfNeeded]; -} - - -- (void)_suspendAutodisplay -{ - // A drawRect: call on WKView causes a switch to screen mode, which is slow due to relayout, and we want to avoid that. - // Disabling autodisplay will prevent random updates from causing this, but resizing the window will still work. - if (_autodisplayResumeTimer) { - [_autodisplayResumeTimer invalidate]; - _autodisplayResumeTimer = nil; - } else - [self _setAutodisplay:NO]; -} - -- (void)_delayedResumeAutodisplayTimerFired -{ - ASSERT(isMainThread()); - - _autodisplayResumeTimer = nil; - [self _setAutodisplay:YES]; - - // Enabling autodisplay normally implicitly calls endPrinting() via -[WKView drawRect:], but not when content is in accelerated compositing mode. - if (_webFrame->page()) - _webFrame->page()->endPrinting(); -} - -- (void)_delayedResumeAutodisplay -{ - // AppKit calls endDocument/beginDocument when print option change. We don't want to switch between print and screen mode just for that, - // and enabling autodisplay may result in switching into screen mode. So, autodisplay is only resumed on next run loop iteration. - if (!_autodisplayResumeTimer) { - _autodisplayResumeTimer = [NSTimer timerWithTimeInterval:0 target:self selector:@selector(_delayedResumeAutodisplayTimerFired) userInfo:nil repeats:NO]; - // The timer must be scheduled on main thread, because printing thread may finish before it fires. - [[NSRunLoop mainRunLoop] addTimer:_autodisplayResumeTimer forMode:NSDefaultRunLoopMode]; - } -} - -- (void)_adjustPrintingMarginsForHeaderAndFooter -{ - ASSERT(isMainThread()); // This funciton calls the client, which should only be done on main thread. - - NSPrintInfo *info = [_printOperation printInfo]; - NSMutableDictionary *infoDictionary = [info dictionary]; - - // We need to modify the top and bottom margins in the NSPrintInfo to account for the space needed by the - // header and footer. Because this method can be called more than once on the same NSPrintInfo (see 5038087), - // we stash away the unmodified top and bottom margins the first time this method is called, and we read from - // those stashed-away values on subsequent calls. - double originalTopMargin; - double originalBottomMargin; - NSNumber *originalTopMarginNumber = [infoDictionary objectForKey:WebKitOriginalTopPrintingMarginKey]; - if (!originalTopMarginNumber) { - ASSERT(![infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey]); - originalTopMargin = [info topMargin]; - originalBottomMargin = [info bottomMargin]; - [infoDictionary setObject:[NSNumber numberWithDouble:originalTopMargin] forKey:WebKitOriginalTopPrintingMarginKey]; - [infoDictionary setObject:[NSNumber numberWithDouble:originalBottomMargin] forKey:WebKitOriginalBottomPrintingMarginKey]; - } else { - ASSERT([originalTopMarginNumber isKindOfClass:[NSNumber class]]); - ASSERT([[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] isKindOfClass:[NSNumber class]]); - originalTopMargin = [originalTopMarginNumber doubleValue]; - originalBottomMargin = [[infoDictionary objectForKey:WebKitOriginalBottomPrintingMarginKey] doubleValue]; - } - - CGFloat scale = [info scalingFactor]; - [info setTopMargin:originalTopMargin + _webFrame->page()->headerHeight(_webFrame.get()) * scale]; - [info setBottomMargin:originalBottomMargin + _webFrame->page()->footerHeight(_webFrame.get()) * scale]; -} - -- (BOOL)_isPrintingPreview -{ - // <rdar://problem/8901041> Please add an API returning whether the current print operation is for preview. - // Assuming that if NSPrintOperation is allowed to spawn a thread for printing, it will. Print preview doesn't spawn a thread. - return !_isPrintingFromSecondaryThread; -} - -- (void)_updatePreview -{ - // <rdar://problem/8900923> Please add an API to force print preview update. - ASSERT(!isForcingPreviewUpdate); - isForcingPreviewUpdate = YES; - [[NSNotificationCenter defaultCenter] postNotificationName:NSPrintInfoDidChangeNotification object:nil]; - isForcingPreviewUpdate = NO; -} - -- (BOOL)_hasPageRects -{ - // WebCore always prints at least one page. - return !_printingPageRects.isEmpty(); -} - -- (NSUInteger)_firstPrintedPageNumber -{ - // Need to directly access the dictionary because -[NSPrintOperation pageRange] verifies pagination, potentially causing recursion. - return [[[[_printOperation printInfo] dictionary] objectForKey:NSPrintFirstPage] unsignedIntegerValue]; -} - -- (NSUInteger)_lastPrintedPageNumber -{ - ASSERT([self _hasPageRects]); - - // Need to directly access the dictionary because -[NSPrintOperation pageRange] verifies pagination, potentially causing recursion. - NSUInteger firstPage = [[[[_printOperation printInfo] dictionary] objectForKey:NSPrintFirstPage] unsignedIntegerValue]; - NSUInteger lastPage = [[[[_printOperation printInfo] dictionary] objectForKey:NSPrintLastPage] unsignedIntegerValue]; - if (lastPage - firstPage >= _printingPageRects.size()) - return _printingPageRects.size(); - return lastPage; -} - -- (uint64_t)_expectedPreviewCallbackForRect:(const IntRect&)rect -{ - for (HashMap<uint64_t, WebCore::IntRect>::iterator iter = _expectedPreviewCallbacks.begin(); iter != _expectedPreviewCallbacks.end(); ++iter) { - if (iter->value == rect) - return iter->key; - } - return 0; -} - -struct IPCCallbackContext { - RetainPtr<WKPrintingView> view; - uint64_t callbackID; -}; - -static void pageDidDrawToImage(const ShareableBitmap::Handle& imageHandle, WKErrorRef, void* untypedContext) -{ - ASSERT(isMainThread()); - - OwnPtr<IPCCallbackContext> context = adoptPtr(static_cast<IPCCallbackContext*>(untypedContext)); - WKPrintingView *view = context->view.get(); - - // If the user has already changed print setup, then this response is obsolete. And if this callback is not in response to the latest request, - // then the user has already moved to another page - we'll cache the response, but won't draw it. - HashMap<uint64_t, WebCore::IntRect>::iterator iter = view->_expectedPreviewCallbacks.find(context->callbackID); - if (iter != view->_expectedPreviewCallbacks.end()) { - ASSERT([view _isPrintingPreview]); - - if (!imageHandle.isNull()) { - RefPtr<ShareableBitmap> image = ShareableBitmap::create(imageHandle, SharedMemory::ReadOnly); - - if (image) - view->_pagePreviews.add(iter->value, image); - } - - view->_expectedPreviewCallbacks.remove(context->callbackID); - bool receivedResponseToLatestRequest = view->_latestExpectedPreviewCallback == context->callbackID; - if (receivedResponseToLatestRequest) { - view->_latestExpectedPreviewCallback = 0; - [view _updatePreview]; - } - } -} - -static void pageDidDrawToPDF(WKDataRef dataRef, WKErrorRef, void* untypedContext) -{ - ASSERT(isMainThread()); - - OwnPtr<IPCCallbackContext> context = adoptPtr(static_cast<IPCCallbackContext*>(untypedContext)); - WKPrintingView *view = context->view.get(); - WebData* data = toImpl(dataRef); - - if (context->callbackID == view->_expectedPrintCallback) { - ASSERT(![view _isPrintingPreview]); - ASSERT(view->_printedPagesData.isEmpty()); - ASSERT(!view->_printedPagesPDFDocument); - if (data) - view->_printedPagesData.append(data->bytes(), data->size()); - view->_expectedPrintCallback = 0; - view->_printingCallbackCondition.signal(); - } -} - -- (void)_preparePDFDataForPrintingOnSecondaryThread -{ - ASSERT(isMainThread()); - - if (!_webFrame->page()) { - _printingCallbackCondition.signal(); - return; - } - - MutexLocker lock(_printingCallbackMutex); - - ASSERT([self _hasPageRects]); - ASSERT(_printedPagesData.isEmpty()); - ASSERT(!_printedPagesPDFDocument); - ASSERT(!_expectedPrintCallback); - - NSUInteger firstPage = [self _firstPrintedPageNumber]; - NSUInteger lastPage = [self _lastPrintedPageNumber]; - - ASSERT(firstPage > 0); - ASSERT(firstPage <= lastPage); - LOG(View, "WKPrintingView requesting PDF data for pages %u...%u", firstPage, lastPage); - - PrintInfo printInfo([_printOperation printInfo]); - // Return to printing mode if we're already back to screen (e.g. due to window resizing). - _webFrame->page()->beginPrinting(_webFrame.get(), printInfo); - - IPCCallbackContext* context = new IPCCallbackContext; - RefPtr<DataCallback> callback = DataCallback::create(context, pageDidDrawToPDF); - _expectedPrintCallback = callback->callbackID(); - - context->view = self; - context->callbackID = callback->callbackID(); - - _webFrame->page()->drawPagesToPDF(_webFrame.get(), printInfo, firstPage - 1, lastPage - firstPage + 1, callback.get()); -} - -static void pageDidComputePageRects(const Vector<WebCore::IntRect>& pageRects, double totalScaleFactorForPrinting, WKErrorRef, void* untypedContext) -{ - ASSERT(isMainThread()); - - OwnPtr<IPCCallbackContext> context = adoptPtr(static_cast<IPCCallbackContext*>(untypedContext)); - WKPrintingView *view = context->view.get(); - - // If the user has already changed print setup, then this response is obsolete. - if (context->callbackID == view->_expectedComputedPagesCallback) { - ASSERT(isMainThread()); - ASSERT(view->_expectedPreviewCallbacks.isEmpty()); - ASSERT(!view->_latestExpectedPreviewCallback); - ASSERT(!view->_expectedPrintCallback); - ASSERT(view->_pagePreviews.isEmpty()); - view->_expectedComputedPagesCallback = 0; - - view->_printingPageRects = pageRects; - view->_totalScaleFactorForPrinting = totalScaleFactorForPrinting; - - // Sanitize a response coming from the Web process. - if (view->_printingPageRects.isEmpty()) - view->_printingPageRects.append(IntRect(0, 0, 1, 1)); - if (view->_totalScaleFactorForPrinting <= 0) - view->_totalScaleFactorForPrinting = 1; - - const IntRect& lastPrintingPageRect = view->_printingPageRects[view->_printingPageRects.size() - 1]; - NSRect newFrameSize = NSMakeRect(0, 0, - ceil(lastPrintingPageRect.maxX() * view->_totalScaleFactorForPrinting), - ceil(lastPrintingPageRect.maxY() * view->_totalScaleFactorForPrinting)); - LOG(View, "WKPrintingView setting frame size to x:%g y:%g width:%g height:%g", newFrameSize.origin.x, newFrameSize.origin.y, newFrameSize.size.width, newFrameSize.size.height); - [view setFrame:newFrameSize]; - - if ([view _isPrintingPreview]) { - // Show page count, and ask for an actual image to replace placeholder. - [view _updatePreview]; - } else { - // When printing, request everything we'll need beforehand. - [view _preparePDFDataForPrintingOnSecondaryThread]; - } - } -} - -- (BOOL)_askPageToComputePageRects -{ - ASSERT(isMainThread()); - - if (!_webFrame->page()) - return NO; - - ASSERT(!_expectedComputedPagesCallback); - - IPCCallbackContext* context = new IPCCallbackContext; - RefPtr<ComputedPagesCallback> callback = ComputedPagesCallback::create(context, pageDidComputePageRects); - _expectedComputedPagesCallback = callback->callbackID(); - context->view = self; - context->callbackID = _expectedComputedPagesCallback; - - _webFrame->page()->computePagesForPrinting(_webFrame.get(), PrintInfo([_printOperation printInfo]), callback.release()); - return YES; -} - -static void prepareDataForPrintingOnSecondaryThread(void* untypedContext) -{ - ASSERT(isMainThread()); - - WKPrintingView *view = static_cast<WKPrintingView *>(untypedContext); - MutexLocker lock(view->_printingCallbackMutex); - - // We may have received page rects while a message to call this function traveled from secondary thread to main one. - if ([view _hasPageRects]) { - [view _preparePDFDataForPrintingOnSecondaryThread]; - return; - } - - // A request for pages has already been made, just wait for it to finish. - if (view->_expectedComputedPagesCallback) - return; - - [view _askPageToComputePageRects]; -} - -- (BOOL)knowsPageRange:(NSRangePointer)range -{ - LOG(View, "-[WKPrintingView %p knowsPageRange:], %s, %s", self, [self _hasPageRects] ? "print data is available" : "print data is not available yet", isMainThread() ? "on main thread" : "on secondary thread"); - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - - // Assuming that once we switch to printing from a secondary thread, we don't go back. - ASSERT(!_isPrintingFromSecondaryThread || !isMainThread()); - if (!isMainThread()) - _isPrintingFromSecondaryThread = YES; - - if (!_webFrame->page()) { - *range = NSMakeRange(1, NSIntegerMax); - return YES; - } - - [self _suspendAutodisplay]; - - [self performSelectorOnMainThread:@selector(_adjustPrintingMarginsForHeaderAndFooter) withObject:nil waitUntilDone:YES]; - - if ([self _hasPageRects]) - *range = NSMakeRange(1, _printingPageRects.size()); - else if (!isMainThread()) { - ASSERT(![self _isPrintingPreview]); - MutexLocker lock(_printingCallbackMutex); - callOnMainThread(prepareDataForPrintingOnSecondaryThread, self); - _printingCallbackCondition.wait(_printingCallbackMutex); - *range = NSMakeRange(1, _printingPageRects.size()); - } else { - ASSERT([self _isPrintingPreview]); - - // If a request for pages hasn't already been made, make it now. - if (!_expectedComputedPagesCallback) - [self _askPageToComputePageRects]; - - *range = NSMakeRange(1, NSIntegerMax); - } - return YES; -} - -- (unsigned)_pageForRect:(NSRect)rect -{ - // Assuming that rect exactly matches one of the pages. - for (size_t i = 0; i < _printingPageRects.size(); ++i) { - IntRect currentRect(_printingPageRects[i]); - currentRect.scale(_totalScaleFactorForPrinting); - if (rect.origin.y == currentRect.y() && rect.origin.x == currentRect.x()) - return i + 1; - } - ASSERT_NOT_REACHED(); - return 0; // Invalid page number. -} - -- (void)_drawPDFDocument:(PDFDocument *)pdfDocument page:(unsigned)page atPoint:(NSPoint)point -{ - if (!pdfDocument) { - LOG_ERROR("Couldn't create a PDF document with data passed for preview"); - return; - } - - PDFPage *pdfPage; - @try { - pdfPage = [pdfDocument pageAtIndex:page]; - } @catch (id exception) { - LOG_ERROR("Preview data doesn't have page %d: %@", page, exception); - return; - } - - NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext currentContext]; - CGContextRef context = static_cast<CGContextRef>([nsGraphicsContext graphicsPort]); - - CGContextSaveGState(context); - CGContextTranslateCTM(context, point.x, point.y); - CGContextScaleCTM(context, _totalScaleFactorForPrinting, -_totalScaleFactorForPrinting); - CGContextTranslateCTM(context, 0, -[pdfPage boundsForBox:kPDFDisplayBoxMediaBox].size.height); - [pdfPage drawWithBox:kPDFDisplayBoxMediaBox]; - - CGAffineTransform transform = CGContextGetCTM(context); - - for (PDFAnnotation *annotation in [pdfPage annotations]) { - if (![annotation isKindOfClass:pdfAnnotationLinkClass()]) - continue; - - PDFAnnotationLink *linkAnnotation = (PDFAnnotationLink *)annotation; - NSURL *url = [linkAnnotation URL]; - if (!url) - continue; - - CGRect urlRect = NSRectToCGRect([linkAnnotation bounds]); - CGRect transformedRect = CGRectApplyAffineTransform(urlRect, transform); - CGPDFContextSetURLForRect(context, (CFURLRef)url, transformedRect); - } - - CGContextRestoreGState(context); -} - -- (void)_drawPreview:(NSRect)nsRect -{ - ASSERT(isMainThread()); - - 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: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; - } else { - // Preview isn't available yet, request it asynchronously. - if (!_webFrame->page()) - return; - - // Return to printing mode if we're already back to screen (e.g. due to window resizing). - _webFrame->page()->beginPrinting(_webFrame.get(), PrintInfo([_printOperation printInfo])); - - IPCCallbackContext* context = new IPCCallbackContext; - RefPtr<ImageCallback> callback = ImageCallback::create(context, pageDidDrawToImage); - _latestExpectedPreviewCallback = callback->callbackID(); - _expectedPreviewCallbacks.add(_latestExpectedPreviewCallback, scaledPrintingRect); - - context->view = self; - context->callbackID = callback->callbackID(); - - _webFrame->page()->drawRectToImage(_webFrame.get(), PrintInfo([_printOperation printInfo]), scaledPrintingRect, imageSize, callback.get()); - return; - } - } - - // FIXME: Draw a placeholder - return; - } - - RefPtr<ShareableBitmap> bitmap = pagePreviewIterator->value; - CGContextRef cgContext = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]); - - GraphicsContext context(cgContext); - GraphicsContextStateSaver stateSaver(context); - - bitmap->paint(context, _webFrame->page()->deviceScaleFactor(), IntPoint(nsRect.origin), bitmap->bounds()); -} - -- (void)drawRect:(NSRect)nsRect -{ - LOG(View, "WKPrintingView %p printing rect x:%g, y:%g, width:%g, height:%g%s", self, nsRect.origin.x, nsRect.origin.y, nsRect.size.width, nsRect.size.height, [self _isPrintingPreview] ? " for preview" : ""); - - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - - if (!_webFrame->page()) - return; - - if ([self _isPrintingPreview]) { - [self _drawPreview:nsRect]; - return; - } - - ASSERT(!isMainThread()); - 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()]); - } - - unsigned printedPageNumber = [self _pageForRect:nsRect] - [self _firstPrintedPageNumber]; - [self _drawPDFDocument:_printedPagesPDFDocument.get() page:printedPageNumber atPoint:NSMakePoint(nsRect.origin.x, nsRect.origin.y)]; -} - -- (void)_drawPageBorderWithSizeOnMainThread:(NSSize)borderSize -{ - ASSERT(isMainThread()); - - // When printing from a secondary thread, the main thread doesn't have graphics context and printing operation set up. - NSGraphicsContext *currentContext = [NSGraphicsContext currentContext]; - [NSGraphicsContext setCurrentContext:[_printOperation context]]; - - ASSERT(![NSPrintOperation currentOperation]); - [NSPrintOperation setCurrentOperation:_printOperation]; - - [self drawPageBorderWithSize:borderSize]; - - [NSPrintOperation setCurrentOperation:nil]; - [NSGraphicsContext setCurrentContext:currentContext]; -} - -- (void)drawPageBorderWithSize:(NSSize)borderSize -{ - ASSERT(NSEqualSizes(borderSize, [[_printOperation printInfo] paperSize])); - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - - if (!isMainThread()) { - // Don't call the client from a secondary thread. - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[WKPrintingView instanceMethodSignatureForSelector:@selector(_drawPageBorderWithSizeOnMainThread:)]]; - [invocation setSelector:@selector(_drawPageBorderWithSizeOnMainThread:)]; - [invocation setArgument:&borderSize atIndex:2]; - [invocation performSelectorOnMainThread:@selector(invokeWithTarget:) withObject:self waitUntilDone:YES]; - return; - } - - if (!_webFrame->page()) - return; - - // The header and footer rect height scales with the page, but the width is always - // all the way across the printed page (inset by printing margins). - NSPrintInfo *printInfo = [_printOperation printInfo]; - CGFloat scale = [printInfo scalingFactor]; - NSSize paperSize = [printInfo paperSize]; - CGFloat headerFooterLeft = [printInfo leftMargin] / scale; - CGFloat headerFooterWidth = (paperSize.width - ([printInfo leftMargin] + [printInfo rightMargin])) / scale; - NSRect footerRect = NSMakeRect(headerFooterLeft, [printInfo bottomMargin] / scale - _webFrame->page()->footerHeight(_webFrame.get()), headerFooterWidth, _webFrame->page()->footerHeight(_webFrame.get())); - NSRect headerRect = NSMakeRect(headerFooterLeft, (paperSize.height - [printInfo topMargin]) / scale, headerFooterWidth, _webFrame->page()->headerHeight(_webFrame.get())); - - NSGraphicsContext *currentContext = [NSGraphicsContext currentContext]; - [currentContext saveGraphicsState]; - NSRectClip(headerRect); - _webFrame->page()->drawHeader(_webFrame.get(), headerRect); - [currentContext restoreGraphicsState]; - - [currentContext saveGraphicsState]; - NSRectClip(footerRect); - _webFrame->page()->drawFooter(_webFrame.get(), footerRect); - [currentContext restoreGraphicsState]; -} - -- (NSRect)rectForPage:(NSInteger)page -{ - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - if (![self _hasPageRects]) { - LOG(View, "-[WKPrintingView %p rectForPage:%d] - data is not yet available", self, (int)page); - if (!_webFrame->page()) { - // We may have not told AppKit how many pages there are, so it will try to print until a null rect is returned. - return NSMakeRect(0, 0, 0, 0); - } - // We must be still calculating the page range. - ASSERT(_expectedComputedPagesCallback); - return NSMakeRect(0, 0, 1, 1); - } - - // If Web process crashes while computing page rects, we never tell AppKit how many pages there are. - // Returning a null rect prevents selecting non-existent pages in preview dialog. - if (static_cast<unsigned>(page) > _printingPageRects.size()) { - ASSERT(!_webFrame->page()); - return NSMakeRect(0, 0, 0, 0); - } - - IntRect rect = _printingPageRects[page - 1]; - rect.scale(_totalScaleFactorForPrinting); - LOG(View, "-[WKPrintingView %p rectForPage:%d] -> x %d, y %d, width %d, height %d", self, (int)page, rect.x(), rect.y(), rect.width(), rect.height()); - return rect; -} - -// Temporary workaround for <rdar://problem/8944535>. Force correct printout positioning. -- (NSPoint)locationOfPrintRect:(NSRect)aRect -{ - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - return NSMakePoint([[_printOperation printInfo] leftMargin], [[_printOperation printInfo] bottomMargin]); -} - -- (void)beginDocument -{ - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - - // Forcing preview update gets us here, but page setup hasn't actually changed. - if (isForcingPreviewUpdate) - return; - - LOG(View, "-[WKPrintingView %p beginDocument]", self); - - [super beginDocument]; - - [self _suspendAutodisplay]; -} - -- (void)endDocument -{ - ASSERT(_printOperation == [NSPrintOperation currentOperation]); - - // Forcing preview update gets us here, but page setup hasn't actually changed. - if (isForcingPreviewUpdate) - return; - - LOG(View, "-[WKPrintingView %p endDocument] - clearing cached data", self); - - // Both existing data and pending responses are now obsolete. - _printingPageRects.clear(); - _totalScaleFactorForPrinting = 1; - _pagePreviews.clear(); - _printedPagesData.clear(); - _printedPagesPDFDocument = nullptr; - _expectedComputedPagesCallback = 0; - _expectedPreviewCallbacks.clear(); - _latestExpectedPreviewCallback = 0; - _expectedPrintCallback = 0; - - [self _delayedResumeAutodisplay]; - - [super endDocument]; -} -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h b/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h deleted file mode 100644 index 95944814a..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <Foundation/Foundation.h> -#import <WebKit2/WKBase.h> - -@class WKProcessGroup, WKProcessGroupData, WKConnection; - -@protocol WKProcessGroupDelegate <NSObject> -@optional - -- (id)processGroupWillCreateConnectionToWebProcessPlugIn:(WKProcessGroup *)processGroup; - -@required - -- (void)processGroup:(WKProcessGroup *)processGroup didCreateConnectionToWebProcessPlugIn:(WKConnection *)connection; - -@end - -WK_EXPORT -@interface WKProcessGroup : NSObject { -@private - WKProcessGroupData *_data; -} - -- (id)initWithInjectedBundleURL:(NSURL *)bundleURL; - - -#pragma mark Delegates - -@property(assign) id<WKProcessGroupDelegate> delegate; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm b/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm deleted file mode 100644 index 044716b82..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKProcessGroup.mm +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKProcessGroup.h" -#import "WKProcessGroupPrivate.h" - -#import "ObjCObjectGraph.h" -#import "WKConnectionInternal.h" -#import "WKContext.h" -#import "WKRetainPtr.h" -#import "WKStringCF.h" -#import <wtf/RetainPtr.h> - -@interface WKProcessGroupData : NSObject { -@public - // Underlying context object. - WKRetainPtr<WKContextRef> _contextRef; - - // Delegate for callbacks. - id<WKProcessGroupDelegate> _delegate; -} -@end - -@implementation WKProcessGroupData -@end - -@implementation WKProcessGroup - -static void didCreateConnection(WKContextRef, WKConnectionRef connectionRef, const void* clientInfo) -{ - WKProcessGroup *processGroup = (WKProcessGroup *)clientInfo; - if ([processGroup.delegate respondsToSelector:@selector(processGroup:didCreateConnectionToWebProcessPlugIn:)]) { - RetainPtr<WKConnection> connection = adoptNS([[WKConnection alloc] _initWithConnectionRef:connectionRef]); - [processGroup.delegate processGroup:processGroup didCreateConnectionToWebProcessPlugIn:connection.get()]; - } -} - -static void setUpConnectionClient(WKProcessGroup *processGroup, WKContextRef contextRef) -{ - WKContextConnectionClient connectionClient; - memset(&connectionClient, 0, sizeof(connectionClient)); - - connectionClient.version = kWKContextConnectionClientCurrentVersion; - connectionClient.clientInfo = processGroup; - connectionClient.didCreateConnection = didCreateConnection; - - 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]; -} - -- (id)initWithInjectedBundleURL:(NSURL *)bundleURL -{ - self = [super init]; - if (!self) - return nil; - - _data = [[WKProcessGroupData alloc] init]; - - if (bundleURL) - _data->_contextRef = adoptWK(WKContextCreateWithInjectedBundlePath(adoptWK(WKStringCreateWithCFString((CFStringRef)[bundleURL path])).get())); - else - _data->_contextRef = adoptWK(WKContextCreate()); - - setUpConnectionClient(self, _data->_contextRef.get()); - setUpInectedBundleClient(self, _data->_contextRef.get()); - - return self; -} - -- (void)dealloc -{ - WKContextSetConnectionClient(_data->_contextRef.get(), 0); - WKContextSetInjectedBundleClient(_data->_contextRef.get(), 0); - - [_data release]; - [super dealloc]; -} - -- (id<WKProcessGroupDelegate>)delegate -{ - return _data->_delegate; -} - -- (void)setDelegate:(id<WKProcessGroupDelegate>)delegate -{ - _data->_delegate = delegate; -} - -@end - -@implementation WKProcessGroup (Private) - -- (WKContextRef)_contextRef -{ - return _data->_contextRef.get(); -} - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKTextInputWindowController.mm b/Source/WebKit2/UIProcess/API/mac/WKTextInputWindowController.mm deleted file mode 100644 index 8834dcd33..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKTextInputWindowController.mm +++ /dev/null @@ -1,205 +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. - */ - -#import "config.h" -#import "WKTextInputWindowController.h" - -#if USE(APPKIT) - -#import <WebKitSystemInterface.h> - -@interface WKTextInputView : NSTextView { -} -@end - -@implementation WKTextInputView - -- (NSArray *)validAttributesForMarkedText -{ - // Let TSM know that a bottom input window would be created for marked text. - NSArray *regularAttributes = [super validAttributesForMarkedText]; - NSMutableArray *floatingWindowAttributes = [NSMutableArray arrayWithArray:regularAttributes]; - [floatingWindowAttributes addObject:@"__NSUsesFloatingInputWindow"]; - return floatingWindowAttributes; -} - -@end - -@interface WKTextInputPanel : NSPanel { - NSTextView *_inputTextView; -} - -- (NSTextInputContext *)_inputContext; -- (BOOL)_interpretKeyEvent:(NSEvent *)event usingLegacyCocoaTextInput:(BOOL)usingLegacyCocoaTextInput string:(NSString **)string; - -- (BOOL)_hasMarkedText; -- (void)_unmarkText; - -@end - -#define inputWindowHeight 20 - -@implementation WKTextInputPanel - -- (void)dealloc -{ - [[NSNotificationCenter defaultCenter] removeObserver:self]; - - [_inputTextView release]; - - [super dealloc]; -} - -- (id)init -{ - self = [super initWithContentRect:NSZeroRect styleMask:WKGetInputPanelWindowStyle() backing:NSBackingStoreBuffered defer:YES]; - if (!self) - return nil; - - // Set the frame size. - NSRect visibleFrame = [[NSScreen mainScreen] visibleFrame]; - NSRect frame = NSMakeRect(visibleFrame.origin.x, visibleFrame.origin.y, visibleFrame.size.width, inputWindowHeight); - - [self setFrame:frame display:NO]; - - _inputTextView = [[WKTextInputView alloc] initWithFrame:[(NSView *)self.contentView frame]]; - _inputTextView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable | NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin; - - NSScrollView* scrollView = [[NSScrollView alloc] initWithFrame:[(NSView *)self.contentView frame]]; - scrollView.documentView = _inputTextView; - self.contentView = scrollView; - [scrollView release]; - - [self setFloatingPanel:YES]; - - return self; -} - -- (void)_unmarkText -{ - [_inputTextView setString:@""]; - [self orderOut:nil]; -} - -- (BOOL)_interpretKeyEvent:(NSEvent *)event usingLegacyCocoaTextInput:(BOOL)usingLegacyCocoaTextInput string:(NSString **)string -{ - BOOL hadMarkedText = [_inputTextView hasMarkedText]; - - *string = nil; - - // Let TSM know that a bottom input window would be created for marked text. - // FIXME: Can be removed once we can rely on __NSUsesFloatingInputWindow (or a better API) being available everywhere. - EventRef carbonEvent = static_cast<EventRef>(const_cast<void*>([event eventRef])); - if (carbonEvent) { - Boolean ignorePAH = true; - SetEventParameter(carbonEvent, 'iPAH', typeBoolean, sizeof(ignorePAH), &ignorePAH); - } - - if (![[_inputTextView inputContext] handleEvent:event]) - return NO; - - if ([_inputTextView hasMarkedText]) { - // Don't show the input method window for dead keys - if ([[event characters] length] > 0) - [self orderFront:nil]; - - return YES; - } - - bool shouldReturnTextString = hadMarkedText; - - // In the updated Cocoa text input model spec, we always want to return the text even if the text view didn't have marked text. - if (!usingLegacyCocoaTextInput) - shouldReturnTextString = true; - - if (shouldReturnTextString) { - [self orderOut:nil]; - - NSString *text = [[_inputTextView textStorage] string]; - if ([text length] > 0) - *string = [[text copy] autorelease]; - } - - [_inputTextView setString:@""]; - return hadMarkedText; -} - -- (NSTextInputContext *)_inputContext -{ - return [_inputTextView inputContext]; -} - -- (BOOL)_hasMarkedText -{ - return [_inputTextView hasMarkedText]; -} - -@end - -@implementation WKTextInputWindowController - -+ (WKTextInputWindowController *)sharedTextInputWindowController -{ - static WKTextInputWindowController *textInputWindowController; - if (!textInputWindowController) - textInputWindowController = [[WKTextInputWindowController alloc] init]; - - return textInputWindowController; -} - -- (id)init -{ - self = [super init]; - if (!self) - return nil; - - _panel = [[WKTextInputPanel alloc] init]; - - return self; -} - -- (NSTextInputContext *)inputContext -{ - return [_panel _inputContext]; -} - -- (BOOL)hasMarkedText -{ - return [_panel _hasMarkedText]; -} - -- (BOOL)interpretKeyEvent:(NSEvent *)event usingLegacyCocoaTextInput:(BOOL)usingLegacyCocoaTextInput string:(NSString **)string -{ - return [_panel _interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:string]; -} - -- (void)unmarkText -{ - [_panel _unmarkText]; -} - -@end - -#endif // USE(APPKIT) diff --git a/Source/WebKit2/UIProcess/API/mac/WKView.h b/Source/WebKit2/UIProcess/API/mac/WKView.h deleted file mode 100644 index fec8d6380..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKView.h +++ /dev/null @@ -1,49 +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. - */ - -#import <Cocoa/Cocoa.h> -#import <WebKit2/WKBase.h> - -@class WKBrowsingContextController; -@class WKBrowsingContextGroup; -@class WKProcessGroup; -@class WKViewData; - -WK_EXPORT -@interface WKView : NSView <NSTextInputClient> { -@private - WKViewData *_data; - unsigned _unused; -} - -- (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup; -- (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView; - -@property(readonly) WKBrowsingContextController *browsingContextController; - -@property BOOL drawsBackground; -@property BOOL drawsTransparentBackground; - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKView.mm b/Source/WebKit2/UIProcess/API/mac/WKView.mm deleted file mode 100644 index 1d8760988..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKView.mm +++ /dev/null @@ -1,3487 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKView.h" - -#if USE(DICTATION_ALTERNATIVES) -#import <AppKit/NSTextAlternatives.h> -#import <AppKit/NSAttributedString.h> -#endif - -#import "AttributedString.h" -#import "ColorSpaceData.h" -#import "DataReference.h" -#import "DrawingAreaProxyImpl.h" -#import "EditorState.h" -#import "FindIndicator.h" -#import "FindIndicatorWindow.h" -#import "LayerTreeContext.h" -#import "Logging.h" -#import "NativeWebKeyboardEvent.h" -#import "NativeWebMouseEvent.h" -#import "NativeWebWheelEvent.h" -#import "PageClientImpl.h" -#import "PasteboardTypes.h" -#import "RemoteLayerTreeDrawingAreaProxy.h" -#import "StringUtilities.h" -#import "TextChecker.h" -#import "TextCheckerState.h" -#import "TiledCoreAnimationDrawingAreaProxy.h" -#import "WKAPICast.h" -#import "WKFullScreenWindowController.h" -#import "WKPrintingView.h" -#import "WKStringCF.h" -#import "WKTextInputWindowController.h" -#import "WKViewInternal.h" -#import "WKViewPrivate.h" -#import "WebContext.h" -#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> -#import <WebCore/DragSession.h> -#import <WebCore/FloatRect.h> -#import <WebCore/Image.h> -#import <WebCore/IntRect.h> -#import <WebCore/KeyboardEvent.h> -#import <WebCore/LocalizedStrings.h> -#import <WebCore/PlatformEventFactoryMac.h> -#import <WebCore/PlatformScreen.h> -#import <WebCore/Region.h> -#import <WebCore/RunLoop.h> -#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> -#import <wtf/RefPtr.h> -#import <wtf/RetainPtr.h> - -/* API internals. */ -#import "WKBrowsingContextControllerInternal.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; -- (void)_setCurrentEvent:(NSEvent *)event; -@end - -@interface NSObject (WKNSTextInputContextDetails) -- (BOOL)wantsToHandleMouseEvents; -- (BOOL)handleMouseEvent:(NSEvent *)event; -@end - -@interface NSWindow (WKNSWindowDetails) -- (NSRect)_intersectBottomCornersWithRect:(NSRect)viewRect; -- (void)_maskRoundedBottomCorners:(NSRect)clipRect; -@end - -using namespace WebKit; -using namespace WebCore; - -namespace WebKit { - -typedef id <NSValidatedUserInterfaceItem> ValidationItem; -typedef Vector<RetainPtr<ValidationItem>> ValidationVector; -typedef HashMap<String, ValidationVector> ValidationMap; - -} - -struct WKViewInterpretKeyEventsParameters { - bool eventInterpretationHadSideEffects; - bool consumedByIM; - bool executingSavedKeypressCommands; - Vector<KeypressCommand>* commands; -}; - -@interface WKView () -- (void)_accessibilityRegisterUIProcessTokens; -- (void)_disableComplexTextInputIfNecessary; -- (float)_intrinsicDeviceScaleFactor; -- (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent; -- (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 { -@public - OwnPtr<PageClientImpl> _pageClient; - RefPtr<WebPageProxy> _page; - - // Cache of the associated WKBrowsingContextController. - RetainPtr<WKBrowsingContextController> _browsingContextController; - - // For ToolTips. - NSToolTipTag _lastToolTipTag; - id _trackingRectOwner; - void* _trackingRectUserData; - - RetainPtr<NSView> _layerHostingView; - - RetainPtr<id> _remoteAccessibilityChild; - - // For asynchronous validation. - ValidationMap _validationMap; - - OwnPtr<FindIndicatorWindow> _findIndicatorWindow; - // We keep here the event when resending it to - // the application to distinguish the case of a new event from one - // that has been already sent to WebCore. - RetainPtr<NSEvent> _keyDownEventBeingResent; - WKViewInterpretKeyEventsParameters* _interpretKeyEventsParameters; - - NSSize _resizeScrollOffset; - - // The identifier of the plug-in we want to send complex text input to, or 0 if there is none. - uint64_t _pluginComplexTextInputIdentifier; - - // The state of complex text input for the plug-in. - PluginComplexTextInputState _pluginComplexTextInputState; - - bool _inBecomeFirstResponder; - bool _inResignFirstResponder; - NSEvent *_mouseDownEvent; - BOOL _ignoringMouseDraggedEvents; - - id _flagsChangedEventMonitor; -#if ENABLE(GESTURE_EVENTS) - id _endGestureMonitor; -#endif - -#if ENABLE(FULLSCREEN_API) - RetainPtr<WKFullScreenWindowController> _fullScreenWindowController; -#endif - - BOOL _hasSpellCheckerDocumentTag; - NSInteger _spellCheckerDocumentTag; - - BOOL _inSecureInputState; - - 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. - // We use this flag to determine when we need to paint the background (white or clear) - // when the web process is unresponsive or takes too long to paint. - BOOL _windowHasValidBackingStore; - - RetainPtr<NSColorSpace> _colorSpace; - - RefPtr<WebCore::Image> _promisedImage; - 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 - -@implementation WKViewData -@end - -@interface WKResponderChainSink : NSResponder { - NSResponder *_lastResponderInChain; - bool _didReceiveUnhandledCommand; -} -- (id)initWithResponderChain:(NSResponder *)chain; -- (void)detach; -- (bool)didReceiveUnhandledCommand; -@end - -@interface WKFlippedView : NSView -@end - -@implementation WKFlippedView - -- (BOOL)isFlipped -{ - return YES; -} - -@end - -@implementation WKView - -- (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup -{ - return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:nil]; -} - -- (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView -{ - return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:relatedView ? toAPI(relatedView->_data->_page.get()) : nil]; -} - -- (void)dealloc -{ - _data->_page->close(); - - ASSERT(!_data->_inSecureInputState); - - [_data release]; - _data = nil; - - NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter]; - [workspaceNotificationCenter removeObserver:self name:NSWorkspaceActiveSpaceDidChangeNotification object:nil]; - - WebContext::statistics().wkViewCount--; - - [super dealloc]; -} - -- (WKBrowsingContextController *)browsingContextController -{ - if (!_data->_browsingContextController) - _data->_browsingContextController = adoptNS([[WKBrowsingContextController alloc] _initWithPageRef:[self pageRef]]); - return _data->_browsingContextController.get(); -} - -- (void)setDrawsBackground:(BOOL)drawsBackground -{ - _data->_page->setDrawsBackground(drawsBackground); -} - -- (BOOL)drawsBackground -{ - return _data->_page->drawsBackground(); -} - -- (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground -{ - _data->_page->setDrawsTransparentBackground(drawsTransparentBackground); -} - -- (BOOL)drawsTransparentBackground -{ - return _data->_page->drawsTransparentBackground(); -} - -- (BOOL)acceptsFirstResponder -{ - return YES; -} - -- (BOOL)becomeFirstResponder -{ - NSSelectionDirection direction = [[self window] keyViewSelectionDirection]; - - _data->_inBecomeFirstResponder = true; - - [self _updateSecureInputState]; - _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused); - - _data->_inBecomeFirstResponder = false; - - if (direction != NSDirectSelection) { - NSEvent *event = [NSApp currentEvent]; - NSEvent *keyboardEvent = nil; - if ([event type] == NSKeyDown || [event type] == NSKeyUp) - keyboardEvent = event; - _data->_page->setInitialFocus(direction == NSSelectingNext, keyboardEvent != nil, NativeWebKeyboardEvent(keyboardEvent, self)); - } - return YES; -} - -- (BOOL)resignFirstResponder -{ - _data->_inResignFirstResponder = true; - - if (_data->_page->editorState().hasComposition && !_data->_page->editorState().shouldIgnoreCompositionSelectionChange) - _data->_page->cancelComposition(); - - [self _notifyInputContextAboutDiscardedComposition]; - - [self _resetSecureInputState]; - - if (!_data->_page->maintainsInactiveSelection()) - _data->_page->clearSelection(); - - _data->_page->viewStateDidChange(WebPageProxy::ViewIsFocused); - - _data->_inResignFirstResponder = false; - - return YES; -} - -- (void)viewWillStartLiveResize -{ - _data->_page->viewWillStartLiveResize(); -} - -- (void)viewDidEndLiveResize -{ - _data->_page->viewWillEndLiveResize(); -} - -- (BOOL)isFlipped -{ - return YES; -} - -- (NSSize)intrinsicContentSize -{ - 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; - - 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 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 -{ - 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 -{ - // Hide the find indicator. - _data->_findIndicatorWindow = nullptr; - - // Update the view frame. - if ([self window]) - [self _updateWindowAndViewFrames]; - - [super renewGState]; -} - -- (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState -{ - _data->_pluginComplexTextInputState = pluginComplexTextInputState; - - if (_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled) - return; - - // Send back an empty string to the plug-in. This will disable text input. - _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, String()); -} - -typedef HashMap<SEL, String> SelectorNameMap; - -// Map selectors into Editor command names. -// This is not needed for any selectors that have the same name as the Editor command. -static const SelectorNameMap* createSelectorExceptionMap() -{ - SelectorNameMap* map = new HashMap<SEL, String>; - - map->add(@selector(insertNewlineIgnoringFieldEditor:), "InsertNewline"); - map->add(@selector(insertParagraphSeparator:), "InsertNewline"); - map->add(@selector(insertTabIgnoringFieldEditor:), "InsertTab"); - map->add(@selector(pageDown:), "MovePageDown"); - map->add(@selector(pageDownAndModifySelection:), "MovePageDownAndModifySelection"); - map->add(@selector(pageUp:), "MovePageUp"); - map->add(@selector(pageUpAndModifySelection:), "MovePageUpAndModifySelection"); - map->add(@selector(scrollPageDown:), "ScrollPageForward"); - map->add(@selector(scrollPageUp:), "ScrollPageBackward"); - - return map; -} - -static String commandNameForSelector(SEL selector) -{ - // Check the exception map first. - static const SelectorNameMap* exceptionMap = createSelectorExceptionMap(); - SelectorNameMap::const_iterator it = exceptionMap->find(selector); - if (it != exceptionMap->end()) - return it->value; - - // Remove the trailing colon. - // No need to capitalize the command name since Editor command names are - // not case sensitive. - const char* selectorName = sel_getName(selector); - size_t selectorNameLength = strlen(selectorName); - if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':') - return String(); - return String(selectorName, selectorNameLength - 1); -} - -// Editing commands - -#define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_page->executeEditCommand(commandNameForSelector(_cmd)); } - -WEBCORE_COMMAND(alignCenter) -WEBCORE_COMMAND(alignJustified) -WEBCORE_COMMAND(alignLeft) -WEBCORE_COMMAND(alignRight) -WEBCORE_COMMAND(copy) -WEBCORE_COMMAND(cut) -WEBCORE_COMMAND(delete) -WEBCORE_COMMAND(deleteBackward) -WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter) -WEBCORE_COMMAND(deleteForward) -WEBCORE_COMMAND(deleteToBeginningOfLine) -WEBCORE_COMMAND(deleteToBeginningOfParagraph) -WEBCORE_COMMAND(deleteToEndOfLine) -WEBCORE_COMMAND(deleteToEndOfParagraph) -WEBCORE_COMMAND(deleteToMark) -WEBCORE_COMMAND(deleteWordBackward) -WEBCORE_COMMAND(deleteWordForward) -WEBCORE_COMMAND(ignoreSpelling) -WEBCORE_COMMAND(indent) -WEBCORE_COMMAND(insertBacktab) -WEBCORE_COMMAND(insertLineBreak) -WEBCORE_COMMAND(insertNewline) -WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor) -WEBCORE_COMMAND(insertParagraphSeparator) -WEBCORE_COMMAND(insertTab) -WEBCORE_COMMAND(insertTabIgnoringFieldEditor) -WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight) -WEBCORE_COMMAND(makeTextWritingDirectionNatural) -WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft) -WEBCORE_COMMAND(moveBackward) -WEBCORE_COMMAND(moveBackwardAndModifySelection) -WEBCORE_COMMAND(moveDown) -WEBCORE_COMMAND(moveDownAndModifySelection) -WEBCORE_COMMAND(moveForward) -WEBCORE_COMMAND(moveForwardAndModifySelection) -WEBCORE_COMMAND(moveLeft) -WEBCORE_COMMAND(moveLeftAndModifySelection) -WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection) -WEBCORE_COMMAND(moveParagraphForwardAndModifySelection) -WEBCORE_COMMAND(moveRight) -WEBCORE_COMMAND(moveRightAndModifySelection) -WEBCORE_COMMAND(moveToBeginningOfDocument) -WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection) -WEBCORE_COMMAND(moveToBeginningOfLine) -WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection) -WEBCORE_COMMAND(moveToBeginningOfParagraph) -WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection) -WEBCORE_COMMAND(moveToBeginningOfSentence) -WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection) -WEBCORE_COMMAND(moveToEndOfDocument) -WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection) -WEBCORE_COMMAND(moveToEndOfLine) -WEBCORE_COMMAND(moveToEndOfLineAndModifySelection) -WEBCORE_COMMAND(moveToEndOfParagraph) -WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection) -WEBCORE_COMMAND(moveToEndOfSentence) -WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection) -WEBCORE_COMMAND(moveToLeftEndOfLine) -WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection) -WEBCORE_COMMAND(moveToRightEndOfLine) -WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection) -WEBCORE_COMMAND(moveUp) -WEBCORE_COMMAND(moveUpAndModifySelection) -WEBCORE_COMMAND(moveWordBackward) -WEBCORE_COMMAND(moveWordBackwardAndModifySelection) -WEBCORE_COMMAND(moveWordForward) -WEBCORE_COMMAND(moveWordForwardAndModifySelection) -WEBCORE_COMMAND(moveWordLeft) -WEBCORE_COMMAND(moveWordLeftAndModifySelection) -WEBCORE_COMMAND(moveWordRight) -WEBCORE_COMMAND(moveWordRightAndModifySelection) -WEBCORE_COMMAND(outdent) -WEBCORE_COMMAND(pageDown) -WEBCORE_COMMAND(pageDownAndModifySelection) -WEBCORE_COMMAND(pageUp) -WEBCORE_COMMAND(pageUpAndModifySelection) -WEBCORE_COMMAND(paste) -WEBCORE_COMMAND(pasteAsPlainText) -WEBCORE_COMMAND(scrollPageDown) -WEBCORE_COMMAND(scrollPageUp) -WEBCORE_COMMAND(scrollLineDown) -WEBCORE_COMMAND(scrollLineUp) -WEBCORE_COMMAND(scrollToBeginningOfDocument) -WEBCORE_COMMAND(scrollToEndOfDocument) -WEBCORE_COMMAND(selectAll) -WEBCORE_COMMAND(selectLine) -WEBCORE_COMMAND(selectParagraph) -WEBCORE_COMMAND(selectSentence) -WEBCORE_COMMAND(selectToMark) -WEBCORE_COMMAND(selectWord) -WEBCORE_COMMAND(setMark) -WEBCORE_COMMAND(subscript) -WEBCORE_COMMAND(superscript) -WEBCORE_COMMAND(swapWithMark) -WEBCORE_COMMAND(takeFindStringFromSelection) -WEBCORE_COMMAND(transpose) -WEBCORE_COMMAND(underline) -WEBCORE_COMMAND(unscript) -WEBCORE_COMMAND(yank) -WEBCORE_COMMAND(yankAndSelect) - -#undef WEBCORE_COMMAND - -// This method is needed to support Mac OS X services. - -- (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types -{ - size_t numTypes = [types count]; - [pasteboard declareTypes:types owner:nil]; - for (size_t i = 0; i < numTypes; ++i) { - if ([[types objectAtIndex:i] isEqualTo:NSStringPboardType]) - [pasteboard setString:_data->_page->stringSelectionForPasteboard() forType:NSStringPboardType]; - else { - RefPtr<SharedBuffer> buffer = _data->_page->dataSelectionForPasteboard([types objectAtIndex:i]); - [pasteboard setData:buffer ? [buffer->createNSData() autorelease] : nil forType:[types objectAtIndex:i]]; - } - } - return YES; -} - -- (void)centerSelectionInVisibleArea:(id)sender -{ - _data->_page->centerSelectionInVisibleArea(); -} - -// This method is needed to support Mac OS X services. - -- (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType -{ - 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] && editorState.isContentEditable) { - // We can insert strings in any editable context. We can insert other types, like images, only in rich edit contexts. - isValidReturnType = editorState.isContentRichlyEditable || [returnType isEqualToString:NSStringPboardType]; - } - if (isValidSendType && isValidReturnType) - return self; - return [[self nextResponder] validRequestorForSendType:sendType returnType:returnType]; -} - -// This method is needed to support Mac OS X services. - -- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard -{ - return _data->_page->readSelectionFromPasteboard([pasteboard name]); -} - -/* - -When possible, editing-related methods should be implemented in WebCore with the -EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing -individual methods here with Mac-specific code. - -Editing-related methods still unimplemented that are implemented in WebKit1: - -- (void)capitalizeWord:(id)sender; -- (void)changeFont:(id)sender; -- (void)complete:(id)sender; -- (void)copyFont:(id)sender; -- (void)lowercaseWord:(id)sender; -- (void)makeBaseWritingDirectionLeftToRight:(id)sender; -- (void)makeBaseWritingDirectionNatural:(id)sender; -- (void)makeBaseWritingDirectionRightToLeft:(id)sender; -- (void)pasteFont:(id)sender; -- (void)scrollLineDown:(id)sender; -- (void)scrollLineUp:(id)sender; -- (void)showGuessPanel:(id)sender; -- (void)uppercaseWord:(id)sender; - -Some other editing-related methods still unimplemented: - -- (void)changeCaseOfLetter:(id)sender; -- (void)copyRuler:(id)sender; -- (void)insertContainerBreak:(id)sender; -- (void)insertDoubleQuoteIgnoringSubstitution:(id)sender; -- (void)insertSingleQuoteIgnoringSubstitution:(id)sender; -- (void)pasteRuler:(id)sender; -- (void)toggleRuler:(id)sender; -- (void)transposeWords:(id)sender; - -*/ - -// Menu items validation - -static NSMenuItem *menuItem(id <NSValidatedUserInterfaceItem> item) -{ - if (![(NSObject *)item isKindOfClass:[NSMenuItem class]]) - return nil; - return (NSMenuItem *)item; -} - -static NSToolbarItem *toolbarItem(id <NSValidatedUserInterfaceItem> item) -{ - if (![(NSObject *)item isKindOfClass:[NSToolbarItem class]]) - return nil; - return (NSToolbarItem *)item; -} - -static void validateCommandCallback(WKStringRef commandName, bool isEnabled, int32_t state, WKErrorRef error, void* context) -{ - // If the process exits before the command can be validated, we'll be called back with an error. - if (error) - return; - - WKView* wkView = static_cast<WKView*>(context); - ASSERT(wkView); - - [wkView _setUserInterfaceItemState:nsStringFromWebCoreString(toImpl(commandName)->string()) enabled:isEnabled state:state]; -} - -- (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item -{ - SEL action = [item action]; - - if (action == @selector(showGuessPanel:)) { - if (NSMenuItem *menuItem = ::menuItem(item)) - [menuItem setTitle:contextMenuItemTagShowSpellingPanel(![[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible])]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(checkSpelling:) || action == @selector(changeSpelling:)) - return _data->_page->editorState().isContentEditable; - - if (action == @selector(toggleContinuousSpellChecking:)) { - bool enabled = TextChecker::isContinuousSpellCheckingAllowed(); - bool checked = enabled && TextChecker::state().isContinuousSpellCheckingEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return enabled; - } - - if (action == @selector(toggleGrammarChecking:)) { - bool checked = TextChecker::state().isGrammarCheckingEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return YES; - } - - if (action == @selector(toggleAutomaticSpellingCorrection:)) { - bool checked = TextChecker::state().isAutomaticSpellingCorrectionEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(orderFrontSubstitutionsPanel:)) { - if (NSMenuItem *menuItem = ::menuItem(item)) - [menuItem setTitle:contextMenuItemTagShowSubstitutions(![[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible])]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(toggleSmartInsertDelete:)) { - bool checked = _data->_page->isSmartInsertDeleteEnabled(); - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(toggleAutomaticQuoteSubstitution:)) { - bool checked = TextChecker::state().isAutomaticQuoteSubstitutionEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(toggleAutomaticDashSubstitution:)) { - bool checked = TextChecker::state().isAutomaticDashSubstitutionEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(toggleAutomaticLinkDetection:)) { - bool checked = TextChecker::state().isAutomaticLinkDetectionEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(toggleAutomaticTextReplacement:)) { - bool checked = TextChecker::state().isAutomaticTextReplacementEnabled; - [menuItem(item) setState:checked ? NSOnState : NSOffState]; - return _data->_page->editorState().isContentEditable; - } - - if (action == @selector(uppercaseWord:) || action == @selector(lowercaseWord:) || action == @selector(capitalizeWord:)) - return _data->_page->editorState().selectionIsRange && _data->_page->editorState().isContentEditable; - - if (action == @selector(stopSpeaking:)) - return [NSApp isSpeaking]; - - // The centerSelectionInVisibleArea: selector is enabled if there's a selection range or if there's an insertion point in an editable area. - if (action == @selector(centerSelectionInVisibleArea:)) - return _data->_page->editorState().selectionIsRange || (_data->_page->editorState().isContentEditable && !_data->_page->editorState().selectionIsNone); - - // Next, handle editor commands. Start by returning YES for anything that is not an editor command. - // Returning YES is the default thing to do in an AppKit validate method for any selector that is not recognized. - String commandName = commandNameForSelector([item action]); - if (!Editor::commandIsSupportedFromMenuOrKeyBinding(commandName)) - return YES; - - // Add this item to the vector of items for a given command that are awaiting validation. - ValidationMap::AddResult addResult = _data->_validationMap.add(commandName, ValidationVector()); - addResult.iterator->value.append(item); - if (addResult.isNewEntry) { - // If we are not already awaiting validation for this command, start the asynchronous validation process. - // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time - // we asked for the same command; there is no guarantee the answer is still valid. - _data->_page->validateCommand(commandName, ValidateCommandCallback::create(self, validateCommandCallback)); - } - - // Treat as enabled until we get the result back from the web process and _setUserInterfaceItemState is called. - // FIXME <rdar://problem/8803459>: This means disabled items will flash enabled at first for a moment. - // But returning NO here would be worse; that would make keyboard commands such as command-C fail. - return YES; -} - -static void speakString(WKStringRef string, WKErrorRef error, void*) -{ - if (error) - return; - if (!string) - return; - - NSString *convertedString = toImpl(string)->string(); - [NSApp speakString:convertedString]; -} - -- (IBAction)startSpeaking:(id)sender -{ - _data->_page->getSelectionOrContentsAsString(StringCallback::create(0, speakString)); -} - -- (IBAction)stopSpeaking:(id)sender -{ - [NSApp stopSpeaking:sender]; -} - -- (IBAction)showGuessPanel:(id)sender -{ - NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker]; - if (!checker) { - LOG_ERROR("No NSSpellChecker"); - return; - } - - NSPanel *spellingPanel = [checker spellingPanel]; - if ([spellingPanel isVisible]) { - [spellingPanel orderOut:sender]; - return; - } - - _data->_page->advanceToNextMisspelling(true); - [spellingPanel orderFront:sender]; -} - -- (IBAction)checkSpelling:(id)sender -{ - _data->_page->advanceToNextMisspelling(false); -} - -- (void)changeSpelling:(id)sender -{ - NSString *word = [[sender selectedCell] stringValue]; - - _data->_page->changeSpellingToWord(word); -} - -- (IBAction)toggleContinuousSpellChecking:(id)sender -{ - bool spellCheckingEnabled = !TextChecker::state().isContinuousSpellCheckingEnabled; - TextChecker::setContinuousSpellCheckingEnabled(spellCheckingEnabled); - - _data->_page->process()->updateTextCheckerState(); -} - -- (BOOL)isGrammarCheckingEnabled -{ - return TextChecker::state().isGrammarCheckingEnabled; -} - -- (void)setGrammarCheckingEnabled:(BOOL)flag -{ - if (static_cast<bool>(flag) == TextChecker::state().isGrammarCheckingEnabled) - return; - - TextChecker::setGrammarCheckingEnabled(flag); - _data->_page->process()->updateTextCheckerState(); -} - -- (IBAction)toggleGrammarChecking:(id)sender -{ - bool grammarCheckingEnabled = !TextChecker::state().isGrammarCheckingEnabled; - TextChecker::setGrammarCheckingEnabled(grammarCheckingEnabled); - - _data->_page->process()->updateTextCheckerState(); -} - -- (IBAction)toggleAutomaticSpellingCorrection:(id)sender -{ - TextChecker::setAutomaticSpellingCorrectionEnabled(!TextChecker::state().isAutomaticSpellingCorrectionEnabled); - - _data->_page->process()->updateTextCheckerState(); -} - -- (void)orderFrontSubstitutionsPanel:(id)sender -{ - NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker]; - if (!checker) { - LOG_ERROR("No NSSpellChecker"); - return; - } - - NSPanel *substitutionsPanel = [checker substitutionsPanel]; - if ([substitutionsPanel isVisible]) { - [substitutionsPanel orderOut:sender]; - return; - } - [substitutionsPanel orderFront:sender]; -} - -- (IBAction)toggleSmartInsertDelete:(id)sender -{ - _data->_page->setSmartInsertDeleteEnabled(!_data->_page->isSmartInsertDeleteEnabled()); -} - -- (BOOL)isAutomaticQuoteSubstitutionEnabled -{ - return TextChecker::state().isAutomaticQuoteSubstitutionEnabled; -} - -- (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag -{ - if (static_cast<bool>(flag) == TextChecker::state().isAutomaticQuoteSubstitutionEnabled) - return; - - TextChecker::setAutomaticQuoteSubstitutionEnabled(flag); - _data->_page->process()->updateTextCheckerState(); -} - -- (void)toggleAutomaticQuoteSubstitution:(id)sender -{ - TextChecker::setAutomaticQuoteSubstitutionEnabled(!TextChecker::state().isAutomaticQuoteSubstitutionEnabled); - _data->_page->process()->updateTextCheckerState(); -} - -- (BOOL)isAutomaticDashSubstitutionEnabled -{ - return TextChecker::state().isAutomaticDashSubstitutionEnabled; -} - -- (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag -{ - if (static_cast<bool>(flag) == TextChecker::state().isAutomaticDashSubstitutionEnabled) - return; - - TextChecker::setAutomaticDashSubstitutionEnabled(flag); - _data->_page->process()->updateTextCheckerState(); -} - -- (void)toggleAutomaticDashSubstitution:(id)sender -{ - TextChecker::setAutomaticDashSubstitutionEnabled(!TextChecker::state().isAutomaticDashSubstitutionEnabled); - _data->_page->process()->updateTextCheckerState(); -} - -- (BOOL)isAutomaticLinkDetectionEnabled -{ - return TextChecker::state().isAutomaticLinkDetectionEnabled; -} - -- (void)setAutomaticLinkDetectionEnabled:(BOOL)flag -{ - if (static_cast<bool>(flag) == TextChecker::state().isAutomaticLinkDetectionEnabled) - return; - - TextChecker::setAutomaticLinkDetectionEnabled(flag); - _data->_page->process()->updateTextCheckerState(); -} - -- (void)toggleAutomaticLinkDetection:(id)sender -{ - TextChecker::setAutomaticLinkDetectionEnabled(!TextChecker::state().isAutomaticLinkDetectionEnabled); - _data->_page->process()->updateTextCheckerState(); -} - -- (BOOL)isAutomaticTextReplacementEnabled -{ - return TextChecker::state().isAutomaticTextReplacementEnabled; -} - -- (void)setAutomaticTextReplacementEnabled:(BOOL)flag -{ - if (static_cast<bool>(flag) == TextChecker::state().isAutomaticTextReplacementEnabled) - return; - - TextChecker::setAutomaticTextReplacementEnabled(flag); - _data->_page->process()->updateTextCheckerState(); -} - -- (void)toggleAutomaticTextReplacement:(id)sender -{ - TextChecker::setAutomaticTextReplacementEnabled(!TextChecker::state().isAutomaticTextReplacementEnabled); - _data->_page->process()->updateTextCheckerState(); -} - -- (void)uppercaseWord:(id)sender -{ - _data->_page->uppercaseWord(); -} - -- (void)lowercaseWord:(id)sender -{ - _data->_page->lowercaseWord(); -} - -- (void)capitalizeWord:(id)sender -{ - _data->_page->capitalizeWord(); -} - -- (void)displayIfNeeded -{ - // 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. - NSWindow *window = [self window]; - BOOL shouldMaskWindow = window && !NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect); - if (shouldMaskWindow) - NSDisableScreenUpdates(); - - [super displayIfNeeded]; - - if (shouldMaskWindow) { - [window _maskRoundedBottomCorners:_data->_windowBottomCornerIntersectionRect]; - NSEnableScreenUpdates(); - _data->_windowBottomCornerIntersectionRect = NSZeroRect; - } -} - -// Events - -// Override this so that AppKit will send us arrow keys as key down events so we can -// support them via the key bindings mechanism. -- (BOOL)_wantsKeyDownForEvent:(NSEvent *)event -{ - return YES; -} - -- (void)_setMouseDownEvent:(NSEvent *)event -{ - ASSERT(!event || [event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown); - - if (event == _data->_mouseDownEvent) - return; - - [_data->_mouseDownEvent release]; - _data->_mouseDownEvent = [event retain]; -} - -#define NATIVE_MOUSE_EVENT_HANDLER(Selector) \ - - (void)Selector:(NSEvent *)theEvent \ - { \ - if ([[self inputContext] handleEvent:theEvent]) { \ - LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \ - return; \ - } \ - NativeWebMouseEvent webEvent(theEvent, self); \ - _data->_page->handleMouseEvent(webEvent); \ - } - -NATIVE_MOUSE_EVENT_HANDLER(mouseEntered) -NATIVE_MOUSE_EVENT_HANDLER(mouseExited) -NATIVE_MOUSE_EVENT_HANDLER(mouseMovedInternal) -NATIVE_MOUSE_EVENT_HANDLER(mouseDownInternal) -NATIVE_MOUSE_EVENT_HANDLER(mouseUpInternal) -NATIVE_MOUSE_EVENT_HANDLER(mouseDraggedInternal) -NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown) -NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged) -NATIVE_MOUSE_EVENT_HANDLER(otherMouseMoved) -NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp) -NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown) -NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged) -NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp) - -#undef NATIVE_MOUSE_EVENT_HANDLER - -#define NATIVE_EVENT_HANDLER(Selector, Type) \ - - (void)Selector:(NSEvent *)theEvent \ - { \ - NativeWeb##Type##Event webEvent = NativeWeb##Type##Event(theEvent, self); \ - _data->_page->handle##Type##Event(webEvent); \ - } - -NATIVE_EVENT_HANDLER(scrollWheel, Wheel) - -#undef NATIVE_EVENT_HANDLER - -- (void)mouseMoved:(NSEvent *)event -{ - // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect. - if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect])) - return; - - [self mouseMovedInternal:event]; -} - -- (void)mouseDown:(NSEvent *)event -{ - [self _setMouseDownEvent:event]; - _data->_ignoringMouseDraggedEvents = NO; - [self mouseDownInternal:event]; -} - -- (void)mouseUp:(NSEvent *)event -{ - [self _setMouseDownEvent:nil]; - [self mouseUpInternal:event]; -} - -- (void)mouseDragged:(NSEvent *)event -{ - if (_data->_ignoringMouseDraggedEvents) - return; - [self mouseDraggedInternal:event]; -} - -- (BOOL)acceptsFirstMouse:(NSEvent *)event -{ - // There's a chance that responding to this event will run a nested event loop, and - // fetching a new event might release the old one. Retaining and then autoreleasing - // the current event prevents that from causing a problem inside WebKit or AppKit code. - [[event retain] autorelease]; - - if (![self hitTest:[event locationInWindow]]) - return NO; - - [self _setMouseDownEvent:event]; - bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, self)); - [self _setMouseDownEvent:nil]; - return result; -} - -- (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event -{ - // If this is the active window or we don't have a range selection, there is no need to perform additional checks - // and we can avoid making a synchronous call to the WebProcess. - if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange) - return NO; - - // There's a chance that responding to this event will run a nested event loop, and - // fetching a new event might release the old one. Retaining and then autoreleasing - // the current event prevents that from causing a problem inside WebKit or AppKit code. - [[event retain] autorelease]; - - if (![self hitTest:[event locationInWindow]]) - return NO; - - [self _setMouseDownEvent:event]; - bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, self)); - [self _setMouseDownEvent:nil]; - return result; -} - -#if ENABLE(GESTURE_EVENTS) - -static const short kIOHIDEventTypeScroll = 6; - -- (void)shortCircuitedEndGestureWithEvent:(NSEvent *)event -{ - if ([event subtype] != kIOHIDEventTypeScroll) - return; - - WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self); - _data->_page->handleGestureEvent(webEvent); - - if (_data->_endGestureMonitor) { - [NSEvent removeMonitor:_data->_endGestureMonitor]; - _data->_endGestureMonitor = nil; - } -} - -- (void)beginGestureWithEvent:(NSEvent *)event -{ - if ([event subtype] != kIOHIDEventTypeScroll) - return; - - WebGestureEvent webEvent = WebEventFactory::createWebGestureEvent(event, self); - _data->_page->handleGestureEvent(webEvent); - - if (!_data->_endGestureMonitor) { - _data->_endGestureMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskEndGesture handler:^(NSEvent *blockEvent) { - [self shortCircuitedEndGestureWithEvent:blockEvent]; - return blockEvent; - }]; - } -} -#endif - -- (void)doCommandBySelector:(SEL)selector -{ - LOG(TextInput, "doCommandBySelector:\"%s\"", sel_getName(selector)); - - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - if (parameters) - parameters->consumedByIM = false; - - // As in insertText:replacementRange:, we assume that the call comes from an input method if there is marked text. - bool isFromInputMethod = _data->_page->editorState().hasComposition; - - if (parameters && !isFromInputMethod) { - KeypressCommand command(NSStringFromSelector(selector)); - parameters->commands->append(command); - _data->_page->registerKeypressCommandName(command.commandName); - } else { - // FIXME: Send the command to Editor synchronously and only send it along the - // responder chain if it's a selector that does not correspond to an editing command. - [super doCommandBySelector:selector]; - } -} - -- (void)insertText:(id)string -{ - // Unlike and NSTextInputClient variant with replacementRange, this NSResponder method is called when there is no input context, - // so text input processing isn't performed. We are not going to actually insert any text in that case, but saving an insertText - // command ensures that a keypress event is dispatched as appropriate. - [self insertText:string replacementRange:NSMakeRange(NSNotFound, 0)]; -} - -- (void)insertText:(id)string replacementRange:(NSRange)replacementRange -{ - BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; - ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]); - - if (replacementRange.location != NSNotFound) - LOG(TextInput, "insertText:\"%@\" replacementRange:(%u, %u)", isAttributedString ? [string string] : string, replacementRange.location, replacementRange.length); - else - LOG(TextInput, "insertText:\"%@\"", isAttributedString ? [string string] : string); - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - if (parameters) - parameters->consumedByIM = false; - - NSString *text; - bool isFromInputMethod = _data->_page->editorState().hasComposition; - - Vector<TextAlternativeWithRange> dictationAlternatives; - - if (isAttributedString) { -#if USE(DICTATION_ALTERNATIVES) - collectDictationTextAlternatives(string, dictationAlternatives); -#endif - // FIXME: We ignore most attributes from the string, so for example inserting from Character Palette loses font and glyph variation data. - text = [string string]; - } else - text = string; - - // insertText can be called for several reasons: - // - If it's from normal key event processing (including key bindings), we may need to save the action to perform it later. - // - If it's from an input method, then we should go ahead and insert the text now. We assume it's from the input method if we have marked text. - // FIXME: In theory, this could be wrong for some input methods, so we should try to find another way to determine if the call is from the input method. - // - If it's sent outside of keyboard event processing (e.g. from Character Viewer, or when confirming an inline input area with a mouse), - // then we also execute it immediately, as there will be no other chance. - if (parameters && !isFromInputMethod) { - // FIXME: Handle replacementRange in this case, too. It's known to occur in practice when canceling Press and Hold (see <rdar://11940670>). - ASSERT(replacementRange.location == NSNotFound); - KeypressCommand command("insertText:", text); - parameters->commands->append(command); - _data->_page->registerKeypressCommandName(command.commandName); - return; - } - - String eventText = text; - eventText.replace(NSBackTabCharacter, NSTabCharacter); // same thing is done in KeyEventMac.mm in WebCore - bool eventHandled; - if (!dictationAlternatives.isEmpty()) - eventHandled = _data->_page->insertDictatedText(eventText, replacementRange.location, NSMaxRange(replacementRange), dictationAlternatives); - else - eventHandled = _data->_page->insertText(eventText, replacementRange.location, NSMaxRange(replacementRange)); - - if (parameters) - parameters->eventInterpretationHadSideEffects |= eventHandled; -} - -- (BOOL)_handleStyleKeyEquivalent:(NSEvent *)event -{ - if (!_data->_page->editorState().isContentEditable) - return NO; - - if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) != NSCommandKeyMask) - return NO; - - // Here we special case cmd+b and cmd+i but not cmd+u, for historic reason. - // This should not be changed, since it could break some Mac applications that - // rely on this inherent behavior. - // See https://bugs.webkit.org/show_bug.cgi?id=24943 - - NSString *string = [event characters]; - if ([string caseInsensitiveCompare:@"b"] == NSOrderedSame) { - _data->_page->executeEditCommand("ToggleBold"); - return YES; - } - if ([string caseInsensitiveCompare:@"i"] == NSOrderedSame) { - _data->_page->executeEditCommand("ToggleItalic"); - return YES; - } - - return NO; -} - -- (BOOL)performKeyEquivalent:(NSEvent *)event -{ - // There's a chance that responding to this event will run a nested event loop, and - // fetching a new event might release the old one. Retaining and then autoreleasing - // the current event prevents that from causing a problem inside WebKit or AppKit code. - [[event retain] autorelease]; - - BOOL eventWasSentToWebCore = (_data->_keyDownEventBeingResent == event); - - if (!eventWasSentToWebCore) - [self _disableComplexTextInputIfNecessary]; - - // Pass key combos through WebCore if there is a key binding available for - // this event. This lets web pages have a crack at intercepting key-modified keypresses. - // But don't do it if we have already handled the event. - // Pressing Esc results in a fake event being sent - don't pass it to WebCore. - if (!eventWasSentToWebCore && event == [NSApp currentEvent] && self == [[self window] firstResponder]) { - _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(event, self)); - return YES; - } - - return [self _handleStyleKeyEquivalent:event] || [super performKeyEquivalent:event]; -} - -- (void)keyUp:(NSEvent *)theEvent -{ - LOG(TextInput, "keyUp:%p %@", theEvent, theEvent); - _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self)); -} - -- (void)_disableComplexTextInputIfNecessary -{ - if (!_data->_pluginComplexTextInputIdentifier) - return; - - if (_data->_pluginComplexTextInputState != PluginComplexTextInputEnabled) - return; - - // Check if the text input window has been dismissed. - if (![[WKTextInputWindowController sharedTextInputWindowController] hasMarkedText]) - [self _setPluginComplexTextInputState:PluginComplexTextInputDisabled]; -} - -- (BOOL)_handlePluginComplexTextInputKeyDown:(NSEvent *)event -{ - ASSERT(_data->_pluginComplexTextInputIdentifier); - ASSERT(_data->_pluginComplexTextInputState != PluginComplexTextInputDisabled); - - BOOL usingLegacyCocoaTextInput = _data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy; - - NSString *string = nil; - BOOL didHandleEvent = [[WKTextInputWindowController sharedTextInputWindowController] interpretKeyEvent:event usingLegacyCocoaTextInput:usingLegacyCocoaTextInput string:&string]; - - if (string) { - _data->_page->sendComplexTextInputToPlugin(_data->_pluginComplexTextInputIdentifier, string); - - if (!usingLegacyCocoaTextInput) - _data->_pluginComplexTextInputState = PluginComplexTextInputDisabled; - } - - return didHandleEvent; -} - -- (BOOL)_tryHandlePluginComplexTextInputKeyDown:(NSEvent *)event -{ - if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled) - return NO; - - // Check if the text input window has been dismissed and let the plug-in process know. - // This is only valid with the updated Cocoa text input spec. - [self _disableComplexTextInputIfNecessary]; - - // Try feeding the keyboard event directly to the plug-in. - if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy) - return [self _handlePluginComplexTextInputKeyDown:event]; - - return NO; -} - -- (void)keyDown:(NSEvent *)theEvent -{ - LOG(TextInput, "keyDown:%p %@%s", theEvent, theEvent, (theEvent == _data->_keyDownEventBeingResent) ? " (re-sent)" : ""); - - // There's a chance that responding to this event will run a nested event loop, and - // fetching a new event might release the old one. Retaining and then autoreleasing - // the current event prevents that from causing a problem inside WebKit or AppKit code. - [[theEvent retain] autorelease]; - - if ([self _tryHandlePluginComplexTextInputKeyDown:theEvent]) { - LOG(TextInput, "...handled by plug-in"); - return; - } - - // We could be receiving a key down from AppKit if we have re-sent an event - // that maps to an action that is currently unavailable (for example a copy when - // there is no range selection). - // If this is the case we should ignore the key down. - if (_data->_keyDownEventBeingResent == theEvent) { - [super keyDown:theEvent]; - return; - } - _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self)); -} - -- (void)flagsChanged:(NSEvent *)theEvent -{ - LOG(TextInput, "flagsChanged:%p %@", theEvent, theEvent); - - // There's a chance that responding to this event will run a nested event loop, and - // fetching a new event might release the old one. Retaining and then autoreleasing - // the current event prevents that from causing a problem inside WebKit or AppKit code. - [[theEvent retain] autorelease]; - - unsigned short keyCode = [theEvent keyCode]; - - // Don't make an event from the num lock and function keys - if (!keyCode || keyCode == 10 || keyCode == 63) - return; - - _data->_page->handleKeyboardEvent(NativeWebKeyboardEvent(theEvent, self)); -} - -- (void)_executeSavedKeypressCommands -{ - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - if (!parameters || parameters->commands->isEmpty()) - return; - - // We could be called again if the execution of one command triggers a call to selectedRange. - // In this case, the state is up to date, and we don't need to execute any more saved commands to return a result. - if (parameters->executingSavedKeypressCommands) - return; - - LOG(TextInput, "Executing %u saved keypress commands...", parameters->commands->size()); - - parameters->executingSavedKeypressCommands = true; - parameters->eventInterpretationHadSideEffects |= _data->_page->executeKeypressCommands(*parameters->commands); - parameters->commands->clear(); - parameters->executingSavedKeypressCommands = false; - - LOG(TextInput, "...done executing saved keypress commands."); -} - -- (NSTextInputContext *)inputContext -{ - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - - if (_data->_pluginComplexTextInputIdentifier && !parameters) - return [[WKTextInputWindowController sharedTextInputWindowController] inputContext]; - - // Disable text input machinery when in non-editable content. An invisible inline input area affects performance, and can prevent Expose from working. - if (!_data->_page->editorState().isContentEditable) - return nil; - - return [super inputContext]; -} - -- (NSRange)selectedRange -{ - [self _executeSavedKeypressCommands]; - - uint64_t selectionStart; - uint64_t selectionLength; - _data->_page->getSelectedRange(selectionStart, selectionLength); - - NSRange result = NSMakeRange(selectionStart, selectionLength); - if (result.location == NSNotFound) - LOG(TextInput, "selectedRange -> (NSNotFound, %u)", result.length); - else - LOG(TextInput, "selectedRange -> (%u, %u)", result.location, result.length); - - return result; -} - -- (BOOL)hasMarkedText -{ - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - - BOOL result; - if (parameters) { - result = _data->_page->editorState().hasComposition; - if (result) { - // A saved command can confirm a composition, but it cannot start a new one. - [self _executeSavedKeypressCommands]; - result = _data->_page->editorState().hasComposition; - } - } else { - uint64_t location; - uint64_t length; - _data->_page->getMarkedRange(location, length); - result = location != NSNotFound; - } - - LOG(TextInput, "hasMarkedText -> %u", result); - return result; -} - -- (void)unmarkText -{ - [self _executeSavedKeypressCommands]; - - LOG(TextInput, "unmarkText"); - - // Use pointer to get parameters passed to us by the caller of interpretKeyEvents. - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - - if (parameters) { - parameters->eventInterpretationHadSideEffects = true; - parameters->consumedByIM = false; - } - - _data->_page->confirmComposition(); -} - -- (NSArray *)validAttributesForMarkedText -{ - static NSArray *validAttributes; - if (!validAttributes) { - validAttributes = [[NSArray alloc] initWithObjects: - NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName, - NSMarkedClauseSegmentAttributeName, -#if USE(DICTATION_ALTERNATIVES) - NSTextAlternativesAttributeName, -#endif - nil]; - // NSText also supports the following attributes, but it's - // hard to tell which are really required for text input to - // work well; I have not seen any input method make use of them yet. - // NSFontAttributeName, NSForegroundColorAttributeName, - // NSBackgroundColorAttributeName, NSLanguageAttributeName. - CFRetain(validAttributes); - } - LOG(TextInput, "validAttributesForMarkedText -> (...)"); - return validAttributes; -} - -static void extractUnderlines(NSAttributedString *string, Vector<CompositionUnderline>& result) -{ - int length = [[string string] length]; - - int i = 0; - while (i < length) { - NSRange range; - NSDictionary *attrs = [string attributesAtIndex:i longestEffectiveRange:&range inRange:NSMakeRange(i, length - i)]; - - if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) { - Color color = Color::black; - if (NSColor *colorAttr = [attrs objectForKey:NSUnderlineColorAttributeName]) - color = colorFromNSColor([colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]); - result.append(CompositionUnderline(range.location, NSMaxRange(range), color, [style intValue] > 1)); - } - - i = range.location + range.length; - } -} - -- (void)setMarkedText:(id)string selectedRange:(NSRange)newSelRange replacementRange:(NSRange)replacementRange -{ - [self _executeSavedKeypressCommands]; - - BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; - ASSERT(isAttributedString || [string isKindOfClass:[NSString class]]); - - LOG(TextInput, "setMarkedText:\"%@\" selectedRange:(%u, %u)", isAttributedString ? [string string] : string, newSelRange.location, newSelRange.length); - - // Use pointer to get parameters passed to us by the caller of interpretKeyEvents. - WKViewInterpretKeyEventsParameters* parameters = _data->_interpretKeyEventsParameters; - - if (parameters) { - parameters->eventInterpretationHadSideEffects = true; - parameters->consumedByIM = false; - } - - Vector<CompositionUnderline> underlines; - NSString *text; - - if (isAttributedString) { - // FIXME: We ignore most attributes from the string, so an input method cannot specify e.g. a font or a glyph variation. - text = [string string]; - extractUnderlines(string, underlines); - } else - text = string; - - if (_data->_page->editorState().isInPasswordField) { - // In password fields, we only allow ASCII dead keys, and don't allow inline input, matching NSSecureTextInputField. - // Allowing ASCII dead keys is necessary to enable full Roman input when using a Vietnamese keyboard. - ASSERT(!_data->_page->editorState().hasComposition); - [self _notifyInputContextAboutDiscardedComposition]; - if ([text length] == 1 && [[text decomposedStringWithCanonicalMapping] characterAtIndex:0] < 0x80) { - _data->_page->insertText(text, replacementRange.location, NSMaxRange(replacementRange)); - } else - NSBeep(); - return; - } - - _data->_page->setComposition(text, underlines, newSelRange.location, NSMaxRange(newSelRange), replacementRange.location, NSMaxRange(replacementRange)); -} - -- (NSRange)markedRange -{ - [self _executeSavedKeypressCommands]; - - uint64_t location; - uint64_t length; - _data->_page->getMarkedRange(location, length); - - LOG(TextInput, "markedRange -> (%u, %u)", location, length); - return NSMakeRange(location, length); -} - -- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange -{ - [self _executeSavedKeypressCommands]; - - if (!_data->_page->editorState().isContentEditable) { - LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> nil", nsRange.location, nsRange.length); - return nil; - } - - if (_data->_page->editorState().isInPasswordField) - return nil; - - AttributedString result; - _data->_page->getAttributedSubstringFromRange(nsRange.location, NSMaxRange(nsRange), result); - - if (actualRange) { - *actualRange = nsRange; - actualRange->length = [result.string.get() length]; - } - - LOG(TextInput, "attributedSubstringFromRange:(%u, %u) -> \"%@\"", nsRange.location, nsRange.length, [result.string.get() string]); - return [[result.string.get() retain] autorelease]; -} - -- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint -{ - [self _executeSavedKeypressCommands]; - - NSWindow *window = [self window]; - - if (window) - thePoint = [window convertScreenToBase:thePoint]; - thePoint = [self convertPoint:thePoint fromView:nil]; // the point is relative to the main frame - - uint64_t result = _data->_page->characterIndexForPoint(IntPoint(thePoint)); - LOG(TextInput, "characterIndexForPoint:(%f, %f) -> %u", thePoint.x, thePoint.y, result); - return result; -} - -- (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange -{ - [self _executeSavedKeypressCommands]; - - // Just to match NSTextView's behavior. Regression tests cannot detect this; - // to reproduce, use a test application from http://bugs.webkit.org/show_bug.cgi?id=4682 - // (type something; try ranges (1, -1) and (2, -1). - if ((theRange.location + theRange.length < theRange.location) && (theRange.location + theRange.length != 0)) - theRange.length = 0; - - NSRect resultRect = _data->_page->firstRectForCharacterRange(theRange.location, theRange.length); - resultRect = [self convertRect:resultRect toView:nil]; - - NSWindow *window = [self window]; - if (window) - resultRect.origin = [window convertBaseToScreen:resultRect.origin]; - - if (actualRange) { - // FIXME: Update actualRange to match the range of first rect. - *actualRange = theRange; - } - - LOG(TextInput, "firstRectForCharacterRange:(%u, %u) -> (%f, %f, %f, %f)", theRange.location, theRange.length, resultRect.origin.x, resultRect.origin.y, resultRect.size.width, resultRect.size.height); - return resultRect; -} - -#if ENABLE(DRAG_SUPPORT) -- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation -{ - NSPoint windowImageLoc = [[self window] convertScreenToBase:aPoint]; - NSPoint windowMouseLoc = windowImageLoc; - - // Prevent queued mouseDragged events from coming after the drag and fake mouseUp event. - _data->_ignoringMouseDraggedEvents = YES; - - _data->_page->dragEnded(IntPoint(windowMouseLoc), globalPoint(windowMouseLoc, [self window]), operation); -} - -- (DragApplicationFlags)applicationFlags:(id <NSDraggingInfo>)draggingInfo -{ - uint32_t flags = 0; - if ([NSApp modalWindow]) - flags = DragApplicationIsModal; - if ([[self window] attachedSheet]) - flags |= DragApplicationHasAttachedSheet; - if ([draggingInfo draggingSource] == self) - flags |= DragApplicationIsSource; - if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) - flags |= DragApplicationIsCopyKeyDown; - return static_cast<DragApplicationFlags>(flags); -} - -- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo -{ - IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]); - IntPoint global(globalPoint([draggingInfo draggingLocation], [self window])); - DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]); - - _data->_page->resetDragOperation(); - _data->_page->dragEntered(&dragData, [[draggingInfo draggingPasteboard] name]); - return NSDragOperationCopy; -} - -- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo -{ - IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]); - IntPoint global(globalPoint([draggingInfo draggingLocation], [self window])); - DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]); - _data->_page->dragUpdated(&dragData, [[draggingInfo draggingPasteboard] name]); - - WebCore::DragSession dragSession = _data->_page->dragSession(); - NSInteger numberOfValidItemsForDrop = dragSession.numberOfItemsToBeAccepted; - NSDraggingFormation draggingFormation = NSDraggingFormationNone; - if (dragSession.mouseIsOverFileInput && numberOfValidItemsForDrop > 0) - draggingFormation = NSDraggingFormationList; - - if ([draggingInfo numberOfValidItemsForDrop] != numberOfValidItemsForDrop) - [draggingInfo setNumberOfValidItemsForDrop:numberOfValidItemsForDrop]; - if ([draggingInfo draggingFormation] != draggingFormation) - [draggingInfo setDraggingFormation:draggingFormation]; - - return dragSession.operation; -} - -- (void)draggingExited:(id <NSDraggingInfo>)draggingInfo -{ - IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]); - IntPoint global(globalPoint([draggingInfo draggingLocation], [self window])); - DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]); - _data->_page->dragExited(&dragData, [[draggingInfo draggingPasteboard] name]); - _data->_page->resetDragOperation(); -} - -- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo -{ - return YES; -} - -// FIXME: This code is more or less copied from Pasteboard::getBestURL. -// It would be nice to be able to share the code somehow. -static bool maybeCreateSandboxExtensionFromPasteboard(NSPasteboard *pasteboard, SandboxExtension::Handle& sandboxExtensionHandle) -{ - NSArray *types = [pasteboard types]; - if (![types containsObject:NSFilenamesPboardType]) - return false; - - NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType]; - if ([files count] != 1) - return false; - - NSString *file = [files objectAtIndex:0]; - BOOL isDirectory; - if (![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory]) - return false; - - if (isDirectory) - return false; - - SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle); - return true; -} - -static void createSandboxExtensionsForFileUpload(NSPasteboard *pasteboard, SandboxExtension::HandleArray& handles) -{ - NSArray *types = [pasteboard types]; - if (![types containsObject:NSFilenamesPboardType]) - return; - - NSArray *files = [pasteboard propertyListForType:NSFilenamesPboardType]; - handles.allocate([files count]); - for (unsigned i = 0; i < [files count]; i++) { - NSString *file = [files objectAtIndex:i]; - if (![[NSFileManager defaultManager] fileExistsAtPath:file]) - continue; - SandboxExtension::Handle handle; - SandboxExtension::createHandle(file, SandboxExtension::ReadOnly, handles[i]); - } -} - -- (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo -{ - IntPoint client([self convertPoint:[draggingInfo draggingLocation] fromView:nil]); - IntPoint global(globalPoint([draggingInfo draggingLocation], [self window])); - DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]); - - SandboxExtension::Handle sandboxExtensionHandle; - bool createdExtension = maybeCreateSandboxExtensionFromPasteboard([draggingInfo draggingPasteboard], sandboxExtensionHandle); - if (createdExtension) - _data->_page->process()->willAcquireUniversalFileReadSandboxExtension(); - - SandboxExtension::HandleArray sandboxExtensionForUpload; - createSandboxExtensionsForFileUpload([draggingInfo draggingPasteboard], sandboxExtensionForUpload); - - _data->_page->performDrag(&dragData, [[draggingInfo draggingPasteboard] name], sandboxExtensionHandle, sandboxExtensionForUpload); - - return YES; -} - -// This code is needed to support drag and drop when the drag types cannot be matched. -// This is the case for elements that do not place content -// in the drag pasteboard automatically when the drag start (i.e. dragging a DIV element). -- (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types -{ - if ([[self superview] mouse:*point inRect:[self frame]]) - return self; - return nil; -} -#endif // ENABLE(DRAG_SUPPORT) - -- (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc -{ - NSPoint localPoint = [self convertPoint:loc fromView:nil]; - NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect()); - return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]); -} - -- (void)_updateWindowVisibility -{ - _data->_page->updateWindowIsVisible([[self window] isVisible]); -} - - -// FIXME: Use AppKit constants for these when they are available. -static NSString * const windowDidChangeBackingPropertiesNotification = @"NSWindowDidChangeBackingPropertiesNotification"; -static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOldScaleFactorKey"; - -- (void)addWindowObserversForWindow:(NSWindow *)window -{ - if (window) { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidBecomeKey:) - name:NSWindowDidBecomeKeyNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResignKey:) - name:NSWindowDidResignKeyNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMiniaturize:) - name:NSWindowDidMiniaturizeNotification object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidDeminiaturize:) - name:NSWindowDidDeminiaturizeNotification object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidMove:) - name:NSWindowDidMoveNotification object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidResize:) - name:NSWindowDidResizeNotification object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOffScreen:) - name:@"NSWindowDidOrderOffScreenNotification" object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidOrderOnScreen:) - name:@"_NSWindowDidBecomeVisible" object:window]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowDidChangeBackingProperties:) - 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 - } -} - -- (void)removeWindowObservers -{ - NSWindow *window = [self window]; - if (!window) - return; - - [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidBecomeKeyNotification object:nil]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidResignKeyNotification object:nil]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:NSWindowDidMiniaturizeNotification object:window]; - [[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 -{ - NSWindow *currentWindow = [self window]; - if (window == currentWindow) - return; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED == 1070 - // Avoid calling the code added in 121482 that ensures that the undo stack is cleaned up - // before the WKView is moved from one window to another when the WKView is being moved - // out of a popover window. This avoids a bug in OS X 10.7 that was fixed in 10.8. - // While this technically reopens a potentially crashing code path that 121482 closed, - // it only reopens it for WKViews that are used for text editing and that are removed - // from an NSPopover at some time earlier than tear-down of the NSPopover. - if (![currentWindow isKindOfClass:NSClassFromString(@"_NSPopoverWindow")]) -#endif - _data->_pageClient->viewWillMoveToAnotherWindow(); - - [self removeWindowObservers]; - [self addWindowObserversForWindow:window]; -} - -- (void)viewDidMoveToWindow -{ - // We want to make sure to update the active state while hidden, so if the view is about to become visible, we - // 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); - - if ([self isDeferringViewInWindowChanges]) { - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); - _data->_viewInWindowChangeWasDeferred = YES; - } else - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible | WebPageProxy::ViewIsInWindow); - - [self _updateWindowAndViewFrames]; - - if (!_data->_flagsChangedEventMonitor) { - _data->_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSFlagsChangedMask handler:^(NSEvent *flagsChangedEvent) { - [self _postFakeMouseMovedEventForFlagsChangedEvent:flagsChangedEvent]; - return flagsChangedEvent; - }]; - } - - [self _accessibilityRegisterUIProcessTokens]; - } else { - [self _updateWindowVisibility]; - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); - - 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; - -#if ENABLE(GESTURE_EVENTS) - if (_data->_endGestureMonitor) { - [NSEvent removeMonitor:_data->_endGestureMonitor]; - _data->_endGestureMonitor = nil; - } -#endif - WKHideWordDefinitionWindow(); - } - - _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]); -} - -- (void)doWindowDidChangeScreen -{ - _data->_page->windowScreenDidChange((PlatformDisplayID)[[[[[self window] screen] deviceDescription] objectForKey:@"NSScreenNumber"] intValue]); -} - -- (void)_windowDidBecomeKey:(NSNotification *)notification -{ - NSWindow *keyWindow = [notification object]; - if (keyWindow == [self window] || keyWindow == [[self window] attachedSheet]) { - [self _updateSecureInputState]; - _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); - } -} - -- (void)_windowDidChangeScreen:(NSNotification *)notification -{ - [self doWindowDidChangeScreen]; -} - -- (void)_windowDidResignKey:(NSNotification *)notification -{ - NSWindow *formerKeyWindow = [notification object]; - if (formerKeyWindow == [self window] || formerKeyWindow == [[self window] attachedSheet]) { - [self _updateSecureInputState]; - _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); - } -} - -- (void)_windowDidMiniaturize:(NSNotification *)notification -{ - _data->_windowHasValidBackingStore = NO; - - [self _updateWindowVisibility]; -} - -- (void)_windowDidDeminiaturize:(NSNotification *)notification -{ - [self _updateWindowVisibility]; -} - -- (void)_windowDidMove:(NSNotification *)notification -{ - [self _updateWindowAndViewFrames]; -} - -- (void)_windowDidResize:(NSNotification *)notification -{ - _data->_windowHasValidBackingStore = NO; - - [self _updateWindowAndViewFrames]; -} - -- (void)_windowDidOrderOffScreen:(NSNotification *)notification -{ - [self _updateWindowVisibility]; - - // We want to make sure to update the active state while hidden, so since the view is about to be hidden, - // we hide it first and then update the active state. - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); - _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); -} - -- (void)_windowDidOrderOnScreen:(NSNotification *)notification -{ - [self _updateWindowVisibility]; - - // We want to make sure to update the active state while hidden, so since the view is about to become visible, - // we update the active state first and then make it visible. - _data->_page->viewStateDidChange(WebPageProxy::ViewWindowIsActive); - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -- (void)_windowDidChangeBackingProperties:(NSNotification *)notification -{ - CGFloat oldBackingScaleFactor = [[notification.userInfo objectForKey:backingPropertyOldScaleFactorKey] doubleValue]; - CGFloat newBackingScaleFactor = [self _intrinsicDeviceScaleFactor]; - if (oldBackingScaleFactor == newBackingScaleFactor) - return; - - _data->_windowHasValidBackingStore = NO; - _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()) - return; - - CGContextSaveGState(context); - CGContextSetBlendMode(context, kCGBlendModeCopy); - - CGColorRef backgroundColor; - if (page->drawsTransparentBackground()) - backgroundColor = CGColorGetConstantColor(kCGColorClear); - else - backgroundColor = CGColorGetConstantColor(kCGColorWhite); - - CGContextSetFillColorWithColor(context, backgroundColor); - CGContextFillRect(context, rect); - - CGContextRestoreGState(context); -} - -- (void)drawRect:(NSRect)rect -{ - LOG(View, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); - _data->_page->endPrinting(); - - if ([self _shouldUseTiledDrawingArea]) { - // Nothing to do here. - return; - } - - CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext currentContext] graphicsPort]); - - if (DrawingAreaProxyImpl* drawingArea = static_cast<DrawingAreaProxyImpl*>(_data->_page->drawingArea())) { - const NSRect *rectsBeingDrawn; - NSInteger numRectsBeingDrawn; - [self getRectsBeingDrawn:&rectsBeingDrawn count:&numRectsBeingDrawn]; - for (NSInteger i = 0; i < numRectsBeingDrawn; ++i) { - Region unpaintedRegion; - drawingArea->paint(context, enclosingIntRect(rectsBeingDrawn[i]), unpaintedRegion); - - // 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 || !drawingArea->hasReceivedFirstUpdate()) { - Vector<IntRect> unpaintedRects = unpaintedRegion.rects(); - for (size_t i = 0; i < unpaintedRects.size(); ++i) - drawPageBackground(context, _data->_page.get(), unpaintedRects[i]); - - _data->_windowHasValidBackingStore = YES; - } - } - } else - drawPageBackground(context, _data->_page.get(), enclosingIntRect(rect)); - - _data->_page->didDraw(); -} - -- (BOOL)isOpaque -{ - return _data->_page->drawsBackground(); -} - -- (BOOL)mouseDownCanMoveWindow -{ - // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent, - // but we don't want a drag in the NSView to move the window, even if it's transparent. - return NO; -} - -- (void)viewDidHide -{ - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -- (void)viewDidUnhide -{ - _data->_page->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -- (void)viewDidChangeBackingProperties -{ - NSColorSpace *colorSpace = [[self window] colorSpace]; - if ([colorSpace isEqualTo:_data->_colorSpace.get()]) - return; - - _data->_colorSpace = nullptr; - if (DrawingAreaProxy *drawingArea = _data->_page->drawingArea()) - 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 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); -} - -- (void)_updateRemoteAccessibilityRegistration:(BOOL)registerProcess -{ - // When the tree is connected/disconnected, the remote accessibility registration - // needs to be updated with the pid of the remote process. If the process is going - // away, that information is not present in WebProcess - pid_t pid = 0; - if (registerProcess && _data->_page->process()) - pid = _data->_page->process()->processIdentifier(); - else if (!registerProcess) { - pid = WKAXRemoteProcessIdentifier(_data->_remoteAccessibilityChild.get()); - _data->_remoteAccessibilityChild = nil; - } - if (pid) - WKAXRegisterRemoteProcess(registerProcess, pid); -} - -- (void)enableAccessibilityIfNecessary -{ - 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(); -} - -- (BOOL)accessibilityIsIgnored -{ - return NO; -} - -- (id)accessibilityHitTest:(NSPoint)point -{ - [self enableAccessibilityIfNecessary]; - return _data->_remoteAccessibilityChild.get(); -} - -- (id)accessibilityAttributeValue:(NSString*)attribute -{ - [self enableAccessibilityIfNecessary]; - - if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) { - - id child = nil; - if (_data->_remoteAccessibilityChild) - child = _data->_remoteAccessibilityChild.get(); - - if (!child) - return nil; - return [NSArray arrayWithObject:child]; - } - if ([attribute isEqualToString:NSAccessibilityRoleAttribute]) - return NSAccessibilityGroupRole; - if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute]) - return NSAccessibilityRoleDescription(NSAccessibilityGroupRole, nil); - if ([attribute isEqualToString:NSAccessibilityParentAttribute]) - return NSAccessibilityUnignoredAncestor([self superview]); - if ([attribute isEqualToString:NSAccessibilityEnabledAttribute]) - return [NSNumber numberWithBool:YES]; - - return [super accessibilityAttributeValue:attribute]; -} - -- (NSView *)hitTest:(NSPoint)point -{ - NSView *hitView = [super hitTest:point]; - if (hitView && _data && hitView == _data->_layerHostingView) - hitView = self; - - return hitView; -} - -- (void)_postFakeMouseMovedEventForFlagsChangedEvent:(NSEvent *)flagsChangedEvent -{ - NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved location:[[flagsChangedEvent window] convertScreenToBase:[NSEvent mouseLocation]] - modifierFlags:[flagsChangedEvent modifierFlags] timestamp:[flagsChangedEvent timestamp] windowNumber:[flagsChangedEvent windowNumber] - context:[flagsChangedEvent context] eventNumber:0 clickCount:0 pressure:0]; - NativeWebMouseEvent webEvent(fakeEvent, self); - _data->_page->handleMouseEvent(webEvent); -} - -- (NSInteger)conversationIdentifier -{ - return (NSInteger)self; -} - -- (float)_intrinsicDeviceScaleFactor -{ - NSWindow *window = [self window]; - if (window) - return [window backingScaleFactor]; - return [[NSScreen mainScreen] backingScaleFactor]; -} - -- (void)_setDrawingAreaSize:(NSSize)size -{ - if (!_data->_page->drawingArea()) - return; - - 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; -} - -- (BOOL)_shouldUseTiledDrawingArea -{ - return NO; -} - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 -- (void)quickLookWithEvent:(NSEvent *)event -{ - NSPoint locationInViewCoordinates = [self convertPoint:[event locationInWindow] fromView:nil]; - _data->_page->performDictionaryLookupAtLocation(FloatPoint(locationInViewCoordinates.x, locationInViewCoordinates.y)); -} -#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) - -- (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy -{ -#if ENABLE(THREADED_SCROLLING) - if ([self _shouldUseTiledDrawingArea]) { - if (getenv("WK_USE_REMOTE_LAYER_TREE_DRAWING_AREA")) - return RemoteLayerTreeDrawingAreaProxy::create(_data->_page.get()); - - return TiledCoreAnimationDrawingAreaProxy::create(_data->_page.get()); - } -#endif - - return DrawingAreaProxyImpl::create(_data->_page.get()); -} - -- (BOOL)_isFocused -{ - if (_data->_inBecomeFirstResponder) - return YES; - if (_data->_inResignFirstResponder) - return NO; - return [[self window] firstResponder] == self; -} - -- (WebKit::ColorSpaceData)_colorSpace -{ - if (!_data->_colorSpace) { - if ([self window]) - _data->_colorSpace = [[self window] colorSpace]; - else - _data->_colorSpace = [[NSScreen mainScreen] colorSpace]; - } - - ColorSpaceData colorSpaceData; - colorSpaceData.cgColorSpace = [_data->_colorSpace.get() CGColorSpace]; - - return colorSpaceData; -} - -- (void)_processDidCrash -{ - if (_data->_layerHostingView) - [self _setAcceleratedCompositingModeRootLayer:nil]; - - [self _updateRemoteAccessibilityRegistration:NO]; -} - -- (void)_pageClosed -{ - [self _updateRemoteAccessibilityRegistration:NO]; -} - -- (void)_didRelaunchProcess -{ - [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) - return; - [cursor set]; -} - -- (void)_setUserInterfaceItemState:(NSString *)commandName enabled:(BOOL)isEnabled state:(int)newState -{ - ValidationVector items = _data->_validationMap.take(commandName); - size_t size = items.size(); - for (size_t i = 0; i < size; ++i) { - ValidationItem item = items[i].get(); - [menuItem(item) setState:newState]; - [menuItem(item) setEnabled:isEnabled]; - [toolbarItem(item) setEnabled:isEnabled]; - // FIXME <rdar://problem/8803392>: If the item is neither a menu nor toolbar item, it will be left enabled. - } -} - -- (BOOL)_tryPostProcessPluginComplexTextInputKeyDown:(NSEvent *)event -{ - if (!_data->_pluginComplexTextInputIdentifier || _data->_pluginComplexTextInputState == PluginComplexTextInputDisabled) - return NO; - - // In the legacy text input model, the event has already been sent to the input method. - if (_data->_pluginComplexTextInputState == PluginComplexTextInputEnabledLegacy) - return NO; - - return [self _handlePluginComplexTextInputKeyDown:event]; -} - -- (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled -{ - if ([event type] != NSKeyDown) - return; - - if ([self _tryPostProcessPluginComplexTextInputKeyDown:event]) - return; - - if (eventWasHandled) { - [NSCursor setHiddenUntilMouseMoves:YES]; - return; - } - - // resending the event may destroy this WKView - RetainPtr<WKView> protector(self); - - ASSERT(!_data->_keyDownEventBeingResent); - _data->_keyDownEventBeingResent = event; - [NSApp _setCurrentEvent:event]; - [NSApp sendEvent:event]; - - _data->_keyDownEventBeingResent = nullptr; -} - -- (BOOL)_interpretKeyEvent:(NSEvent *)event savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands -{ - ASSERT(!_data->_interpretKeyEventsParameters); - ASSERT(commands.isEmpty()); - - if ([event type] == NSFlagsChanged) - return NO; - - WKViewInterpretKeyEventsParameters parameters; - parameters.eventInterpretationHadSideEffects = false; - parameters.executingSavedKeypressCommands = false; - // We assume that an input method has consumed the event, and only change this assumption if one of the NSTextInput methods is called. - // We assume the IM will *not* consume hotkey sequences. - parameters.consumedByIM = !([event modifierFlags] & NSCommandKeyMask); - parameters.commands = &commands; - _data->_interpretKeyEventsParameters = ¶meters; - - LOG(TextInput, "-> interpretKeyEvents:%p %@", event, event); - [self interpretKeyEvents:[NSArray arrayWithObject:event]]; - - _data->_interpretKeyEventsParameters = 0; - - // An input method may consume an event and not tell us (e.g. when displaying a candidate window), - // in which case we should not bubble the event up the DOM. - if (parameters.consumedByIM) { - LOG(TextInput, "...event %p was consumed by an input method", event); - return YES; - } - - LOG(TextInput, "...interpretKeyEvents for event %p done, returns %d", event, parameters.eventInterpretationHadSideEffects); - - // If we have already executed all or some of the commands, the event is "handled". Note that there are additional checks on web process side. - return parameters.eventInterpretationHadSideEffects; -} - -- (NSRect)_convertToDeviceSpace:(NSRect)rect -{ - return toDeviceSpace(rect, [self window]); -} - -- (NSRect)_convertToUserSpace:(NSRect)rect -{ - return toUserSpace(rect, [self window]); -} - -// Any non-zero value will do, but using something recognizable might help us debug some day. -#define TRACKING_RECT_TAG 0xBADFACE - -- (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside -{ - ASSERT(_data->_trackingRectOwner == nil); - _data->_trackingRectOwner = owner; - _data->_trackingRectUserData = data; - return TRACKING_RECT_TAG; -} - -- (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag -{ - ASSERT(tag == 0 || tag == TRACKING_RECT_TAG); - ASSERT(_data->_trackingRectOwner == nil); - _data->_trackingRectOwner = owner; - _data->_trackingRectUserData = data; - return TRACKING_RECT_TAG; -} - -- (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count -{ - ASSERT(count == 1); - ASSERT(trackingNums[0] == 0 || trackingNums[0] == TRACKING_RECT_TAG); - ASSERT(_data->_trackingRectOwner == nil); - _data->_trackingRectOwner = owner; - _data->_trackingRectUserData = userDataList[0]; - trackingNums[0] = TRACKING_RECT_TAG; -} - -- (void)removeTrackingRect:(NSTrackingRectTag)tag -{ - if (!_data) - return; - - if (tag == 0) - return; - - if (tag == TRACKING_RECT_TAG) { - _data->_trackingRectOwner = nil; - return; - } - - if (tag == _data->_lastToolTipTag) { - [super removeTrackingRect:tag]; - _data->_lastToolTipTag = 0; - return; - } - - // If any other tracking rect is being removed, we don't know how it was created - // and it's possible there's a leak involved (see 3500217) - ASSERT_NOT_REACHED(); -} - -- (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count -{ - int i; - for (i = 0; i < count; ++i) { - int tag = tags[i]; - if (tag == 0) - continue; - ASSERT(tag == TRACKING_RECT_TAG); - if (_data != nil) { - _data->_trackingRectOwner = nil; - } - } -} - -- (void)_sendToolTipMouseExited -{ - // Nothing matters except window, trackingNumber, and userData. - NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseExited - location:NSMakePoint(0, 0) - modifierFlags:0 - timestamp:0 - windowNumber:[[self window] windowNumber] - context:NULL - eventNumber:0 - trackingNumber:TRACKING_RECT_TAG - userData:_data->_trackingRectUserData]; - [_data->_trackingRectOwner mouseExited:fakeEvent]; -} - -- (void)_sendToolTipMouseEntered -{ - // Nothing matters except window, trackingNumber, and userData. - NSEvent *fakeEvent = [NSEvent enterExitEventWithType:NSMouseEntered - location:NSMakePoint(0, 0) - modifierFlags:0 - timestamp:0 - windowNumber:[[self window] windowNumber] - context:NULL - eventNumber:0 - trackingNumber:TRACKING_RECT_TAG - userData:_data->_trackingRectUserData]; - [_data->_trackingRectOwner mouseEntered:fakeEvent]; -} - -- (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data -{ - return nsStringFromWebCoreString(_data->_page->toolTip()); -} - -- (void)_toolTipChangedFrom:(NSString *)oldToolTip to:(NSString *)newToolTip -{ - if (oldToolTip) - [self _sendToolTipMouseExited]; - - if (newToolTip && [newToolTip length] > 0) { - // See radar 3500217 for why we remove all tooltips rather than just the single one we created. - [self removeAllToolTips]; - NSRect wideOpenRect = NSMakeRect(-100000, -100000, 200000, 200000); - _data->_lastToolTipTag = [self addToolTipRect:wideOpenRect owner:self userData:NULL]; - [self _sendToolTipMouseEntered]; - } -} - -- (void)_setFindIndicator:(PassRefPtr<FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut animate:(BOOL)animate -{ - if (!findIndicator) { - _data->_findIndicatorWindow = nullptr; - return; - } - - if (!_data->_findIndicatorWindow) - _data->_findIndicatorWindow = FindIndicatorWindow::create(self); - - _data->_findIndicatorWindow->setFindIndicator(findIndicator, fadeOut, animate); -} - - -- (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer -{ - [CATransaction begin]; - [CATransaction setDisableActions:YES]; - - if (rootLayer) { - if (!_data->_layerHostingView) { - // Create an NSView that will host our layer tree. - _data->_layerHostingView = adoptNS([[WKFlippedView alloc] initWithFrame:[self bounds]]); - [_data->_layerHostingView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; - - - [self addSubview:_data->_layerHostingView.get() positioned:NSWindowBelow relativeTo:nil]; - - // Create a root layer that will back the NSView. - RetainPtr<CALayer> layer = adoptNS([[CALayer alloc] init]); -#ifndef NDEBUG - [layer setName:@"Hosting root layer"]; -#endif - - [_data->_layerHostingView setLayer:layer.get()]; - [_data->_layerHostingView setWantsLayer:YES]; - } - - [_data->_layerHostingView layer].sublayers = [NSArray arrayWithObject:rootLayer]; - } else { - if (_data->_layerHostingView) { - [_data->_layerHostingView removeFromSuperview]; - [_data->_layerHostingView setLayer:nil]; - [_data->_layerHostingView setWantsLayer:NO]; - - _data->_layerHostingView = nullptr; - _data->_frameOrigin = NSZeroPoint; - } - } - - [CATransaction commit]; -} - -- (void)_setAccessibilityWebProcessToken:(NSData *)data -{ - _data->_remoteAccessibilityChild = WKAXRemoteElementForToken(data); - [self _updateRemoteAccessibilityRegistration:YES]; -} - -- (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier -{ - BOOL inputSourceChanged = _data->_pluginComplexTextInputIdentifier; - - if (pluginHasFocusAndWindowHasFocus) { - // Check if we're already allowing text input for this plug-in. - if (pluginComplexTextInputIdentifier == _data->_pluginComplexTextInputIdentifier) - return; - - _data->_pluginComplexTextInputIdentifier = pluginComplexTextInputIdentifier; - - } else { - // Check if we got a request to unfocus a plug-in that isn't focused. - if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) - return; - - _data->_pluginComplexTextInputIdentifier = 0; - } - - if (inputSourceChanged) { - // The input source changed, go ahead and discard any entered text. - [[WKTextInputWindowController sharedTextInputWindowController] unmarkText]; - } - - // This will force the current input context to be updated to its correct value. - [NSApp updateWindows]; -} - -- (void)_setPluginComplexTextInputState:(PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier -{ - if (pluginComplexTextInputIdentifier != _data->_pluginComplexTextInputIdentifier) { - // We're asked to update the state for a plug-in that doesn't have focus. - return; - } - - [self _setPluginComplexTextInputState:pluginComplexTextInputState]; -} - -- (void)_setDragImage:(NSImage *)image at:(NSPoint)clientPoint linkDrag:(BOOL)linkDrag -{ - IntSize size([image size]); - size.scale(1.0 / _data->_page->deviceScaleFactor()); - [image setSize:size]; - - // The call to super could release this WKView. - RetainPtr<WKView> protector(self); - - [super dragImage:image - at:clientPoint - offset:NSZeroSize - event:(linkDrag) ? [NSApp currentEvent] :_data->_mouseDownEvent - pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard] - source:self - slideBack:YES]; -} - -static bool matchesExtensionOrEquivalent(NSString *filename, NSString *extension) -{ - NSString *extensionAsSuffix = [@"." stringByAppendingString:extension]; - return hasCaseInsensitiveSuffix(filename, extensionAsSuffix) || (stringIsCaseInsensitiveEqualToString(extension, @"jpeg") - && hasCaseInsensitiveSuffix(filename, @".jpg")); -} - -- (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 - -{ - NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName]; - RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:NSFilesPromisePboardType, nil]); - - [types.get() addObjectsFromArray:archiveBuffer ? PasteboardTypes::forImagesWithArchive() : PasteboardTypes::forImages()]; - [pasteboard declareTypes:types.get() owner:self]; - if (!matchesExtensionOrEquivalent(filename, extension)) - filename = [[filename stringByAppendingString:@"."] stringByAppendingString:extension]; - - [pasteboard setString:visibleUrl forType:NSStringPboardType]; - [pasteboard setString:visibleUrl forType:PasteboardTypes::WebURLPboardType]; - [pasteboard setString:title forType:PasteboardTypes::WebURLNamePboardType]; - [pasteboard setPropertyList:[NSArray arrayWithObjects:[NSArray arrayWithObject:visibleUrl], [NSArray arrayWithObject:title], nil] forType:PasteboardTypes::WebURLsWithTitlesPboardType]; - [pasteboard setPropertyList:[NSArray arrayWithObject:extension] forType:NSFilesPromisePboardType]; - - if (archiveBuffer) - [pasteboard setData:[archiveBuffer->createNSData() autorelease] forType:PasteboardTypes::WebArchivePboardType]; - - _data->_promisedImage = image; - _data->_promisedFilename = filename; - _data->_promisedURL = url; -} - -- (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard -{ - _data->_promisedImage = 0; - _data->_promisedFilename = ""; - _data->_promisedURL = ""; -} - -- (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type -{ - // FIXME: need to support NSRTFDPboardType - - if ([type isEqual:NSTIFFPboardType] && _data->_promisedImage) { - [pasteboard setData:(NSData *)_data->_promisedImage->getTIFFRepresentation() forType:NSTIFFPboardType]; - _data->_promisedImage = 0; - } -} - -static BOOL fileExists(NSString *path) -{ - struct stat statBuffer; - return !lstat([path fileSystemRepresentation], &statBuffer); -} - -static NSString *pathWithUniqueFilenameForPath(NSString *path) -{ - // "Fix" the filename of the path. - NSString *filename = filenameByFixingIllegalCharacters([path lastPathComponent]); - path = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:filename]; - - if (fileExists(path)) { - // Don't overwrite existing file by appending "-n", "-n.ext" or "-n.ext.ext" to the filename. - NSString *extensions = nil; - NSString *pathWithoutExtensions; - NSString *lastPathComponent = [path lastPathComponent]; - NSRange periodRange = [lastPathComponent rangeOfString:@"."]; - - if (periodRange.location == NSNotFound) { - pathWithoutExtensions = path; - } else { - extensions = [lastPathComponent substringFromIndex:periodRange.location + 1]; - lastPathComponent = [lastPathComponent substringToIndex:periodRange.location]; - pathWithoutExtensions = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:lastPathComponent]; - } - - for (unsigned i = 1; ; i++) { - NSString *pathWithAppendedNumber = [NSString stringWithFormat:@"%@-%d", pathWithoutExtensions, i]; - path = [extensions length] ? [pathWithAppendedNumber stringByAppendingPathExtension:extensions] : pathWithAppendedNumber; - if (!fileExists(path)) - break; - } - } - - return path; -} - -- (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination -{ - RetainPtr<NSFileWrapper> wrapper; - RetainPtr<NSData> data; - - if (_data->_promisedImage) { - data = adoptNS(_data->_promisedImage->data()->createNSData()); - wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]); - [wrapper.get() setPreferredFilename:_data->_promisedFilename]; - } - - if (!wrapper) { - LOG_ERROR("Failed to create image file."); - return nil; - } - - // FIXME: Report an error if we fail to create a file. - NSString *path = [[dropDestination path] stringByAppendingPathComponent:[wrapper.get() preferredFilename]]; - path = pathWithUniqueFilenameForPath(path); - if (![wrapper.get() writeToFile:path atomically:NO updateFilenames:YES]) - LOG_ERROR("Failed to create image file via -[NSFileWrapper writeToFile:atomically:updateFilenames:]"); - - if (!_data->_promisedURL.isEmpty()) - WebCore::setMetadataURL(_data->_promisedURL, "", String(path)); - - return [NSArray arrayWithObject:[path lastPathComponent]]; -} - -- (void)_updateSecureInputState -{ - if (![[self window] isKeyWindow] || ![self _isFocused]) { - if (_data->_inSecureInputState) { - DisableSecureEventInput(); - _data->_inSecureInputState = NO; - } - return; - } - // WKView has a single input context for all editable areas (except for plug-ins). - NSTextInputContext *context = [super inputContext]; - bool isInPasswordField = _data->_page->editorState().isInPasswordField; - - if (isInPasswordField) { - if (!_data->_inSecureInputState) - EnableSecureEventInput(); - static NSArray *romanInputSources = [[NSArray alloc] initWithObjects:&NSAllRomanInputSourcesLocaleIdentifier count:1]; - LOG(TextInput, "-> setAllowedInputSourceLocales:romanInputSources"); - [context setAllowedInputSourceLocales:romanInputSources]; - } else { - if (_data->_inSecureInputState) - DisableSecureEventInput(); - LOG(TextInput, "-> setAllowedInputSourceLocales:nil"); - [context setAllowedInputSourceLocales:nil]; - } - _data->_inSecureInputState = isInPasswordField; -} - -- (void)_resetSecureInputState -{ - if (_data->_inSecureInputState) { - DisableSecureEventInput(); - _data->_inSecureInputState = NO; - } -} - -- (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. -} - -#if ENABLE(FULLSCREEN_API) -- (BOOL)hasFullScreenWindowController -{ - return (bool)_data->_fullScreenWindowController; -} - -- (WKFullScreenWindowController*)fullScreenWindowController -{ - if (!_data->_fullScreenWindowController) { - _data->_fullScreenWindowController = adoptNS([[WKFullScreenWindowController alloc] initWithWindow:[self createFullScreenWindow]]); - [_data->_fullScreenWindowController.get() setWebView:self]; - } - return _data->_fullScreenWindowController.get(); -} - -- (void)closeFullScreenWindowController -{ - if (!_data->_fullScreenWindowController) - return; - [_data->_fullScreenWindowController.get() close]; - _data->_fullScreenWindowController = nullptr; -} -#endif - -- (bool)_executeSavedCommandBySelector:(SEL)selector -{ - // 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]); - [super doCommandBySelector:selector]; - [sink.get() detach]; - return ![sink.get() didReceiveUnhandledCommand]; -} - -- (void)_setIntrinsicContentSize:(NSSize)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 -{ - // FIXME: We should remove this code when <rdar://problem/9362085> is resolved. - NSWindow *window = [self window]; - if (!window) - return; - - _data->_windowBottomCornerIntersectionRect = [window _intersectBottomCornersWithRect:[self convertRect:[self visibleRect] toView:nil]]; - if (!NSIsEmptyRect(_data->_windowBottomCornerIntersectionRect)) - [self setNeedsDisplayInRect:[self convertRect:_data->_windowBottomCornerIntersectionRect fromView:nil]]; -} - -- (NSInteger)spellCheckerDocumentTag -{ - if (!_data->_hasSpellCheckerDocumentTag) { - _data->_spellCheckerDocumentTag = [NSSpellChecker uniqueSpellDocumentTag]; - _data->_hasSpellCheckerDocumentTag = YES; - } - return _data->_spellCheckerDocumentTag; -} - -- (void)handleAcceptedAlternativeText:(NSString*)text -{ - _data->_page->handleAlternativeTextUIResult(text); -} - -- (void)_setSuppressVisibilityUpdates:(BOOL)suppressVisibilityUpdates -{ - _data->_page->setSuppressVisibilityUpdates(suppressVisibilityUpdates); -} - -- (BOOL)_suppressVisibilityUpdates -{ - 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) - -- (void)_registerDraggedTypes -{ - NSMutableSet *types = [[NSMutableSet alloc] initWithArray:PasteboardTypes::forEditing()]; - [types addObjectsFromArray:PasteboardTypes::forURL()]; - [self registerForDraggedTypes:[types allObjects]]; - [types release]; -} - -- (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef -{ - return [self initWithFrame:frame contextRef:contextRef pageGroupRef:pageGroupRef relatedToPage:nil]; -} - -- (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef relatedToPage:(WKPageRef)relatedPage -{ - self = [super initWithFrame:frame]; - if (!self) - return nil; - - [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()]; - - InitWebCoreSystemInterface(); - RunLoop::initializeMainRunLoop(); - - // Legacy style scrollbars have design details that rely on tracking the mouse all the time. - NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingInVisibleRect; - if (WKRecommendedScrollerStyle() == NSScrollerStyleLegacy) - options |= NSTrackingActiveAlways; - else - options |= NSTrackingActiveInKeyWindow; - - NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:frame - options:options - owner:self - userInfo:nil]; - [self addTrackingArea:trackingArea]; - [trackingArea release]; - - _data = [[WKViewData alloc] init]; - - _data->_pageClient = PageClientImpl::create(self); - _data->_page = toImpl(contextRef)->createWebPage(_data->_pageClient.get(), toImpl(pageGroupRef), toImpl(relatedPage)); - _data->_page->setIntrinsicDeviceScaleFactor([self _intrinsicDeviceScaleFactor]); - _data->_page->initializeWebPage(); -#if ENABLE(FULLSCREEN_API) - _data->_page->fullScreenManager()->setWebView(self); -#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]) { - self.wantsLayer = YES; - - // Explicitly set the layer contents placement so AppKit will make sure that our layer has masksToBounds set to YES. - self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft; - } - - WebContext::statistics().wkViewCount++; - - NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter]; - [workspaceNotificationCenter addObserver:self selector:@selector(_activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil]; - - return self; -} - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 -- (BOOL)wantsUpdateLayer -{ - return [self _shouldUseTiledDrawingArea]; -} - -- (void)updateLayer -{ - 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(); -} -#endif - -- (WKPageRef)pageRef -{ - return toAPI(_data->_page.get()); -} - -- (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef -{ - // PDF documents are already paginated, so we can't change them to add headers and footers. - return !toImpl(frameRef)->isDisplayingPDFDocument(); -} - -- (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef -{ - LOG(View, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data()); - - // 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 -{ - ASSERT(NSEqualSizes(_data->_resizeScrollOffset, NSZeroSize)); - - _data->_resizeScrollOffset = offset; - [self setFrame:rect]; -} - -- (void)disableFrameSizeUpdates -{ - _data->_frameSizeUpdatesDisabledCount++; -} - -- (void)enableFrameSizeUpdates -{ - if (!_data->_frameSizeUpdatesDisabledCount) - return; - - if (!(--_data->_frameSizeUpdatesDisabledCount)) { - if (_data->_clipsToVisibleRect) - [self _updateViewExposedRect]; - [self _setDrawingAreaSize:[self frame].size]; - } -} - -- (BOOL)frameSizeUpdatesDisabled -{ - return _data->_frameSizeUpdatesDisabledCount > 0; -} - -- (void)performDictionaryLookupAtCurrentMouseLocation -{ - NSPoint thePoint = [NSEvent mouseLocation]; - thePoint = [[self window] convertScreenToBase:thePoint]; - thePoint = [self convertPoint:thePoint fromView:nil]; - - _data->_page->performDictionaryLookupAtLocation(FloatPoint(thePoint.x, thePoint.y)); -} - -+ (void)hideWordDefinitionWindow -{ - WKHideWordDefinitionWindow(); -} - -- (CGFloat)minimumLayoutWidth -{ - static BOOL loggedDeprecationWarning = NO; - - if (!loggedDeprecationWarning) { - NSLog(@"Please use minimumSizeForAutoLayout instead of minimumLayoutWidth."); - loggedDeprecationWarning = YES; - } - - return self.minimumSizeForAutoLayout.width; -} - -- (void)setMinimumLayoutWidth:(CGFloat)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 - -@implementation WKResponderChainSink - -- (id)initWithResponderChain:(NSResponder *)chain -{ - self = [super init]; - if (!self) - return nil; - _lastResponderInChain = chain; - while (NSResponder *next = [_lastResponderInChain nextResponder]) - _lastResponderInChain = next; - [_lastResponderInChain setNextResponder:self]; - return self; -} - -- (void)detach -{ - // This assumes that the responder chain was either unmodified since - // -initWithResponderChain: was called, or was modified in such a way - // that _lastResponderInChain is still in the chain, and self was not - // moved earlier in the chain than _lastResponderInChain. - NSResponder *responderBeforeSelf = _lastResponderInChain; - NSResponder *next = [responderBeforeSelf nextResponder]; - for (; next && next != self; next = [next nextResponder]) - responderBeforeSelf = next; - - // Nothing to be done if we are no longer in the responder chain. - if (next != self) - return; - - [responderBeforeSelf setNextResponder:[self nextResponder]]; - _lastResponderInChain = nil; -} - -- (bool)didReceiveUnhandledCommand -{ - return _didReceiveUnhandledCommand; -} - -- (void)noResponderFor:(SEL)selector -{ - _didReceiveUnhandledCommand = true; -} - -- (void)doCommandBySelector:(SEL)selector -{ - _didReceiveUnhandledCommand = true; -} - -- (BOOL)tryToPerform:(SEL)action with:(id)object -{ - _didReceiveUnhandledCommand = true; - return YES; -} - -@end diff --git a/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h b/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h deleted file mode 100644 index 8e62c576a..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKViewInternal.h +++ /dev/null @@ -1,101 +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. - */ - -#import "PluginComplexTextInputState.h" -#import "WKView.h" -#import "WebFindOptions.h" -#import <wtf/Forward.h> -#import <wtf/Vector.h> - -namespace CoreIPC { - class DataReference; -} - -namespace WebCore { - struct KeypressCommand; - class Image; - class SharedBuffer; -} - -namespace WebKit { - class DrawingAreaProxy; - class FindIndicator; - class LayerTreeContext; - struct ColorSpaceData; - struct EditorState; -} - -@class WKFullScreenWindowController; - -@interface WKView (Internal) -- (PassOwnPtr<WebKit::DrawingAreaProxy>)_createDrawingAreaProxy; -- (BOOL)_isFocused; -- (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; -- (BOOL)_interpretKeyEvent:(NSEvent *)theEvent savingCommandsTo:(Vector<WebCore::KeypressCommand>&)commands; -- (void)_doneWithKeyEvent:(NSEvent *)event eventWasHandled:(BOOL)eventWasHandled; -- (bool)_executeSavedCommandBySelector:(SEL)selector; -- (void)_setIntrinsicContentSize:(NSSize)intrinsicContentSize; -- (NSRect)_convertToDeviceSpace:(NSRect)rect; -- (NSRect)_convertToUserSpace:(NSRect)rect; -- (void)_setFindIndicator:(PassRefPtr<WebKit::FindIndicator>)findIndicator fadeOut:(BOOL)fadeOut animate:(BOOL)animate; - -- (void)_setAcceleratedCompositingModeRootLayer:(CALayer *)rootLayer; - -- (void)_setAccessibilityWebProcessToken:(NSData *)data; - -- (void)_pluginFocusOrWindowFocusChanged:(BOOL)pluginHasFocusAndWindowHasFocus pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier; -- (void)_setPluginComplexTextInputState:(WebKit::PluginComplexTextInputState)pluginComplexTextInputState pluginComplexTextInputIdentifier:(uint64_t)pluginComplexTextInputIdentifier; - -- (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)_resetSecureInputState; -- (void)_notifyInputContextAboutDiscardedComposition; - -- (WebKit::ColorSpaceData)_colorSpace; - -#if ENABLE(FULLSCREEN_API) -- (BOOL)hasFullScreenWindowController; -- (WKFullScreenWindowController*)fullScreenWindowController; -- (void)closeFullScreenWindowController; -#endif - -- (void)_cacheWindowBottomCornerRect; - -- (NSInteger)spellCheckerDocumentTag; -- (void)handleAcceptedAlternativeText:(NSString*)text; - -- (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 deleted file mode 100644 index a9ff9d30f..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WKViewPrivate.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#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; - -- (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef; -- (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef; - -- (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset; - -// Stops updating the size of the page as the WKView frame size updates. -// This should always be followed by enableFrameSizeUpdates. Calls can be nested. -- (void)disableFrameSizeUpdates; -// Immediately updates the size of the page to match WKView's frame size -// and allows subsequent updates as the frame size is set. Calls can be nested. -- (void)enableFrameSizeUpdates; -- (BOOL)frameSizeUpdatesDisabled; - -- (void)performDictionaryLookupAtCurrentMouseLocation; -+ (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/mac/WebKit2.h b/Source/WebKit2/UIProcess/API/mac/WebKit2.h deleted file mode 100644 index 7a2bd1a23..000000000 --- a/Source/WebKit2/UIProcess/API/mac/WebKit2.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import <WebKit2/WKBrowsingContextController.h> -#import <WebKit2/WKBrowsingContextGroup.h> -#import <WebKit2/WKBrowsingContextLoadDelegate.h> -#import <WebKit2/WKConnection.h> -#import <WebKit2/WKProcessGroup.h> -#import <WebKit2/WKView.h> diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp b/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp index bc2d5d21c..32ac886f3 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview.cpp @@ -594,7 +594,7 @@ void QQuickWebViewPrivate::processDidCrash() { Q_Q(QQuickWebView); - QUrl url(KURL(WebCore::ParsedURLString, webPageProxy->urlAtProcessExit())); + QUrl url(URL(WebCore::ParsedURLString, webPageProxy->urlAtProcessExit())); qWarning("WARNING: The web process experienced a crash on '%s'.", qPrintable(url.toString(QUrl::RemoveUserInfo))); pageEventHandler->resetGestureRecognizers(); @@ -642,9 +642,9 @@ void QQuickWebViewPrivate::processDidBecomeResponsive(WKPageRef, const void* cli emit q->experimental()->processDidBecomeResponsive(); } -PassOwnPtr<DrawingAreaProxy> QQuickWebViewPrivate::createDrawingAreaProxy() +std::unique_ptr<DrawingAreaProxy> QQuickWebViewPrivate::createDrawingAreaProxy() { - return DrawingAreaProxyImpl::create(webPageProxy.get()); + return std::make_unique<WebKit::DrawingAreaProxyImpl>(webPageProxy.get()); } void QQuickWebViewPrivate::handleDownloadRequest(DownloadProxy* download) diff --git a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h index a7358b5cf..2d1e5d911 100644 --- a/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qquickwebview_p_p.h @@ -135,7 +135,7 @@ public: virtual void pageDidRequestScroll(const QPoint& pos) { } void processDidCrash(); void didRelaunchProcess(); - PassOwnPtr<WebKit::DrawingAreaProxy> createDrawingAreaProxy(); + std::unique_ptr<WebKit::DrawingAreaProxy> createDrawingAreaProxy(); void handleDownloadRequest(WebKit::DownloadProxy*); void didReceiveMessageFromNavigatorQtObject(WKStringRef message); diff --git a/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport.cpp b/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport.cpp index 49f14d83b..209596954 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport.cpp @@ -1,32 +1,40 @@ /**************************************************************************** ** ** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com> -** Contact: http://www.qt.io/licensing/ +** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWebChannel module of the Qt Toolkit. ** -** $QT_BEGIN_LICENSE:LGPL21$ +** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see http://www.qt.io/terms-conditions. For further -** information use the contact form at http://www.qt.io/contact-us. +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** -** As a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** ** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport_p.h b/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport_p.h index 11a0b4829..ef6140359 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qwebchannelwebkittransport_p.h @@ -1,32 +1,40 @@ /**************************************************************************** ** ** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com> -** Contact: http://www.qt.io/licensing/ +** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWebChannel module of the Qt Toolkit. ** -** $QT_BEGIN_LICENSE:LGPL21$ +** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see http://www.qt.io/terms-conditions. For further -** information use the contact form at http://www.qt.io/contact-us. +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** As a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** ** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest.cpp b/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest.cpp index 92af27179..7a75c583a 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest.cpp +++ b/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest.cpp @@ -25,12 +25,13 @@ class QWebNavigationRequestPrivate { public: - QWebNavigationRequestPrivate(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType) + QWebNavigationRequestPrivate(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, bool isMainFrame) : url(url) , mouseButton(mouseButton) , keyboardModifiers(keyboardModifiers) , action(QQuickWebView::AcceptRequest) , navigationType(navigationType) + , isMainFrame(isMainFrame) { } @@ -43,11 +44,12 @@ public: Qt::KeyboardModifiers keyboardModifiers; QQuickWebView::NavigationRequestAction action; QQuickWebView::NavigationType navigationType; + bool isMainFrame; }; -QWebNavigationRequest::QWebNavigationRequest(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, QObject* parent) +QWebNavigationRequest::QWebNavigationRequest(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, bool isMainFrame, QObject* parent) : QObject(parent) - , d(new QWebNavigationRequestPrivate(url, mouseButton, keyboardModifiers, navigationType)) + , d(new QWebNavigationRequestPrivate(url, mouseButton, keyboardModifiers, navigationType, isMainFrame)) { } @@ -89,3 +91,8 @@ QQuickWebView::NavigationType QWebNavigationRequest::navigationType() const { return d->navigationType; } + +bool QWebNavigationRequest::isMainFrame() const +{ + return d->isMainFrame; +} diff --git a/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest_p.h b/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest_p.h index b401deda5..312f503bc 100644 --- a/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest_p.h +++ b/Source/WebKit2/UIProcess/API/qt/qwebnavigationrequest_p.h @@ -35,9 +35,10 @@ class QWEBKIT_EXPORT QWebNavigationRequest : public QObject { Q_PROPERTY(int keyboardModifiers READ keyboardModifiers CONSTANT FINAL) Q_PROPERTY(QQuickWebView::NavigationRequestAction action READ action WRITE setAction NOTIFY actionChanged FINAL) Q_PROPERTY(QQuickWebView::NavigationType navigationType READ navigationType CONSTANT FINAL) + Q_PROPERTY(bool isMainFrame READ isMainFrame CONSTANT FINAL REVISION 1) public: - QWebNavigationRequest(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, QObject* parent = 0); + QWebNavigationRequest(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, bool isMainFrame, QObject* parent = 0); ~QWebNavigationRequest(); QUrl url() const; @@ -48,6 +49,8 @@ public: void setAction(QQuickWebView::NavigationRequestAction action); QQuickWebView::NavigationType navigationType() const; + bool isMainFrame() const; + Q_SIGNALS: void actionChanged(); diff --git a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp index 89f729705..31b3d8177 100644 --- a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp +++ b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview.cpp @@ -239,9 +239,9 @@ void QRawWebViewPrivate::doneWithKeyEvent(const WebKit::NativeWebKeyboardEvent& m_client->doneWithKeyEvent(event.nativeEvent(), wasEventHandled); } -PassOwnPtr<WebKit::DrawingAreaProxy> QRawWebViewPrivate::createDrawingAreaProxy() +std::unique_ptr<WebKit::DrawingAreaProxy> QRawWebViewPrivate::createDrawingAreaProxy() { - return WebKit::DrawingAreaProxyImpl::create(m_webPageProxy.get()); + return std::make_unique<WebKit::DrawingAreaProxyImpl>(m_webPageProxy.get()); } QRawWebViewPrivate::QRawWebViewPrivate(WebKit::WebContext* context, WebKit::WebPageGroup* pageGroup, QRawWebViewClient* client) 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 58d6b1390..42ef3d4f6 100644 --- a/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p_p.h +++ b/Source/WebKit2/UIProcess/API/qt/raw/qrawwebview_p_p.h @@ -94,7 +94,7 @@ public: // PageClient - virtual PassOwnPtr<WebKit::DrawingAreaProxy> createDrawingAreaProxy(); + virtual std::unique_ptr<WebKit::DrawingAreaProxy> createDrawingAreaProxy(); virtual void pageDidRequestScroll(const WebCore::IntPoint& pos); virtual void processDidCrash(); diff --git a/Source/WebKit2/UIProcess/API/qt/tests/inspectorserver/inspectorserver.pro b/Source/WebKit2/UIProcess/API/qt/tests/inspectorserver/inspectorserver.pro deleted file mode 100644 index 4a8d86f80..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/inspectorserver/inspectorserver.pro +++ /dev/null @@ -1,4 +0,0 @@ -include(../tests.pri) -SOURCES += $${TARGET}.cpp -QT += webkit-private -DEFINES += IMPORT_DIR=\"\\\"$${ROOT_BUILD_DIR}$${QMAKE_DIR_SEP}imports\\\"\" diff --git a/Source/WebKit2/UIProcess/API/qt/tests/publicapi/publicapi.pro b/Source/WebKit2/UIProcess/API/qt/tests/publicapi/publicapi.pro deleted file mode 100644 index 02dc197c7..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/publicapi/publicapi.pro +++ /dev/null @@ -1,3 +0,0 @@ -include(../tests.pri) -SOURCES += $${TARGET}.cpp -QT += webkit-private diff --git a/Source/WebKit2/UIProcess/API/qt/tests/publicapi/tst_publicapi.cpp b/Source/WebKit2/UIProcess/API/qt/tests/publicapi/tst_publicapi.cpp index 192e1bb1a..c042a3494 100644 --- a/Source/WebKit2/UIProcess/API/qt/tests/publicapi/tst_publicapi.cpp +++ b/Source/WebKit2/UIProcess/API/qt/tests/publicapi/tst_publicapi.cpp @@ -90,6 +90,7 @@ static QStringList expectedAPI = QStringList() << "QWebNavigationRequest.keyboardModifiers --> int" << "QWebNavigationRequest.action --> QQuickWebView::NavigationRequestAction" << "QWebNavigationRequest.navigationType --> QQuickWebView::NavigationType" + << "QWebNavigationRequest.isMainFrame --> bool" << "QWebNavigationRequest.actionChanged() --> void" ; diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/DesktopBehavior.pro b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/DesktopBehavior.pro deleted file mode 100644 index e8ac901f1..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/DesktopBehavior.pro +++ /dev/null @@ -1,18 +0,0 @@ -include(../tests.pri) -SOURCES += tst_qmltests.cpp -TARGET = tst_qmltests_DesktopBehavior -OBJECTS_DIR = .obj_DesktopBehavior - -QT += webkit-private -CONFIG += testcase - -QT += qmltest - -DEFINES += DISABLE_FLICKABLE_VIEWPORT=1 -# Test the QML files under DesktopBehavior in the source repository. -DEFINES += QUICK_TEST_SOURCE_DIR=\"\\\"$$PWD$${QMAKE_DIR_SEP}DesktopBehavior\\\"\" -DEFINES += IMPORT_DIR=\"\\\"$${ROOT_BUILD_DIR}$${QMAKE_DIR_SEP}imports\\\"\" - -OTHER_FILES += \ - DesktopBehavior/* \ - common/* diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView.pro b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView.pro deleted file mode 100644 index 6c67da96e..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView.pro +++ /dev/null @@ -1,19 +0,0 @@ -include(../tests.pri) -SOURCES += tst_qmltests.cpp -TARGET = tst_qmltests_WebView -OBJECTS_DIR = .obj_WebView - -QT += webkit-private -CONFIG += testcase - -QT += qmltest - -# Test the QML files under WebView in the source repository. -DEFINES += QUICK_TEST_SOURCE_DIR=\"\\\"$$PWD$${QMAKE_DIR_SEP}WebView\\\"\" -DEFINES += IMPORT_DIR=\"\\\"$${ROOT_BUILD_DIR}$${QMAKE_DIR_SEP}imports\\\"\" - -OTHER_FILES += \ - WebView/* \ - common/* - -RESOURCES = resources.qrc diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_webchannel.qml b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_webchannel.qml index 26f30eedd..e16b7866e 100644 --- a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_webchannel.qml +++ b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/WebView/tst_webchannel.qml @@ -1,32 +1,40 @@ /**************************************************************************** ** ** Copyright (C) 2014 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com> -** Contact: http://www.qt.io/licensing/ +** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWebChannel module of the Qt Toolkit. ** -** $QT_BEGIN_LICENSE:LGPL21$ +** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see http://www.qt.io/terms-conditions. For further -** information use the contact form at http://www.qt.io/contact-us. +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** -** As a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** ** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/qmltests.pro b/Source/WebKit2/UIProcess/API/qt/tests/qmltests/qmltests.pro deleted file mode 100644 index 8ddc4484e..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/qmltests/qmltests.pro +++ /dev/null @@ -1,3 +0,0 @@ -TEMPLATE = subdirs - -SUBDIRS += DesktopBehavior.pro WebView.pro diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qquickwebview/qquickwebview.pro b/Source/WebKit2/UIProcess/API/qt/tests/qquickwebview/qquickwebview.pro deleted file mode 100644 index 4a8d86f80..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/qquickwebview/qquickwebview.pro +++ /dev/null @@ -1,4 +0,0 @@ -include(../tests.pri) -SOURCES += $${TARGET}.cpp -QT += webkit-private -DEFINES += IMPORT_DIR=\"\\\"$${ROOT_BUILD_DIR}$${QMAKE_DIR_SEP}imports\\\"\" diff --git a/Source/WebKit2/UIProcess/API/qt/tests/qrawwebview/qrawwebview.pro b/Source/WebKit2/UIProcess/API/qt/tests/qrawwebview/qrawwebview.pro deleted file mode 100644 index 02dc197c7..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/qrawwebview/qrawwebview.pro +++ /dev/null @@ -1,3 +0,0 @@ -include(../tests.pri) -SOURCES += $${TARGET}.cpp -QT += webkit-private diff --git a/Source/WebKit2/UIProcess/API/qt/tests/tests.pri b/Source/WebKit2/UIProcess/API/qt/tests/tests.pri deleted file mode 100644 index a1133530d..000000000 --- a/Source/WebKit2/UIProcess/API/qt/tests/tests.pri +++ /dev/null @@ -1,20 +0,0 @@ -TEMPLATE = app - -VPATH += $$_PRO_FILE_PWD_ -TARGET = tst_$$TARGET - -INCLUDEPATH += $$PWD -SOURCES += ../util.cpp - -QT += testlib webkit -have?(QTQUICK) { - QT += qml quick quick-private - HEADERS += ../bytearraytestdata.h \ - ../util.h - - SOURCES += ../bytearraytestdata.cpp -} -WEBKIT += wtf # For platform macros - -DEFINES += TESTS_SOURCE_DIR=\\\"$$PWD\\\" \ - QWP_PATH=\\\"$${ROOT_BUILD_DIR}/bin\\\" diff --git a/Source/WebKit2/UIProcess/efl/WebViewEfl.h b/Source/WebKit2/UIProcess/ApplicationStateTracker.h index d717234c6..5af49dfda 100644 --- a/Source/WebKit2/UIProcess/efl/WebViewEfl.h +++ b/Source/WebKit2/UIProcess/ApplicationStateTracker.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Intel Corporation. All rights reserved. + * Copyright (C) 2015 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,46 +23,47 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebViewEfl_h -#define WebViewEfl_h +#ifndef ApplicationStateTracker_h +#define ApplicationStateTracker_h -#include "WebView.h" +#if PLATFORM(IOS) -class EwkView; +#import "WeakObjCPtr.h" +#import <wtf/Forward.h> +#import <wtf/WeakPtr.h> -namespace WebKit { +OBJC_CLASS BKSApplicationStateMonitor; +OBJC_CLASS UIView; -#if ENABLE(TOUCH_EVENTS) -class EwkTouchEvent; -#endif +namespace WebKit { -class WebViewEfl : public WebView { +class ApplicationStateTracker { public: - void setEwkView(EwkView*); - EwkView* ewkView() { return m_ewkView; } + ApplicationStateTracker(UIView *, SEL didEnterBackgroundSelector, SEL willEnterForegroundSelector); + ~ApplicationStateTracker(); - void paintToCairoSurface(cairo_surface_t*); - void setThemePath(const String&); - -#if ENABLE(TOUCH_EVENTS) - void sendTouchEvent(EwkTouchEvent*); -#endif + bool isInBackground() const { return m_isInBackground; } private: - WebViewEfl(WebContext*, WebPageGroup*); + void applicationDidEnterBackground(); + void applicationWillEnterForeground(); - void setCursor(const WebCore::Cursor&) OVERRIDE; - PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*) OVERRIDE; - PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*) OVERRIDE; - void updateTextInputState() OVERRIDE; - void handleDownloadRequest(DownloadProxy*) OVERRIDE; + WeakObjCPtr<UIView> m_view; + SEL m_didEnterBackgroundSelector; + SEL m_willEnterForegroundSelector; -private: - EwkView* m_ewkView; + bool m_isInBackground; + + WeakPtrFactory<ApplicationStateTracker> m_weakPtrFactory; + + RetainPtr<BKSApplicationStateMonitor> m_applicationStateMonitor; - friend class WebView; + id m_didEnterBackgroundObserver; + id m_willEnterForegroundObserver; }; -} // namespace WebKit +} + +#endif -#endif // WebViewEfl_h +#endif // ApplicationStateTracker_h diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp index 9f64885ae..9bdd73b44 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.cpp @@ -37,7 +37,7 @@ namespace WebKit { -AuthenticationChallengeProxy::AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, CoreIPC::Connection* connection) +AuthenticationChallengeProxy::AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, IPC::Connection* connection) : m_coreAuthenticationChallenge(authenticationChallenge) , m_challengeID(challengeID) , m_connection(connection) @@ -62,15 +62,19 @@ void AuthenticationChallengeProxy::useCredential(WebCredential* credential) if (!m_challengeID) return; - if (!credential) - m_connection->send(Messages::AuthenticationManager::ContinueWithoutCredentialForChallenge(m_challengeID), 0); - else { - WebCertificateInfo* certificateInfo = credential->certificateInfo(); - PlatformCertificateInfo platformInfo = certificateInfo ? certificateInfo->platformCertificateInfo() : PlatformCertificateInfo(); - m_connection->send(Messages::AuthenticationManager::UseCredentialForChallenge(m_challengeID, credential->core(), platformInfo), 0); + uint64_t challengeID = m_challengeID; + m_challengeID = 0; + + if (!credential) { + m_connection->send(Messages::AuthenticationManager::ContinueWithoutCredentialForChallenge(challengeID), 0); + return; } - m_challengeID = 0; + WebCore::CertificateInfo certificateInfo; + if (credential->certificateInfo()) + certificateInfo = credential->certificateInfo()->certificateInfo(); + + m_connection->send(Messages::AuthenticationManager::UseCredentialForChallenge(challengeID, credential->credential(), certificateInfo), 0); } void AuthenticationChallengeProxy::cancel() @@ -83,6 +87,26 @@ void AuthenticationChallengeProxy::cancel() m_challengeID = 0; } +void AuthenticationChallengeProxy::performDefaultHandling() +{ + if (!m_challengeID) + return; + + m_connection->send(Messages::AuthenticationManager::PerformDefaultHandling(m_challengeID), 0); + + m_challengeID = 0; +} + +void AuthenticationChallengeProxy::rejectProtectionSpaceAndContinue() +{ + if (!m_challengeID) + return; + + m_connection->send(Messages::AuthenticationManager::RejectProtectionSpaceAndContinue(m_challengeID), 0); + + m_challengeID = 0; +} + WebCredential* AuthenticationChallengeProxy::proposedCredential() const { if (!m_webCredential) diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h index ce3d6d6e5..9bac83f40 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationChallengeProxy.h @@ -30,7 +30,7 @@ #include <WebCore/AuthenticationChallenge.h> #include <wtf/PassRefPtr.h> -namespace CoreIPC { +namespace IPC { class Connection; } @@ -41,17 +41,19 @@ class ChildProcessProxy; class WebCredential; class WebProtectionSpace; -class AuthenticationChallengeProxy : public TypedAPIObject<APIObject::TypeAuthenticationChallenge> { +class AuthenticationChallengeProxy : public API::ObjectImpl<API::Object::Type::AuthenticationChallenge> { public: - static PassRefPtr<AuthenticationChallengeProxy> create(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, CoreIPC::Connection* connection) + static Ref<AuthenticationChallengeProxy> create(const WebCore::AuthenticationChallenge& authenticationChallenge, uint64_t challengeID, IPC::Connection* connection) { - return adoptRef(new AuthenticationChallengeProxy(authenticationChallenge, challengeID, connection)); + return adoptRef(*new AuthenticationChallengeProxy(authenticationChallenge, challengeID, connection)); } ~AuthenticationChallengeProxy(); void useCredential(WebCredential*); void cancel(); + void performDefaultHandling(); + void rejectProtectionSpaceAndContinue(); AuthenticationDecisionListener* listener() const { return m_listener.get(); } WebCredential* proposedCredential() const; @@ -60,11 +62,11 @@ public: const WebCore::AuthenticationChallenge& core() { return m_coreAuthenticationChallenge; } private: - AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge&, uint64_t challengeID, CoreIPC::Connection*); + AuthenticationChallengeProxy(const WebCore::AuthenticationChallenge&, uint64_t challengeID, IPC::Connection*); WebCore::AuthenticationChallenge m_coreAuthenticationChallenge; uint64_t m_challengeID; - RefPtr<CoreIPC::Connection> m_connection; + RefPtr<IPC::Connection> m_connection; RefPtr<AuthenticationDecisionListener> m_listener; mutable RefPtr<WebCredential> m_webCredential; mutable RefPtr<WebProtectionSpace> m_webProtectionSpace; diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.cpp b/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.cpp index 00cd8748c..8bde289e3 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.cpp +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.cpp @@ -52,6 +52,18 @@ void AuthenticationDecisionListener::cancel() m_challengeProxy->cancel(); } +void AuthenticationDecisionListener::performDefaultHandling() +{ + if (m_challengeProxy) + m_challengeProxy->performDefaultHandling(); +} + +void AuthenticationDecisionListener::rejectProtectionSpaceAndContinue() +{ + if (m_challengeProxy) + m_challengeProxy->rejectProtectionSpaceAndContinue(); +} + void AuthenticationDecisionListener::detachChallenge() { m_challengeProxy = 0; diff --git a/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h b/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h index 940a65021..b5bd2b09a 100644 --- a/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h +++ b/Source/WebKit2/UIProcess/Authentication/AuthenticationDecisionListener.h @@ -35,16 +35,18 @@ namespace WebKit { class AuthenticationChallengeProxy; class WebCredential; -class AuthenticationDecisionListener : public TypedAPIObject<APIObject::TypeAuthenticationDecisionListener> { +class AuthenticationDecisionListener : public API::ObjectImpl<API::Object::Type::AuthenticationDecisionListener> { public: - static PassRefPtr<AuthenticationDecisionListener> create(AuthenticationChallengeProxy* authenticationChallenge) + static Ref<AuthenticationDecisionListener> create(AuthenticationChallengeProxy* authenticationChallenge) { - return adoptRef(new AuthenticationDecisionListener(authenticationChallenge)); + return adoptRef(*new AuthenticationDecisionListener(authenticationChallenge)); } void useCredential(WebCredential*); void cancel(); - + void performDefaultHandling(); + void rejectProtectionSpaceAndContinue(); + void detachChallenge(); private: diff --git a/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp b/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp index a69d509c7..a2d1d17cd 100644 --- a/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp +++ b/Source/WebKit2/UIProcess/Authentication/WebCredential.cpp @@ -49,14 +49,9 @@ WebCertificateInfo* WebCredential::certificateInfo() return m_certificateInfo.get(); } -const WebCore::Credential& WebCredential::core() +const WebCore::Credential& WebCredential::credential() { return m_coreCredential; } -const String& WebCredential::user() const -{ - return m_coreCredential.user(); -} - } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Authentication/WebCredential.h b/Source/WebKit2/UIProcess/Authentication/WebCredential.h index a957e7827..eaaa1f70c 100644 --- a/Source/WebKit2/UIProcess/Authentication/WebCredential.h +++ b/Source/WebKit2/UIProcess/Authentication/WebCredential.h @@ -27,41 +27,31 @@ #define WebCredential_h #include "APIObject.h" -#include "WebString.h" - +#include "APIString.h" #include <WebCore/Credential.h> -#include <wtf/PassRefPtr.h> - namespace WebKit { class WebCertificateInfo; -class WebCredential : public TypedAPIObject<APIObject::TypeCredential> { +class WebCredential : public API::ObjectImpl<API::Object::Type::Credential> { public: ~WebCredential(); - static PassRefPtr<WebCredential> create(const WebCore::Credential& credential) + static Ref<WebCredential> create(const WebCore::Credential& credential) { - return adoptRef(new WebCredential(credential)); + return adoptRef(*new WebCredential(credential)); } - static PassRefPtr<WebCredential> create(WebString* username, WebString* password, WebCore::CredentialPersistence persistence) - { - return adoptRef(new WebCredential(WebCore::Credential(username->string(), password->string(), persistence))); - } - - static PassRefPtr<WebCredential> create(WebCertificateInfo* certificateInfo) + static Ref<WebCredential> create(WebCertificateInfo* certificateInfo) { - return adoptRef(new WebCredential(certificateInfo)); + return adoptRef(*new WebCredential(certificateInfo)); } WebCertificateInfo* certificateInfo(); - const WebCore::Credential& core(); + const WebCore::Credential& credential(); - const String& user() const; - private: explicit WebCredential(const WebCore::Credential&); explicit WebCredential(WebCertificateInfo*); diff --git a/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h b/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h index 4d4905fe9..28beba6e8 100644 --- a/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h +++ b/Source/WebKit2/UIProcess/Authentication/WebProtectionSpace.h @@ -28,15 +28,14 @@ #include "APIObject.h" #include <WebCore/ProtectionSpace.h> -#include <wtf/PassRefPtr.h> namespace WebKit { -class WebProtectionSpace : public TypedAPIObject<APIObject::TypeProtectionSpace> { +class WebProtectionSpace : public API::ObjectImpl<API::Object::Type::ProtectionSpace> { public: - static PassRefPtr<WebProtectionSpace> create(const WebCore::ProtectionSpace& protectionSpace) + static Ref<WebProtectionSpace> create(const WebCore::ProtectionSpace& protectionSpace) { - return adoptRef(new WebProtectionSpace(protectionSpace)); + return adoptRef(*new WebProtectionSpace(protectionSpace)); } const String& protocol() const; @@ -48,6 +47,8 @@ public: bool receivesCredentialSecurely() const; WebCore::ProtectionSpaceAuthenticationScheme authenticationScheme() const; + const WebCore::ProtectionSpace& protectionSpace() const { return m_coreProtectionSpace; } + private: explicit WebProtectionSpace(const WebCore::ProtectionSpace&); diff --git a/Source/WebKit2/UIProcess/AutoCorrectionCallback.h b/Source/WebKit2/UIProcess/AutoCorrectionCallback.h new file mode 100644 index 000000000..752e4cc58 --- /dev/null +++ b/Source/WebKit2/UIProcess/AutoCorrectionCallback.h @@ -0,0 +1,43 @@ +/* + * 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 AutoCorrectionCallback_h +#define AutoCorrectionCallback_h + +#include "APIError.h" +#include "GenericCallback.h" +#include "WKAPICast.h" +#include <wtf/HashMap.h> +#include <wtf/RefCounted.h> + +namespace WebKit { + +typedef GenericCallback<const Vector<WebCore::FloatRect>&, const String&, double, uint64_t> AutocorrectionDataCallback; +typedef GenericCallback<const String&, const String&, const String&, const String&, uint64_t, uint64_t> AutocorrectionContextCallback; +typedef GenericCallback<const String&, const String&, const String&> DictationContextCallback; + +} // namespace WebKit + +#endif // AutoCorrectionCallback_h diff --git a/Source/WebKit2/UIProcess/BackingStore.cpp b/Source/WebKit2/UIProcess/BackingStore.cpp index 30ec8e629..f90d91cff 100644 --- a/Source/WebKit2/UIProcess/BackingStore.cpp +++ b/Source/WebKit2/UIProcess/BackingStore.cpp @@ -33,12 +33,7 @@ using namespace WebCore; namespace WebKit { -PassOwnPtr<BackingStore> BackingStore::create(const IntSize& size, float deviceScaleFactor, WebPageProxy* webPageProxy) -{ - return adoptPtr(new BackingStore(size, deviceScaleFactor, webPageProxy)); -} - -BackingStore::BackingStore(const IntSize& size, float deviceScaleFactor, WebPageProxy* webPageProxy) +BackingStore::BackingStore(const IntSize& size, float deviceScaleFactor, WebPageProxy& webPageProxy) : m_size(size) , m_deviceScaleFactor(deviceScaleFactor) , m_webPageProxy(webPageProxy) diff --git a/Source/WebKit2/UIProcess/BackingStore.h b/Source/WebKit2/UIProcess/BackingStore.h index 7c2613feb..43c9d9031 100644 --- a/Source/WebKit2/UIProcess/BackingStore.h +++ b/Source/WebKit2/UIProcess/BackingStore.h @@ -28,11 +28,6 @@ #include <WebCore/IntRect.h> #include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> - -#if PLATFORM(MAC) -#include <wtf/RetainPtr.h> -#endif #if PLATFORM(QT) #include <QtGui/QPainter> @@ -40,8 +35,7 @@ #endif #if USE(CAIRO) -#include <RefPtrCairo.h> -#include <WebCore/WidgetBackingStore.h> +#include <WebCore/BackingStoreBackendCairo.h> #endif namespace WebKit { @@ -54,15 +48,13 @@ class BackingStore { WTF_MAKE_NONCOPYABLE(BackingStore); public: - static PassOwnPtr<BackingStore> create(const WebCore::IntSize&, float deviceScaleFactor, WebPageProxy*); + BackingStore(const WebCore::IntSize&, float deviceScaleFactor, WebPageProxy&); ~BackingStore(); const WebCore::IntSize& size() const { return m_size; } float deviceScaleFactor() const { return m_deviceScaleFactor; } -#if PLATFORM(MAC) - typedef CGContextRef PlatformGraphicsContext; -#elif PLATFORM(QT) +#if PLATFORM(QT) typedef QPainter* PlatformGraphicsContext; #elif USE(CAIRO) typedef cairo_t* PlatformGraphicsContext; @@ -72,34 +64,20 @@ public: void incorporateUpdate(const UpdateInfo&); private: - BackingStore(const WebCore::IntSize&, float deviceScaleFactor, WebPageProxy*); - void incorporateUpdate(ShareableBitmap*, const UpdateInfo&); void scroll(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); +#if USE(CAIRO) + std::unique_ptr<WebCore::BackingStoreBackendCairo> createBackend(); +#endif + WebCore::IntSize m_size; float m_deviceScaleFactor; - WebPageProxy* m_webPageProxy; - -#if PLATFORM(MAC) - CGContextRef backingStoreContext(); - - void performWithScrolledRectTransform(const WebCore::IntRect&, void (^)(const WebCore::IntRect&, const WebCore::IntSize&)); - void resetScrolledRect(); - - RetainPtr<CGLayerRef> m_cgLayer; - RetainPtr<CGContextRef> m_bitmapContext; - - // The rectange that was scrolled most recently. - WebCore::IntRect m_scrolledRect; - - // Contents of m_scrolledRect are offset by this amount (and wrapped around) with respect to - // their original location. - WebCore::IntSize m_scrolledRectOffset; + WebPageProxy& m_webPageProxy; +#if USE(CAIRO) + std::unique_ptr<WebCore::BackingStoreBackendCairo> m_backend; #elif PLATFORM(QT) QPixmap m_pixmap; -#elif USE(CAIRO) - OwnPtr<WebCore::WidgetBackingStore> m_backingStore; #endif }; diff --git a/Source/WebKit2/UIProcess/ChildProcessProxy.cpp b/Source/WebKit2/UIProcess/ChildProcessProxy.cpp new file mode 100644 index 000000000..a41be8e11 --- /dev/null +++ b/Source/WebKit2/UIProcess/ChildProcessProxy.cpp @@ -0,0 +1,228 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ChildProcessProxy.h" + +#include "ChildProcessMessages.h" +#include <wtf/RunLoop.h> + +namespace WebKit { + +ChildProcessProxy::ChildProcessProxy() +{ +} + +ChildProcessProxy::~ChildProcessProxy() +{ + if (m_connection) + m_connection->invalidate(); + + if (m_processLauncher) { + m_processLauncher->invalidate(); + m_processLauncher = nullptr; + } +} + +ChildProcessProxy* ChildProcessProxy::fromConnection(IPC::Connection* connection) +{ + ASSERT(connection); + + ChildProcessProxy* childProcessProxy = static_cast<ChildProcessProxy*>(connection->client()); + ASSERT(childProcessProxy->connection() == connection); + + return childProcessProxy; +} + +void ChildProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +{ + if (const char* userDirectorySuffix = getenv("DIRHELPER_USER_DIR_SUFFIX")) + launchOptions.extraInitializationData.add(ASCIILiteral("user-directory-suffix"), userDirectorySuffix); + +#if !defined(NDEBUG) && (PLATFORM(GTK) || PLATFORM(EFL)) + const char* varname; + switch (launchOptions.processType) { + case ProcessLauncher::ProcessType::Web: + varname = "WEB_PROCESS_CMD_PREFIX"; + break; +#if ENABLE(NETSCAPE_PLUGIN_API) + case ProcessLauncher::ProcessType::Plugin64: + case ProcessLauncher::ProcessType::Plugin32: + varname = "PLUGIN_PROCESS_CMD_PREFIX"; + break; +#endif + case ProcessLauncher::ProcessType::Network: + varname = "NETWORK_PROCESS_CMD_PREFIX"; + break; +#if ENABLE(DATABASE_PROCESS) + case ProcessLauncher::ProcessType::Database: + varname = "DATABASE_PROCESS_CMD_PREFIX"; + break; +#endif + } + const char* processCmdPrefix = getenv(varname); + if (processCmdPrefix && *processCmdPrefix) + launchOptions.processCmdPrefix = String::fromUTF8(processCmdPrefix); +#endif // !defined(NDEBUG) && (PLATFORM(GTK) || PLATFORM(EFL) +} + +void ChildProcessProxy::connect() +{ + ASSERT(!m_processLauncher); + ProcessLauncher::LaunchOptions launchOptions; + getLaunchOptions(launchOptions); + m_processLauncher = ProcessLauncher::create(this, launchOptions); +} + +void ChildProcessProxy::terminate() +{ +#if PLATFORM(COCOA) + if (m_connection && m_connection->kill()) + return; +#endif + + // FIXME: We should really merge process launching into IPC connection creation and get rid of the process launcher. + if (m_processLauncher) + m_processLauncher->terminateProcess(); +} + +ChildProcessProxy::State ChildProcessProxy::state() const +{ + if (m_processLauncher && m_processLauncher->isLaunching()) + return ChildProcessProxy::State::Launching; + + if (!m_connection) + return ChildProcessProxy::State::Terminated; + + return ChildProcessProxy::State::Running; +} + +bool ChildProcessProxy::sendMessage(std::unique_ptr<IPC::MessageEncoder> encoder, unsigned messageSendFlags) +{ + switch (state()) { + case State::Launching: + // If we're waiting for the child process to launch, we need to stash away the messages so we can send them once we have a connection. + m_pendingMessages.append(std::make_pair(WTFMove(encoder), messageSendFlags)); + return true; + + case State::Running: + return connection()->sendMessage(WTFMove(encoder), messageSendFlags); + + case State::Terminated: + return false; + } + + return false; +} + +void ChildProcessProxy::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver) +{ + m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver); +} + +void ChildProcessProxy::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver) +{ + m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver); +} + +void ChildProcessProxy::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID) +{ + m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID); +} + +void ChildProcessProxy::removeMessageReceiver(IPC::StringReference messageReceiverName) +{ + m_messageReceiverMap.removeMessageReceiver(messageReceiverName); +} + +bool ChildProcessProxy::dispatchMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) +{ + return m_messageReceiverMap.dispatchMessage(connection, decoder); +} + +bool ChildProcessProxy::dispatchSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) +{ + return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder); +} + +void ChildProcessProxy::didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier connectionIdentifier) +{ + ASSERT(!m_connection); + + m_connection = IPC::Connection::createServerConnection(connectionIdentifier, *this); +#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED <= 101000 + m_connection->setShouldCloseConnectionOnMachExceptions(); +#elif PLATFORM(QT) && !OS(WINDOWS) + m_connection->setShouldCloseConnectionOnProcessTermination(processIdentifier()); +#endif + + connectionWillOpen(*m_connection); + m_connection->open(); + + for (size_t i = 0; i < m_pendingMessages.size(); ++i) { + std::unique_ptr<IPC::MessageEncoder> message = WTFMove(m_pendingMessages[i].first); + unsigned messageSendFlags = m_pendingMessages[i].second; + m_connection->sendMessage(WTFMove(message), messageSendFlags); + } + + m_pendingMessages.clear(); +} + +void ChildProcessProxy::shutDownProcess() +{ + switch (state()) { + case State::Launching: + m_processLauncher->invalidate(); + m_processLauncher = nullptr; + break; + case State::Running: +#if PLATFORM(IOS) + // On iOS deploy a watchdog in the UI process, since the child process may be suspended. + // If 30s is insufficient for any outstanding activity to complete cleanly, then it will be killed. + ASSERT(m_connection); + m_connection->terminateSoon(30); +#endif + break; + case State::Terminated: + return; + } + + if (!m_connection) + return; + + processWillShutDown(*m_connection); + + if (canSendMessage()) + send(Messages::ChildProcess::ShutDown(), 0); + + m_connection->invalidate(); + m_connection = nullptr; +} + +void ChildProcessProxy::connectionWillOpen(IPC::Connection&) +{ +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/ChildProcessProxy.h b/Source/WebKit2/UIProcess/ChildProcessProxy.h new file mode 100644 index 000000000..af63f12ac --- /dev/null +++ b/Source/WebKit2/UIProcess/ChildProcessProxy.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2012 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ChildProcessProxy_h +#define ChildProcessProxy_h + +#include "Connection.h" +#include "MessageReceiverMap.h" +#include "ProcessLauncher.h" + +#include <wtf/ThreadSafeRefCounted.h> + +namespace WebKit { + +class ChildProcessProxy : ProcessLauncher::Client, public IPC::Connection::Client, public ThreadSafeRefCounted<ChildProcessProxy> { + WTF_MAKE_NONCOPYABLE(ChildProcessProxy); + +public: + ChildProcessProxy(); + virtual ~ChildProcessProxy(); + + // FIXME: This function does an unchecked upcast, and it is only used in a deprecated code path. Would like to get rid of it. + static ChildProcessProxy* fromConnection(IPC::Connection*); + + void connect(); + void terminate(); + + template<typename T> bool send(T&& message, uint64_t destinationID, unsigned messageSendFlags = 0); + template<typename T> bool sendSync(T&& message, typename T::Reply&&, uint64_t destinationID, std::chrono::milliseconds timeout = std::chrono::seconds(1), unsigned sendSyncFlags = 0); + + IPC::Connection* connection() const + { + ASSERT(m_connection); + return m_connection.get(); + } + + void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&); + void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&); + void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID); + void removeMessageReceiver(IPC::StringReference messageReceiverName); + + enum class State { + Launching, + Running, + Terminated, + }; + State state() const; + + PlatformProcessIdentifier processIdentifier() const { return m_processLauncher->processIdentifier(); } + + bool canSendMessage() const { return state() != State::Terminated;} + bool sendMessage(std::unique_ptr<IPC::MessageEncoder>, unsigned messageSendFlags); + + void shutDownProcess(); + +protected: + // ProcessLauncher::Client + virtual void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override; + + bool dispatchMessage(IPC::Connection&, IPC::MessageDecoder&); + bool dispatchSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&); + + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&); + +private: + virtual void connectionWillOpen(IPC::Connection&); + virtual void processWillShutDown(IPC::Connection&) = 0; + + Vector<std::pair<std::unique_ptr<IPC::MessageEncoder>, unsigned>> m_pendingMessages; + RefPtr<ProcessLauncher> m_processLauncher; + RefPtr<IPC::Connection> m_connection; + IPC::MessageReceiverMap m_messageReceiverMap; +}; + +template<typename T> +bool ChildProcessProxy::send(T&& message, uint64_t destinationID, unsigned messageSendFlags) +{ + COMPILE_ASSERT(!T::isSync, AsyncMessageExpected); + + auto encoder = std::make_unique<IPC::MessageEncoder>(T::receiverName(), T::name(), destinationID); + encoder->encode(message.arguments()); + + return sendMessage(WTFMove(encoder), messageSendFlags); +} + +template<typename U> +bool ChildProcessProxy::sendSync(U&& message, typename U::Reply&& reply, uint64_t destinationID, std::chrono::milliseconds timeout, unsigned sendSyncFlags) +{ + COMPILE_ASSERT(U::isSync, SyncMessageExpected); + + if (!m_connection) + return false; + + return connection()->sendSync(std::forward<U>(message), WTFMove(reply), destinationID, timeout, sendSyncFlags); +} + +} // namespace WebKit + +#endif // ChildProcessProxy_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedDrawingAreaProxy.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedDrawingAreaProxy.cpp new file mode 100644 index 000000000..512b89a18 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedDrawingAreaProxy.cpp @@ -0,0 +1,239 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 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. + */ + +#include "config.h" + +#if USE(COORDINATED_GRAPHICS) +#include "CoordinatedDrawingAreaProxy.h" + +#include "CoordinatedLayerTreeHostProxy.h" +#include "DrawingAreaMessages.h" +#include "DrawingAreaProxyMessages.h" +#include "LayerTreeContext.h" +#include "UpdateInfo.h" +#include "WebPageGroup.h" +#include "WebPageProxy.h" +#include "WebPreferences.h" +#include "WebProcessProxy.h" +#include <WebCore/Region.h> + +using namespace WebCore; + +namespace WebKit { + +CoordinatedDrawingAreaProxy::CoordinatedDrawingAreaProxy(WebPageProxy& webPageProxy) + : DrawingAreaProxy(DrawingAreaTypeCoordinated, webPageProxy) + , m_currentBackingStoreStateID(0) + , m_nextBackingStoreStateID(0) + , m_isWaitingForDidUpdateBackingStoreState(false) + , m_hasReceivedFirstUpdate(false) +{ + // Construct the proxy early to allow messages to be sent to the web process while AC is entered there. + m_coordinatedLayerTreeHostProxy = std::make_unique<CoordinatedLayerTreeHostProxy>(this); +} + +CoordinatedDrawingAreaProxy::~CoordinatedDrawingAreaProxy() +{ + // Make sure to exit accelerated compositing mode. + if (isInAcceleratedCompositingMode()) + exitAcceleratedCompositingMode(); +} + +void CoordinatedDrawingAreaProxy::updateViewport() +{ + m_webPageProxy.setViewNeedsDisplay(viewportVisibleRect()); +} + +WebCore::IntRect CoordinatedDrawingAreaProxy::contentsRect() const +{ + return IntRect(IntPoint::zero(), m_webPageProxy.viewSize()); +} + +void CoordinatedDrawingAreaProxy::sizeDidChange() +{ + backingStoreStateDidChange(RespondImmediately); +} + +void CoordinatedDrawingAreaProxy::deviceScaleFactorDidChange() +{ + backingStoreStateDidChange(RespondImmediately); +} + +void CoordinatedDrawingAreaProxy::visibilityDidChange() +{ + // If we don't have a backing store, go ahead and mark the backing store as being changed so + // that when paint we'll actually wait for something to paint and not flash white. + if (m_layerTreeContext.isEmpty()) + backingStoreStateDidChange(DoNotRespondImmediately); +} + +void CoordinatedDrawingAreaProxy::waitForBackingStoreUpdateOnNextPaint() +{ + m_hasReceivedFirstUpdate = true; +} + +void CoordinatedDrawingAreaProxy::didUpdateBackingStoreState(uint64_t backingStoreStateID, const UpdateInfo& updateInfo, const LayerTreeContext& layerTreeContext) +{ + ASSERT_ARG(backingStoreStateID, backingStoreStateID <= m_nextBackingStoreStateID); + ASSERT_ARG(backingStoreStateID, backingStoreStateID > m_currentBackingStoreStateID); + m_currentBackingStoreStateID = backingStoreStateID; + + m_isWaitingForDidUpdateBackingStoreState = false; + + // Stop the responsiveness timer that was started in sendUpdateBackingStoreState. + m_webPageProxy.process().responsivenessTimer().stop(); + + if (layerTreeContext != m_layerTreeContext) { + if (!m_layerTreeContext.isEmpty()) { + exitAcceleratedCompositingMode(); + ASSERT(m_layerTreeContext.isEmpty()); + } + + if (!layerTreeContext.isEmpty()) { + enterAcceleratedCompositingMode(layerTreeContext); + ASSERT(layerTreeContext == m_layerTreeContext); + } + } + + if (m_nextBackingStoreStateID != m_currentBackingStoreStateID) + sendUpdateBackingStoreState(RespondImmediately); + else + m_hasReceivedFirstUpdate = true; +} + +void CoordinatedDrawingAreaProxy::enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext& layerTreeContext) +{ + ASSERT_ARG(backingStoreStateID, backingStoreStateID <= m_currentBackingStoreStateID); + if (backingStoreStateID < m_currentBackingStoreStateID) + return; + + enterAcceleratedCompositingMode(layerTreeContext); +} + +void CoordinatedDrawingAreaProxy::exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo& updateInfo) +{ + ASSERT_ARG(backingStoreStateID, backingStoreStateID <= m_currentBackingStoreStateID); + if (backingStoreStateID < m_currentBackingStoreStateID) + return; + + exitAcceleratedCompositingMode(); +} + +void CoordinatedDrawingAreaProxy::updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext& layerTreeContext) +{ + ASSERT_ARG(backingStoreStateID, backingStoreStateID <= m_currentBackingStoreStateID); + if (backingStoreStateID < m_currentBackingStoreStateID) + return; + + updateAcceleratedCompositingMode(layerTreeContext); +} + +void CoordinatedDrawingAreaProxy::backingStoreStateDidChange(RespondImmediatelyOrNot respondImmediatelyOrNot) +{ + ++m_nextBackingStoreStateID; + sendUpdateBackingStoreState(respondImmediatelyOrNot); +} + +void CoordinatedDrawingAreaProxy::sendUpdateBackingStoreState(RespondImmediatelyOrNot respondImmediatelyOrNot) +{ + ASSERT(m_currentBackingStoreStateID < m_nextBackingStoreStateID); + + if (!m_webPageProxy.isValid()) + return; + + if (m_isWaitingForDidUpdateBackingStoreState) + return; + + if (m_webPageProxy.viewSize().isEmpty() && !m_webPageProxy.useFixedLayout()) + return; + + m_isWaitingForDidUpdateBackingStoreState = respondImmediatelyOrNot == RespondImmediately; + + m_webPageProxy.process().send(Messages::DrawingArea::UpdateBackingStoreState(m_nextBackingStoreStateID, respondImmediatelyOrNot == RespondImmediately, m_webPageProxy.deviceScaleFactor(), m_size, m_scrollOffset), m_webPageProxy.pageID()); + m_scrollOffset = IntSize(); + + if (m_isWaitingForDidUpdateBackingStoreState) { + // Start the responsiveness timer. We will stop it when we hear back from the WebProcess + // in didUpdateBackingStoreState. + m_webPageProxy.process().responsivenessTimer().start(); + } + + if (m_isWaitingForDidUpdateBackingStoreState && !m_layerTreeContext.isEmpty()) { + // Wait for the DidUpdateBackingStoreState message. Normally we do this in CoordinatedDrawingAreaProxy::paint, but that + // function is never called when in accelerated compositing mode. + waitForAndDispatchDidUpdateBackingStoreState(); + } +} + +void CoordinatedDrawingAreaProxy::waitForAndDispatchDidUpdateBackingStoreState() +{ + ASSERT(m_isWaitingForDidUpdateBackingStoreState); + + if (!m_webPageProxy.isValid()) + return; + if (m_webPageProxy.process().state() == WebProcessProxy::State::Launching) + return; + + // FIXME: waitForAndDispatchImmediately will always return the oldest DidUpdateBackingStoreState message that + // hasn't yet been processed. But it might be better to skip ahead to some other DidUpdateBackingStoreState + // message, if multiple DidUpdateBackingStoreState messages are waiting to be processed. For instance, we could + // choose the most recent one, or the one that is closest to our current size. + + // The timeout, in seconds, we use when waiting for a DidUpdateBackingStoreState message when we're asked to paint. + m_webPageProxy.process().connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateBackingStoreState>(m_webPageProxy.pageID(), std::chrono::milliseconds(500)); +} + +void CoordinatedDrawingAreaProxy::enterAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) +{ + ASSERT(!isInAcceleratedCompositingMode()); + + m_layerTreeContext = layerTreeContext; + m_webPageProxy.enterAcceleratedCompositingMode(layerTreeContext); +} + +void CoordinatedDrawingAreaProxy::setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, const WebCore::FloatPoint& trajectoryVector) +{ + m_coordinatedLayerTreeHostProxy->setVisibleContentsRect(visibleContentsRect, trajectoryVector); +} + +void CoordinatedDrawingAreaProxy::exitAcceleratedCompositingMode() +{ + ASSERT(isInAcceleratedCompositingMode()); + + m_layerTreeContext = LayerTreeContext(); + m_webPageProxy.exitAcceleratedCompositingMode(); +} + +void CoordinatedDrawingAreaProxy::updateAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) +{ + ASSERT(isInAcceleratedCompositingMode()); + + m_layerTreeContext = layerTreeContext; + m_webPageProxy.updateAcceleratedCompositingMode(layerTreeContext); +} + +} // namespace WebKit +#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedDrawingAreaProxy.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedDrawingAreaProxy.h new file mode 100644 index 000000000..bef7730d0 --- /dev/null +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedDrawingAreaProxy.h @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 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 CoordinatedDrawingAreaProxy_h +#define CoordinatedDrawingAreaProxy_h + +#if USE(COORDINATED_GRAPHICS) + +#include "BackingStore.h" +#include "DrawingAreaProxy.h" +#include "LayerTreeContext.h" +#include <wtf/RunLoop.h> + +namespace WebCore { +class Region; +} + +namespace WebKit { + +class CoordinatedLayerTreeHostProxy; + +class CoordinatedDrawingAreaProxy : public DrawingAreaProxy { +public: + explicit CoordinatedDrawingAreaProxy(WebPageProxy&); + virtual ~CoordinatedDrawingAreaProxy(); + + bool isInAcceleratedCompositingMode() const { return !m_layerTreeContext.isEmpty(); } + void visibilityDidChange(); + + void setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, const WebCore::FloatPoint& trajectory); + + bool hasReceivedFirstUpdate() const { return m_hasReceivedFirstUpdate; } + + CoordinatedLayerTreeHostProxy& coordinatedLayerTreeHostProxy() const { return *m_coordinatedLayerTreeHostProxy.get(); } + + WebCore::IntRect viewportVisibleRect() const { return contentsRect(); } + WebCore::IntRect contentsRect() const; + void updateViewport(); + + WebPageProxy& page() { return m_webPageProxy; } +private: + // DrawingAreaProxy + virtual void sizeDidChange(); + virtual void deviceScaleFactorDidChange(); + + virtual void waitForBackingStoreUpdateOnNextPaint(); + + // IPC message handlers + virtual void didUpdateBackingStoreState(uint64_t backingStoreStateID, const UpdateInfo&, const LayerTreeContext&); + virtual void enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&); + virtual void exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo&); + virtual void updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&); + + enum RespondImmediatelyOrNot { DoNotRespondImmediately, RespondImmediately }; + void backingStoreStateDidChange(RespondImmediatelyOrNot); + void sendUpdateBackingStoreState(RespondImmediatelyOrNot); + void waitForAndDispatchDidUpdateBackingStoreState(); + + void enterAcceleratedCompositingMode(const LayerTreeContext&); + void exitAcceleratedCompositingMode(); + void updateAcceleratedCompositingMode(const LayerTreeContext&); + + std::unique_ptr<CoordinatedLayerTreeHostProxy> m_coordinatedLayerTreeHostProxy; + + // The state ID corresponding to our current backing store. Updated whenever we allocate + // a new backing store. Any messages received that correspond to an earlier state are ignored, + // as they don't apply to our current backing store. + uint64_t m_currentBackingStoreStateID; + + // The next backing store state ID we will request the web process update to. Incremented + // whenever our state changes in a way that will require a new backing store to be allocated. + uint64_t m_nextBackingStoreStateID; + + // The current layer tree context. + LayerTreeContext m_layerTreeContext; + + // Whether we've sent a UpdateBackingStoreState message and are now waiting for a DidUpdateBackingStoreState message. + // Used to throttle UpdateBackingStoreState messages so we don't send them faster than the Web process can handle. + bool m_isWaitingForDidUpdateBackingStoreState; + + // For a new Drawing Area don't draw anything until the WebProcess has sent over the first content. + bool m_hasReceivedFirstUpdate; +}; + +} // namespace WebKit + +#endif // USE(COORDINATED_GRAPHICS) +#endif // CoordinatedDrawingAreaProxy_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp index d42dcfdf3..de1f0af8e 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.cpp @@ -23,9 +23,9 @@ #if USE(COORDINATED_GRAPHICS) #include "CoordinatedLayerTreeHostProxy.h" +#include "CoordinatedDrawingAreaProxy.h" #include "CoordinatedLayerTreeHostMessages.h" #include "CoordinatedLayerTreeHostProxyMessages.h" -#include "DrawingAreaProxy.h" #include "WebPageProxy.h" #include "WebProcessProxy.h" #include <WebCore/CoordinatedGraphicsState.h> @@ -34,16 +34,16 @@ namespace WebKit { using namespace WebCore; -CoordinatedLayerTreeHostProxy::CoordinatedLayerTreeHostProxy(DrawingAreaProxy* drawingAreaProxy) +CoordinatedLayerTreeHostProxy::CoordinatedLayerTreeHostProxy(CoordinatedDrawingAreaProxy* drawingAreaProxy) : m_drawingAreaProxy(drawingAreaProxy) , m_scene(adoptRef(new CoordinatedGraphicsScene(this))) { - m_drawingAreaProxy->page()->process()->addMessageReceiver(Messages::CoordinatedLayerTreeHostProxy::messageReceiverName(), m_drawingAreaProxy->page()->pageID(), this); + m_drawingAreaProxy->page().process().addMessageReceiver(Messages::CoordinatedLayerTreeHostProxy::messageReceiverName(), m_drawingAreaProxy->page().pageID(), *this); } CoordinatedLayerTreeHostProxy::~CoordinatedLayerTreeHostProxy() { - m_drawingAreaProxy->page()->process()->removeMessageReceiver(Messages::CoordinatedLayerTreeHostProxy::messageReceiverName(), m_drawingAreaProxy->page()->pageID()); + m_drawingAreaProxy->page().process().removeMessageReceiver(Messages::CoordinatedLayerTreeHostProxy::messageReceiverName(), m_drawingAreaProxy->page().pageID()); m_scene->detach(); } @@ -52,51 +52,47 @@ void CoordinatedLayerTreeHostProxy::updateViewport() m_drawingAreaProxy->updateViewport(); } -void CoordinatedLayerTreeHostProxy::dispatchUpdate(const Function<void()>& function) +void CoordinatedLayerTreeHostProxy::dispatchUpdate(std::function<void()> function) { - m_scene->appendUpdate(function); + m_scene->appendUpdate(WTFMove(function)); } void CoordinatedLayerTreeHostProxy::commitCoordinatedGraphicsState(const CoordinatedGraphicsState& graphicsState) { - dispatchUpdate(bind(&CoordinatedGraphicsScene::commitSceneState, m_scene.get(), graphicsState)); + RefPtr<CoordinatedGraphicsScene> sceneProtector(m_scene); + dispatchUpdate([=] { + sceneProtector->commitSceneState(graphicsState); + }); + updateViewport(); -#if USE(TILED_BACKING_STORE) - m_drawingAreaProxy->page()->didRenderFrame(graphicsState.contentsSize, graphicsState.coveredRect); +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) + m_drawingAreaProxy->page().didRenderFrame(graphicsState.contentsSize, graphicsState.coveredRect); #endif } void CoordinatedLayerTreeHostProxy::setVisibleContentsRect(const FloatRect& rect, const FloatPoint& trajectoryVector) { - // Inform the renderer to adjust viewport-fixed layers. - dispatchUpdate(bind(&CoordinatedGraphicsScene::setScrollPosition, m_scene.get(), rect.location())); - if (rect == m_lastSentVisibleRect && trajectoryVector == m_lastSentTrajectoryVector) return; - m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::SetVisibleContentsRect(rect, trajectoryVector), m_drawingAreaProxy->page()->pageID()); + m_drawingAreaProxy->page().process().send(Messages::CoordinatedLayerTreeHost::SetVisibleContentsRect(rect, trajectoryVector), m_drawingAreaProxy->page().pageID()); m_lastSentVisibleRect = rect; m_lastSentTrajectoryVector = trajectoryVector; } void CoordinatedLayerTreeHostProxy::renderNextFrame() { - m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::RenderNextFrame(), m_drawingAreaProxy->page()->pageID()); + m_drawingAreaProxy->page().process().send(Messages::CoordinatedLayerTreeHost::RenderNextFrame(), m_drawingAreaProxy->page().pageID()); } void CoordinatedLayerTreeHostProxy::purgeBackingStores() { - m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::PurgeBackingStores(), m_drawingAreaProxy->page()->pageID()); -} - -void CoordinatedLayerTreeHostProxy::setBackgroundColor(const Color& color) -{ - dispatchUpdate(bind(&CoordinatedGraphicsScene::setBackgroundColor, m_scene.get(), color)); + m_drawingAreaProxy->page().process().send(Messages::CoordinatedLayerTreeHost::PurgeBackingStores(), m_drawingAreaProxy->page().pageID()); } void CoordinatedLayerTreeHostProxy::commitScrollOffset(uint32_t layerID, const IntSize& offset) { - m_drawingAreaProxy->page()->process()->send(Messages::CoordinatedLayerTreeHost::CommitScrollOffset(layerID, offset), m_drawingAreaProxy->page()->pageID()); + m_drawingAreaProxy->page().process().send(Messages::CoordinatedLayerTreeHost::CommitScrollOffset(layerID, offset), m_drawingAreaProxy->page().pageID()); } } diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h index 2fb17b3ed..4655423f6 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.h @@ -24,46 +24,45 @@ #if USE(COORDINATED_GRAPHICS) #include "CoordinatedGraphicsArgumentCoders.h" +#include "CoordinatedGraphicsScene.h" #include "MessageReceiver.h" -#include <WebCore/CoordinatedGraphicsScene.h> -#include <wtf/Functional.h> +#include <functional> namespace WebCore { -class CoordinatedGraphicsState; +struct CoordinatedGraphicsState; class IntSize; } namespace WebKit { -class DrawingAreaProxy; +class CoordinatedDrawingAreaProxy; -class CoordinatedLayerTreeHostProxy : public WebCore::CoordinatedGraphicsSceneClient, public CoreIPC::MessageReceiver { +class CoordinatedLayerTreeHostProxy : public CoordinatedGraphicsSceneClient, public IPC::MessageReceiver { WTF_MAKE_NONCOPYABLE(CoordinatedLayerTreeHostProxy); WTF_MAKE_FAST_ALLOCATED; public: - explicit CoordinatedLayerTreeHostProxy(DrawingAreaProxy*); + explicit CoordinatedLayerTreeHostProxy(CoordinatedDrawingAreaProxy*); virtual ~CoordinatedLayerTreeHostProxy(); void commitCoordinatedGraphicsState(const WebCore::CoordinatedGraphicsState&); - void setBackgroundColor(const WebCore::Color&); void setVisibleContentsRect(const WebCore::FloatRect&, const WebCore::FloatPoint& trajectoryVector); - WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene() const { return m_scene.get(); } + CoordinatedGraphicsScene* coordinatedGraphicsScene() const { return m_scene.get(); } - virtual void updateViewport() OVERRIDE; - virtual void renderNextFrame() OVERRIDE; - virtual void purgeBackingStores() OVERRIDE; + virtual void updateViewport() override; + virtual void renderNextFrame() override; + virtual void purgeBackingStores() override; - virtual void commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset); + virtual void commitScrollOffset(uint32_t layerID, const WebCore::IntSize& offset) override; protected: - void dispatchUpdate(const Function<void()>&); + void dispatchUpdate(std::function<void()>); - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - DrawingAreaProxy* m_drawingAreaProxy; - RefPtr<WebCore::CoordinatedGraphicsScene> m_scene; + CoordinatedDrawingAreaProxy* m_drawingAreaProxy; + RefPtr<CoordinatedGraphicsScene> m_scene; WebCore::FloatRect m_lastSentVisibleRect; WebCore::FloatPoint m_lastSentTrajectoryVector; }; diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in index ae84b4395..edb2f0f77 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/CoordinatedLayerTreeHostProxy.messages.in @@ -21,7 +21,6 @@ #if USE(COORDINATED_GRAPHICS) messages -> CoordinatedLayerTreeHostProxy { - CommitCoordinatedGraphicsState(WebCore::CoordinatedGraphicsState state) - SetBackgroundColor(WebCore::Color color) + CommitCoordinatedGraphicsState(struct WebCore::CoordinatedGraphicsState state) } #endif diff --git a/Source/WebKit2/UIProcess/PageViewportController.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/PageViewportController.cpp index 6254cf75d..1715657b8 100644 --- a/Source/WebKit2/UIProcess/PageViewportController.cpp +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/PageViewportController.cpp @@ -20,10 +20,9 @@ */ #include "config.h" - -#if USE(ACCELERATED_COMPOSITING) #include "PageViewportController.h" +#include "CoordinatedDrawingAreaProxy.h" #include "PageViewportControllerClient.h" #include "WebPageProxy.h" #include <WebCore/FloatRect.h> @@ -34,12 +33,7 @@ using namespace WebCore; namespace WebKit { -bool fuzzyCompare(float a, float b, float epsilon) -{ - return std::abs(a - b) < epsilon; -} - -PageViewportController::PageViewportController(WebKit::WebPageProxy* proxy, PageViewportControllerClient* client) +PageViewportController::PageViewportController(WebKit::WebPageProxy* proxy, PageViewportControllerClient& client) : m_webPageProxy(proxy) , m_client(client) , m_allowsUserScaling(false) @@ -49,6 +43,7 @@ PageViewportController::PageViewportController(WebKit::WebPageProxy* proxy, Page , m_pageScaleFactor(1) , m_pendingPositionChange(false) , m_pendingScaleChange(false) + , m_layerTreeStateIsFrozen(false) { // Initializing Viewport Raw Attributes to avoid random negative or infinity scale factors // if there is a race condition between the first layout and setting the viewport attributes for the first time. @@ -60,9 +55,6 @@ PageViewportController::PageViewportController(WebKit::WebPageProxy* proxy, Page // using the viewport size and the final layout size. // To be able to assert for valid scale we initialize it to -1. m_rawAttributes.initialScale = -1; - - ASSERT(m_client); - m_client->setController(this); } float PageViewportController::innerBoundedViewportScale(float viewportScale) const @@ -143,6 +135,12 @@ void PageViewportController::didCommitLoad() // Do not continue to use the content size of the previous page. m_contentsSize = IntSize(); + m_contentsPosition = FloatPoint(); + + m_layerTreeStateIsFrozen = true; + + m_initiallyFitToViewport = true; + // Reset the position to the top, page/history scroll requests may override this before we re-enable rendering. applyPositionAfterRenderingContents(FloatPoint()); } @@ -161,7 +159,7 @@ void PageViewportController::didChangeContentsSize(const IntSize& newSize) } if (minimumScaleUpdated) - m_client->didChangeViewportAttributes(); + m_client.didChangeViewportAttributes(); // We might have pending position change which is now possible. syncVisibleContents(); @@ -174,7 +172,7 @@ void PageViewportController::didRenderFrame(const IntSize& contentsSize, const I // Only update the viewport's contents dimensions along with its render if the // size actually changed since animations on the page trigger DidRenderFrame // messages without causing dimension changes. - m_client->didChangeContentsSize(contentsSize); + m_client.didChangeContentsSize(contentsSize); } m_lastFrameCoveredRect = coveredRect; @@ -188,7 +186,7 @@ void PageViewportController::didRenderFrame(const IntSize& contentsSize, const I if (m_pendingScaleChange) { m_pendingScaleChange = false; - m_client->setPageScaleFactor(m_pageScaleFactor); + m_client.setPageScaleFactor(m_pageScaleFactor); // The scale changed, we have to re-pixel align. m_pendingPositionChange = true; @@ -202,24 +200,28 @@ void PageViewportController::didRenderFrame(const IntSize& contentsSize, const I // There might be rendered frames not covering our requested position yet, wait for it. FloatRect endVisibleContentRect(m_contentsPosition, visibleContentsSize()); if (m_pendingPositionChange && endVisibleContentRect.intersects(coveredRect)) { - m_client->setViewportPosition(m_contentsPosition); + m_client.setViewportPosition(m_contentsPosition); m_pendingPositionChange = false; } + + m_layerTreeStateIsFrozen = false; } void PageViewportController::pageTransitionViewportReady() { - if (!m_rawAttributes.layoutSize.isEmpty()) { + if (!m_rawAttributes.layoutSize.isEmpty() && m_initiallyFitToViewport) { m_hadUserInteraction = false; float initialScale = m_initiallyFitToViewport ? m_minimumScaleToFit : m_rawAttributes.initialScale; applyScaleAfterRenderingContents(innerBoundedViewportScale(initialScale)); } +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) // At this point we should already have received the first viewport arguments and the requested scroll // position for the newly loaded page and sent our reactions to the web process. It's now safe to tell // the web process to start rendering the new page contents and possibly re-use the current tiles. // This assumes that all messages have been handled in order and that nothing has been pushed back on the event loop. m_webPageProxy->commitPageTransitionViewport(); +#endif } void PageViewportController::pageDidRequestScroll(const IntPoint& cssPosition) @@ -233,7 +235,7 @@ void PageViewportController::pageDidRequestScroll(const IntPoint& cssPosition) FloatRect endVisibleContentRect(alignedPosition, visibleContentsSize()); if (m_lastFrameCoveredRect.intersects(endVisibleContentRect)) - m_client->setViewportPosition(alignedPosition); + m_client.setViewportPosition(alignedPosition); else { // Keep the unbound position in case the contents size is changed later on. FloatPoint position = pixelAlignedFloatPoint(FloatPoint(cssPosition)); @@ -247,10 +249,6 @@ void PageViewportController::didChangeViewportSize(const FloatSize& newSize) return; m_viewportSize = newSize; - - // Let the WebProcess know about the new viewport size, so that - // it can resize the content accordingly. - m_webPageProxy->drawingArea()->setSize(roundedIntSize(newSize), IntSize(), IntSize()); } void PageViewportController::didChangeContentsVisibility(const FloatPoint& position, float scale, const FloatPoint& trajectoryVector) @@ -263,21 +261,27 @@ void PageViewportController::didChangeContentsVisibility(const FloatPoint& posit syncVisibleContents(trajectoryVector); } -void PageViewportController::syncVisibleContents(const FloatPoint& trajectoryVector) +bool PageViewportController::syncVisibleContents(const FloatPoint& trajectoryVector) { - DrawingAreaProxy* drawingArea = m_webPageProxy->drawingArea(); + CoordinatedDrawingAreaProxy* drawingArea = static_cast<CoordinatedDrawingAreaProxy*>(m_webPageProxy->drawingArea()); if (!drawingArea || m_viewportSize.isEmpty() || m_contentsSize.isEmpty()) - return; + return false; FloatRect visibleContentsRect(boundContentsPosition(m_contentsPosition), visibleContentsSize()); visibleContentsRect.intersect(FloatRect(FloatPoint::zero(), m_contentsSize)); drawingArea->setVisibleContentsRect(visibleContentsRect, trajectoryVector); - m_client->didChangeVisibleContents(); + if (!m_layerTreeStateIsFrozen) + m_client.didChangeVisibleContents(); + + return true; } void PageViewportController::didChangeViewportAttributes(const WebCore::ViewportAttributes& newAttributes) { + if (!m_initiallyFitToViewport) + return; + if (newAttributes.layoutSize.isEmpty()) return; @@ -296,7 +300,7 @@ void PageViewportController::didChangeViewportAttributes(const WebCore::Viewport m_pendingPositionChange = true; m_pendingScaleChange = true; - m_client->didChangeViewportAttributes(); + m_client.didChangeViewportAttributes(); } FloatSize PageViewportController::visibleContentsSize() const @@ -309,9 +313,13 @@ void PageViewportController::applyScaleAfterRenderingContents(float scale) if (m_pageScaleFactor == scale) return; + float oldPageScaleFactor = m_pageScaleFactor; m_pageScaleFactor = scale; m_pendingScaleChange = true; - syncVisibleContents(); + if (!syncVisibleContents()) { + m_pageScaleFactor = oldPageScaleFactor; + m_webPageProxy->scalePage(m_pageScaleFactor, roundedIntPoint(m_contentsPosition)); + } } void PageViewportController::applyPositionAfterRenderingContents(const FloatPoint& pos) @@ -326,17 +334,18 @@ void PageViewportController::applyPositionAfterRenderingContents(const FloatPoin bool PageViewportController::updateMinimumScaleToFit(bool userInitiatedUpdate) { - if (m_viewportSize.isEmpty() || m_contentsSize.isEmpty()) + if (m_viewportSize.isEmpty() || m_contentsSize.isEmpty() || !m_initiallyFitToViewport || m_hadUserInteraction) return false; - bool currentlyScaledToFit = fuzzyCompare(m_pageScaleFactor, m_minimumScaleToFit, 0.0001); - + // FIXME: Why this arbitrary precision? We likely want to omit the third argument so that + // std::numeric_limits<float>::epsilon() is used instead, similarly to Mac / iOS. + bool currentlyScaledToFit = WTF::areEssentiallyEqual(m_pageScaleFactor, m_minimumScaleToFit, 0.0001f); float minimumScale = WebCore::computeMinimumScaleFactorForContentContained(m_rawAttributes, WebCore::roundedIntSize(m_viewportSize), WebCore::roundedIntSize(m_contentsSize)); if (minimumScale <= 0) return false; - if (!fuzzyCompare(minimumScale, m_minimumScaleToFit, 0.0001)) { + if (!WTF::areEssentiallyEqual(minimumScale, m_minimumScaleToFit, 0.0001f)) { m_minimumScaleToFit = minimumScale; if (!m_webPageProxy->areActiveDOMObjectsAndAnimationsSuspended()) { @@ -345,7 +354,7 @@ bool PageViewportController::updateMinimumScaleToFit(bool userInitiatedUpdate) else { // Ensure the effective scale stays within bounds. float boundedScale = innerBoundedViewportScale(m_pageScaleFactor); - if (!fuzzyCompare(boundedScale, m_pageScaleFactor, 0.0001)) + if (!WTF::areEssentiallyEqual(boundedScale, m_pageScaleFactor, 0.0001f)) applyScaleAfterRenderingContents(boundedScale); } } @@ -356,5 +365,3 @@ bool PageViewportController::updateMinimumScaleToFit(bool userInitiatedUpdate) } } // namespace WebKit - -#endif diff --git a/Source/WebKit2/UIProcess/PageViewportController.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/PageViewportController.h index b8973abbd..e02d7671d 100644 --- a/Source/WebKit2/UIProcess/PageViewportController.h +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/PageViewportController.h @@ -22,12 +22,11 @@ #ifndef PageViewportController_h #define PageViewportController_h -#if USE(ACCELERATED_COMPOSITING) - #include <WebCore/FloatPoint.h> #include <WebCore/FloatRect.h> #include <WebCore/FloatSize.h> #include <WebCore/ViewportArguments.h> +#include <wtf/Noncopyable.h> namespace WebCore { class IntPoint; @@ -44,7 +43,7 @@ class PageViewportController { WTF_MAKE_NONCOPYABLE(PageViewportController); public: - PageViewportController(WebKit::WebPageProxy*, PageViewportControllerClient*); + PageViewportController(WebKit::WebPageProxy*, PageViewportControllerClient&); virtual ~PageViewportController() { } float innerBoundedViewportScale(float) const; @@ -67,6 +66,7 @@ public: float currentScale() const { return m_pageScaleFactor; } void setHadUserInteraction(bool didUserInteract) { m_hadUserInteraction = didUserInteract; } + void setInitiallyFitToViewport(bool initiallyFit) { m_initiallyFitToViewport = initiallyFit; } // Notifications from the viewport. void didChangeViewportSize(const WebCore::FloatSize& newSize); @@ -81,13 +81,13 @@ public: void pageDidRequestScroll(const WebCore::IntPoint& cssPosition); private: - void syncVisibleContents(const WebCore::FloatPoint &trajectoryVector = WebCore::FloatPoint::zero()); + bool syncVisibleContents(const WebCore::FloatPoint &trajectoryVector = WebCore::FloatPoint::zero()); void applyScaleAfterRenderingContents(float scale); void applyPositionAfterRenderingContents(const WebCore::FloatPoint& pos); bool updateMinimumScaleToFit(bool userInitiatedUpdate); WebPageProxy* const m_webPageProxy; - PageViewportControllerClient* m_client; + PageViewportControllerClient& m_client; WebCore::ViewportAttributes m_rawAttributes; @@ -105,12 +105,10 @@ private: bool m_pendingPositionChange; bool m_pendingScaleChange; + bool m_layerTreeStateIsFrozen; WebCore::FloatRect m_lastFrameCoveredRect; }; -bool fuzzyCompare(float, float, float epsilon); - } // namespace WebKit -#endif // USE(ACCELERATED_COMPOSITING) #endif // PageViewportController_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h index fc9f0d608..d33dcdaea 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WKCoordinatedSceneAPICast.h @@ -12,10 +12,10 @@ * 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 + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR @@ -28,21 +28,22 @@ #ifndef WKCoordinatedSceneAPICast_h #define WKCoordinatedSceneAPICast_h -#include <WebKit2/WKCoordinatedScene.h> +#include <WebKit/WKCoordinatedScene.h> namespace WebCore { - -class CoordinatedGraphicsScene; class TextureMapperLayer; +} -} // namespace WebCore +namespace WebKit { -inline WebCore::CoordinatedGraphicsScene* toImpl(WKCoordinatedScene scene) +class CoordinatedGraphicsScene; + +inline WebKit::CoordinatedGraphicsScene* toImpl(WKCoordinatedScene scene) { - return reinterpret_cast<WebCore::CoordinatedGraphicsScene*>(scene); + return reinterpret_cast<WebKit::CoordinatedGraphicsScene*>(scene); } -inline WKCoordinatedScene toAPI(WebCore::CoordinatedGraphicsScene* scene) +inline WKCoordinatedScene toAPI(WebKit::CoordinatedGraphicsScene* scene) { return reinterpret_cast<WKCoordinatedScene>(scene); } @@ -57,4 +58,6 @@ inline WKCoordinatedSceneLayer toAPI(WebCore::TextureMapperLayer* layer) return reinterpret_cast<WKCoordinatedSceneLayer>(layer); } +} // namespace WebKit + #endif // WKCoordinatedSceneAPICast_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebPageProxyCoordinatedGraphics.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebPageProxyCoordinatedGraphics.cpp index e34a9b338..ad73d369f 100644 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebPageProxyCoordinatedGraphics.cpp +++ b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebPageProxyCoordinatedGraphics.cpp @@ -37,6 +37,7 @@ using namespace WebCore; namespace WebKit { +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) void WebPageProxy::findZoomableAreaForPoint(const IntPoint& point, const IntSize& area) { if (!isValid()) @@ -47,8 +48,9 @@ void WebPageProxy::findZoomableAreaForPoint(const IntPoint& point, const IntSize void WebPageProxy::didFindZoomableArea(const IntPoint& target, const IntRect& area) { - m_pageClient->didFindZoomableArea(target, area); + m_pageClient.didFindZoomableArea(target, area); } +#endif } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.cpp deleted file mode 100644 index 293745e48..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.cpp +++ /dev/null @@ -1,515 +0,0 @@ -/* - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#if USE(COORDINATED_GRAPHICS) - -#include "WebView.h" - -#include "CoordinatedLayerTreeHostProxy.h" -#include "DrawingAreaProxyImpl.h" -#include "NotImplemented.h" -#include "WebContextMenuProxy.h" -#include "WebPageProxy.h" -#include <WebCore/CoordinatedGraphicsScene.h> - -#if ENABLE(FULLSCREEN_API) -#include "WebFullScreenManagerProxy.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -WebView::WebView(WebContext* context, WebPageGroup* pageGroup) - : m_focused(false) - , m_visible(false) - , m_contentScaleFactor(1.0) - , m_opacity(1.0) -{ - // Need to call createWebPage after other data members, specifically m_visible, are initialized. - m_page = context->createWebPage(this, pageGroup); - - m_page->pageGroup()->preferences()->setAcceleratedCompositingEnabled(true); - m_page->pageGroup()->preferences()->setForceCompositingMode(true); - - char* debugVisualsEnvironment = getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS"); - bool showDebugVisuals = debugVisualsEnvironment && !strcmp(debugVisualsEnvironment, "1"); - m_page->pageGroup()->preferences()->setCompositingBordersVisible(showDebugVisuals); - m_page->pageGroup()->preferences()->setCompositingRepaintCountersVisible(showDebugVisuals); -} - -WebView::~WebView() -{ - if (m_page->isClosed()) - return; - - m_page->close(); -} - -void WebView::initialize() -{ - m_page->initializeWebPage(); - if (CoordinatedGraphicsScene* scene = coordinatedGraphicsScene()) - scene->setActive(true); -} - -void WebView::setSize(const WebCore::IntSize& size) -{ - if (m_size == size) - return; - - m_size = size; - - updateViewportSize(); -} - -void WebView::setFocused(bool focused) -{ - if (m_focused == focused) - return; - - m_focused = focused; - m_page->viewStateDidChange(WebPageProxy::ViewIsFocused | WebPageProxy::ViewWindowIsActive); -} - -void WebView::setVisible(bool visible) -{ - if (m_visible == visible) - return; - - m_visible = visible; - m_page->viewStateDidChange(WebPageProxy::ViewIsVisible); -} - -void WebView::setUserViewportTranslation(double tx, double ty) -{ - m_userViewportTransform = TransformationMatrix().translate(tx, ty); -} - -IntPoint WebView::userViewportToContents(const IntPoint& point) const -{ - return transformFromScene().mapPoint(point); -} - -IntPoint WebView::userViewportToScene(const WebCore::IntPoint& point) const -{ - return m_userViewportTransform.mapPoint(point); -} - -IntPoint WebView::contentsToUserViewport(const IntPoint& point) const -{ - return transformToScene().mapPoint(point); -} - -void WebView::paintToCurrentGLContext() -{ - CoordinatedGraphicsScene* scene = coordinatedGraphicsScene(); - if (!scene) - return; - - // FIXME: We need to clean up this code as it is split over CoordGfx and Page. - scene->setDrawsBackground(m_page->drawsBackground()); - const FloatRect& viewport = m_userViewportTransform.mapRect(IntRect(IntPoint(), m_size)); - - scene->paintToCurrentGLContext(transformToScene().toTransformationMatrix(), m_opacity, viewport); -} - -void WebView::setDrawsBackground(bool drawsBackground) -{ - m_page->setDrawsBackground(drawsBackground); -} - -bool WebView::drawsBackground() const -{ - return m_page->drawsBackground(); -} - -void WebView::setDrawsTransparentBackground(bool transparentBackground) -{ - m_page->setDrawsTransparentBackground(transparentBackground); -} - -bool WebView::drawsTransparentBackground() const -{ - return m_page->drawsTransparentBackground(); -} - -void WebView::suspendActiveDOMObjectsAndAnimations() -{ - m_page->suspendActiveDOMObjectsAndAnimations(); -} - -void WebView::resumeActiveDOMObjectsAndAnimations() -{ - m_page->resumeActiveDOMObjectsAndAnimations(); -} - -void WebView::setShowsAsSource(bool showsAsSource) -{ - m_page->setMainFrameInViewSourceMode(showsAsSource); -} - -bool WebView::showsAsSource() const -{ - return m_page->mainFrameInViewSourceMode(); -} - -#if ENABLE(FULLSCREEN_API) -bool WebView::exitFullScreen() -{ -#if PLATFORM(EFL) - // FIXME: Implement this for other platforms. - if (!m_page->fullScreenManager()->isFullScreen()) - return false; -#endif - m_page->fullScreenManager()->requestExitFullScreen(); - return true; -} -#endif - -void WebView::initializeClient(const WKViewClient* client) -{ - m_client.initialize(client); -} - -void WebView::didChangeContentsSize(const WebCore::IntSize& size) -{ - if (m_contentsSize == size) - return; - - m_contentsSize = size; - m_client.didChangeContentsSize(this, size); - - updateViewportSize(); -} - -void WebView::didFindZoomableArea(const WebCore::IntPoint& target, const WebCore::IntRect& area) -{ - m_client.didFindZoomableArea(this, target, area); -} - -AffineTransform WebView::transformFromScene() const -{ - return transformToScene().inverse(); -} - -AffineTransform WebView::transformToScene() const -{ - FloatPoint position = -m_contentPosition; - float effectiveScale = m_contentScaleFactor * m_page->deviceScaleFactor(); - position.scale(effectiveScale, effectiveScale); - - TransformationMatrix transform = m_userViewportTransform; - transform.translate(position.x(), position.y()); - transform.scale(effectiveScale); - - return transform.toAffineTransform(); -} - -CoordinatedGraphicsScene* WebView::coordinatedGraphicsScene() -{ - DrawingAreaProxy* drawingArea = m_page->drawingArea(); - if (!drawingArea) - return 0; - - WebKit::CoordinatedLayerTreeHostProxy* layerTreeHostProxy = drawingArea->coordinatedLayerTreeHostProxy(); - if (!layerTreeHostProxy) - return 0; - - return layerTreeHostProxy->coordinatedGraphicsScene(); -} - -void WebView::updateViewportSize() -{ - if (DrawingAreaProxy* drawingArea = page()->drawingArea()) { - // Web Process expects sizes in UI units, and not raw device units. - drawingArea->setSize(roundedIntSize(dipSize()), IntSize(), IntSize()); - FloatRect visibleContentsRect(contentPosition(), visibleContentsSize()); - visibleContentsRect.intersect(FloatRect(FloatPoint(), contentsSize())); - drawingArea->setVisibleContentsRect(visibleContentsRect, FloatPoint()); - } -} - -inline WebCore::FloatSize WebView::dipSize() const -{ - FloatSize dipSize(size()); - dipSize.scale(1 / m_page->deviceScaleFactor()); - - return dipSize; -} - -WebCore::FloatSize WebView::visibleContentsSize() const -{ - FloatSize visibleContentsSize(dipSize()); - visibleContentsSize.scale(1 / m_contentScaleFactor); - - return visibleContentsSize; -} - -// Page Client - -PassOwnPtr<DrawingAreaProxy> WebView::createDrawingAreaProxy() -{ - OwnPtr<DrawingAreaProxy> drawingArea = DrawingAreaProxyImpl::create(page()); - return drawingArea.release(); -} - -void WebView::setViewNeedsDisplay(const WebCore::IntRect& area) -{ - m_client.viewNeedsDisplay(this, area); -} - -void WebView::displayView() -{ - notImplemented(); -} - -void WebView::scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize&) -{ - setViewNeedsDisplay(scrollRect); -} - -WebCore::IntSize WebView::viewSize() -{ - return roundedIntSize(dipSize()); -} - -bool WebView::isViewWindowActive() -{ - notImplemented(); - return true; -} - -bool WebView::isViewFocused() -{ - return isFocused(); -} - -bool WebView::isViewVisible() -{ - return isVisible(); -} - -bool WebView::isViewInWindow() -{ - notImplemented(); - return true; -} - -void WebView::processDidCrash() -{ - m_client.webProcessCrashed(this, m_page->urlAtProcessExit()); -} - -void WebView::didRelaunchProcess() -{ - m_client.webProcessDidRelaunch(this); -} - -void WebView::pageClosed() -{ - notImplemented(); -} - -void WebView::preferencesDidChange() -{ - notImplemented(); -} - -void WebView::toolTipChanged(const String&, const String& newToolTip) -{ - m_client.didChangeTooltip(this, newToolTip); -} - -void WebView::setCursor(const WebCore::Cursor&) -{ - notImplemented(); -} - -void WebView::setCursorHiddenUntilMouseMoves(bool) -{ - notImplemented(); -} - -void WebView::registerEditCommand(PassRefPtr<WebEditCommandProxy> command, WebPageProxy::UndoOrRedo undoOrRedo) -{ - m_undoController.registerEditCommand(command, undoOrRedo); -} - -void WebView::clearAllEditCommands() -{ - m_undoController.clearAllEditCommands(); -} - -bool WebView::canUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - return m_undoController.canUndoRedo(undoOrRedo); -} - -void WebView::executeUndoRedo(WebPageProxy::UndoOrRedo undoOrRedo) -{ - m_undoController.executeUndoRedo(undoOrRedo); -} - -IntPoint WebView::screenToWindow(const IntPoint& point) -{ - notImplemented(); - return point; -} - -IntRect WebView::windowToScreen(const IntRect&) -{ - notImplemented(); - return IntRect(); -} - -void WebView::doneWithKeyEvent(const NativeWebKeyboardEvent&, bool) -{ - notImplemented(); -} - -#if ENABLE(TOUCH_EVENTS) -void WebView::doneWithTouchEvent(const NativeWebTouchEvent& event, bool wasEventHandled) -{ - m_client.doneWithTouchEvent(this, event, wasEventHandled); -} -#endif - -PassRefPtr<WebPopupMenuProxy> WebView::createPopupMenuProxy(WebPageProxy*) -{ - notImplemented(); - return 0; -} - -PassRefPtr<WebContextMenuProxy> WebView::createContextMenuProxy(WebPageProxy*) -{ - notImplemented(); - return 0; -} - -#if ENABLE(INPUT_TYPE_COLOR) -PassRefPtr<WebColorPicker> WebView::createColorPicker(WebPageProxy*, const WebCore::Color&, const WebCore::IntRect&) -{ - notImplemented(); - return 0; -} -#endif - -void WebView::setFindIndicator(PassRefPtr<FindIndicator>, bool, bool) -{ - notImplemented(); -} - -void WebView::enterAcceleratedCompositingMode(const LayerTreeContext&) -{ - if (CoordinatedGraphicsScene* scene = coordinatedGraphicsScene()) - scene->setActive(true); -} - -void WebView::exitAcceleratedCompositingMode() -{ - if (CoordinatedGraphicsScene* scene = coordinatedGraphicsScene()) - scene->setActive(false); -} - -void WebView::updateAcceleratedCompositingMode(const LayerTreeContext&) -{ - notImplemented(); -} - -void WebView::flashBackingStoreUpdates(const Vector<IntRect>&) -{ - notImplemented(); -} - -void WebView::updateTextInputState() -{ - notImplemented(); -} - -void WebView::handleDownloadRequest(DownloadProxy*) -{ - notImplemented(); -} - -FloatRect WebView::convertToDeviceSpace(const FloatRect& userRect) -{ - if (m_page->useFixedLayout()) { - FloatRect result = userRect; - result.scale(m_page->deviceScaleFactor()); - return result; - } - // Legacy mode. - notImplemented(); - return userRect; -} - -FloatRect WebView::convertToUserSpace(const FloatRect& deviceRect) -{ - if (m_page->useFixedLayout()) { - FloatRect result = deviceRect; - result.scale(1 / m_page->deviceScaleFactor()); - return result; - } - // Legacy mode. - notImplemented(); - return deviceRect; -} - -void WebView::didChangeViewportProperties(const WebCore::ViewportAttributes& attr) -{ - m_client.didChangeViewportAttributes(this, attr); -} - -void WebView::pageDidRequestScroll(const IntPoint& position) -{ - FloatPoint uiPosition(position); - uiPosition.scale(contentScaleFactor(), contentScaleFactor()); - setContentPosition(uiPosition); - - m_client.didChangeContentsPosition(this, position); -} - -void WebView::didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) -{ - m_client.didRenderFrame(this, contentsSize, coveredRect); -} - -void WebView::pageTransitionViewportReady() -{ - m_client.didCompletePageTransition(this); -} - -void WebView::findZoomableAreaForPoint(const IntPoint& point, const IntSize& size) -{ - m_page->findZoomableAreaForPoint(transformFromScene().mapPoint(point), transformFromScene().mapSize(size)); -} - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) - diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.h deleted file mode 100644 index e79a238e3..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebView.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebView_h -#define WebView_h - -#if USE(COORDINATED_GRAPHICS) - -#include "APIObject.h" -#include "DefaultUndoController.h" -#include "PageClient.h" -#include "WebContext.h" -#include "WebGeometry.h" -#include "WebPageGroup.h" -#include "WebPageProxy.h" -#include "WebPreferences.h" -#include "WebViewClient.h" -#include <WebCore/TransformationMatrix.h> - -namespace WebCore { -class CoordinatedGraphicsScene; -} - -namespace WebKit { - -class WebView : public TypedAPIObject<APIObject::TypeView>, public PageClient { -public: - virtual ~WebView(); - - static PassRefPtr<WebView> create(WebContext*, WebPageGroup*); - - void initialize(); - - void setSize(const WebCore::IntSize&); - const WebCore::IntSize& size() const { return m_size; } - - bool isFocused() const { return m_focused; } - void setFocused(bool); - - bool isVisible() const { return m_visible; } - void setVisible(bool); - - void setContentScaleFactor(float scaleFactor) { m_contentScaleFactor = scaleFactor; } - float contentScaleFactor() const { return m_contentScaleFactor; } - - void setContentPosition(const WebCore::FloatPoint& position) { m_contentPosition = position; } - const WebCore::FloatPoint& contentPosition() const { return m_contentPosition; } - - void setUserViewportTranslation(double tx, double ty); - WebCore::IntPoint userViewportToContents(const WebCore::IntPoint&) const; - WebCore::IntPoint userViewportToScene(const WebCore::IntPoint&) const; - WebCore::IntPoint contentsToUserViewport(const WebCore::IntPoint&) const; - - void paintToCurrentGLContext(); - - WKPageRef pageRef() const { return toAPI(m_page.get()); } - - void setDrawsBackground(bool); - bool drawsBackground() const; - void setDrawsTransparentBackground(bool); - bool drawsTransparentBackground() const; - - void suspendActiveDOMObjectsAndAnimations(); - void resumeActiveDOMObjectsAndAnimations(); - - void setShowsAsSource(bool); - bool showsAsSource() const; - -#if ENABLE(FULLSCREEN_API) - bool exitFullScreen(); -#endif - - void findZoomableAreaForPoint(const WebCore::IntPoint&, const WebCore::IntSize&); - - // View client. - void initializeClient(const WKViewClient*); - - WebPageProxy* page() { return m_page.get(); } - - void didChangeContentsSize(const WebCore::IntSize&); - const WebCore::IntSize& contentsSize() const { return m_contentsSize; } - WebCore::FloatSize visibleContentsSize() const; - void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&); - - // FIXME: Should become private when Web Events creation is moved to WebView. - WebCore::AffineTransform transformFromScene() const; - WebCore::AffineTransform transformToScene() const; - - void setOpacity(double opacity) { m_opacity = clampTo(opacity, 0.0, 1.0); } - double opacity() const { return m_opacity; } - -protected: - WebView(WebContext*, WebPageGroup*); - WebCore::CoordinatedGraphicsScene* coordinatedGraphicsScene(); - - void updateViewportSize(); - WebCore::FloatSize dipSize() const; - // PageClient - virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy() OVERRIDE; - - virtual void setViewNeedsDisplay(const WebCore::IntRect&) OVERRIDE; - - virtual void displayView() OVERRIDE; - - virtual bool canScrollView() OVERRIDE { return false; } - virtual void scrollView(const WebCore::IntRect&, const WebCore::IntSize&) OVERRIDE; - - virtual WebCore::IntSize viewSize() OVERRIDE; - - virtual bool isViewWindowActive() OVERRIDE; - virtual bool isViewFocused() OVERRIDE; - virtual bool isViewVisible() OVERRIDE; - virtual bool isViewInWindow() OVERRIDE; - - virtual void processDidCrash() OVERRIDE; - virtual void didRelaunchProcess() OVERRIDE; - virtual void pageClosed() OVERRIDE; - - virtual void preferencesDidChange() OVERRIDE; - - virtual void toolTipChanged(const String&, const String&) OVERRIDE; - - virtual void pageDidRequestScroll(const WebCore::IntPoint&) OVERRIDE; - virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) OVERRIDE; - virtual void pageTransitionViewportReady() OVERRIDE; - - virtual void setCursor(const WebCore::Cursor&) OVERRIDE; - virtual void setCursorHiddenUntilMouseMoves(bool) OVERRIDE; - - virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&) OVERRIDE; - - virtual void registerEditCommand(PassRefPtr<WebEditCommandProxy>, WebPageProxy::UndoOrRedo) OVERRIDE; - virtual void clearAllEditCommands() OVERRIDE; - virtual bool canUndoRedo(WebPageProxy::UndoOrRedo) OVERRIDE; - virtual void executeUndoRedo(WebPageProxy::UndoOrRedo) OVERRIDE; - - virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&) OVERRIDE; - virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&) OVERRIDE; - virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&) OVERRIDE; - virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&) OVERRIDE; - - virtual void updateTextInputState() OVERRIDE; - - virtual void handleDownloadRequest(DownloadProxy*) OVERRIDE; - - virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool) OVERRIDE; -#if ENABLE(TOUCH_EVENTS) - virtual void doneWithTouchEvent(const NativeWebTouchEvent&, bool wasEventHandled) OVERRIDE; -#endif - - virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*) OVERRIDE; - virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*) OVERRIDE; -#if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&) OVERRIDE; -#endif - - virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool, bool) OVERRIDE; - - virtual void enterAcceleratedCompositingMode(const LayerTreeContext&) OVERRIDE; - virtual void exitAcceleratedCompositingMode() OVERRIDE; - virtual void updateAcceleratedCompositingMode(const LayerTreeContext&) OVERRIDE; - - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>&) OVERRIDE; - -protected: - WebViewClient m_client; - RefPtr<WebPageProxy> m_page; - DefaultUndoController m_undoController; - WebCore::TransformationMatrix m_userViewportTransform; - WebCore::IntSize m_size; // Size in device units. - bool m_focused; - bool m_visible; - float m_contentScaleFactor; - double m_opacity; - WebCore::FloatPoint m_contentPosition; // Position in UI units. - WebCore::IntSize m_contentsSize; -}; - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) - -#endif // WebView_h diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.cpp b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.cpp deleted file mode 100644 index f75de5023..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#if USE(COORDINATED_GRAPHICS) - -#include "WebViewClient.h" - -#include "NotImplemented.h" -#include "WKAPICast.h" -#include "WKBase.h" -#include "WKRetainPtr.h" -#include "WebViewportAttributes.h" - -#if ENABLE(TOUCH_EVENTS) -#include "NativeWebTouchEvent.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -void WebViewClient::viewNeedsDisplay(WebView* view, const IntRect& area) -{ - if (!m_client.viewNeedsDisplay) - return; - - m_client.viewNeedsDisplay(toAPI(view), toAPI(area), m_client.clientInfo); -} - -void WebViewClient::didChangeContentsSize(WebView* view, const IntSize& size) -{ - if (!m_client.didChangeContentsSize) - return; - - m_client.didChangeContentsSize(toAPI(view), toAPI(size), m_client.clientInfo); -} - -void WebViewClient::webProcessCrashed(WebView* view, const String& url) -{ - if (!m_client.webProcessCrashed) - return; - - m_client.webProcessCrashed(toAPI(view), adoptWK(toCopiedURLAPI(url)).get(), m_client.clientInfo); -} - -void WebViewClient::webProcessDidRelaunch(WebView* view) -{ - if (!m_client.webProcessDidRelaunch) - return; - - m_client.webProcessDidRelaunch(toAPI(view), m_client.clientInfo); -} - -void WebViewClient::didChangeContentsPosition(WebView* view, const WebCore::IntPoint& point) -{ - if (!m_client.didChangeContentsPosition) - return; - - m_client.didChangeContentsPosition(toAPI(view), toAPI(point), m_client.clientInfo); -} - -void WebViewClient::didRenderFrame(WebView* view, const WebCore::IntSize& size, const WebCore::IntRect& coveredRect) -{ - if (!m_client.didRenderFrame) - return; - - m_client.didRenderFrame(toAPI(view), toAPI(size), toAPI(coveredRect), m_client.clientInfo); -} - -void WebViewClient::didCompletePageTransition(WebView* view) -{ - if (!m_client.didCompletePageTransition) - return; - - m_client.didCompletePageTransition(toAPI(view), m_client.clientInfo); -} - -void WebViewClient::didChangeViewportAttributes(WebView* view, const ViewportAttributes& attributes) -{ - if (!m_client.didChangeViewportAttributes) - return; - - WKRetainPtr<WKViewportAttributesRef> wkAttributes = adoptWK(toAPI(WebViewportAttributes::create(attributes).leakRef())); - m_client.didChangeViewportAttributes(toAPI(view), wkAttributes.get(), m_client.clientInfo); -} - -void WebViewClient::didChangeTooltip(WebView* view, const String& tooltip) -{ - if (!m_client.didChangeTooltip) - return; - - m_client.didChangeTooltip(toAPI(view), adoptWK(toCopiedAPI(tooltip)).get(), m_client.clientInfo); -} - -void WebViewClient::didFindZoomableArea(WebView* view, const IntPoint& target, const IntRect& area) -{ - if (!m_client.didFindZoomableArea) - return; - - m_client.didFindZoomableArea(toAPI(view), toAPI(target), toAPI(area), m_client.clientInfo); -} - -#if ENABLE(TOUCH_EVENTS) -void WebViewClient::doneWithTouchEvent(WebView* view, const NativeWebTouchEvent& event, bool wasEventHandled) -{ -#if PLATFORM(EFL) - if (!m_client.doneWithTouchEvent) - return; - - m_client.doneWithTouchEvent(toAPI(view), toAPI(const_cast<EwkTouchEvent*>(event.nativeEvent())), wasEventHandled, m_client.clientInfo); -#else - notImplemented(); - UNUSED_PARAM(view); - UNUSED_PARAM(event); - UNUSED_PARAM(wasEventHandled); -#endif -} -#endif - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) diff --git a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.h b/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.h deleted file mode 100644 index 51979e9c7..000000000 --- a/Source/WebKit2/UIProcess/CoordinatedGraphics/WebViewClient.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebViewClient_h -#define WebViewClient_h - -#if USE(COORDINATED_GRAPHICS) - -#include "APIClient.h" -#include "WKView.h" -#include <wtf/text/WTFString.h> - -namespace WebCore { -class IntPoint; -class IntRect; -class IntSize; -class ViewportAttributes; -} - -namespace WebKit { - -class WebView; - -#if ENABLE(TOUCH_EVENTS) -class NativeWebTouchEvent; -#endif - -class WebViewClient: public APIClient<WKViewClient, kWKViewClientCurrentVersion> { -public: - void viewNeedsDisplay(WebView*, const WebCore::IntRect&); - void didChangeContentsSize(WebView*, const WebCore::IntSize&); - void webProcessCrashed(WebView*, const String& url); - void webProcessDidRelaunch(WebView*); - void didChangeContentsPosition(WebView*, const WebCore::IntPoint&); - void didRenderFrame(WebView*, const WebCore::IntSize&, const WebCore::IntRect&); - void didCompletePageTransition(WebView*); - void didChangeViewportAttributes(WebView*, const WebCore::ViewportAttributes&); - void didChangeTooltip(WebView*, const String& tooltip); - void didFindZoomableArea(WebView*, const WebCore::IntPoint&, const WebCore::IntRect&); -#if ENABLE(TOUCH_EVENTS) - void doneWithTouchEvent(WebView*, const NativeWebTouchEvent&, bool); -#endif -}; - -} // namespace WebKit - -#endif // USE(COORDINATED_GRAPHICS) - -#endif // WebViewClient_h diff --git a/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.cpp b/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.cpp new file mode 100644 index 000000000..7ed02d6dc --- /dev/null +++ b/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "DatabaseProcessProxy.h" + +#include "DatabaseProcessMessages.h" +#include "DatabaseProcessProxyMessages.h" +#include "WebProcessPool.h" +#include "WebsiteData.h" +#include <WebCore/NotImplemented.h> + +#if ENABLE(DATABASE_PROCESS) + +using namespace WebCore; + +namespace WebKit { + +static uint64_t generateCallbackID() +{ + static uint64_t callbackID; + + return ++callbackID; +} + +Ref<DatabaseProcessProxy> DatabaseProcessProxy::create(WebProcessPool* processPool) +{ + return adoptRef(*new DatabaseProcessProxy(processPool)); +} + +DatabaseProcessProxy::DatabaseProcessProxy(WebProcessPool* processPool) + : m_processPool(processPool) + , m_numPendingConnectionRequests(0) +{ + connect(); +} + +DatabaseProcessProxy::~DatabaseProcessProxy() +{ + ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty()); +} + +void DatabaseProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +{ + launchOptions.processType = ProcessLauncher::ProcessType::Database; + ChildProcessProxy::getLaunchOptions(launchOptions); +} + +void DatabaseProcessProxy::processWillShutDown(IPC::Connection& connection) +{ + ASSERT_UNUSED(connection, this->connection() == &connection); +} + +void DatabaseProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) +{ + if (decoder.messageReceiverName() == Messages::DatabaseProcessProxy::messageReceiverName()) { + didReceiveDatabaseProcessProxyMessage(connection, decoder); + return; + } +} + +void DatabaseProcessProxy::fetchWebsiteData(SessionID sessionID, WebsiteDataTypes dataTypes, std::function<void (WebsiteData)> completionHandler) +{ + ASSERT(canSendMessage()); + + uint64_t callbackID = generateCallbackID(); + m_pendingFetchWebsiteDataCallbacks.add(callbackID, WTFMove(completionHandler)); + + send(Messages::DatabaseProcess::FetchWebsiteData(sessionID, dataTypes, callbackID), 0); +} + +void DatabaseProcessProxy::deleteWebsiteData(WebCore::SessionID sessionID, WebsiteDataTypes dataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler) +{ + auto callbackID = generateCallbackID(); + + m_pendingDeleteWebsiteDataCallbacks.add(callbackID, WTFMove(completionHandler)); + send(Messages::DatabaseProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0); +} + +void DatabaseProcessProxy::deleteWebsiteDataForOrigins(SessionID sessionID, WebsiteDataTypes dataTypes, const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, std::function<void ()> completionHandler) +{ + ASSERT(canSendMessage()); + + uint64_t callbackID = generateCallbackID(); + m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, WTFMove(completionHandler)); + + Vector<SecurityOriginData> originData; + for (auto& origin : origins) + originData.append(SecurityOriginData::fromSecurityOrigin(*origin)); + + send(Messages::DatabaseProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, originData, callbackID), 0); +} + +void DatabaseProcessProxy::getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply> reply) +{ + m_pendingConnectionReplies.append(reply); + + if (state() == State::Launching) { + m_numPendingConnectionRequests++; + return; + } + + connection()->send(Messages::DatabaseProcess::CreateDatabaseToWebProcessConnection(), 0, IPC::DispatchMessageEvenWhenWaitingForSyncReply); +} + +void DatabaseProcessProxy::didClose(IPC::Connection&) +{ + // The database process must have crashed or exited, so send any pending sync replies we might have. + while (!m_pendingConnectionReplies.isEmpty()) { + auto reply = m_pendingConnectionReplies.takeFirst(); + +#if USE(UNIX_DOMAIN_SOCKETS) + reply->send(IPC::Attachment()); +#elif OS(DARWIN) + reply->send(IPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND)); +#else + notImplemented(); +#endif + } + + for (const auto& callback : m_pendingFetchWebsiteDataCallbacks.values()) + callback(WebsiteData()); + m_pendingFetchWebsiteDataCallbacks.clear(); + + for (const auto& callback : m_pendingDeleteWebsiteDataCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataCallbacks.clear(); + + for (const auto& callback : m_pendingDeleteWebsiteDataForOriginsCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataForOriginsCallbacks.clear(); + + // Tell ProcessPool to forget about this database process. This may cause us to be deleted. + m_processPool->databaseProcessCrashed(this); +} + +void DatabaseProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) +{ +} + +void DatabaseProcessProxy::didCreateDatabaseToWebProcessConnection(const IPC::Attachment& connectionIdentifier) +{ + ASSERT(!m_pendingConnectionReplies.isEmpty()); + + RefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); + +#if USE(UNIX_DOMAIN_SOCKETS) + reply->send(connectionIdentifier); +#elif OS(DARWIN) + reply->send(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND)); +#else + notImplemented(); +#endif +} + +void DatabaseProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData) +{ + auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID); + callback(websiteData); +} + +void DatabaseProcessProxy::didDeleteWebsiteData(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID); + callback(); +} + +void DatabaseProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID); + callback(); +} + +void DatabaseProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connection::Identifier connectionIdentifier) +{ + ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier); + + if (IPC::Connection::identifierIsNull(connectionIdentifier)) { + // FIXME: Do better cleanup here. + return; + } + + for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i) + connection()->send(Messages::DatabaseProcess::CreateDatabaseToWebProcessConnection(), 0); + + m_numPendingConnectionRequests = 0; +} + +} // namespace WebKit + +#endif // ENABLE(DATABASE_PROCESS) diff --git a/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.h b/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.h new file mode 100644 index 000000000..c37f3a263 --- /dev/null +++ b/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.h @@ -0,0 +1,96 @@ +/* + * 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 DatabaseProcessProxy_h +#define DatabaseProcessProxy_h + +#if ENABLE(DATABASE_PROCESS) + +#include "ChildProcessProxy.h" +#include "ProcessLauncher.h" +#include "WebProcessProxyMessages.h" +#include "WebsiteDataTypes.h" +#include <wtf/Deque.h> + +namespace WebCore { +class SecurityOrigin; +class SessionID; +} + +namespace WebKit { + +class WebProcessPool; + +class DatabaseProcessProxy : public ChildProcessProxy { +public: + static Ref<DatabaseProcessProxy> create(WebProcessPool*); + ~DatabaseProcessProxy(); + + void fetchWebsiteData(WebCore::SessionID, WebsiteDataTypes, std::function<void (WebsiteData)> completionHandler); + void deleteWebsiteData(WebCore::SessionID, WebsiteDataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler); + void deleteWebsiteDataForOrigins(WebCore::SessionID, WebsiteDataTypes, const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, std::function<void ()> completionHandler); + + void getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply>); + +private: + DatabaseProcessProxy(WebProcessPool*); + + // ChildProcessProxy + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) override; + virtual void processWillShutDown(IPC::Connection&) override; + + // IPC::Connection::Client + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didClose(IPC::Connection&) override; + virtual void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override; + virtual IPC::ProcessType localProcessType() override { return IPC::ProcessType::UI; } + virtual IPC::ProcessType remoteProcessType() override { return IPC::ProcessType::Database; } + + void didReceiveDatabaseProcessProxyMessage(IPC::Connection&, IPC::MessageDecoder&); + + // Message handlers + void didCreateDatabaseToWebProcessConnection(const IPC::Attachment&); + void didFetchWebsiteData(uint64_t callbackID, const WebsiteData&); + void didDeleteWebsiteData(uint64_t callbackID); + void didDeleteWebsiteDataForOrigins(uint64_t callbackID); + + // ProcessLauncher::Client + virtual void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override; + + WebProcessPool* m_processPool; + + unsigned m_numPendingConnectionRequests; + Deque<RefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply>> m_pendingConnectionReplies; + + HashMap<uint64_t, std::function<void (WebsiteData)>> m_pendingFetchWebsiteDataCallbacks; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataCallbacks; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataForOriginsCallbacks; +}; + +} // namespace WebKit + +#endif // ENABLE(DATABASE_PROCESS) + +#endif // DatabaseProcessProxy_h diff --git a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.messages.in b/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.messages.in index b6baf8ac8..1986cd445 100644 --- a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.messages.in +++ b/Source/WebKit2/UIProcess/Databases/DatabaseProcessProxy.messages.in @@ -20,10 +20,14 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> SecItemShimProxy { +#if ENABLE(DATABASE_PROCESS) -#if USE(SECURITY_FRAMEWORK) - SecItemRequest(uint64_t requestID, WebKit::SecItemRequestData request) WantsConnection -#endif +messages -> DatabaseProcessProxy LegacyReceiver { + DidCreateDatabaseToWebProcessConnection(IPC::Attachment connectionIdentifier) + DidFetchWebsiteData(uint64_t callbackID, struct WebKit::WebsiteData websiteData) + DidDeleteWebsiteData(uint64_t callbackID) + DidDeleteWebsiteDataForOrigins(uint64_t callbackID) } + +#endif // ENABLE(DATABASE_PROCESS) diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp index 1070eb64d..6418ce9ec 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.cpp @@ -26,20 +26,19 @@ #include "config.h" #include "DownloadProxy.h" +#include "APIData.h" +#include "APIDownloadClient.h" #include "AuthenticationChallengeProxy.h" #include "DataReference.h" #include "DownloadProxyMap.h" -#include "WebContext.h" -#include "WebData.h" +#include "NetworkProcessMessages.h" +#include "NetworkProcessProxy.h" #include "WebProcessMessages.h" +#include "WebProcessPool.h" +#include "WebProtectionSpace.h" #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> -#if ENABLE(NETWORK_PROCESS) -#include "NetworkProcessMessages.h" -#include "NetworkProcessProxy.h" -#endif - using namespace WebCore; namespace WebKit { @@ -50,107 +49,135 @@ static uint64_t generateDownloadID() return ++uniqueDownloadID; } -PassRefPtr<DownloadProxy> DownloadProxy::create(DownloadProxyMap& downloadProxyMap, WebContext* webContext) +PassRefPtr<DownloadProxy> DownloadProxy::create(DownloadProxyMap& downloadProxyMap, WebProcessPool& processPool, const ResourceRequest& resourceRequest) { - return adoptRef(new DownloadProxy(downloadProxyMap, webContext)); + return adoptRef(new DownloadProxy(downloadProxyMap, processPool, resourceRequest)); } -DownloadProxy::DownloadProxy(DownloadProxyMap& downloadProxyMap, WebContext* webContext) +DownloadProxy::DownloadProxy(DownloadProxyMap& downloadProxyMap, WebProcessPool& processPool, const ResourceRequest& resourceRequest) : m_downloadProxyMap(downloadProxyMap) - , m_webContext(webContext) + , m_processPool(&processPool) , m_downloadID(generateDownloadID()) + , m_request(resourceRequest) { } DownloadProxy::~DownloadProxy() { - ASSERT(!m_webContext); + ASSERT(!m_processPool); } void DownloadProxy::cancel() { - if (!m_webContext) + if (!m_processPool) return; -#if ENABLE(NETWORK_PROCESS) - if (m_webContext->usesNetworkProcess()) { - if (NetworkProcessProxy* networkProcess = m_webContext->networkProcess()) - networkProcess->connection()->send(Messages::NetworkProcess::CancelDownload(m_downloadID), 0); - return; - } -#endif - - m_webContext->sendToAllProcesses(Messages::WebProcess::CancelDownload(m_downloadID)); + if (NetworkProcessProxy* networkProcess = m_processPool->networkProcess()) + networkProcess->connection()->send(Messages::NetworkProcess::CancelDownload(m_downloadID), 0); } void DownloadProxy::invalidate() { - ASSERT(m_webContext); - m_webContext = 0; + ASSERT(m_processPool); + m_processPool = nullptr; } void DownloadProxy::processDidClose() { - if (!m_webContext) + if (!m_processPool) return; - m_webContext->downloadClient().processDidCrash(m_webContext.get(), this); + m_processPool->downloadClient().processDidCrash(m_processPool.get(), this); } void DownloadProxy::didStart(const ResourceRequest& request) { m_request = request; - if (!m_webContext) + if (!m_processPool) return; - m_webContext->downloadClient().didStart(m_webContext.get(), this); + m_processPool->downloadClient().didStart(m_processPool.get(), this); } void DownloadProxy::didReceiveAuthenticationChallenge(const AuthenticationChallenge& authenticationChallenge, uint64_t challengeID) { - if (!m_webContext) + if (!m_processPool) + return; + + RefPtr<AuthenticationChallengeProxy> authenticationChallengeProxy = AuthenticationChallengeProxy::create(authenticationChallenge, challengeID, m_processPool->networkingProcessConnection()); + + m_processPool->downloadClient().didReceiveAuthenticationChallenge(m_processPool.get(), this, authenticationChallengeProxy.get()); +} + +#if USE(NETWORK_SESSION) +void DownloadProxy::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace) +{ + if (!m_processPool) + return; + + auto* networkProcessProxy = m_processPool->networkProcess(); + if (!networkProcessProxy) return; - RefPtr<AuthenticationChallengeProxy> authenticationChallengeProxy = AuthenticationChallengeProxy::create(authenticationChallenge, challengeID, m_webContext->networkingProcessConnection()); + bool result = m_processPool->downloadClient().canAuthenticateAgainstProtectionSpace(getPtr(WebProtectionSpace::create(protectionSpace))); + + networkProcessProxy->connection()->send(Messages::NetworkProcess::ContinueCanAuthenticateAgainstProtectionSpace(m_downloadID, result), 0); +} + +void DownloadProxy::willSendRequest(const ResourceRequest& proposedRequest, const ResourceResponse& redirectResponse) +{ + if (!m_processPool) + return; - m_webContext->downloadClient().didReceiveAuthenticationChallenge(m_webContext.get(), this, authenticationChallengeProxy.get()); + RefPtr<DownloadProxy> protectedThis(this); + m_processPool->downloadClient().willSendRequest(proposedRequest, redirectResponse, [protectedThis](const ResourceRequest& newRequest) { + if (!protectedThis->m_processPool) + return; + + auto* networkProcessProxy = protectedThis->m_processPool->networkProcess(); + if (!networkProcessProxy) + return; + + networkProcessProxy->connection()->send(Messages::NetworkProcess::ContinueWillSendRequest(protectedThis->m_downloadID, newRequest), 0); + }); } +#endif void DownloadProxy::didReceiveResponse(const ResourceResponse& response) { - if (!m_webContext) + if (!m_processPool) return; - m_webContext->downloadClient().didReceiveResponse(m_webContext.get(), this, response); + m_processPool->downloadClient().didReceiveResponse(m_processPool.get(), this, response); } void DownloadProxy::didReceiveData(uint64_t length) { - if (!m_webContext) + if (!m_processPool) return; - m_webContext->downloadClient().didReceiveData(m_webContext.get(), this, length); + m_processPool->downloadClient().didReceiveData(m_processPool.get(), this, length); } void DownloadProxy::shouldDecodeSourceDataOfMIMEType(const String& mimeType, bool& result) { result = false; - if (!m_webContext) + if (!m_processPool) return; - result = m_webContext->downloadClient().shouldDecodeSourceDataOfMIMEType(m_webContext.get(), this, mimeType); + result = m_processPool->downloadClient().shouldDecodeSourceDataOfMIMEType(m_processPool.get(), this, mimeType); } void DownloadProxy::decideDestinationWithSuggestedFilename(const String& filename, String& destination, bool& allowOverwrite, SandboxExtension::Handle& sandboxExtensionHandle) { allowOverwrite = false; - if (!m_webContext) + if (!m_processPool) return; - destination = m_webContext->downloadClient().decideDestinationWithSuggestedFilename(m_webContext.get(), this, filename, allowOverwrite); + destination = m_processPool->downloadClient().decideDestinationWithSuggestedFilename(m_processPool.get(), this, filename, allowOverwrite); if (!destination.isNull()) SandboxExtension::createHandle(destination, SandboxExtension::ReadWrite, sandboxExtensionHandle); @@ -158,49 +185,49 @@ void DownloadProxy::decideDestinationWithSuggestedFilename(const String& filenam void DownloadProxy::didCreateDestination(const String& path) { - if (!m_webContext) + if (!m_processPool) return; - m_webContext->downloadClient().didCreateDestination(m_webContext.get(), this, path); + m_processPool->downloadClient().didCreateDestination(m_processPool.get(), this, path); } void DownloadProxy::didFinish() { - if (!m_webContext) + if (!m_processPool) return; - m_webContext->downloadClient().didFinish(m_webContext.get(), this); + m_processPool->downloadClient().didFinish(m_processPool.get(), this); // This can cause the DownloadProxy object to be deleted. m_downloadProxyMap.downloadFinished(this); } -static PassRefPtr<WebData> createWebData(const CoreIPC::DataReference& data) +static RefPtr<API::Data> createData(const IPC::DataReference& data) { if (data.isEmpty()) return 0; - return WebData::create(data.data(), data.size()); + return API::Data::create(data.data(), data.size()); } -void DownloadProxy::didFail(const ResourceError& error, const CoreIPC::DataReference& resumeData) +void DownloadProxy::didFail(const ResourceError& error, const IPC::DataReference& resumeData) { - if (!m_webContext) + if (!m_processPool) return; - m_resumeData = createWebData(resumeData); + m_resumeData = createData(resumeData); - m_webContext->downloadClient().didFail(m_webContext.get(), this, error); + m_processPool->downloadClient().didFail(m_processPool.get(), this, error); // This can cause the DownloadProxy object to be deleted. m_downloadProxyMap.downloadFinished(this); } -void DownloadProxy::didCancel(const CoreIPC::DataReference& resumeData) +void DownloadProxy::didCancel(const IPC::DataReference& resumeData) { - m_resumeData = createWebData(resumeData); + m_resumeData = createData(resumeData); - m_webContext->downloadClient().didCancel(m_webContext.get(), this); + m_processPool->downloadClient().didCancel(m_processPool.get(), this); // This can cause the DownloadProxy object to be deleted. m_downloadProxyMap.downloadFinished(this); diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h index 1d98305e0..cf4fa157c 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.h @@ -28,51 +28,56 @@ #include "APIObject.h" #include "Connection.h" +#include "DownloadID.h" #include "SandboxExtension.h" #include <WebCore/ResourceRequest.h> #include <wtf/Forward.h> #include <wtf/PassRefPtr.h> +namespace API { +class Data; +} + namespace WebCore { - class AuthenticationChallenge; - class ResourceError; - class ResourceResponse; +class AuthenticationChallenge; +class ProtectionSpace; +class ResourceError; +class ResourceResponse; } namespace WebKit { class DownloadProxyMap; -class WebContext; -class WebData; class WebPageProxy; +class WebProcessPool; -class DownloadProxy : public TypedAPIObject<APIObject::TypeDownload>, public CoreIPC::MessageReceiver { +class DownloadProxy : public API::ObjectImpl<API::Object::Type::Download>, public IPC::MessageReceiver { public: - static PassRefPtr<DownloadProxy> create(DownloadProxyMap&, WebContext*); + static PassRefPtr<DownloadProxy> create(DownloadProxyMap&, WebProcessPool&, const WebCore::ResourceRequest&); ~DownloadProxy(); - uint64_t downloadID() const { return m_downloadID; } + DownloadID downloadID() const { return m_downloadID; } const WebCore::ResourceRequest& request() const { return m_request; } - WebData* resumeData() const { return m_resumeData.get(); } + API::Data* resumeData() const { return m_resumeData.get(); } void cancel(); void invalidate(); void processDidClose(); - void didReceiveDownloadProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - void didReceiveSyncDownloadProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + void didReceiveDownloadProxyMessage(IPC::Connection&, IPC::MessageDecoder&); + void didReceiveSyncDownloadProxyMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&); #if PLATFORM(QT) void startTransfer(const String& filename); #endif private: - explicit DownloadProxy(DownloadProxyMap&, WebContext*); + explicit DownloadProxy(DownloadProxyMap&, WebProcessPool&, const WebCore::ResourceRequest&); - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; // Message handlers. void didStart(const WebCore::ResourceRequest&); @@ -83,14 +88,18 @@ private: void decideDestinationWithSuggestedFilename(const String& filename, String& destination, bool& allowOverwrite, SandboxExtension::Handle& sandboxExtensionHandle); void didCreateDestination(const String& path); void didFinish(); - void didFail(const WebCore::ResourceError&, const CoreIPC::DataReference& resumeData); - void didCancel(const CoreIPC::DataReference& resumeData); + void didFail(const WebCore::ResourceError&, const IPC::DataReference& resumeData); + void didCancel(const IPC::DataReference& resumeData); +#if USE(NETWORK_SESSION) + void canAuthenticateAgainstProtectionSpace(const WebCore::ProtectionSpace&); + void willSendRequest(const WebCore::ResourceRequest& redirectRequest, const WebCore::ResourceResponse& redirectResponse); +#endif DownloadProxyMap& m_downloadProxyMap; - RefPtr<WebContext> m_webContext; - uint64_t m_downloadID; + RefPtr<WebProcessPool> m_processPool; + DownloadID m_downloadID; - RefPtr<WebData> m_resumeData; + RefPtr<API::Data> m_resumeData; WebCore::ResourceRequest m_request; }; diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.messages.in b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.messages.in index d72559988..9c8ec2269 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxy.messages.in +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxy.messages.in @@ -23,13 +23,17 @@ messages -> DownloadProxy { DidStart(WebCore::ResourceRequest request) DidReceiveAuthenticationChallenge(WebCore::AuthenticationChallenge challenge, uint64_t challengeID) +#if USE(NETWORK_SESSION) + WillSendRequest(WebCore::ResourceRequest redirectRequest, WebCore::ResourceResponse redirectResponse)); + CanAuthenticateAgainstProtectionSpace(WebCore::ProtectionSpace protectionSpace) +#endif DidReceiveResponse(WebCore::ResourceResponse response) DidReceiveData(uint64_t length) ShouldDecodeSourceDataOfMIMEType(String mimeType) -> (bool result) DecideDestinationWithSuggestedFilename(String filename) -> (String destination, bool allowOverwrite, WebKit::SandboxExtension::Handle sandboxExtensionHandle) - DidCreateDestination(WTF::String path) + DidCreateDestination(String path) DidFinish() - DidFail(WebCore::ResourceError error, CoreIPC::DataReference resumeData) - DidCancel(CoreIPC::DataReference resumeData) + DidFail(WebCore::ResourceError error, IPC::DataReference resumeData) + DidCancel(IPC::DataReference resumeData) } diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp index f1c1eecd0..7509ddedb 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.cpp @@ -44,36 +44,38 @@ DownloadProxyMap::~DownloadProxyMap() ASSERT(m_downloads.isEmpty()); } -DownloadProxy* DownloadProxyMap::createDownloadProxy(WebContext* webContext) +DownloadProxy* DownloadProxyMap::createDownloadProxy(WebProcessPool& processPool, const WebCore::ResourceRequest& resourceRequest) { - RefPtr<DownloadProxy> downloadProxy = DownloadProxy::create(*this, webContext); + RefPtr<DownloadProxy> downloadProxy = DownloadProxy::create(*this, processPool, resourceRequest); m_downloads.set(downloadProxy->downloadID(), downloadProxy); - m_process->addMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID(), downloadProxy.get()); + m_process->addMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID().downloadID(), *downloadProxy); return downloadProxy.get(); } void DownloadProxyMap::downloadFinished(DownloadProxy* downloadProxy) { - ASSERT(m_downloads.contains(downloadProxy->downloadID())); + auto downloadID = downloadProxy->downloadID(); - downloadProxy->invalidate(); - m_downloads.remove(downloadProxy->downloadID()); + ASSERT(m_downloads.contains(downloadID)); - m_process->removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID()); + m_process->removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadID.downloadID()); + downloadProxy->invalidate(); + m_downloads.remove(downloadID); } void DownloadProxyMap::processDidClose() { // Invalidate all outstanding downloads. - for (HashMap<uint64_t, RefPtr<DownloadProxy> >::iterator::Values it = m_downloads.begin().values(), end = m_downloads.end().values(); it != end; ++it) { - (*it)->processDidClose(); - (*it)->invalidate(); + for (const auto& download : m_downloads.values()) { + download->processDidClose(); + download->invalidate(); + m_process->removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), download->downloadID().downloadID()); } m_downloads.clear(); - m_process = 0; + m_process = nullptr; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.h b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.h index 72359d55d..d60e5a8e9 100644 --- a/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.h +++ b/Source/WebKit2/UIProcess/Downloads/DownloadProxyMap.h @@ -26,15 +26,20 @@ #ifndef DownloadProxyMap_h #define DownloadProxyMap_h +#include "DownloadID.h" #include <wtf/HashMap.h> #include <wtf/Noncopyable.h> #include <wtf/PassRefPtr.h> +namespace WebCore { +class ResourceRequest; +} + namespace WebKit { class ChildProcessProxy; class DownloadProxy; -class WebContext; +class WebProcessPool; class DownloadProxyMap { WTF_MAKE_NONCOPYABLE(DownloadProxyMap); @@ -43,7 +48,7 @@ public: explicit DownloadProxyMap(ChildProcessProxy*); ~DownloadProxyMap(); - DownloadProxy* createDownloadProxy(WebContext*); + DownloadProxy* createDownloadProxy(WebProcessPool&, const WebCore::ResourceRequest&); void downloadFinished(DownloadProxy*); bool isEmpty() const { return m_downloads.isEmpty(); } @@ -52,7 +57,7 @@ public: private: ChildProcessProxy* m_process; - HashMap<uint64_t, RefPtr<DownloadProxy> > m_downloads; + HashMap<DownloadID, RefPtr<DownloadProxy>> m_downloads; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp b/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp index 4d49d816c..3d5b9e2e1 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp +++ b/Source/WebKit2/UIProcess/DrawingAreaProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,31 +26,29 @@ #include "config.h" #include "DrawingAreaProxy.h" +#include "DrawingAreaMessages.h" #include "DrawingAreaProxyMessages.h" #include "WebPageProxy.h" #include "WebProcessProxy.h" -#if USE(COORDINATED_GRAPHICS) -#include "CoordinatedLayerTreeHostProxy.h" -#endif - using namespace WebCore; namespace WebKit { -const double DrawingAreaProxy::didUpdateBackingStoreStateTimeout = 0.5; - -DrawingAreaProxy::DrawingAreaProxy(DrawingAreaType type, WebPageProxy* webPageProxy) +DrawingAreaProxy::DrawingAreaProxy(DrawingAreaType type, WebPageProxy& webPageProxy) : m_type(type) , m_webPageProxy(webPageProxy) - , m_size(webPageProxy->viewSize()) + , m_size(webPageProxy.viewSize()) +#if PLATFORM(MAC) + , m_exposedRectChangedTimer(RunLoop::main(), this, &DrawingAreaProxy::exposedRectChangedTimerFired) +#endif { - m_webPageProxy->process()->addMessageReceiver(Messages::DrawingAreaProxy::messageReceiverName(), webPageProxy->pageID(), this); + m_webPageProxy.process().addMessageReceiver(Messages::DrawingAreaProxy::messageReceiverName(), m_webPageProxy.pageID(), *this); } DrawingAreaProxy::~DrawingAreaProxy() { - m_webPageProxy->process()->removeMessageReceiver(Messages::DrawingAreaProxy::messageReceiverName(), m_webPageProxy->pageID()); + m_webPageProxy.process().removeMessageReceiver(Messages::DrawingAreaProxy::messageReceiverName(), m_webPageProxy.pageID()); } void DrawingAreaProxy::setSize(const IntSize& size, const IntSize& layerPosition, const IntSize& scrollOffset) @@ -64,16 +62,29 @@ void DrawingAreaProxy::setSize(const IntSize& size, const IntSize& layerPosition sizeDidChange(); } -#if USE(COORDINATED_GRAPHICS) -void DrawingAreaProxy::updateViewport() +#if PLATFORM(MAC) +void DrawingAreaProxy::setExposedRect(const FloatRect& exposedRect) { - m_webPageProxy->setViewNeedsDisplay(viewportVisibleRect()); + if (!m_webPageProxy.isValid()) + return; + + m_exposedRect = exposedRect; + + if (!m_exposedRectChangedTimer.isActive()) + m_exposedRectChangedTimer.startOneShot(0); } -WebCore::IntRect DrawingAreaProxy::contentsRect() const +void DrawingAreaProxy::exposedRectChangedTimerFired() { - return IntRect(IntPoint::zero(), m_webPageProxy->viewSize()); + if (!m_webPageProxy.isValid()) + return; + + if (m_exposedRect == m_lastSentExposedRect) + return; + + m_webPageProxy.process().send(Messages::DrawingArea::SetExposedRect(m_exposedRect), m_webPageProxy.pageID()); + m_lastSentExposedRect = m_exposedRect; } -#endif +#endif // PLATFORM(MAC) } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxy.h b/Source/WebKit2/UIProcess/DrawingAreaProxy.h index 93b9f0b70..7973df1a1 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxy.h +++ b/Source/WebKit2/UIProcess/DrawingAreaProxy.h @@ -27,14 +27,17 @@ #ifndef DrawingAreaProxy_h #define DrawingAreaProxy_h -#include "BackingStore.h" #include "DrawingAreaInfo.h" +#include "GenericCallback.h" #include "MessageReceiver.h" -#include <WebCore/FloatPoint.h> +#include <WebCore/FloatRect.h> #include <WebCore/IntRect.h> #include <WebCore/IntSize.h> +#include <chrono> #include <stdint.h> #include <wtf/Noncopyable.h> +#include <wtf/RunLoop.h> +#include <wtf/TypeCasts.h> namespace WebKit { @@ -43,7 +46,7 @@ class CoordinatedLayerTreeHostProxy; class UpdateInfo; class WebPageProxy; -class DrawingAreaProxy : public CoreIPC::MessageReceiver { +class DrawingAreaProxy : public IPC::MessageReceiver { WTF_MAKE_NONCOPYABLE(DrawingAreaProxy); public: @@ -54,9 +57,6 @@ public: virtual void deviceScaleFactorDidChange() = 0; // FIXME: These should be pure virtual. - virtual void visibilityDidChange() { } - virtual void layerHostingModeDidChange() { } - virtual void setBackingStoreIsDiscardable(bool) { } virtual void waitForBackingStoreUpdateOnNextPaint() { } @@ -64,58 +64,82 @@ public: const WebCore::IntSize& size() const { return m_size; } void setSize(const WebCore::IntSize&, const WebCore::IntSize&, const WebCore::IntSize& scrollOffset); - // The timeout, in seconds, we use when waiting for a DidUpdateGeometry message. - static const double didUpdateBackingStoreStateTimeout; + // The timeout we use when waiting for a DidUpdateGeometry message. + static constexpr std::chrono::milliseconds didUpdateBackingStoreStateTimeout() { return std::chrono::milliseconds(500); } - virtual void waitForPossibleGeometryUpdate(double = didUpdateBackingStoreStateTimeout) { } + virtual void waitForPossibleGeometryUpdate(std::chrono::milliseconds = didUpdateBackingStoreStateTimeout()) { } virtual void colorSpaceDidChange() { } virtual void minimumLayoutSizeDidChange() { } -#if USE(COORDINATED_GRAPHICS) - virtual void updateViewport(); - virtual WebCore::IntRect viewportVisibleRect() const { return contentsRect(); } - virtual WebCore::IntRect contentsRect() const; - CoordinatedLayerTreeHostProxy* coordinatedLayerTreeHostProxy() const { return m_coordinatedLayerTreeHostProxy.get(); } - virtual void setVisibleContentsRect(const WebCore::FloatRect& /* visibleContentsRect */, const WebCore::FloatPoint& /* trajectoryVector */) { } + virtual void adjustTransientZoom(double, WebCore::FloatPoint) { } + virtual void commitTransientZoom(double, WebCore::FloatPoint) { } - WebPageProxy* page() { return m_webPageProxy; } +#if PLATFORM(MAC) + virtual void setExposedRect(const WebCore::FloatRect&); + WebCore::FloatRect exposedRect() const { return m_exposedRect; } +#endif +#if PLATFORM(COCOA) + void exposedRectChangedTimerFired(); #endif + + virtual void updateDebugIndicator() { } + + virtual void waitForDidUpdateViewState() { } + + virtual void dispatchAfterEnsuringDrawing(std::function<void (CallbackBase::Error)>) { ASSERT_NOT_REACHED(); } + + // Hide the content until the currently pending update arrives. + virtual void hideContentUntilPendingUpdate() { ASSERT_NOT_REACHED(); } + + // Hide the content until any update arrives. + virtual void hideContentUntilAnyUpdate() { ASSERT_NOT_REACHED(); } + + virtual bool hasVisibleContent() const { return true; } + + virtual void willSendUpdateGeometry() { } + protected: - explicit DrawingAreaProxy(DrawingAreaType, WebPageProxy*); + explicit DrawingAreaProxy(DrawingAreaType, WebPageProxy&); DrawingAreaType m_type; - WebPageProxy* m_webPageProxy; + WebPageProxy& m_webPageProxy; WebCore::IntSize m_size; WebCore::IntSize m_layerPosition; WebCore::IntSize m_scrollOffset; -#if USE(COORDINATED_GRAPHICS) - OwnPtr<CoordinatedLayerTreeHostProxy> m_coordinatedLayerTreeHostProxy; -#endif + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; private: virtual void sizeDidChange() = 0; - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - // CoreIPC message handlers. + // Message handlers. // FIXME: These should be pure virtual. virtual void update(uint64_t /* backingStoreStateID */, const UpdateInfo&) { } virtual void didUpdateBackingStoreState(uint64_t /* backingStoreStateID */, const UpdateInfo&, const LayerTreeContext&) { } -#if USE(ACCELERATED_COMPOSITING) virtual void enterAcceleratedCompositingMode(uint64_t /* backingStoreStateID */, const LayerTreeContext&) { } virtual void exitAcceleratedCompositingMode(uint64_t /* backingStoreStateID */, const UpdateInfo&) { } virtual void updateAcceleratedCompositingMode(uint64_t /* backingStoreStateID */, const LayerTreeContext&) { } -#endif -#if PLATFORM(MAC) + virtual void willEnterAcceleratedCompositingMode(uint64_t /* backingStoreStateID */) { } +#if PLATFORM(COCOA) virtual void didUpdateGeometry() { } - virtual void intrinsicContentSizeDidChange(const WebCore::IntSize& newIntrinsicContentSize) { } + virtual void intrinsicContentSizeDidChange(const WebCore::IntSize&) { } + +#if PLATFORM(MAC) + RunLoop::Timer<DrawingAreaProxy> m_exposedRectChangedTimer; + WebCore::FloatRect m_exposedRect; + WebCore::FloatRect m_lastSentExposedRect; +#endif // PLATFORM(MAC) #endif }; } // namespace WebKit +#define SPECIALIZE_TYPE_TRAITS_DRAWING_AREA_PROXY(ToValueTypeName, ProxyType) \ +SPECIALIZE_TYPE_TRAITS_BEGIN(WebKit::ToValueTypeName) \ + static bool isType(const WebKit::DrawingAreaProxy& proxy) { return proxy.type() == WebKit::ProxyType; } \ +SPECIALIZE_TYPE_TRAITS_END() + #endif // DrawingAreaProxy_h diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in b/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in index a272cb59d..8d51cdefd 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in +++ b/Source/WebKit2/UIProcess/DrawingAreaProxy.messages.in @@ -23,13 +23,12 @@ messages -> DrawingAreaProxy { Update(uint64_t stateID, WebKit::UpdateInfo updateInfo) DidUpdateBackingStoreState(uint64_t backingStoreStateID, WebKit::UpdateInfo updateInfo, WebKit::LayerTreeContext context) -#if USE(ACCELERATED_COMPOSITING) EnterAcceleratedCompositingMode(uint64_t backingStoreStateID, WebKit::LayerTreeContext context) ExitAcceleratedCompositingMode(uint64_t backingStoreStateID, WebKit::UpdateInfo updateInfo) UpdateAcceleratedCompositingMode(uint64_t backingStoreStateID, WebKit::LayerTreeContext context) -#endif + WillEnterAcceleratedCompositingMode(uint64_t backingStoreStateID) -#if PLATFORM(MAC) +#if PLATFORM(COCOA) // Used by TiledCoreAnimationDrawingAreaProxy. DidUpdateGeometry() IntrinsicContentSizeDidChange(WebCore::IntSize newIntrinsicContentSize) diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp index 790c8a939..6c41a0ee6 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp +++ b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.cpp @@ -36,20 +36,11 @@ #include "WebProcessProxy.h" #include <WebCore/Region.h> -#if USE(COORDINATED_GRAPHICS) -#include "CoordinatedLayerTreeHostProxy.h" -#endif - using namespace WebCore; namespace WebKit { -PassOwnPtr<DrawingAreaProxyImpl> DrawingAreaProxyImpl::create(WebPageProxy* webPageProxy) -{ - return adoptPtr(new DrawingAreaProxyImpl(webPageProxy)); -} - -DrawingAreaProxyImpl::DrawingAreaProxyImpl(WebPageProxy* webPageProxy) +DrawingAreaProxyImpl::DrawingAreaProxyImpl(WebPageProxy& webPageProxy) : DrawingAreaProxy(DrawingAreaTypeImpl, webPageProxy) , m_currentBackingStoreStateID(0) , m_nextBackingStoreStateID(0) @@ -58,20 +49,13 @@ DrawingAreaProxyImpl::DrawingAreaProxyImpl(WebPageProxy* webPageProxy) , m_isBackingStoreDiscardable(true) , m_discardBackingStoreTimer(RunLoop::current(), this, &DrawingAreaProxyImpl::discardBackingStore) { -#if USE(COORDINATED_GRAPHICS) - // Construct the proxy early to allow messages to be sent to the web process while AC is entered there. - if (webPageProxy->pageGroup()->preferences()->forceCompositingMode()) - m_coordinatedLayerTreeHostProxy = adoptPtr(new CoordinatedLayerTreeHostProxy(this)); -#endif } DrawingAreaProxyImpl::~DrawingAreaProxyImpl() { -#if USE(ACCELERATED_COMPOSITING) // Make sure to exit accelerated compositing mode. if (isInAcceleratedCompositingMode()) exitAcceleratedCompositingMode(); -#endif } void DrawingAreaProxyImpl::paint(BackingStore::PlatformGraphicsContext context, const IntRect& rect, Region& unpaintedRegion) @@ -127,32 +111,6 @@ void DrawingAreaProxyImpl::deviceScaleFactorDidChange() backingStoreStateDidChange(RespondImmediately); } -void DrawingAreaProxyImpl::layerHostingModeDidChange() -{ - m_webPageProxy->process()->send(Messages::DrawingArea::SetLayerHostingMode(m_webPageProxy->layerHostingMode()), m_webPageProxy->pageID()); -} - -void DrawingAreaProxyImpl::visibilityDidChange() -{ - if (!m_webPageProxy->suppressVisibilityUpdates()) { - if (!m_webPageProxy->isViewVisible()) { - // Suspend painting. - m_webPageProxy->process()->send(Messages::DrawingArea::SuspendPainting(), m_webPageProxy->pageID()); - return; - } - - // Resume painting. - m_webPageProxy->process()->send(Messages::DrawingArea::ResumePainting(), m_webPageProxy->pageID()); - } - -#if USE(ACCELERATED_COMPOSITING) - // If we don't have a backing store, go ahead and mark the backing store as being changed so - // that when paint we'll actually wait for something to paint and not flash white. - if (!m_backingStore && m_layerTreeContext.isEmpty()) - backingStoreStateDidChange(DoNotRespondImmediately); -#endif -} - void DrawingAreaProxyImpl::setBackingStoreIsDiscardable(bool isBackingStoreDiscardable) { if (m_isBackingStoreDiscardable == isBackingStoreDiscardable) @@ -179,7 +137,7 @@ void DrawingAreaProxyImpl::update(uint64_t backingStoreStateID, const UpdateInfo // FIXME: Handle the case where the view is hidden. incorporateUpdate(updateInfo); - m_webPageProxy->process()->send(Messages::DrawingArea::DidUpdate(), m_webPageProxy->pageID()); + m_webPageProxy.process().send(Messages::DrawingArea::DidUpdate(), m_webPageProxy.pageID()); } void DrawingAreaProxyImpl::didUpdateBackingStoreState(uint64_t backingStoreStateID, const UpdateInfo& updateInfo, const LayerTreeContext& layerTreeContext) @@ -191,9 +149,8 @@ void DrawingAreaProxyImpl::didUpdateBackingStoreState(uint64_t backingStoreState m_isWaitingForDidUpdateBackingStoreState = false; // Stop the responsiveness timer that was started in sendUpdateBackingStoreState. - m_webPageProxy->process()->responsivenessTimer()->stop(); + m_webPageProxy.process().responsivenessTimer().stop(); -#if USE(ACCELERATED_COMPOSITING) if (layerTreeContext != m_layerTreeContext) { if (!m_layerTreeContext.isEmpty()) { exitAcceleratedCompositingMode(); @@ -205,21 +162,16 @@ void DrawingAreaProxyImpl::didUpdateBackingStoreState(uint64_t backingStoreState ASSERT(layerTreeContext == m_layerTreeContext); } } -#endif if (m_nextBackingStoreStateID != m_currentBackingStoreStateID) sendUpdateBackingStoreState(RespondImmediately); else m_hasReceivedFirstUpdate = true; -#if USE(ACCELERATED_COMPOSITING) if (isInAcceleratedCompositingMode()) { ASSERT(!m_backingStore); return; } -#else - UNUSED_PARAM(layerTreeContext); -#endif // If we have a backing store the right size, reuse it. if (m_backingStore && (m_backingStore->size() != updateInfo.viewSize || m_backingStore->deviceScaleFactor() != updateInfo.deviceScaleFactor)) @@ -233,11 +185,7 @@ void DrawingAreaProxyImpl::enterAcceleratedCompositingMode(uint64_t backingStore if (backingStoreStateID < m_currentBackingStoreStateID) return; -#if USE(ACCELERATED_COMPOSITING) enterAcceleratedCompositingMode(layerTreeContext); -#else - UNUSED_PARAM(layerTreeContext); -#endif } void DrawingAreaProxyImpl::exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo& updateInfo) @@ -246,9 +194,7 @@ void DrawingAreaProxyImpl::exitAcceleratedCompositingMode(uint64_t backingStoreS if (backingStoreStateID < m_currentBackingStoreStateID) return; -#if USE(ACCELERATED_COMPOSITING) exitAcceleratedCompositingMode(); -#endif incorporateUpdate(updateInfo); } @@ -259,11 +205,16 @@ void DrawingAreaProxyImpl::updateAcceleratedCompositingMode(uint64_t backingStor if (backingStoreStateID < m_currentBackingStoreStateID) return; -#if USE(ACCELERATED_COMPOSITING) updateAcceleratedCompositingMode(layerTreeContext); -#else - UNUSED_PARAM(layerTreeContext); -#endif +} + +void DrawingAreaProxyImpl::willEnterAcceleratedCompositingMode(uint64_t backingStoreStateID) +{ + // WillEnterAcceleratedCompositingMode message is sent when the LayerTreeHost is created in the Web Process. + // This can happen while there's still a DidUpdateBackingStoreState pending, in which case we are receiving + // here the new backingStoreStateID, but m_currentBackingStoreStateID hasn't been updated yet. + ASSERT_ARG(backingStoreStateID, backingStoreStateID <= m_nextBackingStoreStateID); + m_webPageProxy.willEnterAcceleratedCompositingMode(); } void DrawingAreaProxyImpl::incorporateUpdate(const UpdateInfo& updateInfo) @@ -274,27 +225,24 @@ void DrawingAreaProxyImpl::incorporateUpdate(const UpdateInfo& updateInfo) return; if (!m_backingStore) - m_backingStore = BackingStore::create(updateInfo.viewSize, updateInfo.deviceScaleFactor, m_webPageProxy); + m_backingStore = std::make_unique<BackingStore>(updateInfo.viewSize, updateInfo.deviceScaleFactor, m_webPageProxy); m_backingStore->incorporateUpdate(updateInfo); bool shouldScroll = !updateInfo.scrollRect.isEmpty(); if (shouldScroll) - m_webPageProxy->scrollView(updateInfo.scrollRect, updateInfo.scrollOffset); + m_webPageProxy.scrollView(updateInfo.scrollRect, updateInfo.scrollOffset); - if (shouldScroll && !m_webPageProxy->canScrollView()) - m_webPageProxy->setViewNeedsDisplay(IntRect(IntPoint(), m_webPageProxy->viewSize())); + if (shouldScroll && !m_webPageProxy.canScrollView()) + m_webPageProxy.setViewNeedsDisplay(IntRect(IntPoint(), m_webPageProxy.viewSize())); else { for (size_t i = 0; i < updateInfo.updateRects.size(); ++i) - m_webPageProxy->setViewNeedsDisplay(updateInfo.updateRects[i]); + m_webPageProxy.setViewNeedsDisplay(updateInfo.updateRects[i]); } - - if (WebPageProxy::debugPaintFlags() & kWKDebugFlashBackingStoreUpdates) - m_webPageProxy->flashBackingStoreUpdates(updateInfo.updateRects); if (shouldScroll) - m_webPageProxy->displayView(); + m_webPageProxy.displayView(); } void DrawingAreaProxyImpl::backingStoreStateDidChange(RespondImmediatelyOrNot respondImmediatelyOrNot) @@ -307,84 +255,89 @@ void DrawingAreaProxyImpl::sendUpdateBackingStoreState(RespondImmediatelyOrNot r { ASSERT(m_currentBackingStoreStateID < m_nextBackingStoreStateID); - if (!m_webPageProxy->isValid()) + if (!m_webPageProxy.isValid()) return; if (m_isWaitingForDidUpdateBackingStoreState) return; - if (m_webPageProxy->viewSize().isEmpty() && !m_webPageProxy->useFixedLayout()) + if (m_webPageProxy.viewSize().isEmpty() && !m_webPageProxy.useFixedLayout()) return; m_isWaitingForDidUpdateBackingStoreState = respondImmediatelyOrNot == RespondImmediately; - m_webPageProxy->process()->send(Messages::DrawingArea::UpdateBackingStoreState(m_nextBackingStoreStateID, respondImmediatelyOrNot == RespondImmediately, m_webPageProxy->deviceScaleFactor(), m_size, m_scrollOffset), m_webPageProxy->pageID()); + m_webPageProxy.process().send(Messages::DrawingArea::UpdateBackingStoreState(m_nextBackingStoreStateID, respondImmediatelyOrNot == RespondImmediately, m_webPageProxy.deviceScaleFactor(), m_size, m_scrollOffset), m_webPageProxy.pageID()); m_scrollOffset = IntSize(); if (m_isWaitingForDidUpdateBackingStoreState) { // Start the responsiveness timer. We will stop it when we hear back from the WebProcess // in didUpdateBackingStoreState. - m_webPageProxy->process()->responsivenessTimer()->start(); + m_webPageProxy.process().responsivenessTimer().start(); } -#if USE(ACCELERATED_COMPOSITING) if (m_isWaitingForDidUpdateBackingStoreState && !m_layerTreeContext.isEmpty()) { // Wait for the DidUpdateBackingStoreState message. Normally we do this in DrawingAreaProxyImpl::paint, but that // function is never called when in accelerated compositing mode. waitForAndDispatchDidUpdateBackingStoreState(); } -#endif } void DrawingAreaProxyImpl::waitForAndDispatchDidUpdateBackingStoreState() { ASSERT(m_isWaitingForDidUpdateBackingStoreState); - if (!m_webPageProxy->isValid()) + if (!m_webPageProxy.isValid()) return; - if (m_webPageProxy->process()->isLaunching()) + if (m_webPageProxy.process().state() == WebProcessProxy::State::Launching) return; -#if USE(ACCELERATED_COMPOSITING) // FIXME: waitForAndDispatchImmediately will always return the oldest DidUpdateBackingStoreState message that // hasn't yet been processed. But it might be better to skip ahead to some other DidUpdateBackingStoreState // message, if multiple DidUpdateBackingStoreState messages are waiting to be processed. For instance, we could // choose the most recent one, or the one that is closest to our current size. - // The timeout, in seconds, we use when waiting for a DidUpdateBackingStoreState message when we're asked to paint. - static const double didUpdateBackingStoreStateTimeout = 0.5; - m_webPageProxy->process()->connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateBackingStoreState>(m_webPageProxy->pageID(), didUpdateBackingStoreStateTimeout); -#endif + // The timeout we use when waiting for a DidUpdateBackingStoreState message when we're asked to paint is 500 milliseconds. + m_webPageProxy.process().connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateBackingStoreState>(m_webPageProxy.pageID(), std::chrono::milliseconds(500)); } -#if USE(ACCELERATED_COMPOSITING) void DrawingAreaProxyImpl::enterAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) { ASSERT(!isInAcceleratedCompositingMode()); m_backingStore = nullptr; m_layerTreeContext = layerTreeContext; - m_webPageProxy->enterAcceleratedCompositingMode(layerTreeContext); -#if USE(COORDINATED_GRAPHICS) - if (!m_coordinatedLayerTreeHostProxy) - m_coordinatedLayerTreeHostProxy = adoptPtr(new CoordinatedLayerTreeHostProxy(this)); -#endif + m_webPageProxy.enterAcceleratedCompositingMode(layerTreeContext); } -#if USE(COORDINATED_GRAPHICS) -void DrawingAreaProxyImpl::setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, const WebCore::FloatPoint& trajectoryVector) +#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) +void DrawingAreaProxyImpl::setNativeSurfaceHandleForCompositing(uint64_t handle) { - if (m_coordinatedLayerTreeHostProxy) - m_coordinatedLayerTreeHostProxy->setVisibleContentsRect(visibleContentsRect, trajectoryVector); + m_webPageProxy.process().send(Messages::DrawingArea::SetNativeSurfaceHandleForCompositing(handle), m_webPageProxy.pageID()); +} + +void DrawingAreaProxyImpl::destroyNativeSurfaceHandleForCompositing() +{ + bool handled; + m_webPageProxy.process().sendSync(Messages::DrawingArea::DestroyNativeSurfaceHandleForCompositing(), Messages::DrawingArea::DestroyNativeSurfaceHandleForCompositing::Reply(handled), m_webPageProxy.pageID()); } #endif +void DrawingAreaProxyImpl::dispatchAfterEnsuringDrawing(std::function<void (CallbackBase::Error)> callbackFunction) +{ + if (!m_webPageProxy.isValid()) { + callbackFunction(CallbackBase::Error::OwnerWasInvalidated); + return; + } + + RunLoop::main().dispatch([callbackFunction] { callbackFunction(CallbackBase::Error::None); }); +} + void DrawingAreaProxyImpl::exitAcceleratedCompositingMode() { ASSERT(isInAcceleratedCompositingMode()); m_layerTreeContext = LayerTreeContext(); - m_webPageProxy->exitAcceleratedCompositingMode(); + m_webPageProxy.exitAcceleratedCompositingMode(); } void DrawingAreaProxyImpl::updateAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) @@ -392,9 +345,8 @@ void DrawingAreaProxyImpl::updateAcceleratedCompositingMode(const LayerTreeConte ASSERT(isInAcceleratedCompositingMode()); m_layerTreeContext = layerTreeContext; - m_webPageProxy->updateAcceleratedCompositingMode(layerTreeContext); + m_webPageProxy.updateAcceleratedCompositingMode(layerTreeContext); } -#endif void DrawingAreaProxyImpl::discardBackingStoreSoon() { diff --git a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h index 27bc14307..24da66a65 100644 --- a/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h +++ b/Source/WebKit2/UIProcess/DrawingAreaProxyImpl.h @@ -29,9 +29,7 @@ #include "BackingStore.h" #include "DrawingAreaProxy.h" #include "LayerTreeContext.h" -#include <WebCore/RunLoop.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> +#include <wtf/RunLoop.h> namespace WebCore { class Region; @@ -39,39 +37,39 @@ class Region; namespace WebKit { -class CoordinatedLayerTreeHostProxy; - class DrawingAreaProxyImpl : public DrawingAreaProxy { public: - static PassOwnPtr<DrawingAreaProxyImpl> create(WebPageProxy*); + explicit DrawingAreaProxyImpl(WebPageProxy&); virtual ~DrawingAreaProxyImpl(); void paint(BackingStore::PlatformGraphicsContext, const WebCore::IntRect&, WebCore::Region& unpaintedRegion); -#if USE(ACCELERATED_COMPOSITING) bool isInAcceleratedCompositingMode() const { return !m_layerTreeContext.isEmpty(); } -#endif bool hasReceivedFirstUpdate() const { return m_hasReceivedFirstUpdate; } -private: - explicit DrawingAreaProxyImpl(WebPageProxy*); +#if USE(TEXTURE_MAPPER) && PLATFORM(GTK) + void setNativeSurfaceHandleForCompositing(uint64_t); + void destroyNativeSurfaceHandleForCompositing(); +#endif + + virtual void dispatchAfterEnsuringDrawing(std::function<void (CallbackBase::Error)>) override; +private: // DrawingAreaProxy - virtual void sizeDidChange(); - virtual void deviceScaleFactorDidChange(); - virtual void layerHostingModeDidChange() OVERRIDE; + virtual void sizeDidChange() override; + virtual void deviceScaleFactorDidChange() override; - virtual void visibilityDidChange(); - virtual void setBackingStoreIsDiscardable(bool); - virtual void waitForBackingStoreUpdateOnNextPaint(); + virtual void setBackingStoreIsDiscardable(bool) override; + virtual void waitForBackingStoreUpdateOnNextPaint() override; - // CoreIPC message handlers - virtual void update(uint64_t backingStoreStateID, const UpdateInfo&); - virtual void didUpdateBackingStoreState(uint64_t backingStoreStateID, const UpdateInfo&, const LayerTreeContext&); - virtual void enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&); - virtual void exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo&); - virtual void updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&); + // IPC message handlers + virtual void update(uint64_t backingStoreStateID, const UpdateInfo&) override; + virtual void didUpdateBackingStoreState(uint64_t backingStoreStateID, const UpdateInfo&, const LayerTreeContext&) override; + virtual void enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&) override; + virtual void exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo&) override; + virtual void updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&) override; + virtual void willEnterAcceleratedCompositingMode(uint64_t backingStoreStateID) override; void incorporateUpdate(const UpdateInfo&); @@ -80,16 +78,9 @@ private: void sendUpdateBackingStoreState(RespondImmediatelyOrNot); void waitForAndDispatchDidUpdateBackingStoreState(); -#if USE(ACCELERATED_COMPOSITING) void enterAcceleratedCompositingMode(const LayerTreeContext&); void exitAcceleratedCompositingMode(); void updateAcceleratedCompositingMode(const LayerTreeContext&); -#if USE(COORDINATED_GRAPHICS) - virtual void setVisibleContentsRect(const WebCore::FloatRect& visibleContentsRect, const WebCore::FloatPoint& trajectory) OVERRIDE; -#endif -#else - bool isInAcceleratedCompositingMode() const { return false; } -#endif void discardBackingStoreSoon(); void discardBackingStore(); @@ -103,10 +94,8 @@ private: // whenever our state changes in a way that will require a new backing store to be allocated. uint64_t m_nextBackingStoreStateID; -#if USE(ACCELERATED_COMPOSITING) // The current layer tree context. LayerTreeContext m_layerTreeContext; -#endif // Whether we've sent a UpdateBackingStoreState message and are now waiting for a DidUpdateBackingStoreState message. // Used to throttle UpdateBackingStoreState messages so we don't send them faster than the Web process can handle. @@ -116,9 +105,9 @@ private: bool m_hasReceivedFirstUpdate; bool m_isBackingStoreDiscardable; - OwnPtr<BackingStore> m_backingStore; + std::unique_ptr<BackingStore> m_backingStore; - WebCore::RunLoop::Timer<DrawingAreaProxyImpl> m_discardBackingStoreTimer; + RunLoop::Timer<DrawingAreaProxyImpl> m_discardBackingStoreTimer; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/FindIndicator.cpp b/Source/WebKit2/UIProcess/FindIndicator.cpp deleted file mode 100644 index 2ad193f1b..000000000 --- a/Source/WebKit2/UIProcess/FindIndicator.cpp +++ /dev/null @@ -1,212 +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 "FindIndicator.h" - -#include "ShareableBitmap.h" -#include <WebCore/Gradient.h> -#include <WebCore/GraphicsContext.h> -#include <WebCore/IntRect.h> -#include <WebCore/Path.h> - -using namespace WebCore; - -static const float cornerRadius = 3.0; - -static const float shadowOffsetX = 0.0; -static const float shadowOffsetY = 1.0; -static const float shadowBlurRadius = 3.0; - -static const int shadowRed = 0; -static const int shadowGreen = 0; -static const int shadowBlue = 0; -static const int shadowAlpha = 204; - -static const float lightBorderThickness = 1.0; -static const float horizontalPaddingInsideLightBorder = 3.0; -static const float verticalPaddingInsideLightBorder = 1.0; - -static const float horizontalBorderInsideShadow = lightBorderThickness + horizontalPaddingInsideLightBorder; -static const float verticalBorderInsideShadow = lightBorderThickness + verticalPaddingInsideLightBorder; - -static const float leftBorderThickness = horizontalBorderInsideShadow + shadowOffsetX + shadowBlurRadius / 2.0; -static const float topBorderThickness = verticalBorderInsideShadow - shadowOffsetY + shadowBlurRadius / 2.0; -static const float rightBorderThickness = horizontalBorderInsideShadow - shadowOffsetX + shadowBlurRadius / 2.0; -static const float bottomBorderThickness = verticalBorderInsideShadow + shadowOffsetY + shadowBlurRadius / 2.0; - -static const float horizontalOutsetToCenterOfLightBorder = horizontalBorderInsideShadow - lightBorderThickness / 2.0; -static const float verticalOutsetToCenterOfLightBorder = verticalBorderInsideShadow - lightBorderThickness / 2.0; - -static const int lightBorderRed = 245; -static const int lightBorderGreen = 230; -static const int lightBorderBlue = 0; -static const int lightBorderAlpha = 255; - -static const int gradientDarkRed = 237; -static const int gradientDarkGreen = 204; -static const int gradientDarkBlue = 0; -static const int gradientDarkAlpha = 255; - -static const int gradientLightRed = 242; -static const int gradientLightGreen = 239; -static const int gradientLightBlue = 0; -static const int gradientLightAlpha = 255; - -namespace WebKit { - -PassRefPtr<FindIndicator> FindIndicator::create(const FloatRect& selectionRectInWindowCoordinates, const Vector<FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle) -{ - RefPtr<ShareableBitmap> contentImage = ShareableBitmap::create(contentImageHandle); - if (!contentImage) - return 0; - ASSERT(contentImageScaleFactor != 1 || contentImage->size() == enclosingIntRect(selectionRectInWindowCoordinates).size()); - - return adoptRef(new FindIndicator(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, contentImageScaleFactor, contentImage.release())); -} - -static bool findIndicatorsForTextRectsOverlap(const Vector<FloatRect>& textRects) -{ - size_t count = textRects.size(); - if (count <= 1) - return false; - - Vector<FloatRect> indicatorRects; - indicatorRects.reserveInitialCapacity(count); - - for (size_t i = 0; i < count; ++i) { - FloatRect indicatorRect = textRects[i]; - indicatorRect.move(-leftBorderThickness, -topBorderThickness); - indicatorRect.expand(leftBorderThickness + rightBorderThickness, topBorderThickness + bottomBorderThickness); - - for (size_t j = indicatorRects.size(); j; ) { - --j; - if (indicatorRect.intersects(indicatorRects[j])) - return true; - } - - indicatorRects.uncheckedAppend(indicatorRect); - } - - return false; -} - -FindIndicator::FindIndicator(const WebCore::FloatRect& selectionRectInWindowCoordinates, const Vector<WebCore::FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, PassRefPtr<ShareableBitmap> contentImage) - : m_selectionRectInWindowCoordinates(selectionRectInWindowCoordinates) - , m_textRectsInSelectionRectCoordinates(textRectsInSelectionRectCoordinates) - , m_contentImageScaleFactor(contentImageScaleFactor) - , m_contentImage(contentImage) -{ - if (findIndicatorsForTextRectsOverlap(m_textRectsInSelectionRectCoordinates)) { - m_textRectsInSelectionRectCoordinates[0] = unionRect(m_textRectsInSelectionRectCoordinates); - m_textRectsInSelectionRectCoordinates.shrink(1); - } -} - -FindIndicator::~FindIndicator() -{ -} - -static FloatRect inflateRect(const FloatRect& rect, float inflateX, float inflateY) -{ - FloatRect inflatedRect = rect; - inflatedRect.inflateX(inflateX); - inflatedRect.inflateY(inflateY); - - return inflatedRect; -} - -FloatRect FindIndicator::frameRect() const -{ - return FloatRect(m_selectionRectInWindowCoordinates.x() - leftBorderThickness, m_selectionRectInWindowCoordinates.y() - topBorderThickness, - m_selectionRectInWindowCoordinates.width() + rightBorderThickness + leftBorderThickness, - m_selectionRectInWindowCoordinates.height() + topBorderThickness + bottomBorderThickness); -} - -static Color lightBorderColor() -{ - return Color(lightBorderRed, lightBorderGreen, lightBorderBlue, lightBorderAlpha); -} - -static Color shadowColor() -{ - return Color(shadowRed, shadowGreen, shadowBlue, shadowAlpha); -} - -static Color gradientLightColor() -{ - return Color(gradientLightRed, gradientLightGreen, gradientLightBlue, gradientLightAlpha); -} - -static Color gradientDarkColor() -{ - return Color(gradientDarkRed, gradientDarkGreen, gradientDarkBlue, gradientDarkAlpha); -} - -static Path pathWithRoundedRect(const FloatRect& pathRect, float radius) -{ - Path path; - path.addRoundedRect(pathRect, FloatSize(radius, radius)); - - return path; -} - -void FindIndicator::draw(GraphicsContext& graphicsContext, const IntRect& /*dirtyRect*/) -{ - for (size_t i = 0; i < m_textRectsInSelectionRectCoordinates.size(); ++i) { - FloatRect textRect = m_textRectsInSelectionRectCoordinates[i]; - textRect.move(leftBorderThickness, topBorderThickness); - - FloatRect outerPathRect = inflateRect(textRect, horizontalOutsetToCenterOfLightBorder, verticalOutsetToCenterOfLightBorder); - FloatRect innerPathRect = inflateRect(textRect, horizontalPaddingInsideLightBorder, verticalPaddingInsideLightBorder); - - { - GraphicsContextStateSaver stateSaver(graphicsContext); - graphicsContext.setShadow(FloatSize(shadowOffsetX, shadowOffsetY), shadowBlurRadius, shadowColor(), ColorSpaceSRGB); - graphicsContext.setFillColor(lightBorderColor(), ColorSpaceDeviceRGB); - graphicsContext.fillPath(pathWithRoundedRect(outerPathRect, cornerRadius)); - } - - { - GraphicsContextStateSaver stateSaver(graphicsContext); - graphicsContext.clip(pathWithRoundedRect(innerPathRect, cornerRadius)); - RefPtr<Gradient> gradient = Gradient::create(FloatPoint(innerPathRect.x(), innerPathRect.y()), FloatPoint(innerPathRect.x(), innerPathRect.maxY())); - gradient->addColorStop(0, gradientLightColor()); - gradient->addColorStop(1, gradientDarkColor()); - graphicsContext.setFillGradient(gradient); - graphicsContext.fillRect(outerPathRect); - } - - { - GraphicsContextStateSaver stateSaver(graphicsContext); - graphicsContext.translate(FloatSize(roundf(leftBorderThickness), roundf(topBorderThickness))); - - IntRect contentImageRect = enclosingIntRect(m_textRectsInSelectionRectCoordinates[i]); - m_contentImage->paint(graphicsContext, m_contentImageScaleFactor, contentImageRect.location(), contentImageRect); - } - } -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/FrameLoadState.cpp b/Source/WebKit2/UIProcess/FrameLoadState.cpp new file mode 100644 index 000000000..d28f5c62c --- /dev/null +++ b/Source/WebKit2/UIProcess/FrameLoadState.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "FrameLoadState.h" + +namespace WebKit { + +FrameLoadState::FrameLoadState() + : m_state(State::Finished) +{ +} + +FrameLoadState::~FrameLoadState() +{ +} + +void FrameLoadState::didStartProvisionalLoad(const String& url) +{ + ASSERT(m_provisionalURL.isEmpty()); + + m_state = State::Provisional; + m_provisionalURL = url; +} + +void FrameLoadState::didReceiveServerRedirectForProvisionalLoad(const String& url) +{ + ASSERT(m_state == State::Provisional); + + m_provisionalURL = url; +} + +void FrameLoadState::didFailProvisionalLoad() +{ + ASSERT(m_state == State::Provisional); + + m_state = State::Finished; + m_provisionalURL = String(); + m_unreachableURL = m_lastUnreachableURL; +} + +void FrameLoadState::didCommitLoad() +{ + ASSERT(m_state == State::Provisional); + + m_state = State::Committed; + m_url = m_provisionalURL; + m_provisionalURL = String(); +} + +void FrameLoadState::didFinishLoad() +{ + ASSERT(m_state == State::Committed); + ASSERT(m_provisionalURL.isEmpty()); + + m_state = State::Finished; +} + +void FrameLoadState::didFailLoad() +{ + ASSERT(m_state == State::Committed); + ASSERT(m_provisionalURL.isEmpty()); + + m_state = State::Finished; +} + +void FrameLoadState::didSameDocumentNotification(const String& url) +{ + m_url = url; +} + +void FrameLoadState::setUnreachableURL(const String& unreachableURL) +{ + m_lastUnreachableURL = m_unreachableURL; + m_unreachableURL = unreachableURL; +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.h b/Source/WebKit2/UIProcess/FrameLoadState.h index cd6f225fa..2d359b8d1 100644 --- a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.h +++ b/Source/WebKit2/UIProcess/FrameLoadState.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. 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,37 +23,49 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef RequestManagerClientEfl_h -#define RequestManagerClientEfl_h +#ifndef FrameLoadState_h +#define FrameLoadState_h -#include "ewk_context_private.h" -#include <WebKit2/WKBase.h> -#include <WebKit2/WKRetainPtr.h> -#include <wtf/HashMap.h> -#include <wtf/PassOwnPtr.h> #include <wtf/text/WTFString.h> namespace WebKit { -class RequestManagerClientEfl { +class FrameLoadState { public: - ~RequestManagerClientEfl(); - static PassOwnPtr<RequestManagerClientEfl> create(WKContextRef context) - { - return adoptPtr(new RequestManagerClientEfl(context)); - } + FrameLoadState(); + ~FrameLoadState(); - void registerURLSchemeHandler(const String& scheme, Ewk_Url_Scheme_Request_Cb callback, void* userData); + enum class State { + Provisional, + Committed, + Finished + }; -private: - explicit RequestManagerClientEfl(WKContextRef); + void didStartProvisionalLoad(const String& url); + void didReceiveServerRedirectForProvisionalLoad(const String& url); + void didFailProvisionalLoad(); + + void didCommitLoad(); + void didFinishLoad(); + void didFailLoad(); + + void didSameDocumentNotification(const String&); - static void didReceiveURIRequest(WKSoupRequestManagerRef, WKURLRef, WKPageRef, uint64_t requestID, const void* clientInfo); + State state() const { return m_state; } + const String& url() const { return m_url; } + const String& provisionalURL() const { return m_provisionalURL; } - WKRetainPtr<WKSoupRequestManagerRef> m_soupRequestManager; - HashMap<String, class EwkUrlSchemeHandler> m_urlSchemeHandlers; + void setUnreachableURL(const String&); + const String& unreachableURL() const { return m_unreachableURL; } + +private: + State m_state; + String m_url; + String m_provisionalURL; + String m_unreachableURL; + String m_lastUnreachableURL; }; } // namespace WebKit -#endif // RequestManagerClientEfl_h +#endif // FrameLoadState_h diff --git a/Source/WebKit2/UIProcess/GenericCallback.h b/Source/WebKit2/UIProcess/GenericCallback.h index cda020fd0..84ce3de04 100644 --- a/Source/WebKit2/UIProcess/GenericCallback.h +++ b/Source/WebKit2/UIProcess/GenericCallback.h @@ -26,230 +26,196 @@ #ifndef GenericCallback_h #define GenericCallback_h +#include "APIError.h" +#include "APISerializedScriptValue.h" +#include "ProcessThrottler.h" #include "ShareableBitmap.h" #include "WKAPICast.h" -#include "WebError.h" +#include <functional> #include <wtf/HashMap.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> +#include <wtf/RunLoop.h> namespace WebKit { class CallbackBase : public RefCounted<CallbackBase> { public: + enum class Error { + None, + Unknown, + ProcessExited, + OwnerWasInvalidated, + }; + virtual ~CallbackBase() { } uint64_t callbackID() const { return m_callbackID; } + template<class T> + T* as() + { + if (T::type() == m_type) + return static_cast<T*>(this); + + return nullptr; + } + + virtual void invalidate(Error) = 0; + protected: - explicit CallbackBase(void* context) - : m_context(context) + struct TypeTag { }; + typedef const TypeTag* Type; + + explicit CallbackBase(Type type, const ProcessThrottler::BackgroundActivityToken& activityToken) + : m_type(type) , m_callbackID(generateCallbackID()) + , m_activityToken(activityToken) { } - void* context() const { return m_context; } - private: static uint64_t generateCallbackID() { + ASSERT(RunLoop::isMain()); static uint64_t uniqueCallbackID = 1; return uniqueCallbackID++; } - void* m_context; + Type m_type; uint64_t m_callbackID; + ProcessThrottler::BackgroundActivityToken m_activityToken; }; -class VoidCallback : public CallbackBase { +template<typename... T> +class GenericCallback : public CallbackBase { public: - typedef void (*CallbackFunction)(WKErrorRef, void*); + typedef std::function<void (T..., Error)> CallbackFunction; - static PassRefPtr<VoidCallback> create(void* context, CallbackFunction callback) + static PassRefPtr<GenericCallback> create(CallbackFunction callback, const ProcessThrottler::BackgroundActivityToken& activityToken = nullptr) { - return adoptRef(new VoidCallback(context, callback)); + return adoptRef(new GenericCallback(callback, activityToken)); } - virtual ~VoidCallback() + virtual ~GenericCallback() { ASSERT(!m_callback); } - void performCallback() - { - ASSERT(m_callback); - - m_callback(0, context()); - - m_callback = 0; - } - - void invalidate() + void performCallbackWithReturnValue(T... returnValue) { - ASSERT(m_callback); + if (!m_callback) + return; - RefPtr<WebError> error = WebError::create(); - m_callback(toAPI(error.get()), context()); - - m_callback = 0; - } + m_callback(returnValue..., Error::None); -private: - VoidCallback(void* context, CallbackFunction callback) - : CallbackBase(context) - , m_callback(callback) - { + m_callback = nullptr; } - CallbackFunction m_callback; -}; - -template<typename APIReturnValueType, typename InternalReturnValueType = typename APITypeInfo<APIReturnValueType>::ImplType> -class GenericCallback : public CallbackBase { -public: - typedef void (*CallbackFunction)(APIReturnValueType, WKErrorRef, void*); - - static PassRefPtr<GenericCallback> create(void* context, CallbackFunction callback) + void performCallback() { - return adoptRef(new GenericCallback(context, callback)); + performCallbackWithReturnValue(); } - virtual ~GenericCallback() + virtual void invalidate(Error error = Error::Unknown) override final { - ASSERT(!m_callback); - } + if (!m_callback) + return; - void performCallbackWithReturnValue(InternalReturnValueType returnValue) - { - ASSERT(m_callback); + m_callback(typename std::remove_reference<T>::type()..., error); - m_callback(toAPI(returnValue), 0, context()); - - m_callback = 0; - } - - void invalidate() - { - ASSERT(m_callback); - - RefPtr<WebError> error = WebError::create(); - m_callback(0, toAPI(error.get()), context()); - - m_callback = 0; + m_callback = nullptr; } private: - GenericCallback(void* context, CallbackFunction callback) - : CallbackBase(context) + GenericCallback(CallbackFunction callback, const ProcessThrottler::BackgroundActivityToken& activityToken) + : CallbackBase(type(), activityToken) , m_callback(callback) { } - CallbackFunction m_callback; -}; - -// FIXME: Make a version of CallbackBase with two arguments, and define ComputedPagesCallback as a specialization. -class ComputedPagesCallback : public CallbackBase { -public: - typedef void (*CallbackFunction)(const Vector<WebCore::IntRect>&, double, WKErrorRef, void*); - - static PassRefPtr<ComputedPagesCallback> create(void* context, CallbackFunction callback) + friend class CallbackBase; + static Type type() { - return adoptRef(new ComputedPagesCallback(context, callback)); + static TypeTag tag; + return &tag; } - virtual ~ComputedPagesCallback() - { - ASSERT(!m_callback); - } + CallbackFunction m_callback; +}; - void performCallbackWithReturnValue(const Vector<WebCore::IntRect>& returnValue1, double returnValue2) - { - ASSERT(m_callback); +template<typename APIReturnValueType, typename InternalReturnValueType = typename APITypeInfo<APIReturnValueType>::ImplType*> +static typename GenericCallback<InternalReturnValueType>::CallbackFunction toGenericCallbackFunction(void* context, void (*callback)(APIReturnValueType, WKErrorRef, void*)) +{ + return [context, callback](InternalReturnValueType returnValue, CallbackBase::Error error) { + callback(toAPI(returnValue), error != CallbackBase::Error::None ? toAPI(API::Error::create().ptr()) : 0, context); + }; +} - m_callback(returnValue1, returnValue2, 0, context()); +typedef GenericCallback<> VoidCallback; +typedef GenericCallback<const Vector<WebCore::IntRect>&, double> ComputedPagesCallback; +typedef GenericCallback<const ShareableBitmap::Handle&> ImageCallback; - m_callback = 0; - } - - void invalidate() - { - ASSERT(m_callback); - - RefPtr<WebError> error = WebError::create(); - m_callback(Vector<WebCore::IntRect>(), 0, toAPI(error.get()), context()); - - m_callback = 0; - } +template<typename T> +void invalidateCallbackMap(HashMap<uint64_t, T>& callbackMap, CallbackBase::Error error) +{ + Vector<T> callbacks; + copyValuesToVector(callbackMap, callbacks); + for (auto& callback : callbacks) + callback->invalidate(error); -private: + callbackMap.clear(); +} - ComputedPagesCallback(void* context, CallbackFunction callback) - : CallbackBase(context) - , m_callback(callback) +class CallbackMap { +public: + uint64_t put(PassRefPtr<CallbackBase> callback) { - } + ASSERT(!m_map.contains(callback->callbackID())); - CallbackFunction m_callback; -}; + uint64_t callbackID = callback->callbackID(); + m_map.set(callbackID, callback); + return callbackID; + } -class ImageCallback : public CallbackBase { -public: - typedef void (*CallbackFunction)(const ShareableBitmap::Handle&, WKErrorRef, void*); + template<unsigned I, typename T, typename... U> + struct GenericCallbackType { + typedef typename GenericCallbackType<I - 1, U..., T>::type type; + }; - static PassRefPtr<ImageCallback> create(void* context, CallbackFunction callback) - { - return adoptRef(new ImageCallback(context, callback)); - } + template<typename... U> + struct GenericCallbackType<1, CallbackBase::Error, U...> { + typedef GenericCallback<U...> type; + }; - virtual ~ImageCallback() + template<typename... T> + uint64_t put(std::function<void (T...)> function, const ProcessThrottler::BackgroundActivityToken& activityToken) { - ASSERT(!m_callback); + auto callback = GenericCallbackType<sizeof...(T), T...>::type::create(WTFMove(function), activityToken); + return put(callback); } - void performCallbackWithReturnValue(const ShareableBitmap::Handle& returnValue1) + template<class T> + RefPtr<T> take(uint64_t callbackID) { - ASSERT(m_callback); - - m_callback(returnValue1, 0, context()); + RefPtr<CallbackBase> base = m_map.take(callbackID); + if (!base) + return nullptr; - m_callback = 0; + return adoptRef(base.release().leakRef()->as<T>()); } - void invalidate() + void invalidate(CallbackBase::Error error) { - ASSERT(m_callback); - - RefPtr<WebError> error = WebError::create(); - ShareableBitmap::Handle handle; - m_callback(handle, toAPI(error.get()), context()); - - m_callback = 0; + invalidateCallbackMap(m_map, error); } private: - - ImageCallback(void* context, CallbackFunction callback) - : CallbackBase(context) - , m_callback(callback) - { - } - - CallbackFunction m_callback; + HashMap<uint64_t, RefPtr<CallbackBase>> m_map; }; -template<typename T> -void invalidateCallbackMap(HashMap<uint64_t, T>& map) -{ - Vector<T> callbacksVector; - copyValuesToVector(map, callbacksVector); - for (size_t i = 0, size = callbacksVector.size(); i < size; ++i) - callbacksVector[i]->invalidate(); - map.clear(); -} - } // namespace WebKit #endif // GenericCallback_h diff --git a/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.cpp b/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.cpp index b26395736..205a0f06c 100644 --- a/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.cpp @@ -32,17 +32,15 @@ namespace WebKit { -GeolocationPermissionRequestManagerProxy::GeolocationPermissionRequestManagerProxy(WebPageProxy* page) +GeolocationPermissionRequestManagerProxy::GeolocationPermissionRequestManagerProxy(WebPageProxy& page) : m_page(page) { } void GeolocationPermissionRequestManagerProxy::invalidateRequests() { - PendingRequestMap::const_iterator it = m_pendingRequests.begin(); - PendingRequestMap::const_iterator end = m_pendingRequests.end(); - for (; it != end; ++it) - it->value->invalidate(); + for (auto& request : m_pendingRequests.values()) + request->invalidate(); m_pendingRequests.clear(); } @@ -56,15 +54,15 @@ PassRefPtr<GeolocationPermissionRequestProxy> GeolocationPermissionRequestManage void GeolocationPermissionRequestManagerProxy::didReceiveGeolocationPermissionDecision(uint64_t geolocationID, bool allowed) { - if (!m_page->isValid()) + if (!m_page.isValid()) return; - PendingRequestMap::iterator it = m_pendingRequests.find(geolocationID); + auto it = m_pendingRequests.find(geolocationID); if (it == m_pendingRequests.end()) return; #if ENABLE(GEOLOCATION) - m_page->process()->send(Messages::WebPage::DidReceiveGeolocationPermissionDecision(geolocationID, allowed), m_page->pageID()); + m_page.process().send(Messages::WebPage::DidReceiveGeolocationPermissionDecision(geolocationID, allowed), m_page.pageID()); #else UNUSED_PARAM(allowed); #endif diff --git a/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h b/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h index 98885bf07..2f169271b 100644 --- a/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h +++ b/Source/WebKit2/UIProcess/GeolocationPermissionRequestManagerProxy.h @@ -35,7 +35,7 @@ class WebPageProxy; class GeolocationPermissionRequestManagerProxy { public: - explicit GeolocationPermissionRequestManagerProxy(WebPageProxy*); + explicit GeolocationPermissionRequestManagerProxy(WebPageProxy&); void invalidateRequests(); @@ -46,9 +46,8 @@ public: void didReceiveGeolocationPermissionDecision(uint64_t, bool allow); private: - typedef HashMap<uint64_t, RefPtr<GeolocationPermissionRequestProxy> > PendingRequestMap; - PendingRequestMap m_pendingRequests; - WebPageProxy* m_page; + HashMap<uint64_t, RefPtr<GeolocationPermissionRequestProxy>> m_pendingRequests; + WebPageProxy& m_page; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h b/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h index 391275412..03e72965d 100644 --- a/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h +++ b/Source/WebKit2/UIProcess/GeolocationPermissionRequestProxy.h @@ -33,11 +33,11 @@ namespace WebKit { class GeolocationPermissionRequestManagerProxy; -class GeolocationPermissionRequestProxy : public TypedAPIObject<APIObject::TypeGeolocationPermissionRequest> { +class GeolocationPermissionRequestProxy : public API::ObjectImpl<API::Object::Type::GeolocationPermissionRequest> { public: - static PassRefPtr<GeolocationPermissionRequestProxy> create(GeolocationPermissionRequestManagerProxy* manager, uint64_t geolocationID) + static Ref<GeolocationPermissionRequestProxy> create(GeolocationPermissionRequestManagerProxy* manager, uint64_t geolocationID) { - return adoptRef(new GeolocationPermissionRequestProxy(manager, geolocationID)); + return adoptRef(*new GeolocationPermissionRequestProxy(manager, geolocationID)); } void allow(); diff --git a/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp index 734926c6c..5be2e9d2f 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.cpp @@ -74,7 +74,7 @@ size_t HTTPRequest::parseRequestLine(const char* data, size_t length, String& fa { String url; size_t result = parseHTTPRequestLine(data, length, failureReason, m_requestMethod, url, m_httpVersion); - m_url = KURL(KURL(), url); + m_url = URL(URL(), url); return result; } @@ -82,7 +82,7 @@ size_t HTTPRequest::parseHeaders(const char* data, size_t length, String& failur { const char* p = data; const char* end = data + length; - AtomicString name; + String name; String value; for (; p < data + length; p++) { size_t consumedLength = parseHTTPHeader(p, end - p, failureReason, name, value); @@ -93,6 +93,13 @@ size_t HTTPRequest::parseHeaders(const char* data, size_t length, String& failur break; m_headerFields.add(name, value); } + + // If we got here and "name" is empty, it means the headers are valid and ended with a + // blank line (parseHTTPHeader returns "name" as empty if parsing a blank line), otherwise + // the headers didn't end with a blank line and we have an invalid request. + // See also http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html + if (!name.isEmpty()) + return 0; return p - data; } @@ -106,7 +113,7 @@ HTTPRequest::HTTPRequest() { } -HTTPRequest::HTTPRequest(const String& requestMethod, const KURL& url, HTTPVersion version) +HTTPRequest::HTTPRequest(const String& requestMethod, const URL& url, HTTPVersion version) : m_url(url) , m_httpVersion(version) , m_requestMethod(requestMethod) diff --git a/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h index 719e24114..ffb317ec8 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h +++ b/Source/WebKit2/UIProcess/InspectorServer/HTTPRequest.h @@ -34,7 +34,7 @@ #include <WebCore/HTTPHeaderMap.h> #include <WebCore/HTTPParsers.h> -#include <WebCore/KURL.h> +#include <WebCore/URL.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/text/WTFString.h> @@ -43,16 +43,16 @@ namespace WebKit { class HTTPRequest : public RefCounted<HTTPRequest> { public: - static PassRefPtr<HTTPRequest> create() { return adoptRef(new HTTPRequest()); } - static PassRefPtr<HTTPRequest> create(const String& requestMethod, const WebCore::KURL& url, WebCore::HTTPVersion version) { return adoptRef(new HTTPRequest(requestMethod, url, version)); } + static Ref<HTTPRequest> create() { return adoptRef(*new HTTPRequest()); } + static Ref<HTTPRequest> create(const String& requestMethod, const WebCore::URL& url, WebCore::HTTPVersion version) { return adoptRef(*new HTTPRequest(requestMethod, url, version)); } static PassRefPtr<HTTPRequest> parseHTTPRequestFromBuffer(const char* data, size_t length, String& failureReason); virtual ~HTTPRequest(); String requestMethod() const { return m_requestMethod; } void setRequestMethod(const String& method) { m_requestMethod = method; } - WebCore::KURL url() const { return m_url; } - void setURL(const WebCore::KURL& url) { m_url = url; } + WebCore::URL url() const { return m_url; } + void setURL(const WebCore::URL& url) { m_url = url; } const Vector<unsigned char>& body() const { return m_body; } @@ -62,14 +62,14 @@ public: protected: HTTPRequest(); - HTTPRequest(const String& requestMethod, const WebCore::KURL&, WebCore::HTTPVersion); + HTTPRequest(const String& requestMethod, const WebCore::URL&, WebCore::HTTPVersion); // Parsing helpers. size_t parseRequestLine(const char* data, size_t length, String& failureReason); size_t parseHeaders(const char* data, size_t length, String& failureReason); size_t parseRequestBody(const char* data, size_t length); - WebCore::KURL m_url; + WebCore::URL m_url; WebCore::HTTPVersion m_httpVersion; String m_requestMethod; WebCore::HTTPHeaderMap m_headerFields; diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp index cbbd73f66..6374d5159 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.cpp @@ -30,6 +30,7 @@ #include "WebInspectorServer.h" +#include "HTTPHeaderNames.h" #include "HTTPRequest.h" #include "WebInspectorProxy.h" #include "WebSocketServerConnection.h" @@ -50,7 +51,7 @@ static unsigned pageIdFromRequestPath(const String& path) return number; } -WebInspectorServer& WebInspectorServer::shared() +WebInspectorServer& WebInspectorServer::singleton() { static WebInspectorServer& server = *new WebInspectorServer; return server; @@ -111,7 +112,7 @@ void WebInspectorServer::sendMessageOverConnection(unsigned pageIdForConnection, void WebInspectorServer::didReceiveUnrecognizedHTTPRequest(WebSocketServerConnection* connection, PassRefPtr<HTTPRequest> request) { // request->url() contains only the path extracted from the HTTP request line - // and KURL is poor at parsing incomplete URLs, so extract the interesting parts manually. + // and URL is poor at parsing incomplete URLs, so extract the interesting parts manually. String path = request->url(); size_t pathEnd = path.find('?'); if (pathEnd == notFound) @@ -126,10 +127,10 @@ void WebInspectorServer::didReceiveUnrecognizedHTTPRequest(WebSocketServerConnec bool found = platformResourceForPath(path, body, contentType); HTTPHeaderMap headerFields; - headerFields.set("Connection", "close"); - headerFields.set("Content-Length", String::number(body.size())); + headerFields.set(HTTPHeaderName::Connection, "close"); + headerFields.set(HTTPHeaderName::ContentLength, String::number(body.size())); if (found) - headerFields.set("Content-Type", contentType); + headerFields.set(HTTPHeaderName::ContentType, contentType); // Send when ready and close immediately afterwards. connection->sendHTTPResponseHeader(found ? 200 : 404, found ? "OK" : "Not Found", headerFields); @@ -142,7 +143,7 @@ bool WebInspectorServer::didReceiveWebSocketUpgradeHTTPRequest(WebSocketServerCo String path = request->url(); // NOTE: Keep this in sync with WebCore/inspector/front-end/inspector.js. - DEFINE_STATIC_LOCAL(const String, inspectorWebSocketConnectionPathPrefix, (ASCIILiteral("/devtools/page/"))); + DEPRECATED_DEFINE_STATIC_LOCAL(const String, inspectorWebSocketConnectionPathPrefix, (ASCIILiteral("/devtools/page/"))); // Unknown path requested. if (!path.startsWith(inspectorWebSocketConnectionPathPrefix)) diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h index fc8ddf485..4df55898f 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h +++ b/Source/WebKit2/UIProcess/InspectorServer/WebInspectorServer.h @@ -41,7 +41,7 @@ class WebInspectorProxy; class WebInspectorServer : public WebSocketServer, public WebSocketServerClient { public: typedef HashMap<unsigned, WebInspectorProxy*> ClientMap; - static WebInspectorServer& shared(); + static WebInspectorServer& singleton(); // Page registry to manage known pages. int registerPage(WebInspectorProxy* client); @@ -67,10 +67,6 @@ private: void closeConnection(WebInspectorProxy*, WebSocketServerConnection*); -#if PLATFORM(GTK) - String inspectorServerFilesPath(); - String m_inspectorServerFilesPath; -#endif unsigned m_nextAvailablePageId; ClientMap m_clientMap; HashMap<unsigned, WebSocketServerConnection*> m_connectionMap; diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.cpp b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.cpp index cf4ee1305..fd8a930a5 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.cpp @@ -32,7 +32,6 @@ #include "WebSocketServerConnection.h" #include <WebCore/SocketStreamHandle.h> -#include <wtf/PassOwnPtr.h> #if PLATFORM(QT) #include "WebSocketServerQt.h" @@ -82,20 +81,20 @@ void WebSocketServer::close() m_bindAddress = String(); } -void WebSocketServer::didAcceptConnection(PassOwnPtr<WebSocketServerConnection> connection) +void WebSocketServer::didAcceptConnection(std::unique_ptr<WebSocketServerConnection> connection) { - m_connections.append(connection); + m_connections.append(WTFMove(connection)); } void WebSocketServer::didCloseWebSocketServerConnection(WebSocketServerConnection* connection) { - Deque<OwnPtr<WebSocketServerConnection> >::iterator end = m_connections.end(); - for (Deque<OwnPtr<WebSocketServerConnection> >::iterator it = m_connections.begin(); it != end; ++it) { + for (auto it = m_connections.begin(), end = m_connections.end(); it != end; ++it) { if (it->get() == connection) { m_connections.remove(it); return; } } + ASSERT_NOT_REACHED(); } diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h index 68ed64f7c..8472eefb5 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServer.h @@ -29,13 +29,13 @@ #if ENABLE(INSPECTOR_SERVER) +#include <memory> #include <wtf/Deque.h> -#include <wtf/OwnPtr.h> #include <wtf/text/WTFString.h> #if USE(SOUP) #include <gio/gio.h> -#include <wtf/gobject/GRefPtr.h> +#include <wtf/glib/GRefPtr.h> #endif #if PLATFORM(QT) @@ -67,7 +67,7 @@ public: void close(); WebSocketServerClient* client() const { return m_client; } - void didAcceptConnection(PassOwnPtr<WebSocketServerConnection>); + void didAcceptConnection(std::unique_ptr<WebSocketServerConnection>); private: void didCloseWebSocketServerConnection(WebSocketServerConnection*); @@ -77,7 +77,7 @@ private: void platformClose(); ServerState m_state; - Deque<OwnPtr<WebSocketServerConnection> > m_connections; + Deque<std::unique_ptr<WebSocketServerConnection>> m_connections; WebSocketServerClient* m_client; String m_bindAddress; unsigned short m_port; diff --git a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp index a33855546..94a24c90c 100644 --- a/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp +++ b/Source/WebKit2/UIProcess/InspectorServer/WebSocketServerConnection.cpp @@ -30,6 +30,7 @@ #include "WebSocketServerConnection.h" +#include "HTTPHeaderNames.h" #include "HTTPRequest.h" #include "WebSocketServer.h" #include "WebSocketServerClient.h" @@ -125,7 +126,7 @@ void WebSocketServerConnection::sendRawData(const char* data, size_t length) void WebSocketServerConnection::didCloseSocketStream(SocketStreamHandle*) { // Destroy the SocketStreamHandle now to prevent closing an already closed socket later. - m_socket.clear(); + m_socket = nullptr; // Web Socket Mode. if (m_mode == WebSocket) @@ -177,7 +178,7 @@ void WebSocketServerConnection::readHTTPMessage() // If this is a WebSocket request, perform the WebSocket Handshake. const HTTPHeaderMap& headers = request->headerFields(); - String upgradeHeaderValue = headers.get("Upgrade"); + String upgradeHeaderValue = headers.get(HTTPHeaderName::Upgrade); if (upgradeHeaderValue == "websocket") { upgradeToWebSocketServerConnection(request); return; @@ -206,10 +207,10 @@ void WebSocketServerConnection::upgradeToWebSocketServerConnection(PassRefPtr<HT // Build and send the WebSocket handshake response. const HTTPHeaderMap& requestHeaders = protectedRequest->headerFields(); - String accept = WebSocketHandshake::getExpectedWebSocketAccept(requestHeaders.get("Sec-WebSocket-Key")); + String accept = WebSocketHandshake::getExpectedWebSocketAccept(requestHeaders.get(HTTPHeaderName::SecWebSocketKey)); HTTPHeaderMap responseHeaders; - responseHeaders.add("Upgrade", requestHeaders.get("Upgrade")); - responseHeaders.add("Connection", requestHeaders.get("Connection")); + responseHeaders.add("Upgrade", requestHeaders.get(HTTPHeaderName::Upgrade)); + responseHeaders.add("Connection", requestHeaders.get(HTTPHeaderName::Connection)); responseHeaders.add("Sec-WebSocket-Accept", accept); sendHTTPResponseHeader(101, "WebSocket Protocol Handshake", responseHeaders); diff --git a/Source/WebKit2/UIProcess/InspectorServer/efl/WebInspectorServerEfl.cpp b/Source/WebKit2/UIProcess/InspectorServer/efl/WebInspectorServerEfl.cpp deleted file mode 100644 index 0d94c5340..000000000 --- a/Source/WebKit2/UIProcess/InspectorServer/efl/WebInspectorServerEfl.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2012 Seokju Kwon (seokju.kwon@gmail.com) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#if ENABLE(INSPECTOR_SERVER) -#include "WebInspectorServer.h" - -#include "WebInspectorProxy.h" -#include "WebPageProxy.h" -#include <WebCore/EflInspectorUtilities.h> -#include <WebCore/MIMETypeRegistry.h> -#include <sys/stat.h> -#include <wtf/text/StringBuilder.h> - -namespace WebKit { - -bool WebInspectorServer::platformResourceForPath(const String& path, Vector<char>& data, String& contentType) -{ - // The page list contains an unformated list of pages that can be inspected with a link to open a session. - if (path == "/pagelist.json") { - buildPageList(data, contentType); - return true; - } - - // Point the default path to a formatted page that queries the page list and display them. - String localPath = WebCore::inspectorResourcePath() + ((path == "/") ? ASCIILiteral("/inspectorPageIndex.html") : path); - - FILE* fileHandle = fopen(localPath.utf8().data(), "r"); - if (!fileHandle) - return false; - - struct stat fileStat; - if (fstat(fileno(fileHandle), &fileStat)) { - fclose(fileHandle); - return false; - } - - data.grow(fileStat.st_size); - int bytesRead = fread(data.data(), 1, fileStat.st_size, fileHandle); - fclose(fileHandle); - - if (bytesRead < fileStat.st_size) - return false; - - size_t extStart = localPath.reverseFind('.'); - if (extStart == notFound) - return false; - - String ext = localPath.substring(extStart + 1); - if (ext.isEmpty()) - return false; - - contentType = WebCore::MIMETypeRegistry::getMIMETypeForExtension(ext); - - return true; -} - -void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType) -{ - StringBuilder builder; - builder.append('['); - - ClientMap::iterator end = m_clientMap.end(); - for (ClientMap::iterator it = m_clientMap.begin(); it != end; ++it) { - WebPageProxy* webPage = it->value->page(); - if (it != m_clientMap.begin()) - builder.appendLiteral(", "); - builder.appendLiteral("{ \"id\": "); - builder.appendNumber(it->key); - builder.appendLiteral(", \"title\": \""); - builder.append(webPage->pageTitle()); - builder.appendLiteral("\", \"url\": \""); - builder.append(webPage->activeURL()); - builder.appendLiteral("\", \"inspectorUrl\": \""); - builder.appendLiteral("/inspector.html?page="); - builder.appendNumber(it->key); - builder.appendLiteral("\" }"); - } - - builder.append(']'); - CString clientList = builder.toString().utf8(); - data.append(clientList.data(), clientList.length()); - contentType = String("application/json; charset=utf-8", String::ConstructFromLiteral); -} - -} -#endif diff --git a/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp b/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp deleted file mode 100644 index b4cd214b1..000000000 --- a/Source/WebKit2/UIProcess/InspectorServer/gtk/WebInspectorServerGtk.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics Ltd. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#if ENABLE(INSPECTOR_SERVER) -#include "WebInspectorServer.h" - -#include "WebInspectorProxy.h" -#include "WebPageProxy.h" -#include <WebCore/FileSystem.h> -#include <WebCore/MIMETypeRegistry.h> -#include <gio/gio.h> -#include <glib.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/StringBuilder.h> - -namespace WebKit { - -bool WebInspectorServer::platformResourceForPath(const String& path, Vector<char>& data, String& contentType) -{ - // The page list contains an unformated list of pages that can be inspected with a link to open a session. - if (path == "/pagelist.json") { - buildPageList(data, contentType); - return true; - } - - // Point the default path to a formatted page that queries the page list and display them. - CString localPath = WebCore::fileSystemRepresentation(inspectorServerFilesPath() + ((path == "/") ? "/inspectorPageIndex.html" : path)); - if (localPath.isNull()) - return false; - - GRefPtr<GFile> file = adoptGRef(g_file_new_for_path(localPath.data())); - GOwnPtr<GError> error; - GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(file.get(), G_FILE_ATTRIBUTE_STANDARD_SIZE "," G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE, G_FILE_QUERY_INFO_NONE, 0, &error.outPtr())); - if (!fileInfo) { - StringBuilder builder; - builder.appendLiteral("<!DOCTYPE html><html><head></head><body>Error: "); - builder.appendNumber(error->code); - builder.appendLiteral(", "); - builder.append(error->message); - builder.appendLiteral(" occurred during fetching webinspector resource files.<br>Make sure you ran make install or have set WEBKIT_INSPECTOR_SERVER_PATH in your environment to point to webinspector folder.</body></html>"); - CString cstr = builder.toString().utf8(); - data.append(cstr.data(), cstr.length()); - contentType = "text/html; charset=utf-8"; - g_warning("Error fetching webinspector resource files: %d, %s", error->code, error->message); - return true; - } - - GRefPtr<GFileInputStream> inputStream = adoptGRef(g_file_read(file.get(), 0, 0)); - if (!inputStream) - return false; - - data.grow(g_file_info_get_size(fileInfo.get())); - if (!g_input_stream_read_all(G_INPUT_STREAM(inputStream.get()), data.data(), data.size(), 0, 0, 0)) - return false; - - contentType = GOwnPtr<gchar>(g_file_info_get_attribute_as_string(fileInfo.get(), G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE)).get(); - return true; -} - -void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType) -{ - StringBuilder builder; - builder.appendLiteral("[ "); - ClientMap::iterator end = m_clientMap.end(); - for (ClientMap::iterator it = m_clientMap.begin(); it != end; ++it) { - WebPageProxy* webPage = it->value->page(); - if (it != m_clientMap.begin()) - builder.appendLiteral(", "); - builder.appendLiteral("{ \"id\": "); - builder.appendNumber(it->key); - builder.appendLiteral(", \"title\": \""); - builder.append(webPage->pageTitle()); - builder.appendLiteral("\", \"url\": \""); - builder.append(webPage->activeURL()); - builder.appendLiteral("\", \"inspectorUrl\": \""); - builder.appendLiteral("/inspector.html?page="); - builder.appendNumber(it->key); - builder.appendLiteral("\" }"); - } - builder.appendLiteral(" ]"); - CString cstr = builder.toString().utf8(); - data.append(cstr.data(), cstr.length()); - contentType = "application/json; charset=utf-8"; -} - -String WebInspectorServer::inspectorServerFilesPath() -{ - if (!m_inspectorServerFilesPath.isNull()) - return m_inspectorServerFilesPath; - - const char* environmentPath = g_getenv("WEBKIT_INSPECTOR_SERVER_PATH"); - if (environmentPath && g_file_test(environmentPath, G_FILE_TEST_IS_DIR)) - m_inspectorServerFilesPath = String(environmentPath); - else - m_inspectorServerFilesPath = String(WebCore::sharedResourcesPath().data()) + "/webinspector"; - - return m_inspectorServerFilesPath; -} - -} -#endif diff --git a/Source/WebKit2/UIProcess/InspectorServer/soup/WebSocketServerSoup.cpp b/Source/WebKit2/UIProcess/InspectorServer/soup/WebSocketServerSoup.cpp deleted file mode 100644 index 28f4f21d4..000000000 --- a/Source/WebKit2/UIProcess/InspectorServer/soup/WebSocketServerSoup.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics Ltd. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#if ENABLE(INSPECTOR_SERVER) -#include "WebSocketServer.h" - -#include "Logging.h" -#include "WebSocketServerConnection.h" -#include <WebCore/SocketStreamHandle.h> -#include <gio/gio.h> -#include <glib.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> - -using namespace WebCore; - -namespace WebKit { - -static gboolean connectionCallback(GSocketService* /*service*/, GSocketConnection* connection, GObject* /*sourceObject*/, WebSocketServer* server) -{ -#if !LOG_DISABLED - GRefPtr<GSocketAddress> socketAddress = adoptGRef(g_socket_connection_get_remote_address(connection, 0)); - GOwnPtr<gchar> addressString(g_inet_address_to_string(g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(socketAddress.get())))); - LOG(InspectorServer, "New Connection from %s:%d.", addressString.get(), g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(socketAddress.get()))); -#endif - - OwnPtr<WebSocketServerConnection> webSocketConnection = adoptPtr(new WebSocketServerConnection(server->client(), server)); - webSocketConnection->setSocketHandle(SocketStreamHandle::create(connection, webSocketConnection.get())); - server->didAcceptConnection(webSocketConnection.release()); - - return TRUE; -} - -void WebSocketServer::platformInitialize() -{ - m_socketService = adoptGRef(g_socket_service_new()); - g_signal_connect(m_socketService.get(), "incoming", G_CALLBACK(connectionCallback), this); - g_socket_service_start(m_socketService.get()); -} - -bool WebSocketServer::platformListen(const String& bindAddress, unsigned short port) -{ - LOG(InspectorServer, "Listen to address=%s, port=%d.", bindAddress.utf8().data(), port); - GRefPtr<GInetAddress> address = adoptGRef(g_inet_address_new_from_string(bindAddress.utf8().data())); - GRefPtr<GSocketAddress> socketAddress = adoptGRef(g_inet_socket_address_new(address.get(), port)); - return g_socket_listener_add_address(G_SOCKET_LISTENER(m_socketService.get()), socketAddress.get(), G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, 0, 0, 0); -} - -void WebSocketServer::platformClose() -{ - g_socket_service_stop(m_socketService.get()); -} - -} - -#endif // ENABLE(INSPECTOR_SERVER) diff --git a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp index a25b18310..e62e18d03 100644 --- a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp +++ b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.cpp @@ -26,14 +26,15 @@ #include "config.h" #include "ProcessLauncher.h" -#include "WorkQueue.h" #include <wtf/StdLibExtras.h> +#include <wtf/WorkQueue.h> namespace WebKit { -static WorkQueue* processLauncherWorkQueue() +static WorkQueue& processLauncherWorkQueue() { - static WorkQueue* processLauncherWorkQueue = WorkQueue::create("com.apple.WebKit.ProcessLauncher").leakRef(); + + static WorkQueue& processLauncherWorkQueue = WorkQueue::create("com.apple.WebKit.ProcessLauncher").leakRef(); return processLauncherWorkQueue; } @@ -42,28 +43,25 @@ ProcessLauncher::ProcessLauncher(Client* client, const LaunchOptions& launchOpti , m_launchOptions(launchOptions) , m_processIdentifier(0) { - // Launch the process. m_isLaunching = true; - processLauncherWorkQueue()->dispatch(bind(&ProcessLauncher::launchProcess, this)); + + RefPtr<ProcessLauncher> processLauncher(this); + processLauncherWorkQueue().dispatch([processLauncher] { + processLauncher->launchProcess(); + }); } -void ProcessLauncher::didFinishLaunchingProcess(PlatformProcessIdentifier processIdentifier, CoreIPC::Connection::Identifier identifier) +void ProcessLauncher::didFinishLaunchingProcess(PlatformProcessIdentifier processIdentifier, IPC::Connection::Identifier identifier) { m_processIdentifier = processIdentifier; m_isLaunching = false; if (!m_client) { // FIXME: Make Identifier a move-only object and release port rights/connections in the destructor. -#if PLATFORM(MAC) +#if OS(DARWIN) && !PLATFORM(GTK) + // FIXME: Should really be something like USE(MACH) if (identifier.port) mach_port_mod_refs(mach_task_self(), identifier.port, MACH_PORT_RIGHT_RECEIVE, -1); - -#if HAVE(XPC) - if (identifier.xpcConnection) { - xpc_release(identifier.xpcConnection); - identifier.xpcConnection = 0; - } -#endif #endif return; } @@ -77,58 +75,4 @@ void ProcessLauncher::invalidate() platformInvalidate(); } -const char* ProcessLauncher::processTypeAsString(ProcessType processType) -{ - switch (processType) { - case WebProcess: - return "webprocess"; -#if ENABLE(PLUGIN_PROCESS) - case PluginProcess: - return "pluginprocess"; -#endif -#if ENABLE(NETWORK_PROCESS) - case NetworkProcess: - return "networkprocess"; -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - case SharedWorkerProcess: - return "sharedworkerprocess"; -#endif - } - - ASSERT_NOT_REACHED(); - return 0; -} - -bool ProcessLauncher::getProcessTypeFromString(const char* string, ProcessType& processType) -{ - if (!strcmp(string, "webprocess")) { - processType = WebProcess; - return true; - } - -#if ENABLE(PLUGIN_PROCESS) - if (!strcmp(string, "pluginprocess")) { - processType = PluginProcess; - return true; - } -#endif - -#if ENABLE(NETWORK_PROCESS) - if (!strcmp(string, "networkprocess")) { - processType = NetworkProcess; - return true; - } -#endif - -#if ENABLE(SHARED_WORKER_PROCESS) - if (!strcmp(string, "sharedworkerprocess")) { - processType = SharedWorkerProcess; - return true; - } -#endif - - return false; -} - } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h index 85467ee44..74cc770c8 100644 --- a/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h +++ b/Source/WebKit2/UIProcess/Launcher/ProcessLauncher.h @@ -42,43 +42,33 @@ public: public: virtual ~Client() { } - virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier) = 0; + virtual void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) = 0; }; - enum ProcessType { - WebProcess, -#if ENABLE(PLUGIN_PROCESS) - PluginProcess, + enum class ProcessType { + Web, +#if ENABLE(NETSCAPE_PLUGIN_API) + Plugin32, + Plugin64, #endif -#if ENABLE(NETWORK_PROCESS) - NetworkProcess, -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - SharedWorkerProcess + Network, +#if ENABLE(DATABASE_PROCESS) + Database, #endif }; struct LaunchOptions { ProcessType processType; HashMap<String, String> extraInitializationData; -#if PLATFORM(MAC) - static const cpu_type_t MatchCurrentArchitecture = 0; - cpu_type_t architecture; - bool executableHeap; -#if HAVE(XPC) - bool useXPC; -#endif -#endif -#if PLATFORM(EFL) -#ifndef NDEBUG + +#if (PLATFORM(EFL) || PLATFORM(GTK)) && !defined(NDEBUG) String processCmdPrefix; #endif -#endif }; - static PassRefPtr<ProcessLauncher> create(Client* client, const LaunchOptions& launchOptions) + static Ref<ProcessLauncher> create(Client* client, const LaunchOptions& launchOptions) { - return adoptRef(new ProcessLauncher(client, launchOptions)); + return adoptRef(*new ProcessLauncher(client, launchOptions)); } bool isLaunching() const { return m_isLaunching; } @@ -87,14 +77,11 @@ public: void terminateProcess(); void invalidate(); - static bool getProcessTypeFromString(const char*, ProcessType&); - static const char* processTypeAsString(ProcessType); - private: ProcessLauncher(Client*, const LaunchOptions& launchOptions); void launchProcess(); - void didFinishLaunchingProcess(PlatformProcessIdentifier, CoreIPC::Connection::Identifier); + void didFinishLaunchingProcess(PlatformProcessIdentifier, IPC::Connection::Identifier); void platformInvalidate(); diff --git a/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp b/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp deleted file mode 100644 index 9b918abb8..000000000 --- a/Source/WebKit2/UIProcess/Launcher/efl/ProcessLauncherEfl.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright (C) 2012 Samsung Electronics - Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies). - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - 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 "ProcessLauncher.h" - -#include "Connection.h" -#include "ProcessExecutablePath.h" -#include <WebCore/AuthenticationChallenge.h> -#include <WebCore/FileSystem.h> -#include <WebCore/NetworkingContext.h> -#include <WebCore/ResourceHandle.h> -#include <WebCore/RunLoop.h> -#include <wtf/OwnArrayPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -using namespace WebCore; - -namespace WebKit { - -static Vector<OwnArrayPtr<char>> createArgsArray(const String& prefix, const String& executablePath, const String& socket, const String& pluginPath) -{ - ASSERT(!executablePath.isEmpty()); - ASSERT(!socket.isEmpty()); - - Vector<String> splitArgs; - prefix.split(' ', splitArgs); - - splitArgs.append(executablePath); - splitArgs.append(socket); - if (!pluginPath.isEmpty()) - splitArgs.append(pluginPath); - - Vector<OwnArrayPtr<char>> args; - args.resize(splitArgs.size() + 1); // Extra room for null. - - size_t numArgs = splitArgs.size(); - for (size_t i = 0; i < numArgs; ++i) { - CString param = splitArgs[i].utf8(); - args[i] = adoptArrayPtr(new char[param.length() + 1]); // Room for the terminating null coming from the CString. - strncpy(args[i].get(), param.data(), param.length() + 1); // +1 here so that strncpy copies the ending null. - } - // execvp() needs the pointers' array to be null-terminated. - args[numArgs] = nullptr; - - return args; -} - -void ProcessLauncher::launchProcess() -{ - int sockets[2]; - if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) { - ASSERT_NOT_REACHED(); - return; - } - - String processCmdPrefix, executablePath, pluginPath; - switch (m_launchOptions.processType) { - case WebProcess: - executablePath = executablePathOfWebProcess(); - break; -#if ENABLE(PLUGIN_PROCESS) - case PluginProcess: - executablePath = executablePathOfPluginProcess(); - pluginPath = m_launchOptions.extraInitializationData.get("plugin-path"); - break; -#endif - default: - ASSERT_NOT_REACHED(); - return; - } - -#ifndef NDEBUG - if (!m_launchOptions.processCmdPrefix.isEmpty()) - processCmdPrefix = m_launchOptions.processCmdPrefix; -#endif - Vector<OwnArrayPtr<char>> args = createArgsArray(processCmdPrefix, executablePath, String::number(sockets[0]), pluginPath); - - // Do not perform memory allocation in the middle of the fork() - // exec() below. FastMalloc can potentially deadlock because - // the fork() doesn't inherit the running threads. - pid_t pid = fork(); - if (!pid) { // Child process. - close(sockets[1]); - execvp(args.data()[0].get(), reinterpret_cast<char* const*>(args.data())); - } else if (pid > 0) { // parent process; - close(sockets[0]); - m_processIdentifier = pid; - // We've finished launching the process, message back to the main run loop. - RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, pid, sockets[1])); - } else { - ASSERT_NOT_REACHED(); - return; - } -} - -void ProcessLauncher::terminateProcess() -{ - if (m_isLaunching) { - invalidate(); - return; - } - - if (!m_processIdentifier) - return; - kill(m_processIdentifier, SIGKILL); - m_processIdentifier = 0; -} - -void ProcessLauncher::platformInvalidate() -{ -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp b/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp deleted file mode 100644 index 2ae1fdb5c..000000000 --- a/Source/WebKit2/UIProcess/Launcher/gtk/ProcessLauncherGtk.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, 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 MOTOROLA 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 MOTOROLA INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ProcessLauncher.h" - -#include "Connection.h" -#include "ProcessExecutablePath.h" -#include <WebCore/AuthenticationChallenge.h> -#include <WebCore/FileSystem.h> -#include <WebCore/NetworkingContext.h> -#include <WebCore/ResourceHandle.h> -#include <WebCore/RunLoop.h> -#include <errno.h> -#include <glib.h> -#include <locale.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/gobject/GlibUtilities.h> - -#if OS(LINUX) -#include <sys/prctl.h> -#include <sys/socket.h> -#endif - -#ifdef SOCK_SEQPACKET -#define SOCKET_TYPE SOCK_SEQPACKET -#else -#define SOCKET_TYPE SOCK_STREAM -#endif - -using namespace WebCore; - -namespace WebKit { - -static void childSetupFunction(gpointer userData) -{ - int socket = GPOINTER_TO_INT(userData); - close(socket); -} - -void ProcessLauncher::launchProcess() -{ - GPid pid = 0; - - int sockets[2]; - if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) < 0) { - g_printerr("Creation of socket failed: %s.\n", g_strerror(errno)); - ASSERT_NOT_REACHED(); - return; - } - - String executablePath, pluginPath; - CString realExecutablePath, realPluginPath; - if (m_launchOptions.processType == WebProcess) - executablePath = executablePathOfWebProcess(); - else { - executablePath = executablePathOfPluginProcess(); - pluginPath = m_launchOptions.extraInitializationData.get("plugin-path"); - realPluginPath = fileSystemRepresentation(pluginPath); - } - - realExecutablePath = fileSystemRepresentation(executablePath); - GOwnPtr<gchar> socket(g_strdup_printf("%d", sockets[0])); - char* argv[4]; - argv[0] = const_cast<char*>(realExecutablePath.data()); - argv[1] = socket.get(); - argv[2] = const_cast<char*>(realPluginPath.data()); - argv[3] = 0; - - GOwnPtr<GError> error; - if (!g_spawn_async(0, argv, 0, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, childSetupFunction, GINT_TO_POINTER(sockets[1]), &pid, &error.outPtr())) { - g_printerr("Unable to fork a new WebProcess: %s.\n", error->message); - ASSERT_NOT_REACHED(); - } - - close(sockets[0]); - m_processIdentifier = pid; - - // We've finished launching the process, message back to the main run loop. - RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, m_processIdentifier, sockets[1])); -} - -void ProcessLauncher::terminateProcess() -{ - if (m_isLaunching) { - invalidate(); - return; - } - - if (!m_processIdentifier) - return; - - kill(m_processIdentifier, SIGKILL); - m_processIdentifier = 0; -} - -void ProcessLauncher::platformInvalidate() -{ -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm b/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm deleted file mode 100644 index bca9ac3d0..000000000 --- a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.mm +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "DynamicLinkerEnvironmentExtractor.h" - -#include "EnvironmentVariables.h" -#include <mach-o/loader.h> -#include <mach-o/swap.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/text/WTFString.h> - -namespace WebKit { - -DynamicLinkerEnvironmentExtractor::DynamicLinkerEnvironmentExtractor(NSString *executablePath, cpu_type_t architecture) - : m_executablePath(executablePath) - , m_architecture(architecture) -{ - NSData *mainExecutableData = [NSData dataWithContentsOfFile:m_executablePath.get() options:NSDataReadingMappedIfSafe error:0]; - if (!mainExecutableData) - return; - - const void* mainExecutableBytes = [mainExecutableData bytes]; - size_t length = [mainExecutableData length]; - if (length < sizeof(uint32_t)) - return; - - uint32_t magicValue = *static_cast<const uint32_t*>(mainExecutableBytes); - if (magicValue == FAT_MAGIC || magicValue == FAT_CIGAM) { - processFatFile(mainExecutableBytes, length); - return; - } - - processSingleArchitecture(mainExecutableBytes, length); -} - -#define DEFINE_BYTE_SWAPPER(type) inline type byteSwapIfNeeded(const type& data, bool shouldByteSwap) \ -{ \ - type swapped = data; \ - if (shouldByteSwap) \ - swap_##type(&swapped, NX_UnknownByteOrder); \ - return swapped; \ -} - -DEFINE_BYTE_SWAPPER(load_command) -DEFINE_BYTE_SWAPPER(dylinker_command) -DEFINE_BYTE_SWAPPER(mach_header) -DEFINE_BYTE_SWAPPER(mach_header_64) - -#undef DEFINE_BYTE_SWAPPER - -void DynamicLinkerEnvironmentExtractor::processEnvironmentVariable(const char* environmentString) -{ - const char* equalsLocation = strchr(environmentString, '='); - if (!equalsLocation) - return; - - size_t nameLength = equalsLocation - environmentString; - String name(environmentString, nameLength); - - // LC_DYLD_ENVIRONMENT only respects DYLD_*_PATH variables. - if (!name.startsWith("DYLD_") || !name.endsWith("_PATH")) - return; - - CString value(equalsLocation + 1); - m_extractedVariables.append(std::make_pair(name.latin1(), value)); -} - -size_t DynamicLinkerEnvironmentExtractor::processLoadCommand(const void* data, size_t length, bool shouldByteSwap) -{ - if (length < sizeof(load_command)) - return 0; - - const load_command* rawLoadCommand = static_cast<const load_command*>(data); - load_command loadCommand = byteSwapIfNeeded(*rawLoadCommand, shouldByteSwap); - - if (length < loadCommand.cmdsize) - return 0; - - if (loadCommand.cmd == LC_DYLD_ENVIRONMENT) { - if (length < sizeof(dylinker_command)) - return 0; - - dylinker_command environmentCommand = byteSwapIfNeeded(*reinterpret_cast<const dylinker_command*>(rawLoadCommand), shouldByteSwap); - if (loadCommand.cmdsize < environmentCommand.name.offset) - return 0; - - size_t environmentStringLength = loadCommand.cmdsize - environmentCommand.name.offset; - Vector<char, 256> environmentString; - environmentString.reserveCapacity(environmentStringLength + 1); - environmentString.append(reinterpret_cast<const char*>(rawLoadCommand) + environmentCommand.name.offset, environmentStringLength); - environmentString.append(0); - - processEnvironmentVariable(environmentString.data()); - } - - return loadCommand.cmdsize; -} - -void DynamicLinkerEnvironmentExtractor::processLoadCommands(const void* data, size_t length, int32_t numberOfCommands, bool shouldByteSwap) -{ - const void* dataRemaining = data; - size_t lengthRemaining = length; - for (int i = 0; i < numberOfCommands; i++) { - size_t commandLength = processLoadCommand(dataRemaining, lengthRemaining, shouldByteSwap); - if (!commandLength || lengthRemaining < commandLength) - return; - - dataRemaining = static_cast<const char*>(dataRemaining) + commandLength; - lengthRemaining -= commandLength; - } -} - -void DynamicLinkerEnvironmentExtractor::processSingleArchitecture(const void* data, size_t length) -{ - if (length < sizeof(mach_header)) - return; - - const mach_header* header = static_cast<const mach_header*>(data); - if (header->magic == MH_MAGIC || header->magic == MH_CIGAM) { - bool shouldByteSwap = header->magic == MH_CIGAM; - mach_header swappedHeader = byteSwapIfNeeded(*header, shouldByteSwap); - if (swappedHeader.cputype == m_architecture) - processLoadCommands(static_cast<const char*>(data) + sizeof(*header), length - sizeof(*header), swappedHeader.ncmds, shouldByteSwap); - return; - } - - if (length < sizeof(mach_header_64)) - return; - - const mach_header_64* header64 = static_cast<const mach_header_64*>(data); - bool shouldByteSwap = header->magic == MH_CIGAM_64; - mach_header_64 swappedHeader64 = byteSwapIfNeeded(*header64, shouldByteSwap); - if (swappedHeader64.cputype == m_architecture) - processLoadCommands(static_cast<const char*>(data) + sizeof(*header64), length - sizeof(*header64), swappedHeader64.ncmds, shouldByteSwap); -} - -void DynamicLinkerEnvironmentExtractor::processFatFile(const void* data, size_t length) -{ - if (length < sizeof(fat_header)) - return; - - const fat_header* header = static_cast<const fat_header*>(data); - - size_t numberOfArchitectures = OSSwapBigToHostInt32(header->nfat_arch); - - // Ensure that we have enough data remaining for numberOfArchitectures fat_arch structs. - if ((length - sizeof(fat_header)) / sizeof(fat_arch) < numberOfArchitectures) - return; - - const fat_arch* archs = reinterpret_cast<const fat_arch*>(reinterpret_cast<const char*>(data) + sizeof(*header)); - for (uint32_t i = 0; i < numberOfArchitectures; i++) { - uint32_t architectureOffset = OSSwapBigToHostInt32(archs[i].offset); - uint32_t architectureSize = OSSwapBigToHostInt32(archs[i].size); - if (length < architectureOffset + architectureSize) - return; - - processSingleArchitecture(static_cast<const char*>(data) + architectureOffset, architectureSize); - } -} - -void DynamicLinkerEnvironmentExtractor::getExtractedEnvironmentVariables(EnvironmentVariables& environmentVariables) const -{ - size_t extractedVariableCount = m_extractedVariables.size(); - for (size_t i = 0; i < extractedVariableCount; ++i) { - const CString& name = m_extractedVariables[i].first; - - // Preserve any existing environment variable by this name so that it will take - // precedence over what we extracted from the executable file. - if (environmentVariables.get(name.data())) - continue; - - environmentVariables.set(name.data(), m_extractedVariables[i].second.data()); - } -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp b/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp deleted file mode 100644 index 39c6baf4c..000000000 --- a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "EnvironmentVariables.h" - -#include <crt_externs.h> - -namespace WebKit { - -EnvironmentVariables::EnvironmentVariables() - : m_environmentPointer(*_NSGetEnviron()) -{ -} - -EnvironmentVariables::~EnvironmentVariables() -{ - size_t size = m_allocatedStrings.size(); - for (size_t i = 0; i < size; ++i) - fastFree(m_allocatedStrings[i]); -} - -void EnvironmentVariables::set(const char* name, const char* value) -{ - // Check if we need to copy the environment. - if (m_environmentPointer == *_NSGetEnviron()) - copyEnvironmentVariables(); - - // Allocate a string for the name and value. - const char* nameAndValue = createStringForVariable(name, value); - - for (size_t i = 0; i < m_environmentVariables.size() - 1; ++i) { - if (valueIfVariableHasName(m_environmentVariables[i], name)) { - // Just replace the environment variable. - m_environmentVariables[i] = const_cast<char*>(nameAndValue); - return; - } - } - - // Append the new string. - ASSERT(!m_environmentVariables.last()); - m_environmentVariables.last() = const_cast<char*>(nameAndValue); - m_environmentVariables.append(static_cast<char*>(0)); - - m_environmentPointer = m_environmentVariables.data(); -} - -const char* EnvironmentVariables::get(const char* name) const -{ - for (size_t i = 0; m_environmentPointer[i]; ++i) { - if (const char* value = valueIfVariableHasName(m_environmentPointer[i], name)) - return value; - } - return 0; -} - -void EnvironmentVariables::appendValue(const char* name, const char* value, char separator) -{ - const char* existingValue = get(name); - if (!existingValue) { - set(name, value); - return; - } - - Vector<char, 128> newValue; - newValue.append(existingValue, strlen(existingValue)); - newValue.append(separator); - newValue.append(value, strlen(value) + 1); - - set(name, newValue.data()); -} - -const char* EnvironmentVariables::valueIfVariableHasName(const char* environmentVariable, const char* name) const -{ - // Find the environment variable name. - const char* equalsLocation = strchr(environmentVariable, '='); - ASSERT(equalsLocation); - - size_t nameLength = equalsLocation - environmentVariable; - if (strlen(name) != nameLength) - return 0; - if (memcmp(environmentVariable, name, nameLength)) - return 0; - - return equalsLocation + 1; -} - -const char* EnvironmentVariables::createStringForVariable(const char* name, const char* value) -{ - int nameLength = strlen(name); - int valueLength = strlen(value); - - // Allocate enough room to hold 'name=value' and the null character. - char* string = static_cast<char*>(fastMalloc(nameLength + 1 + valueLength + 1)); - memcpy(string, name, nameLength); - string[nameLength] = '='; - memcpy(string + nameLength + 1, value, valueLength); - string[nameLength + 1 + valueLength] = '\0'; - - m_allocatedStrings.append(string); - - return string; -} - -void EnvironmentVariables::copyEnvironmentVariables() -{ - for (size_t i = 0; (*_NSGetEnviron())[i]; i++) - m_environmentVariables.append((*_NSGetEnviron())[i]); - - // Null-terminate the array. - m_environmentVariables.append(static_cast<char*>(0)); - - // Update the environment pointer. - m_environmentPointer = m_environmentVariables.data(); -} - -const char* EnvironmentVariables::preexistingProcessServiceNameKey() -{ - return "WEBKIT_PREEXISTING_PROCESS_SERVICE_NAME"; -} - -const char* EnvironmentVariables::preexistingProcessTypeKey() -{ - return "WEBKIT_PREEXISTING_PROCESS_TYPE"; -} - -void EnvironmentVariables::dump() -{ - for (size_t i = 0; (*_NSGetEnviron())[i]; i++) - printf("%s\n", (*_NSGetEnviron())[i]); - - printf("\n\n\n"); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h b/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h deleted file mode 100644 index 78343cf37..000000000 --- a/Source/WebKit2/UIProcess/Launcher/mac/EnvironmentVariables.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef EnvironmentVariables_h -#define EnvironmentVariables_h - -#include <wtf/Noncopyable.h> -#include <wtf/Vector.h> - -namespace WebKit { - -class EnvironmentVariables { - WTF_MAKE_NONCOPYABLE(EnvironmentVariables); - -public: - EnvironmentVariables(); - ~EnvironmentVariables(); - - void set(const char* name, const char* value); - const char* get(const char* name) const; - - // Will append the value with the given separator if the environment variable already exists. - void appendValue(const char* name, const char* value, char separator); - - char** environmentPointer() const { return m_environmentPointer; } - - static const char* preexistingProcessServiceNameKey(); - static const char* preexistingProcessTypeKey(); - - static void dump(); - -private: - const char* valueIfVariableHasName(const char* environmentVariable, const char* name) const; - const char* createStringForVariable(const char* name, const char* value); - void copyEnvironmentVariables(); - - char** m_environmentPointer; - Vector<char*> m_environmentVariables; - - // These allocated strings will be freed in the destructor. - Vector<char*> m_allocatedStrings; -}; - -} // namespace WebKit - -#endif // EnvironmentVariables_h diff --git a/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm b/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm deleted file mode 100644 index 7c951668c..000000000 --- a/Source/WebKit2/UIProcess/Launcher/mac/ProcessLauncherMac.mm +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "ProcessLauncher.h" - -#import "DynamicLinkerEnvironmentExtractor.h" -#import "EnvironmentVariables.h" -#import "WebKitSystemInterface.h" -#import <WebCore/RunLoop.h> -#import <crt_externs.h> -#import <mach-o/dyld.h> -#import <mach/machine.h> -#import <runtime/InitializeThreading.h> -#import <servers/bootstrap.h> -#import <spawn.h> -#import <sys/param.h> -#import <sys/stat.h> -#import <wtf/PassRefPtr.h> -#import <wtf/RetainPtr.h> -#import <wtf/Threading.h> -#import <wtf/text/CString.h> -#import <wtf/text/WTFString.h> - -#if HAVE(XPC) -#import <xpc/xpc.h> -#endif - -using namespace WebCore; - -// FIXME: We should be doing this another way. -extern "C" kern_return_t bootstrap_register2(mach_port_t, name_t, mach_port_t, uint64_t); - -#if HAVE(XPC) -extern "C" void xpc_connection_set_instance(xpc_connection_t, uuid_t); -extern "C" void xpc_dictionary_set_mach_send(xpc_object_t, const char*, mach_port_t); -#endif - -namespace WebKit { - -namespace { - -struct UUIDHolder : public RefCounted<UUIDHolder> { - static PassRefPtr<UUIDHolder> create() - { - return adoptRef(new UUIDHolder); - } - - UUIDHolder() - { - uuid_generate(uuid); - } - - uuid_t uuid; -}; - -} - -static void setUpTerminationNotificationHandler(pid_t pid) -{ -#if HAVE(DISPATCH_H) - dispatch_source_t processDiedSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, pid, DISPATCH_PROC_EXIT, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); - dispatch_source_set_event_handler(processDiedSource, ^{ - int status; - waitpid(dispatch_source_get_handle(processDiedSource), &status, 0); - dispatch_source_cancel(processDiedSource); - }); - dispatch_source_set_cancel_handler(processDiedSource, ^{ - dispatch_release(processDiedSource); - }); - dispatch_resume(processDiedSource); -#endif -} - -static void addDYLDEnvironmentAdditions(const ProcessLauncher::LaunchOptions& launchOptions, bool isWebKitDevelopmentBuild, EnvironmentVariables& environmentVariables) -{ - DynamicLinkerEnvironmentExtractor environmentExtractor([[NSBundle mainBundle] executablePath], _NSGetMachExecuteHeader()->cputype); - environmentExtractor.getExtractedEnvironmentVariables(environmentVariables); - - NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"]; - NSString *frameworksPath = [[webKit2Bundle bundlePath] stringByDeletingLastPathComponent]; - - // To make engineering builds work, if the path is outside of /System set up - // DYLD_FRAMEWORK_PATH to pick up other frameworks, but don't do it for the - // production configuration because it involves extra file system access. - if (isWebKitDevelopmentBuild) - environmentVariables.appendValue("DYLD_FRAMEWORK_PATH", [frameworksPath fileSystemRepresentation], ':'); - - NSString *processShimPathNSString = nil; -#if ENABLE(PLUGIN_PROCESS) - if (launchOptions.processType == ProcessLauncher::PluginProcess) { - NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"PluginProcess.app"]; - NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; - - processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"PluginProcessShim.dylib"]; - } else -#endif // ENABLE(PLUGIN_PROCESS) - if (launchOptions.processType == ProcessLauncher::WebProcess) { - NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"WebProcess.app"]; - NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; - - processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"WebProcessShim.dylib"]; - } else if (launchOptions.processType == ProcessLauncher::NetworkProcess) { - NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"NetworkProcess.app"]; - NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; - - processShimPathNSString = [[processAppExecutablePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"SecItemShim.dylib"]; - } - - // Make sure that the shim library file exists and insert it. - if (processShimPathNSString) { - const char* processShimPath = [processShimPathNSString fileSystemRepresentation]; - struct stat statBuf; - if (stat(processShimPath, &statBuf) == 0 && (statBuf.st_mode & S_IFMT) == S_IFREG) - environmentVariables.appendValue("DYLD_INSERT_LIBRARIES", processShimPath, ':'); - } - -} - -typedef void (ProcessLauncher::*DidFinishLaunchingProcessFunction)(PlatformProcessIdentifier, CoreIPC::Connection::Identifier); - -#if HAVE(XPC) - -static const char* serviceName(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment) -{ - switch (launchOptions.processType) { - case ProcessLauncher::WebProcess: - if (forDevelopment) - return "com.apple.WebKit.WebContent.Development"; - return "com.apple.WebKit.WebContent"; -#if ENABLE(NETWORK_PROCESS) - case ProcessLauncher::NetworkProcess: - if (forDevelopment) - return "com.apple.WebKit.Networking.Development"; - return "com.apple.WebKit.Networking"; -#endif -#if ENABLE(PLUGIN_PROCESS) - case ProcessLauncher::PluginProcess: - if (forDevelopment) - return "com.apple.WebKit.Plugin.Development"; - - // FIXME: Support plugins that require an executable heap. - if (launchOptions.architecture == CPU_TYPE_X86) - return "com.apple.WebKit.Plugin.32"; - if (launchOptions.architecture == CPU_TYPE_X86_64) - return "com.apple.WebKit.Plugin.64"; - - ASSERT_NOT_REACHED(); - return 0; -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - case ProcessLauncher::SharedWorkerProcess: - ASSERT_NOT_REACHED(); - return 0; -#endif - } -} - -static void connectToService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction, UUIDHolder* instanceUUID) -{ - // Create a connection to the WebKit2 XPC service. - xpc_connection_t connection = xpc_connection_create(serviceName(launchOptions, forDevelopment), 0); - xpc_connection_set_instance(connection, instanceUUID->uuid); - - // XPC requires having an event handler, even if it is not used. - xpc_connection_set_event_handler(connection, ^(xpc_object_t event) { }); - xpc_connection_resume(connection); - -#if ENABLE(NETWORK_PROCESS) - if (launchOptions.processType == ProcessLauncher::NetworkProcess) { - xpc_object_t preBootstrapMessage = xpc_dictionary_create(0, 0, 0); - xpc_dictionary_set_string(preBootstrapMessage, "message-name", "pre-bootstrap"); - xpc_connection_send_message(connection, preBootstrapMessage); - xpc_release(preBootstrapMessage); - } -#endif - - // Create the listening port. - mach_port_t listeningPort; - mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort); - - // Insert a send right so we can send to it. - mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND); - - NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; - CString clientIdentifier = bundleIdentifier ? String([[NSBundle mainBundle] bundleIdentifier]).utf8() : *_NSGetProgname(); - - xpc_object_t bootstrapMessage = xpc_dictionary_create(0, 0, 0); - xpc_dictionary_set_string(bootstrapMessage, "message-name", "bootstrap"); - xpc_dictionary_set_string(bootstrapMessage, "framework-executable-path", [[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] executablePath] fileSystemRepresentation]); - xpc_dictionary_set_mach_send(bootstrapMessage, "server-port", listeningPort); - xpc_dictionary_set_string(bootstrapMessage, "client-identifier", clientIdentifier.data()); - xpc_dictionary_set_string(bootstrapMessage, "ui-process-name", [[[NSProcessInfo processInfo] processName] UTF8String]); - - if (forDevelopment) { - xpc_dictionary_set_fd(bootstrapMessage, "stdout", STDOUT_FILENO); - xpc_dictionary_set_fd(bootstrapMessage, "stderr", STDERR_FILENO); - } - - xpc_object_t extraInitializationData = xpc_dictionary_create(0, 0, 0); - HashMap<String, String>::const_iterator it = launchOptions.extraInitializationData.begin(); - HashMap<String, String>::const_iterator end = launchOptions.extraInitializationData.end(); - for (; it != end; ++it) - xpc_dictionary_set_string(extraInitializationData, it->key.utf8().data(), it->value.utf8().data()); - xpc_dictionary_set_value(bootstrapMessage, "extra-initialization-data", extraInitializationData); - xpc_release(extraInitializationData); - - that->ref(); - - xpc_connection_send_message_with_reply(connection, bootstrapMessage, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t reply) { - xpc_type_t type = xpc_get_type(reply); - if (type == XPC_TYPE_ERROR) { - // We failed to launch. Release the send right. - mach_port_deallocate(mach_task_self(), listeningPort); - - // And the receive right. - mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1); - - RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, 0, CoreIPC::Connection::Identifier())); - } else { - ASSERT(type == XPC_TYPE_DICTIONARY); - ASSERT(!strcmp(xpc_dictionary_get_string(reply, "message-name"), "process-finished-launching")); - - // The process has finished launching, grab the pid from the connection. - pid_t processIdentifier = xpc_connection_get_pid(connection); - - // We've finished launching the process, message back to the main run loop. - RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort, connection))); - } - - that->deref(); - }); - xpc_release(bootstrapMessage); -} - -static void connectToReExecService(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) -{ - EnvironmentVariables environmentVariables; - addDYLDEnvironmentAdditions(launchOptions, true, environmentVariables); - - // Generate the uuid for the service instance we are about to create. - // FIXME: This UUID should be stored on the ChildProcessProxy. - RefPtr<UUIDHolder> instanceUUID = UUIDHolder::create(); - - xpc_connection_t reExecConnection = xpc_connection_create(serviceName(launchOptions, true), 0); - xpc_connection_set_instance(reExecConnection, instanceUUID->uuid); - - // Keep the ProcessLauncher alive while we do the re-execing (balanced in event handler). - that->ref(); - - // We wait for the connection to tear itself down (indicated via an error event) - // to indicate that the service instance re-execed itself, and is now ready to be - // connected to. - xpc_connection_set_event_handler(reExecConnection, ^(xpc_object_t event) { - ASSERT(xpc_get_type(event) == XPC_TYPE_ERROR); - - connectToService(launchOptions, true, that, didFinishLaunchingProcessFunction, instanceUUID.get()); - - // Release the connection. - xpc_release(reExecConnection); - - // Other end of ref called before we setup the event handler. - that->deref(); - }); - xpc_connection_resume(reExecConnection); - - xpc_object_t reExecMessage = xpc_dictionary_create(0, 0, 0); - xpc_dictionary_set_string(reExecMessage, "message-name", "re-exec"); - - cpu_type_t architecture = launchOptions.architecture == ProcessLauncher::LaunchOptions::MatchCurrentArchitecture ? _NSGetMachExecuteHeader()->cputype : launchOptions.architecture; - xpc_dictionary_set_uint64(reExecMessage, "architecture", (uint64_t)architecture); - - xpc_object_t environment = xpc_array_create(0, 0); - char** environmentPointer = environmentVariables.environmentPointer(); - Vector<CString> temps; - for (size_t i = 0; environmentPointer[i]; ++i) { - CString temp(environmentPointer[i], strlen(environmentPointer[i])); - temps.append(temp); - - xpc_array_set_string(environment, XPC_ARRAY_APPEND, temp.data()); - } - xpc_dictionary_set_value(reExecMessage, "environment", environment); - xpc_release(environment); - - xpc_dictionary_set_bool(reExecMessage, "executable-heap", launchOptions.executableHeap); - - xpc_connection_send_message(reExecConnection, reExecMessage); - xpc_release(reExecMessage); -} - -static void createService(const ProcessLauncher::LaunchOptions& launchOptions, bool forDevelopment, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) -{ - if (forDevelopment) { - connectToReExecService(launchOptions, that, didFinishLaunchingProcessFunction); - return; - } - - // Generate the uuid for the service instance we are about to create. - // FIXME: This UUID should be stored on the ChildProcessProxy. - RefPtr<UUIDHolder> instanceUUID = UUIDHolder::create(); - connectToService(launchOptions, false, that, didFinishLaunchingProcessFunction, instanceUUID.get()); -} - -#endif - -static bool tryPreexistingProcess(const ProcessLauncher::LaunchOptions& launchOptions, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) -{ - EnvironmentVariables environmentVariables; - static const char* preexistingProcessServiceName = environmentVariables.get(EnvironmentVariables::preexistingProcessServiceNameKey()); - - ProcessLauncher::ProcessType preexistingProcessType; - if (preexistingProcessServiceName) - ProcessLauncher::getProcessTypeFromString(environmentVariables.get(EnvironmentVariables::preexistingProcessTypeKey()), preexistingProcessType); - - bool usePreexistingProcess = preexistingProcessServiceName && preexistingProcessType == launchOptions.processType; - if (!usePreexistingProcess) - return false; - - // Create the listening port. - mach_port_t listeningPort; - mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort); - - // Insert a send right so we can send to it. - mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND); - - pid_t processIdentifier = 0; - - mach_port_t lookupPort; - bootstrap_look_up(bootstrap_port, preexistingProcessServiceName, &lookupPort); - - mach_msg_header_t header; - header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND); - header.msgh_id = 0; - header.msgh_local_port = listeningPort; - header.msgh_remote_port = lookupPort; - header.msgh_size = sizeof(header); - kern_return_t kr = mach_msg(&header, MACH_SEND_MSG, sizeof(header), 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); - - mach_port_deallocate(mach_task_self(), lookupPort); - preexistingProcessServiceName = 0; - - if (kr) { - LOG_ERROR("Failed to pick up preexisting process at %s (%x). Launching a new process of type %s instead.", preexistingProcessServiceName, kr, ProcessLauncher::processTypeAsString(launchOptions.processType)); - return false; - } - - // We've finished launching the process, message back to the main run loop. - RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort))); - return true; -} - -static void createProcess(const ProcessLauncher::LaunchOptions& launchOptions, bool isWebKitDevelopmentBuild, ProcessLauncher* that, DidFinishLaunchingProcessFunction didFinishLaunchingProcessFunction) -{ - EnvironmentVariables environmentVariables; - addDYLDEnvironmentAdditions(launchOptions, isWebKitDevelopmentBuild, environmentVariables); - - // Create the listening port. - mach_port_t listeningPort; - mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort); - - // Insert a send right so we can send to it. - mach_port_insert_right(mach_task_self(), listeningPort, listeningPort, MACH_MSG_TYPE_MAKE_SEND); - - RetainPtr<CFStringRef> cfLocalization = adoptCF(WKCopyCFLocalizationPreferredName(NULL)); - CString localization = String(cfLocalization.get()).utf8(); - - NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"]; - - NSString *processPath = nil; - switch (launchOptions.processType) { - case ProcessLauncher::WebProcess: - processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"WebProcess.app"]; - break; -#if ENABLE(PLUGIN_PROCESS) - case ProcessLauncher::PluginProcess: - processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"PluginProcess.app"]; - break; -#endif -#if ENABLE(NETWORK_PROCESS) - case ProcessLauncher::NetworkProcess: - processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"NetworkProcess.app"]; - break; -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - case ProcessLauncher::SharedWorkerProcess: - processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"SharedWorkerProcess.app"]; - break; -#endif - } - - NSString *frameworkExecutablePath = [webKit2Bundle executablePath]; - NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; - - NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; - CString clientIdentifier = bundleIdentifier ? String([[NSBundle mainBundle] bundleIdentifier]).utf8() : *_NSGetProgname(); - - // Make a unique, per pid, per process launcher web process service name. - CString serviceName = String::format("com.apple.WebKit.WebProcess-%d-%p", getpid(), that).utf8(); - - Vector<const char*> args; - args.append([processAppExecutablePath fileSystemRepresentation]); - args.append([frameworkExecutablePath fileSystemRepresentation]); - args.append("-type"); - args.append(ProcessLauncher::processTypeAsString(launchOptions.processType)); - args.append("-servicename"); - args.append(serviceName.data()); - args.append("-localization"); - args.append(localization.data()); - args.append("-client-identifier"); - args.append(clientIdentifier.data()); - args.append("-ui-process-name"); - args.append([[[NSProcessInfo processInfo] processName] UTF8String]); - - HashMap<String, String>::const_iterator it = launchOptions.extraInitializationData.begin(); - HashMap<String, String>::const_iterator end = launchOptions.extraInitializationData.end(); - Vector<CString> temps; - for (; it != end; ++it) { - String keyPlusDash = "-" + it->key; - CString key(keyPlusDash.utf8().data()); - temps.append(key); - args.append(key.data()); - - CString value(it->value.utf8().data()); - temps.append(value); - args.append(value.data()); - } - - args.append(nullptr); - - // Register ourselves. - kern_return_t kr = bootstrap_register2(bootstrap_port, const_cast<char*>(serviceName.data()), listeningPort, 0); - ASSERT_UNUSED(kr, kr == KERN_SUCCESS); - - posix_spawnattr_t attr; - posix_spawnattr_init(&attr); - - short flags = 0; - - // We want our process to receive all signals. - sigset_t signalMaskSet; - sigemptyset(&signalMaskSet); - - posix_spawnattr_setsigmask(&attr, &signalMaskSet); - flags |= POSIX_SPAWN_SETSIGMASK; - - // Determine the architecture to use. - cpu_type_t architecture = launchOptions.architecture; - if (architecture == ProcessLauncher::LaunchOptions::MatchCurrentArchitecture) - architecture = _NSGetMachExecuteHeader()->cputype; - - cpu_type_t cpuTypes[] = { architecture }; - size_t outCount = 0; - posix_spawnattr_setbinpref_np(&attr, 1, cpuTypes, &outCount); - - // Start suspended so we can set up the termination notification handler. - flags |= POSIX_SPAWN_START_SUSPENDED; - - static const int allowExecutableHeapFlag = 0x2000; - if (launchOptions.executableHeap) - flags |= allowExecutableHeapFlag; - - posix_spawnattr_setflags(&attr, flags); - - pid_t processIdentifier = 0; - int result = posix_spawn(&processIdentifier, args[0], 0, &attr, const_cast<char**>(args.data()), environmentVariables.environmentPointer()); - - posix_spawnattr_destroy(&attr); - - if (!result) { - // Set up the termination notification handler and then ask the child process to continue. - setUpTerminationNotificationHandler(processIdentifier); - kill(processIdentifier, SIGCONT); - } else { - // We failed to launch. Release the send right. - mach_port_deallocate(mach_task_self(), listeningPort); - - // And the receive right. - mach_port_mod_refs(mach_task_self(), listeningPort, MACH_PORT_RIGHT_RECEIVE, -1); - - listeningPort = MACH_PORT_NULL; - processIdentifier = 0; - } - - // We've finished launching the process, message back to the main run loop. - RunLoop::main()->dispatch(bind(didFinishLaunchingProcessFunction, that, processIdentifier, CoreIPC::Connection::Identifier(listeningPort))); -} - -void ProcessLauncher::launchProcess() -{ - if (tryPreexistingProcess(m_launchOptions, this, &ProcessLauncher::didFinishLaunchingProcess)) - return; - - bool isWebKitDevelopmentBuild = ![[[[NSBundle bundleWithIdentifier:@"com.apple.WebKit2"] bundlePath] stringByDeletingLastPathComponent] hasPrefix:@"/System/"]; - -#if HAVE(XPC) - if (m_launchOptions.useXPC) { - createService(m_launchOptions, isWebKitDevelopmentBuild, this, &ProcessLauncher::didFinishLaunchingProcess); - return; - } -#endif - - createProcess(m_launchOptions, isWebKitDevelopmentBuild, this, &ProcessLauncher::didFinishLaunchingProcess); -} - -void ProcessLauncher::terminateProcess() -{ - if (m_isLaunching) { - invalidate(); - return; - } - - if (!m_processIdentifier) - return; - - kill(m_processIdentifier, SIGKILL); - m_processIdentifier = 0; -} - -void ProcessLauncher::platformInvalidate() -{ -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebFullScreenClientGtk.h b/Source/WebKit2/UIProcess/LegacySessionStateCoding.h index f39376449..2321a2ecd 100644 --- a/Source/WebKit2/UIProcess/gtk/WebFullScreenClientGtk.h +++ b/Source/WebKit2/UIProcess/LegacySessionStateCoding.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2014 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,22 +23,23 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebFullScreenClientGtk_h -#define WebFullScreenClientGtk_h +#ifndef LegacySessionStateCoding_h +#define LegacySessionStateCoding_h -#include "APIClient.h" -#include "WKFullScreenClientGtk.h" +#include <wtf/Forward.h> + +namespace API { +class Data; +} namespace WebKit { -class APIObject; +struct FrameState; +struct SessionState; -class WebFullScreenClientGtk : public APIClient<WKFullScreenClientGtk, kWKFullScreenClientGtkCurrentVersion> { -public: - bool willEnterFullScreen(); - bool willExitFullScreen(); -}; +RefPtr<API::Data> encodeLegacySessionState(const SessionState&); +bool decodeLegacySessionState(const uint8_t* data, size_t, SessionState&); } // namespace WebKit -#endif // WebFullScreenClientGtk_h +#endif // LegacySessionStateCoding_h diff --git a/Source/WebKit2/UIProcess/efl/WebPreferencesEfl.cpp b/Source/WebKit2/UIProcess/LegacySessionStateCodingNone.cpp index dd2108452..4627bc990 100644 --- a/Source/WebKit2/UIProcess/efl/WebPreferencesEfl.cpp +++ b/Source/WebKit2/UIProcess/LegacySessionStateCodingNone.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Samsung Electronics + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,40 +24,35 @@ */ #include "config.h" -#include "WebPreferences.h" +#include "LegacySessionStateCoding.h" -#include <WebCore/NotImplemented.h> +#include "APIData.h" +#include "ArgumentDecoder.h" +#include "ArgumentEncoder.h" +#include "SessionState.h" +#include "WebCoreArgumentCoders.h" namespace WebKit { -void WebPreferences::platformInitializeStore() +RefPtr<API::Data> encodeLegacySessionState(const SessionState& sessionState) { - notImplemented(); + IPC::ArgumentEncoder encoder; + encoder << sessionState.backForwardListState; + encoder << sessionState.renderTreeSize; + encoder << sessionState.provisionalURL; + return API::Data::create(encoder.buffer(), encoder.bufferSize()); } -void WebPreferences::platformUpdateStringValueForKey(const String&, const String&) +bool decodeLegacySessionState(const uint8_t* data, size_t dataSize, SessionState& sessionState) { - notImplemented(); -} - -void WebPreferences::platformUpdateBoolValueForKey(const String&, bool) -{ - notImplemented(); -} - -void WebPreferences::platformUpdateUInt32ValueForKey(const String&, uint32_t) -{ - notImplemented(); -} - -void WebPreferences::platformUpdateDoubleValueForKey(const String&, double) -{ - notImplemented(); -} - -void WebPreferences::platformUpdateFloatValueForKey(const String&, float) -{ - notImplemented(); + IPC::ArgumentDecoder decoder(data, dataSize); + if (!decoder.decode(sessionState.backForwardListState)) + return false; + if (!decoder.decode(sessionState.renderTreeSize)) + return false; + if (!decoder.decode(sessionState.provisionalURL)) + return false; + return true; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h b/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h index 214552570..6600a277f 100644 --- a/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h +++ b/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.h @@ -26,11 +26,9 @@ #ifndef CustomProtocolManagerProxy_h #define CustomProtocolManagerProxy_h -#if ENABLE(CUSTOM_PROTOCOLS) - #include "MessageReceiver.h" -#if PLATFORM(MAC) +#if PLATFORM(COCOA) #include <wtf/HashMap.h> #include <wtf/RetainPtr.h> OBJC_CLASS WKCustomProtocolLoader; @@ -43,21 +41,24 @@ class ResourceRequest; namespace WebKit { class ChildProcessProxy; +class WebProcessPool; -class CustomProtocolManagerProxy : public CoreIPC::MessageReceiver { +class CustomProtocolManagerProxy : public IPC::MessageReceiver { public: - explicit CustomProtocolManagerProxy(ChildProcessProxy*); + CustomProtocolManagerProxy(ChildProcessProxy*, WebProcessPool&); + ~CustomProtocolManagerProxy(); void startLoading(uint64_t customProtocolID, const WebCore::ResourceRequest&); void stopLoading(uint64_t customProtocolID); private: - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; ChildProcessProxy* m_childProcessProxy; + WebProcessPool& m_processPool; -#if PLATFORM(MAC) +#if PLATFORM(COCOA) typedef HashMap<uint64_t, RetainPtr<WKCustomProtocolLoader>> LoaderMap; LoaderMap m_loaderMap; #endif @@ -65,6 +66,4 @@ private: } // namespace WebKit -#endif // ENABLE(CUSTOM_PROTOCOLS) - #endif // CustomProtocolManagerProxy_h diff --git a/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.messages.in b/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.messages.in index 7aef0e0e7..93c0ad435 100644 --- a/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.messages.in +++ b/Source/WebKit2/UIProcess/Network/CustomProtocols/CustomProtocolManagerProxy.messages.in @@ -20,11 +20,7 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#if ENABLE(CUSTOM_PROTOCOLS) - messages -> CustomProtocolManagerProxy { StartLoading(uint64_t customProtocolID, WebCore::ResourceRequest request) StopLoading(uint64_t customProtocolID) } - -#endif // ENABLE(CUSTOM_PROTOCOLS) diff --git a/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm b/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm deleted file mode 100644 index 0582d4802..000000000 --- a/Source/WebKit2/UIProcess/Network/CustomProtocols/mac/CustomProtocolManagerProxyMac.mm +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "CustomProtocolManagerProxy.h" - -#if ENABLE(CUSTOM_PROTOCOLS) - -#import "ChildProcessProxy.h" -#import "Connection.h" -#import "CustomProtocolManagerMessages.h" -#import "CustomProtocolManagerProxyMessages.h" -#import "DataReference.h" -#import "WebCoreArgumentCoders.h" -#import <WebCore/ResourceError.h> -#import <WebCore/ResourceRequest.h> -#import <WebCore/ResourceResponse.h> - -using namespace CoreIPC; -using namespace WebCore; -using namespace WebKit; - -@interface WKCustomProtocolLoader : NSObject <NSURLConnectionDelegate> { -@private - CustomProtocolManagerProxy* _customProtocolManagerProxy; - uint64_t _customProtocolID; - RefPtr<Connection> _connection; - NSURLCacheStoragePolicy _storagePolicy; - NSURLConnection *_urlConnection; -} -- (id)initWithCustomProtocolManagerProxy:(CustomProtocolManagerProxy*)customProtocolManagerProxy customProtocolID:(uint64_t)customProtocolID request:(NSURLRequest *)request connection:(Connection *)connection; -@end - -@implementation WKCustomProtocolLoader - -- (id)initWithCustomProtocolManagerProxy:(CustomProtocolManagerProxy*)customProtocolManagerProxy customProtocolID:(uint64_t)customProtocolID request:(NSURLRequest *)request connection:(Connection *)connection -{ - self = [super init]; - if (!self) - return nil; - - ASSERT(customProtocolManagerProxy); - ASSERT(request); - ASSERT(connection); - _customProtocolManagerProxy = customProtocolManagerProxy; - _customProtocolID = customProtocolID; - _connection = connection; - _storagePolicy = NSURLCacheStorageNotAllowed; - _urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; - - return self; -} - -- (void)dealloc -{ - _connection.clear(); - [_urlConnection cancel]; - [_urlConnection release]; - [super dealloc]; -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error -{ - ResourceError coreError(error); - _connection->send(Messages::CustomProtocolManager::DidFailWithError(_customProtocolID, coreError), 0); - _customProtocolManagerProxy->stopLoading(_customProtocolID); -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse -{ - ASSERT(_storagePolicy == NSURLCacheStorageNotAllowed); - _storagePolicy = [cachedResponse storagePolicy]; - return cachedResponse; -} - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - ResourceResponse coreResponse(response); - _connection->send(Messages::CustomProtocolManager::DidReceiveResponse(_customProtocolID, coreResponse, _storagePolicy), 0); -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - CoreIPC::DataReference coreData(static_cast<const uint8_t*>([data bytes]), [data length]); - _connection->send(Messages::CustomProtocolManager::DidLoadData(_customProtocolID, coreData), 0); -} - -- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse -{ - return request; -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - _connection->send(Messages::CustomProtocolManager::DidFinishLoading(_customProtocolID), 0); - _customProtocolManagerProxy->stopLoading(_customProtocolID); -} - -@end - -namespace WebKit { - -CustomProtocolManagerProxy::CustomProtocolManagerProxy(ChildProcessProxy* childProcessProxy) - : m_childProcessProxy(childProcessProxy) -{ - ASSERT(m_childProcessProxy); - m_childProcessProxy->addMessageReceiver(Messages::CustomProtocolManagerProxy::messageReceiverName(), this); -} - -void CustomProtocolManagerProxy::startLoading(uint64_t customProtocolID, const ResourceRequest& coreRequest) -{ - NSURLRequest *request = coreRequest.nsURLRequest(DoNotUpdateHTTPBody); - if (!request) - return; - - WKCustomProtocolLoader *loader = [[WKCustomProtocolLoader alloc] initWithCustomProtocolManagerProxy:this customProtocolID:customProtocolID request:request connection:m_childProcessProxy->connection()]; - ASSERT(loader); - ASSERT(!m_loaderMap.contains(customProtocolID)); - m_loaderMap.add(customProtocolID, loader); - [loader release]; -} - -void CustomProtocolManagerProxy::stopLoading(uint64_t customProtocolID) -{ - m_loaderMap.remove(customProtocolID); -} - -} // namespace WebKit - -#endif // ENABLE(CUSTOM_PROTOCOLS) diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp index f15bdb442..3fb4855d8 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp @@ -26,81 +26,139 @@ #include "config.h" #include "NetworkProcessProxy.h" -#if ENABLE(NETWORK_PROCESS) - #include "AuthenticationChallengeProxy.h" #include "CustomProtocolManagerProxyMessages.h" #include "DownloadProxyMessages.h" #include "NetworkProcessCreationParameters.h" #include "NetworkProcessMessages.h" -#include "WebContext.h" #include "WebProcessMessages.h" -#include <WebCore/RunLoop.h> +#include "WebProcessPool.h" +#include "WebsiteData.h" +#include <wtf/RunLoop.h> -#if USE(SECURITY_FRAMEWORK) +#if ENABLE(SEC_ITEM_SHIM) #include "SecItemShimProxy.h" #endif +#if PLATFORM(IOS) +#include <wtf/spi/darwin/XPCSPI.h> +#endif + #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection()) using namespace WebCore; namespace WebKit { -PassRefPtr<NetworkProcessProxy> NetworkProcessProxy::create(WebContext* webContext) +static uint64_t generateCallbackID() { - return adoptRef(new NetworkProcessProxy(webContext)); + static uint64_t callbackID; + + return ++callbackID; } -NetworkProcessProxy::NetworkProcessProxy(WebContext* webContext) - : m_webContext(webContext) +Ref<NetworkProcessProxy> NetworkProcessProxy::create(WebProcessPool& processPool) +{ + return adoptRef(*new NetworkProcessProxy(processPool)); +} + +NetworkProcessProxy::NetworkProcessProxy(WebProcessPool& processPool) + : m_processPool(processPool) , m_numPendingConnectionRequests(0) -#if ENABLE(CUSTOM_PROTOCOLS) - , m_customProtocolManagerProxy(this) -#endif + , m_customProtocolManagerProxy(this, processPool) + , m_throttler(*this) { connect(); } NetworkProcessProxy::~NetworkProcessProxy() { + ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty()); } void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) { - launchOptions.processType = ProcessLauncher::NetworkProcess; - platformGetLaunchOptions(launchOptions); + launchOptions.processType = ProcessLauncher::ProcessType::Network; + ChildProcessProxy::getLaunchOptions(launchOptions); } -void NetworkProcessProxy::connectionWillOpen(CoreIPC::Connection* connection) +void NetworkProcessProxy::connectionWillOpen(IPC::Connection& connection) { -#if USE(SECURITY_FRAMEWORK) - SecItemShimProxy::shared().initializeConnection(connection); +#if ENABLE(SEC_ITEM_SHIM) + SecItemShimProxy::singleton().initializeConnection(connection); +#else + UNUSED_PARAM(connection); #endif } -void NetworkProcessProxy::connectionWillClose(CoreIPC::Connection*) +void NetworkProcessProxy::processWillShutDown(IPC::Connection& connection) { + ASSERT_UNUSED(connection, this->connection() == &connection); } void NetworkProcessProxy::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) { m_pendingConnectionReplies.append(reply); - if (isLaunching()) { + if (state() == State::Launching) { m_numPendingConnectionRequests++; return; } - connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); + connection()->send(Messages::NetworkProcess::CreateNetworkConnectionToWebProcess(), 0, IPC::DispatchMessageEvenWhenWaitingForSyncReply); } -DownloadProxy* NetworkProcessProxy::createDownloadProxy() +DownloadProxy* NetworkProcessProxy::createDownloadProxy(const ResourceRequest& resourceRequest) { if (!m_downloadProxyMap) - m_downloadProxyMap = adoptPtr(new DownloadProxyMap(this)); + m_downloadProxyMap = std::make_unique<DownloadProxyMap>(this); + + return m_downloadProxyMap->createDownloadProxy(m_processPool, resourceRequest); +} - return m_downloadProxyMap->createDownloadProxy(m_webContext); +void NetworkProcessProxy::fetchWebsiteData(SessionID sessionID, WebsiteDataTypes dataTypes, std::function<void (WebsiteData)> completionHandler) +{ + ASSERT(canSendMessage()); + + uint64_t callbackID = generateCallbackID(); + auto token = throttler().backgroundActivityToken(); + + m_pendingFetchWebsiteDataCallbacks.add(callbackID, [token, completionHandler](WebsiteData websiteData) { + completionHandler(WTFMove(websiteData)); + }); + + send(Messages::WebProcess::FetchWebsiteData(sessionID, dataTypes, callbackID), 0); +} + +void NetworkProcessProxy::deleteWebsiteData(WebCore::SessionID sessionID, WebsiteDataTypes dataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler) +{ + auto callbackID = generateCallbackID(); + auto token = throttler().backgroundActivityToken(); + + m_pendingDeleteWebsiteDataCallbacks.add(callbackID, [token, completionHandler] { + completionHandler(); + }); + send(Messages::NetworkProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0); +} + +void NetworkProcessProxy::deleteWebsiteDataForOrigins(SessionID sessionID, WebsiteDataTypes dataTypes, const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, const Vector<String>& cookieHostNames, std::function<void ()> completionHandler) +{ + ASSERT(canSendMessage()); + + uint64_t callbackID = generateCallbackID(); + auto token = throttler().backgroundActivityToken(); + + m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, [token, completionHandler] { + completionHandler(); + }); + + Vector<SecurityOriginData> originData; + for (auto& origin : origins) + originData.append(SecurityOriginData::fromSecurityOrigin(*origin)); + + send(Messages::NetworkProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, originData, cookieHostNames, callbackID), 0); } void NetworkProcessProxy::networkProcessCrashedOrFailedToLaunch() @@ -109,29 +167,43 @@ void NetworkProcessProxy::networkProcessCrashedOrFailedToLaunch() while (!m_pendingConnectionReplies.isEmpty()) { RefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); -#if PLATFORM(MAC) - reply->send(CoreIPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND)); +#if USE(UNIX_DOMAIN_SOCKETS) + reply->send(IPC::Attachment()); +#elif OS(DARWIN) + reply->send(IPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND)); #else notImplemented(); #endif } + for (const auto& callback : m_pendingFetchWebsiteDataCallbacks.values()) + callback(WebsiteData()); + m_pendingFetchWebsiteDataCallbacks.clear(); + + for (const auto& callback : m_pendingDeleteWebsiteDataCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataCallbacks.clear(); + + for (const auto& callback : m_pendingDeleteWebsiteDataForOriginsCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataForOriginsCallbacks.clear(); + // Tell the network process manager to forget about this network process proxy. This may cause us to be deleted. - m_webContext->networkProcessCrashed(this); + m_processPool.networkProcessCrashed(this); } -void NetworkProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) +void NetworkProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) { if (dispatchMessage(connection, decoder)) return; - if (m_webContext->dispatchMessage(connection, decoder)) + if (m_processPool.dispatchMessage(connection, decoder)) return; didReceiveNetworkProcessProxyMessage(connection, decoder); } -void NetworkProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) +void NetworkProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) { if (dispatchSyncMessage(connection, decoder, replyEncoder)) return; @@ -139,28 +211,32 @@ void NetworkProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, ASSERT_NOT_REACHED(); } -void NetworkProcessProxy::didClose(CoreIPC::Connection*) +void NetworkProcessProxy::didClose(IPC::Connection&) { if (m_downloadProxyMap) m_downloadProxyMap->processDidClose(); + m_tokenForHoldingLockedFiles = nullptr; + // This may cause us to be deleted. networkProcessCrashedOrFailedToLaunch(); } -void NetworkProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference, CoreIPC::StringReference) +void NetworkProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference) { } -void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const CoreIPC::Attachment& connectionIdentifier) +void NetworkProcessProxy::didCreateNetworkConnectionToWebProcess(const IPC::Attachment& connectionIdentifier) { ASSERT(!m_pendingConnectionReplies.isEmpty()); // Grab the first pending connection reply. RefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); -#if PLATFORM(MAC) - reply->send(CoreIPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND)); +#if USE(UNIX_DOMAIN_SOCKETS) + reply->send(connectionIdentifier); +#elif OS(DARWIN) + reply->send(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND)); #else notImplemented(); #endif @@ -175,11 +251,29 @@ void NetworkProcessProxy::didReceiveAuthenticationChallenge(uint64_t pageID, uin page->didReceiveAuthenticationChallengeProxy(frameID, authenticationChallenge.release()); } -void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC::Connection::Identifier connectionIdentifier) +void NetworkProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData) +{ + auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID); + callback(websiteData); +} + +void NetworkProcessProxy::didDeleteWebsiteData(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID); + callback(); +} + +void NetworkProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID); + callback(); +} + +void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connection::Identifier connectionIdentifier) { ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier); - if (CoreIPC::Connection::identifierIsNull(connectionIdentifier)) { + if (IPC::Connection::identifierIsNull(connectionIdentifier)) { // FIXME: Do better cleanup here. return; } @@ -189,12 +283,94 @@ void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC: m_numPendingConnectionRequests = 0; -#if PLATFORM(MAC) - if (m_webContext->canEnableProcessSuppressionForNetworkProcess()) +#if PLATFORM(COCOA) + if (m_processPool.processSuppressionEnabled()) setProcessSuppressionEnabled(true); #endif + +#if PLATFORM(IOS) + if (xpc_connection_t connection = this->connection()->xpcConnection()) + m_throttler.didConnectToProcess(xpc_connection_get_pid(connection)); +#endif } -} // namespace WebKit +void NetworkProcessProxy::logSampledDiagnosticMessage(uint64_t pageID, const String& message, const String& description) +{ + WebPageProxy* page = WebProcessProxy::webPage(pageID); + // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this, + // but for now we simply drop the message in the rare case this happens. + if (!page) + return; + + page->logSampledDiagnosticMessage(message, description); +} + +void NetworkProcessProxy::logSampledDiagnosticMessageWithResult(uint64_t pageID, const String& message, const String& description, uint32_t result) +{ + WebPageProxy* page = WebProcessProxy::webPage(pageID); + // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this, + // but for now we simply drop the message in the rare case this happens. + if (!page) + return; + + page->logSampledDiagnosticMessageWithResult(message, description, result); +} + +void NetworkProcessProxy::logSampledDiagnosticMessageWithValue(uint64_t pageID, const String& message, const String& description, const String& value) +{ + WebPageProxy* page = WebProcessProxy::webPage(pageID); + // FIXME: We do this null-check because by the time the decision to log is made, the page may be gone. We should refactor to avoid this, + // but for now we simply drop the message in the rare case this happens. + if (!page) + return; + + page->logSampledDiagnosticMessageWithValue(message, description, value); +} + +void NetworkProcessProxy::sendProcessWillSuspendImminently() +{ + if (!canSendMessage()) + return; + + bool handled = false; + sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, std::chrono::seconds(1)); +} + +void NetworkProcessProxy::sendPrepareToSuspend() +{ + if (canSendMessage()) + send(Messages::NetworkProcess::PrepareToSuspend(), 0); +} + +void NetworkProcessProxy::sendCancelPrepareToSuspend() +{ + if (canSendMessage()) + send(Messages::NetworkProcess::CancelPrepareToSuspend(), 0); +} -#endif // ENABLE(NETWORK_PROCESS) +void NetworkProcessProxy::sendProcessDidResume() +{ + if (canSendMessage()) + send(Messages::NetworkProcess::ProcessDidResume(), 0); +} + +void NetworkProcessProxy::processReadyToSuspend() +{ + m_throttler.processReadyToSuspend(); +} + +void NetworkProcessProxy::didSetAssertionState(AssertionState) +{ +} + +void NetworkProcessProxy::setIsHoldingLockedFiles(bool isHoldingLockedFiles) +{ + if (!isHoldingLockedFiles) { + m_tokenForHoldingLockedFiles = nullptr; + return; + } + if (!m_tokenForHoldingLockedFiles) + m_tokenForHoldingLockedFiles = m_throttler.backgroundActivityToken(); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h index 2cc9e8840..b2414e141 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h +++ b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.h @@ -26,80 +26,107 @@ #ifndef NetworkProcessProxy_h #define NetworkProcessProxy_h -#if ENABLE(NETWORK_PROCESS) - #include "ChildProcessProxy.h" +#include "CustomProtocolManagerProxy.h" #include "ProcessLauncher.h" +#include "ProcessThrottler.h" +#include "ProcessThrottlerClient.h" #include "WebProcessProxyMessages.h" +#include "WebsiteDataTypes.h" +#include <memory> #include <wtf/Deque.h> -#if ENABLE(CUSTOM_PROTOCOLS) -#include "CustomProtocolManagerProxy.h" -#endif - namespace WebCore { class AuthenticationChallenge; +class ResourceRequest; +class SecurityOrigin; +class SessionID; } namespace WebKit { class DownloadProxy; class DownloadProxyMap; -class WebContext; +class WebProcessPool; struct NetworkProcessCreationParameters; -class NetworkProcessProxy : public ChildProcessProxy { +class NetworkProcessProxy : public ChildProcessProxy, private ProcessThrottlerClient { public: - static PassRefPtr<NetworkProcessProxy> create(WebContext*); + static Ref<NetworkProcessProxy> create(WebProcessPool&); ~NetworkProcessProxy(); void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); - DownloadProxy* createDownloadProxy(); + DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&); + + void fetchWebsiteData(WebCore::SessionID, WebsiteDataTypes, std::function<void (WebsiteData)> completionHandler); + void deleteWebsiteData(WebCore::SessionID, WebsiteDataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler); + void deleteWebsiteDataForOrigins(WebCore::SessionID, WebsiteDataTypes, const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, const Vector<String>& cookieHostNames, std::function<void ()> completionHandler); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void setProcessSuppressionEnabled(bool); #endif + void processReadyToSuspend(); + + void setIsHoldingLockedFiles(bool); + + ProcessThrottler& throttler() { return m_throttler; } + private: - NetworkProcessProxy(WebContext*); + NetworkProcessProxy(WebProcessPool&); // ChildProcessProxy - virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) OVERRIDE; - virtual void connectionWillOpen(CoreIPC::Connection*) OVERRIDE; - virtual void connectionWillClose(CoreIPC::Connection*) OVERRIDE; + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) override; + virtual void connectionWillOpen(IPC::Connection&) override; + virtual void processWillShutDown(IPC::Connection&) override; - void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&); void networkProcessCrashedOrFailedToLaunch(); - // CoreIPC::Connection::Client - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; - virtual void didClose(CoreIPC::Connection*) OVERRIDE; - virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) OVERRIDE; + // ProcessThrottlerClient + void sendProcessWillSuspendImminently() override; + void sendPrepareToSuspend() override; + void sendCancelPrepareToSuspend() override; + void sendProcessDidResume() override; + void didSetAssertionState(AssertionState) override; + + // IPC::Connection::Client + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; + virtual void didClose(IPC::Connection&) override; + virtual void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override; + virtual IPC::ProcessType localProcessType() override { return IPC::ProcessType::UI; } + virtual IPC::ProcessType remoteProcessType() override { return IPC::ProcessType::Network; } // Message handlers - void didReceiveNetworkProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - void didCreateNetworkConnectionToWebProcess(const CoreIPC::Attachment&); + void didReceiveNetworkProcessProxyMessage(IPC::Connection&, IPC::MessageDecoder&); + void didCreateNetworkConnectionToWebProcess(const IPC::Attachment&); void didReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, const WebCore::AuthenticationChallenge&, uint64_t challengeID); + void didFetchWebsiteData(uint64_t callbackID, const WebsiteData&); + void didDeleteWebsiteData(uint64_t callbackID); + void didDeleteWebsiteDataForOrigins(uint64_t callbackID); + void logSampledDiagnosticMessage(uint64_t pageID, const String& message, const String& description); + void logSampledDiagnosticMessageWithResult(uint64_t pageID, const String& message, const String& description, uint32_t result); + void logSampledDiagnosticMessageWithValue(uint64_t pageID, const String& message, const String& description, const String& value); // ProcessLauncher::Client - virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); + virtual void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override; - WebContext* m_webContext; + WebProcessPool& m_processPool; unsigned m_numPendingConnectionRequests; Deque<RefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>> m_pendingConnectionReplies; - OwnPtr<DownloadProxyMap> m_downloadProxyMap; + HashMap<uint64_t, std::function<void (WebsiteData)>> m_pendingFetchWebsiteDataCallbacks; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataCallbacks; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataForOriginsCallbacks; -#if ENABLE(CUSTOM_PROTOCOLS) + std::unique_ptr<DownloadProxyMap> m_downloadProxyMap; CustomProtocolManagerProxy m_customProtocolManagerProxy; -#endif + ProcessThrottler m_throttler; + ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles; }; } // namespace WebKit -#endif // ENABLE(NETWORK_PROCESS) - #endif // NetworkProcessProxy_h diff --git a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in index 7e91c384e..dc93b8481 100644 --- a/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.messages.in @@ -20,12 +20,20 @@ # 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 ENABLE(NETWORK_PROCESS) - messages -> NetworkProcessProxy LegacyReceiver { - DidCreateNetworkConnectionToWebProcess(CoreIPC::Attachment connectionIdentifier) + DidCreateNetworkConnectionToWebProcess(IPC::Attachment connectionIdentifier) DidReceiveAuthenticationChallenge(uint64_t pageID, uint64_t frameID, WebCore::AuthenticationChallenge challenge, uint64_t challengeID) -} -#endif // ENABLE(NETWORK_PROCESS) + DidFetchWebsiteData(uint64_t callbackID, struct WebKit::WebsiteData websiteData) + DidDeleteWebsiteData(uint64_t callbackID) + DidDeleteWebsiteDataForOrigins(uint64_t callbackID) + + ProcessReadyToSuspend() + SetIsHoldingLockedFiles(bool isHoldingLockedFiles) + + # Diagnostic messages logging + LogSampledDiagnosticMessage(uint64_t pageID, String message, String description) + LogSampledDiagnosticMessageWithResult(uint64_t pageID, String message, String description, uint32_t result) + LogSampledDiagnosticMessageWithValue(uint64_t pageID, String message, String description, String value) +} diff --git a/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm b/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm deleted file mode 100644 index 1d1ff1ccf..000000000 --- a/Source/WebKit2/UIProcess/Network/mac/NetworkProcessProxyMac.mm +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "NetworkProcessProxy.h" - -#import "NetworkProcessMessages.h" - -#if ENABLE(NETWORK_PROCESS) - -using namespace WebCore; - -namespace WebKit { - -void NetworkProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled) -{ - if (!isValid()) - return; - - connection()->send(Messages::NetworkProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0); -} - -#if HAVE(XPC) -static bool shouldUseXPC() -{ - if (id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseXPCServiceForWebProcess"]) - return [value boolValue]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - return true; -#else - return false; -#endif -} -#endif - -void NetworkProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) -{ - launchOptions.architecture = ProcessLauncher::LaunchOptions::MatchCurrentArchitecture; - launchOptions.executableHeap = false; - -#if HAVE(XPC) - launchOptions.useXPC = shouldUseXPC(); -#endif -} - -} // namespace WebKit - -#endif // ENABLE(NETWORK_PROCESS) diff --git a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.cpp b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.cpp index 25d37da4b..2128627c5 100644 --- a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.cpp +++ b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.cpp @@ -30,9 +30,9 @@ namespace WebKit { -PassRefPtr<NotificationPermissionRequest> NotificationPermissionRequest::create(WebKit::NotificationPermissionRequestManagerProxy *manager, uint64_t notificationID) +Ref<NotificationPermissionRequest> NotificationPermissionRequest::create(WebKit::NotificationPermissionRequestManagerProxy *manager, uint64_t notificationID) { - return adoptRef(new NotificationPermissionRequest(manager, notificationID)); + return adoptRef(*new NotificationPermissionRequest(manager, notificationID)); } NotificationPermissionRequest::NotificationPermissionRequest(NotificationPermissionRequestManagerProxy* manager, uint64_t notificationID) diff --git a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h index 2576a7a6f..e04840659 100644 --- a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h +++ b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequest.h @@ -33,9 +33,9 @@ namespace WebKit { class NotificationPermissionRequestManagerProxy; -class NotificationPermissionRequest : public TypedAPIObject<APIObject::TypeNotificationPermissionRequest> { +class NotificationPermissionRequest : public API::ObjectImpl<API::Object::Type::NotificationPermissionRequest> { public: - static PassRefPtr<NotificationPermissionRequest> create(NotificationPermissionRequestManagerProxy*, uint64_t notificationID); + static Ref<NotificationPermissionRequest> create(NotificationPermissionRequestManagerProxy*, uint64_t notificationID); void allow(); void deny(); diff --git a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.cpp b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.cpp index 4a0c47529..0b2a63297 100644 --- a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.cpp @@ -33,18 +33,16 @@ namespace WebKit { -NotificationPermissionRequestManagerProxy::NotificationPermissionRequestManagerProxy(WebPageProxy* page) +NotificationPermissionRequestManagerProxy::NotificationPermissionRequestManagerProxy(WebPageProxy& page) : m_page(page) { } void NotificationPermissionRequestManagerProxy::invalidateRequests() { - PendingRequestMap::const_iterator it = m_pendingRequests.begin(); - PendingRequestMap::const_iterator end = m_pendingRequests.end(); - for (; it != end; ++it) - it->value->invalidate(); - + for (auto& request : m_pendingRequests.values()) + request->invalidate(); + m_pendingRequests.clear(); } @@ -57,14 +55,14 @@ PassRefPtr<NotificationPermissionRequest> NotificationPermissionRequestManagerPr void NotificationPermissionRequestManagerProxy::didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allow) { - if (!m_page->isValid()) + if (!m_page.isValid()) return; RefPtr<NotificationPermissionRequest> request = m_pendingRequests.take(notificationID); if (!request) return; - m_page->process()->send(Messages::WebPage::DidReceiveNotificationPermissionDecision(notificationID, allow), m_page->pageID()); + m_page.process().send(Messages::WebPage::DidReceiveNotificationPermissionDecision(notificationID, allow), m_page.pageID()); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h index 12775fb06..5bc83f6f5 100644 --- a/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h +++ b/Source/WebKit2/UIProcess/Notifications/NotificationPermissionRequestManagerProxy.h @@ -36,7 +36,7 @@ class WebPageProxy; class NotificationPermissionRequestManagerProxy { public: - explicit NotificationPermissionRequestManagerProxy(WebPageProxy*); + explicit NotificationPermissionRequestManagerProxy(WebPageProxy&); void invalidateRequests(); @@ -47,12 +47,10 @@ public: void didReceiveNotificationPermissionDecision(uint64_t notificationID, bool allow); private: - typedef HashMap<uint64_t, RefPtr<NotificationPermissionRequest> > PendingRequestMap; - PendingRequestMap m_pendingRequests; - WebPageProxy* m_page; + HashMap<uint64_t, RefPtr<NotificationPermissionRequest>> m_pendingRequests; + WebPageProxy& m_page; }; } // namespace WebKit - #endif // NotificationPermissionRequestManagerProxy_h diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotification.cpp b/Source/WebKit2/UIProcess/Notifications/WebNotification.cpp index 3705fb064..3d7bc00fe 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotification.cpp +++ b/Source/WebKit2/UIProcess/Notifications/WebNotification.cpp @@ -40,7 +40,7 @@ WebNotification::WebNotification(const String& title, const String& body, const , m_tag(tag) , m_lang(lang) , m_dir(dir) - , m_origin(WebSecurityOrigin::createFromString(originString)) + , m_origin(API::SecurityOrigin::createFromString(originString)) , m_notificationID(notificationID) { } diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotification.h b/Source/WebKit2/UIProcess/Notifications/WebNotification.h index 14e905c53..5fd3da718 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotification.h +++ b/Source/WebKit2/UIProcess/Notifications/WebNotification.h @@ -27,25 +27,25 @@ #define WebNotification_h #include "APIObject.h" -#include "WebSecurityOrigin.h" +#include "APISecurityOrigin.h" #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/text/WTFString.h> -namespace CoreIPC { +namespace IPC { class ArgumentDecoder; class ArgumentEncoder; -} // namespace CoreIPC +} // namespace IPC namespace WebKit { -class WebNotification : public TypedAPIObject<APIObject::TypeNotification> { +class WebNotification : public API::ObjectImpl<API::Object::Type::Notification> { public: - static PassRefPtr<WebNotification> create(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID) + static Ref<WebNotification> create(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID) { - return adoptRef(new WebNotification(title, body, iconURL, tag, lang, dir, originString, notificationID)); + return adoptRef(*new WebNotification(title, body, iconURL, tag, lang, dir, originString, notificationID)); } const String& title() const { return m_title; } @@ -54,7 +54,7 @@ public: const String& tag() const { return m_tag; } const String& lang() const { return m_lang; } const String& dir() const { return m_dir; } - WebSecurityOrigin* origin() const { return m_origin.get(); } + API::SecurityOrigin* origin() const { return m_origin.get(); } uint64_t notificationID() const { return m_notificationID; } @@ -67,7 +67,7 @@ private: String m_tag; String m_lang; String m_dir; - RefPtr<WebSecurityOrigin> m_origin; + RefPtr<API::SecurityOrigin> m_origin; uint64_t m_notificationID; }; diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp index 5bb3db5f7..626351687 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.cpp @@ -26,17 +26,15 @@ #include "config.h" #include "WebNotificationManagerProxy.h" -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "WebContext.h" +#include "APIArray.h" +#include "APIDictionary.h" +#include "APISecurityOrigin.h" #include "WebNotification.h" #include "WebNotificationManagerMessages.h" #include "WebPageProxy.h" +#include "WebProcessPool.h" #include "WebProcessProxy.h" -#include "WebSecurityOrigin.h" -using namespace std; -using namespace WTF; using namespace WebCore; namespace WebKit { @@ -52,17 +50,17 @@ const char* WebNotificationManagerProxy::supplementName() return "WebNotificationManagerProxy"; } -PassRefPtr<WebNotificationManagerProxy> WebNotificationManagerProxy::create(WebContext* context) +Ref<WebNotificationManagerProxy> WebNotificationManagerProxy::create(WebProcessPool* processPool) { - return adoptRef(new WebNotificationManagerProxy(context)); + return adoptRef(*new WebNotificationManagerProxy(processPool)); } -WebNotificationManagerProxy::WebNotificationManagerProxy(WebContext* context) - : WebContextSupplement(context) +WebNotificationManagerProxy::WebNotificationManagerProxy(WebProcessPool* processPool) + : WebContextSupplement(processPool) { } -void WebNotificationManagerProxy::initializeProvider(const WKNotificationProvider *provider) +void WebNotificationManagerProxy::initializeProvider(const WKNotificationProviderBase* provider) { m_provider.initialize(provider); m_provider.addNotificationManager(this); @@ -70,33 +68,33 @@ void WebNotificationManagerProxy::initializeProvider(const WKNotificationProvide // WebContextSupplement -void WebNotificationManagerProxy::contextDestroyed() +void WebNotificationManagerProxy::processPoolDestroyed() { m_provider.removeNotificationManager(this); } void WebNotificationManagerProxy::refWebContextSupplement() { - APIObject::ref(); + API::Object::ref(); } void WebNotificationManagerProxy::derefWebContextSupplement() { - APIObject::deref(); + API::Object::deref(); } void WebNotificationManagerProxy::populateCopyOfNotificationPermissions(HashMap<String, bool>& permissions) { - RefPtr<ImmutableDictionary> knownPermissions = m_provider.notificationPermissions(); + RefPtr<API::Dictionary> knownPermissions = m_provider.notificationPermissions(); if (!knownPermissions) return; permissions.clear(); - RefPtr<ImmutableArray> knownOrigins = knownPermissions->keys(); + Ref<API::Array> knownOrigins = knownPermissions->keys(); for (size_t i = 0; i < knownOrigins->size(); ++i) { - WebString* origin = knownOrigins->at<WebString>(i); - permissions.set(origin->string(), knownPermissions->get<WebBoolean>(origin->string())->value()); + API::String* origin = knownOrigins->at<API::String>(i); + permissions.set(origin->string(), knownPermissions->get<API::Boolean>(origin->string())->value()); } } @@ -104,21 +102,21 @@ void WebNotificationManagerProxy::show(WebPageProxy* webPage, const String& titl { uint64_t globalNotificationID = generateGlobalNotificationID(); RefPtr<WebNotification> notification = WebNotification::create(title, body, iconURL, tag, lang, dir, originString, globalNotificationID); - pair<uint64_t, uint64_t> notificationIDPair = make_pair(webPage->pageID(), pageNotificationID); + std::pair<uint64_t, uint64_t> notificationIDPair = std::make_pair(webPage->pageID(), pageNotificationID); m_globalNotificationMap.set(globalNotificationID, notificationIDPair); - m_notifications.set(notificationIDPair, make_pair(globalNotificationID, notification)); + m_notifications.set(notificationIDPair, std::make_pair(globalNotificationID, notification)); m_provider.show(webPage, notification.get()); } void WebNotificationManagerProxy::cancel(WebPageProxy* webPage, uint64_t pageNotificationID) { - if (WebNotification* notification = m_notifications.get(make_pair(webPage->pageID(), pageNotificationID)).second.get()) + if (WebNotification* notification = m_notifications.get(std::make_pair(webPage->pageID(), pageNotificationID)).second.get()) m_provider.cancel(notification); } void WebNotificationManagerProxy::didDestroyNotification(WebPageProxy* webPage, uint64_t pageNotificationID) { - pair<uint64_t, RefPtr<WebNotification> > globalIDNotificationPair = m_notifications.take(make_pair(webPage->pageID(), pageNotificationID)); + auto globalIDNotificationPair = m_notifications.take(std::make_pair(webPage->pageID(), pageNotificationID)); if (uint64_t globalNotificationID = globalIDNotificationPair.first) { WebNotification* notification = globalIDNotificationPair.second.get(); m_globalNotificationMap.remove(globalNotificationID); @@ -153,28 +151,19 @@ void WebNotificationManagerProxy::clearNotifications(WebPageProxy* webPage, cons Vector<uint64_t> globalNotificationIDs; globalNotificationIDs.reserveCapacity(m_globalNotificationMap.size()); - { - HashMap<pair<uint64_t, uint64_t>, pair<uint64_t, RefPtr<WebNotification> > >::iterator it = m_notifications.begin(); - HashMap<pair<uint64_t, uint64_t>, pair<uint64_t, RefPtr<WebNotification> > >::iterator end = m_notifications.end(); - for (; it != end; ++it) { - uint64_t webPageID = it->key.first; - uint64_t pageNotificationID = it->key.second; - if (!filterFunction(webPageID, pageNotificationID, targetPageID, pageNotificationIDs)) - continue; - - uint64_t globalNotificationID = it->value.first; - globalNotificationIDs.append(globalNotificationID); - } - } + for (auto it = m_notifications.begin(), end = m_notifications.end(); it != end; ++it) { + uint64_t webPageID = it->key.first; + uint64_t pageNotificationID = it->key.second; + if (!filterFunction(webPageID, pageNotificationID, targetPageID, pageNotificationIDs)) + continue; + uint64_t globalNotificationID = it->value.first; + globalNotificationIDs.append(globalNotificationID); + } - { - Vector<uint64_t>::iterator it = globalNotificationIDs.begin(); - Vector<uint64_t>::iterator end = globalNotificationIDs.end(); - for (; it != end; ++it) { - pair<uint64_t, uint64_t> pageNotification = m_globalNotificationMap.take(*it); - m_notifications.remove(pageNotification); - } + for (auto it = globalNotificationIDs.begin(), end = globalNotificationIDs.end(); it != end; ++it) { + auto pageNotification = m_globalNotificationMap.take(*it); + m_notifications.remove(pageNotification); } m_provider.clearNotifications(globalNotificationIDs); @@ -182,7 +171,7 @@ void WebNotificationManagerProxy::clearNotifications(WebPageProxy* webPage, cons void WebNotificationManagerProxy::providerDidShowNotification(uint64_t globalNotificationID) { - HashMap<uint64_t, pair<uint64_t, uint64_t> >::iterator it = m_globalNotificationMap.find(globalNotificationID); + auto it = m_globalNotificationMap.find(globalNotificationID); if (it == m_globalNotificationMap.end()) return; @@ -192,12 +181,12 @@ void WebNotificationManagerProxy::providerDidShowNotification(uint64_t globalNot return; uint64_t pageNotificationID = it->value.second; - webPage->process()->send(Messages::WebNotificationManager::DidShowNotification(pageNotificationID), 0); + webPage->process().send(Messages::WebNotificationManager::DidShowNotification(pageNotificationID), 0); } void WebNotificationManagerProxy::providerDidClickNotification(uint64_t globalNotificationID) { - HashMap<uint64_t, pair<uint64_t, uint64_t> >::iterator it = m_globalNotificationMap.find(globalNotificationID); + auto it = m_globalNotificationMap.find(globalNotificationID); if (it == m_globalNotificationMap.end()) return; @@ -207,26 +196,26 @@ void WebNotificationManagerProxy::providerDidClickNotification(uint64_t globalNo return; uint64_t pageNotificationID = it->value.second; - webPage->process()->send(Messages::WebNotificationManager::DidClickNotification(pageNotificationID), 0); + webPage->process().send(Messages::WebNotificationManager::DidClickNotification(pageNotificationID), 0); } -void WebNotificationManagerProxy::providerDidCloseNotifications(ImmutableArray* globalNotificationIDs) +void WebNotificationManagerProxy::providerDidCloseNotifications(API::Array* globalNotificationIDs) { - HashMap<WebPageProxy*, Vector<uint64_t> > pageNotificationIDs; + HashMap<WebPageProxy*, Vector<uint64_t>> pageNotificationIDs; size_t size = globalNotificationIDs->size(); for (size_t i = 0; i < size; ++i) { - HashMap<uint64_t, pair<uint64_t, uint64_t> >::iterator it = m_globalNotificationMap.find(globalNotificationIDs->at<WebUInt64>(i)->value()); + auto it = m_globalNotificationMap.find(globalNotificationIDs->at<API::UInt64>(i)->value()); if (it == m_globalNotificationMap.end()) continue; if (WebPageProxy* webPage = WebProcessProxy::webPage(it->value.first)) { - HashMap<WebPageProxy*, Vector<uint64_t> >::iterator pageIt = pageNotificationIDs.find(webPage); + auto pageIt = pageNotificationIDs.find(webPage); if (pageIt == pageNotificationIDs.end()) { Vector<uint64_t> newVector; newVector.reserveInitialCapacity(size); - pageIt = pageNotificationIDs.add(webPage, newVector).iterator; + pageIt = pageNotificationIDs.add(webPage, WTFMove(newVector)).iterator; } uint64_t pageNotificationID = it->value.second; @@ -237,21 +226,21 @@ void WebNotificationManagerProxy::providerDidCloseNotifications(ImmutableArray* m_globalNotificationMap.remove(it); } - for (HashMap<WebPageProxy*, Vector<uint64_t> >::iterator it = pageNotificationIDs.begin(), end = pageNotificationIDs.end(); it != end; ++it) - it->key->process()->send(Messages::WebNotificationManager::DidCloseNotifications(it->value), 0); + for (auto it = pageNotificationIDs.begin(), end = pageNotificationIDs.end(); it != end; ++it) + it->key->process().send(Messages::WebNotificationManager::DidCloseNotifications(it->value), 0); } -void WebNotificationManagerProxy::providerDidUpdateNotificationPolicy(const WebSecurityOrigin* origin, bool allowed) +void WebNotificationManagerProxy::providerDidUpdateNotificationPolicy(const API::SecurityOrigin* origin, bool allowed) { - if (!context()) + if (!processPool()) return; - context()->sendToAllProcesses(Messages::WebNotificationManager::DidUpdateNotificationDecision(origin->toString(), allowed)); + processPool()->sendToAllProcesses(Messages::WebNotificationManager::DidUpdateNotificationDecision(origin->securityOrigin().toString(), allowed)); } -void WebNotificationManagerProxy::providerDidRemoveNotificationPolicies(ImmutableArray* origins) +void WebNotificationManagerProxy::providerDidRemoveNotificationPolicies(API::Array* origins) { - if (!context()) + if (!processPool()) return; size_t size = origins->size(); @@ -262,9 +251,9 @@ void WebNotificationManagerProxy::providerDidRemoveNotificationPolicies(Immutabl originStrings.reserveInitialCapacity(size); for (size_t i = 0; i < size; ++i) - originStrings.append(origins->at<WebSecurityOrigin>(i)->toString()); + originStrings.append(origins->at<API::SecurityOrigin>(i)->securityOrigin().toString()); - context()->sendToAllProcesses(Messages::WebNotificationManager::DidRemoveNotificationDecisions(originStrings)); + processPool()->sendToAllProcesses(Messages::WebNotificationManager::DidRemoveNotificationDecisions(originStrings)); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h index 98b472e82..02a2269e5 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h +++ b/Source/WebKit2/UIProcess/Notifications/WebNotificationManagerProxy.h @@ -32,25 +32,27 @@ #include "WebNotificationProvider.h" #include <WebCore/NotificationClient.h> #include <wtf/HashMap.h> -#include <wtf/OwnPtr.h> #include <wtf/PassRefPtr.h> #include <wtf/text/StringHash.h> +namespace API { +class Array; +class SecurityOrigin; +} + namespace WebKit { -class ImmutableArray; -class WebContext; class WebPageProxy; -class WebSecurityOrigin; +class WebProcessPool; -class WebNotificationManagerProxy : public TypedAPIObject<APIObject::TypeNotificationManager>, public WebContextSupplement { +class WebNotificationManagerProxy : public API::ObjectImpl<API::Object::Type::NotificationManager>, public WebContextSupplement { public: static const char* supplementName(); - static PassRefPtr<WebNotificationManagerProxy> create(WebContext*); + static Ref<WebNotificationManagerProxy> create(WebProcessPool*); - void initializeProvider(const WKNotificationProvider*); + void initializeProvider(const WKNotificationProviderBase*); void populateCopyOfNotificationPermissions(HashMap<String, bool>&); void show(WebPageProxy*, const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t pageNotificationID); @@ -61,29 +63,29 @@ public: void providerDidShowNotification(uint64_t notificationID); void providerDidClickNotification(uint64_t notificationID); - void providerDidCloseNotifications(ImmutableArray* notificationIDs); - void providerDidUpdateNotificationPolicy(const WebSecurityOrigin*, bool allowed); - void providerDidRemoveNotificationPolicies(ImmutableArray* origins); + void providerDidCloseNotifications(API::Array* notificationIDs); + void providerDidUpdateNotificationPolicy(const API::SecurityOrigin*, bool allowed); + void providerDidRemoveNotificationPolicies(API::Array* origins); - using APIObject::ref; - using APIObject::deref; + using API::Object::ref; + using API::Object::deref; private: - explicit WebNotificationManagerProxy(WebContext*); + explicit WebNotificationManagerProxy(WebProcessPool*); typedef bool (*NotificationFilterFunction)(uint64_t pageID, uint64_t pageNotificationID, uint64_t desiredPageID, const Vector<uint64_t>& desiredPageNotificationIDs); void clearNotifications(WebPageProxy*, const Vector<uint64_t>& pageNotificationIDs, NotificationFilterFunction); // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; + virtual void processPoolDestroyed() override; + virtual void refWebContextSupplement() override; + virtual void derefWebContextSupplement() override; WebNotificationProvider m_provider; // Pair comprised of web page ID and the web process's notification ID - HashMap<uint64_t, pair<uint64_t, uint64_t> > m_globalNotificationMap; + HashMap<uint64_t, std::pair<uint64_t, uint64_t>> m_globalNotificationMap; // Key pair comprised of web page ID and the web process's notification ID; value pair comprised of global notification ID, and notification object - HashMap<pair<uint64_t, uint64_t>, pair<uint64_t, RefPtr<WebNotification> > > m_notifications; + HashMap<std::pair<uint64_t, uint64_t>, std::pair<uint64_t, RefPtr<WebNotification>>> m_notifications; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.cpp b/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.cpp index 133e79aaa..a2a83ada0 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.cpp +++ b/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.cpp @@ -26,13 +26,14 @@ #include "config.h" #include "WebNotificationProvider.h" -#include "ImmutableDictionary.h" -#include "MutableArray.h" +#include "APIArray.h" +#include "APIDictionary.h" +#include "APINumber.h" +#include "APISecurityOrigin.h" #include "WKAPICast.h" #include "WebNotification.h" #include "WebNotificationManagerProxy.h" -#include "WebNumber.h" -#include "WebSecurityOrigin.h" +#include "WebPageProxy.h" namespace WebKit { @@ -41,7 +42,7 @@ void WebNotificationProvider::show(WebPageProxy* page, WebNotification* notifica if (!m_client.show) return; - m_client.show(toAPI(page), toAPI(notification), m_client.clientInfo); + m_client.show(toAPI(page), toAPI(notification), m_client.base.clientInfo); } void WebNotificationProvider::cancel(WebNotification* notification) @@ -49,7 +50,7 @@ void WebNotificationProvider::cancel(WebNotification* notification) if (!m_client.cancel) return; - m_client.cancel(toAPI(notification), m_client.clientInfo); + m_client.cancel(toAPI(notification), m_client.base.clientInfo); } void WebNotificationProvider::didDestroyNotification(WebNotification* notification) @@ -57,7 +58,7 @@ void WebNotificationProvider::didDestroyNotification(WebNotification* notificati if (!m_client.didDestroyNotification) return; - m_client.didDestroyNotification(toAPI(notification), m_client.clientInfo); + m_client.didDestroyNotification(toAPI(notification), m_client.base.clientInfo); } void WebNotificationProvider::clearNotifications(const Vector<uint64_t>& notificationIDs) @@ -65,13 +66,13 @@ void WebNotificationProvider::clearNotifications(const Vector<uint64_t>& notific if (!m_client.clearNotifications) return; - RefPtr<MutableArray> arrayIDs = MutableArray::create(); - size_t count = notificationIDs.size(); - arrayIDs->reserveCapacity(count); - for (size_t i = 0; i < count; ++i) - arrayIDs->append(WebUInt64::create(notificationIDs[i]).leakRef()); + Vector<RefPtr<API::Object>> arrayIDs; + arrayIDs.reserveInitialCapacity(notificationIDs.size()); - m_client.clearNotifications(toAPI(arrayIDs.get()), m_client.clientInfo); + for (const auto& notificationID : notificationIDs) + arrayIDs.uncheckedAppend(API::UInt64::create(notificationID)); + + m_client.clearNotifications(toAPI(API::Array::create(WTFMove(arrayIDs)).ptr()), m_client.base.clientInfo); } void WebNotificationProvider::addNotificationManager(WebNotificationManagerProxy* manager) @@ -79,7 +80,7 @@ void WebNotificationProvider::addNotificationManager(WebNotificationManagerProxy if (!m_client.addNotificationManager) return; - m_client.addNotificationManager(toAPI(manager), m_client.clientInfo); + m_client.addNotificationManager(toAPI(manager), m_client.base.clientInfo); } void WebNotificationProvider::removeNotificationManager(WebNotificationManagerProxy* manager) @@ -87,15 +88,15 @@ void WebNotificationProvider::removeNotificationManager(WebNotificationManagerPr if (!m_client.removeNotificationManager) return; - m_client.removeNotificationManager(toAPI(manager), m_client.clientInfo); + m_client.removeNotificationManager(toAPI(manager), m_client.base.clientInfo); } -PassRefPtr<ImmutableDictionary> WebNotificationProvider::notificationPermissions() +PassRefPtr<API::Dictionary> WebNotificationProvider::notificationPermissions() { if (!m_client.notificationPermissions) - return ImmutableDictionary::create(); + return API::Dictionary::create(); - return adoptRef(toImpl(m_client.notificationPermissions(m_client.clientInfo))); + return adoptRef(toImpl(m_client.notificationPermissions(m_client.base.clientInfo))); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.h b/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.h index 574b887a4..14fabe16c 100644 --- a/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.h +++ b/Source/WebKit2/UIProcess/Notifications/WebNotificationProvider.h @@ -31,15 +31,22 @@ #include <wtf/Forward.h> #include <wtf/Vector.h> +namespace API { + +class Dictionary; + +template<> struct ClientTraits<WKNotificationProviderBase> { + typedef std::tuple<WKNotificationProviderV0> Versions; +}; +} + namespace WebKit { -class ImmutableDictionary; class WebNotification; class WebNotificationManagerProxy; class WebPageProxy; -class WebSecurityOrigin; -class WebNotificationProvider : public APIClient<WKNotificationProvider, kWKNotificationProviderCurrentVersion> { +class WebNotificationProvider : public API::Client<WKNotificationProviderBase> { public: void show(WebPageProxy*, WebNotification*); void cancel(WebNotification*); @@ -49,7 +56,7 @@ public: void addNotificationManager(WebNotificationManagerProxy*); void removeNotificationManager(WebNotificationManagerProxy*); - PassRefPtr<ImmutableDictionary> notificationPermissions(); + PassRefPtr<API::Dictionary> notificationPermissions(); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/PageClient.h b/Source/WebKit2/UIProcess/PageClient.h index 3b7ecb836..edb0897b0 100644 --- a/Source/WebKit2/UIProcess/PageClient.h +++ b/Source/WebKit2/UIProcess/PageClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011, 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -34,7 +34,7 @@ #include <WebCore/EditorClient.h> #include <wtf/Forward.h> -#if PLATFORM(MAC) +#if PLATFORM(COCOA) #include "PluginComplexTextInputState.h" OBJC_CLASS CALayer; @@ -46,29 +46,43 @@ OBJC_CLASS NSTextAlternatives; #endif namespace WebCore { - class Cursor; - struct ViewportAttributes; +class Cursor; +class TextIndicator; +class WebMediaSessionManager; +enum class TextIndicatorWindowLifetime : uint8_t; +enum class TextIndicatorWindowDismissalAnimation : uint8_t; +struct Highlight; +struct ViewportAttributes; } namespace WebKit { class DrawingAreaProxy; -class FindIndicator; class NativeWebKeyboardEvent; -#if ENABLE(TOUCH_EVENTS) -class NativeWebTouchEvent; -#endif -#if ENABLE(GESTURE_EVENTS) -class WebGestureEvent; -#endif +class NativeWebMouseEvent; +class RemoteLayerTreeTransaction; +class ViewSnapshot; class WebContextMenuProxy; class WebEditCommandProxy; class WebPopupMenuProxy; + +#if ENABLE(TOUCH_EVENTS) +class NativeWebTouchEvent; +#endif + #if ENABLE(INPUT_TYPE_COLOR) class WebColorPicker; #endif -#if PLATFORM(MAC) +#if ENABLE(FULLSCREEN_API) +class WebFullScreenManagerProxyClient; +#endif + +#if USE(GSTREAMER) +class InstallMissingMediaPluginsPermissionRequest; +#endif + +#if PLATFORM(COCOA) struct ColorSpaceData; #endif @@ -77,7 +91,7 @@ public: virtual ~PageClient() { } // Create a new drawing area proxy for the given page. - virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy() = 0; + virtual std::unique_ptr<DrawingAreaProxy> createDrawingAreaProxy() = 0; // Tell the view to invalidate the given rect. The rect is in view coordinates. virtual void setViewNeedsDisplay(const WebCore::IntRect&) = 0; @@ -89,6 +103,8 @@ public: virtual bool canScrollView() = 0; // Tell the view to scroll scrollRect by scrollOffset. virtual void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset) = 0; + // Tell the view to scroll to the given position, and whether this was a programmatic scroll. + virtual void requestScroll(const WebCore::FloatPoint& scrollPosition, const WebCore::IntPoint& scrollOrigin, bool isProgrammaticScroll) = 0; // Return the size of the view the page is associated with. virtual WebCore::IntSize viewSize() = 0; @@ -102,13 +118,19 @@ public: // Return whether the view is visible. virtual bool isViewVisible() = 0; + // Return whether the view is visible, or occluded by another window. + virtual bool isViewVisibleOrOccluded() { return isViewVisible(); } + // Return whether the view is in a window. virtual bool isViewInWindow() = 0; + // Return whether the view is visually idle. + virtual bool isVisuallyIdle() { return !isViewVisible(); } + // Return the layer hosting mode for the view. - virtual LayerHostingMode viewLayerHostingMode() { return LayerHostingModeDefault; } + virtual LayerHostingMode viewLayerHostingMode() { return LayerHostingMode::InProcess; } - virtual void processDidCrash() = 0; + virtual void processDidExit() = 0; virtual void didRelaunchProcess() = 0; virtual void pageClosed() = 0; @@ -116,37 +138,41 @@ public: virtual void toolTipChanged(const String&, const String&) = 0; -#if USE(TILED_BACKING_STORE) + virtual bool decidePolicyForGeolocationPermissionRequest(WebFrameProxy&, API::SecurityOrigin&, GeolocationPermissionRequestProxy&) + { + return false; + } + + virtual void didCommitLoadForMainFrame(const String& mimeType, bool useCustomContentProvider) = 0; + +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) virtual void pageDidRequestScroll(const WebCore::IntPoint&) = 0; virtual void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) = 0; virtual void pageTransitionViewportReady() = 0; -#endif -#if USE(COORDINATED_GRAPHICS) virtual void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&) = 0; #endif -#if PLATFORM(QT) - virtual void handleAuthenticationRequiredRequest(const String& hostname, const String& realm, const String& prefilledUsername, String& username, String& password) = 0; - virtual void handleCertificateVerificationRequest(const String& hostname, bool& ignoreErrors) = 0; - virtual void handleProxyAuthenticationRequiredRequest(const String& hostname, uint16_t port, const String& prefilledUsername, String& username, String& password) = 0; - virtual void handleWillSetInputMethodState() = 0; -#endif // PLATFORM(QT). -#if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) +#if PLATFORM(EFL) || PLATFORM(QT) virtual void updateTextInputState() = 0; -#endif // PLATFORM(QT) || PLATFORM(EFL) || PLATOFRM(GTK) +#endif // PLATFORM(EFL) -#if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) virtual void handleDownloadRequest(DownloadProxy*) = 0; -#endif // PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) -#if PLATFORM(QT) || PLATFORM(EFL) - virtual void didChangeContentsSize(const WebCore::IntSize&) = 0; -#endif + virtual bool handleRunOpenPanel(WebPageProxy*, WebFrameProxy*, WebOpenPanelParameters*, WebOpenPanelResultListenerProxy*) { return false; } + + virtual void didChangeContentSize(const WebCore::IntSize&) = 0; -#if PLATFORM(QT) || PLATFORM(GTK) +#if (PLATFORM(QT) || PLATFORM(GTK)) && ENABLE(DRAG_SUPPORT) virtual void startDrag(const WebCore::DragData&, PassRefPtr<ShareableBitmap> dragImage) = 0; #endif +#if PLATFORM(QT) + virtual void handleAuthenticationRequiredRequest(const String& hostname, const String& realm, const String& prefilledUsername, String& username, String& password) = 0; + virtual void handleCertificateVerificationRequest(const String& hostname, bool& ignoreErrors) = 0; + virtual void handleProxyAuthenticationRequiredRequest(const String& hostname, uint16_t port, const String& prefilledUsername, String& username, String& password) = 0; + virtual void handleWillSetInputMethodState() = 0; +#endif // PLATFORM(QT). + virtual void setCursor(const WebCore::Cursor&) = 0; virtual void setCursorHiddenUntilMouseMoves(bool) = 0; virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&) = 0; @@ -155,66 +181,99 @@ public: virtual void clearAllEditCommands() = 0; virtual bool canUndoRedo(WebPageProxy::UndoOrRedo) = 0; virtual void executeUndoRedo(WebPageProxy::UndoOrRedo) = 0; -#if PLATFORM(MAC) - virtual void accessibilityWebProcessTokenReceived(const CoreIPC::DataReference&) = 0; - virtual bool interpretKeyEvent(const NativeWebKeyboardEvent&, Vector<WebCore::KeypressCommand>&) = 0; +#if PLATFORM(COCOA) + virtual void accessibilityWebProcessTokenReceived(const IPC::DataReference&) = 0; virtual bool executeSavedCommandBySelector(const String& selector) = 0; virtual void setDragImage(const WebCore::IntPoint& clientPosition, PassRefPtr<ShareableBitmap> dragImage, bool isLinkDrag) = 0; virtual void updateSecureInputState() = 0; virtual void resetSecureInputState() = 0; virtual void notifyInputContextAboutDiscardedComposition() = 0; virtual void makeFirstResponder() = 0; - virtual void setPromisedData(const String& pasteboardName, PassRefPtr<WebCore::SharedBuffer> imageBuffer, const String& filename, const String& extension, const String& title, + virtual void setAcceleratedCompositingRootLayer(LayerOrView *) = 0; + virtual LayerOrView *acceleratedCompositingRootLayer() const = 0; + virtual PassRefPtr<ViewSnapshot> takeViewSnapshot() = 0; + virtual void wheelEventWasNotHandledByWebCore(const NativeWebWheelEvent&) = 0; +#if ENABLE(MAC_GESTURE_EVENTS) + virtual void gestureEventWasNotHandledByWebCore(const NativeWebGestureEvent&) = 0; +#endif +#endif + +#if PLATFORM(COCOA) || PLATFORM(GTK) + virtual void selectionDidChange() = 0; +#endif + +#if USE(APPKIT) + virtual void setPromisedDataForImage(const String& pasteboardName, PassRefPtr<WebCore::SharedBuffer> imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleUrl, PassRefPtr<WebCore::SharedBuffer> archiveBuffer) = 0; +#if ENABLE(ATTACHMENT_ELEMENT) + virtual void setPromisedDataForAttachment(const String& pasteboardName, const String& filename, const String& extension, const String& title, + const String& url, const String& visibleUrl) = 0; + #endif -#if PLATFORM(GTK) - virtual void getEditorCommandsForKeyEvent(const NativeWebKeyboardEvent&, const AtomicString&, Vector<WTF::String>&) = 0; #endif + virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&) = 0; virtual WebCore::FloatRect convertToUserSpace(const WebCore::FloatRect&) = 0; - virtual WebCore::IntPoint screenToWindow(const WebCore::IntPoint&) = 0; - virtual WebCore::IntRect windowToScreen(const WebCore::IntRect&) = 0; + virtual WebCore::IntPoint screenToRootView(const WebCore::IntPoint&) = 0; + virtual WebCore::IntRect rootViewToScreen(const WebCore::IntRect&) = 0; +#if PLATFORM(IOS) + virtual WebCore::IntPoint accessibilityScreenToRootView(const WebCore::IntPoint&) = 0; + virtual WebCore::IntRect rootViewToAccessibilityScreen(const WebCore::IntRect&) = 0; + virtual void didNotHandleTapAsClick(const WebCore::IntPoint&) = 0; +#endif virtual void doneWithKeyEvent(const NativeWebKeyboardEvent&, bool wasEventHandled) = 0; -#if ENABLE(GESTURE_EVENTS) - virtual void doneWithGestureEvent(const WebGestureEvent&, bool wasEventHandled) = 0; -#endif #if ENABLE(TOUCH_EVENTS) virtual void doneWithTouchEvent(const NativeWebTouchEvent&, bool wasEventHandled) = 0; #endif - virtual PassRefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy*) = 0; - virtual PassRefPtr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy*) = 0; + virtual RefPtr<WebPopupMenuProxy> createPopupMenuProxy(WebPageProxy&) = 0; +#if ENABLE(CONTEXT_MENUS) + virtual std::unique_ptr<WebContextMenuProxy> createContextMenuProxy(WebPageProxy&, const ContextMenuContextData&, const UserData&) = 0; +#endif #if ENABLE(INPUT_TYPE_COLOR) - virtual PassRefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&) = 0; + virtual RefPtr<WebColorPicker> createColorPicker(WebPageProxy*, const WebCore::Color& initialColor, const WebCore::IntRect&) = 0; #endif - virtual void setFindIndicator(PassRefPtr<FindIndicator>, bool fadeOut, bool animate) = 0; +#if PLATFORM(COCOA) + virtual void setTextIndicator(Ref<WebCore::TextIndicator>, WebCore::TextIndicatorWindowLifetime) = 0; + virtual void clearTextIndicator(WebCore::TextIndicatorWindowDismissalAnimation) = 0; + virtual void setTextIndicatorAnimationProgress(float) = 0; +#endif -#if USE(ACCELERATED_COMPOSITING) virtual void enterAcceleratedCompositingMode(const LayerTreeContext&) = 0; virtual void exitAcceleratedCompositingMode() = 0; virtual void updateAcceleratedCompositingMode(const LayerTreeContext&) = 0; -#endif + virtual void willEnterAcceleratedCompositingMode() = 0; #if PLATFORM(MAC) virtual void pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus) = 0; virtual void setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, PluginComplexTextInputState) = 0; - virtual CGContextRef containingWindowGraphicsContext() = 0; - virtual void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&) = 0; - virtual void dismissDictionaryLookupPanel() = 0; + virtual void didPerformDictionaryLookup(const WebCore::DictionaryPopupInfo&) = 0; + virtual void dismissContentRelativeChildWindows(bool withAnimation = true) = 0; virtual void showCorrectionPanel(WebCore::AlternativeTextType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) = 0; virtual void dismissCorrectionPanel(WebCore::ReasonForDismissingAlternativeText) = 0; virtual String dismissCorrectionPanelSoon(WebCore::ReasonForDismissingAlternativeText) = 0; virtual void recordAutocorrectionResponse(WebCore::AutocorrectionResponseType, const String& replacedString, const String& replacementString) = 0; - virtual void recommendedScrollbarStyleDidChange(int32_t newStyle) = 0; + virtual void recommendedScrollbarStyleDidChange(WebCore::ScrollbarStyle) = 0; + virtual void removeNavigationGestureSnapshot() = 0; + + virtual CGRect boundsOfLayerInLayerBackedWindowCoordinates(CALayer *) const = 0; virtual ColorSpaceData colorSpace() = 0; - virtual void setAcceleratedCompositingRootLayer(CALayer *) = 0; + + virtual void showPlatformContextMenu(NSMenu *, WebCore::IntPoint) = 0; + + virtual void startWindowDrag() = 0; + virtual NSWindow *platformWindow() = 0; + +#if WK_API_ENABLED + virtual NSView *inspectorAttachmentView() = 0; + virtual _WKRemoteObjectRegistry *remoteObjectRegistry() = 0; +#endif #if USE(APPKIT) - virtual WKView* wkView() const = 0; virtual void intrinsicContentSizeDidChange(const WebCore::IntSize& intrinsicContentSize) = 0; #if USE(DICTATION_ALTERNATIVES) virtual uint64_t addDictationAlternatives(const RetainPtr<NSTextAlternatives>&) = 0; @@ -222,10 +281,95 @@ public: virtual void showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext) = 0; virtual Vector<String> dictationAlternatives(uint64_t dictationContext) = 0; #endif // USE(DICTATION_ALTERNATIVES) +#if USE(INSERTION_UNDO_GROUPING) + virtual void registerInsertionUndoGrouping() = 0; +#endif // USE(INSERTION_UNDO_GROUPING) #endif // USE(APPKIT) #endif // PLATFORM(MAC) - virtual void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects) = 0; +#if PLATFORM(IOS) + virtual void commitPotentialTapFailed() = 0; + virtual void didGetTapHighlightGeometries(uint64_t requestID, const WebCore::Color&, const Vector<WebCore::FloatQuad>& highlightedQuads, const WebCore::IntSize& topLeftRadius, const WebCore::IntSize& topRightRadius, const WebCore::IntSize& bottomLeftRadius, const WebCore::IntSize& bottomRightRadius) = 0; + + virtual void didCommitLayerTree(const RemoteLayerTreeTransaction&) = 0; + virtual void dynamicViewportUpdateChangedTarget(double newScale, const WebCore::FloatPoint& newScrollPosition, uint64_t transactionID) = 0; + virtual void couldNotRestorePageState() = 0; + virtual void restorePageState(const WebCore::FloatRect&, double) = 0; + virtual void restorePageCenterAndScale(const WebCore::FloatPoint&, double) = 0; + + virtual void startAssistingNode(const AssistedNodeInformation&, bool userIsInteracting, bool blurPreviousNode, API::Object* userData) = 0; + virtual void stopAssistingNode() = 0; + virtual bool isAssistingNode() = 0; + virtual bool interpretKeyEvent(const NativeWebKeyboardEvent&, bool isCharEvent) = 0; + virtual void positionInformationDidChange(const InteractionInformationAtPosition&) = 0; + virtual void saveImageToLibrary(PassRefPtr<WebCore::SharedBuffer>) = 0; + virtual void didUpdateBlockSelectionWithTouch(uint32_t touch, uint32_t flags, float growThreshold, float shrinkThreshold) = 0; + virtual void showPlaybackTargetPicker(bool hasVideo, const WebCore::IntRect& elementRect) = 0; + virtual void zoomToRect(WebCore::FloatRect, double minimumScale, double maximumScale) = 0; + virtual void disableDoubleTapGesturesDuringTapIfNecessary(uint64_t requestID) = 0; + virtual double minimumZoomScale() const = 0; + virtual WebCore::FloatRect documentRect() const = 0; + virtual void overflowScrollViewWillStartPanGesture() = 0; + virtual void overflowScrollViewDidScroll() = 0; + virtual void overflowScrollWillStartScroll() = 0; + virtual void overflowScrollDidEndScroll() = 0; + virtual void didFinishDrawingPagesToPDF(const IPC::DataReference&) = 0; + virtual Vector<String> mimeTypesWithCustomContentProviders() = 0; + + virtual void showInspectorHighlight(const WebCore::Highlight&) = 0; + virtual void hideInspectorHighlight() = 0; + + virtual void showInspectorIndication() = 0; + virtual void hideInspectorIndication() = 0; + + virtual void enableInspectorNodeSearch() = 0; + virtual void disableInspectorNodeSearch() = 0; +#endif + + // Auxiliary Client Creation +#if ENABLE(FULLSCREEN_API) + virtual WebFullScreenManagerProxyClient& fullScreenManagerProxyClient() = 0; +#endif + + // Custom representations. + virtual void didFinishLoadingDataForCustomContentProvider(const String& suggestedFilename, const IPC::DataReference&) = 0; + + virtual void navigationGestureDidBegin() = 0; + virtual void navigationGestureWillEnd(bool willNavigate, WebBackForwardListItem&) = 0; + virtual void navigationGestureDidEnd(bool willNavigate, WebBackForwardListItem&) = 0; + virtual void navigationGestureDidEnd() = 0; + virtual void willRecordNavigationSnapshot(WebBackForwardListItem&) = 0; + virtual void didRemoveNavigationGestureSnapshot() = 0; + + virtual void didFirstVisuallyNonEmptyLayoutForMainFrame() = 0; + virtual void didFinishLoadForMainFrame() = 0; + virtual void didFailLoadForMainFrame() = 0; + virtual void didSameDocumentNavigationForMainFrame(SameDocumentNavigationType) = 0; + + virtual void didChangeBackgroundColor() = 0; + +#if PLATFORM(MAC) + virtual void didPerformImmediateActionHitTest(const WebHitTestResultData&, bool contentPreventsDefault, API::Object*) = 0; + + virtual void* immediateActionAnimationControllerForHitTestResult(RefPtr<API::HitTestResult>, uint64_t, RefPtr<API::Object>) = 0; + + virtual void didHandleAcceptedCandidate() = 0; +#endif + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) + virtual WebCore::WebMediaSessionManager& mediaSessionManager() = 0; +#endif + + virtual void refView() = 0; + virtual void derefView() = 0; + +#if ENABLE(VIDEO) && USE(GSTREAMER) + virtual bool decidePolicyForInstallMissingMediaPluginsPermissionRequest(InstallMissingMediaPluginsPermissionRequest&) = 0; +#endif + + virtual void didRestoreScrollPosition() = 0; + + virtual bool windowIsFrontWindowUnderMouse(const NativeWebMouseEvent&) { return false; } }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/PageLoadState.cpp b/Source/WebKit2/UIProcess/PageLoadState.cpp new file mode 100644 index 000000000..8b501bf11 --- /dev/null +++ b/Source/WebKit2/UIProcess/PageLoadState.cpp @@ -0,0 +1,421 @@ +/* + * Copyright (C) 2013-2015 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 "PageLoadState.h" + +#include "WebPageProxy.h" + +namespace WebKit { + +// Progress always starts at this value. This helps provide feedback as soon as a load starts. +static const double initialProgressValue = 0.1; + +PageLoadState::PageLoadState(WebPageProxy& webPageProxy) + : m_webPageProxy(webPageProxy) + , m_mayHaveUncommittedChanges(false) + , m_outstandingTransactionCount(0) +{ +} + +PageLoadState::~PageLoadState() +{ + ASSERT(m_observers.isEmpty()); +} + +PageLoadState::Transaction::Transaction(PageLoadState& pageLoadState) + : m_webPageProxy(&pageLoadState.m_webPageProxy) + , m_pageLoadState(&pageLoadState) +{ + m_pageLoadState->beginTransaction(); +} + +PageLoadState::Transaction::Transaction(Transaction&& other) + : m_webPageProxy(WTFMove(other.m_webPageProxy)) + , m_pageLoadState(other.m_pageLoadState) +{ + other.m_pageLoadState = nullptr; +} + +PageLoadState::Transaction::~Transaction() +{ + if (m_pageLoadState) + m_pageLoadState->endTransaction(); +} + +void PageLoadState::addObserver(Observer& observer) +{ + ASSERT(!m_observers.contains(&observer)); + + m_observers.append(&observer); +} + +void PageLoadState::removeObserver(Observer& observer) +{ + bool removed = m_observers.removeFirst(&observer); + ASSERT_UNUSED(removed, removed); +} + +void PageLoadState::endTransaction() +{ + ASSERT(m_outstandingTransactionCount > 0); + + if (!--m_outstandingTransactionCount) + commitChanges(); +} + +void PageLoadState::commitChanges() +{ + if (!m_mayHaveUncommittedChanges) + return; + + m_mayHaveUncommittedChanges = false; + + bool canGoBackChanged = m_committedState.canGoBack != m_uncommittedState.canGoBack; + bool canGoForwardChanged = m_committedState.canGoForward != m_uncommittedState.canGoForward; + bool titleChanged = m_committedState.title != m_uncommittedState.title; + bool isLoadingChanged = isLoading(m_committedState) != isLoading(m_uncommittedState); + bool activeURLChanged = activeURL(m_committedState) != activeURL(m_uncommittedState); + bool hasOnlySecureContentChanged = hasOnlySecureContent(m_committedState) != hasOnlySecureContent(m_uncommittedState); + bool estimatedProgressChanged = estimatedProgress(m_committedState) != estimatedProgress(m_uncommittedState); + bool networkRequestsInProgressChanged = m_committedState.networkRequestsInProgress != m_uncommittedState.networkRequestsInProgress; + bool certificateInfoChanged = m_committedState.certificateInfo != m_uncommittedState.certificateInfo; + + if (canGoBackChanged) + callObserverCallback(&Observer::willChangeCanGoBack); + if (canGoForwardChanged) + callObserverCallback(&Observer::willChangeCanGoForward); + if (titleChanged) + callObserverCallback(&Observer::willChangeTitle); + if (isLoadingChanged) + callObserverCallback(&Observer::willChangeIsLoading); + if (activeURLChanged) + callObserverCallback(&Observer::willChangeActiveURL); + if (hasOnlySecureContentChanged) + callObserverCallback(&Observer::willChangeHasOnlySecureContent); + if (estimatedProgressChanged) + callObserverCallback(&Observer::willChangeEstimatedProgress); + if (networkRequestsInProgressChanged) + callObserverCallback(&Observer::willChangeNetworkRequestsInProgress); + if (certificateInfoChanged) + callObserverCallback(&Observer::willChangeCertificateInfo); + + m_committedState = m_uncommittedState; + + // The "did" ordering is the reverse of the "will". This is a requirement of Cocoa Key-Value Observing. + if (certificateInfoChanged) + callObserverCallback(&Observer::didChangeCertificateInfo); + if (networkRequestsInProgressChanged) + callObserverCallback(&Observer::didChangeNetworkRequestsInProgress); + if (estimatedProgressChanged) + callObserverCallback(&Observer::didChangeEstimatedProgress); + if (hasOnlySecureContentChanged) + callObserverCallback(&Observer::didChangeHasOnlySecureContent); + if (activeURLChanged) + callObserverCallback(&Observer::didChangeActiveURL); + if (isLoadingChanged) + callObserverCallback(&Observer::didChangeIsLoading); + if (titleChanged) + callObserverCallback(&Observer::didChangeTitle); + if (canGoForwardChanged) + callObserverCallback(&Observer::didChangeCanGoForward); + if (canGoBackChanged) + callObserverCallback(&Observer::didChangeCanGoBack); +} + +void PageLoadState::reset(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + + m_uncommittedState.state = State::Finished; + m_uncommittedState.hasInsecureContent = false; + + m_uncommittedState.pendingAPIRequestURL = String(); + m_uncommittedState.provisionalURL = String(); + m_uncommittedState.url = String(); + + m_uncommittedState.unreachableURL = String(); + m_lastUnreachableURL = String(); + + m_uncommittedState.title = String(); + + m_uncommittedState.estimatedProgress = 0; + m_uncommittedState.networkRequestsInProgress = false; +} + +bool PageLoadState::isLoading() const +{ + return isLoading(m_committedState); +} + +String PageLoadState::activeURL(const Data& data) +{ + // If there is a currently pending URL, it is the active URL, + // even when there's no main frame yet, as it might be the + // first API request. + if (!data.pendingAPIRequestURL.isNull()) + return data.pendingAPIRequestURL; + + if (!data.unreachableURL.isEmpty()) + return data.unreachableURL; + + switch (data.state) { + case State::Provisional: + return data.provisionalURL; + case State::Committed: + case State::Finished: + return data.url; + } + + ASSERT_NOT_REACHED(); + return String(); +} + +String PageLoadState::activeURL() const +{ + return activeURL(m_committedState); +} + +bool PageLoadState::hasOnlySecureContent(const Data& data) +{ + if (data.hasInsecureContent) + return false; + + return WebCore::protocolIs(data.url, "https"); +} + +bool PageLoadState::hasOnlySecureContent() const +{ + return hasOnlySecureContent(m_committedState); +} + +double PageLoadState::estimatedProgress(const Data& data) +{ + if (!data.pendingAPIRequestURL.isNull()) + return initialProgressValue; + + return data.estimatedProgress; +} + +double PageLoadState::estimatedProgress() const +{ + return estimatedProgress(m_committedState); +} + +const String& PageLoadState::pendingAPIRequestURL() const +{ + return m_committedState.pendingAPIRequestURL; +} + +void PageLoadState::setPendingAPIRequestURL(const Transaction::Token& token, const String& pendingAPIRequestURL) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.pendingAPIRequestURL = pendingAPIRequestURL; +} + +void PageLoadState::clearPendingAPIRequestURL(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.pendingAPIRequestURL = String(); +} + +void PageLoadState::didStartProvisionalLoad(const Transaction::Token& token, const String& url, const String& unreachableURL) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(m_uncommittedState.provisionalURL.isEmpty()); + + m_uncommittedState.state = State::Provisional; + + m_uncommittedState.provisionalURL = url; + + setUnreachableURL(token, unreachableURL); +} + +void PageLoadState::didReceiveServerRedirectForProvisionalLoad(const Transaction::Token& token, const String& url) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(m_uncommittedState.state == State::Provisional); + + m_uncommittedState.provisionalURL = url; +} + +void PageLoadState::didFailProvisionalLoad(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(m_uncommittedState.state == State::Provisional); + + m_uncommittedState.state = State::Finished; + + m_uncommittedState.provisionalURL = String(); + m_uncommittedState.unreachableURL = m_lastUnreachableURL; +} + +void PageLoadState::didCommitLoad(const Transaction::Token& token, WebCertificateInfo& certificateInfo, bool hasInsecureContent) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(m_uncommittedState.state == State::Provisional); + + m_uncommittedState.state = State::Committed; + m_uncommittedState.hasInsecureContent = hasInsecureContent; + m_uncommittedState.certificateInfo = &certificateInfo; + + m_uncommittedState.url = m_uncommittedState.provisionalURL; + m_uncommittedState.provisionalURL = String(); + + m_uncommittedState.title = String(); +} + +void PageLoadState::didFinishLoad(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(m_uncommittedState.state == State::Committed); + ASSERT(m_uncommittedState.provisionalURL.isEmpty()); + + m_uncommittedState.state = State::Finished; +} + +void PageLoadState::didFailLoad(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(m_uncommittedState.provisionalURL.isEmpty()); + + m_uncommittedState.state = State::Finished; +} + +void PageLoadState::didSameDocumentNavigation(const Transaction::Token& token, const String& url) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + ASSERT(!m_uncommittedState.url.isEmpty()); + + m_uncommittedState.url = url; +} + +void PageLoadState::didDisplayOrRunInsecureContent(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + + m_uncommittedState.hasInsecureContent = true; +} + +void PageLoadState::setUnreachableURL(const Transaction::Token& token, const String& unreachableURL) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + + m_lastUnreachableURL = m_uncommittedState.unreachableURL; + m_uncommittedState.unreachableURL = unreachableURL; +} + +const String& PageLoadState::title() const +{ + return m_committedState.title; +} + +void PageLoadState::setTitle(const Transaction::Token& token, const String& title) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.title = title; +} + +bool PageLoadState::canGoBack() const +{ + return m_committedState.canGoBack; +} + +void PageLoadState::setCanGoBack(const Transaction::Token& token, bool canGoBack) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.canGoBack = canGoBack; +} + +bool PageLoadState::canGoForward() const +{ + return m_committedState.canGoForward; +} + +void PageLoadState::setCanGoForward(const Transaction::Token& token, bool canGoForward) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.canGoForward = canGoForward; +} + +void PageLoadState::didStartProgress(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.estimatedProgress = initialProgressValue; +} + +void PageLoadState::didChangeProgress(const Transaction::Token& token, double value) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.estimatedProgress = value; +} + +void PageLoadState::didFinishProgress(const Transaction::Token& token) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.estimatedProgress = 1; +} + +void PageLoadState::setNetworkRequestsInProgress(const Transaction::Token& token, bool networkRequestsInProgress) +{ + ASSERT_UNUSED(token, &token.m_pageLoadState == this); + m_uncommittedState.networkRequestsInProgress = networkRequestsInProgress; +} + +bool PageLoadState::isLoading(const Data& data) +{ + if (!data.pendingAPIRequestURL.isNull()) + return true; + + switch (data.state) { + case State::Provisional: + case State::Committed: + return true; + + case State::Finished: + return false; + } + + ASSERT_NOT_REACHED(); + return false; +} + +void PageLoadState::willChangeProcessIsResponsive() +{ + callObserverCallback(&Observer::willChangeWebProcessIsResponsive); +} + +void PageLoadState::didChangeProcessIsResponsive() +{ + callObserverCallback(&Observer::didChangeWebProcessIsResponsive); +} + +void PageLoadState::callObserverCallback(void (Observer::*callback)()) +{ + for (auto* observer : m_observers) + (observer->*callback)(); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/PageLoadState.h b/Source/WebKit2/UIProcess/PageLoadState.h new file mode 100644 index 000000000..402c97f58 --- /dev/null +++ b/Source/WebKit2/UIProcess/PageLoadState.h @@ -0,0 +1,231 @@ +/* + * Copyright (C) 2013-2015 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 PageLoadState_h +#define PageLoadState_h + +#include "WebCertificateInfo.h" +#include <wtf/text/WTFString.h> + +namespace WebKit { + +class WebCertificateInfo; +class WebPageProxy; + +class PageLoadState { +public: + explicit PageLoadState(WebPageProxy&); + ~PageLoadState(); + + enum class State { + Provisional, + Committed, + Finished + }; + + class Observer { + public: + virtual ~Observer() { } + + virtual void willChangeIsLoading() = 0; + virtual void didChangeIsLoading() = 0; + + virtual void willChangeTitle() = 0; + virtual void didChangeTitle() = 0; + + virtual void willChangeActiveURL() = 0; + virtual void didChangeActiveURL() = 0; + + virtual void willChangeHasOnlySecureContent() = 0; + virtual void didChangeHasOnlySecureContent() = 0; + + virtual void willChangeEstimatedProgress() = 0; + virtual void didChangeEstimatedProgress() = 0; + + virtual void willChangeCanGoBack() = 0; + virtual void didChangeCanGoBack() = 0; + + virtual void willChangeCanGoForward() = 0; + virtual void didChangeCanGoForward() = 0; + + virtual void willChangeNetworkRequestsInProgress() = 0; + virtual void didChangeNetworkRequestsInProgress() = 0; + + virtual void willChangeCertificateInfo() = 0; + virtual void didChangeCertificateInfo() = 0; + + virtual void willChangeWebProcessIsResponsive() = 0; + virtual void didChangeWebProcessIsResponsive() = 0; + }; + + class Transaction { + WTF_MAKE_NONCOPYABLE(Transaction); + public: + Transaction(Transaction&&); + ~Transaction(); + + private: + friend class PageLoadState; + + explicit Transaction(PageLoadState&); + + class Token { + public: + Token(Transaction& transaction) +#if !ASSERT_DISABLED + : m_pageLoadState(*transaction.m_pageLoadState) +#endif + { + transaction.m_pageLoadState->m_mayHaveUncommittedChanges = true; + } + +#if !ASSERT_DISABLED + PageLoadState& m_pageLoadState; +#endif + }; + + RefPtr<WebPageProxy> m_webPageProxy; + PageLoadState* m_pageLoadState; + }; + + void addObserver(Observer&); + void removeObserver(Observer&); + + Transaction transaction() { return Transaction(*this); } + void commitChanges(); + + void reset(const Transaction::Token&); + + bool isLoading() const; + + const String& provisionalURL() const { return m_committedState.provisionalURL; } + const String& url() const { return m_committedState.url; } + const String& unreachableURL() const { return m_committedState.unreachableURL; } + + String activeURL() const; + + bool hasOnlySecureContent() const; + + double estimatedProgress() const; + bool networkRequestsInProgress() const { return m_committedState.networkRequestsInProgress; } + + WebCertificateInfo* certificateInfo() const { return m_committedState.certificateInfo.get(); } + + const String& pendingAPIRequestURL() const; + void setPendingAPIRequestURL(const Transaction::Token&, const String&); + void clearPendingAPIRequestURL(const Transaction::Token&); + + void didStartProvisionalLoad(const Transaction::Token&, const String& url, const String& unreachableURL); + void didReceiveServerRedirectForProvisionalLoad(const Transaction::Token&, const String& url); + void didFailProvisionalLoad(const Transaction::Token&); + + void didCommitLoad(const Transaction::Token&, WebCertificateInfo&, bool hasInsecureContent); + void didFinishLoad(const Transaction::Token&); + void didFailLoad(const Transaction::Token&); + + void didSameDocumentNavigation(const Transaction::Token&, const String& url); + + void didDisplayOrRunInsecureContent(const Transaction::Token&); + + void setUnreachableURL(const Transaction::Token&, const String&); + + const String& title() const; + void setTitle(const Transaction::Token&, const String&); + + bool canGoBack() const; + void setCanGoBack(const Transaction::Token&, bool); + + bool canGoForward() const; + void setCanGoForward(const Transaction::Token&, bool); + + void didStartProgress(const Transaction::Token&); + void didChangeProgress(const Transaction::Token&, double); + void didFinishProgress(const Transaction::Token&); + void setNetworkRequestsInProgress(const Transaction::Token&, bool); + + // FIXME: We piggy-back off PageLoadState::Observer so that both WKWebView and WKObservablePageState + // can listen for changes. Once we get rid of WKObservablePageState these could just be part of API::NavigationClient. + void willChangeProcessIsResponsive(); + void didChangeProcessIsResponsive(); + +private: + void beginTransaction() { ++m_outstandingTransactionCount; } + void endTransaction(); + + void callObserverCallback(void (Observer::*)()); + + Vector<Observer*> m_observers; + + struct Data { + Data() + : state(State::Finished) + , hasInsecureContent(false) + , canGoBack(false) + , canGoForward(false) + , estimatedProgress(0) + , networkRequestsInProgress(false) + { + } + + State state; + bool hasInsecureContent; + + String pendingAPIRequestURL; + + String provisionalURL; + String url; + + String unreachableURL; + + String title; + + bool canGoBack; + bool canGoForward; + + double estimatedProgress; + bool networkRequestsInProgress; + + RefPtr<WebCertificateInfo> certificateInfo; + }; + + static bool isLoading(const Data&); + static String activeURL(const Data&); + static bool hasOnlySecureContent(const Data&); + static double estimatedProgress(const Data&); + + WebPageProxy& m_webPageProxy; + + Data m_committedState; + Data m_uncommittedState; + + String m_lastUnreachableURL; + + bool m_mayHaveUncommittedChanges; + unsigned m_outstandingTransactionCount; +}; + +} // namespace WebKit + +#endif // PageLoadState_h diff --git a/Source/WebKit2/UIProcess/PageViewportControllerClient.h b/Source/WebKit2/UIProcess/PageViewportControllerClient.h index 15d9a5e5d..4ad7ce506 100644 --- a/Source/WebKit2/UIProcess/PageViewportControllerClient.h +++ b/Source/WebKit2/UIProcess/PageViewportControllerClient.h @@ -30,22 +30,18 @@ class IntSize; namespace WebKit { -class PageViewportController; - class PageViewportControllerClient { WTF_MAKE_NONCOPYABLE(PageViewportControllerClient); public: PageViewportControllerClient() { } virtual ~PageViewportControllerClient() { } - virtual void setViewportPosition(const WebCore::FloatPoint& contentsPoint) = 0; + virtual void setViewportPosition(const WebCore::FloatPoint&) = 0; virtual void setPageScaleFactor(float) = 0; virtual void didChangeContentsSize(const WebCore::IntSize&) = 0; virtual void didChangeVisibleContents() = 0; virtual void didChangeViewportAttributes() = 0; - - virtual void setController(PageViewportController*) = 0; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp index fd0e1d9ee..25075924e 100644 --- a/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012, 2013 Apple Inc. All rights reserved. + * Copyright (C) 2012-2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,11 +26,11 @@ #include "config.h" #include "PlugInAutoStartProvider.h" -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "WebContext.h" +#include "APIArray.h" +#include "APIDictionary.h" #include "WebContextClient.h" #include "WebProcessMessages.h" +#include "WebProcessPool.h" #include <wtf/CurrentTime.h> using namespace WebCore; @@ -39,9 +39,11 @@ static const double plugInAutoStartExpirationTimeThreshold = 30 * 24 * 60 * 60; namespace WebKit { -PlugInAutoStartProvider::PlugInAutoStartProvider(WebContext* context) - : m_context(context) +PlugInAutoStartProvider::PlugInAutoStartProvider(WebProcessPool* processPool) + : m_processPool(processPool) { + m_hashToOriginMap.add(SessionID::defaultSessionID(), HashMap<unsigned, String>()); + m_autoStartTable.add(SessionID::defaultSessionID(), AutoStartTable()); } static double expirationTimeFromNow() @@ -49,110 +51,141 @@ static double expirationTimeFromNow() return currentTime() + plugInAutoStartExpirationTimeThreshold; } -void PlugInAutoStartProvider::addAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash) +void PlugInAutoStartProvider::addAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, SessionID sessionID) { - if (m_hashToOriginMap.contains(plugInOriginHash)) + auto sessionIterator = m_hashToOriginMap.find(sessionID); + if (sessionIterator == m_hashToOriginMap.end()) { + if (m_hashToOriginMap.get(SessionID::defaultSessionID()).contains(plugInOriginHash)) + return; + sessionIterator = m_hashToOriginMap.set(sessionID, HashMap<unsigned, String>()).iterator; + } else if (sessionIterator->value.contains(plugInOriginHash) || m_hashToOriginMap.get(SessionID::defaultSessionID()).contains(plugInOriginHash)) return; - AutoStartTable::iterator it = m_autoStartTable.find(pageOrigin); - if (it == m_autoStartTable.end()) - it = m_autoStartTable.add(pageOrigin, PlugInAutoStartOriginHash()).iterator; + AutoStartTable::iterator it = m_autoStartTable.add(sessionID, AutoStartTable()).iterator->value.add(pageOrigin, PlugInAutoStartOriginMap()).iterator; double expirationTime = expirationTimeFromNow(); it->value.set(plugInOriginHash, expirationTime); - m_hashToOriginMap.set(plugInOriginHash, pageOrigin); + sessionIterator->value.set(plugInOriginHash, pageOrigin); - m_context->sendToAllProcesses(Messages::WebProcess::DidAddPlugInAutoStartOriginHash(plugInOriginHash, expirationTime)); - m_context->client().plugInAutoStartOriginHashesChanged(m_context); + m_processPool->sendToAllProcesses(Messages::WebProcess::DidAddPlugInAutoStartOriginHash(plugInOriginHash, expirationTime, sessionID)); + + if (!sessionID.isEphemeral()) + m_processPool->client().plugInAutoStartOriginHashesChanged(m_processPool); } -PlugInAutoStartOriginHash PlugInAutoStartProvider::autoStartOriginHashesCopy() const +SessionPlugInAutoStartOriginMap PlugInAutoStartProvider::autoStartOriginHashesCopy() const { - PlugInAutoStartOriginHash copyMap; - AutoStartTable::const_iterator end = m_autoStartTable.end(); - for (AutoStartTable::const_iterator it = m_autoStartTable.begin(); it != end; ++it) { - PlugInAutoStartOriginHash::const_iterator mapEnd = it->value.end(); - for (PlugInAutoStartOriginHash::const_iterator mapIt = it->value.begin(); mapIt != mapEnd; ++mapIt) - copyMap.set(mapIt->key, mapIt->value); + SessionPlugInAutoStartOriginMap sessionMap; + + for (const auto& sessionKeyOriginHash : m_autoStartTable) { + PlugInAutoStartOriginMap& map = sessionMap.add(sessionKeyOriginHash.key, PlugInAutoStartOriginMap()).iterator->value; + for (const auto& keyOriginHash : sessionKeyOriginHash.value) { + for (const auto& originHash : keyOriginHash.value) + map.set(originHash.key, originHash.value); + } } - return copyMap; + return sessionMap; } -PassRefPtr<ImmutableDictionary> PlugInAutoStartProvider::autoStartOriginsTableCopy() const +Ref<API::Dictionary> PlugInAutoStartProvider::autoStartOriginsTableCopy() const { - ImmutableDictionary::MapType map; - AutoStartTable::const_iterator end = m_autoStartTable.end(); + API::Dictionary::MapType map; + double now = currentTime(); - for (AutoStartTable::const_iterator it = m_autoStartTable.begin(); it != end; ++it) { - ImmutableDictionary::MapType hashMap; - PlugInAutoStartOriginHash::const_iterator valueEnd = it->value.end(); - for (PlugInAutoStartOriginHash::const_iterator valueIt = it->value.begin(); valueIt != valueEnd; ++valueIt) { - if (now > valueIt->value) - continue; - hashMap.set(String::number(valueIt->key), WebDouble::create(valueIt->value)); + for (const auto& stringOriginHash : m_autoStartTable.get(SessionID::defaultSessionID())) { + API::Dictionary::MapType hashMap; + for (const auto& originHash : stringOriginHash.value) { + if (now <= originHash.value) + hashMap.set(String::number(originHash.key), API::Double::create(originHash.value)); } - if (hashMap.size()) - map.set(it->key, ImmutableDictionary::adopt(hashMap)); + map.set(stringOriginHash.key, API::Dictionary::create(WTFMove(hashMap))); } - return ImmutableDictionary::adopt(map); + return API::Dictionary::create(WTFMove(map)); } -void PlugInAutoStartProvider::setAutoStartOriginsTable(ImmutableDictionary& table) +void PlugInAutoStartProvider::setAutoStartOriginsTable(API::Dictionary& table) { + setAutoStartOriginsTableWithItemsPassingTest(table, [](double) { + return true; + }); +} + +void PlugInAutoStartProvider::setAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& table, double time) +{ + double adjustedTimestamp = time + plugInAutoStartExpirationTimeThreshold; + setAutoStartOriginsTableWithItemsPassingTest(table, [adjustedTimestamp](double expirationTimestamp) { + return adjustedTimestamp > expirationTimestamp; + }); +} + +void PlugInAutoStartProvider::setAutoStartOriginsTableWithItemsPassingTest(API::Dictionary& table, std::function<bool(double expirationTimestamp)> isExpirationTimeAcceptable) +{ + ASSERT(isExpirationTimeAcceptable); + m_hashToOriginMap.clear(); m_autoStartTable.clear(); HashMap<unsigned, double> hashMap; + HashMap<unsigned, String>& hashToOriginMap = m_hashToOriginMap.add(SessionID::defaultSessionID(), HashMap<unsigned, String>()).iterator->value; + AutoStartTable& ast = m_autoStartTable.add(SessionID::defaultSessionID(), AutoStartTable()).iterator->value; - ImmutableDictionary::MapType::const_iterator end = table.map().end(); - for (ImmutableDictionary::MapType::const_iterator it = table.map().begin(); it != end; ++it) { - PlugInAutoStartOriginHash hashes; - ImmutableDictionary* hashesForPage = static_cast<ImmutableDictionary*>(it->value.get()); - ImmutableDictionary::MapType::const_iterator hashEnd = hashesForPage->map().end(); - for (ImmutableDictionary::MapType::const_iterator hashIt = hashesForPage->map().begin(); hashIt != hashEnd; ++hashIt) { + for (auto& strDict : table.map()) { + PlugInAutoStartOriginMap hashes; + for (auto& hashTime : static_cast<API::Dictionary*>(strDict.value.get())->map()) { bool ok; - unsigned hash = hashIt->key.toUInt(&ok); + unsigned hash = hashTime.key.toUInt(&ok); if (!ok) continue; - if (hashIt->value->type() != WebDouble::APIType) + if (hashTime.value->type() != API::Double::APIType) + continue; + + double expirationTime = static_cast<API::Double*>(hashTime.value.get())->value(); + if (!isExpirationTimeAcceptable(expirationTime)) continue; - double expirationTime = static_cast<WebDouble*>(hashIt->value.get())->value(); hashes.set(hash, expirationTime); hashMap.set(hash, expirationTime); - m_hashToOriginMap.set(hash, it->key); + hashToOriginMap.set(hash, strDict.key); } - m_autoStartTable.set(it->key, hashes); + if (!hashes.isEmpty()) + ast.set(strDict.key, hashes); } - m_context->sendToAllProcesses(Messages::WebProcess::ResetPlugInAutoStartOriginHashes(hashMap)); + m_processPool->sendToAllProcesses(Messages::WebProcess::ResetPlugInAutoStartOriginDefaultHashes(hashMap)); } -void PlugInAutoStartProvider::setAutoStartOriginsArray(ImmutableArray& originList) +void PlugInAutoStartProvider::setAutoStartOriginsArray(API::Array& originList) { m_autoStartOrigins.clear(); - for (size_t i = 0, length = originList.size(); i < length; ++i) { - if (originList.at(i)->type() != WebString::APIType) - continue; - m_autoStartOrigins.append(static_cast<WebString*>(originList.at(i))->string()); - } + for (const auto& string : originList.elementsOfType<API::String>()) + m_autoStartOrigins.append(string->string()); } -void PlugInAutoStartProvider::didReceiveUserInteraction(unsigned plugInOriginHash) +void PlugInAutoStartProvider::didReceiveUserInteraction(unsigned plugInOriginHash, SessionID sessionID) { - HashMap<unsigned, String>::const_iterator it = m_hashToOriginMap.find(plugInOriginHash); - if (it == m_hashToOriginMap.end()) { - ASSERT_NOT_REACHED(); - return; + HashMap<WebCore::SessionID, HashMap<unsigned, String>>::const_iterator sessionIterator = m_hashToOriginMap.find(sessionID); + HashMap<unsigned, String>::const_iterator it; + bool contains = false; + if (sessionIterator != m_hashToOriginMap.end()) { + it = sessionIterator->value.find(plugInOriginHash); + contains = it != sessionIterator->value.end(); + } + if (!contains) { + sessionIterator = m_hashToOriginMap.find(SessionID::defaultSessionID()); + it = sessionIterator->value.find(plugInOriginHash); + if (it == sessionIterator->value.end()) { + ASSERT_NOT_REACHED(); + return; + } } double newExpirationTime = expirationTimeFromNow(); - m_autoStartTable.find(it->value)->value.set(plugInOriginHash, newExpirationTime); - m_context->sendToAllProcesses(Messages::WebProcess::DidAddPlugInAutoStartOriginHash(plugInOriginHash, newExpirationTime)); - m_context->client().plugInAutoStartOriginHashesChanged(m_context); + m_autoStartTable.add(sessionID, AutoStartTable()).iterator->value.add(it->value, PlugInAutoStartOriginMap()).iterator->value.set(plugInOriginHash, newExpirationTime); + m_processPool->sendToAllProcesses(Messages::WebProcess::DidAddPlugInAutoStartOriginHash(plugInOriginHash, newExpirationTime, sessionID)); + m_processPool->client().plugInAutoStartOriginHashesChanged(m_processPool); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.h b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.h index 87c81fe3a..fe6bc6f56 100644 --- a/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.h +++ b/Source/WebKit2/UIProcess/Plugins/PlugInAutoStartProvider.h @@ -26,6 +26,8 @@ #ifndef PlugInAutoStartProvider_h #define PlugInAutoStartProvider_h +#include <WebCore/SessionID.h> +#include <functional> #include <wtf/HashMap.h> #include <wtf/HashSet.h> #include <wtf/Noncopyable.h> @@ -33,37 +35,45 @@ #include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> +namespace API { +class Array; +class Dictionary; +} + namespace WebKit { -class ImmutableArray; -class ImmutableDictionary; -class WebContext; +class WebProcessPool; -typedef HashMap<unsigned, double> PlugInAutoStartOriginHash; +typedef HashMap<unsigned, double> PlugInAutoStartOriginMap; +typedef HashMap<WebCore::SessionID, PlugInAutoStartOriginMap> SessionPlugInAutoStartOriginMap; typedef Vector<String> PlugInAutoStartOrigins; class PlugInAutoStartProvider { WTF_MAKE_NONCOPYABLE(PlugInAutoStartProvider); public: - explicit PlugInAutoStartProvider(WebContext*); + explicit PlugInAutoStartProvider(WebProcessPool*); - void addAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash); - void didReceiveUserInteraction(unsigned plugInOriginHash); + void addAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, WebCore::SessionID); + void didReceiveUserInteraction(unsigned plugInOriginHash, WebCore::SessionID); - PassRefPtr<ImmutableDictionary> autoStartOriginsTableCopy() const; - void setAutoStartOriginsTable(ImmutableDictionary&); - void setAutoStartOriginsArray(ImmutableArray&); + Ref<API::Dictionary> autoStartOriginsTableCopy() const; + void setAutoStartOriginsTable(API::Dictionary&); + void setAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, double time); + void setAutoStartOriginsArray(API::Array&); - PlugInAutoStartOriginHash autoStartOriginHashesCopy() const; + SessionPlugInAutoStartOriginMap autoStartOriginHashesCopy() const; const PlugInAutoStartOrigins& autoStartOrigins() const { return m_autoStartOrigins; } private: - WebContext* m_context; + WebProcessPool* m_processPool; + + void setAutoStartOriginsTableWithItemsPassingTest(API::Dictionary&, std::function<bool(double expirationTimestamp)>); - typedef HashMap<String, PlugInAutoStartOriginHash, CaseFoldingHash> AutoStartTable; - AutoStartTable m_autoStartTable; + typedef HashMap<String, PlugInAutoStartOriginMap, ASCIICaseInsensitiveHash> AutoStartTable; + typedef HashMap<WebCore::SessionID, AutoStartTable> SessionAutoStartTable; + SessionAutoStartTable m_autoStartTable; - HashMap<unsigned, String> m_hashToOriginMap; + HashMap<WebCore::SessionID, HashMap<unsigned, String>> m_hashToOriginMap; PlugInAutoStartOrigins m_autoStartOrigins; }; diff --git a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp index ae95a0b68..294c77117 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.cpp @@ -29,7 +29,7 @@ #if ENABLE(NETSCAPE_PLUGIN_API) #include "PluginModuleInfo.h" -#include <WebCore/KURL.h> +#include <WebCore/URL.h> #include <WebCore/MIMETypeRegistry.h> #include <algorithm> #include <wtf/ListHashSet.h> @@ -66,9 +66,9 @@ static void addFromVector(T& hashSet, const U& vector) // We use a ListHashSet so that plugins will be loaded from the additional plugins directories first // (which in turn means those plugins will be preferred if two plugins claim the same MIME type). #if OS(WINDOWS) -typedef ListHashSet<String, 32, CaseFoldingHash> PathHashSet; +typedef ListHashSet<String, ASCIICaseInsensitiveHash> PathHashSet; #else -typedef ListHashSet<String, 32> PathHashSet; +typedef ListHashSet<String> PathHashSet; #endif void PluginInfoStore::loadPluginsIfNecessary() @@ -92,8 +92,7 @@ void PluginInfoStore::loadPluginsIfNecessary() m_plugins.clear(); - PathHashSet::const_iterator end = uniquePluginPaths.end(); - for (PathHashSet::const_iterator it = uniquePluginPaths.begin(); it != end; ++it) + for (const auto& pluginPath : uniquePluginPaths) loadPlugin(m_plugins, *it); m_pluginListIsUpToDate = true; @@ -124,15 +123,12 @@ Vector<PluginModuleInfo> PluginInfoStore::plugins() PluginModuleInfo PluginInfoStore::findPluginForMIMEType(const String& mimeType, PluginData::AllowedPluginTypes allowedPluginTypes) const { ASSERT(!mimeType.isNull()); - - for (size_t i = 0; i < m_plugins.size(); ++i) { - const PluginModuleInfo& plugin = m_plugins[i]; + for (const auto& plugin : m_plugins) { if (allowedPluginTypes == PluginData::OnlyApplicationPlugins && !plugin.info.isApplicationPlugin) continue; - - for (size_t j = 0; j < plugin.info.mimes.size(); ++j) { - const MimeClassInfo& mimeClassInfo = plugin.info.mimes[j]; + + for (const auto& mimeClassInfo : plugin.info.mimes) { if (mimeClassInfo.type == mimeType) return plugin; } @@ -144,19 +140,13 @@ PluginModuleInfo PluginInfoStore::findPluginForMIMEType(const String& mimeType, PluginModuleInfo PluginInfoStore::findPluginForExtension(const String& extension, String& mimeType, PluginData::AllowedPluginTypes allowedPluginTypes) const { ASSERT(!extension.isNull()); - - for (size_t i = 0; i < m_plugins.size(); ++i) { - const PluginModuleInfo& plugin = m_plugins[i]; + for (const auto& plugin : m_plugins) { if (allowedPluginTypes == PluginData::OnlyApplicationPlugins && !plugin.info.isApplicationPlugin) continue; - for (size_t j = 0; j < plugin.info.mimes.size(); ++j) { - const MimeClassInfo& mimeClassInfo = plugin.info.mimes[j]; - - const Vector<String>& extensions = mimeClassInfo.extensions; - - if (std::find(extensions.begin(), extensions.end(), extension) != extensions.end()) { + for (const auto& mimeClassInfo : plugin.info.mimes) { + if (mimeClassInfo.extensions.contains(extension)) { // We found a supported extension, set the correct MIME type. mimeType = mimeClassInfo.type; return plugin; @@ -167,29 +157,24 @@ PluginModuleInfo PluginInfoStore::findPluginForExtension(const String& extension return PluginModuleInfo(); } -static inline String pathExtension(const KURL& url) +static inline String pathExtension(const URL& url) { String extension; String filename = url.lastPathComponent(); if (!filename.endsWith('/')) { - int extensionPos = filename.reverseFind('.'); - if (extensionPos != -1) + size_t extensionPos = filename.reverseFind('.'); + if (extensionPos != notFound) extension = filename.substring(extensionPos + 1); } - - return extension; + return extension.convertToASCIILowercase(); } -#if !PLATFORM(MAC) +#if !PLATFORM(COCOA) + PluginModuleLoadPolicy PluginInfoStore::defaultLoadPolicyForPlugin(const PluginModuleInfo&) { return PluginModuleLoadNormally; } - -String PluginInfoStore::getMIMETypeForExtension(const String& extension) -{ - return MIMETypeRegistry::getMIMETypeForExtension(extension); -} PluginModuleInfo PluginInfoStore::findPluginWithBundleIdentifier(const String&) { @@ -199,7 +184,7 @@ PluginModuleInfo PluginInfoStore::findPluginWithBundleIdentifier(const String&) #endif -PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url, PluginData::AllowedPluginTypes allowedPluginTypes) +PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const URL& url, PluginData::AllowedPluginTypes allowedPluginTypes) { loadPluginsIfNecessary(); @@ -211,14 +196,14 @@ PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url, } // Next, check if any plug-ins claim to support the URL extension. - String extension = pathExtension(url).lower(); + String extension = pathExtension(url); if (!extension.isNull() && mimeType.isEmpty()) { PluginModuleInfo plugin = findPluginForExtension(extension, mimeType, allowedPluginTypes); if (!plugin.path.isNull()) return plugin; // Finally, try to get the MIME type from the extension in a platform specific manner and use that. - String extensionMimeType = getMIMETypeForExtension(extension); + String extensionMimeType = MIMETypeRegistry::getMIMETypeForExtension(extension); if (!extensionMimeType.isNull()) { PluginModuleInfo plugin = findPluginForMIMEType(extensionMimeType, allowedPluginTypes); if (!plugin.path.isNull()) { @@ -233,11 +218,11 @@ PluginModuleInfo PluginInfoStore::findPlugin(String& mimeType, const KURL& url, PluginModuleInfo PluginInfoStore::infoForPluginWithPath(const String& pluginPath) const { - for (size_t i = 0; i < m_plugins.size(); ++i) { - if (m_plugins[i].path == pluginPath) - return m_plugins[i]; + for (const auto& plugin : m_plugins) { + if (plugin.path == pluginPath) + return plugin; } - + ASSERT_NOT_REACHED(); return PluginModuleInfo(); } diff --git a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h index c49cea7b9..7b4f509c7 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h +++ b/Source/WebKit2/UIProcess/Plugins/PluginInfoStore.h @@ -33,7 +33,7 @@ #include <WebCore/PluginData.h> namespace WebCore { - class KURL; + class URL; } namespace WebKit { @@ -63,7 +63,7 @@ public: // Returns the info for a plug-in that can handle the given MIME type. // If the MIME type is null, the file extension of the given url will be used to infer the // plug-in type. In that case, mimeType will be filled in with the right MIME type. - PluginModuleInfo findPlugin(String& mimeType, const WebCore::KURL&, WebCore::PluginData::AllowedPluginTypes = WebCore::PluginData::AllPlugins); + PluginModuleInfo findPlugin(String& mimeType, const WebCore::URL&, WebCore::PluginData::AllowedPluginTypes = WebCore::PluginData::AllPlugins); // Returns the info for the plug-in with the given bundle identifier. PluginModuleInfo findPluginWithBundleIdentifier(const String& bundleIdentifier); @@ -100,9 +100,6 @@ private: // Return whether this plug-in should be used (added to the list of plug-ins) or not. static bool shouldUsePlugin(Vector<PluginModuleInfo>& alreadyLoadedPlugins, const PluginModuleInfo&); - // Get the MIME type for the given extension. - static String getMIMETypeForExtension(const String& extension); - Vector<String> m_additionalPluginsDirectories; Vector<PluginModuleInfo> m_plugins; bool m_pluginListIsUpToDate; diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp index e89accaf4..47eaa0950 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.cpp @@ -26,23 +26,25 @@ #include "config.h" #include "PluginProcessManager.h" -#if ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) #include "PluginProcessProxy.h" -#include "WebContext.h" #include <wtf/CryptographicallyRandomNumber.h> #include <wtf/StdLibExtras.h> #include <wtf/text/WTFString.h> namespace WebKit { -PluginProcessManager& PluginProcessManager::shared() +PluginProcessManager& PluginProcessManager::singleton() { - DEFINE_STATIC_LOCAL(PluginProcessManager, pluginProcessManager, ()); + static NeverDestroyed<PluginProcessManager> pluginProcessManager; return pluginProcessManager; } PluginProcessManager::PluginProcessManager() +#if PLATFORM(COCOA) + : m_processSuppressionDisabledForPageCounter([this](bool value) { updateProcessSuppressionDisabled(value); }) +#endif { } @@ -71,11 +73,7 @@ uint64_t PluginProcessManager::pluginProcessToken(const PluginModuleInfo& plugin attributes.processType = pluginProcessType; attributes.sandboxPolicy = pluginProcessSandboxPolicy; -#if COMPILER_SUPPORTS(CXX_RVALUE_REFERENCES) - m_pluginProcessTokens.append(std::make_pair(std::move(attributes), token)); -#else - m_pluginProcessTokens.append(std::make_pair(attributes, token)); -#endif + m_pluginProcessTokens.append(std::make_pair(WTFMove(attributes), token)); m_knownTokens.add(token); return token; @@ -97,16 +95,24 @@ void PluginProcessManager::removePluginProcessProxy(PluginProcessProxy* pluginPr m_pluginProcesses.remove(vectorIndex); } -void PluginProcessManager::getSitesWithData(const PluginModuleInfo& plugin, WebPluginSiteDataManager* webPluginSiteDataManager, uint64_t callbackID) +void PluginProcessManager::fetchWebsiteData(const PluginModuleInfo& plugin, std::function<void (Vector<String>)> completionHandler) +{ + PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(pluginProcessToken(plugin, PluginProcessTypeNormal, PluginProcessSandboxPolicyNormal)); + + pluginProcess->fetchWebsiteData(WTFMove(completionHandler)); +} + +void PluginProcessManager::deleteWebsiteData(const PluginModuleInfo& plugin, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler) { PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(pluginProcessToken(plugin, PluginProcessTypeNormal, PluginProcessSandboxPolicyNormal)); - pluginProcess->getSitesWithData(webPluginSiteDataManager, callbackID); + + pluginProcess->deleteWebsiteData(modifiedSince, WTFMove(completionHandler)); } -void PluginProcessManager::clearSiteData(const PluginModuleInfo& plugin, WebPluginSiteDataManager* webPluginSiteDataManager, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID) +void PluginProcessManager::deleteWebsiteDataForHostNames(const PluginModuleInfo& plugin, const Vector<String>& hostNames, std::function<void ()> completionHandler) { PluginProcessProxy* pluginProcess = getOrCreatePluginProcess(pluginProcessToken(plugin, PluginProcessTypeNormal, PluginProcessSandboxPolicyNormal)); - pluginProcess->clearSiteData(webPluginSiteDataManager, sites, flags, maxAgeInSeconds, callbackID); + pluginProcess->deleteWebsiteDataForHostNames(hostNames, WTFMove(completionHandler)); } PluginProcessProxy* PluginProcessManager::getOrCreatePluginProcess(uint64_t pluginProcessToken) @@ -117,7 +123,7 @@ PluginProcessProxy* PluginProcessManager::getOrCreatePluginProcess(uint64_t plug } for (size_t i = 0; i < m_pluginProcessTokens.size(); ++i) { - std::pair<PluginProcessAttributes, uint64_t>& attributesAndToken = m_pluginProcessTokens[i]; + auto& attributesAndToken = m_pluginProcessTokens[i]; if (attributesAndToken.second == pluginProcessToken) { RefPtr<PluginProcessProxy> pluginProcess = PluginProcessProxy::create(this, attributesAndToken.first, attributesAndToken.second); PluginProcessProxy* pluginProcessPtr = pluginProcess.get(); @@ -127,9 +133,9 @@ PluginProcessProxy* PluginProcessManager::getOrCreatePluginProcess(uint64_t plug } } - return 0; + return nullptr; } } // namespace WebKit -#endif // ENABLE(PLUGIN_PROCESS) +#endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h index 0ffd4099a..8152125da 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessManager.h @@ -26,18 +26,21 @@ #ifndef PluginProcessManager_h #define PluginProcessManager_h -#if ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) #include "PluginModuleInfo.h" #include "PluginProcess.h" #include "PluginProcessAttributes.h" +#include "ProcessThrottler.h" #include "WebProcessProxyMessages.h" #include <wtf/Forward.h> #include <wtf/HashSet.h> +#include <wtf/NeverDestroyed.h> #include <wtf/Noncopyable.h> +#include <wtf/RefCounter.h> #include <wtf/Vector.h> -namespace CoreIPC { +namespace IPC { class ArgumentEncoder; } @@ -46,23 +49,26 @@ namespace WebKit { class PluginInfoStore; class PluginProcessProxy; class WebProcessProxy; -class WebPluginSiteDataManager; class PluginProcessManager { WTF_MAKE_NONCOPYABLE(PluginProcessManager); + friend class NeverDestroyed<PluginProcessManager>; public: - static PluginProcessManager& shared(); + static PluginProcessManager& singleton(); uint64_t pluginProcessToken(const PluginModuleInfo&, PluginProcessType, PluginProcessSandboxPolicy); void getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); void removePluginProcessProxy(PluginProcessProxy*); - void getSitesWithData(const PluginModuleInfo&, WebPluginSiteDataManager*, uint64_t callbackID); - void clearSiteData(const PluginModuleInfo&, WebPluginSiteDataManager*, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID); + void fetchWebsiteData(const PluginModuleInfo&, std::function<void (Vector<String>)> completionHandler); + void deleteWebsiteData(const PluginModuleInfo&, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler); + void deleteWebsiteDataForHostNames(const PluginModuleInfo&, const Vector<String>& hostNames, std::function<void ()> completionHandler); -#if PLATFORM(MAC) - void setProcessSuppressionEnabled(bool); +#if PLATFORM(COCOA) + inline ProcessSuppressionDisabledToken processSuppressionDisabledToken(); + inline bool processSuppressionDisabled() const; + void updateProcessSuppressionDisabled(bool); #endif private: @@ -70,14 +76,30 @@ private: PluginProcessProxy* getOrCreatePluginProcess(uint64_t pluginProcessToken); - Vector<std::pair<PluginProcessAttributes, uint64_t> > m_pluginProcessTokens; + Vector<std::pair<PluginProcessAttributes, uint64_t>> m_pluginProcessTokens; HashSet<uint64_t> m_knownTokens; - Vector<RefPtr<PluginProcessProxy> > m_pluginProcesses; + Vector<RefPtr<PluginProcessProxy>> m_pluginProcesses; + +#if PLATFORM(COCOA) + RefCounter m_processSuppressionDisabledForPageCounter; +#endif }; +#if PLATFORM(COCOA) +inline ProcessSuppressionDisabledToken PluginProcessManager::processSuppressionDisabledToken() +{ + return m_processSuppressionDisabledForPageCounter.token<ProcessSuppressionDisabledTokenType>(); +} + +inline bool PluginProcessManager::processSuppressionDisabled() const +{ + return m_processSuppressionDisabledForPageCounter.value(); +} +#endif + } // namespace WebKit -#endif // ENABLE(PLUGIN_PROCESS) +#endif // ENABLE(NETSCAPE_PLUGIN_API) #endif // PluginProcessManager_h diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp index 107ad1633..62c75e45c 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.cpp @@ -26,22 +26,17 @@ #include "config.h" #include "PluginProcessProxy.h" -#if ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) #include "PluginProcessConnectionManagerMessages.h" #include "PluginProcessCreationParameters.h" #include "PluginProcessManager.h" #include "PluginProcessMessages.h" -#include "WebContext.h" #include "WebCoreArgumentCoders.h" -#include "WebPluginSiteDataManager.h" +#include "WebProcessPool.h" #include "WebProcessProxy.h" #include <WebCore/NotImplemented.h> -#include <WebCore/RunLoop.h> - -#if PLATFORM(MAC) -#include "MachPort.h" -#endif +#include <wtf/RunLoop.h> using namespace WebCore; @@ -53,9 +48,16 @@ static const double snapshottingMinimumLifetime = 30; static const double shutdownTimeout = 1 * 60; static const double snapshottingShutdownTimeout = 15; -PassRefPtr<PluginProcessProxy> PluginProcessProxy::create(PluginProcessManager* PluginProcessManager, const PluginProcessAttributes& pluginProcessAttributes, uint64_t pluginProcessToken) +static uint64_t generateCallbackID() { - return adoptRef(new PluginProcessProxy(PluginProcessManager, pluginProcessAttributes, pluginProcessToken)); + static uint64_t callbackID; + + return ++callbackID; +} + +Ref<PluginProcessProxy> PluginProcessProxy::create(PluginProcessManager* PluginProcessManager, const PluginProcessAttributes& pluginProcessAttributes, uint64_t pluginProcessToken) +{ + return adoptRef(*new PluginProcessProxy(PluginProcessManager, pluginProcessAttributes, pluginProcessToken)); } PluginProcessProxy::PluginProcessProxy(PluginProcessManager* PluginProcessManager, const PluginProcessAttributes& pluginProcessAttributes, uint64_t pluginProcessToken) @@ -63,7 +65,7 @@ PluginProcessProxy::PluginProcessProxy(PluginProcessManager* PluginProcessManage , m_pluginProcessAttributes(pluginProcessAttributes) , m_pluginProcessToken(pluginProcessToken) , m_numPendingConnectionRequests(0) -#if PLATFORM(MAC) +#if PLATFORM(COCOA) , m_modalWindowIsShowing(false) , m_fullscreenWindowIsShowing(false) , m_preFullscreenAppPresentationOptions(0) @@ -74,61 +76,76 @@ PluginProcessProxy::PluginProcessProxy(PluginProcessManager* PluginProcessManage PluginProcessProxy::~PluginProcessProxy() { + ASSERT(m_pendingFetchWebsiteDataRequests.isEmpty()); + ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataRequests.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty()); } void PluginProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) { - launchOptions.processType = ProcessLauncher::PluginProcess; + ChildProcessProxy::getLaunchOptions(launchOptions); platformGetLaunchOptions(launchOptions, m_pluginProcessAttributes); } +void PluginProcessProxy::processWillShutDown(IPC::Connection& connection) +{ + ASSERT_UNUSED(connection, this->connection() == &connection); +} + // Asks the plug-in process to create a new connection to a web process. The connection identifier will be // encoded in the given argument encoder and sent back to the connection of the given web process. void PluginProcessProxy::getPluginProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) { m_pendingConnectionReplies.append(reply); - if (isLaunching()) { + if (state() == State::Launching) { m_numPendingConnectionRequests++; return; } // Ask the plug-in process to create a connection. Since the plug-in can be waiting for a synchronous reply // we need to make sure that this message is always processed, even when the plug-in is waiting for a synchronus reply. - m_connection->send(Messages::PluginProcess::CreateWebProcessConnection(), 0, CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); + m_connection->send(Messages::PluginProcess::CreateWebProcessConnection(), 0, IPC::DispatchMessageEvenWhenWaitingForSyncReply); } -void PluginProcessProxy::getSitesWithData(WebPluginSiteDataManager* webPluginSiteDataManager, uint64_t callbackID) +void PluginProcessProxy::fetchWebsiteData(std::function<void (Vector<String>)> completionHandler) { - ASSERT(!m_pendingGetSitesReplies.contains(callbackID)); - m_pendingGetSitesReplies.set(callbackID, webPluginSiteDataManager); + uint64_t callbackID = generateCallbackID(); + m_pendingFetchWebsiteDataCallbacks.set(callbackID, WTFMove(completionHandler)); - if (isLaunching()) { - m_pendingGetSitesRequests.append(callbackID); + if (state() == State::Launching) { + m_pendingFetchWebsiteDataRequests.append(callbackID); return; } - // Ask the plug-in process for the sites with data. m_connection->send(Messages::PluginProcess::GetSitesWithData(callbackID), 0); } -void PluginProcessProxy::clearSiteData(WebPluginSiteDataManager* webPluginSiteDataManager, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID) +void PluginProcessProxy::deleteWebsiteData(std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler) { - ASSERT(!m_pendingClearSiteDataReplies.contains(callbackID)); - m_pendingClearSiteDataReplies.set(callbackID, webPluginSiteDataManager); - - if (isLaunching()) { - ClearSiteDataRequest request; - request.sites = sites; - request.flags = flags; - request.maxAgeInSeconds = maxAgeInSeconds; - request.callbackID = callbackID; - m_pendingClearSiteDataRequests.append(request); + uint64_t callbackID = generateCallbackID(); + m_pendingDeleteWebsiteDataCallbacks.set(callbackID, WTFMove(completionHandler)); + + if (state() == State::Launching) { + m_pendingDeleteWebsiteDataRequests.append({ modifiedSince, callbackID }); return; } - // Ask the plug-in process to clear the site data. - m_connection->send(Messages::PluginProcess::ClearSiteData(sites, flags, maxAgeInSeconds, callbackID), 0); + m_connection->send(Messages::PluginProcess::DeleteWebsiteData(modifiedSince, callbackID), 0); +} + +void PluginProcessProxy::deleteWebsiteDataForHostNames(const Vector<String>& hostNames, std::function<void ()> completionHandler) +{ + uint64_t callbackID = generateCallbackID(); + m_pendingDeleteWebsiteDataForHostNamesCallbacks.set(callbackID, WTFMove(completionHandler)); + + if (state() == State::Launching) { + m_pendingDeleteWebsiteDataForHostNamesRequests.append({ hostNames, callbackID }); + return; + } + + m_connection->send(Messages::PluginProcess::DeleteWebsiteDataForHostNames(hostNames, callbackID), 0); } void PluginProcessProxy::pluginProcessCrashedOrFailedToLaunch() @@ -137,28 +154,37 @@ void PluginProcessProxy::pluginProcessCrashedOrFailedToLaunch() while (!m_pendingConnectionReplies.isEmpty()) { RefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); -#if PLATFORM(MAC) - reply->send(CoreIPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND), false); -#elif USE(UNIX_DOMAIN_SOCKETS) - reply->send(CoreIPC::Attachment(), false); +#if USE(UNIX_DOMAIN_SOCKETS) + reply->send(IPC::Attachment(), false); +#elif OS(DARWIN) + reply->send(IPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND), false); #else notImplemented(); #endif } - while (!m_pendingGetSitesReplies.isEmpty()) - didGetSitesWithData(Vector<String>(), m_pendingGetSitesReplies.begin()->key); + m_pendingFetchWebsiteDataRequests.clear(); + for (const auto& callback : m_pendingFetchWebsiteDataCallbacks.values()) + callback({ }); + m_pendingFetchWebsiteDataCallbacks.clear(); + + m_pendingDeleteWebsiteDataRequests.clear(); + for (const auto& callback : m_pendingDeleteWebsiteDataCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataRequests.clear(); - while (!m_pendingClearSiteDataReplies.isEmpty()) - didClearSiteData(m_pendingClearSiteDataReplies.begin()->key); + m_pendingDeleteWebsiteDataForHostNamesRequests.clear(); + for (const auto& callback : m_pendingDeleteWebsiteDataForHostNamesCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataForHostNamesCallbacks.clear(); // Tell the plug-in process manager to forget about this plug-in process proxy. This may cause us to be deleted. m_pluginProcessManager->removePluginProcessProxy(this); } -void PluginProcessProxy::didClose(CoreIPC::Connection*) +void PluginProcessProxy::didClose(IPC::Connection&) { -#if PLATFORM(MAC) +#if PLATFORM(COCOA) if (m_modalWindowIsShowing) endModal(); @@ -166,29 +192,29 @@ void PluginProcessProxy::didClose(CoreIPC::Connection*) exitFullscreen(); #endif - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0; i < contexts.size(); ++i) - contexts[i]->sendToAllProcesses(Messages::PluginProcessConnectionManager::PluginProcessCrashed(m_pluginProcessToken)); + const Vector<WebProcessPool*>& processPools = WebProcessPool::allProcessPools(); + for (size_t i = 0; i < processPools.size(); ++i) + processPools[i]->sendToAllProcesses(Messages::PluginProcessConnectionManager::PluginProcessCrashed(m_pluginProcessToken)); // This will cause us to be deleted. pluginProcessCrashedOrFailedToLaunch(); } -void PluginProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference, CoreIPC::StringReference) +void PluginProcessProxy::didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference, IPC::StringReference) { } -void PluginProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier connectionIdentifier) +void PluginProcessProxy::didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier connectionIdentifier) { ASSERT(!m_connection); - if (CoreIPC::Connection::identifierIsNull(connectionIdentifier)) { + if (IPC::Connection::identifierIsNull(connectionIdentifier)) { pluginProcessCrashedOrFailedToLaunch(); return; } - m_connection = CoreIPC::Connection::createServerConnection(connectionIdentifier, this, RunLoop::main()); -#if PLATFORM(MAC) + m_connection = IPC::Connection::createServerConnection(connectionIdentifier, *this); +#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED <= 101000 m_connection->setShouldCloseConnectionOnMachExceptions(); #elif PLATFORM(QT) m_connection->setShouldCloseConnectionOnProcessTermination(processIdentifier()); @@ -210,39 +236,44 @@ void PluginProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connectio // Initialize the plug-in host process. m_connection->send(Messages::PluginProcess::InitializePluginProcess(parameters), 0); - // Send all our pending requests. - for (size_t i = 0; i < m_pendingGetSitesRequests.size(); ++i) - m_connection->send(Messages::PluginProcess::GetSitesWithData(m_pendingGetSitesRequests[i]), 0); - m_pendingGetSitesRequests.clear(); +#if PLATFORM(COCOA) + m_connection->send(Messages::PluginProcess::SetQOS(pluginProcessLatencyQOS(), pluginProcessThroughputQOS()), 0); +#endif + + for (auto callbackID : m_pendingFetchWebsiteDataRequests) + m_connection->send(Messages::PluginProcess::GetSitesWithData(callbackID), 0); + m_pendingFetchWebsiteDataRequests.clear(); - for (size_t i = 0; i < m_pendingClearSiteDataRequests.size(); ++i) { - const ClearSiteDataRequest& request = m_pendingClearSiteDataRequests[i]; - m_connection->send(Messages::PluginProcess::ClearSiteData(request.sites, request.flags, request.maxAgeInSeconds, request.callbackID), 0); - } - m_pendingClearSiteDataRequests.clear(); + for (auto& request : m_pendingDeleteWebsiteDataRequests) + m_connection->send(Messages::PluginProcess::DeleteWebsiteData(request.modifiedSince, request.callbackID), 0); + m_pendingDeleteWebsiteDataRequests.clear(); + + for (auto& request : m_pendingDeleteWebsiteDataForHostNamesRequests) + m_connection->send(Messages::PluginProcess::DeleteWebsiteDataForHostNames(request.hostNames, request.callbackID), 0); + m_pendingDeleteWebsiteDataForHostNamesRequests.clear(); for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i) m_connection->send(Messages::PluginProcess::CreateWebProcessConnection(), 0); m_numPendingConnectionRequests = 0; -#if PLATFORM(MAC) - if (WebContext::canEnableProcessSuppressionForGlobalChildProcesses()) +#if PLATFORM(COCOA) + if (!PluginProcessManager::singleton().processSuppressionDisabled()) setProcessSuppressionEnabled(true); #endif } -void PluginProcessProxy::didCreateWebProcessConnection(const CoreIPC::Attachment& connectionIdentifier, bool supportsAsynchronousPluginInitialization) +void PluginProcessProxy::didCreateWebProcessConnection(const IPC::Attachment& connectionIdentifier, bool supportsAsynchronousPluginInitialization) { ASSERT(!m_pendingConnectionReplies.isEmpty()); // Grab the first pending connection reply. RefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); -#if PLATFORM(MAC) - reply->send(CoreIPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND), supportsAsynchronousPluginInitialization); -#elif USE(UNIX_DOMAIN_SOCKETS) +#if USE(UNIX_DOMAIN_SOCKETS) reply->send(connectionIdentifier, supportsAsynchronousPluginInitialization); +#elif OS(DARWIN) + reply->send(IPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND), supportsAsynchronousPluginInitialization); #else notImplemented(); #endif @@ -250,20 +281,22 @@ void PluginProcessProxy::didCreateWebProcessConnection(const CoreIPC::Attachment void PluginProcessProxy::didGetSitesWithData(const Vector<String>& sites, uint64_t callbackID) { - RefPtr<WebPluginSiteDataManager> webPluginSiteDataManager = m_pendingGetSitesReplies.take(callbackID); - ASSERT(webPluginSiteDataManager); + auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID); + callback(sites); +} - webPluginSiteDataManager->didGetSitesWithDataForSinglePlugin(sites, callbackID); +void PluginProcessProxy::didDeleteWebsiteData(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID); + callback(); } -void PluginProcessProxy::didClearSiteData(uint64_t callbackID) +void PluginProcessProxy::didDeleteWebsiteDataForHostNames(uint64_t callbackID) { - RefPtr<WebPluginSiteDataManager> webPluginSiteDataManager = m_pendingClearSiteDataReplies.take(callbackID); - ASSERT(webPluginSiteDataManager); - - webPluginSiteDataManager->didClearSiteDataForSinglePlugin(callbackID); + auto callback = m_pendingDeleteWebsiteDataForHostNamesCallbacks.take(callbackID); + callback(); } } // namespace WebKit -#endif // ENABLE(PLUGIN_PROCESS) +#endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h index a76cba196..b43b78353 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.h @@ -26,7 +26,7 @@ #ifndef PluginProcessProxy_h #define PluginProcessProxy_h -#if ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) #include "ChildProcessProxy.h" #include "Connection.h" @@ -37,21 +37,15 @@ #include "WebProcessProxyMessages.h" #include <wtf/Deque.h> -#if PLATFORM(MAC) +#if PLATFORM(COCOA) #include <wtf/RetainPtr.h> OBJC_CLASS NSObject; OBJC_CLASS WKPlaceholderModalWindow; #endif -// FIXME: This is platform specific. -namespace CoreIPC { - class MachPort; -} - namespace WebKit { class PluginProcessManager; -class WebPluginSiteDataManager; class WebProcessProxy; struct PluginProcessCreationParameters; @@ -60,12 +54,21 @@ struct RawPluginMetaData { String name; String description; String mimeDescription; + +#if PLATFORM(GTK) + bool requiresGtk2; +#endif }; #endif +#if PLATFORM(COCOA) +int pluginProcessLatencyQOS(); +int pluginProcessThroughputQOS(); +#endif + class PluginProcessProxy : public ChildProcessProxy { public: - static PassRefPtr<PluginProcessProxy> create(PluginProcessManager*, const PluginProcessAttributes&, uint64_t pluginProcessToken); + static Ref<PluginProcessProxy> create(PluginProcessManager*, const PluginProcessAttributes&, uint64_t pluginProcessToken); ~PluginProcessProxy(); const PluginProcessAttributes& pluginProcessAttributes() const { return m_pluginProcessAttributes; } @@ -74,25 +77,23 @@ public: // Asks the plug-in process to create a new connection to a web process. The connection identifier will be // encoded in the given argument encoder and sent back to the connection of the given web process. void getPluginProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); - - // Asks the plug-in process to get a list of domains for which the plug-in has data stored. - void getSitesWithData(WebPluginSiteDataManager*, uint64_t callbackID); - // Asks the plug-in process to clear the data for the given sites. - void clearSiteData(WebPluginSiteDataManager*, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID); + void fetchWebsiteData(std::function<void (Vector<String>)> completionHandler); + void deleteWebsiteData(std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler); + void deleteWebsiteDataForHostNames(const Vector<String>& hostNames, std::function<void ()> completionHandler); bool isValid() const { return m_connection; } -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void setProcessSuppressionEnabled(bool); - // Returns whether the plug-in needs the heap to be marked executable. - static bool pluginNeedsExecutableHeap(const PluginModuleInfo&); - +#if __MAC_OS_X_VERSION_MIN_REQUIRED <= 101000 // Creates a property list in ~/Library/Preferences that contains all the MIME types supported by the plug-in. static bool createPropertyListFile(const PluginModuleInfo&); #endif +#endif + #if PLUGIN_ARCHITECTURE(X11) static bool scanPlugin(const String& pluginPath, RawPluginMetaData& result); #endif @@ -100,27 +101,31 @@ public: private: PluginProcessProxy(PluginProcessManager*, const PluginProcessAttributes&, uint64_t pluginProcessToken); - virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) OVERRIDE; + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) override; void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&, const PluginProcessAttributes&); + virtual void processWillShutDown(IPC::Connection&) override; void pluginProcessCrashedOrFailedToLaunch(); - // CoreIPC::Connection::Client - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + // IPC::Connection::Client + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; - virtual void didClose(CoreIPC::Connection*) OVERRIDE; - virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) OVERRIDE; + virtual void didClose(IPC::Connection&) override; + virtual void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override; + virtual IPC::ProcessType localProcessType() override { return IPC::ProcessType::UI; } + virtual IPC::ProcessType remoteProcessType() override { return IPC::ProcessType::Plugin; } // ProcessLauncher::Client - virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); + virtual void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override; // Message handlers - void didCreateWebProcessConnection(const CoreIPC::Attachment&, bool supportsAsynchronousPluginInitialization); + void didCreateWebProcessConnection(const IPC::Attachment&, bool supportsAsynchronousPluginInitialization); void didGetSitesWithData(const Vector<String>& sites, uint64_t callbackID); - void didClearSiteData(uint64_t callbackID); + void didDeleteWebsiteData(uint64_t callbackID); + void didDeleteWebsiteDataForHostNames(uint64_t callbackID); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) bool getPluginProcessSerialNumber(ProcessSerialNumber&); void makePluginProcessTheFrontProcess(); void makeUIProcessTheFrontProcess(); @@ -134,10 +139,10 @@ private: void endModal(); void applicationDidBecomeActive(); - void openPluginPreferencePane(); void launchProcess(const String& launchPath, const Vector<String>& arguments, bool& result); void launchApplicationAtURL(const String& urlString, const Vector<String>& arguments, bool& result); void openURL(const String& url, bool& result, int32_t& status, String& launchedURLString); + void openFile(const String& fullPath, bool& result); #endif void platformInitializePluginProcess(PluginProcessCreationParameters& parameters); @@ -149,27 +154,32 @@ private: uint64_t m_pluginProcessToken; // The connection to the plug-in host process. - RefPtr<CoreIPC::Connection> m_connection; + RefPtr<IPC::Connection> m_connection; + + Deque<RefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>> m_pendingConnectionReplies; - Deque<RefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> > m_pendingConnectionReplies; + Vector<uint64_t> m_pendingFetchWebsiteDataRequests; + HashMap<uint64_t, std::function<void (Vector<String>)>> m_pendingFetchWebsiteDataCallbacks; - Vector<uint64_t> m_pendingGetSitesRequests; - HashMap<uint64_t, RefPtr<WebPluginSiteDataManager> > m_pendingGetSitesReplies; + struct DeleteWebsiteDataRequest { + std::chrono::system_clock::time_point modifiedSince; + uint64_t callbackID; + }; + Vector<DeleteWebsiteDataRequest> m_pendingDeleteWebsiteDataRequests; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataCallbacks; - struct ClearSiteDataRequest { - Vector<String> sites; - uint64_t flags; - uint64_t maxAgeInSeconds; + struct DeleteWebsiteDataForHostNamesRequest { + Vector<String> hostNames; uint64_t callbackID; }; - Vector<ClearSiteDataRequest> m_pendingClearSiteDataRequests; - HashMap<uint64_t, RefPtr<WebPluginSiteDataManager> > m_pendingClearSiteDataReplies; + Vector<DeleteWebsiteDataForHostNamesRequest> m_pendingDeleteWebsiteDataForHostNamesRequests; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataForHostNamesCallbacks; // If createPluginConnection is called while the process is still launching we'll keep count of it and send a bunch of requests // when the process finishes launching. unsigned m_numPendingConnectionRequests; -#if PLATFORM(MAC) +#if PLATFORM(COCOA) RetainPtr<NSObject> m_activationObserver; RetainPtr<WKPlaceholderModalWindow *> m_placeholderWindow; bool m_modalWindowIsShowing; @@ -180,6 +190,6 @@ private: } // namespace WebKit -#endif // ENABLE(PLUGIN_PROCESS) +#endif // ENABLE(NETSCAPE_PLUGIN_API) #endif // PluginProcessProxy_h diff --git a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in index aa3b106c5..e18e55eb0 100644 --- a/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/Plugins/PluginProcessProxy.messages.in @@ -20,29 +20,30 @@ # 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 ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) messages -> PluginProcessProxy { - DidCreateWebProcessConnection(CoreIPC::Attachment connectionIdentifier, bool supportsAsynchronousPluginInitialization) + DidCreateWebProcessConnection(IPC::Attachment connectionIdentifier, bool supportsAsynchronousPluginInitialization) - DidGetSitesWithData(Vector<WTF::String> sites, uint64_t callbackID) - DidClearSiteData(uint64_t callbackID) + DidGetSitesWithData(Vector<String> sites, uint64_t callbackID) + DidDeleteWebsiteData(uint64_t callbackID) + DidDeleteWebsiteDataForHostNames(uint64_t callbackID) -#if PLATFORM(MAC) +#if PLATFORM(COCOA) SetModalWindowIsShowing(bool modalWindowIsShowing) SetFullscreenWindowIsShowing(bool fullscreenWindowIsShowing) - # Open the plug-ins preference pane (as specified in the plug-in's Info.plist file). - OpenPluginPreferencePane() - # Returns true if the UI process launched the process. - LaunchProcess(WTF::String launchPath, Vector<WTF::String> arguments) -> (bool result) + LaunchProcess(String launchPath, Vector<String> arguments) -> (bool result) # Returns true if the UI process launched the application. - LaunchApplicationAtURL(WTF::String url, Vector<WTF::String> arguments) -> (bool result) + LaunchApplicationAtURL(String url, Vector<String> arguments) -> (bool result) # Returns true if the UI process did open the URL. - OpenURL(WTF::String urlString) -> (bool result, int32_t status, WTF::String launchedURLString) + OpenURL(String urlString) -> (bool result, int32_t status, String launchedURLString) + + # Returns true if the UI process did open the file. + OpenFile(String fullPath) -> (bool result) #endif } diff --git a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp b/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp deleted file mode 100644 index 1ea01a088..000000000 --- a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPluginSiteDataManager.h" - -#if ENABLE(NETSCAPE_PLUGIN_API) - -#include "ImmutableArray.h" -#include "PluginProcessManager.h" -#include "WebContext.h" -#include "WebProcessMessages.h" - -using namespace WebCore; - -namespace WebKit { - -#if ENABLE(PLUGIN_PROCESS) -class WebPluginSiteDataManager::GetSitesWithDataState { -public: - explicit GetSitesWithDataState(WebPluginSiteDataManager* webPluginSiteDataManager, uint64_t callbackID) - : m_webPluginSiteDataManager(webPluginSiteDataManager) - , m_callbackID(callbackID) - , m_plugins(webPluginSiteDataManager->m_webContext->pluginInfoStore().plugins()) - { - } - - void getSitesWithDataForNextPlugin() - { - if (m_plugins.isEmpty()) { - Vector<String> sites; - copyToVector(m_sites, sites); - - m_webPluginSiteDataManager->didGetSitesWithDataForAllPlugins(sites, m_callbackID); - return; - } - - PluginProcessManager::shared().getSitesWithData(m_plugins.last(), m_webPluginSiteDataManager, m_callbackID); - m_plugins.removeLast(); - } - - void didGetSitesWithDataForSinglePlugin(const Vector<String>& sites) - { - for (size_t i = 0; i < sites.size(); ++i) - m_sites.add(sites[i]); - - getSitesWithDataForNextPlugin(); - } - -private: - WebPluginSiteDataManager* m_webPluginSiteDataManager; - uint64_t m_callbackID; - Vector<PluginModuleInfo> m_plugins; - HashSet<String> m_sites; -}; - -class WebPluginSiteDataManager::ClearSiteDataState { -public: - explicit ClearSiteDataState(WebPluginSiteDataManager* webPluginSiteDataManager, const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID) - : m_webPluginSiteDataManager(webPluginSiteDataManager) - , m_sites(sites) - , m_flags(flags) - , m_maxAgeInSeconds(maxAgeInSeconds) - , m_callbackID(callbackID) - , m_plugins(webPluginSiteDataManager->m_webContext->pluginInfoStore().plugins()) - { - } - - void clearSiteDataForNextPlugin() - { - if (m_plugins.isEmpty()) { - m_webPluginSiteDataManager->didClearSiteDataForAllPlugins(m_callbackID); - return; - } - - PluginProcessManager::shared().clearSiteData(m_plugins.last(), m_webPluginSiteDataManager, m_sites, m_flags, m_maxAgeInSeconds, m_callbackID); - m_plugins.removeLast(); - } - - void didClearSiteDataForSinglePlugin() - { - clearSiteDataForNextPlugin(); - } - -private: - WebPluginSiteDataManager* m_webPluginSiteDataManager; - Vector<String> m_sites; - uint64_t m_flags; - uint64_t m_maxAgeInSeconds; - uint64_t m_callbackID; - Vector<PluginModuleInfo> m_plugins; -}; -#endif // ENABLE(PLUGIN_PROCESS) - -PassRefPtr<WebPluginSiteDataManager> WebPluginSiteDataManager::create(WebContext* webContext) -{ - return adoptRef(new WebPluginSiteDataManager(webContext)); -} - -WebPluginSiteDataManager::WebPluginSiteDataManager(WebContext* webContext) - : m_webContext(webContext) -{ -} - -WebPluginSiteDataManager::~WebPluginSiteDataManager() -{ - ASSERT(m_arrayCallbacks.isEmpty()); - ASSERT(m_voidCallbacks.isEmpty()); -#if ENABLE(PLUGIN_PROCESS) - ASSERT(m_pendingGetSitesWithData.isEmpty()); - ASSERT(m_pendingClearSiteData.isEmpty()); -#endif -} - -void WebPluginSiteDataManager::invalidate() -{ - invalidateCallbackMap(m_arrayCallbacks); - -#if ENABLE(PLUGIN_PROCESS) - m_pendingGetSitesWithData.clear(); - m_pendingClearSiteData.clear(); -#endif -} - -void WebPluginSiteDataManager::getSitesWithData(PassRefPtr<ArrayCallback> prpCallback) -{ - RefPtr<ArrayCallback> callback = prpCallback; - - if (!m_webContext) { - callback->invalidate(); - return; - } - - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - -#if ENABLE(PLUGIN_PROCESS) - ASSERT(!m_pendingGetSitesWithData.contains(callbackID)); - - GetSitesWithDataState* state = new GetSitesWithDataState(this, callbackID); - m_pendingGetSitesWithData.set(callbackID, adoptPtr(state)); - state->getSitesWithDataForNextPlugin(); -#else - Vector<PluginModuleInfo> plugins = m_webContext->pluginInfoStore().plugins(); - Vector<String> pluginPaths; - for (size_t i = 0; i < plugins.size(); ++i) - pluginPaths.append(plugins[i].path); - - ASSERT(m_webContext->processModel() == ProcessModelSharedSecondaryProcess); // Plugin process is required for multiple WebProcess mode. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebProcess::GetSitesWithPluginData(pluginPaths, callbackID)); -#endif -} - -void WebPluginSiteDataManager::didGetSitesWithData(const Vector<String>& sites, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - if (!callback) { - // FIXME: Log error or assert. - return; - } - - Vector<RefPtr<APIObject> > sitesWK(sites.size()); - - for (size_t i = 0; i < sites.size(); ++i) - sitesWK[i] = WebString::create(sites[i]); - - RefPtr<ImmutableArray> resultArray = ImmutableArray::adopt(sitesWK); - callback->performCallbackWithReturnValue(resultArray.get()); -} - -void WebPluginSiteDataManager::clearSiteData(ImmutableArray* sites, uint64_t flags, uint64_t maxAgeInSeconds, PassRefPtr<VoidCallback> prpCallback) -{ - RefPtr<VoidCallback> callback = prpCallback; - if (!m_webContext) { - callback->invalidate(); - return; - } - - Vector<String> sitesVector; - - // If the array is empty, don't do anything. - if (sites) { - if (!sites->size()) { - callback->performCallback(); - return; - } - - for (size_t i = 0; i < sites->size(); ++i) { - if (WebString* site = sites->at<WebString>(i)) - sitesVector.append(site->string()); - } - } - - uint64_t callbackID = callback->callbackID(); - m_voidCallbacks.set(callbackID, callback.release()); - -#if ENABLE(PLUGIN_PROCESS) - ASSERT(!m_pendingClearSiteData.contains(callbackID)); - - ClearSiteDataState* state = new ClearSiteDataState(this, sitesVector, flags, maxAgeInSeconds, callbackID); - m_pendingClearSiteData.set(callbackID, adoptPtr(state)); - state->clearSiteDataForNextPlugin(); -#else - Vector<PluginModuleInfo> plugins = m_webContext->pluginInfoStore().plugins(); - Vector<String> pluginPaths; - for (size_t i = 0; i < plugins.size(); ++i) - pluginPaths.append(plugins[i].path); - - ASSERT(m_webContext->processModel() == ProcessModelSharedSecondaryProcess); // Plugin process is required for multiple WebProcess mode. - m_webContext->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebProcess::ClearPluginSiteData(pluginPaths, sitesVector, flags, maxAgeInSeconds, callbackID)); -#endif -} - -void WebPluginSiteDataManager::didClearSiteData(uint64_t callbackID) -{ - RefPtr<VoidCallback> callback = m_voidCallbacks.take(callbackID); - if (!callback) { - // FIXME: Log error or assert. - return; - } - - callback->performCallback(); -} - -bool WebPluginSiteDataManager::shouldTerminate(WebProcessProxy*) const -{ -#if ENABLE(PLUGIN_PROCESS) - // When out of process plug-ins are enabled, the web process is not involved in fetching site data. - return true; -#else - return m_arrayCallbacks.isEmpty() && m_voidCallbacks.isEmpty(); -#endif -} - -#if ENABLE(PLUGIN_PROCESS) -void WebPluginSiteDataManager::didGetSitesWithDataForSinglePlugin(const Vector<String>& sites, uint64_t callbackID) -{ - GetSitesWithDataState* state = m_pendingGetSitesWithData.get(callbackID); - ASSERT(state); - - state->didGetSitesWithDataForSinglePlugin(sites); -} - -void WebPluginSiteDataManager::didGetSitesWithDataForAllPlugins(const Vector<String>& sites, uint64_t callbackID) -{ - OwnPtr<GetSitesWithDataState> state = m_pendingGetSitesWithData.take(callbackID); - ASSERT(state); - - didGetSitesWithData(sites, callbackID); -} - -void WebPluginSiteDataManager::didClearSiteDataForSinglePlugin(uint64_t callbackID) -{ - ClearSiteDataState* state = m_pendingClearSiteData.get(callbackID); - ASSERT(state); - - state->didClearSiteDataForSinglePlugin(); -} - -void WebPluginSiteDataManager::didClearSiteDataForAllPlugins(uint64_t callbackID) -{ - OwnPtr<ClearSiteDataState> state = m_pendingClearSiteData.take(callbackID); - ASSERT(state); - - didClearSiteData(callbackID); -} - -#endif - -} // namespace WebKit - -#endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h b/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h deleted file mode 100644 index c770f132b..000000000 --- a/Source/WebKit2/UIProcess/Plugins/WebPluginSiteDataManager.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebPluginSiteDataManager_h -#define WebPluginSiteDataManager_h - -#if ENABLE(NETSCAPE_PLUGIN_API) - -#include "APIObject.h" -#include "Arguments.h" -#include "GenericCallback.h" -#include <wtf/HashMap.h> -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -class WebContext; -class WebProcessProxy; - -typedef GenericCallback<WKArrayRef> ArrayCallback; - -class WebPluginSiteDataManager : public TypedAPIObject<APIObject::TypePluginSiteDataManager> { -public: - static PassRefPtr<WebPluginSiteDataManager> create(WebContext*); - virtual ~WebPluginSiteDataManager(); - - void invalidate(); - void clearContext() { m_webContext = 0; } - - void getSitesWithData(PassRefPtr<ArrayCallback>); - void didGetSitesWithData(const Vector<String>& sites, uint64_t callbackID); - - void clearSiteData(ImmutableArray* sites, uint64_t flags, uint64_t maxAgeInSeconds, PassRefPtr<VoidCallback>); - void didClearSiteData(uint64_t callbackID); - -#if ENABLE(PLUGIN_PROCESS) - void didGetSitesWithDataForSinglePlugin(const Vector<String>& sites, uint64_t callbackID); - void didClearSiteDataForSinglePlugin(uint64_t callbackID); -#endif - - bool shouldTerminate(WebProcessProxy*) const; - -private: - explicit WebPluginSiteDataManager(WebContext*); - - WebContext* m_webContext; - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; - HashMap<uint64_t, RefPtr<VoidCallback> > m_voidCallbacks; - -#if ENABLE(PLUGIN_PROCESS) - void didGetSitesWithDataForAllPlugins(const Vector<String>& sites, uint64_t callbackID); - void didClearSiteDataForAllPlugins(uint64_t callbackID); - - class GetSitesWithDataState; - HashMap<uint64_t, OwnPtr<GetSitesWithDataState> > m_pendingGetSitesWithData; - - class ClearSiteDataState; - HashMap<uint64_t, OwnPtr<ClearSiteDataState> > m_pendingClearSiteData; -#endif -}; - -} // namespace WebKit - -#endif // ENABLE(NETSCAPE_PLUGIN_API) - -#endif // WebPluginSiteDataManager_h diff --git a/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm b/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm deleted file mode 100644 index 61367c51b..000000000 --- a/Source/WebKit2/UIProcess/Plugins/mac/PluginInfoStoreMac.mm +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (C) 2010, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "PluginInfoStore.h" - -#if ENABLE(NETSCAPE_PLUGIN_API) - -#import "NetscapePluginModule.h" -#import "WebKitSystemInterface.h" -#import <WebCore/WebCoreNSStringExtras.h> -#import <wtf/HashSet.h> -#import <wtf/RetainPtr.h> - -using namespace WebCore; - -static const char* const oracleJavaAppletPluginBundleIdentifier = "com.oracle.java.JavaAppletPlugin"; - -namespace WebKit { - -Vector<String> PluginInfoStore::pluginsDirectories() -{ - Vector<String> pluginsDirectories; - - pluginsDirectories.append([NSHomeDirectory() stringByAppendingPathComponent:@"Library/Internet Plug-Ins"]); - pluginsDirectories.append("/Library/Internet Plug-Ins"); - - return pluginsDirectories; -} - -// FIXME: Once the UI process knows the difference between the main thread and the web thread we can drop this and just use -// String::createCFString. -static CFStringRef safeCreateCFString(const String& string) -{ - return CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(string.characters()), string.length()); -} - -Vector<String> PluginInfoStore::pluginPathsInDirectory(const String& directory) -{ - Vector<String> pluginPaths; - - RetainPtr<CFStringRef> directoryCFString = adoptCF(safeCreateCFString(directory)); - - NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:(NSString *)directoryCFString.get() error:nil]; - for (NSString *filename in filenames) - pluginPaths.append([(NSString *)directoryCFString.get() stringByAppendingPathComponent:filename]); - - return pluginPaths; -} - -Vector<String> PluginInfoStore::individualPluginPaths() -{ - return Vector<String>(); -} - -bool PluginInfoStore::getPluginInfo(const String& pluginPath, PluginModuleInfo& plugin) -{ - return NetscapePluginModule::getPluginInfo(pluginPath, plugin); -} - -static size_t findPluginWithBundleIdentifier(const Vector<PluginModuleInfo>& plugins, const String& bundleIdentifier) -{ - for (size_t i = 0; i < plugins.size(); ++i) { - if (plugins[i].bundleIdentifier == bundleIdentifier) - return i; - } - - return notFound; -} - -// Returns true if the given plug-in should be loaded, false otherwise. -static bool checkForPreferredPlugin(Vector<PluginModuleInfo>& alreadyLoadedPlugins, const PluginModuleInfo& plugin, const String& oldPluginBundleIdentifier, const String& newPluginBundleIdentifier) -{ - if (plugin.bundleIdentifier == oldPluginBundleIdentifier) { - // If we've already found the new plug-in, we don't want to load the old plug-in. - if (findPluginWithBundleIdentifier(alreadyLoadedPlugins, newPluginBundleIdentifier) != notFound) - return false; - } else if (plugin.bundleIdentifier == newPluginBundleIdentifier) { - // If we've already found the old plug-in, remove it from the list of loaded plug-ins. - size_t oldPluginIndex = findPluginWithBundleIdentifier(alreadyLoadedPlugins, oldPluginBundleIdentifier); - if (oldPluginIndex != notFound) - alreadyLoadedPlugins.remove(oldPluginIndex); - } - - return true; -} - -static bool shouldBlockPlugin(const PluginModuleInfo& plugin) -{ - return PluginInfoStore::defaultLoadPolicyForPlugin(plugin) == PluginModuleBlocked; -} - -bool PluginInfoStore::shouldUsePlugin(Vector<PluginModuleInfo>& alreadyLoadedPlugins, const PluginModuleInfo& plugin) -{ - for (size_t i = 0; i < alreadyLoadedPlugins.size(); ++i) { - const PluginModuleInfo& loadedPlugin = alreadyLoadedPlugins[i]; - - // If a plug-in with the same bundle identifier already exists, we don't want to load it. - // However, if the already existing plug-in is blocked we want to replace it with the new plug-in. - if (loadedPlugin.bundleIdentifier == plugin.bundleIdentifier) { - if (!shouldBlockPlugin(loadedPlugin)) - return false; - - alreadyLoadedPlugins.remove(i); - break; - } - } - - // Prefer the Oracle Java plug-in over the Apple java plug-in. - if (!checkForPreferredPlugin(alreadyLoadedPlugins, plugin, "com.apple.java.JavaAppletPlugin", oracleJavaAppletPluginBundleIdentifier)) - return false; - - return true; -} - -PluginModuleLoadPolicy PluginInfoStore::defaultLoadPolicyForPlugin(const PluginModuleInfo& plugin) -{ - if (WKShouldBlockPlugin(plugin.bundleIdentifier, plugin.versionString)) - return PluginModuleBlocked; - - return PluginModuleLoadNormally; -} - -String PluginInfoStore::getMIMETypeForExtension(const String& extension) -{ - // FIXME: This should just call MIMETypeRegistry::getMIMETypeForExtension and be - // strength reduced into the callsite once we can safely convert String - // to CFStringRef off the main thread. - - RetainPtr<CFStringRef> extensionCFString = adoptCF(safeCreateCFString(extension)); - return WKGetMIMETypeForExtension((NSString *)extensionCFString.get()); -} - -PluginModuleInfo PluginInfoStore::findPluginWithBundleIdentifier(const String& bundleIdentifier) -{ - loadPluginsIfNecessary(); - - for (size_t i = 0; i < m_plugins.size(); ++i) { - if (m_plugins[i].bundleIdentifier == bundleIdentifier) - return m_plugins[i]; - } - - return PluginModuleInfo(); -} - -} // namespace WebKit - -#endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm b/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm deleted file mode 100644 index 771cf7801..000000000 --- a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessManagerMac.mm +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "PluginProcessManager.h" - -#if ENABLE(PLUGIN_PROCESS) - -#import "PluginProcessProxy.h" - -namespace WebKit { - -void PluginProcessManager::setProcessSuppressionEnabled(bool processSuppressionEnabled) -{ - size_t processCount = m_pluginProcesses.size(); - for (size_t i = 0; i < processCount; ++i) - m_pluginProcesses[i]->setProcessSuppressionEnabled(processSuppressionEnabled); -} - -} // namespace WebKit - -#endif // ENABLE(PLUGIN_PROCESS) diff --git a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm b/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm deleted file mode 100644 index 4ce88b3d2..000000000 --- a/Source/WebKit2/UIProcess/Plugins/mac/PluginProcessProxyMac.mm +++ /dev/null @@ -1,477 +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. - */ - -#import "config.h" -#import "PluginProcessProxy.h" - -#if ENABLE(PLUGIN_PROCESS) - -#import "DynamicLinkerEnvironmentExtractor.h" -#import "EnvironmentVariables.h" -#import "PluginProcessCreationParameters.h" -#import "PluginProcessMessages.h" -#import "WebKitSystemInterface.h" -#import <WebCore/FileSystem.h> -#import <WebCore/KURL.h> -#import <WebCore/RuntimeApplicationChecks.h> -#import <crt_externs.h> -#import <mach-o/dyld.h> -#import <spawn.h> -#import <wtf/text/CString.h> - -#import <QuartzCore/CARemoteLayerServer.h> - -@interface WKPlaceholderModalWindow : NSWindow -@end - -@implementation WKPlaceholderModalWindow - -// Prevent NSApp from calling requestUserAttention: when the window is shown -// modally, even if the app is inactive. See 6823049. -- (BOOL)_wantsUserAttention -{ - return NO; -} - -@end - -using namespace WebCore; - -namespace WebKit { - -bool PluginProcessProxy::pluginNeedsExecutableHeap(const PluginModuleInfo& pluginInfo) -{ - static bool forceNonexecutableHeapForPlugins = [[NSUserDefaults standardUserDefaults] boolForKey:@"ForceNonexecutableHeapForPlugins"]; - if (forceNonexecutableHeapForPlugins) - return false; - - if (pluginInfo.bundleIdentifier == "com.apple.QuickTime Plugin.plugin") - return false; - - return true; -} - -bool PluginProcessProxy::createPropertyListFile(const PluginModuleInfo& plugin) -{ - NSBundle *webKit2Bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit2"]; - NSString *frameworksPath = [[webKit2Bundle bundlePath] stringByDeletingLastPathComponent]; - const char* frameworkExecutablePath = [[webKit2Bundle executablePath] fileSystemRepresentation]; - - NSString *processPath = [webKit2Bundle pathForAuxiliaryExecutable:@"PluginProcess.app"]; - NSString *processAppExecutablePath = [[NSBundle bundleWithPath:processPath] executablePath]; - - CString pluginPathString = fileSystemRepresentation(plugin.path); - - posix_spawnattr_t attr; - posix_spawnattr_init(&attr); - - cpu_type_t cpuTypes[] = { plugin.pluginArchitecture }; - size_t outCount = 0; - posix_spawnattr_setbinpref_np(&attr, 1, cpuTypes, &outCount); - - EnvironmentVariables environmentVariables; - - DynamicLinkerEnvironmentExtractor environmentExtractor([[NSBundle mainBundle] executablePath], _NSGetMachExecuteHeader()->cputype); - environmentExtractor.getExtractedEnvironmentVariables(environmentVariables); - - // To make engineering builds work, if the path is outside of /System set up - // DYLD_FRAMEWORK_PATH to pick up other frameworks, but don't do it for the - // production configuration because it involves extra file system access. - if (![frameworksPath hasPrefix:@"/System/"]) - environmentVariables.appendValue("DYLD_FRAMEWORK_PATH", [frameworksPath fileSystemRepresentation], ':'); - - const char* args[] = { [processAppExecutablePath fileSystemRepresentation], frameworkExecutablePath, "-type", "pluginprocess", "-createPluginMIMETypesPreferences", pluginPathString.data(), 0 }; - - pid_t pid; - int result = posix_spawn(&pid, args[0], 0, &attr, const_cast<char* const*>(args), environmentVariables.environmentPointer()); - posix_spawnattr_destroy(&attr); - - if (result) - return false; - int status; - if (waitpid(pid, &status, 0) < 0) - return false; - - if (!WIFEXITED(status)) - return false; - - if (WEXITSTATUS(status) != EXIT_SUCCESS) - return false; - - return true; -} - -#if HAVE(XPC) -static bool shouldUseXPC() -{ - if (id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseXPCServiceForWebProcess"]) - return [value boolValue]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - // FIXME: Temporary workaround for <rdar://problem/13236883> - if (applicationIsSafari()) - return false; - - return true; -#else - return false; -#endif -} -#endif - -void PluginProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginProcessAttributes& pluginProcessAttributes) -{ - launchOptions.architecture = pluginProcessAttributes.moduleInfo.pluginArchitecture; - launchOptions.executableHeap = PluginProcessProxy::pluginNeedsExecutableHeap(pluginProcessAttributes.moduleInfo); - launchOptions.extraInitializationData.add("plugin-path", pluginProcessAttributes.moduleInfo.path); - - // FIXME: Don't allow this if the UI process is sandboxed. - if (pluginProcessAttributes.sandboxPolicy == PluginProcessSandboxPolicyUnsandboxed) - launchOptions.extraInitializationData.add("disable-sandbox", "1"); - -#if HAVE(XPC) - launchOptions.useXPC = shouldUseXPC(); -#endif -} - -void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationParameters& parameters) -{ - // For now only Flash is known to behave with asynchronous plug-in initialization. - parameters.supportsAsynchronousPluginInitialization = m_pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.macromedia.Flash Player.plugin"; - -#if USE(ACCELERATED_COMPOSITING) && HAVE(HOSTED_CORE_ANIMATION) - mach_port_t renderServerPort = [[CARemoteLayerServer sharedServer] serverPort]; - if (renderServerPort != MACH_PORT_NULL) - parameters.acceleratedCompositingPort = CoreIPC::MachPort(renderServerPort, MACH_MSG_TYPE_COPY_SEND); -#endif -} - -bool PluginProcessProxy::getPluginProcessSerialNumber(ProcessSerialNumber& pluginProcessSerialNumber) -{ - pid_t pluginProcessPID = processIdentifier(); -#if COMPILER(CLANG) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - return GetProcessForPID(pluginProcessPID, &pluginProcessSerialNumber) == noErr; -#if COMPILER(CLANG) -#pragma clang diagnostic pop -#endif -} - -void PluginProcessProxy::makePluginProcessTheFrontProcess() -{ - ProcessSerialNumber pluginProcessSerialNumber; - if (!getPluginProcessSerialNumber(pluginProcessSerialNumber)) - return; - -#if COMPILER(CLANG) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - SetFrontProcess(&pluginProcessSerialNumber); -#if COMPILER(CLANG) -#pragma clang diagnostic pop -#endif -} - -void PluginProcessProxy::makeUIProcessTheFrontProcess() -{ - ProcessSerialNumber processSerialNumber; -#if COMPILER(CLANG) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - GetCurrentProcess(&processSerialNumber); - SetFrontProcess(&processSerialNumber); -#if COMPILER(CLANG) -#pragma clang diagnostic pop -#endif -} - -void PluginProcessProxy::setFullscreenWindowIsShowing(bool fullscreenWindowIsShowing) -{ - if (m_fullscreenWindowIsShowing == fullscreenWindowIsShowing) - return; - - m_fullscreenWindowIsShowing = fullscreenWindowIsShowing; - if (m_fullscreenWindowIsShowing) - enterFullscreen(); - else - exitFullscreen(); -} - -void PluginProcessProxy::enterFullscreen() -{ - // Get the current presentation options. - m_preFullscreenAppPresentationOptions = [NSApp presentationOptions]; - - // Figure out which presentation options to use. - unsigned presentationOptions = m_preFullscreenAppPresentationOptions & ~(NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar); - presentationOptions |= NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar; - - [NSApp setPresentationOptions:presentationOptions]; - makePluginProcessTheFrontProcess(); -} - -void PluginProcessProxy::exitFullscreen() -{ - // If the plug-in host is the current application then we should bring ourselves to the front when it exits full-screen mode. - ProcessSerialNumber frontProcessSerialNumber; -#if COMPILER(CLANG) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - GetFrontProcess(&frontProcessSerialNumber); -#if COMPILER(CLANG) -#pragma clang diagnostic pop -#endif - - // The UI process must be the front process in order to change the presentation mode. - makeUIProcessTheFrontProcess(); - [NSApp setPresentationOptions:m_preFullscreenAppPresentationOptions]; - - ProcessSerialNumber pluginProcessSerialNumber; - if (!getPluginProcessSerialNumber(pluginProcessSerialNumber)) - return; - - // If the plug-in process was not the front process, switch back to the previous front process. - // (Otherwise we'll keep the UI process as the front process). - Boolean isPluginProcessFrontProcess; -#if COMPILER(CLANG) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - SameProcess(&frontProcessSerialNumber, &pluginProcessSerialNumber, &isPluginProcessFrontProcess); -#if COMPILER(CLANG) -#pragma clang diagnostic pop -#endif - if (!isPluginProcessFrontProcess) { -#if COMPILER(CLANG) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - SetFrontProcess(&frontProcessSerialNumber); -#if COMPILER(CLANG) -#pragma clang diagnostic pop -#endif - } -} - -void PluginProcessProxy::setModalWindowIsShowing(bool modalWindowIsShowing) -{ - if (modalWindowIsShowing == m_modalWindowIsShowing) - return; - - m_modalWindowIsShowing = modalWindowIsShowing; - - if (m_modalWindowIsShowing) - beginModal(); - else - endModal(); -} - -void PluginProcessProxy::beginModal() -{ - ASSERT(!m_placeholderWindow); - ASSERT(!m_activationObserver); - - m_placeholderWindow = adoptNS([[WKPlaceholderModalWindow alloc] initWithContentRect:NSMakeRect(0, 0, 1, 1) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]); - [m_placeholderWindow.get() setReleasedWhenClosed:NO]; - - m_activationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationWillBecomeActiveNotification object:NSApp queue:nil - usingBlock:^(NSNotification *){ applicationDidBecomeActive(); }]; - - // The call to -[NSApp runModalForWindow:] below will run a nested run loop, and if the plug-in process - // crashes the PluginProcessProxy object can be destroyed. Protect against this here. - RefPtr<PluginProcessProxy> protect(this); - - [NSApp runModalForWindow:m_placeholderWindow.get()]; - - [m_placeholderWindow.get() orderOut:nil]; - m_placeholderWindow = nullptr; -} - -void PluginProcessProxy::endModal() -{ - ASSERT(m_placeholderWindow); - ASSERT(m_activationObserver); - - [[NSNotificationCenter defaultCenter] removeObserver:m_activationObserver.get()]; - m_activationObserver = nullptr; - - [NSApp stopModal]; - - makeUIProcessTheFrontProcess(); -} - -void PluginProcessProxy::applicationDidBecomeActive() -{ - makePluginProcessTheFrontProcess(); -} - -void PluginProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled) -{ - if (!isValid()) - return; - - m_connection->send(Messages::PluginProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0); -} - -void PluginProcessProxy::openPluginPreferencePane() -{ - if (!m_pluginProcessAttributes.moduleInfo.preferencePanePath) - return; - - NSURL *preferenceURL = [NSURL fileURLWithPath:m_pluginProcessAttributes.moduleInfo.preferencePanePath]; - if (!preferenceURL) { - LOG_ERROR("Creating URL for preference pane path \"%@\" failed.", (NSString *)m_pluginProcessAttributes.moduleInfo.preferencePanePath); - return; - } - - NSArray *preferenceURLs = [NSArray arrayWithObject:preferenceURL]; - - LSLaunchURLSpec prefSpec; - prefSpec.appURL = 0; - prefSpec.itemURLs = reinterpret_cast<CFArrayRef>(preferenceURLs); - prefSpec.passThruParams = 0; - prefSpec.launchFlags = kLSLaunchAsync | kLSLaunchDontAddToRecents; - prefSpec.asyncRefCon = 0; - - OSStatus error = LSOpenFromURLSpec(&prefSpec, 0); - if (error != noErr) - LOG_ERROR("LSOpenFromURLSpec to open \"%@\" failed with error %d.", (NSString *)m_pluginProcessAttributes.moduleInfo.preferencePanePath, error); -} - -static bool isFlashUpdater(const String& launchPath, const Vector<String>& arguments) -{ - if (launchPath != "/Applications/Utilities/Adobe Flash Player Install Manager.app/Contents/MacOS/Adobe Flash Player Install Manager") - return false; - - if (arguments.size() != 1) - return false; - - if (arguments[0] != "-update") - return false; - - return true; -} - -static bool shouldLaunchProcess(const PluginProcessAttributes& pluginProcessAttributes, const String& launchPath, const Vector<String>& arguments) -{ - if (pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.macromedia.Flash Player.plugin") - return isFlashUpdater(launchPath, arguments); - - return false; -} - -void PluginProcessProxy::launchProcess(const String& launchPath, const Vector<String>& arguments, bool& result) -{ - if (!shouldLaunchProcess(m_pluginProcessAttributes, launchPath, arguments)) { - result = false; - return; - } - - result = true; - - RetainPtr<NSMutableArray> argumentsArray = adoptNS([[NSMutableArray alloc] initWithCapacity:arguments.size()]); - for (size_t i = 0; i < arguments.size(); ++i) - [argumentsArray addObject:(NSString *)arguments[i]]; - - [NSTask launchedTaskWithLaunchPath:launchPath arguments:argumentsArray.get()]; -} - -static bool isJavaUpdaterURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) -{ - NSURL *url = [NSURL URLWithString:urlString]; - if (![url isFileURL]) - return false; - - NSString *javaUpdaterPath = [NSString pathWithComponents:[NSArray arrayWithObjects:(NSString *)pluginProcessAttributes.moduleInfo.path, @"Contents/Resources/Java Updater.app", nil]]; - return [url.path isEqualToString:javaUpdaterPath]; -} - -static bool shouldLaunchApplicationAtURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) -{ - if (pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.oracle.java.JavaAppletPlugin") - return isJavaUpdaterURL(pluginProcessAttributes, urlString); - - return false; -} - -void PluginProcessProxy::launchApplicationAtURL(const String& urlString, const Vector<String>& arguments, bool& result) -{ - if (!shouldLaunchApplicationAtURL(m_pluginProcessAttributes, urlString)) { - result = false; - return; - } - - result = true; - - RetainPtr<NSMutableArray> argumentsArray = adoptNS([[NSMutableArray alloc] initWithCapacity:arguments.size()]); - for (size_t i = 0; i < arguments.size(); ++i) - [argumentsArray addObject:(NSString *)arguments[i]]; - - NSDictionary *configuration = [NSDictionary dictionaryWithObject:argumentsArray.get() forKey:NSWorkspaceLaunchConfigurationArguments]; - [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL URLWithString:urlString] options:NSWorkspaceLaunchAsync configuration:configuration error:nullptr]; -} - -static bool isSilverlightPreferencesURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) -{ - NSURL *silverlightPreferencesURL = [NSURL fileURLWithPathComponents:[NSArray arrayWithObjects:(NSString *)pluginProcessAttributes.moduleInfo.path, @"Contents/Resources/Silverlight Preferences.app", nil]]; - - return [[NSURL URLWithString:urlString] isEqual:silverlightPreferencesURL]; -} - -static bool shouldOpenURL(const PluginProcessAttributes& pluginProcessAttributes, const String& urlString) -{ - if (pluginProcessAttributes.moduleInfo.bundleIdentifier == "com.microsoft.SilverlightPlugin") - return isSilverlightPreferencesURL(pluginProcessAttributes, urlString); - - return false; -} - -void PluginProcessProxy::openURL(const String& urlString, bool& result, int32_t& status, String& launchedURLString) -{ - if (!shouldOpenURL(m_pluginProcessAttributes, urlString)) { - result = false; - return; - } - - result = true; - CFURLRef launchedURL; - status = LSOpenCFURLRef(KURL(ParsedURLString, urlString).createCFURL().get(), &launchedURL); - - if (launchedURL) { - launchedURLString = KURL(launchedURL).string(); - CFRelease(launchedURL); - } - - result = false; -} - -} // namespace WebKit - -#endif // ENABLE(PLUGIN_PROCESS) diff --git a/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp b/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp index 3726401f6..cfe9bd7b4 100644 --- a/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp +++ b/Source/WebKit2/UIProcess/Plugins/unix/PluginInfoStoreUnix.cpp @@ -32,50 +32,20 @@ #include "PluginInfoStore.h" #include "NetscapePluginModule.h" -#include "PluginDatabase.h" +#include "PluginSearchPath.h" #include <WebCore/FileSystem.h> +#if PLATFORM(GTK) +#include "PluginInfoCache.h" +#endif + using namespace WebCore; namespace WebKit { Vector<String> PluginInfoStore::pluginsDirectories() { - Vector<String> result; - - result.append(homeDirectoryPath() + "/.mozilla/plugins"); - result.append(homeDirectoryPath() + "/.netscape/plugins"); - result.append("/usr/lib/browser/plugins"); - result.append("/usr/local/lib/mozilla/plugins"); - result.append("/usr/lib/firefox/plugins"); - result.append("/usr/lib64/browser-plugins"); - result.append("/usr/lib/browser-plugins"); - result.append("/usr/lib/mozilla/plugins"); - result.append("/usr/local/netscape/plugins"); - result.append("/opt/mozilla/plugins"); - result.append("/opt/mozilla/lib/plugins"); - result.append("/opt/netscape/plugins"); - result.append("/opt/netscape/communicator/plugins"); - result.append("/usr/lib/netscape/plugins"); - result.append("/usr/lib/netscape/plugins-libc5"); - result.append("/usr/lib/netscape/plugins-libc6"); - result.append("/usr/lib64/netscape/plugins"); - result.append("/usr/lib64/mozilla/plugins"); - result.append("/usr/lib/nsbrowser/plugins"); - result.append("/usr/lib64/nsbrowser/plugins"); - - String mozillaHome(getenv("MOZILLA_HOME")); - if (!mozillaHome.isEmpty()) - result.append(mozillaHome + "/plugins"); - - String mozillaPaths(getenv("MOZ_PLUGIN_PATH")); - if (!mozillaPaths.isEmpty()) { - Vector<String> paths; - mozillaPaths.split(UChar(':'), /* allowEmptyEntries */ false, paths); - result.appendVector(paths); - } - - return result; + return WebKit::pluginsDirectories(); } Vector<String> PluginInfoStore::pluginPathsInDirectory(const String& directory) @@ -98,7 +68,18 @@ Vector<String> PluginInfoStore::individualPluginPaths() bool PluginInfoStore::getPluginInfo(const String& pluginPath, PluginModuleInfo& plugin) { +#if PLATFORM(GTK) + if (PluginInfoCache::singleton().getPluginInfo(pluginPath, plugin)) + return true; + + if (NetscapePluginModule::getPluginInfo(pluginPath, plugin)) { + PluginInfoCache::singleton().updatePluginInfo(pluginPath, plugin); + return true; + } + return false; +#else return NetscapePluginModule::getPluginInfo(pluginPath, plugin); +#endif } bool PluginInfoStore::shouldUsePlugin(Vector<PluginModuleInfo>& /*alreadyLoadedPlugins*/, const PluginModuleInfo& /*plugin*/) diff --git a/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp b/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp index d52cae647..8569450ba 100644 --- a/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp +++ b/Source/WebKit2/UIProcess/Plugins/unix/PluginProcessProxyUnix.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Igalia S.L. + * Copyright (C) 2011, 2014 Igalia S.L. * Copyright (C) 2011 Apple Inc. * Copyright (C) 2012 Samsung Electronics * @@ -33,11 +33,17 @@ #include "PluginProcessCreationParameters.h" #include "ProcessExecutablePath.h" #include <WebCore/FileSystem.h> +#include <sys/wait.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> + #if PLATFORM(GTK) || PLATFORM(EFL) #include <glib.h> -#include <wtf/gobject/GOwnPtr.h> +#include <wtf/glib/GUniquePtr.h> +#endif + +#if PLATFORM(GTK) +#include "Module.h" #endif using namespace WebCore; @@ -46,67 +52,105 @@ namespace WebKit { void PluginProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions, const PluginProcessAttributes& pluginProcessAttributes) { -#if PLATFORM(EFL) && !defined(NDEBUG) - const char* commandPrefix = getenv("PLUGIN_PROCESS_COMMAND_PREFIX"); - if (commandPrefix && *commandPrefix) - launchOptions.processCmdPrefix = String::fromUTF8(commandPrefix); -#endif + launchOptions.processType = ProcessLauncher::ProcessType::Plugin64; launchOptions.extraInitializationData.add("plugin-path", pluginProcessAttributes.moduleInfo.path); +#if PLATFORM(GTK) + if (pluginProcessAttributes.moduleInfo.requiresGtk2) + launchOptions.extraInitializationData.add("requires-gtk2", emptyString()); +#endif } void PluginProcessProxy::platformInitializePluginProcess(PluginProcessCreationParameters&) { } +#if PLATFORM(GTK) +static bool pluginRequiresGtk2(const String& pluginPath) +{ + std::unique_ptr<Module> module = std::make_unique<Module>(pluginPath); + if (!module->load()) + return false; + return module->functionPointer<gpointer>("gtk_object_get_type"); +} +#endif + +#if PLUGIN_ARCHITECTURE(X11) bool PluginProcessProxy::scanPlugin(const String& pluginPath, RawPluginMetaData& result) { #if PLATFORM(GTK) || PLATFORM(EFL) - CString binaryPath = fileSystemRepresentation(executablePathOfPluginProcess()); + String pluginProcessPath = executablePathOfPluginProcess(); + +#if PLATFORM(GTK) + bool requiresGtk2 = pluginRequiresGtk2(pluginPath); + if (requiresGtk2) +#if ENABLE(PLUGIN_PROCESS_GTK2) + pluginProcessPath.append('2'); +#else + return false; +#endif +#endif + + CString binaryPath = fileSystemRepresentation(pluginProcessPath); CString pluginPathCString = fileSystemRepresentation(pluginPath); char* argv[4]; argv[0] = const_cast<char*>(binaryPath.data()); argv[1] = const_cast<char*>("-scanPlugin"); argv[2] = const_cast<char*>(pluginPathCString.data()); - argv[3] = 0; - - int status; - GOwnPtr<char> stdOut; + argv[3] = nullptr; // If the disposition of SIGCLD signal is set to SIG_IGN (default) // then the signal will be ignored and g_spawn_sync() will not be // able to return the status. // As a consequence, we make sure that the disposition is set to // SIG_DFL before calling g_spawn_sync(). +#if defined(SIGCLD) struct sigaction action; sigaction(SIGCLD, 0, &action); if (action.sa_handler == SIG_IGN) { action.sa_handler = SIG_DFL; sigaction(SIGCLD, &action, 0); } +#endif - if (!g_spawn_sync(0, argv, 0, G_SPAWN_STDERR_TO_DEV_NULL, 0, 0, &stdOut.outPtr(), 0, &status, 0)) + int status; + GUniqueOutPtr<char> stdOut; + GUniqueOutPtr<GError> error; + if (!g_spawn_sync(nullptr, argv, nullptr, G_SPAWN_STDERR_TO_DEV_NULL, nullptr, nullptr, &stdOut.outPtr(), nullptr, &status, &error.outPtr())) { + WTFLogAlways("Failed to launch %s: %s", argv[0], error->message); return false; + } - if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS || !stdOut) + if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS) { + WTFLogAlways("Error scanning plugin %s, %s returned %d exit status", argv[2], argv[0], status); return false; + } - String stdOutString(reinterpret_cast<const UChar*>(stdOut.get())); + if (!stdOut) { + WTFLogAlways("Error scanning plugin %s, %s didn't write any output to stdout", argv[2], argv[0]); + return false; + } Vector<String> lines; - stdOutString.split(UChar('\n'), true, lines); + String::fromUTF8(stdOut.get()).split(UChar('\n'), true, lines); - if (lines.size() < 3) + if (lines.size() < 3) { + WTFLogAlways("Error scanning plugin %s, too few lines of output provided", argv[2]); return false; + } result.name.swap(lines[0]); result.description.swap(lines[1]); result.mimeDescription.swap(lines[2]); +#if PLATFORM(GTK) + result.requiresGtk2 = requiresGtk2; +#endif return !result.mimeDescription.isEmpty(); #else // PLATFORM(GTK) || PLATFORM(EFL) return false; #endif // PLATFORM(GTK) || PLATFORM(EFL) } +#endif // PLUGIN_ARCHITECTURE(X11) } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebPreferencesGtk.cpp b/Source/WebKit2/UIProcess/ProcessAssertion.cpp index 321a9cfcc..e0279bd8a 100644 --- a/Source/WebKit2/UIProcess/gtk/WebPreferencesGtk.cpp +++ b/Source/WebKit2/UIProcess/ProcessAssertion.cpp @@ -1,6 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -25,40 +24,48 @@ */ #include "config.h" -#include "WebPreferences.h" +#include "ProcessAssertion.h" -#include <WebCore/NotImplemented.h> +#if !PLATFORM(IOS) namespace WebKit { -void WebPreferences::platformInitializeStore() +ProcessAssertion::ProcessAssertion(pid_t, AssertionState assertionState) + : m_assertionState(assertionState) { - notImplemented(); } -void WebPreferences::platformUpdateStringValueForKey(const String&, const String&) +ProcessAssertion::~ProcessAssertion() { - notImplemented(); } -void WebPreferences::platformUpdateBoolValueForKey(const String&, bool) +void ProcessAssertion::setState(AssertionState assertionState) +{ + if (m_assertionState == assertionState) + return; + + m_assertionState = assertionState; +} + +ProcessAndUIAssertion::ProcessAndUIAssertion(pid_t pid, AssertionState assertionState) + : ProcessAssertion(pid, assertionState) { - notImplemented(); } -void WebPreferences::platformUpdateUInt32ValueForKey(const String&, uint32_t) +ProcessAndUIAssertion::~ProcessAndUIAssertion() { - notImplemented(); } -void WebPreferences::platformUpdateDoubleValueForKey(const String&, double) +void ProcessAndUIAssertion::setState(AssertionState assertionState) { - notImplemented(); + ProcessAssertion::setState(assertionState); } -void WebPreferences::platformUpdateFloatValueForKey(const String&, float) +void ProcessAndUIAssertion::setClient(ProcessAssertionClient& client) { - notImplemented(); + ProcessAssertion::setClient(client); +} + } -} // namespace WebKit +#endif // !PLATFORM(IOS) diff --git a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.h b/Source/WebKit2/UIProcess/ProcessAssertion.h index 7b2145424..95c97c13e 100644 --- a/Source/WebKit2/UIProcess/Launcher/mac/DynamicLinkerEnvironmentExtractor.h +++ b/Source/WebKit2/UIProcess/ProcessAssertion.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,40 +23,57 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef DynamicLinkerEnvironmentExtractor_h -#define DynamicLinkerEnvironmentExtractor_h +#ifndef ProcessAssertion_h +#define ProcessAssertion_h -#include <mach/machine.h> -#include <wtf/Noncopyable.h> +#if PLATFORM(IOS) && !PLATFORM(IOS_SIMULATOR) #include <wtf/RetainPtr.h> -#include <wtf/Vector.h> -#include <wtf/text/CString.h> +OBJC_CLASS BKSProcessAssertion; +#endif namespace WebKit { + +enum class AssertionState { + Suspended, + Background, + Foreground +}; -class EnvironmentVariables; - -class DynamicLinkerEnvironmentExtractor { - WTF_MAKE_NONCOPYABLE(DynamicLinkerEnvironmentExtractor); +class ProcessAssertionClient { +public: + virtual ~ProcessAssertionClient() { }; + virtual void assertionWillExpireImminently() = 0; +}; +class ProcessAssertion { public: - DynamicLinkerEnvironmentExtractor(NSString *executablePath, cpu_type_t architecture); + ProcessAssertion(pid_t, AssertionState); + ~ProcessAssertion(); - void getExtractedEnvironmentVariables(EnvironmentVariables&) const; + void setClient(ProcessAssertionClient& client) { m_client = &client; } + ProcessAssertionClient* client() { return m_client; } + + AssertionState state() const { return m_assertionState; } + void setState(AssertionState); private: - void processSingleArchitecture(const void* data, size_t length); - void processFatFile(const void* data, size_t length); - void processLoadCommands(const void* data, size_t length, int32_t numberOfCommands, bool shouldByteSwap); - size_t processLoadCommand(const void* data, size_t length, bool shouldByteSwap); - void processEnvironmentVariable(const char* environmentString); +#if PLATFORM(IOS) && !PLATFORM(IOS_SIMULATOR) + RetainPtr<BKSProcessAssertion> m_assertion; +#endif + AssertionState m_assertionState; + ProcessAssertionClient* m_client { nullptr }; +}; + +class ProcessAndUIAssertion : public ProcessAssertion { +public: + ProcessAndUIAssertion(pid_t, AssertionState); + ~ProcessAndUIAssertion(); - RetainPtr<NSString> m_executablePath; - cpu_type_t m_architecture; + void setClient(ProcessAssertionClient&); - Vector<std::pair<CString, CString>> m_extractedVariables; + void setState(AssertionState); }; + +} -} // namespace WebKit - -#endif // DynamicLinkerEnvironmentExtractor_h +#endif // ProcessAssertion_h diff --git a/Source/WebKit2/UIProcess/ProcessModel.h b/Source/WebKit2/UIProcess/ProcessModel.h deleted file mode 100644 index 6c18da0a2..000000000 --- a/Source/WebKit2/UIProcess/ProcessModel.h +++ /dev/null @@ -1,38 +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 ProcessModel_h -#define ProcessModel_h - -namespace WebKit { - -enum ProcessModel { - ProcessModelSharedSecondaryProcess, - ProcessModelMultipleSecondaryProcesses -}; - -} // namespace WebKit - -#endif // ProcessModel_h diff --git a/Source/WebKit2/UIProcess/ProcessThrottler.cpp b/Source/WebKit2/UIProcess/ProcessThrottler.cpp new file mode 100644 index 000000000..b4b017960 --- /dev/null +++ b/Source/WebKit2/UIProcess/ProcessThrottler.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2014 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 "ProcessThrottler.h" + +#include "ProcessThrottlerClient.h" + +namespace WebKit { + +static const unsigned processSuspensionTimeout = 30; + +ProcessThrottler::ProcessThrottler(ProcessThrottlerClient& process) + : m_process(process) + , m_suspendTimer(RunLoop::main(), this, &ProcessThrottler::suspendTimerFired) + , m_foregroundCounter([this](bool) { updateAssertion(); }) + , m_backgroundCounter([this](bool) { updateAssertion(); }) + , m_suspendMessageCount(0) +{ +} + +AssertionState ProcessThrottler::assertionState() +{ + ASSERT(!m_suspendTimer.isActive()); + + if (m_foregroundCounter.value()) + return AssertionState::Foreground; + if (m_backgroundCounter.value()) + return AssertionState::Background; + return AssertionState::Suspended; +} + +void ProcessThrottler::updateAssertionNow() +{ + m_suspendTimer.stop(); + if (m_assertion) { + m_assertion->setState(assertionState()); + m_process.didSetAssertionState(assertionState()); + } +} + +void ProcessThrottler::updateAssertion() +{ + // If the process is currently runnable but will be suspended then first give it a chance to complete what it was doing + // and clean up - move it to the background and send it a message to notify. Schedule a timeout so it can't stay running + // in the background for too long. + if (m_assertion && m_assertion->state() != AssertionState::Suspended && !m_foregroundCounter.value() && !m_backgroundCounter.value()) { + ++m_suspendMessageCount; + m_process.sendPrepareToSuspend(); + m_suspendTimer.startOneShot(processSuspensionTimeout); + m_assertion->setState(AssertionState::Background); + m_process.didSetAssertionState(AssertionState::Background); + return; + } + + bool shouldBeRunnable = m_foregroundCounter.value() || m_backgroundCounter.value(); + + // If we're currently waiting for the Web process to do suspension cleanup, but no longer need to be suspended, tell the Web process to cancel the cleanup. + if (m_suspendTimer.isActive() && shouldBeRunnable) + m_process.sendCancelPrepareToSuspend(); + + if (m_assertion && m_assertion->state() == AssertionState::Suspended && shouldBeRunnable) + m_process.sendProcessDidResume(); + + updateAssertionNow(); +} + +void ProcessThrottler::didConnectToProcess(pid_t pid) +{ + m_suspendTimer.stop(); + m_assertion = std::make_unique<ProcessAndUIAssertion>(pid, assertionState()); + m_process.didSetAssertionState(assertionState()); + m_assertion->setClient(*this); +} + +void ProcessThrottler::suspendTimerFired() +{ + updateAssertionNow(); +} + +void ProcessThrottler::processReadyToSuspend() +{ + if (!--m_suspendMessageCount) + updateAssertionNow(); + ASSERT(m_suspendMessageCount >= 0); +} + +void ProcessThrottler::didCancelProcessSuspension() +{ + if (!--m_suspendMessageCount) + updateAssertionNow(); + ASSERT(m_suspendMessageCount >= 0); +} + +void ProcessThrottler::assertionWillExpireImminently() +{ + m_process.sendProcessWillSuspendImminently(); +} + +} diff --git a/Source/WebKit2/UIProcess/ProcessThrottler.h b/Source/WebKit2/UIProcess/ProcessThrottler.h new file mode 100644 index 000000000..3878d0ae8 --- /dev/null +++ b/Source/WebKit2/UIProcess/ProcessThrottler.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2014 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 ProcessThrottler_h +#define ProcessThrottler_h + +#include "ProcessAssertion.h" + +#include <wtf/RefCounter.h> +#include <wtf/RunLoop.h> +#include <wtf/WeakPtr.h> + +namespace WebKit { + +enum UserObservablePageTokenType { }; +typedef RefCounter::Token<UserObservablePageTokenType> UserObservablePageToken; +enum ProcessSuppressionDisabledTokenType { }; +typedef RefCounter::Token<ProcessSuppressionDisabledTokenType> ProcessSuppressionDisabledToken; + +class ProcessThrottlerClient; + +class ProcessThrottler : private ProcessAssertionClient { +public: + enum ForegroundActivityTokenType { }; + typedef RefCounter::Token<ForegroundActivityTokenType> ForegroundActivityToken; + enum BackgroundActivityTokenType { }; + typedef RefCounter::Token<BackgroundActivityTokenType> BackgroundActivityToken; + + ProcessThrottler(ProcessThrottlerClient&); + + inline ForegroundActivityToken foregroundActivityToken() const; + inline BackgroundActivityToken backgroundActivityToken() const; + + void didConnectToProcess(pid_t); + void processReadyToSuspend(); + void didCancelProcessSuspension(); + +private: + AssertionState assertionState(); + void updateAssertion(); + void updateAssertionNow(); + void suspendTimerFired(); + + // ProcessAssertionClient + void assertionWillExpireImminently() override; + + ProcessThrottlerClient& m_process; + std::unique_ptr<ProcessAndUIAssertion> m_assertion; + RunLoop::Timer<ProcessThrottler> m_suspendTimer; + RefCounter m_foregroundCounter; + RefCounter m_backgroundCounter; + int m_suspendMessageCount; +}; + +inline ProcessThrottler::ForegroundActivityToken ProcessThrottler::foregroundActivityToken() const +{ + return ForegroundActivityToken(m_foregroundCounter.token<ForegroundActivityTokenType>()); +} + +inline ProcessThrottler::BackgroundActivityToken ProcessThrottler::backgroundActivityToken() const +{ + return BackgroundActivityToken(m_backgroundCounter.token<BackgroundActivityTokenType>()); +} + +} + +#endif // ProcessThrottler_h diff --git a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.h b/Source/WebKit2/UIProcess/ProcessThrottlerClient.h index f036b3fcf..75ab75726 100644 --- a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.h +++ b/Source/WebKit2/UIProcess/ProcessThrottlerClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2015 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,30 +23,26 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ContextMenuClientEfl_h -#define ContextMenuClientEfl_h +#ifndef ProcessThrottlerClient_h +#define ProcessThrottlerClient_h -#include <wtf/PassOwnPtr.h> - -class EwkView; +#include "ProcessAssertion.h" namespace WebKit { -class ContextMenuClientEfl { +class ProcessThrottlerClient { public: - static PassOwnPtr<ContextMenuClientEfl> create(EwkView* viewImpl) - { - return adoptPtr(new ContextMenuClientEfl(viewImpl)); - } - - EwkView* view() { return m_view; } + virtual ~ProcessThrottlerClient() { } -private: - explicit ContextMenuClientEfl(EwkView*); + virtual void sendProcessWillSuspendImminently() = 0; + virtual void sendPrepareToSuspend() = 0; + virtual void sendCancelPrepareToSuspend() = 0; + virtual void sendProcessDidResume() = 0; - EwkView* m_view; + virtual void didSetAssertionState(AssertionState) = 0; }; } // namespace WebKit -#endif // ContextMenuClientEfl_h +#endif // ProcessThrottlerClient_h + diff --git a/Source/WebKit2/UIProcess/ResponsivenessTimer.cpp b/Source/WebKit2/UIProcess/ResponsivenessTimer.cpp index 766ae0e20..c3cc981ad 100644 --- a/Source/WebKit2/UIProcess/ResponsivenessTimer.cpp +++ b/Source/WebKit2/UIProcess/ResponsivenessTimer.cpp @@ -26,13 +26,11 @@ #include "config.h" #include "ResponsivenessTimer.h" -using namespace WebCore; - namespace WebKit { static const double responsivenessTimeout = 3; -ResponsivenessTimer::ResponsivenessTimer(ResponsivenessTimer::Client* client) +ResponsivenessTimer::ResponsivenessTimer(ResponsivenessTimer::Client& client) : m_client(client) , m_isResponsive(true) , m_timer(RunLoop::main(), this, &ResponsivenessTimer::timerFired) @@ -51,13 +49,14 @@ void ResponsivenessTimer::invalidate() void ResponsivenessTimer::timerFired() { - if (m_isResponsive) { - m_isResponsive = false; - m_client->didBecomeUnresponsive(this); - } else { - // The timer fired while unresponsive. - m_client->interactionOccurredWhileUnresponsive(this); - } + if (!m_isResponsive) + return; + + m_client.willChangeIsResponsive(); + m_isResponsive = false; + m_client.didChangeIsResponsive(); + + m_client.didBecomeUnresponsive(); } void ResponsivenessTimer::start() @@ -71,12 +70,21 @@ void ResponsivenessTimer::start() void ResponsivenessTimer::stop() { if (!m_isResponsive) { - // We got a life sign from the web process! - m_client->didBecomeResponsive(this); + // We got a life sign from the web process. + m_client.willChangeIsResponsive(); m_isResponsive = true; + m_client.didChangeIsResponsive(); + + m_client.didBecomeResponsive(); } m_timer.stop(); } +void ResponsivenessTimer::processTerminated() +{ + // Since there is no web process, we must not be waiting for it anymore. + stop(); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/ResponsivenessTimer.h b/Source/WebKit2/UIProcess/ResponsivenessTimer.h index 8db2872fd..6d2bd4e3b 100644 --- a/Source/WebKit2/UIProcess/ResponsivenessTimer.h +++ b/Source/WebKit2/UIProcess/ResponsivenessTimer.h @@ -26,7 +26,7 @@ #ifndef ResponsivenessTimer_h #define ResponsivenessTimer_h -#include <WebCore/RunLoop.h> +#include <wtf/RunLoop.h> namespace WebKit { @@ -35,12 +35,14 @@ public: class Client { public: virtual ~Client() { } - virtual void didBecomeUnresponsive(ResponsivenessTimer*) = 0; - virtual void interactionOccurredWhileUnresponsive(ResponsivenessTimer*) = 0; - virtual void didBecomeResponsive(ResponsivenessTimer*) = 0; + virtual void didBecomeUnresponsive() = 0; + virtual void didBecomeResponsive() = 0; + + virtual void willChangeIsResponsive() = 0; + virtual void didChangeIsResponsive() = 0; }; - explicit ResponsivenessTimer(ResponsivenessTimer::Client*); + explicit ResponsivenessTimer(ResponsivenessTimer::Client&); ~ResponsivenessTimer(); void start(); @@ -50,13 +52,15 @@ public: bool isResponsive() { return m_isResponsive; } + void processTerminated(); + private: void timerFired(); - ResponsivenessTimer::Client* m_client; + ResponsivenessTimer::Client& m_client; bool m_isResponsive; - WebCore::RunLoop::Timer<ResponsivenessTimer> m_timer; + RunLoop::Timer<ResponsivenessTimer> m_timer; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingCoordinatorProxy.cpp b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingCoordinatorProxy.cpp new file mode 100644 index 000000000..4b4373320 --- /dev/null +++ b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingCoordinatorProxy.cpp @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2014 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 "RemoteScrollingCoordinatorProxy.h" + +#if ENABLE(ASYNC_SCROLLING) + +#include "ArgumentCoders.h" +#include "MessageDecoder.h" +#include "MessageEncoder.h" +#include "RemoteLayerTreeDrawingAreaProxy.h" +#include "RemoteScrollingCoordinator.h" +#include "RemoteScrollingCoordinatorMessages.h" +#include "RemoteScrollingCoordinatorTransaction.h" +#include "WebPageProxy.h" +#include "WebProcessProxy.h" +#include <WebCore/ScrollingStateFrameScrollingNode.h> +#include <WebCore/ScrollingStateOverflowScrollingNode.h> +#include <WebCore/ScrollingStateTree.h> +#include <WebCore/ScrollingTreeScrollingNode.h> + +using namespace WebCore; + +namespace WebKit { + +RemoteScrollingCoordinatorProxy::RemoteScrollingCoordinatorProxy(WebPageProxy& webPageProxy) + : m_webPageProxy(webPageProxy) + , m_scrollingTree(RemoteScrollingTree::create(*this)) + , m_requestedScrollInfo(nullptr) + , m_propagatesMainFrameScrolls(true) +{ +} + +RemoteScrollingCoordinatorProxy::~RemoteScrollingCoordinatorProxy() +{ +} + +ScrollingNodeID RemoteScrollingCoordinatorProxy::rootScrollingNodeID() const +{ + if (!m_scrollingTree->rootNode()) + return 0; + + return m_scrollingTree->rootNode()->scrollingNodeID(); +} + +const RemoteLayerTreeHost* RemoteScrollingCoordinatorProxy::layerTreeHost() const +{ + DrawingAreaProxy* drawingArea = m_webPageProxy.drawingArea(); + if (!is<RemoteLayerTreeDrawingAreaProxy>(drawingArea)) { + ASSERT_NOT_REACHED(); + return nullptr; + } + + RemoteLayerTreeDrawingAreaProxy& remoteDrawingArea = downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea); + return &remoteDrawingArea.remoteLayerTreeHost(); +} + +void RemoteScrollingCoordinatorProxy::updateScrollingTree(const RemoteScrollingCoordinatorTransaction& transaction, RequestedScrollInfo& requestedScrollInfo) +{ + m_requestedScrollInfo = &requestedScrollInfo; + + // FIXME: There must be a better idiom for this. + std::unique_ptr<ScrollingStateTree> stateTree(const_cast<RemoteScrollingCoordinatorTransaction&>(transaction).scrollingStateTree().release()); + + const RemoteLayerTreeHost* layerTreeHost = this->layerTreeHost(); + if (!layerTreeHost) { + ASSERT_NOT_REACHED(); + return; + } + + connectStateNodeLayers(*stateTree, *layerTreeHost); + m_scrollingTree->commitNewTreeState(WTFMove(stateTree)); + + m_requestedScrollInfo = nullptr; +} + +#if !PLATFORM(IOS) +void RemoteScrollingCoordinatorProxy::connectStateNodeLayers(ScrollingStateTree& stateTree, const RemoteLayerTreeHost& layerTreeHost) +{ + for (auto& currNode : stateTree.nodeMap().values()) { + if (currNode->hasChangedProperty(ScrollingStateNode::ScrollLayer)) + currNode->setLayer(layerTreeHost.getLayer(currNode->layer())); + + switch (currNode->nodeType()) { + case FrameScrollingNode: { + ScrollingStateFrameScrollingNode& scrollingStateNode = downcast<ScrollingStateFrameScrollingNode>(*currNode); + + if (scrollingStateNode.hasChangedProperty(ScrollingStateFrameScrollingNode::ScrolledContentsLayer)) + scrollingStateNode.setScrolledContentsLayer(layerTreeHost.getLayer(scrollingStateNode.scrolledContentsLayer())); + + if (scrollingStateNode.hasChangedProperty(ScrollingStateFrameScrollingNode::CounterScrollingLayer)) + scrollingStateNode.setCounterScrollingLayer(layerTreeHost.getLayer(scrollingStateNode.counterScrollingLayer())); + + if (scrollingStateNode.hasChangedProperty(ScrollingStateFrameScrollingNode::InsetClipLayer)) + scrollingStateNode.setInsetClipLayer(layerTreeHost.getLayer(scrollingStateNode.insetClipLayer())); + + if (scrollingStateNode.hasChangedProperty(ScrollingStateFrameScrollingNode::ContentShadowLayer)) + scrollingStateNode.setContentShadowLayer(layerTreeHost.getLayer(scrollingStateNode.contentShadowLayer())); + + // FIXME: we should never have header and footer layers coming from the WebProcess. + if (scrollingStateNode.hasChangedProperty(ScrollingStateFrameScrollingNode::HeaderLayer)) + scrollingStateNode.setHeaderLayer(layerTreeHost.getLayer(scrollingStateNode.headerLayer())); + + if (scrollingStateNode.hasChangedProperty(ScrollingStateFrameScrollingNode::FooterLayer)) + scrollingStateNode.setFooterLayer(layerTreeHost.getLayer(scrollingStateNode.footerLayer())); + break; + } + case OverflowScrollingNode: { + ScrollingStateOverflowScrollingNode& scrollingStateNode = downcast<ScrollingStateOverflowScrollingNode>(*currNode); + + if (scrollingStateNode.hasChangedProperty(ScrollingStateOverflowScrollingNode::ScrolledContentsLayer)) + scrollingStateNode.setScrolledContentsLayer(layerTreeHost.getLayer(scrollingStateNode.scrolledContentsLayer())); + break; + } + case FixedNode: + case StickyNode: + break; + } + } +} +#endif + +bool RemoteScrollingCoordinatorProxy::handleWheelEvent(const PlatformWheelEvent& event) +{ + ScrollingTree::EventResult result = m_scrollingTree->tryToHandleWheelEvent(event); + return result == ScrollingTree::DidHandleEvent; // FIXME: handle other values. +} + +bool RemoteScrollingCoordinatorProxy::isPointInNonFastScrollableRegion(const IntPoint& p) const +{ + return m_scrollingTree->isPointInNonFastScrollableRegion(p); +} + +void RemoteScrollingCoordinatorProxy::viewportChangedViaDelegatedScrolling(ScrollingNodeID nodeID, const FloatRect& fixedPositionRect, double scale) +{ + m_scrollingTree->viewportChangedViaDelegatedScrolling(nodeID, fixedPositionRect, scale); +} + +void RemoteScrollingCoordinatorProxy::currentSnapPointIndicesDidChange(WebCore::ScrollingNodeID nodeID, unsigned horizontal, unsigned vertical) +{ + m_webPageProxy.send(Messages::RemoteScrollingCoordinator::CurrentSnapPointIndicesChangedForNode(nodeID, horizontal, vertical)); +} + +// This comes from the scrolling tree. +void RemoteScrollingCoordinatorProxy::scrollingTreeNodeDidScroll(ScrollingNodeID scrolledNodeID, const FloatPoint& newScrollPosition, SetOrSyncScrollingLayerPosition scrollingLayerPositionAction) +{ + // Scroll updates for the main frame are sent via WebPageProxy::updateVisibleContentRects() + // so don't send them here. + if (!m_propagatesMainFrameScrolls && scrolledNodeID == rootScrollingNodeID()) + return; + +#if PLATFORM(IOS) + m_webPageProxy.overflowScrollViewDidScroll(); +#endif + m_webPageProxy.send(Messages::RemoteScrollingCoordinator::ScrollPositionChangedForNode(scrolledNodeID, newScrollPosition, scrollingLayerPositionAction)); +} + +void RemoteScrollingCoordinatorProxy::scrollingTreeNodeRequestsScroll(ScrollingNodeID scrolledNodeID, const FloatPoint& scrollPosition, bool representsProgrammaticScroll) +{ + if (scrolledNodeID == rootScrollingNodeID() && m_requestedScrollInfo) { + m_requestedScrollInfo->requestsScrollPositionUpdate = true; + m_requestedScrollInfo->requestIsProgrammaticScroll = representsProgrammaticScroll; + m_requestedScrollInfo->requestedScrollPosition = scrollPosition; + } +} + +} // namespace WebKit + +#endif // ENABLE(ASYNC_SCROLLING) diff --git a/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingCoordinatorProxy.h b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingCoordinatorProxy.h new file mode 100644 index 000000000..a7bb60fb8 --- /dev/null +++ b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingCoordinatorProxy.h @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2014-2015 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 RemoteScrollingCoordinatorProxy_h +#define RemoteScrollingCoordinatorProxy_h + +#if ENABLE(ASYNC_SCROLLING) + +#include "MessageReceiver.h" +#include "RemoteScrollingCoordinator.h" +#include "RemoteScrollingTree.h" +#include <wtf/Noncopyable.h> +#include <wtf/RefPtr.h> + +namespace WebCore { +class FloatPoint; +class PlatformWheelEvent; +} + +namespace WebKit { + +class RemoteLayerTreeHost; +class RemoteScrollingCoordinatorTransaction; +class RemoteScrollingTree; +class WebPageProxy; + +class RemoteScrollingCoordinatorProxy { + WTF_MAKE_NONCOPYABLE(RemoteScrollingCoordinatorProxy); +public: + explicit RemoteScrollingCoordinatorProxy(WebPageProxy&); + virtual ~RemoteScrollingCoordinatorProxy(); + + // Inform the web process that the scroll position changed (called from the scrolling tree) + void scrollingTreeNodeDidScroll(WebCore::ScrollingNodeID, const WebCore::FloatPoint& newScrollPosition, WebCore::SetOrSyncScrollingLayerPosition); + void scrollingTreeNodeRequestsScroll(WebCore::ScrollingNodeID, const WebCore::FloatPoint& scrollPosition, bool representsProgrammaticScroll); + + bool isPointInNonFastScrollableRegion(const WebCore::IntPoint&) const; + + // Called externally when native views move around. + void viewportChangedViaDelegatedScrolling(WebCore::ScrollingNodeID, const WebCore::FloatRect& fixedPositionRect, double scale); + + void currentSnapPointIndicesDidChange(WebCore::ScrollingNodeID, unsigned horizontal, unsigned vertical); + + // FIXME: expose the tree and pass this to that? + bool handleWheelEvent(const WebCore::PlatformWheelEvent&); + + WebCore::ScrollingNodeID rootScrollingNodeID() const; + + const RemoteLayerTreeHost* layerTreeHost() const; + + struct RequestedScrollInfo { + bool requestsScrollPositionUpdate { }; + bool requestIsProgrammaticScroll { }; + WebCore::FloatPoint requestedScrollPosition; + }; + void updateScrollingTree(const RemoteScrollingCoordinatorTransaction&, RequestedScrollInfo&); + + void setPropagatesMainFrameScrolls(bool propagatesMainFrameScrolls) { m_propagatesMainFrameScrolls = propagatesMainFrameScrolls; } + bool propagatesMainFrameScrolls() const { return m_propagatesMainFrameScrolls; } + bool hasFixedOrSticky() const { return m_scrollingTree->hasFixedOrSticky(); } + +#if PLATFORM(IOS) + WebCore::FloatRect customFixedPositionRect() const; + void scrollingTreeNodeWillStartPanGesture(); + void scrollingTreeNodeWillStartScroll(); + void scrollingTreeNodeDidEndScroll(); +#if ENABLE(CSS_SCROLL_SNAP) + void adjustTargetContentOffsetForSnapping(CGSize maxScrollDimensions, CGPoint velocity, CGFloat topInset, CGPoint* targetContentOffset); + bool hasActiveSnapPoint() const; + CGPoint nearestActiveContentInsetAdjustedSnapPoint(CGFloat topInset, const CGPoint&) const; + bool shouldSetScrollViewDecelerationRateFast() const; +#endif +#endif + +private: + void connectStateNodeLayers(WebCore::ScrollingStateTree&, const RemoteLayerTreeHost&); +#if ENABLE(CSS_SCROLL_SNAP) + bool shouldSnapForMainFrameScrolling(WebCore::ScrollEventAxis) const; + float closestSnapOffsetForMainFrameScrolling(WebCore::ScrollEventAxis, float scrollDestination, float velocity, unsigned& closestIndex) const; +#endif + + WebPageProxy& m_webPageProxy; + RefPtr<RemoteScrollingTree> m_scrollingTree; + RequestedScrollInfo* m_requestedScrollInfo; +#if ENABLE(CSS_SCROLL_SNAP) + unsigned m_currentHorizontalSnapPointIndex { 0 }; + unsigned m_currentVerticalSnapPointIndex { 0 }; +#endif + bool m_propagatesMainFrameScrolls; +}; + +} // namespace WebKit + +#endif // ENABLE(ASYNC_SCROLLING) + +#endif // RemoteScrollingCoordinatorProxy_h diff --git a/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingTree.cpp b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingTree.cpp new file mode 100644 index 000000000..a3b9407a1 --- /dev/null +++ b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingTree.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2014 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 "RemoteScrollingTree.h" + +#if ENABLE(ASYNC_SCROLLING) + +#include "RemoteLayerTreeHost.h" +#include "RemoteScrollingCoordinatorProxy.h" +#include <WebCore/ScrollingTreeFixedNode.h> +#include <WebCore/ScrollingTreeStickyNode.h> + +#if PLATFORM(IOS) +#include "ScrollingTreeOverflowScrollingNodeIOS.h" +#include <WebCore/ScrollingTreeFrameScrollingNodeIOS.h> +#else +#include <WebCore/ScrollingTreeFrameScrollingNodeMac.h> +#endif + +using namespace WebCore; + +namespace WebKit { + +Ref<RemoteScrollingTree> RemoteScrollingTree::create(RemoteScrollingCoordinatorProxy& scrollingCoordinator) +{ + return adoptRef(*new RemoteScrollingTree(scrollingCoordinator)); +} + +RemoteScrollingTree::RemoteScrollingTree(RemoteScrollingCoordinatorProxy& scrollingCoordinator) + : m_scrollingCoordinatorProxy(scrollingCoordinator) +{ +} + +RemoteScrollingTree::~RemoteScrollingTree() +{ +} + +ScrollingTree::EventResult RemoteScrollingTree::tryToHandleWheelEvent(const PlatformWheelEvent& wheelEvent) +{ + if (shouldHandleWheelEventSynchronously(wheelEvent)) + return SendToMainThread; + + if (willWheelEventStartSwipeGesture(wheelEvent)) + return DidNotHandleEvent; + + handleWheelEvent(wheelEvent); + return DidHandleEvent; +} + +#if PLATFORM(MAC) +void RemoteScrollingTree::handleWheelEventPhase(PlatformWheelEventPhase phase) +{ + // FIXME: hand off to m_scrollingCoordinatorProxy? +} +#endif + +#if PLATFORM(IOS) +WebCore::FloatRect RemoteScrollingTree::fixedPositionRect() +{ + return m_scrollingCoordinatorProxy.customFixedPositionRect(); +} + +void RemoteScrollingTree::scrollingTreeNodeWillStartPanGesture() +{ + m_scrollingCoordinatorProxy.scrollingTreeNodeWillStartPanGesture(); +} + +void RemoteScrollingTree::scrollingTreeNodeWillStartScroll() +{ + m_scrollingCoordinatorProxy.scrollingTreeNodeWillStartScroll(); +} + +void RemoteScrollingTree::scrollingTreeNodeDidEndScroll() +{ + m_scrollingCoordinatorProxy.scrollingTreeNodeDidEndScroll(); +} + +#endif + +void RemoteScrollingTree::scrollingTreeNodeDidScroll(ScrollingNodeID nodeID, const FloatPoint& scrollPosition, SetOrSyncScrollingLayerPosition scrollingLayerPositionAction) +{ + m_scrollingCoordinatorProxy.scrollingTreeNodeDidScroll(nodeID, scrollPosition, scrollingLayerPositionAction); +} + +void RemoteScrollingTree::scrollingTreeNodeRequestsScroll(ScrollingNodeID nodeID, const FloatPoint& scrollPosition, bool representsProgrammaticScroll) +{ + m_scrollingCoordinatorProxy.scrollingTreeNodeRequestsScroll(nodeID, scrollPosition, representsProgrammaticScroll); +} + +PassRefPtr<ScrollingTreeNode> RemoteScrollingTree::createScrollingTreeNode(ScrollingNodeType nodeType, ScrollingNodeID nodeID) +{ + switch (nodeType) { + case FrameScrollingNode: +#if PLATFORM(IOS) + return ScrollingTreeFrameScrollingNodeIOS::create(*this, nodeID); +#else + return ScrollingTreeFrameScrollingNodeMac::create(*this, nodeID); +#endif + case OverflowScrollingNode: +#if PLATFORM(IOS) + return ScrollingTreeOverflowScrollingNodeIOS::create(*this, nodeID); +#else + ASSERT_NOT_REACHED(); + return nullptr; +#endif + case FixedNode: + return ScrollingTreeFixedNode::create(*this, nodeID); + case StickyNode: + return ScrollingTreeStickyNode::create(*this, nodeID); + } + return nullptr; +} + +void RemoteScrollingTree::currentSnapPointIndicesDidChange(ScrollingNodeID nodeID, unsigned horizontal, unsigned vertical) +{ + m_scrollingCoordinatorProxy.currentSnapPointIndicesDidChange(nodeID, horizontal, vertical); +} + +} // namespace WebKit + +#endif // ENABLE(ASYNC_SCROLLING) diff --git a/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingTree.h b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingTree.h new file mode 100644 index 000000000..cb1e930cb --- /dev/null +++ b/Source/WebKit2/UIProcess/Scrolling/RemoteScrollingTree.h @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2014 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 RemoteScrollingTree_h +#define RemoteScrollingTree_h + +#if ENABLE(ASYNC_SCROLLING) + +#include "RemoteScrollingCoordinator.h" +#include <WebCore/ScrollingConstraints.h> +#include <WebCore/ScrollingTree.h> + +namespace WebKit { + +class RemoteScrollingCoordinatorProxy; + +class RemoteScrollingTree : public WebCore::ScrollingTree { +public: + static Ref<RemoteScrollingTree> create(RemoteScrollingCoordinatorProxy&); + virtual ~RemoteScrollingTree(); + + virtual bool isRemoteScrollingTree() const override { return true; } + virtual EventResult tryToHandleWheelEvent(const WebCore::PlatformWheelEvent&) override; + + const RemoteScrollingCoordinatorProxy& scrollingCoordinatorProxy() const { return m_scrollingCoordinatorProxy; } + + virtual void scrollingTreeNodeDidScroll(WebCore::ScrollingNodeID, const WebCore::FloatPoint& scrollPosition, WebCore::SetOrSyncScrollingLayerPosition = WebCore::SyncScrollingLayerPosition) override; + virtual void scrollingTreeNodeRequestsScroll(WebCore::ScrollingNodeID, const WebCore::FloatPoint& scrollPosition, bool representsProgrammaticScroll) override; + void currentSnapPointIndicesDidChange(WebCore::ScrollingNodeID, unsigned horizontal, unsigned vertical) override; + +private: + explicit RemoteScrollingTree(RemoteScrollingCoordinatorProxy&); + +#if PLATFORM(MAC) + virtual void handleWheelEventPhase(WebCore::PlatformWheelEventPhase) override; +#endif + +#if PLATFORM(IOS) + virtual WebCore::FloatRect fixedPositionRect() override; + virtual void scrollingTreeNodeWillStartPanGesture() override; + virtual void scrollingTreeNodeWillStartScroll() override; + virtual void scrollingTreeNodeDidEndScroll() override; +#endif + + virtual PassRefPtr<WebCore::ScrollingTreeNode> createScrollingTreeNode(WebCore::ScrollingNodeType, WebCore::ScrollingNodeID) override; + + RemoteScrollingCoordinatorProxy& m_scrollingCoordinatorProxy; +}; + +} // namespace WebKit + +SPECIALIZE_TYPE_TRAITS_SCROLLING_TREE(WebKit::RemoteScrollingTree, isRemoteScrollingTree()); + +#endif // ENABLE(ASYNC_SCROLLING) + +#endif // RemoteScrollingTree_h diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.cpp b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.cpp deleted file mode 100644 index f91efd9ed..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2010, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "SharedWorkerProcessManager.h" - -#if ENABLE(SHARED_WORKER_PROCESS) - -#include "SharedWorkerProcessProxy.h" -#include "WebContext.h" -#include <wtf/StdLibExtras.h> -#include <wtf/text/WTFString.h> - -namespace WebKit { - -SharedWorkerProcessManager& SharedWorkerProcessManager::shared() -{ - DEFINE_STATIC_LOCAL(SharedWorkerProcessManager, manager, ()); - return manager; -} - -SharedWorkerProcessManager::SharedWorkerProcessManager() -{ -} - -void SharedWorkerProcessManager::getSharedWorkerProcessConnection(const String& url, const String& name, PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply> reply) -{ - SharedWorkerProcessProxy* sharedWorkerProcess = getOrCreateSharedWorkerProcess(url, name); - sharedWorkerProcess->getSharedWorkerProcessConnection(reply); -} - -void SharedWorkerProcessManager::removeSharedWorkerProcessProxy(SharedWorkerProcessProxy* sharedWorkerProcessProxy) -{ - size_t vectorIndex = m_sharedWorkerProcesses.find(sharedWorkerProcessProxy); - ASSERT(vectorIndex != notFound); - - m_sharedWorkerProcesses.remove(vectorIndex); -} - -SharedWorkerProcessProxy* SharedWorkerProcessManager::getOrCreateSharedWorkerProcess(const String& url, const String& name) -{ - // FIXME: Find an existing shared worker that matches. - - RefPtr<SharedWorkerProcessProxy> sharedWorkerProcess = SharedWorkerProcessProxy::create(this, url, name); - SharedWorkerProcessProxy* sharedWorkerProcessPtr = sharedWorkerProcess.get(); - - m_sharedWorkerProcesses.append(sharedWorkerProcess.release()); - - return sharedWorkerProcessPtr; -} - -} // namespace WebKit - -#endif // ENABLE(SHARED_WORKER_PROCESS) diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h deleted file mode 100644 index 299133879..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessManager.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2010, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef SharedWorkerProcessManager_h -#define SharedWorkerProcessManager_h - -#if ENABLE(SHARED_WORKER_PROCESS) - -#include "PluginModuleInfo.h" -#include "WebProcessProxyMessages.h" -#include <wtf/Forward.h> -#include <wtf/Noncopyable.h> -#include <wtf/Vector.h> - -namespace CoreIPC { - class ArgumentEncoder; -} - -namespace WebKit { - -class PluginInfoStore; -class SharedWorkerProcessProxy; -class WebProcessProxy; -class WebPluginSiteDataManager; - -class SharedWorkerProcessManager { - WTF_MAKE_NONCOPYABLE(SharedWorkerProcessManager); -public: - static SharedWorkerProcessManager& shared(); - - void getSharedWorkerProcessConnection(const String& url, const String& name, PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>); - void removeSharedWorkerProcessProxy(SharedWorkerProcessProxy*); - -#if PLATFORM(MAC) - void setProcessSuppressionEnabled(bool); -#endif - -private: - SharedWorkerProcessManager(); - - SharedWorkerProcessProxy* getOrCreateSharedWorkerProcess(const String& url, const String& name); - - Vector<RefPtr<SharedWorkerProcessProxy> > m_sharedWorkerProcesses; -}; - -} // namespace WebKit - -#endif // ENABLE(SHARED_WORKER_PROCESS) - -#endif // SharedWorkerProcessManager_h diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp deleted file mode 100644 index 636085b17..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (C) 2010, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "SharedWorkerProcessProxy.h" - -#if ENABLE(SHARED_WORKER_PROCESS) - -#include "SharedWorkerProcessCreationParameters.h" -#include "SharedWorkerProcessManager.h" -#include "SharedWorkerProcessMessages.h" -#include "WebContext.h" -#include "WebCoreArgumentCoders.h" -#include "WebProcessMessages.h" -#include "WebProcessProxy.h" -#include <WebCore/NotImplemented.h> -#include <WebCore/RunLoop.h> - -#if PLATFORM(MAC) -#include "MachPort.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -// FIXME: Are these relevant to shared worker process at all? -static const double minimumLifetime = 30 * 60; -static const double shutdownTimeout = 10 * 60; - -PassRefPtr<SharedWorkerProcessProxy> SharedWorkerProcessProxy::create(SharedWorkerProcessManager* sharedWorkerProcessManager, const String& url, const String& name) -{ - return adoptRef(new SharedWorkerProcessProxy(sharedWorkerProcessManager, url, name)); -} - -SharedWorkerProcessProxy::SharedWorkerProcessProxy(SharedWorkerProcessManager* sharedWorkerProcessManager, const String& url, const String& name) - : m_sharedWorkerProcessManager(sharedWorkerProcessManager) - , m_numPendingConnectionRequests(0) -{ - ProcessLauncher::LaunchOptions launchOptions; - launchOptions.processType = ProcessLauncher::SharedWorkerProcess; - // FIXME: Pass URL down to the process to load. -#if PLATFORM(MAC) -#if HAVE(XPC) - launchOptions.useXPC = false; -#endif -#endif - - m_processLauncher = ProcessLauncher::create(this, launchOptions); -} - -SharedWorkerProcessProxy::~SharedWorkerProcessProxy() -{ -} - -// Asks the shared worker process to create a new connection to a web process. The connection identifier will be -// encoded in the given argument encoder and sent back to the connection of the given web process. -void SharedWorkerProcessProxy::getSharedWorkerProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply> reply) -{ - m_pendingConnectionReplies.append(reply); - - if (m_processLauncher->isLaunching()) { - m_numPendingConnectionRequests++; - return; - } - - // Ask the shared worker process to create a connection. Since the shared worker can be waiting for a synchronous reply - // we need to make sure that this message is always processed, even when the shared worker is waiting for a synchronus reply. - m_connection->send(Messages::SharedWorkerProcess::CreateWebProcessConnection(), 0, CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); -} - -void SharedWorkerProcessProxy::terminate() -{ - m_processLauncher->terminateProcess(); -} - -void SharedWorkerProcessProxy::sharedWorkerProcessCrashedOrFailedToLaunch() -{ - // The shared worker process must have crashed or exited, send any pending sync replies we might have. - while (!m_pendingConnectionReplies.isEmpty()) { - RefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); - -#if PLATFORM(MAC) - reply->send(CoreIPC::Attachment(0, MACH_MSG_TYPE_MOVE_SEND)); -#elif USE(UNIX_DOMAIN_SOCKETS) - reply->send(CoreIPC::Attachment()); -#else - notImplemented(); -#endif - } - - // Tell the shared worker process manager to forget about this shared worker process proxy. This may cause us to be deleted. - m_sharedWorkerProcessManager->removeSharedWorkerProcessProxy(this); -} - -void SharedWorkerProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) -{ - didReceiveSharedWorkerProcessProxyMessage(connection, decoder); -} - -void SharedWorkerProcessProxy::didClose(CoreIPC::Connection*) -{ - // FIXME: Notify web processes. - - // This will cause us to be deleted. - sharedWorkerProcessCrashedOrFailedToLaunch(); -} - -void SharedWorkerProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference, CoreIPC::StringReference) -{ -} - -void SharedWorkerProcessProxy::didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier connectionIdentifier) -{ - ASSERT(!m_connection); - - if (CoreIPC::Connection::identifierIsNull(connectionIdentifier)) { - sharedWorkerProcessCrashedOrFailedToLaunch(); - return; - } - - m_connection = CoreIPC::Connection::createServerConnection(connectionIdentifier, this, RunLoop::main()); -#if PLATFORM(MAC) - m_connection->setShouldCloseConnectionOnMachExceptions(); -#elif PLATFORM(QT) - m_connection->setShouldCloseConnectionOnProcessTermination(m_processLauncher->processIdentifier()); -#endif - - m_connection->open(); - - SharedWorkerProcessCreationParameters parameters; - - parameters.minimumLifetime = minimumLifetime; - parameters.terminationTimeout = shutdownTimeout; - - platformInitializeSharedWorkerProcess(parameters); - - // Initialize the shared worker host process. - m_connection->send(Messages::SharedWorkerProcess::InitializeSharedWorkerProcess(parameters), 0); - - for (unsigned i = 0; i < m_numPendingConnectionRequests; ++i) - m_connection->send(Messages::SharedWorkerProcess::CreateWebProcessConnection(), 0); - - m_numPendingConnectionRequests = 0; - -#if PLATFORM(MAC) - if (WebContext::canEnableProcessSuppressionForGlobalChildProcesses()) - setProcessSuppressionEnabled(true); -#endif -} - -void SharedWorkerProcessProxy::didCreateWebProcessConnection(const CoreIPC::Attachment& connectionIdentifier) -{ - ASSERT(!m_pendingConnectionReplies.isEmpty()); - - // Grab the first pending connection reply. - RefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply> reply = m_pendingConnectionReplies.takeFirst(); - -#if PLATFORM(MAC) - reply->send(CoreIPC::Attachment(connectionIdentifier.port(), MACH_MSG_TYPE_MOVE_SEND)); -#elif USE(UNIX_DOMAIN_SOCKETS) - reply->send(connectionIdentifier); -#else - notImplemented(); -#endif -} - -} // namespace WebKit - -#endif // ENABLE(SHARED_WORKER_PROCESS) diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h deleted file mode 100644 index c84e99be5..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2010, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef SharedWorkerProcessProxy_h -#define SharedWorkerProcessProxy_h - -#if ENABLE(SHARED_WORKER_PROCESS) - -#include "Connection.h" -#include "ProcessLauncher.h" -#include "WebProcessProxyMessages.h" -#include <wtf/Deque.h> - -// FIXME: This is platform specific. -namespace CoreIPC { - class MachPort; -} - -namespace WebKit { - -class SharedWorkerProcessManager; -class WebProcessProxy; -struct SharedWorkerProcessCreationParameters; - -class SharedWorkerProcessProxy : public RefCounted<SharedWorkerProcessProxy>, CoreIPC::Connection::Client, ProcessLauncher::Client { -public: - static PassRefPtr<SharedWorkerProcessProxy> create(SharedWorkerProcessManager*, const String& url, const String& name); - ~SharedWorkerProcessProxy(); - - // Asks the shared worker process to create a new connection to a web process. The connection identifier will be - // encoded in the given argument encoder and sent back to the connection of the given web process. - void getSharedWorkerProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>); - - // Terminates the shared worker process. - void terminate(); - - bool isValid() const { return m_connection; } - -#if PLATFORM(MAC) - void setProcessSuppressionEnabled(bool); -#endif - -private: - SharedWorkerProcessProxy(SharedWorkerProcessManager*, const String& url, const String& name); - - void sharedWorkerProcessCrashedOrFailedToLaunch(); - - // CoreIPC::Connection::Client - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - virtual void didClose(CoreIPC::Connection*); - virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName); - - // ProcessLauncher::Client - virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier); - - // Message handlers - void didReceiveSharedWorkerProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - void didCreateWebProcessConnection(const CoreIPC::Attachment&); - - void platformInitializeSharedWorkerProcess(SharedWorkerProcessCreationParameters&); - - // The shared worker host process manager. - SharedWorkerProcessManager* m_sharedWorkerProcessManager; - - // The connection to the plug-in host process. - RefPtr<CoreIPC::Connection> m_connection; - - // The process launcher for the plug-in host process. - RefPtr<ProcessLauncher> m_processLauncher; - - Deque<RefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>> m_pendingConnectionReplies; - - // If createPluginConnection is called while the process is still launching we'll keep count of it and send a bunch of requests - // when the process finishes launching. - unsigned m_numPendingConnectionRequests; -}; - -} // namespace WebKit - -#endif // ENABLE(SHARED_WORKER_PROCESS) - -#endif // SharedWorkerProcessProxy_h diff --git a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in b/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in deleted file mode 100644 index f5dc4eadc..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/SharedWorkerProcessProxy.messages.in +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (C) 2010, 2012 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#if ENABLE(SHARED_WORKER_PROCESS) - -messages -> SharedWorkerProcessProxy LegacyReceiver { - DidCreateWebProcessConnection(CoreIPC::Attachment connectionIdentifier) -} - -#endif // ENABLE(SHARED_WORKER_PROCESS) diff --git a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm b/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm deleted file mode 100644 index 85ca4aa25..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessManagerMac.mm +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "SharedWorkerProcessManager.h" - -#if ENABLE(SHARED_WORKER_PROCESS) - -#import "SharedWorkerProcessProxy.h" - -namespace WebKit { - -void SharedWorkerProcessManager::setProcessSuppressionEnabled(bool processSuppressionEnabled) -{ - size_t processCount = m_sharedWorkerProcesses.size(); - for (size_t i = 0; i < processCount; ++i) - m_sharedWorkerProcesses[i]->setProcessSuppressionEnabled(processSuppressionEnabled); -} - -} // namespace WebKit - -#endif // ENABLE(SHARED_WORKER_PROCESS) diff --git a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm b/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm deleted file mode 100644 index fab4acdc6..000000000 --- a/Source/WebKit2/UIProcess/SharedWorkers/mac/SharedWorkerProcessProxyMac.mm +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "SharedWorkerProcessProxy.h" - -#if ENABLE(SHARED_WORKER_PROCESS) - -#import "SharedWorkerProcessMessages.h" - -namespace WebKit { - -void SharedWorkerProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled) -{ - if (!isValid()) - return; - - m_connection->send(Messages::SharedWorkerProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0); -} - -} // namespace WebKit - -#endif // ENABLE(SHARED_WORKER_PROCESS) diff --git a/Source/WebKit2/UIProcess/StatisticsRequest.cpp b/Source/WebKit2/UIProcess/StatisticsRequest.cpp index 6f81ccbb3..bf51d234b 100644 --- a/Source/WebKit2/UIProcess/StatisticsRequest.cpp +++ b/Source/WebKit2/UIProcess/StatisticsRequest.cpp @@ -26,9 +26,8 @@ #include "config.h" #include "StatisticsRequest.h" -#include "ImmutableArray.h" -#include "MutableDictionary.h" -#include <wtf/Threading.h> +#include "APIArray.h" +#include "APIDictionary.h" namespace WebKit { @@ -45,32 +44,24 @@ StatisticsRequest::~StatisticsRequest() uint64_t StatisticsRequest::addOutstandingRequest() { - static int64_t uniqueRequestID; + static std::atomic<int64_t> uniqueRequestID; -#if HAVE(ATOMICS_64BIT) - uint64_t requestID = atomicIncrement(&uniqueRequestID); -#else - static Mutex uniqueRequestMutex; - uniqueRequestMutex.lock(); uint64_t requestID = ++uniqueRequestID; - uniqueRequestMutex.unlock(); -#endif - m_outstandingRequests.add(requestID); return requestID; } -static void addToDictionaryFromHashMap(MutableDictionary* dictionary, const HashMap<String, uint64_t>& map) +static void addToDictionaryFromHashMap(API::Dictionary* dictionary, const HashMap<String, uint64_t>& map) { HashMap<String, uint64_t>::const_iterator end = map.end(); for (HashMap<String, uint64_t>::const_iterator it = map.begin(); it != end; ++it) - dictionary->set(it->key, RefPtr<WebUInt64>(WebUInt64::create(it->value)).get()); + dictionary->set(it->key, RefPtr<API::UInt64>(API::UInt64::create(it->value)).get()); } -static PassRefPtr<MutableDictionary> createDictionaryFromHashMap(const HashMap<String, uint64_t>& map) +static Ref<API::Dictionary> createDictionaryFromHashMap(const HashMap<String, uint64_t>& map) { - RefPtr<MutableDictionary> result = MutableDictionary::create(); - addToDictionaryFromHashMap(result.get(), map); + Ref<API::Dictionary> result = API::Dictionary::create(); + addToDictionaryFromHashMap(result.ptr(), map); return result; } @@ -80,7 +71,7 @@ void StatisticsRequest::completedRequest(uint64_t requestID, const StatisticsDat m_outstandingRequests.remove(requestID); if (!m_responseDictionary) - m_responseDictionary = MutableDictionary::create(); + m_responseDictionary = API::Dictionary::create(); // FIXME (Multi-WebProcess) <rdar://problem/13200059>: This code overwrites any previous response data received. // When getting responses from multiple WebProcesses we need to combine items instead of clobbering them. @@ -88,21 +79,23 @@ void StatisticsRequest::completedRequest(uint64_t requestID, const StatisticsDat addToDictionaryFromHashMap(m_responseDictionary.get(), data.statisticsNumbers); if (!data.javaScriptProtectedObjectTypeCounts.isEmpty()) - m_responseDictionary->set("JavaScriptProtectedObjectTypeCounts", createDictionaryFromHashMap(data.javaScriptProtectedObjectTypeCounts).get()); + m_responseDictionary->set("JavaScriptProtectedObjectTypeCounts", createDictionaryFromHashMap(data.javaScriptProtectedObjectTypeCounts)); if (!data.javaScriptObjectTypeCounts.isEmpty()) - m_responseDictionary->set("JavaScriptObjectTypeCounts", createDictionaryFromHashMap(data.javaScriptObjectTypeCounts).get()); - - size_t cacheStatisticsCount = data.webCoreCacheStatistics.size(); - if (cacheStatisticsCount) { - Vector<RefPtr<APIObject> > cacheStatisticsVector(cacheStatisticsCount); - for (size_t i = 0; i < cacheStatisticsCount; ++i) - cacheStatisticsVector[i] = createDictionaryFromHashMap(data.webCoreCacheStatistics[i]); - m_responseDictionary->set("WebCoreCacheStatistics", ImmutableArray::adopt(cacheStatisticsVector).get()); + m_responseDictionary->set("JavaScriptObjectTypeCounts", createDictionaryFromHashMap(data.javaScriptObjectTypeCounts)); + + if (!data.webCoreCacheStatistics.isEmpty()) { + Vector<RefPtr<API::Object>> cacheStatistics; + cacheStatistics.reserveInitialCapacity(data.webCoreCacheStatistics.size()); + + for (const auto& statistic : data.webCoreCacheStatistics) + cacheStatistics.uncheckedAppend(createDictionaryFromHashMap(statistic)); + + m_responseDictionary->set("WebCoreCacheStatistics", API::Array::create(WTFMove(cacheStatistics))); } if (m_outstandingRequests.isEmpty()) { m_callback->performCallbackWithReturnValue(m_responseDictionary.get()); - m_callback = 0; + m_callback = nullptr; } } diff --git a/Source/WebKit2/UIProcess/StatisticsRequest.h b/Source/WebKit2/UIProcess/StatisticsRequest.h index bf9c37bbe..c5f03c887 100644 --- a/Source/WebKit2/UIProcess/StatisticsRequest.h +++ b/Source/WebKit2/UIProcess/StatisticsRequest.h @@ -35,7 +35,7 @@ namespace WebKit { struct StatisticsData; -typedef GenericCallback<WKDictionaryRef> DictionaryCallback; +typedef GenericCallback<API::Dictionary*> DictionaryCallback; enum StatisticsRequestType { StatisticsRequestTypeWebContent = 0x00000001, @@ -61,7 +61,7 @@ private: HashSet<uint64_t> m_outstandingRequests; RefPtr<DictionaryCallback> m_callback; - RefPtr<MutableDictionary> m_responseDictionary; + RefPtr<API::Dictionary> m_responseDictionary; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp index 4dbb9eab1..1367438af 100644 --- a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.cpp @@ -27,34 +27,35 @@ #include "LocalStorageDatabase.h" #include "LocalStorageDatabaseTracker.h" -#include "WorkQueue.h" #include <WebCore/FileSystem.h> #include <WebCore/SQLiteStatement.h> #include <WebCore/SQLiteTransaction.h> #include <WebCore/SecurityOrigin.h> #include <WebCore/StorageMap.h> +#include <WebCore/SuddenTermination.h> #include <wtf/PassRefPtr.h> +#include <wtf/WorkQueue.h> #include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> using namespace WebCore; -static const double databaseUpdateIntervalInSeconds = 1.0; +static const auto databaseUpdateInterval = std::chrono::seconds(1); static const int maximumItemsToUpdate = 100; namespace WebKit { -PassRefPtr<LocalStorageDatabase> LocalStorageDatabase::create(PassRefPtr<WorkQueue> queue, PassRefPtr<LocalStorageDatabaseTracker> tracker, PassRefPtr<SecurityOrigin> securityOrigin) +PassRefPtr<LocalStorageDatabase> LocalStorageDatabase::create(PassRefPtr<WorkQueue> queue, PassRefPtr<LocalStorageDatabaseTracker> tracker, Ref<SecurityOrigin>&& securityOrigin) { - return adoptRef(new LocalStorageDatabase(queue, tracker, securityOrigin)); + return adoptRef(new LocalStorageDatabase(queue, tracker, WTFMove(securityOrigin))); } -LocalStorageDatabase::LocalStorageDatabase(PassRefPtr<WorkQueue> queue, PassRefPtr<LocalStorageDatabaseTracker> tracker, PassRefPtr<SecurityOrigin> securityOrigin) +LocalStorageDatabase::LocalStorageDatabase(PassRefPtr<WorkQueue> queue, PassRefPtr<LocalStorageDatabaseTracker> tracker, Ref<SecurityOrigin>&& securityOrigin) : m_queue(queue) , m_tracker(tracker) - , m_securityOrigin(securityOrigin) - , m_databasePath(m_tracker->databasePath(m_securityOrigin.get())) + , m_securityOrigin(WTFMove(securityOrigin)) + , m_databasePath(m_tracker->databasePath(m_securityOrigin.ptr())) , m_failedToOpenDatabase(false) , m_didImportItems(false) , m_isClosed(false) @@ -79,7 +80,7 @@ void LocalStorageDatabase::openDatabase(DatabaseOpeningStrategy openingStrategy) } if (m_database.isOpen()) - m_tracker->didOpenDatabaseWithOrigin(m_securityOrigin.get()); + m_tracker->didOpenDatabaseWithOrigin(m_securityOrigin.ptr()); } bool LocalStorageDatabase::tryToOpenDatabase(DatabaseOpeningStrategy openingStrategy) @@ -171,7 +172,7 @@ void LocalStorageDatabase::importItems(StorageMap& storageMap) return; SQLiteStatement query(m_database, "SELECT key, value FROM ItemTable"); - if (query.prepare() != SQLResultOk) { + if (query.prepare() != SQLITE_OK) { LOG_ERROR("Unable to select items from ItemTable for local storage"); return; } @@ -179,12 +180,12 @@ void LocalStorageDatabase::importItems(StorageMap& storageMap) HashMap<String, String> items; int result = query.step(); - while (result == SQLResultRow) { + while (result == SQLITE_ROW) { items.set(query.getColumnText(0), query.getColumnBlobAsString(1)); result = query.step(); } - if (result != SQLResultDone) { + if (result != SQLITE_DONE) { LOG_ERROR("Error reading items from ItemTable for local storage"); return; } @@ -226,7 +227,7 @@ void LocalStorageDatabase::close() m_database.close(); if (isEmpty) - m_tracker->deleteDatabaseWithOrigin(m_securityOrigin.get()); + m_tracker->deleteDatabaseWithOrigin(m_securityOrigin.ptr()); } void LocalStorageDatabase::itemDidChange(const String& key, const String& value) @@ -240,8 +241,15 @@ void LocalStorageDatabase::scheduleDatabaseUpdate() if (m_didScheduleDatabaseUpdate) return; + if (!m_disableSuddenTerminationWhileWritingToLocalStorage) + m_disableSuddenTerminationWhileWritingToLocalStorage = std::make_unique<SuddenTerminationDisabler>(); + m_didScheduleDatabaseUpdate = true; - m_queue->dispatchAfterDelay(bind(&LocalStorageDatabase::updateDatabase, this), databaseUpdateIntervalInSeconds); + + RefPtr<LocalStorageDatabase> localStorageDatabase(this); + m_queue->dispatchAfter(databaseUpdateInterval, [localStorageDatabase] { + localStorageDatabase->updateDatabase(); + }); } void LocalStorageDatabase::updateDatabase() @@ -256,9 +264,11 @@ void LocalStorageDatabase::updateDatabase() if (m_changedItems.size() <= maximumItemsToUpdate) { // There are few enough changed items that we can just always write all of them. m_changedItems.swap(changedItems); + updateDatabaseWithChangedItems(changedItems); + m_disableSuddenTerminationWhileWritingToLocalStorage = nullptr; } else { for (int i = 0; i < maximumItemsToUpdate; ++i) { - HashMap<String, String>::iterator it = m_changedItems.begin(); + auto it = m_changedItems.begin(); changedItems.add(it->key, it->value); m_changedItems.remove(it); @@ -268,9 +278,8 @@ void LocalStorageDatabase::updateDatabase() // Reschedule the update for the remaining items. scheduleDatabaseUpdate(); + updateDatabaseWithChangedItems(changedItems); } - - updateDatabaseWithChangedItems(changedItems); } void LocalStorageDatabase::updateDatabaseWithChangedItems(const HashMap<String, String>& changedItems) @@ -284,26 +293,26 @@ void LocalStorageDatabase::updateDatabaseWithChangedItems(const HashMap<String, m_shouldClearItems = false; SQLiteStatement clearStatement(m_database, "DELETE FROM ItemTable"); - if (clearStatement.prepare() != SQLResultOk) { + if (clearStatement.prepare() != SQLITE_OK) { LOG_ERROR("Failed to prepare clear statement - cannot write to local storage database"); return; } int result = clearStatement.step(); - if (result != SQLResultDone) { + if (result != SQLITE_DONE) { LOG_ERROR("Failed to clear all items in the local storage database - %i", result); return; } } SQLiteStatement insertStatement(m_database, "INSERT INTO ItemTable VALUES (?, ?)"); - if (insertStatement.prepare() != SQLResultOk) { + if (insertStatement.prepare() != SQLITE_OK) { LOG_ERROR("Failed to prepare insert statement - cannot write to local storage database"); return; } SQLiteStatement deleteStatement(m_database, "DELETE FROM ItemTable WHERE key=?"); - if (deleteStatement.prepare() != SQLResultOk) { + if (deleteStatement.prepare() != SQLITE_OK) { LOG_ERROR("Failed to prepare delete statement - cannot write to local storage database"); return; } @@ -311,9 +320,7 @@ void LocalStorageDatabase::updateDatabaseWithChangedItems(const HashMap<String, SQLiteTransaction transaction(m_database); transaction.begin(); - HashMap<String, String>::const_iterator it = changedItems.begin(); - const HashMap<String, String>::const_iterator end = changedItems.end(); - for (; it != end; ++it) { + for (auto it = changedItems.begin(), end = changedItems.end(); it != end; ++it) { // A null value means that the key/value pair should be deleted. SQLiteStatement& statement = it->value.isNull() ? deleteStatement : insertStatement; @@ -324,7 +331,7 @@ void LocalStorageDatabase::updateDatabaseWithChangedItems(const HashMap<String, statement.bindBlob(2, it->value); int result = statement.step(); - if (result != SQLResultDone) { + if (result != SQLITE_DONE) { LOG_ERROR("Failed to update item in the local storage database - %i", result); break; } @@ -341,13 +348,13 @@ bool LocalStorageDatabase::databaseIsEmpty() return false; SQLiteStatement query(m_database, "SELECT COUNT(*) FROM ItemTable"); - if (query.prepare() != SQLResultOk) { + if (query.prepare() != SQLITE_OK) { LOG_ERROR("Unable to count number of rows in ItemTable for local storage"); return false; } int result = query.step(); - if (result != SQLResultRow) { + if (result != SQLITE_ROW) { LOG_ERROR("No results when counting number of rows in ItemTable for local storage"); return false; } diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h index 1acd6b253..3340ef714 100644 --- a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabase.h @@ -31,12 +31,12 @@ #include <wtf/HashMap.h> #include <wtf/RefPtr.h> #include <wtf/ThreadSafeRefCounted.h> - -class WorkQueue; +#include <wtf/WorkQueue.h> namespace WebCore { class SecurityOrigin; class StorageMap; +class SuddenTerminationDisabler; } namespace WebKit { @@ -45,7 +45,7 @@ class LocalStorageDatabaseTracker; class LocalStorageDatabase : public ThreadSafeRefCounted<LocalStorageDatabase> { public: - static PassRefPtr<LocalStorageDatabase> create(PassRefPtr<WorkQueue>, PassRefPtr<LocalStorageDatabaseTracker>, PassRefPtr<WebCore::SecurityOrigin>); + static PassRefPtr<LocalStorageDatabase> create(PassRefPtr<WorkQueue>, PassRefPtr<LocalStorageDatabaseTracker>, Ref<WebCore::SecurityOrigin>&&); ~LocalStorageDatabase(); // Will block until the import is complete. @@ -59,7 +59,7 @@ public: void close(); private: - LocalStorageDatabase(PassRefPtr<WorkQueue>, PassRefPtr<LocalStorageDatabaseTracker>, PassRefPtr<WebCore::SecurityOrigin>); + LocalStorageDatabase(PassRefPtr<WorkQueue>, PassRefPtr<LocalStorageDatabaseTracker>, Ref<WebCore::SecurityOrigin>&&); enum DatabaseOpeningStrategy { CreateIfNonExistent, @@ -80,7 +80,7 @@ private: RefPtr<WorkQueue> m_queue; RefPtr<LocalStorageDatabaseTracker> m_tracker; - RefPtr<WebCore::SecurityOrigin> m_securityOrigin; + Ref<WebCore::SecurityOrigin> m_securityOrigin; String m_databasePath; WebCore::SQLiteDatabase m_database; @@ -91,6 +91,8 @@ private: bool m_didScheduleDatabaseUpdate; bool m_shouldClearItems; HashMap<String, String> m_changedItems; + + std::unique_ptr<WebCore::SuddenTerminationDisabler> m_disableSuddenTerminationWhileWritingToLocalStorage; }; diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp index 3a106e0d0..ad81e146d 100644 --- a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.cpp @@ -26,36 +26,39 @@ #include "config.h" #include "LocalStorageDatabaseTracker.h" -#include "WorkQueue.h" #include <WebCore/FileSystem.h> #include <WebCore/SQLiteStatement.h> #include <WebCore/SecurityOrigin.h> +#include <WebCore/TextEncoding.h> +#include <wtf/WorkQueue.h> #include <wtf/text/CString.h> using namespace WebCore; namespace WebKit { -PassRefPtr<LocalStorageDatabaseTracker> LocalStorageDatabaseTracker::create(PassRefPtr<WorkQueue> queue) +PassRefPtr<LocalStorageDatabaseTracker> LocalStorageDatabaseTracker::create(PassRefPtr<WorkQueue> queue, const String& localStorageDirectory) { - return adoptRef(new LocalStorageDatabaseTracker(queue)); + return adoptRef(new LocalStorageDatabaseTracker(queue, localStorageDirectory)); } -LocalStorageDatabaseTracker::LocalStorageDatabaseTracker(PassRefPtr<WorkQueue> queue) +LocalStorageDatabaseTracker::LocalStorageDatabaseTracker(PassRefPtr<WorkQueue> queue, const String& localStorageDirectory) : m_queue(queue) + , m_localStorageDirectory(localStorageDirectory.isolatedCopy()) { -} + ASSERT(!m_localStorageDirectory.isEmpty()); -LocalStorageDatabaseTracker::~LocalStorageDatabaseTracker() -{ + // Make sure the encoding is initialized before we start dispatching things to the queue. + UTF8Encoding(); + + RefPtr<LocalStorageDatabaseTracker> localStorageDatabaseTracker(this); + m_queue->dispatch([localStorageDatabaseTracker] { + localStorageDatabaseTracker->importOriginIdentifiers(); + }); } -void LocalStorageDatabaseTracker::setLocalStorageDirectory(const String& localStorageDirectory) +LocalStorageDatabaseTracker::~LocalStorageDatabaseTracker() { - // FIXME: We should come up with a better idiom for safely copying strings across threads. - RefPtr<StringImpl> copiedLocalStorageDirectory = localStorageDirectory.impl() ? localStorageDirectory.impl()->isolatedCopy() : PassRefPtr<StringImpl>(); - - m_queue->dispatch(bind(&LocalStorageDatabaseTracker::setLocalStorageDirectoryInternal, this, copiedLocalStorageDirectory.release())); } String LocalStorageDatabaseTracker::databasePath(SecurityOrigin* securityOrigin) const @@ -82,19 +85,19 @@ void LocalStorageDatabaseTracker::deleteAllDatabases() return; SQLiteStatement statement(m_database, "SELECT origin, path FROM Origins"); - if (statement.prepare() != SQLResultOk) { + if (statement.prepare() != SQLITE_OK) { LOG_ERROR("Failed to prepare statement."); return; } int result; - while ((result = statement.step()) == SQLResultRow) { + while ((result = statement.step()) == SQLITE_ROW) { deleteFile(statement.getColumnText(1)); // FIXME: Call out to the client. } - if (result != SQLResultDone) + if (result != SQLITE_DONE) LOG_ERROR("Failed to read in all origins from the database."); if (m_database.isOpen()) @@ -108,7 +111,7 @@ void LocalStorageDatabaseTracker::deleteAllDatabases() return; SQLiteStatement deleteStatement(m_database, "DELETE FROM Origins"); - if (deleteStatement.prepare() != SQLResultOk) { + if (deleteStatement.prepare() != SQLITE_OK) { LOG_ERROR("Unable to prepare deletion of all origins"); return; } @@ -121,32 +124,81 @@ void LocalStorageDatabaseTracker::deleteAllDatabases() deleteEmptyDirectory(m_localStorageDirectory); } -Vector<RefPtr<WebCore::SecurityOrigin> > LocalStorageDatabaseTracker::origins() const +static Optional<time_t> fileCreationTime(const String& filePath) +{ + time_t time; + return getFileCreationTime(filePath, time) ? time : Optional<time_t>(Nullopt); +} + +static Optional<time_t> fileModificationTime(const String& filePath) +{ + time_t time; + if (!getFileModificationTime(filePath, time)) + return Nullopt; + + return time; +} + +Vector<Ref<SecurityOrigin>> LocalStorageDatabaseTracker::deleteDatabasesModifiedSince(std::chrono::system_clock::time_point time) +{ + Vector<String> originIdentifiersToDelete; + + for (const String& origin : m_origins) { + String filePath = pathForDatabaseWithOriginIdentifier(origin); + + auto modificationTime = fileModificationTime(filePath); + if (!modificationTime) + continue; + + if (modificationTime.value() >= std::chrono::system_clock::to_time_t(time)) + originIdentifiersToDelete.append(origin); + } + + Vector<Ref<SecurityOrigin>> deletedDatabaseOrigins; + deletedDatabaseOrigins.reserveInitialCapacity(originIdentifiersToDelete.size()); + + for (const auto& originIdentifier : originIdentifiersToDelete) { + removeDatabaseWithOriginIdentifier(originIdentifier); + + deletedDatabaseOrigins.uncheckedAppend(SecurityOrigin::createFromDatabaseIdentifier(originIdentifier)); + } + + return deletedDatabaseOrigins; +} + +Vector<Ref<WebCore::SecurityOrigin>> LocalStorageDatabaseTracker::origins() const { - Vector<RefPtr<SecurityOrigin> > origins; + Vector<Ref<SecurityOrigin>> origins; origins.reserveInitialCapacity(m_origins.size()); - for (HashSet<String>::const_iterator it = m_origins.begin(), end = m_origins.end(); it != end; ++it) - origins.uncheckedAppend(SecurityOrigin::createFromDatabaseIdentifier(*it)); + for (const String& origin : m_origins) + origins.uncheckedAppend(SecurityOrigin::createFromDatabaseIdentifier(origin)); return origins; } -void LocalStorageDatabaseTracker::setLocalStorageDirectoryInternal(StringImpl* localStorageDirectory) +Vector<LocalStorageDatabaseTracker::OriginDetails> LocalStorageDatabaseTracker::originDetails() { - if (m_database.isOpen()) - m_database.close(); + Vector<OriginDetails> result; + result.reserveInitialCapacity(m_origins.size()); - m_localStorageDirectory = localStorageDirectory; - m_origins.clear(); + for (const String& origin : m_origins) { + String filePath = pathForDatabaseWithOriginIdentifier(origin); + + OriginDetails details; + details.originIdentifier = origin.isolatedCopy(); + details.creationTime = fileCreationTime(filePath); + details.modificationTime = fileModificationTime(filePath); + result.uncheckedAppend(details); + } - m_queue->dispatch(bind(&LocalStorageDatabaseTracker::importOriginIdentifiers, this)); + return result; } String LocalStorageDatabaseTracker::databasePath(const String& filename) const { if (!makeAllDirectories(m_localStorageDirectory)) { - LOG_ERROR("Unabled to create LocalStorage database path %s", m_localStorageDirectory.utf8().data()); + LOG_ERROR("Unable to create LocalStorage database path %s", m_localStorageDirectory.utf8().data()); return String(); } @@ -190,17 +242,17 @@ void LocalStorageDatabaseTracker::importOriginIdentifiers() if (m_database.isOpen()) { SQLiteStatement statement(m_database, "SELECT origin FROM Origins"); - if (statement.prepare() != SQLResultOk) { + if (statement.prepare() != SQLITE_OK) { LOG_ERROR("Failed to prepare statement."); return; } int result; - while ((result = statement.step()) == SQLResultRow) + while ((result = statement.step()) == SQLITE_ROW) m_origins.add(statement.getColumnText(0)); - if (result != SQLResultDone) { + if (result != SQLITE_DONE) { LOG_ERROR("Failed to read in all origins from the database."); return; } @@ -232,7 +284,7 @@ void LocalStorageDatabaseTracker::updateTrackerDatabaseFromLocalStorageDatabaseF originsFromLocalStorageDatabaseFiles.add(originIdentifier); } - for (HashSet<String>::iterator it = origins.begin(), end = origins.end(); it != end; ++it) { + for (auto it = origins.begin(), end = origins.end(); it != end; ++it) { const String& originIdentifier = *it; if (origins.contains(originIdentifier)) continue; @@ -248,7 +300,7 @@ void LocalStorageDatabaseTracker::addDatabaseWithOriginIdentifier(const String& return; SQLiteStatement statement(m_database, "INSERT INTO Origins VALUES (?, ?)"); - if (statement.prepare() != SQLResultOk) { + if (statement.prepare() != SQLITE_OK) { LOG_ERROR("Unable to establish origin '%s' in the tracker", originIdentifier.utf8().data()); return; } @@ -256,7 +308,7 @@ void LocalStorageDatabaseTracker::addDatabaseWithOriginIdentifier(const String& statement.bindText(1, originIdentifier); statement.bindText(2, databasePath); - if (statement.step() != SQLResultDone) + if (statement.step() != SQLITE_DONE) LOG_ERROR("Unable to establish origin '%s' in the tracker", originIdentifier.utf8().data()); m_origins.add(originIdentifier); @@ -275,7 +327,7 @@ void LocalStorageDatabaseTracker::removeDatabaseWithOriginIdentifier(const Strin return; SQLiteStatement deleteStatement(m_database, "DELETE FROM Origins where origin=?"); - if (deleteStatement.prepare() != SQLResultOk) { + if (deleteStatement.prepare() != SQLITE_OK) { LOG_ERROR("Unable to prepare deletion of origin '%s'", originIdentifier.ascii().data()); return; } @@ -289,7 +341,7 @@ void LocalStorageDatabaseTracker::removeDatabaseWithOriginIdentifier(const Strin m_origins.remove(originIdentifier); if (m_origins.isEmpty()) { - // There are no origins left, go ahead and delete the tracker database. + // There are no origins left; delete the tracker database. m_database.close(); deleteFile(trackerDatabasePath()); deleteEmptyDirectory(m_localStorageDirectory); @@ -304,7 +356,7 @@ String LocalStorageDatabaseTracker::pathForDatabaseWithOriginIdentifier(const St return String(); SQLiteStatement pathStatement(m_database, "SELECT path FROM Origins WHERE origin=?"); - if (pathStatement.prepare() != SQLResultOk) { + if (pathStatement.prepare() != SQLITE_OK) { LOG_ERROR("Unable to prepare selection of path for origin '%s'", originIdentifier.utf8().data()); return String(); } @@ -312,7 +364,7 @@ String LocalStorageDatabaseTracker::pathForDatabaseWithOriginIdentifier(const St pathStatement.bindText(1, originIdentifier); int result = pathStatement.step(); - if (result != SQLResultRow) + if (result != SQLITE_ROW) return String(); return pathStatement.getColumnText(0); diff --git a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h index 1e633512d..04f61fd0b 100644 --- a/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h +++ b/Source/WebKit2/UIProcess/Storage/LocalStorageDatabaseTracker.h @@ -28,9 +28,11 @@ #include <WebCore/SQLiteDatabase.h> #include <wtf/HashSet.h> +#include <wtf/Optional.h> #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/ThreadSafeRefCounted.h> +#include <wtf/WorkQueue.h> #include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> @@ -38,28 +40,35 @@ namespace WebCore { class SecurityOrigin; } -class WorkQueue; - namespace WebKit { +struct LocalStorageDetails; + class LocalStorageDatabaseTracker : public ThreadSafeRefCounted<LocalStorageDatabaseTracker> { public: - static PassRefPtr<LocalStorageDatabaseTracker> create(PassRefPtr<WorkQueue>); + static PassRefPtr<LocalStorageDatabaseTracker> create(PassRefPtr<WorkQueue>, const String& localStorageDirectory); ~LocalStorageDatabaseTracker(); - void setLocalStorageDirectory(const String&); String databasePath(WebCore::SecurityOrigin*) const; void didOpenDatabaseWithOrigin(WebCore::SecurityOrigin*); void deleteDatabaseWithOrigin(WebCore::SecurityOrigin*); void deleteAllDatabases(); - Vector<RefPtr<WebCore::SecurityOrigin> > origins() const; + // Returns a vector of the origins whose databases have been deleted. + Vector<Ref<WebCore::SecurityOrigin>> deleteDatabasesModifiedSince(std::chrono::system_clock::time_point); -private: - explicit LocalStorageDatabaseTracker(PassRefPtr<WorkQueue>); + Vector<Ref<WebCore::SecurityOrigin>> origins() const; - void setLocalStorageDirectoryInternal(StringImpl*); + struct OriginDetails { + String originIdentifier; + Optional<time_t> creationTime; + Optional<time_t> modificationTime; + }; + Vector<OriginDetails> originDetails(); + +private: + LocalStorageDatabaseTracker(PassRefPtr<WorkQueue>, const String& localStorageDirectory); String databasePath(const String& filename) const; String trackerDatabasePath() const; diff --git a/Source/WebKit2/UIProcess/Storage/StorageManager.cpp b/Source/WebKit2/UIProcess/Storage/StorageManager.cpp index 8e5dbef8b..fdc8196d4 100644 --- a/Source/WebKit2/UIProcess/Storage/StorageManager.cpp +++ b/Source/WebKit2/UIProcess/Storage/StorageManager.cpp @@ -28,14 +28,16 @@ #include "LocalStorageDatabase.h" #include "LocalStorageDatabaseTracker.h" -#include "SecurityOriginData.h" #include "StorageAreaMapMessages.h" #include "StorageManagerMessages.h" #include "WebProcessProxy.h" -#include "WorkQueue.h" +#include <WebCore/SecurityOriginData.h> #include <WebCore/SecurityOriginHash.h> #include <WebCore/StorageMap.h> #include <WebCore/TextEncoding.h> +#include <memory> +#include <wtf/WorkQueue.h> +#include <wtf/threads/BinarySemaphore.h> using namespace WebCore; @@ -43,53 +45,55 @@ namespace WebKit { class StorageManager::StorageArea : public ThreadSafeRefCounted<StorageManager::StorageArea> { public: - static PassRefPtr<StorageArea> create(LocalStorageNamespace*, PassRefPtr<SecurityOrigin>, unsigned quotaInBytes); + static Ref<StorageArea> create(LocalStorageNamespace*, Ref<SecurityOrigin>&&, unsigned quotaInBytes); ~StorageArea(); - SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); } + SecurityOrigin& securityOrigin() { return m_securityOrigin.get(); } - void addListener(CoreIPC::Connection*, uint64_t storageMapID); - void removeListener(CoreIPC::Connection*, uint64_t storageMapID); + void addListener(IPC::Connection&, uint64_t storageMapID); + void removeListener(IPC::Connection&, uint64_t storageMapID); - PassRefPtr<StorageArea> clone() const; + Ref<StorageArea> clone() const; - void setItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException); - void removeItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString); - void clear(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString); + void setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException); + void removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString); + void clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString); const HashMap<String, String>& items(); void clear(); + bool isSessionStorage() const { return !m_localStorageNamespace; } + private: - explicit StorageArea(LocalStorageNamespace*, PassRefPtr<SecurityOrigin>, unsigned quotaInBytes); + explicit StorageArea(LocalStorageNamespace*, Ref<SecurityOrigin>&&, unsigned quotaInBytes); void openDatabaseAndImportItemsIfNeeded(); - void dispatchEvents(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const; + void dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const; // Will be null if the storage area belongs to a session storage namespace. LocalStorageNamespace* m_localStorageNamespace; RefPtr<LocalStorageDatabase> m_localStorageDatabase; bool m_didImportItemsFromDatabase; - RefPtr<SecurityOrigin> m_securityOrigin; + Ref<SecurityOrigin> m_securityOrigin; unsigned m_quotaInBytes; RefPtr<StorageMap> m_storageMap; - HashSet<std::pair<RefPtr<CoreIPC::Connection>, uint64_t> > m_eventListeners; + HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>> m_eventListeners; }; class StorageManager::LocalStorageNamespace : public ThreadSafeRefCounted<LocalStorageNamespace> { public: - static PassRefPtr<LocalStorageNamespace> create(StorageManager*, uint64_t storageManagerID); + static Ref<LocalStorageNamespace> create(StorageManager*, uint64_t storageManagerID); ~LocalStorageNamespace(); StorageManager* storageManager() const { return m_storageManager; } - PassRefPtr<StorageArea> getOrCreateStorageArea(PassRefPtr<SecurityOrigin>); + Ref<StorageArea> getOrCreateStorageArea(Ref<SecurityOrigin>&&); void didDestroyStorageArea(StorageArea*); - void clearStorageAreasMatchingOrigin(SecurityOrigin*); + void clearStorageAreasMatchingOrigin(const SecurityOrigin&); void clearAllStorageAreas(); private: @@ -103,15 +107,74 @@ private: HashMap<RefPtr<SecurityOrigin>, StorageArea*> m_storageAreaMap; }; -PassRefPtr<StorageManager::StorageArea> StorageManager::StorageArea::create(LocalStorageNamespace* localStorageNamespace, PassRefPtr<SecurityOrigin> securityOrigin, unsigned quotaInBytes) +class StorageManager::TransientLocalStorageNamespace : public ThreadSafeRefCounted<TransientLocalStorageNamespace> { +public: + static Ref<TransientLocalStorageNamespace> create() + { + return adoptRef(*new TransientLocalStorageNamespace()); + } + + ~TransientLocalStorageNamespace() + { + } + + Ref<StorageArea> getOrCreateStorageArea(Ref<SecurityOrigin>&& securityOrigin) + { + auto& slot = m_storageAreaMap.add(securityOrigin.ptr(), nullptr).iterator->value; + if (slot) + return *slot; + + auto storageArea = StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes); + slot = &storageArea.get(); + + return storageArea; + } + + Vector<Ref<SecurityOrigin>> origins() const + { + Vector<Ref<SecurityOrigin>> origins; + + for (const auto& storageArea : m_storageAreaMap.values()) { + if (!storageArea->items().isEmpty()) + origins.append(storageArea->securityOrigin()); + } + + return origins; + } + + void clearStorageAreasMatchingOrigin(const SecurityOrigin& securityOrigin) + { + for (auto& storageArea : m_storageAreaMap.values()) { + if (storageArea->securityOrigin().equal(&securityOrigin)) + storageArea->clear(); + } + } + + void clearAllStorageAreas() + { + for (auto& storageArea : m_storageAreaMap.values()) + storageArea->clear(); + } + +private: + explicit TransientLocalStorageNamespace() + { + } + + const unsigned m_quotaInBytes = 5 * 1024 * 1024; + + HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea>> m_storageAreaMap; +}; + +Ref<StorageManager::StorageArea> StorageManager::StorageArea::create(LocalStorageNamespace* localStorageNamespace, Ref<SecurityOrigin>&& securityOrigin, unsigned quotaInBytes) { - return adoptRef(new StorageArea(localStorageNamespace, securityOrigin, quotaInBytes)); + return adoptRef(*new StorageArea(localStorageNamespace, WTFMove(securityOrigin), quotaInBytes)); } -StorageManager::StorageArea::StorageArea(LocalStorageNamespace* localStorageNamespace, PassRefPtr<SecurityOrigin> securityOrigin, unsigned quotaInBytes) +StorageManager::StorageArea::StorageArea(LocalStorageNamespace* localStorageNamespace, Ref<SecurityOrigin>&& securityOrigin, unsigned quotaInBytes) : m_localStorageNamespace(localStorageNamespace) , m_didImportItemsFromDatabase(false) - , m_securityOrigin(securityOrigin) + , m_securityOrigin(WTFMove(securityOrigin)) , m_quotaInBytes(quotaInBytes) , m_storageMap(StorageMap::create(m_quotaInBytes)) { @@ -128,29 +191,29 @@ StorageManager::StorageArea::~StorageArea() m_localStorageNamespace->didDestroyStorageArea(this); } -void StorageManager::StorageArea::addListener(CoreIPC::Connection* connection, uint64_t storageMapID) +void StorageManager::StorageArea::addListener(IPC::Connection& connection, uint64_t storageMapID) { - ASSERT(!m_eventListeners.contains(std::make_pair(connection, storageMapID))); - m_eventListeners.add(std::make_pair(connection, storageMapID)); + ASSERT(!m_eventListeners.contains(std::make_pair(&connection, storageMapID))); + m_eventListeners.add(std::make_pair(&connection, storageMapID)); } -void StorageManager::StorageArea::removeListener(CoreIPC::Connection* connection, uint64_t storageMapID) +void StorageManager::StorageArea::removeListener(IPC::Connection& connection, uint64_t storageMapID) { - ASSERT(m_eventListeners.contains(std::make_pair(connection, storageMapID))); - m_eventListeners.remove(std::make_pair(connection, storageMapID)); + ASSERT(isSessionStorage() || m_eventListeners.contains(std::make_pair(&connection, storageMapID))); + m_eventListeners.remove(std::make_pair(&connection, storageMapID)); } -PassRefPtr<StorageManager::StorageArea> StorageManager::StorageArea::clone() const +Ref<StorageManager::StorageArea> StorageManager::StorageArea::clone() const { ASSERT(!m_localStorageNamespace); - RefPtr<StorageArea> storageArea = StorageArea::create(0, m_securityOrigin, m_quotaInBytes); + auto storageArea = StorageArea::create(0, m_securityOrigin.copyRef(), m_quotaInBytes); storageArea->m_storageMap = m_storageMap; - return storageArea.release(); + return storageArea; } -void StorageManager::StorageArea::setItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException) +void StorageManager::StorageArea::setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException) { openDatabaseAndImportItemsIfNeeded(); @@ -169,7 +232,7 @@ void StorageManager::StorageArea::setItem(CoreIPC::Connection* sourceConnection, dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, value, urlString); } -void StorageManager::StorageArea::removeItem(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString) +void StorageManager::StorageArea::removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString) { openDatabaseAndImportItemsIfNeeded(); @@ -187,7 +250,7 @@ void StorageManager::StorageArea::removeItem(CoreIPC::Connection* sourceConnecti dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, String(), urlString); } -void StorageManager::StorageArea::clear(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString) +void StorageManager::StorageArea::clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString) { openDatabaseAndImportItemsIfNeeded(); @@ -218,7 +281,7 @@ void StorageManager::StorageArea::clear() m_localStorageDatabase = nullptr; } - for (HashSet<std::pair<RefPtr<CoreIPC::Connection>, uint64_t> >::iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) + for (auto it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) it->first->send(Messages::StorageAreaMap::ClearCache(), it->second); } @@ -229,7 +292,7 @@ void StorageManager::StorageArea::openDatabaseAndImportItemsIfNeeded() // We open the database here even if we've already imported our items to ensure that the database is open if we need to write to it. if (!m_localStorageDatabase) - m_localStorageDatabase = LocalStorageDatabase::create(m_localStorageNamespace->storageManager()->m_queue, m_localStorageNamespace->storageManager()->m_localStorageDatabaseTracker, m_securityOrigin.get()); + m_localStorageDatabase = LocalStorageDatabase::create(m_localStorageNamespace->storageManager()->m_queue, m_localStorageNamespace->storageManager()->m_localStorageDatabaseTracker, m_securityOrigin.copyRef()); if (m_didImportItemsFromDatabase) return; @@ -238,18 +301,18 @@ void StorageManager::StorageArea::openDatabaseAndImportItemsIfNeeded() m_didImportItemsFromDatabase = true; } -void StorageManager::StorageArea::dispatchEvents(CoreIPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const +void StorageManager::StorageArea::dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const { - for (HashSet<std::pair<RefPtr<CoreIPC::Connection>, uint64_t> >::const_iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) { + for (HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>>::const_iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) { uint64_t storageAreaID = it->first == sourceConnection ? sourceStorageAreaID : 0; it->first->send(Messages::StorageAreaMap::DispatchStorageEvent(storageAreaID, key, oldValue, newValue, urlString), it->second); } } -PassRefPtr<StorageManager::LocalStorageNamespace> StorageManager::LocalStorageNamespace::create(StorageManager* storageManager, uint64_t storageNamespaceID) +Ref<StorageManager::LocalStorageNamespace> StorageManager::LocalStorageNamespace::create(StorageManager* storageManager, uint64_t storageNamespaceID) { - return adoptRef(new LocalStorageNamespace(storageManager, storageNamespaceID)); + return adoptRef(*new LocalStorageNamespace(storageManager, storageNamespaceID)); } // FIXME: The quota value is copied from GroupSettings.cpp. @@ -266,23 +329,23 @@ StorageManager::LocalStorageNamespace::~LocalStorageNamespace() ASSERT(m_storageAreaMap.isEmpty()); } -PassRefPtr<StorageManager::StorageArea> StorageManager::LocalStorageNamespace::getOrCreateStorageArea(PassRefPtr<SecurityOrigin> securityOrigin) +Ref<StorageManager::StorageArea> StorageManager::LocalStorageNamespace::getOrCreateStorageArea(Ref<SecurityOrigin>&& securityOrigin) { - HashMap<RefPtr<SecurityOrigin>, StorageArea*>::AddResult result = m_storageAreaMap.add(securityOrigin, 0); - if (!result.isNewEntry) - return result.iterator->value; + auto& slot = m_storageAreaMap.add(securityOrigin.ptr(), nullptr).iterator->value; + if (slot) + return *slot; - RefPtr<StorageArea> storageArea = StorageArea::create(this, result.iterator->key, m_quotaInBytes); - result.iterator->value = storageArea.get(); + auto storageArea = StorageArea::create(this, WTFMove(securityOrigin), m_quotaInBytes); + slot = &storageArea.get(); - return storageArea.release(); + return storageArea; } void StorageManager::LocalStorageNamespace::didDestroyStorageArea(StorageArea* storageArea) { - ASSERT(m_storageAreaMap.contains(storageArea->securityOrigin())); + ASSERT(m_storageAreaMap.contains(&storageArea->securityOrigin())); - m_storageAreaMap.remove(storageArea->securityOrigin()); + m_storageAreaMap.remove(&storageArea->securityOrigin()); if (!m_storageAreaMap.isEmpty()) return; @@ -290,51 +353,76 @@ void StorageManager::LocalStorageNamespace::didDestroyStorageArea(StorageArea* s m_storageManager->m_localStorageNamespaces.remove(m_storageNamespaceID); } -void StorageManager::LocalStorageNamespace::clearStorageAreasMatchingOrigin(SecurityOrigin* securityOrigin) +void StorageManager::LocalStorageNamespace::clearStorageAreasMatchingOrigin(const SecurityOrigin& securityOrigin) { - for (HashMap<RefPtr<SecurityOrigin>, StorageArea*>::iterator it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) { - if (it->key->equal(securityOrigin)) - it->value->clear(); + for (const auto& originAndStorageArea : m_storageAreaMap) { + if (originAndStorageArea.key->equal(&securityOrigin)) + originAndStorageArea.value->clear(); } } void StorageManager::LocalStorageNamespace::clearAllStorageAreas() { - for (HashMap<RefPtr<SecurityOrigin>, StorageArea*>::iterator it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) + for (auto it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) it->value->clear(); } class StorageManager::SessionStorageNamespace : public ThreadSafeRefCounted<SessionStorageNamespace> { public: - static PassRefPtr<SessionStorageNamespace> create(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + static Ref<SessionStorageNamespace> create(unsigned quotaInBytes); ~SessionStorageNamespace(); bool isEmpty() const { return m_storageAreaMap.isEmpty(); } - CoreIPC::Connection* allowedConnection() const { return m_allowedConnection.get(); } - void setAllowedConnection(CoreIPC::Connection*); + IPC::Connection* allowedConnection() const { return m_allowedConnection.get(); } + void setAllowedConnection(IPC::Connection*); - PassRefPtr<StorageArea> getOrCreateStorageArea(PassRefPtr<SecurityOrigin>); + Ref<StorageArea> getOrCreateStorageArea(Ref<SecurityOrigin>&&); void cloneTo(SessionStorageNamespace& newSessionStorageNamespace); + Vector<Ref<SecurityOrigin>> origins() const + { + Vector<Ref<SecurityOrigin>> origins; + + for (const auto& storageArea : m_storageAreaMap.values()) { + if (!storageArea->items().isEmpty()) + origins.append(storageArea->securityOrigin()); + } + + return origins; + } + + void clearStorageAreasMatchingOrigin(const SecurityOrigin& securityOrigin) + { + for (auto& storageArea : m_storageAreaMap.values()) { + if (storageArea->securityOrigin().equal(&securityOrigin)) + storageArea->clear(); + } + } + + void clearAllStorageAreas() + { + for (auto& storageArea : m_storageAreaMap.values()) + storageArea->clear(); + } + private: - SessionStorageNamespace(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + explicit SessionStorageNamespace(unsigned quotaInBytes); - RefPtr<CoreIPC::Connection> m_allowedConnection; + RefPtr<IPC::Connection> m_allowedConnection; unsigned m_quotaInBytes; - HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea> > m_storageAreaMap; + HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea>> m_storageAreaMap; }; -PassRefPtr<StorageManager::SessionStorageNamespace> StorageManager::SessionStorageNamespace::create(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) +Ref<StorageManager::SessionStorageNamespace> StorageManager::SessionStorageNamespace::create(unsigned quotaInBytes) { - return adoptRef(new SessionStorageNamespace(allowedConnection, quotaInBytes)); + return adoptRef(*new SessionStorageNamespace(quotaInBytes)); } -StorageManager::SessionStorageNamespace::SessionStorageNamespace(CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) - : m_allowedConnection(allowedConnection) - , m_quotaInBytes(quotaInBytes) +StorageManager::SessionStorageNamespace::SessionStorageNamespace(unsigned quotaInBytes) + : m_quotaInBytes(quotaInBytes) { } @@ -342,38 +430,38 @@ StorageManager::SessionStorageNamespace::~SessionStorageNamespace() { } -void StorageManager::SessionStorageNamespace::setAllowedConnection(CoreIPC::Connection* allowedConnection) +void StorageManager::SessionStorageNamespace::setAllowedConnection(IPC::Connection* allowedConnection) { ASSERT(!allowedConnection || !m_allowedConnection); m_allowedConnection = allowedConnection; } -PassRefPtr<StorageManager::StorageArea> StorageManager::SessionStorageNamespace::getOrCreateStorageArea(PassRefPtr<SecurityOrigin> securityOrigin) +Ref<StorageManager::StorageArea> StorageManager::SessionStorageNamespace::getOrCreateStorageArea(Ref<SecurityOrigin>&& securityOrigin) { - HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea> >::AddResult result = m_storageAreaMap.add(securityOrigin, 0); - if (result.isNewEntry) - result.iterator->value = StorageArea::create(0, result.iterator->key, m_quotaInBytes); + auto& slot = m_storageAreaMap.add(securityOrigin.ptr(), nullptr).iterator->value; + if (!slot) + slot = StorageArea::create(0, WTFMove(securityOrigin), m_quotaInBytes); - return result.iterator->value; + return *slot; } void StorageManager::SessionStorageNamespace::cloneTo(SessionStorageNamespace& newSessionStorageNamespace) { ASSERT_UNUSED(newSessionStorageNamespace, newSessionStorageNamespace.isEmpty()); - for (HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea> >::const_iterator it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) + for (HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageArea>>::const_iterator it = m_storageAreaMap.begin(), end = m_storageAreaMap.end(); it != end; ++it) newSessionStorageNamespace.m_storageAreaMap.add(it->key, it->value->clone()); } -PassRefPtr<StorageManager> StorageManager::create() +Ref<StorageManager> StorageManager::create(const String& localStorageDirectory) { - return adoptRef(new StorageManager); + return adoptRef(*new StorageManager(localStorageDirectory)); } -StorageManager::StorageManager() +StorageManager::StorageManager(const String& localStorageDirectory) : m_queue(WorkQueue::create("com.apple.WebKit.StorageManager")) - , m_localStorageDatabaseTracker(LocalStorageDatabaseTracker::create(m_queue)) + , m_localStorageDatabaseTracker(LocalStorageDatabaseTracker::create(m_queue, localStorageDirectory)) { // Make sure the encoding is initialized before we start dispatching things to the queue. UTF8Encoding(); @@ -383,70 +471,242 @@ StorageManager::~StorageManager() { } -void StorageManager::setLocalStorageDirectory(const String& localStorageDirectory) +void StorageManager::createSessionStorageNamespace(uint64_t storageNamespaceID, unsigned quotaInBytes) { - m_localStorageDatabaseTracker->setLocalStorageDirectory(localStorageDirectory); -} + RefPtr<StorageManager> storageManager(this); -void StorageManager::createSessionStorageNamespace(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) -{ - m_queue->dispatch(bind(&StorageManager::createSessionStorageNamespaceInternal, this, storageNamespaceID, RefPtr<CoreIPC::Connection>(allowedConnection), quotaInBytes)); + m_queue->dispatch([storageManager, storageNamespaceID, quotaInBytes] { + ASSERT(!storageManager->m_sessionStorageNamespaces.contains(storageNamespaceID)); + + storageManager->m_sessionStorageNamespaces.set(storageNamespaceID, SessionStorageNamespace::create(quotaInBytes)); + }); } void StorageManager::destroySessionStorageNamespace(uint64_t storageNamespaceID) { - m_queue->dispatch(bind(&StorageManager::destroySessionStorageNamespaceInternal, this, storageNamespaceID)); + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, storageNamespaceID] { + ASSERT(storageManager->m_sessionStorageNamespaces.contains(storageNamespaceID)); + storageManager->m_sessionStorageNamespaces.remove(storageNamespaceID); + }); } -void StorageManager::setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection) +void StorageManager::setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, IPC::Connection* allowedConnection) { - m_queue->dispatch(bind(&StorageManager::setAllowedSessionStorageNamespaceConnectionInternal, this, storageNamespaceID, RefPtr<CoreIPC::Connection>(allowedConnection))); + RefPtr<StorageManager> storageManager(this); + RefPtr<IPC::Connection> connection(allowedConnection); + + m_queue->dispatch([storageManager, connection, storageNamespaceID] { + ASSERT(storageManager->m_sessionStorageNamespaces.contains(storageNamespaceID)); + + storageManager->m_sessionStorageNamespaces.get(storageNamespaceID)->setAllowedConnection(connection.get()); + }); } void StorageManager::cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID) { - m_queue->dispatch(bind(&StorageManager::cloneSessionStorageNamespaceInternal, this, storageNamespaceID, newStorageNamespaceID)); + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, storageNamespaceID, newStorageNamespaceID] { + SessionStorageNamespace* sessionStorageNamespace = storageManager->m_sessionStorageNamespaces.get(storageNamespaceID); + if (!sessionStorageNamespace) { + // FIXME: We can get into this situation if someone closes the originating page from within a + // createNewPage callback. We bail for now, but we should really find a way to keep the session storage alive + // so we we'll clone the session storage correctly. + return; + } + + SessionStorageNamespace* newSessionStorageNamespace = storageManager->m_sessionStorageNamespaces.get(newStorageNamespaceID); + ASSERT(newSessionStorageNamespace); + + sessionStorageNamespace->cloneTo(*newSessionStorageNamespace); + }); } -void StorageManager::processWillOpenConnection(WebProcessProxy* webProcessProxy) +void StorageManager::processWillOpenConnection(WebProcessProxy&, IPC::Connection& connection) { - webProcessProxy->connection()->addWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName(), m_queue.get(), this); + connection.addWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName(), m_queue.get(), this); } -void StorageManager::processWillCloseConnection(WebProcessProxy* webProcessProxy) +void StorageManager::processDidCloseConnection(WebProcessProxy&, IPC::Connection& connection) { - webProcessProxy->connection()->removeWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName()); + connection.removeWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName()); + + RefPtr<StorageManager> storageManager(this); + RefPtr<IPC::Connection> protectedConnection(&connection); + + m_queue->dispatch([storageManager, protectedConnection] { + Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; + auto storageAreasByConnection = storageManager->m_storageAreasByConnection; + + for (auto it = storageAreasByConnection.begin(), end = storageAreasByConnection.end(); it != end; ++it) { + if (it->key.first != protectedConnection) + continue; - m_queue->dispatch(bind(&StorageManager::invalidateConnectionInternal, this, RefPtr<CoreIPC::Connection>(webProcessProxy->connection()))); + it->value->removeListener(*it->key.first, it->key.second); + connectionAndStorageMapIDPairsToRemove.append(it->key); + } + + for (size_t i = 0; i < connectionAndStorageMapIDPairsToRemove.size(); ++i) + storageManager->m_storageAreasByConnection.remove(connectionAndStorageMapIDPairsToRemove[i]); + }); } -void StorageManager::getOrigins(FunctionDispatcher* callbackDispatcher, void* context, void (*callback)(const Vector<RefPtr<WebCore::SecurityOrigin> >& securityOrigins, void* context)) +void StorageManager::getSessionStorageOrigins(std::function<void (HashSet<RefPtr<WebCore::SecurityOrigin>>&&)> completionHandler) { - m_queue->dispatch(bind(&StorageManager::getOriginsInternal, this, RefPtr<FunctionDispatcher>(callbackDispatcher), context, callback)); + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, completionHandler] { + HashSet<RefPtr<SecurityOrigin>> origins; + + for (const auto& sessionStorageNamespace : storageManager->m_sessionStorageNamespaces.values()) { + for (auto& origin : sessionStorageNamespace->origins()) + origins.add(WTFMove(origin)); + } + + RunLoop::main().dispatch([origins, completionHandler]() mutable { + completionHandler(WTFMove(origins)); + }); + }); } -void StorageManager::deleteEntriesForOrigin(SecurityOrigin* securityOrigin) +void StorageManager::deleteSessionStorageOrigins(std::function<void ()> completionHandler) { - m_queue->dispatch(bind(&StorageManager::deleteEntriesForOriginInternal, this, RefPtr<SecurityOrigin>(securityOrigin))); + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, completionHandler] { + for (auto& sessionStorageNamespace : storageManager->m_sessionStorageNamespaces.values()) + sessionStorageNamespace->clearAllStorageAreas(); + + RunLoop::main().dispatch(completionHandler); + }); } -void StorageManager::deleteAllEntries() +void StorageManager::deleteSessionStorageEntriesForOrigins(const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, std::function<void ()> completionHandler) { - m_queue->dispatch(bind(&StorageManager::deleteAllEntriesInternal, this)); + Vector<RefPtr<WebCore::SecurityOrigin>> copiedOrigins; + copiedOrigins.reserveInitialCapacity(origins.size()); + + for (auto& origin : origins) + copiedOrigins.uncheckedAppend(origin->isolatedCopy()); + + RefPtr<StorageManager> storageManager(this); + m_queue->dispatch([storageManager, copiedOrigins, completionHandler] { + for (auto& origin : copiedOrigins) { + for (auto& sessionStorageNamespace : storageManager->m_sessionStorageNamespaces.values()) + sessionStorageNamespace->clearStorageAreasMatchingOrigin(*origin); + } + + RunLoop::main().dispatch(completionHandler); + }); } -void StorageManager::createLocalStorageMap(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& securityOriginData) +void StorageManager::getLocalStorageOrigins(std::function<void (HashSet<RefPtr<WebCore::SecurityOrigin>>&&)> completionHandler) { - std::pair<RefPtr<CoreIPC::Connection>, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, completionHandler] { + HashSet<RefPtr<SecurityOrigin>> origins; + + for (auto& origin : storageManager->m_localStorageDatabaseTracker->origins()) + origins.add(WTFMove(origin)); + + for (auto& transientLocalStorageNamespace : storageManager->m_transientLocalStorageNamespaces.values()) { + for (auto& origin : transientLocalStorageNamespace->origins()) + origins.add(WTFMove(origin)); + } + + RunLoop::main().dispatch([origins, completionHandler]() mutable { + completionHandler(WTFMove(origins)); + }); + }); +} + +void StorageManager::getLocalStorageOriginDetails(std::function<void (Vector<LocalStorageDatabaseTracker::OriginDetails>)> completionHandler) +{ + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, completionHandler] { + auto originDetails = storageManager->m_localStorageDatabaseTracker->originDetails(); + + RunLoop::main().dispatch([originDetails, completionHandler]() mutable { + completionHandler(WTFMove(originDetails)); + }); + }); +} + +void StorageManager::deleteLocalStorageEntriesForOrigin(const SecurityOrigin& securityOrigin) +{ + RefPtr<StorageManager> storageManager(this); + + RefPtr<SecurityOrigin> copiedOrigin = securityOrigin.isolatedCopy(); + m_queue->dispatch([storageManager, copiedOrigin] { + for (auto& localStorageNamespace : storageManager->m_localStorageNamespaces.values()) + localStorageNamespace->clearStorageAreasMatchingOrigin(*copiedOrigin); + + for (auto& transientLocalStorageNamespace : storageManager->m_transientLocalStorageNamespaces.values()) + transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(*copiedOrigin); + + storageManager->m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(copiedOrigin.get()); + }); +} + +void StorageManager::deleteLocalStorageOriginsModifiedSince(std::chrono::system_clock::time_point time, std::function<void ()> completionHandler) +{ + RefPtr<StorageManager> storageManager(this); + + m_queue->dispatch([storageManager, time, completionHandler] { + auto deletedOrigins = storageManager->m_localStorageDatabaseTracker->deleteDatabasesModifiedSince(time); + + for (const auto& origin : deletedOrigins) { + for (auto& localStorageNamespace : storageManager->m_localStorageNamespaces.values()) + localStorageNamespace->clearStorageAreasMatchingOrigin(origin.get()); + } + + for (auto& transientLocalStorageNamespace : storageManager->m_transientLocalStorageNamespaces.values()) + transientLocalStorageNamespace->clearAllStorageAreas(); + + RunLoop::main().dispatch(completionHandler); + }); +} + +void StorageManager::deleteLocalStorageEntriesForOrigins(const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, std::function<void ()> completionHandler) +{ + Vector<RefPtr<WebCore::SecurityOrigin>> copiedOrigins; + copiedOrigins.reserveInitialCapacity(origins.size()); + + for (auto& origin : origins) + copiedOrigins.uncheckedAppend(origin->isolatedCopy()); + + RefPtr<StorageManager> storageManager(this); + m_queue->dispatch([storageManager, copiedOrigins, completionHandler] { + for (auto& origin : copiedOrigins) { + for (auto& localStorageNamespace : storageManager->m_localStorageNamespaces.values()) + localStorageNamespace->clearStorageAreasMatchingOrigin(*origin); + + for (auto& transientLocalStorageNamespace : storageManager->m_transientLocalStorageNamespaces.values()) + transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(*origin); + + storageManager->m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(origin.get()); + } + + RunLoop::main().dispatch(completionHandler); + }); +} + +void StorageManager::createLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& securityOriginData) +{ + std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); // FIXME: This should be a message check. - ASSERT((HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::isValidKey(connectionAndStorageMapIDPair))); + ASSERT((HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair))); - HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, 0); + HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, nullptr); // FIXME: These should be a message checks. ASSERT(result.isNewEntry); - ASSERT((HashMap<uint64_t, RefPtr<LocalStorageNamespace> >::isValidKey(storageNamespaceID))); + ASSERT((HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::isValidKey(storageNamespaceID))); LocalStorageNamespace* localStorageNamespace = getOrCreateLocalStorageNamespace(storageNamespaceID); @@ -459,10 +719,47 @@ void StorageManager::createLocalStorageMap(CoreIPC::Connection* connection, uint result.iterator->value = storageArea.release(); } -void StorageManager::createSessionStorageMap(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& securityOriginData) +void StorageManager::createTransientLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& topLevelOriginData, const SecurityOriginData& securityOriginData) { // FIXME: This should be a message check. - ASSERT((HashMap<uint64_t, RefPtr<SessionStorageNamespace> >::isValidKey(storageNamespaceID))); + ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID })); + + Ref<SecurityOrigin> origin = securityOriginData.securityOrigin(); + + // See if we already have session storage for this connection/origin combo. + // If so, update the map with the new ID, otherwise keep on trucking. + for (auto it = m_storageAreasByConnection.begin(), end = m_storageAreasByConnection.end(); it != end; ++it) { + if (it->key.first != &connection) + continue; + Ref<StorageArea> area = *it->value; + if (!area->isSessionStorage()) + continue; + if (!origin->isSameSchemeHostPort(&area->securityOrigin())) + continue; + area->addListener(connection, storageMapID); + m_storageAreasByConnection.remove(it); + m_storageAreasByConnection.add({ &connection, storageMapID }, WTFMove(area)); + return; + } + + auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value; + + // FIXME: This should be a message check. + ASSERT(!slot); + + TransientLocalStorageNamespace* transientLocalStorageNamespace = getOrCreateTransientLocalStorageNamespace(storageNamespaceID, topLevelOriginData.securityOrigin()); + + auto storageArea = transientLocalStorageNamespace->getOrCreateStorageArea(securityOriginData.securityOrigin()); + storageArea->addListener(connection, storageMapID); + + slot = WTFMove(storageArea); +} + +void StorageManager::createSessionStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData& securityOriginData) +{ + // FIXME: This should be a message check. + ASSERT(m_sessionStorageNamespaces.isValidKey(storageNamespaceID)); + SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); if (!sessionStorageNamespace) { // We're getting an incoming message from the web process that's for session storage for a web page @@ -470,43 +767,46 @@ void StorageManager::createSessionStorageMap(CoreIPC::Connection* connection, ui return; } - std::pair<RefPtr<CoreIPC::Connection>, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); - // FIXME: This should be a message check. - ASSERT((HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::isValidKey(connectionAndStorageMapIDPair))); + ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID })); - HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, 0); + auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value; // FIXME: This should be a message check. - ASSERT(result.isNewEntry); + ASSERT(!slot); // FIXME: This should be a message check. - ASSERT(connection == sessionStorageNamespace->allowedConnection()); + ASSERT(&connection == sessionStorageNamespace->allowedConnection()); - RefPtr<StorageArea> storageArea = sessionStorageNamespace->getOrCreateStorageArea(securityOriginData.securityOrigin()); + auto storageArea = sessionStorageNamespace->getOrCreateStorageArea(securityOriginData.securityOrigin()); storageArea->addListener(connection, storageMapID); - result.iterator->value = storageArea.release(); + slot = WTFMove(storageArea); } -void StorageManager::destroyStorageMap(CoreIPC::Connection* connection, uint64_t storageMapID) +void StorageManager::destroyStorageMap(IPC::Connection& connection, uint64_t storageMapID) { - std::pair<RefPtr<CoreIPC::Connection>, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); + std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); // FIXME: This should be a message check. - ASSERT((HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::isValidKey(connectionAndStorageMapIDPair))); + ASSERT(m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair)); - HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::iterator it = m_storageAreasByConnection.find(connectionAndStorageMapIDPair); + auto it = m_storageAreasByConnection.find(connectionAndStorageMapIDPair); if (it == m_storageAreasByConnection.end()) { // The connection has been removed because the last page was closed. return; } it->value->removeListener(connection, storageMapID); + + // Don't remove session storage maps. The web process may reconnect and expect the data to still be around. + if (it->value->isSessionStorage()) + return; + m_storageAreasByConnection.remove(connectionAndStorageMapIDPair); } -void StorageManager::getValues(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values) +void StorageManager::getValues(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { @@ -515,10 +815,10 @@ void StorageManager::getValues(CoreIPC::Connection* connection, uint64_t storage } values = storageArea->items(); - connection->send(Messages::StorageAreaMap::DidGetValues(storageMapSeed), storageMapID); + connection.send(Messages::StorageAreaMap::DidGetValues(storageMapSeed), storageMapID); } -void StorageManager::setItem(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString) +void StorageManager::setItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { @@ -527,11 +827,11 @@ void StorageManager::setItem(CoreIPC::Connection* connection, uint64_t storageMa } bool quotaError; - storageArea->setItem(connection, sourceStorageAreaID, key, value, urlString, quotaError); - connection->send(Messages::StorageAreaMap::DidSetItem(storageMapSeed, key, quotaError), storageMapID); + storageArea->setItem(&connection, sourceStorageAreaID, key, value, urlString, quotaError); + connection.send(Messages::StorageAreaMap::DidSetItem(storageMapSeed, key, quotaError), storageMapID); } -void StorageManager::removeItem(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString) +void StorageManager::removeItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { @@ -539,11 +839,11 @@ void StorageManager::removeItem(CoreIPC::Connection* connection, uint64_t storag return; } - storageArea->removeItem(connection, sourceStorageAreaID, key, urlString); - connection->send(Messages::StorageAreaMap::DidRemoveItem(storageMapSeed, key), storageMapID); + storageArea->removeItem(&connection, sourceStorageAreaID, key, urlString); + connection.send(Messages::StorageAreaMap::DidRemoveItem(storageMapSeed, key), storageMapID); } -void StorageManager::clear(CoreIPC::Connection* connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString) +void StorageManager::clear(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { @@ -551,105 +851,60 @@ void StorageManager::clear(CoreIPC::Connection* connection, uint64_t storageMapI return; } - storageArea->clear(connection, sourceStorageAreaID, urlString); - connection->send(Messages::StorageAreaMap::DidClear(storageMapSeed), storageMapID); -} - -void StorageManager::createSessionStorageNamespaceInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes) -{ - ASSERT(!m_sessionStorageNamespaces.contains(storageNamespaceID)); - - m_sessionStorageNamespaces.set(storageNamespaceID, SessionStorageNamespace::create(allowedConnection, quotaInBytes)); + storageArea->clear(&connection, sourceStorageAreaID, urlString); + connection.send(Messages::StorageAreaMap::DidClear(storageMapSeed), storageMapID); } -void StorageManager::destroySessionStorageNamespaceInternal(uint64_t storageNamespaceID) +void StorageManager::applicationWillTerminate() { - ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); - m_sessionStorageNamespaces.remove(storageNamespaceID); -} + BinarySemaphore semaphore; + m_queue->dispatch([this, &semaphore] { + Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; + for (auto& connectionStorageAreaPair : m_storageAreasByConnection) { + connectionStorageAreaPair.value->removeListener(*connectionStorageAreaPair.key.first, connectionStorageAreaPair.key.second); + connectionAndStorageMapIDPairsToRemove.append(connectionStorageAreaPair.key); + } -void StorageManager::setAllowedSessionStorageNamespaceConnectionInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection) -{ - ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); + for (auto& connectionStorageAreaPair : connectionAndStorageMapIDPairsToRemove) + m_storageAreasByConnection.remove(connectionStorageAreaPair); - m_sessionStorageNamespaces.get(storageNamespaceID)->setAllowedConnection(allowedConnection); + semaphore.signal(); + }); + semaphore.wait(std::numeric_limits<double>::max()); } -void StorageManager::cloneSessionStorageNamespaceInternal(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID) +StorageManager::StorageArea* StorageManager::findStorageArea(IPC::Connection& connection, uint64_t storageMapID) const { - SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); - ASSERT(sessionStorageNamespace); - - SessionStorageNamespace* newSessionStorageNamespace = m_sessionStorageNamespaces.get(newStorageNamespaceID); - ASSERT(newSessionStorageNamespace); + std::pair<IPC::Connection*, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); - sessionStorageNamespace->cloneTo(*newSessionStorageNamespace); -} - -void StorageManager::invalidateConnectionInternal(CoreIPC::Connection* connection) -{ - Vector<std::pair<RefPtr<CoreIPC::Connection>, uint64_t> > connectionAndStorageMapIDPairsToRemove; - HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> > storageAreasByConnection = m_storageAreasByConnection; - for (HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::const_iterator it = storageAreasByConnection.begin(), end = storageAreasByConnection.end(); it != end; ++it) { - if (it->key.first != connection) - continue; - - it->value->removeListener(it->key.first.get(), it->key.second); - connectionAndStorageMapIDPairsToRemove.append(it->key); - } - - for (size_t i = 0; i < connectionAndStorageMapIDPairsToRemove.size(); ++i) - m_storageAreasByConnection.remove(connectionAndStorageMapIDPairsToRemove[i]); -} - -StorageManager::StorageArea* StorageManager::findStorageArea(CoreIPC::Connection* connection, uint64_t storageMapID) const -{ - std::pair<CoreIPC::Connection*, uint64_t> connectionAndStorageMapIDPair(connection, storageMapID); - if (!HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> >::isValidKey(connectionAndStorageMapIDPair)) - return 0; + if (!m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair)) + return nullptr; return m_storageAreasByConnection.get(connectionAndStorageMapIDPair); } StorageManager::LocalStorageNamespace* StorageManager::getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID) { - if (!HashMap<uint64_t, RefPtr<LocalStorageNamespace> >::isValidKey(storageNamespaceID)) + if (!m_localStorageNamespaces.isValidKey(storageNamespaceID)) return 0; - HashMap<uint64_t, RefPtr<LocalStorageNamespace> >::AddResult result = m_localStorageNamespaces.add(storageNamespaceID, 0); - if (result.isNewEntry) - result.iterator->value = LocalStorageNamespace::create(this, storageNamespaceID); + auto& slot = m_localStorageNamespaces.add(storageNamespaceID, nullptr).iterator->value; + if (!slot) + slot = LocalStorageNamespace::create(this, storageNamespaceID); - return result.iterator->value.get(); + return slot.get(); } -static void callCallbackFunction(void* context, void (*callbackFunction)(const Vector<RefPtr<WebCore::SecurityOrigin> >& securityOrigins, void* context), Vector<RefPtr<WebCore::SecurityOrigin> >* securityOriginsPtr) +StorageManager::TransientLocalStorageNamespace* StorageManager::getOrCreateTransientLocalStorageNamespace(uint64_t storageNamespaceID, WebCore::SecurityOrigin& topLevelOrigin) { - OwnPtr<Vector<RefPtr<WebCore::SecurityOrigin> > > securityOrigins = adoptPtr(securityOriginsPtr); - callbackFunction(*securityOrigins, context); -} + if (!m_transientLocalStorageNamespaces.isValidKey({ storageNamespaceID, &topLevelOrigin })) + return nullptr; -void StorageManager::getOriginsInternal(FunctionDispatcher* dispatcher, void* context, void (*callbackFunction)(const Vector<RefPtr<WebCore::SecurityOrigin> >& securityOrigins, void* context)) -{ - OwnPtr<Vector<RefPtr<WebCore::SecurityOrigin> > > securityOrigins = adoptPtr(new Vector<RefPtr<WebCore::SecurityOrigin> >(m_localStorageDatabaseTracker->origins())); - dispatcher->dispatch(bind(callCallbackFunction, context, callbackFunction, securityOrigins.leakPtr())); -} - -void StorageManager::deleteEntriesForOriginInternal(SecurityOrigin* securityOrigin) -{ - for (HashMap<uint64_t, RefPtr<LocalStorageNamespace> >::iterator it = m_localStorageNamespaces.begin(), end = m_localStorageNamespaces.end(); it != end; ++it) - it->value->clearStorageAreasMatchingOrigin(securityOrigin); - - m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(securityOrigin); -} - -void StorageManager::deleteAllEntriesInternal() -{ - for (HashMap<uint64_t, RefPtr<LocalStorageNamespace> >::iterator it = m_localStorageNamespaces.begin(), end = m_localStorageNamespaces.end(); it != end; ++it) - it->value->clearAllStorageAreas(); + auto& slot = m_transientLocalStorageNamespaces.add({ storageNamespaceID, &topLevelOrigin }, nullptr).iterator->value; + if (!slot) + slot = TransientLocalStorageNamespace::create(); - m_localStorageDatabaseTracker->deleteAllDatabases(); + return slot.get(); } - } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Storage/StorageManager.h b/Source/WebKit2/UIProcess/Storage/StorageManager.h index 2f0f5bfa9..a0f179313 100644 --- a/Source/WebKit2/UIProcess/Storage/StorageManager.h +++ b/Source/WebKit2/UIProcess/Storage/StorageManager.h @@ -27,87 +27,88 @@ #define StorageManager_h #include "Connection.h" +#include "LocalStorageDatabaseTracker.h" +#include <WebCore/SecurityOriginHash.h> +#include <chrono> #include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> +#include <wtf/HashSet.h> #include <wtf/ThreadSafeRefCounted.h> #include <wtf/text/StringHash.h> -class WorkQueue; - namespace WebCore { class SecurityOrigin; +struct SecurityOriginData; } namespace WebKit { -struct SecurityOriginData; class LocalStorageDatabaseTracker; class WebProcessProxy; -class StorageManager : public CoreIPC::Connection::WorkQueueMessageReceiver { +class StorageManager : public IPC::Connection::WorkQueueMessageReceiver { public: - static PassRefPtr<StorageManager> create(); + static Ref<StorageManager> create(const String& localStorageDirectory); ~StorageManager(); - void setLocalStorageDirectory(const String&); - - void createSessionStorageNamespace(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); + void createSessionStorageNamespace(uint64_t storageNamespaceID, unsigned quotaInBytes); void destroySessionStorageNamespace(uint64_t storageNamespaceID); - void setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection); + void setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, IPC::Connection* allowedConnection); void cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID); - void processWillOpenConnection(WebProcessProxy*); - void processWillCloseConnection(WebProcessProxy*); + void processWillOpenConnection(WebProcessProxy&, IPC::Connection&); + void processDidCloseConnection(WebProcessProxy&, IPC::Connection&); + void applicationWillTerminate(); - // FIXME: Instead of a context + C function, this should take a WTF::Function, but we currently don't - // support arguments in functions. - void getOrigins(FunctionDispatcher* callbackDispatcher, void* context, void (*callback)(const Vector<RefPtr<WebCore::SecurityOrigin> >& securityOrigins, void* context)); - void deleteEntriesForOrigin(WebCore::SecurityOrigin*); - void deleteAllEntries(); + void getSessionStorageOrigins(std::function<void (HashSet<RefPtr<WebCore::SecurityOrigin>>&&)> completionHandler); + void deleteSessionStorageOrigins(std::function<void ()> completionHandler); + void deleteSessionStorageEntriesForOrigins(const Vector<RefPtr<WebCore::SecurityOrigin>>&, std::function<void ()> completionHandler); -private: - StorageManager(); + void getLocalStorageOrigins(std::function<void (HashSet<RefPtr<WebCore::SecurityOrigin>>&&)> completionHandler); + void deleteLocalStorageEntriesForOrigin(const WebCore::SecurityOrigin&); - // CoreIPC::Connection::WorkQueueMessageReceiver. - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) OVERRIDE; + void deleteLocalStorageOriginsModifiedSince(std::chrono::system_clock::time_point, std::function<void ()> completionHandler); + void deleteLocalStorageEntriesForOrigins(const Vector<RefPtr<WebCore::SecurityOrigin>>&, std::function<void ()> completionHandler); - // Message handlers. - void createLocalStorageMap(CoreIPC::Connection*, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData&); - void createSessionStorageMap(CoreIPC::Connection*, uint64_t storageMapID, uint64_t storageNamespaceID, const SecurityOriginData&); - void destroyStorageMap(CoreIPC::Connection*, uint64_t storageMapID); + void getLocalStorageOriginDetails(std::function<void (Vector<LocalStorageDatabaseTracker::OriginDetails>)> completionHandler); - void getValues(CoreIPC::Connection*, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values); - void setItem(CoreIPC::Connection*, uint64_t storageAreaID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString); - void removeItem(CoreIPC::Connection*, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString); - void clear(CoreIPC::Connection*, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString); +private: + explicit StorageManager(const String& localStorageDirectory); - void createSessionStorageNamespaceInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection, unsigned quotaInBytes); - void destroySessionStorageNamespaceInternal(uint64_t storageNamespaceID); - void setAllowedSessionStorageNamespaceConnectionInternal(uint64_t storageNamespaceID, CoreIPC::Connection* allowedConnection); - void cloneSessionStorageNamespaceInternal(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID); + // IPC::Connection::WorkQueueMessageReceiver. + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) override; - void invalidateConnectionInternal(CoreIPC::Connection*); + // Message handlers. + void createLocalStorageMap(IPC::Connection&, uint64_t storageMapID, uint64_t storageNamespaceID, const WebCore::SecurityOriginData&); + void createTransientLocalStorageMap(IPC::Connection&, uint64_t storageMapID, uint64_t storageNamespaceID, const WebCore::SecurityOriginData& topLevelOriginData, const WebCore::SecurityOriginData&); + void createSessionStorageMap(IPC::Connection&, uint64_t storageMapID, uint64_t storageNamespaceID, const WebCore::SecurityOriginData&); + void destroyStorageMap(IPC::Connection&, uint64_t storageMapID); + + void getValues(IPC::Connection&, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values); + void setItem(IPC::Connection&, uint64_t storageAreaID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString); + void removeItem(IPC::Connection&, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString); + void clear(IPC::Connection&, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString); class StorageArea; - StorageArea* findStorageArea(CoreIPC::Connection*, uint64_t) const; + StorageArea* findStorageArea(IPC::Connection&, uint64_t) const; class LocalStorageNamespace; LocalStorageNamespace* getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID); - void getOriginsInternal(FunctionDispatcher* callbackDispatcher, void* context, void (*callback)(const Vector<RefPtr<WebCore::SecurityOrigin> >& securityOrigins, void* context)); - void deleteEntriesForOriginInternal(WebCore::SecurityOrigin*); - void deleteAllEntriesInternal(); + class TransientLocalStorageNamespace; + TransientLocalStorageNamespace* getOrCreateTransientLocalStorageNamespace(uint64_t storageNamespaceID, WebCore::SecurityOrigin& topLevelOrigin); RefPtr<WorkQueue> m_queue; RefPtr<LocalStorageDatabaseTracker> m_localStorageDatabaseTracker; - HashMap<uint64_t, RefPtr<LocalStorageNamespace> > m_localStorageNamespaces; + HashMap<uint64_t, RefPtr<LocalStorageNamespace>> m_localStorageNamespaces; + + HashMap<std::pair<uint64_t, RefPtr<WebCore::SecurityOrigin>>, RefPtr<TransientLocalStorageNamespace>> m_transientLocalStorageNamespaces; class SessionStorageNamespace; - HashMap<uint64_t, RefPtr<SessionStorageNamespace> > m_sessionStorageNamespaces; + HashMap<uint64_t, RefPtr<SessionStorageNamespace>> m_sessionStorageNamespaces; - HashMap<std::pair<RefPtr<CoreIPC::Connection>, uint64_t>, RefPtr<StorageArea> > m_storageAreasByConnection; + HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>> m_storageAreasByConnection; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/Storage/StorageManager.messages.in b/Source/WebKit2/UIProcess/Storage/StorageManager.messages.in index 22d0121fe..25789f74c 100644 --- a/Source/WebKit2/UIProcess/Storage/StorageManager.messages.in +++ b/Source/WebKit2/UIProcess/Storage/StorageManager.messages.in @@ -21,13 +21,14 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. messages -> StorageManager { - CreateLocalStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, WebKit::SecurityOriginData securityOriginData) WantsConnection - CreateSessionStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, WebKit::SecurityOriginData securityOriginData) WantsConnection + CreateLocalStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, struct WebCore::SecurityOriginData securityOriginData) WantsConnection + CreateTransientLocalStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, struct WebCore::SecurityOriginData topLevelSecurityOriginData, struct WebCore::SecurityOriginData securityOriginData) WantsConnection + CreateSessionStorageMap(uint64_t storageMapID, uint64_t storageNamespaceID, struct WebCore::SecurityOriginData securityOriginData) WantsConnection DestroyStorageMap(uint64_t storageMapID) WantsConnection - GetValues(uint64_t storageMapID, uint64_t storageMapSeed) -> (WTF::HashMap<WTF::String, WTF::String> values) WantsConnection + GetValues(uint64_t storageMapID, uint64_t storageMapSeed) -> (HashMap<String, String> values) WantsConnection - SetItem(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, WTF::String key, WTF::String value, WTF::String urlString) WantsConnection - RemoveItem(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, WTF::String key, WTF::String urlString) WantsConnection - Clear(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, WTF::String urlString) WantsConnection + SetItem(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, String key, String value, String urlString) WantsConnection + RemoveItem(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, String key, String urlString) WantsConnection + Clear(uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, String urlString) WantsConnection } diff --git a/Source/WebKit2/UIProcess/TextChecker.h b/Source/WebKit2/UIProcess/TextChecker.h index bd08d354d..5f1d7101c 100644 --- a/Source/WebKit2/UIProcess/TextChecker.h +++ b/Source/WebKit2/UIProcess/TextChecker.h @@ -43,7 +43,7 @@ public: static void setContinuousSpellCheckingEnabled(bool); static void setGrammarCheckingEnabled(bool); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) static void setAutomaticSpellingCorrectionEnabled(bool); static void setAutomaticQuoteSubstitutionEnabled(bool); static void setAutomaticDashSubstitutionEnabled(bool); @@ -62,15 +62,20 @@ public: static void toggleSubstitutionsPanelIsShowing(); #endif +#if PLATFORM(GTK) + static void setSpellCheckingLanguages(const Vector<String>&); + static Vector<String> loadedSpellCheckingLanguages(); +#endif + static void continuousSpellCheckingEnabledStateChanged(bool); static void grammarCheckingEnabledStateChanged(bool); static int64_t uniqueSpellDocumentTag(WebPageProxy*); static void closeSpellDocumentWithTag(int64_t); #if USE(UNIFIED_TEXT_CHECKING) - static Vector<WebCore::TextCheckingResult> checkTextOfParagraph(int64_t spellDocumentTag, const UChar* text, int length, uint64_t checkingTypes); + static Vector<WebCore::TextCheckingResult> checkTextOfParagraph(int64_t spellDocumentTag, StringView text, uint64_t checkingTypes); #endif - static void checkSpellingOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, int32_t& misspellingLocation, int32_t& misspellingLength); - static void checkGrammarOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, Vector<WebCore::GrammarDetail>&, int32_t& badGrammarLocation, int32_t& badGrammarLength); + static void checkSpellingOfString(int64_t spellDocumentTag, StringView text, int32_t& misspellingLocation, int32_t& misspellingLength); + static void checkGrammarOfString(int64_t spellDocumentTag, StringView text, Vector<WebCore::GrammarDetail>&, int32_t& badGrammarLocation, int32_t& badGrammarLength); static bool spellingUIIsShowing(); static void toggleSpellingUIIsShowing(); static void updateSpellingUIWithMisspelledWord(int64_t spellDocumentTag, const String& misspelledWord); diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.mm b/Source/WebKit2/UIProcess/UserContent/WebScriptMessageHandler.cpp index 277e69d69..bfacf041a 100644 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.mm +++ b/Source/WebKit2/UIProcess/UserContent/WebScriptMessageHandler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,30 +24,49 @@ */ #include "config.h" -#include "RemoteLayerTreeDrawingAreaProxy.h" +#include "WebScriptMessageHandler.h" + +#include "ArgumentCoders.h" namespace WebKit { -PassOwnPtr<RemoteLayerTreeDrawingAreaProxy> RemoteLayerTreeDrawingAreaProxy::create(WebPageProxy* webPageProxy) +void WebScriptMessageHandlerHandle::encode(IPC::ArgumentEncoder& encoder) const { - return adoptPtr(new RemoteLayerTreeDrawingAreaProxy(webPageProxy)); + encoder << identifier; + encoder << name; } -RemoteLayerTreeDrawingAreaProxy::RemoteLayerTreeDrawingAreaProxy(WebPageProxy* webPageProxy) - : DrawingAreaProxy(DrawingAreaTypeRemoteLayerTree, webPageProxy) - , m_remoteLayerTreeHost(webPageProxy) +bool WebScriptMessageHandlerHandle::decode(IPC::ArgumentDecoder& decoder, WebScriptMessageHandlerHandle& handle) { + if (!decoder.decode(handle.identifier)) + return false; + + if (!decoder.decode(handle.name)) + return false; + + return true; +} + +static uint64_t generateIdentifier() +{ + static uint64_t identifier; + + return ++identifier; } -RemoteLayerTreeDrawingAreaProxy::~RemoteLayerTreeDrawingAreaProxy() +PassRefPtr<WebScriptMessageHandler> WebScriptMessageHandler::create(std::unique_ptr<Client> client, const String& name) { + return adoptRef(new WebScriptMessageHandler(WTFMove(client), name)); } -void RemoteLayerTreeDrawingAreaProxy::sizeDidChange() +WebScriptMessageHandler::WebScriptMessageHandler(std::unique_ptr<Client> client, const String& name) + : m_identifier(generateIdentifier()) + , m_client(WTFMove(client)) + , m_name(name) { } -void RemoteLayerTreeDrawingAreaProxy::deviceScaleFactorDidChange() +WebScriptMessageHandler::~WebScriptMessageHandler() { } diff --git a/Source/WebKit2/UIProcess/FindIndicator.h b/Source/WebKit2/UIProcess/UserContent/WebScriptMessageHandler.h index a34973b84..22d73bbcc 100644 --- a/Source/WebKit2/UIProcess/FindIndicator.h +++ b/Source/WebKit2/UIProcess/UserContent/WebScriptMessageHandler.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,42 +23,63 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef FindIndicator_h -#define FindIndicator_h +#ifndef WebScriptMessageHandler_h +#define WebScriptMessageHandler_h -#include "ShareableBitmap.h" -#include <WebCore/FloatRect.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> -#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace IPC { +class ArgumentDecoder; +class ArgumentEncoder; +} namespace WebCore { - class GraphicsContext; +struct SecurityOriginData; +class SerializedScriptValue; } namespace WebKit { -class FindIndicator : public RefCounted<FindIndicator> { +class WebPageProxy; +class WebFrameProxy; + +struct WebScriptMessageHandlerHandle { + void encode(IPC::ArgumentEncoder&) const; + static bool decode(IPC::ArgumentDecoder&, WebScriptMessageHandlerHandle&); + + uint64_t identifier; + String name; +}; + +class WebScriptMessageHandler : public RefCounted<WebScriptMessageHandler> { public: - static PassRefPtr<FindIndicator> create(const WebCore::FloatRect& selectionRectInWindowCoordinates, const Vector<WebCore::FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle); - ~FindIndicator(); + class Client { + public: + virtual ~Client() { } + virtual void didPostMessage(WebPageProxy&, WebFrameProxy&, const WebCore::SecurityOriginData&, WebCore::SerializedScriptValue&) = 0; + }; - WebCore::FloatRect selectionRectInWindowCoordinates() const { return m_selectionRectInWindowCoordinates; } - WebCore::FloatRect frameRect() const; + static PassRefPtr<WebScriptMessageHandler> create(std::unique_ptr<Client>, const String& name); + virtual ~WebScriptMessageHandler(); - ShareableBitmap* contentImage() const { return m_contentImage.get(); } + WebScriptMessageHandlerHandle handle() { return { m_identifier, m_name }; } - void draw(WebCore::GraphicsContext&, const WebCore::IntRect& dirtyRect); + uint64_t identifier() const { return m_identifier; } + String name() const { return m_name; } + + Client& client() const { return *m_client; } private: - FindIndicator(const WebCore::FloatRect& selectionRect, const Vector<WebCore::FloatRect>& textRects, float contentImageScaleFactor, PassRefPtr<ShareableBitmap> contentImage); + WebScriptMessageHandler(std::unique_ptr<Client>, const String&); + + uint64_t m_identifier; - WebCore::FloatRect m_selectionRectInWindowCoordinates; - Vector<WebCore::FloatRect> m_textRectsInSelectionRectCoordinates; - float m_contentImageScaleFactor; - RefPtr<ShareableBitmap> m_contentImage; + std::unique_ptr<Client> m_client; + String m_name; }; -} // namespace WebKit - -#endif // FindIndicator_h +} // namespace API + +#endif // WebScriptMessageHandler_h diff --git a/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.cpp b/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.cpp new file mode 100644 index 000000000..b40662f06 --- /dev/null +++ b/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.cpp @@ -0,0 +1,233 @@ +/* + * Copyright (C) 2014 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 "WebUserContentControllerProxy.h" + +#include "APIArray.h" +#include "APIUserScript.h" +#include "APIUserStyleSheet.h" +#include "DataReference.h" +#include "WebProcessProxy.h" +#include "WebScriptMessageHandler.h" +#include "WebUserContentControllerMessages.h" +#include "WebUserContentControllerProxyMessages.h" +#include <WebCore/SerializedScriptValue.h> + +#if ENABLE(CONTENT_EXTENSIONS) +#include "APIUserContentExtension.h" +#include "WebCompiledContentExtension.h" +#endif + +namespace WebKit { + +static uint64_t generateIdentifier() +{ + static uint64_t identifier; + + return ++identifier; +} + +WebUserContentControllerProxy::WebUserContentControllerProxy() + : m_identifier(generateIdentifier()) + , m_userScripts(API::Array::create()) + , m_userStyleSheets(API::Array::create()) +{ +} + +WebUserContentControllerProxy::~WebUserContentControllerProxy() +{ + for (WebProcessProxy* process : m_processes) { + process->removeMessageReceiver(Messages::WebUserContentControllerProxy::messageReceiverName(), m_identifier); + process->didDestroyWebUserContentControllerProxy(*this); + } +} + +void WebUserContentControllerProxy::addProcess(WebProcessProxy& webProcessProxy) +{ + ASSERT(webProcessProxy.state() == WebProcessProxy::State::Running); + + if (!m_processes.add(&webProcessProxy).isNewEntry) + return; + + webProcessProxy.addMessageReceiver(Messages::WebUserContentControllerProxy::messageReceiverName(), m_identifier, *this); + + Vector<WebCore::UserScript> userScripts; + for (const auto& userScript : m_userScripts->elementsOfType<API::UserScript>()) + userScripts.append(userScript->userScript()); + webProcessProxy.connection()->send(Messages::WebUserContentController::AddUserScripts(userScripts), m_identifier); + + Vector<WebCore::UserStyleSheet> userStyleSheets; + for (const auto& userStyleSheet : m_userStyleSheets->elementsOfType<API::UserStyleSheet>()) + userStyleSheets.append(userStyleSheet->userStyleSheet()); + webProcessProxy.connection()->send(Messages::WebUserContentController::AddUserStyleSheets(userStyleSheets), m_identifier); + + Vector<WebScriptMessageHandlerHandle> messageHandlerHandles; + for (auto& handler : m_scriptMessageHandlers.values()) + messageHandlerHandles.append(handler->handle()); + webProcessProxy.connection()->send(Messages::WebUserContentController::AddUserScriptMessageHandlers(messageHandlerHandles), m_identifier); + +#if ENABLE(CONTENT_EXTENSIONS) + Vector<std::pair<String, WebCompiledContentExtensionData>> userContentExtensions; + for (const auto& userContentExtension : m_userContentExtensions.values()) + userContentExtensions.append(std::make_pair(userContentExtension->name(), userContentExtension->compiledExtension().data())); + webProcessProxy.connection()->send(Messages::WebUserContentController::AddUserContentExtensions(userContentExtensions), m_identifier); +#endif +} + +void WebUserContentControllerProxy::removeProcess(WebProcessProxy& webProcessProxy) +{ + ASSERT(m_processes.contains(&webProcessProxy)); + + m_processes.remove(&webProcessProxy); + webProcessProxy.removeMessageReceiver(Messages::WebUserContentControllerProxy::messageReceiverName(), m_identifier); +} + +void WebUserContentControllerProxy::addUserScript(API::UserScript& userScript) +{ + m_userScripts->elements().append(&userScript); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::AddUserScripts({ userScript.userScript() }), m_identifier); +} + +void WebUserContentControllerProxy::removeUserScript(const API::UserScript& userScript) +{ + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveUserScript({ userScript.userScript().url().string() }), m_identifier); + + m_userScripts->elements().removeAll(&userScript); +} + +void WebUserContentControllerProxy::removeAllUserScripts() +{ + m_userScripts->elements().clear(); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveAllUserScripts(), m_identifier); +} + +void WebUserContentControllerProxy::addUserStyleSheet(API::UserStyleSheet& userStyleSheet) +{ + m_userStyleSheets->elements().append(&userStyleSheet); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::AddUserStyleSheets({ userStyleSheet.userStyleSheet() }), m_identifier); +} + +void WebUserContentControllerProxy::removeUserStyleSheet(const API::UserStyleSheet& userStyleSheet) +{ + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveUserStyleSheet({ userStyleSheet.userStyleSheet().url().string() }), m_identifier); + + m_userStyleSheets->elements().removeAll(&userStyleSheet); +} + +void WebUserContentControllerProxy::removeAllUserStyleSheets() +{ + m_userStyleSheets->elements().clear(); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveAllUserStyleSheets(), m_identifier); +} + +bool WebUserContentControllerProxy::addUserScriptMessageHandler(WebScriptMessageHandler* handler) +{ + for (auto& existingHandler : m_scriptMessageHandlers.values()) { + if (existingHandler->name() == handler->name()) + return false; + } + + m_scriptMessageHandlers.add(handler->identifier(), handler); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::AddUserScriptMessageHandlers({ handler->handle() }), m_identifier); + + return true; +} + +void WebUserContentControllerProxy::removeUserMessageHandlerForName(const String& name) +{ + for (auto it = m_scriptMessageHandlers.begin(), end = m_scriptMessageHandlers.end(); it != end; ++it) { + if (it->value->name() == name) { + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveUserScriptMessageHandler(it->value->identifier()), m_identifier); + m_scriptMessageHandlers.remove(it); + return; + } + } +} + +void WebUserContentControllerProxy::didPostMessage(IPC::Connection& connection, uint64_t pageID, uint64_t frameID, const WebCore::SecurityOriginData& securityOrigin, uint64_t messageHandlerID, const IPC::DataReference& dataReference) +{ + WebPageProxy* page = WebProcessProxy::webPage(pageID); + if (!page) + return; + + WebProcessProxy* webProcess = WebProcessProxy::fromConnection(&connection); + WebFrameProxy* frame = webProcess->webFrame(frameID); + if (!frame) + return; + + if (!HashMap<uint64_t, RefPtr<WebScriptMessageHandler>>::isValidKey(messageHandlerID)) + return; + + RefPtr<WebScriptMessageHandler> handler = m_scriptMessageHandlers.get(messageHandlerID); + if (!handler) + return; + + handler->client().didPostMessage(*page, *frame, securityOrigin, + WebCore::SerializedScriptValue::adopt(dataReference.vector())); +} + +#if ENABLE(CONTENT_EXTENSIONS) +void WebUserContentControllerProxy::addUserContentExtension(API::UserContentExtension& userContentExtension) +{ + m_userContentExtensions.set(userContentExtension.name(), &userContentExtension); + + auto pair = std::make_pair(userContentExtension.name(), userContentExtension.compiledExtension().data()); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::AddUserContentExtensions({ pair }), m_identifier); +} + +void WebUserContentControllerProxy::removeUserContentExtension(const String& name) +{ + m_userContentExtensions.remove(name); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveUserContentExtension(name), m_identifier); +} + +void WebUserContentControllerProxy::removeAllUserContentExtensions() +{ + m_userContentExtensions.clear(); + + for (WebProcessProxy* process : m_processes) + process->connection()->send(Messages::WebUserContentController::RemoveAllUserContentExtensions(), m_identifier); +} +#endif + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.h b/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.h new file mode 100644 index 000000000..e9ff9a92e --- /dev/null +++ b/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.h @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2014 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 WebUserContentControllerProxy_h +#define WebUserContentControllerProxy_h + +#include "APIObject.h" +#include "MessageReceiver.h" +#include <wtf/Forward.h> +#include <wtf/HashMap.h> +#include <wtf/HashSet.h> +#include <wtf/PassRefPtr.h> +#include <wtf/Ref.h> +#include <wtf/RefCounted.h> +#include <wtf/Vector.h> +#include <wtf/text/StringHash.h> + +namespace API { +class Array; +class UserContentExtension; +class UserScript; +class UserStyleSheet; +} + +namespace IPC { +class DataReference; +} + +namespace WebCore { +struct SecurityOriginData; +} + +namespace WebKit { + +class WebProcessProxy; +class WebScriptMessageHandler; + +class WebUserContentControllerProxy : public API::ObjectImpl<API::Object::Type::UserContentController>, private IPC::MessageReceiver { +public: + static Ref<WebUserContentControllerProxy> create() + { + return adoptRef(*new WebUserContentControllerProxy); + } + explicit WebUserContentControllerProxy(); + ~WebUserContentControllerProxy(); + + uint64_t identifier() const { return m_identifier; } + + void addProcess(WebProcessProxy&); + void removeProcess(WebProcessProxy&); + + API::Array& userScripts() { return m_userScripts.get(); } + void addUserScript(API::UserScript&); + void removeUserScript(const API::UserScript&); + void removeAllUserScripts(); + + API::Array& userStyleSheets() { return m_userStyleSheets.get(); } + void addUserStyleSheet(API::UserStyleSheet&); + void removeUserStyleSheet(const API::UserStyleSheet&); + void removeAllUserStyleSheets(); + + // Returns false if there was a name conflict. + bool addUserScriptMessageHandler(WebScriptMessageHandler*); + void removeUserMessageHandlerForName(const String&); + +#if ENABLE(CONTENT_EXTENSIONS) + void addUserContentExtension(API::UserContentExtension&); + void removeUserContentExtension(const String&); + void removeAllUserContentExtensions(); +#endif + +private: + // IPC::MessageReceiver. + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + + void didPostMessage(IPC::Connection&, uint64_t pageID, uint64_t frameID, const WebCore::SecurityOriginData&, uint64_t messageHandlerID, const IPC::DataReference&); + + uint64_t m_identifier; + HashSet<WebProcessProxy*> m_processes; + Ref<API::Array> m_userScripts; + Ref<API::Array> m_userStyleSheets; + HashMap<uint64_t, RefPtr<WebScriptMessageHandler>> m_scriptMessageHandlers; + +#if ENABLE(CONTENT_EXTENSIONS) + HashMap<String, RefPtr<API::UserContentExtension>> m_userContentExtensions; +#endif +}; + +} // namespace WebKit + +#endif // WebUserContentControllerProxy_h diff --git a/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.messages.in b/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.messages.in new file mode 100644 index 000000000..3536d799d --- /dev/null +++ b/Source/WebKit2/UIProcess/UserContent/WebUserContentControllerProxy.messages.in @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2014 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. + */ + +messages -> WebUserContentControllerProxy { + DidPostMessage(uint64_t pageID, uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, uint64_t messageHandlerID, IPC::DataReference message) WantsConnection +} diff --git a/Source/WebKit2/UIProcess/UserMediaPermissionCheckProxy.cpp b/Source/WebKit2/UIProcess/UserMediaPermissionCheckProxy.cpp new file mode 100644 index 000000000..340d88d15 --- /dev/null +++ b/Source/WebKit2/UIProcess/UserMediaPermissionCheckProxy.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "UserMediaPermissionCheckProxy.h" + +#include "UserMediaPermissionRequestManagerProxy.h" + +namespace WebKit { + +UserMediaPermissionCheckProxy::UserMediaPermissionCheckProxy(UserMediaPermissionRequestManagerProxy& manager, uint64_t userMediaID) + : m_manager(&manager) + , m_userMediaID(userMediaID) +{ +} + +void UserMediaPermissionCheckProxy::setHasPersistentPermission(bool allowed) +{ + ASSERT(m_manager); + if (!m_manager) + return; + + m_manager->didCompleteUserMediaPermissionCheck(m_userMediaID, allowed); + m_manager = nullptr; +} + +void UserMediaPermissionCheckProxy::invalidate() +{ + m_manager = nullptr; +} + +} // namespace WebKit + diff --git a/Source/WebKit2/UIProcess/UserMediaPermissionCheckProxy.h b/Source/WebKit2/UIProcess/UserMediaPermissionCheckProxy.h new file mode 100644 index 000000000..bb1a0a3a4 --- /dev/null +++ b/Source/WebKit2/UIProcess/UserMediaPermissionCheckProxy.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2015 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef UserMediaPermissionCheckProxy_h +#define UserMediaPermissionCheckProxy_h + +#include "APIObject.h" +#include <WebCore/RealtimeMediaSource.h> +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace WebKit { + +class UserMediaPermissionRequestManagerProxy; + +class UserMediaPermissionCheckProxy : public API::ObjectImpl<API::Object::Type::UserMediaPermissionCheck> { +public: + static Ref<UserMediaPermissionCheckProxy> create(UserMediaPermissionRequestManagerProxy& manager, uint64_t userMediaID) + { + return adoptRef(*new UserMediaPermissionCheckProxy(manager, userMediaID)); + } + + void setHasPersistentPermission(bool allowed); + void invalidate(); + +private: + UserMediaPermissionCheckProxy(UserMediaPermissionRequestManagerProxy&, uint64_t userMediaID); + + UserMediaPermissionRequestManagerProxy* m_manager; + uint64_t m_userMediaID; +}; + +} // namespace WebKit + +#endif // UserMediaPermissionCheckProxy_h diff --git a/Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.cpp b/Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.cpp new file mode 100644 index 000000000..cde35fab6 --- /dev/null +++ b/Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2014 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 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "UserMediaPermissionRequestManagerProxy.h" + +#include "WebPageMessages.h" +#include "WebPageProxy.h" +#include "WebProcessProxy.h" + +namespace WebKit { + +UserMediaPermissionRequestManagerProxy::UserMediaPermissionRequestManagerProxy(WebPageProxy& page) + : m_page(page) +{ +} + +void UserMediaPermissionRequestManagerProxy::invalidateRequests() +{ + for (auto& request : m_pendingUserMediaRequests.values()) + request->invalidate(); + + m_pendingUserMediaRequests.clear(); +} + +Ref<UserMediaPermissionRequestProxy> UserMediaPermissionRequestManagerProxy::createRequest(uint64_t userMediaID, const Vector<String>& audioDeviceUIDs, const Vector<String>& videoDeviceUIDs) +{ + Ref<UserMediaPermissionRequestProxy> request = UserMediaPermissionRequestProxy::create(*this, userMediaID, audioDeviceUIDs, videoDeviceUIDs); + m_pendingUserMediaRequests.add(userMediaID, request.ptr()); + return request; +} + +void UserMediaPermissionRequestManagerProxy::didReceiveUserMediaPermissionDecision(uint64_t userMediaID, bool allowed, const String& audioDeviceUID, const String& videoDeviceUID) +{ + if (!m_page.isValid()) + return; + + if (!m_pendingUserMediaRequests.take(userMediaID)) + return; + +#if ENABLE(MEDIA_STREAM) + m_page.process().send(Messages::WebPage::DidReceiveUserMediaPermissionDecision(userMediaID, allowed, audioDeviceUID, videoDeviceUID), m_page.pageID()); +#else + UNUSED_PARAM(allowed); +#endif +} + +Ref<UserMediaPermissionCheckProxy> UserMediaPermissionRequestManagerProxy::createUserMediaPermissionCheck(uint64_t userMediaID) +{ + Ref<UserMediaPermissionCheckProxy> request = UserMediaPermissionCheckProxy::create(*this, userMediaID); + m_pendingDeviceRequests.add(userMediaID, request.ptr()); + return request; +} + +void UserMediaPermissionRequestManagerProxy::didCompleteUserMediaPermissionCheck(uint64_t userMediaID, bool allowed) +{ + if (!m_page.isValid()) + return; + + if (!m_pendingDeviceRequests.take(userMediaID)) + return; + +#if ENABLE(MEDIA_STREAM) + m_page.process().send(Messages::WebPage::DidCompleteUserMediaPermissionCheck(userMediaID, allowed), m_page.pageID()); +#else + UNUSED_PARAM(allowed); +#endif +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.h b/Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.h new file mode 100644 index 000000000..88d4563b9 --- /dev/null +++ b/Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2014 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 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef UserMediaPermissionRequestManagerProxy_h +#define UserMediaPermissionRequestManagerProxy_h + +#include "UserMediaPermissionCheckProxy.h" +#include "UserMediaPermissionRequestProxy.h" +#include <wtf/HashMap.h> + +namespace WebKit { + +class WebPageProxy; + +class UserMediaPermissionRequestManagerProxy { +public: + explicit UserMediaPermissionRequestManagerProxy(WebPageProxy&); + + void invalidateRequests(); + + Ref<UserMediaPermissionRequestProxy> createRequest(uint64_t userMediaID, const Vector<String>& audioDeviceUIDs, const Vector<String>& videoDeviceUIDs); + void didReceiveUserMediaPermissionDecision(uint64_t, bool allow, const String& audioDeviceUID, const String& videoDeviceUID); + + + Ref<UserMediaPermissionCheckProxy> createUserMediaPermissionCheck(uint64_t userMediaID); + void didCompleteUserMediaPermissionCheck(uint64_t, bool allow); + +private: + HashMap<uint64_t, RefPtr<UserMediaPermissionRequestProxy>> m_pendingUserMediaRequests; + HashMap<uint64_t, RefPtr<UserMediaPermissionCheckProxy>> m_pendingDeviceRequests; + WebPageProxy& m_page; +}; + +} // namespace WebKit + +#endif // UserMediaPermissionRequestManagerProxy_h diff --git a/Source/WebKit2/UIProcess/UserMediaPermissionRequestProxy.cpp b/Source/WebKit2/UIProcess/UserMediaPermissionRequestProxy.cpp new file mode 100644 index 000000000..1da57f96c --- /dev/null +++ b/Source/WebKit2/UIProcess/UserMediaPermissionRequestProxy.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2014 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 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "UserMediaPermissionRequestProxy.h" + +#include "UserMediaPermissionRequestManagerProxy.h" +#include <WebCore/MediaStreamTrackSourcesRequestClient.h> +#include <WebCore/RealtimeMediaSourceCenter.h> +#include <wtf/text/StringHash.h> + +namespace WebKit { + +UserMediaPermissionRequestProxy::UserMediaPermissionRequestProxy(UserMediaPermissionRequestManagerProxy& manager, uint64_t userMediaID, const Vector<String>& audioDeviceUIDs, const Vector<String>& videoDeviceUIDs) + : m_manager(&manager) + , m_userMediaID(userMediaID) + , m_videoDeviceUIDs(videoDeviceUIDs) + , m_audioDeviceUIDs(audioDeviceUIDs) +{ +} + +void UserMediaPermissionRequestProxy::allow(const String& audioDeviceUID, const String& videoDeviceUID) +{ + ASSERT(m_manager); + if (!m_manager) + return; + + m_manager->didReceiveUserMediaPermissionDecision(m_userMediaID, true, audioDeviceUID, videoDeviceUID); + m_manager = nullptr; +} + +void UserMediaPermissionRequestProxy::deny() +{ + ASSERT(m_manager); + if (!m_manager) + return; + + m_manager->didReceiveUserMediaPermissionDecision(m_userMediaID, false, emptyString(), emptyString()); + m_manager = nullptr; +} + +void UserMediaPermissionRequestProxy::invalidate() +{ + m_manager = nullptr; +} + +} // namespace WebKit + diff --git a/Source/WebKit2/UIProcess/UserMediaPermissionRequestProxy.h b/Source/WebKit2/UIProcess/UserMediaPermissionRequestProxy.h new file mode 100644 index 000000000..47cd9c249 --- /dev/null +++ b/Source/WebKit2/UIProcess/UserMediaPermissionRequestProxy.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2014 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 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef UserMediaPermissionRequestProxy_h +#define UserMediaPermissionRequestProxy_h + +#include "APIObject.h" +#include <WebCore/RealtimeMediaSource.h> +#include <wtf/Vector.h> +#include <wtf/text/WTFString.h> + +namespace WebKit { + +class UserMediaPermissionRequestManagerProxy; + +class UserMediaPermissionRequestProxy : public API::ObjectImpl<API::Object::Type::UserMediaPermissionRequest> { +public: + static Ref<UserMediaPermissionRequestProxy> create(UserMediaPermissionRequestManagerProxy& manager, uint64_t userMediaID, const Vector<String>& videoDeviceUIDs, const Vector<String>& audioDeviceUIDs) + { + return adoptRef(*new UserMediaPermissionRequestProxy(manager, userMediaID, videoDeviceUIDs, audioDeviceUIDs)); + } + + void allow(const String& videoDeviceUID, const String& audioDeviceUID); + void deny(); + + void invalidate(); + + bool requiresAudio() const { return m_audioDeviceUIDs.size(); } + bool requiresVideo() const { return m_videoDeviceUIDs.size(); } + + const Vector<String>& videoDeviceUIDs() const { return m_videoDeviceUIDs; } + const Vector<String>& audioDeviceUIDs() const { return m_audioDeviceUIDs; } + + const String& firstVideoDeviceUID() const { return !videoDeviceUIDs().isEmpty() ? videoDeviceUIDs().at(0) : emptyString(); } + const String& firstAudioDeviceUID() const { return !audioDeviceUIDs().isEmpty() ? audioDeviceUIDs().at(0) : emptyString(); } + +private: + UserMediaPermissionRequestProxy(UserMediaPermissionRequestManagerProxy&, uint64_t userMediaID, const Vector<String>& videoDeviceUIDs, const Vector<String>& audioDeviceUIDs); + + UserMediaPermissionRequestManagerProxy* m_manager; + uint64_t m_userMediaID; + Vector<String> m_videoDeviceUIDs; + Vector<String> m_audioDeviceUIDs; +}; + +} // namespace WebKit + +#endif // UserMediaPermissionRequestProxy_h diff --git a/Source/WebKit2/UIProcess/ViewGestureController.cpp b/Source/WebKit2/UIProcess/ViewGestureController.cpp new file mode 100644 index 000000000..135151f81 --- /dev/null +++ b/Source/WebKit2/UIProcess/ViewGestureController.cpp @@ -0,0 +1,285 @@ +/* + * Copyright (C) 2013-2015 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 "ViewGestureController.h" + +#import "Logging.h" +#import "RemoteLayerTreeDrawingAreaProxy.h" +#import "ViewGestureControllerMessages.h" +#import "WebPageProxy.h" +#import "WebProcessProxy.h" +#import <wtf/MathExtras.h> + +using namespace WebCore; + +namespace WebKit { + +static const std::chrono::seconds swipeSnapshotRemovalWatchdogAfterFirstVisuallyNonEmptyLayoutDuration = 3_s; +static const std::chrono::milliseconds swipeSnapshotRemovalActiveLoadMonitoringInterval = 250_ms; + +#if PLATFORM(MAC) +static const std::chrono::seconds swipeSnapshotRemovalWatchdogDuration = 5_s; +#else +static const std::chrono::seconds swipeSnapshotRemovalWatchdogDuration = 3_s; +#endif + +static HashMap<uint64_t, ViewGestureController*>& viewGestureControllersForAllPages() +{ + // The key in this map is the associated page ID. + static NeverDestroyed<HashMap<uint64_t, ViewGestureController*>> viewGestureControllers; + return viewGestureControllers.get(); +} + +ViewGestureController::ViewGestureController(WebPageProxy& webPageProxy) + : m_webPageProxy(webPageProxy) + , m_swipeActiveLoadMonitoringTimer(RunLoop::main(), this, &ViewGestureController::checkForActiveLoads) +#if PLATFORM(MAC) + , m_pendingSwipeTracker(webPageProxy, std::bind(&ViewGestureController::trackSwipeGesture, this, std::placeholders::_1, std::placeholders::_2)) +#endif +{ + m_webPageProxy.process().addMessageReceiver(Messages::ViewGestureController::messageReceiverName(), m_webPageProxy.pageID(), *this); + + viewGestureControllersForAllPages().add(webPageProxy.pageID(), this); +} + +ViewGestureController::~ViewGestureController() +{ + platformTeardown(); + + viewGestureControllersForAllPages().remove(m_webPageProxy.pageID()); + + m_webPageProxy.process().removeMessageReceiver(Messages::ViewGestureController::messageReceiverName(), m_webPageProxy.pageID()); +} + +ViewGestureController* ViewGestureController::gestureControllerForPage(uint64_t pageID) +{ + auto gestureControllerIter = viewGestureControllersForAllPages().find(pageID); + if (gestureControllerIter == viewGestureControllersForAllPages().end()) + return nullptr; + return gestureControllerIter->value; +} + +void ViewGestureController::didFirstVisuallyNonEmptyLayoutForMainFrame() +{ + if (!m_snapshotRemovalTracker.eventOccurred(SnapshotRemovalTracker::VisuallyNonEmptyLayout)) + return; + + m_snapshotRemovalTracker.cancelOutstandingEvent(SnapshotRemovalTracker::MainFrameLoad); + m_snapshotRemovalTracker.cancelOutstandingEvent(SnapshotRemovalTracker::SubresourceLoads); + m_snapshotRemovalTracker.startWatchdog(swipeSnapshotRemovalWatchdogAfterFirstVisuallyNonEmptyLayoutDuration); +} + +void ViewGestureController::didRepaintAfterNavigation() +{ + m_snapshotRemovalTracker.eventOccurred(SnapshotRemovalTracker::RepaintAfterNavigation); +} + +void ViewGestureController::didHitRenderTreeSizeThreshold() +{ + m_snapshotRemovalTracker.eventOccurred(SnapshotRemovalTracker::RenderTreeSizeThreshold); +} + +void ViewGestureController::didRestoreScrollPosition() +{ + m_snapshotRemovalTracker.eventOccurred(SnapshotRemovalTracker::ScrollPositionRestoration); +} + +void ViewGestureController::didReachMainFrameLoadTerminalState() +{ + if (!m_snapshotRemovalTracker.eventOccurred(SnapshotRemovalTracker::MainFrameLoad)) + return; + + // Coming back from the page cache will result in getting a load event, but no first visually non-empty layout. + // WebCore considers a loaded document enough to be considered visually non-empty, so that's good + // enough for us too. + m_snapshotRemovalTracker.cancelOutstandingEvent(SnapshotRemovalTracker::VisuallyNonEmptyLayout); + + // With Web-process scrolling, we check if the scroll position restoration succeeded by comparing the + // requested and actual scroll position. It's possible that we will never succeed in restoring + // the exact scroll position we wanted, in the case of a dynamic page, but we know that by + // main frame load time that we've gotten as close as we're going to get, so stop waiting. + // We don't want to do this with UI-side scrolling because scroll position restoration is baked into the transaction. + // FIXME: It seems fairly dirty to type-check the DrawingArea like this. + if (auto drawingArea = m_webPageProxy.drawingArea()) { + if (is<RemoteLayerTreeDrawingAreaProxy>(drawingArea)) + m_snapshotRemovalTracker.cancelOutstandingEvent(SnapshotRemovalTracker::ScrollPositionRestoration); + } + + checkForActiveLoads(); +} + +void ViewGestureController::didSameDocumentNavigationForMainFrame(SameDocumentNavigationType type) +{ + bool cancelledOutstandingEvent = false; + + // Same-document navigations don't have a main frame load or first visually non-empty layout. + cancelledOutstandingEvent |= m_snapshotRemovalTracker.cancelOutstandingEvent(SnapshotRemovalTracker::MainFrameLoad); + cancelledOutstandingEvent |= m_snapshotRemovalTracker.cancelOutstandingEvent(SnapshotRemovalTracker::VisuallyNonEmptyLayout); + + if (!cancelledOutstandingEvent) + return; + + if (type != SameDocumentNavigationSessionStateReplace && type != SameDocumentNavigationSessionStatePop) + return; + + checkForActiveLoads(); +} + +void ViewGestureController::checkForActiveLoads() +{ + if (m_webPageProxy.pageLoadState().isLoading()) { + if (!m_swipeActiveLoadMonitoringTimer.isActive()) + m_swipeActiveLoadMonitoringTimer.startRepeating(swipeSnapshotRemovalActiveLoadMonitoringInterval); + return; + } + + m_swipeActiveLoadMonitoringTimer.stop(); + m_snapshotRemovalTracker.eventOccurred(SnapshotRemovalTracker::SubresourceLoads); +} + +ViewGestureController::SnapshotRemovalTracker::SnapshotRemovalTracker() + : m_watchdogTimer(RunLoop::main(), this, &SnapshotRemovalTracker::watchdogTimerFired) +{ +} + +String ViewGestureController::SnapshotRemovalTracker::eventsDescription(Events event) +{ + StringBuilder description; + + if (event & ViewGestureController::SnapshotRemovalTracker::VisuallyNonEmptyLayout) + description.append("VisuallyNonEmptyLayout "); + + if (event & ViewGestureController::SnapshotRemovalTracker::RenderTreeSizeThreshold) + description.append("RenderTreeSizeThreshold "); + + if (event & ViewGestureController::SnapshotRemovalTracker::RepaintAfterNavigation) + description.append("RepaintAfterNavigation "); + + if (event & ViewGestureController::SnapshotRemovalTracker::MainFrameLoad) + description.append("MainFrameLoad "); + + if (event & ViewGestureController::SnapshotRemovalTracker::SubresourceLoads) + description.append("SubresourceLoads "); + + if (event & ViewGestureController::SnapshotRemovalTracker::ScrollPositionRestoration) + description.append("ScrollPositionRestoration "); + + return description.toString(); +} + + +void ViewGestureController::SnapshotRemovalTracker::log(const String& log) const +{ +#if !LOG_DISABLED + auto now = std::chrono::steady_clock::now(); + double millisecondsSinceStart = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(now - m_startTime).count(); +#endif + LOG(ViewGestures, "Swipe Snapshot Removal (%0.2f ms) - %s", millisecondsSinceStart, log.utf8().data()); +} + +void ViewGestureController::SnapshotRemovalTracker::start(Events desiredEvents, std::function<void()> removalCallback) +{ + m_outstandingEvents = desiredEvents; + m_removalCallback = WTFMove(removalCallback); + m_startTime = std::chrono::steady_clock::now(); + + log("start"); + + startWatchdog(swipeSnapshotRemovalWatchdogDuration); +} + +void ViewGestureController::SnapshotRemovalTracker::reset() +{ + if (m_outstandingEvents) + log("reset; had outstanding events: " + eventsDescription(m_outstandingEvents)); + m_outstandingEvents = 0; + m_watchdogTimer.stop(); + m_removalCallback = nullptr; +} + +bool ViewGestureController::SnapshotRemovalTracker::stopWaitingForEvent(Events event, const String& logReason) +{ + ASSERT(hasOneBitSet(event)); + + if (!(m_outstandingEvents & event)) + return false; + +#if LOG_DISABLED + UNUSED_PARAM(logReason); +#endif + log(logReason + eventsDescription(event)); + + m_outstandingEvents &= ~event; + + fireRemovalCallbackIfPossible(); + return true; +} + +bool ViewGestureController::SnapshotRemovalTracker::eventOccurred(Events event) +{ + return stopWaitingForEvent(event, "outstanding event occurred: "); +} + +bool ViewGestureController::SnapshotRemovalTracker::cancelOutstandingEvent(Events event) +{ + return stopWaitingForEvent(event, "wait for event cancelled: "); +} + +void ViewGestureController::SnapshotRemovalTracker::fireRemovalCallbackIfPossible() +{ + if (m_outstandingEvents) { + log("deferring removal; had outstanding events: " + eventsDescription(m_outstandingEvents)); + return; + } + + fireRemovalCallbackImmediately(); +} + +void ViewGestureController::SnapshotRemovalTracker::fireRemovalCallbackImmediately() +{ + m_watchdogTimer.stop(); + + auto removalCallback = WTFMove(m_removalCallback); + if (removalCallback) { + log("removing snapshot"); + reset(); + removalCallback(); + } +} + +void ViewGestureController::SnapshotRemovalTracker::watchdogTimerFired() +{ + log("watchdog timer fired"); + fireRemovalCallbackImmediately(); +} + +void ViewGestureController::SnapshotRemovalTracker::startWatchdog(std::chrono::seconds duration) +{ + log(String::format("(re)started watchdog timer for %lld seconds", duration.count())); + m_watchdogTimer.startOneShot(duration.count()); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/VisitedLinkProvider.cpp b/Source/WebKit2/UIProcess/VisitedLinkProvider.cpp deleted file mode 100644 index 7ecae847c..000000000 --- a/Source/WebKit2/UIProcess/VisitedLinkProvider.cpp +++ /dev/null @@ -1,199 +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 "VisitedLinkProvider.h" - -#include "SharedMemory.h" -#include "VisitedLinkTable.h" -#include "WebContext.h" -#include "WebProcessMessages.h" - -using namespace WebCore; - -namespace WebKit { - -static const int VisitedLinkTableMaxLoad = 2; - -VisitedLinkProvider::VisitedLinkProvider(WebContext* context) - : m_context(context) - , m_visitedLinksPopulated(false) - , m_keyCount(0) - , m_tableSize(0) - , m_pendingVisitedLinksTimer(RunLoop::main(), this, &VisitedLinkProvider::pendingVisitedLinksTimerFired) -{ -} - -void VisitedLinkProvider::processDidFinishLaunching(WebProcessProxy* process) -{ - m_processesWithoutVisitedLinkState.add(process); - - if (m_keyCount) - m_pendingVisitedLinksTimer.startOneShot(0); - - if (m_visitedLinksPopulated) - return; - - m_context->populateVisitedLinks(); - - m_visitedLinksPopulated = true; -} - -void VisitedLinkProvider::addVisitedLink(LinkHash linkHash) -{ - m_pendingVisitedLinks.add(linkHash); - - if (!m_pendingVisitedLinksTimer.isActive()) - m_pendingVisitedLinksTimer.startOneShot(0); -} - -void VisitedLinkProvider::processDidClose(WebProcessProxy* process) -{ - m_processesWithVisitedLinkState.remove(process); - m_processesWithoutVisitedLinkState.remove(process); -} - -static unsigned nextPowerOf2(unsigned v) -{ - // Taken from http://www.cs.utk.edu/~vose/c-stuff/bithacks.html - // Devised by Sean Anderson, Sepember 14, 2001 - - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - - return v; -} - -static unsigned tableSizeForKeyCount(unsigned keyCount) -{ - // We want the table to be at least half empty. - unsigned tableSize = nextPowerOf2(keyCount * VisitedLinkTableMaxLoad); - - // Ensure that the table size is at least the size of a page. - size_t minimumTableSize = SharedMemory::systemPageSize() / sizeof(LinkHash); - if (tableSize < minimumTableSize) - return minimumTableSize; - - return tableSize; -} - -void VisitedLinkProvider::pendingVisitedLinksTimerFired() -{ - Vector<WebCore::LinkHash> pendingVisitedLinks; - copyToVector(m_pendingVisitedLinks, pendingVisitedLinks); - m_pendingVisitedLinks.clear(); - - unsigned currentTableSize = m_tableSize; - - // Upper bound on needed size - some of the links may be duplicates, in which case we could have done with less. - unsigned newTableSize = tableSizeForKeyCount(m_keyCount + pendingVisitedLinks.size()); - - // Never decrease table size when adding to it, to avoid unneeded churn. - newTableSize = std::max(currentTableSize, newTableSize); - - // Links that were added. - Vector<WebCore::LinkHash> addedVisitedLinks; - - // VisitedLinkTable remains internally consistent when adding, so it's OK to modify it in place - // even if a web process is accessing it at the same time. - if (currentTableSize != newTableSize) { - RefPtr<SharedMemory> newTableMemory = SharedMemory::create(newTableSize * sizeof(LinkHash)); - - // We failed to create the shared memory. - if (!newTableMemory) { - LOG_ERROR("Could not allocate shared memory for visited link table"); - return; - } - - memset(newTableMemory->data(), 0, newTableMemory->size()); - - RefPtr<SharedMemory> currentTableMemory = m_table.sharedMemory(); - - m_table.setSharedMemory(newTableMemory); - m_tableSize = newTableSize; - - if (currentTableMemory) { - ASSERT(currentTableMemory->size() == currentTableSize * sizeof(LinkHash)); - - // Go through the current hash table and re-add all entries to the new hash table. - const LinkHash* currentLinkHashes = static_cast<const LinkHash*>(currentTableMemory->data()); - for (unsigned i = 0; i < currentTableSize; ++i) { - LinkHash linkHash = currentLinkHashes[i]; - - if (!linkHash) - continue; - - // It should always be possible to add the link hash to a new table. - if (!m_table.addLinkHash(linkHash)) - ASSERT_NOT_REACHED(); - } - } - } - - for (size_t i = 0; i < pendingVisitedLinks.size(); ++i) { - if (m_table.addLinkHash(pendingVisitedLinks[i])) - addedVisitedLinks.append(pendingVisitedLinks[i]); - } - - m_keyCount += pendingVisitedLinks.size(); - - - for (HashSet<WebProcessProxy*>::iterator iter = m_processesWithVisitedLinkState.begin(); iter != m_processesWithVisitedLinkState.end(); ++iter) { - WebProcessProxy* process = *iter; - if (currentTableSize != newTableSize) { - // In the rare case of needing to resize the table, we'll bypass the VisitedLinkStateChanged optimization, - // and unconditionally use AllVisitedLinkStateChanged for the process. - m_processesWithoutVisitedLinkState.add(process); - continue; - } - - if (addedVisitedLinks.size() <= 20) - process->send(Messages::WebProcess::VisitedLinkStateChanged(addedVisitedLinks), 0); - else - process->send(Messages::WebProcess::AllVisitedLinkStateChanged(), 0); - } - - for (HashSet<WebProcessProxy*>::iterator iter = m_processesWithoutVisitedLinkState.begin(); iter != m_processesWithoutVisitedLinkState.end(); ++iter) { - WebProcessProxy* process = *iter; - - SharedMemory::Handle handle; - if (!m_table.sharedMemory()->createHandle(handle, SharedMemory::ReadOnly)) - return; - - process->send(Messages::WebProcess::SetVisitedLinkTable(handle), 0); - process->send(Messages::WebProcess::AllVisitedLinkStateChanged(), 0); - - m_processesWithVisitedLinkState.add(process); - } - - m_processesWithoutVisitedLinkState.clear(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/VisitedLinkStore.cpp b/Source/WebKit2/UIProcess/VisitedLinkStore.cpp new file mode 100644 index 000000000..a3fb770f5 --- /dev/null +++ b/Source/WebKit2/UIProcess/VisitedLinkStore.cpp @@ -0,0 +1,259 @@ +/* + * 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 "VisitedLinkStore.h" + +#include "SharedMemory.h" +#include "VisitedLinkStoreMessages.h" +#include "VisitedLinkTable.h" +#include "VisitedLinkTableControllerMessages.h" +#include "WebProcessMessages.h" +#include "WebProcessPool.h" +#include "WebProcessProxy.h" + +using namespace WebCore; + +namespace WebKit { + +static const int visitedLinkTableMaxLoad = 2; + +static uint64_t generateIdentifier() +{ + static uint64_t identifier; + + return ++identifier; +} + +Ref<VisitedLinkStore> VisitedLinkStore::create() +{ + return adoptRef(*new VisitedLinkStore); +} + +VisitedLinkStore::~VisitedLinkStore() +{ + for (WebProcessProxy* process : m_processes) { + process->removeMessageReceiver(Messages::VisitedLinkStore::messageReceiverName(), m_identifier); + process->didDestroyVisitedLinkStore(*this); + } +} + +VisitedLinkStore::VisitedLinkStore() + : m_identifier(generateIdentifier()) + , m_keyCount(0) + , m_tableSize(0) + , m_pendingVisitedLinksTimer(RunLoop::main(), this, &VisitedLinkStore::pendingVisitedLinksTimerFired) +{ +} + +void VisitedLinkStore::addProcess(WebProcessProxy& process) +{ + ASSERT(process.state() == WebProcessProxy::State::Running); + + if (!m_processes.add(&process).isNewEntry) + return; + + process.addMessageReceiver(Messages::VisitedLinkStore::messageReceiverName(), m_identifier, *this); + + if (!m_keyCount) + return; + + ASSERT(m_table.sharedMemory()); + + sendTable(process); +} + +void VisitedLinkStore::removeProcess(WebProcessProxy& process) +{ + ASSERT(m_processes.contains(&process)); + + m_processes.remove(&process); + process.removeMessageReceiver(Messages::VisitedLinkStore::messageReceiverName(), m_identifier); +} + +void VisitedLinkStore::addVisitedLinkHash(LinkHash linkHash) +{ + m_pendingVisitedLinks.add(linkHash); + + if (!m_pendingVisitedLinksTimer.isActive()) + m_pendingVisitedLinksTimer.startOneShot(0); +} + +void VisitedLinkStore::removeAll() +{ + m_pendingVisitedLinksTimer.stop(); + m_pendingVisitedLinks.clear(); + m_keyCount = 0; + m_tableSize = 0; + m_table.clear(); + + for (WebProcessProxy* process : m_processes) { + ASSERT(process->processPool().processes().contains(process)); + process->connection()->send(Messages::VisitedLinkTableController::RemoveAllVisitedLinks(), m_identifier); + } +} + +void VisitedLinkStore::webProcessWillOpenConnection(WebProcessProxy&, IPC::Connection&) +{ + // FIXME: Implement. +} + +void VisitedLinkStore::webProcessDidCloseConnection(WebProcessProxy&, IPC::Connection&) +{ + // FIXME: Implement. +} + +void VisitedLinkStore::addVisitedLinkHashFromPage(uint64_t pageID, LinkHash linkHash) +{ + if (WebPageProxy* webPageProxy = WebProcessProxy::webPage(pageID)) { + if (!webPageProxy->addsVisitedLinks()) + return; + } + + addVisitedLinkHash(linkHash); +} + +static unsigned nextPowerOf2(unsigned v) +{ + // Taken from http://www.cs.utk.edu/~vose/c-stuff/bithacks.html + // Devised by Sean Anderson, Sepember 14, 2001 + + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + + return v; +} + +static unsigned tableSizeForKeyCount(unsigned keyCount) +{ + // We want the table to be at least half empty. + unsigned tableSize = nextPowerOf2(keyCount * visitedLinkTableMaxLoad); + + // Ensure that the table size is at least the size of a page. + size_t minimumTableSize = SharedMemory::systemPageSize() / sizeof(LinkHash); + if (tableSize < minimumTableSize) + return minimumTableSize; + + return tableSize; +} + +void VisitedLinkStore::pendingVisitedLinksTimerFired() +{ + unsigned currentTableSize = m_tableSize; + unsigned newTableSize = tableSizeForKeyCount(m_keyCount + m_pendingVisitedLinks.size()); + + newTableSize = std::max(currentTableSize, newTableSize); + + if (currentTableSize != newTableSize) { + resizeTable(newTableSize); + return; + } + + Vector<WebCore::LinkHash> addedVisitedLinks; + + for (auto& linkHash : m_pendingVisitedLinks) { + if (m_table.addLinkHash(linkHash)) { + addedVisitedLinks.append(linkHash); + ++m_keyCount; + } + } + + m_pendingVisitedLinks.clear(); + + if (addedVisitedLinks.isEmpty()) + return; + + for (WebProcessProxy* process : m_processes) { + ASSERT(process->processPool().processes().contains(process)); + + if (addedVisitedLinks.size() > 20) + process->connection()->send(Messages::VisitedLinkTableController::AllVisitedLinkStateChanged(), m_identifier); + else + process->connection()->send(Messages::VisitedLinkTableController::VisitedLinkStateChanged(addedVisitedLinks), m_identifier); + } +} + +void VisitedLinkStore::resizeTable(unsigned newTableSize) +{ + RefPtr<SharedMemory> newTableMemory = SharedMemory::allocate(newTableSize * sizeof(LinkHash)); + + if (!newTableMemory) { + LOG_ERROR("Could not allocate shared memory for visited link table"); + return; + } + + memset(newTableMemory->data(), 0, newTableMemory->size()); + + RefPtr<SharedMemory> currentTableMemory = m_table.sharedMemory(); + unsigned currentTableSize = m_tableSize; + + m_table.setSharedMemory(newTableMemory); + m_tableSize = newTableSize; + + if (currentTableMemory) { + ASSERT_UNUSED(currentTableSize, currentTableMemory->size() == currentTableSize * sizeof(LinkHash)); + + // Go through the current hash table and re-add all entries to the new hash table. + const LinkHash* currentLinkHashes = static_cast<const LinkHash*>(currentTableMemory->data()); + for (unsigned i = 0; i < currentTableSize; ++i) { + LinkHash linkHash = currentLinkHashes[i]; + + if (!linkHash) + continue; + + bool didAddLinkHash = m_table.addLinkHash(linkHash); + + // It should always be possible to add the link hash to a new table. + ASSERT_UNUSED(didAddLinkHash, didAddLinkHash); + } + } + + for (auto& linkHash : m_pendingVisitedLinks) { + if (m_table.addLinkHash(linkHash)) + m_keyCount++; + } + m_pendingVisitedLinks.clear(); + + for (WebProcessProxy* process : m_processes) + sendTable(*process); +} + +void VisitedLinkStore::sendTable(WebProcessProxy& process) +{ + ASSERT(process.processPool().processes().contains(&process)); + + SharedMemory::Handle handle; + if (!m_table.sharedMemory()->createHandle(handle, SharedMemory::Protection::ReadOnly)) + return; + + process.connection()->send(Messages::VisitedLinkTableController::SetVisitedLinkTable(handle), m_identifier); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/VisitedLinkProvider.h b/Source/WebKit2/UIProcess/VisitedLinkStore.h index e0e531025..06a4b2cf3 100644 --- a/Source/WebKit2/UIProcess/VisitedLinkProvider.h +++ b/Source/WebKit2/UIProcess/VisitedLinkStore.h @@ -23,46 +23,66 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef VisitedLinkProvider_h -#define VisitedLinkProvider_h +#ifndef VisitedLinkStore_h +#define VisitedLinkStore_h +#include "APIObject.h" +#include "MessageReceiver.h" #include "VisitedLinkTable.h" +#include "WebProcessLifetimeObserver.h" #include <WebCore/LinkHash.h> -#include <WebCore/RunLoop.h> #include <wtf/Forward.h> #include <wtf/HashSet.h> +#include <wtf/RefCounted.h> +#include <wtf/RunLoop.h> namespace WebKit { -class WebContext; +class WebPageProxy; class WebProcessProxy; -class VisitedLinkProvider { - WTF_MAKE_NONCOPYABLE(VisitedLinkProvider); +class VisitedLinkStore final : public API::ObjectImpl<API::Object::Type::VisitedLinkStore>, private IPC::MessageReceiver, public WebProcessLifetimeObserver { public: - explicit VisitedLinkProvider(WebContext*); + static Ref<VisitedLinkStore> create(); - void addVisitedLink(WebCore::LinkHash); + explicit VisitedLinkStore(); + virtual ~VisitedLinkStore(); - void processDidFinishLaunching(WebProcessProxy*); - void processDidClose(WebProcessProxy*); + uint64_t identifier() const { return m_identifier; } + + void addProcess(WebProcessProxy&); + void removeProcess(WebProcessProxy&); + + void addVisitedLinkHash(WebCore::LinkHash); + void removeAll(); private: + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + + // WebProcessLifetimeObserver + virtual void webProcessWillOpenConnection(WebProcessProxy&, IPC::Connection&) override; + virtual void webProcessDidCloseConnection(WebProcessProxy&, IPC::Connection&) override; + + void addVisitedLinkHashFromPage(uint64_t pageID, WebCore::LinkHash); + void pendingVisitedLinksTimerFired(); - WebContext* m_context; - bool m_visitedLinksPopulated; - HashSet<WebProcessProxy*> m_processesWithVisitedLinkState; - HashSet<WebProcessProxy*> m_processesWithoutVisitedLinkState; + void resizeTable(unsigned newTableSize); + void sendTable(WebProcessProxy&); + + HashSet<WebProcessProxy*> m_processes; + + uint64_t m_identifier; unsigned m_keyCount; unsigned m_tableSize; VisitedLinkTable m_table; HashSet<WebCore::LinkHash, WebCore::LinkHashHash> m_pendingVisitedLinks; - WebCore::RunLoop::Timer<VisitedLinkProvider> m_pendingVisitedLinksTimer; + RunLoop::Timer<VisitedLinkStore> m_pendingVisitedLinksTimer; }; } // namespace WebKit -#endif // VisitedLinkProvider_h +#endif // VisitedLinkStore_h diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.messages.in b/Source/WebKit2/UIProcess/VisitedLinkStore.messages.in index 18058f5c7..e7862e365 100644 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.messages.in +++ b/Source/WebKit2/UIProcess/VisitedLinkStore.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2012 Igalia S.L. +# Copyright (C) 2014 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -20,6 +20,6 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> WebSoupRequestManagerProxy { - DidFailToLoadURIRequest(uint64_t requestID); +messages -> VisitedLinkStore { + AddVisitedLinkHashFromPage(uint64_t pageID, uint64_t linkHash) } diff --git a/Source/WebKit2/UIProcess/mac/WKFullKeyboardAccessWatcher.h b/Source/WebKit2/UIProcess/WKImagePreviewViewController.h index 72e7dbe0a..852931b6b 100644 --- a/Source/WebKit2/UIProcess/mac/WKFullKeyboardAccessWatcher.h +++ b/Source/WebKit2/UIProcess/WKImagePreviewViewController.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,16 +23,22 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WKFullKeyboardAccessWatcher_h -#define WKFullKeyboardAccessWatcher_h +#if PLATFORM(IOS) -@interface WKFullKeyboardAccessWatcher : NSObject { +#import <UIKit/UIKit.h> + +#import <wtf/RetainPtr.h> + +@class _WKActivatedElementInfo; +@class _WKElementAction; + +@interface WKImagePreviewViewController : UIViewController { @private - BOOL fullKeyboardAccessEnabled; + RetainPtr<NSArray> _imageActions; + RetainPtr<_WKActivatedElementInfo> _activatedElementInfo; } -+ (BOOL)fullKeyboardAccessEnabled; - -@end; +- (id)initWithCGImage:(RetainPtr<CGImageRef>)image defaultActions:(RetainPtr<NSArray>)actions elementInfo:(RetainPtr<_WKActivatedElementInfo>)elementInfo; +@end -#endif // WKFullKeyboardAccessWatcher_h +#endif // PLATFORM(IOS) diff --git a/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.h b/Source/WebKit2/UIProcess/WKInspectorHighlightView.h index 7b81e9a98..117660cb3 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKTypeRefWrapper.h +++ b/Source/WebKit2/UIProcess/WKInspectorHighlightView.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,18 +23,18 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#if defined(__LP64__) && defined(__clang__) +#if PLATFORM(IOS) -#import <Foundation/Foundation.h> -#import <WebKit2/WKBase.h> +#import <UIKit/UIKit.h> -WK_EXPORT -@interface WKTypeRefWrapper : NSObject - -- (id)initWithObject:(WKTypeRef)object; - -@property(readonly) WKTypeRef object; +namespace WebCore { +struct Highlight; +} +@interface WKInspectorHighlightView : UIView { + NSMutableArray *_layers; // CAShapeLayers. +} +- (void)update:(const WebCore::Highlight&)highlight; @end #endif diff --git a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp deleted file mode 100644 index 494ca6bd7..000000000 --- a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebApplicationCacheManagerProxy.h" - -#include "SecurityOriginData.h" -#include "WebApplicationCacheManagerMessages.h" -#include "WebApplicationCacheManagerProxyMessages.h" -#include "WebContext.h" -#include "WebSecurityOrigin.h" - -namespace WebKit { - -const char* WebApplicationCacheManagerProxy::supplementName() -{ - return "WebApplicationCacheManagerProxy"; -} - -PassRefPtr<WebApplicationCacheManagerProxy> WebApplicationCacheManagerProxy::create(WebContext* context) -{ - return adoptRef(new WebApplicationCacheManagerProxy(context)); -} - -WebApplicationCacheManagerProxy::WebApplicationCacheManagerProxy(WebContext* context) - : WebContextSupplement(context) -{ - context->addMessageReceiver(Messages::WebApplicationCacheManagerProxy::messageReceiverName(), this); -} - -WebApplicationCacheManagerProxy::~WebApplicationCacheManagerProxy() -{ -} - - -void WebApplicationCacheManagerProxy::contextDestroyed() -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -void WebApplicationCacheManagerProxy::processDidClose(WebProcessProxy*) -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -bool WebApplicationCacheManagerProxy::shouldTerminate(WebProcessProxy*) const -{ - return m_arrayCallbacks.isEmpty(); -} - -void WebApplicationCacheManagerProxy::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebApplicationCacheManagerProxy::derefWebContextSupplement() -{ - APIObject::deref(); -} - -void WebApplicationCacheManagerProxy::getApplicationCacheOrigins(PassRefPtr<ArrayCallback> prpCallback) -{ - if (!context()) - return; - - RefPtr<ArrayCallback> callback = prpCallback; - - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::GetApplicationCacheOrigins(callbackID)); -} - -void WebApplicationCacheManagerProxy::didGetApplicationCacheOrigins(const Vector<SecurityOriginData>& originDatas, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - performAPICallbackWithSecurityOriginDataVector(originDatas, callback.get()); -} - -void WebApplicationCacheManagerProxy::deleteEntriesForOrigin(WebSecurityOrigin* origin) -{ - if (!context()) - return; - - SecurityOriginData securityOriginData; - securityOriginData.protocol = origin->protocol(); - securityOriginData.host = origin->host(); - securityOriginData.port = origin->port(); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteEntriesForOrigin(securityOriginData)); -} - -void WebApplicationCacheManagerProxy::deleteAllEntries() -{ - if (!context()) - return; - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Make manipulating cache information work with per-tab WebProcess. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebApplicationCacheManager::DeleteAllEntries()); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h deleted file mode 100644 index ee5a27051..000000000 --- a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebApplicationCacheManagerProxy_h -#define WebApplicationCacheManagerProxy_h - -#include "APIObject.h" -#include "GenericCallback.h" -#include "ImmutableArray.h" -#include "MessageReceiver.h" -#include "WebContextSupplement.h" -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace CoreIPC { - class Connection; -} - -namespace WebKit { - -class WebSecurityOrigin; -struct SecurityOriginData; - -typedef GenericCallback<WKArrayRef> ArrayCallback; - -class WebApplicationCacheManagerProxy : public TypedAPIObject<APIObject::TypeApplicationCacheManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { -public: - static const char* supplementName(); - - static PassRefPtr<WebApplicationCacheManagerProxy> create(WebContext*); - virtual ~WebApplicationCacheManagerProxy(); - - void getApplicationCacheOrigins(PassRefPtr<ArrayCallback>); - void deleteEntriesForOrigin(WebSecurityOrigin*); - void deleteAllEntries(); - - using APIObject::ref; - using APIObject::deref; - -private: - explicit WebApplicationCacheManagerProxy(WebContext*); - - void didGetApplicationCacheOrigins(const Vector<SecurityOriginData>&, uint64_t callbackID); - - // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; -}; - -} // namespace WebKit - -#endif // WebApplicationCacheManagerProxy_h diff --git a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.messages.in deleted file mode 100644 index 2aa0f670e..000000000 --- a/Source/WebKit2/UIProcess/WebApplicationCacheManagerProxy.messages.in +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (C) 2011 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -messages -> WebApplicationCacheManagerProxy { - DidGetApplicationCacheOrigins(Vector<WebKit::SecurityOriginData> originIdentifiers, uint64_t callbackID); -} diff --git a/Source/WebKit2/UIProcess/WebColorPickerResultListenerProxy.cpp b/Source/WebKit2/UIProcess/WebAutomationSession.cpp index 0ee79dd71..44258a7e6 100644 --- a/Source/WebKit2/UIProcess/WebColorPickerResultListenerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebAutomationSession.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. + * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,7 +10,7 @@ * 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'' + * 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 @@ -24,37 +24,53 @@ */ #include "config.h" -#include "WebColorPickerResultListenerProxy.h" +#include "WebAutomationSession.h" -#if ENABLE(INPUT_TYPE_COLOR) - -#include "WebPageProxy.h" +#include "APIAutomationSessionClient.h" namespace WebKit { -WebColorPickerResultListenerProxy::WebColorPickerResultListenerProxy(WebPageProxy* page) - : m_page(page) +WebAutomationSession::WebAutomationSession() + : m_client(std::make_unique<API::AutomationSessionClient>()) +{ +} + +WebAutomationSession::~WebAutomationSession() { + ASSERT(!m_client); } -WebColorPickerResultListenerProxy::~WebColorPickerResultListenerProxy() +void WebAutomationSession::setClient(std::unique_ptr<API::AutomationSessionClient> client) { + m_client = WTFMove(client); } -void WebColorPickerResultListenerProxy::invalidate() +// NOTE: this class could be split at some point to support local and remote automation sessions. +// For now, it only works with a remote automation driver over a RemoteInspector connection. + +#if ENABLE(REMOTE_INSPECTOR) + +// Inspector::RemoteAutomationTarget API + +void WebAutomationSession::dispatchMessageFromRemote(const String&) { - m_page = 0; + // FIXME: to be implemented. } -void WebColorPickerResultListenerProxy::setColor(const String& color) +void WebAutomationSession::connect(Inspector::FrontendChannel* channel, bool isAutomaticConnection) { - if (!m_page) - return; + UNUSED_PARAM(isAutomaticConnection); - m_page->setColorChooserColor(WebCore::Color(color)); - m_page->endColorChooser(); + m_remoteChannel = channel; + setIsPaired(true); } -} // namespace WebKit +void WebAutomationSession::disconnect(Inspector::FrontendChannel* channel) +{ + m_remoteChannel = nullptr; + setIsPaired(false); +} + +#endif // ENABLE(REMOTE_INSPECTOR) -#endif // ENABLE(INPUT_TYPE_COLOR) +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebAutomationSession.h b/Source/WebKit2/UIProcess/WebAutomationSession.h new file mode 100644 index 000000000..8835efd6c --- /dev/null +++ b/Source/WebKit2/UIProcess/WebAutomationSession.h @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2016 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 WebAutomationSession_h +#define WebAutomationSession_h + +#include "APIObject.h" +#include <wtf/Forward.h> + +#if ENABLE(REMOTE_INSPECTOR) +#include <JavaScriptCore/RemoteAutomationTarget.h> +#endif + +namespace API { +class AutomationSessionClient; +} + +namespace WebKit { + +class WebAutomationSessionClient; + +class WebAutomationSession final : public API::ObjectImpl<API::Object::Type::AutomationSession> +#if ENABLE(REMOTE_INSPECTOR) + , public Inspector::RemoteAutomationTarget +#endif +{ +public: + WebAutomationSession(); + ~WebAutomationSession(); + + void setClient(std::unique_ptr<API::AutomationSessionClient>); + + void setSessionIdentifier(const String& sessionIdentifier) { m_sessionIdentifier = sessionIdentifier; } + String sessionIdentifier() const { return m_sessionIdentifier; } + +#if ENABLE(REMOTE_INSPECTOR) + // Inspector::RemoteAutomationTarget API + virtual String name() const override { return m_sessionIdentifier; } + virtual void dispatchMessageFromRemote(const String& message) override; + virtual void connect(Inspector::FrontendChannel*, bool isAutomaticConnection = false) override; + virtual void disconnect(Inspector::FrontendChannel*) override; +#endif + +private: + std::unique_ptr<API::AutomationSessionClient> m_client; + String m_sessionIdentifier { ASCIILiteral("Untitled Session") }; + +#if ENABLE(REMOTE_INSPECTOR) + Inspector::FrontendChannel* m_remoteChannel { nullptr }; +#endif +}; + +} // namespace WebKit + +#endif // WebAutomationSession_h diff --git a/Source/WebKit2/UIProcess/WebBackForwardList.cpp b/Source/WebKit2/UIProcess/WebBackForwardList.cpp index 763023d07..273431232 100644 --- a/Source/WebKit2/UIProcess/WebBackForwardList.cpp +++ b/Source/WebKit2/UIProcess/WebBackForwardList.cpp @@ -26,19 +26,34 @@ #include "config.h" #include "WebBackForwardList.h" +#include "APIArray.h" +#include "SessionState.h" #include "WebPageProxy.h" +#include <WebCore/DiagnosticLoggingKeys.h> namespace WebKit { +// FIXME: Make this static once WebBackForwardListCF.cpp is no longer using it. +uint64_t generateWebBackForwardItemID(); + +uint64_t generateWebBackForwardItemID() +{ + // These IDs exist in the UIProcess for items created by the UIProcess. + // The IDs generated here need to never collide with the IDs created in WebBackForwardListProxy in the WebProcess. + // We accomplish this by starting from 2, and only ever using even ids. + static uint64_t uniqueHistoryItemID = 0; + uniqueHistoryItemID += 2; + return uniqueHistoryItemID; +} + static const unsigned DefaultCapacity = 100; -WebBackForwardList::WebBackForwardList(WebPageProxy* page) - : m_page(page) +WebBackForwardList::WebBackForwardList(WebPageProxy& page) + : m_page(&page) , m_hasCurrentIndex(false) , m_currentIndex(0) , m_capacity(DefaultCapacity) { - ASSERT(m_page); } WebBackForwardList::~WebBackForwardList() @@ -58,7 +73,8 @@ void WebBackForwardList::pageClosed() ASSERT(m_entries[i]); if (!m_entries[i]) continue; - m_page->backForwardRemovedItem(m_entries[i]->itemID()); + + didRemoveItem(*m_entries[i]); } } @@ -74,14 +90,16 @@ void WebBackForwardList::addItem(WebBackForwardListItem* newItem) if (!m_capacity || !newItem || !m_page) return; - Vector<RefPtr<APIObject> > removedItems; + Vector<RefPtr<WebBackForwardListItem>> removedItems; if (m_hasCurrentIndex) { + m_page->recordNavigationSnapshot(); + // Toss everything in the forward list. unsigned targetSize = m_currentIndex + 1; removedItems.reserveCapacity(m_entries.size() - targetSize); while (m_entries.size() > targetSize) { - m_page->backForwardRemovedItem(m_entries.last()->itemID()); + didRemoveItem(*m_entries.last()); removedItems.append(m_entries.last().release()); m_entries.removeLast(); } @@ -89,7 +107,7 @@ void WebBackForwardList::addItem(WebBackForwardListItem* newItem) // Toss the first item if the list is getting too big, as long as we're not using it // (or even if we are, if we only want 1 entry). if (m_entries.size() == m_capacity && (m_currentIndex || m_capacity == 1)) { - m_page->backForwardRemovedItem(m_entries[0]->itemID()); + didRemoveItem(*m_entries[0]); removedItems.append(m_entries[0].release()); m_entries.remove(0); @@ -108,26 +126,41 @@ void WebBackForwardList::addItem(WebBackForwardListItem* newItem) ASSERT(m_entries[i]); if (!m_entries[i]) continue; - m_page->backForwardRemovedItem(m_entries[i]->itemID()); + didRemoveItem(*m_entries[i]); removedItems.append(m_entries[i].release()); } m_entries.clear(); } - + + bool shouldKeepCurrentItem = true; + if (!m_hasCurrentIndex) { ASSERT(m_entries.isEmpty()); m_currentIndex = 0; m_hasCurrentIndex = true; - } else - m_currentIndex++; + } else { + shouldKeepCurrentItem = m_page->shouldKeepCurrentBackForwardListItemInList(m_entries[m_currentIndex].get()); + if (shouldKeepCurrentItem) + m_currentIndex++; + } - // m_current never be pointing more than 1 past the end of the entries Vector. - // If it is, something has gone wrong and we should not try to insert the new item. - ASSERT(m_currentIndex <= m_entries.size()); - if (m_currentIndex <= m_entries.size()) - m_entries.insert(m_currentIndex, newItem); + if (!shouldKeepCurrentItem) { + // m_current should never be pointing past the end of the entries Vector. + // If it is, something has gone wrong and we should not try to swap in the new item. + ASSERT(m_currentIndex < m_entries.size()); + + removedItems.append(m_entries[m_currentIndex]); + m_entries[m_currentIndex] = newItem; + } else { + // m_current should never be pointing more than 1 past the end of the entries Vector. + // If it is, something has gone wrong and we should not try to insert the new item. + ASSERT(m_currentIndex <= m_entries.size()); - m_page->didChangeBackForwardList(newItem, &removedItems); + if (m_currentIndex <= m_entries.size()) + m_entries.insert(m_currentIndex, newItem); + } + + m_page->didChangeBackForwardList(newItem, WTFMove(removedItems)); } void WebBackForwardList::goToItem(WebBackForwardListItem* item) @@ -136,52 +169,76 @@ void WebBackForwardList::goToItem(WebBackForwardListItem* item) if (!m_entries.size() || !item || !m_page || !m_hasCurrentIndex) return; - - unsigned index = 0; - for (; index < m_entries.size(); ++index) { - if (m_entries[index] == item) - break; + + size_t targetIndex = m_entries.find(item); + + // If the target item wasn't even in the list, there's nothing else to do. + if (targetIndex == notFound) + return; + + if (targetIndex < m_currentIndex) { + unsigned delta = m_entries.size() - targetIndex - 1; + String deltaValue = delta > 10 ? ASCIILiteral("over10") : String::number(delta); + m_page->logDiagnosticMessageWithValue(WebCore::DiagnosticLoggingKeys::backNavigationKey(), WebCore::DiagnosticLoggingKeys::deltaKey(), deltaValue, false /* shouldSample */); } - if (index < m_entries.size()) { - m_currentIndex = index; - m_page->didChangeBackForwardList(0, 0); + + // If we're going to an item different from the current item, ask the client if the current + // item should remain in the list. + WebBackForwardListItem* currentItem = m_entries[m_currentIndex].get(); + bool shouldKeepCurrentItem = true; + if (currentItem != item) { + m_page->recordNavigationSnapshot(); + shouldKeepCurrentItem = m_page->shouldKeepCurrentBackForwardListItemInList(m_entries[m_currentIndex].get()); } + + // If the client said to remove the current item, remove it and then update the target index. + Vector<RefPtr<WebBackForwardListItem>> removedItems; + if (!shouldKeepCurrentItem) { + removedItems.append(currentItem); + m_entries.remove(m_currentIndex); + targetIndex = m_entries.find(item); + + ASSERT(targetIndex != notFound); + } + + m_currentIndex = targetIndex; + m_page->didChangeBackForwardList(nullptr, removedItems); } -WebBackForwardListItem* WebBackForwardList::currentItem() +WebBackForwardListItem* WebBackForwardList::currentItem() const { ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); - return m_page && m_hasCurrentIndex ? m_entries[m_currentIndex].get() : 0; + return m_page && m_hasCurrentIndex ? m_entries[m_currentIndex].get() : nullptr; } -WebBackForwardListItem* WebBackForwardList::backItem() +WebBackForwardListItem* WebBackForwardList::backItem() const { ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); - return m_page && m_hasCurrentIndex && m_currentIndex ? m_entries[m_currentIndex - 1].get() : 0; + return m_page && m_hasCurrentIndex && m_currentIndex ? m_entries[m_currentIndex - 1].get() : nullptr; } -WebBackForwardListItem* WebBackForwardList::forwardItem() +WebBackForwardListItem* WebBackForwardList::forwardItem() const { ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); - return m_page && m_hasCurrentIndex && m_entries.size() && m_currentIndex < m_entries.size() - 1 ? m_entries[m_currentIndex + 1].get() : 0; + return m_page && m_hasCurrentIndex && m_entries.size() && m_currentIndex < m_entries.size() - 1 ? m_entries[m_currentIndex + 1].get() : nullptr; } -WebBackForwardListItem* WebBackForwardList::itemAtIndex(int index) +WebBackForwardListItem* WebBackForwardList::itemAtIndex(int index) const { ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); if (!m_hasCurrentIndex || !m_page) - return 0; + return nullptr; // Do range checks without doing math on index to avoid overflow. if (index < -backListCount()) - return 0; + return nullptr; if (index > forwardListCount()) - return 0; + return nullptr; return m_entries[index + m_currentIndex].get(); } @@ -200,19 +257,29 @@ int WebBackForwardList::forwardListCount() const return m_page && m_hasCurrentIndex ? m_entries.size() - (m_currentIndex + 1) : 0; } -PassRefPtr<ImmutableArray> WebBackForwardList::backListAsImmutableArrayWithLimit(unsigned limit) const +Ref<API::Array> WebBackForwardList::backList() const +{ + return backListAsAPIArrayWithLimit(backListCount()); +} + +Ref<API::Array> WebBackForwardList::forwardList() const +{ + return forwardListAsAPIArrayWithLimit(forwardListCount()); +} + +Ref<API::Array> WebBackForwardList::backListAsAPIArrayWithLimit(unsigned limit) const { ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); if (!m_page || !m_hasCurrentIndex) - return ImmutableArray::create(); + return API::Array::create(); unsigned backListSize = static_cast<unsigned>(backListCount()); unsigned size = std::min(backListSize, limit); if (!size) - return ImmutableArray::create(); + return API::Array::create(); - Vector<RefPtr<APIObject> > vector; + Vector<RefPtr<API::Object>> vector; vector.reserveInitialCapacity(size); ASSERT(backListSize >= size); @@ -221,21 +288,21 @@ PassRefPtr<ImmutableArray> WebBackForwardList::backListAsImmutableArrayWithLimit vector.uncheckedAppend(m_entries[i].get()); } - return ImmutableArray::adopt(vector); + return API::Array::create(WTFMove(vector)); } -PassRefPtr<ImmutableArray> WebBackForwardList::forwardListAsImmutableArrayWithLimit(unsigned limit) const +Ref<API::Array> WebBackForwardList::forwardListAsAPIArrayWithLimit(unsigned limit) const { ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); if (!m_page || !m_hasCurrentIndex) - return ImmutableArray::create(); + return API::Array::create(); unsigned size = std::min(static_cast<unsigned>(forwardListCount()), limit); if (!size) - return ImmutableArray::create(); + return API::Array::create(); - Vector<RefPtr<APIObject> > vector; + Vector<RefPtr<API::Object>> vector; vector.reserveInitialCapacity(size); unsigned last = m_currentIndex + size; @@ -245,7 +312,27 @@ PassRefPtr<ImmutableArray> WebBackForwardList::forwardListAsImmutableArrayWithLi vector.uncheckedAppend(m_entries[i].get()); } - return ImmutableArray::adopt(vector); + return API::Array::create(WTFMove(vector)); +} + +void WebBackForwardList::removeAllItems() +{ + ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); + + Vector<RefPtr<WebBackForwardListItem>> removedItems; + + for (auto& entry : m_entries) { + ASSERT(entry); + if (!entry) + continue; + + didRemoveItem(*entry); + removedItems.append(WTFMove(entry)); + } + + m_entries.clear(); + m_hasCurrentIndex = false; + m_page->didChangeBackForwardList(nullptr, WTFMove(removedItems)); } void WebBackForwardList::clear() @@ -257,7 +344,7 @@ void WebBackForwardList::clear() return; RefPtr<WebBackForwardListItem> currentItem = this->currentItem(); - Vector<RefPtr<APIObject> > removedItems; + Vector<RefPtr<WebBackForwardListItem>> removedItems; if (!currentItem) { // We should only ever have no current item if we also have no current item index. @@ -269,13 +356,13 @@ void WebBackForwardList::clear() if (!m_entries[i]) continue; - m_page->backForwardRemovedItem(m_entries[i]->itemID()); + didRemoveItem(*m_entries[i]); removedItems.append(m_entries[i].release()); } m_entries.clear(); m_hasCurrentIndex = false; - m_page->didChangeBackForwardList(0, &removedItems); + m_page->didChangeBackForwardList(nullptr, WTFMove(removedItems)); return; } @@ -283,7 +370,7 @@ void WebBackForwardList::clear() for (size_t i = 0; i < size; ++i) { ASSERT(m_entries[i]); if (m_entries[i] && m_entries[i] != currentItem) - m_page->backForwardRemovedItem(m_entries[i]->itemID()); + didRemoveItem(*m_entries[i]); } removedItems.reserveCapacity(size - 1); @@ -302,7 +389,69 @@ void WebBackForwardList::clear() m_hasCurrentIndex = false; } - m_page->didChangeBackForwardList(0, &removedItems); + m_page->didChangeBackForwardList(nullptr, WTFMove(removedItems)); +} + +BackForwardListState WebBackForwardList::backForwardListState(const std::function<bool (WebBackForwardListItem&)>& filter) const +{ + ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); + + BackForwardListState backForwardListState; + if (m_hasCurrentIndex) + backForwardListState.currentIndex = m_currentIndex; + + for (size_t i = 0; i < m_entries.size(); ++i) { + auto& entry = *m_entries[i]; + + if (filter && !filter(entry)) { + auto& currentIndex = backForwardListState.currentIndex; + if (currentIndex && i <= currentIndex.value() && currentIndex.value()) + --currentIndex.value(); + + continue; + } + + backForwardListState.items.append(entry.itemState()); + } + + if (backForwardListState.items.isEmpty()) + backForwardListState.currentIndex = Nullopt; + + return backForwardListState; +} + +void WebBackForwardList::restoreFromState(BackForwardListState backForwardListState) +{ + Vector<RefPtr<WebBackForwardListItem>> items; + items.reserveInitialCapacity(backForwardListState.items.size()); + + for (auto& backForwardListItemState : backForwardListState.items) { + backForwardListItemState.identifier = generateWebBackForwardItemID(); + items.uncheckedAppend(WebBackForwardListItem::create(WTFMove(backForwardListItemState), m_page->pageID())); + } + m_hasCurrentIndex = !!backForwardListState.currentIndex; + m_currentIndex = backForwardListState.currentIndex.valueOr(0); + m_entries = WTFMove(items); +} + +Vector<BackForwardListItemState> WebBackForwardList::itemStates() const +{ + Vector<BackForwardListItemState> itemStates; + itemStates.reserveInitialCapacity(m_entries.size()); + + for (const auto& entry : m_entries) + itemStates.uncheckedAppend(entry->itemState()); + + return itemStates; +} + +void WebBackForwardList::didRemoveItem(WebBackForwardListItem& backForwardListItem) +{ + m_page->backForwardRemovedItem(backForwardListItem.itemID()); + +#if PLATFORM(COCOA) + backForwardListItem.setSnapshot(nullptr); +#endif } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebBackForwardList.h b/Source/WebKit2/UIProcess/WebBackForwardList.h index ecef42b4f..178f07e87 100644 --- a/Source/WebKit2/UIProcess/WebBackForwardList.h +++ b/Source/WebKit2/UIProcess/WebBackForwardList.h @@ -27,10 +27,9 @@ #define WebBackForwardList_h #include "APIObject.h" -#include "ImmutableArray.h" #include "WebBackForwardListItem.h" #include "WebPageProxy.h" -#include <wtf/PassRefPtr.h> +#include <wtf/Ref.h> #include <wtf/RefPtr.h> #include <wtf/Vector.h> #if USE(CF) @@ -39,19 +38,13 @@ namespace WebKit { -typedef Vector<RefPtr<WebBackForwardListItem> > BackForwardListItemVector; +struct BackForwardListState; -/* - * Current - * |---------*--------------| Entries - * Back Forward - */ - -class WebBackForwardList : public TypedAPIObject<APIObject::TypeBackForwardList> { +class WebBackForwardList : public API::ObjectImpl<API::Object::Type::BackForwardList> { public: - static PassRefPtr<WebBackForwardList> create(WebPageProxy* page) + static Ref<WebBackForwardList> create(WebPageProxy& page) { - return adoptRef(new WebBackForwardList(page)); + return adoptRef(*new WebBackForwardList(page)); } void pageClosed(); @@ -59,31 +52,35 @@ public: void addItem(WebBackForwardListItem*); void goToItem(WebBackForwardListItem*); + void removeAllItems(); void clear(); - WebBackForwardListItem* currentItem(); - WebBackForwardListItem* backItem(); - WebBackForwardListItem* forwardItem(); - WebBackForwardListItem* itemAtIndex(int); - + WebBackForwardListItem* currentItem() const; + WebBackForwardListItem* backItem() const; + WebBackForwardListItem* forwardItem() const; + WebBackForwardListItem* itemAtIndex(int) const; + const BackForwardListItemVector& entries() const { return m_entries; } uint32_t currentIndex() const { return m_currentIndex; } int backListCount() const; int forwardListCount() const; - PassRefPtr<ImmutableArray> backListAsImmutableArrayWithLimit(unsigned limit) const; - PassRefPtr<ImmutableArray> forwardListAsImmutableArrayWithLimit(unsigned limit) const; + Ref<API::Array> backList() const; + Ref<API::Array> forwardList() const; -#if USE(CF) - CFDictionaryRef createCFDictionaryRepresentation(WebPageProxy::WebPageProxySessionStateFilterCallback, void* context) const; - bool restoreFromCFDictionaryRepresentation(CFDictionaryRef); - bool restoreFromV0CFDictionaryRepresentation(CFDictionaryRef); - bool restoreFromV1CFDictionaryRepresentation(CFDictionaryRef); -#endif + Ref<API::Array> backListAsAPIArrayWithLimit(unsigned limit) const; + Ref<API::Array> forwardListAsAPIArrayWithLimit(unsigned limit) const; + + BackForwardListState backForwardListState(const std::function<bool (WebBackForwardListItem&)>&) const; + void restoreFromState(BackForwardListState); + + Vector<BackForwardListItemState> itemStates() const; private: - explicit WebBackForwardList(WebPageProxy*); + explicit WebBackForwardList(WebPageProxy&); + + void didRemoveItem(WebBackForwardListItem&); WebPageProxy* m_page; BackForwardListItemVector m_entries; diff --git a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp index 43e54f796..4caa76e3f 100644 --- a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.cpp @@ -30,7 +30,7 @@ #include "WebBatteryManagerMessages.h" #include "WebBatteryManagerProxyMessages.h" -#include "WebContext.h" +#include "WebProcessPool.h" namespace WebKit { @@ -39,23 +39,23 @@ const char* WebBatteryManagerProxy::supplementName() return "WebBatteryManagerProxy"; } -PassRefPtr<WebBatteryManagerProxy> WebBatteryManagerProxy::create(WebContext* context) +Ref<WebBatteryManagerProxy> WebBatteryManagerProxy::create(WebProcessPool* processPool) { - return adoptRef(new WebBatteryManagerProxy(context)); + return adoptRef(*new WebBatteryManagerProxy(processPool)); } -WebBatteryManagerProxy::WebBatteryManagerProxy(WebContext* context) - : WebContextSupplement(context) +WebBatteryManagerProxy::WebBatteryManagerProxy(WebProcessPool* processPool) + : WebContextSupplement(processPool) , m_isUpdating(false) { - WebContextSupplement::context()->addMessageReceiver(Messages::WebBatteryManagerProxy::messageReceiverName(), this); + WebContextSupplement::processPool()->addMessageReceiver(Messages::WebBatteryManagerProxy::messageReceiverName(), *this); } WebBatteryManagerProxy::~WebBatteryManagerProxy() { } -void WebBatteryManagerProxy::initializeProvider(const WKBatteryProvider* provider) +void WebBatteryManagerProxy::initializeProvider(const WKBatteryProviderBase* provider) { m_provider.initialize(provider); } @@ -63,23 +63,23 @@ void WebBatteryManagerProxy::initializeProvider(const WKBatteryProvider* provide void WebBatteryManagerProxy::providerDidChangeBatteryStatus(const WTF::AtomicString& eventType, WebBatteryStatus* status) { - if (!context()) + if (!processPool()) return; - context()->sendToAllProcesses(Messages::WebBatteryManager::DidChangeBatteryStatus(eventType, status->data())); + processPool()->sendToAllProcesses(Messages::WebBatteryManager::DidChangeBatteryStatus(eventType, status->data())); } void WebBatteryManagerProxy::providerUpdateBatteryStatus(WebBatteryStatus* status) { - if (!context()) + if (!processPool()) return; - context()->sendToAllProcesses(Messages::WebBatteryManager::UpdateBatteryStatus(status->data())); + processPool()->sendToAllProcesses(Messages::WebBatteryManager::UpdateBatteryStatus(status->data())); } // WebContextSupplement -void WebBatteryManagerProxy::contextDestroyed() +void WebBatteryManagerProxy::processPoolDestroyed() { stopUpdating(); } @@ -91,12 +91,12 @@ void WebBatteryManagerProxy::processDidClose(WebProcessProxy*) void WebBatteryManagerProxy::refWebContextSupplement() { - APIObject::ref(); + API::Object::ref(); } void WebBatteryManagerProxy::derefWebContextSupplement() { - APIObject::deref(); + API::Object::deref(); } void WebBatteryManagerProxy::startUpdating() diff --git a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h index cbaed1050..c4cc32928 100644 --- a/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebBatteryManagerProxy.h @@ -36,35 +36,35 @@ namespace WebKit { -class WebContext; +class WebProcessPool; class WebBatteryStatus; -class WebBatteryManagerProxy : public TypedAPIObject<APIObject::TypeBatteryManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { +class WebBatteryManagerProxy : public API::ObjectImpl<API::Object::Type::BatteryManager>, public WebContextSupplement, private IPC::MessageReceiver { public: static const char* supplementName(); - static PassRefPtr<WebBatteryManagerProxy> create(WebContext*); + static Ref<WebBatteryManagerProxy> create(WebProcessPool*); virtual ~WebBatteryManagerProxy(); - void initializeProvider(const WKBatteryProvider*); + void initializeProvider(const WKBatteryProviderBase*); void providerDidChangeBatteryStatus(const WTF::AtomicString&, WebBatteryStatus*); void providerUpdateBatteryStatus(WebBatteryStatus*); - using APIObject::ref; - using APIObject::deref; + using API::Object::ref; + using API::Object::deref; private: - explicit WebBatteryManagerProxy(WebContext*); + explicit WebBatteryManagerProxy(WebProcessPool*); // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; + virtual void processPoolDestroyed() override; + virtual void processDidClose(WebProcessProxy*) override; + virtual void refWebContextSupplement() override; + virtual void derefWebContextSupplement() override; - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; void startUpdating(); void stopUpdating(); diff --git a/Source/WebKit2/UIProcess/WebBatteryProvider.cpp b/Source/WebKit2/UIProcess/WebBatteryProvider.cpp index 82841601d..28eed97ae 100644 --- a/Source/WebKit2/UIProcess/WebBatteryProvider.cpp +++ b/Source/WebKit2/UIProcess/WebBatteryProvider.cpp @@ -38,7 +38,7 @@ void WebBatteryProvider::startUpdating(WebBatteryManagerProxy* batteryManager) if (!m_client.startUpdating) return; - m_client.startUpdating(toAPI(batteryManager), m_client.clientInfo); + m_client.startUpdating(toAPI(batteryManager), m_client.base.clientInfo); } void WebBatteryProvider::stopUpdating(WebBatteryManagerProxy* batteryManager) @@ -46,7 +46,7 @@ void WebBatteryProvider::stopUpdating(WebBatteryManagerProxy* batteryManager) if (!m_client.stopUpdating) return; - m_client.stopUpdating(toAPI(batteryManager), m_client.clientInfo); + m_client.stopUpdating(toAPI(batteryManager), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebBatteryProvider.h b/Source/WebKit2/UIProcess/WebBatteryProvider.h index f599068c9..a1dba015e 100644 --- a/Source/WebKit2/UIProcess/WebBatteryProvider.h +++ b/Source/WebKit2/UIProcess/WebBatteryProvider.h @@ -32,11 +32,17 @@ #include "WKBatteryManager.h" #include <wtf/Forward.h> +namespace API { +template<> struct ClientTraits<WKBatteryProviderBase> { + typedef std::tuple<WKBatteryProviderV0> Versions; +}; +} + namespace WebKit { class WebBatteryManagerProxy; -class WebBatteryProvider : public APIClient<WKBatteryProvider, kWKBatteryProviderCurrentVersion> { +class WebBatteryProvider : public API::Client<WKBatteryProviderBase> { public: void startUpdating(WebBatteryManagerProxy*); void stopUpdating(WebBatteryManagerProxy*); diff --git a/Source/WebKit2/UIProcess/WebColorPicker.cpp b/Source/WebKit2/UIProcess/WebColorPicker.cpp index 3487da97f..1132c0745 100644 --- a/Source/WebKit2/UIProcess/WebColorPicker.cpp +++ b/Source/WebKit2/UIProcess/WebColorPicker.cpp @@ -39,12 +39,18 @@ WebColorPicker::~WebColorPicker() { } -void WebColorPicker::endChooser() +void WebColorPicker::invalidate() +{ + endPicker(); + m_client = 0; +} + +void WebColorPicker::endPicker() { if (!m_client) return; - m_client->didEndColorChooser(); + m_client->didEndColorPicker(); } void WebColorPicker::setSelectedColor(const WebCore::Color& color) @@ -55,6 +61,12 @@ void WebColorPicker::setSelectedColor(const WebCore::Color& color) m_client->didChooseColor(color); } +void WebColorPicker::showColorPicker(const WebCore::Color&) +{ + ASSERT_NOT_REACHED(); + return; +} + } // namespace WebKit #endif // ENABLE(INPUT_TYPE_COLOR) diff --git a/Source/WebKit2/UIProcess/WebColorPicker.h b/Source/WebKit2/UIProcess/WebColorPicker.h index bd886475b..5400ddc14 100644 --- a/Source/WebKit2/UIProcess/WebColorPicker.h +++ b/Source/WebKit2/UIProcess/WebColorPicker.h @@ -47,7 +47,7 @@ public: public: virtual void didChooseColor(const WebCore::Color&) = 0; - virtual void didEndColorChooser() = 0; + virtual void didEndColorPicker() = 0; }; static PassRefPtr<WebColorPicker> create(Client* client) @@ -57,10 +57,11 @@ public: virtual ~WebColorPicker(); - void invalidate() { m_client = 0; } + void invalidate(); - virtual void endChooser(); + virtual void endPicker(); virtual void setSelectedColor(const WebCore::Color&); + virtual void showColorPicker(const WebCore::Color&); protected: explicit WebColorPicker(Client*); diff --git a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp index c2c6e2455..e8e08500f 100644 --- a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp +++ b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.cpp @@ -27,7 +27,6 @@ #include "WebConnectionToWebProcess.h" #include "WebConnectionMessages.h" -#include "WebContextUserMessageCoders.h" #include "WebProcessProxy.h" namespace WebKit { @@ -40,25 +39,26 @@ PassRefPtr<WebConnectionToWebProcess> WebConnectionToWebProcess::create(WebProce WebConnectionToWebProcess::WebConnectionToWebProcess(WebProcessProxy* process) : m_process(process) { - m_process->addMessageReceiver(Messages::WebConnection::messageReceiverName(), this); + m_process->addMessageReceiver(Messages::WebConnection::messageReceiverName(), *this); } void WebConnectionToWebProcess::invalidate() { + m_process->removeMessageReceiver(Messages::WebConnection::messageReceiverName()); + m_process = 0; } // WebConnection -void WebConnectionToWebProcess::encodeMessageBody(CoreIPC::ArgumentEncoder& encoder, APIObject* messageBody) +RefPtr<API::Object> WebConnectionToWebProcess::transformHandlesToObjects(API::Object* object) { - encoder << WebContextUserMessageEncoder(messageBody); + return m_process->transformHandlesToObjects(object); } -bool WebConnectionToWebProcess::decodeMessageBody(CoreIPC::ArgumentDecoder& decoder, RefPtr<APIObject>& messageBody) +RefPtr<API::Object> WebConnectionToWebProcess::transformObjectsToHandles(API::Object* object) { - WebContextUserMessageDecoder messageBodyDecoder(messageBody, m_process); - return decoder.decode(messageBodyDecoder); + return m_process->transformObjectsToHandles(object); } bool WebConnectionToWebProcess::hasValidConnection() const @@ -66,7 +66,7 @@ bool WebConnectionToWebProcess::hasValidConnection() const return m_process; } -CoreIPC::Connection* WebConnectionToWebProcess::messageSenderConnection() +IPC::Connection* WebConnectionToWebProcess::messageSenderConnection() { return m_process->connection(); } diff --git a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h index 5717f4625..a3664be5a 100644 --- a/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h +++ b/Source/WebKit2/UIProcess/WebConnectionToWebProcess.h @@ -44,13 +44,13 @@ private: WebConnectionToWebProcess(WebProcessProxy*); // WebConnection - virtual void encodeMessageBody(CoreIPC::ArgumentEncoder&, APIObject*) OVERRIDE; - virtual bool decodeMessageBody(CoreIPC::ArgumentDecoder&, RefPtr<APIObject>&) OVERRIDE; - virtual bool hasValidConnection() const OVERRIDE; + virtual RefPtr<API::Object> transformHandlesToObjects(API::Object*) override; + virtual RefPtr<API::Object> transformObjectsToHandles(API::Object*) override; + virtual bool hasValidConnection() const override; - // CoreIPC::MessageSender - virtual CoreIPC::Connection* messageSenderConnection() OVERRIDE; - virtual uint64_t messageSenderDestinationID() OVERRIDE; + // IPC::MessageSender + virtual IPC::Connection* messageSenderConnection() override; + virtual uint64_t messageSenderDestinationID() override; WebProcessProxy* m_process; }; diff --git a/Source/WebKit2/UIProcess/WebContext.cpp b/Source/WebKit2/UIProcess/WebContext.cpp deleted file mode 100644 index fd57610d4..000000000 --- a/Source/WebKit2/UIProcess/WebContext.cpp +++ /dev/null @@ -1,1257 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebContext.h" - -#include "DownloadProxy.h" -#include "DownloadProxyMessages.h" -#include "ImmutableArray.h" -#include "Logging.h" -#include "MutableDictionary.h" -#include "SandboxExtension.h" -#include "StatisticsData.h" -#include "TextChecker.h" -#include "WKContextPrivate.h" -#include "WebApplicationCacheManagerProxy.h" -#include "WebContextMessageKinds.h" -#include "WebContextMessages.h" -#include "WebContextSupplement.h" -#include "WebContextUserMessageCoders.h" -#include "WebCookieManagerProxy.h" -#include "WebCoreArgumentCoders.h" -#include "WebDatabaseManagerProxy.h" -#include "WebGeolocationManagerProxy.h" -#include "WebIconDatabase.h" -#include "WebKeyValueStorageManager.h" -#include "WebMediaCacheManagerProxy.h" -#include "WebNotificationManagerProxy.h" -#include "WebPluginSiteDataManager.h" -#include "WebPageGroup.h" -#include "WebPreferences.h" -#include "WebMemorySampler.h" -#include "WebProcessCreationParameters.h" -#include "WebProcessMessages.h" -#include "WebProcessProxy.h" -#include "WebResourceCacheManagerProxy.h" -#include <WebCore/InitializeLogging.h> -#include <WebCore/Language.h> -#include <WebCore/LinkHash.h> -#include <WebCore/ResourceRequest.h> -#include <WebCore/RunLoop.h> -#include <runtime/InitializeThreading.h> -#include <runtime/Operations.h> -#include <wtf/CurrentTime.h> -#include <wtf/MainThread.h> - -#if ENABLE(BATTERY_STATUS) -#include "WebBatteryManagerProxy.h" -#endif - -#if ENABLE(NETWORK_INFO) -#include "WebNetworkInfoManagerProxy.h" -#endif - -#if ENABLE(NETWORK_PROCESS) -#include "NetworkProcessCreationParameters.h" -#include "NetworkProcessMessages.h" -#include "NetworkProcessProxy.h" -#endif - -#if ENABLE(CUSTOM_PROTOCOLS) -#include "CustomProtocolManagerMessages.h" -#endif - -#if USE(SOUP) -#include "WebSoupRequestManagerProxy.h" -#endif - -#ifndef NDEBUG -#include <wtf/RefCountedLeakCounter.h> -#endif - -using namespace WebCore; - -namespace WebKit { - -static const double sharedSecondaryProcessShutdownTimeout = 60; - -DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webContextCounter, ("WebContext")); - -PassRefPtr<WebContext> WebContext::create(const String& injectedBundlePath) -{ - JSC::initializeThreading(); - WTF::initializeMainThread(); - RunLoop::initializeMainRunLoop(); - return adoptRef(new WebContext(ProcessModelSharedSecondaryProcess, injectedBundlePath)); -} - -static Vector<WebContext*>& contexts() -{ - DEFINE_STATIC_LOCAL(Vector<WebContext*>, contexts, ()); - - return contexts; -} - -const Vector<WebContext*>& WebContext::allContexts() -{ - return contexts(); -} - -WebContext::WebContext(ProcessModel processModel, const String& injectedBundlePath) - : m_processModel(processModel) - , m_webProcessCountLimit(UINT_MAX) - , m_haveInitialEmptyProcess(false) - , m_processWithPageCache(0) - , m_defaultPageGroup(WebPageGroup::create()) - , m_injectedBundlePath(injectedBundlePath) - , m_visitedLinkProvider(this) - , m_plugInAutoStartProvider(this) - , m_alwaysUsesComplexTextCodePath(false) - , m_shouldUseFontSmoothing(true) - , m_cacheModel(CacheModelDocumentViewer) - , m_memorySamplerEnabled(false) - , m_memorySamplerInterval(1400.0) - , m_storageManager(StorageManager::create()) -#if USE(SOUP) - , m_initialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) -#endif - , m_processTerminationEnabled(true) -#if ENABLE(NETWORK_PROCESS) - , m_usesNetworkProcess(false) -#endif -#if PLATFORM(MAC) - , m_processSuppressionEnabled(true) -#endif -#if USE(SOUP) - , m_ignoreTLSErrors(true) -#endif -{ - platformInitialize(); - - addMessageReceiver(Messages::WebContext::messageReceiverName(), this); - addMessageReceiver(WebContextLegacyMessages::messageReceiverName(), this); - - // NOTE: These sub-objects must be initialized after m_messageReceiverMap.. - m_iconDatabase = WebIconDatabase::create(this); -#if ENABLE(NETSCAPE_PLUGIN_API) - m_pluginSiteDataManager = WebPluginSiteDataManager::create(this); -#endif // ENABLE(NETSCAPE_PLUGIN_API) - - addSupplement<WebApplicationCacheManagerProxy>(); - addSupplement<WebCookieManagerProxy>(); - addSupplement<WebGeolocationManagerProxy>(); - addSupplement<WebKeyValueStorageManager>(); - addSupplement<WebMediaCacheManagerProxy>(); - addSupplement<WebNotificationManagerProxy>(); - addSupplement<WebResourceCacheManagerProxy>(); -#if ENABLE(SQL_DATABASE) - addSupplement<WebDatabaseManagerProxy>(); -#endif -#if USE(SOUP) - addSupplement<WebSoupRequestManagerProxy>(); -#endif -#if ENABLE(BATTERY_STATUS) - addSupplement<WebBatteryManagerProxy>(); -#endif -#if ENABLE(NETWORK_INFO) - addSupplement<WebNetworkInfoManagerProxy>(); -#endif - - contexts().append(this); - - addLanguageChangeObserver(this, languageChanged); - -#if !LOG_DISABLED - WebCore::initializeLoggingChannelsIfNecessary(); - WebKit::initializeLogChannelsIfNecessary(); -#endif // !LOG_DISABLED - -#if ENABLE(NETSCAPE_PLUGIN_API) - m_pluginInfoStore.setClient(this); -#endif - -#ifndef NDEBUG - webContextCounter.increment(); -#endif - - String localStorageDirectory = this->localStorageDirectory(); - if (!localStorageDirectory.isEmpty()) - m_storageManager->setLocalStorageDirectory(localStorageDirectory); -} - -#if !PLATFORM(MAC) -void WebContext::platformInitialize() -{ -} -#endif - -WebContext::~WebContext() -{ - ASSERT(contexts().find(this) != notFound); - contexts().remove(contexts().find(this)); - - removeLanguageChangeObserver(this); - - m_messageReceiverMap.invalidate(); - - WebContextSupplementMap::const_iterator it = m_supplements.begin(); - WebContextSupplementMap::const_iterator end = m_supplements.end(); - for (; it != end; ++it) { - it->value->contextDestroyed(); - it->value->clearContext(); - } - - m_iconDatabase->invalidate(); - m_iconDatabase->clearContext(); - -#if ENABLE(NETSCAPE_PLUGIN_API) - m_pluginSiteDataManager->invalidate(); - m_pluginSiteDataManager->clearContext(); -#endif - - invalidateCallbackMap(m_dictionaryCallbacks); - - platformInvalidateContext(); - -#if ENABLE(NETSCAPE_PLUGIN_API) - m_pluginInfoStore.setClient(0); -#endif - -#ifndef NDEBUG - webContextCounter.decrement(); -#endif -} - -void WebContext::initializeClient(const WKContextClient* client) -{ - m_client.initialize(client); -} - -void WebContext::initializeInjectedBundleClient(const WKContextInjectedBundleClient* client) -{ - m_injectedBundleClient.initialize(client); -} - -void WebContext::initializeConnectionClient(const WKContextConnectionClient* client) -{ - m_connectionClient.initialize(client); -} - -void WebContext::initializeHistoryClient(const WKContextHistoryClient* client) -{ - m_historyClient.initialize(client); - - sendToAllProcesses(Messages::WebProcess::SetShouldTrackVisitedLinks(m_historyClient.shouldTrackVisitedLinks())); -} - -void WebContext::initializeDownloadClient(const WKContextDownloadClient* client) -{ - m_downloadClient.initialize(client); -} - -void WebContext::setProcessModel(ProcessModel processModel) -{ - // Guard against API misuse. - if (!m_processes.isEmpty()) - CRASH(); - if (processModel != ProcessModelSharedSecondaryProcess && !m_messagesToInjectedBundlePostedToEmptyContext.isEmpty()) - CRASH(); - -#if !ENABLE(PLUGIN_PROCESS) - // Plugin process is required for multiple web process mode. - if (processModel != ProcessModelSharedSecondaryProcess) - CRASH(); -#endif - - m_processModel = processModel; -} - -void WebContext::setMaximumNumberOfProcesses(unsigned maximumNumberOfProcesses) -{ - // Guard against API misuse. - if (!m_processes.isEmpty()) - CRASH(); - - if (maximumNumberOfProcesses == 0) - m_webProcessCountLimit = UINT_MAX; - else - m_webProcessCountLimit = maximumNumberOfProcesses; -} - -CoreIPC::Connection* WebContext::networkingProcessConnection() -{ - switch (m_processModel) { - case ProcessModelSharedSecondaryProcess: -#if ENABLE(NETWORK_PROCESS) - if (m_usesNetworkProcess) - return m_networkProcess->connection(); -#endif - return m_processes[0]->connection(); - case ProcessModelMultipleSecondaryProcesses: -#if ENABLE(NETWORK_PROCESS) - ASSERT(m_usesNetworkProcess); - return m_networkProcess->connection(); -#else - break; -#endif - } - ASSERT_NOT_REACHED(); - return 0; -} - -void WebContext::languageChanged(void* context) -{ - static_cast<WebContext*>(context)->languageChanged(); -} - -void WebContext::languageChanged() -{ - sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged(userPreferredLanguages())); -} - -void WebContext::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled) -{ - sendToAllProcesses(Messages::WebProcess::FullKeyboardAccessModeChanged(fullKeyboardAccessEnabled)); -} - -void WebContext::textCheckerStateChanged() -{ - sendToAllProcesses(Messages::WebProcess::SetTextCheckerState(TextChecker::state())); -} - -void WebContext::setUsesNetworkProcess(bool usesNetworkProcess) -{ -#if ENABLE(NETWORK_PROCESS) - m_usesNetworkProcess = usesNetworkProcess; -#else - UNUSED_PARAM(usesNetworkProcess); -#endif -} - -bool WebContext::usesNetworkProcess() const -{ -#if ENABLE(NETWORK_PROCESS) - return m_usesNetworkProcess; -#else - return false; -#endif -} - -#if ENABLE(NETWORK_PROCESS) -void WebContext::ensureNetworkProcess() -{ - if (m_networkProcess) - return; - - m_networkProcess = NetworkProcessProxy::create(this); - - NetworkProcessCreationParameters parameters; - - parameters.diskCacheDirectory = diskCacheDirectory(); - if (!parameters.diskCacheDirectory.isEmpty()) - SandboxExtension::createHandleForReadWriteDirectory(parameters.diskCacheDirectory, parameters.diskCacheDirectoryExtensionHandle); - - parameters.privateBrowsingEnabled = WebPreferences::anyPageGroupsAreUsingPrivateBrowsing(); - - parameters.cacheModel = m_cacheModel; - - // Add any platform specific parameters - platformInitializeNetworkProcess(parameters); - - // Initialize the network process. - m_networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0); -} - -void WebContext::networkProcessCrashed(NetworkProcessProxy* networkProcessProxy) -{ - ASSERT(m_networkProcess); - ASSERT(networkProcessProxy == m_networkProcess.get()); - - WebContextSupplementMap::const_iterator it = m_supplements.begin(); - WebContextSupplementMap::const_iterator end = m_supplements.end(); - for (; it != end; ++it) - it->value->processDidClose(networkProcessProxy); - - m_networkProcess = nullptr; - - m_client.networkProcessDidCrash(this); -} - -void WebContext::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) -{ - ASSERT(reply); - - ensureNetworkProcess(); - ASSERT(m_networkProcess); - - m_networkProcess->getNetworkProcessConnection(reply); -} -#endif - - -void WebContext::willStartUsingPrivateBrowsing() -{ - const Vector<WebContext*>& contexts = allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) { -#if ENABLE(NETWORK_PROCESS) - if (contexts[i]->usesNetworkProcess() && contexts[i]->networkProcess()) - contexts[i]->networkProcess()->send(Messages::NetworkProcess::EnsurePrivateBrowsingSession(), 0); -#endif - contexts[i]->sendToAllProcesses(Messages::WebProcess::EnsurePrivateBrowsingSession()); - } -} - -void WebContext::willStopUsingPrivateBrowsing() -{ - const Vector<WebContext*>& contexts = allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) { -#if ENABLE(NETWORK_PROCESS) - if (contexts[i]->usesNetworkProcess() && contexts[i]->networkProcess()) - contexts[i]->networkProcess()->send(Messages::NetworkProcess::DestroyPrivateBrowsingSession(), 0); -#endif - - contexts[i]->sendToAllProcesses(Messages::WebProcess::DestroyPrivateBrowsingSession()); - } -} - -void (*s_invalidMessageCallback)(WKStringRef messageName); - -void WebContext::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName)) -{ - s_invalidMessageCallback = invalidMessageCallback; -} - -void WebContext::didReceiveInvalidMessage(const CoreIPC::StringReference& messageReceiverName, const CoreIPC::StringReference& messageName) -{ - if (!s_invalidMessageCallback) - return; - - StringBuilder messageNameStringBuilder; - messageNameStringBuilder.append(messageReceiverName.data(), messageReceiverName.size()); - messageNameStringBuilder.append("."); - messageNameStringBuilder.append(messageName.data(), messageName.size()); - - s_invalidMessageCallback(toAPI(WebString::create(messageNameStringBuilder.toString()).get())); -} - -void WebContext::processDidCachePage(WebProcessProxy* process) -{ - if (m_processWithPageCache && m_processWithPageCache != process) - m_processWithPageCache->releasePageCache(); - m_processWithPageCache = process; -} - -WebProcessProxy* WebContext::ensureSharedWebProcess() -{ - ASSERT(m_processModel == ProcessModelSharedSecondaryProcess); - if (m_processes.isEmpty()) - createNewWebProcess(); - return m_processes[0].get(); -} - -WebProcessProxy* WebContext::createNewWebProcess() -{ -#if ENABLE(NETWORK_PROCESS) - if (m_usesNetworkProcess) - ensureNetworkProcess(); -#endif - - RefPtr<WebProcessProxy> process = WebProcessProxy::create(this); - - WebProcessCreationParameters parameters; - - parameters.injectedBundlePath = injectedBundlePath(); - if (!parameters.injectedBundlePath.isEmpty()) - SandboxExtension::createHandle(parameters.injectedBundlePath, SandboxExtension::ReadOnly, parameters.injectedBundlePathExtensionHandle); - - parameters.applicationCacheDirectory = applicationCacheDirectory(); - if (!parameters.applicationCacheDirectory.isEmpty()) - SandboxExtension::createHandleForReadWriteDirectory(parameters.applicationCacheDirectory, parameters.applicationCacheDirectoryExtensionHandle); - - parameters.databaseDirectory = databaseDirectory(); - if (!parameters.databaseDirectory.isEmpty()) - SandboxExtension::createHandleForReadWriteDirectory(parameters.databaseDirectory, parameters.databaseDirectoryExtensionHandle); - - parameters.localStorageDirectory = localStorageDirectory(); - if (!parameters.localStorageDirectory.isEmpty()) - SandboxExtension::createHandleForReadWriteDirectory(parameters.localStorageDirectory, parameters.localStorageDirectoryExtensionHandle); - - parameters.diskCacheDirectory = diskCacheDirectory(); - if (!parameters.diskCacheDirectory.isEmpty()) - SandboxExtension::createHandleForReadWriteDirectory(parameters.diskCacheDirectory, parameters.diskCacheDirectoryExtensionHandle); - - parameters.cookieStorageDirectory = cookieStorageDirectory(); - if (!parameters.cookieStorageDirectory.isEmpty()) - SandboxExtension::createHandleForReadWriteDirectory(parameters.cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle); - - parameters.shouldTrackVisitedLinks = m_historyClient.shouldTrackVisitedLinks(); - parameters.cacheModel = m_cacheModel; - parameters.languages = userPreferredLanguages(); - - copyToVector(m_schemesToRegisterAsEmptyDocument, parameters.urlSchemesRegistererdAsEmptyDocument); - copyToVector(m_schemesToRegisterAsSecure, parameters.urlSchemesRegisteredAsSecure); - copyToVector(m_schemesToSetDomainRelaxationForbiddenFor, parameters.urlSchemesForWhichDomainRelaxationIsForbidden); - copyToVector(m_schemesToRegisterAsLocal, parameters.urlSchemesRegisteredAsLocal); - copyToVector(m_schemesToRegisterAsNoAccess, parameters.urlSchemesRegisteredAsNoAccess); - copyToVector(m_schemesToRegisterAsDisplayIsolated, parameters.urlSchemesRegisteredAsDisplayIsolated); - copyToVector(m_schemesToRegisterAsCORSEnabled, parameters.urlSchemesRegisteredAsCORSEnabled); - - parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath; - parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing; - - parameters.iconDatabaseEnabled = !iconDatabasePath().isEmpty(); - - parameters.terminationTimeout = (m_processModel == ProcessModelSharedSecondaryProcess) ? sharedSecondaryProcessShutdownTimeout : 0; - - parameters.textCheckerState = TextChecker::state(); - - parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled(); - - parameters.defaultRequestTimeoutInterval = WebURLRequest::defaultTimeoutInterval(); - -#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) - // FIXME: There should be a generic way for supplements to add to the intialization parameters. - supplement<WebNotificationManagerProxy>()->populateCopyOfNotificationPermissions(parameters.notificationPermissions); -#endif - -#if ENABLE(NETWORK_PROCESS) - parameters.usesNetworkProcess = m_usesNetworkProcess; -#endif - - parameters.plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy(); - copyToVector(m_plugInAutoStartProvider.autoStartOrigins(), parameters.plugInAutoStartOrigins); - - // Add any platform specific parameters - platformInitializeWebProcess(parameters); - - RefPtr<APIObject> injectedBundleInitializationUserData = m_injectedBundleClient.getInjectedBundleInitializationUserData(this); - if (!injectedBundleInitializationUserData) - injectedBundleInitializationUserData = m_injectedBundleInitializationUserData; - process->send(Messages::WebProcess::InitializeWebProcess(parameters, WebContextUserMessageEncoder(injectedBundleInitializationUserData.get())), 0); - - if (WebPreferences::anyPageGroupsAreUsingPrivateBrowsing()) - process->send(Messages::WebProcess::EnsurePrivateBrowsingSession(), 0); - - m_processes.append(process); - - if (m_processModel == ProcessModelSharedSecondaryProcess) { - for (size_t i = 0; i != m_messagesToInjectedBundlePostedToEmptyContext.size(); ++i) { - pair<String, RefPtr<APIObject> >& message = m_messagesToInjectedBundlePostedToEmptyContext[i]; - - OwnPtr<CoreIPC::ArgumentEncoder> messageData = CoreIPC::ArgumentEncoder::create(); - - messageData->encode(message.first); - messageData->encode(WebContextUserMessageEncoder(message.second.get())); - process->send(Messages::WebProcess::PostInjectedBundleMessage(CoreIPC::DataReference(messageData->buffer(), messageData->bufferSize())), 0); - } - m_messagesToInjectedBundlePostedToEmptyContext.clear(); - } else - ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty()); - - return process.get(); -} - -void WebContext::warmInitialProcess() -{ - if (m_haveInitialEmptyProcess) { - ASSERT(!m_processes.isEmpty()); - return; - } - - if (m_processes.size() >= m_webProcessCountLimit) - return; - - createNewWebProcess(); - m_haveInitialEmptyProcess = true; -} - -void WebContext::enableProcessTermination() -{ - m_processTerminationEnabled = true; - Vector<RefPtr<WebProcessProxy> > processes = m_processes; - for (size_t i = 0; i < processes.size(); ++i) { - if (shouldTerminate(processes[i].get())) - processes[i]->terminate(); - } -} - -bool WebContext::shouldTerminate(WebProcessProxy* process) -{ - ASSERT(m_processes.contains(process)); - - if (!m_processTerminationEnabled) - return false; - - WebContextSupplementMap::const_iterator it = m_supplements.begin(); - WebContextSupplementMap::const_iterator end = m_supplements.end(); - for (; it != end; ++it) { - if (!it->value->shouldTerminate(process)) - return false; - } - -#if ENABLE(NETSCAPE_PLUGIN_API) - if (!m_pluginSiteDataManager->shouldTerminate(process)) - return false; -#endif - - return true; -} - -void WebContext::processWillOpenConnection(WebProcessProxy* process) -{ - m_storageManager->processWillOpenConnection(process); -} - -void WebContext::processWillCloseConnection(WebProcessProxy* process) -{ - m_storageManager->processWillCloseConnection(process); -} - -void WebContext::processDidFinishLaunching(WebProcessProxy* process) -{ - ASSERT(m_processes.contains(process)); - - m_visitedLinkProvider.processDidFinishLaunching(process); - - // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching - // so check if it needs to be started here - if (m_memorySamplerEnabled) { - SandboxExtension::Handle sampleLogSandboxHandle; - double now = WTF::currentTime(); - String sampleLogFilePath = String::format("WebProcess%llupid%d", static_cast<unsigned long long>(now), process->processIdentifier()); - sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::ReadWrite, sampleLogSandboxHandle); - - process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0); - } - - m_connectionClient.didCreateConnection(this, process->webConnection()); -} - -void WebContext::disconnectProcess(WebProcessProxy* process) -{ - ASSERT(m_processes.contains(process)); - - m_visitedLinkProvider.processDidClose(process); - - if (m_haveInitialEmptyProcess && process == m_processes.last()) - m_haveInitialEmptyProcess = false; - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> Some of the invalidation calls below are still necessary in multi-process mode, but they should only affect data structures pertaining to the process being disconnected. - // Clearing everything causes assertion failures, so it's less trouble to skip that for now. - if (m_processModel != ProcessModelSharedSecondaryProcess) { - RefPtr<WebProcessProxy> protect(process); - if (m_processWithPageCache == process) - m_processWithPageCache = 0; - m_processes.remove(m_processes.find(process)); - return; - } - - WebContextSupplementMap::const_iterator it = m_supplements.begin(); - WebContextSupplementMap::const_iterator end = m_supplements.end(); - for (; it != end; ++it) - it->value->processDidClose(process); - - // When out of process plug-ins are enabled, we don't want to invalidate the plug-in site data - // manager just because the web process crashes since it's not involved. -#if ENABLE(NETSCAPE_PLUGIN_API) && !ENABLE(PLUGIN_PROCESS) - m_pluginSiteDataManager->invalidate(); -#endif - - // The vector may have the last reference to process proxy, which in turn may have the last reference to the context. - // Since vector elements are destroyed in place, we would recurse into WebProcessProxy destructor - // if it were invoked from Vector::remove(). RefPtr delays destruction until it's safe. - RefPtr<WebProcessProxy> protect(process); - if (m_processWithPageCache == process) - m_processWithPageCache = 0; - m_processes.remove(m_processes.find(process)); -} - -WebProcessProxy* WebContext::createNewWebProcessRespectingProcessCountLimit() -{ - if (m_processes.size() < m_webProcessCountLimit) - return createNewWebProcess(); - - // Choose a process with fewest pages, to achieve flat distribution. - WebProcessProxy* result = 0; - unsigned fewestPagesSeen = UINT_MAX; - for (unsigned i = 0; i < m_processes.size(); ++i) { - if (fewestPagesSeen > m_processes[i]->pages().size()) { - result = m_processes[i].get(); - fewestPagesSeen = m_processes[i]->pages().size(); - } - } - return result; -} - -PassRefPtr<WebPageProxy> WebContext::createWebPage(PageClient* pageClient, WebPageGroup* pageGroup, WebPageProxy* relatedPage) -{ - RefPtr<WebProcessProxy> process; - if (m_processModel == ProcessModelSharedSecondaryProcess) { - process = ensureSharedWebProcess(); - } else { - if (m_haveInitialEmptyProcess) { - process = m_processes.last(); - m_haveInitialEmptyProcess = false; - } else if (relatedPage) { - // Sharing processes, e.g. when creating the page via window.open(). - process = relatedPage->process(); - } else - process = createNewWebProcessRespectingProcessCountLimit(); - } - - if (!pageGroup) - pageGroup = m_defaultPageGroup.get(); - - return process->createWebPage(pageClient, this, pageGroup); -} - -DownloadProxy* WebContext::download(WebPageProxy* initiatingPage, const ResourceRequest& request) -{ - DownloadProxy* downloadProxy = createDownloadProxy(); - uint64_t initiatingPageID = initiatingPage ? initiatingPage->pageID() : 0; - -#if ENABLE(NETWORK_PROCESS) - if (usesNetworkProcess() && networkProcess()) { - // FIXME (NetworkProcess): Replicate whatever FrameLoader::setOriginalURLForDownloadRequest does with the request here. - networkProcess()->connection()->send(Messages::NetworkProcess::DownloadRequest(downloadProxy->downloadID(), request), 0); - return downloadProxy; - } -#endif - -#if PLATFORM(QT) - ASSERT(initiatingPage); // Our design does not suppport downloads without a WebPage. - initiatingPage->handleDownloadRequest(downloadProxy); -#endif - - m_processes[0]->send(Messages::WebProcess::DownloadRequest(downloadProxy->downloadID(), initiatingPageID, request), 0); - return downloadProxy; -} - -void WebContext::postMessageToInjectedBundle(const String& messageName, APIObject* messageBody) -{ - if (m_processes.isEmpty()) { - if (m_processModel == ProcessModelSharedSecondaryProcess) - m_messagesToInjectedBundlePostedToEmptyContext.append(std::make_pair(messageName, messageBody)); - return; - } - - // FIXME: Return early if the message body contains any references to WKPageRefs/WKFrameRefs etc. since they're local to a process. - - OwnPtr<CoreIPC::ArgumentEncoder> messageData = CoreIPC::ArgumentEncoder::create(); - messageData->encode(messageName); - messageData->encode(WebContextUserMessageEncoder(messageBody)); - - for (size_t i = 0; i < m_processes.size(); ++i) { - m_processes[i]->send(Messages::WebProcess::PostInjectedBundleMessage(CoreIPC::DataReference(messageData->buffer(), messageData->bufferSize())), 0); - } -} - -// InjectedBundle client - -void WebContext::didReceiveMessageFromInjectedBundle(const String& messageName, APIObject* messageBody) -{ - m_injectedBundleClient.didReceiveMessageFromInjectedBundle(this, messageName, messageBody); -} - -void WebContext::didReceiveSynchronousMessageFromInjectedBundle(const String& messageName, APIObject* messageBody, RefPtr<APIObject>& returnData) -{ - m_injectedBundleClient.didReceiveSynchronousMessageFromInjectedBundle(this, messageName, messageBody, returnData); -} - -void WebContext::populateVisitedLinks() -{ - m_historyClient.populateVisitedLinks(this); -} - -WebContext::Statistics& WebContext::statistics() -{ - static Statistics statistics = Statistics(); - - return statistics; -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -void WebContext::setAdditionalPluginsDirectory(const String& directory) -{ - Vector<String> directories; - directories.append(directory); - - m_pluginInfoStore.setAdditionalPluginsDirectories(directories); -} -#endif // ENABLE(NETSCAPE_PLUGIN_API) - -void WebContext::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText) -{ - m_alwaysUsesComplexTextCodePath = alwaysUseComplexText; - sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText)); -} - -void WebContext::setShouldUseFontSmoothing(bool useFontSmoothing) -{ - m_shouldUseFontSmoothing = useFontSmoothing; - sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing)); -} - -void WebContext::registerURLSchemeAsEmptyDocument(const String& urlScheme) -{ - m_schemesToRegisterAsEmptyDocument.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme)); -} - -void WebContext::registerURLSchemeAsSecure(const String& urlScheme) -{ - m_schemesToRegisterAsSecure.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme)); -} - -void WebContext::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme) -{ - m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme)); -} - -void WebContext::registerURLSchemeAsLocal(const String& urlScheme) -{ - m_schemesToRegisterAsLocal.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme)); -} - -void WebContext::registerURLSchemeAsNoAccess(const String& urlScheme) -{ - m_schemesToRegisterAsNoAccess.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme)); -} - -void WebContext::registerURLSchemeAsDisplayIsolated(const String& urlScheme) -{ - m_schemesToRegisterAsDisplayIsolated.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme)); -} - -void WebContext::registerURLSchemeAsCORSEnabled(const String& urlScheme) -{ - m_schemesToRegisterAsCORSEnabled.add(urlScheme); - sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme)); -} - -void WebContext::setCacheModel(CacheModel cacheModel) -{ - m_cacheModel = cacheModel; - sendToAllProcesses(Messages::WebProcess::SetCacheModel(static_cast<uint32_t>(m_cacheModel))); - - // FIXME: Inform the Network Process if in use. -} - -void WebContext::setDefaultRequestTimeoutInterval(double timeoutInterval) -{ - sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval)); -} - -void WebContext::addVisitedLink(const String& visitedURL) -{ - if (visitedURL.isEmpty()) - return; - - LinkHash linkHash = visitedLinkHash(visitedURL); - addVisitedLinkHash(linkHash); -} - -void WebContext::addVisitedLinkHash(LinkHash linkHash) -{ - m_visitedLinkProvider.addVisitedLink(linkHash); -} - -DownloadProxy* WebContext::createDownloadProxy() -{ -#if ENABLE(NETWORK_PROCESS) - if (usesNetworkProcess()) - return m_networkProcess->createDownloadProxy(); -#endif - - return ensureSharedWebProcess()->createDownloadProxy(); -} - -void WebContext::addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver* messageReceiver) -{ - m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver); -} - -void WebContext::addMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID, CoreIPC::MessageReceiver* messageReceiver) -{ - m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver); -} - -void WebContext::removeMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID) -{ - m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID); -} - -bool WebContext::dispatchMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) -{ - return m_messageReceiverMap.dispatchMessage(connection, decoder); -} - -bool WebContext::dispatchSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) -{ - return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder); -} - -void WebContext::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) -{ - if (decoder.messageReceiverName() == Messages::WebContext::messageReceiverName()) { - didReceiveWebContextMessage(connection, decoder); - return; - } - - if (decoder.messageReceiverName() == WebContextLegacyMessages::messageReceiverName() - && decoder.messageName() == WebContextLegacyMessages::postMessageMessageName()) { - String messageName; - RefPtr<APIObject> messageBody; - WebContextUserMessageDecoder messageBodyDecoder(messageBody, WebProcessProxy::fromConnection(connection)); - if (!decoder.decode(messageName)) - return; - if (!decoder.decode(messageBodyDecoder)) - return; - - didReceiveMessageFromInjectedBundle(messageName, messageBody.get()); - return; - } - - ASSERT_NOT_REACHED(); -} - -void WebContext::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) -{ - if (decoder.messageReceiverName() == Messages::WebContext::messageReceiverName()) { - didReceiveSyncWebContextMessage(connection, decoder, replyEncoder); - return; - } - - if (decoder.messageReceiverName() == WebContextLegacyMessages::messageReceiverName() - && decoder.messageName() == WebContextLegacyMessages::postSynchronousMessageMessageName()) { - // FIXME: We should probably encode something in the case that the arguments do not decode correctly. - - String messageName; - RefPtr<APIObject> messageBody; - WebContextUserMessageDecoder messageBodyDecoder(messageBody, WebProcessProxy::fromConnection(connection)); - if (!decoder.decode(messageName)) - return; - if (!decoder.decode(messageBodyDecoder)) - return; - - RefPtr<APIObject> returnData; - didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody.get(), returnData); - replyEncoder->encode(WebContextUserMessageEncoder(returnData.get())); - return; - } - - ASSERT_NOT_REACHED(); -} - -void WebContext::setEnhancedAccessibility(bool flag) -{ - sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag)); -} - -void WebContext::startMemorySampler(const double interval) -{ - // For new WebProcesses we will also want to start the Memory Sampler - m_memorySamplerEnabled = true; - m_memorySamplerInterval = interval; - - // For UIProcess -#if ENABLE(MEMORY_SAMPLER) - WebMemorySampler::shared()->start(interval); -#endif - - // For WebProcess - SandboxExtension::Handle sampleLogSandboxHandle; - double now = WTF::currentTime(); - String sampleLogFilePath = String::format("WebProcess%llu", static_cast<unsigned long long>(now)); - sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::ReadWrite, sampleLogSandboxHandle); - - sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval)); -} - -void WebContext::stopMemorySampler() -{ - // For WebProcess - m_memorySamplerEnabled = false; - - // For UIProcess -#if ENABLE(MEMORY_SAMPLER) - WebMemorySampler::shared()->stop(); -#endif - - sendToAllProcesses(Messages::WebProcess::StopMemorySampler()); -} - -String WebContext::applicationCacheDirectory() const -{ - if (!m_overrideApplicationCacheDirectory.isEmpty()) - return m_overrideApplicationCacheDirectory; - - return platformDefaultApplicationCacheDirectory(); -} - -String WebContext::databaseDirectory() const -{ - if (!m_overrideDatabaseDirectory.isEmpty()) - return m_overrideDatabaseDirectory; - - return platformDefaultDatabaseDirectory(); -} - -void WebContext::setIconDatabasePath(const String& path) -{ - m_overrideIconDatabasePath = path; - m_iconDatabase->setDatabasePath(path); -} - -String WebContext::iconDatabasePath() const -{ - if (!m_overrideIconDatabasePath.isEmpty()) - return m_overrideIconDatabasePath; - - return platformDefaultIconDatabasePath(); -} - -void WebContext::setLocalStorageDirectory(const String& directory) -{ - m_overrideLocalStorageDirectory = directory; - m_storageManager->setLocalStorageDirectory(localStorageDirectory()); -} - -String WebContext::localStorageDirectory() const -{ - if (!m_overrideLocalStorageDirectory.isEmpty()) - return m_overrideLocalStorageDirectory; - - return platformDefaultLocalStorageDirectory(); -} - -String WebContext::diskCacheDirectory() const -{ - if (!m_overrideDiskCacheDirectory.isEmpty()) - return m_overrideDiskCacheDirectory; - - return platformDefaultDiskCacheDirectory(); -} - -String WebContext::cookieStorageDirectory() const -{ - if (!m_overrideCookieStorageDirectory.isEmpty()) - return m_overrideCookieStorageDirectory; - - return platformDefaultCookieStorageDirectory(); -} - -void WebContext::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host) -{ -#if ENABLE(NETWORK_PROCESS) - if (m_usesNetworkProcess && m_networkProcess) { - m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->platformCertificateInfo(), host), 0); - return; - } -#else - UNUSED_PARAM(certificate); - UNUSED_PARAM(host); -#endif - // FIXME: It's unclear whether we want this SPI to be exposed and used for clients that don't use the NetworkProcess. - ASSERT_NOT_REACHED(); -} - -void WebContext::setHTTPPipeliningEnabled(bool enabled) -{ -#if PLATFORM(MAC) - ResourceRequest::setHTTPPipeliningEnabled(enabled); -#else - UNUSED_PARAM(enabled); -#endif -} - -bool WebContext::httpPipeliningEnabled() const -{ -#if PLATFORM(MAC) - return ResourceRequest::httpPipeliningEnabled(); -#else - return false; -#endif -} - -void WebContext::getStatistics(uint32_t statisticsMask, PassRefPtr<DictionaryCallback> callback) -{ - if (!statisticsMask) { - callback->invalidate(); - return; - } - - RefPtr<StatisticsRequest> request = StatisticsRequest::create(callback); - - if (statisticsMask & StatisticsRequestTypeWebContent) - requestWebContentStatistics(request.get()); - - if (statisticsMask & StatisticsRequestTypeNetworking) - requestNetworkingStatistics(request.get()); -} - -void WebContext::requestWebContentStatistics(StatisticsRequest* request) -{ - if (m_processModel == ProcessModelSharedSecondaryProcess) { - if (m_processes.isEmpty()) - return; - - uint64_t requestID = request->addOutstandingRequest(); - m_statisticsRequests.set(requestID, request); - m_processes[0]->send(Messages::WebProcess::GetWebCoreStatistics(requestID), 0); - - } else { - // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work. - } -} - -void WebContext::requestNetworkingStatistics(StatisticsRequest* request) -{ - bool networkProcessUnavailable; -#if ENABLE(NETWORK_PROCESS) - networkProcessUnavailable = !m_usesNetworkProcess || !m_networkProcess; -#else - networkProcessUnavailable = true; -#endif - - if (networkProcessUnavailable) { - LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable"); - return; - } - -#if ENABLE(NETWORK_PROCESS) - uint64_t requestID = request->addOutstandingRequest(); - m_statisticsRequests.set(requestID, request); - m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0); -#else - UNUSED_PARAM(request); -#endif -} - -#if !PLATFORM(MAC) -void WebContext::dummy(bool&) -{ -} -#endif - -void WebContext::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID) -{ - RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID); - if (!request) { - LOG_ERROR("Cannot report networking statistics."); - return; - } - - request->completedRequest(requestID, statisticsData); -} - -void WebContext::garbageCollectJavaScriptObjects() -{ - sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects()); -} - -void WebContext::setJavaScriptGarbageCollectorTimerEnabled(bool flag) -{ - sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag)); -} - -void WebContext::addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash) -{ - m_plugInAutoStartProvider.addAutoStartOriginHash(pageOrigin, plugInOriginHash); -} - -void WebContext::plugInDidReceiveUserInteraction(unsigned plugInOriginHash) -{ - m_plugInAutoStartProvider.didReceiveUserInteraction(plugInOriginHash); -} - -PassRefPtr<ImmutableDictionary> WebContext::plugInAutoStartOriginHashes() const -{ - return m_plugInAutoStartProvider.autoStartOriginsTableCopy(); -} - -void WebContext::setPlugInAutoStartOriginHashes(ImmutableDictionary& dictionary) -{ - m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary); -} - -void WebContext::setPlugInAutoStartOrigins(ImmutableArray& array) -{ - m_plugInAutoStartProvider.setAutoStartOriginsArray(array); -} - -#if ENABLE(CUSTOM_PROTOCOLS) -void WebContext::registerSchemeForCustomProtocol(const String& scheme) -{ - sendToNetworkingProcess(Messages::CustomProtocolManager::RegisterScheme(scheme)); -} - -void WebContext::unregisterSchemeForCustomProtocol(const String& scheme) -{ - sendToNetworkingProcess(Messages::CustomProtocolManager::UnregisterScheme(scheme)); -} -#endif - -#if ENABLE(NETSCAPE_PLUGIN_API) -void WebContext::pluginInfoStoreDidLoadPlugins(PluginInfoStore* store) -{ -#ifdef NDEBUG - UNUSED_PARAM(store); -#endif - ASSERT(store == &m_pluginInfoStore); - - Vector<RefPtr<APIObject> > pluginArray; - - Vector<PluginModuleInfo> plugins = m_pluginInfoStore.plugins(); - for (size_t i = 0; i < plugins.size(); ++i) { - PluginModuleInfo& plugin = plugins[i]; - ImmutableDictionary::MapType map; - map.set(ASCIILiteral("path"), WebString::create(plugin.path)); - map.set(ASCIILiteral("name"), WebString::create(plugin.info.name)); - map.set(ASCIILiteral("file"), WebString::create(plugin.info.file)); - map.set(ASCIILiteral("desc"), WebString::create(plugin.info.desc)); - Vector<RefPtr<APIObject> > mimeArray; - for (size_t j = 0; j < plugin.info.mimes.size(); ++j) - mimeArray.append(WebString::create(plugin.info.mimes[j].type)); - map.set(ASCIILiteral("mimes"), ImmutableArray::adopt(mimeArray)); -#if PLATFORM(MAC) - map.set(ASCIILiteral("bundleId"), WebString::create(plugin.bundleIdentifier)); - map.set(ASCIILiteral("version"), WebString::create(plugin.versionString)); -#endif - - pluginArray.append(ImmutableDictionary::adopt(map)); - } - - m_client.plugInInformationBecameAvailable(this, ImmutableArray::adopt(pluginArray).get()); -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContext.h b/Source/WebKit2/UIProcess/WebContext.h deleted file mode 100644 index 84a385653..000000000 --- a/Source/WebKit2/UIProcess/WebContext.h +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * 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 WebContext_h -#define WebContext_h - -#include "APIObject.h" -#include "DownloadProxyMap.h" -#include "GenericCallback.h" -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "MessageReceiver.h" -#include "MessageReceiverMap.h" -#include "PlugInAutoStartProvider.h" -#include "PluginInfoStore.h" -#include "ProcessModel.h" -#include "StatisticsRequest.h" -#include "StorageManager.h" -#include "VisitedLinkProvider.h" -#include "WebContextClient.h" -#include "WebContextConnectionClient.h" -#include "WebContextInjectedBundleClient.h" -#include "WebDownloadClient.h" -#include "WebHistoryClient.h" -#include "WebProcessProxy.h" -#include <WebCore/LinkHash.h> -#include <wtf/Forward.h> -#include <wtf/HashMap.h> -#include <wtf/HashSet.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/text/StringHash.h> -#include <wtf/text/WTFString.h> - -#if ENABLE(NETWORK_PROCESS) -#include "NetworkProcessProxy.h" -#endif - -#if PLATFORM(MAC) -OBJC_CLASS NSObject; -OBJC_CLASS NSString; -#endif - -namespace WebKit { - -class DownloadProxy; -class WebContextSupplement; -class WebIconDatabase; -class WebPageGroup; -class WebPageProxy; -struct StatisticsData; -struct WebProcessCreationParameters; - -typedef GenericCallback<WKDictionaryRef> DictionaryCallback; - -#if ENABLE(NETWORK_INFO) -class WebNetworkInfoManagerProxy; -#endif -#if ENABLE(NETWORK_PROCESS) -struct NetworkProcessCreationParameters; -#endif - -#if PLATFORM(MAC) -extern NSString *SchemeForCustomProtocolRegisteredNotificationName; -extern NSString *SchemeForCustomProtocolUnregisteredNotificationName; -#endif - -class WebContext : public TypedAPIObject<APIObject::TypeContext>, private CoreIPC::MessageReceiver -#if ENABLE(NETSCAPE_PLUGIN_API) - , private PluginInfoStoreClient -#endif - { -public: - static PassRefPtr<WebContext> create(const String& injectedBundlePath); - virtual ~WebContext(); - - static const Vector<WebContext*>& allContexts(); - - template <typename T> - T* supplement() - { - return static_cast<T*>(m_supplements.get(T::supplementName())); - } - - template <typename T> - void addSupplement() - { - m_supplements.add(T::supplementName(), T::create(this)); - } - - void addMessageReceiver(CoreIPC::StringReference messageReceiverName, CoreIPC::MessageReceiver*); - void addMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID, CoreIPC::MessageReceiver*); - void removeMessageReceiver(CoreIPC::StringReference messageReceiverName, uint64_t destinationID); - - bool dispatchMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - bool dispatchSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - - void initializeClient(const WKContextClient*); - void initializeInjectedBundleClient(const WKContextInjectedBundleClient*); - void initializeConnectionClient(const WKContextConnectionClient*); - void initializeHistoryClient(const WKContextHistoryClient*); - void initializeDownloadClient(const WKContextDownloadClient*); - - void setProcessModel(ProcessModel); // Can only be called when there are no processes running. - ProcessModel processModel() const { return m_processModel; } - - void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running. - unsigned maximumNumberOfProcesses() const { return m_webProcessCountLimit; } - - // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null. - CoreIPC::Connection* networkingProcessConnection(); - - template<typename U> void sendToAllProcesses(const U& message); - template<typename U> void sendToAllProcessesRelaunchingThemIfNecessary(const U& message); - template<typename U> void sendToOneProcess(const U& message); - - // Sends the message to WebProcess or NetworkProcess as approporiate for current process model. - template<typename U> void sendToNetworkingProcess(const U& message); - template<typename U> void sendToNetworkingProcessRelaunchingIfNecessary(const U& message); - - void processWillOpenConnection(WebProcessProxy*); - void processWillCloseConnection(WebProcessProxy*); - void processDidFinishLaunching(WebProcessProxy*); - - // Disconnect the process from the context. - void disconnectProcess(WebProcessProxy*); - - StorageManager& storageManager() const { return *m_storageManager; } - - PassRefPtr<WebPageProxy> createWebPage(PageClient*, WebPageGroup*, WebPageProxy* relatedPage = 0); - - const String& injectedBundlePath() const { return m_injectedBundlePath; } - - DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&); - - void setInjectedBundleInitializationUserData(PassRefPtr<APIObject> userData) { m_injectedBundleInitializationUserData = userData; } - - void postMessageToInjectedBundle(const String&, APIObject*); - - // InjectedBundle client - void didReceiveMessageFromInjectedBundle(const String&, APIObject*); - void didReceiveSynchronousMessageFromInjectedBundle(const String&, APIObject*, RefPtr<APIObject>& returnData); - - void populateVisitedLinks(); - -#if ENABLE(NETSCAPE_PLUGIN_API) - void setAdditionalPluginsDirectory(const String&); - - PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; } -#endif - - void setAlwaysUsesComplexTextCodePath(bool); - void setShouldUseFontSmoothing(bool); - - void registerURLSchemeAsEmptyDocument(const String&); - void registerURLSchemeAsSecure(const String&); - void setDomainRelaxationForbiddenForURLScheme(const String&); - void registerURLSchemeAsLocal(const String&); - void registerURLSchemeAsNoAccess(const String&); - void registerURLSchemeAsDisplayIsolated(const String&); - void registerURLSchemeAsCORSEnabled(const String&); - - void addVisitedLink(const String&); - void addVisitedLinkHash(WebCore::LinkHash); - - // MessageReceiver. - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; - - void setCacheModel(CacheModel); - CacheModel cacheModel() const { return m_cacheModel; } - - void setDefaultRequestTimeoutInterval(double); - - void startMemorySampler(const double interval); - void stopMemorySampler(); - -#if USE(SOUP) - void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; } -#endif - void setEnhancedAccessibility(bool); - - // Downloads. - DownloadProxy* createDownloadProxy(); - WebDownloadClient& downloadClient() { return m_downloadClient; } - - WebHistoryClient& historyClient() { return m_historyClient; } - WebContextClient& client() { return m_client; } - - WebIconDatabase* iconDatabase() const { return m_iconDatabase.get(); } -#if ENABLE(NETSCAPE_PLUGIN_API) - WebPluginSiteDataManager* pluginSiteDataManager() const { return m_pluginSiteDataManager.get(); } -#endif - - struct Statistics { - unsigned wkViewCount; - unsigned wkPageCount; - unsigned wkFrameCount; - }; - static Statistics& statistics(); - - void setApplicationCacheDirectory(const String& dir) { m_overrideApplicationCacheDirectory = dir; } - void setDatabaseDirectory(const String& dir) { m_overrideDatabaseDirectory = dir; } - void setIconDatabasePath(const String&); - String iconDatabasePath() const; - void setLocalStorageDirectory(const String&); - void setDiskCacheDirectory(const String& dir) { m_overrideDiskCacheDirectory = dir; } - void setCookieStorageDirectory(const String& dir) { m_overrideCookieStorageDirectory = dir; } - - void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host); - - WebProcessProxy* ensureSharedWebProcess(); - WebProcessProxy* createNewWebProcessRespectingProcessCountLimit(); // Will return an existing one if limit is met. - void warmInitialProcess(); - - bool shouldTerminate(WebProcessProxy*); - - void disableProcessTermination() { m_processTerminationEnabled = false; } - void enableProcessTermination(); - - // Defaults to false. - void setHTTPPipeliningEnabled(bool); - bool httpPipeliningEnabled() const; - - void getStatistics(uint32_t statisticsMask, PassRefPtr<DictionaryCallback>); - - void garbageCollectJavaScriptObjects(); - void setJavaScriptGarbageCollectorTimerEnabled(bool flag); - -#if PLATFORM(MAC) - static bool omitPDFSupport(); -#endif - - void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled); - - void textCheckerStateChanged(); - - PassRefPtr<ImmutableDictionary> plugInAutoStartOriginHashes() const; - void setPlugInAutoStartOriginHashes(ImmutableDictionary&); - void setPlugInAutoStartOrigins(ImmutableArray&); - - // Network Process Management - - void setUsesNetworkProcess(bool); - bool usesNetworkProcess() const; - -#if ENABLE(NETWORK_PROCESS) - void ensureNetworkProcess(); - NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); } - void networkProcessCrashed(NetworkProcessProxy*); - - void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); -#endif - - -#if PLATFORM(MAC) - void setProcessSuppressionEnabled(bool); - bool processSuppressionEnabled() const { return m_processSuppressionEnabled; } - bool canEnableProcessSuppressionForNetworkProcess() const; - bool canEnableProcessSuppressionForWebProcess(const WebProcessProxy*) const; - static bool canEnableProcessSuppressionForGlobalChildProcesses(); - void updateProcessSuppressionStateOfChildProcesses(); -#endif - - static void willStartUsingPrivateBrowsing(); - static void willStopUsingPrivateBrowsing(); - -#if USE(SOUP) - void setIgnoreTLSErrors(bool); - bool ignoreTLSErrors() const { return m_ignoreTLSErrors; } -#endif - - static void setInvalidMessageCallback(void (*)(WKStringRef)); - static void didReceiveInvalidMessage(const CoreIPC::StringReference& messageReceiverName, const CoreIPC::StringReference& messageName); - - void processDidCachePage(WebProcessProxy*); - - bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const; - void resetHSTSHosts(); - -private: - WebContext(ProcessModel, const String& injectedBundlePath); - void platformInitialize(); - - void platformInitializeWebProcess(WebProcessCreationParameters&); - void platformInvalidateContext(); - - WebProcessProxy* createNewWebProcess(); - - void requestWebContentStatistics(StatisticsRequest*); - void requestNetworkingStatistics(StatisticsRequest*); - -#if ENABLE(NETWORK_PROCESS) - void platformInitializeNetworkProcess(NetworkProcessCreationParameters&); -#endif - -#if PLATFORM(MAC) - void getPasteboardTypes(const String& pasteboardName, Vector<String>& pasteboardTypes); - void getPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, Vector<String>& pathnames); - void getPasteboardStringForType(const String& pasteboardName, const String& pasteboardType, String&); - void getPasteboardBufferForType(const String& pasteboardName, const String& pasteboardType, SharedMemory::Handle&, uint64_t& size); - void pasteboardCopy(const String& fromPasteboard, const String& toPasteboard); - void getPasteboardChangeCount(const String& pasteboardName, uint64_t& changeCount); - void getPasteboardUniqueName(String& pasteboardName); - void getPasteboardColor(const String& pasteboardName, WebCore::Color&); - void getPasteboardURL(const String& pasteboardName, WTF::String&); - void addPasteboardTypes(const String& pasteboardName, const Vector<String>& pasteboardTypes); - void setPasteboardTypes(const String& pasteboardName, const Vector<String>& pasteboardTypes); - void setPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, const Vector<String>& pathnames); - void setPasteboardStringForType(const String& pasteboardName, const String& pasteboardType, const String&); - void setPasteboardBufferForType(const String& pasteboardName, const String& pasteboardType, const SharedMemory::Handle&, uint64_t size); -#endif - -#if !PLATFORM(MAC) - // FIXME: This a dummy message, to avoid breaking the build for platforms that don't require - // any synchronous messages, and should be removed when <rdar://problem/8775115> is fixed. - void dummy(bool&); -#endif - - void didGetStatistics(const StatisticsData&, uint64_t callbackID); - - // Implemented in generated WebContextMessageReceiver.cpp - void didReceiveWebContextMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - void didReceiveSyncWebContextMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - - static void languageChanged(void* context); - void languageChanged(); - - String applicationCacheDirectory() const; - String platformDefaultApplicationCacheDirectory() const; - - String databaseDirectory() const; - String platformDefaultDatabaseDirectory() const; - - String platformDefaultIconDatabasePath() const; - - String localStorageDirectory() const; - String platformDefaultLocalStorageDirectory() const; - - String diskCacheDirectory() const; - String platformDefaultDiskCacheDirectory() const; - - String cookieStorageDirectory() const; - String platformDefaultCookieStorageDirectory() const; - -#if PLATFORM(MAC) - void processSuppressionEnabledChanged(); - void registerNotificationObservers(); - void unregisterNotificationObservers(); -#endif - -#if ENABLE(CUSTOM_PROTOCOLS) - void registerSchemeForCustomProtocol(const String&); - void unregisterSchemeForCustomProtocol(const String&); -#endif - - void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash); - void plugInDidReceiveUserInteraction(unsigned plugInOriginHash); - -#if ENABLE(NETSCAPE_PLUGIN_API) - // PluginInfoStoreClient: - virtual void pluginInfoStoreDidLoadPlugins(PluginInfoStore*) OVERRIDE; -#endif - - CoreIPC::MessageReceiverMap m_messageReceiverMap; - - ProcessModel m_processModel; - unsigned m_webProcessCountLimit; // The limit has no effect when process model is ProcessModelSharedSecondaryProcess. - - Vector<RefPtr<WebProcessProxy> > m_processes; - bool m_haveInitialEmptyProcess; - - WebProcessProxy* m_processWithPageCache; - - RefPtr<WebPageGroup> m_defaultPageGroup; - - RefPtr<APIObject> m_injectedBundleInitializationUserData; - String m_injectedBundlePath; - WebContextInjectedBundleClient m_injectedBundleClient; - - WebContextClient m_client; - WebContextConnectionClient m_connectionClient; - WebDownloadClient m_downloadClient; - WebHistoryClient m_historyClient; - -#if ENABLE(NETSCAPE_PLUGIN_API) - PluginInfoStore m_pluginInfoStore; -#endif - VisitedLinkProvider m_visitedLinkProvider; - PlugInAutoStartProvider m_plugInAutoStartProvider; - - HashSet<String> m_schemesToRegisterAsEmptyDocument; - HashSet<String> m_schemesToRegisterAsSecure; - HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor; - HashSet<String> m_schemesToRegisterAsLocal; - HashSet<String> m_schemesToRegisterAsNoAccess; - HashSet<String> m_schemesToRegisterAsDisplayIsolated; - HashSet<String> m_schemesToRegisterAsCORSEnabled; - - bool m_alwaysUsesComplexTextCodePath; - bool m_shouldUseFontSmoothing; - - // Messages that were posted before any pages were created. - // The client should use initialization messages instead, so that a restarted process would get the same state. - Vector<pair<String, RefPtr<APIObject> > > m_messagesToInjectedBundlePostedToEmptyContext; - - CacheModel m_cacheModel; - - bool m_memorySamplerEnabled; - double m_memorySamplerInterval; - - RefPtr<WebIconDatabase> m_iconDatabase; -#if ENABLE(NETSCAPE_PLUGIN_API) - RefPtr<WebPluginSiteDataManager> m_pluginSiteDataManager; -#endif - - RefPtr<StorageManager> m_storageManager; - - typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*> > WebContextSupplementMap; - WebContextSupplementMap m_supplements; - -#if USE(SOUP) - HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy; -#endif - -#if PLATFORM(MAC) - RetainPtr<NSObject> m_enhancedAccessibilityObserver; - RetainPtr<NSObject> m_customSchemeRegisteredObserver; - RetainPtr<NSObject> m_customSchemeUnregisteredObserver; - - RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver; - RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver; - RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver; -#endif -#endif - - String m_overrideApplicationCacheDirectory; - String m_overrideDatabaseDirectory; - String m_overrideIconDatabasePath; - String m_overrideLocalStorageDirectory; - String m_overrideDiskCacheDirectory; - String m_overrideCookieStorageDirectory; - - bool m_processTerminationEnabled; - -#if ENABLE(NETWORK_PROCESS) - bool m_usesNetworkProcess; - RefPtr<NetworkProcessProxy> m_networkProcess; -#endif - - HashMap<uint64_t, RefPtr<DictionaryCallback> > m_dictionaryCallbacks; - HashMap<uint64_t, RefPtr<StatisticsRequest> > m_statisticsRequests; - -#if PLATFORM(MAC) - bool m_processSuppressionEnabled; -#endif - -#if USE(SOUP) - bool m_ignoreTLSErrors; -#endif -}; - -template<typename U> inline void WebContext::sendToNetworkingProcess(const U& message) -{ - switch (m_processModel) { - case ProcessModelSharedSecondaryProcess: - if (!m_processes.isEmpty() && m_processes[0]->canSendMessage()) - m_processes[0]->send(message, 0); - return; - case ProcessModelMultipleSecondaryProcesses: -#if ENABLE(NETWORK_PROCESS) - if (m_networkProcess->canSendMessage()) - m_networkProcess->send(message, 0); - return; -#else - break; -#endif - } - ASSERT_NOT_REACHED(); -} - -template<typename U> void WebContext::sendToNetworkingProcessRelaunchingIfNecessary(const U& message) -{ - switch (m_processModel) { - case ProcessModelSharedSecondaryProcess: - ensureSharedWebProcess(); - m_processes[0]->send(message, 0); - return; - case ProcessModelMultipleSecondaryProcesses: -#if ENABLE(NETWORK_PROCESS) - ensureNetworkProcess(); - m_networkProcess->send(message, 0); - return; -#else - break; -#endif - } - ASSERT_NOT_REACHED(); -} - -template<typename U> inline void WebContext::sendToAllProcesses(const U& message) -{ - size_t processCount = m_processes.size(); - for (size_t i = 0; i < processCount; ++i) { - WebProcessProxy* process = m_processes[i].get(); - if (process->canSendMessage()) - process->send(message, 0); - } -} - -template<typename U> void WebContext::sendToAllProcessesRelaunchingThemIfNecessary(const U& message) -{ -// FIXME (Multi-WebProcess): WebContext doesn't track processes that have exited, so it cannot relaunch these. Perhaps this functionality won't be needed in this mode. - if (m_processModel == ProcessModelSharedSecondaryProcess) - ensureSharedWebProcess(); - sendToAllProcesses(message); -} - -template<typename U> inline void WebContext::sendToOneProcess(const U& message) -{ - if (m_processModel == ProcessModelSharedSecondaryProcess) - ensureSharedWebProcess(); - - bool messageSent = false; - size_t processCount = m_processes.size(); - for (size_t i = 0; i < processCount; ++i) { - WebProcessProxy* process = m_processes[i].get(); - if (process->canSendMessage()) { - process->send(message, 0); - messageSent = true; - break; - } - } - - if (!messageSent && m_processModel == ProcessModelMultipleSecondaryProcesses) { - warmInitialProcess(); - RefPtr<WebProcessProxy> process = m_processes.last(); - if (process->canSendMessage()) - process->send(message, 0); - } -} - -} // namespace WebKit - -#endif // WebContext_h diff --git a/Source/WebKit2/UIProcess/WebContext.messages.in b/Source/WebKit2/UIProcess/WebContext.messages.in deleted file mode 100644 index f3df087f9..000000000 --- a/Source/WebKit2/UIProcess/WebContext.messages.in +++ /dev/null @@ -1,58 +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. - -messages -> WebContext LegacyReceiver { - - # Visited link provider messages. - AddVisitedLinkHash(uint64_t linkHash) - - DidGetStatistics(WebKit::StatisticsData statisticsData, uint64_t callbackID) - -#if PLATFORM(MAC) - # Pasteboard messages. - - GetPasteboardTypes(WTF::String pasteboardName) -> (Vector<WTF::String> types) - GetPasteboardPathnamesForType(WTF::String pasteboardName, WTF::String pasteboardType) -> (Vector<WTF::String> pathnames) - GetPasteboardStringForType(WTF::String pasteboardName, WTF::String pasteboardType) -> (WTF::String string) - GetPasteboardBufferForType(WTF::String pasteboardName, WTF::String pasteboardType) -> (WebKit::SharedMemory::Handle handle, uint64_t size) - PasteboardCopy(WTF::String fromPasteboard, WTF::String toPasteboard) - GetPasteboardChangeCount(WTF::String pasteboardName) -> (uint64_t changeCount) - GetPasteboardUniqueName() -> (WTF::String pasteboardName) - GetPasteboardColor(WTF::String pasteboardName) -> (WebCore::Color color) - GetPasteboardURL(WTF::String pasteboardName) -> (WTF::String urlString) - AddPasteboardTypes(WTF::String pasteboardName, Vector<WTF::String> pasteboardTypes) - SetPasteboardTypes(WTF::String pasteboardName, Vector<WTF::String> pasteboardTypes) - SetPasteboardPathnamesForType(WTF::String pasteboardName, WTF::String pasteboardType, Vector<WTF::String> pathnames) - SetPasteboardStringForType(WTF::String pasteboardName, WTF::String pasteboardType, WTF::String string) - SetPasteboardBufferForType(WTF::String pasteboardName, WTF::String pasteboardType, WebKit::SharedMemory::Handle handle, uint64_t size) -#endif - -#if !PLATFORM(MAC) - // FIXME: This a dummy message, to avoid breaking the build for platforms that don't require - // any synchronous messages, and should be removed when <rdar://problem/8775115> is fixed. - Dummy() -> (bool dummyReturn) -#endif - - # Plug-in messages. - void AddPlugInAutoStartOriginHash(WTF::String pageOrigin, uint32_t hash) - void PlugInDidReceiveUserInteraction(uint32_t hash) -} diff --git a/Source/WebKit2/UIProcess/WebContextClient.cpp b/Source/WebKit2/UIProcess/WebContextClient.cpp index df13e8778..46b36d196 100644 --- a/Source/WebKit2/UIProcess/WebContextClient.cpp +++ b/Source/WebKit2/UIProcess/WebContextClient.cpp @@ -26,27 +26,28 @@ #include "config.h" #include "WebContextClient.h" -#include "WebContext.h" +#include "APIArray.h" +#include "WebProcessPool.h" namespace WebKit { -void WebContextClient::plugInAutoStartOriginHashesChanged(WebContext* context) +void WebContextClient::plugInAutoStartOriginHashesChanged(WebProcessPool* processPool) { if (!m_client.plugInAutoStartOriginHashesChanged) return; - m_client.plugInAutoStartOriginHashesChanged(toAPI(context), m_client.clientInfo); + m_client.plugInAutoStartOriginHashesChanged(toAPI(processPool), m_client.base.clientInfo); } -void WebContextClient::networkProcessDidCrash(WebContext* context) +void WebContextClient::networkProcessDidCrash(WebProcessPool* processPool) { if (!m_client.networkProcessDidCrash) return; - m_client.networkProcessDidCrash(toAPI(context), m_client.clientInfo); + m_client.networkProcessDidCrash(toAPI(processPool), m_client.base.clientInfo); } -void WebContextClient::plugInInformationBecameAvailable(WebContext* context, ImmutableArray* plugInInfo) +void WebContextClient::plugInInformationBecameAvailable(WebProcessPool* processPool, API::Array* plugInInfo) { if (!m_client.plugInInformationBecameAvailable) return; @@ -54,7 +55,15 @@ void WebContextClient::plugInInformationBecameAvailable(WebContext* context, Imm // FIXME: The API contract expects us to hand a reference to the array here. This is wrong. plugInInfo->ref(); - m_client.plugInInformationBecameAvailable(toAPI(context), toAPI(plugInInfo), m_client.clientInfo); + m_client.plugInInformationBecameAvailable(toAPI(processPool), toAPI(plugInInfo), m_client.base.clientInfo); +} + +PassRefPtr<API::Data> WebContextClient::copyWebCryptoMasterKey(WebProcessPool* processPool) +{ + if (!m_client.copyWebCryptoMasterKey) + return nullptr; + + return adoptRef(toImpl(m_client.copyWebCryptoMasterKey(toAPI(processPool), m_client.base.clientInfo))); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextClient.h b/Source/WebKit2/UIProcess/WebContextClient.h index 698607c73..44d43cdfa 100644 --- a/Source/WebKit2/UIProcess/WebContextClient.h +++ b/Source/WebKit2/UIProcess/WebContextClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2012, 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,18 +27,28 @@ #define WebContextClient_h #include "APIClient.h" +#include "APIData.h" #include "WKContext.h" +namespace API { +class Array; + +template<> struct ClientTraits<WKContextClientBase> { + typedef std::tuple<WKContextClientV0, WKContextClientV1> Versions; +}; +} + + namespace WebKit { -class ImmutableArray; -class WebContext; +class WebProcessPool; -class WebContextClient : public APIClient<WKContextClient, kWKContextClientCurrentVersion> { +class WebContextClient : public API::Client<WKContextClientBase> { public: - void plugInAutoStartOriginHashesChanged(WebContext*); - void networkProcessDidCrash(WebContext*); - void plugInInformationBecameAvailable(WebContext*, ImmutableArray*); + void plugInAutoStartOriginHashesChanged(WebProcessPool*); + void networkProcessDidCrash(WebProcessPool*); + void plugInInformationBecameAvailable(WebProcessPool*, API::Array*); + PassRefPtr<API::Data> copyWebCryptoMasterKey(WebProcessPool*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextConnectionClient.cpp b/Source/WebKit2/UIProcess/WebContextConnectionClient.cpp index c5873ab52..3b47d0e13 100644 --- a/Source/WebKit2/UIProcess/WebContextConnectionClient.cpp +++ b/Source/WebKit2/UIProcess/WebContextConnectionClient.cpp @@ -27,15 +27,16 @@ #include "WebContextConnectionClient.h" #include "WKAPICast.h" +#include "WebProcessPool.h" namespace WebKit { -void WebContextConnectionClient::didCreateConnection(WebContext* context, WebConnection* connection) +void WebContextConnectionClient::didCreateConnection(WebProcessPool* processPool, WebConnection* connection) { if (!m_client.didCreateConnection) return; - m_client.didCreateConnection(toAPI(context), toAPI(connection), m_client.clientInfo); + m_client.didCreateConnection(toAPI(processPool), toAPI(connection), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextConnectionClient.h b/Source/WebKit2/UIProcess/WebContextConnectionClient.h index 148bd1bdb..23bddf0a6 100644 --- a/Source/WebKit2/UIProcess/WebContextConnectionClient.h +++ b/Source/WebKit2/UIProcess/WebContextConnectionClient.h @@ -29,14 +29,20 @@ #include "APIClient.h" #include "WKContext.h" +namespace API { +template<> struct ClientTraits<WKContextConnectionClientBase> { + typedef std::tuple<WKContextConnectionClientV0> Versions; +}; +} + namespace WebKit { class WebConnection; -class WebContext; +class WebProcessPool; -class WebContextConnectionClient : public APIClient<WKContextConnectionClient, kWKContextConnectionClientCurrentVersion> { +class WebContextConnectionClient : public API::Client<WKContextConnectionClientBase> { public: - void didCreateConnection(WebContext*, WebConnection*); + void didCreateConnection(WebProcessPool*, WebConnection*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.cpp b/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.cpp index 825388b09..c68a163ee 100644 --- a/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.cpp +++ b/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.cpp @@ -27,36 +27,37 @@ #include "WebContextInjectedBundleClient.h" #include "WKAPICast.h" +#include "WebProcessPool.h" #include <wtf/text/WTFString.h> using namespace WebCore; namespace WebKit { -void WebContextInjectedBundleClient::didReceiveMessageFromInjectedBundle(WebContext* context, const String& messageName, APIObject* messageBody) +void WebContextInjectedBundleClient::didReceiveMessageFromInjectedBundle(WebProcessPool* processPool, const String& messageName, API::Object* messageBody) { if (!m_client.didReceiveMessageFromInjectedBundle) return; - m_client.didReceiveMessageFromInjectedBundle(toAPI(context), toAPI(messageName.impl()), toAPI(messageBody), m_client.clientInfo); + m_client.didReceiveMessageFromInjectedBundle(toAPI(processPool), toAPI(messageName.impl()), toAPI(messageBody), m_client.base.clientInfo); } -void WebContextInjectedBundleClient::didReceiveSynchronousMessageFromInjectedBundle(WebContext* context, const String& messageName, APIObject* messageBody, RefPtr<APIObject>& returnData) +void WebContextInjectedBundleClient::didReceiveSynchronousMessageFromInjectedBundle(WebProcessPool* processPool, const String& messageName, API::Object* messageBody, RefPtr<API::Object>& returnData) { if (!m_client.didReceiveSynchronousMessageFromInjectedBundle) return; WKTypeRef returnDataRef = 0; - m_client.didReceiveSynchronousMessageFromInjectedBundle(toAPI(context), toAPI(messageName.impl()), toAPI(messageBody), &returnDataRef, m_client.clientInfo); + m_client.didReceiveSynchronousMessageFromInjectedBundle(toAPI(processPool), toAPI(messageName.impl()), toAPI(messageBody), &returnDataRef, m_client.base.clientInfo); returnData = adoptRef(toImpl(returnDataRef)); } -PassRefPtr<APIObject> WebContextInjectedBundleClient::getInjectedBundleInitializationUserData(WebContext* context) +PassRefPtr<API::Object> WebContextInjectedBundleClient::getInjectedBundleInitializationUserData(WebProcessPool* processPool) { if (!m_client.getInjectedBundleInitializationUserData) return 0; - return toImpl(m_client.getInjectedBundleInitializationUserData(toAPI(context), m_client.clientInfo)); + return adoptRef(toImpl(m_client.getInjectedBundleInitializationUserData(toAPI(processPool), m_client.base.clientInfo))); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.h b/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.h index d6b274ece..c934fe8b7 100644 --- a/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.h +++ b/Source/WebKit2/UIProcess/WebContextInjectedBundleClient.h @@ -30,16 +30,23 @@ #include "WKContext.h" #include <wtf/Forward.h> +namespace API { +class Object; + +template<> struct ClientTraits<WKContextInjectedBundleClientBase> { + typedef std::tuple<WKContextInjectedBundleClientV0, WKContextInjectedBundleClientV1> Versions; +}; +} + namespace WebKit { -class APIObject; -class WebContext; +class WebProcessPool; -class WebContextInjectedBundleClient : public APIClient<WKContextInjectedBundleClient, kWKContextInjectedBundleClientCurrentVersion> { +class WebContextInjectedBundleClient : public API::Client<WKContextInjectedBundleClientBase> { public: - void didReceiveMessageFromInjectedBundle(WebContext*, const String&, APIObject*); - void didReceiveSynchronousMessageFromInjectedBundle(WebContext*, const String&, APIObject*, RefPtr<APIObject>& returnData); - PassRefPtr<APIObject> getInjectedBundleInitializationUserData(WebContext*); + void didReceiveMessageFromInjectedBundle(WebProcessPool*, const String&, API::Object*); + void didReceiveSynchronousMessageFromInjectedBundle(WebProcessPool*, const String&, API::Object*, RefPtr<API::Object>& returnData); + PassRefPtr<API::Object> getInjectedBundleInitializationUserData(WebProcessPool*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextMenuProxy.cpp b/Source/WebKit2/UIProcess/WebContextMenuProxy.cpp index 4c4cb26c0..1764c4615 100644 --- a/Source/WebKit2/UIProcess/WebContextMenuProxy.cpp +++ b/Source/WebKit2/UIProcess/WebContextMenuProxy.cpp @@ -26,9 +26,13 @@ #include "config.h" #include "WebContextMenuProxy.h" +#if ENABLE(CONTEXT_MENUS) + namespace WebKit { -WebContextMenuProxy::WebContextMenuProxy() +WebContextMenuProxy::WebContextMenuProxy(const ContextMenuContextData& context, const UserData& userData) + : m_context(context) + , m_userData(userData) { } @@ -37,3 +41,5 @@ WebContextMenuProxy::~WebContextMenuProxy() } } // namespace WebKit + +#endif diff --git a/Source/WebKit2/UIProcess/WebContextMenuProxy.h b/Source/WebKit2/UIProcess/WebContextMenuProxy.h index 098552d3a..0a849addc 100644 --- a/Source/WebKit2/UIProcess/WebContextMenuProxy.h +++ b/Source/WebKit2/UIProcess/WebContextMenuProxy.h @@ -26,29 +26,31 @@ #ifndef WebContextMenuProxy_h #define WebContextMenuProxy_h -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> -#include <wtf/Vector.h> +#if ENABLE(CONTEXT_MENUS) -namespace WebCore { - class IntPoint; -} +#include "ContextMenuContextData.h" +#include "UserData.h" +#include <wtf/RefCounted.h> namespace WebKit { -class WebContextMenuItemData; +class WebContextMenuItem; -class WebContextMenuProxy : public RefCounted<WebContextMenuProxy> { +class WebContextMenuProxy { public: virtual ~WebContextMenuProxy(); - virtual void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>& items) = 0; - virtual void hideContextMenu() = 0; + virtual void show() = 0; protected: - WebContextMenuProxy(); + WebContextMenuProxy(const ContextMenuContextData&, const UserData&); + + const ContextMenuContextData m_context; + const UserData m_userData; }; } // namespace WebKit +#endif + #endif // WebPopupMenuProxy_h diff --git a/Source/WebKit2/UIProcess/WebContextSupplement.h b/Source/WebKit2/UIProcess/WebContextSupplement.h index 69f87e4e4..31fe9c4a0 100644 --- a/Source/WebKit2/UIProcess/WebContextSupplement.h +++ b/Source/WebKit2/UIProcess/WebContextSupplement.h @@ -28,14 +28,15 @@ namespace WebKit { +class DatabaseProcessProxy; class NetworkProcessProxy; -class WebContext; +class WebProcessPool; class WebProcessProxy; class WebContextSupplement { public: - WebContextSupplement(WebContext* context) - : m_context(context) + WebContextSupplement(WebProcessPool* processPool) + : m_processPool(processPool) { } @@ -43,7 +44,7 @@ public: { } - virtual void contextDestroyed() + virtual void processPoolDestroyed() { } @@ -55,13 +56,12 @@ public: { } - virtual bool shouldTerminate(WebProcessProxy*) const + virtual void processDidClose(DatabaseProcessProxy*) { - return true; } - WebContext* context() const { return m_context; } - void clearContext() { m_context = 0; } + WebProcessPool* processPool() const { return m_processPool; } + void clearProcessPool() { m_processPool = nullptr; } void ref() { refWebContextSupplement(); } void deref() { derefWebContextSupplement(); } @@ -70,7 +70,7 @@ private: virtual void refWebContextSupplement() = 0; virtual void derefWebContextSupplement() = 0; - WebContext* m_context; + WebProcessPool* m_processPool; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h b/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h deleted file mode 100644 index 041c234fd..000000000 --- a/Source/WebKit2/UIProcess/WebContextUserMessageCoders.h +++ /dev/null @@ -1,162 +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 "UserMessageCoders.h" -#include "WebContext.h" -#include "WebFrameProxy.h" -#include "WebPageGroup.h" -#include "WebPageGroupData.h" -#include "WebPageProxy.h" - -#if PLATFORM(MAC) -#include "ObjCObjectGraphCoders.h" -#endif - -namespace WebKit { - -// Adds -// - Page -> BundlePage -// - Frame -> BundleFrame -// - PageGroup -> BundlePageGroup - -class WebContextUserMessageEncoder : public UserMessageEncoder<WebContextUserMessageEncoder> { -public: - typedef UserMessageEncoder<WebContextUserMessageEncoder> Base; - - explicit WebContextUserMessageEncoder(APIObject* root) - : Base(root) - { - } - - void encode(CoreIPC::ArgumentEncoder& encoder) const - { - APIObject::Type type = APIObject::TypeNull; - if (baseEncode(encoder, type)) - return; - - switch (type) { - case APIObject::TypePage: { - WebPageProxy* page = static_cast<WebPageProxy*>(m_root); - encoder << page->pageID(); - break; - } - case APIObject::TypeFrame: { - WebFrameProxy* frame = static_cast<WebFrameProxy*>(m_root); - encoder << frame->frameID(); - break; - } - case APIObject::TypePageGroup: { - WebPageGroup* pageGroup = static_cast<WebPageGroup*>(m_root); - encoder << pageGroup->data(); - break; - } -#if PLATFORM(MAC) - case APIObject::TypeObjCObjectGraph: { - ObjCObjectGraph* objectGraph = static_cast<ObjCObjectGraph*>(m_root); - encoder << WebContextObjCObjectGraphEncoder(objectGraph); - break; - } -#endif - default: - ASSERT_NOT_REACHED(); - break; - } - } -}; - -// Adds -// - Page -> BundlePage -// - Frame -> BundleFrame -// - PageGroup -> BundlePageGroup - -class WebContextUserMessageDecoder : public UserMessageDecoder<WebContextUserMessageDecoder> { -public: - typedef UserMessageDecoder<WebContextUserMessageDecoder> Base; - - WebContextUserMessageDecoder(RefPtr<APIObject>& root, WebProcessProxy* process) - : Base(root) - , m_process(process) - { - } - - WebContextUserMessageDecoder(WebContextUserMessageDecoder& userMessageDecoder, RefPtr<APIObject>& root) - : Base(root) - , m_process(userMessageDecoder.m_process) - { - } - - static bool decode(CoreIPC::ArgumentDecoder& decoder, WebContextUserMessageDecoder& coder) - { - APIObject::Type type = APIObject::TypeNull; - if (!Base::baseDecode(decoder, coder, type)) - return false; - - if (coder.m_root || type == APIObject::TypeNull) - return true; - - switch (type) { - case APIObject::TypeBundlePage: { - uint64_t pageID; - if (!decoder.decode(pageID)) - return false; - coder.m_root = coder.m_process->webPage(pageID); - break; - } - case APIObject::TypeBundleFrame: { - uint64_t frameID; - if (!decoder.decode(frameID)) - return false; - coder.m_root = coder.m_process->webFrame(frameID); - break; - } - case APIObject::TypeBundlePageGroup: { - uint64_t pageGroupID; - if (!decoder.decode(pageGroupID)) - return false; - coder.m_root = WebPageGroup::get(pageGroupID); - break; - } -#if PLATFORM(MAC) - case APIObject::TypeObjCObjectGraph: { - RefPtr<ObjCObjectGraph> objectGraph; - WebContextObjCObjectGraphDecoder objectGraphDecoder(objectGraph, coder.m_process); - if (!decoder.decode(objectGraphDecoder)) - return false; - coder.m_root = objectGraph.get(); - break; - } -#endif - default: - return false; - } - - return true; - } - -private: - WebProcessProxy* m_process; -}; - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp b/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp index 4830cf0c6..977f5f634 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxy.cpp @@ -26,11 +26,12 @@ #include "config.h" #include "WebCookieManagerProxy.h" -#include "SecurityOriginData.h" -#include "WebContext.h" +#include "APIArray.h" +#include "APISecurityOrigin.h" #include "WebCookieManagerMessages.h" #include "WebCookieManagerProxyMessages.h" -#include "WebSecurityOrigin.h" +#include "WebProcessPool.h" +#include <WebCore/SecurityOriginData.h> namespace WebKit { @@ -39,75 +40,69 @@ const char* WebCookieManagerProxy::supplementName() return "WebCookieManagerProxy"; } -PassRefPtr<WebCookieManagerProxy> WebCookieManagerProxy::create(WebContext* context) +PassRefPtr<WebCookieManagerProxy> WebCookieManagerProxy::create(WebProcessPool* processPool) { - return adoptRef(new WebCookieManagerProxy(context)); + return adoptRef(new WebCookieManagerProxy(processPool)); } -WebCookieManagerProxy::WebCookieManagerProxy(WebContext* context) - : WebContextSupplement(context) +WebCookieManagerProxy::WebCookieManagerProxy(WebProcessPool* processPool) + : WebContextSupplement(processPool) #if USE(SOUP) , m_cookiePersistentStorageType(SoupCookiePersistentStorageSQLite) #endif { - WebContextSupplement::context()->addMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName(), this); + WebContextSupplement::processPool()->addMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName(), *this); } WebCookieManagerProxy::~WebCookieManagerProxy() { } -void WebCookieManagerProxy::initializeClient(const WKCookieManagerClient* client) +void WebCookieManagerProxy::initializeClient(const WKCookieManagerClientBase* client) { m_client.initialize(client); } // WebContextSupplement -void WebCookieManagerProxy::contextDestroyed() +void WebCookieManagerProxy::processPoolDestroyed() { - invalidateCallbackMap(m_arrayCallbacks); - invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks); + invalidateCallbackMap(m_arrayCallbacks, CallbackBase::Error::OwnerWasInvalidated); + invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks, CallbackBase::Error::OwnerWasInvalidated); } void WebCookieManagerProxy::processDidClose(WebProcessProxy*) { - invalidateCallbackMap(m_arrayCallbacks); - invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks); + invalidateCallbackMap(m_arrayCallbacks, CallbackBase::Error::ProcessExited); + invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks, CallbackBase::Error::ProcessExited); } void WebCookieManagerProxy::processDidClose(NetworkProcessProxy*) { - invalidateCallbackMap(m_arrayCallbacks); - invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks); -} - -bool WebCookieManagerProxy::shouldTerminate(WebProcessProxy*) const -{ - return context()->processModel() != ProcessModelSharedSecondaryProcess - || (m_arrayCallbacks.isEmpty() && m_httpCookieAcceptPolicyCallbacks.isEmpty()); + invalidateCallbackMap(m_arrayCallbacks, CallbackBase::Error::ProcessExited); + invalidateCallbackMap(m_httpCookieAcceptPolicyCallbacks, CallbackBase::Error::ProcessExited); } void WebCookieManagerProxy::refWebContextSupplement() { - APIObject::ref(); + API::Object::ref(); } void WebCookieManagerProxy::derefWebContextSupplement() { - APIObject::deref(); + API::Object::deref(); } -void WebCookieManagerProxy::getHostnamesWithCookies(PassRefPtr<ArrayCallback> prpCallback) +void WebCookieManagerProxy::getHostnamesWithCookies(std::function<void (API::Array*, CallbackBase::Error)> callbackFunction) { - RefPtr<ArrayCallback> callback = prpCallback; + RefPtr<ArrayCallback> callback = ArrayCallback::create(WTFMove(callbackFunction)); uint64_t callbackID = callback->callbackID(); m_arrayCallbacks.set(callbackID, callback.release()); - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::GetHostnamesWithCookies(callbackID)); + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::GetHostnamesWithCookies(callbackID)); } -void WebCookieManagerProxy::didGetHostnamesWithCookies(const Vector<String>& hostnameList, uint64_t callbackID) +void WebCookieManagerProxy::didGetHostnamesWithCookies(const Vector<String>& hostnames, uint64_t callbackID) { RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); if (!callback) { @@ -115,33 +110,32 @@ void WebCookieManagerProxy::didGetHostnamesWithCookies(const Vector<String>& hos return; } - size_t hostnameCount = hostnameList.size(); - Vector<RefPtr<APIObject> > hostnames(hostnameCount); - - for (size_t i = 0; i < hostnameCount; ++i) - hostnames[i] = WebString::create(hostnameList[i]); - - callback->performCallbackWithReturnValue(ImmutableArray::adopt(hostnames).get()); + callback->performCallbackWithReturnValue(API::Array::createStringArray(hostnames).ptr()); } void WebCookieManagerProxy::deleteCookiesForHostname(const String& hostname) { - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteCookiesForHostname(hostname)); + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteCookiesForHostname(hostname)); } void WebCookieManagerProxy::deleteAllCookies() { - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteAllCookies()); + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteAllCookies()); +} + +void WebCookieManagerProxy::deleteAllCookiesModifiedSince(std::chrono::system_clock::time_point time) +{ + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteAllCookiesModifiedSince(time)); } void WebCookieManagerProxy::startObservingCookieChanges() { - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StartObservingCookieChanges()); + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StartObservingCookieChanges()); } void WebCookieManagerProxy::stopObservingCookieChanges() { - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StopObservingCookieChanges()); + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StopObservingCookieChanges()); } void WebCookieManagerProxy::cookiesDidChange() @@ -151,24 +145,29 @@ void WebCookieManagerProxy::cookiesDidChange() void WebCookieManagerProxy::setHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { -#if PLATFORM(MAC) - persistHTTPCookieAcceptPolicy(policy); +#if PLATFORM(COCOA) + if (!processPool()->isUsingTestingNetworkSession()) + persistHTTPCookieAcceptPolicy(policy); #endif #if USE(SOUP) - context()->setInitialHTTPCookieAcceptPolicy(policy); + processPool()->setInitialHTTPCookieAcceptPolicy(policy); #endif - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy)); + // The policy is not sent to newly created processes (only Soup does that via setInitialHTTPCookieAcceptPolicy()). This is not a serious problem, because: + // - When testing, we only have one WebProcess and one NetworkProcess, and WebKitTestRunner never restarts them; + // - When not testing, Cocoa has the policy persisted, and thus new processes use it (even for ephemeral sessions). + processPool()->sendToAllProcesses(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy)); + processPool()->sendToNetworkingProcess(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy)); } -void WebCookieManagerProxy::getHTTPCookieAcceptPolicy(PassRefPtr<HTTPCookieAcceptPolicyCallback> prpCallback) +void WebCookieManagerProxy::getHTTPCookieAcceptPolicy(std::function<void (HTTPCookieAcceptPolicy, CallbackBase::Error)> callbackFunction) { - RefPtr<HTTPCookieAcceptPolicyCallback> callback = prpCallback; + RefPtr<HTTPCookieAcceptPolicyCallback> callback = HTTPCookieAcceptPolicyCallback::create(WTFMove(callbackFunction)); uint64_t callbackID = callback->callbackID(); m_httpCookieAcceptPolicyCallbacks.set(callbackID, callback.release()); - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::GetHTTPCookieAcceptPolicy(callbackID)); + processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::GetHTTPCookieAcceptPolicy(callbackID)); } void WebCookieManagerProxy::didGetHTTPCookieAcceptPolicy(uint32_t policy, uint64_t callbackID) diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxy.h b/Source/WebKit2/UIProcess/WebCookieManagerProxy.h index ae3b5c265..e1aa527bb 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxy.h @@ -28,7 +28,6 @@ #include "APIObject.h" #include "GenericCallback.h" -#include "ImmutableArray.h" #include "MessageReceiver.h" #include "WebContextSupplement.h" #include "WebCookieManagerProxyClient.h" @@ -40,29 +39,35 @@ #include "SoupCookiePersistentStorageType.h" #endif +namespace API { +class Array; +} + + namespace WebKit { -class WebContext; +class WebProcessPool; class WebProcessProxy; -typedef GenericCallback<WKArrayRef> ArrayCallback; -typedef GenericCallback<WKHTTPCookieAcceptPolicy, HTTPCookieAcceptPolicy> HTTPCookieAcceptPolicyCallback; +typedef GenericCallback<API::Array*> ArrayCallback; +typedef GenericCallback<HTTPCookieAcceptPolicy> HTTPCookieAcceptPolicyCallback; -class WebCookieManagerProxy : public TypedAPIObject<APIObject::TypeCookieManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { +class WebCookieManagerProxy : public API::ObjectImpl<API::Object::Type::CookieManager>, public WebContextSupplement, private IPC::MessageReceiver { public: static const char* supplementName(); - static PassRefPtr<WebCookieManagerProxy> create(WebContext*); + static PassRefPtr<WebCookieManagerProxy> create(WebProcessPool*); virtual ~WebCookieManagerProxy(); - void initializeClient(const WKCookieManagerClient*); + void initializeClient(const WKCookieManagerClientBase*); - void getHostnamesWithCookies(PassRefPtr<ArrayCallback>); + void getHostnamesWithCookies(std::function<void (API::Array*, CallbackBase::Error)>); void deleteCookiesForHostname(const String& hostname); void deleteAllCookies(); + void deleteAllCookiesModifiedSince(std::chrono::system_clock::time_point); void setHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy); - void getHTTPCookieAcceptPolicy(PassRefPtr<HTTPCookieAcceptPolicyCallback>); + void getHTTPCookieAcceptPolicy(std::function<void (HTTPCookieAcceptPolicy, CallbackBase::Error)>); void startObservingCookieChanges(); void stopObservingCookieChanges(); @@ -72,11 +77,11 @@ public: void getCookiePersistentStorage(String& storagePath, uint32_t& storageType) const; #endif - using APIObject::ref; - using APIObject::deref; + using API::Object::ref; + using API::Object::deref; private: - WebCookieManagerProxy(WebContext*); + WebCookieManagerProxy(WebProcessPool*); void didGetHostnamesWithCookies(const Vector<String>&, uint64_t callbackID); void didGetHTTPCookieAcceptPolicy(uint32_t policy, uint64_t callbackID); @@ -84,22 +89,21 @@ private: void cookiesDidChange(); // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual void processDidClose(NetworkProcessProxy*) OVERRIDE; - virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; + virtual void processPoolDestroyed() override; + virtual void processDidClose(WebProcessProxy*) override; + virtual void processDidClose(NetworkProcessProxy*) override; + virtual void refWebContextSupplement() override; + virtual void derefWebContextSupplement() override; - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void persistHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy); #endif - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; - HashMap<uint64_t, RefPtr<HTTPCookieAcceptPolicyCallback> > m_httpCookieAcceptPolicyCallbacks; + HashMap<uint64_t, RefPtr<ArrayCallback>> m_arrayCallbacks; + HashMap<uint64_t, RefPtr<HTTPCookieAcceptPolicyCallback>> m_httpCookieAcceptPolicyCallbacks; WebCookieManagerProxyClient m_client; diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebCookieManagerProxy.messages.in index 2ae0545c3..49ac6db23 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxy.messages.in @@ -21,7 +21,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. messages -> WebCookieManagerProxy { - DidGetHostnamesWithCookies(Vector<WTF::String> hostnames, uint64_t callbackID); + DidGetHostnamesWithCookies(Vector<String> hostnames, uint64_t callbackID); DidGetHTTPCookieAcceptPolicy(uint32_t policy, uint64_t callbackID); CookiesDidChange() diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.cpp b/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.cpp index da5512df7..79c660f81 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.cpp +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.cpp @@ -27,6 +27,7 @@ #include "WebCookieManagerProxyClient.h" #include "WKAPICast.h" +#include "WebCookieManagerProxy.h" namespace WebKit { @@ -35,7 +36,7 @@ void WebCookieManagerProxyClient::cookiesDidChange(WebCookieManagerProxy* cookie if (!m_client.cookiesDidChange) return; - m_client.cookiesDidChange(toAPI(cookieManager), m_client.clientInfo); + m_client.cookiesDidChange(toAPI(cookieManager), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.h b/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.h index 2faa167c0..0346fd8e5 100644 --- a/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.h +++ b/Source/WebKit2/UIProcess/WebCookieManagerProxyClient.h @@ -30,11 +30,17 @@ #include "WKCookieManager.h" #include <wtf/Forward.h> +namespace API { +template<> struct ClientTraits<WKCookieManagerClientBase> { + typedef std::tuple<WKCookieManagerClientV0> Versions; +}; +} + namespace WebKit { class WebCookieManagerProxy; -class WebCookieManagerProxyClient : public APIClient<WKCookieManagerClient, kWKCookieManagerClientCurrentVersion> { +class WebCookieManagerProxyClient : public API::Client<WKCookieManagerClientBase> { public: void cookiesDidChange(WebCookieManagerProxy*); }; diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp deleted file mode 100644 index c4febdc26..000000000 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.cpp +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * 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 "WebDatabaseManagerProxy.h" - -#if ENABLE(SQL_DATABASE) - -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "WebContext.h" -#include "WebDatabaseManagerMessages.h" -#include "WebDatabaseManagerProxyMessages.h" -#include "WebSecurityOrigin.h" - -using namespace WebCore; - -namespace WebKit { - -const char* WebDatabaseManagerProxy::supplementName() -{ - return "WebDatabaseManagerProxy"; -} - -String WebDatabaseManagerProxy::originKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerOriginKey"))); - return key; -} - -String WebDatabaseManagerProxy::originQuotaKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerOriginQuotaKey"))); - return key; -} - -String WebDatabaseManagerProxy::originUsageKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerOriginUsageKey"))); - return key; -} - -String WebDatabaseManagerProxy::databaseDetailsKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerDatabaseDetailsKey"))); - return key; -} - -String WebDatabaseManagerProxy::databaseDetailsNameKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerDatabaseDetailsNameKey"))); - return key; -} - -String WebDatabaseManagerProxy::databaseDetailsDisplayNameKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerDatabaseDetailsDisplayNameKey"))); - return key; -} - -String WebDatabaseManagerProxy::databaseDetailsExpectedUsageKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerDatabaseDetailsExpectedUsageKey"))); - return key; -} - -String WebDatabaseManagerProxy::databaseDetailsCurrentUsageKey() -{ - DEFINE_STATIC_LOCAL(String, key, (ASCIILiteral("WebDatabaseManagerDatabaseDetailsCurrentUsageKey"))); - return key; -} - -PassRefPtr<WebDatabaseManagerProxy> WebDatabaseManagerProxy::create(WebContext* webContext) -{ - return adoptRef(new WebDatabaseManagerProxy(webContext)); -} - -WebDatabaseManagerProxy::WebDatabaseManagerProxy(WebContext* webContext) - : WebContextSupplement(webContext) -{ - WebContextSupplement::context()->addMessageReceiver(Messages::WebDatabaseManagerProxy::messageReceiverName(), this); -} - -WebDatabaseManagerProxy::~WebDatabaseManagerProxy() -{ -} - -void WebDatabaseManagerProxy::initializeClient(const WKDatabaseManagerClient* client) -{ - m_client.initialize(client); -} - -// WebContextSupplement - -void WebDatabaseManagerProxy::contextDestroyed() -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -void WebDatabaseManagerProxy::processDidClose(WebProcessProxy*) -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -bool WebDatabaseManagerProxy::shouldTerminate(WebProcessProxy*) const -{ - return m_arrayCallbacks.isEmpty(); -} - -void WebDatabaseManagerProxy::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebDatabaseManagerProxy::derefWebContextSupplement() -{ - APIObject::deref(); -} - -void WebDatabaseManagerProxy::getDatabasesByOrigin(PassRefPtr<ArrayCallback> prpCallback) -{ - RefPtr<ArrayCallback> callback = prpCallback; - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - - context()->sendToOneProcess(Messages::WebDatabaseManager::GetDatabasesByOrigin(callbackID)); -} - -void WebDatabaseManagerProxy::didGetDatabasesByOrigin(const Vector<OriginAndDatabases>& originAndDatabasesVector, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - if (!callback) { - // FIXME: Log error or assert. - return; - } - - size_t originAndDatabasesCount = originAndDatabasesVector.size(); - Vector<RefPtr<APIObject> > result(originAndDatabasesCount); - - for (size_t i = 0; i < originAndDatabasesCount; ++i) { - const OriginAndDatabases& originAndDatabases = originAndDatabasesVector[i]; - - RefPtr<APIObject> origin = WebSecurityOrigin::createFromDatabaseIdentifier(originAndDatabases.originIdentifier); - - size_t databasesCount = originAndDatabases.databases.size(); - Vector<RefPtr<APIObject> > databases(databasesCount); - - for (size_t j = 0; j < databasesCount; ++j) { - const DatabaseDetails& details = originAndDatabases.databases[i]; - HashMap<String, RefPtr<APIObject> > detailsMap; - - detailsMap.set(databaseDetailsNameKey(), WebString::create(details.name())); - detailsMap.set(databaseDetailsDisplayNameKey(), WebString::create(details.displayName())); - detailsMap.set(databaseDetailsExpectedUsageKey(), WebUInt64::create(details.expectedUsage())); - detailsMap.set(databaseDetailsCurrentUsageKey(), WebUInt64::create(details.currentUsage())); - databases.append(ImmutableDictionary::adopt(detailsMap)); - } - - HashMap<String, RefPtr<APIObject> > originAndDatabasesMap; - originAndDatabasesMap.set(originKey(), origin); - originAndDatabasesMap.set(originQuotaKey(), WebUInt64::create(originAndDatabases.originQuota)); - originAndDatabasesMap.set(originUsageKey(), WebUInt64::create(originAndDatabases.originUsage)); - originAndDatabasesMap.set(databaseDetailsKey(), ImmutableArray::adopt(databases)); - - result.append(ImmutableDictionary::adopt(originAndDatabasesMap)); - } - - RefPtr<ImmutableArray> resultArray = ImmutableArray::adopt(result); - callback->performCallbackWithReturnValue(resultArray.get()); -} - -void WebDatabaseManagerProxy::getDatabaseOrigins(PassRefPtr<ArrayCallback> prpCallback) -{ - RefPtr<ArrayCallback> callback = prpCallback; - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - - context()->sendToOneProcess(Messages::WebDatabaseManager::GetDatabaseOrigins(callbackID)); -} - -void WebDatabaseManagerProxy::didGetDatabaseOrigins(const Vector<String>& originIdentifiers, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - if (!callback) { - // FIXME: Log error or assert. - return; - } - - size_t originIdentifiersCount = originIdentifiers.size(); - Vector<RefPtr<APIObject> > securityOrigins(originIdentifiersCount); - - for (size_t i = 0; i < originIdentifiersCount; ++i) - securityOrigins[i] = WebSecurityOrigin::createFromDatabaseIdentifier(originIdentifiers[i]); - - callback->performCallbackWithReturnValue(ImmutableArray::adopt(securityOrigins).get()); -} - -void WebDatabaseManagerProxy::deleteDatabaseWithNameForOrigin(const String& databaseIdentifier, WebSecurityOrigin* origin) -{ - context()->sendToOneProcess(Messages::WebDatabaseManager::DeleteDatabaseWithNameForOrigin(databaseIdentifier, origin->databaseIdentifier())); -} - -void WebDatabaseManagerProxy::deleteDatabasesForOrigin(WebSecurityOrigin* origin) -{ - context()->sendToOneProcess(Messages::WebDatabaseManager::DeleteDatabasesForOrigin(origin->databaseIdentifier())); -} - -void WebDatabaseManagerProxy::deleteAllDatabases() -{ - context()->sendToOneProcess(Messages::WebDatabaseManager::DeleteAllDatabases()); -} - -void WebDatabaseManagerProxy::setQuotaForOrigin(WebSecurityOrigin* origin, uint64_t quota) -{ - context()->sendToOneProcess(Messages::WebDatabaseManager::SetQuotaForOrigin(origin->databaseIdentifier(), quota)); -} - -void WebDatabaseManagerProxy::didModifyOrigin(const String& originIdentifier) -{ - RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromDatabaseIdentifier(originIdentifier); - m_client.didModifyOrigin(this, origin.get()); -} - -void WebDatabaseManagerProxy::didModifyDatabase(const String& originIdentifier, const String& databaseIdentifier) -{ - RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromDatabaseIdentifier(originIdentifier); - m_client.didModifyDatabase(this, origin.get(), databaseIdentifier); -} - -} // namespace WebKit - -#endif // ENABLE(SQL_DATABASE) diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h deleted file mode 100644 index 3266d5849..000000000 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2010, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * 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 WebDatabaseManagerProxy_h -#define WebDatabaseManagerProxy_h - -#if ENABLE(SQL_DATABASE) - -#include "APIObject.h" -#include "Arguments.h" -#include "GenericCallback.h" -#include "MessageReceiver.h" -#include "OriginAndDatabases.h" -#include "WebContextSupplement.h" -#include "WebDatabaseManagerProxyClient.h" -#include <wtf/HashMap.h> -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -class WebContext; -class WebProcessProxy; -class WebSecurityOrigin; - -typedef GenericCallback<WKArrayRef> ArrayCallback; - -class WebDatabaseManagerProxy : public TypedAPIObject<APIObject::TypeDatabaseManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { -public: - static const char* supplementName(); - - static PassRefPtr<WebDatabaseManagerProxy> create(WebContext*); - virtual ~WebDatabaseManagerProxy(); - - void initializeClient(const WKDatabaseManagerClient*); - - void getDatabasesByOrigin(PassRefPtr<ArrayCallback>); - void getDatabaseOrigins(PassRefPtr<ArrayCallback>); - void deleteDatabaseWithNameForOrigin(const String& databaseIdentifier, WebSecurityOrigin*); - void deleteDatabasesForOrigin(WebSecurityOrigin*); - void deleteAllDatabases(); - void setQuotaForOrigin(WebSecurityOrigin*, uint64_t quota); - - static String originKey(); - static String originQuotaKey(); - static String originUsageKey(); - static String databaseDetailsKey(); - static String databaseDetailsNameKey(); - static String databaseDetailsDisplayNameKey(); - static String databaseDetailsExpectedUsageKey(); - static String databaseDetailsCurrentUsageKey(); - - using APIObject::ref; - using APIObject::deref; - -private: - explicit WebDatabaseManagerProxy(WebContext*); - - // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - // Message handlers. - void didGetDatabasesByOrigin(const Vector<OriginAndDatabases>& originAndDatabases, uint64_t callbackID); - void didGetDatabaseOrigins(const Vector<String>& originIdentifiers, uint64_t callbackID); - void didModifyOrigin(const String& originIdentifier); - void didModifyDatabase(const String& originIdentifier, const String& databaseIdentifier); - - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; - WebDatabaseManagerProxyClient m_client; -}; - -} // namespace WebKit - -#endif // ENABLE(SQL_DATABASE) - -#endif // DatabaseManagerProxy_h diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.messages.in deleted file mode 100644 index 503275fff..000000000 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxy.messages.in +++ /dev/null @@ -1,32 +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. - -#if ENABLE(SQL_DATABASE) - -messages -> WebDatabaseManagerProxy { - DidGetDatabasesByOrigin(Vector<WebKit::OriginAndDatabases> originAndDatabases, uint64_t callbackID); - DidGetDatabaseOrigins(Vector<WTF::String> originIdentifiers, uint64_t callbackID) - DidModifyOrigin(WTF::String originIdentifier) - DidModifyDatabase(WTF::String originIdentifier, WTF::String databaseIdentifier) -} - -#endif // ENABLE(SQL_DATABASE) diff --git a/Source/WebKit2/UIProcess/WebDownloadClient.cpp b/Source/WebKit2/UIProcess/WebDownloadClient.cpp deleted file mode 100644 index 612a056c2..000000000 --- a/Source/WebKit2/UIProcess/WebDownloadClient.cpp +++ /dev/null @@ -1,126 +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 "WebDownloadClient.h" - -#include "WKAPICast.h" -#include "WebURLResponse.h" -#include "WKRetainPtr.h" - -using namespace WebCore; - -namespace WebKit { - -void WebDownloadClient::didStart(WebContext* webContext, DownloadProxy* downloadProxy) -{ - if (!m_client.didStart) - return; - - m_client.didStart(toAPI(webContext), toAPI(downloadProxy), m_client.clientInfo); -} - -void WebDownloadClient::didReceiveAuthenticationChallenge(WebContext* webContext, DownloadProxy* downloadProxy, AuthenticationChallengeProxy* authenticationChallengeProxy) -{ - if (!m_client.didReceiveAuthenticationChallenge) - return; - - m_client.didReceiveAuthenticationChallenge(toAPI(webContext), toAPI(downloadProxy), toAPI(authenticationChallengeProxy), m_client.clientInfo); -} - -void WebDownloadClient::didReceiveResponse(WebContext* webContext, DownloadProxy* downloadProxy, const ResourceResponse& response) -{ - if (!m_client.didReceiveResponse) - return; - - m_client.didReceiveResponse(toAPI(webContext), toAPI(downloadProxy), toAPI(WebURLResponse::create(response).get()), m_client.clientInfo); -} - -void WebDownloadClient::didReceiveData(WebContext* webContext, DownloadProxy* downloadProxy, uint64_t length) -{ - if (!m_client.didReceiveData) - return; - - m_client.didReceiveData(toAPI(webContext), toAPI(downloadProxy), length, m_client.clientInfo); -} - -bool WebDownloadClient::shouldDecodeSourceDataOfMIMEType(WebContext* webContext, DownloadProxy* downloadProxy, const String& mimeType) -{ - if (!m_client.shouldDecodeSourceDataOfMIMEType) - return true; - - return m_client.shouldDecodeSourceDataOfMIMEType(toAPI(webContext), toAPI(downloadProxy), toAPI(mimeType.impl()), m_client.clientInfo); -} - -String WebDownloadClient::decideDestinationWithSuggestedFilename(WebContext* webContext, DownloadProxy* downloadProxy, const String& filename, bool& allowOverwrite) -{ - if (!m_client.decideDestinationWithSuggestedFilename) - return String(); - - WKRetainPtr<WKStringRef> destination(AdoptWK, m_client.decideDestinationWithSuggestedFilename(toAPI(webContext), toAPI(downloadProxy), toAPI(filename.impl()), &allowOverwrite, m_client.clientInfo)); - return toWTFString(destination.get()); -} - -void WebDownloadClient::didCreateDestination(WebContext* webContext, DownloadProxy* downloadProxy, const String& path) -{ - if (!m_client.didCreateDestination) - return; - - m_client.didCreateDestination(toAPI(webContext), toAPI(downloadProxy), toAPI(path.impl()), m_client.clientInfo); -} - -void WebDownloadClient::didFinish(WebContext* webContext, DownloadProxy* downloadProxy) -{ - if (!m_client.didFinish) - return; - - m_client.didFinish(toAPI(webContext), toAPI(downloadProxy), m_client.clientInfo); -} - -void WebDownloadClient::didFail(WebContext* webContext, DownloadProxy* downloadProxy, const ResourceError& error) -{ - if (!m_client.didFail) - return; - - m_client.didFail(toAPI(webContext), toAPI(downloadProxy), toAPI(error), m_client.clientInfo); -} - -void WebDownloadClient::didCancel(WebContext* webContext, DownloadProxy* downloadProxy) -{ - if (!m_client.didCancel) - return; - - m_client.didCancel(toAPI(webContext), toAPI(downloadProxy), m_client.clientInfo); -} - -void WebDownloadClient::processDidCrash(WebContext* webContext, DownloadProxy* downloadProxy) -{ - if (!m_client.processDidCrash) - return; - - m_client.processDidCrash(toAPI(webContext), toAPI(downloadProxy), m_client.clientInfo); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebDownloadClient.h b/Source/WebKit2/UIProcess/WebDownloadClient.h deleted file mode 100644 index 20950e569..000000000 --- a/Source/WebKit2/UIProcess/WebDownloadClient.h +++ /dev/null @@ -1,61 +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 WebDownloadClient_h -#define WebDownloadClient_h - -#include "APIClient.h" -#include "WKContext.h" -#include <wtf/Forward.h> - -namespace WebCore { - class ResourceError; - class ResourceResponse; -} - -namespace WebKit { - -class AuthenticationChallengeProxy; -class DownloadProxy; -class WebContext; - -class WebDownloadClient : public APIClient<WKContextDownloadClient, kWKContextDownloadClientCurrentVersion> { -public: - void didStart(WebContext*, DownloadProxy*); - void didReceiveAuthenticationChallenge(WebContext*, DownloadProxy*, AuthenticationChallengeProxy*); - void didReceiveResponse(WebContext*, DownloadProxy*, const WebCore::ResourceResponse&); - void didReceiveData(WebContext*, DownloadProxy*, uint64_t length); - bool shouldDecodeSourceDataOfMIMEType(WebContext*, DownloadProxy*, const String& mimeType); - String decideDestinationWithSuggestedFilename(WebContext*, DownloadProxy*, const String& filename, bool& allowOverwrite); - void didCreateDestination(WebContext*, DownloadProxy*, const String& path); - void didFinish(WebContext*, DownloadProxy*); - void didFail(WebContext*, DownloadProxy*, const WebCore::ResourceError&); - void didCancel(WebContext*, DownloadProxy*); - void processDidCrash(WebContext*, DownloadProxy*); -}; - -} // namespace WebKit - -#endif // WebDownloadClient_h diff --git a/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp b/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp index 81f145d51..878559546 100644 --- a/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp +++ b/Source/WebKit2/UIProcess/WebEditCommandProxy.cpp @@ -55,7 +55,7 @@ void WebEditCommandProxy::unapply() if (!m_page || !m_page->isValid()) return; - m_page->process()->send(Messages::WebPage::UnapplyEditCommand(m_commandID), m_page->pageID(), CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); + m_page->process().send(Messages::WebPage::UnapplyEditCommand(m_commandID), m_page->pageID(), IPC::DispatchMessageEvenWhenWaitingForSyncReply); m_page->registerEditCommand(this, WebPageProxy::Redo); } @@ -64,15 +64,18 @@ void WebEditCommandProxy::reapply() if (!m_page || !m_page->isValid()) return; - m_page->process()->send(Messages::WebPage::ReapplyEditCommand(m_commandID), m_page->pageID(), CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply); + m_page->process().send(Messages::WebPage::ReapplyEditCommand(m_commandID), m_page->pageID(), IPC::DispatchMessageEvenWhenWaitingForSyncReply); m_page->registerEditCommand(this, WebPageProxy::Undo); } String WebEditCommandProxy::nameForEditAction(EditAction editAction) { + // FIXME: This is identical to code in WebKit's WebEditorClient class; would be nice to share the strings instead of having two copies. switch (editAction) { case EditActionUnspecified: return String(); + case EditActionInsert: + return String(); case EditActionSetColor: return WEB_UI_STRING_KEY("Set Color", "Set Color (Undo action name)", "Undo action name"); case EditActionSetBackgroundColor: @@ -129,6 +132,10 @@ String WebEditCommandProxy::nameForEditAction(EditAction editAction) return WEB_UI_STRING_KEY("Bold", "Bold (Undo action name)", "Undo action name"); case EditActionItalics: return WEB_UI_STRING_KEY("Italics", "Italics (Undo action name)", "Undo action name"); + case EditActionDelete: + return WEB_UI_STRING_KEY("Delete", "Delete (Undo action name)", "Undo action name"); + case EditActionDictation: + return WEB_UI_STRING_KEY("Dictation", "Dictation (Undo action name)", "Undo action name"); case EditActionPaste: return WEB_UI_STRING_KEY("Paste", "Paste (Undo action name)", "Undo action name"); case EditActionPasteFont: diff --git a/Source/WebKit2/UIProcess/WebEditCommandProxy.h b/Source/WebKit2/UIProcess/WebEditCommandProxy.h index f4f32ca43..154d954f6 100644 --- a/Source/WebKit2/UIProcess/WebEditCommandProxy.h +++ b/Source/WebKit2/UIProcess/WebEditCommandProxy.h @@ -36,7 +36,7 @@ namespace WebKit { class WebPageProxy; -class WebEditCommandProxy : public TypedAPIObject<APIObject::TypeEditCommandProxy> { +class WebEditCommandProxy : public API::ObjectImpl<API::Object::Type::EditCommandProxy> { public: static PassRefPtr<WebEditCommandProxy> create(uint64_t commandID, WebCore::EditAction editAction, WebPageProxy* page) { diff --git a/Source/WebKit2/UIProcess/WebFormClient.cpp b/Source/WebKit2/UIProcess/WebFormClient.cpp index ecddbcc42..716b7bd60 100644 --- a/Source/WebKit2/UIProcess/WebFormClient.cpp +++ b/Source/WebKit2/UIProcess/WebFormClient.cpp @@ -26,25 +26,31 @@ #include "config.h" #include "WebFormClient.h" -#include "ImmutableDictionary.h" +#include "APIDictionary.h" +#include "APIString.h" #include "WKAPICast.h" -#include "WebString.h" -#include <wtf/text/WTFString.h> +#include "WebFormSubmissionListenerProxy.h" +#include "WebPageProxy.h" namespace WebKit { -bool WebFormClient::willSubmitForm(WebPageProxy* page, WebFrameProxy* frame, WebFrameProxy* sourceFrame, const Vector<std::pair<String, String> >& textFieldValues, APIObject* userData, WebFormSubmissionListenerProxy* listener) +WebFormClient::WebFormClient(const WKPageFormClientBase* wkClient) { - if (!m_client.willSubmitForm) - return false; + initialize(wkClient); +} - ImmutableDictionary::MapType map; - for (size_t i = 0; i < textFieldValues.size(); ++i) - map.set(textFieldValues[i].first, WebString::create(textFieldValues[i].second)); - RefPtr<ImmutableDictionary> textFieldsMap = ImmutableDictionary::adopt(map); +void WebFormClient::willSubmitForm(WebPageProxy& page, WebFrameProxy& frame, WebFrameProxy& sourceFrame, const Vector<std::pair<String, String>>& textFieldValues, API::Object* userData, Ref<WebFormSubmissionListenerProxy>&& listener) +{ + if (!m_client.willSubmitForm) { + listener->continueSubmission(); + return; + } - m_client.willSubmitForm(toAPI(page), toAPI(frame), toAPI(sourceFrame), toAPI(textFieldsMap.get()), toAPI(userData), toAPI(listener), m_client.clientInfo); - return true; + API::Dictionary::MapType map; + for (size_t i = 0; i < textFieldValues.size(); ++i) + map.set(textFieldValues[i].first, API::String::create(textFieldValues[i].second)); + Ref<API::Dictionary> textFieldsMap = API::Dictionary::create(WTFMove(map)); + m_client.willSubmitForm(toAPI(&page), toAPI(&frame), toAPI(&sourceFrame), toAPI(textFieldsMap.ptr()), toAPI(userData), toAPI(&listener.get()), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFormClient.h b/Source/WebKit2/UIProcess/WebFormClient.h index 05925239f..66fefed9d 100644 --- a/Source/WebKit2/UIProcess/WebFormClient.h +++ b/Source/WebKit2/UIProcess/WebFormClient.h @@ -27,21 +27,22 @@ #define WebFormClient_h #include "APIClient.h" -#include "WKPage.h" -#include <utility> -#include <wtf/Forward.h> -#include <wtf/Vector.h> +#include "APIFormClient.h" +#include "WKPageFormClient.h" -namespace WebKit { +namespace API { +template<> struct ClientTraits<WKPageFormClientBase> { + typedef std::tuple<WKPageFormClientV0> Versions; +}; +} -class APIObject; -class WebPageProxy; -class WebFrameProxy; -class WebFormSubmissionListenerProxy; +namespace WebKit { -class WebFormClient : public APIClient<WKPageFormClient, kWKPageFormClientCurrentVersion> { +class WebFormClient : public API::FormClient, API::Client<WKPageFormClientBase> { public: - bool willSubmitForm(WebPageProxy*, WebFrameProxy*, WebFrameProxy*, const Vector<std::pair<String, String> >& textFieldValues, APIObject* userData, WebFormSubmissionListenerProxy*); + explicit WebFormClient(const WKPageFormClientBase*); + + virtual void willSubmitForm(WebPageProxy&, WebFrameProxy&, WebFrameProxy&, const Vector<std::pair<String, String>>& textFieldValues, API::Object* userData, Ref<WebFormSubmissionListenerProxy>&&) override; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFormSubmissionListenerProxy.h b/Source/WebKit2/UIProcess/WebFormSubmissionListenerProxy.h index 53ba3b980..70bac5e52 100644 --- a/Source/WebKit2/UIProcess/WebFormSubmissionListenerProxy.h +++ b/Source/WebKit2/UIProcess/WebFormSubmissionListenerProxy.h @@ -28,13 +28,19 @@ #include "WebFrameListenerProxy.h" +#if PLATFORM(COCOA) +#include "WKFoundation.h" +#endif + +#define DELEGATE_REF_COUNTING_TO_COCOA (PLATFORM(COCOA) && WK_API_ENABLED) + namespace WebKit { class WebFrameProxy; class WebFormSubmissionListenerProxy : public WebFrameListenerProxy { public: - static const Type APIType = TypeFormSubmissionListener; + static const Type APIType = Type::FormSubmissionListener; static PassRefPtr<WebFormSubmissionListenerProxy> create(WebFrameProxy* frame, uint64_t listenerID) { @@ -47,8 +53,14 @@ private: WebFormSubmissionListenerProxy(WebFrameProxy*, uint64_t listenerID); virtual Type type() const { return APIType; } + +#if DELEGATE_REF_COUNTING_TO_COCOA + void* operator new(size_t size) { return newObject(size, APIType); } +#endif }; } // namespace WebKit +#undef DELEGATE_REF_COUNTING_TO_COCOA + #endif // WebFramePolicyListenerProxy_h diff --git a/Source/WebKit2/UIProcess/WebFrameListenerProxy.cpp b/Source/WebKit2/UIProcess/WebFrameListenerProxy.cpp index b998f5836..4061dd529 100644 --- a/Source/WebKit2/UIProcess/WebFrameListenerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebFrameListenerProxy.cpp @@ -42,7 +42,7 @@ WebFrameListenerProxy::~WebFrameListenerProxy() void WebFrameListenerProxy::invalidate() { - m_frame = 0; + m_frame = nullptr; } void WebFrameListenerProxy::receivedPolicyDecision(WebCore::PolicyAction action) @@ -50,8 +50,8 @@ void WebFrameListenerProxy::receivedPolicyDecision(WebCore::PolicyAction action) if (!m_frame) return; - m_frame->receivedPolicyDecision(action, m_listenerID); - m_frame = 0; + m_frame->receivedPolicyDecision(action, m_listenerID, m_navigation.get()); + m_frame = nullptr; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFrameListenerProxy.h b/Source/WebKit2/UIProcess/WebFrameListenerProxy.h index fd9ad7194..6a87f6e34 100644 --- a/Source/WebKit2/UIProcess/WebFrameListenerProxy.h +++ b/Source/WebKit2/UIProcess/WebFrameListenerProxy.h @@ -26,22 +26,27 @@ #ifndef WebFrameListenerProxy_h #define WebFrameListenerProxy_h +#include "APINavigation.h" #include "APIObject.h" #include <WebCore/FrameLoaderTypes.h> #include <wtf/PassRefPtr.h> +#include <wtf/Ref.h> #include <wtf/RefPtr.h> namespace WebKit { class WebFrameProxy; -class WebFrameListenerProxy : public APIObject { +class WebFrameListenerProxy : public API::Object { public: virtual ~WebFrameListenerProxy(); void invalidate(); uint64_t listenerID() const { return m_listenerID; } + API::Navigation* navigation() { return m_navigation.get(); } + void setNavigation(Ref<API::Navigation>&& navigation) { m_navigation = WTFMove(navigation); } + protected: WebFrameListenerProxy(WebFrameProxy*, uint64_t listenerID); @@ -50,6 +55,7 @@ protected: private: RefPtr<WebFrameProxy> m_frame; uint64_t m_listenerID; + RefPtr<API::Navigation> m_navigation; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFramePolicyListenerProxy.h b/Source/WebKit2/UIProcess/WebFramePolicyListenerProxy.h index 779d2a56c..1b9b64c55 100644 --- a/Source/WebKit2/UIProcess/WebFramePolicyListenerProxy.h +++ b/Source/WebKit2/UIProcess/WebFramePolicyListenerProxy.h @@ -28,11 +28,17 @@ #include "WebFrameListenerProxy.h" +#if PLATFORM(COCOA) +#include "WKFoundation.h" +#endif + +#define DELEGATE_REF_COUNTING_TO_COCOA (PLATFORM(COCOA) && WK_API_ENABLED) + namespace WebKit { class WebFramePolicyListenerProxy : public WebFrameListenerProxy { public: - static const Type APIType = TypeFramePolicyListener; + static const Type APIType = Type::FramePolicyListener; static PassRefPtr<WebFramePolicyListenerProxy> create(WebFrameProxy* frame, uint64_t listenerID) { @@ -47,8 +53,14 @@ private: WebFramePolicyListenerProxy(WebFrameProxy*, uint64_t listenerID); virtual Type type() const { return APIType; } + +#if DELEGATE_REF_COUNTING_TO_COCOA + void* operator new(size_t size) { return newObject(size, APIType); } +#endif }; } // namespace WebKit +#undef DELEGATE_REF_COUNTING_TO_COCOA + #endif // WebFramePolicyListenerProxy_h diff --git a/Source/WebKit2/UIProcess/WebFrameProxy.cpp b/Source/WebKit2/UIProcess/WebFrameProxy.cpp index a57087c1f..15b8e28f2 100644 --- a/Source/WebKit2/UIProcess/WebFrameProxy.cpp +++ b/Source/WebKit2/UIProcess/WebFrameProxy.cpp @@ -27,11 +27,11 @@ #include "WebFrameProxy.h" #include "WebCertificateInfo.h" -#include "WebContext.h" #include "WebFormSubmissionListenerProxy.h" #include "WebFramePolicyListenerProxy.h" #include "WebPageMessages.h" #include "WebPageProxy.h" +#include "WebProcessPool.h" #include <WebCore/DOMImplementation.h> #include <WebCore/Image.h> #include <WebCore/MIMETypeRegistry.h> @@ -44,25 +44,24 @@ namespace WebKit { WebFrameProxy::WebFrameProxy(WebPageProxy* page, uint64_t frameID) : m_page(page) - , m_loadState(LoadStateFinished) , m_isFrameSet(false) , m_frameID(frameID) { - WebContext::statistics().wkFrameCount++; + WebProcessPool::statistics().wkFrameCount++; } WebFrameProxy::~WebFrameProxy() { - WebContext::statistics().wkFrameCount--; + WebProcessPool::statistics().wkFrameCount--; } -void WebFrameProxy::disconnect() +void WebFrameProxy::webProcessWillShutDown() { - m_page = 0; + m_page = nullptr; if (m_activeListener) { m_activeListener->invalidate(); - m_activeListener = 0; + m_activeListener = nullptr; } } @@ -74,6 +73,14 @@ bool WebFrameProxy::isMainFrame() const return this == m_page->mainFrame(); } +void WebFrameProxy::loadURL(const String& url) +{ + if (!m_page) + return; + + m_page->process().send(Messages::WebPage::LoadURLInFrame(url, m_frameID), m_page->pageID()); +} + void WebFrameProxy::stopLoading() const { if (!m_page) @@ -82,7 +89,7 @@ void WebFrameProxy::stopLoading() const if (!m_page->isValid()) return; - m_page->process()->send(Messages::WebPage::StopLoadingFrame(m_frameID), m_page->pageID()); + m_page->process().send(Messages::WebPage::StopLoadingFrame(m_frameID), m_page->pageID()); } bool WebFrameProxy::canProvideSource() const @@ -103,6 +110,11 @@ bool WebFrameProxy::isDisplayingStandaloneImageDocument() const return Image::supportsType(m_MIMEType); } +bool WebFrameProxy::isDisplayingStandaloneMediaDocument() const +{ + return MIMETypeRegistry::isSupportedMediaMIMEType(m_MIMEType); +} + bool WebFrameProxy::isDisplayingMarkupDocument() const { // FIXME: This check should be moved to somewhere in WebCore. @@ -119,54 +131,43 @@ bool WebFrameProxy::isDisplayingPDFDocument() const void WebFrameProxy::didStartProvisionalLoad(const String& url) { - ASSERT(m_provisionalURL.isEmpty()); - m_loadState = LoadStateProvisional; - m_provisionalURL = url; + m_frameLoadState.didStartProvisionalLoad(url); } void WebFrameProxy::didReceiveServerRedirectForProvisionalLoad(const String& url) { - ASSERT(m_loadState == LoadStateProvisional); - m_provisionalURL = url; + m_frameLoadState.didReceiveServerRedirectForProvisionalLoad(url); } void WebFrameProxy::didFailProvisionalLoad() { - ASSERT(m_loadState == LoadStateProvisional); - m_loadState = LoadStateFinished; - m_provisionalURL = String(); - m_unreachableURL = m_lastUnreachableURL; + m_frameLoadState.didFailProvisionalLoad(); } -void WebFrameProxy::didCommitLoad(const String& contentType, const PlatformCertificateInfo& certificateInfo) +void WebFrameProxy::didCommitLoad(const String& contentType, WebCertificateInfo& certificateInfo, bool containsPluginDocument) { - ASSERT(m_loadState == LoadStateProvisional); - m_loadState = LoadStateCommitted; - m_url = m_provisionalURL; - m_provisionalURL = String(); + m_frameLoadState.didCommitLoad(); + m_title = String(); m_MIMEType = contentType; m_isFrameSet = false; - m_certificateInfo = WebCertificateInfo::create(certificateInfo); + m_certificateInfo = &certificateInfo; + m_containsPluginDocument = containsPluginDocument; } void WebFrameProxy::didFinishLoad() { - ASSERT(m_loadState == LoadStateCommitted); - ASSERT(m_provisionalURL.isEmpty()); - m_loadState = LoadStateFinished; + m_frameLoadState.didFinishLoad(); } void WebFrameProxy::didFailLoad() { - ASSERT(m_loadState == LoadStateCommitted); - ASSERT(m_provisionalURL.isEmpty()); - m_loadState = LoadStateFinished; + m_frameLoadState.didFailLoad(); } void WebFrameProxy::didSameDocumentNavigation(const String& url) { - m_url = url; + m_frameLoadState.didSameDocumentNotification(url); } void WebFrameProxy::didChangeTitle(const String& title) @@ -174,66 +175,86 @@ void WebFrameProxy::didChangeTitle(const String& title) m_title = title; } -void WebFrameProxy::receivedPolicyDecision(WebCore::PolicyAction action, uint64_t listenerID) +void WebFrameProxy::receivedPolicyDecision(WebCore::PolicyAction action, uint64_t listenerID, API::Navigation* navigation) { if (!m_page) return; ASSERT(m_activeListener); ASSERT(m_activeListener->listenerID() == listenerID); - m_page->receivedPolicyDecision(action, this, listenerID); + m_page->receivedPolicyDecision(action, this, listenerID, navigation); } -WebFramePolicyListenerProxy* WebFrameProxy::setUpPolicyListenerProxy(uint64_t listenerID) +WebFramePolicyListenerProxy& WebFrameProxy::setUpPolicyListenerProxy(uint64_t listenerID) { if (m_activeListener) m_activeListener->invalidate(); m_activeListener = WebFramePolicyListenerProxy::create(this, listenerID); - return static_cast<WebFramePolicyListenerProxy*>(m_activeListener.get()); + return *static_cast<WebFramePolicyListenerProxy*>(m_activeListener.get()); } -WebFormSubmissionListenerProxy* WebFrameProxy::setUpFormSubmissionListenerProxy(uint64_t listenerID) +WebFormSubmissionListenerProxy& WebFrameProxy::setUpFormSubmissionListenerProxy(uint64_t listenerID) { if (m_activeListener) m_activeListener->invalidate(); m_activeListener = WebFormSubmissionListenerProxy::create(this, listenerID); - return static_cast<WebFormSubmissionListenerProxy*>(m_activeListener.get()); + return *static_cast<WebFormSubmissionListenerProxy*>(m_activeListener.get()); } -void WebFrameProxy::getWebArchive(PassRefPtr<DataCallback> callback) +void WebFrameProxy::getWebArchive(std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { if (!m_page) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - m_page->getWebArchiveOfFrame(this, callback); + m_page->getWebArchiveOfFrame(this, callbackFunction); } -void WebFrameProxy::getMainResourceData(PassRefPtr<DataCallback> callback) +void WebFrameProxy::getMainResourceData(std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { if (!m_page) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - m_page->getMainResourceDataOfFrame(this, callback); + m_page->getMainResourceDataOfFrame(this, callbackFunction); } -void WebFrameProxy::getResourceData(WebURL* resourceURL, PassRefPtr<DataCallback> callback) +void WebFrameProxy::getResourceData(API::URL* resourceURL, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { if (!m_page) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - m_page->getResourceDataFromFrame(this, resourceURL, callback); + m_page->getResourceDataFromFrame(this, resourceURL, callbackFunction); } void WebFrameProxy::setUnreachableURL(const String& unreachableURL) { - m_lastUnreachableURL = m_unreachableURL; - m_unreachableURL = unreachableURL; + m_frameLoadState.setUnreachableURL(unreachableURL); +} + +#if ENABLE(CONTENT_FILTERING) +bool WebFrameProxy::didHandleContentFilterUnblockNavigation(const WebCore::ResourceRequest& request) +{ + if (!m_contentFilterUnblockHandler.canHandleRequest(request)) { + m_contentFilterUnblockHandler = { }; + return false; + } + + RefPtr<WebPageProxy> page { m_page }; + ASSERT(page); + m_contentFilterUnblockHandler.requestUnblockAsync([page](bool unblocked) { + if (unblocked) { + const bool reloadFromOrigin = false; + const bool contentBlockersEnabled = true; + page->reload(reloadFromOrigin, contentBlockersEnabled); + } + }); + return true; } +#endif } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFrameProxy.h b/Source/WebKit2/UIProcess/WebFrameProxy.h index 0bee666ff..2ee80489b 100644 --- a/Source/WebKit2/UIProcess/WebFrameProxy.h +++ b/Source/WebKit2/UIProcess/WebFrameProxy.h @@ -27,7 +27,7 @@ #define WebFrameProxy_h #include "APIObject.h" -#include "ImmutableArray.h" +#include "FrameLoadState.h" #include "GenericCallback.h" #include "WebFrameListenerProxy.h" #include <WebCore/FrameLoaderTypes.h> @@ -35,23 +35,29 @@ #include <wtf/PassRefPtr.h> #include <wtf/text/WTFString.h> -namespace CoreIPC { +#if ENABLE(CONTENT_FILTERING) +#include <WebCore/ContentFilterUnblockHandler.h> +#endif + +namespace API { +class Navigation; +} + + +namespace IPC { class ArgumentDecoder; class Connection; } namespace WebKit { - -class ImmutableArray; -class PlatformCertificateInfo; class WebCertificateInfo; class WebFormSubmissionListenerProxy; class WebFramePolicyListenerProxy; class WebPageProxy; -typedef GenericCallback<WKDataRef> DataCallback; +typedef GenericCallback<API::Data*> DataCallback; -class WebFrameProxy : public TypedAPIObject<APIObject::TypeFrame> { +class WebFrameProxy : public API::ObjectImpl<API::Object::Type::Frame> { public: static PassRefPtr<WebFrameProxy> create(WebPageProxy* page, uint64_t frameID) { @@ -60,33 +66,29 @@ public: virtual ~WebFrameProxy(); - enum LoadState { - LoadStateProvisional, - LoadStateCommitted, - LoadStateFinished - }; - uint64_t frameID() const { return m_frameID; } WebPageProxy* page() const { return m_page; } - void disconnect(); + void webProcessWillShutDown(); bool isMainFrame() const; void setIsFrameSet(bool value) { m_isFrameSet = value; } bool isFrameSet() const { return m_isFrameSet; } - LoadState loadState() const { return m_loadState; } - + FrameLoadState& frameLoadState() { return m_frameLoadState; } + + void loadURL(const String&); void stopLoading() const; - const String& url() const { return m_url; } - const String& provisionalURL() const { return m_provisionalURL; } + const String& url() const { return m_frameLoadState.url(); } + const String& provisionalURL() const { return m_frameLoadState.provisionalURL(); } void setUnreachableURL(const String&); - const String& unreachableURL() const { return m_unreachableURL; } + const String& unreachableURL() const { return m_frameLoadState.unreachableURL(); } const String& mimeType() const { return m_MIMEType; } + bool containsPluginDocument() const { return m_containsPluginDocument; } const String& title() const { return m_title; } @@ -96,42 +98,51 @@ public: bool canShowMIMEType(const String& mimeType) const; bool isDisplayingStandaloneImageDocument() const; + bool isDisplayingStandaloneMediaDocument() const; bool isDisplayingMarkupDocument() const; bool isDisplayingPDFDocument() const; - void getWebArchive(PassRefPtr<DataCallback>); - void getMainResourceData(PassRefPtr<DataCallback>); - void getResourceData(WebURL*, PassRefPtr<DataCallback>); + void getWebArchive(std::function<void (API::Data*, CallbackBase::Error)>); + void getMainResourceData(std::function<void (API::Data*, CallbackBase::Error)>); + void getResourceData(API::URL*, std::function<void (API::Data*, CallbackBase::Error)>); void didStartProvisionalLoad(const String& url); void didReceiveServerRedirectForProvisionalLoad(const String& url); void didFailProvisionalLoad(); - void didCommitLoad(const String& contentType, const PlatformCertificateInfo&); + void didCommitLoad(const String& contentType, WebCertificateInfo&, bool containsPluginDocument); void didFinishLoad(); void didFailLoad(); void didSameDocumentNavigation(const String&); // eg. anchor navigation, session state change. void didChangeTitle(const String&); // Policy operations. - void receivedPolicyDecision(WebCore::PolicyAction, uint64_t listenerID); - WebFramePolicyListenerProxy* setUpPolicyListenerProxy(uint64_t listenerID); - WebFormSubmissionListenerProxy* setUpFormSubmissionListenerProxy(uint64_t listenerID); + void receivedPolicyDecision(WebCore::PolicyAction, uint64_t listenerID, API::Navigation* = nullptr); + WebFramePolicyListenerProxy& setUpPolicyListenerProxy(uint64_t listenerID); + WebFormSubmissionListenerProxy& setUpFormSubmissionListenerProxy(uint64_t listenerID); + +#if ENABLE(CONTENT_FILTERING) + void contentFilterDidBlockLoad(WebCore::ContentFilterUnblockHandler contentFilterUnblockHandler) { m_contentFilterUnblockHandler = WTFMove(contentFilterUnblockHandler); } + bool didHandleContentFilterUnblockNavigation(const WebCore::ResourceRequest&); +#endif private: WebFrameProxy(WebPageProxy* page, uint64_t frameID); WebPageProxy* m_page; - LoadState m_loadState; - String m_url; - String m_provisionalURL; - String m_unreachableURL; - String m_lastUnreachableURL; + + FrameLoadState m_frameLoadState; + String m_MIMEType; String m_title; bool m_isFrameSet; + bool m_containsPluginDocument { false }; RefPtr<WebCertificateInfo> m_certificateInfo; RefPtr<WebFrameListenerProxy> m_activeListener; uint64_t m_frameID; + +#if ENABLE(CONTENT_FILTERING) + WebCore::ContentFilterUnblockHandler m_contentFilterUnblockHandler; +#endif }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp index 58fbb5973..4817f3fb0 100644 --- a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.cpp @@ -28,64 +28,60 @@ #if ENABLE(FULLSCREEN_API) -#include "WebContext.h" #include "WebFullScreenManagerMessages.h" #include "WebFullScreenManagerProxyMessages.h" +#include "WebPageProxy.h" +#include "WebProcessProxy.h" +#include <WebCore/IntRect.h> + +using namespace WebCore; namespace WebKit { -PassRefPtr<WebFullScreenManagerProxy> WebFullScreenManagerProxy::create(WebPageProxy* page) +PassRefPtr<WebFullScreenManagerProxy> WebFullScreenManagerProxy::create(WebPageProxy& page, WebFullScreenManagerProxyClient& client) { - return adoptRef(new WebFullScreenManagerProxy(page)); + return adoptRef(new WebFullScreenManagerProxy(page, client)); } -WebFullScreenManagerProxy::WebFullScreenManagerProxy(WebPageProxy* page) - : m_page(page) - , m_webView(0) -#if PLATFORM(EFL) - , m_hasRequestedFullScreen(false) -#endif +WebFullScreenManagerProxy::WebFullScreenManagerProxy(WebPageProxy& page, WebFullScreenManagerProxyClient& client) + : m_page(&page) + , m_client(&client) { - m_page->process()->addMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID(), this); + m_page->process().addMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID(), *this); } WebFullScreenManagerProxy::~WebFullScreenManagerProxy() { } -void WebFullScreenManagerProxy::setWebView(PlatformWebView* webView) -{ - m_webView = webView; -} - void WebFullScreenManagerProxy::willEnterFullScreen() { - m_page->process()->send(Messages::WebFullScreenManager::WillEnterFullScreen(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::WillEnterFullScreen(), m_page->pageID()); } void WebFullScreenManagerProxy::didEnterFullScreen() { - m_page->process()->send(Messages::WebFullScreenManager::DidEnterFullScreen(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::DidEnterFullScreen(), m_page->pageID()); } void WebFullScreenManagerProxy::willExitFullScreen() { - m_page->process()->send(Messages::WebFullScreenManager::WillExitFullScreen(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::WillExitFullScreen(), m_page->pageID()); } void WebFullScreenManagerProxy::didExitFullScreen() { - m_page->process()->send(Messages::WebFullScreenManager::DidExitFullScreen(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::DidExitFullScreen(), m_page->pageID()); } void WebFullScreenManagerProxy::setAnimatingFullScreen(bool animating) { - m_page->process()->send(Messages::WebFullScreenManager::SetAnimatingFullScreen(animating), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::SetAnimatingFullScreen(animating), m_page->pageID()); } void WebFullScreenManagerProxy::requestExitFullScreen() { - m_page->process()->send(Messages::WebFullScreenManager::RequestExitFullScreen(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::RequestExitFullScreen(), m_page->pageID()); } void WebFullScreenManagerProxy::supportsFullScreen(bool withKeyboard, bool& supports) @@ -95,12 +91,65 @@ void WebFullScreenManagerProxy::supportsFullScreen(bool withKeyboard, bool& supp void WebFullScreenManagerProxy::saveScrollPosition() { - m_page->process()->send(Messages::WebFullScreenManager::SaveScrollPosition(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::SaveScrollPosition(), m_page->pageID()); } void WebFullScreenManagerProxy::restoreScrollPosition() { - m_page->process()->send(Messages::WebFullScreenManager::RestoreScrollPosition(), m_page->pageID()); + m_page->process().send(Messages::WebFullScreenManager::RestoreScrollPosition(), m_page->pageID()); +} + +void WebFullScreenManagerProxy::invalidate() +{ + m_page->process().removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); + + if (!m_client) + return; + + m_client->closeFullScreenManager(); + m_client = nullptr; +} + +void WebFullScreenManagerProxy::close() +{ + if (!m_client) + return; + m_client->closeFullScreenManager(); +} + +bool WebFullScreenManagerProxy::isFullScreen() +{ + if (!m_client) + return false; + return m_client->isFullScreen(); +} + +void WebFullScreenManagerProxy::enterFullScreen() +{ + if (!m_client) + return; + m_client->enterFullScreen(); +} + +void WebFullScreenManagerProxy::exitFullScreen() +{ + if (!m_client) + return; + m_client->exitFullScreen(); +} + +void WebFullScreenManagerProxy::beganEnterFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) +{ + if (!m_client) + return; + m_client->beganEnterFullScreen(initialFrame, finalFrame); +} + +void WebFullScreenManagerProxy::beganExitFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) +{ + if (!m_client) + return; + m_client->beganExitFullScreen(initialFrame, finalFrame); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h index 9dab61c3c..864531780 100644 --- a/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebFullScreenManagerProxy.h @@ -37,37 +37,29 @@ namespace WebCore { class IntRect; } -#if PLATFORM(MAC) -OBJC_CLASS WKView; -#elif PLATFORM(GTK) -typedef struct _WebKitWebViewBase WebKitWebViewBase; -#elif PLATFORM(QT) -class QQuickWebView; -#endif - namespace WebKit { - -#if PLATFORM(MAC) -typedef WKView PlatformWebView; -#elif PLATFORM(QT) -typedef QQuickWebView PlatformWebView; -#elif PLATFORM(GTK) -typedef WebKitWebViewBase PlatformWebView; -#elif PLATFORM(EFL) -typedef Evas_Object PlatformWebView; -#endif class WebPageProxy; -class LayerTreeContext; -class WebFullScreenManagerProxy : public RefCounted<WebFullScreenManagerProxy>, public CoreIPC::MessageReceiver { +class WebFullScreenManagerProxyClient { public: - static PassRefPtr<WebFullScreenManagerProxy> create(WebPageProxy*); + virtual ~WebFullScreenManagerProxyClient() { } + + virtual void closeFullScreenManager() = 0; + virtual bool isFullScreen() = 0; + virtual void enterFullScreen() = 0; + virtual void exitFullScreen() = 0; + virtual void beganEnterFullScreen(const WebCore::IntRect& initialFrame, const WebCore::IntRect& finalFrame) = 0; + virtual void beganExitFullScreen(const WebCore::IntRect& initialFrame, const WebCore::IntRect& finalFrame) = 0; +}; + +class WebFullScreenManagerProxy : public RefCounted<WebFullScreenManagerProxy>, public IPC::MessageReceiver { +public: + static PassRefPtr<WebFullScreenManagerProxy> create(WebPageProxy&, WebFullScreenManagerProxyClient&); virtual ~WebFullScreenManagerProxy(); void invalidate(); - void setWebView(PlatformWebView*); bool isFullScreen(); void close(); @@ -81,7 +73,7 @@ public: void restoreScrollPosition(); private: - explicit WebFullScreenManagerProxy(WebPageProxy*); + explicit WebFullScreenManagerProxy(WebPageProxy&, WebFullScreenManagerProxyClient&); void supportsFullScreen(bool withKeyboard, bool&); void enterFullScreen(); @@ -89,15 +81,11 @@ private: void beganEnterFullScreen(const WebCore::IntRect& initialFrame, const WebCore::IntRect& finalFrame); void beganExitFullScreen(const WebCore::IntRect& initialFrame, const WebCore::IntRect& finalFrame); - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; WebPageProxy* m_page; - PlatformWebView* m_webView; - -#if PLATFORM(EFL) - bool m_hasRequestedFullScreen; -#endif + WebFullScreenManagerProxyClient* m_client; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp index 5f5408024..740be469b 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.cpp @@ -26,9 +26,9 @@ #include "config.h" #include "WebGeolocationManagerProxy.h" -#include "WebContext.h" #include "WebGeolocationManagerMessages.h" #include "WebGeolocationManagerProxyMessages.h" +#include "WebProcessPool.h" namespace WebKit { @@ -37,81 +37,116 @@ const char* WebGeolocationManagerProxy::supplementName() return "WebGeolocationManagerProxy"; } -PassRefPtr<WebGeolocationManagerProxy> WebGeolocationManagerProxy::create(WebContext* context) +PassRefPtr<WebGeolocationManagerProxy> WebGeolocationManagerProxy::create(WebProcessPool* processPool) { - return adoptRef(new WebGeolocationManagerProxy(context)); + return adoptRef(new WebGeolocationManagerProxy(processPool)); } -WebGeolocationManagerProxy::WebGeolocationManagerProxy(WebContext* context) - : WebContextSupplement(context) - , m_isUpdating(false) +WebGeolocationManagerProxy::WebGeolocationManagerProxy(WebProcessPool* processPool) + : WebContextSupplement(processPool) { - WebContextSupplement::context()->addMessageReceiver(Messages::WebGeolocationManagerProxy::messageReceiverName(), this); + WebContextSupplement::processPool()->addMessageReceiver(Messages::WebGeolocationManagerProxy::messageReceiverName(), *this); } -WebGeolocationManagerProxy::~WebGeolocationManagerProxy() -{ -} - -void WebGeolocationManagerProxy::initializeProvider(const WKGeolocationProvider* provider) +void WebGeolocationManagerProxy::initializeProvider(const WKGeolocationProviderBase* provider) { m_provider.initialize(provider); } // WebContextSupplement -void WebGeolocationManagerProxy::contextDestroyed() +void WebGeolocationManagerProxy::processPoolDestroyed() { - stopUpdating(); + bool wasUpdating = isUpdating(); + m_updateRequesters.clear(); + + ASSERT(!isUpdating()); + if (wasUpdating) + m_provider.stopUpdating(this); } -void WebGeolocationManagerProxy::processDidClose(WebProcessProxy*) +void WebGeolocationManagerProxy::processDidClose(WebProcessProxy* webProcessProxy) { - stopUpdating(); + removeRequester(webProcessProxy); } void WebGeolocationManagerProxy::refWebContextSupplement() { - APIObject::ref(); + API::Object::ref(); } void WebGeolocationManagerProxy::derefWebContextSupplement() { - APIObject::deref(); + API::Object::deref(); } void WebGeolocationManagerProxy::providerDidChangePosition(WebGeolocationPosition* position) { - if (!context()) + if (!processPool()) return; - context()->sendToAllProcesses(Messages::WebGeolocationManager::DidChangePosition(position->data())); + processPool()->sendToAllProcesses(Messages::WebGeolocationManager::DidChangePosition(position->data())); } void WebGeolocationManagerProxy::providerDidFailToDeterminePosition(const String& errorMessage) { - if (!context()) + if (!processPool()) return; - context()->sendToAllProcesses(Messages::WebGeolocationManager::DidFailToDeterminePosition(errorMessage)); + processPool()->sendToAllProcesses(Messages::WebGeolocationManager::DidFailToDeterminePosition(errorMessage)); } -void WebGeolocationManagerProxy::startUpdating() +#if PLATFORM(IOS) +void WebGeolocationManagerProxy::resetPermissions() { - if (m_isUpdating) - return; + processPool()->sendToAllProcesses(Messages::WebGeolocationManager::ResetPermissions()); +} +#endif - m_provider.startUpdating(this); - m_isUpdating = true; +void WebGeolocationManagerProxy::startUpdating(IPC::Connection& connection) +{ + bool wasUpdating = isUpdating(); + m_updateRequesters.add(connection.client()); + if (!wasUpdating) { + m_provider.setEnableHighAccuracy(this, isHighAccuracyEnabled()); + m_provider.startUpdating(this); + } } -void WebGeolocationManagerProxy::stopUpdating() +void WebGeolocationManagerProxy::stopUpdating(IPC::Connection& connection) { - if (!m_isUpdating) - return; + removeRequester(connection.client()); +} + +void WebGeolocationManagerProxy::removeRequester(const IPC::Connection::Client* client) +{ + bool wasUpdating = isUpdating(); + bool highAccuracyWasEnabled = isHighAccuracyEnabled(); + + m_highAccuracyRequesters.remove(client); + m_updateRequesters.remove(client); + + if (wasUpdating && !isUpdating()) + m_provider.stopUpdating(this); + else { + bool highAccuracyShouldBeEnabled = isHighAccuracyEnabled(); + if (highAccuracyShouldBeEnabled != highAccuracyWasEnabled) + m_provider.setEnableHighAccuracy(this, highAccuracyShouldBeEnabled); + } +} + +void WebGeolocationManagerProxy::setEnableHighAccuracy(IPC::Connection& connection, bool enabled) +{ + bool highAccuracyWasEnabled = isHighAccuracyEnabled(); + + if (enabled) + m_highAccuracyRequesters.add(connection.client()); + else + m_highAccuracyRequesters.remove(connection.client()); - m_provider.stopUpdating(this); - m_isUpdating = false; + bool highAccuracyShouldBeEnabled = isHighAccuracyEnabled(); + if (isUpdating() && highAccuracyWasEnabled != highAccuracyShouldBeEnabled) + m_provider.setEnableHighAccuracy(this, highAccuracyShouldBeEnabled); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h index a2d97c6ea..fa50846a5 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h +++ b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.h @@ -27,47 +27,57 @@ #define WebGeolocationManagerProxy_h #include "APIObject.h" +#include "Connection.h" #include "MessageReceiver.h" #include "WebContextSupplement.h" #include "WebGeolocationProvider.h" +#include <wtf/HashSet.h> #include <wtf/text/WTFString.h> namespace WebKit { -class WebContext; class WebGeolocationPosition; +class WebProcessPool; -class WebGeolocationManagerProxy : public TypedAPIObject<APIObject::TypeGeolocationManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { +class WebGeolocationManagerProxy : public API::ObjectImpl<API::Object::Type::GeolocationManager>, public WebContextSupplement, private IPC::MessageReceiver { public: static const char* supplementName(); - static PassRefPtr<WebGeolocationManagerProxy> create(WebContext*); - virtual ~WebGeolocationManagerProxy(); + static PassRefPtr<WebGeolocationManagerProxy> create(WebProcessPool*); - void initializeProvider(const WKGeolocationProvider*); + void initializeProvider(const WKGeolocationProviderBase*); void providerDidChangePosition(WebGeolocationPosition*); void providerDidFailToDeterminePosition(const String& errorMessage = String()); +#if PLATFORM(IOS) + void resetPermissions(); +#endif - using APIObject::ref; - using APIObject::deref; + using API::Object::ref; + using API::Object::deref; private: - explicit WebGeolocationManagerProxy(WebContext*); + explicit WebGeolocationManagerProxy(WebProcessPool*); // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; + virtual void processPoolDestroyed() override; + virtual void processDidClose(WebProcessProxy*) override; + virtual void refWebContextSupplement() override; + virtual void derefWebContextSupplement() override; - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; - void startUpdating(); - void stopUpdating(); + bool isUpdating() const { return !m_updateRequesters.isEmpty(); } + bool isHighAccuracyEnabled() const { return !m_highAccuracyRequesters.isEmpty(); } - bool m_isUpdating; + void startUpdating(IPC::Connection&); + void stopUpdating(IPC::Connection&); + void removeRequester(const IPC::Connection::Client*); + void setEnableHighAccuracy(IPC::Connection&, bool); + + HashSet<const IPC::Connection::Client*> m_updateRequesters; + HashSet<const IPC::Connection::Client*> m_highAccuracyRequesters; WebGeolocationProvider m_provider; }; diff --git a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.messages.in index fe5a27300..9e08a6a6e 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebGeolocationManagerProxy.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2011 Apple Inc. All rights reserved. +# Copyright (C) 2011, 2013 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -21,6 +21,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. messages -> WebGeolocationManagerProxy { - StartUpdating(); - StopUpdating(); + StartUpdating() WantsConnection + StopUpdating() WantsConnection + SetEnableHighAccuracy(bool enabled) WantsConnection } diff --git a/Source/WebKit2/UIProcess/WebGeolocationProvider.cpp b/Source/WebKit2/UIProcess/WebGeolocationProvider.cpp index c382235c7..cc5ddc183 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationProvider.cpp +++ b/Source/WebKit2/UIProcess/WebGeolocationProvider.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -36,7 +36,7 @@ void WebGeolocationProvider::startUpdating(WebGeolocationManagerProxy* geolocati if (!m_client.startUpdating) return; - m_client.startUpdating(toAPI(geolocationManager), m_client.clientInfo); + m_client.startUpdating(toAPI(geolocationManager), m_client.base.clientInfo); } void WebGeolocationProvider::stopUpdating(WebGeolocationManagerProxy* geolocationManager) @@ -44,7 +44,15 @@ void WebGeolocationProvider::stopUpdating(WebGeolocationManagerProxy* geolocatio if (!m_client.stopUpdating) return; - m_client.stopUpdating(toAPI(geolocationManager), m_client.clientInfo); + m_client.stopUpdating(toAPI(geolocationManager), m_client.base.clientInfo); +} + +void WebGeolocationProvider::setEnableHighAccuracy(WebGeolocationManagerProxy* geolocationManager, bool enabled) +{ + if (!m_client.setEnableHighAccuracy) + return; + + m_client.setEnableHighAccuracy(toAPI(geolocationManager), enabled, m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebGeolocationProvider.h b/Source/WebKit2/UIProcess/WebGeolocationProvider.h index 1776879d5..8c3392962 100644 --- a/Source/WebKit2/UIProcess/WebGeolocationProvider.h +++ b/Source/WebKit2/UIProcess/WebGeolocationProvider.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,14 +30,21 @@ #include "WKGeolocationManager.h" #include <wtf/Forward.h> +namespace API { +template<> struct ClientTraits<WKGeolocationProviderBase> { + typedef std::tuple<WKGeolocationProviderV0, WKGeolocationProviderV1> Versions; +}; +} + namespace WebKit { class WebGeolocationManagerProxy; -class WebGeolocationProvider : public APIClient<WKGeolocationProvider, kWKGeolocationProviderCurrentVersion> { +class WebGeolocationProvider : public API::Client<WKGeolocationProviderBase> { public: void startUpdating(WebGeolocationManagerProxy*); void stopUpdating(WebGeolocationManagerProxy*); + void setEnableHighAccuracy(WebGeolocationManagerProxy*, bool); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebGrammarDetail.cpp b/Source/WebKit2/UIProcess/WebGrammarDetail.cpp index 8df528cd9..0fe1bfb31 100644 --- a/Source/WebKit2/UIProcess/WebGrammarDetail.cpp +++ b/Source/WebKit2/UIProcess/WebGrammarDetail.cpp @@ -26,13 +26,13 @@ #include "config.h" #include "WebGrammarDetail.h" -#include "ImmutableArray.h" +#include "APIArray.h" +#include "APIString.h" #include "WKGrammarDetail.h" -#include "WebString.h" namespace WebKit { -PassRefPtr<WebGrammarDetail> WebGrammarDetail::create(int location, int length, ImmutableArray* guesses, const String& userDescription) +PassRefPtr<WebGrammarDetail> WebGrammarDetail::create(int location, int length, API::Array* guesses, const String& userDescription) { return adoptRef(new WebGrammarDetail(location, length, guesses, userDescription)); } @@ -42,7 +42,7 @@ PassRefPtr<WebGrammarDetail> WebGrammarDetail::create(const WebCore::GrammarDeta return adoptRef(new WebGrammarDetail(grammarDetail)); } -WebGrammarDetail::WebGrammarDetail(int location, int length, ImmutableArray* guesses, const String& userDescription) +WebGrammarDetail::WebGrammarDetail(int location, int length, API::Array* guesses, const String& userDescription) { m_grammarDetail.location = location; m_grammarDetail.length = length; @@ -50,18 +50,18 @@ WebGrammarDetail::WebGrammarDetail(int location, int length, ImmutableArray* gue size_t numGuesses = guesses->size(); m_grammarDetail.guesses.reserveCapacity(numGuesses); for (size_t i = 0; i < numGuesses; ++i) - m_grammarDetail.guesses.uncheckedAppend(guesses->at<WebString>(i)->string()); + m_grammarDetail.guesses.uncheckedAppend(guesses->at<API::String>(i)->string()); m_grammarDetail.userDescription = userDescription; } -PassRefPtr<ImmutableArray> WebGrammarDetail::guesses() const +Ref<API::Array> WebGrammarDetail::guesses() const { size_t numGuesses = m_grammarDetail.guesses.size(); - Vector<RefPtr<APIObject> > wkGuesses(numGuesses); + Vector<RefPtr<API::Object> > wkGuesses(numGuesses); for (unsigned i = 0; i < numGuesses; ++i) - wkGuesses[i] = WebString::create(m_grammarDetail.guesses[i]); - return ImmutableArray::adopt(wkGuesses); + wkGuesses[i] = API::String::create(m_grammarDetail.guesses[i]); + return API::Array::create(WTFMove(wkGuesses)); } WebGrammarDetail::WebGrammarDetail(const WebCore::GrammarDetail& grammarDetail) diff --git a/Source/WebKit2/UIProcess/WebGrammarDetail.h b/Source/WebKit2/UIProcess/WebGrammarDetail.h index 0460740e6..7d1770570 100644 --- a/Source/WebKit2/UIProcess/WebGrammarDetail.h +++ b/Source/WebKit2/UIProcess/WebGrammarDetail.h @@ -26,6 +26,7 @@ #ifndef WebGrammarDetail_h #define WebGrammarDetail_h +#include "APIArray.h" #include "APIObject.h" #include <WebCore/TextCheckerClient.h> #include <wtf/Forward.h> @@ -33,22 +34,20 @@ namespace WebKit { -class ImmutableArray; - -class WebGrammarDetail : public TypedAPIObject<APIObject::TypeGrammarDetail> { +class WebGrammarDetail : public API::ObjectImpl<API::Object::Type::GrammarDetail> { public: - static PassRefPtr<WebGrammarDetail> create(int location, int length, ImmutableArray* guesses, const String& userDescription); + static PassRefPtr<WebGrammarDetail> create(int location, int length, API::Array* guesses, const String& userDescription); static PassRefPtr<WebGrammarDetail> create(const WebCore::GrammarDetail&); int location() const { return m_grammarDetail.location; } int length() const { return m_grammarDetail.length; } - PassRefPtr<ImmutableArray> guesses() const; + Ref<API::Array> guesses() const; const String& userDescription() const { return m_grammarDetail.userDescription; } const WebCore::GrammarDetail& grammarDetail() { return m_grammarDetail; } private: - WebGrammarDetail(int location, int length, ImmutableArray* guesses, const String& userDescription); + WebGrammarDetail(int location, int length, API::Array* guesses, const String& userDescription); explicit WebGrammarDetail(const WebCore::GrammarDetail&); WebCore::GrammarDetail m_grammarDetail; diff --git a/Source/WebKit2/UIProcess/WebHistoryClient.cpp b/Source/WebKit2/UIProcess/WebHistoryClient.cpp deleted file mode 100644 index ca6cf9446..000000000 --- a/Source/WebKit2/UIProcess/WebHistoryClient.cpp +++ /dev/null @@ -1,78 +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 "WebHistoryClient.h" - -#include "WKAPICast.h" -#include "WebNavigationData.h" -#include <wtf/RefPtr.h> - -using namespace WebCore; - -namespace WebKit { - -void WebHistoryClient::didNavigateWithNavigationData(WebContext* context, WebPageProxy* page, const WebNavigationDataStore& navigationDataStore, WebFrameProxy* frame) -{ - if (!m_client.didNavigateWithNavigationData) - return; - - RefPtr<WebNavigationData> navigationData = WebNavigationData::create(navigationDataStore); - m_client.didNavigateWithNavigationData(toAPI(context), toAPI(page), toAPI(navigationData.get()), toAPI(frame), m_client.clientInfo); -} - -void WebHistoryClient::didPerformClientRedirect(WebContext* context, WebPageProxy* page, const String& sourceURL, const String& destinationURL, WebFrameProxy* frame) -{ - if (!m_client.didPerformClientRedirect) - return; - - m_client.didPerformClientRedirect(toAPI(context), toAPI(page), toURLRef(sourceURL.impl()), toURLRef(destinationURL.impl()), toAPI(frame), m_client.clientInfo); -} - -void WebHistoryClient::didPerformServerRedirect(WebContext* context, WebPageProxy* page, const String& sourceURL, const String& destinationURL, WebFrameProxy* frame) -{ - if (!m_client.didPerformServerRedirect) - return; - - m_client.didPerformServerRedirect(toAPI(context), toAPI(page), toURLRef(sourceURL.impl()), toURLRef(destinationURL.impl()), toAPI(frame), m_client.clientInfo); -} - -void WebHistoryClient::didUpdateHistoryTitle(WebContext* context, WebPageProxy* page, const String& title, const String& url, WebFrameProxy* frame) -{ - if (!m_client.didUpdateHistoryTitle) - return; - - m_client.didUpdateHistoryTitle(toAPI(context), toAPI(page), toAPI(title.impl()), toURLRef(url.impl()), toAPI(frame), m_client.clientInfo); -} - -void WebHistoryClient::populateVisitedLinks(WebContext* context) -{ - if (!m_client.populateVisitedLinks) - return; - - m_client.populateVisitedLinks(toAPI(context), m_client.clientInfo); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebIconDatabase.cpp b/Source/WebKit2/UIProcess/WebIconDatabase.cpp index 7b7f9984b..56f5da1a2 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabase.cpp +++ b/Source/WebKit2/UIProcess/WebIconDatabase.cpp @@ -26,41 +26,40 @@ #include "config.h" #include "WebIconDatabase.h" -#include "DataReference.h" #include "Logging.h" -#include "WebContext.h" #include "WebIconDatabaseMessages.h" #include "WebIconDatabaseProxyMessages.h" +#include "WebProcessPool.h" #include <WebCore/FileSystem.h> #include <WebCore/IconDatabase.h> -#include <WebCore/IconDatabaseBase.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> +#include <WebCore/Image.h> +#include <WebCore/SharedBuffer.h> using namespace WebCore; namespace WebKit { -PassRefPtr<WebIconDatabase> WebIconDatabase::create(WebContext* context) +PassRefPtr<WebIconDatabase> WebIconDatabase::create(WebProcessPool* processPool) { - return adoptRef(new WebIconDatabase(context)); + return adoptRef(new WebIconDatabase(*processPool)); } WebIconDatabase::~WebIconDatabase() { } -WebIconDatabase::WebIconDatabase(WebContext* context) - : m_webContext(context) +WebIconDatabase::WebIconDatabase(WebProcessPool& processPool) + : m_processPool(&processPool) , m_urlImportCompleted(false) , m_databaseCleanupDisabled(false) + , m_shouldDerefWhenAppropriate(false) { - m_webContext->addMessageReceiver(Messages::WebIconDatabase::messageReceiverName(), this); + m_processPool->addMessageReceiver(Messages::WebIconDatabase::messageReceiverName(), *this); } void WebIconDatabase::invalidate() { - setGlobalIconDatabase(0); + setGlobalIconDatabase(nullptr); } void WebIconDatabase::setDatabasePath(const String& path) @@ -70,15 +69,20 @@ void WebIconDatabase::setDatabasePath(const String& path) return; } - m_iconDatabaseImpl = IconDatabase::create(); + m_iconDatabaseImpl = std::make_unique<IconDatabase>(); m_iconDatabaseImpl->setClient(this); IconDatabase::delayDatabaseCleanup(); m_databaseCleanupDisabled = true; m_iconDatabaseImpl->setEnabled(true); + + // FIXME: WebIconDatabases are per-ProcessPool but ProcessPools's don't have their own notion of the current private browsing setting. + // As we clean up private browsing throughout the stack we need to clean it up here. + m_iconDatabaseImpl->setPrivateBrowsingEnabled(WebPreferences::anyPagesAreUsingPrivateBrowsing()); + if (!m_iconDatabaseImpl->open(directoryName(path), pathGetFileName(path))) { LOG_ERROR("Unable to open WebKit2 icon database on disk"); - m_iconDatabaseImpl.clear(); - setGlobalIconDatabase(0); + m_iconDatabaseImpl = nullptr; + setGlobalIconDatabase(nullptr); IconDatabase::allowDatabaseCleanup(); m_databaseCleanupDisabled = false; } @@ -97,7 +101,7 @@ void WebIconDatabase::enableDatabaseCleanup() ASSERT_NOT_REACHED(); return; } - + IconDatabase::allowDatabaseCleanup(); m_databaseCleanupDisabled = false; } @@ -121,19 +125,17 @@ void WebIconDatabase::setIconURLForPageURL(const String& iconURL, const String& m_iconDatabaseImpl->setIconURLForPageURL(iconURL, pageURL); } -void WebIconDatabase::setIconDataForIconURL(const CoreIPC::DataReference& iconData, const String& iconURL) +void WebIconDatabase::setIconDataForIconURL(const IPC::DataReference& iconData, const String& iconURL) { LOG(IconDatabase, "WK2 UIProcess setting icon data (%i bytes) for page URL %s", (int)iconData.size(), iconURL.ascii().data()); if (!m_iconDatabaseImpl) return; - - RefPtr<SharedBuffer> buffer = SharedBuffer::create(iconData.data(), iconData.size()); - m_iconDatabaseImpl->setIconDataForIconURL(buffer.release(), iconURL); + m_iconDatabaseImpl->setIconDataForIconURL(SharedBuffer::create(iconData.data(), iconData.size()), iconURL); } -void WebIconDatabase::synchronousIconDataForPageURL(const String&, CoreIPC::DataReference& iconData) +void WebIconDatabase::synchronousIconDataForPageURL(const String&, IPC::DataReference& iconData) { - iconData = CoreIPC::DataReference(); + iconData = IPC::DataReference(); } void WebIconDatabase::synchronousIconURLForPageURL(const String& pageURL, String& iconURL) @@ -142,7 +144,6 @@ void WebIconDatabase::synchronousIconURLForPageURL(const String& pageURL, String iconURL = String(); return; } - iconURL = m_iconDatabaseImpl->synchronousIconURLForPageURL(pageURL); } @@ -160,12 +161,12 @@ void WebIconDatabase::getLoadDecisionForIconURL(const String& iconURL, uint64_t { LOG(IconDatabase, "WK2 UIProcess getting load decision for icon URL %s with callback ID %lli", iconURL.ascii().data(), static_cast<long long>(callbackID)); - if (!m_webContext) + if (!m_processPool) return; if (!m_iconDatabaseImpl || !m_iconDatabaseImpl->isOpen() || iconURL.isEmpty()) { // FIXME (Multi-WebProcess): <rdar://problem/12240223> We need to know which connection to send this message to. - m_webContext->sendToAllProcesses(Messages::WebIconDatabaseProxy::ReceivedIconLoadDecision(static_cast<int>(IconLoadNo), callbackID)); + m_processPool->sendToAllProcesses(Messages::WebIconDatabaseProxy::ReceivedIconLoadDecision(static_cast<int>(IconLoadNo), callbackID)); return; } @@ -176,11 +177,11 @@ void WebIconDatabase::getLoadDecisionForIconURL(const String& iconURL, uint64_t ASSERT(!m_urlImportCompleted); m_pendingLoadDecisionURLMap.set(callbackID, iconURL); - return; + return; } // FIXME (Multi-WebProcess): <rdar://problem/12240223> We need to know which connection to send this message to. - m_webContext->sendToAllProcesses(Messages::WebIconDatabaseProxy::ReceivedIconLoadDecision((int)decision, callbackID)); + m_processPool->sendToAllProcesses(Messages::WebIconDatabaseProxy::ReceivedIconLoadDecision((int)decision, callbackID)); } void WebIconDatabase::didReceiveIconForPageURL(const String& pageURL) @@ -188,20 +189,20 @@ void WebIconDatabase::didReceiveIconForPageURL(const String& pageURL) notifyIconDataReadyForPageURL(pageURL); } -Image* WebIconDatabase::imageForPageURL(const String& pageURL, const WebCore::IntSize& iconSize) +Image* WebIconDatabase::imageForPageURL(const String& pageURL, const IntSize& iconSize) { - if (!m_webContext || !m_iconDatabaseImpl || !m_iconDatabaseImpl->isOpen() || pageURL.isEmpty()) - return 0; + if (!m_processPool || !m_iconDatabaseImpl || !m_iconDatabaseImpl->isOpen() || pageURL.isEmpty()) + return nullptr; // The WebCore IconDatabase ignores the passed in size parameter. // If that changes we'll need to rethink how this API is exposed. return m_iconDatabaseImpl->synchronousIconForPageURL(pageURL, iconSize); } -WebCore::NativeImagePtr WebIconDatabase::nativeImageForPageURL(const String& pageURL, const WebCore::IntSize& iconSize) +NativeImagePtr WebIconDatabase::nativeImageForPageURL(const String& pageURL, const IntSize& iconSize) { - if (!m_webContext || !m_iconDatabaseImpl || !m_iconDatabaseImpl->isOpen() || pageURL.isEmpty()) - return 0; + if (!m_processPool || !m_iconDatabaseImpl || !m_iconDatabaseImpl->isOpen() || pageURL.isEmpty()) + return nullptr; return m_iconDatabaseImpl->synchronousNativeIconForPageURL(pageURL, iconSize); } @@ -218,7 +219,7 @@ bool WebIconDatabase::isUrlImportCompleted() void WebIconDatabase::removeAllIcons() { - m_iconDatabaseImpl->removeAllIcons(); + m_iconDatabaseImpl->removeAllIcons(); } void WebIconDatabase::checkIntegrityBeforeOpening() @@ -232,7 +233,7 @@ void WebIconDatabase::close() m_iconDatabaseImpl->close(); } -void WebIconDatabase::initializeIconDatabaseClient(const WKIconDatabaseClient* client) +void WebIconDatabase::initializeIconDatabaseClient(const WKIconDatabaseClientBase* client) { m_iconDatabaseClient.initialize(client); } @@ -251,7 +252,7 @@ void WebIconDatabase::didImportIconDataForPageURL(const String& pageURL) void WebIconDatabase::didChangeIconForPageURL(const String& pageURL) { - m_iconDatabaseClient.didChangeIconForPageURL(this, WebURL::create(pageURL).get()); + m_iconDatabaseClient.didChangeIconForPageURL(this, API::URL::create(pageURL).ptr()); } void WebIconDatabase::didRemoveAllIcons() @@ -261,36 +262,76 @@ void WebIconDatabase::didRemoveAllIcons() void WebIconDatabase::didFinishURLImport() { - if (!m_webContext) + if (!m_processPool) return; - + ASSERT(!m_urlImportCompleted); LOG(IconDatabase, "WK2 UIProcess URL import complete, notifying all %i pending page URL load decisions", m_pendingLoadDecisionURLMap.size()); - - HashMap<uint64_t, String>::iterator i = m_pendingLoadDecisionURLMap.begin(); - HashMap<uint64_t, String>::iterator end = m_pendingLoadDecisionURLMap.end(); - for (; i != end; ++i) { - LOG(IconDatabase, "WK2 UIProcess performing delayed callback on callback ID %i for page url %s", (int)i->key, i->value.ascii().data()); - IconLoadDecision decision = m_iconDatabaseImpl->synchronousLoadDecisionForIconURL(i->value, 0); + for (auto& slot : m_pendingLoadDecisionURLMap) { + LOG(IconDatabase, "WK2 UIProcess performing delayed callback on callback ID %i for page url %s", (int)slot.key, slot.value.ascii().data()); + IconLoadDecision decision = m_iconDatabaseImpl->synchronousLoadDecisionForIconURL(slot.value, nullptr); - // Decisions should never be unknown after the inital import is complete + // Decisions should never be unknown after the inital import is complete. ASSERT(decision != IconLoadUnknown); // FIXME (Multi-WebProcess): <rdar://problem/12240223> We need to know which connection to send this message to. - m_webContext->sendToAllProcesses(Messages::WebIconDatabaseProxy::ReceivedIconLoadDecision(static_cast<int>(decision), i->key)); + m_processPool->sendToAllProcesses(Messages::WebIconDatabaseProxy::ReceivedIconLoadDecision(static_cast<int>(decision), slot.key)); } - + m_pendingLoadDecisionURLMap.clear(); - + m_urlImportCompleted = true; } +void WebIconDatabase::didClose() +{ + if (!m_shouldDerefWhenAppropriate) + return; + + deref(); +} + +void WebIconDatabase::derefWhenAppropriate() +{ + if (m_iconDatabaseImpl && m_iconDatabaseImpl->isOpen()) { + m_shouldDerefWhenAppropriate = true; + return; + } + + deref(); +} + void WebIconDatabase::notifyIconDataReadyForPageURL(const String& pageURL) { - m_iconDatabaseClient.iconDataReadyForPageURL(this, WebURL::create(pageURL).get()); + m_iconDatabaseClient.iconDataReadyForPageURL(this, API::URL::create(pageURL).ptr()); didChangeIconForPageURL(pageURL); } +void WebIconDatabase::setPrivateBrowsingEnabled(bool privateBrowsingEnabled) +{ + if (m_iconDatabaseImpl) + m_iconDatabaseImpl->setPrivateBrowsingEnabled(privateBrowsingEnabled); +} + +PassRefPtr<API::Data> WebIconDatabase::iconDataForPageURL(const String& pageURL) +{ + auto* image = imageForPageURL(pageURL); + if (!image) + return nullptr; + + SharedBuffer* sharedBuffer = image->data(); + if (!sharedBuffer) + return nullptr; + + // Balanced by deref() below. + sharedBuffer->ref(); + return API::Data::createWithoutCopying(reinterpret_cast<const unsigned char*>(sharedBuffer->data()), sharedBuffer->size(), + [](unsigned char*, const void* untypedSharedBuffer) { + // Balanced by ref() above. + static_cast<SharedBuffer*>(const_cast<void*>(untypedSharedBuffer))->deref(); + }, sharedBuffer); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebIconDatabase.h b/Source/WebKit2/UIProcess/WebIconDatabase.h index be1b3dcbc..7d8b6025f 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabase.h +++ b/Source/WebKit2/UIProcess/WebIconDatabase.h @@ -27,21 +27,14 @@ #define WebIconDatabase_h #include "APIObject.h" - #include "Connection.h" #include "WebIconDatabaseClient.h" #include <WebCore/IconDatabaseClient.h> -#include <WebCore/ImageSource.h> #include <WebCore/IntSize.h> -#include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> -#include <wtf/text/StringHash.h> - -namespace CoreIPC { -class ArgumentDecoder; -class DataReference; +#include <WebCore/NativeImagePtr.h> + +namespace API { +class Data; } namespace WebCore { @@ -51,33 +44,35 @@ class Image; namespace WebKit { -class WebContext; +class WebProcessPool; -class WebIconDatabase : public TypedAPIObject<APIObject::TypeIconDatabase>, public WebCore::IconDatabaseClient, private CoreIPC::MessageReceiver { +class WebIconDatabase : public API::ObjectImpl<API::Object::Type::IconDatabase>, private WebCore::IconDatabaseClient, private IPC::MessageReceiver { public: - static PassRefPtr<WebIconDatabase> create(WebContext*); + static PassRefPtr<WebIconDatabase> create(WebProcessPool*); virtual ~WebIconDatabase(); void invalidate(); - void clearContext() { m_webContext = 0; } + void clearProcessPool() { m_processPool = nullptr; } void setDatabasePath(const String&); void enableDatabaseCleanup(); void retainIconForPageURL(const String&); void releaseIconForPageURL(const String&); void setIconURLForPageURL(const String&, const String&); - void setIconDataForIconURL(const CoreIPC::DataReference&, const String&); - - void synchronousIconDataForPageURL(const String&, CoreIPC::DataReference&); + void setIconDataForIconURL(const IPC::DataReference&, const String&); + + void synchronousIconDataForPageURL(const String&, IPC::DataReference&); void synchronousIconURLForPageURL(const String&, String&); void synchronousIconDataKnownForIconURL(const String&, bool&) const; void synchronousLoadDecisionForIconURL(const String&, int&) const; - + void getLoadDecisionForIconURL(const String&, uint64_t callbackID); void didReceiveIconForPageURL(const String&); WebCore::Image* imageForPageURL(const String&, const WebCore::IntSize& iconSize = WebCore::IntSize(32, 32)); WebCore::NativeImagePtr nativeImageForPageURL(const String&, const WebCore::IntSize& iconSize = WebCore::IntSize(32, 32)); + PassRefPtr<API::Data> iconDataForPageURL(const String& pageURL); + bool isOpen(); bool isUrlImportCompleted(); @@ -85,29 +80,38 @@ public: void checkIntegrityBeforeOpening(); void close(); - void initializeIconDatabaseClient(const WKIconDatabaseClient*); + void initializeIconDatabaseClient(const WKIconDatabaseClientBase*); + + void setPrivateBrowsingEnabled(bool); + + // Called when the WebProcessPool is through with this WebIconDatabase but the + // WebCore::IconDatabase possibly isn't done shutting down. + // In that case this WebIconDatabase will deref() itself when the time is right. + void derefWhenAppropriate(); private: - WebIconDatabase(WebContext*); + explicit WebIconDatabase(WebProcessPool&); // WebCore::IconDatabaseClient - virtual void didImportIconURLForPageURL(const String&); - virtual void didImportIconDataForPageURL(const String&); - virtual void didChangeIconForPageURL(const String&); - virtual void didRemoveAllIcons(); - virtual void didFinishURLImport(); + virtual void didImportIconURLForPageURL(const String&) override; + virtual void didImportIconDataForPageURL(const String&) override; + virtual void didChangeIconForPageURL(const String&) override; + virtual void didRemoveAllIcons() override; + virtual void didFinishURLImport() override; + virtual void didClose() override; - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; void notifyIconDataReadyForPageURL(const String&); - WebContext* m_webContext; - - OwnPtr<WebCore::IconDatabase> m_iconDatabaseImpl; + WebProcessPool* m_processPool; + + std::unique_ptr<WebCore::IconDatabase> m_iconDatabaseImpl; bool m_urlImportCompleted; bool m_databaseCleanupDisabled; + bool m_shouldDerefWhenAppropriate; HashMap<uint64_t, String> m_pendingLoadDecisionURLMap; WebIconDatabaseClient m_iconDatabaseClient; diff --git a/Source/WebKit2/UIProcess/WebIconDatabase.messages.in b/Source/WebKit2/UIProcess/WebIconDatabase.messages.in index 400adb081..f5b96fd1f 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabase.messages.in +++ b/Source/WebKit2/UIProcess/WebIconDatabase.messages.in @@ -21,16 +21,14 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. messages -> WebIconDatabase { - RetainIconForPageURL(WTF::String pageURL) - ReleaseIconForPageURL(WTF::String pageURL) - SetIconURLForPageURL(WTF::String iconURL, WTF::String pageURL) - SetIconDataForIconURL(CoreIPC::DataReference iconData, WTF::String iconURL) + SetIconURLForPageURL(String iconURL, String pageURL) + SetIconDataForIconURL(IPC::DataReference iconData, String iconURL) - SynchronousIconDataForPageURL(WTF::String pageURL) -> (CoreIPC::DataReference iconData) - SynchronousIconURLForPageURL(WTF::String pageURL) -> (WTF::String iconURL) - SynchronousIconDataKnownForIconURL(WTF::String iconURL) -> (bool dataKnown) - SynchronousLoadDecisionForIconURL(WTF::String iconURL) -> (int loadDecision) + SynchronousIconDataForPageURL(String pageURL) -> (IPC::DataReference iconData) + SynchronousIconURLForPageURL(String pageURL) -> (String iconURL) + SynchronousIconDataKnownForIconURL(String iconURL) -> (bool dataKnown) + SynchronousLoadDecisionForIconURL(String iconURL) -> (int loadDecision) - GetLoadDecisionForIconURL(WTF::String iconURL, uint64_t callbackID) - DidReceiveIconForPageURL(WTF::String pageURL) + GetLoadDecisionForIconURL(String iconURL, uint64_t callbackID) + DidReceiveIconForPageURL(String pageURL) } diff --git a/Source/WebKit2/UIProcess/WebIconDatabaseClient.cpp b/Source/WebKit2/UIProcess/WebIconDatabaseClient.cpp index 4fbfd3ccd..9555bc233 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabaseClient.cpp +++ b/Source/WebKit2/UIProcess/WebIconDatabaseClient.cpp @@ -28,15 +28,16 @@ #include "WKAPICast.h" #include "WKSharedAPICast.h" +#include "WebIconDatabase.h" namespace WebKit { -void WebIconDatabaseClient::didChangeIconForPageURL(WebIconDatabase* iconDatabase, WebURL* url) +void WebIconDatabaseClient::didChangeIconForPageURL(WebIconDatabase* iconDatabase, API::URL* url) { if (!m_client.didChangeIconForPageURL) return; - m_client.didChangeIconForPageURL(toAPI(iconDatabase), toAPI(url), m_client.clientInfo); + m_client.didChangeIconForPageURL(toAPI(iconDatabase), toAPI(url), m_client.base.clientInfo); } void WebIconDatabaseClient::didRemoveAllIcons(WebIconDatabase* iconDatabase) @@ -44,15 +45,15 @@ void WebIconDatabaseClient::didRemoveAllIcons(WebIconDatabase* iconDatabase) if (!m_client.didRemoveAllIcons) return; - m_client.didRemoveAllIcons(toAPI(iconDatabase), m_client.clientInfo); + m_client.didRemoveAllIcons(toAPI(iconDatabase), m_client.base.clientInfo); } -void WebIconDatabaseClient::iconDataReadyForPageURL(WebIconDatabase* iconDatabase, WebURL* url) +void WebIconDatabaseClient::iconDataReadyForPageURL(WebIconDatabase* iconDatabase, API::URL* url) { if (!m_client.iconDataReadyForPageURL) return; - m_client.iconDataReadyForPageURL(toAPI(iconDatabase), toAPI(url), m_client.clientInfo); + m_client.iconDataReadyForPageURL(toAPI(iconDatabase), toAPI(url), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebIconDatabaseClient.h b/Source/WebKit2/UIProcess/WebIconDatabaseClient.h index 5fe2fea43..fc73dcbac 100644 --- a/Source/WebKit2/UIProcess/WebIconDatabaseClient.h +++ b/Source/WebKit2/UIProcess/WebIconDatabaseClient.h @@ -29,17 +29,22 @@ #include "APIClient.h" #include "WKIconDatabase.h" +namespace API { +class URL; +template<> struct ClientTraits<WKIconDatabaseClientBase> { + typedef std::tuple<WKIconDatabaseClientV0, WKIconDatabaseClientV1> Versions; +}; +} + namespace WebKit { -class APIObject; class WebIconDatabase; -class WebURL; -class WebIconDatabaseClient : public APIClient<WKIconDatabaseClient, kWKIconDatabaseClientCurrentVersion> { +class WebIconDatabaseClient : public API::Client<WKIconDatabaseClientBase> { public: - void didChangeIconForPageURL(WebIconDatabase*, WebURL*); + void didChangeIconForPageURL(WebIconDatabase*, API::URL*); void didRemoveAllIcons(WebIconDatabase*); - void iconDataReadyForPageURL(WebIconDatabase*, WebURL*); + void iconDataReadyForPageURL(WebIconDatabase*, API::URL*); }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebInspectorProxy.cpp b/Source/WebKit2/UIProcess/WebInspectorProxy.cpp index 98802fff3..fa84acd7c 100644 --- a/Source/WebKit2/UIProcess/WebInspectorProxy.cpp +++ b/Source/WebKit2/UIProcess/WebInspectorProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2014 Apple Inc. All rights reserved. * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,18 +27,23 @@ #include "config.h" #include "WebInspectorProxy.h" -#if ENABLE(INSPECTOR) - +#include "APIProcessPoolConfiguration.h" +#include "APIURLRequest.h" +#include "WKArray.h" +#include "WKContextMenuItem.h" +#include "WKMutableArray.h" #include "WebFramePolicyListenerProxy.h" #include "WebFrameProxy.h" #include "WebInspectorMessages.h" #include "WebInspectorProxyMessages.h" -#include "WebPageCreationParameters.h" +#include "WebInspectorUIMessages.h" #include "WebPageGroup.h" #include "WebPageProxy.h" #include "WebPreferences.h" +#include "WebProcessPool.h" #include "WebProcessProxy.h" -#include "WebURLRequest.h" +#include <WebCore/NotImplemented.h> +#include <wtf/NeverDestroyed.h> #if ENABLE(INSPECTOR_SERVER) #include "WebInspectorServer.h" @@ -48,82 +53,73 @@ using namespace WebCore; namespace WebKit { -const unsigned WebInspectorProxy::minimumWindowWidth = 750; +const unsigned WebInspectorProxy::minimumWindowWidth = 500; const unsigned WebInspectorProxy::minimumWindowHeight = 400; const unsigned WebInspectorProxy::initialWindowWidth = 1000; const unsigned WebInspectorProxy::initialWindowHeight = 650; -const unsigned WebInspectorProxy::minimumAttachedWidth = 750; -const unsigned WebInspectorProxy::minimumAttachedHeight = 250; +typedef HashMap<WebPageProxy*, unsigned> PageLevelMap; -static PassRefPtr<WebPageGroup> createInspectorPageGroup() +static PageLevelMap& pageLevelMap() { - RefPtr<WebPageGroup> pageGroup = WebPageGroup::create("__WebInspectorPageGroup__", false, false); + static NeverDestroyed<PageLevelMap> map; + return map; +} -#ifndef NDEBUG - // Allow developers to inspect the Web Inspector in debug builds. - pageGroup->preferences()->setDeveloperExtrasEnabled(true); - pageGroup->preferences()->setLogsPageMessagesToSystemConsoleEnabled(true); +WebInspectorProxy::WebInspectorProxy(WebPageProxy* inspectedPage) + : m_inspectedPage(inspectedPage) +#if PLATFORM(MAC) && WK_API_ENABLED + , m_closeTimer(RunLoop::main(), this, &WebInspectorProxy::closeTimerFired) #endif +{ + m_inspectedPage->process().addMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_inspectedPage->pageID(), *this); +} - pageGroup->preferences()->setApplicationChromeModeEnabled(true); - - return pageGroup.release(); +WebInspectorProxy::~WebInspectorProxy() +{ } -WebPageGroup* WebInspectorProxy::inspectorPageGroup() +unsigned WebInspectorProxy::inspectionLevel() const { - static WebPageGroup* pageGroup = createInspectorPageGroup().leakRef(); - return pageGroup; + auto findResult = pageLevelMap().find(inspectedPage()); + if (findResult != pageLevelMap().end()) + return findResult->value + 1; + + return 1; } -WebInspectorProxy::WebInspectorProxy(WebPageProxy* page) - : m_page(page) - , m_isVisible(false) - , m_isAttached(false) - , m_isDebuggingJavaScript(false) - , m_isProfilingJavaScript(false) - , m_isProfilingPage(false) - , m_showMessageSent(false) - , m_createdInspectorPage(false) - , m_ignoreFirstBringToFront(false) - , m_attachmentSide(AttachmentSideBottom) -#if PLATFORM(GTK) || PLATFORM(EFL) - , m_inspectorView(0) - , m_inspectorWindow(0) -#endif -#if ENABLE(INSPECTOR_SERVER) - , m_remoteInspectionPageId(0) -#endif +String WebInspectorProxy::inspectorPageGroupIdentifier() const { - m_page->process()->addMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_page->pageID(), this); + return String::format("__WebInspectorPageGroupLevel%u__", inspectionLevel()); } -WebInspectorProxy::~WebInspectorProxy() +WebPreferences& WebInspectorProxy::inspectorPagePreferences() const { + ASSERT(m_inspectorPage); + return m_inspectorPage->pageGroup().preferences(); } void WebInspectorProxy::invalidate() { #if ENABLE(INSPECTOR_SERVER) if (m_remoteInspectionPageId) - WebInspectorServer::shared().unregisterPage(m_remoteInspectionPageId); + WebInspectorServer::singleton().unregisterPage(m_remoteInspectionPageId); #endif - m_page->process()->removeMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_page->pageID()); - - m_page->close(); + m_inspectedPage->process().removeMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_inspectedPage->pageID()); didClose(); + platformInvalidate(); - m_page = 0; + pageLevelMap().remove(m_inspectedPage); + m_inspectedPage = nullptr; } // Public APIs bool WebInspectorProxy::isFront() { - if (!m_page) + if (!m_inspectedPage) return false; return platformIsFront(); @@ -131,7 +127,7 @@ bool WebInspectorProxy::isFront() void WebInspectorProxy::connect() { - if (!m_page) + if (!m_inspectedPage) return; if (m_showMessageSent) @@ -140,12 +136,14 @@ void WebInspectorProxy::connect() m_showMessageSent = true; m_ignoreFirstBringToFront = true; - m_page->process()->send(Messages::WebInspector::Show(), m_page->pageID()); + eagerlyCreateInspectorPage(); + + m_inspectedPage->process().send(Messages::WebInspector::Show(), m_inspectedPage->pageID()); } void WebInspectorProxy::show() { - if (!m_page) + if (!m_inspectedPage) return; if (isConnected()) { @@ -161,7 +159,7 @@ void WebInspectorProxy::show() void WebInspectorProxy::hide() { - if (!m_page) + if (!m_inspectedPage) return; m_isVisible = false; @@ -171,68 +169,87 @@ void WebInspectorProxy::hide() void WebInspectorProxy::close() { - if (!m_page) + if (!m_inspectedPage) return; - m_page->process()->send(Messages::WebInspector::Close(), m_page->pageID()); + m_inspectedPage->process().send(Messages::WebInspector::Close(), m_inspectedPage->pageID()); didClose(); } +void WebInspectorProxy::didRelaunchInspectorPageProcess() +{ + m_inspectorPage->process().addMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_inspectedPage->pageID(), *this); + m_inspectorPage->process().assumeReadAccessToBaseURL(WebInspectorProxy::inspectorBaseURL()); + + // When didRelaunchInspectorPageProcess is called we can assume it is during a load request. + // Any messages we would have sent to a terminated process need to be re-sent. + + m_inspectorPage->process().send(Messages::WebInspectorUI::EstablishConnection(m_connectionIdentifier, m_inspectedPage->pageID(), m_underTest, inspectionLevel()), m_inspectorPage->pageID()); +} + void WebInspectorProxy::showConsole() { - if (!m_page) + if (!m_inspectedPage) return; - m_page->process()->send(Messages::WebInspector::ShowConsole(), m_page->pageID()); + eagerlyCreateInspectorPage(); + + m_inspectedPage->process().send(Messages::WebInspector::ShowConsole(), m_inspectedPage->pageID()); } void WebInspectorProxy::showResources() { - if (!m_page) + if (!m_inspectedPage) return; - m_page->process()->send(Messages::WebInspector::ShowResources(), m_page->pageID()); + eagerlyCreateInspectorPage(); + + m_inspectedPage->process().send(Messages::WebInspector::ShowResources(), m_inspectedPage->pageID()); } void WebInspectorProxy::showMainResourceForFrame(WebFrameProxy* frame) { - if (!m_page) + if (!m_inspectedPage) return; - m_page->process()->send(Messages::WebInspector::ShowMainResourceForFrame(frame->frameID()), m_page->pageID()); + eagerlyCreateInspectorPage(); + + m_inspectedPage->process().send(Messages::WebInspector::ShowMainResourceForFrame(frame->frameID()), m_inspectedPage->pageID()); } void WebInspectorProxy::attachBottom() { - attach(AttachmentSideBottom); + attach(AttachmentSide::Bottom); } void WebInspectorProxy::attachRight() { - attach(AttachmentSideRight); + attach(AttachmentSide::Right); } void WebInspectorProxy::attach(AttachmentSide side) { - if (!m_page || !canAttach()) + if (!m_inspectedPage || !canAttach()) return; m_isAttached = true; m_attachmentSide = side; - inspectorPageGroup()->preferences()->setInspectorAttachmentSide(side); + inspectorPagePreferences().setInspectorAttachmentSide(static_cast<uint32_t>(side)); if (m_isVisible) - inspectorPageGroup()->preferences()->setInspectorStartsAttached(true); + inspectorPagePreferences().setInspectorStartsAttached(true); + + m_inspectedPage->process().send(Messages::WebInspector::SetAttached(true), m_inspectedPage->pageID()); switch (m_attachmentSide) { - case AttachmentSideBottom: - m_page->process()->send(Messages::WebInspector::AttachedBottom(), m_page->pageID()); + case AttachmentSide::Bottom: + m_inspectorPage->process().send(Messages::WebInspectorUI::AttachedBottom(), m_inspectorPage->pageID()); break; - case AttachmentSideRight: - m_page->process()->send(Messages::WebInspector::AttachedRight(), m_page->pageID()); + case AttachmentSide::Right: + m_inspectorPage->process().send(Messages::WebInspectorUI::AttachedRight(), m_inspectorPage->pageID()); break; } @@ -241,79 +258,102 @@ void WebInspectorProxy::attach(AttachmentSide side) void WebInspectorProxy::detach() { - if (!m_page) + if (!m_inspectedPage) return; m_isAttached = false; if (m_isVisible) - inspectorPageGroup()->preferences()->setInspectorStartsAttached(false); + inspectorPagePreferences().setInspectorStartsAttached(false); - m_page->process()->send(Messages::WebInspector::Detached(), m_page->pageID()); + m_inspectedPage->process().send(Messages::WebInspector::SetAttached(false), m_inspectedPage->pageID()); + m_inspectorPage->process().send(Messages::WebInspectorUI::Detached(), m_inspectorPage->pageID()); platformDetach(); } void WebInspectorProxy::setAttachedWindowHeight(unsigned height) { - inspectorPageGroup()->preferences()->setInspectorAttachedHeight(height); + inspectorPagePreferences().setInspectorAttachedHeight(height); platformSetAttachedWindowHeight(height); } void WebInspectorProxy::setAttachedWindowWidth(unsigned width) { - inspectorPageGroup()->preferences()->setInspectorAttachedWidth(width); + inspectorPagePreferences().setInspectorAttachedWidth(width); platformSetAttachedWindowWidth(width); } -void WebInspectorProxy::toggleJavaScriptDebugging() +void WebInspectorProxy::startWindowDrag() +{ + platformStartWindowDrag(); +} + +void WebInspectorProxy::togglePageProfiling() { - if (!m_page) + if (!m_inspectedPage) return; - if (m_isDebuggingJavaScript) - m_page->process()->send(Messages::WebInspector::StopJavaScriptDebugging(), m_page->pageID()); + if (m_isProfilingPage) + m_inspectedPage->process().send(Messages::WebInspector::StopPageProfiling(), m_inspectedPage->pageID()); else - m_page->process()->send(Messages::WebInspector::StartJavaScriptDebugging(), m_page->pageID()); + m_inspectedPage->process().send(Messages::WebInspector::StartPageProfiling(), m_inspectedPage->pageID()); // FIXME: have the WebProcess notify us on state changes. - m_isDebuggingJavaScript = !m_isDebuggingJavaScript; + m_isProfilingPage = !m_isProfilingPage; } -void WebInspectorProxy::toggleJavaScriptProfiling() +static WebProcessPool* s_mainInspectorProcessPool; +static WebProcessPool* s_nestedInspectorProcessPool; + +WebProcessPool& WebInspectorProxy::inspectorProcessPool(unsigned inspectionLevel) { - if (!m_page) - return; + // Having our own process pool removes us from the main process pool and + // guarantees no process sharing for our user interface. + WebProcessPool*& pool = inspectionLevel == 1 ? s_mainInspectorProcessPool : s_nestedInspectorProcessPool; + if (!pool) { + auto configuration = API::ProcessPoolConfiguration::createWithLegacyOptions(); + pool = &WebProcessPool::create(configuration.get()).leakRef(); + } + return *pool; +} - if (m_isProfilingJavaScript) - m_page->process()->send(Messages::WebInspector::StopJavaScriptProfiling(), m_page->pageID()); - else - m_page->process()->send(Messages::WebInspector::StartJavaScriptProfiling(), m_page->pageID()); +bool WebInspectorProxy::isInspectorProcessPool(WebProcessPool& processPool) +{ + return (s_mainInspectorProcessPool && s_mainInspectorProcessPool == &processPool) + || (s_nestedInspectorProcessPool && s_nestedInspectorProcessPool == &processPool); +} - // FIXME: have the WebProcess notify us on state changes. - m_isProfilingJavaScript = !m_isProfilingJavaScript; +bool WebInspectorProxy::isInspectorPage(WebPageProxy& webPage) +{ + return pageLevelMap().contains(&webPage); } -void WebInspectorProxy::togglePageProfiling() +static bool isMainOrTestInspectorPage(WKURLRequestRef requestRef) { - if (!m_page) - return; + // Use URL so we can compare the paths and protocols. + const URL& requestURL = toImpl(requestRef)->resourceRequest().url(); + URL mainPageURL(URL(), WebInspectorProxy::inspectorPageURL()); + if (requestURL.protocol() == mainPageURL.protocol() && decodeURLEscapeSequences(requestURL.path()) == decodeURLEscapeSequences(mainPageURL.path())) + return true; - if (m_isProfilingPage) - m_page->process()->send(Messages::WebInspector::StopPageProfiling(), m_page->pageID()); - else - m_page->process()->send(Messages::WebInspector::StartPageProfiling(), m_page->pageID()); + // We might not have a Test URL in Production builds. + String testPageURLString = WebInspectorProxy::inspectorTestPageURL(); + if (testPageURLString.isNull()) + return false; - // FIXME: have the WebProcess notify us on state changes. - m_isProfilingPage = !m_isProfilingPage; + URL testPageURL(URL(), testPageURLString); + return requestURL.protocol() == testPageURL.protocol() && decodeURLEscapeSequences(requestURL.path()) == decodeURLEscapeSequences(testPageURL.path()); } -bool WebInspectorProxy::isInspectorPage(WebPageProxy* page) +static void processDidCrash(WKPageRef, const void* clientInfo) { - return page->pageGroup() == inspectorPageGroup(); + WebInspectorProxy* webInspectorProxy = static_cast<WebInspectorProxy*>(const_cast<void*>(clientInfo)); + ASSERT(webInspectorProxy); + webInspectorProxy->close(); } -static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef frameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef requestRef, WKFramePolicyListenerRef listenerRef, WKTypeRef, const void* clientInfo) +static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef frameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKFrameRef, WKURLRequestRef requestRef, WKFramePolicyListenerRef listenerRef, WKTypeRef, const void* clientInfo) { // Allow non-main frames to navigate anywhere. if (!toImpl(frameRef)->isMainFrame()) { @@ -324,14 +364,8 @@ static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef frameRef, WKFr const WebInspectorProxy* webInspectorProxy = static_cast<const WebInspectorProxy*>(clientInfo); ASSERT(webInspectorProxy); - // Use KURL so we can compare just the fileSystemPaths. - KURL inspectorURL(KURL(), webInspectorProxy->inspectorPageURL()); - KURL requestURL(KURL(), toImpl(requestRef)->url()); - - ASSERT(inspectorURL.isLocalFile()); - // Allow loading of the main inspector file. - if (requestURL.isLocalFile() && requestURL.fileSystemPath() == inspectorURL.fileSystemPath()) { + if (isMainOrTestInspectorPage(requestRef)) { toImpl(listenerRef)->use(); return; } @@ -340,89 +374,187 @@ static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef frameRef, WKFr toImpl(listenerRef)->ignore(); // And instead load it in the inspected page. - webInspectorProxy->page()->loadURLRequest(toImpl(requestRef)); + webInspectorProxy->inspectedPage()->loadRequest(toImpl(requestRef)->resourceRequest()); +} + +static void getContextMenuFromProposedMenu(WKPageRef pageRef, WKArrayRef proposedMenuRef, WKArrayRef* newMenuRef, WKHitTestResultRef, WKTypeRef, const void*) +{ + WKMutableArrayRef menuItems = WKMutableArrayCreate(); + + size_t count = WKArrayGetSize(proposedMenuRef); + for (size_t i = 0; i < count; ++i) { + WKContextMenuItemRef contextMenuItem = static_cast<WKContextMenuItemRef>(WKArrayGetItemAtIndex(proposedMenuRef, i)); + switch (WKContextMenuItemGetTag(contextMenuItem)) { + case kWKContextMenuItemTagOpenLinkInNewWindow: + case kWKContextMenuItemTagOpenImageInNewWindow: + case kWKContextMenuItemTagOpenFrameInNewWindow: + case kWKContextMenuItemTagOpenMediaInNewWindow: + case kWKContextMenuItemTagDownloadLinkToDisk: + case kWKContextMenuItemTagDownloadImageToDisk: + break; + default: + WKArrayAppendItem(menuItems, contextMenuItem); + break; + } + } + + *newMenuRef = menuItems; } #if ENABLE(INSPECTOR_SERVER) void WebInspectorProxy::enableRemoteInspection() { if (!m_remoteInspectionPageId) - m_remoteInspectionPageId = WebInspectorServer::shared().registerPage(this); + m_remoteInspectionPageId = WebInspectorServer::singleton().registerPage(this); } void WebInspectorProxy::remoteFrontendConnected() { - m_page->process()->send(Messages::WebInspector::RemoteFrontendConnected(), m_page->pageID()); + m_inspectedPage->process().send(Messages::WebInspector::RemoteFrontendConnected(), m_inspectedPage->pageID()); } void WebInspectorProxy::remoteFrontendDisconnected() { - m_page->process()->send(Messages::WebInspector::RemoteFrontendDisconnected(), m_page->pageID()); + m_inspectedPage->process().send(Messages::WebInspector::RemoteFrontendDisconnected(), m_inspectedPage->pageID()); } void WebInspectorProxy::dispatchMessageFromRemoteFrontend(const String& message) { - m_page->process()->send(Messages::WebInspector::DispatchMessageFromRemoteFrontend(message), m_page->pageID()); + m_inspectedPage->process().send(Messages::WebInspector::SendMessageToBackend(message), m_inspectedPage->pageID()); } #endif -// Called by WebInspectorProxy messages -void WebInspectorProxy::createInspectorPage(uint64_t& inspectorPageID, WebPageCreationParameters& inspectorPageParameters) +void WebInspectorProxy::eagerlyCreateInspectorPage() { - inspectorPageID = 0; - - if (!m_page) + if (m_inspectorPage) return; - m_isAttached = shouldOpenAttached(); - m_attachmentSide = static_cast<AttachmentSide>(inspectorPageGroup()->preferences()->inspectorAttachmentSide()); - - WebPageProxy* inspectorPage = platformCreateInspectorPage(); - ASSERT(inspectorPage); - if (!inspectorPage) + m_inspectorPage = platformCreateInspectorPage(); + ASSERT(m_inspectorPage); + if (!m_inspectorPage) return; - inspectorPageID = inspectorPage->pageID(); - inspectorPageParameters = inspectorPage->creationParameters(); + pageLevelMap().set(m_inspectorPage, inspectionLevel()); - WKPagePolicyClient policyClient = { - kWKPagePolicyClientCurrentVersion, - this, /* clientInfo */ + WKPagePolicyClientV1 policyClient = { + { 1, this }, + nullptr, // decidePolicyForNavigationAction_deprecatedForUseWithV0 + nullptr, // decidePolicyForNewWindowAction + nullptr, // decidePolicyForResponse_deprecatedForUseWithV0 + nullptr, // unableToImplementPolicy decidePolicyForNavigationAction, - 0, /* decidePolicyForNewWindowAction */ - 0, /* decidePolicyForResponse */ - 0 /* unableToImplementPolicy */ + nullptr, // decidePolicyForResponse }; - inspectorPage->initializePolicyClient(&policyClient); + WKPageLoaderClientV5 loaderClient = { + { 5, this }, + nullptr, // didStartProvisionalLoadForFrame + nullptr, // didReceiveServerRedirectForProvisionalLoadForFrame + nullptr, // didFailProvisionalLoadWithErrorForFrame + nullptr, // didCommitLoadForFrame + nullptr, // didFinishDocumentLoadForFrame + nullptr, // didFinishLoadForFrame + nullptr, // didFailLoadWithErrorForFrame + nullptr, // didSameDocumentNavigationForFrame + nullptr, // didReceiveTitleForFrame + nullptr, // didFirstLayoutForFrame + nullptr, // didFirstVisuallyNonEmptyLayoutForFrame + nullptr, // didRemoveFrameFromHierarchy + nullptr, // didDisplayInsecureContentForFrame + nullptr, // didRunInsecureContentForFrame + nullptr, // canAuthenticateAgainstProtectionSpaceInFrame + nullptr, // didReceiveAuthenticationChallengeInFrame + nullptr, // didStartProgress + nullptr, // didChangeProgress + nullptr, // didFinishProgress + nullptr, // didBecomeUnresponsive + nullptr, // didBecomeResponsive + processDidCrash, + nullptr, // didChangeBackForwardList + nullptr, // shouldGoToBackForwardListItem + nullptr, // didFailToInitializePlugin_deprecatedForUseWithV0 + nullptr, // didDetectXSSForFrame + nullptr, // didNewFirstVisuallyNonEmptyLayout_unavailable + nullptr, // willGoToBackForwardListItem + nullptr, // interactionOccurredWhileProcessUnresponsive + nullptr, // pluginDidFail_deprecatedForUseWithV1 + nullptr, // didReceiveIntentForFrame_unavailable + nullptr, // registerIntentServiceForFrame_unavailable + nullptr, // didLayout + nullptr, // pluginLoadPolicy_deprecatedForUseWithV2 + nullptr, // pluginDidFail + nullptr, // pluginLoadPolicy + nullptr, // webGLLoadPolicy + nullptr, // resolveWebGLLoadPolicy + nullptr, // shouldKeepCurrentBackForwardListItemInList + }; - String url = inspectorPageURL(); + WKPageContextMenuClientV3 contextMenuClient = { + { 3, this }, + 0, // getContextMenuFromProposedMenu_deprecatedForUseWithV0 + 0, // customContextMenuItemSelected + 0, // contextMenuDismissed + getContextMenuFromProposedMenu, + 0, // showContextMenu + 0, // hideContextMenu + }; - url.append("?dockSide="); + WKPageSetPagePolicyClient(toAPI(m_inspectorPage), &policyClient.base); + WKPageSetPageLoaderClient(toAPI(m_inspectorPage), &loaderClient.base); + WKPageSetPageContextMenuClient(toAPI(m_inspectorPage), &contextMenuClient.base); - if (m_isAttached) { - switch (m_attachmentSide) { - case AttachmentSideBottom: - url.append("bottom"); - m_page->process()->send(Messages::WebInspector::AttachedBottom(), m_page->pageID()); - break; - case AttachmentSideRight: - url.append("right"); - m_page->process()->send(Messages::WebInspector::AttachedRight(), m_page->pageID()); - break; - } - } else - url.append("undocked"); + m_inspectorPage->process().addMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_inspectedPage->pageID(), *this); + m_inspectorPage->process().assumeReadAccessToBaseURL(WebInspectorProxy::inspectorBaseURL()); +} + +// Called by WebInspectorProxy messages +void WebInspectorProxy::createInspectorPage(IPC::Attachment connectionIdentifier, bool canAttach, bool underTest) +{ + if (!m_inspectedPage) + return; + + m_underTest = underTest; + eagerlyCreateInspectorPage(); + + ASSERT(m_inspectorPage); + if (!m_inspectorPage) + return; + + m_connectionIdentifier = WTFMove(connectionIdentifier); + + m_inspectorPage->process().send(Messages::WebInspectorUI::EstablishConnection(m_connectionIdentifier, m_inspectedPage->pageID(), m_underTest, inspectionLevel()), m_inspectorPage->pageID()); + + if (!m_underTest) { + m_canAttach = platformCanAttach(canAttach); + m_isAttached = shouldOpenAttached(); + m_attachmentSide = static_cast<AttachmentSide>(inspectorPagePreferences().inspectorAttachmentSide()); + + m_inspectedPage->process().send(Messages::WebInspector::SetAttached(m_isAttached), m_inspectedPage->pageID()); - m_page->process()->assumeReadAccessToBaseURL(inspectorBaseURL()); + if (m_isAttached) { + switch (m_attachmentSide) { + case AttachmentSide::Bottom: + m_inspectorPage->process().send(Messages::WebInspectorUI::AttachedBottom(), m_inspectorPage->pageID()); + break; - inspectorPage->loadURL(url); + case AttachmentSide::Right: + m_inspectorPage->process().send(Messages::WebInspectorUI::AttachedRight(), m_inspectorPage->pageID()); + break; + } + } else + m_inspectorPage->process().send(Messages::WebInspectorUI::Detached(), m_inspectorPage->pageID()); - m_createdInspectorPage = true; + m_inspectorPage->process().send(Messages::WebInspectorUI::SetDockingUnavailable(!m_canAttach), m_inspectorPage->pageID()); + } + + m_inspectorPage->loadRequest(URL(URL(), m_underTest ? WebInspectorProxy::inspectorTestPageURL() : WebInspectorProxy::inspectorPageURL())); } void WebInspectorProxy::open() { + if (m_underTest) + return; + m_isVisible = true; platformOpen(); @@ -430,20 +562,27 @@ void WebInspectorProxy::open() void WebInspectorProxy::didClose() { - if (!m_createdInspectorPage) + if (!m_inspectorPage) return; + m_inspectorPage->process().removeMessageReceiver(Messages::WebInspectorProxy::messageReceiverName(), m_inspectedPage->pageID()); + m_isVisible = false; - m_isDebuggingJavaScript = false; - m_isProfilingJavaScript = false; m_isProfilingPage = false; - m_createdInspectorPage = false; m_showMessageSent = false; m_ignoreFirstBringToFront = false; if (m_isAttached) platformDetach(); + + // Null out m_inspectorPage after platformDetach(), so the views can be cleaned up correctly. + m_inspectorPage = nullptr; + m_isAttached = false; + m_canAttach = false; + m_underTest = false; + + m_connectionIdentifier = IPC::Attachment(); platformDidClose(); } @@ -466,7 +605,17 @@ void WebInspectorProxy::bringToFront() void WebInspectorProxy::attachAvailabilityChanged(bool available) { - platformAttachAvailabilityChanged(available); + bool previousCanAttach = m_canAttach; + + m_canAttach = platformCanAttach(available); + + if (previousCanAttach == m_canAttach) + return; + + if (m_inspectorPage && !m_underTest) + m_inspectorPage->process().send(Messages::WebInspectorUI::SetDockingUnavailable(!m_canAttach), m_inspectorPage->pageID()); + + platformAttachAvailabilityChanged(m_canAttach); } void WebInspectorProxy::inspectedURLChanged(const String& urlString) @@ -474,9 +623,9 @@ void WebInspectorProxy::inspectedURLChanged(const String& urlString) platformInspectedURLChanged(urlString); } -void WebInspectorProxy::save(const String& filename, const String& content, bool forceSaveAs) +void WebInspectorProxy::save(const String& filename, const String& content, bool base64Encoded, bool forceSaveAs) { - platformSave(filename, content, forceSaveAs); + platformSave(filename, content, base64Encoded, forceSaveAs); } void WebInspectorProxy::append(const String& filename, const String& content) @@ -484,42 +633,135 @@ void WebInspectorProxy::append(const String& filename, const String& content) platformAppend(filename, content); } -bool WebInspectorProxy::canAttach() +bool WebInspectorProxy::shouldOpenAttached() { - // Keep this in sync with InspectorFrontendClientLocal::canAttachWindow. There are two implementations - // to make life easier in the multi-process world we have. WebInspectorProxy uses canAttach to decide if - // we can attach on open (on the UI process side). And InspectorFrontendClientLocal::canAttachWindow is - // used to decide if we can attach when the attach button is pressed (on the WebProcess side). + return inspectorPagePreferences().inspectorStartsAttached() && canAttach(); +} - // If we are already attached, allow attaching again to allow switching sides. - if (m_isAttached) - return true; +#if ENABLE(INSPECTOR_SERVER) +void WebInspectorProxy::sendMessageToRemoteFrontend(const String& message) +{ + ASSERT(m_remoteInspectionPageId); + WebInspectorServer::singleton().sendMessageOverConnection(m_remoteInspectionPageId, message); +} +#endif - // Don't allow attaching to another inspector -- two inspectors in one window is too much! - bool isInspectorPage = m_page->pageGroup() == inspectorPageGroup(); - if (isInspectorPage) - return false; +// Unsupported configurations can use the stubs provided here. - // Don't allow the attach if the window would be too small to accommodate the minimum inspector height. - unsigned inspectedPageHeight = platformInspectedWindowHeight(); - unsigned inspectedPageWidth = platformInspectedWindowWidth(); - unsigned maximumAttachedHeight = inspectedPageHeight * 3 / 4; - return minimumAttachedHeight <= maximumAttachedHeight && minimumAttachedWidth <= inspectedPageWidth; +#if PLATFORM(IOS) || (PLATFORM(MAC) && !WK_API_ENABLED) + +WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() +{ + notImplemented(); + return nullptr; } -bool WebInspectorProxy::shouldOpenAttached() +void WebInspectorProxy::platformOpen() { - return inspectorPageGroup()->preferences()->inspectorStartsAttached() && canAttach(); + notImplemented(); } -#if ENABLE(INSPECTOR_SERVER) -void WebInspectorProxy::sendMessageToRemoteFrontend(const String& message) +void WebInspectorProxy::platformDidClose() { - ASSERT(m_remoteInspectionPageId); - WebInspectorServer::shared().sendMessageOverConnection(m_remoteInspectionPageId, message); + notImplemented(); } -#endif -} // namespace WebKit +void WebInspectorProxy::platformInvalidate() +{ + notImplemented(); +} + +void WebInspectorProxy::platformBringToFront() +{ + notImplemented(); +} + +void WebInspectorProxy::platformHide() +{ + notImplemented(); +} + +bool WebInspectorProxy::platformIsFront() +{ + notImplemented(); + return false; +} + +void WebInspectorProxy::platformInspectedURLChanged(const String&) +{ + notImplemented(); +} -#endif // ENABLE(INSPECTOR) +void WebInspectorProxy::platformSave(const String& suggestedURL, const String& content, bool base64Encoded, bool forceSaveDialog) +{ + notImplemented(); +} + +void WebInspectorProxy::platformAppend(const String& suggestedURL, const String& content) +{ + notImplemented(); +} + +unsigned WebInspectorProxy::platformInspectedWindowHeight() +{ + notImplemented(); + return 0; +} + +unsigned WebInspectorProxy::platformInspectedWindowWidth() +{ + notImplemented(); + return 0; +} + +void WebInspectorProxy::platformAttach() +{ + notImplemented(); +} + +void WebInspectorProxy::platformDetach() +{ + notImplemented(); +} + +void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformStartWindowDrag() +{ + notImplemented(); +} + +String WebInspectorProxy::inspectorPageURL() +{ + notImplemented(); + return String(); +} + +String WebInspectorProxy::inspectorTestPageURL() +{ + notImplemented(); + return String(); +} + +String WebInspectorProxy::inspectorBaseURL() +{ + notImplemented(); + return String(); +} + +void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned) +{ + notImplemented(); +} + +void WebInspectorProxy::platformAttachAvailabilityChanged(bool) +{ + notImplemented(); +} + +#endif // PLATFORM(IOS) || (PLATFORM(MAC) && !WK_API_ENABLED) + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebInspectorProxy.h b/Source/WebKit2/UIProcess/WebInspectorProxy.h index ef46b7823..cffa26698 100644 --- a/Source/WebKit2/UIProcess/WebInspectorProxy.h +++ b/Source/WebKit2/UIProcess/WebInspectorProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2014 Apple Inc. All rights reserved. * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,12 +27,10 @@ #ifndef WebInspectorProxy_h #define WebInspectorProxy_h -#if ENABLE(INSPECTOR) - #include "APIObject.h" +#include "Attachment.h" #include "MessageReceiver.h" #include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> #include <wtf/text/WTFString.h> @@ -40,12 +38,13 @@ #include "WKGeometry.h" #include <wtf/HashMap.h> #include <wtf/RetainPtr.h> +#include <wtf/RunLoop.h> -OBJC_CLASS NSButton; OBJC_CLASS NSURL; +OBJC_CLASS NSView; OBJC_CLASS NSWindow; OBJC_CLASS WKWebInspectorProxyObjCAdapter; -OBJC_CLASS WKWebInspectorWKView; +OBJC_CLASS WKWebInspectorWKWebView; #endif #if PLATFORM(GTK) @@ -60,20 +59,20 @@ OBJC_CLASS WKWebInspectorWKView; namespace WebKit { class WebFrameProxy; -class WebPageGroup; class WebPageProxy; -struct WebPageCreationParameters; +class WebPreferences; +class WebProcessPool; -enum AttachmentSide { - AttachmentSideBottom, - AttachmentSideRight +enum class AttachmentSide { + Bottom, + Right }; -class WebInspectorProxy : public TypedAPIObject<APIObject::TypeInspector>, public CoreIPC::MessageReceiver { +class WebInspectorProxy : public API::ObjectImpl<API::Object::Type::Inspector>, public IPC::MessageReceiver { public: - static PassRefPtr<WebInspectorProxy> create(WebPageProxy* page) + static Ref<WebInspectorProxy> create(WebPageProxy* inspectedPage) { - return adoptRef(new WebInspectorProxy(page)); + return adoptRef(*new WebInspectorProxy(inspectedPage)); } ~WebInspectorProxy(); @@ -81,9 +80,9 @@ public: void invalidate(); // Public APIs - WebPageProxy* page() const { return m_page; } + WebPageProxy* inspectedPage() const { return m_inspectedPage; } - bool isConnected() const { return m_createdInspectorPage; } + bool isConnected() const { return !!m_inspectorPage; } bool isVisible() const { return m_isVisible; } bool isFront(); @@ -92,51 +91,56 @@ public: void show(); void hide(); void close(); - -#if PLATFORM(MAC) + + void didRelaunchInspectorPageProcess(); + +#if PLATFORM(MAC) && WK_API_ENABLED void createInspectorWindow(); void updateInspectorWindowTitle() const; void inspectedViewFrameDidChange(CGFloat = 0); void windowFrameDidChange(); + void windowFullScreenDidChange(); NSWindow* inspectorWindow() const { return m_inspectorWindow.get(); } void setInspectorWindowFrame(WKRect&); WKRect inspectorWindowFrame(); + + void closeTimerFired(); + + void attachmentViewDidChange(NSView *oldView, NSView *newView); #endif #if PLATFORM(GTK) GtkWidget* inspectorView() const { return m_inspectorView; }; - void initializeInspectorClientGtk(const WKInspectorClientGtk*); + void initializeInspectorClientGtk(const WKInspectorClientGtkBase*); #endif void showConsole(); void showResources(); void showMainResourceForFrame(WebFrameProxy*); + AttachmentSide attachmentSide() const { return m_attachmentSide; } bool isAttached() const { return m_isAttached; } void attachRight(); void attachBottom(); - void attach(AttachmentSide = AttachmentSideBottom); + void attach(AttachmentSide = AttachmentSide::Bottom); void detach(); void setAttachedWindowHeight(unsigned); void setAttachedWindowWidth(unsigned); - void setToolbarHeight(unsigned height) { platformSetToolbarHeight(height); } - - bool isDebuggingJavaScript() const { return m_isDebuggingJavaScript; } - void toggleJavaScriptDebugging(); - bool isProfilingJavaScript() const { return m_isProfilingJavaScript; } - void toggleJavaScriptProfiling(); + void startWindowDrag(); bool isProfilingPage() const { return m_isProfilingPage; } void togglePageProfiling(); - static bool isInspectorPage(WebPageProxy*); + static bool isInspectorProcessPool(WebProcessPool&); + static bool isInspectorPage(WebPageProxy&); - // Implemented the platform WebInspectorProxy file - String inspectorPageURL() const; - String inspectorBaseURL() const; + // Provided by platform WebInspectorProxy implementations. + static String inspectorPageURL(); + static String inspectorTestPageURL(); + static String inspectorBaseURL(); #if ENABLE(INSPECTOR_SERVER) void enableRemoteInspection(); @@ -149,13 +153,17 @@ public: private: explicit WebInspectorProxy(WebPageProxy*); - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + static WebProcessPool& inspectorProcessPool(unsigned inspectionLevel); + + void eagerlyCreateInspectorPage(); + + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; WebPageProxy* platformCreateInspectorPage(); void platformOpen(); void platformDidClose(); + void platformInvalidate(); void platformBringToFront(); void platformHide(); bool platformIsFront(); @@ -167,81 +175,95 @@ private: void platformDetach(); void platformSetAttachedWindowHeight(unsigned); void platformSetAttachedWindowWidth(unsigned); - void platformSetToolbarHeight(unsigned); - void platformSave(const String& filename, const String& content, bool forceSaveAs); + void platformStartWindowDrag(); + void platformSave(const String& filename, const String& content, bool base64Encoded, bool forceSaveAs); void platformAppend(const String& filename, const String& content); +#if PLATFORM(MAC) && WK_API_ENABLED + bool platformCanAttach(bool webProcessCanAttach); +#else + bool platformCanAttach(bool webProcessCanAttach) { return webProcessCanAttach; } +#endif + // Called by WebInspectorProxy messages - void createInspectorPage(uint64_t& inspectorPageID, WebPageCreationParameters&); + void createInspectorPage(IPC::Attachment, bool canAttach, bool underTest); void didClose(); void bringToFront(); void attachAvailabilityChanged(bool); void inspectedURLChanged(const String&); - void save(const String& filename, const String& content, bool forceSaveAs); + void save(const String& filename, const String& content, bool base64Encoded, bool forceSaveAs); void append(const String& filename, const String& content); #if ENABLE(INSPECTOR_SERVER) void sendMessageToRemoteFrontend(const String& message); #endif - bool canAttach(); + bool canAttach() const { return m_canAttach; } bool shouldOpenAttached(); + bool isUnderTest() const { return m_underTest; } + void open(); - static WebPageGroup* inspectorPageGroup(); + // The inspection level is used to give different preferences to each inspector + // by setting a per-level page group identifier. Local storage settings in the frontend + // also use the inspection level in the key prefix to disambiguate persistent view state. + unsigned inspectionLevel() const; + String inspectorPageGroupIdentifier() const; + WebPreferences& inspectorPagePreferences() const; #if PLATFORM(GTK) || PLATFORM(EFL) void createInspectorWindow(); #endif +#if PLATFORM(GTK) + void updateInspectorWindowTitle() const; +#endif + static const unsigned minimumWindowWidth; static const unsigned minimumWindowHeight; static const unsigned initialWindowWidth; static const unsigned initialWindowHeight; - // Keep this in sync with the value in InspectorFrontendClientLocal. - static const unsigned minimumAttachedWidth; - static const unsigned minimumAttachedHeight; + WebPageProxy* m_inspectedPage {nullptr}; + WebPageProxy* m_inspectorPage {nullptr}; - WebPageProxy* m_page; + bool m_underTest {false}; + bool m_isVisible {false}; + bool m_isAttached {false}; + bool m_canAttach {false}; + bool m_isProfilingPage {false}; + bool m_showMessageSent {false}; + bool m_ignoreFirstBringToFront {false}; - bool m_isVisible; - bool m_isAttached; - bool m_isDebuggingJavaScript; - bool m_isProfilingJavaScript; - bool m_isProfilingPage; - bool m_showMessageSent; - bool m_createdInspectorPage; - bool m_ignoreFirstBringToFront; + IPC::Attachment m_connectionIdentifier; - AttachmentSide m_attachmentSide; + AttachmentSide m_attachmentSide {AttachmentSide::Bottom}; -#if PLATFORM(MAC) - RetainPtr<WKWebInspectorWKView> m_inspectorView; +#if PLATFORM(MAC) && WK_API_ENABLED + RetainPtr<WKWebInspectorWKWebView> m_inspectorView; RetainPtr<NSWindow> m_inspectorWindow; - RetainPtr<NSButton> m_dockBottomButton; - RetainPtr<NSButton> m_dockRightButton; RetainPtr<WKWebInspectorProxyObjCAdapter> m_inspectorProxyObjCAdapter; - String m_urlString; HashMap<String, RetainPtr<NSURL>> m_suggestedToActualURLMap; + RunLoop::Timer<WebInspectorProxy> m_closeTimer; + String m_urlString; #elif PLATFORM(GTK) WebInspectorClientGtk m_client; - GtkWidget* m_inspectorView; - GtkWidget* m_inspectorWindow; + GtkWidget* m_inspectorView {nullptr}; + GtkWidget* m_inspectorWindow {nullptr}; + GtkWidget* m_headerBar {nullptr}; + String m_inspectedURLString; #elif PLATFORM(EFL) - Evas_Object* m_inspectorView; - Ecore_Evas* m_inspectorWindow; + Evas_Object* m_inspectorView {nullptr}; + Ecore_Evas* m_inspectorWindow {nullptr}; #endif #if ENABLE(INSPECTOR_SERVER) - int m_remoteInspectionPageId; + int m_remoteInspectionPageId {0}; #endif }; } // namespace WebKit -#endif // ENABLE(INSPECTOR) - #endif // WebInspectorProxy_h diff --git a/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in b/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in index 17f77a5ca..7f13b67d2 100644 --- a/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebInspectorProxy.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2010 Apple Inc. All rights reserved. +# Copyright (C) 2010, 2014 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions @@ -20,29 +20,29 @@ # 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 ENABLE(INSPECTOR) - messages -> WebInspectorProxy { - CreateInspectorPage() -> (uint64_t inspectorPageID, WebKit::WebPageCreationParameters inspectorPageParameters) + CreateInspectorPage(IPC::Attachment connectionIdentifier, bool canAttach, bool underTest) + DidClose() BringToFront() - InspectedURLChanged(WTF::String urlString) - Save(WTF::String filename, WTF::String content, bool forceSaveAs) - Append(WTF::String filename, WTF::String content) + InspectedURLChanged(String urlString) + + Save(String filename, String content, bool base64Encoded, bool forceSaveAs) + Append(String filename, String content) AttachBottom() AttachRight() Detach() + AttachAvailabilityChanged(bool available) SetAttachedWindowHeight(unsigned height) SetAttachedWindowWidth(unsigned width) - SetToolbarHeight(unsigned height) + + StartWindowDrag() #if ENABLE(INSPECTOR_SERVER) - SendMessageToRemoteFrontend(WTF::String message) + SendMessageToRemoteFrontend(String message) #endif } - -#endif diff --git a/Source/WebKit2/UIProcess/WebKeyValueStorageManager.cpp b/Source/WebKit2/UIProcess/WebKeyValueStorageManager.cpp deleted file mode 100644 index cb10ee0b2..000000000 --- a/Source/WebKit2/UIProcess/WebKeyValueStorageManager.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebKeyValueStorageManager.h" - -#include "SecurityOriginData.h" -#include "WebContext.h" -#include "WebSecurityOrigin.h" - -using namespace WebCore; - -namespace WebKit { - -const char* WebKeyValueStorageManager::supplementName() -{ - return "WebKeyValueStorageManager"; -} - -PassRefPtr<WebKeyValueStorageManager> WebKeyValueStorageManager::create(WebContext* context) -{ - return adoptRef(new WebKeyValueStorageManager(context)); -} - -WebKeyValueStorageManager::WebKeyValueStorageManager(WebContext* context) - : WebContextSupplement(context) -{ -} - -WebKeyValueStorageManager::~WebKeyValueStorageManager() -{ -} - -// WebContextSupplement - -void WebKeyValueStorageManager::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebKeyValueStorageManager::derefWebContextSupplement() -{ - APIObject::deref(); -} - -static void didGetKeyValueStorageOrigins(const Vector<RefPtr<WebCore::SecurityOrigin> >& securityOrigins, void* context) -{ - RefPtr<ArrayCallback> callback = adoptRef(static_cast<ArrayCallback*>(context)); - - Vector<RefPtr<APIObject> > webSecurityOrigins; - webSecurityOrigins.reserveInitialCapacity(securityOrigins.size()); - - for (unsigned i = 0; i < securityOrigins.size(); ++i) - webSecurityOrigins.uncheckedAppend(WebSecurityOrigin::create(securityOrigins[i])); - - callback->performCallbackWithReturnValue(ImmutableArray::adopt(webSecurityOrigins).get()); -} - -void WebKeyValueStorageManager::getKeyValueStorageOrigins(PassRefPtr<ArrayCallback> prpCallback) -{ - context()->storageManager().getOrigins(RunLoop::main(), prpCallback.leakRef(), didGetKeyValueStorageOrigins); -} - -void WebKeyValueStorageManager::deleteEntriesForOrigin(WebSecurityOrigin* origin) -{ - context()->storageManager().deleteEntriesForOrigin(origin->securityOrigin()); -} - -void WebKeyValueStorageManager::deleteAllEntries() -{ - context()->storageManager().deleteAllEntries(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebKeyValueStorageManager.h b/Source/WebKit2/UIProcess/WebKeyValueStorageManager.h deleted file mode 100644 index eb1c8eb6e..000000000 --- a/Source/WebKit2/UIProcess/WebKeyValueStorageManager.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebKeyValueStorageManager_h -#define WebKeyValueStorageManager_h - -#include "APIObject.h" -#include "GenericCallback.h" -#include "ImmutableArray.h" -#include "MessageReceiver.h" -#include "WebContextSupplement.h" -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebKit { - -typedef GenericCallback<WKArrayRef> ArrayCallback; - -class WebKeyValueStorageManager : public TypedAPIObject<APIObject::TypeKeyValueStorageManager>, public WebContextSupplement { -public: - static const char* supplementName(); - - static PassRefPtr<WebKeyValueStorageManager> create(WebContext*); - virtual ~WebKeyValueStorageManager(); - - void getKeyValueStorageOrigins(PassRefPtr<ArrayCallback>); - void deleteEntriesForOrigin(WebSecurityOrigin*); - void deleteAllEntries(); - - using APIObject::ref; - using APIObject::deref; - -private: - explicit WebKeyValueStorageManager(WebContext*); - - // WebContextSupplement - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; -}; - -} // namespace WebKit - -#endif // WebKeyValueStorageManager_h diff --git a/Source/WebKit2/UIProcess/WebLoaderClient.cpp b/Source/WebKit2/UIProcess/WebLoaderClient.cpp deleted file mode 100644 index e1c587c13..000000000 --- a/Source/WebKit2/UIProcess/WebLoaderClient.cpp +++ /dev/null @@ -1,340 +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 "WebLoaderClient.h" - -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "PluginInformation.h" -#include "WKAPICast.h" -#include "WebBackForwardListItem.h" -#include "WebPageProxy.h" -#include <string.h> - -using namespace WebCore; - -namespace WebKit { - -void WebLoaderClient::didStartProvisionalLoadForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didStartProvisionalLoadForFrame) - return; - - m_client.didStartProvisionalLoadForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didReceiveServerRedirectForProvisionalLoadForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didReceiveServerRedirectForProvisionalLoadForFrame) - return; - - m_client.didReceiveServerRedirectForProvisionalLoadForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFailProvisionalLoadWithErrorForFrame(WebPageProxy* page, WebFrameProxy* frame, const ResourceError& error, APIObject* userData) -{ - if (!m_client.didFailProvisionalLoadWithErrorForFrame) - return; - - m_client.didFailProvisionalLoadWithErrorForFrame(toAPI(page), toAPI(frame), toAPI(error), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didCommitLoadForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didCommitLoadForFrame) - return; - - m_client.didCommitLoadForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFinishDocumentLoadForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didFinishDocumentLoadForFrame) - return; - - m_client.didFinishDocumentLoadForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFinishLoadForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didFinishLoadForFrame) - return; - - m_client.didFinishLoadForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFailLoadWithErrorForFrame(WebPageProxy* page, WebFrameProxy* frame, const ResourceError& error, APIObject* userData) -{ - if (!m_client.didFailLoadWithErrorForFrame) - return; - - m_client.didFailLoadWithErrorForFrame(toAPI(page), toAPI(frame), toAPI(error), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didSameDocumentNavigationForFrame(WebPageProxy* page, WebFrameProxy* frame, SameDocumentNavigationType type, APIObject* userData) -{ - if (!m_client.didSameDocumentNavigationForFrame) - return; - - m_client.didSameDocumentNavigationForFrame(toAPI(page), toAPI(frame), toAPI(type), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didReceiveTitleForFrame(WebPageProxy* page, const String& title, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didReceiveTitleForFrame) - return; - - m_client.didReceiveTitleForFrame(toAPI(page), toAPI(title.impl()), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFirstLayoutForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didFirstLayoutForFrame) - return; - - m_client.didFirstLayoutForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFirstVisuallyNonEmptyLayoutForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didFirstVisuallyNonEmptyLayoutForFrame) - return; - - m_client.didFirstVisuallyNonEmptyLayoutForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didNewFirstVisuallyNonEmptyLayout(WebPageProxy* page, APIObject* userData) -{ - if (!m_client.didNewFirstVisuallyNonEmptyLayout) - return; - - m_client.didNewFirstVisuallyNonEmptyLayout(toAPI(page), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didLayout(WebPageProxy* page, LayoutMilestones milestones, APIObject* userData) -{ - if (!m_client.didLayout) - return; - - m_client.didLayout(toAPI(page), toWKLayoutMilestones(milestones), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didRemoveFrameFromHierarchy(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didRemoveFrameFromHierarchy) - return; - - m_client.didRemoveFrameFromHierarchy(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didDisplayInsecureContentForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didDisplayInsecureContentForFrame) - return; - - m_client.didDisplayInsecureContentForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didRunInsecureContentForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didRunInsecureContentForFrame) - return; - - m_client.didRunInsecureContentForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didDetectXSSForFrame(WebPageProxy* page, WebFrameProxy* frame, APIObject* userData) -{ - if (!m_client.didDetectXSSForFrame) - return; - - m_client.didDetectXSSForFrame(toAPI(page), toAPI(frame), toAPI(userData), m_client.clientInfo); -} - -bool WebLoaderClient::canAuthenticateAgainstProtectionSpaceInFrame(WebPageProxy* page, WebFrameProxy* frame, WebProtectionSpace* protectionSpace) -{ - if (!m_client.canAuthenticateAgainstProtectionSpaceInFrame) - return false; - - return m_client.canAuthenticateAgainstProtectionSpaceInFrame(toAPI(page), toAPI(frame), toAPI(protectionSpace), m_client.clientInfo); -} - -void WebLoaderClient::didReceiveAuthenticationChallengeInFrame(WebPageProxy* page, WebFrameProxy* frame, AuthenticationChallengeProxy* authenticationChallenge) -{ - if (!m_client.didReceiveAuthenticationChallengeInFrame) - return; - - m_client.didReceiveAuthenticationChallengeInFrame(toAPI(page), toAPI(frame), toAPI(authenticationChallenge), m_client.clientInfo); -} - -void WebLoaderClient::didStartProgress(WebPageProxy* page) -{ - if (!m_client.didStartProgress) - return; - - m_client.didStartProgress(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::didChangeProgress(WebPageProxy* page) -{ - if (!m_client.didChangeProgress) - return; - - m_client.didChangeProgress(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::didFinishProgress(WebPageProxy* page) -{ - if (!m_client.didFinishProgress) - return; - - m_client.didFinishProgress(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::processDidBecomeUnresponsive(WebPageProxy* page) -{ - if (!m_client.processDidBecomeUnresponsive) - return; - - m_client.processDidBecomeUnresponsive(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::interactionOccurredWhileProcessUnresponsive(WebPageProxy* page) -{ - if (!m_client.interactionOccurredWhileProcessUnresponsive) - return; - - m_client.interactionOccurredWhileProcessUnresponsive(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::processDidBecomeResponsive(WebPageProxy* page) -{ - if (!m_client.processDidBecomeResponsive) - return; - - m_client.processDidBecomeResponsive(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::processDidCrash(WebPageProxy* page) -{ - if (!m_client.processDidCrash) - return; - - m_client.processDidCrash(toAPI(page), m_client.clientInfo); -} - -void WebLoaderClient::didChangeBackForwardList(WebPageProxy* page, WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject> >* removedItems) -{ - if (!m_client.didChangeBackForwardList) - return; - - RefPtr<ImmutableArray> removedItemsArray; - if (removedItems && !removedItems->isEmpty()) - removedItemsArray = ImmutableArray::adopt(*removedItems); - - m_client.didChangeBackForwardList(toAPI(page), toAPI(addedItem), toAPI(removedItemsArray.get()), m_client.clientInfo); -} - -bool WebLoaderClient::shouldGoToBackForwardListItem(WebPageProxy* page, WebBackForwardListItem* item) -{ - // We should only even considering sending the shouldGoToBackForwardListItem() client callback - // for version 0 clients. Later versioned clients should get willGoToBackForwardListItem() instead, - // but due to XPC race conditions this one might have been called instead. - if (m_client.version > 0 || !m_client.shouldGoToBackForwardListItem) - return true; - - return m_client.shouldGoToBackForwardListItem(toAPI(page), toAPI(item), m_client.clientInfo); -} - -void WebLoaderClient::willGoToBackForwardListItem(WebPageProxy* page, WebBackForwardListItem* item, APIObject* userData) -{ - if (m_client.willGoToBackForwardListItem) - m_client.willGoToBackForwardListItem(toAPI(page), toAPI(item), toAPI(userData), m_client.clientInfo); -} - -void WebLoaderClient::didFailToInitializePlugin(WebPageProxy* page, ImmutableDictionary* pluginInformation) -{ - if (m_client.didFailToInitializePlugin_deprecatedForUseWithV0) - m_client.didFailToInitializePlugin_deprecatedForUseWithV0( - toAPI(page), - toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), - m_client.clientInfo); - - if (m_client.pluginDidFail_deprecatedForUseWithV1) - m_client.pluginDidFail_deprecatedForUseWithV1( - toAPI(page), - kWKErrorCodeCannotLoadPlugIn, - toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), - 0, - 0, - m_client.clientInfo); - - if (m_client.pluginDidFail) - m_client.pluginDidFail( - toAPI(page), - kWKErrorCodeCannotLoadPlugIn, - toAPI(pluginInformation), - m_client.clientInfo); -} - -void WebLoaderClient::didBlockInsecurePluginVersion(WebPageProxy* page, ImmutableDictionary* pluginInformation) -{ - if (m_client.pluginDidFail_deprecatedForUseWithV1) - m_client.pluginDidFail_deprecatedForUseWithV1( - toAPI(page), - kWKErrorCodeInsecurePlugInVersion, - toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), - toAPI(pluginInformation->get<WebString>(pluginInformationBundleIdentifierKey())), - toAPI(pluginInformation->get<WebString>(pluginInformationBundleVersionKey())), - m_client.clientInfo); - - if (m_client.pluginDidFail) - m_client.pluginDidFail( - toAPI(page), - kWKErrorCodeInsecurePlugInVersion, - toAPI(pluginInformation), - m_client.clientInfo); -} - -PluginModuleLoadPolicy WebLoaderClient::pluginLoadPolicy(WebPageProxy* page, PluginModuleLoadPolicy currentPluginLoadPolicy, ImmutableDictionary* pluginInformation, String& unavailabilityDescription) -{ - WKStringRef unavailabilityDescriptionOut = 0; - PluginModuleLoadPolicy loadPolicy = currentPluginLoadPolicy; - - if (m_client.pluginLoadPolicy_deprecatedForUseWithV2) - loadPolicy = toPluginModuleLoadPolicy(m_client.pluginLoadPolicy_deprecatedForUseWithV2(toAPI(page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), m_client.clientInfo)); - else if (m_client.pluginLoadPolicy) - loadPolicy = toPluginModuleLoadPolicy(m_client.pluginLoadPolicy(toAPI(page), toWKPluginLoadPolicy(currentPluginLoadPolicy), toAPI(pluginInformation), &unavailabilityDescriptionOut, m_client.clientInfo)); - - if (unavailabilityDescriptionOut) { - RefPtr<WebString> webUnavailabilityDescription = adoptRef(toImpl(unavailabilityDescriptionOut)); - unavailabilityDescription = webUnavailabilityDescription->string(); - } - - return loadPolicy; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebLoaderClient.h b/Source/WebKit2/UIProcess/WebLoaderClient.h deleted file mode 100644 index c3fe2b422..000000000 --- a/Source/WebKit2/UIProcess/WebLoaderClient.h +++ /dev/null @@ -1,100 +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 WebLoaderClient_h -#define WebLoaderClient_h - -#include "APIClient.h" -#include "PluginModuleInfo.h" -#include "SameDocumentNavigationType.h" -#include "WKPage.h" -#include <WebCore/LayoutMilestones.h> -#include <wtf/Forward.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { -class ResourceError; -} - -namespace WebKit { - -class APIObject; -class AuthenticationChallengeProxy; -class AuthenticationDecisionListener; -class ImmutableDictionary; -class WebBackForwardListItem; -class WebFrameProxy; -class WebPageProxy; -class WebProtectionSpace; - -class WebLoaderClient : public APIClient<WKPageLoaderClient, kWKPageLoaderClientCurrentVersion> { -public: - void didStartProvisionalLoadForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didReceiveServerRedirectForProvisionalLoadForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didFailProvisionalLoadWithErrorForFrame(WebPageProxy*, WebFrameProxy*, const WebCore::ResourceError&, APIObject*); - void didCommitLoadForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didFinishDocumentLoadForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didFinishLoadForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didFailLoadWithErrorForFrame(WebPageProxy*, WebFrameProxy*, const WebCore::ResourceError&, APIObject*); - void didSameDocumentNavigationForFrame(WebPageProxy*, WebFrameProxy*, SameDocumentNavigationType, APIObject*); - void didReceiveTitleForFrame(WebPageProxy*, const String&, WebFrameProxy*, APIObject*); - void didFirstLayoutForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didFirstVisuallyNonEmptyLayoutForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didRemoveFrameFromHierarchy(WebPageProxy*, WebFrameProxy*, APIObject*); - void didDisplayInsecureContentForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didRunInsecureContentForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - void didDetectXSSForFrame(WebPageProxy*, WebFrameProxy*, APIObject*); - - // FIXME: didNewFirstVisuallyNonEmptyLayout should be removed. We should consider removing didFirstVisuallyNonEmptyLayoutForFrame - // as well. They are both being replaced by didLayout. - void didNewFirstVisuallyNonEmptyLayout(WebPageProxy*, APIObject*); - void didLayout(WebPageProxy*, WebCore::LayoutMilestones, APIObject*); - - bool canAuthenticateAgainstProtectionSpaceInFrame(WebPageProxy*, WebFrameProxy*, WebProtectionSpace*); - void didReceiveAuthenticationChallengeInFrame(WebPageProxy*, WebFrameProxy*, AuthenticationChallengeProxy*); - - void didStartProgress(WebPageProxy*); - void didChangeProgress(WebPageProxy*); - void didFinishProgress(WebPageProxy*); - - // FIXME: These three functions should not be part of this client. - void processDidBecomeUnresponsive(WebPageProxy*); - void interactionOccurredWhileProcessUnresponsive(WebPageProxy*); - void processDidBecomeResponsive(WebPageProxy*); - void processDidCrash(WebPageProxy*); - - void didChangeBackForwardList(WebPageProxy*, WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject> >* removedItems); - bool shouldGoToBackForwardListItem(WebPageProxy*, WebBackForwardListItem*); - void willGoToBackForwardListItem(WebPageProxy*, WebBackForwardListItem*, APIObject*); - - PluginModuleLoadPolicy pluginLoadPolicy(WebPageProxy*, PluginModuleLoadPolicy currentPluginLoadPolicy, ImmutableDictionary*, String& unavailabilityDescriptionOutParameter); - void didFailToInitializePlugin(WebPageProxy*, ImmutableDictionary*); - void didBlockInsecurePluginVersion(WebPageProxy*, ImmutableDictionary*); -}; - -} // namespace WebKit - -#endif // WebLoaderClient_h diff --git a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp deleted file mode 100644 index 425dc91e8..000000000 --- a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebMediaCacheManagerProxy.h" - -#include "WebContext.h" -#include "WebMediaCacheManagerMessages.h" -#include "WebMediaCacheManagerProxyMessages.h" -#include "WebSecurityOrigin.h" - -namespace WebKit { - -const char* WebMediaCacheManagerProxy::supplementName() -{ - return "WebMediaCacheManagerProxy"; -} - -PassRefPtr<WebMediaCacheManagerProxy> WebMediaCacheManagerProxy::create(WebContext* context) -{ - return adoptRef(new WebMediaCacheManagerProxy(context)); -} - -WebMediaCacheManagerProxy::WebMediaCacheManagerProxy(WebContext* context) - : WebContextSupplement(context) -{ - WebContextSupplement::context()->addMessageReceiver(Messages::WebMediaCacheManagerProxy::messageReceiverName(), this); -} - -WebMediaCacheManagerProxy::~WebMediaCacheManagerProxy() -{ -} - -// WebContextSupplement - -void WebMediaCacheManagerProxy::contextDestroyed() -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -void WebMediaCacheManagerProxy::processDidClose(WebProcessProxy*) -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -bool WebMediaCacheManagerProxy::shouldTerminate(WebProcessProxy*) const -{ - return m_arrayCallbacks.isEmpty(); -} - -void WebMediaCacheManagerProxy::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebMediaCacheManagerProxy::derefWebContextSupplement() -{ - APIObject::deref(); -} - -void WebMediaCacheManagerProxy::getHostnamesWithMediaCache(PassRefPtr<ArrayCallback> prpCallback) -{ - RefPtr<ArrayCallback> callback = prpCallback; - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> When we're sending this to multiple processes, we need to aggregate the callback data when it comes back. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::GetHostnamesWithMediaCache(callbackID)); -} - -void WebMediaCacheManagerProxy::didGetHostnamesWithMediaCache(const Vector<String>& hostnameList, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - if (!callback) { - // FIXME: Log error or assert. - return; - } - - size_t hostnameCount = hostnameList.size(); - Vector<RefPtr<APIObject> > hostnames(hostnameCount); - - for (size_t i = 0; i < hostnameCount; ++i) - hostnames[i] = WebString::create(hostnameList[i]); - - callback->performCallbackWithReturnValue(ImmutableArray::adopt(hostnames).get()); -} - -void WebMediaCacheManagerProxy::clearCacheForHostname(const String& hostname) -{ - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::ClearCacheForHostname(hostname)); -} - -void WebMediaCacheManagerProxy::clearCacheForAllHostnames() -{ - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebMediaCacheManager::ClearCacheForAllHostnames()); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h deleted file mode 100644 index 5c10b24f0..000000000 --- a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebMediaCacheManagerProxy_h -#define WebMediaCacheManagerProxy_h - -#include "APIObject.h" -#include "GenericCallback.h" -#include "ImmutableArray.h" -#include "MessageReceiver.h" -#include "WebContextSupplement.h" -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebKit { - -class WebContext; -class WebProcessProxy; - -typedef GenericCallback<WKArrayRef> ArrayCallback; - -class WebMediaCacheManagerProxy : public TypedAPIObject<APIObject::TypeMediaCacheManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { -public: - static const char* supplementName(); - - static PassRefPtr<WebMediaCacheManagerProxy> create(WebContext*); - virtual ~WebMediaCacheManagerProxy(); - - void getHostnamesWithMediaCache(PassRefPtr<ArrayCallback>); - void clearCacheForHostname(const String&); - void clearCacheForAllHostnames(); - - using APIObject::ref; - using APIObject::deref; - -private: - explicit WebMediaCacheManagerProxy(WebContext*); - - void didGetHostnamesWithMediaCache(const Vector<String>&, uint64_t callbackID); - - // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; -}; - -} // namespace WebKit - -#endif // WebMediaCacheManagerProxy_h diff --git a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.messages.in deleted file mode 100644 index 7929064a8..000000000 --- a/Source/WebKit2/UIProcess/WebMediaCacheManagerProxy.messages.in +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (C) 2011 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -messages -> WebMediaCacheManagerProxy { - DidGetHostnamesWithMediaCache(Vector<WTF::String> hostnames, uint64_t callbackID); -} diff --git a/Source/WebKit2/UIProcess/WebMediaSessionFocusManager.cpp b/Source/WebKit2/UIProcess/WebMediaSessionFocusManager.cpp new file mode 100644 index 000000000..4bf626e78 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebMediaSessionFocusManager.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2015 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 "WebMediaSessionFocusManager.h" + +#if ENABLE(MEDIA_SESSION) + +#include "WebProcessPool.h" + +namespace WebKit { + +const char* WebMediaSessionFocusManager::supplementName() +{ + return "WebMediaSessionFocusManager"; +} + +PassRefPtr<WebMediaSessionFocusManager> WebMediaSessionFocusManager::create(WebProcessPool* processPool) +{ + return adoptRef(new WebMediaSessionFocusManager(processPool)); +} + +WebMediaSessionFocusManager::WebMediaSessionFocusManager(WebProcessPool* processPool) + : WebContextSupplement(processPool) { } + +// WebContextSupplement + +void WebMediaSessionFocusManager::refWebContextSupplement() +{ + API::Object::ref(); +} + +void WebMediaSessionFocusManager::derefWebContextSupplement() +{ + API::Object::deref(); +} + +void WebMediaSessionFocusManager::initializeClient(const WKMediaSessionFocusManagerClientBase* client) +{ + m_client.initialize(client); +} + +bool WebMediaSessionFocusManager::valueForPlaybackAttribute(WKMediaSessionFocusManagerPlaybackAttribute attribute) const +{ + if (!m_focusedMediaElement) + return false; + + return m_playbackAttributes & attribute; +} + +void WebMediaSessionFocusManager::updatePlaybackAttribute(WKMediaSessionFocusManagerPlaybackAttribute attribute, bool value) +{ + if (value) + m_playbackAttributes |= attribute; + else + m_playbackAttributes &= ~attribute; + + m_client.didChangePlaybackAttribute(this, attribute, value); +} + +void WebMediaSessionFocusManager::setVolumeOfFocusedMediaElement(double volume) +{ + if (!m_focusedMediaElement) + return; + + if (WebPageProxy* proxy = m_focusedMediaElement->first) + proxy->setVolumeOfMediaElement(volume, m_focusedMediaElement->second); +} + +void WebMediaSessionFocusManager::updatePlaybackAttributesFromMediaState(WebPageProxy* proxy, uint64_t elementID, WebCore::MediaProducer::MediaStateFlags flags) +{ + if (m_focusedMediaElement) { + if (proxy == m_focusedMediaElement->first && elementID == m_focusedMediaElement->second) { + updatePlaybackAttribute(IsPlaying, flags & WebCore::MediaProducer::IsSourceElementPlaying); + updatePlaybackAttribute(IsNextTrackControlEnabled, flags & WebCore::MediaProducer::IsNextTrackControlEnabled); + updatePlaybackAttribute(IsPreviousTrackControlEnabled, flags & WebCore::MediaProducer::IsPreviousTrackControlEnabled); + } + } +} + +void WebMediaSessionFocusManager::setFocusedMediaElement(WebPageProxy& proxy, uint64_t elementID) +{ + m_focusedMediaElement = std::make_unique<FocusedMediaElement>(&proxy, elementID); +} + +void WebMediaSessionFocusManager::clearFocusedMediaElement() +{ + m_focusedMediaElement = nullptr; +} + +} // namespace WebKit + +#endif // ENABLE(MEDIA_SESSION) diff --git a/Source/WebKit2/UIProcess/WebMediaSessionFocusManager.h b/Source/WebKit2/UIProcess/WebMediaSessionFocusManager.h new file mode 100644 index 000000000..d3bfd4519 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebMediaSessionFocusManager.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2015 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 WebMediaSessionFocusManager_h +#define WebMediaSessionFocusManager_h + +#if ENABLE(MEDIA_SESSION) + +#include "APIObject.h" +#include "WebContextSupplement.h" +#include "WebMediaSessionFocusManagerClient.h" +#include "WebPageProxy.h" + +namespace WebKit { + +typedef std::pair<WebPageProxy*, uint64_t> FocusedMediaElement; + +class WebMediaSessionFocusManager : public API::ObjectImpl<API::Object::Type::MediaSessionFocusManager>, public WebContextSupplement { +public: + static const char* supplementName(); + + static PassRefPtr<WebMediaSessionFocusManager> create(WebProcessPool*); + + void initializeClient(const WKMediaSessionFocusManagerClientBase*); + + bool valueForPlaybackAttribute(WKMediaSessionFocusManagerPlaybackAttribute) const; + void updatePlaybackAttributesFromMediaState(WebPageProxy*, uint64_t, WebCore::MediaProducer::MediaStateFlags); + void setVolumeOfFocusedMediaElement(double); + + void setFocusedMediaElement(WebPageProxy&, uint64_t); + void clearFocusedMediaElement(); + + using API::Object::ref; + using API::Object::deref; + +private: + explicit WebMediaSessionFocusManager(WebProcessPool*); + + // WebContextSupplement + virtual void refWebContextSupplement() override; + virtual void derefWebContextSupplement() override; + + void updatePlaybackAttribute(WKMediaSessionFocusManagerPlaybackAttribute, bool); + + std::unique_ptr<FocusedMediaElement> m_focusedMediaElement; + WKMediaSessionFocusManagerPlaybackAttributes m_playbackAttributes { 0 }; + WebMediaSessionFocusManagerClient m_client; +}; + +} // namespace WebKit + +#endif // ENABLE(MEDIA_SESSION) + +#endif /* WebMediaSessionFocusManager_h */ diff --git a/Source/WebKit2/UIProcess/efl/EwkTouchPoint.cpp b/Source/WebKit2/UIProcess/WebMediaSessionFocusManagerClient.cpp index 6efa67d9f..54a6f3782 100644 --- a/Source/WebKit2/UIProcess/efl/EwkTouchPoint.cpp +++ b/Source/WebKit2/UIProcess/WebMediaSessionFocusManagerClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,23 +24,23 @@ */ #include "config.h" -#include "EwkTouchPoint.h" +#include "WebMediaSessionFocusManagerClient.h" -#if ENABLE(TOUCH_EVENTS) +#if ENABLE(MEDIA_SESSION) + +#include "WKAPICast.h" +#include "WebMediaSessionFocusManager.h" namespace WebKit { -EwkTouchPoint::EwkTouchPoint(uint32_t id, WKTouchPointState state, const WKPoint& screenPosition, const WKPoint& position, const WKSize& radius, float rotationAngle, float forceFactor) - : m_id(id) - , m_state(state) - , m_screenPosition(screenPosition) - , m_position(position) - , m_radius(radius) - , m_rotationAngle(rotationAngle) - , m_forceFactor(forceFactor) +void WebMediaSessionFocusManagerClient::didChangePlaybackAttribute(WebMediaSessionFocusManager* manager, WKMediaSessionFocusManagerPlaybackAttribute playbackAttribute, bool value) { + if (!m_client.didChangePlaybackAttribute) + return; + + m_client.didChangePlaybackAttribute(toAPI(manager), playbackAttribute, value, m_client.base.clientInfo); } } // namespace WebKit -#endif // ENABLE(TOUCH_EVENTS) +#endif // ENABLE(MEDIA_SESSION) diff --git a/Source/WebKit2/UIProcess/gtk/WebInspectorClientGtk.h b/Source/WebKit2/UIProcess/WebMediaSessionFocusManagerClient.h index 89d0f73d9..ef69a6690 100644 --- a/Source/WebKit2/UIProcess/gtk/WebInspectorClientGtk.h +++ b/Source/WebKit2/UIProcess/WebMediaSessionFocusManagerClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Igalia S.L. + * Copyright (C) 2015 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,30 +23,32 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebInspectorClientGtk_h -#define WebInspectorClientGtk_h +#ifndef WebMediaSessionFocusManagerClient_h +#define WebMediaSessionFocusManagerClient_h + +#if ENABLE(MEDIA_SESSION) #include "APIClient.h" -#include "WKInspectorClientGtk.h" +#include "WKMediaSessionFocusManager.h" +#include <wtf/Forward.h> -#include <wtf/text/WTFString.h> +namespace API { +template<> struct ClientTraits<WKMediaSessionFocusManagerClientBase> { + typedef std::tuple<WKMediaSessionFocusManagerClientV0> Versions; +}; +} namespace WebKit { -class APIObject; -class WebInspectorProxy; +class WebMediaSessionFocusManager; -class WebInspectorClientGtk : public APIClient<WKInspectorClientGtk, kWKInspectorClientGtkCurrentVersion> { +class WebMediaSessionFocusManagerClient : public API::Client<WKMediaSessionFocusManagerClientBase> { public: - bool openWindow(WebInspectorProxy*); - void didClose(WebInspectorProxy*); - bool bringToFront(WebInspectorProxy*); - void inspectedURLChanged(WebInspectorProxy*, const String& url); - bool attach(WebInspectorProxy*); - bool detach(WebInspectorProxy*); - void didChangeAttachedHeight(WebInspectorProxy*, unsigned height); + void didChangePlaybackAttribute(WebMediaSessionFocusManager*, WKMediaSessionFocusManagerPlaybackAttribute, bool); }; } // namespace WebKit -#endif // WebInspectorClientGtk_h +#endif // ENABLE(MEDIA_SESSION) + +#endif // WebMediaSessionFocusManagerClient_h diff --git a/Source/WebKit2/UIProcess/WebNavigationState.cpp b/Source/WebKit2/UIProcess/WebNavigationState.cpp new file mode 100644 index 000000000..43d57ccbb --- /dev/null +++ b/Source/WebKit2/UIProcess/WebNavigationState.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2015 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 "WebNavigationState.h" + +#include "APINavigation.h" +#include "WebPageProxy.h" +#include <WebCore/ResourceRequest.h> + +namespace WebKit { + +WebNavigationState::WebNavigationState() +{ +} + +WebNavigationState::~WebNavigationState() +{ +} + +Ref<API::Navigation> WebNavigationState::createLoadRequestNavigation(const WebCore::ResourceRequest& request) +{ + auto navigation = API::Navigation::create(*this, request); + + m_navigations.set(navigation->navigationID(), navigation.ptr()); + + return navigation; +} + +Ref<API::Navigation> WebNavigationState::createBackForwardNavigation() +{ + auto navigation = API::Navigation::create(*this); + + m_navigations.set(navigation->navigationID(), navigation.ptr()); + + return navigation; +} + +Ref<API::Navigation> WebNavigationState::createReloadNavigation() +{ + auto navigation = API::Navigation::create(*this); + + m_navigations.set(navigation->navigationID(), navigation.ptr()); + + return navigation; +} + +Ref<API::Navigation> WebNavigationState::createLoadDataNavigation() +{ + auto navigation = API::Navigation::create(*this); + + m_navigations.set(navigation->navigationID(), navigation.ptr()); + + return navigation; +} + +API::Navigation& WebNavigationState::navigation(uint64_t navigationID) +{ + ASSERT(navigationID); + + return *m_navigations.get(navigationID); +} + +Ref<API::Navigation> WebNavigationState::takeNavigation(uint64_t navigationID) +{ + ASSERT(navigationID); + + return m_navigations.take(navigationID).releaseNonNull(); +} + +void WebNavigationState::didDestroyNavigation(uint64_t navigationID) +{ + ASSERT(navigationID); + + m_navigations.remove(navigationID); +} + +void WebNavigationState::clearAllNavigations() +{ + m_navigations.clear(); +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.h b/Source/WebKit2/UIProcess/WebNavigationState.h index 20ffd0b67..13b0c9727 100644 --- a/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.h +++ b/Source/WebKit2/UIProcess/WebNavigationState.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,42 +23,50 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebContextMenuProxyMac_h -#define WebContextMenuProxyMac_h +#ifndef WebNavigationState_h +#define WebNavigationState_h -#include "WebContextMenuProxy.h" -#include <wtf/RetainPtr.h> +#include <wtf/HashMap.h> +#include <wtf/Ref.h> -OBJC_CLASS NSPopUpButtonCell; -OBJC_CLASS WKView; +namespace API { +class Navigation; +} + +namespace WebCore { +class ResourceRequest; +} namespace WebKit { class WebPageProxy; +class WebBackForwardListItem; -class WebContextMenuProxyMac : public WebContextMenuProxy { +class WebNavigationState { public: - static PassRefPtr<WebContextMenuProxyMac> create(WKView* webView, WebPageProxy* page) - { - return adoptRef(new WebContextMenuProxyMac(webView, page)); - } - ~WebContextMenuProxyMac(); + explicit WebNavigationState(); + ~WebNavigationState(); - virtual void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); - virtual void hideContextMenu(); - - void contextMenuItemSelected(const WebContextMenuItemData&); + Ref<API::Navigation> createBackForwardNavigation(); + Ref<API::Navigation> createLoadRequestNavigation(const WebCore::ResourceRequest&); + Ref<API::Navigation> createReloadNavigation(); + Ref<API::Navigation> createLoadDataNavigation(); -private: - WebContextMenuProxyMac(WKView*, WebPageProxy*); + API::Navigation& navigation(uint64_t navigationID); + Ref<API::Navigation> takeNavigation(uint64_t navigationID); + void didDestroyNavigation(uint64_t navigationID); + void clearAllNavigations(); - void populate(const Vector<WebContextMenuItemData>&); + uint64_t generateNavigationID() + { + return ++m_navigationID; + } - RetainPtr<NSPopUpButtonCell> m_popup; - WKView* m_webView; - WebPageProxy* m_page; +private: + HashMap<uint64_t, RefPtr<API::Navigation>> m_navigations; + uint64_t m_navigationID { 0 }; }; } // namespace WebKit -#endif // WebContextMenuProxyMac_h +#endif // WebNavigationState_h diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp deleted file mode 100644 index 0e439d219..000000000 --- a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.cpp +++ /dev/null @@ -1,124 +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 "WebNetworkInfoManagerProxy.h" - -#if ENABLE(NETWORK_INFO) - -#include "WebContext.h" -#include "WebNetworkInfo.h" -#include "WebNetworkInfoManagerMessages.h" -#include "WebNetworkInfoManagerProxyMessages.h" - -namespace WebKit { - -const char* WebNetworkInfoManagerProxy::supplementName() -{ - return "WebNetworkInfoManagerProxy"; -} - -PassRefPtr<WebNetworkInfoManagerProxy> WebNetworkInfoManagerProxy::create(WebContext* context) -{ - return adoptRef(new WebNetworkInfoManagerProxy(context)); -} - -WebNetworkInfoManagerProxy::WebNetworkInfoManagerProxy(WebContext* context) - : WebContextSupplement(context) - , m_isUpdating(false) -{ - WebContextSupplement::context()->addMessageReceiver(Messages::WebNetworkInfoManagerProxy::messageReceiverName(), this); -} - -WebNetworkInfoManagerProxy::~WebNetworkInfoManagerProxy() -{ -} - -void WebNetworkInfoManagerProxy::initializeProvider(const WKNetworkInfoProvider* provider) -{ - m_provider.initialize(provider); -} - -void WebNetworkInfoManagerProxy::providerDidChangeNetworkInformation(const AtomicString& eventType, WebNetworkInfo* networkInformation) -{ - if (!context()) - return; - - context()->sendToAllProcesses(Messages::WebNetworkInfoManager::DidChangeNetworkInformation(eventType, networkInformation->data())); -} - -// WebContextSupplement - -void WebNetworkInfoManagerProxy::contextDestroyed() -{ - stopUpdating(); -} - -void WebNetworkInfoManagerProxy::processDidClose(WebProcessProxy*) -{ - stopUpdating(); -} - -void WebNetworkInfoManagerProxy::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebNetworkInfoManagerProxy::derefWebContextSupplement() -{ - APIObject::deref(); -} - -void WebNetworkInfoManagerProxy::startUpdating() -{ - if (m_isUpdating) - return; - - m_provider.startUpdating(this); - m_isUpdating = true; -} - -void WebNetworkInfoManagerProxy::stopUpdating() -{ - if (!m_isUpdating) - return; - - m_provider.stopUpdating(this); - m_isUpdating = false; -} - -void WebNetworkInfoManagerProxy::getBandwidth(double& bandwidth) -{ - bandwidth = m_provider.bandwidth(this); -} - -void WebNetworkInfoManagerProxy::isMetered(bool& isMetered) -{ - isMetered = m_provider.isMetered(this); -} - -} // namespace WebKit - -#endif // ENABLE(NETWORK_INFO) diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h deleted file mode 100644 index a74a2b8ba..000000000 --- a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.h +++ /dev/null @@ -1,85 +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 WebNetworkInfoManagerProxy_h -#define WebNetworkInfoManagerProxy_h - -#if ENABLE(NETWORK_INFO) - -#include "APIObject.h" -#include "MessageReceiver.h" -#include "WebContextSupplement.h" -#include "WebNetworkInfoProvider.h" -#include <wtf/Forward.h> - -namespace WebKit { - -class WebContext; -class WebNetworkInfo; - -class WebNetworkInfoManagerProxy : public TypedAPIObject<APIObject::TypeNetworkInfoManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { -public: - static const char* supplementName(); - - static PassRefPtr<WebNetworkInfoManagerProxy> create(WebContext*); - virtual ~WebNetworkInfoManagerProxy(); - - void initializeProvider(const WKNetworkInfoProvider*); - - void providerDidChangeNetworkInformation(const WTF::AtomicString& eventType, WebNetworkInfo*); - - using APIObject::ref; - using APIObject::deref; - -private: - explicit WebNetworkInfoManagerProxy(WebContext*); - - // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; - - void startUpdating(); - void stopUpdating(); - - void getBandwidth(double&); - void isMetered(bool&); - - bool m_isUpdating; - - WebContext* m_context; - WebNetworkInfoProvider m_provider; -}; - -} // namespace WebKit - -#endif // ENABLE(NETWORK_INFO) - -#endif // WebNetworkInfoManagerProxy_h diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.messages.in deleted file mode 100644 index b6acdc26b..000000000 --- a/Source/WebKit2/UIProcess/WebNetworkInfoManagerProxy.messages.in +++ /dev/null @@ -1,33 +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. - -#if ENABLE(NETWORK_INFO) - -messages -> WebNetworkInfoManagerProxy { - StartUpdating(); - StopUpdating(); - - GetBandwidth() -> (double bandwidth); - IsMetered() -> (bool metered); -} - -#endif diff --git a/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.cpp b/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.cpp index 288a736fb..a377e4af0 100644 --- a/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.cpp +++ b/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.cpp @@ -26,9 +26,10 @@ #include "config.h" #include "WebOpenPanelResultListenerProxy.h" -#include "ImmutableArray.h" +#include "APIArray.h" +#include "APIString.h" #include "WebPageProxy.h" -#include <WebCore/KURL.h> +#include <WebCore/URL.h> #include <wtf/Vector.h> using namespace WebCore; @@ -44,25 +45,38 @@ WebOpenPanelResultListenerProxy::~WebOpenPanelResultListenerProxy() { } -void WebOpenPanelResultListenerProxy::chooseFiles(ImmutableArray* fileURLsArray) +static Vector<String> filePathsFromFileURLs(const API::Array& fileURLs) { - if (!m_page) - return; - - size_t size = fileURLsArray->size(); - Vector<String> filePaths; + + size_t size = fileURLs.size(); filePaths.reserveInitialCapacity(size); for (size_t i = 0; i < size; ++i) { - WebURL* webURL = fileURLsArray->at<WebURL>(i); - if (webURL) { - KURL url(KURL(), webURL->string()); - filePaths.uncheckedAppend(url.fileSystemPath()); - } + API::URL* apiURL = fileURLs.at<API::URL>(i); + if (apiURL) + filePaths.uncheckedAppend(URL(URL(), apiURL->string()).fileSystemPath()); } - m_page->didChooseFilesForOpenPanel(filePaths); + return filePaths; +} + +#if PLATFORM(IOS) +void WebOpenPanelResultListenerProxy::chooseFiles(API::Array* fileURLsArray, API::String* displayString, const API::Data* iconImageData) +{ + if (!m_page) + return; + + m_page->didChooseFilesForOpenPanelWithDisplayStringAndIcon(filePathsFromFileURLs(*fileURLsArray), displayString ? displayString->string() : String(), iconImageData); +} +#endif + +void WebOpenPanelResultListenerProxy::chooseFiles(API::Array* fileURLsArray) +{ + if (!m_page) + return; + + m_page->didChooseFilesForOpenPanel(filePathsFromFileURLs(*fileURLsArray)); } void WebOpenPanelResultListenerProxy::cancel() @@ -75,7 +89,7 @@ void WebOpenPanelResultListenerProxy::cancel() void WebOpenPanelResultListenerProxy::invalidate() { - m_page = 0; + m_page = nullptr; } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h b/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h index 98ab30ce8..ae6eaf788 100644 --- a/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h +++ b/Source/WebKit2/UIProcess/WebOpenPanelResultListenerProxy.h @@ -30,12 +30,17 @@ #include <wtf/PassRefPtr.h> #include <wtf/RefPtr.h> +namespace API { +class Array; +class Data; +class String; +} + namespace WebKit { -class ImmutableArray; class WebPageProxy; -class WebOpenPanelResultListenerProxy : public TypedAPIObject<APIObject::TypeFramePolicyListener> { +class WebOpenPanelResultListenerProxy : public API::ObjectImpl<API::Object::Type::FramePolicyListener> { public: static PassRefPtr<WebOpenPanelResultListenerProxy> create(WebPageProxy* page) { @@ -44,7 +49,10 @@ public: virtual ~WebOpenPanelResultListenerProxy(); - void chooseFiles(ImmutableArray*); +#if PLATFORM(IOS) + void chooseFiles(API::Array*, API::String* displayString, const API::Data* iconImageData); +#endif + void chooseFiles(API::Array*); void cancel(); void invalidate(); diff --git a/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp b/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp deleted file mode 100644 index 96275760c..000000000 --- a/Source/WebKit2/UIProcess/WebPageContextMenuClient.cpp +++ /dev/null @@ -1,125 +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" - -#if ENABLE(CONTEXT_MENUS) - -#include "WebPageContextMenuClient.h" - -#include "Logging.h" -#include "MutableArray.h" -#include "WebContextMenuItem.h" -#include "WKAPICast.h" -#include "WKSharedAPICast.h" - -namespace WebKit { - -bool WebPageContextMenuClient::getContextMenuFromProposedMenu(WebPageProxy* page, const Vector<WebContextMenuItemData>& proposedMenuVector, Vector<WebContextMenuItemData>& customMenu, const WebHitTestResult::Data& hitTestResultData, APIObject* userData) -{ - if (!m_client.getContextMenuFromProposedMenu && !m_client.getContextMenuFromProposedMenu_deprecatedForUseWithV0) - return false; - - if (m_client.version >= 2 && !m_client.getContextMenuFromProposedMenu) - return false; - - unsigned size = proposedMenuVector.size(); - RefPtr<MutableArray> proposedMenu = MutableArray::create(); - proposedMenu->reserveCapacity(size); - for (unsigned i = 0; i < size; ++i) - proposedMenu->append(WebContextMenuItem::create(proposedMenuVector[i]).get()); - - WKArrayRef newMenu = 0; - if (m_client.version >= 2) { - RefPtr<WebHitTestResult> webHitTestResult = WebHitTestResult::create(hitTestResultData); - m_client.getContextMenuFromProposedMenu(toAPI(page), toAPI(proposedMenu.get()), &newMenu, toAPI(webHitTestResult.get()), toAPI(userData), m_client.clientInfo); - } else - m_client.getContextMenuFromProposedMenu_deprecatedForUseWithV0(toAPI(page), toAPI(proposedMenu.get()), &newMenu, toAPI(userData), m_client.clientInfo); - - RefPtr<ImmutableArray> array = adoptRef(toImpl(newMenu)); - - customMenu.clear(); - - size_t newSize = array ? array->size() : 0; - for (size_t i = 0; i < newSize; ++i) { - WebContextMenuItem* item = array->at<WebContextMenuItem>(i); - if (!item) { - LOG(ContextMenu, "New menu entry at index %i is not a WebContextMenuItem", (int)i); - continue; - } - - customMenu.append(*item->data()); - } - - return true; -} - -void WebPageContextMenuClient::customContextMenuItemSelected(WebPageProxy* page, const WebContextMenuItemData& itemData) -{ - if (!m_client.customContextMenuItemSelected) - return; - - RefPtr<WebContextMenuItem> item = WebContextMenuItem::create(itemData); - m_client.customContextMenuItemSelected(toAPI(page), toAPI(item.get()), m_client.clientInfo); -} - -void WebPageContextMenuClient::contextMenuDismissed(WebPageProxy* page) -{ - if (!m_client.contextMenuDismissed) - return; - - m_client.contextMenuDismissed(toAPI(page), m_client.clientInfo); -} - -bool WebPageContextMenuClient::showContextMenu(WebPageProxy* page, const WebCore::IntPoint& menuLocation, const Vector<WebContextMenuItemData>& menuItemsVector) -{ - if (!m_client.showContextMenu) - return false; - - unsigned size = menuItemsVector.size(); - - Vector<RefPtr<APIObject> > menuItems; - menuItems.reserveCapacity(size); - - for (unsigned i = 0; i < size; ++i) - menuItems.uncheckedAppend(WebContextMenuItem::create(menuItemsVector[i]).get()); - - m_client.showContextMenu(toAPI(page), toAPI(menuLocation), toAPI(ImmutableArray::adopt(menuItems).get()), m_client.clientInfo); - - return true; -} - -bool WebPageContextMenuClient::hideContextMenu(WebPageProxy* page) -{ - if (!m_client.hideContextMenu) - return false; - - m_client.hideContextMenu(toAPI(page), m_client.clientInfo); - - return true; -} - -} // namespace WebKit -#endif // ENABLE(CONTEXT_MENUS) diff --git a/Source/WebKit2/UIProcess/WebFindClient.cpp b/Source/WebKit2/UIProcess/WebPageDiagnosticLoggingClient.cpp index 702d187ca..d8e4263cd 100644 --- a/Source/WebKit2/UIProcess/WebFindClient.cpp +++ b/Source/WebKit2/UIProcess/WebPageDiagnosticLoggingClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,51 +24,41 @@ */ #include "config.h" -#include "WebFindClient.h" +#include "WebPageDiagnosticLoggingClient.h" + #include "WKAPICast.h" +#include "WebPageProxy.h" #include <wtf/text/WTFString.h> namespace WebKit { -void WebFindClient::didFindString(WebPageProxy* page, const String& string, uint32_t matchCount) -{ - if (!m_client.didFindString) - return; - - m_client.didFindString(toAPI(page), toAPI(string.impl()), matchCount, m_client.clientInfo); - -} - -void WebFindClient::didFailToFindString(WebPageProxy* page, const String& string) +WebPageDiagnosticLoggingClient::WebPageDiagnosticLoggingClient(const WKPageDiagnosticLoggingClientBase* client) { - if (!m_client.didFailToFindString) - return; - - m_client.didFailToFindString(toAPI(page), toAPI(string.impl()), m_client.clientInfo); + initialize(client); } -void WebFindClient::didCountStringMatches(WebPageProxy* page, const String& string, uint32_t matchCount) +void WebPageDiagnosticLoggingClient::logDiagnosticMessage(WebPageProxy* page, const String& message, const String& description) { - if (!m_client.didCountStringMatches) + if (!m_client.logDiagnosticMessage) return; - m_client.didCountStringMatches(toAPI(page), toAPI(string.impl()), matchCount, m_client.clientInfo); + m_client.logDiagnosticMessage(toAPI(page), toAPI(message.impl()), toAPI(description.impl()), m_client.base.clientInfo); } -void WebFindMatchesClient::didFindStringMatches(WebPageProxy* page, const String& string, ImmutableArray* matches, int firstIndex) +void WebPageDiagnosticLoggingClient::logDiagnosticMessageWithResult(WebPageProxy* page, const String& message, const String& description, WebCore::DiagnosticLoggingResultType result) { - if (!m_client.didFindStringMatches) + if (!m_client.logDiagnosticMessageWithResult) return; - m_client.didFindStringMatches(toAPI(page), toAPI(string.impl()), toAPI(matches), firstIndex, m_client.clientInfo); + m_client.logDiagnosticMessageWithResult(toAPI(page), toAPI(message.impl()), toAPI(description.impl()), toAPI(result), m_client.base.clientInfo); } -void WebFindMatchesClient::didGetImageForMatchResult(WebPageProxy* page, WebImage* image, uint32_t index) +void WebPageDiagnosticLoggingClient::logDiagnosticMessageWithValue(WebPageProxy* page, const String& message, const String& description, const String& value) { - if (!m_client.didGetImageForMatchResult) + if (!m_client.logDiagnosticMessageWithValue) return; - m_client.didGetImageForMatchResult(toAPI(page), toAPI(image), index, m_client.clientInfo); + + m_client.logDiagnosticMessageWithValue(toAPI(page), toAPI(message.impl()), toAPI(description.impl()), toAPI(value.impl()), m_client.base.clientInfo); } } // namespace WebKit - diff --git a/Source/WebKit2/UIProcess/WebFindClient.h b/Source/WebKit2/UIProcess/WebPageDiagnosticLoggingClient.h index 605f3d502..41c834f4c 100644 --- a/Source/WebKit2/UIProcess/WebFindClient.h +++ b/Source/WebKit2/UIProcess/WebPageDiagnosticLoggingClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,32 +23,36 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebFindClient_h -#define WebFindClient_h +#ifndef WebPageDiagnosticLoggingClient_h +#define WebPageDiagnosticLoggingClient_h #include "APIClient.h" +#include "APIDiagnosticLoggingClient.h" #include "WKPage.h" +#include <WebCore/DiagnosticLoggingResultType.h> #include <wtf/Forward.h> +namespace API { + +template<> struct ClientTraits<WKPageDiagnosticLoggingClientBase> { + typedef std::tuple<WKPageDiagnosticLoggingClientV0> Versions; +}; + +} // namespace API + namespace WebKit { -class ImmutableArray; class WebPageProxy; -class WebImage; -class WebFindClient : public APIClient<WKPageFindClient, kWKPageFindClientCurrentVersion> { +class WebPageDiagnosticLoggingClient final : public API::Client<WKPageDiagnosticLoggingClientBase>, public API::DiagnosticLoggingClient { public: - void didFindString(WebPageProxy*, const String&, uint32_t matchCount); - void didFailToFindString(WebPageProxy*, const String&); - void didCountStringMatches(WebPageProxy*, const String&, uint32_t matchCount); -}; + explicit WebPageDiagnosticLoggingClient(const WKPageDiagnosticLoggingClientBase*); -class WebFindMatchesClient : public APIClient<WKPageFindMatchesClient, kWKPageFindMatchesClientCurrentVersion> { -public: - void didFindStringMatches(WebPageProxy*, const String&, ImmutableArray*, int); - void didGetImageForMatchResult(WebPageProxy*, WebImage*, uint32_t); + virtual void logDiagnosticMessage(WebPageProxy*, const String& message, const String& description) override; + virtual void logDiagnosticMessageWithResult(WebPageProxy*, const String& message, const String& description, WebCore::DiagnosticLoggingResultType) override; + virtual void logDiagnosticMessageWithValue(WebPageProxy*, const String& message, const String& description, const String& value) override; }; } // namespace WebKit -#endif // WebFindClient_h +#endif // WebPageDiagnosticLoggingClient_h diff --git a/Source/WebKit2/UIProcess/WebPageGroup.cpp b/Source/WebKit2/UIProcess/WebPageGroup.cpp index 0cdbf817d..c8db22493 100644 --- a/Source/WebKit2/UIProcess/WebPageGroup.cpp +++ b/Source/WebKit2/UIProcess/WebPageGroup.cpp @@ -26,10 +26,14 @@ #include "config.h" #include "WebPageGroup.h" +#include "APIArray.h" +#include "APIUserContentExtension.h" +#include "WebCompiledContentExtension.h" #include "WebPageGroupProxyMessages.h" #include "WebPageProxy.h" #include "WebPreferences.h" #include <wtf/HashMap.h> +#include <wtf/NeverDestroyed.h> #include <wtf/text/StringConcatenate.h> namespace WebKit { @@ -44,17 +48,18 @@ typedef HashMap<uint64_t, WebPageGroup*> WebPageGroupMap; static WebPageGroupMap& webPageGroupMap() { - DEFINE_STATIC_LOCAL(WebPageGroupMap, map, ()); + static NeverDestroyed<WebPageGroupMap> map; return map; } PassRefPtr<WebPageGroup> WebPageGroup::create(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient) { - RefPtr<WebPageGroup> pageGroup = adoptRef(new WebPageGroup(identifier, visibleToInjectedBundle, visibleToHistoryClient)); - - webPageGroupMap().set(pageGroup->pageGroupID(), pageGroup.get()); + return adoptRef(new WebPageGroup(identifier, visibleToInjectedBundle, visibleToHistoryClient)); +} - return pageGroup.release(); +Ref<WebPageGroup> WebPageGroup::createNonNull(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient) +{ + return adoptRef(*new WebPageGroup(identifier, visibleToInjectedBundle, visibleToHistoryClient)); } WebPageGroup* WebPageGroup::get(uint64_t pageGroupID) @@ -62,23 +67,34 @@ WebPageGroup* WebPageGroup::get(uint64_t pageGroupID) return webPageGroupMap().get(pageGroupID); } -WebPageGroup::WebPageGroup(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient) +static WebPageGroupData pageGroupData(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient) { - m_data.pageGroupID = generatePageGroupID(); + WebPageGroupData data; - if (!identifier.isNull()) - m_data.identifer = identifier; + data.pageGroupID = generatePageGroupID(); + + if (!identifier.isEmpty()) + data.identifier = identifier; else - m_data.identifer = m_data.identifer = makeString("__uniquePageGroupID-", String::number(m_data.pageGroupID)); + data.identifier = makeString("__uniquePageGroupID-", String::number(data.pageGroupID)); + + data.visibleToInjectedBundle = visibleToInjectedBundle; + data.visibleToHistoryClient = visibleToHistoryClient; - m_data.visibleToInjectedBundle = visibleToInjectedBundle; - m_data.visibleToHistoryClient = visibleToHistoryClient; + return data; +} + +// FIXME: Why does the WebPreferences object here use ".WebKit2" instead of "WebKit2." which all the other constructors use. +// If it turns out that it's wrong, we can change it to to "WebKit2." and get rid of the globalDebugKeyPrefix from WebPreferences. +WebPageGroup::WebPageGroup(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient) + : m_data(pageGroupData(identifier, visibleToInjectedBundle, visibleToHistoryClient)) + , m_preferences(WebPreferences::createWithLegacyDefaults(m_data.identifier, ".WebKit2", "WebKit2.")) +{ + webPageGroupMap().set(m_data.pageGroupID, this); } WebPageGroup::~WebPageGroup() { - if (m_preferences) - m_preferences->removePageGroup(this); webPageGroupMap().remove(pageGroupID()); } @@ -97,28 +113,15 @@ void WebPageGroup::setPreferences(WebPreferences* preferences) if (preferences == m_preferences) return; - if (!m_preferences) { - m_preferences = preferences; - m_preferences->addPageGroup(this); - } else { - m_preferences->removePageGroup(this); - m_preferences = preferences; - m_preferences->addPageGroup(this); + m_preferences = preferences; - preferencesDidChange(); - } + for (auto& webPageProxy : m_pages) + webPageProxy->setPreferences(*m_preferences); } -WebPreferences* WebPageGroup::preferences() const +WebPreferences& WebPageGroup::preferences() const { - if (!m_preferences) { - if (!m_data.identifer.isNull()) - m_preferences = WebPreferences::create(m_data.identifer); - else - m_preferences = WebPreferences::create(); - m_preferences->addPageGroup(const_cast<WebPageGroup*>(this)); - } - return m_preferences.get(); + return *m_preferences; } void WebPageGroup::preferencesDidChange() @@ -129,43 +132,23 @@ void WebPageGroup::preferencesDidChange() } } -static Vector<String> toStringVector(ImmutableArray* array) -{ - Vector<String> patternVector; - if (!array) - return patternVector; - - size_t size = array->size(); - if (!size) - return patternVector; - - patternVector.reserveInitialCapacity(size); - for (size_t i = 0; i < size; ++i) { - WebString* webString = array->at<WebString>(i); - ASSERT(webString); - patternVector.uncheckedAppend(webString->string()); - } - - return patternVector; -} - -void WebPageGroup::addUserStyleSheet(const String& source, const String& baseURL, ImmutableArray* whitelist, ImmutableArray* blacklist, WebCore::UserContentInjectedFrames injectedFrames, WebCore::UserStyleLevel level) +void WebPageGroup::addUserStyleSheet(const String& source, const String& baseURL, API::Array* whitelist, API::Array* blacklist, WebCore::UserContentInjectedFrames injectedFrames, WebCore::UserStyleLevel level) { if (source.isEmpty()) return; - WebCore::UserStyleSheet userStyleSheet = WebCore::UserStyleSheet(source, (baseURL.isEmpty() ? WebCore::blankURL() : WebCore::KURL(WebCore::KURL(), baseURL)), toStringVector(whitelist), toStringVector(blacklist), injectedFrames, level); + WebCore::UserStyleSheet userStyleSheet = WebCore::UserStyleSheet(source, (baseURL.isEmpty() ? WebCore::blankURL() : WebCore::URL(WebCore::URL(), baseURL)), whitelist ? whitelist->toStringVector() : Vector<String>(), blacklist ? blacklist->toStringVector() : Vector<String>(), injectedFrames, level); m_data.userStyleSheets.append(userStyleSheet); sendToAllProcessesInGroup(Messages::WebPageGroupProxy::AddUserStyleSheet(userStyleSheet), m_data.pageGroupID); } -void WebPageGroup::addUserScript(const String& source, const String& baseURL, ImmutableArray* whitelist, ImmutableArray* blacklist, WebCore::UserContentInjectedFrames injectedFrames, WebCore::UserScriptInjectionTime injectionTime) +void WebPageGroup::addUserScript(const String& source, const String& baseURL, API::Array* whitelist, API::Array* blacklist, WebCore::UserContentInjectedFrames injectedFrames, WebCore::UserScriptInjectionTime injectionTime) { if (source.isEmpty()) return; - WebCore::UserScript userScript = WebCore::UserScript(source, (baseURL.isEmpty() ? WebCore::blankURL() : WebCore::KURL(WebCore::KURL(), baseURL)), toStringVector(whitelist), toStringVector(blacklist), injectionTime, injectedFrames); + WebCore::UserScript userScript = WebCore::UserScript(source, (baseURL.isEmpty() ? WebCore::blankURL() : WebCore::URL(WebCore::URL(), baseURL)), whitelist ? whitelist->toStringVector() : Vector<String>(), blacklist ? blacklist->toStringVector() : Vector<String>(), injectionTime, injectedFrames); m_data.userScripts.append(userScript); sendToAllProcessesInGroup(Messages::WebPageGroupProxy::AddUserScript(userScript), m_data.pageGroupID); @@ -190,4 +173,24 @@ void WebPageGroup::removeAllUserContent() sendToAllProcessesInGroup(Messages::WebPageGroupProxy::RemoveAllUserContent(), m_data.pageGroupID); } +#if ENABLE(CONTENT_EXTENSIONS) +void WebPageGroup::addUserContentExtension(const API::UserContentExtension& userContentExtension) +{ + m_data.userContentExtensions.set(userContentExtension.name(), userContentExtension.compiledExtension().data()); + sendToAllProcessesInGroup(Messages::WebPageGroupProxy::AddUserContentExtension(userContentExtension.name(), userContentExtension.compiledExtension().data()), m_data.pageGroupID); +} + +void WebPageGroup::removeUserContentExtension(const String& contentExtensionName) +{ + m_data.userContentExtensions.remove(contentExtensionName); + sendToAllProcessesInGroup(Messages::WebPageGroupProxy::RemoveUserContentExtension(contentExtensionName), m_data.pageGroupID); +} + +void WebPageGroup::removeAllUserContentExtensions() +{ + m_data.userContentExtensions.clear(); + sendToAllProcessesInGroup(Messages::WebPageGroupProxy::RemoveAllUserContentExtensions(), m_data.pageGroupID); +} +#endif + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPageGroup.h b/Source/WebKit2/UIProcess/WebPageGroup.h index f0fddf551..472993859 100644 --- a/Source/WebKit2/UIProcess/WebPageGroup.h +++ b/Source/WebKit2/UIProcess/WebPageGroup.h @@ -32,15 +32,18 @@ #include "WebProcessProxy.h" #include <wtf/Forward.h> #include <wtf/HashSet.h> +#include <wtf/text/WTFString.h> namespace WebKit { class WebPreferences; class WebPageProxy; -class WebPageGroup : public TypedAPIObject<APIObject::TypePageGroup> { +class WebPageGroup : public API::ObjectImpl<API::Object::Type::PageGroup> { public: + WebPageGroup(const String& identifier = String(), bool visibleToInjectedBundle = true, bool visibleToHistoryClient = true); static PassRefPtr<WebPageGroup> create(const String& identifier = String(), bool visibleToInjectedBundle = true, bool visibleToHistoryClient = true); + static Ref<WebPageGroup> createNonNull(const String& identifier = String(), bool visibleToInjectedBundle = true, bool visibleToHistoryClient = true); static WebPageGroup* get(uint64_t pageGroupID); virtual ~WebPageGroup(); @@ -48,41 +51,47 @@ public: void addPage(WebPageProxy*); void removePage(WebPageProxy*); - const String& identifier() const { return m_data.identifer; } + const String& identifier() const { return m_data.identifier; } uint64_t pageGroupID() const { return m_data.pageGroupID; } - const WebPageGroupData& data() { return m_data; } + const WebPageGroupData& data() const { return m_data; } void setPreferences(WebPreferences*); - WebPreferences* preferences() const; + WebPreferences& preferences() const; void preferencesDidChange(); - void addUserStyleSheet(const String& source, const String& baseURL, ImmutableArray* whitelist, ImmutableArray* blacklist, WebCore::UserContentInjectedFrames, WebCore::UserStyleLevel); - void addUserScript(const String& source, const String& baseURL, ImmutableArray* whitelist, ImmutableArray* blacklist, WebCore::UserContentInjectedFrames, WebCore::UserScriptInjectionTime); + void addUserStyleSheet(const String& source, const String& baseURL, API::Array* whitelist, API::Array* blacklist, WebCore::UserContentInjectedFrames, WebCore::UserStyleLevel); + void addUserScript(const String& source, const String& baseURL, API::Array* whitelist, API::Array* blacklist, WebCore::UserContentInjectedFrames, WebCore::UserScriptInjectionTime); void removeAllUserStyleSheets(); void removeAllUserScripts(); void removeAllUserContent(); -private: - WebPageGroup(const String& identifier, bool visibleToInjectedBundle, bool visibleToHistoryClient); +#if ENABLE(CONTENT_EXTENSIONS) + void addUserContentExtension(const API::UserContentExtension&); + void removeUserContentExtension(const String&); + void removeAllUserContentExtensions(); +#endif - template<typename MessageType> void sendToAllProcessesInGroup(const MessageType&, uint64_t destinationID); +private: + template<typename T> void sendToAllProcessesInGroup(const T&, uint64_t destinationID); WebPageGroupData m_data; - mutable RefPtr<WebPreferences> m_preferences; + RefPtr<WebPreferences> m_preferences; HashSet<WebPageProxy*> m_pages; }; - -template<typename MessageType> inline void WebPageGroup::sendToAllProcessesInGroup(const MessageType& message, uint64_t destinationID) + +template<typename T> +void WebPageGroup::sendToAllProcessesInGroup(const T& message, uint64_t destinationID) { HashSet<WebProcessProxy*> processesSeen; - for (HashSet<WebPageProxy*>::const_iterator it = m_pages.begin(), end = m_pages.end(); it != end; ++it) { - WebProcessProxy* webProcessProxy = (*it)->process(); - ASSERT(webProcessProxy); - if (!processesSeen.add(webProcessProxy).isNewEntry) + + for (WebPageProxy* webPageProxy : m_pages) { + WebProcessProxy& webProcessProxy = webPageProxy->process(); + if (!processesSeen.add(&webProcessProxy).isNewEntry) continue; - if (webProcessProxy->canSendMessage()) - webProcessProxy->send(message, destinationID); + + if (webProcessProxy.canSendMessage()) + webProcessProxy.send(T(message), destinationID); } } diff --git a/Source/WebKit2/UIProcess/WebDatabaseManagerProxyClient.cpp b/Source/WebKit2/UIProcess/WebPageInjectedBundleClient.cpp index 2f3c767e6..a89357533 100644 --- a/Source/WebKit2/UIProcess/WebDatabaseManagerProxyClient.cpp +++ b/Source/WebKit2/UIProcess/WebPageInjectedBundleClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,26 +24,32 @@ */ #include "config.h" -#include "WebDatabaseManagerProxyClient.h" +#include "WebPageInjectedBundleClient.h" #include "WKAPICast.h" +#include "WebProcessPool.h" +#include <wtf/text/WTFString.h> + +using namespace WebCore; namespace WebKit { -void WebDatabaseManagerProxyClient::didModifyOrigin(WebDatabaseManagerProxy* databaseManager, WebSecurityOrigin* origin) +void WebPageInjectedBundleClient::didReceiveMessageFromInjectedBundle(WebPageProxy* page, const String& messageName, API::Object* messageBody) { - if (!m_client.didModifyOrigin) + if (!m_client.didReceiveMessageFromInjectedBundle) return; - m_client.didModifyOrigin(toAPI(databaseManager), toAPI(origin), m_client.clientInfo); + m_client.didReceiveMessageFromInjectedBundle(toAPI(page), toAPI(messageName.impl()), toAPI(messageBody), m_client.base.clientInfo); } -void WebDatabaseManagerProxyClient::didModifyDatabase(WebDatabaseManagerProxy* databaseManager, WebSecurityOrigin* origin, const String& databaseIdentifier) +void WebPageInjectedBundleClient::didReceiveSynchronousMessageFromInjectedBundle(WebPageProxy* page, const String& messageName, API::Object* messageBody, RefPtr<API::Object>& returnData) { - if (!m_client.didModifyDatabase) + if (!m_client.didReceiveSynchronousMessageFromInjectedBundle) return; - m_client.didModifyDatabase(toAPI(databaseManager), toAPI(origin), toAPI(databaseIdentifier.impl()), m_client.clientInfo); + WKTypeRef returnDataRef = 0; + m_client.didReceiveSynchronousMessageFromInjectedBundle(toAPI(page), toAPI(messageName.impl()), toAPI(messageBody), &returnDataRef, m_client.base.clientInfo); + returnData = adoptRef(toImpl(returnDataRef)); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoProvider.h b/Source/WebKit2/UIProcess/WebPageInjectedBundleClient.h index f7205d05b..30c7f354c 100644 --- a/Source/WebKit2/UIProcess/WebNetworkInfoProvider.h +++ b/Source/WebKit2/UIProcess/WebPageInjectedBundleClient.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 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,30 +23,31 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebNetworkInfoProvider_h -#define WebNetworkInfoProvider_h - -#if ENABLE(NETWORK_INFO) +#ifndef WebPageInjectedBundleClient_h +#define WebPageInjectedBundleClient_h #include "APIClient.h" -#include "WKNetworkInfoManager.h" +#include "WKPage.h" #include <wtf/Forward.h> +namespace API { +class Object; + +template<> struct ClientTraits<WKPageInjectedBundleClientBase> { + typedef std::tuple<WKPageInjectedBundleClientV0> Versions; +}; +} + namespace WebKit { -class WebNetworkInfoManagerProxy; +class WebPageProxy; -class WebNetworkInfoProvider : public APIClient<WKNetworkInfoProvider, kWKNetworkInfoProviderCurrentVersion> { +class WebPageInjectedBundleClient : public API::Client<WKPageInjectedBundleClientBase> { public: - void startUpdating(WebNetworkInfoManagerProxy*); - void stopUpdating(WebNetworkInfoManagerProxy*); - - double bandwidth(WebNetworkInfoManagerProxy*) const; - bool isMetered(WebNetworkInfoManagerProxy*) const; + void didReceiveMessageFromInjectedBundle(WebPageProxy*, const String&, API::Object*); + void didReceiveSynchronousMessageFromInjectedBundle(WebPageProxy*, const String&, API::Object*, RefPtr<API::Object>& returnData); }; } // namespace WebKit -#endif // ENABLE(NETWORK_INFO) - -#endif // WebNetworkInfoProvider_h +#endif // WebPageInjectedBundleClient_h diff --git a/Source/WebKit2/UIProcess/WebPageProxy.cpp b/Source/WebKit2/UIProcess/WebPageProxy.cpp index 765a7cee1..85fdbf8ed 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.cpp +++ b/Source/WebKit2/UIProcess/WebPageProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011, 2015-2016 Apple Inc. All rights reserved. * Copyright (C) 2012 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,6 +27,26 @@ #include "config.h" #include "WebPageProxy.h" +#include "APIArray.h" +#include "APIContextMenuClient.h" +#include "APIFindClient.h" +#include "APIFindMatchesClient.h" +#include "APIFormClient.h" +#include "APIFrameInfo.h" +#include "APIGeometry.h" +#include "APIHistoryClient.h" +#include "APIHitTestResult.h" +#include "APILegacyContextHistoryClient.h" +#include "APILoaderClient.h" +#include "APINavigation.h" +#include "APINavigationAction.h" +#include "APINavigationClient.h" +#include "APINavigationResponse.h" +#include "APIPageConfiguration.h" +#include "APIPolicyClient.h" +#include "APISecurityOrigin.h" +#include "APIUIClient.h" +#include "APIURLRequest.h" #include "AuthenticationChallengeProxy.h" #include "AuthenticationDecisionListener.h" #include "DataReference.h" @@ -34,40 +54,42 @@ #include "DrawingAreaProxy.h" #include "DrawingAreaProxyMessages.h" #include "EventDispatcherMessages.h" -#include "FindIndicator.h" -#include "ImmutableArray.h" #include "Logging.h" +#include "NativeWebGestureEvent.h" #include "NativeWebKeyboardEvent.h" #include "NativeWebMouseEvent.h" #include "NativeWebWheelEvent.h" +#include "NavigationActionData.h" +#include "NetworkProcessMessages.h" #include "NotificationPermissionRequest.h" #include "NotificationPermissionRequestManager.h" #include "PageClient.h" #include "PluginInformation.h" #include "PluginProcessManager.h" #include "PrintInfo.h" -#include "SessionState.h" #include "TextChecker.h" #include "TextCheckerState.h" +#include "UserMediaPermissionRequestProxy.h" #include "WKContextPrivate.h" #include "WebBackForwardList.h" #include "WebBackForwardListItem.h" #include "WebCertificateInfo.h" -#include "WebColorPickerResultListenerProxy.h" -#include "WebContext.h" +#include "WebContextMenuItem.h" #include "WebContextMenuProxy.h" -#include "WebContextUserMessageCoders.h" #include "WebCoreArgumentCoders.h" -#include "WebData.h" #include "WebEditCommandProxy.h" #include "WebEvent.h" +#include "WebEventConversion.h" #include "WebFormSubmissionListenerProxy.h" #include "WebFramePolicyListenerProxy.h" #include "WebFullScreenManagerProxy.h" #include "WebFullScreenManagerProxyMessages.h" +#include "WebImage.h" #include "WebInspectorProxy.h" #include "WebInspectorProxyMessages.h" +#include "WebNavigationState.h" #include "WebNotificationManagerProxy.h" +#include "WebOpenPanelParameters.h" #include "WebOpenPanelResultListenerProxy.h" #include "WebPageCreationParameters.h" #include "WebPageGroup.h" @@ -78,35 +100,39 @@ #include "WebPopupMenuProxy.h" #include "WebPreferences.h" #include "WebProcessMessages.h" +#include "WebProcessPool.h" #include "WebProcessProxy.h" #include "WebProtectionSpace.h" -#include "WebSecurityOrigin.h" -#include "WebURLRequest.h" +#include "WebUserContentControllerProxy.h" +#include "WebsiteDataStore.h" +#include <WebCore/BitmapImage.h> +#include <WebCore/DiagnosticLoggingClient.h> #include <WebCore/DragController.h> #include <WebCore/DragData.h> -#include <WebCore/DragSession.h> #include <WebCore/FloatRect.h> #include <WebCore/FocusDirection.h> +#include <WebCore/JSDOMBinding.h> #include <WebCore/MIMETypeRegistry.h> #include <WebCore/RenderEmbeddedObject.h> +#include <WebCore/SerializedCryptoKeyWrap.h> #include <WebCore/TextCheckerClient.h> +#include <WebCore/TextIndicator.h> +#include <WebCore/URL.h> #include <WebCore/WindowFeatures.h> #include <stdio.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/text/StringView.h> -#if USE(COORDINATED_GRAPHICS) -#include "CoordinatedLayerTreeHostProxyMessages.h" +#if ENABLE(ASYNC_SCROLLING) +#include "RemoteScrollingCoordinatorProxy.h" #endif #if PLATFORM(QT) #include "ArgumentCodersQt.h" #endif -#if PLATFORM(GTK) -#include "ArgumentCodersGtk.h" -#endif - -#if USE(SOUP) -#include "WebSoupRequestManagerProxy.h" +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) +#include "CoordinatedLayerTreeHostProxyMessages.h" #endif #if ENABLE(VIBRATION) @@ -117,6 +143,36 @@ #include <wtf/RefCountedLeakCounter.h> #endif +#if PLATFORM(COCOA) +#include "RemoteLayerTreeDrawingAreaProxy.h" +#include "RemoteLayerTreeScrollingPerformanceData.h" +#include "ViewSnapshotStore.h" +#include "WebVideoFullscreenManagerProxy.h" +#include "WebVideoFullscreenManagerProxyMessages.h" +#include <WebCore/MachSendRight.h> +#include <WebCore/RunLoopObserver.h> +#include <WebCore/TextIndicatorWindow.h> +#endif + +#if USE(CAIRO) +#include <WebCore/CairoUtilities.h> +#endif + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) +#include <WebCore/MediaPlaybackTarget.h> +#include <WebCore/WebMediaSessionManager.h> +#endif + +#if ENABLE(MEDIA_SESSION) +#include "WebMediaSessionFocusManager.h" +#include "WebMediaSessionMetadata.h" +#include <WebCore/MediaSessionMetadata.h> +#endif + +#if USE(APPLE_INTERNAL_SDK) +#include <WebKitAdditions/WebPageProxyIncludes.h> +#endif + // This controls what strategy we use for mouse wheel coalescing. #define MERGE_WHEEL_EVENTS 1 @@ -130,12 +186,11 @@ static const unsigned wheelEventQueueSizeThreshold = 10; namespace WebKit { -WKPageDebugPaintFlags WebPageProxy::s_debugPaintFlags = 0; - DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, webPageProxyCounter, ("WebPageProxy")); class ExceededDatabaseQuotaRecords { WTF_MAKE_NONCOPYABLE(ExceededDatabaseQuotaRecords); WTF_MAKE_FAST_ALLOCATED; + friend class NeverDestroyed<ExceededDatabaseQuotaRecords>; public: struct Record { uint64_t frameID; @@ -149,37 +204,37 @@ public: RefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply; }; - static ExceededDatabaseQuotaRecords& shared(); + static ExceededDatabaseQuotaRecords& singleton(); - PassOwnPtr<Record> createRecord(uint64_t frameID, String originIdentifier, + std::unique_ptr<Record> createRecord(uint64_t frameID, String originIdentifier, String databaseName, String displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply>); - void add(PassOwnPtr<Record>); - bool areBeingProcessed() const { return m_currentRecord; } + void add(std::unique_ptr<Record>); + bool areBeingProcessed() const { return !!m_currentRecord; } Record* next(); private: ExceededDatabaseQuotaRecords() { } ~ExceededDatabaseQuotaRecords() { } - Deque<OwnPtr<Record> > m_records; - OwnPtr<Record> m_currentRecord; + Deque<std::unique_ptr<Record>> m_records; + std::unique_ptr<Record> m_currentRecord; }; -ExceededDatabaseQuotaRecords& ExceededDatabaseQuotaRecords::shared() +ExceededDatabaseQuotaRecords& ExceededDatabaseQuotaRecords::singleton() { - DEFINE_STATIC_LOCAL(ExceededDatabaseQuotaRecords, records, ()); + static NeverDestroyed<ExceededDatabaseQuotaRecords> records; return records; } -PassOwnPtr<ExceededDatabaseQuotaRecords::Record> ExceededDatabaseQuotaRecords::createRecord( +std::unique_ptr<ExceededDatabaseQuotaRecords::Record> ExceededDatabaseQuotaRecords::createRecord( uint64_t frameID, String originIdentifier, String databaseName, String displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply) { - OwnPtr<Record> record = adoptPtr(new Record); + auto record = std::make_unique<Record>(); record->frameID = frameID; record->originIdentifier = originIdentifier; record->databaseName = databaseName; @@ -189,17 +244,17 @@ PassOwnPtr<ExceededDatabaseQuotaRecords::Record> ExceededDatabaseQuotaRecords::c record->currentDatabaseUsage = currentDatabaseUsage; record->expectedUsage = expectedUsage; record->reply = reply; - return record.release(); + return record; } -void ExceededDatabaseQuotaRecords::add(PassOwnPtr<ExceededDatabaseQuotaRecords::Record> record) +void ExceededDatabaseQuotaRecords::add(std::unique_ptr<ExceededDatabaseQuotaRecords::Record> record) { - m_records.append(record); + m_records.append(WTFMove(record)); } ExceededDatabaseQuotaRecords::Record* ExceededDatabaseQuotaRecords::next() { - m_currentRecord.clear(); + m_currentRecord = nullptr; if (!m_records.isEmpty()) m_currentRecord = m_records.takeFirst(); return m_currentRecord.get(); @@ -228,44 +283,91 @@ static const char* webKeyboardEventTypeString(WebEvent::Type type) } #endif // !LOG_DISABLED -PassRefPtr<WebPageProxy> WebPageProxy::create(PageClient* pageClient, PassRefPtr<WebProcessProxy> process, WebPageGroup* pageGroup, uint64_t pageID) +class PageClientProtector { + WTF_MAKE_NONCOPYABLE(PageClientProtector); +public: + PageClientProtector(PageClient& pageClient) + : m_pageClient(pageClient) + { + m_pageClient.refView(); + } + + ~PageClientProtector() + { + m_pageClient.derefView(); + } + +private: + PageClient& m_pageClient; +}; + +Ref<WebPageProxy> WebPageProxy::create(PageClient& pageClient, WebProcessProxy& process, uint64_t pageID, Ref<API::PageConfiguration>&& configuration) { - return adoptRef(new WebPageProxy(pageClient, process, pageGroup, pageID)); + return adoptRef(*new WebPageProxy(pageClient, process, pageID, WTFMove(configuration))); } -WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> process, WebPageGroup* pageGroup, uint64_t pageID) +WebPageProxy::WebPageProxy(PageClient& pageClient, WebProcessProxy& process, uint64_t pageID, Ref<API::PageConfiguration>&& configuration) : m_pageClient(pageClient) + , m_configuration(WTFMove(configuration)) + , m_loaderClient(std::make_unique<API::LoaderClient>()) + , m_policyClient(std::make_unique<API::PolicyClient>()) + , m_formClient(std::make_unique<API::FormClient>()) + , m_uiClient(std::make_unique<API::UIClient>()) + , m_findClient(std::make_unique<API::FindClient>()) + , m_findMatchesClient(std::make_unique<API::FindMatchesClient>()) + , m_diagnosticLoggingClient(std::make_unique<API::DiagnosticLoggingClient>()) +#if ENABLE(CONTEXT_MENUS) + , m_contextMenuClient(std::make_unique<API::ContextMenuClient>()) +#endif + , m_navigationState(std::make_unique<WebNavigationState>()) , m_process(process) - , m_pageGroup(pageGroup) - , m_mainFrame(0) + , m_pageGroup(*m_configuration->pageGroup()) + , m_preferences(*m_configuration->preferences()) + , m_userContentController(m_configuration->userContentController()) + , m_visitedLinkStore(*m_configuration->visitedLinkStore()) + , m_websiteDataStore(m_configuration->websiteDataStore()->websiteDataStore()) + , m_mainFrame(nullptr) , m_userAgent(standardUserAgent()) - , m_geolocationPermissionRequestManager(this) - , m_notificationPermissionRequestManager(this) - , m_estimatedProgress(0) - , m_isInWindow(m_pageClient->isViewInWindow()) - , m_isVisible(m_pageClient->isViewVisible()) - , m_backForwardList(WebBackForwardList::create(this)) - , m_loadStateAtProcessExit(WebFrameProxy::LoadStateFinished) - , m_temporarilyClosedComposition(false) + , m_treatsSHA1CertificatesAsInsecure(m_configuration->treatsSHA1SignedCertificatesAsInsecure()) +#if PLATFORM(IOS) + , m_hasReceivedLayerTreeTransactionAfterDidCommitLoad(true) + , m_firstLayerTreeTransactionIdAfterDidCommitLoad(0) + , m_deviceOrientation(0) + , m_dynamicViewportSizeUpdateWaitingForTarget(false) + , m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit(false) + , m_dynamicViewportSizeUpdateLayerTreeTransactionID(0) + , m_layerTreeTransactionIdAtLastTouchStart(0) + , m_hasNetworkRequestsOnSuspended(false) +#endif + , m_geolocationPermissionRequestManager(*this) + , m_notificationPermissionRequestManager(*this) + , m_userMediaPermissionRequestManager(*this) + , m_viewState(ViewState::NoFlags) + , m_viewWasEverInWindow(false) +#if PLATFORM(IOS) + , m_alwaysRunsAtForegroundPriority(m_configuration->alwaysRunsAtForegroundPriority()) +#endif + , m_backForwardList(WebBackForwardList::create(*this)) + , m_loadStateAtProcessExit(FrameLoadState::LoadStateFinished) + , m_maintainsInactiveSelection(false) + , m_isEditable(false) , m_textZoomFactor(1) , m_pageZoomFactor(1) , m_pageScaleFactor(1) + , m_pluginZoomFactor(1) + , m_pluginScaleFactor(1) , m_intrinsicDeviceScaleFactor(1) , m_customDeviceScaleFactor(0) -#if HAVE(LAYER_HOSTING_IN_WINDOW_SERVER) - , m_layerHostingMode(LayerHostingModeInWindowServer) -#else - , m_layerHostingMode(LayerHostingModeDefault) -#endif + , m_topContentInset(0) + , m_layerHostingMode(LayerHostingMode::InProcess) , m_drawsBackground(true) - , m_drawsTransparentBackground(false) - , m_areMemoryCacheClientCallsEnabled(true) , m_useFixedLayout(false) , m_suppressScrollbarAnimations(false) , m_paginationMode(Pagination::Unpaginated) , m_paginationBehavesLikeColumns(false) , m_pageLength(0) , m_gapBetweenPages(0) + , m_paginationLineGridEnabled(false) , m_isValid(true) , m_isClosed(false) , m_canRunModal(false) @@ -282,85 +384,138 @@ WebPageProxy::WebPageProxy(PageClient* pageClient, PassRefPtr<WebProcessProxy> p , m_syncNavigationActionPolicyDownloadID(0) , m_processingMouseMoveEvent(false) #if ENABLE(TOUCH_EVENTS) - , m_needTouchEvents(false) + , m_isTrackingTouchEvents(false) #endif , m_pageID(pageID) + , m_sessionID(m_configuration->sessionID()) , m_isPageSuspended(false) -#if PLATFORM(MAC) + , m_addsVisitedLinks(true) +#if ENABLE(REMOTE_INSPECTOR) + , m_allowsRemoteInspection(true) +#endif +#if PLATFORM(COCOA) , m_isSmartInsertDeleteEnabled(TextChecker::isSmartInsertDeleteEnabled()) #endif +#if PLATFORM(GTK) + , m_backgroundColor(Color::white) +#endif , m_spellDocumentTag(0) , m_hasSpellDocumentTag(false) , m_pendingLearnOrIgnoreWordMessageCount(0) + , m_mainFrameHasCustomContentProvider(false) +#if ENABLE(DRAG_SUPPORT) + , m_currentDragOperation(DragOperationNone) + , m_currentDragIsOverFileInput(false) + , m_currentDragNumberOfFilesToBeAccepted(0) +#endif + , m_pageLoadState(*this) + , m_delegatesScrolling(false) , m_mainFrameHasHorizontalScrollbar(false) , m_mainFrameHasVerticalScrollbar(false) , m_canShortCircuitHorizontalWheelEvents(true) - , m_mainFrameIsPinnedToLeftSide(false) - , m_mainFrameIsPinnedToRightSide(false) - , m_mainFrameIsPinnedToTopSide(false) - , m_mainFrameIsPinnedToBottomSide(false) - , m_rubberBandsAtBottom(false) - , m_rubberBandsAtTop(false) - , m_mainFrameInViewSourceMode(false) + , m_mainFrameIsPinnedToLeftSide(true) + , m_mainFrameIsPinnedToRightSide(true) + , m_mainFrameIsPinnedToTopSide(true) + , m_mainFrameIsPinnedToBottomSide(true) + , m_shouldUseImplicitRubberBandControl(false) + , m_rubberBandsAtLeft(true) + , m_rubberBandsAtRight(true) + , m_rubberBandsAtTop(true) + , m_rubberBandsAtBottom(true) + , m_enableVerticalRubberBanding(true) + , m_enableHorizontalRubberBanding(true) + , m_backgroundExtendsBeyondPage(false) + , m_shouldRecordNavigationSnapshots(false) + , m_isShowingNavigationGestureSnapshot(false) , m_pageCount(0) , m_renderTreeSize(0) - , m_shouldSendEventsSynchronously(false) + , m_sessionRestorationRenderTreeSize(0) + , m_wantsSessionRestorationRenderTreeSizeThresholdEvent(false) + , m_hitRenderTreeSizeThreshold(false) , m_suppressVisibilityUpdates(false) + , m_autoSizingShouldExpandToViewHeight(false) , m_mediaVolume(1) + , m_muted(false) , m_mayStartMediaWhenInWindow(true) - , m_waitingForDidUpdateInWindowState(false) -#if PLATFORM(MAC) - , m_exposedRectChangedTimer(this, &WebPageProxy::exposedRectChangedTimerFired) - , m_clipsToExposedRect(false) - , m_lastSentClipsToExposedRect(false) -#endif -#if ENABLE(PAGE_VISIBILITY_API) - , m_visibilityState(PageVisibilityStateVisible) + , m_waitingForDidUpdateViewState(false) +#if PLATFORM(COCOA) + , m_scrollPerformanceDataCollectionEnabled(false) #endif , m_scrollPinningBehavior(DoNotPin) + , m_navigationID(0) + , m_configurationPreferenceValues(m_configuration->preferenceValues()) + , m_potentiallyChangedViewStateFlags(ViewState::NoFlags) + , m_viewStateChangeWantsSynchronousReply(false) { -#if ENABLE(PAGE_VISIBILITY_API) - if (!m_isVisible) - m_visibilityState = PageVisibilityStateHidden; + m_webProcessLifetimeTracker.addObserver(m_visitedLinkStore); + m_webProcessLifetimeTracker.addObserver(m_websiteDataStore); + + updateViewState(); + updateActivityToken(); + updateProccessSuppressionState(); + +#if HAVE(OUT_OF_PROCESS_LAYER_HOSTING) + m_layerHostingMode = m_viewState & ViewState::IsInWindow ? m_pageClient.viewLayerHostingMode() : LayerHostingMode::OutOfProcess; #endif + + platformInitialize(); + #ifndef NDEBUG webPageProxyCounter.increment(); #endif - WebContext::statistics().wkPageCount++; + WebProcessPool::statistics().wkPageCount++; + m_preferences->addPage(*this); m_pageGroup->addPage(this); -#if ENABLE(INSPECTOR) m_inspector = WebInspectorProxy::create(this); -#endif #if ENABLE(FULLSCREEN_API) - m_fullScreenManager = WebFullScreenManagerProxy::create(this); + m_fullScreenManager = WebFullScreenManagerProxy::create(*this, m_pageClient.fullScreenManagerProxyClient()); +#endif +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) + m_videoFullscreenManager = WebVideoFullscreenManagerProxy::create(*this); #endif #if ENABLE(VIBRATION) m_vibration = WebVibrationProxy::create(this); #endif -#if ENABLE(THREADED_SCROLLING) - m_rubberBandsAtBottom = true; - m_rubberBandsAtTop = true; + +#if USE(APPLE_INTERNAL_SDK) +#include <WebKitAdditions/WebPageProxyInitialization.cpp> #endif - m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, this); + m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, *this); + + if (m_sessionID.isEphemeral()) { + m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::EnsurePrivateBrowsingSession(m_sessionID)); + m_process->processPool().sendToAllProcesses(Messages::WebProcess::EnsurePrivateBrowsingSession(m_sessionID)); + } - // FIXME: If we ever expose the session storage size as a preference, we need to pass it here. - m_process->context()->storageManager().createSessionStorageNamespace(m_pageID, m_process->isValid() ? m_process->connection() : 0, std::numeric_limits<unsigned>::max()); +#if PLATFORM(COCOA) + const CFIndex viewStateChangeRunLoopOrder = (CFIndex)RunLoopObserver::WellKnownRunLoopOrders::CoreAnimationCommit - 1; + m_viewStateChangeDispatcher = std::make_unique<RunLoopObserver>(viewStateChangeRunLoopOrder, [this] { + this->dispatchViewStateChange(); + }); +#endif } WebPageProxy::~WebPageProxy() { + ASSERT(m_process->webPage(m_pageID) != this); +#if !ASSERT_DISABLED + for (WebPageProxy* page : m_process->pages()) + ASSERT(page != this); +#endif + if (!m_isClosed) close(); - WebContext::statistics().wkPageCount--; + WebProcessPool::statistics().wkPageCount--; if (m_hasSpellDocumentTag) TextChecker::closeSpellDocumentWithTag(m_spellDocumentTag); + m_preferences->removePage(*this); m_pageGroup->removePage(this); #ifndef NDEBUG @@ -368,9 +523,9 @@ WebPageProxy::~WebPageProxy() #endif } -WebProcessProxy* WebPageProxy::process() const +const API::PageConfiguration& WebPageProxy::configuration() const { - return m_process.get(); + return m_configuration.get(); } PlatformProcessIdentifier WebPageProxy::processIdentifier() const @@ -390,266 +545,330 @@ bool WebPageProxy::isValid() const return m_isValid; } -PassRefPtr<ImmutableArray> WebPageProxy::relatedPages() const +void WebPageProxy::setPreferences(WebPreferences& preferences) { - // pages() returns a list of pages in WebProcess, so this page may or may not be among them - a client can use a reference to WebPageProxy after the page has closed. - Vector<WebPageProxy*> pages = m_process->pages(); + if (&preferences == m_preferences.ptr()) + return; - Vector<RefPtr<APIObject> > result; - result.reserveCapacity(pages.size()); - for (size_t i = 0; i < pages.size(); ++i) { - if (pages[i] != this) - result.append(pages[i]); - } + m_preferences->removePage(*this); + m_preferences = preferences; + m_preferences->addPage(*this); - return ImmutableArray::adopt(result); + preferencesDidChange(); } - -void WebPageProxy::initializeLoaderClient(const WKPageLoaderClient* loadClient) -{ - m_loaderClient.initialize(loadClient); - if (!loadClient) - return; +void WebPageProxy::setHistoryClient(std::unique_ptr<API::HistoryClient> historyClient) +{ + m_historyClient = WTFMove(historyClient); +} - // It would be nice to get rid of this code and transition all clients to using didLayout instead of - // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required - // for backwards compatibility. - WebCore::LayoutMilestones milestones = 0; - if (loadClient->didFirstLayoutForFrame) - milestones |= WebCore::DidFirstLayout; - if (loadClient->didFirstVisuallyNonEmptyLayoutForFrame) - milestones |= WebCore::DidFirstVisuallyNonEmptyLayout; - if (loadClient->didNewFirstVisuallyNonEmptyLayout) - milestones |= WebCore::DidHitRelevantRepaintedObjectsAreaThreshold; +void WebPageProxy::setNavigationClient(std::unique_ptr<API::NavigationClient> navigationClient) +{ + m_navigationClient = WTFMove(navigationClient); +} - if (milestones) - m_process->send(Messages::WebPage::ListenForLayoutMilestones(milestones), m_pageID); +void WebPageProxy::setLoaderClient(std::unique_ptr<API::LoaderClient> loaderClient) +{ + if (!loaderClient) { + m_loaderClient = std::make_unique<API::LoaderClient>(); + return; + } - m_process->send(Messages::WebPage::SetWillGoToBackForwardItemCallbackEnabled(loadClient->version > 0), m_pageID); + m_loaderClient = WTFMove(loaderClient); } -void WebPageProxy::initializePolicyClient(const WKPagePolicyClient* policyClient) +void WebPageProxy::setPolicyClient(std::unique_ptr<API::PolicyClient> policyClient) { - m_policyClient.initialize(policyClient); + if (!policyClient) { + m_policyClient = std::make_unique<API::PolicyClient>(); + return; + } + + m_policyClient = WTFMove(policyClient); } -void WebPageProxy::initializeFormClient(const WKPageFormClient* formClient) +void WebPageProxy::setFormClient(std::unique_ptr<API::FormClient> formClient) { - m_formClient.initialize(formClient); + if (!formClient) { + m_formClient = std::make_unique<API::FormClient>(); + return; + } + + m_formClient = WTFMove(formClient); } -void WebPageProxy::initializeUIClient(const WKPageUIClient* client) +void WebPageProxy::setUIClient(std::unique_ptr<API::UIClient> uiClient) { + if (!uiClient) { + m_uiClient = std::make_unique<API::UIClient>(); + return; + } + + m_uiClient = WTFMove(uiClient); + if (!isValid()) return; - m_uiClient.initialize(client); + m_process->send(Messages::WebPage::SetCanRunBeforeUnloadConfirmPanel(m_uiClient->canRunBeforeUnloadConfirmPanel()), m_pageID); + setCanRunModal(m_uiClient->canRunModal()); +} - m_process->send(Messages::WebPage::SetCanRunBeforeUnloadConfirmPanel(m_uiClient.canRunBeforeUnloadConfirmPanel()), m_pageID); - setCanRunModal(m_uiClient.canRunModal()); +void WebPageProxy::setFindClient(std::unique_ptr<API::FindClient> findClient) +{ + if (!findClient) { + m_findClient = std::make_unique<API::FindClient>(); + return; + } + + m_findClient = WTFMove(findClient); } -void WebPageProxy::initializeFindClient(const WKPageFindClient* client) +void WebPageProxy::setFindMatchesClient(std::unique_ptr<API::FindMatchesClient> findMatchesClient) { - m_findClient.initialize(client); + if (!findMatchesClient) { + m_findMatchesClient = std::make_unique<API::FindMatchesClient>(); + return; + } + + m_findMatchesClient = WTFMove(findMatchesClient); } -void WebPageProxy::initializeFindMatchesClient(const WKPageFindMatchesClient* client) +void WebPageProxy::setDiagnosticLoggingClient(std::unique_ptr<API::DiagnosticLoggingClient> diagnosticLoggingClient) { - m_findMatchesClient.initialize(client); + if (!diagnosticLoggingClient) { + m_diagnosticLoggingClient = std::make_unique<API::DiagnosticLoggingClient>(); + return; + } + + m_diagnosticLoggingClient = WTFMove(diagnosticLoggingClient); } #if ENABLE(CONTEXT_MENUS) -void WebPageProxy::initializeContextMenuClient(const WKPageContextMenuClient* client) +void WebPageProxy::setContextMenuClient(std::unique_ptr<API::ContextMenuClient> contextMenuClient) { - m_contextMenuClient.initialize(client); + if (!contextMenuClient) { + m_contextMenuClient = std::make_unique<API::ContextMenuClient>(); + return; + } + + m_contextMenuClient = WTFMove(contextMenuClient); } #endif +void WebPageProxy::setInjectedBundleClient(const WKPageInjectedBundleClientBase* client) +{ + if (!client) { + m_injectedBundleClient = nullptr; + return; + } + + m_injectedBundleClient = std::make_unique<WebPageInjectedBundleClient>(); + m_injectedBundleClient->initialize(client); +} + +void WebPageProxy::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody) +{ + auto* webProcessProxy = WebProcessProxy::fromConnection(&connection); + if (!webProcessProxy || !m_injectedBundleClient) + return; + m_injectedBundleClient->didReceiveMessageFromInjectedBundle(this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get()); +} + +void WebPageProxy::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, UserData& returnUserData) +{ + if (!WebProcessProxy::fromConnection(&connection) || !m_injectedBundleClient) + return; + + RefPtr<API::Object> returnData; + m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(this, messageName, WebProcessProxy::fromConnection(&connection)->transformHandlesToObjects(messageBody.object()).get(), returnData); + returnUserData = UserData(WebProcessProxy::fromConnection(&connection)->transformObjectsToHandles(returnData.get())); +} + + void WebPageProxy::reattachToWebProcess() { + ASSERT(!m_isClosed); ASSERT(!isValid()); - ASSERT(m_process); - ASSERT(!m_process->isValid()); - ASSERT(!m_process->isLaunching()); + ASSERT(m_process->state() == WebProcessProxy::State::Terminated); m_isValid = true; + m_process->removeWebPage(m_pageID); + m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID); - if (m_process->context()->processModel() == ProcessModelSharedSecondaryProcess) - m_process = m_process->context()->ensureSharedWebProcess(); - else - m_process = m_process->context()->createNewWebProcessRespectingProcessCountLimit(); + m_process = m_process->processPool().createNewWebProcessRespectingProcessCountLimit(); + + ASSERT(m_process->state() != ChildProcessProxy::State::Terminated); + if (m_process->state() == ChildProcessProxy::State::Running) + processDidFinishLaunching(); m_process->addExistingWebPage(this, m_pageID); - m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, this); + m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID, *this); + + updateViewState(); + updateActivityToken(); -#if ENABLE(INSPECTOR) m_inspector = WebInspectorProxy::create(this); -#endif #if ENABLE(FULLSCREEN_API) - m_fullScreenManager = WebFullScreenManagerProxy::create(this); + m_fullScreenManager = WebFullScreenManagerProxy::create(*this, m_pageClient.fullScreenManagerProxyClient()); +#endif +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) + m_videoFullscreenManager = WebVideoFullscreenManagerProxy::create(*this); +#endif + +#if USE(APPLE_INTERNAL_SDK) +#include <WebKitAdditions/WebPageProxyInitialization.cpp> #endif initializeWebPage(); - m_pageClient->didRelaunchProcess(); + m_pageClient.didRelaunchProcess(); m_drawingArea->waitForBackingStoreUpdateOnNextPaint(); } -void WebPageProxy::reattachToWebProcessWithItem(WebBackForwardListItem* item) +RefPtr<API::Navigation> WebPageProxy::reattachToWebProcessForReload() { - if (item && item != m_backForwardList->currentItem()) - m_backForwardList->goToItem(item); + if (m_isClosed) + return nullptr; + ASSERT(!isValid()); reattachToWebProcess(); - if (!item) - return; + if (!m_backForwardList->currentItem()) + return nullptr; + + auto navigation = m_navigationState->createReloadNavigation(); + + // We allow stale content when reloading a WebProcess that's been killed or crashed. + m_process->send(Messages::WebPage::GoToBackForwardItem(navigation->navigationID(), m_backForwardList->currentItem()->itemID()), m_pageID); + m_process->responsivenessTimer().start(); - m_process->send(Messages::WebPage::GoToBackForwardItem(item->itemID()), m_pageID); - m_process->responsivenessTimer()->start(); + return WTFMove(navigation); } -void WebPageProxy::initializeWebPage() +RefPtr<API::Navigation> WebPageProxy::reattachToWebProcessWithItem(WebBackForwardListItem* item) { - ASSERT(isValid()); + if (m_isClosed) + return nullptr; - BackForwardListItemVector items = m_backForwardList->entries(); - for (size_t i = 0; i < items.size(); ++i) - m_process->registerNewWebBackForwardListItem(items[i].get()); + ASSERT(!isValid()); + reattachToWebProcess(); - m_drawingArea = m_pageClient->createDrawingAreaProxy(); - ASSERT(m_drawingArea); + if (!item) + return nullptr; -#if ENABLE(INSPECTOR_SERVER) - if (m_pageGroup->preferences()->developerExtrasEnabled()) - inspector()->enableRemoteInspection(); -#endif + if (item != m_backForwardList->currentItem()) + m_backForwardList->goToItem(item); - m_process->send(Messages::WebProcess::CreateWebPage(m_pageID, creationParameters()), 0); + auto navigation = m_navigationState->createBackForwardNavigation(); -#if ENABLE(PAGE_VISIBILITY_API) - m_process->send(Messages::WebPage::SetVisibilityState(m_visibilityState, /* isInitialState */ true), m_pageID); -#elif ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING) - m_process->send(Messages::WebPage::SetVisibilityState(m_isVisible ? PageVisibilityStateVisible : PageVisibilityStateHidden, /* isInitialState */ true), m_pageID); -#endif + m_process->send(Messages::WebPage::GoToBackForwardItem(navigation->navigationID(), item->itemID()), m_pageID); + m_process->responsivenessTimer().start(); -#if PLATFORM(MAC) - m_process->send(Messages::WebPage::SetSmartInsertDeleteEnabled(m_isSmartInsertDeleteEnabled), m_pageID); -#endif + return WTFMove(navigation); } -void WebPageProxy::close() +void WebPageProxy::setSessionID(SessionID sessionID) { if (!isValid()) return; - m_isClosed = true; + m_sessionID = sessionID; + m_process->send(Messages::WebPage::SetSessionID(sessionID), m_pageID); - m_backForwardList->pageClosed(); - m_pageClient->pageClosed(); + if (sessionID.isEphemeral()) + m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::EnsurePrivateBrowsingSession(sessionID)); +} - m_process->disconnectFramesFromPage(this); - m_mainFrame = 0; +void WebPageProxy::initializeWebPage() +{ + ASSERT(isValid()); -#if ENABLE(INSPECTOR) - if (m_inspector) { - m_inspector->invalidate(); - m_inspector = 0; - } -#endif + BackForwardListItemVector items = m_backForwardList->entries(); + for (size_t i = 0; i < items.size(); ++i) + m_process->registerNewWebBackForwardListItem(items[i].get()); -#if ENABLE(FULLSCREEN_API) - if (m_fullScreenManager) { - m_fullScreenManager->invalidate(); - m_fullScreenManager = 0; + m_drawingArea = m_pageClient.createDrawingAreaProxy(); + ASSERT(m_drawingArea); + +#if ENABLE(ASYNC_SCROLLING) + if (m_drawingArea->type() == DrawingAreaTypeRemoteLayerTree) { + m_scrollingCoordinatorProxy = std::make_unique<RemoteScrollingCoordinatorProxy>(*this); +#if PLATFORM(IOS) + // On iOS, main frame scrolls are sent in terms of visible rect updates. + m_scrollingCoordinatorProxy->setPropagatesMainFrameScrolls(false); +#endif } #endif -#if ENABLE(VIBRATION) - m_vibration->invalidate(); +#if ENABLE(INSPECTOR_SERVER) + if (m_preferences->developerExtrasEnabled()) + inspector()->enableRemoteInspection(); #endif - if (m_openPanelResultListener) { - m_openPanelResultListener->invalidate(); - m_openPanelResultListener = 0; - } + process().send(Messages::WebProcess::CreateWebPage(m_pageID, creationParameters()), 0); -#if ENABLE(INPUT_TYPE_COLOR) - if (m_colorPicker) { - m_colorPicker->invalidate(); - m_colorPicker = nullptr; - } - - if (m_colorPickerResultListener) { - m_colorPickerResultListener->invalidate(); - m_colorPickerResultListener = nullptr; - } +#if PLATFORM(COCOA) + send(Messages::WebPage::SetSmartInsertDeleteEnabled(m_isSmartInsertDeleteEnabled)); #endif -#if ENABLE(GEOLOCATION) - m_geolocationPermissionRequestManager.invalidateRequests(); -#endif + m_needsToFinishInitializingWebPageAfterProcessLaunch = true; + finishInitializingWebPageAfterProcessLaunch(); +} - m_notificationPermissionRequestManager.invalidateRequests(); - m_process->context()->supplement<WebNotificationManagerProxy>()->clearNotifications(this); +void WebPageProxy::finishInitializingWebPageAfterProcessLaunch() +{ + if (!m_needsToFinishInitializingWebPageAfterProcessLaunch) + return; + if (m_process->state() != WebProcessProxy::State::Running) + return; - m_toolTip = String(); + m_needsToFinishInitializingWebPageAfterProcessLaunch = false; - m_mainFrameHasHorizontalScrollbar = false; - m_mainFrameHasVerticalScrollbar = false; + if (m_userContentController) + m_process->addWebUserContentControllerProxy(*m_userContentController); + m_process->addVisitedLinkStore(m_visitedLinkStore); +} - m_mainFrameIsPinnedToLeftSide = false; - m_mainFrameIsPinnedToRightSide = false; - m_mainFrameIsPinnedToTopSide = false; - m_mainFrameIsPinnedToBottomSide = false; +void WebPageProxy::close() +{ + if (m_isClosed) + return; - m_visibleScrollerThumbRect = IntRect(); + m_isClosed = true; - invalidateCallbackMap(m_voidCallbacks); - invalidateCallbackMap(m_dataCallbacks); - invalidateCallbackMap(m_imageCallbacks); - invalidateCallbackMap(m_stringCallbacks); - m_loadDependentStringCallbackIDs.clear(); - invalidateCallbackMap(m_scriptValueCallbacks); - invalidateCallbackMap(m_computedPagesCallbacks); -#if PLATFORM(GTK) - invalidateCallbackMap(m_printFinishedCallbacks); + if (m_activePopupMenu) + m_activePopupMenu->cancelTracking(); + +#if ENABLE(CONTEXT_MENUS) + m_activeContextMenu = nullptr; #endif - Vector<WebEditCommandProxy*> editCommandVector; - copyToVector(m_editCommandSet, editCommandVector); - m_editCommandSet.clear(); - for (size_t i = 0, size = editCommandVector.size(); i < size; ++i) - editCommandVector[i]->invalidate(); + m_backForwardList->pageClosed(); + m_pageClient.pageClosed(); - m_activePopupMenu = 0; + m_process->disconnectFramesFromPage(this); - m_estimatedProgress = 0.0; + resetState(ResetStateReason::PageInvalidated); - m_loaderClient.initialize(0); - m_policyClient.initialize(0); - m_formClient.initialize(0); - m_uiClient.initialize(0); + m_loaderClient = std::make_unique<API::LoaderClient>(); + m_policyClient = std::make_unique<API::PolicyClient>(); + m_formClient = std::make_unique<API::FormClient>(); + m_uiClient = std::make_unique<API::UIClient>(); #if PLATFORM(EFL) - m_uiPopupMenuClient.initialize(0); + m_uiPopupMenuClient.initialize(nullptr); #endif - m_findClient.initialize(0); - m_findMatchesClient.initialize(0); + m_findClient = std::make_unique<API::FindClient>(); + m_findMatchesClient = std::make_unique<API::FindMatchesClient>(); + m_diagnosticLoggingClient = std::make_unique<API::DiagnosticLoggingClient>(); #if ENABLE(CONTEXT_MENUS) - m_contextMenuClient.initialize(0); + m_contextMenuClient = std::make_unique<API::ContextMenuClient>(); #endif - m_drawingArea = nullptr; - -#if PLATFORM(MAC) - m_exposedRectChangedTimer.stop(); -#endif + m_webProcessLifetimeTracker.pageWasInvalidated(); m_process->send(Messages::WebPage::Close(), m_pageID); m_process->removeWebPage(m_pageID); m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID); - m_process->context()->storageManager().destroySessionStorageNamespace(m_pageID); + m_process->processPool().supplement<WebNotificationManagerProxy>()->clearNotifications(this); } bool WebPageProxy::tryClose() @@ -657,132 +876,207 @@ bool WebPageProxy::tryClose() if (!isValid()) return true; + // Close without delay if the process allows it. Our goal is to terminate + // the process, so we check a per-process status bit. + if (m_process->isSuddenTerminationEnabled()) + return true; + m_process->send(Messages::WebPage::TryClose(), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->responsivenessTimer().start(); return false; } -bool WebPageProxy::maybeInitializeSandboxExtensionHandle(const KURL& url, SandboxExtension::Handle& sandboxExtensionHandle) +bool WebPageProxy::maybeInitializeSandboxExtensionHandle(const URL& url, SandboxExtension::Handle& sandboxExtensionHandle) { if (!url.isLocalFile()) return false; -#if ENABLE(INSPECTOR) - // Don't give the inspector full access to the file system. - if (WebInspectorProxy::isInspectorPage(this)) + if (m_process->hasAssumedReadAccessToURL(url)) return false; -#endif + + // Inspector resources are in a directory with assumed access. + ASSERT_WITH_SECURITY_IMPLICATION(!WebInspectorProxy::isInspectorPage(*this)); SandboxExtension::createHandle("/", SandboxExtension::ReadOnly, sandboxExtensionHandle); return true; } -void WebPageProxy::loadURL(const String& url, APIObject* userData) +RefPtr<API::Navigation> WebPageProxy::loadRequest(const ResourceRequest& request, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy, API::Object* userData) { - setPendingAPIRequestURL(url); + if (m_isClosed) + return nullptr; - if (!isValid()) - reattachToWebProcess(); + auto navigation = m_navigationState->createLoadRequestNavigation(request); - SandboxExtension::Handle sandboxExtensionHandle; - bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), url), sandboxExtensionHandle); - if (createdExtension) - m_process->willAcquireUniversalFileReadSandboxExtension(); - m_process->send(Messages::WebPage::LoadURL(url, sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); -} + auto transaction = m_pageLoadState.transaction(); -void WebPageProxy::loadURLRequest(WebURLRequest* urlRequest, APIObject* userData) -{ - setPendingAPIRequestURL(urlRequest->resourceRequest().url()); + m_pageLoadState.setPendingAPIRequestURL(transaction, request.url()); if (!isValid()) reattachToWebProcess(); SandboxExtension::Handle sandboxExtensionHandle; - bool createdExtension = maybeInitializeSandboxExtensionHandle(urlRequest->resourceRequest().url(), sandboxExtensionHandle); + bool createdExtension = maybeInitializeSandboxExtensionHandle(request.url(), sandboxExtensionHandle); if (createdExtension) m_process->willAcquireUniversalFileReadSandboxExtension(); - m_process->send(Messages::WebPage::LoadURLRequest(urlRequest->resourceRequest(), sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->send(Messages::WebPage::LoadRequest(navigation->navigationID(), request, sandboxExtensionHandle, (uint64_t)shouldOpenExternalURLsPolicy, UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); + + return WTFMove(navigation); } -void WebPageProxy::loadFile(const String& fileURLString, const String& resourceDirectoryURLString, APIObject* userData) +RefPtr<API::Navigation> WebPageProxy::loadFile(const String& fileURLString, const String& resourceDirectoryURLString, API::Object* userData) { + if (m_isClosed) + return nullptr; + if (!isValid()) reattachToWebProcess(); - KURL fileURL = KURL(KURL(), fileURLString); + URL fileURL = URL(URL(), fileURLString); if (!fileURL.isLocalFile()) - return; + return nullptr; - KURL resourceDirectoryURL; + URL resourceDirectoryURL; if (resourceDirectoryURLString.isNull()) - resourceDirectoryURL = KURL(ParsedURLString, ASCIILiteral("file:///")); + resourceDirectoryURL = URL(ParsedURLString, ASCIILiteral("file:///")); else { - resourceDirectoryURL = KURL(KURL(), resourceDirectoryURLString); + resourceDirectoryURL = URL(URL(), resourceDirectoryURLString); if (!resourceDirectoryURL.isLocalFile()) - return; + return nullptr; } + auto navigation = m_navigationState->createLoadRequestNavigation(ResourceRequest(fileURL)); + + auto transaction = m_pageLoadState.transaction(); + + m_pageLoadState.setPendingAPIRequestURL(transaction, fileURLString); + String resourceDirectoryPath = resourceDirectoryURL.fileSystemPath(); SandboxExtension::Handle sandboxExtensionHandle; SandboxExtension::createHandle(resourceDirectoryPath, SandboxExtension::ReadOnly, sandboxExtensionHandle); m_process->assumeReadAccessToBaseURL(resourceDirectoryURL); - m_process->send(Messages::WebPage::LoadURL(fileURL, sandboxExtensionHandle, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->send(Messages::WebPage::LoadRequest(navigation->navigationID(), fileURL, sandboxExtensionHandle, (uint64_t)ShouldOpenExternalURLsPolicy::ShouldNotAllow, UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); + + return WTFMove(navigation); } -void WebPageProxy::loadData(WebData* data, const String& MIMEType, const String& encoding, const String& baseURL, APIObject* userData) +RefPtr<API::Navigation> WebPageProxy::loadData(API::Data* data, const String& MIMEType, const String& encoding, const String& baseURL, API::Object* userData) { + if (m_isClosed) + return nullptr; + + auto navigation = m_navigationState->createLoadDataNavigation(); + + auto transaction = m_pageLoadState.transaction(); + + m_pageLoadState.setPendingAPIRequestURL(transaction, !baseURL.isEmpty() ? baseURL : blankURL().string()); + if (!isValid()) reattachToWebProcess(); m_process->assumeReadAccessToBaseURL(baseURL); - m_process->send(Messages::WebPage::LoadData(data->dataReference(), MIMEType, encoding, baseURL, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->send(Messages::WebPage::LoadData(navigation->navigationID(), data->dataReference(), MIMEType, encoding, baseURL, UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); + + return WTFMove(navigation); } -void WebPageProxy::loadHTMLString(const String& htmlString, const String& baseURL, APIObject* userData) +// FIXME: Get rid of loadHTMLString and just use loadData instead. +RefPtr<API::Navigation> WebPageProxy::loadHTMLString(const String& htmlString, const String& baseURL, API::Object* userData) { + if (m_isClosed) + return nullptr; + + auto navigation = m_navigationState->createLoadDataNavigation(); + + auto transaction = m_pageLoadState.transaction(); + + m_pageLoadState.setPendingAPIRequestURL(transaction, !baseURL.isEmpty() ? baseURL : blankURL().string()); + if (!isValid()) reattachToWebProcess(); m_process->assumeReadAccessToBaseURL(baseURL); - m_process->send(Messages::WebPage::LoadHTMLString(htmlString, baseURL, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->send(Messages::WebPage::LoadHTMLString(navigation->navigationID(), htmlString, baseURL, UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); + + return WTFMove(navigation); } -void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, APIObject* userData) +void WebPageProxy::loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, API::Object* userData) { + // When the UIProcess is in the process of handling a failing provisional load, do not attempt to + // start a second alternative HTML load as this will prevent the page load state from being + // handled properly. + if (m_isClosed || m_isLoadingAlternateHTMLStringForFailingProvisionalLoad) + return; + + if (!m_failingProvisionalLoadURL.isEmpty()) + m_isLoadingAlternateHTMLStringForFailingProvisionalLoad = true; + if (!isValid()) reattachToWebProcess(); + auto transaction = m_pageLoadState.transaction(); + + m_pageLoadState.setPendingAPIRequestURL(transaction, unreachableURL); + m_pageLoadState.setUnreachableURL(transaction, unreachableURL); + if (m_mainFrame) m_mainFrame->setUnreachableURL(unreachableURL); m_process->assumeReadAccessToBaseURL(baseURL); - m_process->send(Messages::WebPage::LoadAlternateHTMLString(htmlString, baseURL, unreachableURL, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->assumeReadAccessToBaseURL(unreachableURL); + m_process->send(Messages::WebPage::LoadAlternateHTMLString(htmlString, baseURL, unreachableURL, m_failingProvisionalLoadURL, UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); } -void WebPageProxy::loadPlainTextString(const String& string, APIObject* userData) +void WebPageProxy::loadPlainTextString(const String& string, API::Object* userData) { + if (m_isClosed) + return; + if (!isValid()) reattachToWebProcess(); - m_process->send(Messages::WebPage::LoadPlainTextString(string, WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.setPendingAPIRequestURL(transaction, blankURL().string()); + + m_process->send(Messages::WebPage::LoadPlainTextString(string, UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); } -void WebPageProxy::loadWebArchiveData(const WebData* webArchiveData, APIObject* userData) +void WebPageProxy::loadWebArchiveData(API::Data* webArchiveData, API::Object* userData) { + if (m_isClosed) + return; + if (!isValid()) reattachToWebProcess(); - m_process->send(Messages::WebPage::LoadWebArchiveData(webArchiveData->dataReference(), WebContextUserMessageEncoder(userData)), m_pageID); - m_process->responsivenessTimer()->start(); + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.setPendingAPIRequestURL(transaction, blankURL().string()); + + m_process->send(Messages::WebPage::LoadWebArchiveData(webArchiveData->dataReference(), UserData(process().transformObjectsToHandles(userData).get())), m_pageID); + m_process->responsivenessTimer().start(); +} + +void WebPageProxy::navigateToPDFLinkWithSimulatedClick(const String& url, IntPoint documentPoint, IntPoint screenPoint) +{ + if (m_isClosed) + return; + + if (WebCore::protocolIsJavaScript(url)) + return; + + if (!isValid()) + reattachToWebProcess(); + + m_process->send(Messages::WebPage::NavigateToPDFLinkWithSimulatedClick(url, documentPoint, screenPoint), m_pageID); + m_process->responsivenessTimer().start(); } void WebPageProxy::stopLoading() @@ -791,187 +1085,202 @@ void WebPageProxy::stopLoading() return; m_process->send(Messages::WebPage::StopLoading(), m_pageID); - m_process->responsivenessTimer()->start(); + m_process->responsivenessTimer().start(); } -void WebPageProxy::reload(bool reloadFromOrigin) +RefPtr<API::Navigation> WebPageProxy::reload(bool reloadFromOrigin, bool contentBlockersEnabled) { SandboxExtension::Handle sandboxExtensionHandle; - if (m_backForwardList->currentItem()) { - String url = m_backForwardList->currentItem()->url(); - setPendingAPIRequestURL(url); + String url = m_pageLoadState.activeURL(); + if (url.isEmpty() && m_backForwardList->currentItem()) + url = m_backForwardList->currentItem()->url(); + + if (!url.isEmpty()) { + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.setPendingAPIRequestURL(transaction, url); // We may not have an extension yet if back/forward list was reinstated after a WebProcess crash or a browser relaunch - bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), url), sandboxExtensionHandle); + bool createdExtension = maybeInitializeSandboxExtensionHandle(URL(URL(), url), sandboxExtensionHandle); if (createdExtension) m_process->willAcquireUniversalFileReadSandboxExtension(); } - if (!isValid()) { - reattachToWebProcessWithItem(m_backForwardList->currentItem()); - return; - } + if (!isValid()) + return reattachToWebProcessForReload(); + + auto navigation = m_navigationState->createReloadNavigation(); + + m_process->send(Messages::WebPage::Reload(navigation->navigationID(), reloadFromOrigin, contentBlockersEnabled, sandboxExtensionHandle), m_pageID); + m_process->responsivenessTimer().start(); + + return WTFMove(navigation); +} - m_process->send(Messages::WebPage::Reload(reloadFromOrigin, sandboxExtensionHandle), m_pageID); - m_process->responsivenessTimer()->start(); +void WebPageProxy::recordNavigationSnapshot() +{ + if (WebBackForwardListItem* item = m_backForwardList->currentItem()) + recordNavigationSnapshot(*item); } -void WebPageProxy::goForward() +void WebPageProxy::recordNavigationSnapshot(WebBackForwardListItem& item) { - if (isValid() && !canGoForward()) + if (!m_shouldRecordNavigationSnapshots || m_suppressNavigationSnapshotting) return; +#if PLATFORM(COCOA) + ViewSnapshotStore::singleton().recordSnapshot(*this, item); +#else + UNUSED_PARAM(item); +#endif +} + +RefPtr<API::Navigation> WebPageProxy::goForward() +{ WebBackForwardListItem* forwardItem = m_backForwardList->forwardItem(); if (!forwardItem) - return; + return nullptr; - setPendingAPIRequestURL(forwardItem->url()); + auto transaction = m_pageLoadState.transaction(); - if (!isValid()) { - reattachToWebProcessWithItem(forwardItem); - return; - } + m_pageLoadState.setPendingAPIRequestURL(transaction, forwardItem->url()); - m_process->send(Messages::WebPage::GoForward(forwardItem->itemID()), m_pageID); - m_process->responsivenessTimer()->start(); -} + if (!isValid()) + return reattachToWebProcessWithItem(forwardItem); -bool WebPageProxy::canGoForward() const -{ - return m_backForwardList->forwardItem(); + RefPtr<API::Navigation> navigation; + if (!m_backForwardList->currentItem()->itemIsInSameDocument(*forwardItem)) + navigation = m_navigationState->createBackForwardNavigation(); + + m_process->send(Messages::WebPage::GoForward(navigation ? navigation->navigationID() : 0, forwardItem->itemID()), m_pageID); + m_process->responsivenessTimer().start(); + + return navigation; } -void WebPageProxy::goBack() +RefPtr<API::Navigation> WebPageProxy::goBack() { - if (isValid() && !canGoBack()) - return; - WebBackForwardListItem* backItem = m_backForwardList->backItem(); if (!backItem) - return; + return nullptr; - setPendingAPIRequestURL(backItem->url()); + auto transaction = m_pageLoadState.transaction(); - if (!isValid()) { - reattachToWebProcessWithItem(backItem); - return; - } + m_pageLoadState.setPendingAPIRequestURL(transaction, backItem->url()); - m_process->send(Messages::WebPage::GoBack(backItem->itemID()), m_pageID); - m_process->responsivenessTimer()->start(); -} + if (!isValid()) + return reattachToWebProcessWithItem(backItem); -bool WebPageProxy::canGoBack() const -{ - return m_backForwardList->backItem(); -} + RefPtr<API::Navigation> navigation; + if (!m_backForwardList->currentItem()->itemIsInSameDocument(*backItem)) + navigation = m_navigationState->createBackForwardNavigation(); -void WebPageProxy::goToBackForwardItem(WebBackForwardListItem* item) -{ - if (!isValid()) { - reattachToWebProcessWithItem(item); - return; - } - - setPendingAPIRequestURL(item->url()); + m_process->send(Messages::WebPage::GoBack(navigation ? navigation->navigationID() : 0, backItem->itemID()), m_pageID); + m_process->responsivenessTimer().start(); - m_process->send(Messages::WebPage::GoToBackForwardItem(item->itemID()), m_pageID); - m_process->responsivenessTimer()->start(); + return navigation; } -void WebPageProxy::tryRestoreScrollPosition() +RefPtr<API::Navigation> WebPageProxy::goToBackForwardItem(WebBackForwardListItem* item) { if (!isValid()) - return; + return reattachToWebProcessWithItem(item); - m_process->send(Messages::WebPage::TryRestoreScrollPosition(), m_pageID); -} + auto transaction = m_pageLoadState.transaction(); -void WebPageProxy::didChangeBackForwardList(WebBackForwardListItem* added, Vector<RefPtr<APIObject> >* removed) -{ - m_loaderClient.didChangeBackForwardList(this, added, removed); -} + m_pageLoadState.setPendingAPIRequestURL(transaction, item->url()); -void WebPageProxy::shouldGoToBackForwardListItem(uint64_t itemID, bool& shouldGoToBackForwardItem) -{ - WebBackForwardListItem* item = m_process->webBackForwardItem(itemID); - shouldGoToBackForwardItem = item && m_loaderClient.shouldGoToBackForwardListItem(this, item); + RefPtr<API::Navigation> navigation; + if (!m_backForwardList->currentItem()->itemIsInSameDocument(*item)) + navigation = m_navigationState->createBackForwardNavigation(); + + m_process->send(Messages::WebPage::GoToBackForwardItem(navigation ? navigation->navigationID() : 0, item->itemID()), m_pageID); + m_process->responsivenessTimer().start(); + + return navigation; } -void WebPageProxy::willGoToBackForwardListItem(uint64_t itemID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::tryRestoreScrollPosition() { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) + if (!isValid()) return; - if (WebBackForwardListItem* item = m_process->webBackForwardItem(itemID)) - m_loaderClient.willGoToBackForwardListItem(this, item, userData.get()); + m_process->send(Messages::WebPage::TryRestoreScrollPosition(), m_pageID); } -String WebPageProxy::activeURL() const +void WebPageProxy::didChangeBackForwardList(WebBackForwardListItem* added, Vector<RefPtr<WebBackForwardListItem>> removed) { - // If there is a currently pending url, it is the active URL, - // even when there's no main frame yet, as it might be the - // first API request. - if (!m_pendingAPIRequestURL.isNull()) - return m_pendingAPIRequestURL; - - if (!m_mainFrame) - return String(); + PageClientProtector protector(m_pageClient); - if (!m_mainFrame->unreachableURL().isEmpty()) - return m_mainFrame->unreachableURL(); + m_loaderClient->didChangeBackForwardList(*this, added, WTFMove(removed)); - switch (m_mainFrame->loadState()) { - case WebFrameProxy::LoadStateProvisional: - return m_mainFrame->provisionalURL(); - case WebFrameProxy::LoadStateCommitted: - case WebFrameProxy::LoadStateFinished: - return m_mainFrame->url(); - } + auto transaction = m_pageLoadState.transaction(); - ASSERT_NOT_REACHED(); - return String(); + m_pageLoadState.setCanGoBack(transaction, m_backForwardList->backItem()); + m_pageLoadState.setCanGoForward(transaction, m_backForwardList->forwardItem()); } -String WebPageProxy::provisionalURL() const +void WebPageProxy::willGoToBackForwardListItem(uint64_t itemID, const UserData& userData) { - if (!m_mainFrame) - return String(); - return m_mainFrame->provisionalURL(); + PageClientProtector protector(m_pageClient); + + if (WebBackForwardListItem* item = m_process->webBackForwardItem(itemID)) + m_loaderClient->willGoToBackForwardListItem(*this, item, m_process->transformHandlesToObjects(userData.object()).get()); } -String WebPageProxy::committedURL() const +bool WebPageProxy::shouldKeepCurrentBackForwardListItemInList(WebBackForwardListItem* item) { - if (!m_mainFrame) - return String(); + PageClientProtector protector(m_pageClient); - return m_mainFrame->url(); + return m_loaderClient->shouldKeepCurrentBackForwardListItemInList(*this, item); } -bool WebPageProxy::canShowMIMEType(const String& mimeType) const +bool WebPageProxy::canShowMIMEType(const String& mimeType) { if (MIMETypeRegistry::canShowMIMEType(mimeType)) return true; #if ENABLE(NETSCAPE_PLUGIN_API) String newMimeType = mimeType; - PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL()); - if (!plugin.path.isNull() && m_pageGroup->preferences()->pluginsEnabled()) + PluginModuleInfo plugin = m_process->processPool().pluginInfoStore().findPlugin(newMimeType, URL()); + if (!plugin.path.isNull() && m_preferences->pluginsEnabled()) return true; #endif // ENABLE(NETSCAPE_PLUGIN_API) -#if PLATFORM(MAC) +#if PLATFORM(COCOA) // On Mac, we can show PDFs. - if (MIMETypeRegistry::isPDFOrPostScriptMIMEType(mimeType) && !WebContext::omitPDFSupport()) + if (MIMETypeRegistry::isPDFOrPostScriptMIMEType(mimeType) && !WebProcessPool::omitPDFSupport()) return true; -#endif // PLATFORM(MAC) +#endif // PLATFORM(COCOA) return false; } +#if ENABLE(REMOTE_INSPECTOR) +void WebPageProxy::setAllowsRemoteInspection(bool allow) +{ + if (m_allowsRemoteInspection == allow) + return; + + m_allowsRemoteInspection = allow; + + if (isValid()) + m_process->send(Messages::WebPage::SetAllowsRemoteInspection(allow), m_pageID); +} + +void WebPageProxy::setRemoteInspectionNameOverride(const String& name) +{ + if (m_remoteInspectionNameOverride == name) + return; + + m_remoteInspectionNameOverride = name; + + if (isValid()) + m_process->send(Messages::WebPage::SetRemoteInspectionNameOverride(m_remoteInspectionNameOverride), m_pageID); +} + +#endif + void WebPageProxy::setDrawsBackground(bool drawsBackground) { if (m_drawsBackground == drawsBackground) @@ -983,15 +1292,15 @@ void WebPageProxy::setDrawsBackground(bool drawsBackground) m_process->send(Messages::WebPage::SetDrawsBackground(drawsBackground), m_pageID); } -void WebPageProxy::setDrawsTransparentBackground(bool drawsTransparentBackground) +void WebPageProxy::setTopContentInset(float contentInset) { - if (m_drawsTransparentBackground == drawsTransparentBackground) + if (m_topContentInset == contentInset) return; - m_drawsTransparentBackground = drawsTransparentBackground; + m_topContentInset = contentInset; if (isValid()) - m_process->send(Messages::WebPage::SetDrawsTransparentBackground(drawsTransparentBackground), m_pageID); + m_process->send(Messages::WebPage::SetTopContentInset(contentInset), m_pageID); } void WebPageProxy::setUnderlayColor(const Color& color) @@ -1009,6 +1318,10 @@ void WebPageProxy::viewWillStartLiveResize() { if (!isValid()) return; +#if ENABLE(INPUT_TYPE_COLOR_POPOVER) && ENABLE(INPUT_TYPE_COLOR) + if (m_colorPicker) + endColorPicker(); +#endif m_process->send(Messages::WebPage::ViewWillStartLiveResize(), m_pageID); } @@ -1021,139 +1334,264 @@ void WebPageProxy::viewWillEndLiveResize() void WebPageProxy::setViewNeedsDisplay(const IntRect& rect) { - m_pageClient->setViewNeedsDisplay(rect); + m_pageClient.setViewNeedsDisplay(rect); } void WebPageProxy::displayView() { - m_pageClient->displayView(); + m_pageClient.displayView(); } bool WebPageProxy::canScrollView() { - return m_pageClient->canScrollView(); + return m_pageClient.canScrollView(); } void WebPageProxy::scrollView(const IntRect& scrollRect, const IntSize& scrollOffset) { - m_pageClient->scrollView(scrollRect, scrollOffset); + m_pageClient.scrollView(scrollRect, scrollOffset); } -void WebPageProxy::viewStateDidChange(ViewStateFlags flags) +void WebPageProxy::requestScroll(const FloatPoint& scrollPosition, const IntPoint& scrollOrigin, bool isProgrammaticScroll) { - if (!isValid()) + m_pageClient.requestScroll(scrollPosition, scrollOrigin, isProgrammaticScroll); +} + +void WebPageProxy::setSuppressVisibilityUpdates(bool flag) +{ + if (m_suppressVisibilityUpdates == flag) return; + m_suppressVisibilityUpdates = flag; - if (flags & ViewIsFocused) - m_process->send(Messages::WebPage::SetFocused(m_pageClient->isViewFocused()), m_pageID); + if (!m_suppressVisibilityUpdates) { +#if PLATFORM(COCOA) + m_viewStateChangeDispatcher->schedule(); +#else + dispatchViewStateChange(); +#endif + } +} - if (flags & ViewWindowIsActive) - m_process->send(Messages::WebPage::SetActive(m_pageClient->isViewWindowActive()), m_pageID); +void WebPageProxy::updateViewState(ViewState::Flags flagsToUpdate) +{ + m_viewState &= ~flagsToUpdate; + if (flagsToUpdate & ViewState::IsFocused && m_pageClient.isViewFocused()) + m_viewState |= ViewState::IsFocused; + if (flagsToUpdate & ViewState::WindowIsActive && m_pageClient.isViewWindowActive()) + m_viewState |= ViewState::WindowIsActive; + if (flagsToUpdate & ViewState::IsVisible && m_pageClient.isViewVisible()) + m_viewState |= ViewState::IsVisible; + if (flagsToUpdate & ViewState::IsVisibleOrOccluded && m_pageClient.isViewVisibleOrOccluded()) + m_viewState |= ViewState::IsVisibleOrOccluded; + if (flagsToUpdate & ViewState::IsInWindow && m_pageClient.isViewInWindow()) + m_viewState |= ViewState::IsInWindow; + if (flagsToUpdate & ViewState::IsVisuallyIdle && m_pageClient.isVisuallyIdle()) + m_viewState |= ViewState::IsVisuallyIdle; +} - if (flags & ViewIsVisible) { - bool isVisible = m_pageClient->isViewVisible(); - if (isVisible != m_isVisible) { - m_isVisible = isVisible; - m_process->pageVisibilityChanged(this); - m_drawingArea->visibilityDidChange(); +void WebPageProxy::viewStateDidChange(ViewState::Flags mayHaveChanged, bool wantsSynchronousReply, ViewStateChangeDispatchMode dispatchMode) +{ + m_potentiallyChangedViewStateFlags |= mayHaveChanged; + m_viewStateChangeWantsSynchronousReply = m_viewStateChangeWantsSynchronousReply || wantsSynchronousReply; - if (!m_isVisible) { - // If we've started the responsiveness timer as part of telling the web process to update the backing store - // state, it might not send back a reply (since it won't paint anything if the web page is hidden) so we - // stop the unresponsiveness timer here. - m_process->responsivenessTimer()->stop(); - } + if (m_suppressVisibilityUpdates && dispatchMode != ViewStateChangeDispatchMode::Immediate) + return; -#if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING) && !ENABLE(PAGE_VISIBILITY_API) - PageVisibilityState visibilityState = m_isVisible ? PageVisibilityStateVisible : PageVisibilityStateHidden; - m_process->send(Messages::WebPage::SetVisibilityState(visibilityState, false), m_pageID); -#endif - } +#if PLATFORM(COCOA) + bool isNewlyInWindow = !isInWindow() && (mayHaveChanged & ViewState::IsInWindow) && m_pageClient.isViewInWindow(); + if (dispatchMode == ViewStateChangeDispatchMode::Immediate || isNewlyInWindow) { + dispatchViewStateChange(); + return; } + m_viewStateChangeDispatcher->schedule(); +#else + UNUSED_PARAM(dispatchMode); + dispatchViewStateChange(); +#endif +} - if (flags & ViewIsInWindow) { - bool isInWindow = m_pageClient->isViewInWindow(); - if (m_isInWindow != isInWindow) { - m_isInWindow = isInWindow; - m_process->send(Messages::WebPage::SetIsInWindow(isInWindow), m_pageID); - } +void WebPageProxy::viewDidLeaveWindow() +{ +#if ENABLE(INPUT_TYPE_COLOR_POPOVER) && ENABLE(INPUT_TYPE_COLOR) + // When leaving the current page, close the popover color well. + if (m_colorPicker) + endColorPicker(); +#endif +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) + // When leaving the current page, close the video fullscreen. + if (m_videoFullscreenManager) + m_videoFullscreenManager->requestHideAndExitFullscreen(); +#endif +} - if (isInWindow) { - LayerHostingMode layerHostingMode = m_pageClient->viewLayerHostingMode(); - if (m_layerHostingMode != layerHostingMode) { - m_layerHostingMode = layerHostingMode; - m_drawingArea->layerHostingModeDidChange(); - } - } +void WebPageProxy::viewDidEnterWindow() +{ + LayerHostingMode layerHostingMode = m_pageClient.viewLayerHostingMode(); + if (m_layerHostingMode != layerHostingMode) { + m_layerHostingMode = layerHostingMode; + m_process->send(Messages::WebPage::SetLayerHostingMode(static_cast<unsigned>(layerHostingMode)), m_pageID); } +} + +void WebPageProxy::dispatchViewStateChange() +{ +#if PLATFORM(COCOA) + m_viewStateChangeDispatcher->invalidate(); +#endif + + if (!isValid()) + return; + + // If the visibility state may have changed, then so may the visually idle & occluded agnostic state. + if (m_potentiallyChangedViewStateFlags & ViewState::IsVisible) + m_potentiallyChangedViewStateFlags |= ViewState::IsVisibleOrOccluded | ViewState::IsVisuallyIdle; + + // Record the prior view state, update the flags that may have changed, + // and check which flags have actually changed. + ViewState::Flags previousViewState = m_viewState; + updateViewState(m_potentiallyChangedViewStateFlags); + ViewState::Flags changed = m_viewState ^ previousViewState; + + bool isNowInWindow = (changed & ViewState::IsInWindow) && isInWindow(); + // We always want to wait for the Web process to reply if we've been in-window before and are coming back in-window. + if (m_viewWasEverInWindow && isNowInWindow && m_drawingArea->hasVisibleContent()) + m_viewStateChangeWantsSynchronousReply = true; + + // Don't wait synchronously if the view state is not visible. (This matters in particular on iOS, where a hidden page may be suspended.) + if (!(m_viewState & ViewState::IsVisible)) + m_viewStateChangeWantsSynchronousReply = false; + + if (changed || m_viewStateChangeWantsSynchronousReply || !m_nextViewStateChangeCallbacks.isEmpty()) + m_process->send(Messages::WebPage::SetViewState(m_viewState, m_viewStateChangeWantsSynchronousReply, m_nextViewStateChangeCallbacks), m_pageID); + + m_nextViewStateChangeCallbacks.clear(); -#if ENABLE(PAGE_VISIBILITY_API) - PageVisibilityState visibilityState = PageVisibilityStateHidden; + // This must happen after the SetViewState message is sent, to ensure the page visibility event can fire. + updateActivityToken(); - if (m_isVisible) - visibilityState = PageVisibilityStateVisible; + // If we've started the responsiveness timer as part of telling the web process to update the backing store + // state, it might not send back a reply (since it won't paint anything if the web page is hidden) so we + // stop the unresponsiveness timer here. + if ((changed & ViewState::IsVisible) && !isViewVisible()) + m_process->responsivenessTimer().stop(); - if (visibilityState != m_visibilityState) { - m_visibilityState = visibilityState; - m_process->send(Messages::WebPage::SetVisibilityState(visibilityState, false), m_pageID); + if (changed & ViewState::IsInWindow) { + if (isInWindow()) + viewDidEnterWindow(); + else + viewDidLeaveWindow(); } -#endif updateBackingStoreDiscardableState(); + + if (m_viewStateChangeWantsSynchronousReply) + waitForDidUpdateViewState(); + + m_potentiallyChangedViewStateFlags = ViewState::NoFlags; + m_viewStateChangeWantsSynchronousReply = false; + m_viewWasEverInWindow |= isNowInWindow; } -void WebPageProxy::waitForDidUpdateInWindowState() +void WebPageProxy::updateActivityToken() { - // If we have previously timed out with no response from the WebProcess, don't block the UIProcess again until it starts responding. - if (m_waitingForDidUpdateInWindowState) + if (m_viewState & ViewState::IsVisuallyIdle) + m_pageIsUserObservableCount = nullptr; + else if (!m_pageIsUserObservableCount) + m_pageIsUserObservableCount = m_process->processPool().userObservablePageCount(); + +#if PLATFORM(IOS) + if (!isViewVisible() && !m_alwaysRunsAtForegroundPriority) + m_activityToken = nullptr; + else if (!m_activityToken) + m_activityToken = m_process->throttler().foregroundActivityToken(); +#endif +} + +void WebPageProxy::updateProccessSuppressionState() +{ + if (m_preferences->pageVisibilityBasedProcessSuppressionEnabled()) + m_preventProcessSuppressionCount = nullptr; + else if (!m_preventProcessSuppressionCount) + m_preventProcessSuppressionCount = m_process->processPool().processSuppressionDisabledForPageCount(); +} + +void WebPageProxy::layerHostingModeDidChange() +{ + if (!isValid()) + return; + + LayerHostingMode layerHostingMode = m_pageClient.viewLayerHostingMode(); + if (m_layerHostingMode == layerHostingMode) return; + m_layerHostingMode = layerHostingMode; + m_process->send(Messages::WebPage::SetLayerHostingMode(static_cast<unsigned>(layerHostingMode)), m_pageID); +} + +void WebPageProxy::waitForDidUpdateViewState() +{ if (!isValid()) return; - m_waitingForDidUpdateInWindowState = true; + if (m_process->state() != WebProcessProxy::State::Running) + return; + + // If we have previously timed out with no response from the WebProcess, don't block the UIProcess again until it starts responding. + if (m_waitingForDidUpdateViewState) + return; - if (!m_process->isLaunching()) { - const double inWindowStateUpdateTimeout = 0.25; - m_process->connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidUpdateInWindowState>(m_pageID, inWindowStateUpdateTimeout); +#if PLATFORM(IOS) + // Hail Mary check. Should not be possible (dispatchViewStateChange should force async if not visible, + // and if visible we should be holding an assertion) - but we should never block on a suspended process. + if (!m_activityToken) { + ASSERT_NOT_REACHED(); + return; } +#endif + + m_waitingForDidUpdateViewState = true; + + m_drawingArea->waitForDidUpdateViewState(); } IntSize WebPageProxy::viewSize() const { - return m_pageClient->viewSize(); + return m_pageClient.viewSize(); } -void WebPageProxy::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& keyboardEvent) +void WebPageProxy::setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent& keyboardEvent, std::function<void (CallbackBase::Error)> callbackFunction) { - if (!isValid()) + if (!isValid()) { + callbackFunction(CallbackBase::Error::OwnerWasInvalidated); return; - m_process->send(Messages::WebPage::SetInitialFocus(forward, isKeyboardEventValid, keyboardEvent), m_pageID); + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + m_process->send(Messages::WebPage::SetInitialFocus(forward, isKeyboardEventValid, keyboardEvent, callbackID), m_pageID); } -void WebPageProxy::setWindowResizerSize(const IntSize& windowResizerSize) +void WebPageProxy::clearSelection() { if (!isValid()) return; - m_process->send(Messages::WebPage::SetWindowResizerSize(windowResizerSize), m_pageID); + m_process->send(Messages::WebPage::ClearSelection(), m_pageID); } - -void WebPageProxy::clearSelection() + +void WebPageProxy::restoreSelectionInFocusedEditableElement() { if (!isValid()) return; - m_process->send(Messages::WebPage::ClearSelection(), m_pageID); + m_process->send(Messages::WebPage::RestoreSelectionInFocusedEditableElement(), m_pageID); } -void WebPageProxy::validateCommand(const String& commandName, PassRefPtr<ValidateCommandCallback> callback) +void WebPageProxy::validateCommand(const String& commandName, std::function<void (const String&, bool, int32_t, CallbackBase::Error)> callbackFunction) { if (!isValid()) { - callback->invalidate(); + callbackFunction(String(), false, 0, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_validateCommandCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::ValidateCommand(commandName, callbackID), m_pageID); } @@ -1162,69 +1600,88 @@ void WebPageProxy::setMaintainsInactiveSelection(bool newValue) m_maintainsInactiveSelection = newValue; } -void WebPageProxy::executeEditCommand(const String& commandName) +void WebPageProxy::executeEditCommand(const String& commandName, const String& argument) { + static NeverDestroyed<String> ignoreSpellingCommandName(ASCIILiteral("ignoreSpelling")); + if (!isValid()) return; - DEFINE_STATIC_LOCAL(String, ignoreSpellingCommandName, (ASCIILiteral("ignoreSpelling"))); if (commandName == ignoreSpellingCommandName) ++m_pendingLearnOrIgnoreWordMessageCount; - m_process->send(Messages::WebPage::ExecuteEditCommand(commandName), m_pageID); + m_process->send(Messages::WebPage::ExecuteEditCommand(commandName, argument), m_pageID); } - -#if USE(TILED_BACKING_STORE) -void WebPageProxy::commitPageTransitionViewport() + +void WebPageProxy::setEditable(bool editable) { + if (editable == m_isEditable) + return; if (!isValid()) return; - process()->send(Messages::WebPage::CommitPageTransitionViewport(), m_pageID); + m_isEditable = editable; + m_process->send(Messages::WebPage::SetEditable(editable), m_pageID); +} + +#if !PLATFORM(IOS) +void WebPageProxy::didCommitLayerTree(const RemoteLayerTreeTransaction&) +{ } #endif #if ENABLE(DRAG_SUPPORT) -void WebPageProxy::dragEntered(DragData* dragData, const String& dragStorageName) +void WebPageProxy::dragEntered(DragData& dragData, const String& dragStorageName) { SandboxExtension::Handle sandboxExtensionHandle; SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray; performDragControllerAction(DragControllerActionEntered, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray); } -void WebPageProxy::dragUpdated(DragData* dragData, const String& dragStorageName) +void WebPageProxy::dragUpdated(DragData& dragData, const String& dragStorageName) { SandboxExtension::Handle sandboxExtensionHandle; SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray; performDragControllerAction(DragControllerActionUpdated, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray); } -void WebPageProxy::dragExited(DragData* dragData, const String& dragStorageName) +void WebPageProxy::dragExited(DragData& dragData, const String& dragStorageName) { SandboxExtension::Handle sandboxExtensionHandle; SandboxExtension::HandleArray sandboxExtensionHandleEmptyArray; performDragControllerAction(DragControllerActionExited, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionHandleEmptyArray); } -void WebPageProxy::performDrag(DragData* dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload) +void WebPageProxy::performDragOperation(DragData& dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload) { - performDragControllerAction(DragControllerActionPerformDrag, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionsForUpload); + performDragControllerAction(DragControllerActionPerformDragOperation, dragData, dragStorageName, sandboxExtensionHandle, sandboxExtensionsForUpload); } -void WebPageProxy::performDragControllerAction(DragControllerAction action, DragData* dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload) +void WebPageProxy::performDragControllerAction(DragControllerAction action, DragData& dragData, const String& dragStorageName, const SandboxExtension::Handle& sandboxExtensionHandle, const SandboxExtension::HandleArray& sandboxExtensionsForUpload) { if (!isValid()) return; -#if PLATFORM(QT) || PLATFORM(GTK) - m_process->send(Messages::WebPage::PerformDragControllerAction(action, *dragData), m_pageID); +#if PLATFORM(GTK) || PLATFORM(QT) + UNUSED_PARAM(dragStorageName); + UNUSED_PARAM(sandboxExtensionHandle); + UNUSED_PARAM(sandboxExtensionsForUpload); + + String url = dragData.asURL(); + if (!url.isEmpty()) + m_process->assumeReadAccessToBaseURL(url); + m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData), m_pageID); #else - m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData->clientPosition(), dragData->globalPosition(), dragData->draggingSourceOperationMask(), dragStorageName, dragData->flags(), sandboxExtensionHandle, sandboxExtensionsForUpload), m_pageID); + m_process->send(Messages::WebPage::PerformDragControllerAction(action, dragData.clientPosition(), dragData.globalPosition(), dragData.draggingSourceOperationMask(), dragStorageName, dragData.flags(), sandboxExtensionHandle, sandboxExtensionsForUpload), m_pageID); #endif } -void WebPageProxy::didPerformDragControllerAction(WebCore::DragSession dragSession) +void WebPageProxy::didPerformDragControllerAction(uint64_t dragOperation, bool mouseIsOverFileInput, unsigned numberOfItemsToBeAccepted) { - m_currentDragSession = dragSession; + MESSAGE_CHECK(dragOperation <= DragOperationDelete); + + m_currentDragOperation = static_cast<DragOperation>(dragOperation); + m_currentDragIsOverFileInput = mouseIsOverFileInput; + m_currentDragNumberOfFilesToBeAccepted = numberOfItemsToBeAccepted; } #if PLATFORM(QT) || PLATFORM(GTK) @@ -1237,7 +1694,7 @@ void WebPageProxy::startDrag(const DragData& dragData, const ShareableBitmap::Ha return; } - m_pageClient->startDrag(dragData, dragImage.release()); + m_pageClient.startDrag(dragData, dragImage.release()); } #endif @@ -1254,12 +1711,15 @@ void WebPageProxy::handleMouseEvent(const NativeWebMouseEvent& event) if (!isValid()) return; + if (m_pageClient.windowIsFrontWindowUnderMouse(event)) + setToolTip(String()); + // NOTE: This does not start the responsiveness timer because mouse move should not indicate interaction. if (event.type() != WebEvent::MouseMove) - m_process->responsivenessTimer()->start(); + m_process->responsivenessTimer().start(); else { if (m_processingMouseMoveEvent) { - m_nextMouseMoveEvent = adoptPtr(new NativeWebMouseEvent(event)); + m_nextMouseMoveEvent = std::make_unique<NativeWebMouseEvent>(event); return; } @@ -1271,14 +1731,9 @@ void WebPageProxy::handleMouseEvent(const NativeWebMouseEvent& event) // we fake a mouse up event by using this stored down event. This event gets cleared // when the mouse up message is received from WebProcess. if (event.type() == WebEvent::MouseDown) - m_currentlyProcessedMouseDownEvent = adoptPtr(new NativeWebMouseEvent(event)); + m_currentlyProcessedMouseDownEvent = std::make_unique<NativeWebMouseEvent>(event); - if (m_shouldSendEventsSynchronously) { - bool handled = false; - m_process->sendSync(Messages::WebPage::MouseEventSyncForTesting(event), Messages::WebPage::MouseEventSyncForTesting::Reply(handled), m_pageID); - didReceiveEvent(event.type(), handled); - } else - m_process->send(Messages::WebPage::MouseEvent(event), m_pageID); + m_process->send(Messages::WebPage::MouseEvent(event), m_pageID); } #if MERGE_WHEEL_EVENTS @@ -1292,7 +1747,7 @@ static bool canCoalesce(const WebWheelEvent& a, const WebWheelEvent& b) return false; if (a.granularity() != b.granularity()) return false; -#if PLATFORM(MAC) +#if PLATFORM(COCOA) if (a.phase() != b.phase()) return false; if (a.momentumPhase() != b.momentumPhase()) @@ -1311,7 +1766,7 @@ static WebWheelEvent coalesce(const WebWheelEvent& a, const WebWheelEvent& b) FloatSize mergedDelta = a.delta() + b.delta(); FloatSize mergedWheelTicks = a.wheelTicks() + b.wheelTicks(); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) FloatSize mergedUnacceleratedScrollingDelta = a.unacceleratedScrollingDelta() + b.unacceleratedScrollingDelta(); return WebWheelEvent(WebEvent::Wheel, b.position(), b.globalPosition(), mergedDelta, mergedWheelTicks, b.granularity(), b.directionInvertedFromDevice(), b.phase(), b.momentumPhase(), b.hasPreciseScrollingDeltas(), b.scrollCount(), mergedUnacceleratedScrollingDelta, b.modifiers(), b.timestamp()); @@ -1347,6 +1802,11 @@ static WebWheelEvent coalescedWheelEvent(Deque<NativeWebWheelEvent>& queue, Vect void WebPageProxy::handleWheelEvent(const NativeWebWheelEvent& event) { +#if ENABLE(ASYNC_SCROLLING) + if (m_scrollingCoordinatorProxy && m_scrollingCoordinatorProxy->handleWheelEvent(platform(event))) + return; +#endif + if (!isValid()) return; @@ -1362,32 +1822,35 @@ void WebPageProxy::handleWheelEvent(const NativeWebWheelEvent& event) return; } - OwnPtr<Vector<NativeWebWheelEvent> > coalescedWheelEvent = adoptPtr(new Vector<NativeWebWheelEvent>); + auto coalescedWheelEvent = std::make_unique<Vector<NativeWebWheelEvent>>(); coalescedWheelEvent->append(event); - m_currentlyProcessedWheelEvents.append(coalescedWheelEvent.release()); + m_currentlyProcessedWheelEvents.append(WTFMove(coalescedWheelEvent)); sendWheelEvent(event); } void WebPageProxy::processNextQueuedWheelEvent() { - OwnPtr<Vector<NativeWebWheelEvent> > nextCoalescedEvent = adoptPtr(new Vector<NativeWebWheelEvent>); + auto nextCoalescedEvent = std::make_unique<Vector<NativeWebWheelEvent>>(); WebWheelEvent nextWheelEvent = coalescedWheelEvent(m_wheelEventQueue, *nextCoalescedEvent.get()); - m_currentlyProcessedWheelEvents.append(nextCoalescedEvent.release()); + m_currentlyProcessedWheelEvents.append(WTFMove(nextCoalescedEvent)); sendWheelEvent(nextWheelEvent); } void WebPageProxy::sendWheelEvent(const WebWheelEvent& event) { - m_process->responsivenessTimer()->start(); - - if (m_shouldSendEventsSynchronously) { - bool handled = false; - m_process->sendSync(Messages::WebPage::WheelEventSyncForTesting(event), Messages::WebPage::WheelEventSyncForTesting::Reply(handled), m_pageID); - didReceiveEvent(event.type(), handled); - return; - } + m_process->send( + Messages::EventDispatcher::WheelEvent( + m_pageID, + event, + shouldUseImplicitRubberBandControl() ? !m_backForwardList->backItem() : rubberBandsAtLeft(), + shouldUseImplicitRubberBandControl() ? !m_backForwardList->forwardItem() : rubberBandsAtRight(), + rubberBandsAtTop(), + rubberBandsAtBottom() + ), 0); - m_process->send(Messages::EventDispatcher::WheelEvent(m_pageID, event, canGoBack(), canGoForward()), 0); + // Manually ping the web process to check for responsiveness since our wheel + // event will dispatch to a non-main thread, which always responds. + m_process->isResponsive(nullptr); } void WebPageProxy::handleKeyboardEvent(const NativeWebKeyboardEvent& event) @@ -1399,25 +1862,35 @@ void WebPageProxy::handleKeyboardEvent(const NativeWebKeyboardEvent& event) m_keyEventQueue.append(event); - m_process->responsivenessTimer()->start(); - if (m_shouldSendEventsSynchronously) { - bool handled = false; - m_process->sendSync(Messages::WebPage::KeyEventSyncForTesting(event), Messages::WebPage::KeyEventSyncForTesting::Reply(handled), m_pageID); - didReceiveEvent(event.type(), handled); - } else if (m_keyEventQueue.size() == 1) // Otherwise, sent from DidReceiveEvent message handler. + m_process->responsivenessTimer().start(); + if (m_keyEventQueue.size() == 1) // Otherwise, sent from DidReceiveEvent message handler. m_process->send(Messages::WebPage::KeyEvent(event), m_pageID); } +WebPreferencesStore WebPageProxy::preferencesStore() const +{ + if (m_configurationPreferenceValues.isEmpty()) + return m_preferences->store(); + + WebPreferencesStore store = m_preferences->store(); + for (const auto& preference : m_configurationPreferenceValues) + store.m_values.set(preference.key, preference.value); + + return store; +} + #if ENABLE(NETSCAPE_PLUGIN_API) void WebPageProxy::findPlugin(const String& mimeType, uint32_t processType, const String& urlString, const String& frameURLString, const String& pageURLString, bool allowOnlyApplicationPlugins, uint64_t& pluginProcessToken, String& newMimeType, uint32_t& pluginLoadPolicy, String& unavailabilityDescription) { + PageClientProtector protector(m_pageClient); + MESSAGE_CHECK_URL(urlString); - newMimeType = mimeType.lower(); + newMimeType = mimeType.convertToASCIILowercase(); pluginLoadPolicy = PluginModuleLoadNormally; PluginData::AllowedPluginTypes allowedPluginTypes = allowOnlyApplicationPlugins ? PluginData::OnlyApplicationPlugins : PluginData::AllPlugins; - PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), urlString), allowedPluginTypes); + PluginModuleInfo plugin = m_process->processPool().pluginInfoStore().findPlugin(newMimeType, URL(URL(), urlString), allowedPluginTypes); if (!plugin.path) { pluginProcessToken = 0; return; @@ -1425,12 +1898,16 @@ void WebPageProxy::findPlugin(const String& mimeType, uint32_t processType, cons pluginLoadPolicy = PluginInfoStore::defaultLoadPolicyForPlugin(plugin); -#if PLATFORM(MAC) - RefPtr<ImmutableDictionary> pluginInformation = createPluginInformationDictionary(plugin, frameURLString, String(), pageURLString, String(), String()); - pluginLoadPolicy = m_loaderClient.pluginLoadPolicy(this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get(), unavailabilityDescription); +#if PLATFORM(COCOA) + RefPtr<API::Dictionary> pluginInformation = createPluginInformationDictionary(plugin, frameURLString, String(), pageURLString, String(), String()); + if (m_navigationClient) + pluginLoadPolicy = m_navigationClient->decidePolicyForPluginLoad(*this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get(), unavailabilityDescription); + else + pluginLoadPolicy = m_loaderClient->pluginLoadPolicy(*this, static_cast<PluginModuleLoadPolicy>(pluginLoadPolicy), pluginInformation.get(), unavailabilityDescription); #else UNUSED_PARAM(frameURLString); UNUSED_PARAM(pageURLString); + UNUSED_PARAM(unavailabilityDescription); #endif PluginProcessSandboxPolicy pluginProcessSandboxPolicy = PluginProcessSandboxPolicyNormal; @@ -1442,30 +1919,91 @@ void WebPageProxy::findPlugin(const String& mimeType, uint32_t processType, cons pluginProcessSandboxPolicy = PluginProcessSandboxPolicyUnsandboxed; break; - case PluginModuleBlocked: + case PluginModuleBlockedForSecurity: + case PluginModuleBlockedForCompatibility: pluginProcessToken = 0; return; } - pluginProcessToken = PluginProcessManager::shared().pluginProcessToken(plugin, static_cast<PluginProcessType>(processType), pluginProcessSandboxPolicy); + pluginProcessToken = PluginProcessManager::singleton().pluginProcessToken(plugin, static_cast<PluginProcessType>(processType), pluginProcessSandboxPolicy); } #endif // ENABLE(NETSCAPE_PLUGIN_API) -#if ENABLE(GESTURE_EVENTS) -void WebPageProxy::handleGestureEvent(const WebGestureEvent& event) +#if ENABLE(TOUCH_EVENTS) + +bool WebPageProxy::shouldStartTrackingTouchEvents(const WebTouchEvent& touchStartEvent) const +{ +#if ENABLE(ASYNC_SCROLLING) + for (auto& touchPoint : touchStartEvent.touchPoints()) { + if (m_scrollingCoordinatorProxy->isPointInNonFastScrollableRegion(touchPoint.location())) + return true; + } + + return false; +#else + UNUSED_PARAM(touchStartEvent); +#endif // ENABLE(ASYNC_SCROLLING) + return true; +} + +#endif + +#if ENABLE(MAC_GESTURE_EVENTS) +void WebPageProxy::handleGestureEvent(const NativeWebGestureEvent& event) { if (!isValid()) return; m_gestureEventQueue.append(event); + // FIXME: Consider doing some coalescing here. + m_process->responsivenessTimer().start(); - m_process->responsivenessTimer()->start(); m_process->send(Messages::EventDispatcher::GestureEvent(m_pageID, event), 0); } #endif -#if ENABLE(TOUCH_EVENTS) +#if ENABLE(IOS_TOUCH_EVENTS) +void WebPageProxy::handleTouchEventSynchronously(const NativeWebTouchEvent& event) +{ + if (!isValid()) + return; + + if (event.type() == WebEvent::TouchStart) { + m_isTrackingTouchEvents = shouldStartTrackingTouchEvents(event); + m_layerTreeTransactionIdAtLastTouchStart = downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea()).lastCommittedLayerTreeTransactionID(); + } + + if (!m_isTrackingTouchEvents) + return; + + m_process->responsivenessTimer().start(); + bool handled = false; + m_process->sendSync(Messages::WebPage::TouchEventSync(event), Messages::WebPage::TouchEventSync::Reply(handled), m_pageID); + didReceiveEvent(event.type(), handled); + m_pageClient.doneWithTouchEvent(event, handled); + m_process->responsivenessTimer().stop(); + + if (event.allTouchPointsAreReleased()) + m_isTrackingTouchEvents = false; +} + +void WebPageProxy::handleTouchEventAsynchronously(const NativeWebTouchEvent& event) +{ + if (!isValid()) + return; + + if (!m_isTrackingTouchEvents) + return; + + m_process->send(Messages::EventDispatcher::TouchEvent(m_pageID, event), 0); + + if (event.allTouchPointsAreReleased()) + m_isTrackingTouchEvents = false; +} + +#elif ENABLE(TOUCH_EVENTS) + #if PLATFORM(QT) void WebPageProxy::handlePotentialActivation(const IntPoint& touchPoint, const IntSize& touchArea) { @@ -1478,22 +2016,23 @@ void WebPageProxy::handleTouchEvent(const NativeWebTouchEvent& event) if (!isValid()) return; + if (event.type() == WebEvent::TouchStart) + m_isTrackingTouchEvents = shouldStartTrackingTouchEvents(event); + + if (!m_isTrackingTouchEvents) + return; + // If the page is suspended, which should be the case during panning, pinching // and animation on the page itself (kinetic scrolling, tap to zoom) etc, then // we do not send any of the events to the page even if is has listeners. - if (m_needTouchEvents && !m_isPageSuspended) { + if (!m_isPageSuspended) { m_touchEventQueue.append(event); - m_process->responsivenessTimer()->start(); - if (m_shouldSendEventsSynchronously) { - bool handled = false; - m_process->sendSync(Messages::WebPage::TouchEventSyncForTesting(event), Messages::WebPage::TouchEventSyncForTesting::Reply(handled), m_pageID); - didReceiveEvent(event.type(), handled); - } else - m_process->send(Messages::WebPage::TouchEvent(event), m_pageID); + m_process->responsivenessTimer().start(); + m_process->send(Messages::WebPage::TouchEvent(event), m_pageID); } else { if (m_touchEventQueue.isEmpty()) { bool isEventHandled = false; - m_pageClient->doneWithTouchEvent(event, isEventHandled); + m_pageClient.doneWithTouchEvent(event, isEventHandled); } else { // We attach the incoming events to the newest queued event so that all // the events are delivered in the correct order when the event is dequed. @@ -1501,8 +2040,11 @@ void WebPageProxy::handleTouchEvent(const NativeWebTouchEvent& event) lastEvent.deferredTouchEvents.append(event); } } + + if (event.allTouchPointsAreReleased()) + m_isTrackingTouchEvents = false; } -#endif +#endif // ENABLE(TOUCH_EVENTS) void WebPageProxy::scrollBy(ScrollDirection direction, ScrollGranularity granularity) { @@ -1520,23 +2062,24 @@ void WebPageProxy::centerSelectionInVisibleArea() m_process->send(Messages::WebPage::CenterSelectionInVisibleArea(), m_pageID); } -void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy* frame, uint64_t listenerID) +void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy* frame, uint64_t listenerID, API::Navigation* navigation) { if (!isValid()) return; + auto transaction = m_pageLoadState.transaction(); + if (action == PolicyIgnore) - clearPendingAPIRequestURL(); + m_pageLoadState.clearPendingAPIRequestURL(transaction); - uint64_t downloadID = 0; + DownloadID downloadID = { }; if (action == PolicyDownload) { // Create a download proxy. - DownloadProxy* download = m_process->context()->createDownloadProxy(); + // FIXME: We should ensure that the downloadRequest is never empty. + const ResourceRequest& downloadRequest = m_decidePolicyForResponseRequest ? *m_decidePolicyForResponseRequest : ResourceRequest(); + DownloadProxy* download = m_process->processPool().createDownloadProxy(downloadRequest); downloadID = download->downloadID(); -#if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) - // Our design does not suppport downloads without a WebPage. handleDownloadRequest(download); -#endif } // If we received a policy decision while in decidePolicyForResponse the decision will @@ -1557,17 +2100,7 @@ void WebPageProxy::receivedPolicyDecision(PolicyAction action, WebFrameProxy* fr return; } - m_process->send(Messages::WebPage::DidReceivePolicyDecision(frame->frameID(), listenerID, action, downloadID), m_pageID); -} - -String WebPageProxy::pageTitle() const -{ - // Return the null string if there is no main frame (e.g. nothing has been loaded in the page yet, WebProcess has - // crashed, page has been closed). - if (!m_mainFrame) - return String(); - - return m_mainFrame->title(); + m_process->send(Messages::WebPage::DidReceivePolicyDecision(frame->frameID(), listenerID, action, navigation ? navigation->navigationID() : 0, downloadID), m_pageID); } void WebPageProxy::setUserAgent(const String& userAgent) @@ -1647,6 +2180,11 @@ void WebPageProxy::setCustomTextEncodingName(const String& encodingName) void WebPageProxy::terminateProcess() { + // requestTermination() is a no-op for launching processes, so we get into an inconsistent state by calling resetStateAfterProcessExited(). + // FIXME: A client can terminate the page at any time, so we should do something more meaningful than assert and fall apart in release builds. + // See also <https://bugs.webkit.org/show_bug.cgi?id=136012>. + ASSERT(m_process->state() != WebProcessProxy::State::Launching); + // NOTE: This uses a check of m_isValid rather than calling isValid() since // we want this to run even for pages being closed or that already closed. if (!m_isValid) @@ -1656,18 +2194,61 @@ void WebPageProxy::terminateProcess() resetStateAfterProcessExited(); } -#if !USE(CF) || defined(BUILDING_QT__) -PassRefPtr<WebData> WebPageProxy::sessionStateData(WebPageProxySessionStateFilterCallback, void* /*context*/) const +SessionState WebPageProxy::sessionState(const std::function<bool (WebBackForwardListItem&)>& filter) const { - // FIXME: Return session state data for saving Page state. - return 0; + SessionState sessionState; + + sessionState.backForwardListState = m_backForwardList->backForwardListState(filter); + + String provisionalURLString = m_pageLoadState.pendingAPIRequestURL(); + if (provisionalURLString.isEmpty()) + provisionalURLString = m_pageLoadState.provisionalURL(); + + if (!provisionalURLString.isEmpty()) + sessionState.provisionalURL = URL(URL(), provisionalURLString); + + sessionState.renderTreeSize = renderTreeSize(); + return sessionState; } -void WebPageProxy::restoreFromSessionStateData(WebData*) +RefPtr<API::Navigation> WebPageProxy::restoreFromSessionState(SessionState sessionState, bool navigate) { - // FIXME: Restore the Page from the passed in session state data. + m_sessionRestorationRenderTreeSize = 0; + m_hitRenderTreeSizeThreshold = false; + + bool hasBackForwardList = !!sessionState.backForwardListState.currentIndex; + + if (hasBackForwardList) { + m_backForwardList->restoreFromState(WTFMove(sessionState.backForwardListState)); + + for (const auto& entry : m_backForwardList->entries()) + process().registerNewWebBackForwardListItem(entry.get()); + + process().send(Messages::WebPage::RestoreSession(m_backForwardList->itemStates()), m_pageID); + + // The back / forward list was restored from a sessionState so we don't want to snapshot the current + // page when navigating away. Suppress navigation snapshotting until the next load has committed. + m_suppressNavigationSnapshotting = true; + } + + // FIXME: Navigating should be separate from state restoration. + if (navigate) { + m_sessionRestorationRenderTreeSize = sessionState.renderTreeSize; + if (!m_sessionRestorationRenderTreeSize) + m_hitRenderTreeSizeThreshold = true; // If we didn't get data on renderTreeSize, just don't fire the milestone. + + if (!sessionState.provisionalURL.isNull()) + return loadRequest(sessionState.provisionalURL); + + if (hasBackForwardList) { + // FIXME: Do we have to null check the back forward list item here? + if (WebBackForwardListItem* item = m_backForwardList->currentItem()) + return goToBackForwardItem(item); + } + } + + return nullptr; } -#endif bool WebPageProxy::supportsTextZoom() const { @@ -1715,14 +2296,57 @@ void WebPageProxy::setPageAndTextZoomFactors(double pageZoomFactor, double textZ m_process->send(Messages::WebPage::SetPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor), m_pageID); } +double WebPageProxy::pageZoomFactor() const +{ + // Zoom factor for non-PDF pages persists across page loads. We maintain a separate member variable for PDF + // zoom which ensures that we don't use the PDF zoom for a normal page. + if (m_mainFramePluginHandlesPageScaleGesture) + return m_pluginZoomFactor; + return m_pageZoomFactor; +} + +double WebPageProxy::pageScaleFactor() const +{ + // PDF documents use zoom and scale factors to size themselves appropriately in the window. We store them + // separately but decide which to return based on the main frame. + if (m_mainFramePluginHandlesPageScaleGesture) + return m_pluginScaleFactor; + return m_pageScaleFactor; +} + void WebPageProxy::scalePage(double scale, const IntPoint& origin) { + ASSERT(scale > 0); + if (!isValid()) return; + m_pageScaleFactor = scale; m_process->send(Messages::WebPage::ScalePage(scale, origin), m_pageID); } +void WebPageProxy::scalePageInViewCoordinates(double scale, const IntPoint& centerInViewCoordinates) +{ + ASSERT(scale > 0); + + if (!isValid()) + return; + + m_pageScaleFactor = scale; + m_process->send(Messages::WebPage::ScalePageInViewCoordinates(scale, centerInViewCoordinates), m_pageID); +} + +void WebPageProxy::scaleView(double scale) +{ + ASSERT(scale > 0); + + if (!isValid()) + return; + + m_viewScaleFactor = scale; + m_process->send(Messages::WebPage::ScaleView(scale), m_pageID); +} + void WebPageProxy::setIntrinsicDeviceScaleFactor(float scaleFactor) { if (m_intrinsicDeviceScaleFactor == scaleFactor) @@ -1754,6 +2378,12 @@ void WebPageProxy::setCustomDeviceScaleFactor(float customScaleFactor) if (!isValid()) return; + // FIXME: Remove this once we bump cairo requirements to support HiDPI. + // https://bugs.webkit.org/show_bug.cgi?id=133378 +#if USE(CAIRO) && !HAVE(CAIRO_SURFACE_SET_DEVICE_SCALE) + return; +#endif + if (m_customDeviceScaleFactor == customScaleFactor) return; @@ -1797,23 +2427,12 @@ void WebPageProxy::listenForLayoutMilestones(WebCore::LayoutMilestones milestone { if (!isValid()) return; + + m_wantsSessionRestorationRenderTreeSizeThresholdEvent = milestones & WebCore::ReachedSessionRestorationRenderTreeSizeThreshold; m_process->send(Messages::WebPage::ListenForLayoutMilestones(milestones), m_pageID); } -void WebPageProxy::setVisibilityState(WebCore::PageVisibilityState visibilityState, bool isInitialState) -{ - if (!isValid()) - return; - -#if ENABLE(PAGE_VISIBILITY_API) - if (visibilityState != m_visibilityState || isInitialState) { - m_visibilityState = visibilityState; - m_process->send(Messages::WebPage::SetVisibilityState(visibilityState, isInitialState), m_pageID); - } -#endif -} - void WebPageProxy::setSuppressScrollbarAnimations(bool suppressAnimations) { if (!isValid()) @@ -1826,30 +2445,95 @@ void WebPageProxy::setSuppressScrollbarAnimations(bool suppressAnimations) m_process->send(Messages::WebPage::SetSuppressScrollbarAnimations(suppressAnimations), m_pageID); } +bool WebPageProxy::rubberBandsAtLeft() const +{ + return m_rubberBandsAtLeft; +} + +void WebPageProxy::setRubberBandsAtLeft(bool rubberBandsAtLeft) +{ + m_rubberBandsAtLeft = rubberBandsAtLeft; +} + +bool WebPageProxy::rubberBandsAtRight() const +{ + return m_rubberBandsAtRight; +} + +void WebPageProxy::setRubberBandsAtRight(bool rubberBandsAtRight) +{ + m_rubberBandsAtRight = rubberBandsAtRight; +} + +bool WebPageProxy::rubberBandsAtTop() const +{ + return m_rubberBandsAtTop; +} + +void WebPageProxy::setRubberBandsAtTop(bool rubberBandsAtTop) +{ + m_rubberBandsAtTop = rubberBandsAtTop; +} + +bool WebPageProxy::rubberBandsAtBottom() const +{ + return m_rubberBandsAtBottom; +} + void WebPageProxy::setRubberBandsAtBottom(bool rubberBandsAtBottom) { - if (rubberBandsAtBottom == m_rubberBandsAtBottom) + m_rubberBandsAtBottom = rubberBandsAtBottom; +} + +void WebPageProxy::setEnableVerticalRubberBanding(bool enableVerticalRubberBanding) +{ + if (enableVerticalRubberBanding == m_enableVerticalRubberBanding) return; - m_rubberBandsAtBottom = rubberBandsAtBottom; + m_enableVerticalRubberBanding = enableVerticalRubberBanding; if (!isValid()) return; + m_process->send(Messages::WebPage::SetEnableVerticalRubberBanding(enableVerticalRubberBanding), m_pageID); +} + +bool WebPageProxy::verticalRubberBandingIsEnabled() const +{ + return m_enableVerticalRubberBanding; +} + +void WebPageProxy::setEnableHorizontalRubberBanding(bool enableHorizontalRubberBanding) +{ + if (enableHorizontalRubberBanding == m_enableHorizontalRubberBanding) + return; + + m_enableHorizontalRubberBanding = enableHorizontalRubberBanding; - m_process->send(Messages::WebPage::SetRubberBandsAtBottom(rubberBandsAtBottom), m_pageID); + if (!isValid()) + return; + m_process->send(Messages::WebPage::SetEnableHorizontalRubberBanding(enableHorizontalRubberBanding), m_pageID); +} + +bool WebPageProxy::horizontalRubberBandingIsEnabled() const +{ + return m_enableHorizontalRubberBanding; } -void WebPageProxy::setRubberBandsAtTop(bool rubberBandsAtTop) +void WebPageProxy::setBackgroundExtendsBeyondPage(bool backgroundExtendsBeyondPage) { - if (rubberBandsAtTop == m_rubberBandsAtTop) + if (backgroundExtendsBeyondPage == m_backgroundExtendsBeyondPage) return; - m_rubberBandsAtTop = rubberBandsAtTop; + m_backgroundExtendsBeyondPage = backgroundExtendsBeyondPage; if (!isValid()) return; + m_process->send(Messages::WebPage::SetBackgroundExtendsBeyondPage(backgroundExtendsBeyondPage), m_pageID); +} - m_process->send(Messages::WebPage::SetRubberBandsAtTop(rubberBandsAtTop), m_pageID); +bool WebPageProxy::backgroundExtendsBeyondPage() const +{ + return m_backgroundExtendsBeyondPage; } void WebPageProxy::setPaginationMode(WebCore::Pagination::Mode mode) @@ -1900,32 +2584,37 @@ void WebPageProxy::setGapBetweenPages(double gap) m_process->send(Messages::WebPage::SetGapBetweenPages(gap), m_pageID); } +void WebPageProxy::setPaginationLineGridEnabled(bool lineGridEnabled) +{ + if (lineGridEnabled == m_paginationLineGridEnabled) + return; + + m_paginationLineGridEnabled = lineGridEnabled; + + if (!isValid()) + return; + m_process->send(Messages::WebPage::SetPaginationLineGridEnabled(lineGridEnabled), m_pageID); +} + void WebPageProxy::pageScaleFactorDidChange(double scaleFactor) { m_pageScaleFactor = scaleFactor; } -void WebPageProxy::pageZoomFactorDidChange(double zoomFactor) +void WebPageProxy::pluginScaleFactorDidChange(double pluginScaleFactor) { - m_pageZoomFactor = zoomFactor; + m_pluginScaleFactor = pluginScaleFactor; } -void WebPageProxy::setMemoryCacheClientCallsEnabled(bool memoryCacheClientCallsEnabled) +void WebPageProxy::pluginZoomFactorDidChange(double pluginZoomFactor) { - if (!isValid()) - return; - - if (m_areMemoryCacheClientCallsEnabled == memoryCacheClientCallsEnabled) - return; - - m_areMemoryCacheClientCallsEnabled = memoryCacheClientCallsEnabled; - m_process->send(Messages::WebPage::SetMemoryCacheMessagesEnabled(memoryCacheClientCallsEnabled), m_pageID); + m_pluginZoomFactor = pluginZoomFactor; } void WebPageProxy::findStringMatches(const String& string, FindOptions options, unsigned maxMatchCount) { if (string.isEmpty()) { - didFindStringMatches(string, Vector<Vector<WebCore::IntRect> > (), 0); + didFindStringMatches(string, Vector<Vector<WebCore::IntRect>> (), 0); return; } @@ -1960,137 +2649,142 @@ void WebPageProxy::countStringMatches(const String& string, FindOptions options, m_process->send(Messages::WebPage::CountStringMatches(string, options, maxMatchCount), m_pageID); } -void WebPageProxy::runJavaScriptInMainFrame(const String& script, PassRefPtr<ScriptValueCallback> prpCallback) +void WebPageProxy::runJavaScriptInMainFrame(const String& script, std::function<void (API::SerializedScriptValue*, bool hadException, const ExceptionDetails&, CallbackBase::Error)> callbackFunction) { - RefPtr<ScriptValueCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(nullptr, false, { }, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_scriptValueCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::RunJavaScriptInMainFrame(script, callbackID), m_pageID); } -void WebPageProxy::getRenderTreeExternalRepresentation(PassRefPtr<StringCallback> prpCallback) +void WebPageProxy::getRenderTreeExternalRepresentation(std::function<void (const String&, CallbackBase::Error)> callbackFunction) { - RefPtr<StringCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(String(), CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_stringCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::GetRenderTreeExternalRepresentation(callbackID), m_pageID); } -void WebPageProxy::getSourceForFrame(WebFrameProxy* frame, PassRefPtr<StringCallback> prpCallback) +void WebPageProxy::getSourceForFrame(WebFrameProxy* frame, std::function<void (const String&, CallbackBase::Error)> callbackFunction) { - RefPtr<StringCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(String(), CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_loadDependentStringCallbackIDs.add(callbackID); - m_stringCallbacks.set(callbackID, callback.get()); m_process->send(Messages::WebPage::GetSourceForFrame(frame->frameID(), callbackID), m_pageID); } -void WebPageProxy::getContentsAsString(PassRefPtr<StringCallback> prpCallback) +void WebPageProxy::getContentsAsString(std::function<void (const String&, CallbackBase::Error)> callbackFunction) { - RefPtr<StringCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(String(), CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_loadDependentStringCallbackIDs.add(callbackID); - m_stringCallbacks.set(callbackID, callback.get()); m_process->send(Messages::WebPage::GetContentsAsString(callbackID), m_pageID); } +void WebPageProxy::getBytecodeProfile(std::function<void (const String&, CallbackBase::Error)> callbackFunction) +{ + if (!isValid()) { + callbackFunction(String(), CallbackBase::Error::Unknown); + return; + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + m_loadDependentStringCallbackIDs.add(callbackID); + m_process->send(Messages::WebPage::GetBytecodeProfile(callbackID), m_pageID); +} + +void WebPageProxy::isWebProcessResponsive(std::function<void (bool isWebProcessResponsive)> callbackFunction) +{ + if (!isValid()) { + RunLoop::main().dispatch([callbackFunction] { + bool isWebProcessResponsive = true; + callbackFunction(isWebProcessResponsive); + }); + return; + } + + m_process->isResponsive(callbackFunction); +} + #if ENABLE(MHTML) -void WebPageProxy::getContentsAsMHTMLData(PassRefPtr<DataCallback> prpCallback, bool useBinaryEncoding) +void WebPageProxy::getContentsAsMHTMLData(std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { - RefPtr<DataCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_dataCallbacks.set(callbackID, callback.get()); - m_process->send(Messages::WebPage::GetContentsAsMHTMLData(callbackID, useBinaryEncoding), m_pageID); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + m_process->send(Messages::WebPage::GetContentsAsMHTMLData(callbackID), m_pageID); } #endif -void WebPageProxy::getSelectionOrContentsAsString(PassRefPtr<StringCallback> prpCallback) +void WebPageProxy::getSelectionOrContentsAsString(std::function<void (const String&, CallbackBase::Error)> callbackFunction) { - RefPtr<StringCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(String(), CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_stringCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::GetSelectionOrContentsAsString(callbackID), m_pageID); } -void WebPageProxy::getSelectionAsWebArchiveData(PassRefPtr<DataCallback> prpCallback) +void WebPageProxy::getSelectionAsWebArchiveData(std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { - RefPtr<DataCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_dataCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::GetSelectionAsWebArchiveData(callbackID), m_pageID); } -void WebPageProxy::getMainResourceDataOfFrame(WebFrameProxy* frame, PassRefPtr<DataCallback> prpCallback) +void WebPageProxy::getMainResourceDataOfFrame(WebFrameProxy* frame, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { - RefPtr<DataCallback> callback = prpCallback; - if (!isValid()) { - callback->invalidate(); + if (!isValid() || !frame) { + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_dataCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::GetMainResourceDataOfFrame(frame->frameID(), callbackID), m_pageID); } -void WebPageProxy::getResourceDataFromFrame(WebFrameProxy* frame, WebURL* resourceURL, PassRefPtr<DataCallback> prpCallback) +void WebPageProxy::getResourceDataFromFrame(WebFrameProxy* frame, API::URL* resourceURL, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { - RefPtr<DataCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_dataCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::GetResourceDataFromFrame(frame->frameID(), resourceURL->string(), callbackID), m_pageID); } -void WebPageProxy::getWebArchiveOfFrame(WebFrameProxy* frame, PassRefPtr<DataCallback> prpCallback) +void WebPageProxy::getWebArchiveOfFrame(WebFrameProxy* frame, std::function<void (API::Data*, CallbackBase::Error)> callbackFunction) { - RefPtr<DataCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + callbackFunction(nullptr, CallbackBase::Error::Unknown); return; } - uint64_t callbackID = callback->callbackID(); - m_dataCallbacks.set(callbackID, callback.get()); + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); m_process->send(Messages::WebPage::GetWebArchiveOfFrame(frame->frameID(), callbackID), m_pageID); } @@ -2098,12 +2792,13 @@ void WebPageProxy::forceRepaint(PassRefPtr<VoidCallback> prpCallback) { RefPtr<VoidCallback> callback = prpCallback; if (!isValid()) { - callback->invalidate(); + // FIXME: If the page is invalid we should not call the callback. It'd be better to just return false from forceRepaint. + callback->invalidate(CallbackBase::Error::OwnerWasInvalidated); return; } uint64_t callbackID = callback->callbackID(); - m_voidCallbacks.set(callbackID, callback.get()); + m_callbacks.put(callback); m_drawingArea->waitForBackingStoreUpdateOnNextPaint(); m_process->send(Messages::WebPage::ForceRepaint(callbackID), m_pageID); } @@ -2114,24 +2809,26 @@ void WebPageProxy::preferencesDidChange() return; #if ENABLE(INSPECTOR_SERVER) - if (m_pageGroup->preferences()->developerExtrasEnabled()) + if (m_preferences->developerExtrasEnabled()) inspector()->enableRemoteInspection(); #endif - m_process->pagePreferencesChanged(this); + updateProccessSuppressionState(); - m_pageClient->preferencesDidChange(); + m_pageClient.preferencesDidChange(); // FIXME: It probably makes more sense to send individual preference changes. // However, WebKitTestRunner depends on getting a preference change notification // even if nothing changed in UI process, so that overrides get removed. // Preferences need to be updated during synchronous printing to make "print backgrounds" preference work when toggled from a print dialog checkbox. - m_process->send(Messages::WebPage::PreferencesDidChange(pageGroup()->preferences()->store()), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_process->send(Messages::WebPage::PreferencesDidChange(preferencesStore()), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } void WebPageProxy::didCreateMainFrame(uint64_t frameID) { + PageClientProtector protector(m_pageClient); + MESSAGE_CHECK(!m_mainFrame); MESSAGE_CHECK(m_process->canCreateFrame(frameID)); @@ -2143,6 +2840,8 @@ void WebPageProxy::didCreateMainFrame(uint64_t frameID) void WebPageProxy::didCreateSubframe(uint64_t frameID) { + PageClientProtector protector(m_pageClient); + MESSAGE_CHECK(m_mainFrame); MESSAGE_CHECK(m_process->canCreateFrame(frameID)); @@ -2152,87 +2851,171 @@ void WebPageProxy::didCreateSubframe(uint64_t frameID) m_process->frameCreated(frameID, subFrame.get()); } -// Always start progress at initialProgressValue. This helps provide feedback as -// soon as a load starts. - -static const double initialProgressValue = 0.1; - double WebPageProxy::estimatedProgress() const { - if (!pendingAPIRequestURL().isNull()) - return initialProgressValue; - return m_estimatedProgress; + return m_pageLoadState.estimatedProgress(); } void WebPageProxy::didStartProgress() { - m_estimatedProgress = initialProgressValue; + PageClientProtector protector(m_pageClient); - m_loaderClient.didStartProgress(this); + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.didStartProgress(transaction); + + m_pageLoadState.commitChanges(); + m_loaderClient->didStartProgress(*this); } void WebPageProxy::didChangeProgress(double value) { - m_estimatedProgress = value; + PageClientProtector protector(m_pageClient); + + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.didChangeProgress(transaction, value); - m_loaderClient.didChangeProgress(this); + m_pageLoadState.commitChanges(); + m_loaderClient->didChangeProgress(*this); } void WebPageProxy::didFinishProgress() { - m_estimatedProgress = 1.0; + PageClientProtector protector(m_pageClient); + + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.didFinishProgress(transaction); - m_loaderClient.didFinishProgress(this); + m_pageLoadState.commitChanges(); + m_loaderClient->didFinishProgress(*this); } -void WebPageProxy::didStartProvisionalLoadForFrame(uint64_t frameID, const String& url, const String& unreachableURL, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::setNetworkRequestsInProgress(bool networkRequestsInProgress) { - clearPendingAPIRequestURL(); + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.setNetworkRequestsInProgress(transaction, networkRequestsInProgress); +} - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; +void WebPageProxy::didDestroyNavigation(uint64_t navigationID) +{ + PageClientProtector protector(m_pageClient); + + // FIXME: Message check the navigationID. + m_navigationState->didDestroyNavigation(navigationID); +} + +void WebPageProxy::didStartProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& url, const String& unreachableURL, const UserData& userData) +{ + PageClientProtector protector(m_pageClient); + + auto transaction = m_pageLoadState.transaction(); + + m_pageLoadState.clearPendingAPIRequestURL(transaction); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(url); - frame->setUnreachableURL(unreachableURL); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + if (frame->isMainFrame()) + m_pageLoadState.didStartProvisionalLoad(transaction, url, unreachableURL); + + frame->setUnreachableURL(unreachableURL); frame->didStartProvisionalLoad(url); - m_loaderClient.didStartProvisionalLoadForFrame(this, frame, userData.get()); + + m_pageLoadState.commitChanges(); + if (m_navigationClient) { + if (frame->isMainFrame()) + m_navigationClient->didStartProvisionalNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didStartProvisionalLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, const String& url, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& url, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(url); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + + auto transaction = m_pageLoadState.transaction(); + + if (frame->isMainFrame()) + m_pageLoadState.didReceiveServerRedirectForProvisionalLoad(transaction, url); + frame->didReceiveServerRedirectForProvisionalLoad(url); - m_loaderClient.didReceiveServerRedirectForProvisionalLoadForFrame(this, frame, userData.get()); + m_pageLoadState.commitChanges(); + if (m_navigationClient) { + if (frame->isMainFrame()) + m_navigationClient->didReceiveServerRedirectForProvisionalNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didReceiveServerRedirectForProvisionalLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didFailProvisionalLoadForFrame(uint64_t frameID, const ResourceError& error, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didChangeProvisionalURLForFrame(uint64_t frameID, uint64_t, const String& url) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); + + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + MESSAGE_CHECK(frame->frameLoadState().state() == FrameLoadState::State::Provisional); + MESSAGE_CHECK_URL(url); + + auto transaction = m_pageLoadState.transaction(); + + // Internally, we handle this the same way we handle a server redirect. There are no client callbacks + // for this, but if this is the main frame, clients may observe a change to the page's URL. + if (frame->isMainFrame()) + m_pageLoadState.didReceiveServerRedirectForProvisionalLoad(transaction, url); + + frame->didReceiveServerRedirectForProvisionalLoad(url); +} + +void WebPageProxy::didFailProvisionalLoadForFrame(uint64_t frameID, const SecurityOriginData& frameSecurityOrigin, uint64_t navigationID, const String& provisionalURL, const ResourceError& error, const UserData& userData) +{ + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = navigationState().takeNavigation(navigationID); + + auto transaction = m_pageLoadState.transaction(); + + if (frame->isMainFrame()) + m_pageLoadState.didFailProvisionalLoad(transaction); + frame->didFailProvisionalLoad(); - m_loaderClient.didFailProvisionalLoadWithErrorForFrame(this, frame, error, userData.get()); + m_pageLoadState.commitChanges(); + + ASSERT(!m_failingProvisionalLoadURL); + m_failingProvisionalLoadURL = provisionalURL; + + if (m_navigationClient) { + if (frame->isMainFrame()) + m_navigationClient->didFailProvisionalNavigationWithError(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get()); + else { + // FIXME: Get the main frame's current navigation. + m_navigationClient->didFailProvisionalLoadInSubframeWithError(*this, *frame, frameSecurityOrigin, nullptr, error, m_process->transformHandlesToObjects(userData.object()).get()); + } + } else + m_loaderClient->didFailProvisionalLoadWithErrorForFrame(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get()); + + m_failingProvisionalLoadURL = { }; } void WebPageProxy::clearLoadDependentCallbacks() @@ -2242,221 +3025,307 @@ void WebPageProxy::clearLoadDependentCallbacks() m_loadDependentStringCallbackIDs.clear(); for (size_t i = 0; i < callbackIDsCopy.size(); ++i) { - RefPtr<StringCallback> callback = m_stringCallbacks.take(callbackIDsCopy[i]); + auto callback = m_callbacks.take<StringCallback>(callbackIDsCopy[i]); if (callback) callback->invalidate(); } } -void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, const String& mimeType, uint32_t opaqueFrameLoadType, const PlatformCertificateInfo& certificateInfo, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didCommitLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& mimeType, bool frameHasCustomContentProvider, bool pluginHandlesPageScaleGesture, uint32_t opaqueFrameLoadType, const WebCore::CertificateInfo& certificateInfo, bool containsPluginDocument, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); -#if PLATFORM(MAC) + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + +#if PLATFORM(IOS) + if (frame->isMainFrame()) { + m_hasReceivedLayerTreeTransactionAfterDidCommitLoad = false; + m_firstLayerTreeTransactionIdAfterDidCommitLoad = downcast<RemoteLayerTreeDrawingAreaProxy>(*drawingArea()).nextLayerTreeTransactionID(); + } +#endif + + auto transaction = m_pageLoadState.transaction(); + bool markPageInsecure = m_treatsSHA1CertificatesAsInsecure && certificateInfo.containsNonRootSHA1SignedCertificate(); + Ref<WebCertificateInfo> webCertificateInfo = WebCertificateInfo::create(certificateInfo); + if (frame->isMainFrame()) { + m_pageLoadState.didCommitLoad(transaction, webCertificateInfo, markPageInsecure); + m_suppressNavigationSnapshotting = false; + } else if (markPageInsecure) + m_pageLoadState.didDisplayOrRunInsecureContent(transaction); + +#if USE(APPKIT) // FIXME (bug 59111): didCommitLoadForFrame comes too late when restoring a page from b/f cache, making us disable secure event mode in password fields. // FIXME: A load going on in one frame shouldn't affect text editing in other frames on the page. - m_pageClient->resetSecureInputState(); - dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored); - m_pageClient->dismissDictionaryLookupPanel(); + m_pageClient.resetSecureInputState(); + m_pageClient.dismissContentRelativeChildWindows(); #endif clearLoadDependentCallbacks(); - frame->didCommitLoad(mimeType, certificateInfo); + frame->didCommitLoad(mimeType, webCertificateInfo, containsPluginDocument); + + if (frame->isMainFrame()) { + m_mainFrameHasCustomContentProvider = frameHasCustomContentProvider; + + if (m_mainFrameHasCustomContentProvider) { + // Always assume that the main frame is pinned here, since the custom representation view will handle + // any wheel events and dispatch them to the WKView when necessary. + m_mainFrameIsPinnedToLeftSide = true; + m_mainFrameIsPinnedToRightSide = true; + m_mainFrameIsPinnedToTopSide = true; + m_mainFrameIsPinnedToBottomSide = true; + + m_uiClient->pinnedStateDidChange(*this); + } + m_pageClient.didCommitLoadForMainFrame(mimeType, frameHasCustomContentProvider); + } // Even if WebPage has the default pageScaleFactor (and therefore doesn't reset it), // WebPageProxy's cache of the value can get out of sync (e.g. in the case where a // plugin is handling page scaling itself) so we should reset it to the default // for standard main frame loads. - if (frame->isMainFrame() && static_cast<FrameLoadType>(opaqueFrameLoadType) == FrameLoadTypeStandard) - m_pageScaleFactor = 1; + if (frame->isMainFrame()) { + m_mainFramePluginHandlesPageScaleGesture = pluginHandlesPageScaleGesture; + + if (static_cast<FrameLoadType>(opaqueFrameLoadType) == FrameLoadType::Standard) { + m_pageScaleFactor = 1; + m_pluginScaleFactor = 1; + } + } - m_loaderClient.didCommitLoadForFrame(this, frame, userData.get()); + m_pageLoadState.commitChanges(); + if (m_navigationClient) { + if (frame->isMainFrame()) + m_navigationClient->didCommitNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didCommitLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didFinishDocumentLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didFinishDocumentLoadForFrame(uint64_t frameID, uint64_t navigationID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_loaderClient.didFinishDocumentLoadForFrame(this, frame, userData.get()); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + + if (m_navigationClient) { + if (frame->isMainFrame()) + m_navigationClient->didFinishDocumentLoad(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didFinishDocumentLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didFinishLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didFinishLoadForFrame(uint64_t frameID, uint64_t navigationID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + + auto transaction = m_pageLoadState.transaction(); + + bool isMainFrame = frame->isMainFrame(); + if (isMainFrame) + m_pageLoadState.didFinishLoad(transaction); + frame->didFinishLoad(); - m_loaderClient.didFinishLoadForFrame(this, frame, userData.get()); + m_pageLoadState.commitChanges(); + if (m_navigationClient) { + if (isMainFrame) + m_navigationClient->didFinishNavigation(*this, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didFinishLoadForFrame(*this, *frame, navigation.get(), m_process->transformHandlesToObjects(userData.object()).get()); + + if (isMainFrame) + m_pageClient.didFinishLoadForMainFrame(); + + m_isLoadingAlternateHTMLStringForFailingProvisionalLoad = false; } -void WebPageProxy::didFailLoadForFrame(uint64_t frameID, const ResourceError& error, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didFailLoadForFrame(uint64_t frameID, uint64_t navigationID, const ResourceError& error, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + clearLoadDependentCallbacks(); + auto transaction = m_pageLoadState.transaction(); + + bool isMainFrame = frame->isMainFrame(); + + if (isMainFrame) + m_pageLoadState.didFailLoad(transaction); + frame->didFailLoad(); - m_loaderClient.didFailLoadWithErrorForFrame(this, frame, error, userData.get()); + m_pageLoadState.commitChanges(); + if (m_navigationClient) { + if (frame->isMainFrame()) + m_navigationClient->didFailNavigationWithError(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didFailLoadWithErrorForFrame(*this, *frame, navigation.get(), error, m_process->transformHandlesToObjects(userData.object()).get()); + + if (isMainFrame) + m_pageClient.didFailLoadForMainFrame(); } -void WebPageProxy::didSameDocumentNavigationForFrame(uint64_t frameID, uint32_t opaqueSameDocumentNavigationType, const String& url, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didSameDocumentNavigationForFrame(uint64_t frameID, uint64_t navigationID, uint32_t opaqueSameDocumentNavigationType, const String& url, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(url); - clearPendingAPIRequestURL(); + // FIXME: We should message check that navigationID is not zero here, but it's currently zero for some navigations through the page cache. + RefPtr<API::Navigation> navigation; + if (frame->isMainFrame() && navigationID) + navigation = &navigationState().navigation(navigationID); + + auto transaction = m_pageLoadState.transaction(); + + bool isMainFrame = frame->isMainFrame(); + if (isMainFrame) + m_pageLoadState.didSameDocumentNavigation(transaction, url); + + m_pageLoadState.clearPendingAPIRequestURL(transaction); frame->didSameDocumentNavigation(url); - m_loaderClient.didSameDocumentNavigationForFrame(this, frame, static_cast<SameDocumentNavigationType>(opaqueSameDocumentNavigationType), userData.get()); + m_pageLoadState.commitChanges(); + + SameDocumentNavigationType navigationType = static_cast<SameDocumentNavigationType>(opaqueSameDocumentNavigationType); + if (m_navigationClient) { + if (isMainFrame) + m_navigationClient->didSameDocumentNavigation(*this, navigation.get(), navigationType, m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_loaderClient->didSameDocumentNavigationForFrame(*this, *frame, navigation.get(), navigationType, m_process->transformHandlesToObjects(userData.object()).get()); + + if (isMainFrame) + m_pageClient.didSameDocumentNavigationForMainFrame(navigationType); } -void WebPageProxy::didReceiveTitleForFrame(uint64_t frameID, const String& title, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didReceiveTitleForFrame(uint64_t frameID, const String& title, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); + auto transaction = m_pageLoadState.transaction(); + + if (frame->isMainFrame()) + m_pageLoadState.setTitle(transaction, title); + frame->didChangeTitle(title); - m_loaderClient.didReceiveTitleForFrame(this, title, frame, userData.get()); + m_pageLoadState.commitChanges(); + m_loaderClient->didReceiveTitleForFrame(*this, title, *frame, m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didFirstLayoutForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didFirstLayoutForFrame(uint64_t frameID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_loaderClient.didFirstLayoutForFrame(this, frame, userData.get()); + m_loaderClient->didFirstLayoutForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_loaderClient.didFirstVisuallyNonEmptyLayoutForFrame(this, frame, userData.get()); -} - -void WebPageProxy::didNewFirstVisuallyNonEmptyLayout(CoreIPC::MessageDecoder& decoder) -{ - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + m_loaderClient->didFirstVisuallyNonEmptyLayoutForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get()); - m_loaderClient.didNewFirstVisuallyNonEmptyLayout(this, userData.get()); + if (frame->isMainFrame()) + m_pageClient.didFirstVisuallyNonEmptyLayoutForMainFrame(); } -void WebPageProxy::didLayout(uint32_t layoutMilestones, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didLayoutForCustomContentProvider() { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; - - m_loaderClient.didLayout(this, static_cast<LayoutMilestones>(layoutMilestones), userData.get()); + didLayout(DidFirstLayout | DidFirstVisuallyNonEmptyLayout | DidHitRelevantRepaintedObjectsAreaThreshold); } -void WebPageProxy::didRemoveFrameFromHierarchy(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didLayout(uint32_t layoutMilestones) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); - WebFrameProxy* frame = m_process->webFrame(frameID); - MESSAGE_CHECK(frame); - - m_loaderClient.didRemoveFrameFromHierarchy(this, frame, userData.get()); + if (m_navigationClient) + m_navigationClient->renderingProgressDidChange(*this, static_cast<LayoutMilestones>(layoutMilestones)); + else + m_loaderClient->didLayout(*this, static_cast<LayoutMilestones>(layoutMilestones)); } -void WebPageProxy::didDisplayInsecureContentForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didDisplayInsecureContentForFrame(uint64_t frameID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_loaderClient.didDisplayInsecureContentForFrame(this, frame, userData.get()); + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.didDisplayOrRunInsecureContent(transaction); + + m_pageLoadState.commitChanges(); + m_loaderClient->didDisplayInsecureContentForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didRunInsecureContentForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didRunInsecureContentForFrame(uint64_t frameID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_loaderClient.didRunInsecureContentForFrame(this, frame, userData.get()); + auto transaction = m_pageLoadState.transaction(); + m_pageLoadState.didDisplayOrRunInsecureContent(transaction); + + m_pageLoadState.commitChanges(); + m_loaderClient->didRunInsecureContentForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::didDetectXSSForFrame(uint64_t frameID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::didDetectXSSForFrame(uint64_t frameID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_loaderClient.didDetectXSSForFrame(this, frame, userData.get()); + m_loaderClient->didDetectXSSForFrame(*this, *frame, m_process->transformHandlesToObjects(userData.object()).get()); } void WebPageProxy::frameDidBecomeFrameSet(uint64_t frameID, bool value) { + PageClientProtector protector(m_pageClient); + WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); @@ -2465,35 +3334,63 @@ void WebPageProxy::frameDidBecomeFrameSet(uint64_t frameID, bool value) m_frameSetLargestFrame = value ? m_mainFrame : 0; } -// PolicyClient -void WebPageProxy::decidePolicyForNavigationAction(uint64_t frameID, uint32_t opaqueNavigationType, uint32_t opaqueModifiers, int32_t opaqueMouseButton, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID) +void WebPageProxy::decidePolicyForNavigationAction(uint64_t frameID, const SecurityOriginData& frameSecurityOrigin, uint64_t navigationID, const NavigationActionData& navigationActionData, uint64_t originatingFrameID, const SecurityOriginData& originatingFrameSecurityOrigin, const WebCore::ResourceRequest& originalRequest, const ResourceRequest& request, uint64_t listenerID, const UserData& userData, bool& receivedPolicyAction, uint64_t& newNavigationID, uint64_t& policyAction, DownloadID& downloadID) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); + + auto transaction = m_pageLoadState.transaction(); - if (request.url() != pendingAPIRequestURL()) - clearPendingAPIRequestURL(); + if (request.url() != m_pageLoadState.pendingAPIRequestURL()) + m_pageLoadState.clearPendingAPIRequestURL(transaction); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(request.url()); + MESSAGE_CHECK_URL(originalRequest.url()); - NavigationType navigationType = static_cast<NavigationType>(opaqueNavigationType); - WebEvent::Modifiers modifiers = static_cast<WebEvent::Modifiers>(opaqueModifiers); - WebMouseEvent::Button mouseButton = static_cast<WebMouseEvent::Button>(opaqueMouseButton); + WebFrameProxy* originatingFrame = m_process->webFrame(originatingFrameID); - RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); + Ref<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); + if (!navigationID && frame->isMainFrame()) { + auto navigation = m_navigationState->createLoadRequestNavigation(request); + newNavigationID = navigation->navigationID(); + listener->setNavigation(WTFMove(navigation)); + } + +#if ENABLE(CONTENT_FILTERING) + if (frame->didHandleContentFilterUnblockNavigation(request)) { + receivedPolicyAction = true; + policyAction = PolicyIgnore; + return; + } +#endif ASSERT(!m_inDecidePolicyForNavigationAction); m_inDecidePolicyForNavigationAction = true; m_syncNavigationActionPolicyActionIsValid = false; - - if (!m_policyClient.decidePolicyForNavigationAction(this, frame, navigationType, modifiers, mouseButton, request, listener.get(), userData.get())) - listener->use(); + if (m_navigationClient) { + RefPtr<API::FrameInfo> destinationFrameInfo; + RefPtr<API::FrameInfo> sourceFrameInfo; + + if (frame) + destinationFrameInfo = API::FrameInfo::create(*frame, frameSecurityOrigin.securityOrigin()); + + if (originatingFrame == frame) + sourceFrameInfo = destinationFrameInfo; + else if (originatingFrame) + sourceFrameInfo = API::FrameInfo::create(*originatingFrame, originatingFrameSecurityOrigin.securityOrigin()); + + bool shouldOpenAppLinks = !m_shouldSuppressAppLinksInNextNavigationPolicyDecision && (!destinationFrameInfo || destinationFrameInfo->isMainFrame()) && !hostsAreEqual(URL(ParsedURLString, m_mainFrame->url()), request.url()); + + auto navigationAction = API::NavigationAction::create(navigationActionData, sourceFrameInfo.get(), destinationFrameInfo.get(), request, originalRequest.url(), shouldOpenAppLinks); + + m_navigationClient->decidePolicyForNavigationAction(*this, navigationAction.get(), WTFMove(listener), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_policyClient->decidePolicyForNavigationAction(*this, frame, navigationActionData, originatingFrame, originalRequest, request, WTFMove(listener), m_process->transformHandlesToObjects(userData.object()).get()); + + m_shouldSuppressAppLinksInNextNavigationPolicyDecision = false; m_inDecidePolicyForNavigationAction = false; // Check if we received a policy decision already. If we did, we can just pass it back. @@ -2504,53 +3401,59 @@ void WebPageProxy::decidePolicyForNavigationAction(uint64_t frameID, uint32_t op } } -void WebPageProxy::decidePolicyForNewWindowAction(uint64_t frameID, uint32_t opaqueNavigationType, uint32_t opaqueModifiers, int32_t opaqueMouseButton, const ResourceRequest& request, const String& frameName, uint64_t listenerID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::decidePolicyForNewWindowAction(uint64_t frameID, const SecurityOriginData& frameSecurityOrigin, const NavigationActionData& navigationActionData, const ResourceRequest& request, const String& frameName, uint64_t listenerID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(request.url()); - NavigationType navigationType = static_cast<NavigationType>(opaqueNavigationType); - WebEvent::Modifiers modifiers = static_cast<WebEvent::Modifiers>(opaqueModifiers); - WebMouseEvent::Button mouseButton = static_cast<WebMouseEvent::Button>(opaqueMouseButton); + Ref<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); + + if (m_navigationClient) { + RefPtr<API::FrameInfo> sourceFrameInfo; + if (frame) + sourceFrameInfo = API::FrameInfo::create(*frame, frameSecurityOrigin.securityOrigin()); + + bool shouldOpenAppLinks = !hostsAreEqual(URL(ParsedURLString, m_mainFrame->url()), request.url()); + auto navigationAction = API::NavigationAction::create(navigationActionData, sourceFrameInfo.get(), nullptr, request, request.url(), shouldOpenAppLinks); + + m_navigationClient->decidePolicyForNavigationAction(*this, navigationAction.get(), WTFMove(listener), m_process->transformHandlesToObjects(userData.object()).get()); - RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); - if (!m_policyClient.decidePolicyForNewWindowAction(this, frame, navigationType, modifiers, mouseButton, request, frameName, listener.get(), userData.get())) - listener->use(); + } else + m_policyClient->decidePolicyForNewWindowAction(*this, *frame, navigationActionData, request, frameName, WTFMove(listener), m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::decidePolicyForResponse(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::decidePolicyForResponse(uint64_t frameID, const SecurityOriginData& frameSecurityOrigin, const ResourceResponse& response, const ResourceRequest& request, bool canShowMIMEType, uint64_t listenerID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + PageClientProtector protector(m_pageClient); WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); MESSAGE_CHECK_URL(request.url()); MESSAGE_CHECK_URL(response.url()); - RefPtr<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); + Ref<WebFramePolicyListenerProxy> listener = frame->setUpPolicyListenerProxy(listenerID); - if (!m_policyClient.decidePolicyForResponse(this, frame, response, request, listener.get(), userData.get())) - listener->use(); + if (m_navigationClient) { + auto navigationResponse = API::NavigationResponse::create(API::FrameInfo::create(*frame, frameSecurityOrigin.securityOrigin()).get(), request, response, canShowMIMEType); + m_navigationClient->decidePolicyForNavigationResponse(*this, navigationResponse.get(), WTFMove(listener), m_process->transformHandlesToObjects(userData.object()).get()); + } else + m_policyClient->decidePolicyForResponse(*this, *frame, response, request, canShowMIMEType, WTFMove(listener), m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::decidePolicyForResponseSync(uint64_t frameID, const ResourceResponse& response, const ResourceRequest& request, uint64_t listenerID, CoreIPC::MessageDecoder& decoder, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID) +void WebPageProxy::decidePolicyForResponseSync(uint64_t frameID, const SecurityOriginData& frameSecurityOrigin, const ResourceResponse& response, const ResourceRequest& request, bool canShowMIMEType, uint64_t listenerID, const UserData& userData, bool& receivedPolicyAction, uint64_t& policyAction, DownloadID& downloadID) { + PageClientProtector protector(m_pageClient); + ASSERT(!m_inDecidePolicyForResponseSync); m_inDecidePolicyForResponseSync = true; m_decidePolicyForResponseRequest = &request; m_syncMimeTypePolicyActionIsValid = false; - decidePolicyForResponse(frameID, response, request, listenerID, decoder); + decidePolicyForResponse(frameID, frameSecurityOrigin, response, request, canShowMIMEType, listenerID, userData); m_inDecidePolicyForResponseSync = false; m_decidePolicyForResponseRequest = 0; @@ -2563,44 +3466,118 @@ void WebPageProxy::decidePolicyForResponseSync(uint64_t frameID, const ResourceR } } -void WebPageProxy::unableToImplementPolicy(uint64_t frameID, const ResourceError& error, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::unableToImplementPolicy(uint64_t frameID, const ResourceError& error, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; - + PageClientProtector protector(m_pageClient); + WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_policyClient.unableToImplementPolicy(this, frame, error, userData.get()); + m_policyClient->unableToImplementPolicy(*this, *frame, error, m_process->transformHandlesToObjects(userData.object()).get()); } // FormClient -void WebPageProxy::willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String> >& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String>>& textFieldValues, uint64_t listenerID, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; - WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); WebFrameProxy* sourceFrame = m_process->webFrame(sourceFrameID); MESSAGE_CHECK(sourceFrame); - RefPtr<WebFormSubmissionListenerProxy> listener = frame->setUpFormSubmissionListenerProxy(listenerID); - if (!m_formClient.willSubmitForm(this, frame, sourceFrame, textFieldValues, userData.get(), listener.get())) - listener->continueSubmission(); + Ref<WebFormSubmissionListenerProxy> listener = frame->setUpFormSubmissionListenerProxy(listenerID); + m_formClient->willSubmitForm(*this, *frame, *sourceFrame, textFieldValues, m_process->transformHandlesToObjects(userData.object()).get(), listener.get()); +} + +void WebPageProxy::didNavigateWithNavigationData(const WebNavigationDataStore& store, uint64_t frameID) +{ + PageClientProtector protector(m_pageClient); + + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + MESSAGE_CHECK(frame->page() == this); + + if (m_historyClient) { + if (frame->isMainFrame()) + m_historyClient->didNavigateWithNavigationData(*this, store); + } else + m_loaderClient->didNavigateWithNavigationData(*this, store, *frame); + process().processPool().historyClient().didNavigateWithNavigationData(process().processPool(), *this, store, *frame); +} + +void WebPageProxy::didPerformClientRedirect(const String& sourceURLString, const String& destinationURLString, uint64_t frameID) +{ + PageClientProtector protector(m_pageClient); + + if (sourceURLString.isEmpty() || destinationURLString.isEmpty()) + return; + + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + MESSAGE_CHECK(frame->page() == this); + + MESSAGE_CHECK_URL(sourceURLString); + MESSAGE_CHECK_URL(destinationURLString); + + if (m_historyClient) { + if (frame->isMainFrame()) + m_historyClient->didPerformClientRedirect(*this, sourceURLString, destinationURLString); + } else + m_loaderClient->didPerformClientRedirect(*this, sourceURLString, destinationURLString, *frame); + process().processPool().historyClient().didPerformClientRedirect(process().processPool(), *this, sourceURLString, destinationURLString, *frame); +} + +void WebPageProxy::didPerformServerRedirect(const String& sourceURLString, const String& destinationURLString, uint64_t frameID) +{ + PageClientProtector protector(m_pageClient); + + if (sourceURLString.isEmpty() || destinationURLString.isEmpty()) + return; + + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + MESSAGE_CHECK(frame->page() == this); + + MESSAGE_CHECK_URL(sourceURLString); + MESSAGE_CHECK_URL(destinationURLString); + + if (m_historyClient) { + if (frame->isMainFrame()) + m_historyClient->didPerformServerRedirect(*this, sourceURLString, destinationURLString); + } else + m_loaderClient->didPerformServerRedirect(*this, sourceURLString, destinationURLString, *frame); + process().processPool().historyClient().didPerformServerRedirect(process().processPool(), *this, sourceURLString, destinationURLString, *frame); +} + +void WebPageProxy::didUpdateHistoryTitle(const String& title, const String& url, uint64_t frameID) +{ + PageClientProtector protector(m_pageClient); + + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + MESSAGE_CHECK(frame->page() == this); + + MESSAGE_CHECK_URL(url); + + if (m_historyClient) { + if (frame->isMainFrame()) + m_historyClient->didUpdateHistoryTitle(*this, title, url); + } else + m_loaderClient->didUpdateHistoryTitle(*this, title, url, *frame); + process().processPool().historyClient().didUpdateHistoryTitle(process().processPool(), *this, title, url, *frame); } // UIClient -void WebPageProxy::createNewPage(const ResourceRequest& request, const WindowFeatures& windowFeatures, uint32_t opaqueModifiers, int32_t opaqueMouseButton, uint64_t& newPageID, WebPageCreationParameters& newPageParameters) +void WebPageProxy::createNewPage(uint64_t frameID, const SecurityOriginData& securityOriginData, const ResourceRequest& request, const WindowFeatures& windowFeatures, const NavigationActionData& navigationActionData, uint64_t& newPageID, WebPageCreationParameters& newPageParameters) { - RefPtr<WebPageProxy> newPage = m_uiClient.createNewPage(this, request, windowFeatures, static_cast<WebEvent::Modifiers>(opaqueModifiers), static_cast<WebMouseEvent::Button>(opaqueMouseButton)); + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + + auto mainFrameURL = m_mainFrame->url(); + + RefPtr<WebPageProxy> newPage = m_uiClient->createNewPage(this, frame, securityOriginData, request, windowFeatures, navigationActionData); if (!newPage) { newPageID = 0; return; @@ -2608,95 +3585,106 @@ void WebPageProxy::createNewPage(const ResourceRequest& request, const WindowFea newPageID = newPage->pageID(); newPageParameters = newPage->creationParameters(); - process()->context()->storageManager().cloneSessionStorageNamespace(m_pageID, newPage->pageID()); + + WebsiteDataStore::cloneSessionData(*this, *newPage); + newPage->m_shouldSuppressAppLinksInNextNavigationPolicyDecision = hostsAreEqual(URL(ParsedURLString, mainFrameURL), request.url()); } void WebPageProxy::showPage() { - m_uiClient.showPage(this); + m_uiClient->showPage(this); +} + +void WebPageProxy::fullscreenMayReturnToInline() +{ + m_uiClient->fullscreenMayReturnToInline(this); +} + +void WebPageProxy::didEnterFullscreen() +{ + m_uiClient->didEnterFullscreen(this); +} + +void WebPageProxy::didExitFullscreen() +{ + m_uiClient->didExitFullscreen(this); } void WebPageProxy::closePage(bool stopResponsivenessTimer) { if (stopResponsivenessTimer) - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); - m_pageClient->clearAllEditCommands(); - m_uiClient.close(this); + m_pageClient.clearAllEditCommands(); + m_uiClient->close(this); } -void WebPageProxy::runJavaScriptAlert(uint64_t frameID, const String& message) +void WebPageProxy::runJavaScriptAlert(uint64_t frameID, const SecurityOriginData& securityOrigin, const String& message, RefPtr<Messages::WebPageProxy::RunJavaScriptAlert::DelayedReply> reply) { WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); // Since runJavaScriptAlert() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); - m_uiClient.runJavaScriptAlert(this, message, frame); + m_uiClient->runJavaScriptAlert(this, message, frame, securityOrigin, [reply]{ reply->send(); }); } -void WebPageProxy::runJavaScriptConfirm(uint64_t frameID, const String& message, bool& result) +void WebPageProxy::runJavaScriptConfirm(uint64_t frameID, const SecurityOriginData& securityOrigin, const String& message, RefPtr<Messages::WebPageProxy::RunJavaScriptConfirm::DelayedReply> reply) { WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); // Since runJavaScriptConfirm() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); - result = m_uiClient.runJavaScriptConfirm(this, message, frame); + m_uiClient->runJavaScriptConfirm(this, message, frame, securityOrigin, [reply](bool result) { reply->send(result); }); } -void WebPageProxy::runJavaScriptPrompt(uint64_t frameID, const String& message, const String& defaultValue, String& result) +void WebPageProxy::runJavaScriptPrompt(uint64_t frameID, const SecurityOriginData& securityOrigin, const String& message, const String& defaultValue, RefPtr<Messages::WebPageProxy::RunJavaScriptPrompt::DelayedReply> reply) { WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); // Since runJavaScriptPrompt() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); - result = m_uiClient.runJavaScriptPrompt(this, message, defaultValue, frame); -} - -void WebPageProxy::shouldInterruptJavaScript(bool& result) -{ - // Since shouldInterruptJavaScript() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); - - result = m_uiClient.shouldInterruptJavaScript(this); + m_uiClient->runJavaScriptPrompt(this, message, defaultValue, frame, securityOrigin, [reply](const String& result) { reply->send(result); }); } void WebPageProxy::setStatusText(const String& text) { - m_uiClient.setStatusText(this, text); + m_uiClient->setStatusText(this, text); } -void WebPageProxy::mouseDidMoveOverElement(const WebHitTestResult::Data& hitTestResultData, uint32_t opaqueModifiers, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::mouseDidMoveOverElement(const WebHitTestResultData& hitTestResultData, uint32_t opaqueModifiers, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + m_lastMouseMoveHitTestResult = API::HitTestResult::create(hitTestResultData); WebEvent::Modifiers modifiers = static_cast<WebEvent::Modifiers>(opaqueModifiers); - m_uiClient.mouseDidMoveOverElement(this, hitTestResultData, modifiers, userData.get()); + m_uiClient->mouseDidMoveOverElement(this, hitTestResultData, modifiers, m_process->transformHandlesToObjects(userData.object()).get()); } -void WebPageProxy::connectionWillOpen(CoreIPC::Connection* connection) +void WebPageProxy::connectionWillOpen(IPC::Connection& connection) { - ASSERT(connection == m_process->connection()); + ASSERT(&connection == m_process->connection()); - m_process->context()->storageManager().setAllowedSessionStorageNamespaceConnection(m_pageID, connection); + m_webProcessLifetimeTracker.connectionWillOpen(connection); } -void WebPageProxy::connectionWillClose(CoreIPC::Connection* connection) +void WebPageProxy::webProcessWillShutDown() { - ASSERT_UNUSED(connection, connection == m_process->connection()); + m_webProcessLifetimeTracker.webProcessWillShutDown(); +} - m_process->context()->storageManager().setAllowedSessionStorageNamespaceConnection(m_pageID, 0); +void WebPageProxy::processDidFinishLaunching() +{ + ASSERT(m_process->state() == WebProcessProxy::State::Running); + finishInitializingWebPageAfterProcessLaunch(); } +#if ENABLE(NETSCAPE_PLUGIN_API) void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& pluginURLString, const String& pluginspageAttributeURLString, const String& frameURLString, const String& pageURLString) { MESSAGE_CHECK_URL(pluginURLString); @@ -2704,12 +3692,10 @@ void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailab MESSAGE_CHECK_URL(frameURLString); MESSAGE_CHECK_URL(pageURLString); - RefPtr<ImmutableDictionary> pluginInformation; -#if ENABLE(NETSCAPE_PLUGIN_API) + RefPtr<API::Dictionary> pluginInformation; String newMimeType = mimeType; - PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), pluginURLString)); + PluginModuleInfo plugin = m_process->processPool().pluginInfoStore().findPlugin(newMimeType, URL(URL(), pluginURLString)); pluginInformation = createPluginInformationDictionary(plugin, frameURLString, mimeType, pageURLString, pluginspageAttributeURLString, pluginURLString); -#endif WKPluginUnavailabilityReason pluginUnavailabilityReason = kWKPluginUnavailabilityReasonPluginMissing; switch (static_cast<RenderEmbeddedObject::PluginUnavailabilityReason>(opaquePluginUnavailabilityReason)) { @@ -2726,116 +3712,145 @@ void WebPageProxy::unavailablePluginButtonClicked(uint32_t opaquePluginUnavailab ASSERT_NOT_REACHED(); } - m_uiClient.unavailablePluginButtonClicked(this, pluginUnavailabilityReason, pluginInformation.get()); + m_uiClient->unavailablePluginButtonClicked(this, pluginUnavailabilityReason, pluginInformation.get()); +} +#endif // ENABLE(NETSCAPE_PLUGIN_API) + +#if ENABLE(WEBGL) +void WebPageProxy::webGLPolicyForURL(const String& url, uint32_t& loadPolicy) +{ + loadPolicy = static_cast<uint32_t>(m_loaderClient->webGLLoadPolicy(*this, url)); +} + +void WebPageProxy::resolveWebGLPolicyForURL(const String& url, uint32_t& loadPolicy) +{ + loadPolicy = static_cast<uint32_t>(m_loaderClient->resolveWebGLLoadPolicy(*this, url)); } +#endif // ENABLE(WEBGL) void WebPageProxy::setToolbarsAreVisible(bool toolbarsAreVisible) { - m_uiClient.setToolbarsAreVisible(this, toolbarsAreVisible); + m_uiClient->setToolbarsAreVisible(this, toolbarsAreVisible); } void WebPageProxy::getToolbarsAreVisible(bool& toolbarsAreVisible) { - toolbarsAreVisible = m_uiClient.toolbarsAreVisible(this); + toolbarsAreVisible = m_uiClient->toolbarsAreVisible(this); } void WebPageProxy::setMenuBarIsVisible(bool menuBarIsVisible) { - m_uiClient.setMenuBarIsVisible(this, menuBarIsVisible); + m_uiClient->setMenuBarIsVisible(this, menuBarIsVisible); } void WebPageProxy::getMenuBarIsVisible(bool& menuBarIsVisible) { - menuBarIsVisible = m_uiClient.menuBarIsVisible(this); + menuBarIsVisible = m_uiClient->menuBarIsVisible(this); } void WebPageProxy::setStatusBarIsVisible(bool statusBarIsVisible) { - m_uiClient.setStatusBarIsVisible(this, statusBarIsVisible); + m_uiClient->setStatusBarIsVisible(this, statusBarIsVisible); } void WebPageProxy::getStatusBarIsVisible(bool& statusBarIsVisible) { - statusBarIsVisible = m_uiClient.statusBarIsVisible(this); + statusBarIsVisible = m_uiClient->statusBarIsVisible(this); } void WebPageProxy::setIsResizable(bool isResizable) { - m_uiClient.setIsResizable(this, isResizable); + m_uiClient->setIsResizable(this, isResizable); } void WebPageProxy::getIsResizable(bool& isResizable) { - isResizable = m_uiClient.isResizable(this); + isResizable = m_uiClient->isResizable(this); } void WebPageProxy::setWindowFrame(const FloatRect& newWindowFrame) { - m_uiClient.setWindowFrame(this, m_pageClient->convertToDeviceSpace(newWindowFrame)); + m_uiClient->setWindowFrame(this, m_pageClient.convertToDeviceSpace(newWindowFrame)); } void WebPageProxy::getWindowFrame(FloatRect& newWindowFrame) { - newWindowFrame = m_pageClient->convertToUserSpace(m_uiClient.windowFrame(this)); + newWindowFrame = m_pageClient.convertToUserSpace(m_uiClient->windowFrame(this)); } -void WebPageProxy::screenToWindow(const IntPoint& screenPoint, IntPoint& windowPoint) +void WebPageProxy::screenToRootView(const IntPoint& screenPoint, IntPoint& windowPoint) { - windowPoint = m_pageClient->screenToWindow(screenPoint); + windowPoint = m_pageClient.screenToRootView(screenPoint); } -void WebPageProxy::windowToScreen(const IntRect& viewRect, IntRect& result) +void WebPageProxy::rootViewToScreen(const IntRect& viewRect, IntRect& result) { - result = m_pageClient->windowToScreen(viewRect); + result = m_pageClient.rootViewToScreen(viewRect); } -void WebPageProxy::runBeforeUnloadConfirmPanel(const String& message, uint64_t frameID, bool& shouldClose) +#if PLATFORM(IOS) +void WebPageProxy::accessibilityScreenToRootView(const IntPoint& screenPoint, IntPoint& windowPoint) +{ + windowPoint = m_pageClient.accessibilityScreenToRootView(screenPoint); +} + +void WebPageProxy::rootViewToAccessibilityScreen(const IntRect& viewRect, IntRect& result) +{ + result = m_pageClient.rootViewToAccessibilityScreen(viewRect); +} +#endif + +void WebPageProxy::runBeforeUnloadConfirmPanel(const String& message, uint64_t frameID, RefPtr<Messages::WebPageProxy::RunBeforeUnloadConfirmPanel::DelayedReply> reply) { WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); // Since runBeforeUnloadConfirmPanel() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); - shouldClose = m_uiClient.runBeforeUnloadConfirmPanel(this, message, frame); + m_uiClient->runBeforeUnloadConfirmPanel(this, message, frame, [reply](bool result) { reply->send(result); }); } -#if USE(TILED_BACKING_STORE) +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) void WebPageProxy::pageDidRequestScroll(const IntPoint& point) { - m_pageClient->pageDidRequestScroll(point); + m_pageClient.pageDidRequestScroll(point); } void WebPageProxy::pageTransitionViewportReady() { - m_pageClient->pageTransitionViewportReady(); + m_pageClient.pageTransitionViewportReady(); } void WebPageProxy::didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect) { - m_pageClient->didRenderFrame(contentsSize, coveredRect); + m_pageClient.didRenderFrame(contentsSize, coveredRect); } +void WebPageProxy::commitPageTransitionViewport() +{ + if (!isValid()) + return; + + process().send(Messages::WebPage::CommitPageTransitionViewport(), m_pageID); +} #endif void WebPageProxy::didChangeViewportProperties(const ViewportAttributes& attr) { - m_pageClient->didChangeViewportProperties(attr); + m_pageClient.didChangeViewportProperties(attr); } void WebPageProxy::pageDidScroll() { - m_uiClient.pageDidScroll(this); -#if PLATFORM(MAC) - dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored); -#endif + m_uiClient->pageDidScroll(this); } void WebPageProxy::runOpenPanel(uint64_t frameID, const FileChooserSettings& settings) { if (m_openPanelResultListener) { m_openPanelResultListener->invalidate(); - m_openPanelResultListener = 0; + m_openPanelResultListener = nullptr; } WebFrameProxy* frame = m_process->webFrame(frameID); @@ -2845,10 +3860,12 @@ void WebPageProxy::runOpenPanel(uint64_t frameID, const FileChooserSettings& set m_openPanelResultListener = WebOpenPanelResultListenerProxy::create(this); // Since runOpenPanel() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); - if (!m_uiClient.runOpenPanel(this, frame, parameters.get(), m_openPanelResultListener.get())) - didCancelForOpenPanel(); + if (!m_uiClient->runOpenPanel(this, frame, parameters.get(), m_openPanelResultListener.get())) { + if (!m_pageClient.handleRunOpenPanel(this, frame, parameters.get(), m_openPanelResultListener.get())) + didCancelForOpenPanel(); + } } void WebPageProxy::printFrame(uint64_t frameID) @@ -2859,7 +3876,7 @@ void WebPageProxy::printFrame(uint64_t frameID) WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); - m_uiClient.printFrame(this, frame); + m_uiClient->printFrame(this, frame); endPrinting(); // Send a message synchronously while m_isPerformingDOMPrintOperation is still true. m_isPerformingDOMPrintOperation = false; @@ -2883,73 +3900,85 @@ void WebPageProxy::setMediaVolume(float volume) m_process->send(Messages::WebPage::SetMediaVolume(volume), m_pageID); } -void WebPageProxy::setMayStartMediaWhenInWindow(bool mayStartMedia) +void WebPageProxy::setMuted(bool muted) { - if (mayStartMedia == m_mayStartMediaWhenInWindow) + if (m_muted == muted) return; - m_mayStartMediaWhenInWindow = mayStartMedia; + m_muted = muted; if (!isValid()) return; - process()->send(Messages::WebPage::SetMayStartMediaWhenInWindow(mayStartMedia), m_pageID); + m_process->send(Messages::WebPage::SetMuted(muted), m_pageID); } -#if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) -void WebPageProxy::handleDownloadRequest(DownloadProxy* download) +#if ENABLE(MEDIA_SESSION) +void WebPageProxy::handleMediaEvent(MediaEventType eventType) { - m_pageClient->handleDownloadRequest(download); + if (!isValid()) + return; + + m_process->send(Messages::WebPage::HandleMediaEvent(eventType), m_pageID); } -#endif // PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) -#if PLATFORM(QT) || PLATFORM(EFL) -void WebPageProxy::didChangeContentsSize(const IntSize& size) +void WebPageProxy::setVolumeOfMediaElement(double volume, uint64_t elementID) { - m_pageClient->didChangeContentsSize(size); -} -#endif + if (!isValid()) + return; -#if ENABLE(TOUCH_EVENTS) -void WebPageProxy::needTouchEvents(bool needTouchEvents) -{ - m_needTouchEvents = needTouchEvents; + m_process->send(Messages::WebPage::SetVolumeOfMediaElement(volume, elementID), m_pageID); } #endif -#if ENABLE(INPUT_TYPE_COLOR) -void WebPageProxy::showColorChooser(const WebCore::Color& initialColor, const IntRect& elementRect) +void WebPageProxy::setMayStartMediaWhenInWindow(bool mayStartMedia) { - ASSERT(!m_colorPicker); - - if (m_colorPickerResultListener) { - m_colorPickerResultListener->invalidate(); - m_colorPickerResultListener = nullptr; - } + if (mayStartMedia == m_mayStartMediaWhenInWindow) + return; - m_colorPickerResultListener = WebColorPickerResultListenerProxy::create(this); - m_colorPicker = WebColorPicker::create(this); + m_mayStartMediaWhenInWindow = mayStartMedia; - if (m_uiClient.showColorPicker(this, initialColor.serialized(), m_colorPickerResultListener.get())) + if (!isValid()) return; - m_colorPicker = m_pageClient->createColorPicker(this, initialColor, elementRect); + process().send(Messages::WebPage::SetMayStartMediaWhenInWindow(mayStartMedia), m_pageID); +} + +void WebPageProxy::handleDownloadRequest(DownloadProxy* download) +{ + m_pageClient.handleDownloadRequest(download); +} + +void WebPageProxy::didChangeContentSize(const IntSize& size) +{ + m_pageClient.didChangeContentSize(size); +} + +#if ENABLE(INPUT_TYPE_COLOR) +void WebPageProxy::showColorPicker(const WebCore::Color& initialColor, const IntRect& elementRect) +{ +#if ENABLE(INPUT_TYPE_COLOR_POPOVER) + // A new popover color well needs to be created (and the previous one destroyed) for + // each activation of a color element. + m_colorPicker = nullptr; +#endif if (!m_colorPicker) - didEndColorChooser(); + m_colorPicker = m_pageClient.createColorPicker(this, initialColor, elementRect); + m_colorPicker->showColorPicker(initialColor); } -void WebPageProxy::setColorChooserColor(const WebCore::Color& color) +void WebPageProxy::setColorPickerColor(const WebCore::Color& color) { ASSERT(m_colorPicker); m_colorPicker->setSelectedColor(color); } -void WebPageProxy::endColorChooser() +void WebPageProxy::endColorPicker() { ASSERT(m_colorPicker); - m_colorPicker->endChooser(); + m_colorPicker->endPicker(); } void WebPageProxy::didChooseColor(const WebCore::Color& color) @@ -2960,34 +3989,23 @@ void WebPageProxy::didChooseColor(const WebCore::Color& color) m_process->send(Messages::WebPage::DidChooseColor(color), m_pageID); } -void WebPageProxy::didEndColorChooser() +void WebPageProxy::didEndColorPicker() { if (!isValid()) return; +#if ENABLE(INPUT_TYPE_COLOR) if (m_colorPicker) { m_colorPicker->invalidate(); m_colorPicker = nullptr; } - - m_process->send(Messages::WebPage::DidEndColorChooser(), m_pageID); - - m_colorPickerResultListener->invalidate(); - m_colorPickerResultListener = nullptr; - - m_uiClient.hideColorPicker(this); -} #endif -void WebPageProxy::didDraw() -{ - m_uiClient.didDraw(this); + m_process->send(Messages::WebPage::DidEndColorPicker(), m_pageID); } +#endif // Inspector - -#if ENABLE(INSPECTOR) - WebInspectorProxy* WebPageProxy::inspector() { if (isClosed() || !isValid()) @@ -2995,14 +4013,35 @@ WebInspectorProxy* WebPageProxy::inspector() return m_inspector.get(); } -#endif - #if ENABLE(FULLSCREEN_API) WebFullScreenManagerProxy* WebPageProxy::fullScreenManager() { return m_fullScreenManager.get(); } #endif + +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) +RefPtr<WebVideoFullscreenManagerProxy> WebPageProxy::videoFullscreenManager() +{ + return m_videoFullscreenManager; +} +#endif + +#if PLATFORM(IOS) +bool WebPageProxy::allowsMediaDocumentInlinePlayback() const +{ + return m_allowsMediaDocumentInlinePlayback; +} + +void WebPageProxy::setAllowsMediaDocumentInlinePlayback(bool allows) +{ + if (m_allowsMediaDocumentInlinePlayback == allows) + return; + m_allowsMediaDocumentInlinePlayback = allows; + + m_process->send(Messages::WebPage::SetAllowsMediaDocumentInlinePlayback(allows), m_pageID); +} +#endif // BackForwardList @@ -3017,7 +4056,7 @@ void WebPageProxy::backForwardGoToItem(uint64_t itemID, SandboxExtension::Handle if (!item) return; - bool createdExtension = maybeInitializeSandboxExtensionHandle(KURL(KURL(), item->url()), sandboxExtensionHandle); + bool createdExtension = maybeInitializeSandboxExtensionHandle(URL(URL(), item->url()), sandboxExtensionHandle); if (createdExtension) m_process->willAcquireUniversalFileReadSandboxExtension(); m_backForwardList->goToItem(item); @@ -3039,35 +4078,12 @@ void WebPageProxy::backForwardForwardListCount(int32_t& count) count = m_backForwardList->forwardListCount(); } -void WebPageProxy::editorStateChanged(const EditorState& editorState) +void WebPageProxy::compositionWasCanceled(const EditorState& editorState) { -#if PLATFORM(MAC) - bool couldChangeSecureInputState = m_editorState.isInPasswordField != editorState.isInPasswordField || m_editorState.selectionIsNone; - bool closedComposition = !editorState.shouldIgnoreCompositionSelectionChange && !editorState.hasComposition && (m_editorState.hasComposition || m_temporarilyClosedComposition); - m_temporarilyClosedComposition = editorState.shouldIgnoreCompositionSelectionChange && (m_temporarilyClosedComposition || m_editorState.hasComposition) && !editorState.hasComposition; -#endif - - m_editorState = editorState; - -#if PLATFORM(MAC) - // Selection being none is a temporary state when editing. Flipping secure input state too quickly was causing trouble (not fully understood). - if (couldChangeSecureInputState && !editorState.selectionIsNone) - m_pageClient->updateSecureInputState(); - - if (editorState.shouldIgnoreCompositionSelectionChange) - return; - - if (closedComposition) - m_pageClient->notifyInputContextAboutDiscardedComposition(); - if (editorState.hasComposition) { - // Abandon the current inline input session if selection changed for any other reason but an input method changing the composition. - // FIXME: This logic should be in WebCore, no need to round-trip to UI process to cancel the composition. - cancelComposition(); - m_pageClient->notifyInputContextAboutDiscardedComposition(); - } -#elif PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) - m_pageClient->updateTextInputState(); +#if PLATFORM(COCOA) + m_pageClient.notifyInputContextAboutDiscardedComposition(); #endif + editorStateChanged(editorState); } // Undo management @@ -3076,65 +4092,96 @@ void WebPageProxy::registerEditCommandForUndo(uint64_t commandID, uint32_t editA { registerEditCommand(WebEditCommandProxy::create(commandID, static_cast<EditAction>(editAction), this), Undo); } + +void WebPageProxy::registerInsertionUndoGrouping() +{ +#if USE(INSERTION_UNDO_GROUPING) + m_pageClient.registerInsertionUndoGrouping(); +#endif +} void WebPageProxy::canUndoRedo(uint32_t action, bool& result) { - result = m_pageClient->canUndoRedo(static_cast<UndoOrRedo>(action)); + result = m_pageClient.canUndoRedo(static_cast<UndoOrRedo>(action)); } void WebPageProxy::executeUndoRedo(uint32_t action, bool& result) { - m_pageClient->executeUndoRedo(static_cast<UndoOrRedo>(action)); + m_pageClient.executeUndoRedo(static_cast<UndoOrRedo>(action)); result = true; } void WebPageProxy::clearAllEditCommands() { - m_pageClient->clearAllEditCommands(); + m_pageClient.clearAllEditCommands(); } void WebPageProxy::didCountStringMatches(const String& string, uint32_t matchCount) { - m_findClient.didCountStringMatches(this, string, matchCount); + m_findClient->didCountStringMatches(this, string, matchCount); } void WebPageProxy::didGetImageForFindMatch(const ShareableBitmap::Handle& contentImageHandle, uint32_t matchIndex) { - m_findMatchesClient.didGetImageForMatchResult(this, WebImage::create(ShareableBitmap::create(contentImageHandle)).get(), matchIndex); + m_findMatchesClient->didGetImageForMatchResult(this, WebImage::create(ShareableBitmap::create(contentImageHandle)).get(), matchIndex); } -void WebPageProxy::setFindIndicator(const FloatRect& selectionRectInWindowCoordinates, const Vector<FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle, bool fadeOut, bool animate) +void WebPageProxy::setTextIndicator(const TextIndicatorData& indicatorData, uint64_t lifetime) { - RefPtr<FindIndicator> findIndicator = FindIndicator::create(selectionRectInWindowCoordinates, textRectsInSelectionRectCoordinates, contentImageScaleFactor, contentImageHandle); - m_pageClient->setFindIndicator(findIndicator.release(), fadeOut, animate); + // FIXME: Make TextIndicatorWindow a platform-independent presentational thing ("TextIndicatorPresentation"?). +#if PLATFORM(COCOA) + m_pageClient.setTextIndicator(TextIndicator::create(indicatorData), static_cast<TextIndicatorWindowLifetime>(lifetime)); +#else + ASSERT_NOT_REACHED(); +#endif } -void WebPageProxy::didFindString(const String& string, uint32_t matchCount) +void WebPageProxy::clearTextIndicator() { - m_findClient.didFindString(this, string, matchCount); +#if PLATFORM(COCOA) + m_pageClient.clearTextIndicator(TextIndicatorWindowDismissalAnimation::FadeOut); +#else + ASSERT_NOT_REACHED(); +#endif } -void WebPageProxy::didFindStringMatches(const String& string, Vector<Vector<WebCore::IntRect> > matchRects, int32_t firstIndexAfterSelection) +void WebPageProxy::setTextIndicatorAnimationProgress(float progress) { - Vector<RefPtr<APIObject> > matches; - matches.reserveInitialCapacity(matchRects.size()); +#if PLATFORM(COCOA) + m_pageClient.setTextIndicatorAnimationProgress(progress); +#else + ASSERT_NOT_REACHED(); +#endif +} - for (size_t i = 0; i < matchRects.size(); ++i) { - const Vector<WebCore::IntRect>& rects = matchRects[i]; - size_t numRects = matchRects[i].size(); - Vector<RefPtr<APIObject> > apiRects; - apiRects.reserveInitialCapacity(numRects); +void WebPageProxy::didFindString(const String& string, const Vector<WebCore::IntRect>& matchRects, uint32_t matchCount, int32_t matchIndex) +{ + m_findClient->didFindString(this, string, matchRects, matchCount, matchIndex); +} - for (size_t i = 0; i < numRects; ++i) - apiRects.uncheckedAppend(WebRect::create(toAPI(rects[i]))); - matches.uncheckedAppend(ImmutableArray::adopt(apiRects)); - } - m_findMatchesClient.didFindStringMatches(this, string, ImmutableArray::adopt(matches).get(), firstIndexAfterSelection); +void WebPageProxy::didFindStringMatches(const String& string, const Vector<Vector<WebCore::IntRect>>& matchRects, int32_t firstIndexAfterSelection) +{ + m_findMatchesClient->didFindStringMatches(this, string, matchRects, firstIndexAfterSelection); } void WebPageProxy::didFailToFindString(const String& string) { - m_findClient.didFailToFindString(this, string); + m_findClient->didFailToFindString(this, string); +} + +bool WebPageProxy::sendMessage(std::unique_ptr<IPC::MessageEncoder> encoder, unsigned messageSendFlags) +{ + return m_process->sendMessage(WTFMove(encoder), messageSendFlags); +} + +IPC::Connection* WebPageProxy::messageSenderConnection() +{ + return m_process->connection(); +} + +uint64_t WebPageProxy::messageSenderDestinationID() +{ + return m_pageID; } void WebPageProxy::valueChangedForPopupMenu(WebPopupMenuProxy*, int32_t newSelectedIndex) @@ -3152,9 +4199,9 @@ NativeWebMouseEvent* WebPageProxy::currentlyProcessedMouseDownEvent() return m_currentlyProcessedMouseDownEvent.get(); } -void WebPageProxy::postMessageToInjectedBundle(const String& messageName, APIObject* messageBody) +void WebPageProxy::postMessageToInjectedBundle(const String& messageName, API::Object* messageBody) { - process()->send(Messages::WebPage::PostInjectedBundleMessage(messageName, WebContextUserMessageEncoder(messageBody)), m_pageID); + process().send(Messages::WebPage::PostInjectedBundleMessage(messageName, UserData(process().transformObjectsToHandles(messageBody).get())), m_pageID); } #if PLATFORM(GTK) @@ -3173,30 +4220,25 @@ void WebPageProxy::showPopupMenu(const IntRect& rect, uint64_t textDirection, co m_activePopupMenu->hidePopupMenu(); #endif m_activePopupMenu->invalidate(); - m_activePopupMenu = 0; + m_activePopupMenu = nullptr; } - m_activePopupMenu = m_pageClient->createPopupMenuProxy(this); + m_activePopupMenu = m_pageClient.createPopupMenuProxy(*this); if (!m_activePopupMenu) return; // Since showPopupMenu() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); #if PLATFORM(EFL) UNUSED_PARAM(data); m_uiPopupMenuClient.showPopupMenu(this, m_activePopupMenu.get(), rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, selectedIndex); #else - RefPtr<WebPopupMenuProxy> protectedActivePopupMenu = m_activePopupMenu; - - protectedActivePopupMenu->showPopupMenu(rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, data, selectedIndex); - // Since Qt and Efl doesn't use a nested mainloop to show the popup and get the answer, we need to keep the client pointer valid. -#if !PLATFORM(QT) - protectedActivePopupMenu->invalidate(); -#endif - protectedActivePopupMenu = 0; + // Showing a popup menu runs a nested runloop, which can handle messages that cause |this| to get closed. + Ref<WebPageProxy> protect(*this); + m_activePopupMenu->showPopupMenu(rect, static_cast<TextDirection>(textDirection), m_pageScaleFactor, items, data, selectedIndex); #endif } @@ -3211,59 +4253,44 @@ void WebPageProxy::hidePopupMenu() m_activePopupMenu->hidePopupMenu(); #endif m_activePopupMenu->invalidate(); - m_activePopupMenu = 0; + m_activePopupMenu = nullptr; } #if ENABLE(CONTEXT_MENUS) -void WebPageProxy::showContextMenu(const IntPoint& menuLocation, const WebHitTestResult::Data& hitTestResultData, const Vector<WebContextMenuItemData>& proposedItems, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::showContextMenu(const ContextMenuContextData& contextMenuContextData, const UserData& userData) { - internalShowContextMenu(menuLocation, hitTestResultData, proposedItems, decoder); + // Showing a context menu runs a nested runloop, which can handle messages that cause |this| to get closed. + Ref<WebPageProxy> protect(*this); + + internalShowContextMenu(contextMenuContextData, userData); // No matter the result of internalShowContextMenu, always notify the WebProcess that the menu is hidden so it starts handling mouse events again. m_process->send(Messages::WebPage::ContextMenuHidden(), m_pageID); } -void WebPageProxy::internalShowContextMenu(const IntPoint& menuLocation, const WebHitTestResult::Data& hitTestResultData, const Vector<WebContextMenuItemData>& proposedItems, CoreIPC::MessageDecoder& decoder) +void WebPageProxy::internalShowContextMenu(const ContextMenuContextData& contextMenuContextData, const UserData& userData) { - RefPtr<APIObject> userData; - WebContextUserMessageDecoder messageDecoder(userData, m_process.get()); - if (!decoder.decode(messageDecoder)) - return; + m_activeContextMenuContextData = contextMenuContextData; - m_activeContextMenuHitTestResultData = hitTestResultData; - - if (!m_contextMenuClient.hideContextMenu(this) && m_activeContextMenu) { - m_activeContextMenu->hideContextMenu(); - m_activeContextMenu = 0; - } - - m_activeContextMenu = m_pageClient->createContextMenuProxy(this); + m_activeContextMenu = m_pageClient.createContextMenuProxy(*this, contextMenuContextData, userData); if (!m_activeContextMenu) return; // Since showContextMenu() can spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); - - // Give the PageContextMenuClient one last swipe at changing the menu. - Vector<WebContextMenuItemData> items; - if (!m_contextMenuClient.getContextMenuFromProposedMenu(this, proposedItems, items, hitTestResultData, userData.get())) { - if (!m_contextMenuClient.showContextMenu(this, menuLocation, proposedItems)) - m_activeContextMenu->showContextMenu(menuLocation, proposedItems); - } else if (!m_contextMenuClient.showContextMenu(this, menuLocation, items)) - m_activeContextMenu->showContextMenu(menuLocation, items); - - m_contextMenuClient.contextMenuDismissed(this); + m_process->responsivenessTimer().stop(); + + m_activeContextMenu->show(); } void WebPageProxy::contextMenuItemSelected(const WebContextMenuItemData& item) { // Application custom items don't need to round-trip through to WebCore in the WebProcess. if (item.action() >= ContextMenuItemBaseApplicationTag) { - m_contextMenuClient.customContextMenuItemSelected(this, item); + m_contextMenuClient->customContextMenuItemSelected(*this, item); return; } -#if PLATFORM(MAC) +#if PLATFORM(COCOA) if (item.action() == ContextMenuItemTagSmartCopyPaste) { setSmartInsertDeleteEnabled(!isSmartInsertDeleteEnabled()); return; @@ -3299,15 +4326,15 @@ void WebPageProxy::contextMenuItemSelected(const WebContextMenuItemData& item) } #endif if (item.action() == ContextMenuItemTagDownloadImageToDisk) { - m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteImageURL)); + m_process->processPool().download(this, URL(URL(), m_activeContextMenuContextData.webHitTestResultData().absoluteImageURL)); return; } if (item.action() == ContextMenuItemTagDownloadLinkToDisk) { - m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteLinkURL)); + m_process->processPool().download(this, URL(URL(), m_activeContextMenuContextData.webHitTestResultData().absoluteLinkURL)); return; } if (item.action() == ContextMenuItemTagDownloadMediaToDisk) { - m_process->context()->download(this, KURL(KURL(), m_activeContextMenuHitTestResultData.absoluteMediaURL)); + m_process->processPool().download(this, URL(URL(), m_activeContextMenuContextData.webHitTestResultData().absoluteMediaURL)); return; } if (item.action() == ContextMenuItemTagCheckSpellingWhileTyping) { @@ -3333,12 +4360,13 @@ void WebPageProxy::contextMenuItemSelected(const WebContextMenuItemData& item) } #endif // ENABLE(CONTEXT_MENUS) -void WebPageProxy::didChooseFilesForOpenPanel(const Vector<String>& fileURLs) +#if PLATFORM(IOS) +void WebPageProxy::didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>& fileURLs, const String& displayString, const API::Data* iconData) { if (!isValid()) return; -#if ENABLE(WEB_PROCESS_SANDBOX) +#if ENABLE(SANDBOX_EXTENSIONS) // FIXME: The sandbox extensions should be sent with the DidChooseFilesForOpenPanel message. This // is gated on a way of passing SandboxExtension::Handles in a Vector. for (size_t i = 0; i < fileURLs.size(); ++i) { @@ -3348,10 +4376,38 @@ void WebPageProxy::didChooseFilesForOpenPanel(const Vector<String>& fileURLs) } #endif + m_process->send(Messages::WebPage::DidChooseFilesForOpenPanelWithDisplayStringAndIcon(fileURLs, displayString, iconData ? iconData->dataReference() : IPC::DataReference()), m_pageID); + + m_openPanelResultListener->invalidate(); + m_openPanelResultListener = nullptr; +} +#endif + +void WebPageProxy::didChooseFilesForOpenPanel(const Vector<String>& fileURLs) +{ + if (!isValid()) + return; + +#if ENABLE(SANDBOX_EXTENSIONS) + // FIXME: The sandbox extensions should be sent with the DidChooseFilesForOpenPanel message. This + // is gated on a way of passing SandboxExtension::Handles in a Vector. + for (size_t i = 0; i < fileURLs.size(); ++i) { + SandboxExtension::Handle sandboxExtensionHandle; + bool createdExtension = SandboxExtension::createHandle(fileURLs[i], SandboxExtension::ReadOnly, sandboxExtensionHandle); + if (!createdExtension) { + // This can legitimately fail if a directory containing the file is deleted after the file was chosen. + // We also have reports of cases where this likely fails for some unknown reason, <rdar://problem/10156710>. + WTFLogAlways("WebPageProxy::didChooseFilesForOpenPanel: could not create a sandbox extension for '%s'\n", fileURLs[i].utf8().data()); + continue; + } + m_process->send(Messages::WebPage::ExtendSandboxForFileFromOpenPanel(sandboxExtensionHandle), m_pageID); + } +#endif + m_process->send(Messages::WebPage::DidChooseFilesForOpenPanel(fileURLs), m_pageID); m_openPanelResultListener->invalidate(); - m_openPanelResultListener = 0; + m_openPanelResultListener = nullptr; } void WebPageProxy::didCancelForOpenPanel() @@ -3362,15 +4418,15 @@ void WebPageProxy::didCancelForOpenPanel() m_process->send(Messages::WebPage::DidCancelForOpenPanel(), m_pageID); m_openPanelResultListener->invalidate(); - m_openPanelResultListener = 0; + m_openPanelResultListener = nullptr; } -void WebPageProxy::advanceToNextMisspelling(bool startBeforeSelection) const +void WebPageProxy::advanceToNextMisspelling(bool startBeforeSelection) { m_process->send(Messages::WebPage::AdvanceToNextMisspelling(startBeforeSelection), m_pageID); } -void WebPageProxy::changeSpellingToWord(const String& word) const +void WebPageProxy::changeSpellingToWord(const String& word) { if (word.isEmpty()) return; @@ -3380,7 +4436,7 @@ void WebPageProxy::changeSpellingToWord(const String& word) const void WebPageProxy::registerEditCommand(PassRefPtr<WebEditCommandProxy> commandProxy, UndoOrRedo undoOrRedo) { - m_pageClient->registerEditCommand(commandProxy, undoOrRedo); + m_pageClient.registerEditCommand(commandProxy, undoOrRedo); } void WebPageProxy::addEditCommand(WebEditCommandProxy* command) @@ -3415,18 +4471,18 @@ int64_t WebPageProxy::spellDocumentTag() #if USE(UNIFIED_TEXT_CHECKING) void WebPageProxy::checkTextOfParagraph(const String& text, uint64_t checkingTypes, Vector<TextCheckingResult>& results) { - results = TextChecker::checkTextOfParagraph(spellDocumentTag(), text.characters(), text.length(), checkingTypes); + results = TextChecker::checkTextOfParagraph(spellDocumentTag(), text, checkingTypes); } #endif void WebPageProxy::checkSpellingOfString(const String& text, int32_t& misspellingLocation, int32_t& misspellingLength) { - TextChecker::checkSpellingOfString(spellDocumentTag(), text.characters(), text.length(), misspellingLocation, misspellingLength); + TextChecker::checkSpellingOfString(spellDocumentTag(), text, misspellingLocation, misspellingLength); } void WebPageProxy::checkGrammarOfString(const String& text, Vector<GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength) { - TextChecker::checkGrammarOfString(spellDocumentTag(), text.characters(), text.length(), grammarDetails, badGrammarLocation, badGrammarLength); + TextChecker::checkGrammarOfString(spellDocumentTag(), text, grammarDetails, badGrammarLocation, badGrammarLength); } void WebPageProxy::spellingUIIsShowing(bool& isShowing) @@ -3470,12 +4526,12 @@ void WebPageProxy::requestCheckingOfString(uint64_t requestID, const TextCheckin TextChecker::requestCheckingOfString(TextCheckerCompletion::create(requestID, request, this)); } -void WebPageProxy::didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>& result) const +void WebPageProxy::didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>& result) { m_process->send(Messages::WebPage::DidFinishCheckingText(requestID, result), m_pageID); } -void WebPageProxy::didCancelCheckingText(uint64_t requestID) const +void WebPageProxy::didCancelCheckingText(uint64_t requestID) { m_process->send(Messages::WebPage::DidCancelCheckingText(requestID), m_pageID); } @@ -3484,34 +4540,34 @@ void WebPageProxy::didCancelCheckingText(uint64_t requestID) const void WebPageProxy::setFocus(bool focused) { if (focused) - m_uiClient.focus(this); + m_uiClient->focus(this); else - m_uiClient.unfocus(this); + m_uiClient->unfocus(this); } void WebPageProxy::takeFocus(uint32_t direction) { - m_uiClient.takeFocus(this, (static_cast<FocusDirection>(direction) == FocusDirectionForward) ? kWKFocusDirectionForward : kWKFocusDirectionBackward); + m_uiClient->takeFocus(this, (static_cast<FocusDirection>(direction) == FocusDirectionForward) ? kWKFocusDirectionForward : kWKFocusDirectionBackward); } void WebPageProxy::setToolTip(const String& toolTip) { String oldToolTip = m_toolTip; m_toolTip = toolTip; - m_pageClient->toolTipChanged(oldToolTip, m_toolTip); + m_pageClient.toolTipChanged(oldToolTip, m_toolTip); } void WebPageProxy::setCursor(const WebCore::Cursor& cursor) { // The Web process may have asked to change the cursor when the view was in an active window, but // if it is no longer in a window or the window is not active, then the cursor should not change. - if (m_pageClient->isViewWindowActive()) - m_pageClient->setCursor(cursor); + if (m_pageClient.isViewWindowActive()) + m_pageClient.setCursor(cursor); } void WebPageProxy::setCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves) { - m_pageClient->setCursorHiddenUntilMouseMoves(hiddenUntilMouseMoves); + m_pageClient.setCursorHiddenUntilMouseMoves(hiddenUntilMouseMoves); } void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) @@ -3521,27 +4577,30 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) switch (type) { case WebEvent::NoType: case WebEvent::MouseMove: + case WebEvent::Wheel: break; case WebEvent::MouseDown: case WebEvent::MouseUp: - case WebEvent::Wheel: + case WebEvent::MouseForceChanged: + case WebEvent::MouseForceDown: + case WebEvent::MouseForceUp: case WebEvent::KeyDown: case WebEvent::KeyUp: case WebEvent::RawKeyDown: case WebEvent::Char: -#if ENABLE(GESTURE_EVENTS) - case WebEvent::GestureScrollBegin: - case WebEvent::GestureScrollEnd: - case WebEvent::GestureSingleTap: -#endif #if ENABLE(TOUCH_EVENTS) case WebEvent::TouchStart: case WebEvent::TouchMove: case WebEvent::TouchEnd: case WebEvent::TouchCancel: #endif - m_process->responsivenessTimer()->stop(); +#if ENABLE(MAC_GESTURE_EVENTS) + case WebEvent::GestureStart: + case WebEvent::GestureChange: + case WebEvent::GestureEnd: +#endif + m_process->responsivenessTimer().stop(); break; } @@ -3550,37 +4609,32 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) break; case WebEvent::MouseMove: m_processingMouseMoveEvent = false; - if (m_nextMouseMoveEvent) { - handleMouseEvent(*m_nextMouseMoveEvent); - m_nextMouseMoveEvent = nullptr; - } + if (m_nextMouseMoveEvent) + handleMouseEvent(*std::exchange(m_nextMouseMoveEvent, nullptr)); break; case WebEvent::MouseDown: break; -#if ENABLE(GESTURE_EVENTS) - case WebEvent::GestureScrollBegin: - case WebEvent::GestureScrollEnd: - case WebEvent::GestureSingleTap: { - WebGestureEvent event = m_gestureEventQueue.first(); - MESSAGE_CHECK(type == event.type()); - - m_gestureEventQueue.removeFirst(); - m_pageClient->doneWithGestureEvent(event, handled); - break; - } -#endif case WebEvent::MouseUp: m_currentlyProcessedMouseDownEvent = nullptr; break; + case WebEvent::MouseForceChanged: + case WebEvent::MouseForceDown: + case WebEvent::MouseForceUp: + break; case WebEvent::Wheel: { - ASSERT(!m_currentlyProcessedWheelEvents.isEmpty()); + MESSAGE_CHECK(!m_currentlyProcessedWheelEvents.isEmpty()); - OwnPtr<Vector<NativeWebWheelEvent> > oldestCoalescedEvent = m_currentlyProcessedWheelEvents.takeFirst(); + std::unique_ptr<Vector<NativeWebWheelEvent>> oldestCoalescedEvent = m_currentlyProcessedWheelEvents.takeFirst(); // FIXME: Dispatch additional events to the didNotHandleWheelEvent client function. - if (!handled && m_uiClient.implementsDidNotHandleWheelEvent()) - m_uiClient.didNotHandleWheelEvent(this, oldestCoalescedEvent->last()); + if (!handled) { + if (m_uiClient->implementsDidNotHandleWheelEvent()) + m_uiClient->didNotHandleWheelEvent(this, oldestCoalescedEvent->last()); +#if PLATFORM(COCOA) + m_pageClient.wheelEventWasNotHandledByWebCore(oldestCoalescedEvent->last()); +#endif + } if (!m_wheelEventQueue.isEmpty()) processNextQueuedWheelEvent(); @@ -3593,35 +4647,61 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) case WebEvent::Char: { LOG(KeyHandling, "WebPageProxy::didReceiveEvent: %s", webKeyboardEventTypeString(type)); - NativeWebKeyboardEvent event = m_keyEventQueue.first(); - MESSAGE_CHECK(type == event.type()); + MESSAGE_CHECK(!m_keyEventQueue.isEmpty()); + NativeWebKeyboardEvent event = m_keyEventQueue.takeFirst(); - m_keyEventQueue.removeFirst(); + MESSAGE_CHECK(type == event.type()); if (!m_keyEventQueue.isEmpty()) m_process->send(Messages::WebPage::KeyEvent(m_keyEventQueue.first()), m_pageID); - m_pageClient->doneWithKeyEvent(event, handled); + // The call to doneWithKeyEvent may close this WebPage. + // Protect against this being destroyed. + Ref<WebPageProxy> protect(*this); + + m_pageClient.doneWithKeyEvent(event, handled); if (handled) break; - if (m_uiClient.implementsDidNotHandleKeyEvent()) - m_uiClient.didNotHandleKeyEvent(this, event); + if (m_uiClient->implementsDidNotHandleKeyEvent()) + m_uiClient->didNotHandleKeyEvent(this, event); break; } -#if ENABLE(TOUCH_EVENTS) +#if ENABLE(MAC_GESTURE_EVENTS) + case WebEvent::GestureStart: + case WebEvent::GestureChange: + case WebEvent::GestureEnd: { + MESSAGE_CHECK(!m_gestureEventQueue.isEmpty()); + NativeWebGestureEvent event = m_gestureEventQueue.takeFirst(); + + MESSAGE_CHECK(type == event.type()); + + if (!handled) + m_pageClient.gestureEventWasNotHandledByWebCore(event); + break; + } + break; +#endif +#if ENABLE(IOS_TOUCH_EVENTS) + case WebEvent::TouchStart: + case WebEvent::TouchMove: + case WebEvent::TouchEnd: + case WebEvent::TouchCancel: + break; +#elif ENABLE(TOUCH_EVENTS) case WebEvent::TouchStart: case WebEvent::TouchMove: case WebEvent::TouchEnd: case WebEvent::TouchCancel: { - QueuedTouchEvents queuedEvents = m_touchEventQueue.first(); + MESSAGE_CHECK(!m_touchEventQueue.isEmpty()); + QueuedTouchEvents queuedEvents = m_touchEventQueue.takeFirst(); + MESSAGE_CHECK(type == queuedEvents.forwardedEvent.type()); - m_touchEventQueue.removeFirst(); - m_pageClient->doneWithTouchEvent(queuedEvents.forwardedEvent, handled); + m_pageClient.doneWithTouchEvent(queuedEvents.forwardedEvent, handled); for (size_t i = 0; i < queuedEvents.deferredTouchEvents.size(); ++i) { bool isEventHandled = false; - m_pageClient->doneWithTouchEvent(queuedEvents.deferredTouchEvents.at(i), isEventHandled); + m_pageClient.doneWithTouchEvent(queuedEvents.deferredTouchEvents.at(i), isEventHandled); } break; } @@ -3631,12 +4711,12 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled) void WebPageProxy::stopResponsivenessTimer() { - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); } void WebPageProxy::voidCallback(uint64_t callbackID) { - RefPtr<VoidCallback> callback = m_voidCallbacks.take(callbackID); + auto callback = m_callbacks.take<VoidCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; @@ -3645,20 +4725,20 @@ void WebPageProxy::voidCallback(uint64_t callbackID) callback->performCallback(); } -void WebPageProxy::dataCallback(const CoreIPC::DataReference& dataReference, uint64_t callbackID) +void WebPageProxy::dataCallback(const IPC::DataReference& dataReference, uint64_t callbackID) { - RefPtr<DataCallback> callback = m_dataCallbacks.take(callbackID); + auto callback = m_callbacks.take<DataCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; } - callback->performCallbackWithReturnValue(WebData::create(dataReference.data(), dataReference.size()).get()); + callback->performCallbackWithReturnValue(API::Data::create(dataReference.data(), dataReference.size()).ptr()); } void WebPageProxy::imageCallback(const ShareableBitmap::Handle& bitmapHandle, uint64_t callbackID) { - RefPtr<ImageCallback> callback = m_imageCallbacks.take(callbackID); + auto callback = m_callbacks.take<ImageCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; @@ -3669,7 +4749,7 @@ void WebPageProxy::imageCallback(const ShareableBitmap::Handle& bitmapHandle, ui void WebPageProxy::stringCallback(const String& resultString, uint64_t callbackID) { - RefPtr<StringCallback> callback = m_stringCallbacks.take(callbackID); + auto callback = m_callbacks.take<StringCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. // this can validly happen if a load invalidated the callback, though @@ -3681,24 +4761,29 @@ void WebPageProxy::stringCallback(const String& resultString, uint64_t callbackI callback->performCallbackWithReturnValue(resultString.impl()); } -void WebPageProxy::scriptValueCallback(const CoreIPC::DataReference& dataReference, uint64_t callbackID) +void WebPageProxy::scriptValueCallback(const IPC::DataReference& dataReference, bool hadException, const ExceptionDetails& details, uint64_t callbackID) { - RefPtr<ScriptValueCallback> callback = m_scriptValueCallbacks.take(callbackID); + auto callback = m_callbacks.take<ScriptValueCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; } + if (dataReference.isEmpty()) { + callback->performCallbackWithReturnValue(nullptr, hadException, details); + return; + } + Vector<uint8_t> data; data.reserveInitialCapacity(dataReference.size()); data.append(dataReference.data(), dataReference.size()); - callback->performCallbackWithReturnValue(data.size() ? WebSerializedScriptValue::adopt(data).get() : 0); + callback->performCallbackWithReturnValue(API::SerializedScriptValue::adopt(WTFMove(data)).ptr(), hadException, details); } void WebPageProxy::computedPagesCallback(const Vector<IntRect>& pageRects, double totalScaleFactorForPrinting, uint64_t callbackID) { - RefPtr<ComputedPagesCallback> callback = m_computedPagesCallbacks.take(callbackID); + auto callback = m_callbacks.take<ComputedPagesCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; @@ -3709,7 +4794,7 @@ void WebPageProxy::computedPagesCallback(const Vector<IntRect>& pageRects, doubl void WebPageProxy::validateCommandCallback(const String& commandName, bool isEnabled, int state, uint64_t callbackID) { - RefPtr<ValidateCommandCallback> callback = m_validateCommandCallbacks.take(callbackID); + auto callback = m_callbacks.take<ValidateCommandCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; @@ -3718,24 +4803,113 @@ void WebPageProxy::validateCommandCallback(const String& commandName, bool isEna callback->performCallbackWithReturnValue(commandName.impl(), isEnabled, state); } +void WebPageProxy::unsignedCallback(uint64_t result, uint64_t callbackID) +{ + auto callback = m_callbacks.take<UnsignedCallback>(callbackID); + if (!callback) { + // FIXME: Log error or assert. + // this can validly happen if a load invalidated the callback, though + return; + } + + callback->performCallbackWithReturnValue(result); +} + +void WebPageProxy::editingRangeCallback(const EditingRange& range, uint64_t callbackID) +{ + MESSAGE_CHECK(range.isValid()); + + auto callback = m_callbacks.take<EditingRangeCallback>(callbackID); + if (!callback) { + // FIXME: Log error or assert. + // this can validly happen if a load invalidated the callback, though + return; + } + + callback->performCallbackWithReturnValue(range); +} + +#if PLATFORM(COCOA) +void WebPageProxy::machSendRightCallback(const MachSendRight& sendRight, uint64_t callbackID) +{ + auto callback = m_callbacks.take<MachSendRightCallback>(callbackID); + if (!callback) + return; + + callback->performCallbackWithReturnValue(sendRight); +} +#endif + +void WebPageProxy::logDiagnosticMessage(const String& message, const String& description, bool shouldSample) +{ + if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample ? ShouldSample::Yes : ShouldSample::No)) + return; + + logSampledDiagnosticMessage(message, description); +} + +void WebPageProxy::logDiagnosticMessageWithResult(const String& message, const String& description, uint32_t result, bool shouldSample) +{ + if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample ? ShouldSample::Yes : ShouldSample::No)) + return; + + logSampledDiagnosticMessageWithResult(message, description, static_cast<WebCore::DiagnosticLoggingResultType>(result)); +} + +void WebPageProxy::logDiagnosticMessageWithValue(const String& message, const String& description, const String& value, bool shouldSample) +{ + if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample ? ShouldSample::Yes : ShouldSample::No)) + return; + + logSampledDiagnosticMessageWithValue(message, description, value); +} + +void WebPageProxy::logSampledDiagnosticMessage(const String& message, const String& description) +{ + m_diagnosticLoggingClient->logDiagnosticMessage(this, message, description); +} + +void WebPageProxy::logSampledDiagnosticMessageWithResult(const String& message, const String& description, uint32_t result) +{ + m_diagnosticLoggingClient->logDiagnosticMessageWithResult(this, message, description, static_cast<WebCore::DiagnosticLoggingResultType>(result)); +} + +void WebPageProxy::logSampledDiagnosticMessageWithValue(const String& message, const String& description, const String& value) +{ + m_diagnosticLoggingClient->logDiagnosticMessageWithValue(this, message, description, value); +} + +void WebPageProxy::rectForCharacterRangeCallback(const IntRect& rect, const EditingRange& actualRange, uint64_t callbackID) +{ + MESSAGE_CHECK(actualRange.isValid()); + + auto callback = m_callbacks.take<RectForCharacterRangeCallback>(callbackID); + if (!callback) { + // FIXME: Log error or assert. + // this can validly happen if a load invalidated the callback, though + return; + } + + callback->performCallbackWithReturnValue(rect, actualRange); +} + #if PLATFORM(GTK) void WebPageProxy::printFinishedCallback(const ResourceError& printError, uint64_t callbackID) { - RefPtr<PrintFinishedCallback> callback = m_printFinishedCallbacks.take(callbackID); + auto callback = m_callbacks.take<PrintFinishedCallback>(callbackID); if (!callback) { // FIXME: Log error or assert. return; } - RefPtr<WebError> error = WebError::create(printError); - callback->performCallbackWithReturnValue(error.get()); + callback->performCallbackWithReturnValue(API::Error::create(printError).ptr()); } #endif void WebPageProxy::focusedFrameChanged(uint64_t frameID) { if (!frameID) { - m_focusedFrame = 0; + m_focusedFrame = nullptr; return; } @@ -3748,7 +4922,7 @@ void WebPageProxy::focusedFrameChanged(uint64_t frameID) void WebPageProxy::frameSetLargestFrameChanged(uint64_t frameID) { if (!frameID) { - m_frameSetLargestFrame = 0; + m_frameSetLargestFrame = nullptr; return; } @@ -3765,65 +4939,93 @@ void WebPageProxy::processDidBecomeUnresponsive() updateBackingStoreDiscardableState(); - m_loaderClient.processDidBecomeUnresponsive(this); + if (m_navigationClient) + m_navigationClient->processDidBecomeUnresponsive(*this); + else + m_loaderClient->processDidBecomeUnresponsive(*this); } -void WebPageProxy::interactionOccurredWhileProcessUnresponsive() +void WebPageProxy::processDidBecomeResponsive() { if (!isValid()) return; + + updateBackingStoreDiscardableState(); - m_loaderClient.interactionOccurredWhileProcessUnresponsive(this); + if (m_navigationClient) + m_navigationClient->processDidBecomeResponsive(*this); + else + m_loaderClient->processDidBecomeResponsive(*this); } -void WebPageProxy::processDidBecomeResponsive() +void WebPageProxy::willChangeProcessIsResponsive() { - if (!isValid()) - return; - - updateBackingStoreDiscardableState(); + m_pageLoadState.willChangeProcessIsResponsive(); +} - m_loaderClient.processDidBecomeResponsive(this); +void WebPageProxy::didChangeProcessIsResponsive() +{ + m_pageLoadState.didChangeProcessIsResponsive(); } void WebPageProxy::processDidCrash() { ASSERT(m_isValid); + // There is a nested transaction in resetStateAfterProcessExited() that we don't want to commit before the client call. + PageLoadState::Transaction transaction = m_pageLoadState.transaction(); + resetStateAfterProcessExited(); - m_pageClient->processDidCrash(); - m_loaderClient.processDidCrash(this); + navigationState().clearAllNavigations(); + + if (m_navigationClient) + m_navigationClient->processDidCrash(*this); + else + m_loaderClient->processDidCrash(*this); } -void WebPageProxy::resetStateAfterProcessExited() +#if PLATFORM(IOS) +void WebPageProxy::processWillBecomeSuspended() { if (!isValid()) return; - ASSERT(m_pageClient); - m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_pageID); + m_hasNetworkRequestsOnSuspended = m_pageLoadState.networkRequestsInProgress(); + if (m_hasNetworkRequestsOnSuspended) + setNetworkRequestsInProgress(false); +} - m_isValid = false; - m_isPageSuspended = false; - m_waitingForDidUpdateInWindowState = false; +void WebPageProxy::processWillBecomeForeground() +{ + if (!isValid()) + return; - if (m_mainFrame) { - m_urlAtProcessExit = m_mainFrame->url(); - m_loadStateAtProcessExit = m_mainFrame->loadState(); + if (m_hasNetworkRequestsOnSuspended) { + setNetworkRequestsInProgress(true); + m_hasNetworkRequestsOnSuspended = false; } +} +#endif +void WebPageProxy::resetState(ResetStateReason resetStateReason) +{ m_mainFrame = nullptr; +#if PLATFORM(COCOA) + m_scrollingPerformanceData = nullptr; +#endif m_drawingArea = nullptr; -#if ENABLE(INSPECTOR) - m_inspector->invalidate(); - m_inspector = nullptr; -#endif + if (m_inspector) { + m_inspector->invalidate(); + m_inspector = nullptr; + } #if ENABLE(FULLSCREEN_API) - m_fullScreenManager->invalidate(); - m_fullScreenManager = nullptr; + if (m_fullScreenManager) { + m_fullScreenManager->invalidate(); + m_fullScreenManager = nullptr; + } #endif #if ENABLE(VIBRATION) @@ -3835,21 +5037,23 @@ void WebPageProxy::resetStateAfterProcessExited() m_openPanelResultListener = nullptr; } +#if ENABLE(TOUCH_EVENTS) + m_isTrackingTouchEvents = false; +#endif + #if ENABLE(INPUT_TYPE_COLOR) if (m_colorPicker) { m_colorPicker->invalidate(); m_colorPicker = nullptr; } - - if (m_colorPickerResultListener) { - m_colorPickerResultListener->invalidate(); - m_colorPickerResultListener = nullptr; - } #endif #if ENABLE(GEOLOCATION) m_geolocationPermissionRequestManager.invalidateRequests(); #endif +#if ENABLE(MEDIA_STREAM) + m_userMediaPermissionRequestManager.invalidateRequests(); +#endif m_notificationPermissionRequestManager.invalidateRequests(); @@ -3858,47 +5062,94 @@ void WebPageProxy::resetStateAfterProcessExited() m_mainFrameHasHorizontalScrollbar = false; m_mainFrameHasVerticalScrollbar = false; - m_mainFrameIsPinnedToLeftSide = false; - m_mainFrameIsPinnedToRightSide = false; - m_mainFrameIsPinnedToTopSide = false; - m_mainFrameIsPinnedToBottomSide = false; + m_mainFrameIsPinnedToLeftSide = true; + m_mainFrameIsPinnedToRightSide = true; + m_mainFrameIsPinnedToTopSide = true; + m_mainFrameIsPinnedToBottomSide = true; m_visibleScrollerThumbRect = IntRect(); - invalidateCallbackMap(m_voidCallbacks); - invalidateCallbackMap(m_dataCallbacks); - invalidateCallbackMap(m_stringCallbacks); - m_loadDependentStringCallbackIDs.clear(); - invalidateCallbackMap(m_scriptValueCallbacks); - invalidateCallbackMap(m_computedPagesCallbacks); - invalidateCallbackMap(m_validateCommandCallbacks); -#if PLATFORM(GTK) - invalidateCallbackMap(m_printFinishedCallbacks); +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) + if (m_videoFullscreenManager) { + m_videoFullscreenManager->invalidate(); + m_videoFullscreenManager = nullptr; + } +#endif + +#if PLATFORM(IOS) + m_lastVisibleContentRectUpdate = VisibleContentRectUpdateInfo(); + m_dynamicViewportSizeUpdateWaitingForTarget = false; + m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit = false; + m_dynamicViewportSizeUpdateLayerTreeTransactionID = 0; + m_layerTreeTransactionIdAtLastTouchStart = 0; + m_hasNetworkRequestsOnSuspended = false; +#endif + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) + m_pageClient.mediaSessionManager().removeAllPlaybackTargetPickerClients(*this); +#endif + +#if USE(APPLE_INTERNAL_SDK) +#include <WebKitAdditions/WebPageProxyInvalidation.cpp> #endif + CallbackBase::Error error; + switch (resetStateReason) { + case ResetStateReason::PageInvalidated: + error = CallbackBase::Error::OwnerWasInvalidated; + break; + + case ResetStateReason::WebProcessExited: + error = CallbackBase::Error::ProcessExited; + break; + } + + m_callbacks.invalidate(error); + m_loadDependentStringCallbackIDs.clear(); + Vector<WebEditCommandProxy*> editCommandVector; copyToVector(m_editCommandSet, editCommandVector); m_editCommandSet.clear(); for (size_t i = 0, size = editCommandVector.size(); i < size; ++i) editCommandVector[i]->invalidate(); - m_pageClient->clearAllEditCommands(); - m_activePopupMenu = 0; + m_activePopupMenu = nullptr; + m_mediaState = MediaProducer::IsNotPlaying; +} - m_estimatedProgress = 0.0; +void WebPageProxy::resetStateAfterProcessExited() +{ + if (!isValid()) + return; - m_pendingLearnOrIgnoreWordMessageCount = 0; + // FIXME: It's weird that resetStateAfterProcessExited() is called even though the process is launching. + ASSERT(m_process->state() == WebProcessProxy::State::Launching || m_process->state() == WebProcessProxy::State::Terminated); + +#if PLATFORM(IOS) + m_activityToken = nullptr; +#endif + m_pageIsUserObservableCount = nullptr; + + m_isValid = false; + m_isPageSuspended = false; + + m_needsToFinishInitializingWebPageAfterProcessLaunch = false; - // If the call out to the loader client didn't cause the web process to be relaunched, - // we'll call setNeedsDisplay on the view so that we won't have the old contents showing. - // If the call did cause the web process to be relaunched, we'll keep the old page contents showing - // until the new web process has painted its contents. - setViewNeedsDisplay(IntRect(IntPoint(), viewSize())); + m_editorState = EditorState(); + + if (m_mainFrame) { + m_urlAtProcessExit = m_mainFrame->url(); + m_loadStateAtProcessExit = m_mainFrame->loadState(); + } + + m_pageClient.processDidExit(); + + resetState(ResetStateReason::WebProcessExited); + + m_pageClient.clearAllEditCommands(); + m_pendingLearnOrIgnoreWordMessageCount = 0; // Can't expect DidReceiveEvent notifications from a crashed web process. -#if ENABLE(GESTURE_EVENTS) - m_gestureEventQueue.clear(); -#endif m_keyEventQueue.clear(); m_wheelEventQueue.clear(); m_currentlyProcessedWheelEvents.clear(); @@ -3908,37 +5159,32 @@ void WebPageProxy::resetStateAfterProcessExited() m_processingMouseMoveEvent = false; -#if ENABLE(TOUCH_EVENTS) - m_needTouchEvents = false; +#if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS) m_touchEventQueue.clear(); #endif - // FIXME: Reset m_editorState. - // FIXME: Notify input methods about abandoned composition. - m_temporarilyClosedComposition = false; - #if PLATFORM(MAC) - dismissCorrectionPanel(ReasonForDismissingAlternativeTextIgnored); - m_pageClient->dismissDictionaryLookupPanel(); + m_pageClient.dismissContentRelativeChildWindows(); #endif + + PageLoadState::Transaction transaction = m_pageLoadState.transaction(); + m_pageLoadState.reset(transaction); + + m_process->responsivenessTimer().processTerminated(); } -WebPageCreationParameters WebPageProxy::creationParameters() const +WebPageCreationParameters WebPageProxy::creationParameters() { WebPageCreationParameters parameters; - parameters.viewSize = m_pageClient->viewSize(); - parameters.isActive = m_pageClient->isViewWindowActive(); - parameters.isFocused = m_pageClient->isViewFocused(); - parameters.isVisible = m_pageClient->isViewVisible(); - parameters.isInWindow = m_pageClient->isViewInWindow(); + parameters.viewSize = m_pageClient.viewSize(); + parameters.viewState = m_viewState; parameters.drawingAreaType = m_drawingArea->type(); - parameters.store = m_pageGroup->preferences()->store(); + parameters.store = preferencesStore(); parameters.pageGroupData = m_pageGroup->data(); parameters.drawsBackground = m_drawsBackground; - parameters.drawsTransparentBackground = m_drawsTransparentBackground; + parameters.isEditable = m_isEditable; parameters.underlayColor = m_underlayColor; - parameters.areMemoryCacheClientCallsEnabled = m_areMemoryCacheClientCallsEnabled; parameters.useFixedLayout = m_useFixedLayout; parameters.fixedLayoutSize = m_fixedLayoutSize; parameters.suppressScrollbarAnimations = m_suppressScrollbarAnimations; @@ -3946,41 +5192,74 @@ WebPageCreationParameters WebPageProxy::creationParameters() const parameters.paginationBehavesLikeColumns = m_paginationBehavesLikeColumns; parameters.pageLength = m_pageLength; parameters.gapBetweenPages = m_gapBetweenPages; + parameters.paginationLineGridEnabled = m_paginationLineGridEnabled; parameters.userAgent = userAgent(); - parameters.sessionState = SessionState(m_backForwardList->entries(), m_backForwardList->currentIndex()); + parameters.itemStates = m_backForwardList->itemStates(); + parameters.sessionID = m_sessionID; parameters.highestUsedBackForwardItemID = WebBackForwardListItem::highedUsedItemID(); - parameters.canRunBeforeUnloadConfirmPanel = m_uiClient.canRunBeforeUnloadConfirmPanel(); + parameters.userContentControllerID = m_userContentController ? m_userContentController->identifier() : 0; + parameters.visitedLinkTableID = m_visitedLinkStore->identifier(); + parameters.websiteDataStoreID = m_websiteDataStore->identifier(); + parameters.canRunBeforeUnloadConfirmPanel = m_uiClient->canRunBeforeUnloadConfirmPanel(); parameters.canRunModal = m_canRunModal; parameters.deviceScaleFactor = deviceScaleFactor(); + parameters.viewScaleFactor = m_viewScaleFactor; + parameters.topContentInset = m_topContentInset; parameters.mediaVolume = m_mediaVolume; + parameters.muted = m_muted; parameters.mayStartMediaWhenInWindow = m_mayStartMediaWhenInWindow; parameters.minimumLayoutSize = m_minimumLayoutSize; + parameters.autoSizingShouldExpandToViewHeight = m_autoSizingShouldExpandToViewHeight; parameters.scrollPinningBehavior = m_scrollPinningBehavior; + if (m_scrollbarOverlayStyle) + parameters.scrollbarOverlayStyle = m_scrollbarOverlayStyle.value(); + else + parameters.scrollbarOverlayStyle = Nullopt; + parameters.backgroundExtendsBeyondPage = m_backgroundExtendsBeyondPage; + parameters.layerHostingMode = m_layerHostingMode; +#if ENABLE(REMOTE_INSPECTOR) + parameters.allowsRemoteInspection = m_allowsRemoteInspection; + parameters.remoteInspectionNameOverride = m_remoteInspectionNameOverride; +#endif +#if PLATFORM(MAC) + parameters.colorSpace = m_pageClient.colorSpace(); +#endif +#if PLATFORM(IOS) + parameters.screenSize = screenSize(); + parameters.availableScreenSize = availableScreenSize(); + parameters.textAutosizingWidth = textAutosizingWidth(); + parameters.mimeTypesWithCustomContentProviders = m_pageClient.mimeTypesWithCustomContentProviders(); +#endif #if PLATFORM(MAC) - parameters.layerHostingMode = m_layerHostingMode; - parameters.colorSpace = m_pageClient->colorSpace(); + parameters.appleMailPaginationQuirkEnabled = appleMailPaginationQuirkEnabled(); +#else + parameters.appleMailPaginationQuirkEnabled = false; #endif + parameters.shouldScaleViewToFitDocument = m_shouldScaleViewToFitDocument; return parameters; } -#if USE(ACCELERATED_COMPOSITING) void WebPageProxy::enterAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) { - m_pageClient->enterAcceleratedCompositingMode(layerTreeContext); + m_pageClient.enterAcceleratedCompositingMode(layerTreeContext); } void WebPageProxy::exitAcceleratedCompositingMode() { - m_pageClient->exitAcceleratedCompositingMode(); + m_pageClient.exitAcceleratedCompositingMode(); } void WebPageProxy::updateAcceleratedCompositingMode(const LayerTreeContext& layerTreeContext) { - m_pageClient->updateAcceleratedCompositingMode(layerTreeContext); + m_pageClient.updateAcceleratedCompositingMode(layerTreeContext); +} + +void WebPageProxy::willEnterAcceleratedCompositingMode() +{ + m_pageClient.willEnterAcceleratedCompositingMode(); } -#endif // USE(ACCELERATED_COMPOSITING) void WebPageProxy::backForwardClear() { @@ -3993,8 +5272,11 @@ void WebPageProxy::canAuthenticateAgainstProtectionSpaceInFrame(uint64_t frameID MESSAGE_CHECK(frame); RefPtr<WebProtectionSpace> protectionSpace = WebProtectionSpace::create(coreProtectionSpace); - - canAuthenticate = m_loaderClient.canAuthenticateAgainstProtectionSpaceInFrame(this, frame, protectionSpace.get()); + + if (m_navigationClient) + canAuthenticate = m_navigationClient->canAuthenticateAgainstProtectionSpace(*this, protectionSpace.get()); + else + canAuthenticate = m_loaderClient->canAuthenticateAgainstProtectionSpaceInFrame(*this, *frame, protectionSpace.get()); } void WebPageProxy::didReceiveAuthenticationChallenge(uint64_t frameID, const AuthenticationChallenge& coreChallenge, uint64_t challengeID) @@ -4010,16 +5292,19 @@ void WebPageProxy::didReceiveAuthenticationChallengeProxy(uint64_t frameID, Pass MESSAGE_CHECK(frame); RefPtr<AuthenticationChallengeProxy> authenticationChallenge = prpAuthenticationChallenge; - m_loaderClient.didReceiveAuthenticationChallengeInFrame(this, frame, authenticationChallenge.get()); + if (m_navigationClient) + m_navigationClient->didReceiveAuthenticationChallenge(*this, authenticationChallenge.get()); + else + m_loaderClient->didReceiveAuthenticationChallengeInFrame(*this, *frame, authenticationChallenge.get()); } void WebPageProxy::exceededDatabaseQuota(uint64_t frameID, const String& originIdentifier, const String& databaseName, const String& displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply> reply) { - ExceededDatabaseQuotaRecords& records = ExceededDatabaseQuotaRecords::shared(); - OwnPtr<ExceededDatabaseQuotaRecords::Record> newRecord = records.createRecord(frameID, + ExceededDatabaseQuotaRecords& records = ExceededDatabaseQuotaRecords::singleton(); + std::unique_ptr<ExceededDatabaseQuotaRecords::Record> newRecord = records.createRecord(frameID, originIdentifier, databaseName, displayName, currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage, reply); - records.add(newRecord.release()); + records.add(WTFMove(newRecord)); if (records.areBeingProcessed()) return; @@ -4029,94 +5314,129 @@ void WebPageProxy::exceededDatabaseQuota(uint64_t frameID, const String& originI WebFrameProxy* frame = m_process->webFrame(record->frameID); MESSAGE_CHECK(frame); - RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromDatabaseIdentifier(record->originIdentifier); - - uint64_t newQuota = m_uiClient.exceededDatabaseQuota(this, frame, origin.get(), + RefPtr<API::SecurityOrigin> origin = API::SecurityOrigin::create(SecurityOrigin::createFromDatabaseIdentifier(record->originIdentifier)); + auto currentReply = record->reply; + m_uiClient->exceededDatabaseQuota(this, frame, origin.get(), record->databaseName, record->displayName, record->currentQuota, - record->currentOriginUsage, record->currentDatabaseUsage, record->expectedUsage); + record->currentOriginUsage, record->currentDatabaseUsage, record->expectedUsage, + [currentReply](unsigned long long newQuota) { currentReply->send(newQuota); }); - record->reply->send(newQuota); record = records.next(); } } +void WebPageProxy::reachedApplicationCacheOriginQuota(const String& originIdentifier, uint64_t currentQuota, uint64_t totalBytesNeeded, PassRefPtr<Messages::WebPageProxy::ReachedApplicationCacheOriginQuota::DelayedReply> reply) +{ + Ref<SecurityOrigin> securityOrigin = SecurityOrigin::createFromDatabaseIdentifier(originIdentifier); + m_uiClient->reachedApplicationCacheOriginQuota(this, securityOrigin.get(), currentQuota, totalBytesNeeded, [reply](unsigned long long newQuota) { reply->send(newQuota); }); +} + void WebPageProxy::requestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, String originIdentifier) { WebFrameProxy* frame = m_process->webFrame(frameID); MESSAGE_CHECK(frame); // FIXME: Geolocation should probably be using toString() as its string representation instead of databaseIdentifier(). - RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromDatabaseIdentifier(originIdentifier); + RefPtr<API::SecurityOrigin> origin = API::SecurityOrigin::create(SecurityOrigin::createFromDatabaseIdentifier(originIdentifier)); RefPtr<GeolocationPermissionRequestProxy> request = m_geolocationPermissionRequestManager.createRequest(geolocationID); - if (!m_uiClient.decidePolicyForGeolocationPermissionRequest(this, frame, origin.get(), request.get())) + if (m_uiClient->decidePolicyForGeolocationPermissionRequest(this, frame, origin.get(), request.get())) + return; + + if (m_pageClient.decidePolicyForGeolocationPermissionRequest(*frame, *origin, *request)) + return; + + request->deny(); +} + +void WebPageProxy::requestUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String originIdentifier, const Vector<String>& audioDeviceUIDs, const Vector<String>& videoDeviceUIDs) +{ + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + + RefPtr<API::SecurityOrigin> origin = API::SecurityOrigin::create(SecurityOrigin::createFromDatabaseIdentifier(originIdentifier)); + RefPtr<UserMediaPermissionRequestProxy> request = m_userMediaPermissionRequestManager.createRequest(userMediaID, audioDeviceUIDs, videoDeviceUIDs); + + if (!m_uiClient->decidePolicyForUserMediaPermissionRequest(*this, *frame, *origin.get(), *request.get())) request->deny(); } +void WebPageProxy::checkUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String originIdentifier) +{ + WebFrameProxy* frame = m_process->webFrame(frameID); + MESSAGE_CHECK(frame); + + RefPtr<API::SecurityOrigin> origin = API::SecurityOrigin::create(SecurityOrigin::createFromDatabaseIdentifier(originIdentifier)); + RefPtr<UserMediaPermissionCheckProxy> request = m_userMediaPermissionRequestManager.createUserMediaPermissionCheck(userMediaID); + + if (!m_uiClient->checkUserMediaPermissionForOrigin(*this, *frame, *origin.get(), *request.get())) + request->setHasPersistentPermission(false); +} + void WebPageProxy::requestNotificationPermission(uint64_t requestID, const String& originString) { if (!isRequestIDValid(requestID)) return; - RefPtr<WebSecurityOrigin> origin = WebSecurityOrigin::createFromString(originString); + RefPtr<API::SecurityOrigin> origin = API::SecurityOrigin::createFromString(originString); RefPtr<NotificationPermissionRequest> request = m_notificationPermissionRequestManager.createRequest(requestID); - if (!m_uiClient.decidePolicyForNotificationPermissionRequest(this, origin.get(), request.get())) + if (!m_uiClient->decidePolicyForNotificationPermissionRequest(this, origin.get(), request.get())) request->deny(); } void WebPageProxy::showNotification(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID) { - m_process->context()->supplement<WebNotificationManagerProxy>()->show(this, title, body, iconURL, tag, lang, dir, originString, notificationID); + m_process->processPool().supplement<WebNotificationManagerProxy>()->show(this, title, body, iconURL, tag, lang, dir, originString, notificationID); } void WebPageProxy::cancelNotification(uint64_t notificationID) { - m_process->context()->supplement<WebNotificationManagerProxy>()->cancel(this, notificationID); + m_process->processPool().supplement<WebNotificationManagerProxy>()->cancel(this, notificationID); } void WebPageProxy::clearNotifications(const Vector<uint64_t>& notificationIDs) { - m_process->context()->supplement<WebNotificationManagerProxy>()->clearNotifications(this, notificationIDs); + m_process->processPool().supplement<WebNotificationManagerProxy>()->clearNotifications(this, notificationIDs); } void WebPageProxy::didDestroyNotification(uint64_t notificationID) { - m_process->context()->supplement<WebNotificationManagerProxy>()->didDestroyNotification(this, notificationID); + m_process->processPool().supplement<WebNotificationManagerProxy>()->didDestroyNotification(this, notificationID); } float WebPageProxy::headerHeight(WebFrameProxy* frame) { if (frame->isDisplayingPDFDocument()) return 0; - return m_uiClient.headerHeight(this, frame); + return m_uiClient->headerHeight(this, frame); } float WebPageProxy::footerHeight(WebFrameProxy* frame) { if (frame->isDisplayingPDFDocument()) return 0; - return m_uiClient.footerHeight(this, frame); + return m_uiClient->footerHeight(this, frame); } void WebPageProxy::drawHeader(WebFrameProxy* frame, const FloatRect& rect) { if (frame->isDisplayingPDFDocument()) return; - m_uiClient.drawHeader(this, frame, rect); + m_uiClient->drawHeader(this, frame, rect); } void WebPageProxy::drawFooter(WebFrameProxy* frame, const FloatRect& rect) { if (frame->isDisplayingPDFDocument()) return; - m_uiClient.drawFooter(this, frame, rect); + m_uiClient->drawFooter(this, frame, rect); } void WebPageProxy::runModal() { // Since runModal() can (and probably will) spin a nested run loop we need to turn off the responsiveness timer. - m_process->responsivenessTimer()->stop(); + m_process->responsivenessTimer().stop(); // Our Connection's run loop might have more messages waiting to be handled after this RunModal message. // To make sure they are handled inside of the the nested modal run loop we must first signal the Connection's @@ -4124,7 +5444,7 @@ void WebPageProxy::runModal() // See http://webkit.org/b/89590 for more discussion. m_process->connection()->wakeUpRunLoop(); - m_uiClient.runModal(this); + m_uiClient->runModal(this); } void WebPageProxy::notifyScrollerThumbIsVisibleInRect(const IntRect& scrollerThumb) @@ -4134,8 +5454,8 @@ void WebPageProxy::notifyScrollerThumbIsVisibleInRect(const IntRect& scrollerThu void WebPageProxy::recommendedScrollbarStyleDidChange(int32_t newStyle) { -#if PLATFORM(MAC) - m_pageClient->recommendedScrollbarStyleDidChange(newStyle); +#if USE(APPKIT) + m_pageClient.recommendedScrollbarStyleDidChange(static_cast<WebCore::ScrollbarStyle>(newStyle)); #else UNUSED_PARAM(newStyle); #endif @@ -4153,6 +5473,8 @@ void WebPageProxy::didChangeScrollOffsetPinningForMainFrame(bool pinnedToLeftSid m_mainFrameIsPinnedToRightSide = pinnedToRightSide; m_mainFrameIsPinnedToTopSide = pinnedToTopSide; m_mainFrameIsPinnedToBottomSide = pinnedToBottomSide; + + m_uiClient->pinnedStateDidChange(*this); } void WebPageProxy::didChangePageCount(unsigned pageCount) @@ -4160,33 +5482,50 @@ void WebPageProxy::didChangePageCount(unsigned pageCount) m_pageCount = pageCount; } +void WebPageProxy::pageExtendedBackgroundColorDidChange(const Color& backgroundColor) +{ + m_pageExtendedBackgroundColor = backgroundColor; +} + +#if ENABLE(NETSCAPE_PLUGIN_API) void WebPageProxy::didFailToInitializePlugin(const String& mimeType, const String& frameURLString, const String& pageURLString) { - m_loaderClient.didFailToInitializePlugin(this, createPluginInformationDictionary(mimeType, frameURLString, pageURLString).get()); + m_loaderClient->didFailToInitializePlugin(*this, createPluginInformationDictionary(mimeType, frameURLString, pageURLString).ptr()); } void WebPageProxy::didBlockInsecurePluginVersion(const String& mimeType, const String& pluginURLString, const String& frameURLString, const String& pageURLString, bool replacementObscured) { - RefPtr<ImmutableDictionary> pluginInformation; + RefPtr<API::Dictionary> pluginInformation; -#if PLATFORM(MAC) && ENABLE(NETSCAPE_PLUGIN_API) +#if PLATFORM(COCOA) && ENABLE(NETSCAPE_PLUGIN_API) String newMimeType = mimeType; - PluginModuleInfo plugin = m_process->context()->pluginInfoStore().findPlugin(newMimeType, KURL(KURL(), pluginURLString)); + PluginModuleInfo plugin = m_process->processPool().pluginInfoStore().findPlugin(newMimeType, URL(URL(), pluginURLString)); pluginInformation = createPluginInformationDictionary(plugin, frameURLString, mimeType, pageURLString, String(), String(), replacementObscured); #else + UNUSED_PARAM(mimeType); UNUSED_PARAM(pluginURLString); + UNUSED_PARAM(frameURLString); + UNUSED_PARAM(pageURLString); + UNUSED_PARAM(replacementObscured); #endif - m_loaderClient.didBlockInsecurePluginVersion(this, pluginInformation.get()); + m_loaderClient->didBlockInsecurePluginVersion(*this, pluginInformation.get()); } +#endif // ENABLE(NETSCAPE_PLUGIN_API) bool WebPageProxy::willHandleHorizontalScrollEvents() const { return !m_canShortCircuitHorizontalWheelEvents; } +void WebPageProxy::didFinishLoadingDataForCustomContentProvider(const String& suggestedFilename, const IPC::DataReference& dataReference) +{ + m_pageClient.didFinishLoadingDataForCustomContentProvider(suggestedFilename, dataReference); +} + void WebPageProxy::backForwardRemovedItem(uint64_t itemID) { + m_process->removeBackForwardItem(itemID); m_process->send(Messages::WebPage::DidRemoveBackForwardItem(itemID), m_pageID); } @@ -4198,7 +5537,7 @@ void WebPageProxy::setCanRunModal(bool canRunModal) // It's only possible to change the state for a WebPage which // already qualifies for running modal child web pages, otherwise // there's no other possibility than not allowing it. - m_canRunModal = m_uiClient.canRunModal() && canRunModal; + m_canRunModal = m_uiClient->canRunModal() && canRunModal; m_process->send(Messages::WebPage::SetCanRunModal(m_canRunModal), m_pageID); } @@ -4213,7 +5552,7 @@ void WebPageProxy::beginPrinting(WebFrameProxy* frame, const PrintInfo& printInf return; m_isInPrintingMode = true; - m_process->send(Messages::WebPage::BeginPrinting(frame->frameID(), printInfo), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_process->send(Messages::WebPage::BeginPrinting(frame->frameID(), printInfo), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } void WebPageProxy::endPrinting() @@ -4222,7 +5561,7 @@ void WebPageProxy::endPrinting() return; m_isInPrintingMode = false; - m_process->send(Messages::WebPage::EndPrinting(), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_process->send(Messages::WebPage::EndPrinting(), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } void WebPageProxy::computePagesForPrinting(WebFrameProxy* frame, const PrintInfo& printInfo, PassRefPtr<ComputedPagesCallback> prpCallback) @@ -4234,12 +5573,12 @@ void WebPageProxy::computePagesForPrinting(WebFrameProxy* frame, const PrintInfo } uint64_t callbackID = callback->callbackID(); - m_computedPagesCallbacks.set(callbackID, callback.get()); + m_callbacks.put(callback); m_isInPrintingMode = true; - m_process->send(Messages::WebPage::ComputePagesForPrinting(frame->frameID(), printInfo, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_process->send(Messages::WebPage::ComputePagesForPrinting(frame->frameID(), printInfo, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void WebPageProxy::drawRectToImage(WebFrameProxy* frame, const PrintInfo& printInfo, const IntRect& rect, const WebCore::IntSize& imageSize, PassRefPtr<ImageCallback> prpCallback) { RefPtr<ImageCallback> callback = prpCallback; @@ -4249,8 +5588,8 @@ void WebPageProxy::drawRectToImage(WebFrameProxy* frame, const PrintInfo& printI } uint64_t callbackID = callback->callbackID(); - m_imageCallbacks.set(callbackID, callback.get()); - m_process->send(Messages::WebPage::DrawRectToImage(frame->frameID(), printInfo, rect, imageSize, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_callbacks.put(callback); + m_process->send(Messages::WebPage::DrawRectToImage(frame->frameID(), printInfo, rect, imageSize, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } void WebPageProxy::drawPagesToPDF(WebFrameProxy* frame, const PrintInfo& printInfo, uint32_t first, uint32_t count, PassRefPtr<DataCallback> prpCallback) @@ -4262,8 +5601,8 @@ void WebPageProxy::drawPagesToPDF(WebFrameProxy* frame, const PrintInfo& printIn } uint64_t callbackID = callback->callbackID(); - m_dataCallbacks.set(callbackID, callback.get()); - m_process->send(Messages::WebPage::DrawPagesToPDF(frame->frameID(), printInfo, first, count, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_callbacks.put(callback); + m_process->send(Messages::WebPage::DrawPagesToPDF(frame->frameID(), printInfo, first, count, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } #elif PLATFORM(GTK) void WebPageProxy::drawPagesForPrinting(WebFrameProxy* frame, const PrintInfo& printInfo, PassRefPtr<PrintFinishedCallback> didPrintCallback) @@ -4275,59 +5614,38 @@ void WebPageProxy::drawPagesForPrinting(WebFrameProxy* frame, const PrintInfo& p } uint64_t callbackID = callback->callbackID(); - m_printFinishedCallbacks.set(callbackID, callback.get()); + m_callbacks.put(callback); m_isInPrintingMode = true; - m_process->send(Messages::WebPage::DrawPagesForPrinting(frame->frameID(), printInfo, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? CoreIPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); + m_process->send(Messages::WebPage::DrawPagesForPrinting(frame->frameID(), printInfo, callbackID), m_pageID, m_isPerformingDOMPrintOperation ? IPC::DispatchMessageEvenWhenWaitingForSyncReply : 0); } #endif -void WebPageProxy::flashBackingStoreUpdates(const Vector<IntRect>& updateRects) -{ - m_pageClient->flashBackingStoreUpdates(updateRects); -} - void WebPageProxy::updateBackingStoreDiscardableState() { ASSERT(isValid()); bool isDiscardable; - if (!m_process->responsivenessTimer()->isResponsive()) + if (!m_process->responsivenessTimer().isResponsive()) isDiscardable = false; else - isDiscardable = !m_pageClient->isViewWindowActive() || !isViewVisible(); + isDiscardable = !m_pageClient.isViewWindowActive() || !isViewVisible(); m_drawingArea->setBackingStoreIsDiscardable(isDiscardable); } -Color WebPageProxy::viewUpdatesFlashColor() -{ - return Color(0, 200, 255); -} - -Color WebPageProxy::backingStoreUpdatesFlashColor() -{ - return Color(200, 0, 255); -} - -void WebPageProxy::saveDataToFileInDownloadsFolder(const String& suggestedFilename, const String& mimeType, const String& originatingURLString, WebData* data) +void WebPageProxy::saveDataToFileInDownloadsFolder(const String& suggestedFilename, const String& mimeType, const String& originatingURLString, API::Data* data) { - m_uiClient.saveDataToFileInDownloadsFolder(this, suggestedFilename, mimeType, originatingURLString, data); + m_uiClient->saveDataToFileInDownloadsFolder(this, suggestedFilename, mimeType, originatingURLString, data); } -void WebPageProxy::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference& data) +void WebPageProxy::savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const IPC::DataReference& dataReference) { if (!suggestedFilename.endsWith(".pdf", false)) return; - RefPtr<WebData> webData = WebData::create(data.data(), data.size()); - - saveDataToFileInDownloadsFolder(suggestedFilename, "application/pdf", originatingURLString, webData.get()); -} - -void WebPageProxy::linkClicked(const String& url, const WebMouseEvent& event) -{ - m_process->send(Messages::WebPage::LinkClicked(url, event), m_pageID, 0); + saveDataToFileInDownloadsFolder(suggestedFilename, "application/pdf", originatingURLString, + API::Data::create(dataReference.data(), dataReference.size()).ptr()); } void WebPageProxy::setMinimumLayoutSize(const IntSize& minimumLayoutSize) @@ -4343,12 +5661,25 @@ void WebPageProxy::setMinimumLayoutSize(const IntSize& minimumLayoutSize) m_process->send(Messages::WebPage::SetMinimumLayoutSize(minimumLayoutSize), m_pageID, 0); m_drawingArea->minimumLayoutSizeDidChange(); -#if PLATFORM(MAC) +#if USE(APPKIT) if (m_minimumLayoutSize.width() <= 0) intrinsicContentSizeDidChange(IntSize(-1, -1)); #endif } +void WebPageProxy::setAutoSizingShouldExpandToViewHeight(bool shouldExpand) +{ + if (m_autoSizingShouldExpandToViewHeight == shouldExpand) + return; + + m_autoSizingShouldExpandToViewHeight = shouldExpand; + + if (!isValid()) + return; + + m_process->send(Messages::WebPage::SetAutoSizingShouldExpandToViewHeight(shouldExpand), m_pageID, 0); +} + #if PLATFORM(MAC) void WebPageProxy::substitutionsPanelIsShowing(bool& isShowing) @@ -4358,22 +5689,22 @@ void WebPageProxy::substitutionsPanelIsShowing(bool& isShowing) void WebPageProxy::showCorrectionPanel(int32_t panelType, const FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) { - m_pageClient->showCorrectionPanel((AlternativeTextType)panelType, boundingBoxOfReplacedString, replacedString, replacementString, alternativeReplacementStrings); + m_pageClient.showCorrectionPanel((AlternativeTextType)panelType, boundingBoxOfReplacedString, replacedString, replacementString, alternativeReplacementStrings); } void WebPageProxy::dismissCorrectionPanel(int32_t reason) { - m_pageClient->dismissCorrectionPanel((ReasonForDismissingAlternativeText)reason); + m_pageClient.dismissCorrectionPanel((ReasonForDismissingAlternativeText)reason); } void WebPageProxy::dismissCorrectionPanelSoon(int32_t reason, String& result) { - result = m_pageClient->dismissCorrectionPanelSoon((ReasonForDismissingAlternativeText)reason); + result = m_pageClient.dismissCorrectionPanelSoon((ReasonForDismissingAlternativeText)reason); } void WebPageProxy::recordAutocorrectionResponse(int32_t responseType, const String& replacedString, const String& replacementString) { - m_pageClient->recordAutocorrectionResponse((AutocorrectionResponseType)responseType, replacedString, replacementString); + m_pageClient.recordAutocorrectionResponse((AutocorrectionResponseType)responseType, replacedString, replacementString); } void WebPageProxy::handleAlternativeTextUIResult(const String& result) @@ -4385,26 +5716,26 @@ void WebPageProxy::handleAlternativeTextUIResult(const String& result) #if USE(DICTATION_ALTERNATIVES) void WebPageProxy::showDictationAlternativeUI(const WebCore::FloatRect& boundingBoxOfDictatedText, uint64_t dictationContext) { - m_pageClient->showDictationAlternativeUI(boundingBoxOfDictatedText, dictationContext); + m_pageClient.showDictationAlternativeUI(boundingBoxOfDictatedText, dictationContext); } void WebPageProxy::removeDictationAlternatives(uint64_t dictationContext) { - m_pageClient->removeDictationAlternatives(dictationContext); + m_pageClient.removeDictationAlternatives(dictationContext); } void WebPageProxy::dictationAlternatives(uint64_t dictationContext, Vector<String>& result) { - result = m_pageClient->dictationAlternatives(dictationContext); + result = m_pageClient.dictationAlternatives(dictationContext); } #endif #endif // PLATFORM(MAC) -#if USE(SOUP) -void WebPageProxy::didReceiveURIRequest(String uriString, uint64_t requestID) +#if PLATFORM(COCOA) +PassRefPtr<ViewSnapshot> WebPageProxy::takeViewSnapshot() { - m_process->context()->supplement<WebSoupRequestManagerProxy>()->didReceiveURIRequest(uriString, this, requestID); + return m_pageClient.takeViewSnapshot(); } #endif @@ -4415,7 +5746,7 @@ void WebPageProxy::setComposition(const String& text, Vector<CompositionUnderlin if (!isValid()) return; - process()->send(Messages::WebPage::SetComposition(text, underlines, selectionStart, selectionEnd, replacementRangeStart, replacementRangeEnd), m_pageID); + process().send(Messages::WebPage::SetComposition(text, underlines, selectionStart, selectionEnd, replacementRangeStart, replacementRangeEnd), m_pageID); } void WebPageProxy::confirmComposition(const String& compositionString, int64_t selectionStart, int64_t selectionLength) @@ -4423,7 +5754,7 @@ void WebPageProxy::confirmComposition(const String& compositionString, int64_t s if (!isValid()) return; - process()->send(Messages::WebPage::ConfirmComposition(compositionString, selectionStart, selectionLength), m_pageID); + process().send(Messages::WebPage::ConfirmComposition(compositionString, selectionStart, selectionLength), m_pageID); } void WebPageProxy::cancelComposition() @@ -4431,21 +5762,10 @@ void WebPageProxy::cancelComposition() if (!isValid()) return; - process()->send(Messages::WebPage::CancelComposition(), m_pageID); + process().send(Messages::WebPage::CancelComposition(), m_pageID); } #endif // PLATFORM(QT) || PLATFORM(GTK) -void WebPageProxy::setMainFrameInViewSourceMode(bool mainFrameInViewSourceMode) -{ - if (m_mainFrameInViewSourceMode == mainFrameInViewSourceMode) - return; - - m_mainFrameInViewSourceMode = mainFrameInViewSourceMode; - - if (isValid()) - m_process->send(Messages::WebPage::SetMainFrameInViewSourceMode(mainFrameInViewSourceMode), m_pageID); -} - void WebPageProxy::didSaveToPageCache() { m_process->didSaveToPageCache(); @@ -4462,4 +5782,436 @@ void WebPageProxy::setScrollPinningBehavior(ScrollPinningBehavior pinning) m_process->send(Messages::WebPage::SetScrollPinningBehavior(pinning), m_pageID); } +void WebPageProxy::setOverlayScrollbarStyle(WTF::Optional<WebCore::ScrollbarOverlayStyle> scrollbarStyle) +{ + if (!m_scrollbarOverlayStyle && !scrollbarStyle) + return; + + if ((m_scrollbarOverlayStyle && scrollbarStyle) && m_scrollbarOverlayStyle.value() == scrollbarStyle.value()) + return; + + m_scrollbarOverlayStyle = scrollbarStyle; + + WTF::Optional<uint32_t> scrollbarStyleForMessage; + if (scrollbarStyle) + scrollbarStyleForMessage = static_cast<ScrollbarOverlayStyle>(scrollbarStyle.value()); + + if (isValid()) + m_process->send(Messages::WebPage::SetScrollbarOverlayStyle(scrollbarStyleForMessage), m_pageID); +} + +#if ENABLE(SUBTLE_CRYPTO) +void WebPageProxy::wrapCryptoKey(const Vector<uint8_t>& key, bool& succeeded, Vector<uint8_t>& wrappedKey) +{ + PageClientProtector protector(m_pageClient); + + Vector<uint8_t> masterKey; + + if (m_navigationClient) { + if (RefPtr<API::Data> keyData = m_navigationClient->webCryptoMasterKey(*this)) + masterKey = keyData->dataReference().vector(); + } else if (RefPtr<API::Data> keyData = m_loaderClient->webCryptoMasterKey(*this)) + masterKey = keyData->dataReference().vector(); + else if (!getDefaultWebCryptoMasterKey(masterKey)) { + succeeded = false; + return; + } + + succeeded = wrapSerializedCryptoKey(masterKey, key, wrappedKey); +} + +void WebPageProxy::unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, bool& succeeded, Vector<uint8_t>& key) +{ + PageClientProtector protector(m_pageClient); + + Vector<uint8_t> masterKey; + + if (m_navigationClient) { + if (RefPtr<API::Data> keyData = m_navigationClient->webCryptoMasterKey(*this)) + masterKey = keyData->dataReference().vector(); + } else if (RefPtr<API::Data> keyData = m_loaderClient->webCryptoMasterKey(*this)) + masterKey = keyData->dataReference().vector(); + else if (!getDefaultWebCryptoMasterKey(masterKey)) { + succeeded = false; + return; + } + + succeeded = unwrapSerializedCryptoKey(masterKey, wrappedKey, key); +} +#endif + +void WebPageProxy::addMIMETypeWithCustomContentProvider(const String& mimeType) +{ + m_process->send(Messages::WebPage::AddMIMETypeWithCustomContentProvider(mimeType), m_pageID); +} + +#if PLATFORM(COCOA) + +void WebPageProxy::insertTextAsync(const String& text, const EditingRange& replacementRange, bool registerUndoGroup, EditingRangeIsRelativeTo editingRangeIsRelativeTo) +{ + if (!isValid()) + return; + + process().send(Messages::WebPage::InsertTextAsync(text, replacementRange, registerUndoGroup, static_cast<uint32_t>(editingRangeIsRelativeTo)), m_pageID); +} + +void WebPageProxy::getMarkedRangeAsync(std::function<void (EditingRange, CallbackBase::Error)> callbackFunction) +{ + if (!isValid()) { + callbackFunction(EditingRange(), CallbackBase::Error::Unknown); + return; + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + process().send(Messages::WebPage::GetMarkedRangeAsync(callbackID), m_pageID); +} + +void WebPageProxy::getSelectedRangeAsync(std::function<void (EditingRange, CallbackBase::Error)> callbackFunction) +{ + if (!isValid()) { + callbackFunction(EditingRange(), CallbackBase::Error::Unknown); + return; + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + process().send(Messages::WebPage::GetSelectedRangeAsync(callbackID), m_pageID); +} + +void WebPageProxy::characterIndexForPointAsync(const WebCore::IntPoint& point, std::function<void (uint64_t, CallbackBase::Error)> callbackFunction) +{ + if (!isValid()) { + callbackFunction(0, CallbackBase::Error::Unknown); + return; + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + process().send(Messages::WebPage::CharacterIndexForPointAsync(point, callbackID), m_pageID); +} + +void WebPageProxy::firstRectForCharacterRangeAsync(const EditingRange& range, std::function<void (const WebCore::IntRect&, const EditingRange&, CallbackBase::Error)> callbackFunction) +{ + if (!isValid()) { + callbackFunction(WebCore::IntRect(), EditingRange(), CallbackBase::Error::Unknown); + return; + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + process().send(Messages::WebPage::FirstRectForCharacterRangeAsync(range, callbackID), m_pageID); +} + +void WebPageProxy::setCompositionAsync(const String& text, Vector<CompositionUnderline> underlines, const EditingRange& selectionRange, const EditingRange& replacementRange) +{ + if (!isValid()) { + // If this fails, we should call -discardMarkedText on input context to notify the input method. + // This will happen naturally later, as part of reloading the page. + return; + } + + process().send(Messages::WebPage::SetCompositionAsync(text, underlines, selectionRange, replacementRange), m_pageID); +} + +void WebPageProxy::confirmCompositionAsync() +{ + if (!isValid()) + return; + + process().send(Messages::WebPage::ConfirmCompositionAsync(), m_pageID); +} + +void WebPageProxy::setScrollPerformanceDataCollectionEnabled(bool enabled) +{ + if (enabled == m_scrollPerformanceDataCollectionEnabled) + return; + + m_scrollPerformanceDataCollectionEnabled = enabled; + + if (m_scrollPerformanceDataCollectionEnabled && !m_scrollingPerformanceData) + m_scrollingPerformanceData = std::make_unique<RemoteLayerTreeScrollingPerformanceData>(downcast<RemoteLayerTreeDrawingAreaProxy>(*m_drawingArea)); + else if (!m_scrollPerformanceDataCollectionEnabled) + m_scrollingPerformanceData = nullptr; +} +#endif + +void WebPageProxy::takeSnapshot(IntRect rect, IntSize bitmapSize, SnapshotOptions options, std::function<void (const ShareableBitmap::Handle&, CallbackBase::Error)> callbackFunction) +{ + if (!isValid()) { + callbackFunction(ShareableBitmap::Handle(), CallbackBase::Error::Unknown); + return; + } + + uint64_t callbackID = m_callbacks.put(WTFMove(callbackFunction), m_process->throttler().backgroundActivityToken()); + m_process->send(Messages::WebPage::TakeSnapshot(rect, bitmapSize, options, callbackID), m_pageID); +} + +void WebPageProxy::navigationGestureDidBegin() +{ + PageClientProtector protector(m_pageClient); + + m_isShowingNavigationGestureSnapshot = true; + m_pageClient.navigationGestureDidBegin(); + + if (m_navigationClient) + m_navigationClient->didBeginNavigationGesture(*this); + else + m_loaderClient->navigationGestureDidBegin(*this); +} + +void WebPageProxy::navigationGestureWillEnd(bool willNavigate, WebBackForwardListItem& item) +{ + PageClientProtector protector(m_pageClient); + + m_pageClient.navigationGestureWillEnd(willNavigate, item); + + if (m_navigationClient) + m_navigationClient->willEndNavigationGesture(*this, willNavigate, item); + else + m_loaderClient->navigationGestureWillEnd(*this, willNavigate, item); +} + +void WebPageProxy::navigationGestureDidEnd(bool willNavigate, WebBackForwardListItem& item) +{ + PageClientProtector protector(m_pageClient); + + m_pageClient.navigationGestureDidEnd(willNavigate, item); + + if (m_navigationClient) + m_navigationClient->didEndNavigationGesture(*this, willNavigate, item); + else + m_loaderClient->navigationGestureDidEnd(*this, willNavigate, item); +} + +void WebPageProxy::navigationGestureDidEnd() +{ + PageClientProtector protector(m_pageClient); + + m_pageClient.navigationGestureDidEnd(); +} + +void WebPageProxy::willRecordNavigationSnapshot(WebBackForwardListItem& item) +{ + PageClientProtector protector(m_pageClient); + + m_pageClient.willRecordNavigationSnapshot(item); +} + +void WebPageProxy::navigationGestureSnapshotWasRemoved() +{ + m_isShowingNavigationGestureSnapshot = false; + + m_pageClient.didRemoveNavigationGestureSnapshot(); + + if (m_navigationClient) + m_navigationClient->didRemoveNavigationGestureSnapshot(*this); +} + +void WebPageProxy::isPlayingMediaDidChange(MediaProducer::MediaStateFlags state, uint64_t sourceElementID) +{ +#if ENABLE(MEDIA_SESSION) + WebMediaSessionFocusManager* focusManager = process().processPool().supplement<WebMediaSessionFocusManager>(); + ASSERT(focusManager); + focusManager->updatePlaybackAttributesFromMediaState(this, sourceElementID, state); +#endif + + if (state == m_mediaState) + return; + + MediaProducer::MediaStateFlags oldState = m_mediaState; + m_mediaState = state; + + if ((oldState & MediaProducer::IsPlayingAudio) == (m_mediaState & MediaProducer::IsPlayingAudio)) + return; + + m_uiClient->isPlayingAudioDidChange(*this); +} + +#if ENABLE(MEDIA_SESSION) +void WebPageProxy::hasMediaSessionWithActiveMediaElementsDidChange(bool state) +{ + m_hasMediaSessionWithActiveMediaElements = state; +} + +void WebPageProxy::mediaSessionMetadataDidChange(const WebCore::MediaSessionMetadata& metadata) +{ + Ref<WebMediaSessionMetadata> webMetadata = WebMediaSessionMetadata::create(metadata); + m_uiClient->mediaSessionMetadataDidChange(*this, webMetadata.ptr()); +} + +void WebPageProxy::focusedContentMediaElementDidChange(uint64_t elementID) +{ + WebMediaSessionFocusManager* focusManager = process().processPool().supplement<WebMediaSessionFocusManager>(); + ASSERT(focusManager); + focusManager->setFocusedMediaElement(*this, elementID); +} +#endif + +#if PLATFORM(MAC) +void WebPageProxy::removeNavigationGestureSnapshot() +{ + m_pageClient.removeNavigationGestureSnapshot(); +} + +void WebPageProxy::performImmediateActionHitTestAtLocation(FloatPoint point) +{ + m_process->send(Messages::WebPage::PerformImmediateActionHitTestAtLocation(point), m_pageID); +} + +void WebPageProxy::immediateActionDidUpdate() +{ + m_process->send(Messages::WebPage::ImmediateActionDidUpdate(), m_pageID); +} + +void WebPageProxy::immediateActionDidCancel() +{ + m_process->send(Messages::WebPage::ImmediateActionDidCancel(), m_pageID); +} + +void WebPageProxy::immediateActionDidComplete() +{ + m_process->send(Messages::WebPage::ImmediateActionDidComplete(), m_pageID); +} + +void WebPageProxy::didPerformImmediateActionHitTest(const WebHitTestResultData& result, bool contentPreventsDefault, const UserData& userData) +{ + m_pageClient.didPerformImmediateActionHitTest(result, contentPreventsDefault, m_process->transformHandlesToObjects(userData.object()).get()); +} + +void* WebPageProxy::immediateActionAnimationControllerForHitTestResult(RefPtr<API::HitTestResult> hitTestResult, uint64_t type, RefPtr<API::Object> userData) +{ + return m_pageClient.immediateActionAnimationControllerForHitTestResult(hitTestResult, type, userData); +} + +void WebPageProxy::installViewStateChangeCompletionHandler(void (^completionHandler)()) +{ + if (!isValid()) { + completionHandler(); + return; + } + + auto copiedCompletionHandler = Block_copy(completionHandler); + RefPtr<VoidCallback> voidCallback = VoidCallback::create([copiedCompletionHandler] (CallbackBase::Error) { + copiedCompletionHandler(); + Block_release(copiedCompletionHandler); + }, m_process->throttler().backgroundActivityToken()); + uint64_t callbackID = m_callbacks.put(voidCallback.release()); + m_nextViewStateChangeCallbacks.append(callbackID); +} + +void WebPageProxy::handleAcceptedCandidate(WebCore::TextCheckingResult acceptedCandidate) +{ + m_process->send(Messages::WebPage::HandleAcceptedCandidate(acceptedCandidate), m_pageID); +} + +void WebPageProxy::didHandleAcceptedCandidate() +{ + m_pageClient.didHandleAcceptedCandidate(); +} +#endif + +void WebPageProxy::imageOrMediaDocumentSizeChanged(const WebCore::IntSize& newSize) +{ + m_uiClient->imageOrMediaDocumentSizeChanged(newSize); +} + +void WebPageProxy::setShouldDispatchFakeMouseMoveEvents(bool shouldDispatchFakeMouseMoveEvents) +{ + m_process->send(Messages::WebPage::SetShouldDispatchFakeMouseMoveEvents(shouldDispatchFakeMouseMoveEvents), m_pageID); +} + +void WebPageProxy::handleAutoFillButtonClick(const UserData& userData) +{ + m_uiClient->didClickAutoFillButton(*this, m_process->transformHandlesToObjects(userData.object()).get()); +} + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) +void WebPageProxy::addPlaybackTargetPickerClient(uint64_t contextId) +{ + m_pageClient.mediaSessionManager().addPlaybackTargetPickerClient(*this, contextId); +} + +void WebPageProxy::removePlaybackTargetPickerClient(uint64_t contextId) +{ + m_pageClient.mediaSessionManager().removePlaybackTargetPickerClient(*this, contextId); +} + +void WebPageProxy::showPlaybackTargetPicker(uint64_t contextId, const WebCore::FloatRect& rect, bool hasVideo) +{ + m_pageClient.mediaSessionManager().showPlaybackTargetPicker(*this, contextId, m_pageClient.rootViewToScreen(IntRect(rect)), hasVideo); +} + +void WebPageProxy::playbackTargetPickerClientStateDidChange(uint64_t contextId, WebCore::MediaProducer::MediaStateFlags state) +{ + m_pageClient.mediaSessionManager().clientStateDidChange(*this, contextId, state); +} + +void WebPageProxy::setMockMediaPlaybackTargetPickerEnabled(bool enabled) +{ + m_pageClient.mediaSessionManager().setMockMediaPlaybackTargetPickerEnabled(enabled); +} + +void WebPageProxy::setMockMediaPlaybackTargetPickerState(const String& name, WebCore::MediaPlaybackTargetContext::State state) +{ + m_pageClient.mediaSessionManager().setMockMediaPlaybackTargetPickerState(name, state); +} + +void WebPageProxy::setPlaybackTarget(uint64_t contextId, Ref<MediaPlaybackTarget>&& target) +{ + if (!isValid()) + return; + + m_process->send(Messages::WebPage::PlaybackTargetSelected(contextId, target->targetContext()), m_pageID); +} + +void WebPageProxy::externalOutputDeviceAvailableDidChange(uint64_t contextId, bool available) +{ + if (!isValid()) + return; + + m_process->send(Messages::WebPage::PlaybackTargetAvailabilityDidChange(contextId, available), m_pageID); +} + +void WebPageProxy::setShouldPlayToPlaybackTarget(uint64_t contextId, bool shouldPlay) +{ + if (!isValid()) + return; + + m_process->send(Messages::WebPage::SetShouldPlayToPlaybackTarget(contextId, shouldPlay), m_pageID); +} +#endif + +void WebPageProxy::didChangeBackgroundColor() +{ + m_pageClient.didChangeBackgroundColor(); +} + +void WebPageProxy::clearWheelEventTestTrigger() +{ + if (!isValid()) + return; + + m_process->send(Messages::WebPage::ClearWheelEventTestTrigger(), m_pageID); +} + +void WebPageProxy::callAfterNextPresentationUpdate(std::function<void (CallbackBase::Error)> callback) +{ + m_drawingArea->dispatchAfterEnsuringDrawing(callback); +} + +void WebPageProxy::setShouldScaleViewToFitDocument(bool shouldScaleViewToFitDocument) +{ + if (m_shouldScaleViewToFitDocument == shouldScaleViewToFitDocument) + return; + + m_shouldScaleViewToFitDocument = shouldScaleViewToFitDocument; + + if (!isValid()) + return; + + m_process->send(Messages::WebPage::SetShouldScaleViewToFitDocument(shouldScaleViewToFitDocument), m_pageID); +} + +void WebPageProxy::didRestoreScrollPosition() +{ + m_pageClient.didRestoreScrollPosition(); +} + } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPageProxy.h b/Source/WebKit2/UIProcess/WebPageProxy.h index 80d1d28fd..8c9bad74d 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.h +++ b/Source/WebKit2/UIProcess/WebPageProxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. + * Copyright (C) 2010, 2011, 2014-2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,53 +27,68 @@ #define WebPageProxy_h #include "APIObject.h" +#include "APISession.h" +#include "AssistedNodeInformation.h" +#include "AutoCorrectionCallback.h" #include "Connection.h" +#include "ContextMenuContextData.h" +#include "DownloadID.h" #include "DragControllerAction.h" #include "DrawingAreaProxy.h" +#include "EditingRange.h" #include "EditorState.h" #include "GeolocationPermissionRequestManagerProxy.h" #include "LayerTreeContext.h" +#include "MessageSender.h" #include "NotificationPermissionRequestManagerProxy.h" +#include "PageLoadState.h" #include "PlatformProcessIdentifier.h" +#include "ProcessThrottler.h" #include "SandboxExtension.h" #include "ShareableBitmap.h" +#include "UserMediaPermissionRequestManagerProxy.h" +#include "VisibleContentRectUpdateInfo.h" #include "WKBase.h" #include "WKPagePrivate.h" #include "WebColorPicker.h" #include "WebContextMenuItemData.h" #include "WebCoreArgumentCoders.h" -#include "WebFindClient.h" -#include "WebFormClient.h" #include "WebFrameProxy.h" -#include "WebHistoryClient.h" -#include "WebHitTestResult.h" -#include "WebLoaderClient.h" -#include "WebPageContextMenuClient.h" +#include "WebPageCreationParameters.h" +#include "WebPageDiagnosticLoggingClient.h" +#include "WebPageInjectedBundleClient.h" +#include "WebPreferences.h" #include <WebCore/AlternativeTextClient.h> // FIXME: Needed by WebPageProxyMessages.h for DICTATION_ALTERNATIVES. #include "WebPageProxyMessages.h" -#include "WebPolicyClient.h" #include "WebPopupMenuProxy.h" -#include "WebUIClient.h" +#include "WebProcessLifetimeTracker.h" #include <WebCore/Color.h> #include <WebCore/DragActions.h> -#include <WebCore/DragSession.h> +#include <WebCore/FrameLoaderTypes.h> #include <WebCore/HitTestResult.h> +#include <WebCore/MediaProducer.h> #include <WebCore/Page.h> #include <WebCore/PlatformScreen.h> #include <WebCore/ScrollTypes.h> +#include <WebCore/SearchPopupMenu.h> #include <WebCore/TextChecking.h> +#include <WebCore/TextGranularity.h> +#include <WebCore/ViewState.h> +#include <WebCore/VisibleSelection.h> +#include <memory> #include <wtf/HashMap.h> #include <wtf/HashSet.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> #include <wtf/PassRefPtr.h> +#include <wtf/Ref.h> #include <wtf/RefPtr.h> #include <wtf/Vector.h> #include <wtf/text/WTFString.h> +OBJC_CLASS NSView; +OBJC_CLASS _WKRemoteObjectRegistry; + #if ENABLE(DRAG_SUPPORT) #include <WebCore/DragActions.h> -#include <WebCore/DragSession.h> #endif #if ENABLE(TOUCH_EVENTS) @@ -86,42 +101,85 @@ #include <Evas.h> #endif +#if PLATFORM(COCOA) +#include "LayerRepresentation.h" +#endif + +#if PLATFORM(MAC) +#include "AttributedString.h" +#endif + #if PLATFORM(QT) #include "QtNetworkRequestData.h" #endif -namespace CoreIPC { - class ArgumentDecoder; - class Connection; -} +#if PLATFORM(IOS) +#include "ProcessThrottler.h" +#endif + +#if PLATFORM(GTK) +#include "ArgumentCodersGtk.h" +#endif + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) +#include <WebCore/MediaPlaybackTargetPicker.h> +#include <WebCore/WebMediaSessionManagerClient.h> +#endif + +#if USE(APPLE_INTERNAL_SDK) +#include <WebKitAdditions/WebPageProxyIncludes.h> +#endif +#if ENABLE(MEDIA_SESSION) namespace WebCore { - class AuthenticationChallenge; - class Cursor; - class DragData; - class FloatRect; - class GraphicsLayer; - class IntSize; - class ProtectionSpace; - class SharedBuffer; - struct FileChooserSettings; - struct TextAlternativeWithRange; - struct TextCheckingResult; - struct ViewportAttributes; - struct WindowFeatures; +class MediaSessionMetadata; } +#endif #if PLATFORM(QT) class QQuickNetworkReply; #endif -#if USE(APPKIT) -#ifdef __OBJC__ -@class WKView; -#else -class WKView; -#endif -#endif +namespace API { +class ContextMenuClient; +class FindClient; +class FindMatchesClient; +class FormClient; +class HistoryClient; +class LoaderClient; +class Navigation; +class NavigationClient; +class PolicyClient; +class UIClient; +class URLRequest; +} + +namespace IPC { +class ArgumentDecoder; +class Connection; +} + +namespace WebCore { +class AuthenticationChallenge; +class Cursor; +class DragData; +class FloatRect; +class GraphicsLayer; +class IntSize; +class MediaConstraintsImpl; +class ProtectionSpace; +class RunLoopObserver; +class SharedBuffer; +class TextIndicator; +struct DictionaryPopupInfo; +struct ExceptionDetails; +struct FileChooserSettings; +struct SecurityOriginData; +struct TextAlternativeWithRange; +struct TextCheckingResult; +struct ViewportAttributes; +struct WindowFeatures; +} #if PLATFORM(GTK) typedef GtkWidget* PlatformWidget; @@ -129,48 +187,57 @@ typedef GtkWidget* PlatformWidget; namespace WebKit { +class CertificateInfo; +class NativeWebGestureEvent; class NativeWebKeyboardEvent; class NativeWebMouseEvent; class NativeWebWheelEvent; class PageClient; -class PlatformCertificateInfo; +class RemoteLayerTreeScrollingPerformanceData; +class RemoteLayerTreeTransaction; +class RemoteScrollingCoordinatorProxy; class StringPairVector; +class UserData; +class ViewSnapshot; +class VisitedLinkStore; class WebBackForwardList; class WebBackForwardListItem; -class WebColorPickerResultListenerProxy; class WebContextMenuProxy; -class WebData; class WebEditCommandProxy; class WebFullScreenManagerProxy; +class WebNavigationState; +class WebVideoFullscreenManagerProxy; class WebKeyboardEvent; class WebMouseEvent; class WebOpenPanelResultListenerProxy; class WebPageGroup; class WebProcessProxy; -class WebURLRequest; +class WebUserContentControllerProxy; class WebWheelEvent; +class WebsiteDataStore; struct AttributedString; struct ColorSpaceData; -struct DictionaryPopupInfo; +struct EditingRange; struct EditorState; struct PlatformPopupMenuData; struct PrintInfo; -struct WebPageCreationParameters; struct WebPopupItem; -#if ENABLE(GESTURE_EVENTS) -class WebGestureEvent; -#endif - #if ENABLE(VIBRATION) class WebVibrationProxy; #endif -typedef GenericCallback<WKStringRef, StringImpl*> StringCallback; -typedef GenericCallback<WKSerializedScriptValueRef, WebSerializedScriptValue*> ScriptValueCallback; +#if USE(QUICK_LOOK) +class QuickLookDocumentData; +#endif + +typedef GenericCallback<uint64_t> UnsignedCallback; +typedef GenericCallback<EditingRange> EditingRangeCallback; +typedef GenericCallback<const String&> StringCallback; +typedef GenericCallback<API::SerializedScriptValue*, bool, const WebCore::ExceptionDetails&> ScriptValueCallback; #if PLATFORM(GTK) -typedef GenericCallback<WKErrorRef> PrintFinishedCallback; +typedef GenericCallback<API::Error*> PrintFinishedCallback; #endif #if ENABLE(TOUCH_EVENTS) @@ -184,64 +251,48 @@ struct QueuedTouchEvents { }; #endif -// FIXME: Make a version of CallbackBase with three arguments, and define ValidateCommandCallback as a specialization. -class ValidateCommandCallback : public CallbackBase { -public: - typedef void (*CallbackFunction)(WKStringRef, bool, int32_t, WKErrorRef, void*); - - static PassRefPtr<ValidateCommandCallback> create(void* context, CallbackFunction callback) - { - return adoptRef(new ValidateCommandCallback(context, callback)); - } - - virtual ~ValidateCommandCallback() - { - ASSERT(!m_callback); - } - - void performCallbackWithReturnValue(StringImpl* returnValue1, bool returnValue2, int returnValue3) - { - ASSERT(m_callback); - - m_callback(toAPI(returnValue1), returnValue2, returnValue3, 0, context()); - - m_callback = 0; - } - - void invalidate() - { - ASSERT(m_callback); - - RefPtr<WebError> error = WebError::create(); - m_callback(0, 0, 0, toAPI(error.get()), context()); - - m_callback = 0; - } - -private: - - ValidateCommandCallback(void* context, CallbackFunction callback) - : CallbackBase(context) - , m_callback(callback) - { - } +typedef GenericCallback<const String&, bool, int32_t> ValidateCommandCallback; +typedef GenericCallback<const WebCore::IntRect&, const EditingRange&> RectForCharacterRangeCallback; - CallbackFunction m_callback; +#if PLATFORM(MAC) +typedef GenericCallback<const AttributedString&, const EditingRange&> AttributedStringForCharacterRangeCallback; +typedef GenericCallback<const String&, double, bool> FontAtSelectionCallback; +#endif + +#if PLATFORM(IOS) +typedef GenericCallback<const WebCore::IntPoint&, uint32_t, uint32_t, uint32_t> GestureCallback; +typedef GenericCallback<const WebCore::IntPoint&, uint32_t> TouchesCallback; +struct NodeAssistanceArguments { + AssistedNodeInformation m_nodeInformation; + bool m_userIsInteracting; + bool m_blurPreviousNode; + RefPtr<API::Object> m_userData; }; +#endif -class WebPageProxy - : public TypedAPIObject<APIObject::TypePage> +#if PLATFORM(COCOA) +typedef GenericCallback<const WebCore::MachSendRight&> MachSendRightCallback; +#endif + +class WebPageProxy : public API::ObjectImpl<API::Object::Type::Page> #if ENABLE(INPUT_TYPE_COLOR) , public WebColorPicker::Client #endif +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) + , public WebCore::WebMediaSessionManagerClient +#endif , public WebPopupMenuProxy::Client - , public CoreIPC::MessageReceiver { + , public IPC::MessageReceiver + , public IPC::MessageSender { public: - - static PassRefPtr<WebPageProxy> create(PageClient*, PassRefPtr<WebProcessProxy>, WebPageGroup*, uint64_t pageID); + static Ref<WebPageProxy> create(PageClient&, WebProcessProxy&, uint64_t pageID, Ref<API::PageConfiguration>&&); virtual ~WebPageProxy(); + const API::PageConfiguration& configuration() const; + uint64_t pageID() const { return m_pageID; } + WebCore::SessionID sessionID() const { return m_sessionID; } + void setSessionID(WebCore::SessionID); WebFrameProxy* mainFrame() const { return m_mainFrame.get(); } WebFrameProxy* focusedFrame() const { return m_focusedFrame.get(); } @@ -249,10 +300,34 @@ public: DrawingAreaProxy* drawingArea() const { return m_drawingArea.get(); } - WebBackForwardList* backForwardList() const { return m_backForwardList.get(); } + WebNavigationState& navigationState() { return *m_navigationState.get(); } + + WebsiteDataStore& websiteDataStore() { return m_websiteDataStore; } + +#if ENABLE(DATA_DETECTION) + NSArray *dataDetectionResults() { return m_dataDetectionResults.get(); } +#endif + +#if ENABLE(ASYNC_SCROLLING) + RemoteScrollingCoordinatorProxy* scrollingCoordinatorProxy() const { return m_scrollingCoordinatorProxy.get(); } +#endif + + WebBackForwardList& backForwardList() { return m_backForwardList; } + + bool addsVisitedLinks() const { return m_addsVisitedLinks; } + void setAddsVisitedLinks(bool addsVisitedLinks) { m_addsVisitedLinks = addsVisitedLinks; } + + void fullscreenMayReturnToInline(); + void didEnterFullscreen(); + void didExitFullscreen(); -#if ENABLE(INSPECTOR) WebInspectorProxy* inspector(); + +#if ENABLE(REMOTE_INSPECTOR) + bool allowsRemoteInspection() const { return m_allowsRemoteInspection; } + void setAllowsRemoteInspection(bool); + String remoteInspectionNameOverride() const { return m_remoteInspectionNameOverride; } + void setRemoteInspectionNameOverride(const String&); #endif #if ENABLE(VIBRATION) @@ -262,18 +337,37 @@ public: #if ENABLE(FULLSCREEN_API) WebFullScreenManagerProxy* fullScreenManager(); #endif +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) + RefPtr<WebVideoFullscreenManagerProxy> videoFullscreenManager(); +#endif + +#if PLATFORM(IOS) + bool allowsMediaDocumentInlinePlayback() const; + void setAllowsMediaDocumentInlinePlayback(bool); +#endif #if ENABLE(CONTEXT_MENUS) - void initializeContextMenuClient(const WKPageContextMenuClient*); -#endif - void initializeFindClient(const WKPageFindClient*); - void initializeFindMatchesClient(const WKPageFindMatchesClient*); - void initializeFormClient(const WKPageFormClient*); - void initializeLoaderClient(const WKPageLoaderClient*); - void initializePolicyClient(const WKPagePolicyClient*); - void initializeUIClient(const WKPageUIClient*); + API::ContextMenuClient& contextMenuClient() { return *m_contextMenuClient; } + void setContextMenuClient(std::unique_ptr<API::ContextMenuClient>); +#endif + API::FindClient& findClient() { return *m_findClient; } + void setFindClient(std::unique_ptr<API::FindClient>); + API::FindMatchesClient& findMatchesClient() { return *m_findMatchesClient; } + void setFindMatchesClient(std::unique_ptr<API::FindMatchesClient>); + API::DiagnosticLoggingClient& diagnosticLoggingClient() { return *m_diagnosticLoggingClient; } + void setDiagnosticLoggingClient(std::unique_ptr<API::DiagnosticLoggingClient>); + void setFormClient(std::unique_ptr<API::FormClient>); + void setNavigationClient(std::unique_ptr<API::NavigationClient>); + void setHistoryClient(std::unique_ptr<API::HistoryClient>); + void setLoaderClient(std::unique_ptr<API::LoaderClient>); + void setPolicyClient(std::unique_ptr<API::PolicyClient>); + void setInjectedBundleClient(const WKPageInjectedBundleClientBase*); + WebPageInjectedBundleClient* injectedBundleClient() { return m_injectedBundleClient.get(); } + + API::UIClient& uiClient() { return *m_uiClient; } + void setUIClient(std::unique_ptr<API::UIClient>); #if PLATFORM(EFL) - void initializeUIPopupMenuClient(const WKPageUIPopupMenuClient*); + void initializeUIPopupMenuClient(const WKPageUIPopupMenuClientBase*); #endif void initializeWebPage(); @@ -282,76 +376,79 @@ public: bool tryClose(); bool isClosed() const { return m_isClosed; } - void loadURL(const String&, APIObject* userData = 0); - void loadURLRequest(WebURLRequest*, APIObject* userData = 0); - void loadFile(const String& fileURL, const String& resourceDirectoryURL, APIObject* userData = 0); - void loadData(WebData*, const String& MIMEType, const String& encoding, const String& baseURL, APIObject* userData = 0); - void loadHTMLString(const String& htmlString, const String& baseURL, APIObject* userData = 0); - void loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, APIObject* userData = 0); - void loadPlainTextString(const String& string, APIObject* userData = 0); - void loadWebArchiveData(const WebData*, APIObject* userData = 0); + RefPtr<API::Navigation> loadRequest(const WebCore::ResourceRequest&, WebCore::ShouldOpenExternalURLsPolicy = WebCore::ShouldOpenExternalURLsPolicy::ShouldAllowExternalSchemes, API::Object* userData = nullptr); + RefPtr<API::Navigation> loadFile(const String& fileURL, const String& resourceDirectoryURL, API::Object* userData = nullptr); + RefPtr<API::Navigation> loadData(API::Data*, const String& MIMEType, const String& encoding, const String& baseURL, API::Object* userData = nullptr); + RefPtr<API::Navigation> loadHTMLString(const String& htmlString, const String& baseURL, API::Object* userData = nullptr); + void loadAlternateHTMLString(const String& htmlString, const String& baseURL, const String& unreachableURL, API::Object* userData = nullptr); + void loadPlainTextString(const String&, API::Object* userData = nullptr); + void loadWebArchiveData(API::Data*, API::Object* userData = nullptr); + void navigateToPDFLinkWithSimulatedClick(const String& url, WebCore::IntPoint documentPoint, WebCore::IntPoint screenPoint); void stopLoading(); - void reload(bool reloadFromOrigin); + RefPtr<API::Navigation> reload(bool reloadFromOrigin, bool contentBlockersEnabled); - void goForward(); - bool canGoForward() const; - void goBack(); - bool canGoBack() const; + RefPtr<API::Navigation> goForward(); + RefPtr<API::Navigation> goBack(); - void goToBackForwardItem(WebBackForwardListItem*); + RefPtr<API::Navigation> goToBackForwardItem(WebBackForwardListItem*); void tryRestoreScrollPosition(); - void didChangeBackForwardList(WebBackForwardListItem* addedItem, Vector<RefPtr<APIObject> >* removedItems); - void shouldGoToBackForwardListItem(uint64_t itemID, bool& shouldGoToBackForwardListItem); - void willGoToBackForwardListItem(uint64_t itemID, CoreIPC::MessageDecoder&); + void didChangeBackForwardList(WebBackForwardListItem* addedItem, Vector<RefPtr<WebBackForwardListItem>> removed); + void willGoToBackForwardListItem(uint64_t itemID, const UserData&); - String activeURL() const; - String provisionalURL() const; - String committedURL() const; + bool shouldKeepCurrentBackForwardListItemInList(WebBackForwardListItem*); bool willHandleHorizontalScrollEvents() const; - bool canShowMIMEType(const String& mimeType) const; + bool canShowMIMEType(const String& mimeType); bool drawsBackground() const { return m_drawsBackground; } void setDrawsBackground(bool); - bool drawsTransparentBackground() const { return m_drawsTransparentBackground; } - void setDrawsTransparentBackground(bool); + float topContentInset() const { return m_topContentInset; } + void setTopContentInset(float); WebCore::Color underlayColor() const { return m_underlayColor; } void setUnderlayColor(const WebCore::Color&); + // At this time, m_pageExtendedBackgroundColor can be set via pageExtendedBackgroundColorDidChange() which is a message + // from the UIProcess, or by didCommitLayerTree(). When PLATFORM(MAC) adopts UI side compositing, we should get rid of + // the message entirely. + WebCore::Color pageExtendedBackgroundColor() const { return m_pageExtendedBackgroundColor; } + void viewWillStartLiveResize(); void viewWillEndLiveResize(); - void setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent&); - void setWindowResizerSize(const WebCore::IntSize&); + void setInitialFocus(bool forward, bool isKeyboardEventValid, const WebKeyboardEvent&, std::function<void (CallbackBase::Error)>); void clearSelection(); + void restoreSelectionInFocusedEditableElement(); void setViewNeedsDisplay(const WebCore::IntRect&); void displayView(); bool canScrollView(); - void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); + void scrollView(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset); // FIXME: CoordinatedGraphics should use requestScroll(). + void requestScroll(const WebCore::FloatPoint& scrollPosition, const WebCore::IntPoint& scrollOrigin, bool isProgrammaticScroll); + + void setDelegatesScrolling(bool delegatesScrolling) { m_delegatesScrolling = delegatesScrolling; } + bool delegatesScrolling() const { return m_delegatesScrolling; } - enum { - ViewWindowIsActive = 1 << 0, - ViewIsFocused = 1 << 1, - ViewIsVisible = 1 << 2, - ViewIsInWindow = 1 << 3, - }; - typedef unsigned ViewStateFlags; - void viewStateDidChange(ViewStateFlags flags); - bool isInWindow() const { return m_isInWindow; } - void waitForDidUpdateInWindowState(); + enum class ViewStateChangeDispatchMode { Deferrable, Immediate }; + void viewStateDidChange(WebCore::ViewState::Flags mayHaveChanged, bool wantsSynchronousReply = false, ViewStateChangeDispatchMode = ViewStateChangeDispatchMode::Deferrable); + bool isInWindow() const { return m_viewState & WebCore::ViewState::IsInWindow; } + void waitForDidUpdateViewState(); + void didUpdateViewState() { m_waitingForDidUpdateViewState = false; } + + void layerHostingModeDidChange(); WebCore::IntSize viewSize() const; - bool isViewVisible() const { return m_isVisible; } + bool isViewVisible() const { return m_viewState & WebCore::ViewState::IsVisible; } bool isViewWindowActive() const; - void executeEditCommand(const String& commandName); - void validateCommand(const String& commandName, PassRefPtr<ValidateCommandCallback>); + void addMIMETypeWithCustomContentProvider(const String& mimeType); + + void executeEditCommand(const String& commandName, const String& argument = String()); + void validateCommand(const String& commandName, std::function<void (const String&, bool, int32_t, CallbackBase::Error)>); const EditorState& editorState() const { return m_editorState; } bool canDelete() const { return hasSelectedRange() && isContentEditable(); } @@ -360,8 +457,88 @@ public: bool maintainsInactiveSelection() const { return m_maintainsInactiveSelection; } void setMaintainsInactiveSelection(bool); -#if USE(TILED_BACKING_STORE) + void setEditable(bool); + bool isEditable() const { return m_isEditable; } + +#if PLATFORM(IOS) + void executeEditCommand(const String& commandName, std::function<void (CallbackBase::Error)>); + double displayedContentScale() const { return m_lastVisibleContentRectUpdate.scale(); } + const WebCore::FloatRect& exposedContentRect() const { return m_lastVisibleContentRectUpdate.exposedRect(); } + const WebCore::FloatRect& unobscuredContentRect() const { return m_lastVisibleContentRectUpdate.unobscuredRect(); } + + void updateVisibleContentRects(const WebCore::FloatRect& exposedRect, const WebCore::FloatRect& unobscuredRect, const WebCore::FloatRect& unobscuredRectInScrollViewCoordinates, const WebCore::FloatRect& customFixedPositionRect, double scale, bool inStableState, bool isChangingObscuredInsetsInteractively, bool allowShrinkToFit, double timestamp, double horizontalVelocity, double verticalVelocity, double scaleChangeRate); + void resendLastVisibleContentRects(); + + enum class UnobscuredRectConstraint { ConstrainedToDocumentRect, Unconstrained }; + WebCore::FloatRect computeCustomFixedPositionRect(const WebCore::FloatRect& unobscuredContentRect, double displayedContentScale, UnobscuredRectConstraint = UnobscuredRectConstraint::Unconstrained) const; + void overflowScrollViewWillStartPanGesture(); + void overflowScrollViewDidScroll(); + void overflowScrollWillStartScroll(); + void overflowScrollDidEndScroll(); + + void dynamicViewportSizeUpdate(const WebCore::FloatSize& minimumLayoutSize, const WebCore::FloatSize& maximumUnobscuredSize, const WebCore::FloatRect& targetExposedContentRect, const WebCore::FloatRect& targetUnobscuredRect, const WebCore::FloatRect& targetUnobscuredRectInScrollViewCoordinates, double targetScale, int32_t deviceOrientation); + void synchronizeDynamicViewportUpdate(); + + void setViewportConfigurationMinimumLayoutSize(const WebCore::FloatSize&); + void setMaximumUnobscuredSize(const WebCore::FloatSize&); + void setDeviceOrientation(int32_t); + int32_t deviceOrientation() const { return m_deviceOrientation; } + void willCommitLayerTree(uint64_t transactionID); + + void selectWithGesture(const WebCore::IntPoint, WebCore::TextGranularity, uint32_t gestureType, uint32_t gestureState, bool isInteractingWithAssistedNode, std::function<void (const WebCore::IntPoint&, uint32_t, uint32_t, uint32_t, CallbackBase::Error)>); + void updateSelectionWithTouches(const WebCore::IntPoint, uint32_t touches, bool baseIsStart, std::function<void (const WebCore::IntPoint&, uint32_t, CallbackBase::Error)>); + void selectWithTwoTouches(const WebCore::IntPoint from, const WebCore::IntPoint to, uint32_t gestureType, uint32_t gestureState, std::function<void (const WebCore::IntPoint&, uint32_t, uint32_t, uint32_t, CallbackBase::Error)>); + void updateBlockSelectionWithTouch(const WebCore::IntPoint, uint32_t touch, uint32_t handlePosition); + void extendSelection(WebCore::TextGranularity); + void selectWordBackward(); + void moveSelectionByOffset(int32_t offset, std::function<void (CallbackBase::Error)>); + void selectTextWithGranularityAtPoint(const WebCore::IntPoint, WebCore::TextGranularity, bool isInteractingWithAssistedNode, std::function<void (CallbackBase::Error)>); + void selectPositionAtPoint(const WebCore::IntPoint, bool isInteractingWithAssistedNode, std::function<void (CallbackBase::Error)>); + void selectPositionAtBoundaryWithDirection(const WebCore::IntPoint, WebCore::TextGranularity, WebCore::SelectionDirection, bool isInteractingWithAssistedNode, std::function<void (CallbackBase::Error)>); + void moveSelectionAtBoundaryWithDirection(WebCore::TextGranularity, WebCore::SelectionDirection, std::function<void(CallbackBase::Error)>); + void beginSelectionInDirection(WebCore::SelectionDirection, std::function<void (uint64_t, CallbackBase::Error)>); + void updateSelectionWithExtentPoint(const WebCore::IntPoint, bool isInteractingWithAssistedNode, std::function<void (uint64_t, CallbackBase::Error)>); + void updateSelectionWithExtentPointAndBoundary(const WebCore::IntPoint, WebCore::TextGranularity, bool isInteractingWithAssistedNode, std::function<void(uint64_t, CallbackBase::Error)>); + void requestAutocorrectionData(const String& textForAutocorrection, std::function<void (const Vector<WebCore::FloatRect>&, const String&, double, uint64_t, CallbackBase::Error)>); + void applyAutocorrection(const String& correction, const String& originalText, std::function<void (const String&, CallbackBase::Error)>); + bool applyAutocorrection(const String& correction, const String& originalText); + void requestAutocorrectionContext(std::function<void (const String&, const String&, const String&, const String&, uint64_t, uint64_t, CallbackBase::Error)>); + void getAutocorrectionContext(String& contextBefore, String& markedText, String& selectedText, String& contextAfter, uint64_t& location, uint64_t& length); + void requestDictationContext(std::function<void (const String&, const String&, const String&, CallbackBase::Error)>); + void replaceDictatedText(const String& oldText, const String& newText); + void replaceSelectedText(const String& oldText, const String& newText); + void didReceivePositionInformation(const InteractionInformationAtPosition&); + void getPositionInformation(const WebCore::IntPoint&, InteractionInformationAtPosition&); + void requestPositionInformation(const WebCore::IntPoint&); + void startInteractionWithElementAtPosition(const WebCore::IntPoint&); + void stopInteraction(); + void performActionOnElement(uint32_t action); + void saveImageToLibrary(const SharedMemory::Handle& imageHandle, uint64_t imageSize); + void didUpdateBlockSelectionWithTouch(uint32_t touch, uint32_t flags, float growThreshold, float shrinkThreshold); + void focusNextAssistedNode(bool isForward, std::function<void (CallbackBase::Error)>); + void setAssistedNodeValue(const String&); + void setAssistedNodeValueAsNumber(double); + void setAssistedNodeSelectedIndex(uint32_t index, bool allowMultipleSelection = false); + void applicationDidEnterBackground(); + void applicationWillEnterForeground(); + void applicationWillResignActive(); + void applicationDidBecomeActive(); + void zoomToRect(WebCore::FloatRect, double minimumScale, double maximumScale); + void commitPotentialTapFailed(); + void didNotHandleTapAsClick(const WebCore::IntPoint&); + void disableDoubleTapGesturesDuringTapIfNecessary(uint64_t requestID); + void didFinishDrawingPagesToPDF(const IPC::DataReference&); + void contentSizeCategoryDidChange(const String& contentSizeCategory); + void getLookupContextAtPoint(const WebCore::IntPoint&, std::function<void(const String&, CallbackBase::Error)>); +#endif +#if ENABLE(DATA_DETECTION) + void setDataDetectionResult(const DataDetectionResult&); +#endif + void didCommitLayerTree(const WebKit::RemoteLayerTreeTransaction&); + +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) void didRenderFrame(const WebCore::IntSize& contentsSize, const WebCore::IntRect& coveredRect); + void commitPageTransitionViewport(); #endif #if PLATFORM(QT) void registerApplicationScheme(const String& scheme); @@ -385,57 +562,78 @@ public: void setInputMethodState(bool enabled); #endif -#if PLATFORM(MAC) - void updateWindowIsVisible(bool windowIsVisible); +#if PLATFORM (GTK) && HAVE(GTK_GESTURES) + void getCenterForZoomGesture(const WebCore::IntPoint& centerInViewCoordinates, WebCore::IntPoint& center); +#endif + +#if PLATFORM(COCOA) void windowAndViewFramesChanged(const WebCore::FloatRect& viewFrameInWindowCoordinates, const WebCore::FloatPoint& accessibilityViewCoordinates); - void viewExposedRectChanged(const WebCore::FloatRect& exposedRect, bool); - void exposedRectChangedTimerFired(WebCore::Timer<WebPageProxy>*); void setMainFrameIsScrollable(bool); - void setComposition(const String& text, Vector<WebCore::CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd); - void confirmComposition(); - void cancelComposition(); - bool insertText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd); - bool insertDictatedText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd, const Vector<WebCore::TextAlternativeWithRange>& dictationAlternatives); - void getMarkedRange(uint64_t& location, uint64_t& length); - void getSelectedRange(uint64_t& location, uint64_t& length); - void getAttributedSubstringFromRange(uint64_t location, uint64_t length, AttributedString&); - uint64_t characterIndexForPoint(const WebCore::IntPoint); - WebCore::IntRect firstRectForCharacterRange(uint64_t, uint64_t); - bool executeKeypressCommands(const Vector<WebCore::KeypressCommand>&); - void sendComplexTextInputToPlugin(uint64_t pluginComplexTextInputIdentifier, const String& textInput); - CGContextRef containingWindowGraphicsContext(); bool shouldDelayWindowOrderingForEvent(const WebMouseEvent&); bool acceptsFirstMouse(int eventNumber, const WebMouseEvent&); - void setAcceleratedCompositingRootLayer(const WebCore::GraphicsLayer*); + void setAcceleratedCompositingRootLayer(LayerOrView*); + LayerOrView* acceleratedCompositingRootLayer() const; -#if USE(APPKIT) - WKView* wkView() const; - void intrinsicContentSizeDidChange(const WebCore::IntSize& intrinsicContentSize); -#endif + void insertTextAsync(const String& text, const EditingRange& replacementRange, bool registerUndoGroup = false, EditingRangeIsRelativeTo = EditingRangeIsRelativeTo::EditableRoot); + void getMarkedRangeAsync(std::function<void (EditingRange, CallbackBase::Error)>); + void getSelectedRangeAsync(std::function<void (EditingRange, CallbackBase::Error)>); + void characterIndexForPointAsync(const WebCore::IntPoint&, std::function<void (uint64_t, CallbackBase::Error)>); + void firstRectForCharacterRangeAsync(const EditingRange&, std::function<void (const WebCore::IntRect&, const EditingRange&, CallbackBase::Error)>); + void setCompositionAsync(const String& text, Vector<WebCore::CompositionUnderline> underlines, const EditingRange& selectionRange, const EditingRange& replacementRange); + void confirmCompositionAsync(); + + void setScrollPerformanceDataCollectionEnabled(bool); + bool scrollPerformanceDataCollectionEnabled() const { return m_scrollPerformanceDataCollectionEnabled; } + RemoteLayerTreeScrollingPerformanceData* scrollingPerformanceData() { return m_scrollingPerformanceData.get(); } +#endif // PLATFORM(COCOA) + +#if PLATFORM(MAC) + void insertDictatedTextAsync(const String& text, const EditingRange& replacementRange, const Vector<WebCore::TextAlternativeWithRange>& dictationAlternatives, bool registerUndoGroup); + void attributedSubstringForCharacterRangeAsync(const EditingRange&, std::function<void (const AttributedString&, const EditingRange&, CallbackBase::Error)>); + void setFont(const String& fontFamily, double fontSize, uint64_t fontTraits); + void fontAtSelection(std::function<void (const String&, double, bool, CallbackBase::Error)>); + + void startWindowDrag(); + NSWindow *platformWindow(); + +#if WK_API_ENABLED + NSView *inspectorAttachmentView(); + _WKRemoteObjectRegistry *remoteObjectRegistry(); #endif + + void intrinsicContentSizeDidChange(const WebCore::IntSize& intrinsicContentSize); + CGRect boundsOfLayerInLayerBackedWindowCoordinates(CALayer *) const; +#endif // PLATFORM(MAC) + #if PLATFORM(EFL) void handleInputMethodKeydown(bool& handled); void confirmComposition(const String&); void setComposition(const String&, Vector<WebCore::CompositionUnderline>&, int); void cancelComposition(); #endif + #if PLATFORM(GTK) PlatformWidget viewWidget(); -#endif -#if USE(TILED_BACKING_STORE) - void commitPageTransitionViewport(); + const WebCore::Color& backgroundColor() const { return m_backgroundColor; } + void setBackgroundColor(const WebCore::Color& color) { m_backgroundColor = color; } #endif void handleMouseEvent(const NativeWebMouseEvent&); void handleWheelEvent(const NativeWebWheelEvent&); void handleKeyboardEvent(const NativeWebKeyboardEvent&); -#if ENABLE(GESTURE_EVENTS) - void handleGestureEvent(const WebGestureEvent&); + +#if ENABLE(MAC_GESTURE_EVENTS) + void handleGestureEvent(const NativeWebGestureEvent&); #endif -#if ENABLE(TOUCH_EVENTS) + +#if ENABLE(IOS_TOUCH_EVENTS) + void handleTouchEventSynchronously(const NativeWebTouchEvent&); + void handleTouchEventAsynchronously(const NativeWebTouchEvent&); + +#elif ENABLE(TOUCH_EVENTS) void handleTouchEvent(const NativeWebTouchEvent&); #if PLATFORM(QT) void handlePotentialActivation(const WebCore::IntPoint& touchPoint, const WebCore::IntSize& touchArea); @@ -445,10 +643,8 @@ public: void scrollBy(WebCore::ScrollDirection, WebCore::ScrollGranularity); void centerSelectionInVisibleArea(); - String pageTitle() const; const String& toolTip() const { return m_toolTip; } - void setUserAgent(const String&); const String& userAgent() const { return m_userAgent; } void setApplicationNameForUserAgent(const String&); const String& applicationNameForUserAgent() const { return m_applicationNameForUserAgent; } @@ -468,27 +664,28 @@ public: void terminateProcess(); - typedef bool (*WebPageProxySessionStateFilterCallback)(WKPageRef, WKStringRef type, WKTypeRef object, void* context); - PassRefPtr<WebData> sessionStateData(WebPageProxySessionStateFilterCallback, void* context) const; - void restoreFromSessionStateData(WebData*); + SessionState sessionState(const std::function<bool (WebBackForwardListItem&)>& = nullptr) const; + RefPtr<API::Navigation> restoreFromSessionState(SessionState, bool navigate); bool supportsTextZoom() const; double textZoomFactor() const { return m_textZoomFactor; } void setTextZoomFactor(double); - double pageZoomFactor() const { return m_pageZoomFactor; } + double pageZoomFactor() const; void setPageZoomFactor(double); void setPageAndTextZoomFactors(double pageZoomFactor, double textZoomFactor); void scalePage(double scale, const WebCore::IntPoint& origin); - double pageScaleFactor() const { return m_pageScaleFactor; } - + void scalePageInViewCoordinates(double scale, const WebCore::IntPoint& centerInViewCoordinates); + double pageScaleFactor() const; + double viewScaleFactor() const { return m_viewScaleFactor; } + void scaleView(double scale); + void setShouldScaleViewToFitDocument(bool); + float deviceScaleFactor() const; void setIntrinsicDeviceScaleFactor(float); void setCustomDeviceScaleFactor(float); void windowScreenDidChange(PlatformDisplayID); - LayerHostingMode layerHostingMode() const { return m_layerHostingMode; } - void setUseFixedLayout(bool); void setFixedLayoutSize(const WebCore::IntSize&); bool useFixedLayout() const { return m_useFixedLayout; }; @@ -496,9 +693,6 @@ public: void listenForLayoutMilestones(WebCore::LayoutMilestones); - void setVisibilityState(WebCore::PageVisibilityState, bool isInitialState); - void didUpdateInWindowState() { m_waitingForDidUpdateInWindowState = false; } - bool hasHorizontalScrollbar() const { return m_mainFrameHasHorizontalScrollbar; } bool hasVerticalScrollbar() const { return m_mainFrameHasVerticalScrollbar; } @@ -510,10 +704,25 @@ public: bool isPinnedToTopSide() const { return m_mainFrameIsPinnedToTopSide; } bool isPinnedToBottomSide() const { return m_mainFrameIsPinnedToBottomSide; } - bool rubberBandsAtBottom() const { return m_rubberBandsAtBottom; } - void setRubberBandsAtBottom(bool); - bool rubberBandsAtTop() const { return m_rubberBandsAtTop; } + bool rubberBandsAtLeft() const; + void setRubberBandsAtLeft(bool); + bool rubberBandsAtRight() const; + void setRubberBandsAtRight(bool); + bool rubberBandsAtTop() const; void setRubberBandsAtTop(bool); + bool rubberBandsAtBottom() const; + void setRubberBandsAtBottom(bool); + + void setShouldUseImplicitRubberBandControl(bool shouldUseImplicitRubberBandControl) { m_shouldUseImplicitRubberBandControl = shouldUseImplicitRubberBandControl; } + bool shouldUseImplicitRubberBandControl() const { return m_shouldUseImplicitRubberBandControl; } + + void setEnableVerticalRubberBanding(bool); + bool verticalRubberBandingIsEnabled() const; + void setEnableHorizontalRubberBanding(bool); + bool horizontalRubberBandingIsEnabled() const; + + void setBackgroundExtendsBeyondPage(bool); + bool backgroundExtendsBeyondPage() const; void setPaginationMode(WebCore::Pagination::Mode); WebCore::Pagination::Mode paginationMode() const { return m_paginationMode; } @@ -523,25 +732,30 @@ public: double pageLength() const { return m_pageLength; } void setGapBetweenPages(double); double gapBetweenPages() const { return m_gapBetweenPages; } + void setPaginationLineGridEnabled(bool); + bool paginationLineGridEnabled() const { return m_paginationLineGridEnabled; } unsigned pageCount() const { return m_pageCount; } -#if PLATFORM(MAC) +#if PLATFORM(COCOA) // Called by the web process through a message. - void registerWebProcessAccessibilityToken(const CoreIPC::DataReference&); + void registerWebProcessAccessibilityToken(const IPC::DataReference&); // Called by the UI process when it is ready to send its tokens to the web process. - void registerUIProcessAccessibilityTokens(const CoreIPC::DataReference& elemenToken, const CoreIPC::DataReference& windowToken); + void registerUIProcessAccessibilityTokens(const IPC::DataReference& elemenToken, const IPC::DataReference& windowToken); bool readSelectionFromPasteboard(const String& pasteboardName); String stringSelectionForPasteboard(); - PassRefPtr<WebCore::SharedBuffer> dataSelectionForPasteboard(const String& pasteboardType); + RefPtr<WebCore::SharedBuffer> dataSelectionForPasteboard(const String& pasteboardType); void makeFirstResponder(); ColorSpaceData colorSpace(); #endif - void pageScaleFactorDidChange(double); - void pageZoomFactorDidChange(double); +#if ENABLE(SERVICE_CONTROLS) + void replaceSelectionWithPasteboardData(const Vector<String>& types, const IPC::DataReference&); +#endif - void setMemoryCacheClientCallsEnabled(bool); + void pageScaleFactorDidChange(double); + void pluginScaleFactorDidChange(double); + void pluginZoomFactorDidChange(double); // Find. void findString(const String&, FindOptions, unsigned maxMatchCount); @@ -552,23 +766,28 @@ public: void hideFindUI(); void countStringMatches(const String&, FindOptions, unsigned maxMatchCount); void didCountStringMatches(const String&, uint32_t matchCount); - void setFindIndicator(const WebCore::FloatRect& selectionRectInWindowCoordinates, const Vector<WebCore::FloatRect>& textRectsInSelectionRectCoordinates, float contentImageScaleFactor, const ShareableBitmap::Handle& contentImageHandle, bool fadeOut, bool animate); - void didFindString(const String&, uint32_t matchCount); + void setTextIndicator(const WebCore::TextIndicatorData&, uint64_t /* WebCore::TextIndicatorWindowLifetime */ lifetime = 0 /* Permanent */); + void setTextIndicatorAnimationProgress(float); + void clearTextIndicator(); + void didFindString(const String&, const Vector<WebCore::IntRect>&, uint32_t matchCount, int32_t matchIndex); void didFailToFindString(const String&); - void didFindStringMatches(const String&, Vector<Vector<WebCore::IntRect> > matchRects, int32_t firstIndexAfterSelection); + void didFindStringMatches(const String&, const Vector<Vector<WebCore::IntRect>>& matchRects, int32_t firstIndexAfterSelection); + + void getContentsAsString(std::function<void (const String&, CallbackBase::Error)>); + void getBytecodeProfile(std::function<void (const String&, CallbackBase::Error)>); + void isWebProcessResponsive(std::function<void (bool isWebProcessResponsive)>); - void getContentsAsString(PassRefPtr<StringCallback>); #if ENABLE(MHTML) - void getContentsAsMHTMLData(PassRefPtr<DataCallback>, bool useBinaryEncoding); -#endif - void getMainResourceDataOfFrame(WebFrameProxy*, PassRefPtr<DataCallback>); - void getResourceDataFromFrame(WebFrameProxy*, WebURL*, PassRefPtr<DataCallback>); - void getRenderTreeExternalRepresentation(PassRefPtr<StringCallback>); - void getSelectionOrContentsAsString(PassRefPtr<StringCallback>); - void getSelectionAsWebArchiveData(PassRefPtr<DataCallback>); - void getSourceForFrame(WebFrameProxy*, PassRefPtr<StringCallback>); - void getWebArchiveOfFrame(WebFrameProxy*, PassRefPtr<DataCallback>); - void runJavaScriptInMainFrame(const String&, PassRefPtr<ScriptValueCallback>); + void getContentsAsMHTMLData(std::function<void (API::Data*, CallbackBase::Error)>); +#endif + void getMainResourceDataOfFrame(WebFrameProxy*, std::function<void (API::Data*, CallbackBase::Error)>); + void getResourceDataFromFrame(WebFrameProxy*, API::URL*, std::function<void (API::Data*, CallbackBase::Error)>); + void getRenderTreeExternalRepresentation(std::function<void (const String&, CallbackBase::Error)>); + void getSelectionOrContentsAsString(std::function<void (const String&, CallbackBase::Error)>); + void getSelectionAsWebArchiveData(std::function<void (API::Data*, CallbackBase::Error)>); + void getSourceForFrame(WebFrameProxy*, std::function<void (const String&, CallbackBase::Error)>); + void getWebArchiveOfFrame(WebFrameProxy*, std::function<void (API::Data*, CallbackBase::Error)>); + void runJavaScriptInMainFrame(const String&, std::function<void (API::SerializedScriptValue*, bool hadException, const WebCore::ExceptionDetails&, CallbackBase::Error)> callbackFunction); void forceRepaint(PassRefPtr<VoidCallback>); float headerHeight(WebFrameProxy*); @@ -576,28 +795,32 @@ public: void drawHeader(WebFrameProxy*, const WebCore::FloatRect&); void drawFooter(WebFrameProxy*, const WebCore::FloatRect&); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) // Dictionary. void performDictionaryLookupAtLocation(const WebCore::FloatPoint&); + void performDictionaryLookupOfCurrentSelection(); #endif - void receivedPolicyDecision(WebCore::PolicyAction, WebFrameProxy*, uint64_t listenerID); + void receivedPolicyDecision(WebCore::PolicyAction, WebFrameProxy*, uint64_t listenerID, API::Navigation* navigationID); void backForwardRemovedItem(uint64_t itemID); #if ENABLE(DRAG_SUPPORT) // Drag and drop support. - void dragEntered(WebCore::DragData*, const String& dragStorageName = String()); - void dragUpdated(WebCore::DragData*, const String& dragStorageName = String()); - void dragExited(WebCore::DragData*, const String& dragStorageName = String()); - void performDrag(WebCore::DragData*, const String& dragStorageName, const SandboxExtension::Handle&, const SandboxExtension::HandleArray&); + void dragEntered(WebCore::DragData&, const String& dragStorageName = String()); + void dragUpdated(WebCore::DragData&, const String& dragStorageName = String()); + void dragExited(WebCore::DragData&, const String& dragStorageName = String()); + void performDragOperation(WebCore::DragData&, const String& dragStorageName, const SandboxExtension::Handle&, const SandboxExtension::HandleArray&); - void didPerformDragControllerAction(WebCore::DragSession); + void didPerformDragControllerAction(uint64_t dragOperation, bool mouseIsOverFileInput, unsigned numberOfItemsToBeAccepted); void dragEnded(const WebCore::IntPoint& clientPosition, const WebCore::IntPoint& globalPosition, uint64_t operation); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void setDragImage(const WebCore::IntPoint& clientPosition, const ShareableBitmap::Handle& dragImageHandle, bool isLinkDrag); - void setPromisedData(const String& pasteboardName, const SharedMemory::Handle& imageHandle, uint64_t imageSize, const String& filename, const String& extension, + void setPromisedDataForImage(const String& pasteboardName, const SharedMemory::Handle& imageHandle, uint64_t imageSize, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL, const SharedMemory::Handle& archiveHandle, uint64_t archiveSize); +#if ENABLE(ATTACHMENT_ELEMENT) + void setPromisedDataForAttachment(const String& pasteboardName, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL); +#endif #endif #if PLATFORM(QT) || PLATFORM(GTK) void startDrag(const WebCore::DragData&, const ShareableBitmap::Handle& dragImage); @@ -605,17 +828,20 @@ public: #endif void processDidBecomeUnresponsive(); - void interactionOccurredWhileProcessUnresponsive(); void processDidBecomeResponsive(); void processDidCrash(); + void willChangeProcessIsResponsive(); + void didChangeProcessIsResponsive(); + +#if PLATFORM(IOS) + void processWillBecomeSuspended(); + void processWillBecomeForeground(); +#endif -#if USE(ACCELERATED_COMPOSITING) virtual void enterAcceleratedCompositingMode(const LayerTreeContext&); virtual void exitAcceleratedCompositingMode(); virtual void updateAcceleratedCompositingMode(const LayerTreeContext&); -#endif - - void didDraw(); + void willEnterAcceleratedCompositingMode(); enum UndoOrRedo { Undo, Redo }; void addEditCommand(WebEditCommandProxy*); @@ -623,26 +849,34 @@ public: bool isValidEditCommand(WebEditCommandProxy*); void registerEditCommand(PassRefPtr<WebEditCommandProxy>, UndoOrRedo); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void registerKeypressCommandName(const String& name) { m_knownKeypressCommandNames.add(name); } bool isValidKeypressCommandName(const String& name) const { return m_knownKeypressCommandNames.contains(name); } #endif - WebProcessProxy* process() const; + WebProcessProxy& process() { return m_process; } PlatformProcessIdentifier processIdentifier() const; - WebPageGroup* pageGroup() const { return m_pageGroup.get(); } + WebPreferences& preferences() { return m_preferences; } + void setPreferences(WebPreferences&); - bool isValid() const; + WebPageGroup& pageGroup() { return m_pageGroup; } - PassRefPtr<ImmutableArray> relatedPages() const; + bool isValid() const; const String& urlAtProcessExit() const { return m_urlAtProcessExit; } - WebFrameProxy::LoadState loadStateAtProcessExit() const { return m_loadStateAtProcessExit; } + FrameLoadState::LoadState loadStateAtProcessExit() const { return m_loadStateAtProcessExit; } #if ENABLE(DRAG_SUPPORT) - WebCore::DragSession dragSession() const { return m_currentDragSession; } - void resetDragOperation() { m_currentDragSession = WebCore::DragSession(); } + WebCore::DragOperation currentDragOperation() const { return m_currentDragOperation; } + bool currentDragIsOverFileInput() const { return m_currentDragIsOverFileInput; } + unsigned currentDragNumberOfFilesToBeAccepted() const { return m_currentDragNumberOfFilesToBeAccepted; } + void resetCurrentDragInformation() + { + m_currentDragOperation = WebCore::DragOperationNone; + m_currentDragIsOverFileInput = false; + m_currentDragNumberOfFilesToBeAccepted = 0; + } #endif void preferencesDidChange(); @@ -653,28 +887,29 @@ public: #endif // Called by the WebOpenPanelResultListenerProxy. +#if PLATFORM(IOS) + void didChooseFilesForOpenPanelWithDisplayStringAndIcon(const Vector<String>&, const String& displayString, const API::Data* iconData); +#endif void didChooseFilesForOpenPanel(const Vector<String>&); void didCancelForOpenPanel(); - WebPageCreationParameters creationParameters() const; + WebPageCreationParameters creationParameters(); -#if USE(COORDINATED_GRAPHICS) +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) void findZoomableAreaForPoint(const WebCore::IntPoint&, const WebCore::IntSize&); #endif -#if PLATFORM(QT) || PLATFORM(EFL) || PLATFORM(GTK) void handleDownloadRequest(DownloadProxy*); -#endif - void advanceToNextMisspelling(bool startBeforeSelection) const; - void changeSpellingToWord(const String& word) const; + void advanceToNextMisspelling(bool startBeforeSelection); + void changeSpellingToWord(const String& word); #if USE(APPKIT) void uppercaseWord(); void lowercaseWord(); void capitalizeWord(); #endif -#if PLATFORM(MAC) +#if PLATFORM(COCOA) bool isSmartInsertDeleteEnabled() const { return m_isSmartInsertDeleteEnabled; } void setSmartInsertDeleteEnabled(bool); #endif @@ -689,158 +924,290 @@ public: void beginPrinting(WebFrameProxy*, const PrintInfo&); void endPrinting(); void computePagesForPrinting(WebFrameProxy*, const PrintInfo&, PassRefPtr<ComputedPagesCallback>); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void drawRectToImage(WebFrameProxy*, const PrintInfo&, const WebCore::IntRect&, const WebCore::IntSize&, PassRefPtr<ImageCallback>); void drawPagesToPDF(WebFrameProxy*, const PrintInfo&, uint32_t first, uint32_t count, PassRefPtr<DataCallback>); #elif PLATFORM(GTK) void drawPagesForPrinting(WebFrameProxy*, const PrintInfo&, PassRefPtr<PrintFinishedCallback>); #endif - const String& pendingAPIRequestURL() const { return m_pendingAPIRequestURL; } - - void flashBackingStoreUpdates(const Vector<WebCore::IntRect>& updateRects); + PageLoadState& pageLoadState() { return m_pageLoadState; } -#if PLATFORM(MAC) +#if PLATFORM(COCOA) void handleAlternativeTextUIResult(const String& result); #endif - static void setDebugPaintFlags(WKPageDebugPaintFlags flags) { s_debugPaintFlags = flags; } - static WKPageDebugPaintFlags debugPaintFlags() { return s_debugPaintFlags; } - - // Color to be used with kWKDebugFlashViewUpdates. - static WebCore::Color viewUpdatesFlashColor(); - - // Color to be used with kWKDebugFlashBackingStoreUpdates. - static WebCore::Color backingStoreUpdatesFlashColor(); - - void saveDataToFileInDownloadsFolder(const String& suggestedFilename, const String& mimeType, const String& originatingURLString, WebData*); - void savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference&); -#if PLATFORM(MAC) + void saveDataToFileInDownloadsFolder(const String& suggestedFilename, const String& mimeType, const String& originatingURLString, API::Data*); + void savePDFToFileInDownloadsFolder(const String& suggestedFilename, const String& originatingURLString, const IPC::DataReference&); +#if PLATFORM(COCOA) void savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID); - void savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference&, const String& pdfUUID); + void savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const IPC::DataReference&, const String& pdfUUID); void openPDFFromTemporaryFolderWithNativeApplication(const String& pdfUUID); #endif - void linkClicked(const String&, const WebMouseEvent&); - WebCore::IntRect visibleScrollerThumbRect() const { return m_visibleScrollerThumbRect; } uint64_t renderTreeSize() const { return m_renderTreeSize; } - void setShouldSendEventsSynchronously(bool sync) { m_shouldSendEventsSynchronously = sync; }; - void printMainFrame(); void setMediaVolume(float); + void setMuted(bool); void setMayStartMediaWhenInWindow(bool); + bool mayStartMediaWhenInWindow() const { return m_mayStartMediaWhenInWindow; } + +#if ENABLE(MEDIA_SESSION) + bool hasMediaSessionWithActiveMediaElements() const { return m_hasMediaSessionWithActiveMediaElements; } + void handleMediaEvent(WebCore::MediaEventType); + void setVolumeOfMediaElement(double, uint64_t); +#endif // WebPopupMenuProxy::Client - virtual NativeWebMouseEvent* currentlyProcessedMouseDownEvent(); - -#if PLATFORM(GTK) && USE(TEXTURE_MAPPER_GL) - void setAcceleratedCompositingWindowId(uint64_t nativeWindowId); -#endif + virtual NativeWebMouseEvent* currentlyProcessedMouseDownEvent() override; - void setSuppressVisibilityUpdates(bool flag) { m_suppressVisibilityUpdates = flag; } + void setSuppressVisibilityUpdates(bool flag); bool suppressVisibilityUpdates() { return m_suppressVisibilityUpdates; } - void postMessageToInjectedBundle(const String& messageName, APIObject* messageBody); +#if PLATFORM(IOS) + void willStartUserTriggeredZooming(); -#if ENABLE(INPUT_TYPE_COLOR) - void setColorChooserColor(const WebCore::Color&); - void endColorChooser(); + void potentialTapAtPosition(const WebCore::FloatPoint&, uint64_t& requestID); + void commitPotentialTap(); + void cancelPotentialTap(); + void tapHighlightAtPosition(const WebCore::FloatPoint&, uint64_t& requestID); + void handleTap(const WebCore::FloatPoint&); + + void inspectorNodeSearchMovedToPosition(const WebCore::FloatPoint&); + void inspectorNodeSearchEndedAtPosition(const WebCore::FloatPoint&); + + void blurAssistedNode(); #endif - const WebLoaderClient& loaderClient() { return m_loaderClient; } + void postMessageToInjectedBundle(const String& messageName, API::Object* messageBody); + +#if ENABLE(INPUT_TYPE_COLOR) + void setColorPickerColor(const WebCore::Color&); + void endColorPicker(); +#endif WebCore::IntSize minimumLayoutSize() const { return m_minimumLayoutSize; } void setMinimumLayoutSize(const WebCore::IntSize&); - bool mainFrameInViewSourceMode() const { return m_mainFrameInViewSourceMode; } - void setMainFrameInViewSourceMode(bool); + bool autoSizingShouldExpandToViewHeight() const { return m_autoSizingShouldExpandToViewHeight; } + void setAutoSizingShouldExpandToViewHeight(bool); void didReceiveAuthenticationChallengeProxy(uint64_t frameID, PassRefPtr<AuthenticationChallengeProxy>); int64_t spellDocumentTag(); - void didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>&) const; - void didCancelCheckingText(uint64_t requestID) const; + void didFinishCheckingText(uint64_t requestID, const Vector<WebCore::TextCheckingResult>&); + void didCancelCheckingText(uint64_t requestID); + + void connectionWillOpen(IPC::Connection&); + void webProcessWillShutDown(); - void connectionWillOpen(CoreIPC::Connection*); - void connectionWillClose(CoreIPC::Connection*); + void processDidFinishLaunching(); void didSaveToPageCache(); void setScrollPinningBehavior(WebCore::ScrollPinningBehavior); - WebCore::ScrollPinningBehavior scrollPinningBehavior() { return m_scrollPinningBehavior; } - + WebCore::ScrollPinningBehavior scrollPinningBehavior() const { return m_scrollPinningBehavior; } + + void setOverlayScrollbarStyle(WTF::Optional<WebCore::ScrollbarOverlayStyle>); + WTF::Optional<WebCore::ScrollbarOverlayStyle> overlayScrollbarStyle() const { return m_scrollbarOverlayStyle; } + + bool shouldRecordNavigationSnapshots() const { return m_shouldRecordNavigationSnapshots; } + void setShouldRecordNavigationSnapshots(bool shouldRecordSnapshots) { m_shouldRecordNavigationSnapshots = shouldRecordSnapshots; } + void recordNavigationSnapshot(); + void recordNavigationSnapshot(WebBackForwardListItem&); + +#if PLATFORM(COCOA) + PassRefPtr<ViewSnapshot> takeViewSnapshot(); +#endif + +#if ENABLE(SUBTLE_CRYPTO) + void wrapCryptoKey(const Vector<uint8_t>&, bool& succeeded, Vector<uint8_t>&); + void unwrapCryptoKey(const Vector<uint8_t>&, bool& succeeded, Vector<uint8_t>&); +#endif + + void takeSnapshot(WebCore::IntRect, WebCore::IntSize bitmapSize, SnapshotOptions, std::function<void (const ShareableBitmap::Handle&, CallbackBase::Error)>); + + void navigationGestureDidBegin(); + void navigationGestureWillEnd(bool willNavigate, WebBackForwardListItem&); + void navigationGestureDidEnd(bool willNavigate, WebBackForwardListItem&); + void navigationGestureDidEnd(); + void navigationGestureSnapshotWasRemoved(); + void willRecordNavigationSnapshot(WebBackForwardListItem&); + + bool isShowingNavigationGestureSnapshot() const { return m_isShowingNavigationGestureSnapshot; } + + bool isPlayingAudio() const { return !!(m_mediaState & WebCore::MediaProducer::IsPlayingAudio); } + void isPlayingMediaDidChange(WebCore::MediaProducer::MediaStateFlags, uint64_t); + +#if ENABLE(MEDIA_SESSION) + void hasMediaSessionWithActiveMediaElementsDidChange(bool); + void mediaSessionMetadataDidChange(const WebCore::MediaSessionMetadata&); + void focusedContentMediaElementDidChange(uint64_t); +#endif + +#if PLATFORM(MAC) + void removeNavigationGestureSnapshot(); + + API::HitTestResult* lastMouseMoveHitTestResult() const { return m_lastMouseMoveHitTestResult.get(); } + void performImmediateActionHitTestAtLocation(WebCore::FloatPoint); + + void immediateActionDidUpdate(); + void immediateActionDidCancel(); + void immediateActionDidComplete(); + + void* immediateActionAnimationControllerForHitTestResult(RefPtr<API::HitTestResult>, uint64_t, RefPtr<API::Object>); + + void installViewStateChangeCompletionHandler(void(^completionHandler)()); + + void handleAcceptedCandidate(WebCore::TextCheckingResult); + void didHandleAcceptedCandidate(); +#endif + +#if PLATFORM(EFL) && HAVE(ACCESSIBILITY) && defined(HAVE_ECORE_X) + bool accessibilityObjectReadByPoint(const WebCore::IntPoint&); + bool accessibilityObjectReadPrevious(); + bool accessibilityObjectReadNext(); +#endif + +#if USE(UNIFIED_TEXT_CHECKING) + void checkTextOfParagraph(const String& text, uint64_t checkingTypes, Vector<WebCore::TextCheckingResult>& results); +#endif + void getGuessesForWord(const String& word, const String& context, Vector<String>& guesses); + + void setShouldDispatchFakeMouseMoveEvents(bool); + + // Diagnostic messages logging. + void logDiagnosticMessage(const String& message, const String& description, bool shouldSample); + void logDiagnosticMessageWithResult(const String& message, const String& description, uint32_t result, bool shouldSample); + void logDiagnosticMessageWithValue(const String& message, const String& description, const String& value, bool shouldSample); + void logSampledDiagnosticMessage(const String& message, const String& description); + void logSampledDiagnosticMessageWithResult(const String& message, const String& description, uint32_t result); + void logSampledDiagnosticMessageWithValue(const String& message, const String& description, const String& value); + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) + void addPlaybackTargetPickerClient(uint64_t); + void removePlaybackTargetPickerClient(uint64_t); + void showPlaybackTargetPicker(uint64_t, const WebCore::FloatRect&, bool hasVideo); + void playbackTargetPickerClientStateDidChange(uint64_t, WebCore::MediaProducer::MediaStateFlags); + void setMockMediaPlaybackTargetPickerEnabled(bool); + void setMockMediaPlaybackTargetPickerState(const String&, WebCore::MediaPlaybackTargetContext::State); + + // WebMediaSessionManagerClient + virtual void setPlaybackTarget(uint64_t, Ref<WebCore::MediaPlaybackTarget>&&) override; + virtual void externalOutputDeviceAvailableDidChange(uint64_t, bool) override; + virtual void setShouldPlayToPlaybackTarget(uint64_t, bool) override; +#endif + + void didChangeBackgroundColor(); + void didLayoutForCustomContentProvider(); + + // For testing + void clearWheelEventTestTrigger(); + void callAfterNextPresentationUpdate(std::function<void (CallbackBase::Error)>); + + void didLayout(uint32_t layoutMilestones); + + void didRestoreScrollPosition(); + private: - WebPageProxy(PageClient*, PassRefPtr<WebProcessProxy>, WebPageGroup*, uint64_t pageID); + WebPageProxy(PageClient&, WebProcessProxy&, uint64_t pageID, Ref<API::PageConfiguration>&&); + void platformInitialize(); + + void updateViewState(WebCore::ViewState::Flags flagsToUpdate = WebCore::ViewState::AllFlags); + void updateActivityToken(); + void updateProccessSuppressionState(); + enum class ResetStateReason { + PageInvalidated, + WebProcessExited, + }; + void resetState(ResetStateReason); void resetStateAfterProcessExited(); - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; + void setUserAgent(const String&); + + // IPC::MessageReceiver + // Implemented in generated WebPageProxyMessageReceiver.cpp + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; + + // IPC::MessageSender + virtual bool sendMessage(std::unique_ptr<IPC::MessageEncoder>, unsigned messageSendFlags) override; + virtual IPC::Connection* messageSenderConnection() override; + virtual uint64_t messageSenderDestinationID() override; // WebPopupMenuProxy::Client - virtual void valueChangedForPopupMenu(WebPopupMenuProxy*, int32_t newSelectedIndex); - virtual void setTextFromItemForPopupMenu(WebPopupMenuProxy*, int32_t index); + virtual void valueChangedForPopupMenu(WebPopupMenuProxy*, int32_t newSelectedIndex) override; + virtual void setTextFromItemForPopupMenu(WebPopupMenuProxy*, int32_t index) override; #if PLATFORM(GTK) - virtual void failedToShowPopupMenu(); + virtual void failedToShowPopupMenu() override; #endif #if PLATFORM(QT) virtual void changeSelectedIndex(int32_t newSelectedIndex); virtual void closePopupMenu(); #endif - // Implemented in generated WebPageProxyMessageReceiver.cpp - void didReceiveWebPageProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - void didReceiveSyncWebPageProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); - void didCreateMainFrame(uint64_t frameID); void didCreateSubframe(uint64_t frameID); - void didStartProvisionalLoadForFrame(uint64_t frameID, const String& url, const String& unreachableURL, CoreIPC::MessageDecoder&); - void didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, const String&, CoreIPC::MessageDecoder&); - void didFailProvisionalLoadForFrame(uint64_t frameID, const WebCore::ResourceError&, CoreIPC::MessageDecoder&); - void didCommitLoadForFrame(uint64_t frameID, const String& mimeType, uint32_t frameLoadType, const PlatformCertificateInfo&, CoreIPC::MessageDecoder&); - void didFinishDocumentLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); - void didFinishLoadForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); - void didFailLoadForFrame(uint64_t frameID, const WebCore::ResourceError&, CoreIPC::MessageDecoder&); - void didSameDocumentNavigationForFrame(uint64_t frameID, uint32_t sameDocumentNavigationType, const String&, CoreIPC::MessageDecoder&); - void didReceiveTitleForFrame(uint64_t frameID, const String&, CoreIPC::MessageDecoder&); - void didFirstLayoutForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); - void didFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); - void didNewFirstVisuallyNonEmptyLayout(CoreIPC::MessageDecoder&); - void didLayout(uint32_t layoutMilestones, CoreIPC::MessageDecoder&); - void didRemoveFrameFromHierarchy(uint64_t frameID, CoreIPC::MessageDecoder&); - void didDisplayInsecureContentForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); - void didRunInsecureContentForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); - void didDetectXSSForFrame(uint64_t frameID, CoreIPC::MessageDecoder&); + void didStartProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& url, const String& unreachableURL, const UserData&); + void didReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, const String&, const UserData&); + void didChangeProvisionalURLForFrame(uint64_t frameID, uint64_t navigationID, const String& url); + void didFailProvisionalLoadForFrame(uint64_t frameID, const WebCore::SecurityOriginData& frameSecurityOrigin, uint64_t navigationID, const String& provisionalURL, const WebCore::ResourceError&, const UserData&); + void didCommitLoadForFrame(uint64_t frameID, uint64_t navigationID, const String& mimeType, bool frameHasCustomContentProvider, bool mainFramePluginHandlesPageScaleGesture, uint32_t frameLoadType, const WebCore::CertificateInfo&, bool containsPluginDocument, const UserData&); + void didFinishDocumentLoadForFrame(uint64_t frameID, uint64_t navigationID, const UserData&); + void didFinishLoadForFrame(uint64_t frameID, uint64_t navigationID, const UserData&); + void didFailLoadForFrame(uint64_t frameID, uint64_t navigationID, const WebCore::ResourceError&, const UserData&); + void didSameDocumentNavigationForFrame(uint64_t frameID, uint64_t navigationID, uint32_t sameDocumentNavigationType, const String&, const UserData&); + void didReceiveTitleForFrame(uint64_t frameID, const String&, const UserData&); + void didFirstLayoutForFrame(uint64_t frameID, const UserData&); + void didFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, const UserData&); + void didDisplayInsecureContentForFrame(uint64_t frameID, const UserData&); + void didRunInsecureContentForFrame(uint64_t frameID, const UserData&); + void didDetectXSSForFrame(uint64_t frameID, const UserData&); void frameDidBecomeFrameSet(uint64_t frameID, bool); void didStartProgress(); void didChangeProgress(double); void didFinishProgress(); + void setNetworkRequestsInProgress(bool); + + void didDestroyNavigation(uint64_t navigationID); - void decidePolicyForNavigationAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID); - void decidePolicyForNewWindowAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, const WebCore::ResourceRequest&, const String& frameName, uint64_t listenerID, CoreIPC::MessageDecoder&); - void decidePolicyForResponse(uint64_t frameID, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&); - void decidePolicyForResponseSync(uint64_t frameID, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, uint64_t listenerID, CoreIPC::MessageDecoder&, bool& receivedPolicyAction, uint64_t& policyAction, uint64_t& downloadID); - void unableToImplementPolicy(uint64_t frameID, const WebCore::ResourceError&, CoreIPC::MessageDecoder&); + void decidePolicyForNavigationAction(uint64_t frameID, const WebCore::SecurityOriginData& frameSecurityOrigin, uint64_t navigationID, const NavigationActionData&, uint64_t originatingFrameID, const WebCore::SecurityOriginData& originatingFrameSecurityOrigin, const WebCore::ResourceRequest& originalRequest, const WebCore::ResourceRequest&, uint64_t listenerID, const UserData&, bool& receivedPolicyAction, uint64_t& newNavigationID, uint64_t& policyAction, DownloadID&); + void decidePolicyForNewWindowAction(uint64_t frameID, const WebCore::SecurityOriginData& frameSecurityOrigin, const NavigationActionData&, const WebCore::ResourceRequest&, const String& frameName, uint64_t listenerID, const UserData&); + void decidePolicyForResponse(uint64_t frameID, const WebCore::SecurityOriginData& frameSecurityOrigin, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, bool canShowMIMEType, uint64_t listenerID, const UserData&); + void decidePolicyForResponseSync(uint64_t frameID, const WebCore::SecurityOriginData& frameSecurityOrigin, const WebCore::ResourceResponse&, const WebCore::ResourceRequest&, bool canShowMIMEType, uint64_t listenerID, const UserData&, bool& receivedPolicyAction, uint64_t& policyAction, DownloadID&); + void unableToImplementPolicy(uint64_t frameID, const WebCore::ResourceError&, const UserData&); - void willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String> >& textFieldValues, uint64_t listenerID, CoreIPC::MessageDecoder&); + void willSubmitForm(uint64_t frameID, uint64_t sourceFrameID, const Vector<std::pair<String, String>>& textFieldValues, uint64_t listenerID, const UserData&); + + // History client + void didNavigateWithNavigationData(const WebNavigationDataStore&, uint64_t frameID); + void didPerformClientRedirect(const String& sourceURLString, const String& destinationURLString, uint64_t frameID); + void didPerformServerRedirect(const String& sourceURLString, const String& destinationURLString, uint64_t frameID); + void didUpdateHistoryTitle(const String& title, const String& url, uint64_t frameID); // UI client - void createNewPage(const WebCore::ResourceRequest&, const WebCore::WindowFeatures&, uint32_t modifiers, int32_t mouseButton, uint64_t& newPageID, WebPageCreationParameters&); + void createNewPage(uint64_t frameID, const WebCore::SecurityOriginData&, const WebCore::ResourceRequest&, const WebCore::WindowFeatures&, const NavigationActionData&, uint64_t& newPageID, WebPageCreationParameters&); void showPage(); void closePage(bool stopResponsivenessTimer); - void runJavaScriptAlert(uint64_t frameID, const String&); - void runJavaScriptConfirm(uint64_t frameID, const String&, bool& result); - void runJavaScriptPrompt(uint64_t frameID, const String&, const String&, String& result); - void shouldInterruptJavaScript(bool& result); + void runJavaScriptAlert(uint64_t frameID, const WebCore::SecurityOriginData&, const String&, RefPtr<Messages::WebPageProxy::RunJavaScriptAlert::DelayedReply>); + void runJavaScriptConfirm(uint64_t frameID, const WebCore::SecurityOriginData&, const String&, RefPtr<Messages::WebPageProxy::RunJavaScriptConfirm::DelayedReply>); + void runJavaScriptPrompt(uint64_t frameID, const WebCore::SecurityOriginData&, const String&, const String&, RefPtr<Messages::WebPageProxy::RunJavaScriptPrompt::DelayedReply>); void setStatusText(const String&); - void mouseDidMoveOverElement(const WebHitTestResult::Data& hitTestResultData, uint32_t modifiers, CoreIPC::MessageDecoder&); + void mouseDidMoveOverElement(const WebHitTestResultData&, uint32_t modifiers, const UserData&); + +#if ENABLE(NETSCAPE_PLUGIN_API) void unavailablePluginButtonClicked(uint32_t opaquePluginUnavailabilityReason, const String& mimeType, const String& pluginURLString, const String& pluginsPageURLString, const String& frameURLString, const String& pageURLString); +#endif // ENABLE(NETSCAPE_PLUGIN_API) +#if ENABLE(WEBGL) + void webGLPolicyForURL(const String& url, uint32_t& loadPolicy); + void resolveWebGLPolicyForURL(const String& url, uint32_t& loadPolicy); +#endif // ENABLE(WEBGL) void setToolbarsAreVisible(bool toolbarsAreVisible); void getToolbarsAreVisible(bool& toolbarsAreVisible); void setMenuBarIsVisible(bool menuBarIsVisible); @@ -851,27 +1218,40 @@ private: void getIsResizable(bool& isResizable); void setWindowFrame(const WebCore::FloatRect&); void getWindowFrame(WebCore::FloatRect&); - void screenToWindow(const WebCore::IntPoint& screenPoint, WebCore::IntPoint& windowPoint); - void windowToScreen(const WebCore::IntRect& viewRect, WebCore::IntRect& result); - void runBeforeUnloadConfirmPanel(const String& message, uint64_t frameID, bool& shouldClose); + void screenToRootView(const WebCore::IntPoint& screenPoint, WebCore::IntPoint& windowPoint); + void rootViewToScreen(const WebCore::IntRect& viewRect, WebCore::IntRect& result); +#if PLATFORM(IOS) + void accessibilityScreenToRootView(const WebCore::IntPoint& screenPoint, WebCore::IntPoint& windowPoint); + void rootViewToAccessibilityScreen(const WebCore::IntRect& viewRect, WebCore::IntRect& result); +#endif + void runBeforeUnloadConfirmPanel(const String& message, uint64_t frameID, RefPtr<Messages::WebPageProxy::RunBeforeUnloadConfirmPanel::DelayedReply>); void didChangeViewportProperties(const WebCore::ViewportAttributes&); void pageDidScroll(); void runOpenPanel(uint64_t frameID, const WebCore::FileChooserSettings&); void printFrame(uint64_t frameID); void exceededDatabaseQuota(uint64_t frameID, const String& originIdentifier, const String& databaseName, const String& displayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage, PassRefPtr<Messages::WebPageProxy::ExceededDatabaseQuota::DelayedReply>); + void reachedApplicationCacheOriginQuota(const String& originIdentifier, uint64_t currentQuota, uint64_t totalBytesNeeded, PassRefPtr<Messages::WebPageProxy::ReachedApplicationCacheOriginQuota::DelayedReply>); void requestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, String originIdentifier); + + void requestUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String originIdentifier, const Vector<String>& audioDeviceUIDs, const Vector<String>& videoDeviceUIDs); + void checkUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String originIdentifier); + void runModal(); void notifyScrollerThumbIsVisibleInRect(const WebCore::IntRect&); void recommendedScrollbarStyleDidChange(int32_t newStyle); void didChangeScrollbarsForMainFrame(bool hasHorizontalScrollbar, bool hasVerticalScrollbar); void didChangeScrollOffsetPinningForMainFrame(bool pinnedToLeftSide, bool pinnedToRightSide, bool pinnedToTopSide, bool pinnedToBottomSide); void didChangePageCount(unsigned); + void pageExtendedBackgroundColorDidChange(const WebCore::Color&); +#if ENABLE(NETSCAPE_PLUGIN_API) void didFailToInitializePlugin(const String& mimeType, const String& frameURLString, const String& pageURLString); void didBlockInsecurePluginVersion(const String& mimeType, const String& pluginURLString, const String& frameURLString, const String& pageURLString, bool replacementObscured); +#endif // ENABLE(NETSCAPE_PLUGIN_API) void setCanShortCircuitHorizontalWheelEvents(bool canShortCircuitHorizontalWheelEvents) { m_canShortCircuitHorizontalWheelEvents = canShortCircuitHorizontalWheelEvents; } void reattachToWebProcess(); - void reattachToWebProcessWithItem(WebBackForwardListItem*); + RefPtr<API::Navigation> reattachToWebProcessForReload(); + RefPtr<API::Navigation> reattachToWebProcessWithItem(WebBackForwardListItem*); void requestNotificationPermission(uint64_t notificationID, const String& originString); void showNotification(const String& title, const String& body, const String& iconURL, const String& tag, const String& lang, const String& dir, const String& originString, uint64_t notificationID); @@ -879,28 +1259,22 @@ private: void clearNotifications(const Vector<uint64_t>& notificationIDs); void didDestroyNotification(uint64_t notificationID); -#if USE(TILED_BACKING_STORE) +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) void pageDidRequestScroll(const WebCore::IntPoint&); void pageTransitionViewportReady(); -#endif -#if USE(COORDINATED_GRAPHICS) void didFindZoomableArea(const WebCore::IntPoint&, const WebCore::IntRect&); #endif -#if PLATFORM(QT) || PLATFORM(EFL) - void didChangeContentsSize(const WebCore::IntSize&); -#endif -#if ENABLE(TOUCH_EVENTS) - void needTouchEvents(bool); -#endif + void didChangeContentSize(const WebCore::IntSize&); #if ENABLE(INPUT_TYPE_COLOR) - void showColorChooser(const WebCore::Color& initialColor, const WebCore::IntRect&); - void didChooseColor(const WebCore::Color&); - void didEndColorChooser(); + void showColorPicker(const WebCore::Color& initialColor, const WebCore::IntRect&); + virtual void didChooseColor(const WebCore::Color&) override; + virtual void didEndColorPicker() override; #endif void editorStateChanged(const EditorState&); + void compositionWasCanceled(const EditorState&); #if PLATFORM(QT) void willSetInputMethodState(); #endif @@ -915,13 +1289,13 @@ private: // Undo management void registerEditCommandForUndo(uint64_t commandID, uint32_t editAction); + void registerInsertionUndoGrouping(); void clearAllEditCommands(); void canUndoRedo(uint32_t action, bool& result); void executeUndoRedo(uint32_t action, bool& result); // Keyboard handling -#if PLATFORM(MAC) - void interpretQueuedKeyEvent(const EditorState&, bool& handled, Vector<WebCore::KeypressCommand>&); +#if PLATFORM(COCOA) void executeSavedCommandBySelector(const String& selector, bool& handled); #endif @@ -938,16 +1312,21 @@ private: void hidePopupMenu(); #if ENABLE(CONTEXT_MENUS) - // Context Menu. - void showContextMenu(const WebCore::IntPoint& menuLocation, const WebHitTestResult::Data&, const Vector<WebContextMenuItemData>&, CoreIPC::MessageDecoder&); - void internalShowContextMenu(const WebCore::IntPoint& menuLocation, const WebHitTestResult::Data&, const Vector<WebContextMenuItemData>&, CoreIPC::MessageDecoder&); + void showContextMenu(const ContextMenuContextData&, const UserData&); + void internalShowContextMenu(const ContextMenuContextData&, const UserData&); +#endif + +#if ENABLE(TELEPHONE_NUMBER_DETECTION) +#if PLATFORM(MAC) + void showTelephoneNumberMenu(const String& telephoneNumber, const WebCore::IntPoint&); +#endif #endif // Search popup results - void saveRecentSearches(const String&, const Vector<String>&); - void loadRecentSearches(const String&, Vector<String>&); + void saveRecentSearches(const String&, const Vector<WebCore::RecentSearch>&); + void loadRecentSearches(const String&, Vector<WebCore::RecentSearch>&); -#if PLATFORM(MAC) +#if PLATFORM(COCOA) // Speech. void getIsSpeaking(bool&); void speak(const String&); @@ -959,19 +1338,19 @@ private: void searchTheWeb(const String&); // Dictionary. - void didPerformDictionaryLookup(const AttributedString&, const DictionaryPopupInfo&); + void didPerformDictionaryLookup(const WebCore::DictionaryPopupInfo&); #endif - // Spelling and grammar. -#if USE(UNIFIED_TEXT_CHECKING) - void checkTextOfParagraph(const String& text, uint64_t checkingTypes, Vector<WebCore::TextCheckingResult>& results); +#if PLATFORM(MAC) + bool appleMailPaginationQuirkEnabled(); #endif + + // Spelling and grammar. void checkSpellingOfString(const String& text, int32_t& misspellingLocation, int32_t& misspellingLength); void checkGrammarOfString(const String& text, Vector<WebCore::GrammarDetail>&, int32_t& badGrammarLocation, int32_t& badGrammarLength); void spellingUIIsShowing(bool&); void updateSpellingUIWithMisspelledWord(const String& misspelledWord); void updateSpellingUIWithGrammarString(const String& badGrammarPhrase, const WebCore::GrammarDetail&); - void getGuessesForWord(const String& word, const String& context, Vector<String>& guesses); void learnWord(const String& word); void ignoreWord(const String& word); void requestCheckingOfString(uint64_t requestID, const WebCore::TextCheckingRequestData&); @@ -986,12 +1365,31 @@ private: void stopResponsivenessTimer(); void voidCallback(uint64_t); - void dataCallback(const CoreIPC::DataReference&, uint64_t); + void dataCallback(const IPC::DataReference&, uint64_t); void imageCallback(const ShareableBitmap::Handle&, uint64_t); void stringCallback(const String&, uint64_t); - void scriptValueCallback(const CoreIPC::DataReference&, uint64_t); + void scriptValueCallback(const IPC::DataReference&, bool hadException, const WebCore::ExceptionDetails&, uint64_t); void computedPagesCallback(const Vector<WebCore::IntRect>&, double totalScaleFactorForPrinting, uint64_t); void validateCommandCallback(const String&, bool, int, uint64_t); + void unsignedCallback(uint64_t, uint64_t); + void editingRangeCallback(const EditingRange&, uint64_t); +#if PLATFORM(COCOA) + void machSendRightCallback(const WebCore::MachSendRight&, uint64_t); +#endif + void rectForCharacterRangeCallback(const WebCore::IntRect&, const EditingRange&, uint64_t); +#if PLATFORM(MAC) + void attributedStringForCharacterRangeCallback(const AttributedString&, const EditingRange&, uint64_t); + void fontAtSelectionCallback(const String&, double, bool, uint64_t); +#endif +#if PLATFORM(IOS) + void gestureCallback(const WebCore::IntPoint&, uint32_t, uint32_t, uint32_t, uint64_t); + void touchesCallback(const WebCore::IntPoint&, uint32_t, uint64_t); + void autocorrectionDataCallback(const Vector<WebCore::FloatRect>&, const String&, float, uint64_t, uint64_t); + void autocorrectionContextCallback(const String&, const String&, const String&, const String&, uint64_t, uint64_t, uint64_t); + void dictationContextCallback(const String&, const String&, const String&, uint64_t); + void interpretKeyEvent(const EditorState&, bool isCharEvent, bool& handled); + void showPlaybackTargetPicker(bool hasVideo, const WebCore::IntRect& elementRect); +#endif #if PLATFORM(GTK) void printFinishedCallback(const WebCore::ResourceError&, uint64_t); #endif @@ -1002,15 +1400,14 @@ private: void canAuthenticateAgainstProtectionSpaceInFrame(uint64_t frameID, const WebCore::ProtectionSpace&, bool& canAuthenticate); void didReceiveAuthenticationChallenge(uint64_t frameID, const WebCore::AuthenticationChallenge&, uint64_t challengeID); -#if PLATFORM(MAC) + void didFinishLoadingDataForCustomContentProvider(const String& suggestedFilename, const IPC::DataReference&); + +#if PLATFORM(COCOA) void pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus); void setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, uint64_t complexTextInputState); #endif - void clearPendingAPIRequestURL() { m_pendingAPIRequestURL = String(); } - void setPendingAPIRequestURL(const String& pendingAPIRequestURL) { m_pendingAPIRequestURL = pendingAPIRequestURL; } - - bool maybeInitializeSandboxExtensionHandle(const WebCore::KURL&, SandboxExtension::Handle&); + bool maybeInitializeSandboxExtensionHandle(const WebCore::URL&, SandboxExtension::Handle&); #if PLATFORM(MAC) void substitutionsPanelIsShowing(bool&); @@ -1026,13 +1423,38 @@ private: #endif #endif // PLATFORM(MAC) -#if USE(SOUP) - void didReceiveURIRequest(String uriString, uint64_t requestID); +#if PLATFORM(IOS) + WebCore::FloatSize screenSize(); + WebCore::FloatSize availableScreenSize(); + float textAutosizingWidth(); + + void dynamicViewportUpdateChangedTarget(double newTargetScale, const WebCore::FloatPoint& newScrollPosition, uint64_t dynamicViewportSizeUpdateID); + void couldNotRestorePageState(); + void restorePageState(const WebCore::FloatRect&, double scale); + void restorePageCenterAndScale(const WebCore::FloatPoint&, double scale); + + void didGetTapHighlightGeometries(uint64_t requestID, const WebCore::Color& color, const Vector<WebCore::FloatQuad>& geometries, const WebCore::IntSize& topLeftRadius, const WebCore::IntSize& topRightRadius, const WebCore::IntSize& bottomLeftRadius, const WebCore::IntSize& bottomRightRadius); + + void startAssistingNode(const AssistedNodeInformation&, bool userIsInteracting, bool blurPreviousNode, const UserData&); + void stopAssistingNode(); + + void showInspectorHighlight(const WebCore::Highlight&); + void hideInspectorHighlight(); + + void showInspectorIndication(); + void hideInspectorIndication(); + + void enableInspectorNodeSearch(); + void disableInspectorNodeSearch(); +#endif // PLATFORM(IOS) + +#if ENABLE(DATA_DETECTION) + RetainPtr<NSArray> m_dataDetectionResults; #endif void clearLoadDependentCallbacks(); - void performDragControllerAction(DragControllerAction, WebCore::DragData*, const String& dragStorageName, const SandboxExtension::Handle&, const SandboxExtension::HandleArray&); + void performDragControllerAction(DragControllerAction, WebCore::DragData&, const String& dragStorageName, const SandboxExtension::Handle&, const SandboxExtension::HandleArray&); void updateBackingStoreDiscardableState(); @@ -1041,32 +1463,97 @@ private: #if PLUGIN_ARCHITECTURE(X11) void createPluginContainer(uint64_t& windowID); void windowedPluginGeometryDidChange(const WebCore::IntRect& frameRect, const WebCore::IntRect& clipRect, uint64_t windowID); + void windowedPluginVisibilityDidChange(bool isVisible, uint64_t windowID); #endif void processNextQueuedWheelEvent(); void sendWheelEvent(const WebWheelEvent&); +#if ENABLE(TOUCH_EVENTS) + bool shouldStartTrackingTouchEvents(const WebTouchEvent&) const; +#endif + #if ENABLE(NETSCAPE_PLUGIN_API) void findPlugin(const String& mimeType, uint32_t processType, const String& urlString, const String& frameURLString, const String& pageURLString, bool allowOnlyApplicationPlugins, uint64_t& pluginProcessToken, String& newMIMEType, uint32_t& pluginLoadPolicy, String& unavailabilityDescription); #endif - PageClient* m_pageClient; - WebLoaderClient m_loaderClient; - WebPolicyClient m_policyClient; - WebFormClient m_formClient; - WebUIClient m_uiClient; +#if USE(QUICK_LOOK) + void didStartLoadForQuickLookDocumentInMainFrame(const String& fileName, const String& uti); + void didFinishLoadForQuickLookDocumentInMainFrame(const QuickLookDocumentData&); +#endif + +#if ENABLE(CONTENT_FILTERING) + void contentFilterDidBlockLoadForFrame(const WebCore::ContentFilterUnblockHandler&, uint64_t frameID); +#endif + + uint64_t generateNavigationID(); + + WebPreferencesStore preferencesStore() const; + + void dispatchViewStateChange(); + void viewDidLeaveWindow(); + void viewDidEnterWindow(); + +#if PLATFORM(MAC) + void didPerformImmediateActionHitTest(const WebHitTestResultData&, bool contentPreventsDefault, const UserData&); +#endif + + void useFixedLayoutDidChange(bool useFixedLayout) { m_useFixedLayout = useFixedLayout; } + void fixedLayoutSizeDidChange(WebCore::IntSize fixedLayoutSize) { m_fixedLayoutSize = fixedLayoutSize; } + + void imageOrMediaDocumentSizeChanged(const WebCore::IntSize&); +#if ENABLE(VIDEO) +#if USE(GSTREAMER) + void requestInstallMissingMediaPlugins(const String& details, const String& description); +#endif +#endif + + void handleAutoFillButtonClick(const UserData&); + + void finishInitializingWebPageAfterProcessLaunch(); + + void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody); + void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData); + + PageClient& m_pageClient; + Ref<API::PageConfiguration> m_configuration; + + std::unique_ptr<API::LoaderClient> m_loaderClient; + std::unique_ptr<API::PolicyClient> m_policyClient; + std::unique_ptr<API::NavigationClient> m_navigationClient; + std::unique_ptr<API::HistoryClient> m_historyClient; + std::unique_ptr<API::FormClient> m_formClient; + std::unique_ptr<API::UIClient> m_uiClient; #if PLATFORM(EFL) WebUIPopupMenuClient m_uiPopupMenuClient; #endif - WebFindClient m_findClient; - WebFindMatchesClient m_findMatchesClient; + std::unique_ptr<API::FindClient> m_findClient; + std::unique_ptr<API::FindMatchesClient> m_findMatchesClient; + std::unique_ptr<API::DiagnosticLoggingClient> m_diagnosticLoggingClient; #if ENABLE(CONTEXT_MENUS) - WebPageContextMenuClient m_contextMenuClient; + std::unique_ptr<API::ContextMenuClient> m_contextMenuClient; +#endif + std::unique_ptr<WebPageInjectedBundleClient> m_injectedBundleClient; + + std::unique_ptr<WebNavigationState> m_navigationState; + String m_failingProvisionalLoadURL; + bool m_isLoadingAlternateHTMLStringForFailingProvisionalLoad { false }; + + std::unique_ptr<DrawingAreaProxy> m_drawingArea; +#if ENABLE(ASYNC_SCROLLING) + std::unique_ptr<RemoteScrollingCoordinatorProxy> m_scrollingCoordinatorProxy; #endif - OwnPtr<DrawingAreaProxy> m_drawingArea; - RefPtr<WebProcessProxy> m_process; - RefPtr<WebPageGroup> m_pageGroup; + Ref<WebProcessProxy> m_process; + Ref<WebPageGroup> m_pageGroup; + Ref<WebPreferences> m_preferences; + + WebProcessLifetimeTracker m_webProcessLifetimeTracker { *this }; + + const RefPtr<WebUserContentControllerProxy> m_userContentController; + Ref<VisitedLinkStore> m_visitedLinkStore; + Ref<WebsiteDataStore> m_websiteDataStore; + RefPtr<WebFrameProxy> m_mainFrame; RefPtr<WebFrameProxy> m_focusedFrame; RefPtr<WebFrameProxy> m_frameSetLargestFrame; @@ -1076,79 +1563,95 @@ private: String m_customUserAgent; String m_customTextEncodingName; -#if ENABLE(INSPECTOR) + bool m_treatsSHA1CertificatesAsInsecure; + RefPtr<WebInspectorProxy> m_inspector; -#endif #if ENABLE(FULLSCREEN_API) RefPtr<WebFullScreenManagerProxy> m_fullScreenManager; #endif +#if PLATFORM(IOS) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)) + RefPtr<WebVideoFullscreenManagerProxy> m_videoFullscreenManager; +#endif +#if PLATFORM(IOS) + VisibleContentRectUpdateInfo m_lastVisibleContentRectUpdate; + bool m_hasReceivedLayerTreeTransactionAfterDidCommitLoad; + uint64_t m_firstLayerTreeTransactionIdAfterDidCommitLoad; + int32_t m_deviceOrientation; + bool m_dynamicViewportSizeUpdateWaitingForTarget; + bool m_dynamicViewportSizeUpdateWaitingForLayerTreeCommit; + uint64_t m_dynamicViewportSizeUpdateLayerTreeTransactionID; + uint64_t m_layerTreeTransactionIdAtLastTouchStart; + uint64_t m_currentDynamicViewportSizeUpdateID { 0 }; + bool m_hasNetworkRequestsOnSuspended; +#endif #if ENABLE(VIBRATION) RefPtr<WebVibrationProxy> m_vibration; #endif - HashMap<uint64_t, RefPtr<VoidCallback> > m_voidCallbacks; - HashMap<uint64_t, RefPtr<DataCallback> > m_dataCallbacks; - HashMap<uint64_t, RefPtr<ImageCallback> > m_imageCallbacks; - HashMap<uint64_t, RefPtr<StringCallback> > m_stringCallbacks; - HashSet<uint64_t> m_loadDependentStringCallbackIDs; - HashMap<uint64_t, RefPtr<ScriptValueCallback> > m_scriptValueCallbacks; - HashMap<uint64_t, RefPtr<ComputedPagesCallback> > m_computedPagesCallbacks; - HashMap<uint64_t, RefPtr<ValidateCommandCallback> > m_validateCommandCallbacks; -#if PLATFORM(GTK) - HashMap<uint64_t, RefPtr<PrintFinishedCallback> > m_printFinishedCallbacks; +#if USE(APPLE_INTERNAL_SDK) +#include <WebKitAdditions/WebPageProxyMembers.h> #endif + CallbackMap m_callbacks; + HashSet<uint64_t> m_loadDependentStringCallbackIDs; + HashSet<WebEditCommandProxy*> m_editCommandSet; -#if PLATFORM(MAC) +#if PLATFORM(COCOA) HashSet<String> m_knownKeypressCommandNames; #endif RefPtr<WebPopupMenuProxy> m_activePopupMenu; - RefPtr<WebContextMenuProxy> m_activeContextMenu; - WebHitTestResult::Data m_activeContextMenuHitTestResultData; +#if ENABLE(CONTEXT_MENUS) + std::unique_ptr<WebContextMenuProxy> m_activeContextMenu; + ContextMenuContextData m_activeContextMenuContextData; +#endif + RefPtr<API::HitTestResult> m_lastMouseMoveHitTestResult; + RefPtr<WebOpenPanelResultListenerProxy> m_openPanelResultListener; GeolocationPermissionRequestManagerProxy m_geolocationPermissionRequestManager; NotificationPermissionRequestManagerProxy m_notificationPermissionRequestManager; - double m_estimatedProgress; - - // Whether the web page is contained in a top-level window. - bool m_isInWindow; - - // Whether the page is visible; if the backing view is visible and inserted into a window. - bool m_isVisible; + UserMediaPermissionRequestManagerProxy m_userMediaPermissionRequestManager; - bool m_canGoBack; - bool m_canGoForward; - RefPtr<WebBackForwardList> m_backForwardList; - + WebCore::ViewState::Flags m_viewState; + bool m_viewWasEverInWindow; +#if PLATFORM(IOS) + bool m_allowsMediaDocumentInlinePlayback { false }; + bool m_alwaysRunsAtForegroundPriority; + ProcessThrottler::ForegroundActivityToken m_activityToken; +#endif + + Ref<WebBackForwardList> m_backForwardList; + bool m_maintainsInactiveSelection; String m_toolTip; String m_urlAtProcessExit; - WebFrameProxy::LoadState m_loadStateAtProcessExit; + FrameLoadState::LoadState m_loadStateAtProcessExit; EditorState m_editorState; - bool m_temporarilyClosedComposition; // Editor state changed from hasComposition to !hasComposition, but that was only with shouldIgnoreCompositionSelectionChange yet. + bool m_isEditable; double m_textZoomFactor; double m_pageZoomFactor; double m_pageScaleFactor; + double m_pluginZoomFactor; + double m_pluginScaleFactor; + double m_viewScaleFactor { 1 }; float m_intrinsicDeviceScaleFactor; float m_customDeviceScaleFactor; + float m_topContentInset; LayerHostingMode m_layerHostingMode; bool m_drawsBackground; - bool m_drawsTransparentBackground; WebCore::Color m_underlayColor; - - bool m_areMemoryCacheClientCallsEnabled; + WebCore::Color m_pageExtendedBackgroundColor; bool m_useFixedLayout; WebCore::IntSize m_fixedLayoutSize; @@ -1159,7 +1662,8 @@ private: bool m_paginationBehavesLikeColumns; double m_pageLength; double m_gapBetweenPages; - + bool m_paginationLineGridEnabled; + // If the process backing the web page is alive and kicking. bool m_isValid; @@ -1169,6 +1673,8 @@ private: // Whether it can run modal child web pages. bool m_canRunModal; + bool m_needsToFinishInitializingWebPageAfterProcessLaunch { false }; + bool m_isInPrintingMode; bool m_isPerformingDOMPrintOperation; @@ -1176,54 +1682,73 @@ private: const WebCore::ResourceRequest* m_decidePolicyForResponseRequest; bool m_syncMimeTypePolicyActionIsValid; WebCore::PolicyAction m_syncMimeTypePolicyAction; - uint64_t m_syncMimeTypePolicyDownloadID; + DownloadID m_syncMimeTypePolicyDownloadID; bool m_inDecidePolicyForNavigationAction; bool m_syncNavigationActionPolicyActionIsValid; WebCore::PolicyAction m_syncNavigationActionPolicyAction; - uint64_t m_syncNavigationActionPolicyDownloadID; + DownloadID m_syncNavigationActionPolicyDownloadID; + bool m_shouldSuppressAppLinksInNextNavigationPolicyDecision { false }; -#if ENABLE(GESTURE_EVENTS) - Deque<WebGestureEvent> m_gestureEventQueue; -#endif Deque<NativeWebKeyboardEvent> m_keyEventQueue; Deque<NativeWebWheelEvent> m_wheelEventQueue; - Deque<OwnPtr<Vector<NativeWebWheelEvent> > > m_currentlyProcessedWheelEvents; + Deque<std::unique_ptr<Vector<NativeWebWheelEvent>>> m_currentlyProcessedWheelEvents; +#if ENABLE(MAC_GESTURE_EVENTS) + Deque<NativeWebGestureEvent> m_gestureEventQueue; +#endif bool m_processingMouseMoveEvent; - OwnPtr<NativeWebMouseEvent> m_nextMouseMoveEvent; - OwnPtr<NativeWebMouseEvent> m_currentlyProcessedMouseDownEvent; + std::unique_ptr<NativeWebMouseEvent> m_nextMouseMoveEvent; + std::unique_ptr<NativeWebMouseEvent> m_currentlyProcessedMouseDownEvent; #if ENABLE(TOUCH_EVENTS) - bool m_needTouchEvents; + bool m_isTrackingTouchEvents; +#endif +#if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS) Deque<QueuedTouchEvents> m_touchEventQueue; #endif + #if ENABLE(INPUT_TYPE_COLOR) RefPtr<WebColorPicker> m_colorPicker; - RefPtr<WebColorPickerResultListenerProxy> m_colorPickerResultListener; #endif - uint64_t m_pageID; + const uint64_t m_pageID; + WebCore::SessionID m_sessionID; bool m_isPageSuspended; + bool m_addsVisitedLinks; -#if PLATFORM(MAC) +#if ENABLE(REMOTE_INSPECTOR) + bool m_allowsRemoteInspection; + String m_remoteInspectionNameOverride; +#endif + +#if PLATFORM(COCOA) bool m_isSmartInsertDeleteEnabled; #endif #if PLATFORM(GTK) String m_accessibilityPlugID; + WebCore::Color m_backgroundColor; #endif int64_t m_spellDocumentTag; bool m_hasSpellDocumentTag; unsigned m_pendingLearnOrIgnoreWordMessageCount; + bool m_mainFrameHasCustomContentProvider; + #if ENABLE(DRAG_SUPPORT) - WebCore::DragSession m_currentDragSession; + // Current drag destination details are delivered as an asynchronous response, + // so we preserve them to be used when the next dragging delegate call is made. + WebCore::DragOperation m_currentDragOperation; + bool m_currentDragIsOverFileInput; + unsigned m_currentDragNumberOfFilesToBeAccepted; #endif - String m_pendingAPIRequestURL; + PageLoadState m_pageLoadState; + + bool m_delegatesScrolling; bool m_mainFrameHasHorizontalScrollbar; bool m_mainFrameHasVerticalScrollbar; @@ -1236,50 +1761,81 @@ private: bool m_mainFrameIsPinnedToTopSide; bool m_mainFrameIsPinnedToBottomSide; - bool m_rubberBandsAtBottom; + bool m_shouldUseImplicitRubberBandControl; + bool m_rubberBandsAtLeft; + bool m_rubberBandsAtRight; bool m_rubberBandsAtTop; - - bool m_mainFrameInViewSourceMode; + bool m_rubberBandsAtBottom; + bool m_enableVerticalRubberBanding; + bool m_enableHorizontalRubberBanding; + + bool m_backgroundExtendsBeyondPage; + + bool m_shouldRecordNavigationSnapshots; + bool m_isShowingNavigationGestureSnapshot; + + bool m_mainFramePluginHandlesPageScaleGesture { false }; + unsigned m_pageCount; WebCore::IntRect m_visibleScrollerThumbRect; uint64_t m_renderTreeSize; - - static WKPageDebugPaintFlags s_debugPaintFlags; - - bool m_shouldSendEventsSynchronously; + uint64_t m_sessionRestorationRenderTreeSize; + bool m_wantsSessionRestorationRenderTreeSizeThresholdEvent; + bool m_hitRenderTreeSizeThreshold; bool m_suppressVisibilityUpdates; + bool m_autoSizingShouldExpandToViewHeight; WebCore::IntSize m_minimumLayoutSize; float m_mediaVolume; + bool m_muted; bool m_mayStartMediaWhenInWindow; - bool m_waitingForDidUpdateInWindowState; + bool m_waitingForDidUpdateViewState; -#if PLATFORM(MAC) - WebCore::Timer<WebPageProxy> m_exposedRectChangedTimer; - WebCore::FloatRect m_exposedRect; - WebCore::FloatRect m_lastSentExposedRect; - bool m_clipsToExposedRect; - bool m_lastSentClipsToExposedRect; -#endif + bool m_shouldScaleViewToFitDocument { false }; + bool m_suppressNavigationSnapshotting { false }; #if PLATFORM(QT) - WTF::HashSet<RefPtr<QtRefCountedNetworkRequestData> > m_applicationSchemeRequests; -#endif - -#if ENABLE(PAGE_VISIBILITY_API) - WebCore::PageVisibilityState m_visibilityState; + WTF::HashSet<RefPtr<QtRefCountedNetworkRequestData>> m_applicationSchemeRequests; #endif - -#if PLATFORM(MAC) +#if PLATFORM(COCOA) HashMap<String, String> m_temporaryPDFFiles; + std::unique_ptr<WebCore::RunLoopObserver> m_viewStateChangeDispatcher; + + std::unique_ptr<RemoteLayerTreeScrollingPerformanceData> m_scrollingPerformanceData; + bool m_scrollPerformanceDataCollectionEnabled; #endif + UserObservablePageToken m_pageIsUserObservableCount; + ProcessSuppressionDisabledToken m_preventProcessSuppressionCount; WebCore::ScrollPinningBehavior m_scrollPinningBehavior; + WTF::Optional<WebCore::ScrollbarOverlayStyle> m_scrollbarOverlayStyle; + + uint64_t m_navigationID; + + WebPreferencesStore::ValueMap m_configurationPreferenceValues; + WebCore::ViewState::Flags m_potentiallyChangedViewStateFlags; + bool m_viewStateChangeWantsSynchronousReply; + Vector<uint64_t> m_nextViewStateChangeCallbacks; + + WebCore::MediaProducer::MediaStateFlags m_mediaState { WebCore::MediaProducer::IsNotPlaying }; + +#if ENABLE(MEDIA_SESSION) + bool m_hasMediaSessionWithActiveMediaElements { false }; +#endif + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) + bool m_requiresTargetMonitoring { false }; +#endif + +#if PLATFORM(IOS) + bool m_hasDeferredStartAssistingNode { false }; + std::unique_ptr<NodeAssistanceArguments> m_deferredNodeAssistanceArguments; +#endif }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPageProxy.messages.in b/Source/WebKit2/UIProcess/WebPageProxy.messages.in index 20e9f624e..cef2edc6b 100644 --- a/Source/WebKit2/UIProcess/WebPageProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebPageProxy.messages.in @@ -22,22 +22,30 @@ messages -> WebPageProxy { # UI messages - CreateNewPage(WebCore::ResourceRequest request, WebCore::WindowFeatures windowFeatures, uint32_t modifiers, int32_t mouseButton) -> (uint64_t newPageID, WebKit::WebPageCreationParameters newPageParameters) + CreateNewPage(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, WebCore::ResourceRequest request, struct WebCore::WindowFeatures windowFeatures, struct WebKit::NavigationActionData navigationActionData) -> (uint64_t newPageID, struct WebKit::WebPageCreationParameters newPageParameters) ShowPage() ClosePage(bool stopResponsivenessTimer) - RunJavaScriptAlert(uint64_t frameID, WTF::String message) -> () - RunJavaScriptConfirm(uint64_t frameID, WTF::String message) -> (bool result) - RunJavaScriptPrompt(uint64_t frameID, WTF::String message, WTF::String defaultValue) -> (WTF::String result) - ShouldInterruptJavaScript() -> (bool shouldInterupt) - MouseDidMoveOverElement(WebKit::WebHitTestResult::Data hitTestResultData, uint32_t modifiers, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - UnavailablePluginButtonClicked(uint32_t pluginUnavailabilityReason, WTF::String mimeType, WTF::String pluginURLString, WTF::String pluginspageAttributeURLString, WTF::String frameURLString, WTF::String pageURLString) - DidChangeViewportProperties(WebCore::ViewportAttributes attributes) + RunJavaScriptAlert(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, String message) -> () Delayed + RunJavaScriptConfirm(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, String message) -> (bool result) Delayed + RunJavaScriptPrompt(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, String message, String defaultValue) -> (String result) Delayed + MouseDidMoveOverElement(struct WebKit::WebHitTestResultData hitTestResultData, uint32_t modifiers, WebKit::UserData userData) + +#if ENABLE(NETSCAPE_PLUGIN_API) + UnavailablePluginButtonClicked(uint32_t pluginUnavailabilityReason, String mimeType, String pluginURLString, String pluginspageAttributeURLString, String frameURLString, String pageURLString) +#endif // ENABLE(NETSCAPE_PLUGIN_API) +#if ENABLE(WEBGL) + WebGLPolicyForURL(String url) -> (uint32_t loadPolicy) + ResolveWebGLPolicyForURL(String url) -> (uint32_t loadPolicy) +#endif // ENABLE(WEBGL) + DidChangeViewportProperties(struct WebCore::ViewportAttributes attributes) DidReceiveEvent(uint32_t type, bool handled) StopResponsivenessTimer() +#if !PLATFORM(IOS) SetCursor(WebCore::Cursor cursor) SetCursorHiddenUntilMouseMoves(bool hiddenUntilMouseMoves) - SetStatusText(WTF::String statusText) - SetToolTip(WTF::String toolTip) +#endif + SetStatusText(String statusText) + SetToolTip(String toolTip) SetFocus(bool focused) TakeFocus(uint32_t direction) FocusedFrameChanged(uint64_t frameID) @@ -53,86 +61,89 @@ messages -> WebPageProxy { GetIsResizable() -> (bool isResizable) SetWindowFrame(WebCore::FloatRect windowFrame) GetWindowFrame() -> (WebCore::FloatRect windowFrame) - ScreenToWindow(WebCore::IntPoint screenPoint) -> (WebCore::IntPoint windowPoint) - WindowToScreen(WebCore::IntRect rect) -> (WebCore::IntRect screenFrame) - RunBeforeUnloadConfirmPanel(WTF::String message, uint64_t frameID) -> (bool shouldClose) + ScreenToRootView(WebCore::IntPoint screenPoint) -> (WebCore::IntPoint windowPoint) + RootViewToScreen(WebCore::IntRect rect) -> (WebCore::IntRect screenFrame) + +#if PLATFORM(IOS) + AccessibilityScreenToRootView(WebCore::IntPoint screenPoint) -> (WebCore::IntPoint windowPoint) + RootViewToAccessibilityScreen(WebCore::IntRect rect) -> (WebCore::IntRect screenFrame) +#endif + + RunBeforeUnloadConfirmPanel(String message, uint64_t frameID) -> (bool shouldClose) Delayed PageDidScroll() - RunOpenPanel(uint64_t frameID, WebCore::FileChooserSettings parameters) + RunOpenPanel(uint64_t frameID, struct WebCore::FileChooserSettings parameters) PrintFrame(uint64_t frameID) -> () RunModal() NotifyScrollerThumbIsVisibleInRect(WebCore::IntRect scrollerThumb) RecommendedScrollbarStyleDidChange(int32_t newStyle) DidChangeScrollbarsForMainFrame(bool hasHorizontalScrollbar, bool hasVerticalScrollbar) DidChangeScrollOffsetPinningForMainFrame(bool pinnedToLeftSide, bool pinnedToRightSide, bool pinnedToTopSide, bool pinnedToBottomSide) - DidChangePageCount(unsigned pageCount); - DidFailToInitializePlugin(WTF::String mimeType, WTF::String frameURLString, WTF::String pageURLString) - DidBlockInsecurePluginVersion(WTF::String mimeType, WTF::String pluginURLString, WTF::String frameURLString, WTF::String pageURLString, bool replacementObscured) + DidChangePageCount(unsigned pageCount) + PageExtendedBackgroundColorDidChange(WebCore::Color backgroundColor) +#if ENABLE(NETSCAPE_PLUGIN_API) + DidFailToInitializePlugin(String mimeType, String frameURLString, String pageURLString) + DidBlockInsecurePluginVersion(String mimeType, String pluginURLString, String frameURLString, String pageURLString, bool replacementObscured) +#endif // ENABLE(NETSCAPE_PLUGIN_API) SetCanShortCircuitHorizontalWheelEvents(bool canShortCircuitHorizontalWheelEvents) #if PLATFORM(EFL) HandleInputMethodKeydown() -> (bool handled) #endif -#if USE(TILED_BACKING_STORE) +#if USE(COORDINATED_GRAPHICS_MULTIPROCESS) PageDidRequestScroll(WebCore::IntPoint point) PageTransitionViewportReady() -#endif -#if USE(COORDINATED_GRAPHICS) DidFindZoomableArea(WebCore::IntPoint target, WebCore::IntRect area) #endif #if PLATFORM(QT) - AuthenticationRequiredRequest(WTF::String hostname, WTF::String realm, WTF::String prefilledUsername) -> (WTF::String username, WTF::String password) - CertificateVerificationRequest(WTF::String hostname) -> (bool ignoreErrors) - ProxyAuthenticationRequiredRequest(WTF::String hostname, uint16_t port, WTF::String prefilledUsername) -> (WTF::String username, WTF::String password) + AuthenticationRequiredRequest(String hostname, String realm, String prefilledUsername) -> (String username, String password) + CertificateVerificationRequest(String hostname) -> (bool ignoreErrors) + ProxyAuthenticationRequiredRequest(String hostname, uint16_t port, String prefilledUsername) -> (String username, String password) #endif -#if PLATFORM(QT) || PLATFORM(EFL) - DidChangeContentsSize(WebCore::IntSize newSize) -#endif - -#if ENABLE(TOUCH_EVENTS) - NeedTouchEvents(bool needTouchEvents) -#endif + DidChangeContentSize(WebCore::IntSize newSize) #if ENABLE(INPUT_TYPE_COLOR) - ShowColorChooser(WebCore::Color initialColor, WebCore::IntRect elementRect); - SetColorChooserColor(WebCore::Color color); - EndColorChooser(); + ShowColorPicker(WebCore::Color initialColor, WebCore::IntRect elementRect); + SetColorPickerColor(WebCore::Color color); + EndColorPicker(); #endif # Policy messages - DecidePolicyForResponseSync(uint64_t frameID, WebCore::ResourceResponse response, WebCore::ResourceRequest request, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) -> (bool receivedPolicyAction, uint64_t policyAction, uint64_t downloadID) Variadic - DecidePolicyForNavigationAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, WebCore::ResourceRequest request, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) -> (bool receivedPolicyAction, uint64_t policyAction, uint64_t downloadID) Variadic - DecidePolicyForNewWindowAction(uint64_t frameID, uint32_t navigationType, uint32_t modifiers, int32_t mouseButton, WebCore::ResourceRequest request, WTF::String frameName, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - UnableToImplementPolicy(uint64_t frameID, WebCore::ResourceError error, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + DecidePolicyForResponseSync(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, WebCore::ResourceResponse response, WebCore::ResourceRequest request, bool canShowMIMEType, uint64_t listenerID, WebKit::UserData userData) -> (bool receivedPolicyAction, uint64_t policyAction, WebKit::DownloadID downloadID) + DecidePolicyForNavigationAction(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, uint64_t navigationID, struct WebKit::NavigationActionData navigationActionData, uint64_t originatingFrameID, struct WebCore::SecurityOriginData originatingFrameSecurityOrigin, WebCore::ResourceRequest originalRequest, WebCore::ResourceRequest request, uint64_t listenerID, WebKit::UserData userData) -> (bool receivedPolicyAction, uint64_t newNavigationID, uint64_t policyAction, WebKit::DownloadID downloadID) + DecidePolicyForNewWindowAction(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, struct WebKit::NavigationActionData navigationActionData, WebCore::ResourceRequest request, String frameName, uint64_t listenerID, WebKit::UserData userData) + UnableToImplementPolicy(uint64_t frameID, WebCore::ResourceError error, WebKit::UserData userData) # Progress messages DidChangeProgress(double value) DidFinishProgress() DidStartProgress() + SetNetworkRequestsInProgress(bool networkRequestsInProgress) + # Frame lifetime messages DidCreateMainFrame(uint64_t frameID) DidCreateSubframe(uint64_t frameID) # Frame load messages - DidCommitLoadForFrame(uint64_t frameID, WTF::String mimeType, uint32_t loadType, WebKit::PlatformCertificateInfo certificateInfo, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidFailLoadForFrame(uint64_t frameID, WebCore::ResourceError error, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidFailProvisionalLoadForFrame(uint64_t frameID, WebCore::ResourceError error, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidFinishDocumentLoadForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidFinishLoadForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidFirstLayoutForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidNewFirstVisuallyNonEmptyLayout(WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidLayout(uint32_t type, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, WTF::String url, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidRemoveFrameFromHierarchy(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidStartProvisionalLoadForFrame(uint64_t frameID, WTF::String url, WTF::String unreachableURL, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidReceiveTitleForFrame(uint64_t frameID, WTF::String title, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidDisplayInsecureContentForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidRunInsecureContentForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidDetectXSSForFrame(uint64_t frameID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic - DidSameDocumentNavigationForFrame(uint64_t frameID, uint32_t type, WTF::String url, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + DidStartProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, String url, String unreachableURL, WebKit::UserData userData) + DidReceiveServerRedirectForProvisionalLoadForFrame(uint64_t frameID, uint64_t navigationID, String url, WebKit::UserData userData) + DidChangeProvisionalURLForFrame(uint64_t frameID, uint64_t navigationID, String url) + DidFailProvisionalLoadForFrame(uint64_t frameID, struct WebCore::SecurityOriginData frameSecurityOrigin, uint64_t navigationID, String provisionalURL, WebCore::ResourceError error, WebKit::UserData userData) + DidCommitLoadForFrame(uint64_t frameID, uint64_t navigationID, String mimeType, bool hasCustomContentProvider, bool pluginHandlesPageScaleGesture, uint32_t loadType, WebCore::CertificateInfo certificateInfo, bool containsPluginDocument, WebKit::UserData userData) + DidFailLoadForFrame(uint64_t frameID, uint64_t navigationID, WebCore::ResourceError error, WebKit::UserData userData) + DidFinishDocumentLoadForFrame(uint64_t frameID, uint64_t navigationID, WebKit::UserData userData) + DidFinishLoadForFrame(uint64_t frameID, uint64_t navigationID, WebKit::UserData userData) + DidFirstLayoutForFrame(uint64_t frameID, WebKit::UserData userData) + DidFirstVisuallyNonEmptyLayoutForFrame(uint64_t frameID, WebKit::UserData userData) + DidLayout(uint32_t type) + DidReceiveTitleForFrame(uint64_t frameID, String title, WebKit::UserData userData) + DidDisplayInsecureContentForFrame(uint64_t frameID, WebKit::UserData userData) + DidRunInsecureContentForFrame(uint64_t frameID, WebKit::UserData userData) + DidDetectXSSForFrame(uint64_t frameID, WebKit::UserData userData) + DidSameDocumentNavigationForFrame(uint64_t frameID, uint64_t navigationID, uint32_t type, String url, WebKit::UserData userData) + DidDestroyNavigation(uint64_t navigationID) FrameDidBecomeFrameSet(uint64_t frameID, bool value) @@ -140,30 +151,67 @@ messages -> WebPageProxy { ResolveApplicationSchemeRequest(WebKit::QtNetworkRequestData request) #endif + # History client messages. + DidNavigateWithNavigationData(struct WebKit::WebNavigationDataStore store, uint64_t frameID) + DidPerformClientRedirect(String sourceURLString, String destinationURLString, uint64_t frameID) + DidPerformServerRedirect(String sourceURLString, String destinationURLString, uint64_t frameID) + DidUpdateHistoryTitle(String title, String url, uint64_t frameID) + + # Custom representations + DidFinishLoadingDataForCustomContentProvider(String suggestedFilename, IPC::DataReference data) + # Forms messages - WillSubmitForm(uint64_t frameID, uint64_t sourceFrameID, WTF::Vector<std::pair<WTF::String, WTF::String> > textFieldValues, uint64_t listenerID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + WillSubmitForm(uint64_t frameID, uint64_t sourceFrameID, Vector<std::pair<String, String>> textFieldValues, uint64_t listenerID, WebKit::UserData userData) # Callback messages VoidCallback(uint64_t callbackID) - DataCallback(CoreIPC::DataReference resultData, uint64_t callbackID) + DataCallback(IPC::DataReference resultData, uint64_t callbackID) ImageCallback(WebKit::ShareableBitmap::Handle bitmapHandle, uint64_t callbackID) - StringCallback(WTF::String resultString, uint64_t callbackID) - ScriptValueCallback(CoreIPC::DataReference resultData, uint64_t callbackID) + StringCallback(String resultString, uint64_t callbackID) + ScriptValueCallback(IPC::DataReference resultData, bool hadException, struct WebCore::ExceptionDetails details, uint64_t callbackID) ComputedPagesCallback(Vector<WebCore::IntRect> pageRects, double totalScaleFactorForPrinting, uint64_t callbackID) - ValidateCommandCallback(WTF::String command, bool isEnabled, int32_t state, uint64_t callbackID) + ValidateCommandCallback(String command, bool isEnabled, int32_t state, uint64_t callbackID) + EditingRangeCallback(struct WebKit::EditingRange range, uint64_t callbackID) + UnsignedCallback(uint64_t result, uint64_t callbackID) + RectForCharacterRangeCallback(WebCore::IntRect rect, struct WebKit::EditingRange actualRange, uint64_t callbackID) +#if PLATFORM(MAC) + AttributedStringForCharacterRangeCallback(struct WebKit::AttributedString string, struct WebKit::EditingRange actualRange, uint64_t callbackID) + FontAtSelectionCallback(String fontName, double fontSize, bool selectioHasMultipleFonts, uint64_t callbackID) +#endif +#if PLATFORM(IOS) + GestureCallback(WebCore::IntPoint point, uint32_t gestureType, uint32_t gestureState, uint32_t flags, uint64_t callbackID) + TouchesCallback(WebCore::IntPoint point, uint32_t touches, uint64_t callbackID) + AutocorrectionDataCallback(Vector<WebCore::FloatRect> textRects, String fontName, double fontSize, uint64_t traits, uint64_t callbackID) + AutocorrectionContextCallback(String beforeText, String markedText, String selectedText, String afterText, uint64_t location, uint64_t length, uint64_t callbackID) + DictationContextCallback(String selectedText, String beforeText, String afterText, uint64_t callbackID) + InterpretKeyEvent(struct WebKit::EditorState state, bool isCharEvent) -> (bool handled) + DidReceivePositionInformation(struct WebKit::InteractionInformationAtPosition information) + SaveImageToLibrary(WebKit::SharedMemory::Handle handle, uint64_t size) + DidUpdateBlockSelectionWithTouch(uint32_t touch, uint32_t flags, float growThreshold, float shrinkThreshold) + ShowPlaybackTargetPicker(bool hasVideo, WebCore::IntRect elementRect) + ZoomToRect(WebCore::FloatRect rect, double minimumScale, double maximumScale) + CommitPotentialTapFailed() + DidNotHandleTapAsClick(WebCore::IntPoint point) + DisableDoubleTapGesturesDuringTapIfNecessary(uint64_t requestID) + DidFinishDrawingPagesToPDF(IPC::DataReference pdfData) +#endif +#if ENABLE(DATA_DETECTION) + SetDataDetectionResult(struct WebKit::DataDetectionResult dataDetectionResult) +#endif #if PLATFORM(GTK) PrintFinishedCallback(WebCore::ResourceError error, uint64_t callbackID) #endif +#if PLATFORM(COCOA) + MachSendRightCallback(WebCore::MachSendRight sendRight, uint64_t callbackID) +#endif PageScaleFactorDidChange(double scaleFactor) - PageZoomFactorDidChange(double zoomFactor) + PluginScaleFactorDidChange(double zoomFactor) + PluginZoomFactorDidChange(double zoomFactor) #if PLATFORM(GTK) - # Support for GTK+ platform keybindings - GetEditorCommandsForKeyEvent(AtomicString eventType) -> (Vector<WTF::String> commandsList) - # Support for connecting the Accessibility worlds of the UI and the Web processes - BindAccessibilityTree(WTF::String plugID) + BindAccessibilityTree(String plugID) SetInputMethodState(bool enabled); #endif @@ -175,35 +223,43 @@ messages -> WebPageProxy { BackForwardBackListCount() -> (int32_t count) BackForwardForwardListCount() -> (int32_t count) BackForwardClear() - ShouldGoToBackForwardListItem(uint64_t itemID) -> (bool shouldGoToBackForwardListItem) - WillGoToBackForwardListItem(uint64_t itemID, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + WillGoToBackForwardListItem(uint64_t itemID, WebKit::UserData userData) # Undo/Redo messages RegisterEditCommandForUndo(uint64_t commandID, uint32_t editAction) ClearAllEditCommands() + RegisterInsertionUndoGrouping() CanUndoRedo(uint32_t action) -> (bool result) ExecuteUndoRedo(uint32_t action) -> (bool result) + # Diagnostic messages logging + LogSampledDiagnosticMessage(String message, String description) + LogSampledDiagnosticMessageWithResult(String message, String description, uint32_t result) + LogSampledDiagnosticMessageWithValue(String message, String description, String value) + # Editor notifications - EditorStateChanged(WebKit::EditorState editorState) + EditorStateChanged(struct WebKit::EditorState editorState) + CompositionWasCanceled(struct WebKit::EditorState editorState) + #if PLATFORM(QT) WillSetInputMethodState() #endif + # Find messages - DidCountStringMatches(WTF::String string, uint32_t matchCount) - SetFindIndicator(WebCore::FloatRect selectionRect, Vector<WebCore::FloatRect> textRects, float contentImageScaleFactor, WebKit::ShareableBitmap::Handle contentImageHandle, bool fadeOut, bool animate) - DidFindString(WTF::String string, uint32_t matchCount) - DidFailToFindString(WTF::String string) - DidFindStringMatches(WTF::String string, Vector<Vector<WebCore::IntRect> > matches, int32_t firstIndexAfterSelection) + DidCountStringMatches(String string, uint32_t matchCount) + SetTextIndicator(struct WebCore::TextIndicatorData indicator, uint64_t lifetime) + ClearTextIndicator() + DidFindString(String string, Vector<WebCore::IntRect> matchRect, uint32_t matchCount, int32_t matchIndex) + DidFailToFindString(String string) + DidFindStringMatches(String string, Vector<Vector<WebCore::IntRect>> matches, int32_t firstIndexAfterSelection) DidGetImageForFindMatch(WebKit::ShareableBitmap::Handle contentImageHandle, uint32_t matchIndex) # PopupMenu messages - ShowPopupMenu(WebCore::IntRect rect, uint64_t textDirection, Vector<WebKit::WebPopupItem> items, int32_t selectedIndex, WebKit::PlatformPopupMenuData data) + ShowPopupMenu(WebCore::IntRect rect, uint64_t textDirection, Vector<WebKit::WebPopupItem> items, int32_t selectedIndex, struct WebKit::PlatformPopupMenuData data) HidePopupMenu() #if ENABLE(CONTEXT_MENUS) - # ContextMenu messages - ShowContextMenu(WebCore::IntPoint menuLocation, WebKit::WebHitTestResult::Data hitTestResultData, Vector<WebKit::WebContextMenuItemData> items, WebKit::InjectedBundleUserMessageEncoder userData) Variadic + ShowContextMenu(WebKit::ContextMenuContextData contextMenuContextData, WebKit::UserData userData) #endif # Authentication messages @@ -211,54 +267,65 @@ messages -> WebPageProxy { DidReceiveAuthenticationChallenge(uint64_t frameID, WebCore::AuthenticationChallenge challenge, uint64_t challengeID) # Database messages - ExceededDatabaseQuota(uint64_t frameID, WTF::String originIdentifier, WTF::String databaseName, WTF::String databaseDisplayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage) -> (uint64_t newQuota) Delayed + ExceededDatabaseQuota(uint64_t frameID, String originIdentifier, String databaseName, String databaseDisplayName, uint64_t currentQuota, uint64_t currentOriginUsage, uint64_t currentDatabaseUsage, uint64_t expectedUsage) -> (uint64_t newQuota) Delayed + + # Application cache messages + ReachedApplicationCacheOriginQuota(String originIdentifier, uint64_t currentQuota, uint64_t totalBytesNeeded) -> (uint64_t newQuota) Delayed # Geolocation messages - RequestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, WTF::String originIdentifier) + RequestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, String originIdentifier) +#if ENABLE(MEDIA_STREAM) + # MediaSteam messages + RequestUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String originIdentifier, Vector<String> audioDeviceUIDs, Vector<String> videoDeviceUIDs) + CheckUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String originIdentifier) +#endif + # Notification messages - RequestNotificationPermission(uint64_t requestID, WTF::String originIdentifier) - ShowNotification(WTF::String title, WTF::String body, WTF::String iconURL, WTF::String tag, WTF::String lang, WTF::String dir, WTF::String originIdentifier, uint64_t notificationID) + RequestNotificationPermission(uint64_t requestID, String originIdentifier) + ShowNotification(String title, String body, String iconURL, String tag, String lang, String dir, String originIdentifier, uint64_t notificationID) CancelNotification(uint64_t notificationID) ClearNotifications(Vector<uint64_t> notificationIDs) DidDestroyNotification(uint64_t notificationID) # Spelling and grammar messages #if USE(UNIFIED_TEXT_CHECKING) - CheckTextOfParagraph(WTF::String text, uint64_t checkingTypes) -> (Vector<WebCore::TextCheckingResult> results) + CheckTextOfParagraph(String text, uint64_t checkingTypes) -> (Vector<WebCore::TextCheckingResult> results) #endif - CheckSpellingOfString(WTF::String text) -> (int32_t misspellingLocation, int32_t misspellingLength) - CheckGrammarOfString(WTF::String text) -> (Vector<WebCore::GrammarDetail> results, int32_t badGrammarLocation, int32_t badGrammarLength) + CheckSpellingOfString(String text) -> (int32_t misspellingLocation, int32_t misspellingLength) + CheckGrammarOfString(String text) -> (Vector<WebCore::GrammarDetail> results, int32_t badGrammarLocation, int32_t badGrammarLength) SpellingUIIsShowing() -> (bool isShowing) - UpdateSpellingUIWithMisspelledWord(WTF::String misspelledWord) - UpdateSpellingUIWithGrammarString(WTF::String badGrammarPhrase, WebCore::GrammarDetail grammarDetail) - GetGuessesForWord(WTF::String word, WTF::String context) -> (Vector<WTF::String> guesses) - LearnWord(WTF::String word); - IgnoreWord(WTF::String word); + UpdateSpellingUIWithMisspelledWord(String misspelledWord) + UpdateSpellingUIWithGrammarString(String badGrammarPhrase, struct WebCore::GrammarDetail grammarDetail) + GetGuessesForWord(String word, String context) -> (Vector<String> guesses) + LearnWord(String word); + IgnoreWord(String word); RequestCheckingOfString(uint64_t requestID, WebCore::TextCheckingRequestData request) # Drag and drop messages #if ENABLE(DRAG_SUPPORT) - DidPerformDragControllerAction(WebCore::DragSession dragSession) + DidPerformDragControllerAction(uint64_t dragOperation, bool mouseIsOverFileInput, unsigned numberOfItemsToBeAccepted) #endif -#if PLATFORM(MAC) && ENABLE(DRAG_SUPPORT) +#if PLATFORM(COCOA) && ENABLE(DRAG_SUPPORT) SetDragImage(WebCore::IntPoint clientPosition, WebKit::ShareableBitmap::Handle dragImage, bool linkDrag) - SetPromisedData(WTF::String pasteboardName, WebKit::SharedMemory::Handle imageHandle, uint64_t imageSize, WTF::String filename, WTF::String extension, WTF::String title, WTF::String url, WTF::String visibleURL, WebKit::SharedMemory::Handle archiveHandle, uint64_t archiveSize) + SetPromisedDataForImage(String pasteboardName, WebKit::SharedMemory::Handle imageHandle, uint64_t imageSize, String filename, String extension, String title, String url, String visibleURL, WebKit::SharedMemory::Handle archiveHandle, uint64_t archiveSize) +#if ENABLE(ATTACHMENT_ELEMENT) + SetPromisedDataForAttachment(String pasteboardName, String filename, String extension, String title, String url, String visibleURL) +#endif #endif #if (PLATFORM(QT) || PLATFORM(GTK)) && ENABLE(DRAG_SUPPORT) StartDrag(WebCore::DragData dragData, WebKit::ShareableBitmap::Handle dragImage) #endif -#if PLATFORM(MAC) +#if PLATFORM(COCOA) # Dictionary support. - DidPerformDictionaryLookup(WebKit::AttributedString text, WebKit::DictionaryPopupInfo dictionaryPopupInfo) + DidPerformDictionaryLookup(struct WebCore::DictionaryPopupInfo dictionaryPopupInfo) # Keyboard input support messages - InterpretQueuedKeyEvent(WebKit::EditorState state) -> (bool handled, Vector<WebCore::KeypressCommand> savedCommands) - ExecuteSavedCommandBySelector(WTF::String selector) -> (bool handled) + ExecuteSavedCommandBySelector(String selector) -> (bool handled) # Remote accessibility messages - RegisterWebProcessAccessibilityToken(CoreIPC::DataReference data) + RegisterWebProcessAccessibilityToken(IPC::DataReference data) # Plug-in complex text input support messages PluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus) @@ -266,18 +333,18 @@ messages -> WebPageProxy { # Speech messages GetIsSpeaking() -> (bool isSpeaking) - Speak(WTF::String string) + Speak(String string) StopSpeaking() MakeFirstResponder() # Spotlight - SearchWithSpotlight(WTF::String string) + SearchWithSpotlight(String string) - SearchTheWeb(WTF::String string) + SearchTheWeb(String string) #endif -#if PLATFORM(MAC) +#if USE(APPKIT) SubstitutionsPanelIsShowing() -> (bool isShowing) #endif #if PLATFORM(MAC) @@ -298,29 +365,107 @@ messages -> WebPageProxy { # X11 windowed plugin messages CreatePluginContainer() -> (uint64_t windowID) WindowedPluginGeometryDidChange(WebCore::IntRect frameRect, WebCore::IntRect clipRect, uint64_t windowID) + WindowedPluginVisibilityDidChange(bool isVisible, uint64_t windowID) #endif - # Search popup menus - SaveRecentSearches(WTF::String name, Vector<String> searchItems) - LoadRecentSearches(WTF::String name) -> (Vector<String> result) - -#if USE(SOUP) - # Soup custom URI request messages - DidReceiveURIRequest(WTF::String uriString, uint64_t requestID); +#if PLATFORM(IOS) + DynamicViewportUpdateChangedTarget(double newTargetScale, WebCore::FloatPoint newScrollPosition, uint64_t dynamicViewportSizeUpdateID) + CouldNotRestorePageState() + RestorePageState(WebCore::FloatRect exposedRect, double scale) + RestorePageCenterAndScale(WebCore::FloatPoint unobscuredCenter, double scale) + DidGetTapHighlightGeometries(uint64_t requestID, WebCore::Color color, Vector<WebCore::FloatQuad> geometries, WebCore::IntSize topLeftRadius, WebCore::IntSize topRightRadius, WebCore::IntSize bottomLeftRadius, WebCore::IntSize bottomRightRadius) + + StartAssistingNode(struct WebKit::AssistedNodeInformation information, bool userIsInteracting, bool blurPreviousNode, WebKit::UserData userData) + StopAssistingNode() + OverflowScrollWillStartScroll() + OverflowScrollDidEndScroll() + ShowInspectorHighlight(struct WebCore::Highlight highlight) + HideInspectorHighlight() + + ShowInspectorIndication() + HideInspectorIndication() + + EnableInspectorNodeSearch() + DisableInspectorNodeSearch() #endif - SavePDFToFileInDownloadsFolder(WTF::String suggestedFilename, WTF::String originatingURLString, CoreIPC::DataReference data) + # Search popup menus + SaveRecentSearches(String name, Vector<WebCore::RecentSearch> searchItems) + LoadRecentSearches(String name) -> (Vector<WebCore::RecentSearch> result) + + SavePDFToFileInDownloadsFolder(String suggestedFilename, String originatingURLString, IPC::DataReference data) -#if PLATFORM(MAC) - SavePDFToTemporaryFolderAndOpenWithNativeApplication(WTF::String suggestedFilename, WTF::String originatingURLString, CoreIPC::DataReference data, WTF::String pdfUUID) - OpenPDFFromTemporaryFolderWithNativeApplication(WTF::String pdfUUID) +#if PLATFORM(COCOA) + SavePDFToTemporaryFolderAndOpenWithNativeApplication(String suggestedFilename, String originatingURLString, IPC::DataReference data, String pdfUUID) + OpenPDFFromTemporaryFolderWithNativeApplication(String pdfUUID) #endif #if ENABLE(NETSCAPE_PLUGIN_API) - FindPlugin(WTF::String mimeType, uint32_t processType, WTF::String urlString, WTF::String frameURLString, WTF::String pageURLString, bool allowOnlyApplicationPlugins) -> (uint64_t pluginProcessToken, WTF::String newMIMEType, uint32_t pluginLoadPolicy, WTF::String unavailabilityDescription) + FindPlugin(String mimeType, uint32_t processType, String urlString, String frameURLString, String pageURLString, bool allowOnlyApplicationPlugins) -> (uint64_t pluginProcessToken, String newMIMEType, uint32_t pluginLoadPolicy, String unavailabilityDescription) #endif - DidUpdateInWindowState() + DidUpdateViewState() DidSaveToPageCache() + +#if ENABLE(SUBTLE_CRYPTO) + WrapCryptoKey(Vector<uint8_t> key) -> (bool succeeded, Vector<uint8_t> wrappedKey) + UnwrapCryptoKey(Vector<uint8_t> wrappedKey) -> (bool succeeded, Vector<uint8_t> key) +#endif + + +#if ENABLE(TELEPHONE_NUMBER_DETECTION) +#if PLATFORM(MAC) + ShowTelephoneNumberMenu(String telephoneNumber, WebCore::IntPoint point) +#endif +#endif + +#if USE(QUICK_LOOK) + DidStartLoadForQuickLookDocumentInMainFrame(String fileName, String uti) + DidFinishLoadForQuickLookDocumentInMainFrame(WebKit::QuickLookDocumentData data) +#endif + +#if ENABLE(CONTENT_FILTERING) + ContentFilterDidBlockLoadForFrame(WebCore::ContentFilterUnblockHandler unblockHandler, uint64_t frameID) +#endif + + IsPlayingMediaDidChange(unsigned state, uint64_t sourceElementID) + +#if ENABLE(MEDIA_SESSION) + HasMediaSessionWithActiveMediaElementsDidChange(bool state) + MediaSessionMetadataDidChange(WebCore::MediaSessionMetadata metadata); + FocusedContentMediaElementDidChange(uint64_t elementID) +#endif + +#if PLATFORM(MAC) + DidPerformImmediateActionHitTest(struct WebKit::WebHitTestResultData result, bool contentPreventsDefault, WebKit::UserData userData) +#endif + HandleMessage(String messageName, WebKit::UserData messageBody) WantsConnection + HandleSynchronousMessage(String messageName, WebKit::UserData messageBody) -> (WebKit::UserData returnData) WantsConnection + + HandleAutoFillButtonClick(WebKit::UserData userData); + +#if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS) + AddPlaybackTargetPickerClient(uint64_t contextId) + RemovePlaybackTargetPickerClient(uint64_t contextId) + ShowPlaybackTargetPicker(uint64_t clientId, WebCore::FloatRect pickerLocation, bool hasVideo) + PlaybackTargetPickerClientStateDidChange(uint64_t contextId, unsigned mediaState) + SetMockMediaPlaybackTargetPickerEnabled(bool enabled) + SetMockMediaPlaybackTargetPickerState(String name, unsigned pickerState) +#endif + + ImageOrMediaDocumentSizeChanged(WebCore::IntSize newSize) + + UseFixedLayoutDidChange(bool useFixedLayout) + FixedLayoutSizeDidChange(WebCore::IntSize fixedLayoutSize) + +#if ENABLE(VIDEO) && USE(GSTREAMER) + RequestInstallMissingMediaPlugins(String details, String description) +#endif + + DidRestoreScrollPosition() + +#if PLATFORM(MAC) + DidHandleAcceptedCandidate() +#endif } diff --git a/Source/WebKit2/UIProcess/efl/WebProcessProxyEfl.cpp b/Source/WebKit2/UIProcess/WebPasteboardProxy.cpp index 9ea9cfc3c..9097cb52b 100644 --- a/Source/WebKit2/UIProcess/efl/WebProcessProxyEfl.cpp +++ b/Source/WebKit2/UIProcess/WebPasteboardProxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Apple Inc. All rights reserved. + * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,19 +24,34 @@ */ #include "config.h" +#include "WebPasteboardProxy.h" + +#include "WebPasteboardProxyMessages.h" #include "WebProcessProxy.h" +#include <mutex> namespace WebKit { -void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) +WebPasteboardProxy& WebPasteboardProxy::singleton() +{ + static std::once_flag onceFlag; + static LazyNeverDestroyed<WebPasteboardProxy> proxy; + + std::call_once(onceFlag, [] { + proxy.construct(); + }); + + return proxy; +} + +WebPasteboardProxy::WebPasteboardProxy() +{ +} + +void WebPasteboardProxy::addWebProcessProxy(WebProcessProxy& webProcessProxy) { -#ifndef NDEBUG - const char* webProcessCmdPrefix = getenv("WEB_PROCESS_CMD_PREFIX"); - if (webProcessCmdPrefix && *webProcessCmdPrefix) - launchOptions.processCmdPrefix = String::fromUTF8(webProcessCmdPrefix); -#else - UNUSED_PARAM(launchOptions); -#endif + // FIXME: Can we handle all of these on a background queue? + webProcessProxy.addMessageReceiver(Messages::WebPasteboardProxy::messageReceiverName(), *this); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPasteboardProxy.h b/Source/WebKit2/UIProcess/WebPasteboardProxy.h new file mode 100644 index 000000000..494aac9f8 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebPasteboardProxy.h @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2014 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 WebPasteboardProxy_h +#define WebPasteboardProxy_h + +#include "MessageReceiver.h" +#include "SharedMemory.h" +#include <wtf/Forward.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/Vector.h> + +namespace WebCore { +class Color; +struct PasteboardImage; +struct PasteboardWebContent; +} + +namespace WebKit { + +class WebProcessProxy; + +class WebPasteboardProxy : public IPC::MessageReceiver { + WTF_MAKE_NONCOPYABLE(WebPasteboardProxy); + friend class LazyNeverDestroyed<WebPasteboardProxy>; +public: + static WebPasteboardProxy& singleton(); + + void addWebProcessProxy(WebProcessProxy&); + +private: + WebPasteboardProxy(); + + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; + +#if PLATFORM(IOS) + void writeWebContentToPasteboard(const WebCore::PasteboardWebContent&); + void writeImageToPasteboard(const WebCore::PasteboardImage&); + void writeStringToPasteboard(const String& pasteboardType, const String&); + void readStringFromPasteboard(uint64_t index, const String& pasteboardType, WTF::String&); + void readURLFromPasteboard(uint64_t index, const String& pasteboardType, String&); + void readBufferFromPasteboard(uint64_t index, const String& pasteboardType, SharedMemory::Handle&, uint64_t& size); + void getPasteboardItemsCount(uint64_t& itemsCount); +#endif +#if PLATFORM(COCOA) + void getPasteboardTypes(const String& pasteboardName, Vector<String>& pasteboardTypes); + void getPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, Vector<String>& pathnames); + void getPasteboardStringForType(const String& pasteboardName, const String& pasteboardType, String&); + void getPasteboardBufferForType(const String& pasteboardName, const String& pasteboardType, SharedMemory::Handle&, uint64_t& size); + void pasteboardCopy(const String& fromPasteboard, const String& toPasteboard, uint64_t& newChangeCount); + void getPasteboardChangeCount(const String& pasteboardName, uint64_t& changeCount); + void getPasteboardUniqueName(String& pasteboardName); + void getPasteboardColor(const String& pasteboardName, WebCore::Color&); + void getPasteboardURL(const String& pasteboardName, WTF::String&); + void addPasteboardTypes(const String& pasteboardName, const Vector<String>& pasteboardTypes, uint64_t& newChangeCount); + void setPasteboardTypes(const String& pasteboardName, const Vector<String>& pasteboardTypes, uint64_t& newChangeCount); + void setPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, const Vector<String>& pathnames, uint64_t& newChangeCount); + void setPasteboardStringForType(const String& pasteboardName, const String& pasteboardType, const String&, uint64_t& newChangeCount); + void setPasteboardBufferForType(const String& pasteboardName, const String& pasteboardType, const SharedMemory::Handle&, uint64_t size, uint64_t& newChangeCount); +#endif +}; + +} // namespace WebKit + +#endif // WebPasteboardProxy_h diff --git a/Source/WebKit2/UIProcess/WebPasteboardProxy.messages.in b/Source/WebKit2/UIProcess/WebPasteboardProxy.messages.in new file mode 100644 index 000000000..d0d9fa12e --- /dev/null +++ b/Source/WebKit2/UIProcess/WebPasteboardProxy.messages.in @@ -0,0 +1,51 @@ +# Copyright (C) 2014 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. + +messages -> WebPasteboardProxy { +#if PLATFORM(IOS) + WriteWebContentToPasteboard(struct WebCore::PasteboardWebContent content) + WriteImageToPasteboard(struct WebCore::PasteboardImage pasteboardImage) + WriteStringToPasteboard(String pasteboardType, String text) + ReadStringFromPasteboard(uint64_t index, String pasteboardType) -> (String string) + ReadURLFromPasteboard(uint64_t index, String pasteboardType) -> (String string) + ReadBufferFromPasteboard(uint64_t index, String pasteboardType) -> (WebKit::SharedMemory::Handle handle, uint64_t size) + GetPasteboardItemsCount() -> (uint64_t itemsCount) +#endif + +#if PLATFORM(COCOA) + # Pasteboard messages. + GetPasteboardTypes(String pasteboardName) -> (Vector<String> types) + GetPasteboardPathnamesForType(String pasteboardName, String pasteboardType) -> (Vector<String> pathnames) + GetPasteboardStringForType(String pasteboardName, String pasteboardType) -> (String string) + GetPasteboardBufferForType(String pasteboardName, String pasteboardType) -> (WebKit::SharedMemory::Handle handle, uint64_t size) + PasteboardCopy(String fromPasteboard, String toPasteboard) -> (uint64_t changeCount) + GetPasteboardChangeCount(String pasteboardName) -> (uint64_t changeCount) + GetPasteboardUniqueName() -> (String pasteboardName) + GetPasteboardColor(String pasteboardName) -> (WebCore::Color color) + GetPasteboardURL(String pasteboardName) -> (String urlString) + AddPasteboardTypes(String pasteboardName, Vector<String> pasteboardTypes) -> (uint64_t changeCount) + SetPasteboardTypes(String pasteboardName, Vector<String> pasteboardTypes) -> (uint64_t changeCount) + SetPasteboardPathnamesForType(String pasteboardName, String pasteboardType, Vector<String> pathnames) -> (uint64_t changeCount) + SetPasteboardStringForType(String pasteboardName, String pasteboardType, String string) -> (uint64_t changeCount) + SetPasteboardBufferForType(String pasteboardName, String pasteboardType, WebKit::SharedMemory::Handle handle, uint64_t size) -> (uint64_t changeCount) +#endif +} diff --git a/Source/WebKit2/UIProcess/WebPolicyClient.cpp b/Source/WebKit2/UIProcess/WebPolicyClient.cpp deleted file mode 100644 index c57c896b3..000000000 --- a/Source/WebKit2/UIProcess/WebPolicyClient.cpp +++ /dev/null @@ -1,79 +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 "WebPolicyClient.h" - -#include "APIObject.h" -#include "WKAPICast.h" -#include "WebURLRequest.h" - -using namespace WebCore; - -namespace WebKit { - -bool WebPolicyClient::decidePolicyForNavigationAction(WebPageProxy* page, WebFrameProxy* frame, NavigationType type, WebEvent::Modifiers modifiers, WebMouseEvent::Button mouseButton, const ResourceRequest& resourceRequest, WebFramePolicyListenerProxy* listener, APIObject* userData) -{ - if (!m_client.decidePolicyForNavigationAction) - return false; - - RefPtr<WebURLRequest> request = WebURLRequest::create(resourceRequest); - - m_client.decidePolicyForNavigationAction(toAPI(page), toAPI(frame), toAPI(type), toAPI(modifiers), toAPI(mouseButton), toAPI(request.get()), toAPI(listener), toAPI(userData), m_client.clientInfo); - return true; -} - -bool WebPolicyClient::decidePolicyForNewWindowAction(WebPageProxy* page, WebFrameProxy* frame, NavigationType type, WebEvent::Modifiers modifiers, WebMouseEvent::Button mouseButton, const ResourceRequest& resourceRequest, const String& frameName, WebFramePolicyListenerProxy* listener, APIObject* userData) -{ - if (!m_client.decidePolicyForNewWindowAction) - return false; - - RefPtr<WebURLRequest> request = WebURLRequest::create(resourceRequest); - - m_client.decidePolicyForNewWindowAction(toAPI(page), toAPI(frame), toAPI(type), toAPI(modifiers), toAPI(mouseButton), toAPI(request.get()), toAPI(frameName.impl()), toAPI(listener), toAPI(userData), m_client.clientInfo); - return true; -} - -bool WebPolicyClient::decidePolicyForResponse(WebPageProxy* page, WebFrameProxy* frame, const ResourceResponse& resourceResponse, const ResourceRequest& resourceRequest, WebFramePolicyListenerProxy* listener, APIObject* userData) -{ - if (!m_client.decidePolicyForResponse) - return false; - - RefPtr<WebURLResponse> response = WebURLResponse::create(resourceResponse); - RefPtr<WebURLRequest> request = WebURLRequest::create(resourceRequest); - - m_client.decidePolicyForResponse(toAPI(page), toAPI(frame), toAPI(response.get()), toAPI(request.get()), toAPI(listener), toAPI(userData), m_client.clientInfo); - return true; -} - -void WebPolicyClient::unableToImplementPolicy(WebPageProxy* page, WebFrameProxy* frame, const ResourceError& error, APIObject* userData) -{ - if (!m_client.unableToImplementPolicy) - return; - - m_client.unableToImplementPolicy(toAPI(page), toAPI(frame), toAPI(error), toAPI(userData), m_client.clientInfo); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPopupMenuProxy.h b/Source/WebKit2/UIProcess/WebPopupMenuProxy.h index 1caf8dd64..a4c28fc72 100644 --- a/Source/WebKit2/UIProcess/WebPopupMenuProxy.h +++ b/Source/WebKit2/UIProcess/WebPopupMenuProxy.h @@ -26,7 +26,7 @@ #ifndef WebPopupMenuProxy_h #define WebPopupMenuProxy_h -#include <WebCore/TextDirection.h> +#include <WebCore/WritingMode.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/Vector.h> @@ -70,12 +70,13 @@ public: virtual void showPopupMenu(const WebCore::IntRect& rect, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, const PlatformPopupMenuData&, int32_t selectedIndex) = 0; virtual void hidePopupMenu() = 0; #endif + virtual void cancelTracking() { } void invalidate() { m_client = 0; } protected: - explicit WebPopupMenuProxy(Client* client) - : m_client(client) + explicit WebPopupMenuProxy(Client& client) + : m_client(&client) { } diff --git a/Source/WebKit2/UIProcess/WebPreferences.cpp b/Source/WebKit2/UIProcess/WebPreferences.cpp index 4768f28bf..e1c390ec8 100644 --- a/Source/WebKit2/UIProcess/WebPreferences.cpp +++ b/Source/WebKit2/UIProcess/WebPreferences.cpp @@ -26,67 +26,89 @@ #include "config.h" #include "WebPreferences.h" -#include "WebContext.h" #include "WebPageGroup.h" +#include "WebPreferencesKeys.h" +#include "WebProcessPool.h" #include <wtf/ThreadingPrimitives.h> namespace WebKit { // FIXME: Manipulating this variable is not thread safe. // Instead of tracking private browsing state as a boolean preference, we should let the client provide storage sessions explicitly. -static unsigned privateBrowsingPageGroupCount; +static unsigned privateBrowsingPageCount; -WebPreferences::WebPreferences() +Ref<WebPreferences> WebPreferences::create(const String& identifier, const String& keyPrefix, const String& globalDebugKeyPrefix) { - platformInitializeStore(); + return adoptRef(*new WebPreferences(identifier, keyPrefix, globalDebugKeyPrefix)); } -WebPreferences::WebPreferences(const String& identifier) +PassRefPtr<WebPreferences> WebPreferences::createWithLegacyDefaults(const String& identifier, const String& keyPrefix, const String& globalDebugKeyPrefix) +{ + RefPtr<WebPreferences> preferences = adoptRef(new WebPreferences(identifier, keyPrefix, globalDebugKeyPrefix)); + // FIXME: The registerDefault...ValueForKey machinery is unnecessarily heavyweight and complicated. + // We can just compute different defaults for modern and legacy APIs in WebPreferencesDefinitions.h macros. + preferences->registerDefaultBoolValueForKey(WebPreferencesKey::javaEnabledKey(), true); + preferences->registerDefaultBoolValueForKey(WebPreferencesKey::javaEnabledForLocalFilesKey(), true); + preferences->registerDefaultBoolValueForKey(WebPreferencesKey::pluginsEnabledKey(), true); + preferences->registerDefaultUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey(), WebCore::SecurityOrigin::AllowAllStorage); + return preferences.release(); +} + +WebPreferences::WebPreferences(const String& identifier, const String& keyPrefix, const String& globalDebugKeyPrefix) : m_identifier(identifier) + , m_keyPrefix(keyPrefix) + , m_globalDebugKeyPrefix(globalDebugKeyPrefix) { platformInitializeStore(); } WebPreferences::WebPreferences(const WebPreferences& other) - : m_store(other.m_store) + : m_keyPrefix(other.m_keyPrefix) + , m_globalDebugKeyPrefix(other.m_globalDebugKeyPrefix) + , m_store(other.m_store) { platformInitializeStore(); } WebPreferences::~WebPreferences() { - ASSERT(m_pageGroups.isEmpty()); + ASSERT(m_pages.isEmpty()); } -void WebPreferences::addPageGroup(WebPageGroup* pageGroup) +PassRefPtr<WebPreferences> WebPreferences::copy() const { - bool didAddPageGroup = m_pageGroups.add(pageGroup).isNewEntry; - if (didAddPageGroup && privateBrowsingEnabled()) { - if (!privateBrowsingPageGroupCount) - WebContext::willStartUsingPrivateBrowsing(); - ++privateBrowsingPageGroupCount; - } + return adoptRef(new WebPreferences(*this)); } -void WebPreferences::removePageGroup(WebPageGroup* pageGroup) +void WebPreferences::addPage(WebPageProxy& webPageProxy) { - HashSet<WebPageGroup*>::iterator iter = m_pageGroups.find(pageGroup); - if (iter == m_pageGroups.end()) - return; + ASSERT(!m_pages.contains(&webPageProxy)); + m_pages.add(&webPageProxy); + + if (privateBrowsingEnabled()) { + if (!privateBrowsingPageCount) + WebProcessPool::willStartUsingPrivateBrowsing(); + + ++privateBrowsingPageCount; + } +} - m_pageGroups.remove(iter); +void WebPreferences::removePage(WebPageProxy& webPageProxy) +{ + ASSERT(m_pages.contains(&webPageProxy)); + m_pages.remove(&webPageProxy); if (privateBrowsingEnabled()) { - --privateBrowsingPageGroupCount; - if (!privateBrowsingPageGroupCount) - WebContext::willStopUsingPrivateBrowsing(); + --privateBrowsingPageCount; + if (!privateBrowsingPageCount) + WebProcessPool::willStopUsingPrivateBrowsing(); } } void WebPreferences::update() { - for (HashSet<WebPageGroup*>::iterator it = m_pageGroups.begin(), end = m_pageGroups.end(); it != end; ++it) - (*it)->preferencesDidChange(); + for (auto& webPageProxy : m_pages) + webPageProxy->preferencesDidChange(); } void WebPreferences::updateStringValueForKey(const String& key, const String& value) @@ -128,23 +150,23 @@ void WebPreferences::updatePrivateBrowsingValue(bool value) { platformUpdateBoolValueForKey(WebPreferencesKey::privateBrowsingEnabledKey(), value); - unsigned pageGroupsChanged = m_pageGroups.size(); - if (!pageGroupsChanged) + unsigned pagesChanged = m_pages.size(); + if (!pagesChanged) return; if (value) { - if (!privateBrowsingPageGroupCount) - WebContext::willStartUsingPrivateBrowsing(); - privateBrowsingPageGroupCount += pageGroupsChanged; + if (!privateBrowsingPageCount) + WebProcessPool::willStartUsingPrivateBrowsing(); + privateBrowsingPageCount += pagesChanged; } update(); // FIXME: Only send over the changed key and value. if (!value) { - ASSERT(privateBrowsingPageGroupCount >= pageGroupsChanged); - privateBrowsingPageGroupCount -= pageGroupsChanged; - if (!privateBrowsingPageGroupCount) - WebContext::willStopUsingPrivateBrowsing(); + ASSERT(privateBrowsingPageCount >= pagesChanged); + privateBrowsingPageCount -= pagesChanged; + if (!privateBrowsingPageCount) + WebProcessPool::willStopUsingPrivateBrowsing(); } } @@ -163,12 +185,29 @@ void WebPreferences::updatePrivateBrowsingValue(bool value) } \ FOR_EACH_WEBKIT_PREFERENCE(DEFINE_PREFERENCE_GETTER_AND_SETTERS) +FOR_EACH_WEBKIT_DEBUG_PREFERENCE(DEFINE_PREFERENCE_GETTER_AND_SETTERS) #undef DEFINE_PREFERENCE_GETTER_AND_SETTERS -bool WebPreferences::anyPageGroupsAreUsingPrivateBrowsing() +bool WebPreferences::anyPagesAreUsingPrivateBrowsing() +{ + return privateBrowsingPageCount; +} + +void WebPreferences::registerDefaultBoolValueForKey(const String& key, bool value) +{ + m_store.setOverrideDefaultsBoolValueForKey(key, value); + bool userValue; + if (platformGetBoolUserValueForKey(key, userValue)) + m_store.setBoolValueForKey(key, userValue); +} + +void WebPreferences::registerDefaultUInt32ValueForKey(const String& key, uint32_t value) { - return privateBrowsingPageGroupCount; + m_store.setOverrideDefaultsUInt32ValueForKey(key, value); + uint32_t userValue; + if (platformGetUInt32UserValueForKey(key, userValue)) + m_store.setUInt32ValueForKey(key, userValue); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebPreferences.h b/Source/WebKit2/UIProcess/WebPreferences.h index 26d23fbb1..018173878 100644 --- a/Source/WebKit2/UIProcess/WebPreferences.h +++ b/Source/WebKit2/UIProcess/WebPreferences.h @@ -28,6 +28,7 @@ #include "APIObject.h" #include "FontSmoothingLevel.h" +#include "WebPreferencesDefinitions.h" #include "WebPreferencesStore.h" #include <wtf/HashSet.h> #include <wtf/PassRefPtr.h> @@ -39,28 +40,22 @@ namespace WebKit { -class WebPageGroup; +class WebPageProxy; -class WebPreferences : public TypedAPIObject<APIObject::TypePreferences> { +class WebPreferences : public API::ObjectImpl<API::Object::Type::Preferences> { public: - static PassRefPtr<WebPreferences> create() - { - return adoptRef(new WebPreferences); - } - static PassRefPtr<WebPreferences> create(const String& identifier) - { - return adoptRef(new WebPreferences(identifier)); - } - - static PassRefPtr<WebPreferences> create(const WebPreferences& other) - { - return adoptRef(new WebPreferences(other)); - } + static Ref<WebPreferences> create(const String& identifier, const String& keyPrefix, const String& globalDebugKeyPrefix); + static PassRefPtr<WebPreferences> createWithLegacyDefaults(const String& identifier, const String& keyPrefix, const String& globalDebugKeyPrefix); + + explicit WebPreferences(const String& identifier, const String& keyPrefix, const String& globalDebugKeyPrefix); + WebPreferences(const WebPreferences&); virtual ~WebPreferences(); - void addPageGroup(WebPageGroup*); - void removePageGroup(WebPageGroup*); + PassRefPtr<WebPreferences> copy() const; + + void addPage(WebPageProxy&); + void removePage(WebPageProxy&); const WebPreferencesStore& store() const { return m_store; } @@ -69,19 +64,16 @@ public: Type KeyLower() const; \ FOR_EACH_WEBKIT_PREFERENCE(DECLARE_PREFERENCE_GETTER_AND_SETTERS) + FOR_EACH_WEBKIT_DEBUG_PREFERENCE(DECLARE_PREFERENCE_GETTER_AND_SETTERS) #undef DECLARE_PREFERENCE_GETTER_AND_SETTERS // Exposed for WebKitTestRunner use only. void forceUpdate() { update(); } - static bool anyPageGroupsAreUsingPrivateBrowsing(); + static bool anyPagesAreUsingPrivateBrowsing(); private: - WebPreferences(); - explicit WebPreferences(const String&); - WebPreferences(const WebPreferences&); - void platformInitializeStore(); void update(); @@ -99,9 +91,20 @@ private: void updatePrivateBrowsingValue(bool value); - HashSet<WebPageGroup*> m_pageGroups; + void registerDefaultBoolValueForKey(const String&, bool); + void registerDefaultUInt32ValueForKey(const String&, uint32_t); + + bool platformGetStringUserValueForKey(const String& key, String& userValue); + bool platformGetBoolUserValueForKey(const String&, bool&); + bool platformGetUInt32UserValueForKey(const String&, uint32_t&); + bool platformGetDoubleUserValueForKey(const String&, double&); + + const String m_identifier; + const String m_keyPrefix; + const String m_globalDebugKeyPrefix; WebPreferencesStore m_store; - String m_identifier; + + HashSet<WebPageProxy*> m_pages; }; } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebProcessLifetimeObserver.cpp b/Source/WebKit2/UIProcess/WebProcessLifetimeObserver.cpp new file mode 100644 index 000000000..c36474f2b --- /dev/null +++ b/Source/WebKit2/UIProcess/WebProcessLifetimeObserver.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2015 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 "WebProcessLifetimeObserver.h" + +#include "WebPageProxy.h" +#include "WebProcessProxy.h" + +namespace WebKit { + +WebProcessLifetimeObserver::WebProcessLifetimeObserver() +{ +} + +WebProcessLifetimeObserver::~WebProcessLifetimeObserver() +{ +} + +void WebProcessLifetimeObserver::addWebPage(WebPageProxy& webPageProxy) +{ + auto& process = webPageProxy.process(); + + ASSERT(process.state() == WebProcessProxy::State::Running); + + if (m_processes.add(&process).isNewEntry) + webProcessWillOpenConnection(process, *process.connection()); + + webPageWillOpenConnection(webPageProxy, *process.connection()); +} + +void WebProcessLifetimeObserver::removeWebPage(WebPageProxy& webPageProxy) +{ + auto& process = webPageProxy.process(); + + // FIXME: This should assert that the page is either closed or that the process is no longer running, + // but we have to make sure that removeWebPage is called after the connection has been removed in that case. + ASSERT(m_processes.contains(&process)); + + webPageDidCloseConnection(webPageProxy, *process.connection()); + + if (m_processes.remove(&process)) + webProcessDidCloseConnection(process, *process.connection()); +} + +WTF::IteratorRange<HashCountedSet<WebProcessProxy*>::const_iterator::Keys> WebProcessLifetimeObserver::processes() const +{ + ASSERT(std::all_of(m_processes.begin().keys(), m_processes.end().keys(), [](WebProcessProxy* process) { + return process->state() == WebProcessProxy::State::Running; + })); + + return makeIteratorRange(m_processes.begin().keys(), m_processes.end().keys()); +} + +} diff --git a/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.h b/Source/WebKit2/UIProcess/WebProcessLifetimeObserver.h index ab73cca0c..5c5bfeae3 100644 --- a/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.h +++ b/Source/WebKit2/UIProcess/WebProcessLifetimeObserver.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2015 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,43 +23,44 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef WebPopupMenuProxyMac_h -#define WebPopupMenuProxyMac_h +#ifndef WebProcessLifetimeObserver_h +#define WebProcessLifetimeObserver_h -#if USE(APPKIT) +#include <wtf/HashCountedSet.h> +#include <wtf/IteratorRange.h> -#include "WebPopupMenuProxy.h" -#include <wtf/RetainPtr.h> - -OBJC_CLASS NSPopUpButtonCell; -OBJC_CLASS WKView; +namespace IPC { +class Connection; +} namespace WebKit { class WebPageProxy; +class WebProcessProxy; -class WebPopupMenuProxyMac : public WebPopupMenuProxy { +class WebProcessLifetimeObserver { public: - static PassRefPtr<WebPopupMenuProxyMac> create(WKView *webView, WebPopupMenuProxy::Client* client) - { - return adoptRef(new WebPopupMenuProxyMac(webView, client)); - } - ~WebPopupMenuProxyMac(); + WebProcessLifetimeObserver(); + virtual ~WebProcessLifetimeObserver(); + + void addWebPage(WebPageProxy&); + void removeWebPage(WebPageProxy&); - virtual void showPopupMenu(const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>&, const PlatformPopupMenuData&, int32_t selectedIndex); - virtual void hidePopupMenu(); + WTF::IteratorRange<HashCountedSet<WebProcessProxy*>::const_iterator::Keys> processes() const; private: - WebPopupMenuProxyMac(WKView *, WebPopupMenuProxy::Client*); + friend class WebProcessLifetimeTracker; - void populate(const Vector<WebPopupItem>&, NSFont *, WebCore::TextDirection); + virtual void webPageWasAdded(WebPageProxy&) { } + virtual void webProcessWillOpenConnection(WebProcessProxy&, IPC::Connection&) { } + virtual void webPageWillOpenConnection(WebPageProxy&, IPC::Connection&) { } + virtual void webPageDidCloseConnection(WebPageProxy&, IPC::Connection&) { } + virtual void webProcessDidCloseConnection(WebProcessProxy&, IPC::Connection&) { } + virtual void webPageWasRemoved(WebPageProxy&) { } - RetainPtr<NSPopUpButtonCell> m_popup; - WKView *m_webView; + HashCountedSet<WebProcessProxy*> m_processes; }; -} // namespace WebKit - -#endif // USE(APPKIT) +} -#endif // WebPopupMenuProxyMac_h +#endif // WebProcessLifetimeObserver_h diff --git a/Source/WebKit2/UIProcess/WebNetworkInfoProvider.cpp b/Source/WebKit2/UIProcess/WebProcessLifetimeTracker.cpp index 47d0cee62..b080cc81c 100644 --- a/Source/WebKit2/UIProcess/WebNetworkInfoProvider.cpp +++ b/Source/WebKit2/UIProcess/WebProcessLifetimeTracker.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,49 +24,65 @@ */ #include "config.h" -#include "WebNetworkInfoProvider.h" +#include "WebProcessLifetimeTracker.h" -#if ENABLE(NETWORK_INFO) - -#include "WKAPICast.h" -#include "WebNetworkInfoManagerProxy.h" -#include <limits.h> +#include "WebProcessLifetimeObserver.h" +#include "WebProcessProxy.h" namespace WebKit { -void WebNetworkInfoProvider::startUpdating(WebNetworkInfoManagerProxy* networkInfoManager) +WebProcessLifetimeTracker::WebProcessLifetimeTracker(WebPageProxy& webPageProxy) + : m_webPageProxy(webPageProxy) { - if (!m_client.startUpdating) - return; +} - m_client.startUpdating(toAPI(networkInfoManager), m_client.clientInfo); +WebProcessLifetimeTracker::~WebProcessLifetimeTracker() +{ } -void WebNetworkInfoProvider::stopUpdating(WebNetworkInfoManagerProxy* networkInfoManager) +void WebProcessLifetimeTracker::addObserver(WebProcessLifetimeObserver& observer) { - if (!m_client.stopUpdating) - return; + ASSERT(!m_observers.contains(&observer)); + + m_observers.add(&observer); + + observer.webPageWasAdded(m_webPageProxy); + + if (processIsRunning()) + observer.addWebPage(m_webPageProxy); +} + +void WebProcessLifetimeTracker::connectionWillOpen(IPC::Connection&) +{ + ASSERT(processIsRunning()); - m_client.stopUpdating(toAPI(networkInfoManager), m_client.clientInfo); + for (auto& observer : m_observers) + observer->addWebPage(m_webPageProxy); } -double WebNetworkInfoProvider::bandwidth(WebNetworkInfoManagerProxy* networkInfoManager) const +void WebProcessLifetimeTracker::webProcessWillShutDown() { - // The spec indicates that we should return "infinity" if the bandwidth is unknown. - if (!m_client.bandwidth) - return std::numeric_limits<double>::infinity(); + ASSERT(processIsRunning()); - return m_client.bandwidth(toAPI(networkInfoManager), m_client.clientInfo); + for (auto& observer : m_observers) + observer->removeWebPage(m_webPageProxy); } -bool WebNetworkInfoProvider::isMetered(WebNetworkInfoManagerProxy* networkInfoManager) const +void WebProcessLifetimeTracker::pageWasInvalidated() { - if (!m_client.isMetered) - return false; + if (!processIsRunning()) + return; - return m_client.isMetered(toAPI(networkInfoManager), m_client.clientInfo); + for (auto& observer : m_observers) { + observer->removeWebPage(m_webPageProxy); + + observer->webPageWasRemoved(m_webPageProxy); + } } -} // namespace WebKit +bool WebProcessLifetimeTracker::processIsRunning() +{ + return m_webPageProxy.process().state() == WebProcessProxy::State::Running; +} -#endif // ENABLE(NETWORK_INFO) +} diff --git a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.h b/Source/WebKit2/UIProcess/WebProcessLifetimeTracker.h index ec49e9a2c..7a73b7367 100644 --- a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.h +++ b/Source/WebKit2/UIProcess/WebProcessLifetimeTracker.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Intel Corporation. All rights reserved. + * Copyright (C) 2015 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,35 +23,40 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef VibrationClientEfl_h -#define VibrationClientEfl_h +#ifndef WebProcessLifetimeTracker_h +#define WebProcessLifetimeTracker_h -#if ENABLE(VIBRATION) +#include <wtf/HashSet.h> -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; +namespace IPC { +class Connection; +} namespace WebKit { -class VibrationClientEfl { +class WebPageProxy; +class WebProcessLifetimeObserver; + +class WebProcessLifetimeTracker { public: - static PassOwnPtr<VibrationClientEfl> create(EwkView*); + explicit WebProcessLifetimeTracker(WebPageProxy&); + ~WebProcessLifetimeTracker(); + + void addObserver(WebProcessLifetimeObserver&); - virtual ~VibrationClientEfl(); + void connectionWillOpen(IPC::Connection&); + void webProcessWillShutDown(); + + void pageWasInvalidated(); private: - explicit VibrationClientEfl(EwkView*); + bool processIsRunning(); - static void vibrateCallback(WKVibrationRef, uint32_t vibrationTime, const void* clientInfo); - static void cancelVibrationCallback(WKVibrationRef, const void* clientInfo); + WebPageProxy& m_webPageProxy; - EwkView* m_view; + HashSet<WebProcessLifetimeObserver*> m_observers; }; -} // namespace WebKit - -#endif // ENABLE(VIBRATION) +} -#endif // VibrationClientEfl_h +#endif // WebProcessLifetimeTracker_h diff --git a/Source/WebKit2/UIProcess/WebProcessPool.cpp b/Source/WebKit2/UIProcess/WebProcessPool.cpp new file mode 100644 index 000000000..352a1f7ca --- /dev/null +++ b/Source/WebKit2/UIProcess/WebProcessPool.cpp @@ -0,0 +1,1328 @@ +/* + * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * 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 "WebProcessPool.h" + +#include "APIArray.h" +#include "APIAutomationClient.h" +#include "APIDownloadClient.h" +#include "APILegacyContextHistoryClient.h" +#include "APIPageConfiguration.h" +#include "APIProcessPoolConfiguration.h" +#include "CustomProtocolManagerMessages.h" +#include "DownloadProxy.h" +#include "DownloadProxyMessages.h" +#include "Logging.h" +#include "NetworkProcessCreationParameters.h" +#include "NetworkProcessMessages.h" +#include "NetworkProcessProxy.h" +#include "SandboxExtension.h" +#include "StatisticsData.h" +#include "TextChecker.h" +#include "WKContextPrivate.h" +#include "WebAutomationSession.h" +#include "WebCertificateInfo.h" +#include "WebContextSupplement.h" +#include "WebCookieManagerProxy.h" +#include "WebCoreArgumentCoders.h" +#include "WebGeolocationManagerProxy.h" +#include "WebIconDatabase.h" +#include "WebKit2Initialize.h" +#include "WebMemorySampler.h" +#include "WebNotificationManagerProxy.h" +#include "WebPageGroup.h" +#include "WebPreferences.h" +#include "WebProcessCreationParameters.h" +#include "WebProcessMessages.h" +#include "WebProcessPoolMessages.h" +#include "WebProcessProxy.h" +#include "WebsiteDataStore.h" +#include <WebCore/ApplicationCacheStorage.h> +#include <WebCore/Language.h> +#include <WebCore/LinkHash.h> +#include <WebCore/Logging.h> +#include <WebCore/ResourceRequest.h> +#include <WebCore/SessionID.h> +#include <runtime/JSCInlines.h> +#include <wtf/CurrentTime.h> +#include <wtf/MainThread.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/RunLoop.h> + +#if ENABLE(BATTERY_STATUS) +#include "WebBatteryManagerProxy.h" +#endif + +#if ENABLE(DATABASE_PROCESS) +#include "DatabaseProcessCreationParameters.h" +#include "DatabaseProcessMessages.h" +#endif + +#if ENABLE(SERVICE_CONTROLS) +#include "ServicesController.h" +#endif + +#if ENABLE(REMOTE_INSPECTOR) +#include <JavaScriptCore/RemoteInspector.h> +#endif + +#if USE(SOUP) +#include "WebSoupCustomProtocolRequestManager.h" +#endif + +#ifndef NDEBUG +#include <wtf/RefCountedLeakCounter.h> +#endif + +using namespace WebCore; +using namespace WebKit; + +namespace WebKit { + +DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, processPoolCounter, ("WebProcessPool")); + +Ref<WebProcessPool> WebProcessPool::create(API::ProcessPoolConfiguration& configuration) +{ + InitializeWebKit2(); + return adoptRef(*new WebProcessPool(configuration)); +} + +static Vector<WebProcessPool*>& processPools() +{ + static NeverDestroyed<Vector<WebProcessPool*>> processPools; + return processPools; +} + +const Vector<WebProcessPool*>& WebProcessPool::allProcessPools() +{ + return processPools(); +} + +static WebsiteDataStore::Configuration legacyWebsiteDataStoreConfiguration(API::ProcessPoolConfiguration& processPoolConfiguration) +{ + WebsiteDataStore::Configuration configuration; + + configuration.localStorageDirectory = processPoolConfiguration.localStorageDirectory(); + configuration.webSQLDatabaseDirectory = processPoolConfiguration.webSQLDatabaseDirectory(); + configuration.applicationCacheDirectory = WebProcessPool::legacyPlatformDefaultApplicationCacheDirectory(); + configuration.mediaKeysStorageDirectory = WebProcessPool::legacyPlatformDefaultMediaKeysStorageDirectory(); + configuration.networkCacheDirectory = WebProcessPool::legacyPlatformDefaultNetworkCacheDirectory(); + + return configuration; +} + +WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration) + : m_configuration(configuration.copy()) + , m_haveInitialEmptyProcess(false) + , m_processWithPageCache(0) + , m_defaultPageGroup(WebPageGroup::createNonNull()) + , m_automationClient(std::make_unique<API::AutomationClient>()) + , m_downloadClient(std::make_unique<API::DownloadClient>()) + , m_historyClient(std::make_unique<API::LegacyContextHistoryClient>()) + , m_visitedLinkStore(VisitedLinkStore::create()) + , m_visitedLinksPopulated(false) + , m_plugInAutoStartProvider(this) + , m_alwaysUsesComplexTextCodePath(false) + , m_shouldUseFontSmoothing(true) + , m_memorySamplerEnabled(false) + , m_memorySamplerInterval(1400.0) + , m_websiteDataStore(m_configuration->shouldHaveLegacyDataStore() ? API::WebsiteDataStore::create(legacyWebsiteDataStoreConfiguration(m_configuration)).ptr() : nullptr) +#if USE(SOUP) + , m_initialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) +#endif + , m_shouldUseTestingNetworkSession(false) + , m_processTerminationEnabled(true) + , m_canHandleHTTPSServerTrustEvaluation(true) + , m_didNetworkProcessCrash(false) + , m_memoryCacheDisabled(false) + , m_userObservablePageCounter([this](bool) { updateProcessSuppressionState(); }) + , m_processSuppressionDisabledForPageCounter([this](bool) { updateProcessSuppressionState(); }) +{ + for (auto& scheme : m_configuration->alwaysRevalidatedURLSchemes()) + m_schemesToRegisterAsAlwaysRevalidated.add(scheme); + +#if ENABLE(CACHE_PARTITIONING) + for (const auto& urlScheme : m_configuration->cachePartitionedURLSchemes()) + m_schemesToRegisterAsCachePartitioned.add(urlScheme); +#endif + + platformInitialize(); + + addMessageReceiver(Messages::WebProcessPool::messageReceiverName(), *this); + + // NOTE: These sub-objects must be initialized after m_messageReceiverMap.. + m_iconDatabase = WebIconDatabase::create(this); + + addSupplement<WebCookieManagerProxy>(); + addSupplement<WebGeolocationManagerProxy>(); + addSupplement<WebNotificationManagerProxy>(); +#if USE(SOUP) + addSupplement<WebSoupCustomProtocolRequestManager>(); +#endif +#if ENABLE(BATTERY_STATUS) + addSupplement<WebBatteryManagerProxy>(); +#endif +#if ENABLE(MEDIA_SESSION) + addSupplement<WebMediaSessionFocusManager>(); +#endif + + processPools().append(this); + + addLanguageChangeObserver(this, languageChanged); + +#if !LOG_DISABLED + WebCore::initializeLoggingChannelsIfNecessary(); + WebKit::initializeLogChannelsIfNecessary(); +#endif // !LOG_DISABLED + +#if ENABLE(NETSCAPE_PLUGIN_API) + m_pluginInfoStore.setClient(this); +#endif + +#ifndef NDEBUG + processPoolCounter.increment(); +#endif +} + +#if !PLATFORM(COCOA) +void WebProcessPool::platformInitialize() +{ +} +#endif + +WebProcessPool::~WebProcessPool() +{ + bool removed = processPools().removeFirst(this); + ASSERT_UNUSED(removed, removed); + + removeLanguageChangeObserver(this); + + m_messageReceiverMap.invalidate(); + + WebContextSupplementMap::const_iterator it = m_supplements.begin(); + WebContextSupplementMap::const_iterator end = m_supplements.end(); + for (; it != end; ++it) { + it->value->processPoolDestroyed(); + it->value->clearProcessPool(); + } + + m_iconDatabase->invalidate(); + m_iconDatabase->clearProcessPool(); + WebIconDatabase* rawIconDatabase = m_iconDatabase.release().leakRef(); + rawIconDatabase->derefWhenAppropriate(); + + invalidateCallbackMap(m_dictionaryCallbacks, CallbackBase::Error::OwnerWasInvalidated); + + platformInvalidateContext(); + +#if ENABLE(NETSCAPE_PLUGIN_API) + m_pluginInfoStore.setClient(0); +#endif + +#ifndef NDEBUG + processPoolCounter.decrement(); +#endif + + if (m_networkProcess) + m_networkProcess->shutDownProcess(); +} + +void WebProcessPool::initializeClient(const WKContextClientBase* client) +{ + m_client.initialize(client); +} + +void WebProcessPool::initializeInjectedBundleClient(const WKContextInjectedBundleClientBase* client) +{ + m_injectedBundleClient.initialize(client); +} + +void WebProcessPool::initializeConnectionClient(const WKContextConnectionClientBase* client) +{ + m_connectionClient.initialize(client); +} + +void WebProcessPool::setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient> historyClient) +{ + if (!historyClient) + m_historyClient = std::make_unique<API::LegacyContextHistoryClient>(); + else + m_historyClient = WTFMove(historyClient); +} + +void WebProcessPool::setDownloadClient(std::unique_ptr<API::DownloadClient> downloadClient) +{ + if (!downloadClient) + m_downloadClient = std::make_unique<API::DownloadClient>(); + else + m_downloadClient = WTFMove(downloadClient); +} + +void WebProcessPool::setAutomationClient(std::unique_ptr<API::AutomationClient> automationClient) +{ + if (!automationClient) + m_automationClient = std::make_unique<API::AutomationClient>(); + else + m_automationClient = WTFMove(automationClient); +} + +void WebProcessPool::setMaximumNumberOfProcesses(unsigned maximumNumberOfProcesses) +{ + // Guard against API misuse. + if (!m_processes.isEmpty()) + CRASH(); + + m_configuration->setMaximumProcessCount(maximumNumberOfProcesses); +} + +IPC::Connection* WebProcessPool::networkingProcessConnection() +{ + return m_networkProcess->connection(); +} + +void WebProcessPool::languageChanged(void* context) +{ + static_cast<WebProcessPool*>(context)->languageChanged(); +} + +void WebProcessPool::languageChanged() +{ + sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged(userPreferredLanguages())); +#if USE(SOUP) + if (m_networkProcess) + m_networkProcess->send(Messages::NetworkProcess::UserPreferredLanguagesChanged(userPreferredLanguages()), 0); +#endif +} + +void WebProcessPool::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled) +{ + sendToAllProcesses(Messages::WebProcess::FullKeyboardAccessModeChanged(fullKeyboardAccessEnabled)); +} + +void WebProcessPool::textCheckerStateChanged() +{ + sendToAllProcesses(Messages::WebProcess::SetTextCheckerState(TextChecker::state())); +} + +NetworkProcessProxy& WebProcessPool::ensureNetworkProcess() +{ + if (m_networkProcess) + return *m_networkProcess; + + m_networkProcess = NetworkProcessProxy::create(*this); + + NetworkProcessCreationParameters parameters; + + parameters.privateBrowsingEnabled = WebPreferences::anyPagesAreUsingPrivateBrowsing(); + + parameters.cacheModel = cacheModel(); + parameters.diskCacheSizeOverride = m_configuration->diskCacheSizeOverride(); + parameters.canHandleHTTPSServerTrustEvaluation = m_canHandleHTTPSServerTrustEvaluation; + + parameters.diskCacheDirectory = m_configuration->diskCacheDirectory(); + if (!parameters.diskCacheDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(parameters.diskCacheDirectory, parameters.diskCacheDirectoryExtensionHandle); + +#if ENABLE(SECCOMP_FILTERS) + parameters.cookieStorageDirectory = this->cookieStorageDirectory(); +#endif + +#if PLATFORM(IOS) + String cookieStorageDirectory = this->cookieStorageDirectory(); + if (!cookieStorageDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle); + + String containerCachesDirectory = this->networkingCachesDirectory(); + if (!containerCachesDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle); + + String parentBundleDirectory = this->parentBundleDirectory(); + if (!parentBundleDirectory.isEmpty()) + SandboxExtension::createHandle(parentBundleDirectory, SandboxExtension::ReadOnly, parameters.parentBundleDirectoryExtensionHandle); +#endif + + parameters.shouldUseTestingNetworkSession = m_shouldUseTestingNetworkSession; + + // Add any platform specific parameters + platformInitializeNetworkProcess(parameters); + + // Initialize the network process. + m_networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0); + +#if PLATFORM(COCOA) + m_networkProcess->send(Messages::NetworkProcess::SetQOS(networkProcessLatencyQOS(), networkProcessThroughputQOS()), 0); +#endif + + if (m_didNetworkProcessCrash) { + m_didNetworkProcessCrash = false; + for (auto& process : m_processes) + process->reinstateNetworkProcessAssertionState(*m_networkProcess); + } + + return *m_networkProcess; +} + +void WebProcessPool::networkProcessCrashed(NetworkProcessProxy* networkProcessProxy) +{ + ASSERT(m_networkProcess); + ASSERT(networkProcessProxy == m_networkProcess.get()); + m_didNetworkProcessCrash = true; + + WebContextSupplementMap::const_iterator it = m_supplements.begin(); + WebContextSupplementMap::const_iterator end = m_supplements.end(); + for (; it != end; ++it) + it->value->processDidClose(networkProcessProxy); + + m_client.networkProcessDidCrash(this); + + // Leave the process proxy around during client call, so that the client could query the process identifier. + m_networkProcess = nullptr; +} + +void WebProcessPool::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) +{ + ASSERT(reply); + + ensureNetworkProcess(); + ASSERT(m_networkProcess); + + m_networkProcess->getNetworkProcessConnection(reply); +} + +#if ENABLE(DATABASE_PROCESS) +void WebProcessPool::ensureDatabaseProcess() +{ + if (m_databaseProcess) + return; + + m_databaseProcess = DatabaseProcessProxy::create(this); + + // ********* + // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>) + // ********* + DatabaseProcessCreationParameters parameters; +#if ENABLE(INDEXED_DATABASE) + ASSERT(!m_configuration->indexedDBDatabaseDirectory().isEmpty()); + parameters.indexedDatabaseDirectory = m_configuration->indexedDBDatabaseDirectory(); + + SandboxExtension::createHandleForReadWriteDirectory(parameters.indexedDatabaseDirectory, parameters.indexedDatabaseDirectoryExtensionHandle); +#endif + + m_databaseProcess->send(Messages::DatabaseProcess::InitializeDatabaseProcess(parameters), 0); +} + +void WebProcessPool::getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply> reply) +{ + ASSERT(reply); + + ensureDatabaseProcess(); + + m_databaseProcess->getDatabaseProcessConnection(reply); +} + +void WebProcessPool::databaseProcessCrashed(DatabaseProcessProxy* databaseProcessProxy) +{ + ASSERT(m_databaseProcess); + ASSERT(databaseProcessProxy == m_databaseProcess.get()); + + for (auto& supplement : m_supplements) + supplement.value->processDidClose(databaseProcessProxy); + + m_databaseProcess = nullptr; +} +#endif + +void WebProcessPool::willStartUsingPrivateBrowsing() +{ + for (auto* processPool : allProcessPools()) + processPool->setAnyPageGroupMightHavePrivateBrowsingEnabled(true); +} + +void WebProcessPool::willStopUsingPrivateBrowsing() +{ + for (auto* processPool : allProcessPools()) + processPool->setAnyPageGroupMightHavePrivateBrowsingEnabled(false); +} + +void WebProcessPool::windowServerConnectionStateChanged() +{ + size_t processCount = m_processes.size(); + for (size_t i = 0; i < processCount; ++i) + m_processes[i]->windowServerConnectionStateChanged(); +} + +void WebProcessPool::setAnyPageGroupMightHavePrivateBrowsingEnabled(bool privateBrowsingEnabled) +{ + m_iconDatabase->setPrivateBrowsingEnabled(privateBrowsingEnabled); + + if (networkProcess()) { + if (privateBrowsingEnabled) + networkProcess()->send(Messages::NetworkProcess::EnsurePrivateBrowsingSession(SessionID::legacyPrivateSessionID()), 0); + else + networkProcess()->send(Messages::NetworkProcess::DestroyPrivateBrowsingSession(SessionID::legacyPrivateSessionID()), 0); + } + + if (privateBrowsingEnabled) + sendToAllProcesses(Messages::WebProcess::EnsurePrivateBrowsingSession(SessionID::legacyPrivateSessionID())); + else + sendToAllProcesses(Messages::WebProcess::DestroyPrivateBrowsingSession(SessionID::legacyPrivateSessionID())); +} + +void (*s_invalidMessageCallback)(WKStringRef messageName); + +void WebProcessPool::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName)) +{ + s_invalidMessageCallback = invalidMessageCallback; +} + +void WebProcessPool::didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName) +{ + if (!s_invalidMessageCallback) + return; + + StringBuilder messageNameStringBuilder; + messageNameStringBuilder.append(messageReceiverName.data(), messageReceiverName.size()); + messageNameStringBuilder.append('.'); + messageNameStringBuilder.append(messageName.data(), messageName.size()); + + s_invalidMessageCallback(toAPI(API::String::create(messageNameStringBuilder.toString()).ptr())); +} + +void WebProcessPool::processDidCachePage(WebProcessProxy* process) +{ + if (m_processWithPageCache && m_processWithPageCache != process) + m_processWithPageCache->releasePageCache(); + m_processWithPageCache = process; +} + +WebProcessProxy& WebProcessPool::createNewWebProcess() +{ + ensureNetworkProcess(); + + Ref<WebProcessProxy> process = WebProcessProxy::create(*this); + + WebProcessCreationParameters parameters; + + parameters.injectedBundlePath = injectedBundlePath(); + if (!parameters.injectedBundlePath.isEmpty()) + SandboxExtension::createHandle(parameters.injectedBundlePath, SandboxExtension::ReadOnly, parameters.injectedBundlePathExtensionHandle); + + parameters.applicationCacheDirectory = m_configuration->applicationCacheDirectory(); + if (!parameters.applicationCacheDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(parameters.applicationCacheDirectory, parameters.applicationCacheDirectoryExtensionHandle); + + parameters.webSQLDatabaseDirectory = m_configuration->webSQLDatabaseDirectory(); + if (!parameters.webSQLDatabaseDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(parameters.webSQLDatabaseDirectory, parameters.webSQLDatabaseDirectoryExtensionHandle); + +#if ENABLE(SECCOMP_FILTERS) + parameters.cookieStorageDirectory = this->cookieStorageDirectory(); +#endif + +#if PLATFORM(IOS) + String cookieStorageDirectory = this->cookieStorageDirectory(); + if (!cookieStorageDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle); + + String containerCachesDirectory = this->webContentCachesDirectory(); + if (!containerCachesDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle); + + String containerTemporaryDirectory = this->containerTemporaryDirectory(); + if (!containerTemporaryDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(containerTemporaryDirectory, parameters.containerTemporaryDirectoryExtensionHandle); +#endif + + parameters.mediaKeyStorageDirectory = m_configuration->mediaKeysStorageDirectory(); + if (!parameters.mediaKeyStorageDirectory.isEmpty()) + SandboxExtension::createHandleForReadWriteDirectory(parameters.mediaKeyStorageDirectory, parameters.mediaKeyStorageDirectoryExtensionHandle); + + parameters.shouldUseTestingNetworkSession = m_shouldUseTestingNetworkSession; + + parameters.cacheModel = cacheModel(); + parameters.languages = userPreferredLanguages(); + + copyToVector(m_schemesToRegisterAsEmptyDocument, parameters.urlSchemesRegisteredAsEmptyDocument); + copyToVector(m_schemesToRegisterAsSecure, parameters.urlSchemesRegisteredAsSecure); + copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy, parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy); + copyToVector(m_schemesToSetDomainRelaxationForbiddenFor, parameters.urlSchemesForWhichDomainRelaxationIsForbidden); + copyToVector(m_schemesToRegisterAsLocal, parameters.urlSchemesRegisteredAsLocal); + copyToVector(m_schemesToRegisterAsNoAccess, parameters.urlSchemesRegisteredAsNoAccess); + copyToVector(m_schemesToRegisterAsDisplayIsolated, parameters.urlSchemesRegisteredAsDisplayIsolated); + copyToVector(m_schemesToRegisterAsCORSEnabled, parameters.urlSchemesRegisteredAsCORSEnabled); + copyToVector(m_schemesToRegisterAsAlwaysRevalidated, parameters.urlSchemesRegisteredAsAlwaysRevalidated); +#if ENABLE(CACHE_PARTITIONING) + copyToVector(m_schemesToRegisterAsCachePartitioned, parameters.urlSchemesRegisteredAsCachePartitioned); +#endif + + parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath; + parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing; + + // FIXME: This leaves UI process and WebProcess disagreeing about the state if the client hasn't set the path. + // iconDatabasePath is non-empty by default, but m_iconDatabase isn't enabled in UI process unless setDatabasePath is called explicitly. + parameters.iconDatabaseEnabled = !iconDatabasePath().isEmpty(); + + parameters.terminationTimeout = 0; + + parameters.textCheckerState = TextChecker::state(); + + parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled(); + + parameters.defaultRequestTimeoutInterval = API::URLRequest::defaultTimeoutInterval(); + +#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS) + // FIXME: There should be a generic way for supplements to add to the intialization parameters. + supplement<WebNotificationManagerProxy>()->populateCopyOfNotificationPermissions(parameters.notificationPermissions); +#endif + + parameters.plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy(); + copyToVector(m_plugInAutoStartProvider.autoStartOrigins(), parameters.plugInAutoStartOrigins); + + parameters.memoryCacheDisabled = m_memoryCacheDisabled; + +#if ENABLE(SERVICE_CONTROLS) + auto& serviceController = ServicesController::singleton(); + parameters.hasImageServices = serviceController.hasImageServices(); + parameters.hasSelectionServices = serviceController.hasSelectionServices(); + parameters.hasRichContentServices = serviceController.hasRichContentServices(); + serviceController.refreshExistingServices(); +#endif + +#if ENABLE(NETSCAPE_PLUGIN_API) + parameters.pluginLoadClientPolicies = m_pluginLoadClientPolicies; +#endif + +#if OS(LINUX) + parameters.shouldEnableMemoryPressureReliefLogging = true; +#endif + + // Add any platform specific parameters + platformInitializeWebProcess(parameters); + + RefPtr<API::Object> injectedBundleInitializationUserData = m_injectedBundleClient.getInjectedBundleInitializationUserData(this); + if (!injectedBundleInitializationUserData) + injectedBundleInitializationUserData = m_injectedBundleInitializationUserData; + parameters.initializationUserData = UserData(process->transformObjectsToHandles(injectedBundleInitializationUserData.get())); + + process->send(Messages::WebProcess::InitializeWebProcess(parameters), 0); + +#if PLATFORM(COCOA) + process->send(Messages::WebProcess::SetQOS(webProcessLatencyQOS(), webProcessThroughputQOS()), 0); +#endif +#if PLATFORM(IOS) + ApplicationCacheStorage::singleton().setDefaultOriginQuota(25ULL * 1024 * 1024); +#endif + + if (WebPreferences::anyPagesAreUsingPrivateBrowsing()) + process->send(Messages::WebProcess::EnsurePrivateBrowsingSession(SessionID::legacyPrivateSessionID()), 0); + + m_processes.append(process.ptr()); + + ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty()); + +#if ENABLE(REMOTE_INSPECTOR) + // Initialize remote inspector connection now that we have a sub-process that is hosting one of our web views. + Inspector::RemoteInspector::singleton(); +#endif + + return process; +} + +void WebProcessPool::warmInitialProcess() +{ + if (m_haveInitialEmptyProcess) { + ASSERT(!m_processes.isEmpty()); + return; + } + + if (m_processes.size() >= maximumNumberOfProcesses()) + return; + + createNewWebProcess(); + m_haveInitialEmptyProcess = true; +} + +void WebProcessPool::enableProcessTermination() +{ + m_processTerminationEnabled = true; + Vector<RefPtr<WebProcessProxy>> processes = m_processes; + for (size_t i = 0; i < processes.size(); ++i) { + if (shouldTerminate(processes[i].get())) + processes[i]->terminate(); + } +} + +bool WebProcessPool::shouldTerminate(WebProcessProxy* process) +{ + ASSERT(m_processes.contains(process)); + + if (!m_processTerminationEnabled) + return false; + + return true; +} + +void WebProcessPool::processDidFinishLaunching(WebProcessProxy* process) +{ + ASSERT(m_processes.contains(process)); + + if (!m_visitedLinksPopulated) { + populateVisitedLinks(); + m_visitedLinksPopulated = true; + } + + // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching + // so check if it needs to be started here + if (m_memorySamplerEnabled) { + SandboxExtension::Handle sampleLogSandboxHandle; + double now = WTF::currentTime(); + String sampleLogFilePath = String::format("WebProcess%llupid%d", static_cast<unsigned long long>(now), process->processIdentifier()); + sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::ReadWrite, sampleLogSandboxHandle); + + process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0); + } + + if (m_configuration->fullySynchronousModeIsAllowedForTesting()) + process->connection()->allowFullySynchronousModeForTesting(); + + m_connectionClient.didCreateConnection(this, process->webConnection()); +} + +void WebProcessPool::disconnectProcess(WebProcessProxy* process) +{ + ASSERT(m_processes.contains(process)); + + if (m_haveInitialEmptyProcess && process == m_processes.last()) + m_haveInitialEmptyProcess = false; + + // FIXME (Multi-WebProcess): <rdar://problem/12239765> Some of the invalidation calls of the other supplements are still necessary in multi-process mode, but they should only affect data structures pertaining to the process being disconnected. + // Clearing everything causes assertion failures, so it's less trouble to skip that for now. + RefPtr<WebProcessProxy> protect(process); + if (m_processWithPageCache == process) + m_processWithPageCache = nullptr; + + static_cast<WebContextSupplement*>(supplement<WebGeolocationManagerProxy>())->processDidClose(process); + + m_processes.removeFirst(process); +} + +WebProcessProxy& WebProcessPool::createNewWebProcessRespectingProcessCountLimit() +{ + if (m_processes.size() < maximumNumberOfProcesses()) + return createNewWebProcess(); + + // Choose the process with fewest pages. + auto& process = *std::min_element(m_processes.begin(), m_processes.end(), [](const RefPtr<WebProcessProxy>& a, const RefPtr<WebProcessProxy>& b) { + return a->pageCount() < b->pageCount(); + }); + + return *process; +} + +Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API::PageConfiguration>&& pageConfiguration) +{ + if (!pageConfiguration->pageGroup()) + pageConfiguration->setPageGroup(m_defaultPageGroup.ptr()); + if (!pageConfiguration->preferences()) + pageConfiguration->setPreferences(&pageConfiguration->pageGroup()->preferences()); + if (!pageConfiguration->visitedLinkStore()) + pageConfiguration->setVisitedLinkStore(m_visitedLinkStore.ptr()); + if (!pageConfiguration->websiteDataStore()) { + ASSERT(!pageConfiguration->sessionID().isValid()); + pageConfiguration->setWebsiteDataStore(m_websiteDataStore.get()); + pageConfiguration->setSessionID(pageConfiguration->preferences()->privateBrowsingEnabled() ? SessionID::legacyPrivateSessionID() : SessionID::defaultSessionID()); + } + + RefPtr<WebProcessProxy> process; + if (m_haveInitialEmptyProcess) { + process = m_processes.last(); + m_haveInitialEmptyProcess = false; + } else if (pageConfiguration->relatedPage()) { + // Sharing processes, e.g. when creating the page via window.open(). + process = &pageConfiguration->relatedPage()->process(); + } else + process = &createNewWebProcessRespectingProcessCountLimit(); + + return process->createWebPage(pageClient, WTFMove(pageConfiguration)); +} + +DownloadProxy* WebProcessPool::download(WebPageProxy* initiatingPage, const ResourceRequest& request) +{ + DownloadProxy* downloadProxy = createDownloadProxy(request); + SessionID sessionID = initiatingPage ? initiatingPage->sessionID() : SessionID::defaultSessionID(); + + if (networkProcess()) { + // FIXME (NetworkProcess): Replicate whatever FrameLoader::setOriginalURLForDownloadRequest does with the request here. + networkProcess()->send(Messages::NetworkProcess::DownloadRequest(sessionID, downloadProxy->downloadID(), request), 0); + return downloadProxy; + } + +#if PLATFORM(QT) + ASSERT(initiatingPage); // Our design does not suppport downloads without a WebPage. + initiatingPage->handleDownloadRequest(downloadProxy); +#endif + + return downloadProxy; +} + +DownloadProxy* WebProcessPool::resumeDownload(const API::Data* resumeData, const String& path) +{ + DownloadProxy* downloadProxy = createDownloadProxy(ResourceRequest()); + + SandboxExtension::Handle sandboxExtensionHandle; + if (!path.isEmpty()) + SandboxExtension::createHandle(path, SandboxExtension::ReadWrite, sandboxExtensionHandle); + + if (networkProcess()) { + // FIXME: If we started a download in an ephemeral session and that session still exists, we should find a way to use that same session. + networkProcess()->send(Messages::NetworkProcess::ResumeDownload(SessionID::defaultSessionID(), downloadProxy->downloadID(), resumeData->dataReference(), path, sandboxExtensionHandle), 0); + return downloadProxy; + } + + return downloadProxy; +} + +void WebProcessPool::postMessageToInjectedBundle(const String& messageName, API::Object* messageBody) +{ + for (auto& process : m_processes) { + // FIXME: Return early if the message body contains any references to WKPageRefs/WKFrameRefs etc. since they're local to a process. + process->send(Messages::WebProcess::HandleInjectedBundleMessage(messageName, UserData(process->transformObjectsToHandles(messageBody).get())), 0); + } +} + +void WebProcessPool::populateVisitedLinks() +{ + m_historyClient->populateVisitedLinks(*this); +} + +WebProcessPool::Statistics& WebProcessPool::statistics() +{ + static Statistics statistics = Statistics(); + + return statistics; +} + +#if ENABLE(NETSCAPE_PLUGIN_API) +void WebProcessPool::setAdditionalPluginsDirectory(const String& directory) +{ + Vector<String> directories; + directories.append(directory); + + m_pluginInfoStore.setAdditionalPluginsDirectories(directories); +} +#endif // ENABLE(NETSCAPE_PLUGIN_API) + +PlatformProcessIdentifier WebProcessPool::networkProcessIdentifier() +{ + if (!m_networkProcess) + return 0; + + return m_networkProcess->processIdentifier(); +} + +void WebProcessPool::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText) +{ + m_alwaysUsesComplexTextCodePath = alwaysUseComplexText; + sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText)); +} + +void WebProcessPool::setShouldUseFontSmoothing(bool useFontSmoothing) +{ + m_shouldUseFontSmoothing = useFontSmoothing; + sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing)); +} + +void WebProcessPool::registerURLSchemeAsEmptyDocument(const String& urlScheme) +{ + m_schemesToRegisterAsEmptyDocument.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme)); +} + +void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme) +{ + m_schemesToRegisterAsSecure.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme)); +} + +void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme) +{ + m_schemesToRegisterAsBypassingContentSecurityPolicy.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme)); +} + +void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme) +{ + m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme)); +} + +void WebProcessPool::setCanHandleHTTPSServerTrustEvaluation(bool value) +{ + m_canHandleHTTPSServerTrustEvaluation = value; + if (m_networkProcess) { + m_networkProcess->send(Messages::NetworkProcess::SetCanHandleHTTPSServerTrustEvaluation(value), 0); + return; + } +} + +void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme) +{ + m_schemesToRegisterAsLocal.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme)); +} + +void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme) +{ + m_schemesToRegisterAsNoAccess.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme)); +} + +void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme) +{ + m_schemesToRegisterAsDisplayIsolated.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme)); +} + +void WebProcessPool::registerURLSchemeAsCORSEnabled(const String& urlScheme) +{ + m_schemesToRegisterAsCORSEnabled.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme)); +} + +HashSet<String, ASCIICaseInsensitiveHash>& WebProcessPool::globalURLSchemesWithCustomProtocolHandlers() +{ + static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> set; + return set; +} + +void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme) +{ + if (!urlScheme) + return; + + globalURLSchemesWithCustomProtocolHandlers().add(urlScheme); + for (auto* processPool : allProcessPools()) + processPool->registerSchemeForCustomProtocol(urlScheme); +} + +void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme) +{ + if (!urlScheme) + return; + + globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme); + for (auto* processPool : allProcessPools()) + processPool->unregisterSchemeForCustomProtocol(urlScheme); +} + +#if ENABLE(CACHE_PARTITIONING) +void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme) +{ + m_schemesToRegisterAsCachePartitioned.add(urlScheme); + sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCachePartitioned(urlScheme)); +} +#endif + +void WebProcessPool::setCacheModel(CacheModel cacheModel) +{ + m_configuration->setCacheModel(cacheModel); + sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel)); + + if (m_networkProcess) + m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel), 0); +} + +void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval) +{ + sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval)); +} + +DownloadProxy* WebProcessPool::createDownloadProxy(const ResourceRequest& request) +{ + return ensureNetworkProcess().createDownloadProxy(request); +} + +void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver) +{ + m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver); +} + +void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver) +{ + m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver); +} + +void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID) +{ + m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID); +} + +bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) +{ + return m_messageReceiverMap.dispatchMessage(connection, decoder); +} + +bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) +{ + return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder); +} + +void WebProcessPool::setEnhancedAccessibility(bool flag) +{ + sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag)); +} + +void WebProcessPool::startMemorySampler(const double interval) +{ + // For new WebProcesses we will also want to start the Memory Sampler + m_memorySamplerEnabled = true; + m_memorySamplerInterval = interval; + + // For UIProcess +#if ENABLE(MEMORY_SAMPLER) + WebMemorySampler::singleton()->start(interval); +#endif + + // For WebProcess + SandboxExtension::Handle sampleLogSandboxHandle; + double now = WTF::currentTime(); + String sampleLogFilePath = String::format("WebProcess%llu", static_cast<unsigned long long>(now)); + sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::ReadWrite, sampleLogSandboxHandle); + + sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval)); +} + +void WebProcessPool::stopMemorySampler() +{ + // For WebProcess + m_memorySamplerEnabled = false; + + // For UIProcess +#if ENABLE(MEMORY_SAMPLER) + WebMemorySampler::singleton()->stop(); +#endif + + sendToAllProcesses(Messages::WebProcess::StopMemorySampler()); +} + +void WebProcessPool::setIconDatabasePath(const String& path) +{ + m_overrideIconDatabasePath = path; + if (!m_overrideIconDatabasePath.isEmpty()) { + // This implicitly enables the database on UI process side. + m_iconDatabase->setDatabasePath(path); + } +} + +String WebProcessPool::iconDatabasePath() const +{ + if (!m_overrideIconDatabasePath.isNull()) + return m_overrideIconDatabasePath; + + return platformDefaultIconDatabasePath(); +} + +#if ENABLE(SECCOMP_FILTERS) +String WebProcessPool::cookieStorageDirectory() const +{ + if (!m_overrideCookieStorageDirectory.isEmpty()) + return m_overrideCookieStorageDirectory; + + // FIXME: This doesn't make much sense. Is this function used at all? We used to call platform code, but no existing platforms implemented that function. + return emptyString(); +} +#endif + +void WebProcessPool::useTestingNetworkSession() +{ + ASSERT(m_processes.isEmpty()); + ASSERT(!m_networkProcess); + + if (m_networkProcess) + return; + + if (!m_processes.isEmpty()) + return; + + m_shouldUseTestingNetworkSession = true; +} + +void WebProcessPool::clearCachedCredentials() +{ + sendToAllProcesses(Messages::WebProcess::ClearCachedCredentials()); + if (m_networkProcess) + m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0); +} + +void WebProcessPool::terminateDatabaseProcess() +{ +#if ENABLE(DATABASE_PROCESS) + ASSERT(m_processes.isEmpty()); + if (!m_databaseProcess) + return; + + m_databaseProcess->terminate(); + m_databaseProcess = nullptr; +#endif +} + +void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host) +{ + if (m_networkProcess) + m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0); +} + +void WebProcessPool::updateAutomationCapabilities() const +{ +#if ENABLE(REMOTE_INSPECTOR) + Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange(); +#endif +} + +void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession) +{ + m_automationSession = WTFMove(automationSession); + +#if ENABLE(REMOTE_INSPECTOR) + if (m_automationSession) + m_automationSession->init(); +#endif +} + +void WebProcessPool::setHTTPPipeliningEnabled(bool enabled) +{ +#if PLATFORM(COCOA) + ResourceRequest::setHTTPPipeliningEnabled(enabled); +#else + UNUSED_PARAM(enabled); +#endif +} + +bool WebProcessPool::httpPipeliningEnabled() const +{ +#if PLATFORM(COCOA) + return ResourceRequest::httpPipeliningEnabled(); +#else + return false; +#endif +} + +void WebProcessPool::getStatistics(uint32_t statisticsMask, std::function<void (API::Dictionary*, CallbackBase::Error)> callbackFunction) +{ + if (!statisticsMask) { + callbackFunction(nullptr, CallbackBase::Error::Unknown); + return; + } + + RefPtr<StatisticsRequest> request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction))); + + if (statisticsMask & StatisticsRequestTypeWebContent) + requestWebContentStatistics(request.get()); + + if (statisticsMask & StatisticsRequestTypeNetworking) + requestNetworkingStatistics(request.get()); +} + +void WebProcessPool::requestWebContentStatistics(StatisticsRequest* request) +{ + // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work. +} + +void WebProcessPool::requestNetworkingStatistics(StatisticsRequest* request) +{ + if (!m_networkProcess) { + LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable"); + return; + } + + uint64_t requestID = request->addOutstandingRequest(); + m_statisticsRequests.set(requestID, request); + m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0); +} + +void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody) +{ + auto* webProcessProxy = WebProcessProxy::fromConnection(&connection); + if (!webProcessProxy) + return; + m_injectedBundleClient.didReceiveMessageFromInjectedBundle(this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get()); +} + +void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, UserData& returnUserData) +{ + auto* webProcessProxy = WebProcessProxy::fromConnection(&connection); + if (!webProcessProxy) + return; + + RefPtr<API::Object> returnData; + m_injectedBundleClient.didReceiveSynchronousMessageFromInjectedBundle(this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), returnData); + returnUserData = UserData(webProcessProxy->transformObjectsToHandles(returnData.get())); +} + +void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID) +{ + RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID); + if (!request) { + LOG_ERROR("Cannot report networking statistics."); + return; + } + + request->completedRequest(requestID, statisticsData); +} + +void WebProcessPool::garbageCollectJavaScriptObjects() +{ + sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects()); +} + +void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag) +{ + sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag)); +} + +void WebProcessPool::addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, SessionID sessionID) +{ + m_plugInAutoStartProvider.addAutoStartOriginHash(pageOrigin, plugInOriginHash, sessionID); +} + +void WebProcessPool::plugInDidReceiveUserInteraction(unsigned plugInOriginHash, SessionID sessionID) +{ + m_plugInAutoStartProvider.didReceiveUserInteraction(plugInOriginHash, sessionID); +} + +PassRefPtr<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const +{ + return m_plugInAutoStartProvider.autoStartOriginsTableCopy(); +} + +void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary) +{ + m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary); +} + +void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array) +{ + m_plugInAutoStartProvider.setAutoStartOriginsArray(array); +} + +void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, double time) +{ + m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time); +} + +void WebProcessPool::registerSchemeForCustomProtocol(const String& scheme) +{ + sendToNetworkingProcess(Messages::CustomProtocolManager::RegisterScheme(scheme)); +} + +void WebProcessPool::unregisterSchemeForCustomProtocol(const String& scheme) +{ + sendToNetworkingProcess(Messages::CustomProtocolManager::UnregisterScheme(scheme)); +} + +#if ENABLE(NETSCAPE_PLUGIN_API) +void WebProcessPool::pluginInfoStoreDidLoadPlugins(PluginInfoStore* store) +{ +#ifdef NDEBUG + UNUSED_PARAM(store); +#endif + ASSERT(store == &m_pluginInfoStore); + + Vector<PluginModuleInfo> pluginModules = m_pluginInfoStore.plugins(); + + Vector<RefPtr<API::Object>> plugins; + plugins.reserveInitialCapacity(pluginModules.size()); + + for (const auto& pluginModule : pluginModules) { + API::Dictionary::MapType map; + map.set(ASCIILiteral("path"), API::String::create(pluginModule.path)); + map.set(ASCIILiteral("name"), API::String::create(pluginModule.info.name)); + map.set(ASCIILiteral("file"), API::String::create(pluginModule.info.file)); + map.set(ASCIILiteral("desc"), API::String::create(pluginModule.info.desc)); + + Vector<RefPtr<API::Object>> mimeTypes; + mimeTypes.reserveInitialCapacity(pluginModule.info.mimes.size()); + for (const auto& mimeClassInfo : pluginModule.info.mimes) + mimeTypes.uncheckedAppend(API::String::create(mimeClassInfo.type)); + map.set(ASCIILiteral("mimes"), API::Array::create(WTFMove(mimeTypes))); + +#if PLATFORM(COCOA) + map.set(ASCIILiteral("bundleId"), API::String::create(pluginModule.bundleIdentifier)); + map.set(ASCIILiteral("version"), API::String::create(pluginModule.versionString)); +#endif + + plugins.uncheckedAppend(API::Dictionary::create(WTFMove(map))); + } + + m_client.plugInInformationBecameAvailable(this, API::Array::create(WTFMove(plugins)).ptr()); +} + +void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString) +{ +#if ENABLE(NETSCAPE_PLUGIN_API) + HashMap<String, HashMap<String, uint8_t>> policiesByIdentifier; + if (m_pluginLoadClientPolicies.contains(host)) + policiesByIdentifier = m_pluginLoadClientPolicies.get(host); + + HashMap<String, uint8_t> versionsToPolicies; + if (policiesByIdentifier.contains(bundleIdentifier)) + versionsToPolicies = policiesByIdentifier.get(bundleIdentifier); + + versionsToPolicies.set(versionString, policy); + policiesByIdentifier.set(bundleIdentifier, versionsToPolicies); + m_pluginLoadClientPolicies.set(host, policiesByIdentifier); +#endif + + sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString)); +} + +void WebProcessPool::clearPluginClientPolicies() +{ +#if ENABLE(NETSCAPE_PLUGIN_API) + m_pluginLoadClientPolicies.clear(); +#endif + sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies()); +} +#endif + +void WebProcessPool::setMemoryCacheDisabled(bool disabled) +{ + m_memoryCacheDisabled = disabled; + sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled)); +} + +void WebProcessPool::setFontWhitelist(API::Array* array) +{ + m_fontWhitelist.clear(); + if (array) { + for (size_t i = 0; i < array->size(); ++i) { + if (API::String* font = array->at<API::String>(i)) + m_fontWhitelist.append(font->string()); + } + } +} + +} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebProcessPool.h b/Source/WebKit2/UIProcess/WebProcessPool.h new file mode 100644 index 000000000..f2b441f9a --- /dev/null +++ b/Source/WebKit2/UIProcess/WebProcessPool.h @@ -0,0 +1,594 @@ +/* + * Copyright (C) 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * 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 WebProcessPool_h +#define WebProcessPool_h + +#include "APIDictionary.h" +#include "APIObject.h" +#include "APIProcessPoolConfiguration.h" +#include "APIWebsiteDataStore.h" +#include "DownloadProxyMap.h" +#include "GenericCallback.h" +#include "MessageReceiver.h" +#include "MessageReceiverMap.h" +#include "NetworkProcessProxy.h" +#include "PlugInAutoStartProvider.h" +#include "PluginInfoStore.h" +#include "ProcessThrottler.h" +#include "StatisticsRequest.h" +#include "VisitedLinkStore.h" +#include "WebContextClient.h" +#include "WebContextConnectionClient.h" +#include "WebContextInjectedBundleClient.h" +#include "WebProcessProxy.h" +#include <WebCore/LinkHash.h> +#include <WebCore/SessionID.h> +#include <wtf/Forward.h> +#include <wtf/HashMap.h> +#include <wtf/HashSet.h> +#include <wtf/PassRefPtr.h> +#include <wtf/RefCounter.h> +#include <wtf/RefPtr.h> +#include <wtf/text/StringHash.h> +#include <wtf/text/WTFString.h> + +#if ENABLE(DATABASE_PROCESS) +#include "DatabaseProcessProxy.h" +#endif + +#if ENABLE(MEDIA_SESSION) +#include "WebMediaSessionFocusManager.h" +#endif + +#if PLATFORM(COCOA) +OBJC_CLASS NSMutableDictionary; +OBJC_CLASS NSObject; +OBJC_CLASS NSString; +#endif + +namespace API { +class AutomationClient; +class DownloadClient; +class LegacyContextHistoryClient; +class PageConfiguration; +} + +namespace WebKit { + +class DownloadProxy; +class WebAutomationSession; +class WebContextSupplement; +class WebIconDatabase; +class WebPageGroup; +class WebPageProxy; +struct NetworkProcessCreationParameters; +struct StatisticsData; +struct WebProcessCreationParameters; + +typedef GenericCallback<API::Dictionary*> DictionaryCallback; + +#if PLATFORM(COCOA) +int networkProcessLatencyQOS(); +int networkProcessThroughputQOS(); +int webProcessLatencyQOS(); +int webProcessThroughputQOS(); +#endif + +class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, private IPC::MessageReceiver +#if ENABLE(NETSCAPE_PLUGIN_API) + , private PluginInfoStoreClient +#endif + { +public: + static Ref<WebProcessPool> create(API::ProcessPoolConfiguration&); + + explicit WebProcessPool(API::ProcessPoolConfiguration&); + virtual ~WebProcessPool(); + + API::ProcessPoolConfiguration& configuration() { return m_configuration.get(); } + + static const Vector<WebProcessPool*>& allProcessPools(); + + template <typename T> + T* supplement() + { + return static_cast<T*>(m_supplements.get(T::supplementName())); + } + + template <typename T> + void addSupplement() + { + m_supplements.add(T::supplementName(), T::create(this)); + } + + void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&); + void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&); + void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID); + + bool dispatchMessage(IPC::Connection&, IPC::MessageDecoder&); + bool dispatchSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&); + + void initializeClient(const WKContextClientBase*); + void initializeInjectedBundleClient(const WKContextInjectedBundleClientBase*); + void initializeConnectionClient(const WKContextConnectionClientBase*); + void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>); + void setDownloadClient(std::unique_ptr<API::DownloadClient>); + void setAutomationClient(std::unique_ptr<API::AutomationClient>); + + void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running. + unsigned maximumNumberOfProcesses() const { return !m_configuration->maximumProcessCount() ? UINT_MAX : m_configuration->maximumProcessCount(); } + + const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; } + + // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null. + IPC::Connection* networkingProcessConnection(); + + template<typename T> void sendToAllProcesses(const T& message); + template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message); + template<typename T> void sendToOneProcess(T&& message); + + // Sends the message to WebProcess or NetworkProcess as approporiate for current process model. + template<typename T> void sendToNetworkingProcess(T&& message); + template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message); + + // Sends the message to WebProcess or DatabaseProcess as approporiate for current process model. + template<typename T> void sendToDatabaseProcessRelaunchingIfNecessary(T&& message); + + void processDidFinishLaunching(WebProcessProxy*); + + // Disconnect the process from the context. + void disconnectProcess(WebProcessProxy*); + + API::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); } + + Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&); + + const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); } + + DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&); + DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path); + + void setInjectedBundleInitializationUserData(PassRefPtr<API::Object> userData) { m_injectedBundleInitializationUserData = userData; } + + void postMessageToInjectedBundle(const String&, API::Object*); + + void populateVisitedLinks(); + +#if ENABLE(NETSCAPE_PLUGIN_API) + void setAdditionalPluginsDirectory(const String&); + + PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; } + + void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString); + void clearPluginClientPolicies(); +#endif + + PlatformProcessIdentifier networkProcessIdentifier(); + + void setAlwaysUsesComplexTextCodePath(bool); + void setShouldUseFontSmoothing(bool); + + void registerURLSchemeAsEmptyDocument(const String&); + void registerURLSchemeAsSecure(const String&); + void registerURLSchemeAsBypassingContentSecurityPolicy(const String&); + void setDomainRelaxationForbiddenForURLScheme(const String&); + void setCanHandleHTTPSServerTrustEvaluation(bool); + void registerURLSchemeAsLocal(const String&); + void registerURLSchemeAsNoAccess(const String&); + void registerURLSchemeAsDisplayIsolated(const String&); + void registerURLSchemeAsCORSEnabled(const String&); +#if ENABLE(CACHE_PARTITIONING) + void registerURLSchemeAsCachePartitioned(const String&); +#endif + + VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); } + + void setCacheModel(CacheModel); + CacheModel cacheModel() const { return m_configuration->cacheModel(); } + + void setDefaultRequestTimeoutInterval(double); + + void startMemorySampler(const double interval); + void stopMemorySampler(); + +#if USE(SOUP) + void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; } +#endif + void setEnhancedAccessibility(bool); + + // Downloads. + DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&); + API::DownloadClient& downloadClient() { return *m_downloadClient; } + + API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; } + WebContextClient& client() { return m_client; } + + WebIconDatabase* iconDatabase() const { return m_iconDatabase.get(); } + + struct Statistics { + unsigned wkViewCount; + unsigned wkPageCount; + unsigned wkFrameCount; + }; + static Statistics& statistics(); + + void setIconDatabasePath(const String&); + String iconDatabasePath() const; + void setCookieStorageDirectory(const String& dir) { m_overrideCookieStorageDirectory = dir; } + + void useTestingNetworkSession(); + bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; } + + void clearCachedCredentials(); + void terminateDatabaseProcess(); + + void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host); + + WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(); // Will return an existing one if limit is met. + void warmInitialProcess(); + + bool shouldTerminate(WebProcessProxy*); + + void disableProcessTermination() { m_processTerminationEnabled = false; } + void enableProcessTermination(); + + void updateAutomationCapabilities() const; + void setAutomationSession(RefPtr<WebAutomationSession>&&); + + // Defaults to false. + void setHTTPPipeliningEnabled(bool); + bool httpPipeliningEnabled() const; + + void getStatistics(uint32_t statisticsMask, std::function<void (API::Dictionary*, CallbackBase::Error)>); + + void garbageCollectJavaScriptObjects(); + void setJavaScriptGarbageCollectorTimerEnabled(bool flag); + +#if PLATFORM(COCOA) + static bool omitPDFSupport(); +#endif + + void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled); + + void textCheckerStateChanged(); + + PassRefPtr<API::Dictionary> plugInAutoStartOriginHashes() const; + void setPlugInAutoStartOriginHashes(API::Dictionary&); + void setPlugInAutoStartOrigins(API::Array&); + void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, double time); + + // Network Process Management + NetworkProcessProxy& ensureNetworkProcess(); + NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); } + void networkProcessCrashed(NetworkProcessProxy*); + + void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); + +#if ENABLE(DATABASE_PROCESS) + void ensureDatabaseProcess(); + DatabaseProcessProxy* databaseProcess() { return m_databaseProcess.get(); } + void getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply>); + void databaseProcessCrashed(DatabaseProcessProxy*); +#endif + +#if PLATFORM(COCOA) + bool processSuppressionEnabled() const; +#endif + + void windowServerConnectionStateChanged(); + + static void willStartUsingPrivateBrowsing(); + static void willStopUsingPrivateBrowsing(); + +#if USE(SOUP) + void setIgnoreTLSErrors(bool); + bool ignoreTLSErrors() const { return m_ignoreTLSErrors; } +#endif + + static void setInvalidMessageCallback(void (*)(WKStringRef)); + static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName); + + void processDidCachePage(WebProcessProxy*); + + bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const; + void resetHSTSHosts(); + void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970); + + void registerSchemeForCustomProtocol(const String&); + void unregisterSchemeForCustomProtocol(const String&); + + static HashSet<String, ASCIICaseInsensitiveHash>& globalURLSchemesWithCustomProtocolHandlers(); + static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&); + static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&); + +#if PLATFORM(COCOA) + void updateProcessSuppressionState(); + + NSMutableDictionary *ensureBundleParameters(); + NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); } +#else + void updateProcessSuppressionState() const { } +#endif + + void setMemoryCacheDisabled(bool); + void setFontWhitelist(API::Array*); + + UserObservablePageToken userObservablePageCount() + { + return m_userObservablePageCounter.token<UserObservablePageTokenType>(); + } + + ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount() + { + return m_processSuppressionDisabledForPageCounter.token<ProcessSuppressionDisabledTokenType>(); + } + + // FIXME: Move these to API::WebsiteDataStore. + static String legacyPlatformDefaultLocalStorageDirectory(); + static String legacyPlatformDefaultIndexedDBDatabaseDirectory(); + static String legacyPlatformDefaultWebSQLDatabaseDirectory(); + static String legacyPlatformDefaultMediaKeysStorageDirectory(); + static String legacyPlatformDefaultApplicationCacheDirectory(); + static String legacyPlatformDefaultNetworkCacheDirectory(); + static bool isNetworkCacheEnabled(); + +private: + void platformInitialize(); + + void platformInitializeWebProcess(WebProcessCreationParameters&); + void platformInvalidateContext(); + + WebProcessProxy& createNewWebProcess(); + + void requestWebContentStatistics(StatisticsRequest*); + void requestNetworkingStatistics(StatisticsRequest*); + + void platformInitializeNetworkProcess(NetworkProcessCreationParameters&); + + void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody); + void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData); + + void didGetStatistics(const StatisticsData&, uint64_t callbackID); + + // IPC::MessageReceiver. + // Implemented in generated WebProcessPoolMessageReceiver.cpp + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; + + static void languageChanged(void* context); + void languageChanged(); + + String platformDefaultIconDatabasePath() const; + +#if PLATFORM(IOS) || ENABLE(SECCOMP_FILTERS) + String cookieStorageDirectory() const; +#endif + +#if PLATFORM(IOS) + String parentBundleDirectory() const; + String networkingCachesDirectory() const; + String webContentCachesDirectory() const; + String containerTemporaryDirectory() const; +#endif + +#if PLATFORM(COCOA) + void registerNotificationObservers(); + void unregisterNotificationObservers(); +#endif + + void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, WebCore::SessionID); + void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, WebCore::SessionID); + + void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool); + +#if ENABLE(NETSCAPE_PLUGIN_API) + // PluginInfoStoreClient: + virtual void pluginInfoStoreDidLoadPlugins(PluginInfoStore*) override; +#endif + + Ref<API::ProcessPoolConfiguration> m_configuration; + + IPC::MessageReceiverMap m_messageReceiverMap; + + Vector<RefPtr<WebProcessProxy>> m_processes; + bool m_haveInitialEmptyProcess; + + WebProcessProxy* m_processWithPageCache; + + Ref<WebPageGroup> m_defaultPageGroup; + + RefPtr<API::Object> m_injectedBundleInitializationUserData; + WebContextInjectedBundleClient m_injectedBundleClient; + + WebContextClient m_client; + WebContextConnectionClient m_connectionClient; + std::unique_ptr<API::AutomationClient> m_automationClient; + std::unique_ptr<API::DownloadClient> m_downloadClient; + std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient; + + RefPtr<WebAutomationSession> m_automationSession; + +#if ENABLE(NETSCAPE_PLUGIN_API) + PluginInfoStore m_pluginInfoStore; +#endif + Ref<VisitedLinkStore> m_visitedLinkStore; + bool m_visitedLinksPopulated; + + PlugInAutoStartProvider m_plugInAutoStartProvider; + + HashSet<String> m_schemesToRegisterAsEmptyDocument; + HashSet<String> m_schemesToRegisterAsSecure; + HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy; + HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor; + HashSet<String> m_schemesToRegisterAsLocal; + HashSet<String> m_schemesToRegisterAsNoAccess; + HashSet<String> m_schemesToRegisterAsDisplayIsolated; + HashSet<String> m_schemesToRegisterAsCORSEnabled; + HashSet<String> m_schemesToRegisterAsAlwaysRevalidated; +#if ENABLE(CACHE_PARTITIONING) + HashSet<String> m_schemesToRegisterAsCachePartitioned; +#endif + + bool m_alwaysUsesComplexTextCodePath; + bool m_shouldUseFontSmoothing; + + Vector<String> m_fontWhitelist; + + // Messages that were posted before any pages were created. + // The client should use initialization messages instead, so that a restarted process would get the same state. + Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext; + + bool m_memorySamplerEnabled; + double m_memorySamplerInterval; + + RefPtr<WebIconDatabase> m_iconDatabase; + + const RefPtr<API::WebsiteDataStore> m_websiteDataStore; + + typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap; + WebContextSupplementMap m_supplements; + +#if USE(SOUP) + HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy; +#endif + +#if PLATFORM(MAC) + RetainPtr<NSObject> m_enhancedAccessibilityObserver; + RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver; + RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver; + RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver; + RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver; +#endif + + String m_overrideIconDatabasePath; + String m_overrideCookieStorageDirectory; + + bool m_shouldUseTestingNetworkSession; + + bool m_processTerminationEnabled; + + bool m_canHandleHTTPSServerTrustEvaluation; + bool m_didNetworkProcessCrash; + RefPtr<NetworkProcessProxy> m_networkProcess; + +#if ENABLE(DATABASE_PROCESS) + RefPtr<DatabaseProcessProxy> m_databaseProcess; +#endif + + HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks; + HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests; + +#if USE(SOUP) + bool m_ignoreTLSErrors { true }; +#endif + + bool m_memoryCacheDisabled; + + RefCounter m_userObservablePageCounter; + RefCounter m_processSuppressionDisabledForPageCounter; + +#if PLATFORM(COCOA) + RetainPtr<NSMutableDictionary> m_bundleParameters; + ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken; +#endif + +#if ENABLE(CONTENT_EXTENSIONS) + HashMap<String, String> m_encodedContentExtensions; +#endif + +#if ENABLE(NETSCAPE_PLUGIN_API) + HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies; +#endif +}; + +template<typename T> +void WebProcessPool::sendToNetworkingProcess(T&& message) +{ + if (m_networkProcess && m_networkProcess->canSendMessage()) + m_networkProcess->send(std::forward<T>(message), 0); +} + +template<typename T> +void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message) +{ + ensureNetworkProcess(); + m_networkProcess->send(std::forward<T>(message), 0); +} + +template<typename T> +void WebProcessPool::sendToDatabaseProcessRelaunchingIfNecessary(T&& message) +{ +#if ENABLE(DATABASE_PROCESS) + ensureDatabaseProcess(); + m_databaseProcess->send(std::forward<T>(message), 0); +#else + sendToAllProcessesRelaunchingThemIfNecessary(std::forward<T>(message)); +#endif +} + +template<typename T> +void WebProcessPool::sendToAllProcesses(const T& message) +{ + size_t processCount = m_processes.size(); + for (size_t i = 0; i < processCount; ++i) { + WebProcessProxy* process = m_processes[i].get(); + if (process->canSendMessage()) + process->send(T(message), 0); + } +} + +template<typename T> +void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message) +{ + // FIXME (Multi-WebProcess): WebProcessPool doesn't track processes that have exited, so it cannot relaunch these. Perhaps this functionality won't be needed in this mode. + sendToAllProcesses(message); +} + +template<typename T> +void WebProcessPool::sendToOneProcess(T&& message) +{ + bool messageSent = false; + size_t processCount = m_processes.size(); + for (size_t i = 0; i < processCount; ++i) { + WebProcessProxy* process = m_processes[i].get(); + if (process->canSendMessage()) { + process->send(std::forward<T>(message), 0); + messageSent = true; + break; + } + } + + if (!messageSent) { + warmInitialProcess(); + RefPtr<WebProcessProxy> process = m_processes.last(); + if (process->canSendMessage()) + process->send(std::forward<T>(message), 0); + } +} + +} // namespace WebKit + +#endif // UIProcessPool_h diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.messages.in b/Source/WebKit2/UIProcess/WebProcessPool.messages.in index d6c217240..76b75cff6 100644 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.messages.in +++ b/Source/WebKit2/UIProcess/WebProcessPool.messages.in @@ -1,4 +1,4 @@ -# Copyright (C) 2012 Apple Inc. All rights reserved. +# 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 @@ -20,6 +20,13 @@ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -messages -> RemoteLayerTreeHost { - void Commit(WebKit::RemoteLayerTreeTransaction transaction) +messages -> WebProcessPool { + HandleMessage(String messageName, WebKit::UserData messageBody) WantsConnection + HandleSynchronousMessage(String messageName, WebKit::UserData messageBody) -> (WebKit::UserData returnData) WantsConnection + + DidGetStatistics(struct WebKit::StatisticsData statisticsData, uint64_t callbackID) + + # Plug-in messages. + void AddPlugInAutoStartOriginHash(String pageOrigin, uint32_t hash, WebCore::SessionID sessionID) + void PlugInDidReceiveUserInteraction(uint32_t hash, WebCore::SessionID sessionID) } diff --git a/Source/WebKit2/UIProcess/WebProcessProxy.cpp b/Source/WebKit2/UIProcess/WebProcessProxy.cpp index 5090abd97..62df9d38d 100644 --- a/Source/WebKit2/UIProcess/WebProcessProxy.cpp +++ b/Source/WebKit2/UIProcess/WebProcessProxy.cpp @@ -26,39 +26,44 @@ #include "config.h" #include "WebProcessProxy.h" +#include "APIFrameHandle.h" +#include "APIPageGroupHandle.h" +#include "APIPageHandle.h" +#include "CustomProtocolManagerProxyMessages.h" #include "DataReference.h" #include "DownloadProxyMap.h" #include "PluginInfoStore.h" #include "PluginProcessManager.h" #include "TextChecker.h" #include "TextCheckerState.h" +#include "UserData.h" #include "WebBackForwardListItem.h" -#include "WebContext.h" +#include "WebIconDatabase.h" +#include "WebInspectorProxy.h" #include "WebNavigationDataStore.h" #include "WebNotificationManagerProxy.h" +#include "WebPageGroup.h" #include "WebPageProxy.h" -#include "WebPluginSiteDataManager.h" +#include "WebPasteboardProxy.h" #include "WebProcessMessages.h" +#include "WebProcessPool.h" #include "WebProcessProxyMessages.h" -#include <WebCore/KURL.h> +#include "WebUserContentControllerProxy.h" +#include "WebsiteData.h" #include <WebCore/SuddenTermination.h> +#include <WebCore/URL.h> #include <stdio.h> -#include <wtf/MainThread.h> +#include <wtf/NeverDestroyed.h> +#include <wtf/RunLoop.h> #include <wtf/text/CString.h> #include <wtf/text/WTFString.h> -#if PLATFORM(MAC) -#include "SimplePDFPlugin.h" -#if ENABLE(PDFKIT_PLUGIN) +#if PLATFORM(COCOA) +#include "ObjCObjectGraph.h" #include "PDFPlugin.h" #endif -#endif -#if ENABLE(CUSTOM_PROTOCOLS) -#include "CustomProtocolManagerProxyMessages.h" -#endif - -#if USE(SECURITY_FRAMEWORK) +#if ENABLE(SEC_ITEM_SHIM) #include "SecItemShimProxy.h" #endif @@ -75,71 +80,111 @@ static uint64_t generatePageID() return ++uniquePageID; } +static uint64_t generateCallbackID() +{ + static uint64_t callbackID; + + return ++callbackID; +} + static WebProcessProxy::WebPageProxyMap& globalPageMap() { - ASSERT(isMainThread()); - DEFINE_STATIC_LOCAL(WebProcessProxy::WebPageProxyMap, pageMap, ()); + ASSERT(RunLoop::isMain()); + static NeverDestroyed<WebProcessProxy::WebPageProxyMap> pageMap; return pageMap; } -PassRefPtr<WebProcessProxy> WebProcessProxy::create(PassRefPtr<WebContext> context) +Ref<WebProcessProxy> WebProcessProxy::create(WebProcessPool& processPool) { - return adoptRef(new WebProcessProxy(context)); + return adoptRef(*new WebProcessProxy(processPool)); } -WebProcessProxy::WebProcessProxy(PassRefPtr<WebContext> context) - : m_responsivenessTimer(this) - , m_context(context) +WebProcessProxy::WebProcessProxy(WebProcessPool& processPool) + : m_responsivenessTimer(*this) + , m_processPool(processPool) , m_mayHaveUniversalFileReadSandboxExtension(false) -#if ENABLE(CUSTOM_PROTOCOLS) - , m_customProtocolManagerProxy(this) -#endif -#if PLATFORM(MAC) - , m_processSuppressionEnabled(false) -#endif + , m_customProtocolManagerProxy(this, processPool) + , m_numberOfTimesSuddenTerminationWasDisabled(0) + , m_throttler(*this) + , m_isResponsive(NoOrMaybe::Maybe) { + WebPasteboardProxy::singleton().addWebProcessProxy(*this); + connect(); } WebProcessProxy::~WebProcessProxy() { + ASSERT(m_pendingFetchWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataCallbacks.isEmpty()); + ASSERT(m_pendingDeleteWebsiteDataForOriginsCallbacks.isEmpty()); + ASSERT(m_pageURLRetainCountMap.isEmpty()); + if (m_webConnection) m_webConnection->invalidate(); + + while (m_numberOfTimesSuddenTerminationWasDisabled-- > 0) + WebCore::enableSuddenTermination(); } void WebProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) { - launchOptions.processType = ProcessLauncher::WebProcess; - platformGetLaunchOptions(launchOptions); + launchOptions.processType = ProcessLauncher::ProcessType::Web; + + ChildProcessProxy::getLaunchOptions(launchOptions); + + if (WebInspectorProxy::isInspectorProcessPool(m_processPool)) + launchOptions.extraInitializationData.add(ASCIILiteral("inspector-process"), ASCIILiteral("1")); + + auto overrideLanguages = m_processPool->configuration().overrideLanguages(); + if (overrideLanguages.size()) { + StringBuilder languageString; + for (size_t i = 0; i < overrideLanguages.size(); ++i) { + if (i) + languageString.append(','); + languageString.append(overrideLanguages[i]); + } + launchOptions.extraInitializationData.add(ASCIILiteral("OverrideLanguages"), languageString.toString()); + } } -void WebProcessProxy::connectionWillOpen(CoreIPC::Connection* connection) +void WebProcessProxy::connectionWillOpen(IPC::Connection& connection) { - ASSERT(this->connection() == connection); + ASSERT(this->connection() == &connection); -#if USE(SECURITY_FRAMEWORK) - SecItemShimProxy::shared().initializeConnection(connection); +#if ENABLE(SEC_ITEM_SHIM) + SecItemShimProxy::singleton().initializeConnection(connection); #endif - for (WebPageProxyMap::iterator it = m_pageMap.begin(), end = m_pageMap.end(); it != end; ++it) - it->value->connectionWillOpen(connection); - - m_context->processWillOpenConnection(this); + for (auto& page : m_pageMap.values()) + page->connectionWillOpen(connection); } -void WebProcessProxy::connectionWillClose(CoreIPC::Connection* connection) +void WebProcessProxy::processWillShutDown(IPC::Connection& connection) { - ASSERT(this->connection() == connection); + ASSERT_UNUSED(connection, this->connection() == &connection); + + for (const auto& callback : m_pendingFetchWebsiteDataCallbacks.values()) + callback(WebsiteData()); + m_pendingFetchWebsiteDataCallbacks.clear(); + + for (const auto& callback : m_pendingDeleteWebsiteDataCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataCallbacks.clear(); + + for (const auto& callback : m_pendingDeleteWebsiteDataForOriginsCallbacks.values()) + callback(); + m_pendingDeleteWebsiteDataForOriginsCallbacks.clear(); - for (WebPageProxyMap::iterator it = m_pageMap.begin(), end = m_pageMap.end(); it != end; ++it) - it->value->connectionWillClose(connection); + for (auto& page : m_pageMap.values()) + page->webProcessWillShutDown(); - m_context->processWillCloseConnection(this); + releaseRemainingIconsForPageURLs(); } -void WebProcessProxy::disconnect() +void WebProcessProxy::shutDown() { - clearConnection(); + shutDownProcess(); if (m_webConnection) { m_webConnection->invalidate(); @@ -147,18 +192,24 @@ void WebProcessProxy::disconnect() } m_responsivenessTimer.invalidate(); + m_tokenForHoldingLockedFiles = nullptr; - Vector<RefPtr<WebFrameProxy> > frames; + Vector<RefPtr<WebFrameProxy>> frames; copyValuesToVector(m_frameMap, frames); for (size_t i = 0, size = frames.size(); i < size; ++i) - frames[i]->disconnect(); + frames[i]->webProcessWillShutDown(); m_frameMap.clear(); - if (m_downloadProxyMap) - m_downloadProxyMap->processDidClose(); + for (VisitedLinkStore* visitedLinkStore : m_visitedLinkStores) + visitedLinkStore->removeProcess(*this); + m_visitedLinkStores.clear(); - m_context->disconnectProcess(this); + for (WebUserContentControllerProxy* webUserContentControllerProxy : m_webUserContentControllerProxies) + webUserContentControllerProxy->removeProcess(*this); + m_webUserContentControllerProxies.clear(); + + m_processPool->disconnectProcess(this); } WebPageProxy* WebProcessProxy::webPage(uint64_t pageID) @@ -166,53 +217,69 @@ WebPageProxy* WebProcessProxy::webPage(uint64_t pageID) return globalPageMap().get(pageID); } -PassRefPtr<WebPageProxy> WebProcessProxy::createWebPage(PageClient* pageClient, WebContext*, WebPageGroup* pageGroup) +Ref<WebPageProxy> WebProcessProxy::createWebPage(PageClient& pageClient, Ref<API::PageConfiguration>&& pageConfiguration) { uint64_t pageID = generatePageID(); - RefPtr<WebPageProxy> webPage = WebPageProxy::create(pageClient, this, pageGroup, pageID); - m_pageMap.set(pageID, webPage.get()); - globalPageMap().set(pageID, webPage.get()); -#if PLATFORM(MAC) - if (pageIsProcessSuppressible(webPage.get())) - m_processSuppressiblePages.add(pageID); - updateProcessSuppressionState(); -#endif - return webPage.release(); + Ref<WebPageProxy> webPage = WebPageProxy::create(pageClient, *this, pageID, WTFMove(pageConfiguration)); + + m_pageMap.set(pageID, webPage.ptr()); + globalPageMap().set(pageID, webPage.ptr()); + + return webPage; } void WebProcessProxy::addExistingWebPage(WebPageProxy* webPage, uint64_t pageID) { + ASSERT(!m_pageMap.contains(pageID)); + ASSERT(!globalPageMap().contains(pageID)); + m_pageMap.set(pageID, webPage); globalPageMap().set(pageID, webPage); -#if PLATFORM(MAC) - if (pageIsProcessSuppressible(webPage)) - m_processSuppressiblePages.add(pageID); - updateProcessSuppressionState(); -#endif } void WebProcessProxy::removeWebPage(uint64_t pageID) { m_pageMap.remove(pageID); globalPageMap().remove(pageID); -#if PLATFORM(MAC) - m_processSuppressiblePages.remove(pageID); - updateProcessSuppressionState(); -#endif + + Vector<uint64_t> itemIDsToRemove; + for (auto& idAndItem : m_backForwardListItemMap) { + if (idAndItem.value->pageID() == pageID) + itemIDsToRemove.append(idAndItem.key); + } + for (auto itemID : itemIDsToRemove) + m_backForwardListItemMap.remove(itemID); // If this was the last WebPage open in that web process, and we have no other reason to keep it alive, let it go. // We only allow this when using a network process, as otherwise the WebProcess needs to preserve its session state. - if (m_context->usesNetworkProcess() && canTerminateChildProcess()) { - abortProcessLaunchIfNeeded(); - disconnect(); - } + if (state() == State::Terminated || !canTerminateChildProcess()) + return; + + shutDown(); } -Vector<WebPageProxy*> WebProcessProxy::pages() const +void WebProcessProxy::addVisitedLinkStore(VisitedLinkStore& store) { - Vector<WebPageProxy*> result; - copyValuesToVector(m_pageMap, result); - return result; + m_visitedLinkStores.add(&store); + store.addProcess(*this); +} + +void WebProcessProxy::addWebUserContentControllerProxy(WebUserContentControllerProxy& proxy) +{ + m_webUserContentControllerProxies.add(&proxy); + proxy.addProcess(*this); +} + +void WebProcessProxy::didDestroyVisitedLinkStore(VisitedLinkStore& store) +{ + ASSERT(m_visitedLinkStores.contains(&store)); + m_visitedLinkStores.remove(&store); +} + +void WebProcessProxy::didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy& proxy) +{ + ASSERT(m_webUserContentControllerProxies.contains(&proxy)); + m_webUserContentControllerProxies.remove(&proxy); } WebBackForwardListItem* WebProcessProxy::webBackForwardItem(uint64_t itemID) const @@ -229,27 +296,47 @@ void WebProcessProxy::registerNewWebBackForwardListItem(WebBackForwardListItem* m_backForwardListItemMap.set(item->itemID(), item); } +void WebProcessProxy::removeBackForwardItem(uint64_t itemID) +{ + m_backForwardListItemMap.remove(itemID); +} + void WebProcessProxy::assumeReadAccessToBaseURL(const String& urlString) { - KURL url(KURL(), urlString); + URL url(URL(), urlString); if (!url.isLocalFile()) return; // There's a chance that urlString does not point to a directory. // Get url's base URL to add to m_localPathsWithAssumedReadAccess. - KURL baseURL(KURL(), url.baseAsString()); + URL baseURL(URL(), url.baseAsString()); // Client loads an alternate string. This doesn't grant universal file read, but the web process is assumed // to have read access to this directory already. m_localPathsWithAssumedReadAccess.add(baseURL.fileSystemPath()); } +bool WebProcessProxy::hasAssumedReadAccessToURL(const URL& url) const +{ + if (!url.isLocalFile()) + return false; + + String path = url.fileSystemPath(); + for (const String& assumedAccessPath : m_localPathsWithAssumedReadAccess) { + // There are no ".." components, because URL removes those. + if (path.startsWith(assumedAccessPath)) + return true; + } + + return false; +} + bool WebProcessProxy::checkURLReceivedFromWebProcess(const String& urlString) { - return checkURLReceivedFromWebProcess(KURL(KURL(), urlString)); + return checkURLReceivedFromWebProcess(URL(URL(), urlString)); } -bool WebProcessProxy::checkURLReceivedFromWebProcess(const KURL& url) +bool WebProcessProxy::checkURLReceivedFromWebProcess(const URL& url) { // FIXME: Consider checking that the URL is valid. Currently, WebProcess sends invalid URLs in many cases, but it probably doesn't have good reasons to do that. @@ -262,19 +349,18 @@ bool WebProcessProxy::checkURLReceivedFromWebProcess(const KURL& url) return true; // If we loaded a string with a file base URL before, loading resources from that subdirectory is fine. - // There are no ".." components, because all URLs received from WebProcess are parsed with KURL, which removes those. - String path = url.fileSystemPath(); - for (HashSet<String>::const_iterator iter = m_localPathsWithAssumedReadAccess.begin(); iter != m_localPathsWithAssumedReadAccess.end(); ++iter) { - if (path.startsWith(*iter)) - return true; - } + if (hasAssumedReadAccessToURL(url)) + return true; // Items in back/forward list have been already checked. // One case where we don't have sandbox extensions for file URLs in b/f list is if the list has been reinstated after a crash or a browser restart. + String path = url.fileSystemPath(); for (WebBackForwardListItemMap::iterator iter = m_backForwardListItemMap.begin(), end = m_backForwardListItemMap.end(); iter != end; ++iter) { - if (KURL(KURL(), iter->value->url()).fileSystemPath() == path) + URL itemURL(URL(), iter->value->url()); + if (itemURL.isLocalFile() && itemURL.fileSystemPath() == path) return true; - if (KURL(KURL(), iter->value->originalURL()).fileSystemPath() == path) + URL itemOriginalURL(URL(), iter->value->originalURL()); + if (itemOriginalURL.isLocalFile() && itemOriginalURL.fileSystemPath() == path) return true; } @@ -283,93 +369,125 @@ bool WebProcessProxy::checkURLReceivedFromWebProcess(const KURL& url) return false; } -#if !PLATFORM(MAC) +#if !PLATFORM(COCOA) bool WebProcessProxy::fullKeyboardAccessEnabled() { return false; } #endif -void WebProcessProxy::addBackForwardItem(uint64_t itemID, const String& originalURL, const String& url, const String& title, const CoreIPC::DataReference& backForwardData) +void WebProcessProxy::addBackForwardItem(uint64_t itemID, uint64_t pageID, const PageState& pageState) { - MESSAGE_CHECK_URL(originalURL); - MESSAGE_CHECK_URL(url); - - WebBackForwardListItemMap::AddResult result = m_backForwardListItemMap.add(itemID, 0); - if (result.isNewEntry) { - result.iterator->value = WebBackForwardListItem::create(originalURL, url, title, backForwardData.data(), backForwardData.size(), itemID); + MESSAGE_CHECK_URL(pageState.mainFrameState.originalURLString); + MESSAGE_CHECK_URL(pageState.mainFrameState.urlString); + + auto& backForwardListItem = m_backForwardListItemMap.add(itemID, nullptr).iterator->value; + if (!backForwardListItem) { + BackForwardListItemState backForwardListItemState; + backForwardListItemState.identifier = itemID; + backForwardListItemState.pageState = pageState; + backForwardListItem = WebBackForwardListItem::create(WTFMove(backForwardListItemState), pageID); return; } // Update existing item. - result.iterator->value->setOriginalURL(originalURL); - result.iterator->value->setURL(url); - result.iterator->value->setTitle(title); - result.iterator->value->setBackForwardData(backForwardData.data(), backForwardData.size()); + backForwardListItem->setPageState(pageState); } #if ENABLE(NETSCAPE_PLUGIN_API) -void WebProcessProxy::getPlugins(bool refresh, Vector<PluginInfo>& plugins) +void WebProcessProxy::getPlugins(bool refresh, Vector<PluginInfo>& plugins, Vector<PluginInfo>& applicationPlugins) { if (refresh) - m_context->pluginInfoStore().refresh(); + m_processPool->pluginInfoStore().refresh(); - Vector<PluginModuleInfo> pluginModules = m_context->pluginInfoStore().plugins(); + Vector<PluginModuleInfo> pluginModules = m_processPool->pluginInfoStore().plugins(); for (size_t i = 0; i < pluginModules.size(); ++i) plugins.append(pluginModules[i].info); -#if PLATFORM(MAC) - // Add built-in PDF last, so that it's not used when a real plug-in is installed. - if (!m_context->omitPDFSupport()) { #if ENABLE(PDFKIT_PLUGIN) + // Add built-in PDF last, so that it's not used when a real plug-in is installed. + if (!m_processPool->omitPDFSupport()) { plugins.append(PDFPlugin::pluginInfo()); -#endif - plugins.append(SimplePDFPlugin::pluginInfo()); + applicationPlugins.append(PDFPlugin::pluginInfo()); } +#else + UNUSED_PARAM(applicationPlugins); #endif } #endif // ENABLE(NETSCAPE_PLUGIN_API) -#if ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) void WebProcessProxy::getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply) { - PluginProcessManager::shared().getPluginProcessConnection(pluginProcessToken, reply); + PluginProcessManager::singleton().getPluginProcessConnection(pluginProcessToken, reply); } +#endif -#elif ENABLE(NETSCAPE_PLUGIN_API) - -void WebProcessProxy::didGetSitesWithPluginData(const Vector<String>& sites, uint64_t callbackID) +void WebProcessProxy::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) { - m_context->pluginSiteDataManager()->didGetSitesWithData(sites, callbackID); + m_processPool->getNetworkProcessConnection(reply); } -void WebProcessProxy::didClearPluginSiteData(uint64_t callbackID) +#if ENABLE(DATABASE_PROCESS) +void WebProcessProxy::getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply> reply) { - m_context->pluginSiteDataManager()->didClearSiteData(callbackID); + m_processPool->getDatabaseProcessConnection(reply); } +#endif // ENABLE(DATABASE_PROCESS) -#endif +void WebProcessProxy::retainIconForPageURL(const String& pageURL) +{ + WebIconDatabase* iconDatabase = processPool().iconDatabase(); + if (!iconDatabase || pageURL.isEmpty()) + return; + + // Track retain counts so we can release them if the WebProcess terminates early. + auto result = m_pageURLRetainCountMap.add(pageURL, 1); + if (!result.isNewEntry) + ++result.iterator->value; + + iconDatabase->retainIconForPageURL(pageURL); +} -#if ENABLE(SHARED_WORKER_PROCESS) -void WebProcessProxy::getSharedWorkerProcessConnection(const String& /* url */, const String& /* name */, PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>) +void WebProcessProxy::releaseIconForPageURL(const String& pageURL) { - // FIXME: Implement + WebIconDatabase* iconDatabase = processPool().iconDatabase(); + if (!iconDatabase || pageURL.isEmpty()) + return; + + // Track retain counts so we can release them if the WebProcess terminates early. + auto result = m_pageURLRetainCountMap.find(pageURL); + if (result == m_pageURLRetainCountMap.end()) + return; + + --result->value; + if (!result->value) + m_pageURLRetainCountMap.remove(result); + + iconDatabase->releaseIconForPageURL(pageURL); } -#endif // ENABLE(SHARED_WORKER_PROCESS) -#if ENABLE(NETWORK_PROCESS) -void WebProcessProxy::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply) +void WebProcessProxy::releaseRemainingIconsForPageURLs() { - m_context->getNetworkProcessConnection(reply); + WebIconDatabase* iconDatabase = processPool().iconDatabase(); + if (!iconDatabase) + return; + + for (auto& entry : m_pageURLRetainCountMap) { + uint64_t count = entry.value; + for (uint64_t i = 0; i < count; ++i) + iconDatabase->releaseIconForPageURL(entry.key); + } + + m_pageURLRetainCountMap.clear(); } -#endif // ENABLE(NETWORK_PROCESS) -void WebProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder) +void WebProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder) { if (dispatchMessage(connection, decoder)) return; - if (m_context->dispatchMessage(connection, decoder)) + if (m_processPool->dispatchMessage(connection, decoder)) return; if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) { @@ -380,12 +498,12 @@ void WebProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC // FIXME: Add unhandled message logging. } -void WebProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder) +void WebProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC::MessageDecoder& decoder, std::unique_ptr<IPC::MessageEncoder>& replyEncoder) { if (dispatchSyncMessage(connection, decoder, replyEncoder)) return; - if (m_context->dispatchSyncMessage(connection, decoder, replyEncoder)) + if (m_processPool->dispatchSyncMessage(connection, decoder, replyEncoder)) return; if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) { @@ -396,72 +514,98 @@ void WebProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, Cor // FIXME: Add unhandled message logging. } -void WebProcessProxy::didClose(CoreIPC::Connection*) +void WebProcessProxy::didClose(IPC::Connection&) { // Protect ourselves, as the call to disconnect() below may otherwise cause us // to be deleted before we can finish our work. - RefPtr<WebProcessProxy> protect(this); + Ref<WebProcessProxy> protect(*this); webConnection()->didClose(); - Vector<RefPtr<WebPageProxy> > pages; + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); - disconnect(); + shutDown(); for (size_t i = 0, size = pages.size(); i < size; ++i) pages[i]->processDidCrash(); } -void WebProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection* connection, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) +void WebProcessProxy::didReceiveInvalidMessage(IPC::Connection& connection, IPC::StringReference messageReceiverName, IPC::StringReference messageName) { WTFLogAlways("Received an invalid message \"%s.%s\" from the web process.\n", messageReceiverName.toString().data(), messageName.toString().data()); - WebContext::didReceiveInvalidMessage(messageReceiverName, messageName); + WebProcessPool::didReceiveInvalidMessage(messageReceiverName, messageName); // Terminate the WebProcess. terminate(); - // Since we've invalidated the connection we'll never get a CoreIPC::Connection::Client::didClose + // Since we've invalidated the connection we'll never get a IPC::Connection::Client::didClose // callback so we'll explicitly call it here instead. didClose(connection); } -void WebProcessProxy::didBecomeUnresponsive(ResponsivenessTimer*) +void WebProcessProxy::didBecomeUnresponsive() { - Vector<RefPtr<WebPageProxy> > pages; + m_isResponsive = NoOrMaybe::No; + + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); - for (size_t i = 0, size = pages.size(); i < size; ++i) - pages[i]->processDidBecomeUnresponsive(); + + auto isResponsiveCallbacks = WTFMove(m_isResponsiveCallbacks); + + for (auto& page : pages) + page->processDidBecomeUnresponsive(); + + bool isWebProcessResponsive = false; + for (auto& callback : isResponsiveCallbacks) + callback(isWebProcessResponsive); } -void WebProcessProxy::interactionOccurredWhileUnresponsive(ResponsivenessTimer*) +void WebProcessProxy::didBecomeResponsive() { - Vector<RefPtr<WebPageProxy> > pages; + m_isResponsive = NoOrMaybe::Maybe; + + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); - for (size_t i = 0, size = pages.size(); i < size; ++i) - pages[i]->interactionOccurredWhileProcessUnresponsive(); + for (auto& page : pages) + page->processDidBecomeResponsive(); } -void WebProcessProxy::didBecomeResponsive(ResponsivenessTimer*) +void WebProcessProxy::willChangeIsResponsive() { - Vector<RefPtr<WebPageProxy> > pages; + Vector<RefPtr<WebPageProxy>> pages; copyValuesToVector(m_pageMap, pages); - for (size_t i = 0, size = pages.size(); i < size; ++i) - pages[i]->processDidBecomeResponsive(); + for (auto& page : pages) + page->willChangeProcessIsResponsive(); +} + +void WebProcessProxy::didChangeIsResponsive() +{ + Vector<RefPtr<WebPageProxy>> pages; + copyValuesToVector(m_pageMap, pages); + for (auto& page : pages) + page->didChangeProcessIsResponsive(); } -void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC::Connection::Identifier connectionIdentifier) +void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connection::Identifier connectionIdentifier) { ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier); + for (WebPageProxy* page : m_pageMap.values()) { + ASSERT(this == &page->process()); + page->processDidFinishLaunching(); + } + m_webConnection = WebConnectionToWebProcess::create(this); - m_context->processDidFinishLaunching(this); + m_processPool->processDidFinishLaunching(this); -#if PLATFORM(MAC) - updateProcessSuppressionState(); +#if PLATFORM(IOS) + xpc_connection_t xpcConnection = connection()->xpcConnection(); + ASSERT(xpcConnection); + m_throttler.didConnectToProcess(xpc_connection_get_pid(xpcConnection)); #endif } @@ -495,18 +639,18 @@ void WebProcessProxy::didDestroyFrame(uint64_t frameID) void WebProcessProxy::disconnectFramesFromPage(WebPageProxy* page) { - Vector<RefPtr<WebFrameProxy> > frames; + Vector<RefPtr<WebFrameProxy>> frames; copyValuesToVector(m_frameMap, frames); for (size_t i = 0, size = frames.size(); i < size; ++i) { if (frames[i]->page() == page) - frames[i]->disconnect(); + frames[i]->webProcessWillShutDown(); } } size_t WebProcessProxy::frameCountInPage(WebPageProxy* page) const { size_t result = 0; - for (HashMap<uint64_t, RefPtr<WebFrameProxy> >::const_iterator iter = m_frameMap.begin(); iter != m_frameMap.end(); ++iter) { + for (HashMap<uint64_t, RefPtr<WebFrameProxy>>::const_iterator iter = m_frameMap.begin(); iter != m_frameMap.end(); ++iter) { if (iter->value->page() == page) ++result; } @@ -518,10 +662,10 @@ bool WebProcessProxy::canTerminateChildProcess() if (!m_pageMap.isEmpty()) return false; - if (m_downloadProxyMap && !m_downloadProxyMap->isEmpty()) + if (!m_pendingDeleteWebsiteDataCallbacks.isEmpty()) return false; - if (!m_context->shouldTerminate(this)) + if (!m_processPool->shouldTerminate(this)) return false; return true; @@ -531,158 +675,352 @@ void WebProcessProxy::shouldTerminate(bool& shouldTerminate) { shouldTerminate = canTerminateChildProcess(); if (shouldTerminate) { - // We know that the web process is going to terminate so disconnect it from the context. - disconnect(); + // We know that the web process is going to terminate so start shutting it down in the UI process. + shutDown(); } } +void WebProcessProxy::didFetchWebsiteData(uint64_t callbackID, const WebsiteData& websiteData) +{ + auto callback = m_pendingFetchWebsiteDataCallbacks.take(callbackID); + callback(websiteData); +} + +void WebProcessProxy::didDeleteWebsiteData(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataCallbacks.take(callbackID); + callback(); +} + +void WebProcessProxy::didDeleteWebsiteDataForOrigins(uint64_t callbackID) +{ + auto callback = m_pendingDeleteWebsiteDataForOriginsCallbacks.take(callbackID); + callback(); +} + void WebProcessProxy::updateTextCheckerState() { if (canSendMessage()) send(Messages::WebProcess::SetTextCheckerState(TextChecker::state()), 0); } -DownloadProxy* WebProcessProxy::createDownloadProxy() +void WebProcessProxy::didSaveToPageCache() { -#if ENABLE(NETWORK_PROCESS) - ASSERT(!m_context->usesNetworkProcess()); -#endif + m_processPool->processDidCachePage(this); +} - if (!m_downloadProxyMap) - m_downloadProxyMap = adoptPtr(new DownloadProxyMap(this)); +void WebProcessProxy::releasePageCache() +{ + if (canSendMessage()) + send(Messages::WebProcess::ReleasePageCache(), 0); +} - return m_downloadProxyMap->createDownloadProxy(m_context.get()); +void WebProcessProxy::windowServerConnectionStateChanged() +{ + for (const auto& page : m_pageMap.values()) + page->viewStateDidChange(ViewState::IsVisuallyIdle); } -void WebProcessProxy::didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore& store, uint64_t frameID) +void WebProcessProxy::fetchWebsiteData(SessionID sessionID, WebsiteDataTypes dataTypes, std::function<void (WebsiteData)> completionHandler) { - WebPageProxy* page = webPage(pageID); - if (!page) - return; - - WebFrameProxy* frame = webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK(frame->page() == page); - - m_context->historyClient().didNavigateWithNavigationData(m_context.get(), page, store, frame); + ASSERT(canSendMessage()); + + uint64_t callbackID = generateCallbackID(); + auto token = throttler().backgroundActivityToken(); + + m_pendingFetchWebsiteDataCallbacks.add(callbackID, [token, completionHandler](WebsiteData websiteData) { + completionHandler(WTFMove(websiteData)); + }); + + send(Messages::WebProcess::FetchWebsiteData(sessionID, dataTypes, callbackID), 0); } -void WebProcessProxy::didPerformClientRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID) +void WebProcessProxy::deleteWebsiteData(SessionID sessionID, WebsiteDataTypes dataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler) { - WebPageProxy* page = webPage(pageID); - if (!page) - return; + ASSERT(canSendMessage()); - if (sourceURLString.isEmpty() || destinationURLString.isEmpty()) - return; - - WebFrameProxy* frame = webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK(frame->page() == page); - MESSAGE_CHECK_URL(sourceURLString); - MESSAGE_CHECK_URL(destinationURLString); + uint64_t callbackID = generateCallbackID(); + auto token = throttler().backgroundActivityToken(); - m_context->historyClient().didPerformClientRedirect(m_context.get(), page, sourceURLString, destinationURLString, frame); + m_pendingDeleteWebsiteDataCallbacks.add(callbackID, [token, completionHandler] { + completionHandler(); + }); + send(Messages::WebProcess::DeleteWebsiteData(sessionID, dataTypes, modifiedSince, callbackID), 0); } -void WebProcessProxy::didPerformServerRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID) +void WebProcessProxy::deleteWebsiteDataForOrigins(SessionID sessionID, WebsiteDataTypes dataTypes, const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, std::function<void ()> completionHandler) { - WebPageProxy* page = webPage(pageID); - if (!page) - return; - - if (sourceURLString.isEmpty() || destinationURLString.isEmpty()) + ASSERT(canSendMessage()); + + uint64_t callbackID = generateCallbackID(); + auto token = throttler().backgroundActivityToken(); + + m_pendingDeleteWebsiteDataForOriginsCallbacks.add(callbackID, [token, completionHandler] { + completionHandler(); + }); + + Vector<SecurityOriginData> originData; + for (auto& origin : origins) + originData.append(SecurityOriginData::fromSecurityOrigin(*origin)); + + send(Messages::WebProcess::DeleteWebsiteDataForOrigins(sessionID, dataTypes, originData, callbackID), 0); +} + +void WebProcessProxy::requestTermination() +{ + if (state() != State::Running) return; - - WebFrameProxy* frame = webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK(frame->page() == page); - MESSAGE_CHECK_URL(sourceURLString); - MESSAGE_CHECK_URL(destinationURLString); - m_context->historyClient().didPerformServerRedirect(m_context.get(), page, sourceURLString, destinationURLString, frame); + ChildProcessProxy::terminate(); + + if (webConnection()) + webConnection()->didClose(); + + shutDown(); } -void WebProcessProxy::didUpdateHistoryTitle(uint64_t pageID, const String& title, const String& url, uint64_t frameID) +void WebProcessProxy::enableSuddenTermination() { - WebPageProxy* page = webPage(pageID); - if (!page) + if (state() != State::Running) return; - WebFrameProxy* frame = webFrame(frameID); - MESSAGE_CHECK(frame); - MESSAGE_CHECK(frame->page() == page); - MESSAGE_CHECK_URL(url); + ASSERT(m_numberOfTimesSuddenTerminationWasDisabled); + WebCore::enableSuddenTermination(); + --m_numberOfTimesSuddenTerminationWasDisabled; +} + +void WebProcessProxy::disableSuddenTermination() +{ + if (state() != State::Running) + return; - m_context->historyClient().didUpdateHistoryTitle(m_context.get(), page, title, url, frame); + WebCore::disableSuddenTermination(); + ++m_numberOfTimesSuddenTerminationWasDisabled; } -void WebProcessProxy::pageVisibilityChanged(WebKit::WebPageProxy *page) +RefPtr<API::Object> WebProcessProxy::transformHandlesToObjects(API::Object* object) { -#if PLATFORM(MAC) - if (pageIsProcessSuppressible(page)) - m_processSuppressiblePages.add(page->pageID()); - else - m_processSuppressiblePages.remove(page->pageID()); - updateProcessSuppressionState(); -#else - UNUSED_PARAM(page); + struct Transformer final : UserData::Transformer { + Transformer(WebProcessProxy& webProcessProxy) + : m_webProcessProxy(webProcessProxy) + { + } + + virtual bool shouldTransformObject(const API::Object& object) const override + { + switch (object.type()) { + case API::Object::Type::FrameHandle: + return static_cast<const API::FrameHandle&>(object).isAutoconverting(); + + case API::Object::Type::PageHandle: + return static_cast<const API::PageHandle&>(object).isAutoconverting(); + + case API::Object::Type::PageGroupHandle: +#if PLATFORM(COCOA) + case API::Object::Type::ObjCObjectGraph: +#endif + return true; + + default: + return false; + } + } + + virtual RefPtr<API::Object> transformObject(API::Object& object) const override + { + switch (object.type()) { + case API::Object::Type::FrameHandle: + ASSERT(static_cast<API::FrameHandle&>(object).isAutoconverting()); + return m_webProcessProxy.webFrame(static_cast<API::FrameHandle&>(object).frameID()); + + case API::Object::Type::PageGroupHandle: + return WebPageGroup::get(static_cast<API::PageGroupHandle&>(object).webPageGroupData().pageGroupID); + + case API::Object::Type::PageHandle: + ASSERT(static_cast<API::PageHandle&>(object).isAutoconverting()); + return m_webProcessProxy.webPage(static_cast<API::PageHandle&>(object).pageID()); + +#if PLATFORM(COCOA) + case API::Object::Type::ObjCObjectGraph: + return m_webProcessProxy.transformHandlesToObjects(static_cast<ObjCObjectGraph&>(object)); #endif + default: + return &object; + } + } + + WebProcessProxy& m_webProcessProxy; + }; + + return UserData::transform(object, Transformer(*this)); } -void WebProcessProxy::pagePreferencesChanged(WebKit::WebPageProxy *page) +RefPtr<API::Object> WebProcessProxy::transformObjectsToHandles(API::Object* object) { -#if PLATFORM(MAC) - if (pageIsProcessSuppressible(page)) - m_processSuppressiblePages.add(page->pageID()); - else - m_processSuppressiblePages.remove(page->pageID()); - updateProcessSuppressionState(); -#else - UNUSED_PARAM(page); + struct Transformer final : UserData::Transformer { + virtual bool shouldTransformObject(const API::Object& object) const override + { + switch (object.type()) { + case API::Object::Type::Frame: + case API::Object::Type::Page: + case API::Object::Type::PageGroup: +#if PLATFORM(COCOA) + case API::Object::Type::ObjCObjectGraph: #endif + return true; + + default: + return false; + } + } + + virtual RefPtr<API::Object> transformObject(API::Object& object) const override + { + switch (object.type()) { + case API::Object::Type::Frame: + return API::FrameHandle::createAutoconverting(static_cast<const WebFrameProxy&>(object).frameID()); + + case API::Object::Type::Page: + return API::PageHandle::createAutoconverting(static_cast<const WebPageProxy&>(object).pageID()); + + case API::Object::Type::PageGroup: + return API::PageGroupHandle::create(WebPageGroupData(static_cast<const WebPageGroup&>(object).data())); + +#if PLATFORM(COCOA) + case API::Object::Type::ObjCObjectGraph: + return transformObjectsToHandles(static_cast<ObjCObjectGraph&>(object)); +#endif + + default: + return &object; + } + } + }; + + return UserData::transform(object, Transformer()); } -void WebProcessProxy::didSaveToPageCache() +void WebProcessProxy::sendProcessWillSuspendImminently() { - m_context->processDidCachePage(this); + if (!canSendMessage()) + return; + + bool handled = false; + sendSync(Messages::WebProcess::ProcessWillSuspendImminently(), Messages::WebProcess::ProcessWillSuspendImminently::Reply(handled), 0, std::chrono::seconds(1)); } -void WebProcessProxy::releasePageCache() +void WebProcessProxy::sendPrepareToSuspend() { if (canSendMessage()) - send(Messages::WebProcess::ReleasePageCache(), 0); + send(Messages::WebProcess::PrepareToSuspend(), 0); } +void WebProcessProxy::sendCancelPrepareToSuspend() +{ + if (canSendMessage()) + send(Messages::WebProcess::CancelPrepareToSuspend(), 0); +} -void WebProcessProxy::requestTermination() +void WebProcessProxy::sendProcessDidResume() { - if (!isValid()) - return; + if (canSendMessage()) + send(Messages::WebProcess::ProcessDidResume(), 0); +} - ChildProcessProxy::terminate(); +void WebProcessProxy::processReadyToSuspend() +{ + m_throttler.processReadyToSuspend(); +} - if (webConnection()) - webConnection()->didClose(); +void WebProcessProxy::didCancelProcessSuspension() +{ + m_throttler.didCancelProcessSuspension(); +} - disconnect(); +void WebProcessProxy::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy) +{ +#if PLATFORM(IOS) + ASSERT(!m_backgroundTokenForNetworkProcess || !m_foregroundTokenForNetworkProcess); + + // The network process crashed; take new tokens for the new network process. + if (m_backgroundTokenForNetworkProcess) + m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken(); + else if (m_foregroundTokenForNetworkProcess) + m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken(); +#else + UNUSED_PARAM(newNetworkProcessProxy); +#endif } +void WebProcessProxy::didSetAssertionState(AssertionState state) +{ +#if PLATFORM(IOS) + ASSERT(!m_backgroundTokenForNetworkProcess || !m_foregroundTokenForNetworkProcess); + + switch (state) { + case AssertionState::Suspended: + m_foregroundTokenForNetworkProcess = nullptr; + m_backgroundTokenForNetworkProcess = nullptr; + for (auto& page : m_pageMap.values()) + page->processWillBecomeSuspended(); + break; + + case AssertionState::Background: + m_backgroundTokenForNetworkProcess = processPool().ensureNetworkProcess().throttler().backgroundActivityToken(); + m_foregroundTokenForNetworkProcess = nullptr; + break; + + case AssertionState::Foreground: + m_foregroundTokenForNetworkProcess = processPool().ensureNetworkProcess().throttler().foregroundActivityToken(); + m_backgroundTokenForNetworkProcess = nullptr; + for (auto& page : m_pageMap.values()) + page->processWillBecomeForeground(); + break; + } -void WebProcessProxy::enableSuddenTermination() + ASSERT(!m_backgroundTokenForNetworkProcess || !m_foregroundTokenForNetworkProcess); +#else + UNUSED_PARAM(state); +#endif +} + +void WebProcessProxy::setIsHoldingLockedFiles(bool isHoldingLockedFiles) { - if (!isValid()) + if (!isHoldingLockedFiles) { + m_tokenForHoldingLockedFiles = nullptr; return; - - WebCore::enableSuddenTermination(); + } + if (!m_tokenForHoldingLockedFiles) + m_tokenForHoldingLockedFiles = m_throttler.backgroundActivityToken(); } -void WebProcessProxy::disableSuddenTermination() +void WebProcessProxy::isResponsive(std::function<void(bool isWebProcessResponsive)> callback) { - if (!isValid()) + if (m_isResponsive == NoOrMaybe::No) { + if (callback) { + RunLoop::main().dispatch([callback] { + bool isWebProcessResponsive = false; + callback(isWebProcessResponsive); + }); + } return; + } - WebCore::disableSuddenTermination(); + if (callback) + m_isResponsiveCallbacks.append(callback); + + responsivenessTimer().start(); + send(Messages::WebProcess::MainThreadPing(), 0); +} + +void WebProcessProxy::didReceiveMainThreadPing() +{ + responsivenessTimer().stop(); + + auto isResponsiveCallbacks = WTFMove(m_isResponsiveCallbacks); + bool isWebProcessResponsive = true; + for (auto& callback : isResponsiveCallbacks) + callback(isWebProcessResponsive); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebProcessProxy.h b/Source/WebKit2/UIProcess/WebProcessProxy.h index a22f4723f..d40c57c23 100644 --- a/Source/WebKit2/UIProcess/WebProcessProxy.h +++ b/Source/WebKit2/UIProcess/WebProcessProxy.h @@ -26,65 +26,78 @@ #ifndef WebProcessProxy_h #define WebProcessProxy_h +#include "APISession.h" #include "ChildProcessProxy.h" +#include "CustomProtocolManagerProxy.h" #include "MessageReceiverMap.h" #include "PlatformProcessIdentifier.h" #include "PluginInfoStore.h" #include "ProcessLauncher.h" +#include "ProcessThrottlerClient.h" #include "ResponsivenessTimer.h" #include "WebConnectionToWebProcess.h" #include "WebPageProxy.h" #include "WebProcessProxyMessages.h" +#include "WebsiteDataTypes.h" #include <WebCore/LinkHash.h> +#include <memory> #include <wtf/Forward.h> #include <wtf/HashMap.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> -#if ENABLE(CUSTOM_PROTOCOLS) -#include "CustomProtocolManagerProxy.h" +#if PLATFORM(IOS) +#include "ProcessThrottler.h" #endif namespace WebCore { -class KURL; +class ResourceRequest; +class URL; struct PluginInfo; }; namespace WebKit { -class DownloadProxyMap; +class NetworkProcessProxy; class WebBackForwardListItem; -class WebContext; class WebPageGroup; +class WebProcessPool; struct WebNavigationDataStore; - -class WebProcessProxy : public ChildProcessProxy, ResponsivenessTimer::Client { + +class WebProcessProxy : public ChildProcessProxy, ResponsivenessTimer::Client, private ProcessThrottlerClient { public: - typedef HashMap<uint64_t, RefPtr<WebBackForwardListItem> > WebBackForwardListItemMap; - typedef HashMap<uint64_t, RefPtr<WebFrameProxy> > WebFrameProxyMap; + typedef HashMap<uint64_t, RefPtr<WebBackForwardListItem>> WebBackForwardListItemMap; + typedef HashMap<uint64_t, RefPtr<WebFrameProxy>> WebFrameProxyMap; typedef HashMap<uint64_t, WebPageProxy*> WebPageProxyMap; - static PassRefPtr<WebProcessProxy> create(PassRefPtr<WebContext>); + static Ref<WebProcessProxy> create(WebProcessPool&); ~WebProcessProxy(); - static WebProcessProxy* fromConnection(CoreIPC::Connection* connection) + static WebProcessProxy* fromConnection(IPC::Connection* connection) { return static_cast<WebProcessProxy*>(ChildProcessProxy::fromConnection(connection)); } WebConnection* webConnection() const { return m_webConnection.get(); } - WebContext* context() const { return m_context.get(); } + WebProcessPool& processPool() { return m_processPool; } static WebPageProxy* webPage(uint64_t pageID); - PassRefPtr<WebPageProxy> createWebPage(PageClient*, WebContext*, WebPageGroup*); + Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&); void addExistingWebPage(WebPageProxy*, uint64_t pageID); void removeWebPage(uint64_t pageID); - Vector<WebPageProxy*> pages() const; + + WTF::IteratorRange<WebPageProxyMap::const_iterator::Values> pages() const { return m_pageMap.values(); } + unsigned pageCount() const { return m_pageMap.size(); } + + void addVisitedLinkStore(VisitedLinkStore&); + void addWebUserContentControllerProxy(WebUserContentControllerProxy&); + void didDestroyVisitedLinkStore(VisitedLinkStore&); + void didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy&); WebBackForwardListItem* webBackForwardItem(uint64_t itemID) const; - ResponsivenessTimer* responsivenessTimer() { return &m_responsivenessTimer; } + ResponsivenessTimer& responsivenessTimer() { return m_responsivenessTimer; } WebFrameProxy* webFrame(uint64_t) const; bool canCreateFrame(uint64_t frameID) const; @@ -95,101 +108,125 @@ public: void updateTextCheckerState(); void registerNewWebBackForwardListItem(WebBackForwardListItem*); + void removeBackForwardItem(uint64_t); void willAcquireUniversalFileReadSandboxExtension() { m_mayHaveUniversalFileReadSandboxExtension = true; } void assumeReadAccessToBaseURL(const String&); + bool hasAssumedReadAccessToURL(const WebCore::URL&) const; bool checkURLReceivedFromWebProcess(const String&); - bool checkURLReceivedFromWebProcess(const WebCore::KURL&); + bool checkURLReceivedFromWebProcess(const WebCore::URL&); static bool fullKeyboardAccessEnabled(); - DownloadProxy* createDownloadProxy(); - - void pageVisibilityChanged(WebPageProxy*); - void pagePreferencesChanged(WebPageProxy*); - void didSaveToPageCache(); void releasePageCache(); -#if PLATFORM(MAC) - bool allPagesAreProcessSuppressible() const; - static bool pageIsProcessSuppressible(WebPageProxy*); - void updateProcessSuppressionState(); -#endif + void fetchWebsiteData(WebCore::SessionID, WebsiteDataTypes, std::function<void (WebsiteData)> completionHandler); + void deleteWebsiteData(WebCore::SessionID, WebsiteDataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler); + void deleteWebsiteDataForOrigins(WebCore::SessionID, WebsiteDataTypes, const Vector<RefPtr<WebCore::SecurityOrigin>>& origins, std::function<void ()> completionHandler); void enableSuddenTermination(); void disableSuddenTermination(); + bool isSuddenTerminationEnabled() { return !m_numberOfTimesSuddenTerminationWasDisabled; } void requestTermination(); + RefPtr<API::Object> transformHandlesToObjects(API::Object*); + static RefPtr<API::Object> transformObjectsToHandles(API::Object*); + +#if PLATFORM(COCOA) + RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&); + static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&); +#endif + + void windowServerConnectionStateChanged(); + + void processReadyToSuspend(); + void didCancelProcessSuspension(); + + void setIsHoldingLockedFiles(bool); + + ProcessThrottler& throttler() { return m_throttler; } + + void reinstateNetworkProcessAssertionState(NetworkProcessProxy&); + + void isResponsive(std::function<void(bool isWebProcessResponsive)>); + void didReceiveMainThreadPing(); + private: - explicit WebProcessProxy(PassRefPtr<WebContext>); + explicit WebProcessProxy(WebProcessPool&); // From ChildProcessProxy - virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) OVERRIDE; - void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&); - virtual void connectionWillOpen(CoreIPC::Connection*) OVERRIDE; - virtual void connectionWillClose(CoreIPC::Connection*) OVERRIDE; + virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&) override; + virtual void connectionWillOpen(IPC::Connection&) override; + virtual void processWillShutDown(IPC::Connection&) override; // Called when the web process has crashed or we know that it will terminate soon. // Will potentially cause the WebProcessProxy object to be freed. - void disconnect(); + void shutDown(); - // CoreIPC message handlers. - void addBackForwardItem(uint64_t itemID, const String& originalURLString, const String& urlString, const String& title, const CoreIPC::DataReference& backForwardData); + // IPC message handlers. + void addBackForwardItem(uint64_t itemID, uint64_t pageID, const PageState&); void didDestroyFrame(uint64_t); void shouldTerminate(bool& shouldTerminate); + void didFetchWebsiteData(uint64_t callbackID, const WebsiteData&); + void didDeleteWebsiteData(uint64_t callbackID); + void didDeleteWebsiteDataForOrigins(uint64_t callbackID); + // Plugins #if ENABLE(NETSCAPE_PLUGIN_API) - void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins); + void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins); #endif // ENABLE(NETSCAPE_PLUGIN_API) -#if ENABLE(PLUGIN_PROCESS) +#if ENABLE(NETSCAPE_PLUGIN_API) void getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>); -#elif ENABLE(NETSCAPE_PLUGIN_API) - void didGetSitesWithPluginData(const Vector<String>& sites, uint64_t callbackID); - void didClearPluginSiteData(uint64_t callbackID); #endif -#if ENABLE(NETWORK_PROCESS) void getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>); +#if ENABLE(DATABASE_PROCESS) + void getDatabaseProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetDatabaseProcessConnection::DelayedReply>); #endif -#if ENABLE(SHARED_WORKER_PROCESS) - void getSharedWorkerProcessConnection(const String& url, const String& name, PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>); -#endif - // CoreIPC::Connection::Client + void retainIconForPageURL(const String& pageURL); + void releaseIconForPageURL(const String& pageURL); + void releaseRemainingIconsForPageURLs(); + + // IPC::Connection::Client friend class WebConnectionToWebProcess; - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - virtual void didReceiveSyncMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&) OVERRIDE; - virtual void didClose(CoreIPC::Connection*) OVERRIDE; - virtual void didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName) OVERRIDE; + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; + virtual void didReceiveSyncMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&) override; + virtual void didClose(IPC::Connection&) override; + virtual void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override; + virtual IPC::ProcessType localProcessType() override { return IPC::ProcessType::UI; } + virtual IPC::ProcessType remoteProcessType() override { return IPC::ProcessType::Web; } // ResponsivenessTimer::Client - void didBecomeUnresponsive(ResponsivenessTimer*) OVERRIDE; - void interactionOccurredWhileUnresponsive(ResponsivenessTimer*) OVERRIDE; - void didBecomeResponsive(ResponsivenessTimer*) OVERRIDE; + void didBecomeUnresponsive() override; + void didBecomeResponsive() override; + virtual void willChangeIsResponsive() override; + virtual void didChangeIsResponsive() override; + + // ProcessThrottlerClient + void sendProcessWillSuspendImminently() override; + void sendPrepareToSuspend() override; + void sendCancelPrepareToSuspend() override; + void sendProcessDidResume() override; + void didSetAssertionState(AssertionState) override; // ProcessLauncher::Client - virtual void didFinishLaunching(ProcessLauncher*, CoreIPC::Connection::Identifier) OVERRIDE; - - // History client - void didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore&, uint64_t frameID); - void didPerformClientRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID); - void didPerformServerRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID); - void didUpdateHistoryTitle(uint64_t pageID, const String& title, const String& url, uint64_t frameID); + virtual void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override; // Implemented in generated WebProcessProxyMessageReceiver.cpp - void didReceiveWebProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&); - void didReceiveSyncWebProcessProxyMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&, OwnPtr<CoreIPC::MessageEncoder>&); + void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::MessageDecoder&); + void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::MessageDecoder&, std::unique_ptr<IPC::MessageEncoder>&); bool canTerminateChildProcess(); ResponsivenessTimer m_responsivenessTimer; RefPtr<WebConnectionToWebProcess> m_webConnection; - RefPtr<WebContext> m_context; + Ref<WebProcessPool> m_processPool; bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it. HashSet<String> m_localPathsWithAssumedReadAccess; @@ -198,18 +235,29 @@ private: WebFrameProxyMap m_frameMap; WebBackForwardListItemMap m_backForwardListItemMap; - OwnPtr<DownloadProxyMap> m_downloadProxyMap; + HashSet<VisitedLinkStore*> m_visitedLinkStores; + HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies; -#if ENABLE(CUSTOM_PROTOCOLS) CustomProtocolManagerProxy m_customProtocolManagerProxy; -#endif -#if PLATFORM(MAC) - HashSet<uint64_t> m_processSuppressiblePages; - bool m_processSuppressionEnabled; + HashMap<uint64_t, std::function<void (WebsiteData)>> m_pendingFetchWebsiteDataCallbacks; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataCallbacks; + HashMap<uint64_t, std::function<void ()>> m_pendingDeleteWebsiteDataForOriginsCallbacks; + + int m_numberOfTimesSuddenTerminationWasDisabled; + ProcessThrottler m_throttler; + ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles; +#if PLATFORM(IOS) + ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess; + ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess; #endif + + HashMap<String, uint64_t> m_pageURLRetainCountMap; + + enum class NoOrMaybe { No, Maybe } m_isResponsive; + Vector<std::function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks; }; - + } // namespace WebKit #endif // WebProcessProxy_h diff --git a/Source/WebKit2/UIProcess/WebProcessProxy.messages.in b/Source/WebKit2/UIProcess/WebProcessProxy.messages.in index fe6d3a295..3fa636273 100644 --- a/Source/WebKit2/UIProcess/WebProcessProxy.messages.in +++ b/Source/WebKit2/UIProcess/WebProcessProxy.messages.in @@ -21,14 +21,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. messages -> WebProcessProxy LegacyReceiver { - - # History client messages. - DidNavigateWithNavigationData(uint64_t pageID, WebKit::WebNavigationDataStore store, uint64_t frameID) - DidPerformClientRedirect(uint64_t pageID, WTF::String sourceURLString, WTF::String destinationURLString, uint64_t frameID) - DidPerformServerRedirect(uint64_t pageID, WTF::String sourceURLString, WTF::String destinationURLString, uint64_t frameID) - DidUpdateHistoryTitle(uint64_t pageID, WTF::String title, WTF::String url, uint64_t frameID) - - AddBackForwardItem(uint64_t itemID, WTF::String originalURL, WTF::String url, WTF::String title, CoreIPC::DataReference backForwardData) + AddBackForwardItem(uint64_t itemID, uint64_t pageID, struct WebKit::PageState pageState) DidDestroyFrame(uint64_t frameID) ShouldTerminate() -> (bool shouldTerminate) @@ -36,22 +29,26 @@ messages -> WebProcessProxy LegacyReceiver { EnableSuddenTermination() DisableSuddenTermination() + DidFetchWebsiteData(uint64_t callbackID, struct WebKit::WebsiteData websiteData) + DidDeleteWebsiteData(uint64_t callbackID) + DidDeleteWebsiteDataForOrigins(uint64_t callbackID) + # Plugin messages. #if ENABLE(NETSCAPE_PLUGIN_API) - GetPlugins(bool refresh) -> (Vector<WebCore::PluginInfo> plugins) -#endif // ENABLE(NETSCAPE_PLUGIN_API) -#if ENABLE(PLUGIN_PROCESS) - GetPluginProcessConnection(uint64_t pluginProcessToken) -> (CoreIPC::Attachment connectionHandle, bool supportsAsynchronousInitialization) Delayed -#endif -#if ENABLE(NETSCAPE_PLUGIN_API) && !ENABLE(PLUGIN_PROCESS) - void DidGetSitesWithPluginData(Vector<WTF::String> sites, uint64_t callbackID) - void DidClearPluginSiteData(uint64_t callbackID) + GetPlugins(bool refresh) -> (Vector<WebCore::PluginInfo> plugins, Vector<WebCore::PluginInfo> applicationPlugins) + GetPluginProcessConnection(uint64_t pluginProcessToken) -> (IPC::Attachment connectionHandle, bool supportsAsynchronousInitialization) Delayed #endif -#if ENABLE(NETWORK_PROCESS) - GetNetworkProcessConnection() -> (CoreIPC::Attachment connectionHandle) Delayed -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - GetSharedWorkerProcessConnection(WTF::String url, WTF::String name) -> (CoreIPC::Attachment connectionHandle) Delayed + GetNetworkProcessConnection() -> (IPC::Attachment connectionHandle) Delayed +#if ENABLE(DATABASE_PROCESS) + GetDatabaseProcessConnection() -> (IPC::Attachment connectionHandle) Delayed #endif + ProcessReadyToSuspend() + DidCancelProcessSuspension() + + SetIsHoldingLockedFiles(bool isHoldingLockedFiles) + + RetainIconForPageURL(String pageURL) + ReleaseIconForPageURL(String pageURL) + DidReceiveMainThreadPing() } diff --git a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp deleted file mode 100644 index 38299871c..000000000 --- a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebResourceCacheManagerProxy.h" - -#include "ImmutableArray.h" -#include "ImmutableDictionary.h" -#include "SecurityOriginData.h" -#include "WebContext.h" -#include "WebResourceCacheManagerMessages.h" -#include "WebResourceCacheManagerProxyMessages.h" -#include "WebSecurityOrigin.h" - -#if ENABLE(NETWORK_PROCESS) -#include "NetworkProcessMessages.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -const char* WebResourceCacheManagerProxy::supplementName() -{ - return "WebResourceCacheManagerProxy"; -} - -PassRefPtr<WebResourceCacheManagerProxy> WebResourceCacheManagerProxy::create(WebContext* webContext) -{ - return adoptRef(new WebResourceCacheManagerProxy(webContext)); -} - -WebResourceCacheManagerProxy::WebResourceCacheManagerProxy(WebContext* webContext) - : WebContextSupplement(webContext) -{ - WebContextSupplement::context()->addMessageReceiver(Messages::WebResourceCacheManagerProxy::messageReceiverName(), this); -} - -WebResourceCacheManagerProxy::~WebResourceCacheManagerProxy() -{ -} - -// WebContextSupplement - -void WebResourceCacheManagerProxy::contextDestroyed() -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -void WebResourceCacheManagerProxy::processDidClose(WebProcessProxy*) -{ - invalidateCallbackMap(m_arrayCallbacks); -} - -bool WebResourceCacheManagerProxy::shouldTerminate(WebProcessProxy*) const -{ - return m_arrayCallbacks.isEmpty(); -} - -void WebResourceCacheManagerProxy::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebResourceCacheManagerProxy::derefWebContextSupplement() -{ - APIObject::deref(); -} - -void WebResourceCacheManagerProxy::getCacheOrigins(PassRefPtr<ArrayCallback> prpCallback) -{ - RefPtr<ArrayCallback> callback = prpCallback; - uint64_t callbackID = callback->callbackID(); - m_arrayCallbacks.set(callbackID, callback.release()); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> When multi-process is enabled, we need to aggregate the callback data from all processes. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::GetCacheOrigins(callbackID)); -} - -void WebResourceCacheManagerProxy::didGetCacheOrigins(const Vector<SecurityOriginData>& origins, uint64_t callbackID) -{ - RefPtr<ArrayCallback> callback = m_arrayCallbacks.take(callbackID); - performAPICallbackWithSecurityOriginDataVector(origins, callback.get()); -} - -void WebResourceCacheManagerProxy::clearCacheForOrigin(WebSecurityOrigin* origin, ResourceCachesToClear cachesToClear) -{ - SecurityOriginData securityOrigin; - securityOrigin.protocol = origin->protocol(); - securityOrigin.host = origin->host(); - securityOrigin.port = origin->port(); - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> There is no need to relaunch all processes. One process to take care of persistent cache is enough. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::ClearCacheForOrigin(securityOrigin, cachesToClear)); -} - -void WebResourceCacheManagerProxy::clearCacheForAllOrigins(ResourceCachesToClear cachesToClear) -{ -#if ENABLE(NETWORK_PROCESS) - context()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::ClearCacheForAllOrigins(cachesToClear)); -#endif - - // FIXME (Multi-WebProcess): <rdar://problem/12239765> There is no need to relaunch all processes. One process to take care of persistent cache is enough. - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebResourceCacheManager::ClearCacheForAllOrigins(cachesToClear)); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h deleted file mode 100644 index 3b5a3b2d9..000000000 --- a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2011, 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebResourceCacheManagerProxy_h -#define WebResourceCacheManagerProxy_h - -#include "APIObject.h" -#include "Arguments.h" -#include "GenericCallback.h" -#include "MessageReceiver.h" -#include "ResourceCachesToClear.h" -#include "WebContextSupplement.h" -#include <wtf/HashMap.h> -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -struct SecurityOriginData; -class WebContext; -class WebProcessProxy; -class WebSecurityOrigin; - -typedef GenericCallback<WKArrayRef> ArrayCallback; - -class WebResourceCacheManagerProxy : public TypedAPIObject<APIObject::TypeCacheManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { -public: - static const char* supplementName(); - - static PassRefPtr<WebResourceCacheManagerProxy> create(WebContext*); - virtual ~WebResourceCacheManagerProxy(); - - void getCacheOrigins(PassRefPtr<ArrayCallback>); - void clearCacheForOrigin(WebSecurityOrigin*, ResourceCachesToClear); - void clearCacheForAllOrigins(ResourceCachesToClear); - - using APIObject::ref; - using APIObject::deref; - -private: - explicit WebResourceCacheManagerProxy(WebContext*); - - // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual bool shouldTerminate(WebProcessProxy*) const OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - // Message handlers. - void didGetCacheOrigins(const Vector<SecurityOriginData>& originIdentifiers, uint64_t callbackID); - - HashMap<uint64_t, RefPtr<ArrayCallback> > m_arrayCallbacks; -}; - -} // namespace WebKit - -#endif // DatabaseManagerProxy_h diff --git a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.messages.in b/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.messages.in deleted file mode 100644 index c1e73a9af..000000000 --- a/Source/WebKit2/UIProcess/WebResourceCacheManagerProxy.messages.in +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (C) 2011 Apple Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -messages -> WebResourceCacheManagerProxy { - DidGetCacheOrigins(Vector<WebKit::SecurityOriginData> originIdentifiers, uint64_t callbackID) -} diff --git a/Source/WebKit2/UIProcess/WebTextChecker.cpp b/Source/WebKit2/UIProcess/WebTextChecker.cpp index f4a65526a..8a85434ea 100644 --- a/Source/WebKit2/UIProcess/WebTextChecker.cpp +++ b/Source/WebKit2/UIProcess/WebTextChecker.cpp @@ -28,12 +28,12 @@ #include "TextChecker.h" #include "WKAPICast.h" -#include "WebContext.h" +#include "WebProcessPool.h" #include <wtf/RefPtr.h> namespace WebKit { -WebTextChecker* WebTextChecker::shared() +WebTextChecker* WebTextChecker::singleton() { static WebTextChecker* textChecker = adoptRef(new WebTextChecker).leakRef(); return textChecker; @@ -43,14 +43,14 @@ WebTextChecker::WebTextChecker() { } -void WebTextChecker::setClient(const WKTextCheckerClient* client) +void WebTextChecker::setClient(const WKTextCheckerClientBase* client) { m_client.initialize(client); } static void updateStateForAllContexts() { - const Vector<WebContext*>& contexts = WebContext::allContexts(); + const Vector<WebProcessPool*>& contexts = WebProcessPool::allProcessPools(); for (size_t i = 0; i < contexts.size(); ++i) contexts[i]->textCheckerStateChanged(); } @@ -67,12 +67,12 @@ void WebTextChecker::grammarCheckingEnabledStateChanged(bool enabled) updateStateForAllContexts(); } -void WebTextChecker::checkSpelling(const WebPageProxy* page, bool startBeforeSelection) +void WebTextChecker::checkSpelling(WebPageProxy* page, bool startBeforeSelection) { page->advanceToNextMisspelling(startBeforeSelection); } -void WebTextChecker::changeSpellingToWord(const WebPageProxy* page, const String& text) +void WebTextChecker::changeSpellingToWord(WebPageProxy* page, const String& text) { page->changeSpellingToWord(text); } diff --git a/Source/WebKit2/UIProcess/WebTextChecker.h b/Source/WebKit2/UIProcess/WebTextChecker.h index 863ed03c7..7c945c726 100644 --- a/Source/WebKit2/UIProcess/WebTextChecker.h +++ b/Source/WebKit2/UIProcess/WebTextChecker.h @@ -35,18 +35,18 @@ namespace WebKit { class WebPageProxy; -class WebTextChecker : public TypedAPIObject<APIObject::TypeTextChecker> { +class WebTextChecker : public API::ObjectImpl<API::Object::Type::TextChecker> { public: - static WebTextChecker* shared(); + static WebTextChecker* singleton(); - void setClient(const WKTextCheckerClient*); + void setClient(const WKTextCheckerClientBase*); WebTextCheckerClient& client() { return m_client; } void continuousSpellCheckingEnabledStateChanged(bool); void grammarCheckingEnabledStateChanged(bool); - void checkSpelling(const WebPageProxy*, bool startBeforeSelection); - void changeSpellingToWord(const WebPageProxy*, const String&); + void checkSpelling(WebPageProxy*, bool startBeforeSelection); + void changeSpellingToWord(WebPageProxy*, const String&); private: WebTextChecker(); diff --git a/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp b/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp index cc69d5e69..2d703d7d6 100644 --- a/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp +++ b/Source/WebKit2/UIProcess/WebTextCheckerClient.cpp @@ -26,7 +26,7 @@ #include "config.h" #include "WebTextCheckerClient.h" -#include "ImmutableArray.h" +#include "APIArray.h" #include "WKAPICast.h" #include "WKSharedAPICast.h" #include "WebGrammarDetail.h" @@ -40,7 +40,7 @@ bool WebTextCheckerClient::continuousSpellCheckingAllowed() if (!m_client.continuousSpellCheckingAllowed) return false; - return m_client.continuousSpellCheckingAllowed(m_client.clientInfo); + return m_client.continuousSpellCheckingAllowed(m_client.base.clientInfo); } bool WebTextCheckerClient::continuousSpellCheckingEnabled() @@ -48,7 +48,7 @@ bool WebTextCheckerClient::continuousSpellCheckingEnabled() if (!m_client.continuousSpellCheckingEnabled) return false; - return m_client.continuousSpellCheckingEnabled(m_client.clientInfo); + return m_client.continuousSpellCheckingEnabled(m_client.base.clientInfo); } void WebTextCheckerClient::setContinuousSpellCheckingEnabled(bool enabled) @@ -56,7 +56,7 @@ void WebTextCheckerClient::setContinuousSpellCheckingEnabled(bool enabled) if (!m_client.setContinuousSpellCheckingEnabled) return; - m_client.setContinuousSpellCheckingEnabled(enabled, m_client.clientInfo); + m_client.setContinuousSpellCheckingEnabled(enabled, m_client.base.clientInfo); } bool WebTextCheckerClient::grammarCheckingEnabled() @@ -64,7 +64,7 @@ bool WebTextCheckerClient::grammarCheckingEnabled() if (!m_client.grammarCheckingEnabled) return false; - return m_client.grammarCheckingEnabled(m_client.clientInfo); + return m_client.grammarCheckingEnabled(m_client.base.clientInfo); } void WebTextCheckerClient::setGrammarCheckingEnabled(bool enabled) @@ -72,7 +72,7 @@ void WebTextCheckerClient::setGrammarCheckingEnabled(bool enabled) if (!m_client.setGrammarCheckingEnabled) return; - m_client.setGrammarCheckingEnabled(enabled, m_client.clientInfo); + m_client.setGrammarCheckingEnabled(enabled, m_client.base.clientInfo); } uint64_t WebTextCheckerClient::uniqueSpellDocumentTag(WebPageProxy* page) @@ -80,7 +80,7 @@ uint64_t WebTextCheckerClient::uniqueSpellDocumentTag(WebPageProxy* page) if (!m_client.uniqueSpellDocumentTag) return 0; - return m_client.uniqueSpellDocumentTag(toAPI(page), m_client.clientInfo); + return m_client.uniqueSpellDocumentTag(toAPI(page), m_client.base.clientInfo); } void WebTextCheckerClient::closeSpellDocumentWithTag(uint64_t tag) @@ -88,7 +88,7 @@ void WebTextCheckerClient::closeSpellDocumentWithTag(uint64_t tag) if (!m_client.closeSpellDocumentWithTag) return; - m_client.closeSpellDocumentWithTag(tag, m_client.clientInfo); + m_client.closeSpellDocumentWithTag(tag, m_client.base.clientInfo); } void WebTextCheckerClient::checkSpellingOfString(uint64_t tag, const String& text, int32_t& misspellingLocation, int32_t& misspellingLength) @@ -99,7 +99,7 @@ void WebTextCheckerClient::checkSpellingOfString(uint64_t tag, const String& tex if (!m_client.checkSpellingOfString) return; - m_client.checkSpellingOfString(tag, toAPI(text.impl()), &misspellingLocation, &misspellingLength, m_client.clientInfo); + m_client.checkSpellingOfString(tag, toAPI(text.impl()), &misspellingLocation, &misspellingLength, m_client.base.clientInfo); } void WebTextCheckerClient::checkGrammarOfString(uint64_t tag, const String& text, Vector<WebCore::GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength) @@ -111,9 +111,9 @@ void WebTextCheckerClient::checkGrammarOfString(uint64_t tag, const String& text return; WKArrayRef wkGrammarDetailsRef = 0; - m_client.checkGrammarOfString(tag, toAPI(text.impl()), &wkGrammarDetailsRef, &badGrammarLocation, &badGrammarLength, m_client.clientInfo); + m_client.checkGrammarOfString(tag, toAPI(text.impl()), &wkGrammarDetailsRef, &badGrammarLocation, &badGrammarLength, m_client.base.clientInfo); - RefPtr<ImmutableArray> wkGrammarDetails = adoptRef(toImpl(wkGrammarDetailsRef)); + RefPtr<API::Array> wkGrammarDetails = adoptRef(toImpl(wkGrammarDetailsRef)); size_t numGrammarDetails = wkGrammarDetails->size(); for (size_t i = 0; i < numGrammarDetails; ++i) grammarDetails.append(wkGrammarDetails->at<WebGrammarDetail>(i)->grammarDetail()); @@ -124,7 +124,7 @@ bool WebTextCheckerClient::spellingUIIsShowing() if (!m_client.spellingUIIsShowing) return false; - return m_client.spellingUIIsShowing(m_client.clientInfo); + return m_client.spellingUIIsShowing(m_client.base.clientInfo); } void WebTextCheckerClient::toggleSpellingUIIsShowing() @@ -132,7 +132,7 @@ void WebTextCheckerClient::toggleSpellingUIIsShowing() if (!m_client.toggleSpellingUIIsShowing) return; - return m_client.toggleSpellingUIIsShowing(m_client.clientInfo); + return m_client.toggleSpellingUIIsShowing(m_client.base.clientInfo); } void WebTextCheckerClient::updateSpellingUIWithMisspelledWord(uint64_t tag, const String& misspelledWord) @@ -140,7 +140,7 @@ void WebTextCheckerClient::updateSpellingUIWithMisspelledWord(uint64_t tag, cons if (!m_client.updateSpellingUIWithMisspelledWord) return; - m_client.updateSpellingUIWithMisspelledWord(tag, toAPI(misspelledWord.impl()), m_client.clientInfo); + m_client.updateSpellingUIWithMisspelledWord(tag, toAPI(misspelledWord.impl()), m_client.base.clientInfo); } void WebTextCheckerClient::updateSpellingUIWithGrammarString(uint64_t tag, const String& badGrammarPhrase, const WebCore::GrammarDetail& grammarDetail) @@ -148,7 +148,7 @@ void WebTextCheckerClient::updateSpellingUIWithGrammarString(uint64_t tag, const if (!m_client.updateSpellingUIWithGrammarString) return; - m_client.updateSpellingUIWithGrammarString(tag, toAPI(badGrammarPhrase.impl()), toAPI(grammarDetail), m_client.clientInfo); + m_client.updateSpellingUIWithGrammarString(tag, toAPI(badGrammarPhrase.impl()), toAPI(grammarDetail), m_client.base.clientInfo); } void WebTextCheckerClient::guessesForWord(uint64_t tag, const String& word, Vector<String>& guesses) @@ -156,10 +156,10 @@ void WebTextCheckerClient::guessesForWord(uint64_t tag, const String& word, Vect if (!m_client.guessesForWord) return; - RefPtr<ImmutableArray> wkGuesses = adoptRef(toImpl(m_client.guessesForWord(tag, toAPI(word.impl()), m_client.clientInfo))); + RefPtr<API::Array> wkGuesses = adoptRef(toImpl(m_client.guessesForWord(tag, toAPI(word.impl()), m_client.base.clientInfo))); size_t numGuesses = wkGuesses->size(); for (size_t i = 0; i < numGuesses; ++i) - guesses.append(wkGuesses->at<WebString>(i)->string()); + guesses.append(wkGuesses->at<API::String>(i)->string()); } void WebTextCheckerClient::learnWord(uint64_t tag, const String& word) @@ -167,7 +167,7 @@ void WebTextCheckerClient::learnWord(uint64_t tag, const String& word) if (!m_client.learnWord) return; - m_client.learnWord(tag, toAPI(word.impl()), m_client.clientInfo); + m_client.learnWord(tag, toAPI(word.impl()), m_client.base.clientInfo); } void WebTextCheckerClient::ignoreWord(uint64_t tag, const String& word) @@ -175,7 +175,7 @@ void WebTextCheckerClient::ignoreWord(uint64_t tag, const String& word) if (!m_client.ignoreWord) return; - m_client.ignoreWord(tag, toAPI(word.impl()), m_client.clientInfo); + m_client.ignoreWord(tag, toAPI(word.impl()), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebTextCheckerClient.h b/Source/WebKit2/UIProcess/WebTextCheckerClient.h index b65003d11..49275fffc 100644 --- a/Source/WebKit2/UIProcess/WebTextCheckerClient.h +++ b/Source/WebKit2/UIProcess/WebTextCheckerClient.h @@ -32,11 +32,17 @@ #include <wtf/Forward.h> #include <wtf/Vector.h> +namespace API { +template<> struct ClientTraits<WKTextCheckerClientBase> { + typedef std::tuple<WKTextCheckerClientV0> Versions; +}; +} + namespace WebKit { class WebPageProxy; -class WebTextCheckerClient : public APIClient<WKTextCheckerClient, kWKTextCheckerClientCurrentVersion> { +class WebTextCheckerClient : public API::Client<WKTextCheckerClientBase> { public: bool continuousSpellCheckingAllowed(); bool continuousSpellCheckingEnabled(); diff --git a/Source/WebKit2/UIProcess/WebUIClient.cpp b/Source/WebKit2/UIProcess/WebUIClient.cpp deleted file mode 100644 index bfa4d8e43..000000000 --- a/Source/WebKit2/UIProcess/WebUIClient.cpp +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebUIClient.h" - -#include "ImmutableDictionary.h" -#include "NativeWebKeyboardEvent.h" -#include "NativeWebWheelEvent.h" -#include "NotificationPermissionRequest.h" -#include "PluginInformation.h" -#include "WKAPICast.h" -#include "WebColorPickerResultListenerProxy.h" -#include "WebNumber.h" -#include "WebOpenPanelResultListenerProxy.h" -#include "WebPageProxy.h" -#include <WebCore/FloatRect.h> -#include <WebCore/IntSize.h> -#include <WebCore/WindowFeatures.h> -#include <string.h> -#include <wtf/text/WTFString.h> - -using namespace WebCore; - -namespace WebKit { - -PassRefPtr<WebPageProxy> WebUIClient::createNewPage(WebPageProxy* page, const ResourceRequest& resourceRequest, const WindowFeatures& windowFeatures, WebEvent::Modifiers modifiers, WebMouseEvent::Button button) -{ - if (!m_client.version && !m_client.createNewPage_deprecatedForUseWithV0) - return 0; - - if (m_client.version == kWKPageUIClientCurrentVersion && !m_client.createNewPage) - return 0; - - ImmutableDictionary::MapType map; - if (windowFeatures.xSet) - map.set("x", WebDouble::create(windowFeatures.x)); - if (windowFeatures.ySet) - map.set("y", WebDouble::create(windowFeatures.y)); - if (windowFeatures.widthSet) - map.set("width", WebDouble::create(windowFeatures.width)); - if (windowFeatures.heightSet) - map.set("height", WebDouble::create(windowFeatures.height)); - map.set("menuBarVisible", WebBoolean::create(windowFeatures.menuBarVisible)); - map.set("statusBarVisible", WebBoolean::create(windowFeatures.statusBarVisible)); - map.set("toolBarVisible", WebBoolean::create(windowFeatures.toolBarVisible)); - map.set("locationBarVisible", WebBoolean::create(windowFeatures.locationBarVisible)); - map.set("scrollbarsVisible", WebBoolean::create(windowFeatures.scrollbarsVisible)); - map.set("resizable", WebBoolean::create(windowFeatures.resizable)); - map.set("fullscreen", WebBoolean::create(windowFeatures.fullscreen)); - map.set("dialog", WebBoolean::create(windowFeatures.dialog)); - RefPtr<ImmutableDictionary> featuresMap = ImmutableDictionary::adopt(map); - - if (!m_client.version) - return adoptRef(toImpl(m_client.createNewPage_deprecatedForUseWithV0(toAPI(page), toAPI(featuresMap.get()), toAPI(modifiers), toAPI(button), m_client.clientInfo))); - - RefPtr<WebURLRequest> request = WebURLRequest::create(resourceRequest); - return adoptRef(toImpl(m_client.createNewPage(toAPI(page), toAPI(request.get()), toAPI(featuresMap.get()), toAPI(modifiers), toAPI(button), m_client.clientInfo))); -} - -void WebUIClient::showPage(WebPageProxy* page) -{ - if (!m_client.showPage) - return; - - m_client.showPage(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::close(WebPageProxy* page) -{ - if (!m_client.close) - return; - - m_client.close(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::takeFocus(WebPageProxy* page, WKFocusDirection direction) -{ - if (!m_client.takeFocus) - return; - - m_client.takeFocus(toAPI(page), direction, m_client.clientInfo); -} - -void WebUIClient::focus(WebPageProxy* page) -{ - if (!m_client.focus) - return; - - m_client.focus(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::unfocus(WebPageProxy* page) -{ - if (!m_client.unfocus) - return; - - m_client.unfocus(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::runJavaScriptAlert(WebPageProxy* page, const String& message, WebFrameProxy* frame) -{ - if (!m_client.runJavaScriptAlert) - return; - - m_client.runJavaScriptAlert(toAPI(page), toAPI(message.impl()), toAPI(frame), m_client.clientInfo); -} - -bool WebUIClient::runJavaScriptConfirm(WebPageProxy* page, const String& message, WebFrameProxy* frame) -{ - if (!m_client.runJavaScriptConfirm) - return false; - - return m_client.runJavaScriptConfirm(toAPI(page), toAPI(message.impl()), toAPI(frame), m_client.clientInfo); -} - -String WebUIClient::runJavaScriptPrompt(WebPageProxy* page, const String& message, const String& defaultValue, WebFrameProxy* frame) -{ - if (!m_client.runJavaScriptPrompt) - return String(); - - WebString* string = toImpl(m_client.runJavaScriptPrompt(toAPI(page), toAPI(message.impl()), toAPI(defaultValue.impl()), toAPI(frame), m_client.clientInfo)); - if (!string) - return String(); - - String result = string->string(); - string->deref(); - - return result; -} - -void WebUIClient::setStatusText(WebPageProxy* page, const String& text) -{ - if (!m_client.setStatusText) - return; - - m_client.setStatusText(toAPI(page), toAPI(text.impl()), m_client.clientInfo); -} - -void WebUIClient::mouseDidMoveOverElement(WebPageProxy* page, const WebHitTestResult::Data& data, WebEvent::Modifiers modifiers, APIObject* userData) -{ - if (!m_client.mouseDidMoveOverElement && !m_client.mouseDidMoveOverElement_deprecatedForUseWithV0) - return; - - if (m_client.version == kWKPageUIClientCurrentVersion && !m_client.mouseDidMoveOverElement) - return; - - if (!m_client.version) { - m_client.mouseDidMoveOverElement_deprecatedForUseWithV0(toAPI(page), toAPI(modifiers), toAPI(userData), m_client.clientInfo); - return; - } - - RefPtr<WebHitTestResult> webHitTestResult = WebHitTestResult::create(data); - m_client.mouseDidMoveOverElement(toAPI(page), toAPI(webHitTestResult.get()), toAPI(modifiers), toAPI(userData), m_client.clientInfo); -} - -void WebUIClient::unavailablePluginButtonClicked(WebPageProxy* page, WKPluginUnavailabilityReason pluginUnavailabilityReason, ImmutableDictionary* pluginInformation) -{ - if (pluginUnavailabilityReason == kWKPluginUnavailabilityReasonPluginMissing) { - if (m_client.missingPluginButtonClicked_deprecatedForUseWithV0) - m_client.missingPluginButtonClicked_deprecatedForUseWithV0( - toAPI(page), - toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), - toAPI(pluginInformation->get<WebString>(pluginInformationPluginURLKey())), - toAPI(pluginInformation->get<WebString>(pluginInformationPluginspageAttributeURLKey())), - m_client.clientInfo); - } - - if (m_client.unavailablePluginButtonClicked_deprecatedForUseWithV1) - m_client.unavailablePluginButtonClicked_deprecatedForUseWithV1( - toAPI(page), - pluginUnavailabilityReason, - toAPI(pluginInformation->get<WebString>(pluginInformationMIMETypeKey())), - toAPI(pluginInformation->get<WebString>(pluginInformationPluginURLKey())), - toAPI(pluginInformation->get<WebString>(pluginInformationPluginspageAttributeURLKey())), - m_client.clientInfo); - - if (m_client.unavailablePluginButtonClicked) - m_client.unavailablePluginButtonClicked( - toAPI(page), - pluginUnavailabilityReason, - toAPI(pluginInformation), - m_client.clientInfo); -} - -bool WebUIClient::implementsDidNotHandleKeyEvent() const -{ - return m_client.didNotHandleKeyEvent; -} - -void WebUIClient::didNotHandleKeyEvent(WebPageProxy* page, const NativeWebKeyboardEvent& event) -{ - if (!m_client.didNotHandleKeyEvent) - return; - m_client.didNotHandleKeyEvent(toAPI(page), event.nativeEvent(), m_client.clientInfo); -} - -bool WebUIClient::implementsDidNotHandleWheelEvent() const -{ - return m_client.didNotHandleWheelEvent; -} - -void WebUIClient::didNotHandleWheelEvent(WebPageProxy* page, const NativeWebWheelEvent& event) -{ - if (!m_client.didNotHandleWheelEvent) - return; - m_client.didNotHandleWheelEvent(toAPI(page), event.nativeEvent(), m_client.clientInfo); -} - -bool WebUIClient::toolbarsAreVisible(WebPageProxy* page) -{ - if (!m_client.toolbarsAreVisible) - return true; - return m_client.toolbarsAreVisible(toAPI(page), m_client.clientInfo); - -} -void WebUIClient::setToolbarsAreVisible(WebPageProxy* page, bool visible) -{ - if (!m_client.setToolbarsAreVisible) - return; - m_client.setToolbarsAreVisible(toAPI(page), visible, m_client.clientInfo); -} - -bool WebUIClient::menuBarIsVisible(WebPageProxy* page) -{ - if (!m_client.menuBarIsVisible) - return true; - return m_client.menuBarIsVisible(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::setMenuBarIsVisible(WebPageProxy* page, bool visible) -{ - if (!m_client.setMenuBarIsVisible) - return; - m_client.setMenuBarIsVisible(toAPI(page), visible, m_client.clientInfo); -} - -bool WebUIClient::statusBarIsVisible(WebPageProxy* page) -{ - if (!m_client.statusBarIsVisible) - return true; - return m_client.statusBarIsVisible(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::setStatusBarIsVisible(WebPageProxy* page, bool visible) -{ - if (!m_client.setStatusBarIsVisible) - return; - m_client.setStatusBarIsVisible(toAPI(page), visible, m_client.clientInfo); -} - -bool WebUIClient::isResizable(WebPageProxy* page) -{ - if (!m_client.isResizable) - return true; - return m_client.isResizable(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::setIsResizable(WebPageProxy* page, bool resizable) -{ - if (!m_client.setIsResizable) - return; - m_client.setIsResizable(toAPI(page), resizable, m_client.clientInfo); -} - -void WebUIClient::setWindowFrame(WebPageProxy* page, const FloatRect& frame) -{ - if (!m_client.setWindowFrame) - return; - - m_client.setWindowFrame(toAPI(page), toAPI(frame), m_client.clientInfo); -} - -FloatRect WebUIClient::windowFrame(WebPageProxy* page) -{ - if (!m_client.getWindowFrame) - return FloatRect(); - - return toFloatRect(m_client.getWindowFrame(toAPI(page), m_client.clientInfo)); -} - -bool WebUIClient::canRunBeforeUnloadConfirmPanel() const -{ - return m_client.runBeforeUnloadConfirmPanel; -} - -bool WebUIClient::runBeforeUnloadConfirmPanel(WebPageProxy* page, const String& message, WebFrameProxy* frame) -{ - if (!m_client.runBeforeUnloadConfirmPanel) - return true; - - return m_client.runBeforeUnloadConfirmPanel(toAPI(page), toAPI(message.impl()), toAPI(frame), m_client.clientInfo); -} - -void WebUIClient::didDraw(WebPageProxy* page) -{ - if (!m_client.didDraw) - return; - - m_client.didDraw(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::pageDidScroll(WebPageProxy* page) -{ - if (!m_client.pageDidScroll) - return; - - m_client.pageDidScroll(toAPI(page), m_client.clientInfo); -} - -unsigned long long WebUIClient::exceededDatabaseQuota(WebPageProxy* page, WebFrameProxy* frame, WebSecurityOrigin* origin, const String& databaseName, const String& databaseDisplayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage) -{ - if (!m_client.exceededDatabaseQuota) - return currentQuota; - - return m_client.exceededDatabaseQuota(toAPI(page), toAPI(frame), toAPI(origin), toAPI(databaseName.impl()), toAPI(databaseDisplayName.impl()), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage, m_client.clientInfo); -} - -bool WebUIClient::runOpenPanel(WebPageProxy* page, WebFrameProxy* frame, WebOpenPanelParameters* parameters, WebOpenPanelResultListenerProxy* listener) -{ - if (!m_client.runOpenPanel) - return false; - - m_client.runOpenPanel(toAPI(page), toAPI(frame), toAPI(parameters), toAPI(listener), m_client.clientInfo); - return true; -} - -bool WebUIClient::decidePolicyForGeolocationPermissionRequest(WebPageProxy* page, WebFrameProxy* frame, WebSecurityOrigin* origin, GeolocationPermissionRequestProxy* permissionRequest) -{ - if (!m_client.decidePolicyForGeolocationPermissionRequest) - return false; - - m_client.decidePolicyForGeolocationPermissionRequest(toAPI(page), toAPI(frame), toAPI(origin), toAPI(permissionRequest), m_client.clientInfo); - return true; -} - -bool WebUIClient::decidePolicyForNotificationPermissionRequest(WebPageProxy* page, WebSecurityOrigin* origin, NotificationPermissionRequest* permissionRequest) -{ - if (!m_client.decidePolicyForNotificationPermissionRequest) - return false; - - m_client.decidePolicyForNotificationPermissionRequest(toAPI(page), toAPI(origin), toAPI(permissionRequest), m_client.clientInfo); - return true; -} - -float WebUIClient::headerHeight(WebPageProxy* page, WebFrameProxy* frame) -{ - if (!m_client.headerHeight) - return 0; - - return m_client.headerHeight(toAPI(page), toAPI(frame), m_client.clientInfo); -} - -float WebUIClient::footerHeight(WebPageProxy* page, WebFrameProxy* frame) -{ - if (!m_client.footerHeight) - return 0; - - return m_client.footerHeight(toAPI(page), toAPI(frame), m_client.clientInfo); -} - -void WebUIClient::drawHeader(WebPageProxy* page, WebFrameProxy* frame, const WebCore::FloatRect& rect) -{ - if (!m_client.drawHeader) - return; - - m_client.drawHeader(toAPI(page), toAPI(frame), toAPI(rect), m_client.clientInfo); -} - -void WebUIClient::drawFooter(WebPageProxy* page, WebFrameProxy* frame, const WebCore::FloatRect& rect) -{ - if (!m_client.drawFooter) - return; - - m_client.drawFooter(toAPI(page), toAPI(frame), toAPI(rect), m_client.clientInfo); -} - -void WebUIClient::printFrame(WebPageProxy* page, WebFrameProxy* frame) -{ - if (!m_client.printFrame) - return; - - m_client.printFrame(toAPI(page), toAPI(frame), m_client.clientInfo); -} - -bool WebUIClient::canRunModal() const -{ - return m_client.runModal; -} - -void WebUIClient::runModal(WebPageProxy* page) -{ - if (!m_client.runModal) - return; - - m_client.runModal(toAPI(page), m_client.clientInfo); -} - -void WebUIClient::saveDataToFileInDownloadsFolder(WebPageProxy* page, const String& suggestedFilename, const String& mimeType, const String& originatingURLString, WebData* data) -{ - if (!m_client.saveDataToFileInDownloadsFolder) - return; - - m_client.saveDataToFileInDownloadsFolder(toAPI(page), toAPI(suggestedFilename.impl()), toAPI(mimeType.impl()), toURLRef(originatingURLString.impl()), toAPI(data), m_client.clientInfo); -} - -bool WebUIClient::shouldInterruptJavaScript(WebPageProxy* page) -{ - if (!m_client.shouldInterruptJavaScript) - return false; - - return m_client.shouldInterruptJavaScript(toAPI(page), m_client.clientInfo); -} - -#if ENABLE(INPUT_TYPE_COLOR) -bool WebUIClient::showColorPicker(WebPageProxy* page, const String& initialColor, WebColorPickerResultListenerProxy* listener) -{ - if (!m_client.showColorPicker) - return false; - - m_client.showColorPicker(toAPI(page), toAPI(initialColor.impl()), toAPI(listener), m_client.clientInfo); - return true; -} - -bool WebUIClient::hideColorPicker(WebPageProxy* page) -{ - if (!m_client.hideColorPicker) - return false; - - m_client.hideColorPicker(toAPI(page), m_client.clientInfo); - return true; -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebUIClient.h b/Source/WebKit2/UIProcess/WebUIClient.h deleted file mode 100644 index 9813f5754..000000000 --- a/Source/WebKit2/UIProcess/WebUIClient.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebUIClient_h -#define WebUIClient_h - -#include "APIClient.h" -#include "WKPage.h" -#include "WebEvent.h" -#include "WebHitTestResult.h" -#include "WebOpenPanelParameters.h" -#include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> - -namespace WebCore { - class FloatRect; - class IntSize; - class ResourceRequest; - struct WindowFeatures; -} - -namespace WebKit { - -class APIObject; -class GeolocationPermissionRequestProxy; -class ImmutableDictionary; -class NativeWebKeyboardEvent; -class NativeWebWheelEvent; -class NotificationPermissionRequest; -class WebColorPickerResultListenerProxy; -class WebData; -class WebFrameProxy; -class WebPageProxy; -class WebSecurityOrigin; -class WebOpenPanelResultListenerProxy; - -class WebUIClient : public APIClient<WKPageUIClient, kWKPageUIClientCurrentVersion> { -public: - PassRefPtr<WebPageProxy> createNewPage(WebPageProxy*, const WebCore::ResourceRequest&, const WebCore::WindowFeatures&, WebEvent::Modifiers, WebMouseEvent::Button); - void showPage(WebPageProxy*); - void close(WebPageProxy*); - - void takeFocus(WebPageProxy*, WKFocusDirection); - void focus(WebPageProxy*); - void unfocus(WebPageProxy*); - - void runJavaScriptAlert(WebPageProxy*, const String&, WebFrameProxy*); - bool runJavaScriptConfirm(WebPageProxy*, const String&, WebFrameProxy*); - String runJavaScriptPrompt(WebPageProxy*, const String&, const String&, WebFrameProxy*); - - void setStatusText(WebPageProxy*, const String&); - void mouseDidMoveOverElement(WebPageProxy*, const WebHitTestResult::Data&, WebEvent::Modifiers, APIObject*); - void unavailablePluginButtonClicked(WebPageProxy*, WKPluginUnavailabilityReason, ImmutableDictionary*); - - bool implementsDidNotHandleKeyEvent() const; - void didNotHandleKeyEvent(WebPageProxy*, const NativeWebKeyboardEvent&); - - bool implementsDidNotHandleWheelEvent() const; - void didNotHandleWheelEvent(WebPageProxy*, const NativeWebWheelEvent&); - - bool toolbarsAreVisible(WebPageProxy*); - void setToolbarsAreVisible(WebPageProxy*, bool); - bool menuBarIsVisible(WebPageProxy*); - void setMenuBarIsVisible(WebPageProxy*, bool); - bool statusBarIsVisible(WebPageProxy*); - void setStatusBarIsVisible(WebPageProxy*, bool); - bool isResizable(WebPageProxy*); - void setIsResizable(WebPageProxy*, bool); - - void setWindowFrame(WebPageProxy*, const WebCore::FloatRect&); - WebCore::FloatRect windowFrame(WebPageProxy*); - - bool canRunBeforeUnloadConfirmPanel() const; - bool runBeforeUnloadConfirmPanel(WebPageProxy*, const String&, WebFrameProxy*); - - void didDraw(WebPageProxy*); - void pageDidScroll(WebPageProxy*); - - unsigned long long exceededDatabaseQuota(WebPageProxy*, WebFrameProxy*, WebSecurityOrigin*, const String& databaseName, const String& databaseDisplayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage); - - bool runOpenPanel(WebPageProxy*, WebFrameProxy*, WebOpenPanelParameters*, WebOpenPanelResultListenerProxy*); - bool decidePolicyForGeolocationPermissionRequest(WebPageProxy*, WebFrameProxy*, WebSecurityOrigin*, GeolocationPermissionRequestProxy*); - bool decidePolicyForNotificationPermissionRequest(WebPageProxy*, WebSecurityOrigin*, NotificationPermissionRequest*); - - // Printing. - float headerHeight(WebPageProxy*, WebFrameProxy*); - float footerHeight(WebPageProxy*, WebFrameProxy*); - void drawHeader(WebPageProxy*, WebFrameProxy*, const WebCore::FloatRect&); - void drawFooter(WebPageProxy*, WebFrameProxy*, const WebCore::FloatRect&); - void printFrame(WebPageProxy*, WebFrameProxy*); - - bool canRunModal() const; - void runModal(WebPageProxy*); - - void saveDataToFileInDownloadsFolder(WebPageProxy*, const String& suggestedFilename, const String& mimeType, const String& originatingURLString, WebData*); - - bool shouldInterruptJavaScript(WebPageProxy*); - -#if ENABLE(INPUT_TYPE_COLOR) - bool showColorPicker(WebPageProxy*, const String&, WebColorPickerResultListenerProxy*); - bool hideColorPicker(WebPageProxy*); -#endif -}; - -} // namespace WebKit - -#endif // WebUIClient_h diff --git a/Source/WebKit2/UIProcess/WebVibrationProvider.cpp b/Source/WebKit2/UIProcess/WebVibrationProvider.cpp index a12f5973b..72f31b2b5 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProvider.cpp +++ b/Source/WebKit2/UIProcess/WebVibrationProvider.cpp @@ -38,7 +38,7 @@ void WebVibrationProvider::vibrate(WebVibrationProxy* vibration, uint32_t vibrat if (!m_client.vibrate) return; - m_client.vibrate(toAPI(vibration), vibrationTime, m_client.clientInfo); + m_client.vibrate(toAPI(vibration), vibrationTime, m_client.base.clientInfo); } void WebVibrationProvider::cancelVibration(WebVibrationProxy* vibration) @@ -46,7 +46,7 @@ void WebVibrationProvider::cancelVibration(WebVibrationProxy* vibration) if (!m_client.cancelVibration) return; - m_client.cancelVibration(toAPI(vibration), m_client.clientInfo); + m_client.cancelVibration(toAPI(vibration), m_client.base.clientInfo); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/WebVibrationProvider.h b/Source/WebKit2/UIProcess/WebVibrationProvider.h index 36159de83..94ea133cf 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProvider.h +++ b/Source/WebKit2/UIProcess/WebVibrationProvider.h @@ -32,11 +32,17 @@ #include "WKVibration.h" #include <wtf/Forward.h> +namespace API { +template<> struct ClientTraits<WKVibrationProviderBase> { + typedef std::tuple<WKVibrationProviderV0> Versions; +}; +} + namespace WebKit { class WebVibrationProxy; -class WebVibrationProvider : public APIClient<WKVibrationProvider, kWKVibrationProviderCurrentVersion> { +class WebVibrationProvider : public API::Client<WKVibrationProviderBase> { public: void vibrate(WebVibrationProxy*, uint32_t vibrationTime); void cancelVibration(WebVibrationProxy*); diff --git a/Source/WebKit2/UIProcess/WebVibrationProxy.cpp b/Source/WebKit2/UIProcess/WebVibrationProxy.cpp index 90da393da..48d290ce3 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProxy.cpp +++ b/Source/WebKit2/UIProcess/WebVibrationProxy.cpp @@ -28,27 +28,27 @@ #if ENABLE(VIBRATION) -#include "WebContext.h" #include "WebPageProxy.h" +#include "WebProcessPool.h" #include "WebProcessProxy.h" #include "WebVibrationProxyMessages.h" namespace WebKit { -PassRefPtr<WebVibrationProxy> WebVibrationProxy::create(WebPageProxy* page) +Ref<WebVibrationProxy> WebVibrationProxy::create(WebPageProxy* page) { - return adoptRef(new WebVibrationProxy(page)); + return adoptRef(*new WebVibrationProxy(page)); } WebVibrationProxy::WebVibrationProxy(WebPageProxy* page) : m_page(page) { - m_page->process()->context()->addMessageReceiver(Messages::WebVibrationProxy::messageReceiverName(), m_page->pageID(), this); + m_page->process().processPool().addMessageReceiver(Messages::WebVibrationProxy::messageReceiverName(), m_page->pageID(), *this); } WebVibrationProxy::~WebVibrationProxy() { - m_page->process()->context()->removeMessageReceiver(Messages::WebVibrationProxy::messageReceiverName(), m_page->pageID()); + m_page->process().processPool().removeMessageReceiver(Messages::WebVibrationProxy::messageReceiverName(), m_page->pageID()); } void WebVibrationProxy::invalidate() @@ -57,7 +57,7 @@ void WebVibrationProxy::invalidate() m_provider.initialize(0); } -void WebVibrationProxy::initializeProvider(const WKVibrationProvider* provider) +void WebVibrationProxy::initializeProvider(const WKVibrationProviderBase* provider) { m_provider.initialize(provider); } diff --git a/Source/WebKit2/UIProcess/WebVibrationProxy.h b/Source/WebKit2/UIProcess/WebVibrationProxy.h index 1f9c891e4..7385660d6 100644 --- a/Source/WebKit2/UIProcess/WebVibrationProxy.h +++ b/Source/WebKit2/UIProcess/WebVibrationProxy.h @@ -37,20 +37,20 @@ namespace WebKit { class WebPageProxy; -class WebVibrationProxy : public TypedAPIObject<APIObject::TypeVibration>, private CoreIPC::MessageReceiver { +class WebVibrationProxy : public API::ObjectImpl<API::Object::Type::Vibration>, private IPC::MessageReceiver { public: - static PassRefPtr<WebVibrationProxy> create(WebPageProxy*); + static Ref<WebVibrationProxy> create(WebPageProxy*); virtual ~WebVibrationProxy(); void invalidate(); - void initializeProvider(const WKVibrationProvider*); + void initializeProvider(const WKVibrationProviderBase*); private: explicit WebVibrationProxy(WebPageProxy*); - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; + // IPC::MessageReceiver + virtual void didReceiveMessage(IPC::Connection&, IPC::MessageDecoder&) override; void vibrate(uint32_t vibrationTime); void cancelVibration(); diff --git a/Source/WebKit2/UIProcess/WebViewportAttributes.h b/Source/WebKit2/UIProcess/WebViewportAttributes.h index 9fb3f59eb..a31065fe4 100644 --- a/Source/WebKit2/UIProcess/WebViewportAttributes.h +++ b/Source/WebKit2/UIProcess/WebViewportAttributes.h @@ -32,11 +32,11 @@ namespace WebKit { -class WebViewportAttributes : public TypedAPIObject<APIObject::TypeViewportAttributes> { +class WebViewportAttributes : public API::ObjectImpl<API::Object::Type::ViewportAttributes> { public: - static PassRefPtr<WebViewportAttributes> create(const WebCore::ViewportAttributes& attributes) + static Ref<WebViewportAttributes> create(const WebCore::ViewportAttributes& attributes) { - return adoptRef(new WebViewportAttributes(attributes)); + return adoptRef(*new WebViewportAttributes(attributes)); } virtual ~WebViewportAttributes(); diff --git a/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataRecord.cpp b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataRecord.cpp new file mode 100644 index 000000000..1aa2c0eb7 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataRecord.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2015 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 "WebsiteDataRecord.h" + +#include <WebCore/LocalizedStrings.h> +#include <WebCore/PublicSuffix.h> +#include <WebCore/SecurityOrigin.h> + +#if PLATFORM(COCOA) +#import <WebCore/CFNetworkSPI.h> +#endif + +static String displayNameForLocalFiles() +{ + return WEB_UI_STRING("Local documents on your computer", "'Website' name displayed when local documents have stored local data"); +} + +namespace WebKit { + +String WebsiteDataRecord::displayNameForCookieHostName(const String& hostName) +{ +#if PLATFORM(COCOA) + if (hostName == String(kCFHTTPCookieLocalFileDomain)) + return displayNameForLocalFiles(); +#endif + +#if ENABLE(PUBLIC_SUFFIX_LIST) + return WebCore::topPrivatelyControlledDomain(hostName.startsWith('.') ? hostName.substring(1) : hostName); +#endif + + return String(); +} + +#if ENABLE(NETSCAPE_PLUGIN_API) +String WebsiteDataRecord::displayNameForPluginDataHostName(const String& hostName) +{ +#if ENABLE(PUBLIC_SUFFIX_LIST) + return WebCore::topPrivatelyControlledDomain(hostName); +#endif + + return String(); +} +#endif + +String WebsiteDataRecord::displayNameForOrigin(const WebCore::SecurityOrigin& securityOrigin) +{ + const auto& protocol = securityOrigin.protocol(); + + if (protocol == "file") + return displayNameForLocalFiles(); + +#if ENABLE(PUBLIC_SUFFIX_LIST) + if (protocol == "http" || protocol == "https") + return WebCore::topPrivatelyControlledDomain(securityOrigin.host()); +#endif + + return String(); +} + +void WebsiteDataRecord::add(WebsiteDataTypes type, RefPtr<WebCore::SecurityOrigin>&& origin) +{ + types |= type; + + origins.add(WTFMove(origin)); +} + +void WebsiteDataRecord::addCookieHostName(const String& hostName) +{ + types |= WebsiteDataTypeCookies; + + cookieHostNames.add(hostName); +} + +#if ENABLE(NETSCAPE_PLUGIN_API) +void WebsiteDataRecord::addPluginDataHostName(const String& hostName) +{ + types |= WebsiteDataTypePlugInData; + + pluginDataHostNames.add(hostName); +} +#endif + +} diff --git a/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataRecord.h b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataRecord.h new file mode 100644 index 000000000..58b3f9184 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataRecord.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2015 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 WebsiteDataRecord_h +#define WebsiteDataRecord_h + +#include "WebsiteDataTypes.h" +#include <WebCore/SecurityOriginHash.h> +#include <wtf/HashSet.h> +#include <wtf/text/StringHash.h> +#include <wtf/text/WTFString.h> + +namespace WebCore { +class SecurityOrigin; +} + +namespace WebKit { + +struct WebsiteDataRecord { + static String displayNameForCookieHostName(const String& hostName); +#if ENABLE(NETSCAPE_PLUGIN_API) + static String displayNameForPluginDataHostName(const String& hostName); +#endif + static String displayNameForOrigin(const WebCore::SecurityOrigin&); + + void add(WebsiteDataTypes, RefPtr<WebCore::SecurityOrigin>&&); + void addCookieHostName(const String& hostName); +#if ENABLE(NETSCAPE_PLUGIN_API) + void addPluginDataHostName(const String& hostName); +#endif + + String displayName; + unsigned types { 0 }; + HashSet<RefPtr<WebCore::SecurityOrigin>> origins; + HashSet<String> cookieHostNames; +#if ENABLE(NETSCAPE_PLUGIN_API) + HashSet<String> pluginDataHostNames; +#endif +}; + +} + +#endif // WebsiteDataRecord_h diff --git a/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataStore.cpp b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataStore.cpp new file mode 100644 index 000000000..1191e7af3 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataStore.cpp @@ -0,0 +1,1080 @@ +/* + * Copyright (C) 2014 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 "WebsiteDataStore.h" + +#include "APIProcessPoolConfiguration.h" +#include "APIWebsiteDataRecord.h" +#include "NetworkProcessMessages.h" +#include "StorageManager.h" +#include "WebProcessPool.h" +#include "WebsiteData.h" +#include <WebCore/ApplicationCacheStorage.h> +#include <WebCore/DatabaseTracker.h> +#include <WebCore/OriginLock.h> +#include <WebCore/SecurityOrigin.h> +#include <wtf/RunLoop.h> + +#if ENABLE(NETSCAPE_PLUGIN_API) +#include "PluginProcessManager.h" +#endif + +namespace WebKit { + +static WebCore::SessionID generateNonPersistentSessionID() +{ + // FIXME: We count backwards here to not conflict with API::Session. + static uint64_t sessionID = std::numeric_limits<uint64_t>::max(); + + return WebCore::SessionID(--sessionID); +} + +static uint64_t generateIdentifier() +{ + static uint64_t identifier; + + return ++identifier; +} + +Ref<WebsiteDataStore> WebsiteDataStore::createNonPersistent() +{ + return adoptRef(*new WebsiteDataStore(generateNonPersistentSessionID())); +} + +Ref<WebsiteDataStore> WebsiteDataStore::create(Configuration configuration) +{ + return adoptRef(*new WebsiteDataStore(WTFMove(configuration))); +} + +WebsiteDataStore::WebsiteDataStore(Configuration configuration) + : m_identifier(generateIdentifier()) + , m_sessionID(WebCore::SessionID::defaultSessionID()) + , m_networkCacheDirectory(WTFMove(configuration.networkCacheDirectory)) + , m_applicationCacheDirectory(WTFMove(configuration.applicationCacheDirectory)) + , m_webSQLDatabaseDirectory(WTFMove(configuration.webSQLDatabaseDirectory)) + , m_mediaKeysStorageDirectory(WTFMove(configuration.mediaKeysStorageDirectory)) + , m_storageManager(StorageManager::create(WTFMove(configuration.localStorageDirectory))) + , m_queue(WorkQueue::create("com.apple.WebKit.WebsiteDataStore")) +{ + platformInitialize(); +} + +WebsiteDataStore::WebsiteDataStore(WebCore::SessionID sessionID) + : m_identifier(generateIdentifier()) + , m_sessionID(sessionID) + , m_queue(WorkQueue::create("com.apple.WebKit.WebsiteDataStore")) +{ + platformInitialize(); +} + +WebsiteDataStore::~WebsiteDataStore() +{ + platformDestroy(); + + if (m_sessionID.isEphemeral()) { + for (auto& processPool : WebProcessPool::allProcessPools()) + processPool->sendToNetworkingProcess(Messages::NetworkProcess::DestroyPrivateBrowsingSession(m_sessionID)); + } +} + +void WebsiteDataStore::cloneSessionData(WebPageProxy& sourcePage, WebPageProxy& newPage) +{ + auto& sourceDataStore = sourcePage.websiteDataStore(); + auto& newDataStore = newPage.websiteDataStore(); + + // FIXME: Handle this. + if (&sourceDataStore != &newDataStore) + return; + + if (!sourceDataStore.m_storageManager) + return; + + sourceDataStore.m_storageManager->cloneSessionStorageNamespace(sourcePage.pageID(), newPage.pageID()); +} + +enum class ProcessAccessType { + None, + OnlyIfLaunched, + Launch, +}; + +static ProcessAccessType computeNetworkProcessAccessTypeForDataFetch(WebsiteDataTypes dataTypes, bool isNonPersistentStore) +{ + ProcessAccessType processAccessType = ProcessAccessType::None; + + if (dataTypes & WebsiteDataTypeCookies) { + if (isNonPersistentStore) + processAccessType = std::max(processAccessType, ProcessAccessType::OnlyIfLaunched); + else + processAccessType = std::max(processAccessType, ProcessAccessType::Launch); + } + + if (dataTypes & WebsiteDataTypeDiskCache && !isNonPersistentStore) + processAccessType = std::max(processAccessType, ProcessAccessType::Launch); + + return processAccessType; +} + +static ProcessAccessType computeWebProcessAccessTypeForDataFetch(WebsiteDataTypes dataTypes, bool isNonPersistentStore) +{ + UNUSED_PARAM(isNonPersistentStore); + + ProcessAccessType processAccessType = ProcessAccessType::None; + + if (dataTypes & WebsiteDataTypeMemoryCache) + return ProcessAccessType::OnlyIfLaunched; + + return processAccessType; +} + +void WebsiteDataStore::fetchData(WebsiteDataTypes dataTypes, std::function<void (Vector<WebsiteDataRecord>)> completionHandler) +{ + struct CallbackAggregator final : ThreadSafeRefCounted<CallbackAggregator> { + explicit CallbackAggregator(std::function<void (Vector<WebsiteDataRecord>)> completionHandler) + : completionHandler(WTFMove(completionHandler)) + { + } + + ~CallbackAggregator() + { + ASSERT(!pendingCallbacks); + } + + void addPendingCallback() + { + pendingCallbacks++; + } + + void removePendingCallback(WebsiteData websiteData) + { + ASSERT(pendingCallbacks); + --pendingCallbacks; + + for (auto& entry : websiteData.entries) { + auto displayName = WebsiteDataRecord::displayNameForOrigin(*entry.origin); + if (!displayName) + continue; + + auto& record = m_websiteDataRecords.add(displayName, WebsiteDataRecord { }).iterator->value; + if (!record.displayName) + record.displayName = WTFMove(displayName); + + record.add(entry.type, WTFMove(entry.origin)); + } + + for (auto& hostName : websiteData.hostNamesWithCookies) { + auto displayName = WebsiteDataRecord::displayNameForCookieHostName(hostName); + if (!displayName) + continue; + + auto& record = m_websiteDataRecords.add(displayName, WebsiteDataRecord { }).iterator->value; + if (!record.displayName) + record.displayName = WTFMove(displayName); + + record.addCookieHostName(hostName); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + for (auto& hostName : websiteData.hostNamesWithPluginData) { + auto displayName = WebsiteDataRecord::displayNameForPluginDataHostName(hostName); + if (!displayName) + continue; + + auto& record = m_websiteDataRecords.add(displayName, WebsiteDataRecord { }).iterator->value; + if (!record.displayName) + record.displayName = WTFMove(displayName); + + record.addPluginDataHostName(hostName); + } +#endif + + callIfNeeded(); + } + + void callIfNeeded() + { + if (pendingCallbacks) + return; + + RefPtr<CallbackAggregator> callbackAggregator(this); + RunLoop::main().dispatch([callbackAggregator] { + + WTF::Vector<WebsiteDataRecord> records; + records.reserveInitialCapacity(callbackAggregator->m_websiteDataRecords.size()); + + for (auto& record : callbackAggregator->m_websiteDataRecords.values()) + records.uncheckedAppend(WTFMove(record)); + + callbackAggregator->completionHandler(WTFMove(records)); + }); + } + + unsigned pendingCallbacks = 0; + std::function<void (Vector<WebsiteDataRecord>)> completionHandler; + + HashMap<String, WebsiteDataRecord> m_websiteDataRecords; + }; + + RefPtr<CallbackAggregator> callbackAggregator = adoptRef(new CallbackAggregator(WTFMove(completionHandler))); + + auto networkProcessAccessType = computeNetworkProcessAccessTypeForDataFetch(dataTypes, !isPersistent()); + if (networkProcessAccessType != ProcessAccessType::None) { + for (auto& processPool : processPools()) { + switch (networkProcessAccessType) { + case ProcessAccessType::OnlyIfLaunched: + if (!processPool->networkProcess()) + continue; + break; + + case ProcessAccessType::Launch: + processPool->ensureNetworkProcess(); + break; + + case ProcessAccessType::None: + ASSERT_NOT_REACHED(); + } + + callbackAggregator->addPendingCallback(); + processPool->networkProcess()->fetchWebsiteData(m_sessionID, dataTypes, [callbackAggregator, processPool](WebsiteData websiteData) { + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + } + } + + auto webProcessAccessType = computeWebProcessAccessTypeForDataFetch(dataTypes, !isPersistent()); + if (webProcessAccessType != ProcessAccessType::None) { + for (auto& process : processes()) { + switch (webProcessAccessType) { + case ProcessAccessType::OnlyIfLaunched: + if (!process->canSendMessage()) + continue; + break; + + case ProcessAccessType::Launch: + // FIXME: Handle this. + ASSERT_NOT_REACHED(); + break; + + case ProcessAccessType::None: + ASSERT_NOT_REACHED(); + } + + callbackAggregator->addPendingCallback(); + process->fetchWebsiteData(m_sessionID, dataTypes, [callbackAggregator](WebsiteData websiteData) { + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + } + } + + if (dataTypes & WebsiteDataTypeSessionStorage && m_storageManager) { + callbackAggregator->addPendingCallback(); + + m_storageManager->getSessionStorageOrigins([callbackAggregator](HashSet<RefPtr<WebCore::SecurityOrigin>>&& origins) { + WebsiteData websiteData; + + while (!origins.isEmpty()) + websiteData.entries.append(WebsiteData::Entry { origins.takeAny(), WebsiteDataTypeSessionStorage }); + + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + } + + if (dataTypes & WebsiteDataTypeLocalStorage && m_storageManager) { + callbackAggregator->addPendingCallback(); + + m_storageManager->getLocalStorageOrigins([callbackAggregator](HashSet<RefPtr<WebCore::SecurityOrigin>>&& origins) { + WebsiteData websiteData; + + while (!origins.isEmpty()) + websiteData.entries.append(WebsiteData::Entry { origins.takeAny(), WebsiteDataTypeLocalStorage }); + + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + } + + if (dataTypes & WebsiteDataTypeOfflineWebApplicationCache && isPersistent()) { + StringCapture applicationCacheDirectory { m_applicationCacheDirectory }; + + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([applicationCacheDirectory, callbackAggregator] { + auto storage = WebCore::ApplicationCacheStorage::create(applicationCacheDirectory.string(), "ApplicationCache"); + + HashSet<RefPtr<WebCore::SecurityOrigin>> origins; + storage->getOriginsWithCache(origins); + + WTF::RunLoop::main().dispatch([callbackAggregator, origins]() mutable { + WebsiteData websiteData; + + for (auto& origin : origins) + websiteData.entries.append(WebsiteData::Entry { origin, WebsiteDataTypeOfflineWebApplicationCache }); + + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + }); + } + + if (dataTypes & WebsiteDataTypeWebSQLDatabases && isPersistent()) { + StringCapture webSQLDatabaseDirectory { m_webSQLDatabaseDirectory }; + + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([webSQLDatabaseDirectory, callbackAggregator] { + Vector<RefPtr<WebCore::SecurityOrigin>> origins; + WebCore::DatabaseTracker::trackerWithDatabasePath(webSQLDatabaseDirectory.string())->origins(origins); + + RunLoop::main().dispatch([callbackAggregator, origins]() mutable { + WebsiteData websiteData; + for (auto& origin : origins) + websiteData.entries.append(WebsiteData::Entry { WTFMove(origin), WebsiteDataTypeWebSQLDatabases }); + + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + }); + } + +#if ENABLE(DATABASE_PROCESS) + if (dataTypes & WebsiteDataTypeIndexedDBDatabases && isPersistent()) { + for (auto& processPool : processPools()) { + processPool->ensureDatabaseProcess(); + + callbackAggregator->addPendingCallback(); + processPool->databaseProcess()->fetchWebsiteData(m_sessionID, dataTypes, [callbackAggregator, processPool](WebsiteData websiteData) { + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + } + } +#endif + + if (dataTypes & WebsiteDataTypeMediaKeys && isPersistent()) { + StringCapture mediaKeysStorageDirectory { m_mediaKeysStorageDirectory }; + + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([mediaKeysStorageDirectory, callbackAggregator] { + auto origins = mediaKeyOrigins(mediaKeysStorageDirectory.string()); + + RunLoop::main().dispatch([callbackAggregator, origins]() mutable { + WebsiteData websiteData; + for (auto& origin : origins) + websiteData.entries.append(WebsiteData::Entry { WTFMove(origin), WebsiteDataTypeMediaKeys }); + + callbackAggregator->removePendingCallback(WTFMove(websiteData)); + }); + }); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + if (dataTypes & WebsiteDataTypePlugInData && isPersistent()) { + class State { + public: + static void fetchData(Ref<CallbackAggregator>&& callbackAggregator, Vector<PluginModuleInfo>&& plugins) + { + new State(WTFMove(callbackAggregator), WTFMove(plugins)); + } + + private: + State(Ref<CallbackAggregator>&& callbackAggregator, Vector<PluginModuleInfo>&& plugins) + : m_callbackAggregator(WTFMove(callbackAggregator)) + , m_plugins(WTFMove(plugins)) + { + m_callbackAggregator->addPendingCallback(); + + fetchWebsiteDataForNextPlugin(); + } + + ~State() + { + ASSERT(m_plugins.isEmpty()); + } + + void fetchWebsiteDataForNextPlugin() + { + if (m_plugins.isEmpty()) { + WebsiteData websiteData; + websiteData.hostNamesWithPluginData = WTFMove(m_hostNames); + + m_callbackAggregator->removePendingCallback(WTFMove(websiteData)); + + delete this; + return; + } + + auto plugin = m_plugins.takeLast(); + PluginProcessManager::singleton().fetchWebsiteData(plugin, [this](Vector<String> hostNames) { + for (auto& hostName : hostNames) + m_hostNames.add(WTFMove(hostName)); + fetchWebsiteDataForNextPlugin(); + }); + } + + Ref<CallbackAggregator> m_callbackAggregator; + Vector<PluginModuleInfo> m_plugins; + HashSet<String> m_hostNames; + }; + + State::fetchData(*callbackAggregator, plugins()); + } +#endif + + callbackAggregator->callIfNeeded(); +} + +static ProcessAccessType computeNetworkProcessAccessTypeForDataRemoval(WebsiteDataTypes dataTypes, bool isNonPersistentStore) +{ + ProcessAccessType processAccessType = ProcessAccessType::None; + + if (dataTypes & WebsiteDataTypeCookies) { + if (isNonPersistentStore) + processAccessType = std::max(processAccessType, ProcessAccessType::OnlyIfLaunched); + else + processAccessType = std::max(processAccessType, ProcessAccessType::Launch); + } + + if (dataTypes & WebsiteDataTypeDiskCache && !isNonPersistentStore) + processAccessType = std::max(processAccessType, ProcessAccessType::Launch); + + if (dataTypes & WebsiteDataTypeHSTSCache) + processAccessType = std::max(processAccessType, ProcessAccessType::Launch); + + return processAccessType; +} + +static ProcessAccessType computeWebProcessAccessTypeForDataRemoval(WebsiteDataTypes dataTypes, bool isNonPersistentStore) +{ + UNUSED_PARAM(isNonPersistentStore); + + ProcessAccessType processAccessType = ProcessAccessType::None; + + if (dataTypes & WebsiteDataTypeMemoryCache) + processAccessType = std::max(processAccessType, ProcessAccessType::OnlyIfLaunched); + + return processAccessType; +} + +void WebsiteDataStore::removeData(WebsiteDataTypes dataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler) +{ + struct CallbackAggregator : ThreadSafeRefCounted<CallbackAggregator> { + explicit CallbackAggregator (std::function<void ()> completionHandler) + : completionHandler(WTFMove(completionHandler)) + { + } + + void addPendingCallback() + { + pendingCallbacks++; + } + + void removePendingCallback() + { + ASSERT(pendingCallbacks); + --pendingCallbacks; + + callIfNeeded(); + } + + void callIfNeeded() + { + if (!pendingCallbacks) + RunLoop::main().dispatch(WTFMove(completionHandler)); + } + + unsigned pendingCallbacks = 0; + std::function<void ()> completionHandler; + }; + + RefPtr<CallbackAggregator> callbackAggregator = adoptRef(new CallbackAggregator(WTFMove(completionHandler))); + + auto networkProcessAccessType = computeNetworkProcessAccessTypeForDataRemoval(dataTypes, !isPersistent()); + if (networkProcessAccessType != ProcessAccessType::None) { + for (auto& processPool : processPools()) { + switch (networkProcessAccessType) { + case ProcessAccessType::OnlyIfLaunched: + if (!processPool->networkProcess()) + continue; + break; + + case ProcessAccessType::Launch: + processPool->ensureNetworkProcess(); + break; + + case ProcessAccessType::None: + ASSERT_NOT_REACHED(); + } + + callbackAggregator->addPendingCallback(); + processPool->networkProcess()->deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator, processPool] { + callbackAggregator->removePendingCallback(); + }); + } + } + + auto webProcessAccessType = computeWebProcessAccessTypeForDataRemoval(dataTypes, !isPersistent()); + if (webProcessAccessType != ProcessAccessType::None) { + for (auto& process : processes()) { + switch (webProcessAccessType) { + case ProcessAccessType::OnlyIfLaunched: + if (!process->canSendMessage()) + continue; + break; + + case ProcessAccessType::Launch: + // FIXME: Handle this. + ASSERT_NOT_REACHED(); + break; + + case ProcessAccessType::None: + ASSERT_NOT_REACHED(); + } + + callbackAggregator->addPendingCallback(); + process->deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + } + } + + if (dataTypes & WebsiteDataTypeSessionStorage && m_storageManager) { + callbackAggregator->addPendingCallback(); + + m_storageManager->deleteSessionStorageOrigins([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + } + + if (dataTypes & WebsiteDataTypeLocalStorage && m_storageManager) { + callbackAggregator->addPendingCallback(); + + m_storageManager->deleteLocalStorageOriginsModifiedSince(modifiedSince, [callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + } + + if (dataTypes & WebsiteDataTypeOfflineWebApplicationCache && isPersistent()) { + StringCapture applicationCacheDirectory { m_applicationCacheDirectory }; + + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([applicationCacheDirectory, callbackAggregator] { + auto storage = WebCore::ApplicationCacheStorage::create(applicationCacheDirectory.string(), "ApplicationCache"); + + storage->deleteAllCaches(); + + WTF::RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + + if (dataTypes & WebsiteDataTypeWebSQLDatabases && isPersistent()) { + StringCapture webSQLDatabaseDirectory { m_webSQLDatabaseDirectory }; + + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([webSQLDatabaseDirectory, callbackAggregator, modifiedSince] { + WebCore::DatabaseTracker::trackerWithDatabasePath(webSQLDatabaseDirectory.string())->deleteDatabasesModifiedSince(modifiedSince); + + RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + +#if ENABLE(DATABASE_PROCESS) + if (dataTypes & WebsiteDataTypeIndexedDBDatabases && isPersistent()) { + for (auto& processPool : processPools()) { + processPool->ensureDatabaseProcess(); + + callbackAggregator->addPendingCallback(); + processPool->databaseProcess()->deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator, processPool] { + callbackAggregator->removePendingCallback(); + }); + } + } +#endif + + if (dataTypes & WebsiteDataTypeMediaKeys && isPersistent()) { + StringCapture mediaKeysStorageDirectory { m_mediaKeysStorageDirectory }; + + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([mediaKeysStorageDirectory, callbackAggregator, modifiedSince] { + removeMediaKeys(mediaKeysStorageDirectory.string(), modifiedSince); + + RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + + if (dataTypes & WebsiteDataTypeSearchFieldRecentSearches && isPersistent()) { + callbackAggregator->addPendingCallback(); + + m_queue->dispatch([modifiedSince, callbackAggregator] { + platformRemoveRecentSearches(modifiedSince); + + RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + if (dataTypes & WebsiteDataTypePlugInData && isPersistent()) { + class State { + public: + static void deleteData(Ref<CallbackAggregator>&& callbackAggregator, Vector<PluginModuleInfo>&& plugins, std::chrono::system_clock::time_point modifiedSince) + { + new State(WTFMove(callbackAggregator), WTFMove(plugins), modifiedSince); + } + + private: + State(Ref<CallbackAggregator>&& callbackAggregator, Vector<PluginModuleInfo>&& plugins, std::chrono::system_clock::time_point modifiedSince) + : m_callbackAggregator(WTFMove(callbackAggregator)) + , m_plugins(WTFMove(plugins)) + , m_modifiedSince(modifiedSince) + { + m_callbackAggregator->addPendingCallback(); + + deleteWebsiteDataForNextPlugin(); + } + + ~State() + { + ASSERT(m_plugins.isEmpty()); + } + + void deleteWebsiteDataForNextPlugin() + { + if (m_plugins.isEmpty()) { + m_callbackAggregator->removePendingCallback(); + + delete this; + return; + } + + auto plugin = m_plugins.takeLast(); + PluginProcessManager::singleton().deleteWebsiteData(plugin, m_modifiedSince, [this] { + deleteWebsiteDataForNextPlugin(); + }); + } + + Ref<CallbackAggregator> m_callbackAggregator; + Vector<PluginModuleInfo> m_plugins; + std::chrono::system_clock::time_point m_modifiedSince; + }; + + State::deleteData(*callbackAggregator, plugins(), modifiedSince); + } +#endif + + // There's a chance that we don't have any pending callbacks. If so, we want to dispatch the completion handler right away. + callbackAggregator->callIfNeeded(); +} + +void WebsiteDataStore::removeData(WebsiteDataTypes dataTypes, const Vector<WebsiteDataRecord>& dataRecords, std::function<void ()> completionHandler) +{ + Vector<RefPtr<WebCore::SecurityOrigin>> origins; + + for (const auto& dataRecord : dataRecords) { + for (auto& origin : dataRecord.origins) + origins.append(origin); + } + + struct CallbackAggregator : ThreadSafeRefCounted<CallbackAggregator> { + explicit CallbackAggregator (std::function<void ()> completionHandler) + : completionHandler(WTFMove(completionHandler)) + { + } + + void addPendingCallback() + { + pendingCallbacks++; + } + + void removePendingCallback() + { + ASSERT(pendingCallbacks); + --pendingCallbacks; + + callIfNeeded(); + } + + void callIfNeeded() + { + if (!pendingCallbacks) + RunLoop::main().dispatch(WTFMove(completionHandler)); + } + + unsigned pendingCallbacks = 0; + std::function<void ()> completionHandler; + }; + + RefPtr<CallbackAggregator> callbackAggregator = adoptRef(new CallbackAggregator(WTFMove(completionHandler))); + + auto networkProcessAccessType = computeNetworkProcessAccessTypeForDataRemoval(dataTypes, !isPersistent()); + if (networkProcessAccessType != ProcessAccessType::None) { + for (auto& processPool : processPools()) { + switch (networkProcessAccessType) { + case ProcessAccessType::OnlyIfLaunched: + if (!processPool->networkProcess()) + continue; + break; + + case ProcessAccessType::Launch: + processPool->ensureNetworkProcess(); + break; + + case ProcessAccessType::None: + ASSERT_NOT_REACHED(); + } + + Vector<String> cookieHostNames; + for (const auto& dataRecord : dataRecords) { + for (auto& hostName : dataRecord.cookieHostNames) + cookieHostNames.append(hostName); + } + + callbackAggregator->addPendingCallback(); + processPool->networkProcess()->deleteWebsiteDataForOrigins(m_sessionID, dataTypes, origins, cookieHostNames, [callbackAggregator, processPool] { + callbackAggregator->removePendingCallback(); + }); + } + } + + auto webProcessAccessType = computeWebProcessAccessTypeForDataRemoval(dataTypes, !isPersistent()); + if (webProcessAccessType != ProcessAccessType::None) { + for (auto& process : processes()) { + switch (webProcessAccessType) { + case ProcessAccessType::OnlyIfLaunched: + if (!process->canSendMessage()) + continue; + break; + + case ProcessAccessType::Launch: + // FIXME: Handle this. + ASSERT_NOT_REACHED(); + break; + + case ProcessAccessType::None: + ASSERT_NOT_REACHED(); + } + + callbackAggregator->addPendingCallback(); + + process->deleteWebsiteDataForOrigins(m_sessionID, dataTypes, origins, [callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + } + } + + if (dataTypes & WebsiteDataTypeSessionStorage && m_storageManager) { + callbackAggregator->addPendingCallback(); + + m_storageManager->deleteSessionStorageEntriesForOrigins(origins, [callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + } + + if (dataTypes & WebsiteDataTypeLocalStorage && m_storageManager) { + callbackAggregator->addPendingCallback(); + + m_storageManager->deleteLocalStorageEntriesForOrigins(origins, [callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + } + + if (dataTypes & WebsiteDataTypeOfflineWebApplicationCache && isPersistent()) { + StringCapture applicationCacheDirectory { m_applicationCacheDirectory }; + + HashSet<RefPtr<WebCore::SecurityOrigin>> origins; + for (const auto& dataRecord : dataRecords) { + for (const auto& origin : dataRecord.origins) + origins.add(origin); + } + + callbackAggregator->addPendingCallback(); + m_queue->dispatch([origins, applicationCacheDirectory, callbackAggregator] { + auto storage = WebCore::ApplicationCacheStorage::create(applicationCacheDirectory.string(), "ApplicationCache"); + + for (const auto& origin : origins) + storage->deleteCacheForOrigin(*origin); + + WTF::RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + + if (dataTypes & WebsiteDataTypeWebSQLDatabases && isPersistent()) { + StringCapture webSQLDatabaseDirectory { m_webSQLDatabaseDirectory }; + + HashSet<RefPtr<WebCore::SecurityOrigin>> origins; + for (const auto& dataRecord : dataRecords) { + for (const auto& origin : dataRecord.origins) + origins.add(origin); + } + + callbackAggregator->addPendingCallback(); + m_queue->dispatch([origins, callbackAggregator, webSQLDatabaseDirectory] { + auto databaseTracker = WebCore::DatabaseTracker::trackerWithDatabasePath(webSQLDatabaseDirectory.string()); + + for (const auto& origin : origins) + databaseTracker->deleteOrigin(origin.get()); + + RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + +#if ENABLE(DATABASE_PROCESS) + if (dataTypes & WebsiteDataTypeIndexedDBDatabases && isPersistent()) { + for (auto& processPool : processPools()) { + processPool->ensureDatabaseProcess(); + + callbackAggregator->addPendingCallback(); + processPool->databaseProcess()->deleteWebsiteDataForOrigins(m_sessionID, dataTypes, origins, [callbackAggregator, processPool] { + callbackAggregator->removePendingCallback(); + }); + } + } +#endif + + if (dataTypes & WebsiteDataTypeMediaKeys && isPersistent()) { + StringCapture mediaKeysStorageDirectory { m_mediaKeysStorageDirectory }; + HashSet<RefPtr<WebCore::SecurityOrigin>> origins; + for (const auto& dataRecord : dataRecords) { + for (const auto& origin : dataRecord.origins) + origins.add(origin); + } + + callbackAggregator->addPendingCallback(); + m_queue->dispatch([mediaKeysStorageDirectory, callbackAggregator, origins] { + + removeMediaKeys(mediaKeysStorageDirectory.string(), origins); + + RunLoop::main().dispatch([callbackAggregator] { + callbackAggregator->removePendingCallback(); + }); + }); + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + if (dataTypes & WebsiteDataTypePlugInData && isPersistent()) { + Vector<String> hostNames; + for (const auto& dataRecord : dataRecords) { + for (const auto& hostName : dataRecord.pluginDataHostNames) + hostNames.append(hostName); + } + + + class State { + public: + static void deleteData(Ref<CallbackAggregator>&& callbackAggregator, Vector<PluginModuleInfo>&& plugins, Vector<String>&& hostNames) + { + new State(WTFMove(callbackAggregator), WTFMove(plugins), WTFMove(hostNames)); + } + + private: + State(Ref<CallbackAggregator>&& callbackAggregator, Vector<PluginModuleInfo>&& plugins, Vector<String>&& hostNames) + : m_callbackAggregator(WTFMove(callbackAggregator)) + , m_plugins(WTFMove(plugins)) + , m_hostNames(WTFMove(hostNames)) + { + m_callbackAggregator->addPendingCallback(); + + deleteWebsiteDataForNextPlugin(); + } + + ~State() + { + ASSERT(m_plugins.isEmpty()); + } + + void deleteWebsiteDataForNextPlugin() + { + if (m_plugins.isEmpty()) { + m_callbackAggregator->removePendingCallback(); + + delete this; + return; + } + + auto plugin = m_plugins.takeLast(); + PluginProcessManager::singleton().deleteWebsiteDataForHostNames(plugin, m_hostNames, [this] { + deleteWebsiteDataForNextPlugin(); + }); + } + + Ref<CallbackAggregator> m_callbackAggregator; + Vector<PluginModuleInfo> m_plugins; + Vector<String> m_hostNames; + }; + + State::deleteData(*callbackAggregator, plugins(), WTFMove(hostNames)); + } +#endif + + // There's a chance that we don't have any pending callbacks. If so, we want to dispatch the completion handler right away. + callbackAggregator->callIfNeeded(); +} + +void WebsiteDataStore::webPageWasAdded(WebPageProxy& webPageProxy) +{ + if (m_storageManager) + m_storageManager->createSessionStorageNamespace(webPageProxy.pageID(), std::numeric_limits<unsigned>::max()); +} + +void WebsiteDataStore::webPageWasRemoved(WebPageProxy& webPageProxy) +{ + if (m_storageManager) + m_storageManager->destroySessionStorageNamespace(webPageProxy.pageID()); +} + +void WebsiteDataStore::webProcessWillOpenConnection(WebProcessProxy& webProcessProxy, IPC::Connection& connection) +{ + if (m_storageManager) + m_storageManager->processWillOpenConnection(webProcessProxy, connection); +} + +void WebsiteDataStore::webPageWillOpenConnection(WebPageProxy& webPageProxy, IPC::Connection& connection) +{ + if (m_storageManager) + m_storageManager->setAllowedSessionStorageNamespaceConnection(webPageProxy.pageID(), &connection); +} + +void WebsiteDataStore::webPageDidCloseConnection(WebPageProxy& webPageProxy, IPC::Connection&) +{ + if (m_storageManager) + m_storageManager->setAllowedSessionStorageNamespaceConnection(webPageProxy.pageID(), nullptr); +} + +void WebsiteDataStore::webProcessDidCloseConnection(WebProcessProxy& webProcessProxy, IPC::Connection& connection) +{ + if (m_storageManager) + m_storageManager->processDidCloseConnection(webProcessProxy, connection); +} + +HashSet<RefPtr<WebProcessPool>> WebsiteDataStore::processPools() const +{ + HashSet<RefPtr<WebProcessPool>> processPools; + for (auto& process : processes()) + processPools.add(&process->processPool()); + + if (processPools.isEmpty()) { + // Check if we're one of the legacy data stores. + for (auto& processPool : WebProcessPool::allProcessPools()) { + if (auto dataStore = processPool->websiteDataStore()) { + if (&dataStore->websiteDataStore() == this) { + processPools.add(processPool); + break; + } + } + } + } + + if (processPools.isEmpty()) { + auto processPool = WebProcessPool::create(API::ProcessPoolConfiguration::create()); + + processPools.add(processPool.ptr()); + } + + return processPools; +} + +#if ENABLE(NETSCAPE_PLUGIN_API) +Vector<PluginModuleInfo> WebsiteDataStore::plugins() const +{ + Vector<PluginModuleInfo> plugins; + + for (auto& processPool : processPools()) { + for (auto& plugin : processPool->pluginInfoStore().plugins()) + plugins.append(plugin); + } + + return plugins; +} +#endif + +static String computeMediaKeyFile(const String& mediaKeyDirectory) +{ + return WebCore::pathByAppendingComponent(mediaKeyDirectory, "SecureStop.plist"); +} + +Vector<RefPtr<WebCore::SecurityOrigin>> WebsiteDataStore::mediaKeyOrigins(const String& mediaKeysStorageDirectory) +{ + ASSERT(!mediaKeysStorageDirectory.isEmpty()); + + Vector<RefPtr<WebCore::SecurityOrigin>> origins; + + for (const auto& originPath : WebCore::listDirectory(mediaKeysStorageDirectory, "*")) { + auto mediaKeyFile = computeMediaKeyFile(originPath); + if (!WebCore::fileExists(mediaKeyFile)) + continue; + + auto mediaKeyIdentifier = WebCore::pathGetFileName(originPath); + + if (auto securityOrigin = WebCore::SecurityOrigin::maybeCreateFromDatabaseIdentifier(mediaKeyIdentifier)) + origins.append(WTFMove(securityOrigin)); + } + + return origins; +} + +void WebsiteDataStore::removeMediaKeys(const String& mediaKeysStorageDirectory, std::chrono::system_clock::time_point modifiedSince) +{ + ASSERT(!mediaKeysStorageDirectory.isEmpty()); + + for (const auto& mediaKeyDirectory : WebCore::listDirectory(mediaKeysStorageDirectory, "*")) { + auto mediaKeyFile = computeMediaKeyFile(mediaKeyDirectory); + + time_t modificationTime; + if (!WebCore::getFileModificationTime(mediaKeyFile, modificationTime)) + continue; + + if (std::chrono::system_clock::from_time_t(modificationTime) < modifiedSince) + continue; + + WebCore::deleteFile(mediaKeyFile); + WebCore::deleteEmptyDirectory(mediaKeyDirectory); + } +} + +void WebsiteDataStore::removeMediaKeys(const String& mediaKeysStorageDirectory, const HashSet<RefPtr<WebCore::SecurityOrigin>>& origins) +{ + ASSERT(!mediaKeysStorageDirectory.isEmpty()); + + for (const auto& origin : origins) { + auto mediaKeyDirectory = WebCore::pathByAppendingComponent(mediaKeysStorageDirectory, origin->databaseIdentifier()); + auto mediaKeyFile = computeMediaKeyFile(mediaKeyDirectory); + + WebCore::deleteFile(mediaKeyFile); + WebCore::deleteEmptyDirectory(mediaKeyDirectory); + } +} + +} diff --git a/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataStore.h b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataStore.h new file mode 100644 index 000000000..0c829da94 --- /dev/null +++ b/Source/WebKit2/UIProcess/WebsiteData/WebsiteDataStore.h @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2014 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 WebsiteDataStore_h +#define WebsiteDataStore_h + +#include "WebProcessLifetimeObserver.h" +#include "WebsiteDataTypes.h" +#include <WebCore/SecurityOriginHash.h> +#include <WebCore/SessionID.h> +#include <functional> +#include <wtf/HashSet.h> +#include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> +#include <wtf/WorkQueue.h> +#include <wtf/text/WTFString.h> + +namespace WebCore { +class SecurityOrigin; +} + +namespace WebKit { + +class StorageManager; +class WebPageProxy; +class WebProcessPool; +struct WebsiteDataRecord; + +#if ENABLE(NETSCAPE_PLUGIN_API) +struct PluginModuleInfo; +#endif + +class WebsiteDataStore : public RefCounted<WebsiteDataStore>, public WebProcessLifetimeObserver { +public: + struct Configuration { + String networkCacheDirectory; + String applicationCacheDirectory; + + String webSQLDatabaseDirectory; + String localStorageDirectory; + String mediaKeysStorageDirectory; + }; + static Ref<WebsiteDataStore> createNonPersistent(); + static Ref<WebsiteDataStore> create(Configuration); + virtual ~WebsiteDataStore(); + + uint64_t identifier() const { return m_identifier; } + + bool isPersistent() const { return !m_sessionID.isEphemeral(); } + WebCore::SessionID sessionID() const { return m_sessionID; } + + static void cloneSessionData(WebPageProxy& sourcePage, WebPageProxy& newPage); + + void fetchData(WebsiteDataTypes, std::function<void (Vector<WebsiteDataRecord>)> completionHandler); + void removeData(WebsiteDataTypes, std::chrono::system_clock::time_point modifiedSince, std::function<void ()> completionHandler); + void removeData(WebsiteDataTypes, const Vector<WebsiteDataRecord>&, std::function<void ()> completionHandler); + + StorageManager* storageManager() { return m_storageManager.get(); } + +private: + explicit WebsiteDataStore(WebCore::SessionID); + explicit WebsiteDataStore(Configuration); + + // WebProcessLifetimeObserver. + virtual void webPageWasAdded(WebPageProxy&) override; + virtual void webPageWasRemoved(WebPageProxy&) override; + virtual void webProcessWillOpenConnection(WebProcessProxy&, IPC::Connection&) override; + virtual void webPageWillOpenConnection(WebPageProxy&, IPC::Connection&) override; + virtual void webPageDidCloseConnection(WebPageProxy&, IPC::Connection&) override; + virtual void webProcessDidCloseConnection(WebProcessProxy&, IPC::Connection&) override; + + void platformInitialize(); + void platformDestroy(); + static void platformRemoveRecentSearches(std::chrono::system_clock::time_point); + + HashSet<RefPtr<WebProcessPool>> processPools() const; + +#if ENABLE(NETSCAPE_PLUGIN_API) + Vector<PluginModuleInfo> plugins() const; +#endif + + static Vector<RefPtr<WebCore::SecurityOrigin>> mediaKeyOrigins(const String& mediaKeysStorageDirectory); + static void removeMediaKeys(const String& mediaKeysStorageDirectory, std::chrono::system_clock::time_point modifiedSince); + static void removeMediaKeys(const String& mediaKeysStorageDirectory, const HashSet<RefPtr<WebCore::SecurityOrigin>>&); + + const uint64_t m_identifier; + const WebCore::SessionID m_sessionID; + + const String m_networkCacheDirectory; + const String m_applicationCacheDirectory; + + const String m_webSQLDatabaseDirectory; + const String m_mediaKeysStorageDirectory; + const RefPtr<StorageManager> m_storageManager; + + Ref<WorkQueue> m_queue; +}; + +} + +#endif // WebsiteDataStore_h diff --git a/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.cpp b/Source/WebKit2/UIProcess/WebsiteData/unix/WebsiteDataStoreUnix.cpp index 11b29e65b..76956fd75 100644 --- a/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.cpp +++ b/Source/WebKit2/UIProcess/WebsiteData/unix/WebsiteDataStoreUnix.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012 Samsung Electronics + * Copyright (C) 2015 University of Szeged. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -10,36 +10,30 @@ * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * 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. + * 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 "WebPopupMenuListenerEfl.h" +#include "WebsiteDataStore.h" namespace WebKit { -WebPopupMenuListenerEfl::WebPopupMenuListenerEfl(WebPopupMenuProxy::Client* client) - : WebPopupMenuProxy(client) +void WebsiteDataStore::platformInitialize() { } -void WebPopupMenuListenerEfl::valueChanged(int newSelectedIndex) +void WebsiteDataStore::platformDestroy() { - if (!m_client) - return; - - m_client->valueChangedForPopupMenu(this, newSelectedIndex); - invalidate(); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/API/mac/WKProcessGroupPrivate.h b/Source/WebKit2/UIProcess/_WKWebViewPrintFormatter.h index 7a9d2f9c0..befdcc78b 100644 --- a/Source/WebKit2/UIProcess/API/mac/WKProcessGroupPrivate.h +++ b/Source/WebKit2/UIProcess/_WKWebViewPrintFormatter.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2011 Apple Inc. All rights reserved. + * Copyright (C) 2014 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,10 +23,16 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#import <WebKit2/WKProcessGroup.h> +#if TARGET_OS_IPHONE -@interface WKProcessGroup (Private) +#import <UIKit/UIPrintFormatter.h> -@property(readonly) WKContextRef _contextRef; +@class _WKFrameHandle; + +@interface _WKWebViewPrintFormatter : UIViewPrintFormatter + +@property (nonatomic, strong) _WKFrameHandle *frameToPrint; @end + +#endif diff --git a/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp b/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp deleted file mode 100644 index 8369a2bd4..000000000 --- a/Source/WebKit2/UIProcess/cairo/BackingStoreCairo.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * Copyright (C) 2011 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. - */ - -#include "config.h" -#include "BackingStore.h" - -#include "ShareableBitmap.h" -#include "UpdateInfo.h" -#include "WebPageProxy.h" -#include <WebCore/GraphicsContext.h> -#include <WebCore/WidgetBackingStoreCairo.h> -#include <cairo.h> - -#if PLATFORM(GTK) && defined(GDK_WINDOWING_X11) -#include <WebCore/WidgetBackingStoreGtkX11.h> -#include <gdk/gdkx.h> -#endif - -#if PLATFORM(EFL) -#include "EwkView.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -#if PLATFORM(GTK) -static OwnPtr<WidgetBackingStore> createBackingStoreForGTK(GtkWidget* widget, const IntSize& size) -{ -#ifdef GDK_WINDOWING_X11 - GdkDisplay* display = gdk_display_manager_get_default_display(gdk_display_manager_get()); - if (GDK_IS_X11_DISPLAY(display)) - return WebCore::WidgetBackingStoreGtkX11::create(widget, size); -#endif - return WebCore::WidgetBackingStoreCairo::create(widget, size); -} -#endif - -void BackingStore::paint(cairo_t* context, const IntRect& rect) -{ - ASSERT(m_backingStore); - - cairo_set_operator(context, CAIRO_OPERATOR_SOURCE); - cairo_set_source_surface(context, m_backingStore->cairoSurface(), 0, 0); - cairo_rectangle(context, rect.x(), rect.y(), rect.width(), rect.height()); - cairo_fill(context); -} - -void BackingStore::incorporateUpdate(ShareableBitmap* bitmap, const UpdateInfo& updateInfo) -{ - if (!m_backingStore) -#if PLATFORM(EFL) - m_backingStore = WidgetBackingStoreCairo::create(EwkView::toEvasObject(toAPI(m_webPageProxy)), size()); -#else - m_backingStore = createBackingStoreForGTK(m_webPageProxy->viewWidget(), size()); -#endif - - scroll(updateInfo.scrollRect, updateInfo.scrollOffset); - - // Paint all update rects. - IntPoint updateRectLocation = updateInfo.updateRectBounds.location(); - RefPtr<cairo_t> context(adoptRef(cairo_create(m_backingStore->cairoSurface()))); - GraphicsContext graphicsContext(context.get()); - for (size_t i = 0; i < updateInfo.updateRects.size(); ++i) { - IntRect updateRect = updateInfo.updateRects[i]; - IntRect srcRect = updateRect; - srcRect.move(-updateRectLocation.x(), -updateRectLocation.y()); - bitmap->paint(graphicsContext, updateRect.location(), srcRect); - } -} - -void BackingStore::scroll(const IntRect& scrollRect, const IntSize& scrollOffset) -{ - if (scrollOffset.isZero()) - return; - - ASSERT(m_backingStore); - m_backingStore->scroll(scrollRect, scrollOffset); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp b/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp deleted file mode 100644 index e85d909ed..000000000 --- a/Source/WebKit2/UIProcess/cf/WebBackForwardListCF.cpp +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebBackForwardList.h" - -#include "Logging.h" -#include <wtf/RetainPtr.h> -#include <CoreFoundation/CoreFoundation.h> - -using namespace WebCore; - -namespace WebKit { - -static uint64_t generateWebBackForwardItemID() -{ - // These IDs exist in the UIProcess for items created by the UIProcess. - // The IDs generated here need to never collide with the IDs created in WebBackForwardListProxy in the WebProcess. - // We accomplish this by starting from 2, and only ever using even ids. - static uint64_t uniqueHistoryItemID = 0; - uniqueHistoryItemID += 2; - return uniqueHistoryItemID; -} - -static CFIndex currentVersion = 1; -DEFINE_STATIC_GETTER(CFNumberRef, SessionHistoryCurrentVersion, (CFNumberCreate(0, kCFNumberCFIndexType, ¤tVersion))); - -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryVersionKey, (CFSTR("SessionHistoryVersion"))); -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryCurrentIndexKey, (CFSTR("SessionHistoryCurrentIndex"))); -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryEntriesKey, (CFSTR("SessionHistoryEntries"))); -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryEntryTitleKey, (CFSTR("SessionHistoryEntryTitle"))); -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryEntryURLKey, (CFSTR("SessionHistoryEntryURL"))); -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryEntryOriginalURLKey, (CFSTR("SessionHistoryEntryOriginalURL"))); -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryEntryDataKey, (CFSTR("SessionHistoryEntryData"))); - -static bool extractBackForwardListEntriesFromArray(CFArrayRef, BackForwardListItemVector&); - -static CFDictionaryRef createEmptySessionHistoryDictionary() -{ - static const void* keys[1] = { SessionHistoryVersionKey() }; - static const void* values[1] = { SessionHistoryCurrentVersion() }; - - return CFDictionaryCreate(0, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); -} - -CFDictionaryRef WebBackForwardList::createCFDictionaryRepresentation(WebPageProxy::WebPageProxySessionStateFilterCallback filter, void* context) const -{ - ASSERT(!m_hasCurrentIndex || m_currentIndex < m_entries.size()); - - if (!m_hasCurrentIndex) { - // We represent having no current index by writing out an empty dictionary (besides the version). - return createEmptySessionHistoryDictionary(); - } - - RetainPtr<CFMutableArrayRef> entries = adoptCF(CFArrayCreateMutable(0, m_entries.size(), &kCFTypeArrayCallBacks)); - - // We may need to update the current index to account for entries that are filtered by the callback. - CFIndex currentIndex = m_currentIndex; - bool hasCurrentIndex = true; - - for (size_t i = 0; i < m_entries.size(); ++i) { - // If we somehow ended up with a null entry then we should consider the data invalid and not save session history at all. - ASSERT(m_entries[i]); - if (!m_entries[i]) { - LOG(SessionState, "WebBackForwardList contained a null entry at index %lu", i); - return 0; - } - - if (filter) { - if (!filter(toAPI(m_page), WKPageGetSessionBackForwardListItemValueType(), toAPI(m_entries[i].get()), context) - || !filter(toAPI(m_page), WKPageGetSessionHistoryURLValueType(), toURLRef(m_entries[i]->originalURL().impl()), context)) { - if (i <= m_currentIndex) - currentIndex--; - continue; - } - } - - RetainPtr<CFStringRef> url = m_entries[i]->url().createCFString(); - RetainPtr<CFStringRef> title = m_entries[i]->title().createCFString(); - RetainPtr<CFStringRef> originalURL = m_entries[i]->originalURL().createCFString(); - - // FIXME: This uses the CoreIPC data encoding format, which means that whenever we change the CoreIPC encoding we need to bump the CurrentSessionStateDataVersion - // constant in WebPageProxyCF.cpp. The CoreIPC data format is meant to be an implementation detail, and not something that should be written to disk. - RetainPtr<CFDataRef> entryData = adoptCF(CFDataCreate(kCFAllocatorDefault, m_entries[i]->backForwardData().data(), m_entries[i]->backForwardData().size())); - - const void* keys[4] = { SessionHistoryEntryURLKey(), SessionHistoryEntryTitleKey(), SessionHistoryEntryOriginalURLKey(), SessionHistoryEntryDataKey() }; - const void* values[4] = { url.get(), title.get(), originalURL.get(), entryData.get() }; - - RetainPtr<CFDictionaryRef> entryDictionary = adoptCF(CFDictionaryCreate(0, keys, values, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); - CFArrayAppendValue(entries.get(), entryDictionary.get()); - } - - ASSERT(currentIndex == -1 || (currentIndex > -1 && currentIndex < CFArrayGetCount(entries.get()))); - if (currentIndex < -1 || currentIndex >= CFArrayGetCount(entries.get())) { - LOG(SessionState, "Filtering entries to be saved resulted in an inconsistent state that we cannot represent"); - return 0; - } - - // If we have an index and all items before and including the current item were filtered then currentIndex will be -1. - // In this case the new current index should point at the first item. - // It's also possible that all items were filtered so we should represent not having a current index. - if (currentIndex == -1) { - if (CFArrayGetCount(entries.get())) - currentIndex = 0; - else - hasCurrentIndex = false; - } - - if (hasCurrentIndex) { - RetainPtr<CFNumberRef> currentIndexNumber = adoptCF(CFNumberCreate(0, kCFNumberCFIndexType, ¤tIndex)); - const void* keys[3] = { SessionHistoryVersionKey(), SessionHistoryCurrentIndexKey(), SessionHistoryEntriesKey() }; - const void* values[3] = { SessionHistoryCurrentVersion(), currentIndexNumber.get(), entries.get() }; - - return CFDictionaryCreate(0, keys, values, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - } - - // We represent having no current index by writing out an empty dictionary (besides the version). - return createEmptySessionHistoryDictionary(); -} - -bool WebBackForwardList::restoreFromCFDictionaryRepresentation(CFDictionaryRef dictionary) -{ - CFNumberRef cfVersion = (CFNumberRef)CFDictionaryGetValue(dictionary, SessionHistoryVersionKey()); - if (!cfVersion) { - // v0 session history dictionaries did not contain versioning - return restoreFromV0CFDictionaryRepresentation(dictionary); - } - - if (CFGetTypeID(cfVersion) != CFNumberGetTypeID()) { - LOG(SessionState, "WebBackForwardList dictionary representation contains a version that is not a number"); - return false; - } - - CFIndex version; - if (!CFNumberGetValue(cfVersion, kCFNumberCFIndexType, &version)) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a correctly typed current version"); - return false; - } - - if (version == 1) - return restoreFromV1CFDictionaryRepresentation(dictionary); - - LOG(SessionState, "WebBackForwardList dictionary representation has an invalid current version (%ld)", version); - return false; -} - -bool WebBackForwardList::restoreFromV0CFDictionaryRepresentation(CFDictionaryRef dictionary) -{ - CFNumberRef cfIndex = (CFNumberRef)CFDictionaryGetValue(dictionary, SessionHistoryCurrentIndexKey()); - if (!cfIndex || CFGetTypeID(cfIndex) != CFNumberGetTypeID()) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a valid current index"); - return false; - } - - CFIndex currentCFIndex; - if (!CFNumberGetValue(cfIndex, kCFNumberCFIndexType, ¤tCFIndex)) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a correctly typed current index"); - return false; - } - - if (currentCFIndex < -1) { - LOG(SessionState, "WebBackForwardList dictionary representation contains an unexpected negative current index (%ld)", currentCFIndex); - return false; - } - - CFArrayRef cfEntries = (CFArrayRef)CFDictionaryGetValue(dictionary, SessionHistoryEntriesKey()); - if (!cfEntries || CFGetTypeID(cfEntries) != CFArrayGetTypeID()) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a valid list of entries"); - return false; - } - - CFIndex size = CFArrayGetCount(cfEntries); - if (size < 0 || currentCFIndex >= size) { - LOG(SessionState, "WebBackForwardList dictionary representation contains an invalid current index (%ld) for the number of entries (%ld)", currentCFIndex, size); - return false; - } - - // Version 0 session history relied on currentIndex == -1 to represent the same thing as not having a current index. - bool hasCurrentIndex = currentCFIndex != -1; - - if (!hasCurrentIndex && size) { - LOG(SessionState, "WebBackForwardList dictionary representation says there is no current index, but there is a list of %ld entries", size); - return false; - } - - BackForwardListItemVector entries; - if (!extractBackForwardListEntriesFromArray(cfEntries, entries)) { - // extractBackForwardListEntriesFromArray has already logged the appropriate error message. - return false; - } - - ASSERT(entries.size() == static_cast<unsigned>(size)); - - m_hasCurrentIndex = hasCurrentIndex; - m_currentIndex = m_hasCurrentIndex ? static_cast<uint32_t>(currentCFIndex) : 0; - m_entries = entries; - - return true; -} - -bool WebBackForwardList::restoreFromV1CFDictionaryRepresentation(CFDictionaryRef dictionary) -{ - CFNumberRef cfIndex = (CFNumberRef)CFDictionaryGetValue(dictionary, SessionHistoryCurrentIndexKey()); - if (!cfIndex) { - // No current index means the dictionary represents an empty session. - m_hasCurrentIndex = false; - m_currentIndex = 0; - m_entries.clear(); - - return true; - } - - if (CFGetTypeID(cfIndex) != CFNumberGetTypeID()) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a valid current index"); - return false; - } - - CFIndex currentCFIndex; - if (!CFNumberGetValue(cfIndex, kCFNumberCFIndexType, ¤tCFIndex)) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a correctly typed current index"); - return false; - } - - if (currentCFIndex < 0) { - LOG(SessionState, "WebBackForwardList dictionary representation contains an unexpected negative current index (%ld)", currentCFIndex); - return false; - } - - CFArrayRef cfEntries = (CFArrayRef)CFDictionaryGetValue(dictionary, SessionHistoryEntriesKey()); - if (!cfEntries || CFGetTypeID(cfEntries) != CFArrayGetTypeID()) { - LOG(SessionState, "WebBackForwardList dictionary representation does not have a valid list of entries"); - return false; - } - - CFIndex size = CFArrayGetCount(cfEntries); - if (currentCFIndex >= size) { - LOG(SessionState, "WebBackForwardList dictionary representation contains an invalid current index (%ld) for the number of entries (%ld)", currentCFIndex, size); - return false; - } - - BackForwardListItemVector entries; - if (!extractBackForwardListEntriesFromArray(cfEntries, entries)) { - // extractBackForwardListEntriesFromArray has already logged the appropriate error message. - return false; - } - - ASSERT(entries.size() == static_cast<unsigned>(size)); - - m_hasCurrentIndex = true; - m_currentIndex = static_cast<uint32_t>(currentCFIndex); - m_entries = entries; - - return true; -} - -static bool extractBackForwardListEntriesFromArray(CFArrayRef cfEntries, BackForwardListItemVector& entries) -{ - CFIndex size = CFArrayGetCount(cfEntries); - - entries.reserveCapacity(size); - for (CFIndex i = 0; i < size; ++i) { - CFDictionaryRef entryDictionary = (CFDictionaryRef)CFArrayGetValueAtIndex(cfEntries, i); - if (!entryDictionary || CFGetTypeID(entryDictionary) != CFDictionaryGetTypeID()) { - LOG(SessionState, "WebBackForwardList entry array does not have a valid entry at index %i", (int)i); - return false; - } - - CFStringRef entryURL = (CFStringRef)CFDictionaryGetValue(entryDictionary, SessionHistoryEntryURLKey()); - if (!entryURL || CFGetTypeID(entryURL) != CFStringGetTypeID()) { - LOG(SessionState, "WebBackForwardList entry at index %i does not have a valid URL", (int)i); - return false; - } - - CFStringRef entryTitle = (CFStringRef)CFDictionaryGetValue(entryDictionary, SessionHistoryEntryTitleKey()); - if (!entryTitle || CFGetTypeID(entryTitle) != CFStringGetTypeID()) { - LOG(SessionState, "WebBackForwardList entry at index %i does not have a valid title", (int)i); - return false; - } - - CFStringRef originalURL = (CFStringRef)CFDictionaryGetValue(entryDictionary, SessionHistoryEntryOriginalURLKey()); - if (!originalURL || CFGetTypeID(originalURL) != CFStringGetTypeID()) { - LOG(SessionState, "WebBackForwardList entry at index %i does not have a valid original URL", (int)i); - return false; - } - - CFDataRef backForwardData = (CFDataRef)CFDictionaryGetValue(entryDictionary, SessionHistoryEntryDataKey()); - if (!backForwardData || CFGetTypeID(backForwardData) != CFDataGetTypeID()) { - LOG(SessionState, "WebBackForwardList entry at index %i does not have back/forward data", (int)i); - return false; - } - - entries.append(WebBackForwardListItem::create(originalURL, entryURL, entryTitle, CFDataGetBytePtr(backForwardData), CFDataGetLength(backForwardData), generateWebBackForwardItemID())); - } - - return true; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp b/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp deleted file mode 100644 index 082b09fd3..000000000 --- a/Source/WebKit2/UIProcess/cf/WebPageProxyCF.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPageProxy.h" - -#include "DataReference.h" -#include "Logging.h" -#include "SessionState.h" -#include "WebBackForwardList.h" -#include "WebData.h" -#include "WebPageMessages.h" -#include "WebProcessProxy.h" - -#include <wtf/RetainPtr.h> -#include <CoreFoundation/CFPropertyList.h> - -using namespace WebCore; - -namespace WebKit { - -DEFINE_STATIC_GETTER(CFStringRef, SessionHistoryKey, (CFSTR("SessionHistory"))); -DEFINE_STATIC_GETTER(CFStringRef, ProvisionalURLKey, (CFSTR("ProvisionalURL"))); - -static const UInt32 CurrentSessionStateDataVersion = 2; - -PassRefPtr<WebData> WebPageProxy::sessionStateData(WebPageProxySessionStateFilterCallback filter, void* context) const -{ - const void* keys[2]; - const void* values[2]; - CFIndex numValues = 0; - - RetainPtr<CFDictionaryRef> sessionHistoryDictionary = adoptCF(m_backForwardList->createCFDictionaryRepresentation(filter, context)); - if (sessionHistoryDictionary) { - keys[numValues] = SessionHistoryKey(); - values[numValues] = sessionHistoryDictionary.get(); - ++numValues; - } - - RetainPtr<CFStringRef> provisionalURLString; - if (m_mainFrame) { - String provisionalURL = pendingAPIRequestURL(); - if (provisionalURL.isEmpty()) - provisionalURL = m_mainFrame->provisionalURL(); - if (!provisionalURL.isEmpty()) { - provisionalURLString = provisionalURL.createCFString(); - keys[numValues] = ProvisionalURLKey(); - values[numValues] = provisionalURLString.get(); - ++numValues; - } - } - - if (!numValues) - return 0; - - RetainPtr<CFDictionaryRef> stateDictionary = adoptCF(CFDictionaryCreate(0, keys, values, numValues, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); - - RetainPtr<CFWriteStreamRef> writeStream = adoptCF(CFWriteStreamCreateWithAllocatedBuffers(0, 0)); - if (!writeStream) - return 0; - - if (!CFWriteStreamOpen(writeStream.get())) - return 0; - - if (!CFPropertyListWriteToStream(stateDictionary.get(), writeStream.get(), kCFPropertyListBinaryFormat_v1_0, 0)) - return 0; - - RetainPtr<CFDataRef> stateCFData = adoptCF((CFDataRef)CFWriteStreamCopyProperty(writeStream.get(), kCFStreamPropertyDataWritten)); - - CFIndex length = CFDataGetLength(stateCFData.get()); - Vector<unsigned char> stateVector(length + sizeof(UInt32)); - - // Put the session state version number at the start of the buffer - stateVector.data()[0] = (CurrentSessionStateDataVersion & 0xFF000000) >> 24; - stateVector.data()[1] = (CurrentSessionStateDataVersion & 0x00FF0000) >> 16; - stateVector.data()[2] = (CurrentSessionStateDataVersion & 0x0000FF00) >> 8; - stateVector.data()[3] = (CurrentSessionStateDataVersion & 0x000000FF); - - // Copy in the actual session state data - CFDataGetBytes(stateCFData.get(), CFRangeMake(0, length), stateVector.data() + sizeof(UInt32)); - - return WebData::create(stateVector); -} - -void WebPageProxy::restoreFromSessionStateData(WebData* webData) -{ - if (!webData || webData->size() < sizeof(UInt32)) - return; - - const unsigned char* buffer = webData->bytes(); - UInt32 versionHeader = (buffer[0] << 24) + (buffer[1] << 16) + (buffer[2] << 8) + buffer[3]; - - if (versionHeader != CurrentSessionStateDataVersion) { - LOG(SessionState, "Unrecognized version header for session state data - cannot restore"); - return; - } - - RetainPtr<CFDataRef> data = adoptCF(CFDataCreate(0, webData->bytes() + sizeof(UInt32), webData->size() - sizeof(UInt32))); - - CFStringRef propertyListError = 0; - RetainPtr<CFPropertyListRef> propertyList = adoptCF(CFPropertyListCreateFromXMLData(0, data.get(), kCFPropertyListImmutable, &propertyListError)); - if (propertyListError) { - CFRelease(propertyListError); - LOG(SessionState, "Could not read session state property list"); - return; - } - - if (!propertyList) - return; - - if (CFGetTypeID(propertyList.get()) != CFDictionaryGetTypeID()) { - LOG(SessionState, "SessionState property list is not a CFDictionaryRef (%i) - its CFTypeID is %i", (int)CFDictionaryGetTypeID(), (int)CFGetTypeID(propertyList.get())); - return; - } - - CFDictionaryRef backForwardListDictionary = 0; - if (CFTypeRef value = CFDictionaryGetValue(static_cast<CFDictionaryRef>(propertyList.get()), SessionHistoryKey())) { - if (CFGetTypeID(value) != CFDictionaryGetTypeID()) - LOG(SessionState, "SessionState dictionary has a SessionHistory key, but the value is not a dictionary"); - else - backForwardListDictionary = static_cast<CFDictionaryRef>(value); - } - - CFStringRef provisionalURL = 0; - if (CFTypeRef value = CFDictionaryGetValue(static_cast<CFDictionaryRef>(propertyList.get()), ProvisionalURLKey())) { - if (CFGetTypeID(value) != CFStringGetTypeID()) - LOG(SessionState, "SessionState dictionary has a ProvisionalValue key, but the value is not a string"); - else - provisionalURL = static_cast<CFStringRef>(value); - } - - if (backForwardListDictionary) { - if (!m_backForwardList->restoreFromCFDictionaryRepresentation(backForwardListDictionary)) - LOG(SessionState, "Failed to restore back/forward list from SessionHistory dictionary"); - else { - const BackForwardListItemVector& entries = m_backForwardList->entries(); - if (size_t size = entries.size()) { - for (size_t i = 0; i < size; ++i) - process()->registerNewWebBackForwardListItem(entries[i].get()); - - SessionState state(m_backForwardList->entries(), m_backForwardList->currentIndex()); - if (provisionalURL) - process()->send(Messages::WebPage::RestoreSession(state), m_pageID); - else { - if (WebBackForwardListItem* item = m_backForwardList->currentItem()) - setPendingAPIRequestURL(item->url()); - - process()->send(Messages::WebPage::RestoreSessionAndNavigateToCurrentItem(state), m_pageID); - } - } - } - } - - if (provisionalURL) - loadURL(provisionalURL); -} - -static RetainPtr<CFStringRef> autosaveKey(const String& name) -{ - return String("com.apple.WebKit.searchField:" + name).createCFString(); -} - -void WebPageProxy::saveRecentSearches(const String& name, const Vector<String>& searchItems) -{ - // The WebProcess shouldn't have bothered to send this message if the name was empty. - ASSERT(!name.isEmpty()); - - RetainPtr<CFMutableArrayRef> items; - - if (size_t size = searchItems.size()) { - items = adoptCF(CFArrayCreateMutable(0, size, &kCFTypeArrayCallBacks)); - for (size_t i = 0; i < size; ++i) - CFArrayAppendValue(items.get(), searchItems[i].createCFString().get()); - } - - CFPreferencesSetAppValue(autosaveKey(name).get(), items.get(), kCFPreferencesCurrentApplication); - CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); -} - -void WebPageProxy::loadRecentSearches(const String& name, Vector<String>& searchItems) -{ - // The WebProcess shouldn't have bothered to send this message if the name was empty. - ASSERT(!name.isEmpty()); - - searchItems.clear(); - RetainPtr<CFArrayRef> items = adoptCF(reinterpret_cast<CFArrayRef>(CFPreferencesCopyAppValue(autosaveKey(name).get(), kCFPreferencesCurrentApplication))); - - if (!items || CFGetTypeID(items.get()) != CFArrayGetTypeID()) - return; - - size_t size = CFArrayGetCount(items.get()); - for (size_t i = 0; i < size; ++i) { - CFStringRef item = (CFStringRef)CFArrayGetValueAtIndex(items.get(), i); - if (CFGetTypeID(item) == CFStringGetTypeID()) - searchItems.append(item); - } -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp b/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp deleted file mode 100644 index f2463a735..000000000 --- a/Source/WebKit2/UIProcess/cf/WebPreferencesCF.cpp +++ /dev/null @@ -1,155 +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 "WebPreferences.h" - -#include <wtf/RetainPtr.h> -#include <wtf/text/StringConcatenate.h> - -#if !PLATFORM(MAC) - -namespace WebKit { - -static RetainPtr<CFStringRef> cfStringFromWebCoreString(const String& string) -{ - return RetainPtr<CFStringRef> = adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(string.characters()), string.length())); -} - -static inline RetainPtr<CFStringRef> makeKey(const String& identifier, const String& baseKey) -{ - return cfStringFromWebCoreString(makeString(identifier, ".WebKit2", baseKey)); -} - -static void setStringValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) -{ - RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); - if (!value) - return; - if (CFGetTypeID(value.get()) != CFStringGetTypeID()) - return; - - store.setStringValueForKey(baseKey, (CFStringRef)value.get()); -} - -static void setBoolValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) -{ - RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); - if (!value) - return; - if (CFGetTypeID(value.get()) != CFBooleanGetTypeID()) - return; - - store.setBoolValueForKey(baseKey, CFBooleanGetValue((CFBooleanRef)value.get()) ? true : false); -} - -static void setUInt32ValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) -{ - RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); - if (!value) - return; - if (CFGetTypeID(value.get()) != CFNumberGetTypeID()) - return; - int32_t intValue = 0; - if (!CFNumberGetValue((CFNumberRef)value.get(), kCFNumberSInt32Type, &intValue)) - return; - - store.setUInt32ValueForKey(baseKey, intValue); -} - -static void setDoubleValueIfInUserDefaults(const String& identifier, const String& baseKey, WebPreferencesStore& store) -{ - RetainPtr<CFPropertyListRef> value = adoptCF(CFPreferencesCopyAppValue(makeKey(identifier, baseKey).get(), kCFPreferencesCurrentApplication)); - if (!value) - return; - if (CFGetTypeID(value.get()) != CFNumberGetTypeID()) - return; - double doubleValue = 0; - if (!CFNumberGetValue((CFNumberRef)value.get(), kCFNumberDoubleType, &doubleValue)) - return; - - store.setDoubleValueForKey(baseKey, doubleValue); -} - -void WebPreferences::platformInitializeStore() -{ - if (!m_identifier) - return; - -#define INITIALIZE_PREFERENCE_FROM_NSUSERDEFAULTS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) \ - set##TypeName##ValueIfInUserDefaults(m_identifier, WebPreferencesKey::KeyLower##Key(), m_store); - - FOR_EACH_WEBKIT_PREFERENCE(INITIALIZE_PREFERENCE_FROM_NSUSERDEFAULTS) - -#undef INITIALIZE_PREFERENCE_FROM_NSUSERDEFAULTS - -} - -void WebPreferences::platformUpdateStringValueForKey(const String& key, const String& value) -{ - if (!m_identifier) - return; - - CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), cfStringFromWebCoreString(value).get(), kCFPreferencesCurrentApplication); -} - -void WebPreferences::platformUpdateBoolValueForKey(const String& key, bool value) -{ - if (!m_identifier) - return; - - CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), value ? kCFBooleanTrue : kCFBooleanFalse, kCFPreferencesCurrentApplication); -} - -void WebPreferences::platformUpdateUInt32ValueForKey(const String& key, uint32_t value) -{ - if (!m_identifier) - return; - - RetainPtr<CFNumberRef> number = adoptCF(CFNumberCreate(0, kCFNumberSInt32Type, &value)); - CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), number.get(), kCFPreferencesCurrentApplication); -} - -void WebPreferences::platformUpdateDoubleValueForKey(const String& key, double value) -{ - if (!m_identifier) - return; - - RetainPtr<CFNumberRef> number = adoptCF(CFNumberCreate(0, kCFNumberDoubleType, &value)); - CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), number.get(), kCFPreferencesCurrentApplication); -} - -void WebPreferences::platformUpdateFloatValueForKey(const String& key, float value) -{ - if (!m_identifier) - return; - - RetainPtr<CFNumberRef> number = adoptCF(CFNumberCreate(0, kCFNumberFloatType, &value)); - CFPreferencesSetAppValue(makeKey(m_identifier, key).get(), number.get(), kCFPreferencesCurrentApplication); -} - -} // namespace WebKit - -#endif // !PLATFORM(MAC) diff --git a/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp b/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp deleted file mode 100644 index 52b14eb12..000000000 --- a/Source/WebKit2/UIProcess/efl/BatteryProvider.cpp +++ /dev/null @@ -1,98 +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 "BatteryProvider.h" - -#if ENABLE(BATTERY_STATUS) - -#include "WKAPICast.h" -#include "WKBatteryManager.h" -#include "WKBatteryStatus.h" - -using namespace WebCore; -using namespace WebKit; - -static inline BatteryProvider* toBatteryProvider(const void* clientInfo) -{ - return static_cast<BatteryProvider*>(const_cast<void*>(clientInfo)); -} - -static void startUpdatingCallback(WKBatteryManagerRef, const void* clientInfo) -{ - toBatteryProvider(clientInfo)->startUpdating(); -} - -static void stopUpdatingCallback(WKBatteryManagerRef, const void* clientInfo) -{ - toBatteryProvider(clientInfo)->stopUpdating(); -} - -BatteryProvider::~BatteryProvider() -{ - m_provider.stopUpdating(); - - WKBatteryManagerSetProvider(m_batteryManager.get(), 0); -} - -PassRefPtr<BatteryProvider> BatteryProvider::create(WKContextRef context) -{ - ASSERT(context); - return adoptRef(new BatteryProvider(context)); -} - -BatteryProvider::BatteryProvider(WKContextRef context) - : m_batteryManager(WKContextGetBatteryManager(context)) - , m_provider(this) -{ - ASSERT(m_batteryManager); - - WKBatteryProvider wkBatteryProvider = { - kWKBatteryProviderCurrentVersion, - this, // clientInfo - startUpdatingCallback, - stopUpdatingCallback - }; - - WKBatteryManagerSetProvider(m_batteryManager.get(), &wkBatteryProvider); -} - -void BatteryProvider::startUpdating() -{ - m_provider.startUpdating(); -} - -void BatteryProvider::stopUpdating() -{ - m_provider.stopUpdating(); -} - -void BatteryProvider::didChangeBatteryStatus(const AtomicString& eventType, PassRefPtr<BatteryStatus> status) -{ - WKRetainPtr<WKBatteryStatusRef> wkBatteryStatus = adoptWK(WKBatteryStatusCreate(status->charging(), status->chargingTime(), status->dischargingTime(), status->level())); - - WKBatteryManagerProviderDidChangeBatteryStatus(m_batteryManager.get(), toAPI(eventType.impl()), wkBatteryStatus.get()); -} -#endif // ENABLE(BATTERY_STATUS) diff --git a/Source/WebKit2/UIProcess/efl/BatteryProvider.h b/Source/WebKit2/UIProcess/efl/BatteryProvider.h deleted file mode 100644 index 893d0f8ea..000000000 --- a/Source/WebKit2/UIProcess/efl/BatteryProvider.h +++ /dev/null @@ -1,62 +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 BatteryProvider_h -#define BatteryProvider_h - -#if ENABLE(BATTERY_STATUS) - -#include "BatteryProviderEfl.h" -#include "BatteryProviderEflClient.h" -#include "BatteryStatus.h" -#include <WebKit2/WKBase.h> -#include <WebKit2/WKRetainPtr.h> -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -class BatteryProvider : public RefCounted<BatteryProvider>, public WebCore::BatteryProviderEflClient { -public: - virtual ~BatteryProvider(); - static PassRefPtr<BatteryProvider> create(WKContextRef); - - void startUpdating(); - void stopUpdating(); - -private: - explicit BatteryProvider(WKContextRef); - - // BatteryProviderEflClient interface. - virtual void didChangeBatteryStatus(const AtomicString& eventType, PassRefPtr<WebCore::BatteryStatus>); - - WKRetainPtr<WKBatteryManagerRef> m_batteryManager; - WebCore::BatteryProviderEfl m_provider; -}; - -} // namespace WebKit - -#endif // ENABLE(BATTERY_STATUS) - -#endif // BatteryProvider_h diff --git a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp deleted file mode 100644 index 2cc4b3013..000000000 --- a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.cpp +++ /dev/null @@ -1,149 +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 "ContextHistoryClientEfl.h" - -#include "EwkView.h" -#include "WKAPICast.h" -#include "WKContext.h" -#include "WKEinaSharedString.h" -#include "WKString.h" -#include "ewk_context_private.h" -#include "ewk_navigation_data.h" -#include "ewk_navigation_data_private.h" -#include "ewk_url_response.h" -#include "ewk_url_response_private.h" - -namespace WebKit { - -static inline const ContextHistoryClientEfl* toContextHistoryClientEfl(const void* clientInfo) -{ - ASSERT(clientInfo); - return static_cast<const ContextHistoryClientEfl*>(clientInfo); -} - -void ContextHistoryClientEfl::didNavigateWithNavigationData(WKContextRef, WKPageRef page, WKNavigationDataRef navigationData, WKFrameRef, const void* clientInfo) -{ - const ContextHistoryClientEfl* historyClient = toContextHistoryClientEfl(clientInfo); - - if (!historyClient->m_navigate) - return; - - RefPtr<EwkNavigationData> navigationDataEwk = EwkNavigationData::create(navigationData); - historyClient->m_navigate(EwkView::toEvasObject(page), navigationDataEwk.get(), historyClient->m_userData); -} - -void ContextHistoryClientEfl::didPerformClientRedirect(WKContextRef, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef, const void* clientInfo) -{ - const ContextHistoryClientEfl* historyClient = toContextHistoryClientEfl(clientInfo); - - if (!historyClient->m_clientRedirect) - return; - - WKEinaSharedString sourceURLString(sourceURL); - WKEinaSharedString destinationURLString(destinationURL); - - historyClient->m_clientRedirect(EwkView::toEvasObject(page), sourceURLString, destinationURLString, historyClient->m_userData); -} - -void ContextHistoryClientEfl::didPerformServerRedirect(WKContextRef, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef, const void* clientInfo) -{ - const ContextHistoryClientEfl* historyClient = toContextHistoryClientEfl(clientInfo); - - if (!historyClient->m_serverRedirect) - return; - - WKEinaSharedString sourceURLString(sourceURL); - WKEinaSharedString destinationURLString(destinationURL); - - historyClient->m_serverRedirect(EwkView::toEvasObject(page), sourceURLString, destinationURLString, historyClient->m_userData); -} - -void ContextHistoryClientEfl::didUpdateHistoryTitle(WKContextRef, WKPageRef page, WKStringRef title, WKURLRef URL, WKFrameRef, const void* clientInfo) -{ - const ContextHistoryClientEfl* historyClient = toContextHistoryClientEfl(clientInfo); - - if (!historyClient->m_titleUpdated) - return; - - WKEinaSharedString titleString(title); - WKEinaSharedString stringURL(URL); - - historyClient->m_titleUpdated(EwkView::toEvasObject(page), titleString, stringURL, historyClient->m_userData); -} - -void ContextHistoryClientEfl::populateVisitedLinks(WKContextRef, const void* clientInfo) -{ - const ContextHistoryClientEfl* historyClient = toContextHistoryClientEfl(clientInfo); - - if (!historyClient->m_populateVisitedLinks) - return; - - historyClient->m_populateVisitedLinks(historyClient->m_userData); -} - -ContextHistoryClientEfl::ContextHistoryClientEfl(WKContextRef context) - : m_context(context) - , m_userData(0) - , m_navigate(0) - , m_clientRedirect(0) - , m_serverRedirect(0) - , m_titleUpdated(0) - , m_populateVisitedLinks(0) -{ - ASSERT(m_context); - - WKContextHistoryClient wkHistoryClient; - memset(&wkHistoryClient, 0, sizeof(WKContextHistoryClient)); - - wkHistoryClient.version = kWKContextHistoryClientCurrentVersion; - wkHistoryClient.clientInfo = this; - - wkHistoryClient.didNavigateWithNavigationData = didNavigateWithNavigationData; - wkHistoryClient.didPerformClientRedirect = didPerformClientRedirect; - wkHistoryClient.didPerformServerRedirect = didPerformServerRedirect; - wkHistoryClient.didUpdateHistoryTitle = didUpdateHistoryTitle; - wkHistoryClient.populateVisitedLinks = populateVisitedLinks; - - WKContextSetHistoryClient(m_context.get(), &wkHistoryClient); -} - -ContextHistoryClientEfl::~ContextHistoryClientEfl() -{ - WKContextSetHistoryClient(m_context.get(), 0); -} - -void ContextHistoryClientEfl::setCallbacks(Ewk_History_Navigation_Cb navigate, Ewk_History_Client_Redirection_Cb clientRedirect, Ewk_History_Server_Redirection_Cb serverRedirect, Ewk_History_Title_Update_Cb titleUpdate, Ewk_History_Populate_Visited_Links_Cb populateVisitedLinks, void* data) -{ - m_navigate = navigate; - m_clientRedirect = clientRedirect; - m_serverRedirect = serverRedirect; - m_titleUpdated = titleUpdate; - m_populateVisitedLinks = populateVisitedLinks; - m_userData = data; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h b/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h deleted file mode 100644 index ffebfab28..000000000 --- a/Source/WebKit2/UIProcess/efl/ContextHistoryClientEfl.h +++ /dev/null @@ -1,67 +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 ContextHistoryClientEfl_h -#define ContextHistoryClientEfl_h - -#include "ewk_context.h" -#include <WebKit2/WKBase.h> -#include <WebKit2/WKRetainPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebKit { - -class ContextHistoryClientEfl { -public: - static PassOwnPtr<ContextHistoryClientEfl> create(WKContextRef context) - { - return adoptPtr(new ContextHistoryClientEfl(context)); - } - - ~ContextHistoryClientEfl(); - - void setCallbacks(Ewk_History_Navigation_Cb, Ewk_History_Client_Redirection_Cb, Ewk_History_Server_Redirection_Cb, Ewk_History_Title_Update_Cb, Ewk_History_Populate_Visited_Links_Cb, void*); - -private: - explicit ContextHistoryClientEfl(WKContextRef); - - static void didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef, WKFrameRef, const void*); - static void didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef, WKFrameRef, const void*); - static void didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef, WKFrameRef, const void*); - static void didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef, WKURLRef, WKFrameRef, const void*); - static void populateVisitedLinks(WKContextRef, const void*); - - WKRetainPtr<WKContextRef> m_context; - void* m_userData; - Ewk_History_Navigation_Cb m_navigate; - Ewk_History_Client_Redirection_Cb m_clientRedirect; - Ewk_History_Server_Redirection_Cb m_serverRedirect; - Ewk_History_Title_Update_Cb m_titleUpdated; - Ewk_History_Populate_Visited_Links_Cb m_populateVisitedLinks; -}; - -} // namespace WebKit - -#endif // ContextHistoryClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp deleted file mode 100644 index 16ca07d3e..000000000 --- a/Source/WebKit2/UIProcess/efl/ContextMenuClientEfl.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2012 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 "ContextMenuClientEfl.h" - -#include "EwkView.h" -#include "WKArray.h" -#include "WKPage.h" - -using namespace WebKit; - -static inline ContextMenuClientEfl* toContextClientEfl(const void* clientInfo) -{ - return static_cast<ContextMenuClientEfl*>(const_cast<void*>(clientInfo)); -} - -static void customContextMenuItemSelected(WKPageRef, WKContextMenuItemRef contextMenuItem, const void* clientInfo) -{ - toContextClientEfl(clientInfo)->view()->customContextMenuItemSelected(contextMenuItem); -} - -static void showContextMenu(WKPageRef, WKPoint menuLocation, WKArrayRef menuItems, const void* clientInfo) -{ - toContextClientEfl(clientInfo)->view()->showContextMenu(menuLocation, menuItems); -} - -static void hideContextMenu(WKPageRef, const void* clientInfo) -{ - toContextClientEfl(clientInfo)->view()->hideContextMenu(); -} - -ContextMenuClientEfl::ContextMenuClientEfl(EwkView* view) - : m_view(view) -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKPageContextMenuClient contextMenuClient; - memset(&contextMenuClient, 0, sizeof(WKPageContextMenuClient)); - contextMenuClient.version = kWKPageContextMenuClientCurrentVersion; - contextMenuClient.clientInfo = this; - contextMenuClient.getContextMenuFromProposedMenu_deprecatedForUseWithV0 = 0; - contextMenuClient.customContextMenuItemSelected = customContextMenuItemSelected; - contextMenuClient.contextMenuDismissed = 0; - contextMenuClient.getContextMenuFromProposedMenu = 0; - contextMenuClient.showContextMenu = showContextMenu; - contextMenuClient.hideContextMenu = hideContextMenu; - - WKPageSetPageContextMenuClient(pageRef, &contextMenuClient); -} - diff --git a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp b/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp deleted file mode 100644 index 0ae172a71..000000000 --- a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.cpp +++ /dev/null @@ -1,164 +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 "DownloadManagerEfl.h" - -#include "EwkView.h" -#include "WKContext.h" -#include "WKDownload.h" -#include "WKString.h" -#include "ewk_context_private.h" -#include "ewk_error_private.h" -#include "ewk_view.h" - -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline DownloadManagerEfl* toDownloadManagerEfl(const void* clientInfo) -{ - return static_cast<DownloadManagerEfl*>(const_cast<void*>(clientInfo)); -} - -WKStringRef DownloadManagerEfl::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef wkDownload, WKStringRef filename, bool* /*allowOverwrite*/, const void* clientInfo) -{ - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); - ASSERT(download); - - download->setSuggestedFileName(toImpl(filename)->string().utf8().data()); - - // We send the new download signal on the Ewk_View only once we have received the response - // and the suggested file name. - download->view()->smartCallback<DownloadJobRequested>().call(download); - - // DownloadSoup expects the destination to be a URL. - String destination = ASCIILiteral("file://") + String::fromUTF8(download->destination()); - - return WKStringCreateWithUTF8CString(destination.utf8().data()); -} - -void DownloadManagerEfl::didReceiveResponse(WKContextRef, WKDownloadRef wkDownload, WKURLResponseRef wkResponse, const void* clientInfo) -{ - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); - ASSERT(download); - download->setResponse(EwkUrlResponse::create(wkResponse)); -} - -void DownloadManagerEfl::didCreateDestination(WKContextRef, WKDownloadRef wkDownload, WKStringRef /*path*/, const void* clientInfo) -{ - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); - ASSERT(download); - - download->setState(EWK_DOWNLOAD_JOB_STATE_DOWNLOADING); -} - -void DownloadManagerEfl::didReceiveData(WKContextRef, WKDownloadRef wkDownload, uint64_t length, const void* clientInfo) -{ - EwkDownloadJob* download = toDownloadManagerEfl(clientInfo)->ewkDownloadJob(wkDownload); - ASSERT(download); - download->incrementReceivedData(length); -} - -void DownloadManagerEfl::didFail(WKContextRef, WKDownloadRef wkDownload, WKErrorRef error, const void* clientInfo) -{ - DownloadManagerEfl* downloadManager = toDownloadManagerEfl(clientInfo); - EwkDownloadJob* download = downloadManager->ewkDownloadJob(wkDownload); - ASSERT(download); - - OwnPtr<EwkError> ewkError = EwkError::create(error); - download->setState(EWK_DOWNLOAD_JOB_STATE_FAILED); - Ewk_Download_Job_Error downloadError = { download, ewkError.get() }; - download->view()->smartCallback<DownloadJobFailed>().call(&downloadError); - downloadManager->unregisterDownloadJob(wkDownload); -} - -void DownloadManagerEfl::didCancel(WKContextRef, WKDownloadRef wkDownload, const void* clientInfo) -{ - DownloadManagerEfl* downloadManager = toDownloadManagerEfl(clientInfo); - EwkDownloadJob* download = downloadManager->ewkDownloadJob(wkDownload); - ASSERT(download); - - download->setState(EWK_DOWNLOAD_JOB_STATE_CANCELLED); - download->view()->smartCallback<DownloadJobCancelled>().call(download); - downloadManager->unregisterDownloadJob(wkDownload); -} - -void DownloadManagerEfl::didFinish(WKContextRef, WKDownloadRef wkDownload, const void* clientInfo) -{ - DownloadManagerEfl* downloadManager = toDownloadManagerEfl(clientInfo); - EwkDownloadJob* download = downloadManager->ewkDownloadJob(wkDownload); - ASSERT(download); - - download->setState(EWK_DOWNLOAD_JOB_STATE_FINISHED); - download->view()->smartCallback<DownloadJobFinished>().call(download); - downloadManager->unregisterDownloadJob(wkDownload); -} - -DownloadManagerEfl::DownloadManagerEfl(WKContextRef context) - : m_context(context) -{ - WKContextDownloadClient wkDownloadClient; - memset(&wkDownloadClient, 0, sizeof(WKContextDownloadClient)); - - wkDownloadClient.version = kWKContextDownloadClientCurrentVersion; - wkDownloadClient.clientInfo = this; - wkDownloadClient.didCancel = didCancel; - wkDownloadClient.decideDestinationWithSuggestedFilename = decideDestinationWithSuggestedFilename; - wkDownloadClient.didCreateDestination = didCreateDestination; - wkDownloadClient.didReceiveResponse = didReceiveResponse; - wkDownloadClient.didReceiveData = didReceiveData; - wkDownloadClient.didFail = didFail; - wkDownloadClient.didFinish = didFinish; - - WKContextSetDownloadClient(m_context.get(), &wkDownloadClient); -} - -DownloadManagerEfl::~DownloadManagerEfl() -{ - WKContextSetDownloadClient(m_context.get(), 0); -} - -void DownloadManagerEfl::registerDownloadJob(WKDownloadRef download, EwkView* viewImpl) -{ - uint64_t downloadId = WKDownloadGetID(download); - if (m_downloadJobs.contains(downloadId)) - return; - - RefPtr<EwkDownloadJob> ewkDownload = EwkDownloadJob::create(download, viewImpl); - m_downloadJobs.add(downloadId, ewkDownload); -} - -EwkDownloadJob* DownloadManagerEfl::ewkDownloadJob(WKDownloadRef wkDownload) -{ - return m_downloadJobs.get(WKDownloadGetID(wkDownload)); -} - -void DownloadManagerEfl::unregisterDownloadJob(WKDownloadRef wkDownload) -{ - m_downloadJobs.remove(WKDownloadGetID(wkDownload)); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.h b/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.h deleted file mode 100644 index 0317a9d86..000000000 --- a/Source/WebKit2/UIProcess/efl/DownloadManagerEfl.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 DownloadManagerEfl_h -#define DownloadManagerEfl_h - -#include "ewk_download_job_private.h" -#include <WebKit2/WKRetainPtr.h> -#include <wtf/HashMap.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/RefPtr.h> - -namespace WebKit { - -class DownloadManagerEfl { -public: - static PassOwnPtr<DownloadManagerEfl> create(WKContextRef context) - { - return adoptPtr(new DownloadManagerEfl(context)); - } - - ~DownloadManagerEfl(); - - void registerDownloadJob(WKDownloadRef, EwkView*); - -private: - explicit DownloadManagerEfl(WKContextRef); - - EwkDownloadJob* ewkDownloadJob(WKDownloadRef); - void unregisterDownloadJob(WKDownloadRef); - - static WKStringRef decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool* allowOverwrite, const void* clientInfo); - static void didReceiveResponse(WKContextRef, WKDownloadRef, WKURLResponseRef, const void* clientInfo); - static void didCreateDestination(WKContextRef, WKDownloadRef, WKStringRef path, const void* clientInfo); - static void didReceiveData(WKContextRef, WKDownloadRef, uint64_t length, const void* clientInfo); - static void didFail(WKContextRef, WKDownloadRef, WKErrorRef, const void* clientInfo); - static void didCancel(WKContextRef, WKDownloadRef, const void* clientInfo); - static void didFinish(WKContextRef, WKDownloadRef, const void* clientInfo); - - WKRetainPtr<WKContextRef> m_context; - HashMap<uint64_t, RefPtr<EwkDownloadJob> > m_downloadJobs; -}; - -} // namespace WebKit - -#endif // DownloadManagerEfl_h diff --git a/Source/WebKit2/UIProcess/efl/EwkTouchPoint.h b/Source/WebKit2/UIProcess/efl/EwkTouchPoint.h deleted file mode 100644 index 943bcbbd1..000000000 --- a/Source/WebKit2/UIProcess/efl/EwkTouchPoint.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef EwkTouchPoint_h -#define EwkTouchPoint_h - -#if ENABLE(TOUCH_EVENTS) - -#include "APIObject.h" -#include "WKArray.h" -#include "WKEventEfl.h" -#include "WKRetainPtr.h" -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -class EwkTouchPoint : public APIObject { -public: - static const APIObject::Type APIType = TypeTouchPoint; - - static PassRefPtr<EwkTouchPoint> create(uint32_t id, WKTouchPointState state, const WKPoint& screenPosition, const WKPoint& position, const WKSize& radius, float rotationAngle = 0, float forceFactor = 1) - { - return adoptRef(new EwkTouchPoint(id, state, screenPosition, position, radius, rotationAngle, forceFactor)); - } - - uint32_t id() const { return m_id; } - WKTouchPointState state() const { return m_state; } - WKPoint screenPosition() const { return m_screenPosition; } - WKPoint position() const { return m_position; } - WKSize radius() const { return m_radius; } - float rotationAngle() const { return m_rotationAngle; } - float forceFactor() const { return m_forceFactor; } - -private: - EwkTouchPoint(uint32_t id, WKTouchPointState, const WKPoint&, const WKPoint&, const WKSize&, float rotationAngle, float forceFactor); - - virtual APIObject::Type type() const { return APIType; } - - uint32_t m_id; - WKTouchPointState m_state; - WKPoint m_screenPosition; - WKPoint m_position; - WKSize m_radius; - float m_rotationAngle; - float m_forceFactor; -}; - -} // namespace WebKit - -#endif // ENABLE(TOUCH_EVENTS) - -#endif /* EwkTouchPoint_h */ diff --git a/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp b/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp deleted file mode 100644 index 334b4b5bd..000000000 --- a/Source/WebKit2/UIProcess/efl/FindClientEfl.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * 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 "FindClientEfl.h" - -#include "EwkView.h" -#include "WKPage.h" - -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline FindClientEfl* toFindClientEfl(const void* clientInfo) -{ - return static_cast<FindClientEfl*>(const_cast<void*>(clientInfo)); -} - -void FindClientEfl::didFindString(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo) -{ - FindClientEfl* findClient = toFindClientEfl(clientInfo); - findClient->m_view->smartCallback<TextFound>().call(&matchCount); -} - -void FindClientEfl::didFailToFindString(WKPageRef, WKStringRef, const void* clientInfo) -{ - FindClientEfl* findClient = toFindClientEfl(clientInfo); - unsigned matchCount = 0; - findClient->m_view->smartCallback<TextFound>().call(&matchCount); -} - -FindClientEfl::FindClientEfl(EwkView* viewImpl) - : m_view(viewImpl) -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKPageFindClient findClient; - memset(&findClient, 0, sizeof(WKPageFindClient)); - findClient.version = kWKPageFindClientCurrentVersion; - findClient.clientInfo = this; - findClient.didFindString = didFindString; - findClient.didFailToFindString = didFailToFindString; - findClient.didCountStringMatches = didFindString; - WKPageSetPageFindClient(pageRef, &findClient); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/FindClientEfl.h b/Source/WebKit2/UIProcess/efl/FindClientEfl.h deleted file mode 100644 index dd12e2f94..000000000 --- a/Source/WebKit2/UIProcess/efl/FindClientEfl.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * 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 FindClientEfl_h -#define FindClientEfl_h - -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class FindClientEfl { -public: - static PassOwnPtr<FindClientEfl> create(EwkView* viewImpl) - { - return adoptPtr(new FindClientEfl(viewImpl)); - } - -private: - explicit FindClientEfl(EwkView*); - - static void didFindString(WKPageRef, WKStringRef, unsigned matchCount, const void* clientInfo); - static void didFailToFindString(WKPageRef, WKStringRef, const void* clientInfo); - - EwkView* m_view; -}; - -} // namespace WebKit - -#endif // FindClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp b/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp deleted file mode 100644 index 155bea22c..000000000 --- a/Source/WebKit2/UIProcess/efl/FormClientEfl.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2012 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "FormClientEfl.h" - -#include "EwkView.h" -#include "WKPage.h" -#include "ewk_form_submission_request_private.h" - -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline FormClientEfl* toFormClientEfl(const void* clientInfo) -{ - return static_cast<FormClientEfl*>(const_cast<void*>(clientInfo)); -} - -void FormClientEfl::willSubmitForm(WKPageRef, WKFrameRef /*frame*/, WKFrameRef /*sourceFrame*/, WKDictionaryRef values, WKTypeRef /*userData*/, WKFormSubmissionListenerRef listener, const void* clientInfo) -{ - FormClientEfl* formClient = toFormClientEfl(clientInfo); - - RefPtr<EwkFormSubmissionRequest> request = EwkFormSubmissionRequest::create(values, listener); - formClient->m_view->smartCallback<NewFormSubmissionRequest>().call(request.get()); -} - -FormClientEfl::FormClientEfl(EwkView* viewImpl) - : m_view(viewImpl) -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKPageFormClient formClient; - memset(&formClient, 0, sizeof(WKPageFormClient)); - formClient.version = kWKPageFormClientCurrentVersion; - formClient.clientInfo = this; - formClient.willSubmitForm = willSubmitForm; - WKPageSetPageFormClient(pageRef, &formClient); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp b/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp deleted file mode 100644 index 87df14208..000000000 --- a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.cpp +++ /dev/null @@ -1,133 +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 "InputMethodContextEfl.h" - -#include "EwkView.h" -#include "WebPageProxy.h" -#include <Ecore_Evas.h> -#include <Ecore_IMF_Evas.h> -#include <WebCore/Editor.h> - -using namespace WebCore; - -namespace WebKit { - -InputMethodContextEfl::InputMethodContextEfl(EwkView* view, PassOwnPtr<Ecore_IMF_Context> context) - : m_view(view) - , m_context(context) - , m_focused(false) -{ - ASSERT(m_context); - ecore_imf_context_event_callback_add(m_context.get(), ECORE_IMF_CALLBACK_PREEDIT_CHANGED, onIMFPreeditSequenceChanged, this); - ecore_imf_context_event_callback_add(m_context.get(), ECORE_IMF_CALLBACK_COMMIT, onIMFInputSequenceComplete, this); -} - -InputMethodContextEfl::~InputMethodContextEfl() -{ -} - -void InputMethodContextEfl::onIMFInputSequenceComplete(void* data, Ecore_IMF_Context*, void* eventInfo) -{ - InputMethodContextEfl* inputMethodContext = static_cast<InputMethodContextEfl*>(data); - if (!eventInfo || !inputMethodContext->m_focused) - return; - - inputMethodContext->m_view->page()->confirmComposition(String::fromUTF8(static_cast<char*>(eventInfo))); -} - -void InputMethodContextEfl::onIMFPreeditSequenceChanged(void* data, Ecore_IMF_Context* context, void*) -{ - InputMethodContextEfl* inputMethodContext = static_cast<InputMethodContextEfl*>(data); - - if (!inputMethodContext->m_view->page()->focusedFrame() || !inputMethodContext->m_focused) - return; - - char* buffer = 0; - ecore_imf_context_preedit_string_get(context, &buffer, 0); - if (!buffer) - return; - - String preeditString = String::fromUTF8(buffer); - free(buffer); - Vector<CompositionUnderline> underlines; - underlines.append(CompositionUnderline(0, preeditString.length(), Color(0, 0, 0), false)); - inputMethodContext->m_view->page()->setComposition(preeditString, underlines, 0); -} - -PassOwnPtr<Ecore_IMF_Context> InputMethodContextEfl::createIMFContext(Evas* canvas) -{ - const char* defaultContextID = ecore_imf_context_default_id_get(); - if (!defaultContextID) - return nullptr; - - OwnPtr<Ecore_IMF_Context> imfContext = adoptPtr(ecore_imf_context_add(defaultContextID)); - if (!imfContext) - return nullptr; - - Ecore_Evas* ecoreEvas = ecore_evas_ecore_evas_get(canvas); - ecore_imf_context_client_window_set(imfContext.get(), reinterpret_cast<void*>(ecore_evas_window_get(ecoreEvas))); - ecore_imf_context_client_canvas_set(imfContext.get(), canvas); - - return imfContext.release(); -} - -void InputMethodContextEfl::handleMouseUpEvent(const Evas_Event_Mouse_Up*) -{ - ecore_imf_context_reset(m_context.get()); -} - -void InputMethodContextEfl::handleKeyDownEvent(const Evas_Event_Key_Down* downEvent, bool* isFiltered) -{ - Ecore_IMF_Event inputMethodEvent; - ecore_imf_evas_event_key_down_wrap(const_cast<Evas_Event_Key_Down*>(downEvent), &inputMethodEvent.key_down); - - *isFiltered = ecore_imf_context_filter_event(m_context.get(), ECORE_IMF_EVENT_KEY_DOWN, &inputMethodEvent); -} - -void InputMethodContextEfl::updateTextInputState() -{ - if (!m_context) - return; - - const EditorState& editor = m_view->page()->editorState(); - - if (editor.isContentEditable) { - if (m_focused) - return; - - ecore_imf_context_reset(m_context.get()); - ecore_imf_context_focus_in(m_context.get()); - m_focused = true; - } else { - if (!m_focused) - return; - - if (editor.hasComposition) - m_view->page()->cancelComposition(); - - m_focused = false; - ecore_imf_context_reset(m_context.get()); - ecore_imf_context_focus_out(m_context.get()); - } -} - -} diff --git a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h b/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h deleted file mode 100644 index 12de0acaa..000000000 --- a/Source/WebKit2/UIProcess/efl/InputMethodContextEfl.h +++ /dev/null @@ -1,65 +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. - */ - -#ifndef InputMethodContextEfl_h -#define InputMethodContextEfl_h - -#include <Ecore_IMF.h> -#include <Evas.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class WebPageProxy; - -class InputMethodContextEfl { -public: - static PassOwnPtr<InputMethodContextEfl> create(EwkView* viewImpl, Evas* canvas) - { - OwnPtr<Ecore_IMF_Context> context = createIMFContext(canvas); - if (!context) - return nullptr; - - return adoptPtr(new InputMethodContextEfl(viewImpl, context.release())); - } - ~InputMethodContextEfl(); - - void handleMouseUpEvent(const Evas_Event_Mouse_Up* upEvent); - void handleKeyDownEvent(const Evas_Event_Key_Down* downEvent, bool* isFiltered); - void updateTextInputState(); - -private: - InputMethodContextEfl(EwkView*, PassOwnPtr<Ecore_IMF_Context>); - - static PassOwnPtr<Ecore_IMF_Context> createIMFContext(Evas* canvas); - static void onIMFInputSequenceComplete(void* data, Ecore_IMF_Context*, void* eventInfo); - static void onIMFPreeditSequenceChanged(void* data, Ecore_IMF_Context*, void* eventInfo); - - EwkView* m_view; - OwnPtr<Ecore_IMF_Context> m_context; - bool m_focused; -}; - -} // namespace WebKit - -#endif // InputMethodContextEfl_h diff --git a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp b/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp deleted file mode 100644 index de7f05f53..000000000 --- a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.cpp +++ /dev/null @@ -1,121 +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 "NetworkInfoProvider.h" - -#if ENABLE(NETWORK_INFO) - -#include "WKNetworkInfoManager.h" -#include <NotImplemented.h> - -using namespace WebKit; - -static inline NetworkInfoProvider* toNetworkInfoProvider(const void* clientInfo) -{ - return static_cast<NetworkInfoProvider*>(const_cast<void*>(clientInfo)); -} - -static void startUpdatingCallback(WKNetworkInfoManagerRef, const void* clientInfo) -{ - toNetworkInfoProvider(clientInfo)->startUpdating(); -} - -static void stopUpdatingCallback(WKNetworkInfoManagerRef, const void* clientInfo) -{ - toNetworkInfoProvider(clientInfo)->stopUpdating(); -} - -static double getBandwidthCallback(WKNetworkInfoManagerRef, const void* clientInfo) -{ - return toNetworkInfoProvider(clientInfo)->bandwidth(); -} - -static bool isMeteredCallback(WKNetworkInfoManagerRef, const void* clientInfo) -{ - return toNetworkInfoProvider(clientInfo)->metered(); -} - -PassRefPtr<NetworkInfoProvider> NetworkInfoProvider::create(WKContextRef context) -{ - return adoptRef(new NetworkInfoProvider(context)); -} - -NetworkInfoProvider::NetworkInfoProvider(WKContextRef context) - : m_context(context) -{ - ASSERT(m_context); - - WKNetworkInfoManagerRef wkNetworkInfoManager = WKContextGetNetworkInfoManager(m_context.get()); - ASSERT(wkNetworkInfoManager); - - WKNetworkInfoProvider wkNetworkInfoProvider = { - kWKNetworkInfoProviderCurrentVersion, - this, // clientInfo - startUpdatingCallback, - stopUpdatingCallback, - getBandwidthCallback, - isMeteredCallback - }; - - WKNetworkInfoManagerSetProvider(wkNetworkInfoManager, &wkNetworkInfoProvider); -} - -NetworkInfoProvider::~NetworkInfoProvider() -{ - WKNetworkInfoManagerRef wkNetworkInfoManager = WKContextGetNetworkInfoManager(m_context.get()); - ASSERT(wkNetworkInfoManager); - - WKNetworkInfoManagerSetProvider(wkNetworkInfoManager, 0); -} - -void NetworkInfoProvider::networkInfoControllerDestroyed() -{ - delete this; -} - -double NetworkInfoProvider::bandwidth() const -{ - return m_provider.bandwidth(); -} - -bool NetworkInfoProvider::metered() const -{ - notImplemented(); - - return false; -} - -void NetworkInfoProvider::startUpdating() -{ - m_provider.startUpdating(); -} - -void NetworkInfoProvider::stopUpdating() -{ - m_provider.stopUpdating(); -} - -#endif // ENABLE(NETWORK_INFO) diff --git a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h b/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h deleted file mode 100644 index bf72384aa..000000000 --- a/Source/WebKit2/UIProcess/efl/NetworkInfoProvider.h +++ /dev/null @@ -1,65 +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 NetworkInfoProvider_h -#define NetworkInfoProvider_h - -#if ENABLE(NETWORK_INFO) - -#include <NetworkInfoClient.h> -#include <NetworkInfoProviderEfl.h> -#include <WebKit2/WKBase.h> -#include <WebKit2/WKContext.h> -#include <WebKit2/WKRetainPtr.h> -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -class NetworkInfoProvider : public RefCounted<NetworkInfoProvider>, public WebCore::NetworkInfoClient { -public: - virtual ~NetworkInfoProvider(); - static PassRefPtr<NetworkInfoProvider> create(WKContextRef); - - // NetworkInfoClient interface. - virtual void networkInfoControllerDestroyed(); - - virtual double bandwidth() const; - virtual bool metered() const; - - virtual void startUpdating(); - virtual void stopUpdating(); - -private: - explicit NetworkInfoProvider(WKContextRef); - - WKRetainPtr<WKContextRef> m_context; - WebCore::NetworkInfoProviderEfl m_provider; -}; - -} // namespace WebKit - -#endif // ENABLE(NETWORK_INFO) - -#endif // NetworkInfoProvider_h diff --git a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp deleted file mode 100644 index 8b961fb9c..000000000 --- a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp +++ /dev/null @@ -1,185 +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 "PageLoadClientEfl.h" - -#include "EwkView.h" -#include "PageViewportController.h" -#include "WKAPICast.h" -#include "WKFrame.h" -#include "WKPage.h" -#include "ewk_auth_request_private.h" -#include "ewk_back_forward_list_private.h" -#include "ewk_error_private.h" -#include "ewk_view.h" - -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline PageLoadClientEfl* toPageLoadClientEfl(const void* clientInfo) -{ - return static_cast<PageLoadClientEfl*>(const_cast<void*>(clientInfo)); -} - -void PageLoadClientEfl::didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - view->smartCallback<TitleChange>().call(toImpl(title)->string()); -} - -void PageLoadClientEfl::didChangeProgress(WKPageRef page, const void* clientInfo) -{ - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - double progress = WKPageGetEstimatedProgress(page); - view->smartCallback<LoadProgress>().call(&progress); -} - -void PageLoadClientEfl::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - view->smartCallback<LoadFinished>().call(); -} - -void PageLoadClientEfl::didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - OwnPtr<EwkError> ewkError = EwkError::create(error); - view->smartCallback<LoadError>().call(ewkError.get()); - view->smartCallback<LoadFinished>().call(); -} - -void PageLoadClientEfl::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - view->informURLChange(); - view->smartCallback<ProvisionalLoadStarted>().call(); -} - -void PageLoadClientEfl::didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - view->informURLChange(); - view->smartCallback<ProvisionalLoadRedirect>().call(); -} - -void PageLoadClientEfl::didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - OwnPtr<EwkError> ewkError = EwkError::create(error); - view->smartCallback<ProvisionalLoadFailed>().call(ewkError.get()); -} - -void PageLoadClientEfl::didCommitLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - if (WKPageUseFixedLayout(view->wkPage())) { -#if USE(ACCELERATED_COMPOSITING) - view->pageViewportController()->didCommitLoad(); -#endif - return; - } - - view->scheduleUpdateDisplay(); -} - -void PageLoadClientEfl::didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void* clientInfo) -{ - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - ASSERT(view); - - Ewk_Back_Forward_List* list = ewk_view_back_forward_list_get(view->evasObject()); - ASSERT(list); - list->update(addedItem, removedItems); - - view->smartCallback<BackForwardListChange>().call(); -} - -void PageLoadClientEfl::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef frame, WKSameDocumentNavigationType, WKTypeRef, const void* clientInfo) -{ - if (!WKFrameIsMainFrame(frame)) - return; - - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - view->informURLChange(); -} - -void PageLoadClientEfl::didReceiveAuthenticationChallengeInFrame(WKPageRef, WKFrameRef, WKAuthenticationChallengeRef authenticationChallenge, const void* clientInfo) -{ - EwkView* view = toPageLoadClientEfl(clientInfo)->view(); - - RefPtr<EwkAuthRequest> authenticationRequest = EwkAuthRequest::create(authenticationChallenge); - view->smartCallback<AuthenticationRequest>().call(authenticationRequest.get()); -} - -PageLoadClientEfl::PageLoadClientEfl(EwkView* view) - : m_view(view) -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKPageLoaderClient loadClient; - memset(&loadClient, 0, sizeof(WKPageLoaderClient)); - loadClient.version = kWKPageLoaderClientCurrentVersion; - loadClient.clientInfo = this; - loadClient.didReceiveTitleForFrame = didReceiveTitleForFrame; - loadClient.didStartProgress = didChangeProgress; - loadClient.didChangeProgress = didChangeProgress; - loadClient.didFinishProgress = didChangeProgress; - loadClient.didFinishLoadForFrame = didFinishLoadForFrame; - loadClient.didFailLoadWithErrorForFrame = didFailLoadWithErrorForFrame; - loadClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; - loadClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame; - loadClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame; - loadClient.didCommitLoadForFrame = didCommitLoadForFrame; - loadClient.didChangeBackForwardList = didChangeBackForwardList; - loadClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; - loadClient.didReceiveAuthenticationChallengeInFrame = didReceiveAuthenticationChallengeInFrame; - WKPageSetPageLoaderClient(pageRef, &loadClient); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h b/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h deleted file mode 100644 index cae1f84fc..000000000 --- a/Source/WebKit2/UIProcess/efl/PageLoadClientEfl.h +++ /dev/null @@ -1,66 +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 PageLoadClientEfl_h -#define PageLoadClientEfl_h - -#include "WKPageLoadTypes.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class PageLoadClientEfl { -public: - static PassOwnPtr<PageLoadClientEfl> create(EwkView* viewImpl) - { - return adoptPtr(new PageLoadClientEfl(viewImpl)); - } - -private: - explicit PageLoadClientEfl(EwkView*); - - inline EwkView* view() const { return m_view; } - - static void didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef, WKTypeRef, const void* clientInfo); - static void didChangeProgress(WKPageRef, const void* clientInfo); - static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); - static void didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef, WKErrorRef, WKTypeRef userData, const void* clientInfo); - static void didCommitLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef userData, const void* clientInfo); - static void didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void* clientInfo); - static void didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef, WKSameDocumentNavigationType, WKTypeRef, const void* clientInfo); - static void didReceiveAuthenticationChallengeInFrame(WKPageRef, WKFrameRef, WKAuthenticationChallengeRef, const void* clientInfo); - - EwkView* m_view; -}; - -} // namespace WebKit - -#endif // PageLoadClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp deleted file mode 100644 index ecda5cb52..000000000 --- a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.cpp +++ /dev/null @@ -1,120 +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 "PagePolicyClientEfl.h" - -#include "EwkView.h" -#include "WKFrame.h" -#include "WKFramePolicyListener.h" -#include "WKString.h" -#include "WKURLResponse.h" -#include "ewk_navigation_policy_decision.h" -#include "ewk_navigation_policy_decision_private.h" -#include <WebCore/HTTPStatusCodes.h> -#include <wtf/text/CString.h> - -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline PagePolicyClientEfl* toPagePolicyClientEfl(const void* clientInfo) -{ - return static_cast<PagePolicyClientEfl*>(const_cast<void*>(clientInfo)); -} - -void PagePolicyClientEfl::decidePolicyForNavigationAction(WKPageRef, WKFrameRef, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef /*userData*/, const void* clientInfo) -{ - PagePolicyClientEfl* policyClient = toPagePolicyClientEfl(clientInfo); - - RefPtr<EwkNavigationPolicyDecision> decision = EwkNavigationPolicyDecision::create(navigationType, mouseButton, modifiers, request, 0, listener); - policyClient->m_view->smartCallback<NavigationPolicyDecision>().call(decision.get()); -} - -void PagePolicyClientEfl::decidePolicyForNewWindowAction(WKPageRef, WKFrameRef, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKStringRef frameName, WKFramePolicyListenerRef listener, WKTypeRef /*userData*/, const void* clientInfo) -{ - PagePolicyClientEfl* policyClient = toPagePolicyClientEfl(clientInfo); - - RefPtr<EwkNavigationPolicyDecision> decision = EwkNavigationPolicyDecision::create(navigationType, mouseButton, modifiers, request, toImpl(frameName)->string().utf8().data(), listener); - policyClient->m_view->smartCallback<NewWindowPolicyDecision>().call(decision.get()); -} - -void PagePolicyClientEfl::decidePolicyForResponseCallback(WKPageRef, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef, WKFramePolicyListenerRef listener, WKTypeRef /*userData*/, const void* /*clientInfo*/) -{ - // Ignore responses with an HTTP status code of 204 (No Content) - if (WKURLResponseHTTPStatusCode(response) == WebCore::HTTPNoContent) { - WKFramePolicyListenerIgnore(listener); - return; - } - - // If the URL Response has "Content-Disposition: attachment;" header, then - // we should download it. - if (WKURLResponseIsAttachment(response)) { - WKFramePolicyListenerDownload(listener); - return; - } - - WKRetainPtr<WKStringRef> mimeType = adoptWK(WKURLResponseCopyMIMEType(response)); - bool canShowMIMEType = WKFrameCanShowMIMEType(frame, mimeType.get()); - if (WKFrameIsMainFrame(frame)) { - if (canShowMIMEType) { - WKFramePolicyListenerUse(listener); - return; - } - - // If we can't use (show) it then we should download it. - WKFramePolicyListenerDownload(listener); - return; - } - - // We should ignore downloadable top-level content for subframes, with an exception for text/xml and application/xml so we can still support Acid3 test. - // It makes the browser intentionally behave differently when it comes to text(application)/xml content in subframes vs. mainframe. - bool isXMLType = WKStringIsEqualToUTF8CString(mimeType.get(), "text/xml") || WKStringIsEqualToUTF8CString(mimeType.get(), "application/xml"); - if (!canShowMIMEType && !isXMLType) { - WKFramePolicyListenerIgnore(listener); - return; - } - - WKFramePolicyListenerUse(listener); -} - -PagePolicyClientEfl::PagePolicyClientEfl(EwkView* view) - : m_view(view) -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKPagePolicyClient policyClient; - memset(&policyClient, 0, sizeof(WKPagePolicyClient)); - policyClient.version = kWKPagePolicyClientCurrentVersion; - policyClient.clientInfo = this; - policyClient.decidePolicyForNavigationAction = decidePolicyForNavigationAction; - policyClient.decidePolicyForNewWindowAction = decidePolicyForNewWindowAction; - policyClient.decidePolicyForResponse = decidePolicyForResponseCallback; - - WKPageSetPagePolicyClient(pageRef, &policyClient); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h b/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h deleted file mode 100644 index 0d05b733b..000000000 --- a/Source/WebKit2/UIProcess/efl/PagePolicyClientEfl.h +++ /dev/null @@ -1,57 +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 PagePolicyClientEfl_h -#define PagePolicyClientEfl_h - -#include "WKEvent.h" -#include "WKPageLoadTypes.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class PagePolicyClientEfl { -public: - static PassOwnPtr<PagePolicyClientEfl> create(EwkView* view) - { - return adoptPtr(new PagePolicyClientEfl(view)); - } - -private: - explicit PagePolicyClientEfl(EwkView*); - - static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef, WKFramePolicyListenerRef, WKTypeRef, const void*); - static void decidePolicyForNewWindowAction(WKPageRef, WKFrameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef, WKStringRef, WKFramePolicyListenerRef, WKTypeRef, const void*); - static void decidePolicyForResponseCallback(WKPageRef, WKFrameRef, WKURLResponseRef, WKURLRequestRef, WKFramePolicyListenerRef, WKTypeRef, const void*); - - EwkView* m_view; -}; - -} // namespace WebKit - -#endif // PagePolicyClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp deleted file mode 100644 index 5488ea136..000000000 --- a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.cpp +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * 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 "PageUIClientEfl.h" - -#include "EwkView.h" -#include "WKAPICast.h" -#include "WKEvent.h" -#include "WKPageEfl.h" -#include "WKString.h" -#include "ewk_file_chooser_request_private.h" -#include "ewk_window_features_private.h" -#include <Ecore_Evas.h> -#include <WebCore/Color.h> - -using namespace EwkViewCallbacks; - -namespace WebKit { - -static inline PageUIClientEfl* toPageUIClientEfl(const void* clientInfo) -{ - return static_cast<PageUIClientEfl*>(const_cast<void*>(clientInfo)); -} - -PageUIClientEfl::PageUIClientEfl(EwkView* view) - : m_view(view) -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKPageUIClient uiClient; - memset(&uiClient, 0, sizeof(WKPageUIClient)); - uiClient.version = kWKPageUIClientCurrentVersion; - uiClient.clientInfo = this; - uiClient.close = close; - uiClient.takeFocus = takeFocus; - uiClient.focus = focus; - uiClient.unfocus = unfocus; - uiClient.runJavaScriptAlert = runJavaScriptAlert; - uiClient.runJavaScriptConfirm = runJavaScriptConfirm; - uiClient.runJavaScriptPrompt = runJavaScriptPrompt; - uiClient.toolbarsAreVisible = toolbarsAreVisible; - uiClient.setToolbarsAreVisible = setToolbarsAreVisible; - uiClient.menuBarIsVisible = menuBarIsVisible; - uiClient.setMenuBarIsVisible = setMenuBarIsVisible; - uiClient.statusBarIsVisible = statusBarIsVisible; - uiClient.setStatusBarIsVisible = setStatusBarIsVisible; - uiClient.isResizable = isResizable; - uiClient.setIsResizable = setIsResizable; - uiClient.getWindowFrame = getWindowFrame; - uiClient.setWindowFrame = setWindowFrame; - uiClient.runBeforeUnloadConfirmPanel = runBeforeUnloadConfirmPanel; -#if ENABLE(SQL_DATABASE) - uiClient.exceededDatabaseQuota = exceededDatabaseQuota; -#endif - uiClient.runOpenPanel = runOpenPanel; - uiClient.createNewPage = createNewPage; -#if ENABLE(INPUT_TYPE_COLOR) - uiClient.showColorPicker = showColorPicker; - uiClient.hideColorPicker = hideColorPicker; -#endif - - WKPageSetPageUIClient(pageRef, &uiClient); - - // Popup Menu UI client. - WKPageUIPopupMenuClient uiPopupMenuClient; - memset(&uiPopupMenuClient, 0, sizeof(WKPageUIPopupMenuClient)); - uiPopupMenuClient.version = kWKPageUIPopupMenuClientCurrentVersion; - uiPopupMenuClient.clientInfo = this; - uiPopupMenuClient.showPopupMenu = showPopupMenu; - uiPopupMenuClient.hidePopupMenu = hidePopupMenu; - WKPageSetUIPopupMenuClient(pageRef, &uiPopupMenuClient); -} - - -void PageUIClientEfl::close(WKPageRef, const void* clientInfo) -{ - toPageUIClientEfl(clientInfo)->m_view->close(); -} - -void PageUIClientEfl::takeFocus(WKPageRef, WKFocusDirection, const void* clientInfo) -{ - // FIXME: this is only a partial implementation. - evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_view->evasObject(), false); -} - -void PageUIClientEfl::focus(WKPageRef, const void* clientInfo) -{ - evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_view->evasObject(), true); -} - -void PageUIClientEfl::unfocus(WKPageRef, const void* clientInfo) -{ - evas_object_focus_set(toPageUIClientEfl(clientInfo)->m_view->evasObject(), false); -} - -void PageUIClientEfl::runJavaScriptAlert(WKPageRef, WKStringRef alertText, WKFrameRef, const void* clientInfo) -{ - toPageUIClientEfl(clientInfo)->m_view->requestJSAlertPopup(WKEinaSharedString(alertText)); -} - -bool PageUIClientEfl::runJavaScriptConfirm(WKPageRef, WKStringRef message, WKFrameRef, const void* clientInfo) -{ - return toPageUIClientEfl(clientInfo)->m_view->requestJSConfirmPopup(WKEinaSharedString(message)); -} - -WKStringRef PageUIClientEfl::runJavaScriptPrompt(WKPageRef, WKStringRef message, WKStringRef defaultValue, WKFrameRef, const void* clientInfo) -{ - WKEinaSharedString value = toPageUIClientEfl(clientInfo)->m_view->requestJSPromptPopup(WKEinaSharedString(message), WKEinaSharedString(defaultValue)); - return value ? WKStringCreateWithUTF8CString(value) : 0; -} - -bool PageUIClientEfl::toolbarsAreVisible(WKPageRef, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - return features->toolbarVisible(); -} - -void PageUIClientEfl::setToolbarsAreVisible(WKPageRef, bool toolbarVisible, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - features->setToolbarVisible(toolbarVisible); -} - -bool PageUIClientEfl::menuBarIsVisible(WKPageRef, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - return features->menuBarVisible(); -} - -void PageUIClientEfl::setMenuBarIsVisible(WKPageRef, bool menuBarVisible, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - features->setMenuBarVisible(menuBarVisible); -} - -bool PageUIClientEfl::statusBarIsVisible(WKPageRef, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - return features->statusBarVisible(); -} - -void PageUIClientEfl::setStatusBarIsVisible(WKPageRef, bool statusBarVisible, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - features->setStatusBarVisible(statusBarVisible); -} - -bool PageUIClientEfl::isResizable(WKPageRef, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - return features->resizable(); -} - -void PageUIClientEfl::setIsResizable(WKPageRef, bool resizable, const void* clientInfo) -{ - EwkWindowFeatures* features = toPageUIClientEfl(clientInfo)->m_view->windowFeatures(); - ASSERT(features); - features->setResizable(resizable); -} - -WKRect PageUIClientEfl::getWindowFrame(WKPageRef, const void* clientInfo) -{ - return toPageUIClientEfl(clientInfo)->m_view->windowGeometry(); -} - -void PageUIClientEfl::setWindowFrame(WKPageRef, WKRect frame, const void* clientInfo) -{ - toPageUIClientEfl(clientInfo)->m_view->setWindowGeometry(frame); -} - -bool PageUIClientEfl::runBeforeUnloadConfirmPanel(WKPageRef, WKStringRef message, WKFrameRef, const void* clientInfo) -{ - return toPageUIClientEfl(clientInfo)->m_view->requestJSConfirmPopup(WKEinaSharedString(message)); -} - -#if ENABLE(SQL_DATABASE) -unsigned long long PageUIClientEfl::exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef databaseName, WKStringRef displayName, unsigned long long currentQuota, unsigned long long currentOriginUsage, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void* clientInfo) -{ - EwkView* view = toPageUIClientEfl(clientInfo)->m_view; - return view->informDatabaseQuotaReached(toImpl(databaseName)->string(), toImpl(displayName)->string(), currentQuota, currentOriginUsage, currentDatabaseUsage, expectedUsage); -} -#endif - -void PageUIClientEfl::runOpenPanel(WKPageRef, WKFrameRef, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void* clientInfo) -{ - EwkView* view = toPageUIClientEfl(clientInfo)->m_view; - RefPtr<EwkFileChooserRequest> fileChooserRequest = EwkFileChooserRequest::create(parameters, listener); - view->smartCallback<FileChooserRequest>().call(fileChooserRequest.get()); -} - -WKPageRef PageUIClientEfl::createNewPage(WKPageRef, WKURLRequestRef wkRequest, WKDictionaryRef wkWindowFeatures, WKEventModifiers, WKEventMouseButton, const void* clientInfo) -{ - RefPtr<EwkUrlRequest> request = EwkUrlRequest::create(wkRequest); - return toPageUIClientEfl(clientInfo)->m_view->createNewPage(request, wkWindowFeatures); -} - -#if ENABLE(INPUT_TYPE_COLOR) -void PageUIClientEfl::showColorPicker(WKPageRef, WKStringRef initialColor, WKColorPickerResultListenerRef listener, const void* clientInfo) -{ - PageUIClientEfl* pageUIClient = toPageUIClientEfl(clientInfo); - WebCore::Color color = WebCore::Color(WebKit::toWTFString(initialColor)); - pageUIClient->m_view->requestColorPicker(listener, color); -} - -void PageUIClientEfl::hideColorPicker(WKPageRef, const void* clientInfo) -{ - PageUIClientEfl* pageUIClient = toPageUIClientEfl(clientInfo); - pageUIClient->m_view->dismissColorPicker(); -} -#endif - -void PageUIClientEfl::showPopupMenu(WKPageRef, WKPopupMenuListenerRef menuListenerRef, WKRect rect, WKPopupItemTextDirection textDirection, double pageScaleFactor, WKArrayRef itemsRef, int32_t selectedIndex, const void* clientInfo) -{ - return toPageUIClientEfl(clientInfo)->m_view->requestPopupMenu(menuListenerRef, rect, textDirection, pageScaleFactor, itemsRef, selectedIndex); -} - -void PageUIClientEfl::hidePopupMenu(WKPageRef, const void* clientInfo) -{ - return toPageUIClientEfl(clientInfo)->m_view->closePopupMenu(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h b/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h deleted file mode 100644 index df47b9716..000000000 --- a/Source/WebKit2/UIProcess/efl/PageUIClientEfl.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * 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 PageUIClientEfl_h -#define PageUIClientEfl_h - -#include "WKPage.h" -#include "WKPopupItem.h" -#include <WebKit2/WKBase.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class PageUIClientEfl { -public: - static PassOwnPtr<PageUIClientEfl> create(EwkView* view) - { - return adoptPtr(new PageUIClientEfl(view)); - } - -private: - explicit PageUIClientEfl(EwkView*); - - static void close(WKPageRef, const void*); - static void takeFocus(WKPageRef, WKFocusDirection, const void*); - static void focus(WKPageRef, const void*); - static void unfocus(WKPageRef, const void*); - static void runJavaScriptAlert(WKPageRef, WKStringRef, WKFrameRef, const void*); - static bool runJavaScriptConfirm(WKPageRef, WKStringRef, WKFrameRef, const void*); - static WKStringRef runJavaScriptPrompt(WKPageRef, WKStringRef, WKStringRef, WKFrameRef, const void*); - static bool toolbarsAreVisible(WKPageRef, const void* clientInfo); - static void setToolbarsAreVisible(WKPageRef, bool, const void* clientInfo); - static bool menuBarIsVisible(WKPageRef, const void* clientInfo); - static void setMenuBarIsVisible(WKPageRef, bool, const void* clientInfo); - static bool statusBarIsVisible(WKPageRef, const void* clientInfo); - static void setStatusBarIsVisible(WKPageRef, bool, const void* clientInfo); - static bool isResizable(WKPageRef, const void* clientInfo); - static void setIsResizable(WKPageRef, bool, const void* clientInfo); - static WKRect getWindowFrame(WKPageRef, const void*); - static void setWindowFrame(WKPageRef, WKRect, const void*); - static bool runBeforeUnloadConfirmPanel(WKPageRef, WKStringRef, WKFrameRef, const void*); -#if ENABLE(SQL_DATABASE) - static unsigned long long exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef, WKStringRef, unsigned long long currentQuota, unsigned long long, unsigned long long, unsigned long long, const void*); -#endif - static void runOpenPanel(WKPageRef, WKFrameRef, WKOpenPanelParametersRef, WKOpenPanelResultListenerRef, const void*); - static WKPageRef createNewPage(WKPageRef, WKURLRequestRef, WKDictionaryRef, WKEventModifiers, WKEventMouseButton, const void*); -#if ENABLE(INPUT_TYPE_COLOR) - static void showColorPicker(WKPageRef, WKStringRef initialColor, WKColorPickerResultListenerRef, const void*); - static void hideColorPicker(WKPageRef, const void*); -#endif - - static void showPopupMenu(WKPageRef, WKPopupMenuListenerRef, WKRect, WKPopupItemTextDirection, double pageScaleFactor, WKArrayRef itemsRef, int32_t selectedIndex, const void* clientInfo); - static void hidePopupMenu(WKPageRef, const void* clientInfo); - - EwkView* m_view; -}; - -} // namespace WebKit - -#endif // PageUIClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp deleted file mode 100644 index 22a45b52f..000000000 --- a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * 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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "PageViewportControllerClientEfl.h" - -#include "EwkView.h" -#include "PageViewportController.h" - -using namespace WebCore; - -namespace WebKit { - -PageViewportControllerClientEfl::PageViewportControllerClientEfl(EwkView* view) - : m_view(view) - , m_controller(0) -{ - ASSERT(m_view); -} - -void PageViewportControllerClientEfl::didChangeContentsSize(const WebCore::IntSize&) -{ - m_view->scheduleUpdateDisplay(); -} - -void PageViewportControllerClientEfl::setViewportPosition(const WebCore::FloatPoint& contentsPoint) -{ - m_contentPosition = contentsPoint; - - FloatPoint pos(contentsPoint); - float scaleFactor = WKViewGetContentScaleFactor(m_view->wkView()); - pos.scale(scaleFactor, scaleFactor); - WKViewSetContentPosition(m_view->wkView(), WKPointMake(pos.x(), pos.y())); - - m_controller->didChangeContentsVisibility(m_contentPosition, scaleFactor); -} - -void PageViewportControllerClientEfl::setPageScaleFactor(float newScale) -{ - WKViewSetContentScaleFactor(m_view->wkView(), newScale); -} - -void PageViewportControllerClientEfl::didChangeVisibleContents() -{ - m_view->scheduleUpdateDisplay(); -} - -void PageViewportControllerClientEfl::didChangeViewportAttributes() -{ -} - -void PageViewportControllerClientEfl::setController(PageViewportController* controller) -{ - m_controller = controller; -} - -} // namespace WebKit -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h b/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h deleted file mode 100644 index e4045b6e1..000000000 --- a/Source/WebKit2/UIProcess/efl/PageViewportControllerClientEfl.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. All rights reserved. - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * 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 PageViewportControllerClientEfl_h -#define PageViewportControllerClientEfl_h - -#include "PageViewportControllerClient.h" -#include <WebCore/FloatPoint.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class PageViewportControllerClientEfl : public PageViewportControllerClient { -public: - static PassOwnPtr<PageViewportControllerClientEfl> create(EwkView* viewImpl) - { - return adoptPtr(new PageViewportControllerClientEfl(viewImpl)); - } - virtual ~PageViewportControllerClientEfl() { } - - virtual void setViewportPosition(const WebCore::FloatPoint&) OVERRIDE; - virtual void setPageScaleFactor(float) OVERRIDE; - - virtual void didChangeContentsSize(const WebCore::IntSize&) OVERRIDE; - virtual void didChangeVisibleContents() OVERRIDE; - virtual void didChangeViewportAttributes() OVERRIDE; - - virtual void setController(PageViewportController*) OVERRIDE; - -private: - explicit PageViewportControllerClientEfl(EwkView*); - - EwkView* m_view; - WebCore::FloatPoint m_contentPosition; - PageViewportController* m_controller; -}; - -} // namespace WebKit - -#endif // PageViewportControllerClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp deleted file mode 100644 index eff93281d..000000000 --- a/Source/WebKit2/UIProcess/efl/RequestManagerClientEfl.cpp +++ /dev/null @@ -1,95 +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 "RequestManagerClientEfl.h" - -#include "WKContextSoup.h" -#include "WKSoupRequestManager.h" -#include "ewk_context_private.h" -#include "ewk_url_scheme_request_private.h" - -namespace WebKit { - -struct EwkUrlSchemeHandler { - Ewk_Url_Scheme_Request_Cb callback; - void* userData; - - EwkUrlSchemeHandler() - : callback(0) - , userData(0) - { } - - EwkUrlSchemeHandler(Ewk_Url_Scheme_Request_Cb callback, void* userData) - : callback(callback) - , userData(userData) - { } -}; - -static inline RequestManagerClientEfl* toRequestManagerClientEfl(const void* clientInfo) -{ - return static_cast<RequestManagerClientEfl*>(const_cast<void*>(clientInfo)); -} - -void RequestManagerClientEfl::didReceiveURIRequest(WKSoupRequestManagerRef soupRequestManagerRef, WKURLRef urlRef, WKPageRef, uint64_t requestID, const void* clientInfo) -{ - RequestManagerClientEfl* requestManager = toRequestManagerClientEfl(clientInfo); - - RefPtr<EwkUrlSchemeRequest> schemeRequest = EwkUrlSchemeRequest::create(soupRequestManagerRef, urlRef, requestID); - EwkUrlSchemeHandler handler = requestManager->m_urlSchemeHandlers.get(schemeRequest->scheme()); - if (!handler.callback) - return; - - handler.callback(schemeRequest.get(), handler.userData); -} - -RequestManagerClientEfl::RequestManagerClientEfl(WKContextRef context) - : m_soupRequestManager(WKContextGetSoupRequestManager(context)) -{ - ASSERT(m_soupRequestManager); - - WKSoupRequestManagerClient wkRequestManagerClient; - memset(&wkRequestManagerClient, 0, sizeof(WKSoupRequestManagerClient)); - - wkRequestManagerClient.version = kWKSoupRequestManagerClientCurrentVersion; - wkRequestManagerClient.clientInfo = this; - wkRequestManagerClient.didReceiveURIRequest = didReceiveURIRequest; - - WKSoupRequestManagerSetClient(m_soupRequestManager.get(), &wkRequestManagerClient); -} - -RequestManagerClientEfl::~RequestManagerClientEfl() -{ -} - -void RequestManagerClientEfl::registerURLSchemeHandler(const String& scheme, Ewk_Url_Scheme_Request_Cb callback, void* userData) -{ - ASSERT(callback); - - m_urlSchemeHandlers.set(scheme, EwkUrlSchemeHandler(callback, userData)); - WKSoupRequestManagerRegisterURIScheme(m_soupRequestManager.get(), adoptWK(toCopiedAPI(scheme)).get()); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp b/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp deleted file mode 100644 index 53c220ec9..000000000 --- a/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "TextCheckerClientEfl.h" - -#if ENABLE(SPELLCHECK) - -#include "EwkView.h" -#include "TextChecker.h" -#include "TextCheckerState.h" -#include "WKAPICast.h" -#include "WKEinaSharedString.h" -#include "WKMutableArray.h" -#include "WKRetainPtr.h" -#include "WKString.h" -#include "WebPageProxy.h" -#include "ewk_text_checker_private.h" -#include <Eina.h> - -using namespace WebCore; -using namespace WebKit; - -static inline TextCheckerClientEfl* toTextCheckerClientEfl(const void* clientInfo) -{ - return static_cast<TextCheckerClientEfl*>(const_cast<void*>(clientInfo)); -} - -TextCheckerClientEfl::TextCheckerClientEfl() - : m_languagesUpdateTimer(this, &TextCheckerClientEfl::languagesUpdateTimerFired) - , m_spellCheckingSettingChangeTimer(this, &TextCheckerClientEfl::spellCheckingSettingChangeTimerFired) - , m_textCheckerEnchant(TextCheckerEnchant::create()) -{ - memset(&m_clientCallbacks, 0, sizeof(ClientCallbacks)); - - WKTextCheckerClient wkTextCheckerClient = { - kWKTextCheckerClientCurrentVersion, - this, - 0, // continuousSpellCheckingAllowed - isContinuousSpellCheckingEnabledCallback, - setContinuousSpellCheckingEnabledCallback, - 0, // grammarCheckingEnabled - 0, // setGrammarCheckingEnabled - uniqueSpellDocumentTagCallback, - closeSpellDocumentWithTagCallback, - checkSpellingOfStringCallback, - 0, // checkGrammarOfString, - 0, // spellingUIIsShowing - 0, // toggleSpellingUIIsShowing - 0, // updateSpellingUIWithMisspelledWord - 0, // updateSpellingUIWithGrammarString - guessesForWordCallback, - learnWordCallback, - ignoreWordCallback - }; - WKTextCheckerSetClient(&wkTextCheckerClient); -} - -TextCheckerClientEfl& TextCheckerClientEfl::instance() -{ - DEFINE_STATIC_LOCAL(TextCheckerClientEfl, textCheckerClient, ()); - return textCheckerClient; -} - -bool TextCheckerClientEfl::isContinuousSpellCheckingEnabled() const -{ - return isContinuousSpellCheckingEnabledCallback(0 /* clientInfo */); -} - -void TextCheckerClientEfl::ensureSpellCheckingLanguage() -{ - if (!m_textCheckerEnchant->hasDictionary()) - updateSpellCheckingLanguages(); -} - -void TextCheckerClientEfl::updateSpellCheckingLanguages(const Vector<String>& defaultLanguages) -{ - m_spellCheckingLanguages = defaultLanguages; - m_languagesUpdateTimer.startOneShot(0); -} - -void TextCheckerClientEfl::languagesUpdateTimerFired(Timer<TextCheckerClientEfl>*) -{ - m_textCheckerEnchant->updateSpellCheckingLanguages(m_spellCheckingLanguages); -} - -void TextCheckerClientEfl::spellCheckingSettingChangeTimerFired(Timer<TextCheckerClientEfl>*) -{ - m_clientCallbacks.continuous_spell_checking_change( - isContinuousSpellCheckingEnabledCallback(0 /* clientInfo */) - ); -} - -Vector<String> TextCheckerClientEfl::availableSpellCheckingLanguages() const -{ - return m_textCheckerEnchant->availableSpellCheckingLanguages(); -} - -Vector<String> TextCheckerClientEfl::loadedSpellCheckingLanguages() const -{ - return m_textCheckerEnchant->loadedSpellCheckingLanguages(); -} - -void TextCheckerClientEfl::callContinuousSpellCheckingChangeCallbackAsync() -{ - m_spellCheckingSettingChangeTimer.startOneShot(0); -} - -bool TextCheckerClientEfl::isContinuousSpellCheckingEnabledCallback(const void*) -{ - return TextChecker::state().isContinuousSpellCheckingEnabled; -} - -void TextCheckerClientEfl::setContinuousSpellCheckingEnabledCallback(bool, const void* clientInfo) -{ - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().continuous_spell_checking_change) - textCheckerClient->callContinuousSpellCheckingChangeCallbackAsync(); -} - -uint64_t TextCheckerClientEfl::uniqueSpellDocumentTagCallback(WKPageRef page, const void* clientInfo) -{ - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().unique_spell_document_tag_get) - return textCheckerClient->clientCallbacks().unique_spell_document_tag_get(EwkView::toEvasObject(page)); - - return 0; -} - -void TextCheckerClientEfl::closeSpellDocumentWithTagCallback(uint64_t tag, const void* clientInfo) -{ - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().unique_spell_document_tag_close) - textCheckerClient->clientCallbacks().unique_spell_document_tag_close(tag); -} - -void TextCheckerClientEfl::checkSpellingOfStringCallback(uint64_t tag, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void* clientInfo) -{ - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().string_spelling_check) - textCheckerClient->clientCallbacks().string_spelling_check(tag, WKEinaSharedString(text), misspellingLocation, misspellingLength); - else - textCheckerClient->m_textCheckerEnchant->checkSpellingOfString(toWTFString(text), *misspellingLocation, *misspellingLength); -} - -WKArrayRef TextCheckerClientEfl::guessesForWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) -{ - WKMutableArrayRef suggestionsForWord = WKMutableArrayCreate(); - - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().word_guesses_get) { - Eina_List* list = textCheckerClient->clientCallbacks().word_guesses_get(tag, WKEinaSharedString(word)); - void* item; - - EINA_LIST_FREE(list, item) { - WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(static_cast<const char*>(item))); - WKArrayAppendItem(suggestionsForWord, suggestion.get()); - free(item); - } - } else { - const Vector<String>& guesses = textCheckerClient->m_textCheckerEnchant->getGuessesForWord(toWTFString(word)); - size_t numberOfGuesses = guesses.size(); - for (size_t i = 0; i < numberOfGuesses; ++i) { - WKRetainPtr<WKStringRef> suggestion(AdoptWK, WKStringCreateWithUTF8CString(guesses[i].utf8().data())); - WKArrayAppendItem(suggestionsForWord, suggestion.get()); - } - } - - return suggestionsForWord; -} - -void TextCheckerClientEfl::learnWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) -{ - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().word_learn) - textCheckerClient->clientCallbacks().word_learn(tag, WKEinaSharedString(word)); - else - textCheckerClient->m_textCheckerEnchant->learnWord(toWTFString(word)); -} - -void TextCheckerClientEfl::ignoreWordCallback(uint64_t tag, WKStringRef word, const void* clientInfo) -{ - TextCheckerClientEfl* textCheckerClient = toTextCheckerClientEfl(clientInfo); - if (textCheckerClient->clientCallbacks().word_ignore) - textCheckerClient->clientCallbacks().word_ignore(tag, WKEinaSharedString(word)); - else - textCheckerClient->m_textCheckerEnchant->ignoreWord(toWTFString(word)); -} - -#endif // ENABLE(SPELLCHECK) diff --git a/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.h b/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.h deleted file mode 100644 index ed013b133..000000000 --- a/Source/WebKit2/UIProcess/efl/TextCheckerClientEfl.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef TextCheckerClientEfl_h -#define TextCheckerClientEfl_h - -#if ENABLE(SPELLCHECK) - -#include "TextCheckerEnchant.h" -#include "Timer.h" -#include <WebKit2/WKTextChecker.h> -#include <WebKit2/ewk_text_checker_private.h> - -namespace WebKit { - -class TextCheckerClientEfl { -public: - static TextCheckerClientEfl& instance(); - - // Can be set by ewk APIs, by default they are 0. - ClientCallbacks& clientCallbacks() { return m_clientCallbacks; } - - bool isContinuousSpellCheckingEnabled() const; - - // Languages support. - void ensureSpellCheckingLanguage(); - Vector<String> availableSpellCheckingLanguages() const; - Vector<String> loadedSpellCheckingLanguages() const; - void updateSpellCheckingLanguages(const Vector<String>& defaultLanguages = Vector<String>()); - -private: - TextCheckerClientEfl(); - - // To set languages on timer. - void languagesUpdateTimerFired(WebCore::Timer<TextCheckerClientEfl>*); - WebCore::Timer<TextCheckerClientEfl> m_languagesUpdateTimer; - Vector<String> m_spellCheckingLanguages; - - // To notify the client about the setting change on timer. - void spellCheckingSettingChangeTimerFired(WebCore::Timer<TextCheckerClientEfl>*); - void callContinuousSpellCheckingChangeCallbackAsync(); - WebCore::Timer<TextCheckerClientEfl> m_spellCheckingSettingChangeTimer; - - // WKTextCheckerClient callbacks. - static bool isContinuousSpellCheckingEnabledCallback(const void*); - static void setContinuousSpellCheckingEnabledCallback(bool, const void*); - static uint64_t uniqueSpellDocumentTagCallback(WKPageRef, const void*); - static void closeSpellDocumentWithTagCallback(uint64_t, const void*); - static void checkSpellingOfStringCallback(uint64_t, WKStringRef text, int32_t* misspellingLocation, int32_t* misspellingLength, const void*); - static WKArrayRef guessesForWordCallback(uint64_t, WKStringRef word, const void*); - static void learnWordCallback(uint64_t, WKStringRef word, const void*); - static void ignoreWordCallback(uint64_t, WKStringRef word, const void*); - - ClientCallbacks m_clientCallbacks; - OwnPtr<WebCore::TextCheckerEnchant> m_textCheckerEnchant; -}; - -} // namespace WebKit - -#endif // ENABLE(SPELLCHECK) -#endif // TextCheckerClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp b/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp deleted file mode 100644 index 86a7d6c6b..000000000 --- a/Source/WebKit2/UIProcess/efl/TextCheckerEfl.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2011-2013 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "TextChecker.h" - -#include "NotImplemented.h" -#include "TextCheckerState.h" - -#if ENABLE(SPELLCHECK) -#include "TextBreakIterator.h" -#include "TextCheckerClientEfl.h" -#include "WebTextChecker.h" -#endif - -using namespace WebCore; - -namespace WebKit { - -static TextCheckerState textCheckerState; - -const TextCheckerState& TextChecker::state() -{ - static bool didInitializeState = false; - if (didInitializeState) - return textCheckerState; - - textCheckerState.isContinuousSpellCheckingEnabled = false; - textCheckerState.isGrammarCheckingEnabled = false; - - didInitializeState = true; - - return textCheckerState; -} - -bool TextChecker::isContinuousSpellCheckingAllowed() -{ - notImplemented(); - return false; -} - -void TextChecker::setContinuousSpellCheckingEnabled(bool isContinuousSpellCheckingEnabled) -{ -#if ENABLE(SPELLCHECK) - if (state().isContinuousSpellCheckingEnabled == isContinuousSpellCheckingEnabled) - return; - - textCheckerState.isContinuousSpellCheckingEnabled = isContinuousSpellCheckingEnabled; - - // Notify the client about the setting change. - WebTextChecker::shared()->client().setContinuousSpellCheckingEnabled(isContinuousSpellCheckingEnabled); -#else - UNUSED_PARAM(isContinuousSpellCheckingEnabled); -#endif -} - -void TextChecker::setGrammarCheckingEnabled(bool) -{ - notImplemented(); -} - -void TextChecker::continuousSpellCheckingEnabledStateChanged(bool enabled) -{ -#if ENABLE(SPELLCHECK) - if (state().isContinuousSpellCheckingEnabled == enabled) - return; - - textCheckerState.isContinuousSpellCheckingEnabled = enabled; -#else - UNUSED_PARAM(enabled); -#endif -} - -void TextChecker::grammarCheckingEnabledStateChanged(bool) -{ - notImplemented(); -} - -int64_t TextChecker::uniqueSpellDocumentTag(WebPageProxy* page) -{ -#if ENABLE(SPELLCHECK) - return WebTextChecker::shared()->client().uniqueSpellDocumentTag(page); -#else - UNUSED_PARAM(page); - return 0; -#endif -} - -void TextChecker::closeSpellDocumentWithTag(int64_t tag) -{ -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().closeSpellDocumentWithTag(tag); -#else - UNUSED_PARAM(tag); -#endif -} - -#if ENABLE(SPELLCHECK) -static int nextWordOffset(const UChar* text, int length, int currentOffset) -{ - // FIXME: avoid creating textIterator object here, it could be passed as a parameter. - // isTextBreak() leaves the iterator pointing to the first boundary position at - // or after "offset" (ubrk_isBoundary side effect). - // For many word separators, the method doesn't properly determine the boundaries - // without resetting the iterator. - TextBreakIterator* textIterator = wordBreakIterator(text, length); - if (!textIterator) - return currentOffset; - - int wordOffset = currentOffset; - while (wordOffset < length && isTextBreak(textIterator, wordOffset)) - ++wordOffset; - - // Do not treat the word's boundary as a separator. - if (!currentOffset && wordOffset == 1) - return currentOffset; - - // Omit multiple separators. - if ((wordOffset - currentOffset) > 1) - --wordOffset; - - return wordOffset; -} -#endif // ENABLE(SPELLCHECK) - -#if USE(UNIFIED_TEXT_CHECKING) -Vector<TextCheckingResult> TextChecker::checkTextOfParagraph(int64_t spellDocumentTag, const UChar* text, int length, uint64_t checkingTypes) -{ - Vector<TextCheckingResult> paragraphCheckingResult; -#if ENABLE(SPELLCHECK) - if (checkingTypes & TextCheckingTypeSpelling) { - TextBreakIterator* textIterator = wordBreakIterator(text, length); - if (!textIterator) - return paragraphCheckingResult; - - // Omit the word separators at the beginning/end of the text to don't unnecessarily - // involve the client to check spelling for them. - int offset = nextWordOffset(text, length, 0); - int lengthStrip = length; - while (lengthStrip > 0 && isTextBreak(textIterator, lengthStrip - 1)) - --lengthStrip; - - while (offset >= 0 && offset < lengthStrip) { - int32_t misspellingLocation = -1; - int32_t misspellingLength = 0; - checkSpellingOfString(spellDocumentTag, text + offset, lengthStrip - offset, misspellingLocation, misspellingLength); - if (!misspellingLength) - break; - - TextCheckingResult misspellingResult; - misspellingResult.type = TextCheckingTypeSpelling; - misspellingResult.location = offset + misspellingLocation; - misspellingResult.length = misspellingLength; - paragraphCheckingResult.append(misspellingResult); - offset += misspellingLocation + misspellingLength; - // Generally, we end up checking at the word separator, move to the adjacent word. - offset = nextWordOffset(text, lengthStrip, offset); - } - } -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(text); - UNUSED_PARAM(length); - UNUSED_PARAM(checkingTypes); -#endif - return paragraphCheckingResult; -} -#endif - -void TextChecker::checkSpellingOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, int32_t& misspellingLocation, int32_t& misspellingLength) -{ -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().checkSpellingOfString(spellDocumentTag, String(text, length), misspellingLocation, misspellingLength); -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(text); - UNUSED_PARAM(length); - UNUSED_PARAM(misspellingLocation); - UNUSED_PARAM(misspellingLength); -#endif -} - -void TextChecker::checkGrammarOfString(int64_t, const UChar*, uint32_t, Vector<GrammarDetail>&, int32_t&, int32_t&) -{ - notImplemented(); -} - -bool TextChecker::spellingUIIsShowing() -{ - notImplemented(); - return false; -} - -void TextChecker::toggleSpellingUIIsShowing() -{ - notImplemented(); -} - -void TextChecker::updateSpellingUIWithMisspelledWord(int64_t, const String&) -{ - notImplemented(); -} - -void TextChecker::updateSpellingUIWithGrammarString(int64_t, const String&, const GrammarDetail&) -{ - notImplemented(); -} - -void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& , Vector<String>& guesses) -{ -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().guessesForWord(spellDocumentTag, word, guesses); -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(word); - UNUSED_PARAM(guesses); -#endif -} - -void TextChecker::learnWord(int64_t spellDocumentTag, const String& word) -{ -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().learnWord(spellDocumentTag, word); -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(word); -#endif -} - -void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) -{ -#if ENABLE(SPELLCHECK) - WebTextChecker::shared()->client().ignoreWord(spellDocumentTag, word); -#else - UNUSED_PARAM(spellDocumentTag); - UNUSED_PARAM(word); -#endif -} - -void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion> completion) -{ -#if ENABLE(SPELLCHECK) - if (!completion) - return; - - TextCheckingRequestData request = completion->textCheckingRequestData(); - ASSERT(request.sequence() != unrequestedTextCheckingSequence); - ASSERT(request.mask() != TextCheckingTypeNone); - - String text = request.text(); - Vector<TextCheckingResult> result = checkTextOfParagraph(completion->spellDocumentTag(), text.characters(), text.length(), request.mask()); - - completion->didFinishCheckingText(result); -#else - UNUSED_PARAM(completion); -#endif -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.cpp b/Source/WebKit2/UIProcess/efl/VibrationClientEfl.cpp deleted file mode 100644 index 5662a8ed0..000000000 --- a/Source/WebKit2/UIProcess/efl/VibrationClientEfl.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 "VibrationClientEfl.h" - -#if ENABLE(VIBRATION) - -#include "EwkView.h" -#include "WKAPICast.h" -#include "WKVibration.h" - -using namespace WebKit; -using namespace EwkViewCallbacks; - -static inline VibrationClientEfl* toVibrationClient(const void* clientInfo) -{ - return static_cast<VibrationClientEfl*>(const_cast<void*>(clientInfo)); -} - -void VibrationClientEfl::vibrateCallback(WKVibrationRef, uint32_t vibrationTime, const void* clientInfo) -{ - toVibrationClient(clientInfo)->m_view->smartCallback<Vibrate>().call(&vibrationTime); -} - -void VibrationClientEfl::cancelVibrationCallback(WKVibrationRef, const void* clientInfo) -{ - toVibrationClient(clientInfo)->m_view->smartCallback<CancelVibration>().call(); -} - -PassOwnPtr<VibrationClientEfl> VibrationClientEfl::create(EwkView* viewImpl) -{ - return adoptPtr(new VibrationClientEfl(viewImpl)); -} - -VibrationClientEfl::VibrationClientEfl(EwkView* view) - : m_view(view) -{ - ASSERT(m_view); - - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKVibrationRef wkVibration = WKPageGetVibration(pageRef); - ASSERT(wkVibration); - - WKVibrationProvider wkVibrationProvider = { - kWKVibrationProviderCurrentVersion, - this, // clientInfo - vibrateCallback, - cancelVibrationCallback - }; - WKVibrationSetProvider(wkVibration, &wkVibrationProvider); -} - -VibrationClientEfl::~VibrationClientEfl() -{ - WKPageRef pageRef = m_view->wkPage(); - ASSERT(pageRef); - - WKVibrationRef wkVibration = WKPageGetVibration(pageRef); - ASSERT(wkVibration); - - WKVibrationSetProvider(wkVibration, 0); -} - -#endif // ENABLE(VIBRATION) diff --git a/Source/WebKit2/UIProcess/efl/ViewClientEfl.cpp b/Source/WebKit2/UIProcess/efl/ViewClientEfl.cpp deleted file mode 100644 index e14214fa4..000000000 --- a/Source/WebKit2/UIProcess/efl/ViewClientEfl.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ViewClientEfl.h" - -#include "EwkView.h" -#include "PageViewportController.h" -#include "WebViewportAttributes.h" -#include <WebKit2/WKString.h> -#include <WebKit2/WKView.h> -#include <WebKit2/WKViewEfl.h> - -using namespace EwkViewCallbacks; -using namespace WebCore; - -namespace WebKit { - -EwkView* ViewClientEfl::toEwkView(const void* clientInfo) -{ - return static_cast<ViewClientEfl*>(const_cast<void*>(clientInfo))->m_view; -} - -void ViewClientEfl::viewNeedsDisplay(WKViewRef, WKRect, const void* clientInfo) -{ - toEwkView(clientInfo)->scheduleUpdateDisplay(); -} - -void ViewClientEfl::didChangeContentsSize(WKViewRef, WKSize size, const void* clientInfo) -{ - EwkView* ewkView = toEwkView(clientInfo); - if (WKPageUseFixedLayout(ewkView->wkPage())) -#if USE(ACCELERATED_COMPOSITING) - ewkView->pageViewportController()->didChangeContentsSize(toIntSize(size)); -#else - { } -#endif - else - ewkView->scheduleUpdateDisplay(); - - ewkView->smartCallback<ContentsSizeChanged>().call(size); -} - -void ViewClientEfl::webProcessCrashed(WKViewRef, WKURLRef url, const void* clientInfo) -{ - EwkView* ewkView = toEwkView(clientInfo); - - // Check if loading was ongoing, when web process crashed. - double loadProgress = WKPageGetEstimatedProgress(ewkView->wkPage()); - if (loadProgress >= 0 && loadProgress < 1) { - loadProgress = 1; - ewkView->smartCallback<LoadProgress>().call(&loadProgress); - } - - ewkView->smartCallback<TooltipTextUnset>().call(); - - bool handled = false; - ewkView->smartCallback<WebProcessCrashed>().call(&handled); - - if (!handled) { - WKEinaSharedString urlString(url); - WARN("WARNING: The web process experienced a crash on '%s'.\n", static_cast<const char*>(urlString)); - - // Display an error page - ewk_view_html_string_load(ewkView->evasObject(), "The web process has crashed.", 0, urlString); - } -} - -void ViewClientEfl::webProcessDidRelaunch(WKViewRef viewRef, const void* clientInfo) -{ - if (const char* themePath = toEwkView(clientInfo)->themePath()) - WKViewSetThemePath(viewRef, adoptWK(WKStringCreateWithUTF8CString(themePath)).get()); -} - -void ViewClientEfl::didChangeContentsPosition(WKViewRef, WKPoint position, const void* clientInfo) -{ - EwkView* ewkView = toEwkView(clientInfo); - if (WKPageUseFixedLayout(ewkView->wkPage())) { -#if USE(ACCELERATED_COMPOSITING) - ewkView->pageViewportController()->pageDidRequestScroll(toIntPoint(position)); -#endif - return; - } - - ewkView->scheduleUpdateDisplay(); -} - -void ViewClientEfl::didRenderFrame(WKViewRef, WKSize contentsSize, WKRect coveredRect, const void* clientInfo) -{ - EwkView* ewkView = toEwkView(clientInfo); - if (WKPageUseFixedLayout(ewkView->wkPage())) { -#if USE(ACCELERATED_COMPOSITING) - ewkView->pageViewportController()->didRenderFrame(toIntSize(contentsSize), toIntRect(coveredRect)); -#endif - return; - } - - ewkView->scheduleUpdateDisplay(); -} - -void ViewClientEfl::didCompletePageTransition(WKViewRef, const void* clientInfo) -{ - EwkView* ewkView = toEwkView(clientInfo); - if (WKPageUseFixedLayout(ewkView->wkPage())) { -#if USE(ACCELERATED_COMPOSITING) - ewkView->pageViewportController()->pageTransitionViewportReady(); -#endif - return; - } - - ewkView->scheduleUpdateDisplay(); -} - -void ViewClientEfl::didChangeViewportAttributes(WKViewRef, WKViewportAttributesRef attributes, const void* clientInfo) -{ - EwkView* ewkView = toEwkView(clientInfo); - if (WKPageUseFixedLayout(ewkView->wkPage())) { -#if USE(ACCELERATED_COMPOSITING) - // FIXME: pageViewportController should accept WKViewportAttributesRef. - ewkView->pageViewportController()->didChangeViewportAttributes(toImpl(attributes)->originalAttributes()); -#endif - return; - } - ewkView->scheduleUpdateDisplay(); -} - -void ViewClientEfl::didChangeTooltip(WKViewRef, WKStringRef tooltip, const void* clientInfo) -{ - if (WKStringIsEmpty(tooltip)) - toEwkView(clientInfo)->smartCallback<TooltipTextUnset>().call(); - else - toEwkView(clientInfo)->smartCallback<TooltipTextSet>().call(WKEinaSharedString(tooltip)); -} - -void ViewClientEfl::didFindZoomableArea(WKViewRef, WKPoint point, WKRect area, const void* clientInfo) -{ - toEwkView(clientInfo)->didFindZoomableArea(point, area); -} - -#if ENABLE(TOUCH_EVENTS) -void ViewClientEfl::doneWithTouchEvent(WKViewRef, WKTouchEventRef event, bool wasEventHandled, const void* clientInfo) -{ - toEwkView(clientInfo)->doneWithTouchEvent(event, wasEventHandled); -} -#endif - -ViewClientEfl::ViewClientEfl(EwkView* view) - : m_view(view) -{ - ASSERT(m_view); - - WKViewClient viewClient; - memset(&viewClient, 0, sizeof(WKViewClient)); - viewClient.version = kWKViewClientCurrentVersion; - viewClient.clientInfo = this; - viewClient.didChangeContentsSize = didChangeContentsSize; - viewClient.didFindZoomableArea = didFindZoomableArea; - viewClient.viewNeedsDisplay = viewNeedsDisplay; - viewClient.webProcessCrashed = webProcessCrashed; - viewClient.webProcessDidRelaunch = webProcessDidRelaunch; - viewClient.didChangeContentsPosition = didChangeContentsPosition; - viewClient.didRenderFrame = didRenderFrame; - viewClient.didCompletePageTransition = didCompletePageTransition; - viewClient.didChangeViewportAttributes = didChangeViewportAttributes; - viewClient.didChangeTooltip = didChangeTooltip; -#if ENABLE(TOUCH_EVENTS) - viewClient.doneWithTouchEvent = doneWithTouchEvent; -#endif - - WKViewSetViewClient(m_view->wkView(), &viewClient); -} - -ViewClientEfl::~ViewClientEfl() -{ - WKViewSetViewClient(m_view->wkView(), 0); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/ViewClientEfl.h b/Source/WebKit2/UIProcess/efl/ViewClientEfl.h deleted file mode 100644 index a384cf597..000000000 --- a/Source/WebKit2/UIProcess/efl/ViewClientEfl.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ViewClientEfl_h -#define ViewClientEfl_h - -#include <WebKit2/WKBase.h> -#include <WebKit2/WKGeometry.h> -#include <wtf/PassOwnPtr.h> - -class EwkView; - -namespace WebKit { - -class ViewClientEfl { -public: - static PassOwnPtr<ViewClientEfl> create(EwkView* view) - { - return adoptPtr(new ViewClientEfl(view)); - } - - ~ViewClientEfl(); - -private: - explicit ViewClientEfl(EwkView*); - - static EwkView* toEwkView(const void* clientInfo); - static void viewNeedsDisplay(WKViewRef, WKRect area, const void* clientInfo); - static void didChangeContentsSize(WKViewRef, WKSize, const void* clientInfo); - static void webProcessCrashed(WKViewRef, WKURLRef, const void* clientInfo); - static void webProcessDidRelaunch(WKViewRef, const void* clientInfo); - static void didChangeContentsPosition(WKViewRef, WKPoint, const void* clientInfo); - static void didRenderFrame(WKViewRef, WKSize, WKRect, const void* clientInfo); - static void didCompletePageTransition(WKViewRef, const void* clientInfo); - static void didChangeViewportAttributes(WKViewRef, WKViewportAttributesRef, const void* clientInfo); - static void didChangeTooltip(WKViewRef, WKStringRef, const void* clientInfo); - static void didFindZoomableArea(WKViewRef, WKPoint, WKRect, const void* clientInfo); -#if ENABLE(TOUCH_EVENTS) - static void doneWithTouchEvent(WKViewRef, WKTouchEventRef, bool, const void* clientInfo); -#endif - - EwkView* m_view; -}; - -} // namespace WebKit - -#endif // ViewClientEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp b/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp deleted file mode 100644 index d2dca3dfc..000000000 --- a/Source/WebKit2/UIProcess/efl/WebContextEfl.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebCookieManagerProxy.h" -#include "WebContext.h" - -#include "Logging.h" -#include "WebInspectorServer.h" -#include "WebProcessCreationParameters.h" -#include "WebProcessMessages.h" -#include "WebSoupRequestManagerProxy.h" -#include <Efreet.h> -#include <WebCore/ApplicationCacheStorage.h> -#include <WebCore/IconDatabase.h> -#include <WebCore/NotImplemented.h> - -namespace WebKit { - -static void initializeInspectorServer() -{ -#if ENABLE(INSPECTOR_SERVER) - static bool initialized = false; - if (initialized) - return; - - // It should be set to true always. - // Because it is to ensure initializeInspectorServer() is executed only once, - // even if the server fails to run. - initialized = true; - - String serverAddress(getenv("WEBKIT_INSPECTOR_SERVER")); - if (!serverAddress.isNull()) { - String bindAddress = ASCIILiteral("127.0.0.1"); - unsigned short port = 2999; - - Vector<String> result; - serverAddress.split(':', result); - - if (result.size() == 2) { - bindAddress = result[0]; - bool ok = false; - port = result[1].toUInt(&ok); - if (!ok) { - port = 2999; - LOG_ERROR("Couldn't parse the port. Using 2999 instead."); - } - } else - LOG_ERROR("Couldn't parse %s, wrong format? Using 127.0.0.1:2999 instead.", serverAddress.utf8().data()); - - if (!WebInspectorServer::shared().listen(bindAddress, port)) - LOG_ERROR("Couldn't start listening on: IP address=%s, port=%d.", bindAddress.utf8().data(), port); - - return; - } - - LOG(InspectorServer, "To start inspector server set WEBKIT_INSPECTOR_SERVER to 127.0.0.1:2999 for example."); -#endif -} - -String WebContext::platformDefaultApplicationCacheDirectory() const -{ - return String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl/Applications"; -} - -void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) -{ - initializeInspectorServer(); - - parameters.urlSchemesRegistered = supplement<WebSoupRequestManagerProxy>()->registeredURISchemes(); - supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(parameters.cookiePersistentStoragePath, parameters.cookiePersistentStorageType); - parameters.cookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy; - parameters.ignoreTLSErrors = m_ignoreTLSErrors; -} - -void WebContext::platformInvalidateContext() -{ - notImplemented(); -} - -String WebContext::platformDefaultDatabaseDirectory() const -{ - return String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/Databases"; -} - -String WebContext::platformDefaultIconDatabasePath() const -{ - return String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/IconDatabase/" + WebCore::IconDatabase::defaultDatabaseFilename(); -} - -String WebContext::platformDefaultLocalStorageDirectory() const -{ - return String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/LocalStorage"; -} - -String WebContext::platformDefaultDiskCacheDirectory() const -{ - return String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl"; -} - -String WebContext::platformDefaultCookieStorageDirectory() const -{ - notImplemented(); - return String(); -} - -void WebContext::setIgnoreTLSErrors(bool ignoreTLSErrors) -{ - m_ignoreTLSErrors = ignoreTLSErrors; - sendToAllProcesses(Messages::WebProcess::SetIgnoreTLSErrors(m_ignoreTLSErrors)); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp deleted file mode 100644 index 830d919c1..000000000 --- a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebContextMenuProxyEfl.h" - -#if ENABLE(CONTEXT_MENUS) - -#include "EwkView.h" -#include "WebContextMenuItemData.h" -#include "WebPageProxy.h" -#include <WebCore/NotImplemented.h> - -using namespace WebCore; - -namespace WebKit { - -WebContextMenuProxyEfl::WebContextMenuProxyEfl(EwkView* view, WebPageProxy* page) - : m_view(view) - , m_page(page) -{ -} - -WebContextMenuProxyEfl::~WebContextMenuProxyEfl() -{ -} - -void WebContextMenuProxyEfl::showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&) -{ - notImplemented(); -} - -void WebContextMenuProxyEfl::hideContextMenu() -{ - notImplemented(); -} - -} // namespace WebKit - -#endif // ENABLE(CONTEXT_MENUS) diff --git a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h b/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h deleted file mode 100644 index b74a54f96..000000000 --- a/Source/WebKit2/UIProcess/efl/WebContextMenuProxyEfl.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebContextMenuProxyEfl_h -#define WebContextMenuProxyEfl_h - -#if ENABLE(CONTEXT_MENUS) - -#include "WebContextMenuProxy.h" -#include <WebCore/ContextMenu.h> -#include <WebCore/IntPoint.h> - -class EwkView; - -namespace WebKit { - -class WebContextMenuItemData; -class WebPageProxy; - -class WebContextMenuProxyEfl : public WebContextMenuProxy { -public: - static PassRefPtr<WebContextMenuProxyEfl> create(EwkView* viewImpl, WebPageProxy* page) - { - return adoptRef(new WebContextMenuProxyEfl(viewImpl, page)); - } - - ~WebContextMenuProxyEfl(); - - void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); - void hideContextMenu(); - -private: - WebContextMenuProxyEfl(EwkView*, WebPageProxy*); - - EwkView* m_view; - WebPageProxy* m_page; -}; - - -} // namespace WebKit - -#endif // ENABLE(CONTEXT_MENUS) -#endif // WebContextMenuProxyEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp deleted file mode 100644 index 4d834bc63..000000000 --- a/Source/WebKit2/UIProcess/efl/WebFullScreenManagerProxyEfl.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebFullScreenManagerProxy.h" -#include "WebFullScreenManagerProxyMessages.h" - -#if ENABLE(FULLSCREEN_API) - -#include "EwkView.h" -#include <WebCore/NotImplemented.h> - -using namespace WebCore; - -namespace WebKit { - -void WebFullScreenManagerProxy::invalidate() -{ - m_page->process()->removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); - m_webView = 0; -} - -void WebFullScreenManagerProxy::close() -{ - notImplemented(); -} - -bool WebFullScreenManagerProxy::isFullScreen() -{ - return m_hasRequestedFullScreen; -} - -void WebFullScreenManagerProxy::enterFullScreen() -{ - if (!m_webView || m_hasRequestedFullScreen) - return; - - m_hasRequestedFullScreen = true; - - willEnterFullScreen(); - toEwkView(m_webView)->enterFullScreen(); - didEnterFullScreen(); -} - -void WebFullScreenManagerProxy::exitFullScreen() -{ - if (!m_webView || !m_hasRequestedFullScreen) - return; - - m_hasRequestedFullScreen = false; - - willExitFullScreen(); - toEwkView(m_webView)->exitFullScreen(); - didExitFullScreen(); -} - -void WebFullScreenManagerProxy::beganEnterFullScreen(const IntRect& /*initialFrame*/, const IntRect& /*finalFrame*/) -{ - notImplemented(); -} - -void WebFullScreenManagerProxy::beganExitFullScreen(const IntRect& /*initialFrame*/, const IntRect& /*finalFrame*/) -{ - notImplemented(); -} - -} // namespace WebKit - -#endif // ENABLE(FULLSCREEN_API) diff --git a/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp deleted file mode 100644 index d11386f21..000000000 --- a/Source/WebKit2/UIProcess/efl/WebInspectorProxyEfl.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebInspectorProxy.h" - -#if ENABLE(INSPECTOR) - -#include "EwkView.h" -#include "WebProcessProxy.h" -#include "ewk_context_private.h" -#include "ewk_page_group_private.h" -#include "ewk_settings.h" -#include "ewk_view.h" -#include "ewk_view_private.h" -#include <WebCore/EflInspectorUtilities.h> -#include <WebCore/NotImplemented.h> -#include <WebKit2/WKPage.h> -#include <WebKit2/WKPageGroup.h> -#include <WebKit2/WKPreferencesPrivate.h> -#include <WebKit2/WKString.h> -#include <WebKit2/WKViewEfl.h> -#include <wtf/text/CString.h> -#include <wtf/text/StringBuilder.h> -#include <wtf/text/WTFString.h> - -namespace WebKit { - -static void resizeInspectorWindow(Ecore_Evas* inspectorWindow) -{ - Evas_Object* inspectorView = evas_object_name_find(ecore_evas_get(inspectorWindow), "inspector"); - if (!inspectorView) - return; - - int width, height; - ecore_evas_geometry_get(inspectorWindow, 0, 0, &width, &height); - - evas_object_move(inspectorView, 0, 0); - evas_object_resize(inspectorView, width, height); -} - -static void destroyInspectorWindow(Ecore_Evas* inspectorWindow) -{ - Evas_Object* inspectorView = evas_object_name_find(ecore_evas_get(inspectorWindow), "inspector"); - if (inspectorView) - evas_object_smart_callback_call(inspectorView, "inspector,view,close", 0); -} - -static void closeInspectorWindow(void* userData, Evas_Object*, void*) -{ - WebInspectorProxy* inspectorProxy = static_cast<WebInspectorProxy*>(userData); - - inspectorProxy->close(); -} - -void WebInspectorProxy::createInspectorWindow() -{ - ecore_evas_title_set(m_inspectorWindow, "Web Inspector"); - ecore_evas_callback_resize_set(m_inspectorWindow, resizeInspectorWindow); - ecore_evas_callback_delete_request_set(m_inspectorWindow, destroyInspectorWindow); - ecore_evas_show(m_inspectorWindow); - - evas_object_name_set(m_inspectorView, "inspector"); - evas_object_move(m_inspectorView, 0, 0); - evas_object_resize(m_inspectorView, initialWindowWidth, initialWindowHeight); - evas_object_show(m_inspectorView); - - evas_object_focus_set(m_inspectorView, true); -} - -WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() -{ - ASSERT(m_page); - -#ifdef HAVE_ECORE_X - const char* engine = "opengl_x11"; - m_inspectorWindow = ecore_evas_new(engine, 0, 0, initialWindowWidth, initialWindowHeight, 0); - - // Gracefully fall back to software if evas_gl engine is not available. - if (!m_inspectorWindow) -#endif - m_inspectorWindow = ecore_evas_new(0, 0, 0, initialWindowWidth, initialWindowHeight, 0); - if (!m_inspectorWindow) - return 0; - - WKContextRef wkContext = toAPI(page()->process()->context()); - WKPageGroupRef wkPageGroup = toAPI(inspectorPageGroup()); - - m_inspectorView = EWKViewCreate(wkContext, wkPageGroup, ecore_evas_get(m_inspectorWindow), /* smart */ 0); - WKViewRef wkView = EWKViewGetWKView(m_inspectorView); - - WKRetainPtr<WKStringRef> wkTheme = adoptWK(WKStringCreateWithUTF8CString(TEST_THEME_DIR "/default.edj")); - WKViewSetThemePath(wkView, wkTheme.get()); - - WKPreferencesRef wkPreferences = WKPageGroupGetPreferences(wkPageGroup); - WKPreferencesSetFileAccessFromFileURLsAllowed(wkPreferences, true); - - return toImpl(WKViewGetPage(wkView)); -} - -void WebInspectorProxy::platformOpen() -{ - if (m_isAttached) - platformAttach(); - else - createInspectorWindow(); - - evas_object_smart_callback_add(m_inspectorView, "inspector,view,close", closeInspectorWindow, this); -} - -void WebInspectorProxy::platformDidClose() -{ - if (m_inspectorView) { - evas_object_del(m_inspectorView); - m_inspectorView = 0; - } - - if (m_inspectorWindow) { - ecore_evas_free(m_inspectorWindow); - m_inspectorWindow = 0; - } -} - -void WebInspectorProxy::platformHide() -{ - notImplemented(); -} - -void WebInspectorProxy::platformBringToFront() -{ - notImplemented(); -} - -bool WebInspectorProxy::platformIsFront() -{ - notImplemented(); - return false; -} - -void WebInspectorProxy::platformInspectedURLChanged(const String& url) -{ - if (!m_inspectorWindow) - return; - - String title = "WebInspector - " + url; - ecore_evas_title_set(m_inspectorWindow, title.utf8().data()); -} - -String WebInspectorProxy::inspectorPageURL() const -{ - StringBuilder builder; - builder.append(inspectorBaseURL()); - builder.appendLiteral("/inspector.html"); - - return builder.toString(); -} - -String WebInspectorProxy::inspectorBaseURL() const -{ - return "file://" + WebCore::inspectorResourcePath(); -} - -unsigned WebInspectorProxy::platformInspectedWindowHeight() -{ - notImplemented(); - return 0; -} - -unsigned WebInspectorProxy::platformInspectedWindowWidth() -{ - notImplemented(); - return 0; -} - -void WebInspectorProxy::platformAttach() -{ - notImplemented(); -} - -void WebInspectorProxy::platformDetach() -{ - notImplemented(); -} - -void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned) -{ - notImplemented(); -} - -void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned) -{ - notImplemented(); -} - -void WebInspectorProxy::platformSetToolbarHeight(unsigned) -{ - notImplemented(); -} - -void WebInspectorProxy::platformSave(const String&, const String&, bool) -{ - notImplemented(); -} - -void WebInspectorProxy::platformAppend(const String&, const String&) -{ - notImplemented(); -} - -void WebInspectorProxy::platformAttachAvailabilityChanged(bool) -{ - notImplemented(); -} - -} // namespace WebKit - -#endif // ENABLE(INSPECTOR) diff --git a/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp b/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp deleted file mode 100644 index a5e44e6d5..000000000 --- a/Source/WebKit2/UIProcess/efl/WebPageProxyEfl.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2011 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPageProxy.h" - -#include "EwkView.h" -#include "NativeWebKeyboardEvent.h" -#include "NotImplemented.h" -#include "WebKitVersion.h" -#include "WebPageMessages.h" -#include "WebProcessProxy.h" -#include "WebView.h" - -#include <sys/utsname.h> - -namespace WebKit { - -String WebPageProxy::standardUserAgent(const String& /*applicationNameForUserAgent*/) -{ - WTF::String platform; - WTF::String version; - WTF::String osVersion; - -#if PLATFORM(X11) - platform = "X11"; -#else - platform = "Unknown"; -#endif - version = String::number(WEBKIT_MAJOR_VERSION) + '.' + String::number(WEBKIT_MINOR_VERSION) + '+'; - struct utsname name; - if (uname(&name) != -1) - osVersion = WTF::String(name.sysname) + " " + WTF::String(name.machine); - else - osVersion = "Unknown"; - - return "Mozilla/5.0 (" + platform + "; " + osVersion + ") AppleWebKit/" + version - + " (KHTML, like Gecko) Version/5.0 Safari/" + version; -} - -void WebPageProxy::getEditorCommandsForKeyEvent(Vector<WTF::String>& /*commandsList*/) -{ - notImplemented(); -} - -void WebPageProxy::saveRecentSearches(const String&, const Vector<String>&) -{ - notImplemented(); -} - -void WebPageProxy::loadRecentSearches(const String&, Vector<String>&) -{ - notImplemented(); -} - -void WebPageProxy::setThemePath(const String& themePath) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::SetThemePath(themePath), m_pageID, 0); -} - -void WebPageProxy::createPluginContainer(uint64_t&) -{ - notImplemented(); -} - -void WebPageProxy::windowedPluginGeometryDidChange(const WebCore::IntRect&, const WebCore::IntRect&, uint64_t) -{ - notImplemented(); -} - -void WebPageProxy::handleInputMethodKeydown(bool& handled) -{ - handled = m_keyEventQueue.first().isFiltered(); -} - -void WebPageProxy::confirmComposition(const String& compositionString) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::ConfirmComposition(compositionString), m_pageID, 0); -} - -void WebPageProxy::setComposition(const String& compositionString, Vector<WebCore::CompositionUnderline>& underlines, int cursorPosition) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::SetComposition(compositionString, underlines, cursorPosition), m_pageID, 0); -} - -void WebPageProxy::cancelComposition() -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::CancelComposition(), m_pageID, 0); -} - -void WebPageProxy::initializeUIPopupMenuClient(const WKPageUIPopupMenuClient* client) -{ - m_uiPopupMenuClient.initialize(client); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.cpp b/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.cpp deleted file mode 100644 index f420c0eba..000000000 --- a/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPopupItemEfl.h" - -namespace WebKit { - -WebPopupItemEfl::WebPopupItemEfl(const WebPopupItem& data) - : m_data(data) -{ -} - -WebPopupItemEfl::~WebPopupItemEfl() -{ -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.h b/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.h deleted file mode 100644 index c3245a481..000000000 --- a/Source/WebKit2/UIProcess/efl/WebPopupItemEfl.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 WebPopupItemEfl_h -#define WebPopupItemEfl_h - -#include "APIObject.h" -#include "WebPopupItem.h" -#include <wtf/PassRefPtr.h> - -namespace WebKit { - -class WebPopupItemEfl : public TypedAPIObject<APIObject::TypePopupMenuItem> { -public: - static PassRefPtr<WebPopupItemEfl> create(const WebPopupItem& data) - { - return adoptRef(new WebPopupItemEfl(data)); - } - - virtual ~WebPopupItemEfl(); - const WebPopupItem& data() const { return m_data; } - - WebPopupItem::Type itemType() const { return m_data.m_type; } - String text() const { return m_data.m_text; } - WebCore::TextDirection textDirection() const { return m_data.m_textDirection; } - bool hasTextDirectionOverride() const { return m_data.m_hasTextDirectionOverride; } - String toolTipText() const { return m_data.m_toolTip; } - String accessibilityText() const { return m_data.m_accessibilityText; } - bool isEnabled() const { return m_data.m_isEnabled; } - bool isLabel() const { return m_data.m_isLabel; } - bool isSelected() const { return m_data.m_isSelected; } - -private: - explicit WebPopupItemEfl(const WebPopupItem&); - - WebPopupItem m_data; -}; - -} // namespace WebKit - -#endif // WebPopupItemEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.h b/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.h deleted file mode 100644 index 6bcf83344..000000000 --- a/Source/WebKit2/UIProcess/efl/WebPopupMenuListenerEfl.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2012 Samsung Electronics - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebPopupMenuListenerEfl_h -#define WebPopupMenuListenerEfl_h - -#include "WebPopupMenuProxy.h" - -namespace WebKit { - -class WebPopupMenuListenerEfl : public WebPopupMenuProxy { -public: - static PassRefPtr<WebPopupMenuListenerEfl> create(WebPopupMenuProxy::Client* client) - { - return adoptRef(new WebPopupMenuListenerEfl(client)); - } - - void valueChanged(int newSelectedIndex); - -private: - WebPopupMenuListenerEfl(WebPopupMenuProxy::Client*); -}; - -} // namespace WebKit - -#endif // WebPopupMenuListenerEfl_h diff --git a/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.cpp b/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.cpp deleted file mode 100644 index 2e6ff5a6b..000000000 --- a/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 "WebUIPopupMenuClient.h" - -#include "ImmutableArray.h" -#include "WKAPICast.h" -#include "WebPopupItemEfl.h" -#include "WebPopupMenuListenerEfl.h" - -using namespace WebCore; -using namespace WebKit; - -void WebUIPopupMenuClient::showPopupMenu(WebPageProxy* pageProxy, WebPopupMenuProxy* popupMenuProxy, const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, int32_t selectedIndex) -{ - if (!m_client.showPopupMenu) - return; - - Vector<RefPtr<APIObject> > webPopupItems; - size_t size = items.size(); - for (size_t i = 0; i < size; ++i) - webPopupItems.append(WebPopupItemEfl::create(items[i])); - - RefPtr<ImmutableArray> ItemsArray; - if (!webPopupItems.isEmpty()) - ItemsArray = ImmutableArray::adopt(webPopupItems); - - m_client.showPopupMenu(toAPI(pageProxy), toAPI(static_cast<WebPopupMenuListenerEfl*>(popupMenuProxy)), toAPI(rect), toAPI(textDirection), pageScaleFactor, toAPI(ItemsArray.get()), selectedIndex, m_client.clientInfo); -} - -void WebUIPopupMenuClient::hidePopupMenu(WebPageProxy* pageProxy) -{ - if (m_client.hidePopupMenu) - m_client.hidePopupMenu(toAPI(pageProxy), m_client.clientInfo); -} diff --git a/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.h b/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.h deleted file mode 100644 index 25932e8be..000000000 --- a/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2013 Samsung Electronics. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WebUIPopupMenuClient_h -#define WebUIPopupMenuClient_h - -#include "APIClient.h" -#include "APIObject.h" -#include "WKPageEfl.h" -#include "WebPopupItem.h" -#include <WebCore/IntRect.h> -#include <WebCore/TextDirection.h> - -namespace WebKit { - -class WebPageProxy; -class WebPopupMenuProxy; - -class WebUIPopupMenuClient : public APIClient<WKPageUIPopupMenuClient, kWKPageUIPopupMenuClientCurrentVersion> { -public: - void showPopupMenu(WebPageProxy*, WebPopupMenuProxy*, const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, int32_t selectedIndex); - void hidePopupMenu(WebPageProxy*); -}; - -} // namespace WebKit -#endif // WebUIPopupMenuClient_h diff --git a/Source/WebKit2/UIProcess/efl/WebViewEfl.cpp b/Source/WebKit2/UIProcess/efl/WebViewEfl.cpp deleted file mode 100644 index 5660be111..000000000 --- a/Source/WebKit2/UIProcess/efl/WebViewEfl.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebViewEfl.h" - -#include "DownloadManagerEfl.h" -#include "EwkView.h" -#include "InputMethodContextEfl.h" -#include "WebContextMenuProxyEfl.h" -#include "WebPopupMenuListenerEfl.h" -#include "ewk_context_private.h" -#include <WebCore/CoordinatedGraphicsScene.h> -#include <WebCore/PlatformContextCairo.h> - -#if ENABLE(FULLSCREEN_API) -#include "WebFullScreenManagerProxy.h" -#endif - -#if ENABLE(TOUCH_EVENTS) -#include "EwkTouchEvent.h" -#endif - -using namespace EwkViewCallbacks; -using namespace WebCore; - -namespace WebKit { - -PassRefPtr<WebView> WebView::create(WebContext* context, WebPageGroup* pageGroup) -{ - return adoptRef(new WebViewEfl(context, pageGroup)); -} - -WebViewEfl::WebViewEfl(WebContext* context, WebPageGroup* pageGroup) - : WebView(context, pageGroup) - , m_ewkView(0) -{ -} - -void WebViewEfl::setEwkView(EwkView* ewkView) -{ - m_ewkView = ewkView; - -#if ENABLE(FULLSCREEN_API) - m_page->fullScreenManager()->setWebView(ewkView->evasObject()); -#endif -} - -void WebViewEfl::paintToCairoSurface(cairo_surface_t* surface) -{ - CoordinatedGraphicsScene* scene = coordinatedGraphicsScene(); - if (!scene) - return; - - PlatformContextCairo context(cairo_create(surface)); - - const FloatPoint& position = contentPosition(); - double effectiveScale = m_page->deviceScaleFactor() * contentScaleFactor(); - - cairo_matrix_t transform = { effectiveScale, 0, 0, effectiveScale, - position.x() * m_page->deviceScaleFactor(), - position.y() * m_page->deviceScaleFactor() }; - cairo_set_matrix(context.cr(), &transform); - scene->paintToGraphicsContext(&context); -} - -PassRefPtr<WebPopupMenuProxy> WebViewEfl::createPopupMenuProxy(WebPageProxy* page) -{ - return WebPopupMenuListenerEfl::create(page); -} - -PassRefPtr<WebContextMenuProxy> WebViewEfl::createContextMenuProxy(WebPageProxy* page) -{ - return WebContextMenuProxyEfl::create(m_ewkView, page); -} - -void WebViewEfl::setCursor(const Cursor& cursor) -{ - m_ewkView->setCursor(cursor); -} - -void WebViewEfl::updateTextInputState() -{ - if (InputMethodContextEfl* inputMethodContext = m_ewkView->inputMethodContext()) - inputMethodContext->updateTextInputState(); -} - -void WebViewEfl::handleDownloadRequest(DownloadProxy* download) -{ - EwkContext* context = m_ewkView->ewkContext(); - context->downloadManager()->registerDownloadJob(toAPI(download), m_ewkView); -} - -void WebViewEfl::setThemePath(const String& theme) -{ - m_page->setThemePath(theme); -} - -#if ENABLE(TOUCH_EVENTS) -void WebViewEfl::sendTouchEvent(EwkTouchEvent* touchEvent) -{ - ASSERT(touchEvent); - m_page->handleTouchEvent(NativeWebTouchEvent(touchEvent, transformFromScene())); -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gstreamer/InstallMissingMediaPluginsPermissionRequest.cpp b/Source/WebKit2/UIProcess/gstreamer/InstallMissingMediaPluginsPermissionRequest.cpp new file mode 100644 index 000000000..11d759e1c --- /dev/null +++ b/Source/WebKit2/UIProcess/gstreamer/InstallMissingMediaPluginsPermissionRequest.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2015 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. + */ + +#include "config.h" +#include "InstallMissingMediaPluginsPermissionRequest.h" + +#if ENABLE(VIDEO) && USE(GSTREAMER) +#include "WebPageMessages.h" +#include "WebPageProxy.h" +#include <wtf/text/CString.h> + +namespace WebKit { + +InstallMissingMediaPluginsPermissionRequest::InstallMissingMediaPluginsPermissionRequest(WebPageProxy& page, const String& details, const String& description) + : m_page(&page) + , m_details(details) + , m_description(description) +{ +} + +InstallMissingMediaPluginsPermissionRequest::~InstallMissingMediaPluginsPermissionRequest() +{ +} + +void InstallMissingMediaPluginsPermissionRequest::allow(GUniquePtr<GstInstallPluginsContext>&& context) +{ + if (!m_page->isValid()) + return; + + CString detail = m_details.utf8(); + const char* detailArray[2] = { detail.data(), nullptr }; + ref(); + GstInstallPluginsReturn result = gst_install_plugins_async(detailArray, context.get(), [](GstInstallPluginsReturn result, gpointer userData) { + RefPtr<InstallMissingMediaPluginsPermissionRequest> request = adoptRef(static_cast<InstallMissingMediaPluginsPermissionRequest*>(userData)); + request->didEndRequestInstallMissingMediaPlugins(static_cast<uint32_t>(result)); + }, this); + + if (result != GST_INSTALL_PLUGINS_STARTED_OK) { + // If the installer didn't start, the callback will not be called, so remove the ref manually. + deref(); + didEndRequestInstallMissingMediaPlugins(static_cast<uint32_t>(result)); + WTFLogAlways("Missing GStreamer Plugin: %s\n", detail.data()); + } +} + +void InstallMissingMediaPluginsPermissionRequest::deny() +{ + didEndRequestInstallMissingMediaPlugins(static_cast<uint32_t>(GST_INSTALL_PLUGINS_USER_ABORT)); +} + +void InstallMissingMediaPluginsPermissionRequest::didEndRequestInstallMissingMediaPlugins(uint32_t result) +{ + if (!m_page->isValid()) + return; + + m_page->send(Messages::WebPage::DidEndRequestInstallMissingMediaPlugins(result)); +} + +} // namespace WebKit + +#endif // ENABLE(VIDEO) && USE(GSTREAMER) diff --git a/Source/WebKit2/UIProcess/gstreamer/InstallMissingMediaPluginsPermissionRequest.h b/Source/WebKit2/UIProcess/gstreamer/InstallMissingMediaPluginsPermissionRequest.h new file mode 100644 index 000000000..5416014cb --- /dev/null +++ b/Source/WebKit2/UIProcess/gstreamer/InstallMissingMediaPluginsPermissionRequest.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2015 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. + */ + +#ifndef InstallMissingMediaPluginsPermissionRequest_h +#define InstallMissingMediaPluginsPermissionRequest_h + +#if ENABLE(VIDEO) && USE(GSTREAMER) +#include <WebCore/GUniquePtrGStreamer.h> +#include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> +#include <wtf/text/WTFString.h> + +namespace WebKit { + +class WebPageProxy; + +class InstallMissingMediaPluginsPermissionRequest : public RefCounted<InstallMissingMediaPluginsPermissionRequest> { +public: + static Ref<InstallMissingMediaPluginsPermissionRequest> create(WebPageProxy& page, const String& details, const String& description) + { + return adoptRef(*new InstallMissingMediaPluginsPermissionRequest(page, details, description)); + } + ~InstallMissingMediaPluginsPermissionRequest(); + + void allow(GUniquePtr<GstInstallPluginsContext>&& = nullptr); + void deny(); + + WebPageProxy& page() const { return *m_page; } + const String& details() const { return m_details; } + const String& description() const { return m_description; } + +private: + InstallMissingMediaPluginsPermissionRequest(WebPageProxy&, const String& details, const String& description); + + void didEndRequestInstallMissingMediaPlugins(uint32_t result); + + RefPtr<WebPageProxy> m_page; + String m_details; + String m_description; +}; + +} // namespace WebKit + +#else + +namespace WebKit { +class InstallMissingMediaPluginsPermissionRequest; +} // namespace WebKit + +#endif // ENABLE(VIDEO) && USE(GSTREAMER) +#endif // InstallMissingMediaPluginsPermissionRequest_h diff --git a/Source/WebKit2/UIProcess/gstreamer/WebPageProxyGStreamer.cpp b/Source/WebKit2/UIProcess/gstreamer/WebPageProxyGStreamer.cpp new file mode 100644 index 000000000..2ed9c34cf --- /dev/null +++ b/Source/WebKit2/UIProcess/gstreamer/WebPageProxyGStreamer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2015 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. + */ + +#include "config.h" +#include "WebPageProxy.h" + +#if ENABLE(VIDEO) && USE(GSTREAMER) +#include "InstallMissingMediaPluginsPermissionRequest.h" +#include "PageClient.h" + +namespace WebKit { + +void WebPageProxy::requestInstallMissingMediaPlugins(const String& details, const String& description) +{ + RefPtr<InstallMissingMediaPluginsPermissionRequest> request = InstallMissingMediaPluginsPermissionRequest::create(*this, details, description); + if (m_pageClient.decidePolicyForInstallMissingMediaPluginsPermissionRequest(*request)) + return; + + request->deny(); +} + +} // namespace WebKit + +#endif // ENABLE(VIDEO) && USE(GSTREAMER) diff --git a/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.cpp b/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.cpp deleted file mode 100644 index 2b45fb61f..000000000 --- a/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2013, Opera Software ASA. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Opera Software ASA nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "ExperimentalFeatures.h" - -namespace WebKit { - -struct Setting { - ExperimentalFeatures::Feature feature; - const char* featureName; - bool enabled; -}; - -static Setting settings[] = { - { ExperimentalFeatures::RegionBasedColumns, "REGION_BASED_COLUMNS", false } -}; - -ExperimentalFeatures::ExperimentalFeatures() -{ - parseEnvironment(); -} - -bool ExperimentalFeatures::isEnabled(Feature feature) -{ - return settings[feature].enabled; -} - -void ExperimentalFeatures::setEnableByName(const String& key, bool enable) -{ - for (unsigned i = 0; i < WTF_ARRAY_LENGTH(settings); i++) { - if (key == settings[i].featureName) { - settings[i].enabled = enable; - break; - } - } -} - -void ExperimentalFeatures::parseEnvironment() -{ - const char* data = getenv("WEBKITGTK_EXPERIMENTAL_FEATURES"); - if (!data) - return; - if (!strcmp(data, "all")) { - for (unsigned i = 0; i < WTF_ARRAY_LENGTH(settings); i++) - settings[i].enabled = true; - } else { - Vector<String> variables; - String(data).split(',', false, variables); - for (unsigned i = 0; i < variables.size(); i++) { - Vector<String> keyAndValue; - variables[i].split('=', false, keyAndValue); - if (keyAndValue.size() != 2) - continue; - setEnableByName(keyAndValue[0], keyAndValue[1][0] - '0'); - } - } -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.h b/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.h deleted file mode 100644 index eb0422884..000000000 --- a/Source/WebKit2/UIProcess/gtk/ExperimentalFeatures.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2013, Opera Software ASA. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Opera Software ASA nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef ExperimentalFeatures_h -#define ExperimentalFeatures_h - -#include <wtf/text/WTFString.h> - -namespace WebKit { - -class ExperimentalFeatures { -public: - enum Feature { - RegionBasedColumns - }; - - ExperimentalFeatures(); - - bool isEnabled(Feature); - -private: - void setEnableByName(const String& key, bool enable); - void parseEnvironment(); -}; - -} // namespace WebKit - -#endif // ExperimentalFeatures_h diff --git a/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp b/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp deleted file mode 100644 index 6bc419079..000000000 --- a/Source/WebKit2/UIProcess/gtk/TextCheckerGtk.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "TextChecker.h" - -#include "TextCheckerState.h" -#include "WebTextChecker.h" -#include <WebCore/NotImplemented.h> - -using namespace WebCore; - -namespace WebKit { - -static TextCheckerState textCheckerState; - -const TextCheckerState& TextChecker::state() -{ - static bool didInitializeState = false; - if (didInitializeState) - return textCheckerState; - - WebTextCheckerClient& client = WebTextChecker::shared()->client(); - textCheckerState.isContinuousSpellCheckingEnabled = client.continuousSpellCheckingEnabled(); - textCheckerState.isGrammarCheckingEnabled = client.grammarCheckingEnabled(); - - didInitializeState = true; - - return textCheckerState; -} - -bool TextChecker::isContinuousSpellCheckingAllowed() -{ - return WebTextChecker::shared()->client().continuousSpellCheckingAllowed(); -} - -void TextChecker::setContinuousSpellCheckingEnabled(bool isContinuousSpellCheckingEnabled) -{ - if (state().isContinuousSpellCheckingEnabled == isContinuousSpellCheckingEnabled) - return; - textCheckerState.isContinuousSpellCheckingEnabled = isContinuousSpellCheckingEnabled; - WebTextChecker::shared()->client().setContinuousSpellCheckingEnabled(isContinuousSpellCheckingEnabled); -} - -void TextChecker::setGrammarCheckingEnabled(bool isGrammarCheckingEnabled) -{ - if (state().isGrammarCheckingEnabled == isGrammarCheckingEnabled) - return; - textCheckerState.isGrammarCheckingEnabled = isGrammarCheckingEnabled; - WebTextChecker::shared()->client().setGrammarCheckingEnabled(isGrammarCheckingEnabled); -} - -void TextChecker::continuousSpellCheckingEnabledStateChanged(bool enabled) -{ - textCheckerState.isContinuousSpellCheckingEnabled = enabled; -} - -void TextChecker::grammarCheckingEnabledStateChanged(bool enabled) -{ - textCheckerState.isGrammarCheckingEnabled = enabled; -} - -int64_t TextChecker::uniqueSpellDocumentTag(WebPageProxy* page) -{ - return WebTextChecker::shared()->client().uniqueSpellDocumentTag(page); -} - -void TextChecker::closeSpellDocumentWithTag(int64_t tag) -{ - WebTextChecker::shared()->client().closeSpellDocumentWithTag(tag); -} - -void TextChecker::checkSpellingOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, int32_t& misspellingLocation, int32_t& misspellingLength) -{ - WebTextChecker::shared()->client().checkSpellingOfString(spellDocumentTag, String(text, length), misspellingLocation, misspellingLength); -} - -void TextChecker::checkGrammarOfString(int64_t spellDocumentTag, const UChar* text, uint32_t length, Vector<WebCore::GrammarDetail>& grammarDetails, int32_t& badGrammarLocation, int32_t& badGrammarLength) -{ - WebTextChecker::shared()->client().checkGrammarOfString(spellDocumentTag, String(text, length), grammarDetails, badGrammarLocation, badGrammarLength); -} - -bool TextChecker::spellingUIIsShowing() -{ - return WebTextChecker::shared()->client().spellingUIIsShowing(); -} - -void TextChecker::toggleSpellingUIIsShowing() -{ - WebTextChecker::shared()->client().toggleSpellingUIIsShowing(); -} - -void TextChecker::updateSpellingUIWithMisspelledWord(int64_t spellDocumentTag, const String& misspelledWord) -{ - WebTextChecker::shared()->client().updateSpellingUIWithMisspelledWord(spellDocumentTag, misspelledWord); -} - -void TextChecker::updateSpellingUIWithGrammarString(int64_t spellDocumentTag, const String& badGrammarPhrase, const GrammarDetail& grammarDetail) -{ - WebTextChecker::shared()->client().updateSpellingUIWithGrammarString(spellDocumentTag, badGrammarPhrase, grammarDetail); -} - -void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& context, Vector<String>& guesses) -{ - WebTextChecker::shared()->client().guessesForWord(spellDocumentTag, word, guesses); -} - -void TextChecker::learnWord(int64_t spellDocumentTag, const String& word) -{ - WebTextChecker::shared()->client().learnWord(spellDocumentTag, word); -} - -void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) -{ - WebTextChecker::shared()->client().ignoreWord(spellDocumentTag, word); -} - -void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion>) -{ - notImplemented(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp deleted file mode 100644 index 22ba2f176..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebContextGtk.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2012 Samsung Electronics Ltd. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebContext.h" - -#include "Logging.h" -#include "WebCookieManagerProxy.h" -#include "WebInspectorServer.h" -#include "WebProcessCreationParameters.h" -#include "WebProcessMessages.h" -#include "WebSoupRequestManagerProxy.h" -#include <WebCore/FileSystem.h> -#include <WebCore/NotImplemented.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> - -namespace WebKit { - -static void initInspectorServer() -{ -#if ENABLE(INSPECTOR_SERVER) - static bool initialized = false; - if (initialized) - return; - - initialized = true; - String serverAddress(g_getenv("WEBKIT_INSPECTOR_SERVER")); - - if (!serverAddress.isNull()) { - String bindAddress = "127.0.0.1"; - unsigned short port = 2999; - - Vector<String> result; - serverAddress.split(":", result); - - if (result.size() == 2) { - bindAddress = result[0]; - bool ok = false; - port = result[1].toInt(&ok); - if (!ok) { - port = 2999; - LOG_ERROR("Couldn't parse the port. Use 2999 instead."); - } - } else - LOG_ERROR("Couldn't parse %s, wrong format? Use 127.0.0.1:2999 instead.", serverAddress.utf8().data()); - - if (!WebInspectorServer::shared().listen(bindAddress, port)) - LOG_ERROR("Couldn't start listening on: IP address=%s, port=%d.", bindAddress.utf8().data(), port); - return; - } - - LOG(InspectorServer, "To start inspector server set WEBKIT_INSPECTOR_SERVER to 127.0.0.1:2999 for example."); -#endif -} - -WTF::String WebContext::platformDefaultApplicationCacheDirectory() const -{ - GOwnPtr<gchar> cacheDirectory(g_build_filename(g_get_user_cache_dir(), "webkitgtk", "applications", NULL)); - return WebCore::filenameToString(cacheDirectory.get()); -} - -void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) -{ - initInspectorServer(); - - parameters.urlSchemesRegistered = supplement<WebSoupRequestManagerProxy>()->registeredURISchemes(); - supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(parameters.cookiePersistentStoragePath, parameters.cookiePersistentStorageType); - parameters.cookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy; - parameters.ignoreTLSErrors = m_ignoreTLSErrors; - parameters.shouldTrackVisitedLinks = true; -} - -void WebContext::platformInvalidateContext() -{ -} - -String WebContext::platformDefaultDatabaseDirectory() const -{ - GOwnPtr<gchar> databaseDirectory(g_build_filename(g_get_user_data_dir(), "webkitgtk", "databases", NULL)); - return WebCore::filenameToString(databaseDirectory.get()); -} - -String WebContext::platformDefaultIconDatabasePath() const -{ - GOwnPtr<gchar> databaseDirectory(g_build_filename(g_get_user_data_dir(), "webkitgtk", "icondatabase", NULL)); - return WebCore::filenameToString(databaseDirectory.get()); -} - -String WebContext::platformDefaultLocalStorageDirectory() const -{ - GOwnPtr<gchar> storageDirectory(g_build_filename(g_get_user_data_dir(), "webkitgtk", "localstorage", NULL)); - return WebCore::filenameToString(storageDirectory.get()); -} - -String WebContext::platformDefaultDiskCacheDirectory() const -{ - GOwnPtr<char> diskCacheDirectory(g_build_filename(g_get_user_cache_dir(), g_get_prgname(), NULL)); - return WebCore::filenameToString(diskCacheDirectory.get()); -} - -String WebContext::platformDefaultCookieStorageDirectory() const -{ - notImplemented(); - return String(); -} - -void WebContext::setIgnoreTLSErrors(bool ignoreTLSErrors) -{ - m_ignoreTLSErrors = ignoreTLSErrors; - sendToAllProcesses(Messages::WebProcess::SetIgnoreTLSErrors(m_ignoreTLSErrors)); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp deleted file mode 100644 index d7d068340..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#include "config.h" -#include "WebContextMenuProxyGtk.h" - -#if ENABLE(CONTEXT_MENUS) - -#include "NativeWebMouseEvent.h" -#include "WebContextMenuItemData.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebPageProxy.h" -#include <WebCore/GtkUtilities.h> -#include <gtk/gtk.h> -#include <wtf/text/CString.h> - - -static const char* gContextMenuActionId = "webkit-context-menu-action"; - -using namespace WebCore; - -namespace WebKit { - -static void contextMenuItemActivatedCallback(GtkAction* action, WebPageProxy* page) -{ - gboolean isToggle = GTK_IS_TOGGLE_ACTION(action); - WebKit::WebContextMenuItemData item(isToggle ? WebCore::CheckableActionType : WebCore::ActionType, - static_cast<WebCore::ContextMenuAction>(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(action), gContextMenuActionId))), - String::fromUTF8(gtk_action_get_label(action)), gtk_action_get_sensitive(action), - isToggle ? gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(action)) : false); - page->contextMenuItemSelected(item); -} - -static void contextMenuItemVisibilityChanged(GtkAction* action, GParamSpec*, WebContextMenuProxyGtk* contextMenuProxy) -{ - GtkMenu* menu = contextMenuProxy->gtkMenu(); - if (!menu) - return; - - GOwnPtr<GList> items(gtk_container_get_children(GTK_CONTAINER(menu))); - bool previousVisibleItemIsNotASeparator = false; - GtkWidget* lastItemVisibleSeparator = 0; - for (GList* iter = items.get(); iter; iter = g_list_next(iter)) { - GtkWidget* widget = GTK_WIDGET(iter->data); - - if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) { - if (previousVisibleItemIsNotASeparator) { - gtk_widget_show(widget); - lastItemVisibleSeparator = widget; - previousVisibleItemIsNotASeparator = false; - } else - gtk_widget_hide(widget); - } else if (gtk_widget_get_visible(widget)) { - lastItemVisibleSeparator = 0; - previousVisibleItemIsNotASeparator = true; - } - } - - if (lastItemVisibleSeparator) - gtk_widget_hide(lastItemVisibleSeparator); -} - -void WebContextMenuProxyGtk::append(ContextMenuItem& menuItem) -{ - GtkAction* action = menuItem.gtkAction(); - if (action) { - switch (menuItem.type()) { - case ActionType: - case CheckableActionType: - g_object_set_data(G_OBJECT(action), gContextMenuActionId, GINT_TO_POINTER(menuItem.action())); - g_signal_connect(action, "activate", G_CALLBACK(contextMenuItemActivatedCallback), m_page); - // Fall through. - case SubmenuType: - g_signal_connect(action, "notify::visible", G_CALLBACK(contextMenuItemVisibilityChanged), this); - break; - case SeparatorType: - break; - } - } - - m_menu.appendItem(menuItem); -} - -// Populate the context menu ensuring that: -// - There aren't separators next to each other. -// - There aren't separators at the beginning of the menu. -// - There aren't separators at the end of the menu. -void WebContextMenuProxyGtk::populate(Vector<ContextMenuItem>& items) -{ - bool previousIsSeparator = false; - bool isEmpty = true; - for (size_t i = 0; i < items.size(); i++) { - ContextMenuItem& menuItem = items.at(i); - if (menuItem.type() == SeparatorType) { - previousIsSeparator = true; - continue; - } - - if (previousIsSeparator && !isEmpty) - append(items.at(i - 1)); - previousIsSeparator = false; - - append(menuItem); - isEmpty = false; - } -} - -void WebContextMenuProxyGtk::populate(const Vector<WebContextMenuItemData>& items) -{ - for (size_t i = 0; i < items.size(); i++) { - ContextMenuItem menuitem = items.at(i).core(); - append(menuitem); - } -} - -void WebContextMenuProxyGtk::showContextMenu(const WebCore::IntPoint& position, const Vector<WebContextMenuItemData>& items) -{ - if (!items.isEmpty()) - populate(items); - - if (!m_menu.itemCount()) - return; - - m_popupPosition = convertWidgetPointToScreenPoint(m_webView, position); - - // Display menu initiated by right click (mouse button pressed = 3). - NativeWebMouseEvent* mouseEvent = m_page->currentlyProcessedMouseDownEvent(); - const GdkEvent* event = mouseEvent ? mouseEvent->nativeEvent() : 0; - gtk_menu_attach_to_widget(m_menu.platformDescription(), GTK_WIDGET(m_webView), 0); - gtk_menu_popup(m_menu.platformDescription(), 0, 0, reinterpret_cast<GtkMenuPositionFunc>(menuPositionFunction), this, - event ? event->button.button : 3, event ? event->button.time : GDK_CURRENT_TIME); -} - -void WebContextMenuProxyGtk::hideContextMenu() -{ - gtk_menu_popdown(m_menu.platformDescription()); -} - -WebContextMenuProxyGtk::WebContextMenuProxyGtk(GtkWidget* webView, WebPageProxy* page) - : m_webView(webView) - , m_page(page) -{ - webkitWebViewBaseSetActiveContextMenuProxy(WEBKIT_WEB_VIEW_BASE(m_webView), this); -} - -WebContextMenuProxyGtk::~WebContextMenuProxyGtk() -{ - webkitWebViewBaseSetActiveContextMenuProxy(WEBKIT_WEB_VIEW_BASE(m_webView), 0); -} - -void WebContextMenuProxyGtk::menuPositionFunction(GtkMenu* menu, gint* x, gint* y, gboolean* pushIn, WebContextMenuProxyGtk* popupMenu) -{ - GtkRequisition menuSize; - gtk_widget_get_preferred_size(GTK_WIDGET(menu), &menuSize, 0); - - GdkScreen* screen = gtk_widget_get_screen(popupMenu->m_webView); - *x = popupMenu->m_popupPosition.x(); - if ((*x + menuSize.width) >= gdk_screen_get_width(screen)) - *x -= menuSize.width; - - *y = popupMenu->m_popupPosition.y(); - if ((*y + menuSize.height) >= gdk_screen_get_height(screen)) - *y -= menuSize.height; - - *pushIn = FALSE; -} - -} // namespace WebKit -#endif // ENABLE(CONTEXT_MENUS) diff --git a/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.h b/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.h deleted file mode 100644 index 144655f4d..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebContextMenuProxyGtk.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#ifndef WebContextMenuProxyGtk_h -#define WebContextMenuProxyGtk_h - -#if ENABLE(CONTEXT_MENUS) - -#include "WebContextMenuProxy.h" -#include <WebCore/ContextMenu.h> -#include <WebCore/IntPoint.h> - -namespace WebKit { - -class WebContextMenuItemData; -class WebPageProxy; - -class WebContextMenuProxyGtk : public WebContextMenuProxy { -public: - static PassRefPtr<WebContextMenuProxyGtk> create(GtkWidget* webView, WebPageProxy* page) - { - return adoptRef(new WebContextMenuProxyGtk(webView, page)); - } - ~WebContextMenuProxyGtk(); - - virtual void showContextMenu(const WebCore::IntPoint&, const Vector<WebContextMenuItemData>&); - virtual void hideContextMenu(); - - void populate(Vector<WebCore::ContextMenuItem>&); - GtkMenu* gtkMenu() const { return m_menu.platformDescription(); } - -private: - WebContextMenuProxyGtk(GtkWidget*, WebPageProxy*); - - void append(WebCore::ContextMenuItem&); - void populate(const Vector<WebContextMenuItemData>&); - static void menuPositionFunction(GtkMenu*, gint*, gint*, gboolean*, WebContextMenuProxyGtk*); - - GtkWidget* m_webView; - WebPageProxy* m_page; - WebCore::ContextMenu m_menu; - WebCore::IntPoint m_popupPosition; -}; - - -} // namespace WebKit - -#endif // ENABLE(CONTEXT_MENUS) -#endif // WebContextMenuProxyGtk_h diff --git a/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp deleted file mode 100644 index 6fd0a9f2b..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebFullScreenManagerProxyGtk.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2011 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 "WebFullScreenManagerProxy.h" - -#if ENABLE(FULLSCREEN_API) - -#include "WebContext.h" -#include "WebFullScreenManagerMessages.h" -#include "WebFullScreenManagerProxyMessages.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebProcess.h" -#include <WebCore/NotImplemented.h> - -using namespace WebCore; - -namespace WebKit { - -void WebFullScreenManagerProxy::invalidate() -{ - m_page->process()->removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); - m_webView = 0; -} - -void WebFullScreenManagerProxy::close() -{ - notImplemented(); -} - -bool WebFullScreenManagerProxy::isFullScreen() -{ - notImplemented(); - return false; -} - -void WebFullScreenManagerProxy::enterFullScreen() -{ - if (!m_webView) - return; - - webkitWebViewBaseEnterFullScreen(m_webView); -} - -void WebFullScreenManagerProxy::exitFullScreen() -{ - if (!m_webView) - return; - - webkitWebViewBaseExitFullScreen(m_webView); -} - -void WebFullScreenManagerProxy::beganEnterFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) -{ - notImplemented(); -} - -void WebFullScreenManagerProxy::beganExitFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) -{ - notImplemented(); -} - -} // namespace WebKit - -#endif // ENABLE(FULLSCREEN_API) diff --git a/Source/WebKit2/UIProcess/gtk/WebInspectorClientGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebInspectorClientGtk.cpp deleted file mode 100644 index 448f42378..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebInspectorClientGtk.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#include "config.h" -#include "WebInspectorClientGtk.h" - -#include "WKAPICast.h" -#include "WKSharedAPICast.h" -#include <wtf/text/WTFString.h> - -namespace WebKit { - -bool WebInspectorClientGtk::openWindow(WebInspectorProxy* inspector) -{ - if (!m_client.openWindow) - return false; - return m_client.openWindow(toAPI(inspector), m_client.clientInfo); -} - -void WebInspectorClientGtk::didClose(WebInspectorProxy* inspector) -{ - if (!m_client.didClose) - return; - m_client.didClose(toAPI(inspector), m_client.clientInfo); -} - -bool WebInspectorClientGtk::bringToFront(WebInspectorProxy* inspector) -{ - if (!m_client.bringToFront) - return false; - return m_client.bringToFront(toAPI(inspector), m_client.clientInfo); -} - -void WebInspectorClientGtk::inspectedURLChanged(WebInspectorProxy* inspector, const String& url) -{ - if (!m_client.inspectedURLChanged) - return; - m_client.inspectedURLChanged(toAPI(inspector), toAPI(url.impl()), m_client.clientInfo); -} - -bool WebInspectorClientGtk::attach(WebInspectorProxy* inspector) -{ - if (!m_client.attach) - return false; - return m_client.attach(toAPI(inspector), m_client.clientInfo); -} - -bool WebInspectorClientGtk::detach(WebInspectorProxy* inspector) -{ - if (!m_client.detach) - return false; - return m_client.detach(toAPI(inspector), m_client.clientInfo); -} - -void WebInspectorClientGtk::didChangeAttachedHeight(WebInspectorProxy* inspector, unsigned height) -{ - if (!m_client.didChangeAttachedHeight) - return; - m_client.didChangeAttachedHeight(toAPI(inspector), height, m_client.clientInfo); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp deleted file mode 100644 index a4c771a3c..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebInspectorProxyGtk.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * Copyright (C) 2012 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. - */ - -#include "config.h" -#include "WebInspectorProxy.h" - -#if ENABLE(INSPECTOR) - -#include "WebKitWebViewBasePrivate.h" -#include "WebProcessProxy.h" -#include <WebCore/FileSystem.h> -#include <WebCore/GtkUtilities.h> -#include <WebCore/NotImplemented.h> -#include <glib/gi18n-lib.h> -#include <gtk/gtk.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> -#include <wtf/text/WTFString.h> - -namespace WebKit { - -static const char* inspectorFilesBasePath() -{ - const gchar* environmentPath = g_getenv("WEBKIT_INSPECTOR_PATH"); - if (environmentPath && g_file_test(environmentPath, G_FILE_TEST_IS_DIR)) - return environmentPath; - - static const char* inspectorFilesPath = DATA_DIR G_DIR_SEPARATOR_S "webkitgtk-" WEBKITGTK_API_VERSION_STRING - G_DIR_SEPARATOR_S "webinspector" G_DIR_SEPARATOR_S; - return inspectorFilesPath; -} - -static void inspectorViewDestroyed(GtkWidget*, gpointer userData) -{ - WebInspectorProxy* inspectorProxy = static_cast<WebInspectorProxy*>(userData); - - // Inform WebProcess about webinspector closure. Not doing so, - // results in failure of subsequent invocation of webinspector. - inspectorProxy->close(); -} - -void WebInspectorProxy::initializeInspectorClientGtk(const WKInspectorClientGtk* inspectorClient) -{ - m_client.initialize(inspectorClient); -} - -WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() -{ - ASSERT(m_page); - ASSERT(!m_inspectorView); - m_inspectorView = GTK_WIDGET(webkitWebViewBaseCreate(page()->process()->context(), inspectorPageGroup())); - g_object_add_weak_pointer(G_OBJECT(m_inspectorView), reinterpret_cast<void**>(&m_inspectorView)); - return webkitWebViewBaseGetPage(WEBKIT_WEB_VIEW_BASE(m_inspectorView)); -} - -void WebInspectorProxy::createInspectorWindow() -{ - if (m_client.openWindow(this)) - return; - - ASSERT(!m_inspectorWindow); - m_inspectorWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); - - GtkWidget* inspectedViewParent = gtk_widget_get_toplevel(m_page->viewWidget()); - if (WebCore::widgetIsOnscreenToplevelWindow(inspectedViewParent)) - gtk_window_set_transient_for(GTK_WINDOW(m_inspectorWindow), GTK_WINDOW(inspectedViewParent)); - - gtk_window_set_title(GTK_WINDOW(m_inspectorWindow), _("Web Inspector")); - gtk_window_set_default_size(GTK_WINDOW(m_inspectorWindow), initialWindowWidth, initialWindowHeight); - - gtk_container_add(GTK_CONTAINER(m_inspectorWindow), m_inspectorView); - gtk_widget_show(m_inspectorView); - - g_object_add_weak_pointer(G_OBJECT(m_inspectorWindow), reinterpret_cast<void**>(&m_inspectorWindow)); - gtk_window_present(GTK_WINDOW(m_inspectorWindow)); -} - -void WebInspectorProxy::platformOpen() -{ - ASSERT(!m_inspectorWindow); - ASSERT(m_inspectorView); - - if (m_isAttached) - platformAttach(); - else - createInspectorWindow(); - g_signal_connect(m_inspectorView, "destroy", G_CALLBACK(inspectorViewDestroyed), this); -} - -void WebInspectorProxy::platformDidClose() -{ - if (m_inspectorView) - g_signal_handlers_disconnect_by_func(m_inspectorView, reinterpret_cast<void*>(inspectorViewDestroyed), this); - - m_client.didClose(this); - - if (m_inspectorWindow) { - gtk_widget_destroy(m_inspectorWindow); - m_inspectorWindow = 0; - } - m_inspectorView = 0; -} - -void WebInspectorProxy::platformHide() -{ - notImplemented(); -} - -void WebInspectorProxy::platformBringToFront() -{ - if (m_client.bringToFront(this)) - return; - - GtkWidget* parent = gtk_widget_get_toplevel(m_inspectorView); - if (WebCore::widgetIsOnscreenToplevelWindow(parent)) - gtk_window_present(GTK_WINDOW(parent)); -} - -bool WebInspectorProxy::platformIsFront() -{ - GtkWidget* parent = gtk_widget_get_toplevel(m_inspectorView); - if (WebCore::widgetIsOnscreenToplevelWindow(parent)) - return m_isVisible && gtk_window_is_active(GTK_WINDOW(parent)); - return false; -} - -void WebInspectorProxy::platformInspectedURLChanged(const String& url) -{ - m_client.inspectedURLChanged(this, url); - - if (!m_inspectorWindow) - return; - GOwnPtr<gchar> title(g_strdup_printf("%s - %s", _("Web Inspector"), url.utf8().data())); - gtk_window_set_title(GTK_WINDOW(m_inspectorWindow), title.get()); -} - -String WebInspectorProxy::inspectorPageURL() const -{ - GOwnPtr<gchar> filePath(g_build_filename(inspectorFilesBasePath(), "inspector.html", NULL)); - GOwnPtr<gchar> fileURI(g_filename_to_uri(filePath.get(), 0, 0)); - return WebCore::filenameToString(fileURI.get()); -} - -String WebInspectorProxy::inspectorBaseURL() const -{ - GOwnPtr<gchar> fileURI(g_filename_to_uri(inspectorFilesBasePath(), 0, 0)); - return WebCore::filenameToString(fileURI.get()); -} - -unsigned WebInspectorProxy::platformInspectedWindowHeight() -{ - return gtk_widget_get_allocated_height(m_page->viewWidget()); -} - -unsigned WebInspectorProxy::platformInspectedWindowWidth() -{ - return gtk_widget_get_allocated_width(m_page->viewWidget()); -} - -void WebInspectorProxy::platformAttach() -{ - GRefPtr<GtkWidget> inspectorView = m_inspectorView; - if (m_inspectorWindow) { - gtk_container_remove(GTK_CONTAINER(m_inspectorWindow), m_inspectorView); - gtk_widget_destroy(m_inspectorWindow); - m_inspectorWindow = 0; - } - - // Set a default attached height based on InspectorFrontendClientLocal. - static const unsigned defaultAttachedHeight = 300; - unsigned maximumAttachedHeight = platformInspectedWindowHeight() * 3 / 4; - platformSetAttachedWindowHeight(std::max(minimumAttachedHeight, std::min(defaultAttachedHeight, maximumAttachedHeight))); - - if (m_client.attach(this)) - return; - - webkitWebViewBaseAddWebInspector(WEBKIT_WEB_VIEW_BASE(m_page->viewWidget()), m_inspectorView); - gtk_widget_show(m_inspectorView); -} - -void WebInspectorProxy::platformDetach() -{ - if (!m_page->isValid()) - return; - - GRefPtr<GtkWidget> inspectorView = m_inspectorView; - if (!m_client.detach(this)) { - GtkWidget* parent = gtk_widget_get_parent(m_inspectorView); - ASSERT(parent); - gtk_container_remove(GTK_CONTAINER(parent), m_inspectorView); - } - - if (!m_isVisible) - return; - - createInspectorWindow(); -} - -void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned height) -{ - if (!m_isAttached) - return; - - m_client.didChangeAttachedHeight(this, height); - webkitWebViewBaseSetInspectorViewHeight(WEBKIT_WEB_VIEW_BASE(m_page->viewWidget()), height); -} - -void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned) -{ - notImplemented(); -} - -void WebInspectorProxy::platformSetToolbarHeight(unsigned) -{ - notImplemented(); -} - -void WebInspectorProxy::platformSave(const String&, const String&, bool) -{ - notImplemented(); -} - -void WebInspectorProxy::platformAppend(const String&, const String&) -{ - notImplemented(); -} - -void WebInspectorProxy::platformAttachAvailabilityChanged(bool) -{ - notImplemented(); -} - -} // namespace WebKit - -#endif // ENABLE(INSPECTOR) diff --git a/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp deleted file mode 100644 index 4b5204941..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebPageProxyGtk.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2010 Apple Inc. All rights reserved. - * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "WebPageProxy.h" - -#include "NativeWebKeyboardEvent.h" -#include "NotImplemented.h" -#include "PageClientImpl.h" -#include "WebKitWebViewBasePrivate.h" -#include "WebPageMessages.h" -#include "WebProcessProxy.h" -#include <WebCore/UserAgentGtk.h> -#include <gtk/gtkx.h> - -namespace WebKit { - -GtkWidget* WebPageProxy::viewWidget() -{ - return static_cast<PageClientImpl*>(m_pageClient)->viewWidget(); -} - -String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent) -{ - return WebCore::standardUserAgent(applicationNameForUserAgent); -} - -void WebPageProxy::getEditorCommandsForKeyEvent(const AtomicString& eventType, Vector<WTF::String>& commandsList) -{ - // When the keyboard event is started in the WebProcess side (e.g. from the Inspector) - // it will arrive without a GdkEvent associated, so the keyEventQueue will be empty. - if (!m_keyEventQueue.isEmpty()) - m_pageClient->getEditorCommandsForKeyEvent(m_keyEventQueue.first(), eventType, commandsList); -} - -void WebPageProxy::bindAccessibilityTree(const String& plugID) -{ - m_accessibilityPlugID = plugID; -} - -void WebPageProxy::saveRecentSearches(const String&, const Vector<String>&) -{ - notImplemented(); -} - -void WebPageProxy::loadRecentSearches(const String&, Vector<String>&) -{ - notImplemented(); -} - -typedef HashMap<uint64_t, GtkWidget* > PluginWindowMap; -static PluginWindowMap& pluginWindowMap() -{ - DEFINE_STATIC_LOCAL(PluginWindowMap, map, ()); - return map; -} - -static gboolean pluginContainerPlugRemoved(GtkSocket* socket) -{ - uint64_t windowID = static_cast<uint64_t>(gtk_socket_get_id(socket)); - pluginWindowMap().remove(windowID); - return FALSE; -} - -void WebPageProxy::createPluginContainer(uint64_t& windowID) -{ - GtkWidget* socket = gtk_socket_new(); - g_signal_connect(socket, "plug-removed", G_CALLBACK(pluginContainerPlugRemoved), 0); - gtk_container_add(GTK_CONTAINER(viewWidget()), socket); - gtk_widget_show(socket); - - windowID = static_cast<uint64_t>(gtk_socket_get_id(GTK_SOCKET(socket))); - pluginWindowMap().set(windowID, socket); -} - -void WebPageProxy::windowedPluginGeometryDidChange(const WebCore::IntRect& frameRect, const WebCore::IntRect& clipRect, uint64_t windowID) -{ - GtkWidget* plugin = pluginWindowMap().get(windowID); - if (!plugin) - return; - - if (gtk_widget_get_realized(plugin)) { - GdkRectangle clip = clipRect; - cairo_region_t* clipRegion = cairo_region_create_rectangle(&clip); - gdk_window_shape_combine_region(gtk_widget_get_window(plugin), clipRegion, 0, 0); - cairo_region_destroy(clipRegion); - } - - webkitWebViewBaseChildMoveResize(WEBKIT_WEB_VIEW_BASE(viewWidget()), plugin, frameRect); -} - -void WebPageProxy::setInputMethodState(bool enabled) -{ - webkitWebViewBaseSetInputMethodState(WEBKIT_WEB_VIEW_BASE(viewWidget()), enabled); -} - -#if USE(TEXTURE_MAPPER_GL) -void WebPageProxy::setAcceleratedCompositingWindowId(uint64_t nativeWindowId) -{ - process()->send(Messages::WebPage::SetAcceleratedCompositingWindowId(nativeWindowId), m_pageID); -} -#endif - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebPopupMenuProxyGtk.cpp b/Source/WebKit2/UIProcess/gtk/WebPopupMenuProxyGtk.cpp deleted file mode 100644 index a41839a3e..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebPopupMenuProxyGtk.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2011 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. - */ - -#include "config.h" -#include "WebPopupMenuProxyGtk.h" - -#include "NativeWebMouseEvent.h" -#include "WebPopupItem.h" -#include <WebCore/GtkUtilities.h> -#include <gtk/gtk.h> -#include <wtf/gobject/GOwnPtr.h> -#include <wtf/text/CString.h> - -using namespace WebCore; - -namespace WebKit { - -WebPopupMenuProxyGtk::WebPopupMenuProxyGtk(GtkWidget* webView, WebPopupMenuProxy::Client* client) - : WebPopupMenuProxy(client) - , m_webView(webView) - , m_activeItem(-1) -{ -} - -WebPopupMenuProxyGtk::~WebPopupMenuProxyGtk() -{ - if (m_popup) { - g_signal_handlers_disconnect_matched(m_popup->platformMenu(), G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); - hidePopupMenu(); - } -} - -GtkAction* WebPopupMenuProxyGtk::createGtkActionForMenuItem(const WebPopupItem& item, int itemIndex) -{ - GOwnPtr<char> actionName(g_strdup_printf("popup-menu-action-%d", itemIndex)); - GtkAction* action = gtk_action_new(actionName.get(), item.m_text.utf8().data(), item.m_toolTip.utf8().data(), 0); - g_object_set_data(G_OBJECT(action), "popup-menu-action-index", GINT_TO_POINTER(itemIndex)); - g_signal_connect(action, "activate", G_CALLBACK(menuItemActivated), this); - gtk_action_set_sensitive(action, item.m_isEnabled); - - return action; -} - -void WebPopupMenuProxyGtk::showPopupMenu(const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, const PlatformPopupMenuData& data, int32_t selectedIndex) -{ - if (m_popup) - m_popup->clear(); - else - m_popup = GtkPopupMenu::create(); - - const int size = items.size(); - for (int i = 0; i < size; i++) { - if (items[i].m_type == WebPopupItem::Separator) - m_popup->appendSeparator(); - else { - GRefPtr<GtkAction> action = adoptGRef(createGtkActionForMenuItem(items[i], i)); - m_popup->appendItem(action.get()); - } - } - - IntPoint menuPosition = convertWidgetPointToScreenPoint(m_webView, rect.location()); - menuPosition.move(0, rect.height()); - - gulong unmapHandler = g_signal_connect(m_popup->platformMenu(), "unmap", G_CALLBACK(menuUnmapped), this); - m_popup->popUp(rect.size(), menuPosition, size, selectedIndex, m_client->currentlyProcessedMouseDownEvent() ? m_client->currentlyProcessedMouseDownEvent()->nativeEvent() : 0); - - // PopupMenu can fail to open when there is no mouse grab. - // Ensure WebCore does not go into some pesky state. - if (!gtk_widget_get_visible(m_popup->platformMenu())) { - m_client->failedToShowPopupMenu(); - return; - } - - // WebPageProxy expects the menu to run in a nested run loop, since it invalidates the - // menu right after calling WebPopupMenuProxy::showPopupMenu(). - m_runLoop = adoptGRef(g_main_loop_new(0, FALSE)); - - gdk_threads_leave(); - g_main_loop_run(m_runLoop.get()); - gdk_threads_enter(); - - m_runLoop.clear(); - - g_signal_handler_disconnect(m_popup->platformMenu(), unmapHandler); - - if (!m_client) - return; - - m_client->valueChangedForPopupMenu(this, m_activeItem); -} - -void WebPopupMenuProxyGtk::hidePopupMenu() -{ - m_popup->popDown(); -} - -void WebPopupMenuProxyGtk::shutdownRunLoop() -{ - if (g_main_loop_is_running(m_runLoop.get())) - g_main_loop_quit(m_runLoop.get()); -} - -void WebPopupMenuProxyGtk::menuItemActivated(GtkAction* action, WebPopupMenuProxyGtk* popupMenu) -{ - popupMenu->setActiveItem(GPOINTER_TO_INT(g_object_get_data(G_OBJECT(action), "popup-menu-action-index"))); - popupMenu->shutdownRunLoop(); -} - -void WebPopupMenuProxyGtk::menuUnmapped(GtkWidget*, WebPopupMenuProxyGtk* popupMenu) -{ - popupMenu->shutdownRunLoop(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/gtk/WebPopupMenuProxyGtk.h b/Source/WebKit2/UIProcess/gtk/WebPopupMenuProxyGtk.h deleted file mode 100644 index 4b335bcde..000000000 --- a/Source/WebKit2/UIProcess/gtk/WebPopupMenuProxyGtk.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2011 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 WebPopupMenuProxyGtk_h -#define WebPopupMenuProxyGtk_h - -#include "WebPopupMenuProxy.h" -#include <WebCore/GtkPopupMenu.h> -#include <WebCore/IntRect.h> -#include <wtf/gobject/GRefPtr.h> - -typedef struct _GMainLoop GMainLoop; - -namespace WebKit { - -class WebPageProxy; - -class WebPopupMenuProxyGtk : public WebPopupMenuProxy { -public: - static PassRefPtr<WebPopupMenuProxyGtk> create(GtkWidget* webView, WebPopupMenuProxy::Client* client) - { - return adoptRef(new WebPopupMenuProxyGtk(webView, client)); - } - ~WebPopupMenuProxyGtk(); - - virtual void showPopupMenu(const WebCore::IntRect&, WebCore::TextDirection, double pageScaleFactor, const Vector<WebPopupItem>&, const PlatformPopupMenuData&, int32_t selectedIndex); - virtual void hidePopupMenu(); - -private: - WebPopupMenuProxyGtk(GtkWidget*, WebPopupMenuProxy::Client*); - void shutdownRunLoop(); - void setActiveItem(int activeItem) { m_activeItem = activeItem; } - GtkAction* createGtkActionForMenuItem(const WebPopupItem&, int itemIndex); - - static void menuItemActivated(GtkAction*, WebPopupMenuProxyGtk*); - static void menuUnmapped(GtkWidget*, WebPopupMenuProxyGtk*); - - GtkWidget* m_webView; - OwnPtr<WebCore::GtkPopupMenu> m_popup; - int m_activeItem; - GRefPtr<GMainLoop> m_runLoop; -}; - -} // namespace WebKit - - -#endif // WebPopupMenuProxyGtk_h diff --git a/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm b/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm deleted file mode 100644 index 7256f2e35..000000000 --- a/Source/WebKit2/UIProcess/mac/BackingStoreMac.mm +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "BackingStore.h" - -#import "CGUtilities.h" -#import "ShareableBitmap.h" -#import "UpdateInfo.h" -#import "WebPageProxy.h" -#import <WebCore/GraphicsContext.h> -#import <WebCore/Region.h> - -using namespace WebCore; - -namespace WebKit { - -void BackingStore::performWithScrolledRectTransform(const IntRect& rect, void (^block)(const IntRect&, const IntSize&)) -{ - if (m_scrolledRect.isEmpty() || m_scrolledRectOffset.isZero() || !m_scrolledRect.intersects(rect)) { - block(rect, IntSize()); - return; - } - - // The part of rect that's outside the scrolled rect is not translated. - Region untranslatedRegion = rect; - untranslatedRegion.subtract(m_scrolledRect); - Vector<IntRect> untranslatedRects = untranslatedRegion.rects(); - for (size_t i = 0; i < untranslatedRects.size(); ++i) - block(untranslatedRects[i], IntSize()); - - // The part of rect that intersects the scrolled rect comprises up to four parts, each subject - // to a different translation (all translations are equivalent modulo the dimensions of the - // scrolled rect to the scroll offset). - IntRect intersection = rect; - intersection.intersect(m_scrolledRect); - - IntRect scrolledRect = m_scrolledRect; - IntSize offset = m_scrolledRectOffset; - scrolledRect.move(-offset); - - IntRect part = intersection; - part.intersect(scrolledRect); - if (!part.isEmpty()) - block(part, offset); - - part = intersection; - offset += IntSize(0, -m_scrolledRect.height()); - scrolledRect.move(IntSize(0, m_scrolledRect.height())); - part.intersect(scrolledRect); - if (!part.isEmpty()) - block(part, offset); - - part = intersection; - offset += IntSize(-m_scrolledRect.width(), 0); - scrolledRect.move(IntSize(m_scrolledRect.width(), 0)); - part.intersect(scrolledRect); - if (!part.isEmpty()) - block(part, offset); - - part = intersection; - offset += IntSize(0, m_scrolledRect.height()); - scrolledRect.move(IntSize(0, -m_scrolledRect.height())); - part.intersect(scrolledRect); - if (!part.isEmpty()) - block(part, offset); -} - -void BackingStore::resetScrolledRect() -{ - ASSERT(!m_scrolledRect.isEmpty()); - - if (m_scrolledRectOffset.isZero()) { - m_scrolledRect = IntRect(); - return; - } - - IntSize scaledSize = m_scrolledRect.size(); - scaledSize.scale(m_deviceScaleFactor); - - RetainPtr<CGColorSpaceRef> colorSpace = adoptCF(CGColorSpaceCreateDeviceRGB()); - RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, scaledSize.width(), scaledSize.height(), 8, scaledSize.width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); - - CGContextScaleCTM(context.get(), m_deviceScaleFactor, m_deviceScaleFactor); - - CGContextScaleCTM(context.get(), 1, -1); - CGContextTranslateCTM(context.get(), -m_scrolledRect.x(), -m_scrolledRect.maxY()); - paint(context.get(), m_scrolledRect); - - IntRect sourceRect(IntPoint(), m_scrolledRect.size()); - paintBitmapContext(backingStoreContext(), context.get(), m_deviceScaleFactor, m_scrolledRect.location(), sourceRect); - - m_scrolledRect = IntRect(); - m_scrolledRectOffset = IntSize(); -} - -void BackingStore::paint(PlatformGraphicsContext context, const IntRect& rect) -{ - // FIXME: This is defined outside the block to work around bugs in llvm-gcc 4.2. - __block CGRect source; - performWithScrolledRectTransform(rect, ^(const IntRect& part, const IntSize& offset) { - if (m_cgLayer) { - CGContextSaveGState(context); - CGContextClipToRect(context, part); - - CGContextScaleCTM(context, 1, -1); - CGContextDrawLayerAtPoint(context, CGPointMake(-offset.width(), offset.height() - m_size.height()), m_cgLayer.get()); - - CGContextRestoreGState(context); - return; - } - - ASSERT(m_bitmapContext); - source = part; - source.origin.x += offset.width(); - source.origin.y += offset.height(); - paintBitmapContext(context, m_bitmapContext.get(), m_deviceScaleFactor, part.location(), source); - }); -} - -CGContextRef BackingStore::backingStoreContext() -{ - if (m_cgLayer) - return CGLayerGetContext(m_cgLayer.get()); - - // Try to create a layer. - if (CGContextRef containingWindowContext = m_webPageProxy->containingWindowGraphicsContext()) { - m_cgLayer = adoptCF(CGLayerCreateWithContext(containingWindowContext, m_size, 0)); - CGContextRef layerContext = CGLayerGetContext(m_cgLayer.get()); - - CGContextSetBlendMode(layerContext, kCGBlendModeCopy); - - // We want the origin to be in the top left corner so flip the backing store context. - CGContextTranslateCTM(layerContext, 0, m_size.height()); - CGContextScaleCTM(layerContext, 1, -1); - - if (m_bitmapContext) { - // Paint the contents of the bitmap into the layer context. - paintBitmapContext(layerContext, m_bitmapContext.get(), m_deviceScaleFactor, CGPointZero, CGRectMake(0, 0, m_size.width(), m_size.height())); - m_bitmapContext = nullptr; - } - - return layerContext; - } - - if (!m_bitmapContext) { - RetainPtr<CGColorSpaceRef> colorSpace = adoptCF(CGColorSpaceCreateDeviceRGB()); - - IntSize scaledSize(m_size); - scaledSize.scale(m_deviceScaleFactor); - m_bitmapContext = adoptCF(CGBitmapContextCreate(0, scaledSize.width(), scaledSize.height(), 8, scaledSize.width() * 4, colorSpace.get(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); - - CGContextSetBlendMode(m_bitmapContext.get(), kCGBlendModeCopy); - - CGContextScaleCTM(m_bitmapContext.get(), m_deviceScaleFactor, m_deviceScaleFactor); - - // We want the origin to be in the top left corner so flip the backing store context. - CGContextTranslateCTM(m_bitmapContext.get(), 0, m_size.height()); - CGContextScaleCTM(m_bitmapContext.get(), 1, -1); - } - - return m_bitmapContext.get(); -} - -void BackingStore::incorporateUpdate(ShareableBitmap* bitmap, const UpdateInfo& updateInfo) -{ - CGContextRef context = backingStoreContext(); - - scroll(updateInfo.scrollRect, updateInfo.scrollOffset); - - IntPoint updateRectLocation = updateInfo.updateRectBounds.location(); - - GraphicsContext ctx(context); - __block GraphicsContext* graphicsContext = &ctx; - - // Paint all update rects. - for (size_t i = 0; i < updateInfo.updateRects.size(); ++i) { - IntRect updateRect = updateInfo.updateRects[i]; - IntRect srcRect = updateRect; - // FIXME: This is defined outside the block to work around bugs in llvm-gcc 4.2. - __block IntRect srcPart; - performWithScrolledRectTransform(srcRect, ^(const IntRect& part, const IntSize& offset) { - srcPart = part; - srcPart.move(-updateRectLocation.x(), -updateRectLocation.y()); - bitmap->paint(*graphicsContext, updateInfo.deviceScaleFactor, part.location() + offset, srcPart); - }); - } -} - -void BackingStore::scroll(const IntRect& scrollRect, const IntSize& scrollOffset) -{ - if (scrollOffset.isZero()) - return; - - ASSERT(!scrollRect.isEmpty()); - - if (!m_scrolledRect.isEmpty() && m_scrolledRect != scrollRect) - resetScrolledRect(); - - m_scrolledRect = scrollRect; - - int width = (m_scrolledRectOffset.width() - scrollOffset.width()) % m_scrolledRect.width(); - if (width < 0) - width += m_scrolledRect.width(); - m_scrolledRectOffset.setWidth(width); - - int height = (m_scrolledRectOffset.height() - scrollOffset.height()) % m_scrolledRect.height(); - if (height < 0) - height += m_scrolledRect.height(); - m_scrolledRectOffset.setHeight(height); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/CorrectionPanel.h b/Source/WebKit2/UIProcess/mac/CorrectionPanel.h deleted file mode 100644 index 4c4c34a57..000000000 --- a/Source/WebKit2/UIProcess/mac/CorrectionPanel.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CorrectionPanel_h -#define CorrectionPanel_h - -#import <WebCore/TextChecking.h> - -#if USE(AUTOCORRECTION_PANEL) - -#import <AppKit/NSSpellChecker.h> -#import <WebCore/AlternativeTextClient.h> -#import <wtf/RetainPtr.h> - -@class WKView; - -namespace WebKit { - -class CorrectionPanel { -public: - CorrectionPanel(); - ~CorrectionPanel(); - void show(WKView*, WebCore::AlternativeTextType, const WebCore::FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings); - String dismiss(WebCore::ReasonForDismissingAlternativeText); - static void recordAutocorrectionResponse(WKView*, NSCorrectionResponse, const String& replacedString, const String& replacementString); - -private: - bool isShowing() const { return m_view; } - String dismissInternal(WebCore::ReasonForDismissingAlternativeText, bool dismissingExternally); - void handleAcceptedReplacement(NSString* acceptedReplacement, NSString* replaced, NSString* proposedReplacement, NSCorrectionIndicatorType); - - bool m_wasDismissedExternally; - WebCore::ReasonForDismissingAlternativeText m_reasonForDismissing; - RetainPtr<WKView> m_view; - RetainPtr<NSString> m_resultForDismissal; -}; - -} // namespace WebKit - -#endif // USE(AUTOCORRECTION_PANEL) - -#endif // CorrectionPanel_h diff --git a/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm b/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm deleted file mode 100644 index 615e15227..000000000 --- a/Source/WebKit2/UIProcess/mac/CorrectionPanel.mm +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "CorrectionPanel.h" - -#if USE(AUTOCORRECTION_PANEL) - -#import "WebPageProxy.h" -#import "WKView.h" -#import "WKViewInternal.h" - -using namespace WebCore; - -static inline NSCorrectionIndicatorType correctionIndicatorType(AlternativeTextType alternativeTextType) -{ - switch (alternativeTextType) { - case AlternativeTextTypeCorrection: - return NSCorrectionIndicatorTypeDefault; - case AlternativeTextTypeReversion: - return NSCorrectionIndicatorTypeReversion; - case AlternativeTextTypeSpellingSuggestions: - return NSCorrectionIndicatorTypeGuesses; - case AlternativeTextTypeDictationAlternatives: - ASSERT_NOT_REACHED(); - break; - } - ASSERT_NOT_REACHED(); - return NSCorrectionIndicatorTypeDefault; -} - -namespace WebKit { - -CorrectionPanel::CorrectionPanel() - : m_wasDismissedExternally(false) - , m_reasonForDismissing(ReasonForDismissingAlternativeTextIgnored) -{ -} - -CorrectionPanel::~CorrectionPanel() -{ - dismissInternal(ReasonForDismissingAlternativeTextIgnored, false); -} - -void CorrectionPanel::show(WKView* view, AlternativeTextType type, const FloatRect& boundingBoxOfReplacedString, const String& replacedString, const String& replacementString, const Vector<String>& alternativeReplacementStrings) -{ - dismissInternal(ReasonForDismissingAlternativeTextIgnored, false); - - if (!view) - return; - - NSString* replacedStringAsNSString = replacedString; - NSString* replacementStringAsNSString = replacementString; - m_view = view; - NSCorrectionIndicatorType indicatorType = correctionIndicatorType(type); - - NSMutableArray* alternativeStrings = 0; - if (!alternativeReplacementStrings.isEmpty()) { - size_t size = alternativeReplacementStrings.size(); - alternativeStrings = [NSMutableArray arrayWithCapacity:size]; - for (size_t i = 0; i < size; ++i) - [alternativeStrings addObject:(NSString*)alternativeReplacementStrings[i]]; - } - - NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; - [spellChecker showCorrectionIndicatorOfType:indicatorType primaryString:replacementStringAsNSString alternativeStrings:alternativeStrings forStringInRect:boundingBoxOfReplacedString view:m_view.get() completionHandler:^(NSString* acceptedString) { - handleAcceptedReplacement(acceptedString, replacedStringAsNSString, replacementStringAsNSString, indicatorType); - }]; -} - -String CorrectionPanel::dismiss(ReasonForDismissingAlternativeText reason) -{ - return dismissInternal(reason, true); -} - -String CorrectionPanel::dismissInternal(ReasonForDismissingAlternativeText reason, bool dismissingExternally) -{ - if (!isShowing()) - return String(); - - m_wasDismissedExternally = dismissingExternally; - m_reasonForDismissing = reason; - m_resultForDismissal.clear(); - [[NSSpellChecker sharedSpellChecker] dismissCorrectionIndicatorForView:m_view.get()]; - return m_resultForDismissal.get(); -} - -void CorrectionPanel::recordAutocorrectionResponse(WKView* view, NSCorrectionResponse response, const String& replacedString, const String& replacementString) -{ - [[NSSpellChecker sharedSpellChecker] recordResponse:response toCorrection:replacementString forWord:replacedString language:nil inSpellDocumentWithTag:[view spellCheckerDocumentTag]]; -} - -void CorrectionPanel::handleAcceptedReplacement(NSString* acceptedReplacement, NSString* replaced, NSString* proposedReplacement, NSCorrectionIndicatorType correctionIndicatorType) -{ - if (!m_view) - return; - - NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; - NSInteger documentTag = [m_view.get() spellCheckerDocumentTag]; - - switch (correctionIndicatorType) { - case NSCorrectionIndicatorTypeDefault: - if (acceptedReplacement) - [spellChecker recordResponse:NSCorrectionResponseAccepted toCorrection:acceptedReplacement forWord:replaced language:nil inSpellDocumentWithTag:documentTag]; - else { - if (!m_wasDismissedExternally || m_reasonForDismissing == ReasonForDismissingAlternativeTextCancelled) - [spellChecker recordResponse:NSCorrectionResponseRejected toCorrection:proposedReplacement forWord:replaced language:nil inSpellDocumentWithTag:documentTag]; - else - [spellChecker recordResponse:NSCorrectionResponseIgnored toCorrection:proposedReplacement forWord:replaced language:nil inSpellDocumentWithTag:documentTag]; - } - break; - case NSCorrectionIndicatorTypeReversion: - if (acceptedReplacement) - [spellChecker recordResponse:NSCorrectionResponseReverted toCorrection:replaced forWord:acceptedReplacement language:nil inSpellDocumentWithTag:documentTag]; - break; - case NSCorrectionIndicatorTypeGuesses: - if (acceptedReplacement) - [spellChecker recordResponse:NSCorrectionResponseAccepted toCorrection:acceptedReplacement forWord:replaced language:nil inSpellDocumentWithTag:documentTag]; - break; - } - - [m_view.get() handleAcceptedAlternativeText:acceptedReplacement]; - m_view.clear(); - if (acceptedReplacement) - m_resultForDismissal = adoptNS([acceptedReplacement copy]); -} - -} // namespace WebKit - -#endif // USE(AUTOCORRECTION_PANEL) diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h b/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h deleted file mode 100644 index c4b952ae1..000000000 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef RemoteLayerTreeHost_h -#define RemoteLayerTreeHost_h - -#include "MessageReceiver.h" -#include <WebCore/GraphicsLayerClient.h> -#include <wtf/HashMap.h> - -namespace WebKit { - -class RemoteLayerTreeTransaction; -class WebPageProxy; - -class RemoteLayerTreeHost : private CoreIPC::MessageReceiver, WebCore::GraphicsLayerClient { -public: - explicit RemoteLayerTreeHost(WebPageProxy*); - ~RemoteLayerTreeHost(); - -private: - // CoreIPC::MessageReceiver. - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - // WebCore::GraphicsLayerClient. - virtual void notifyAnimationStarted(const WebCore::GraphicsLayer*, double time) OVERRIDE; - virtual void notifyFlushRequired(const WebCore::GraphicsLayer*) OVERRIDE; - virtual void paintContents(const WebCore::GraphicsLayer*, WebCore::GraphicsContext&, WebCore::GraphicsLayerPaintingPhase, const WebCore::IntRect& clipRect) OVERRIDE; - - // Message handlers. - void commit(const RemoteLayerTreeTransaction&); - - WebCore::GraphicsLayer* getOrCreateLayer(uint64_t layerID); - - WebPageProxy* m_webPageProxy; - - WebCore::GraphicsLayer* m_rootLayer; - HashMap<uint64_t, OwnPtr<WebCore::GraphicsLayer>> m_layers; -}; - -} // namespace WebKit - -#endif // RemoteLayerTreeHost_h diff --git a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm b/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm deleted file mode 100644 index a006a384b..000000000 --- a/Source/WebKit2/UIProcess/mac/RemoteLayerTreeHost.mm +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "RemoteLayerTreeHost.h" - -#include "RemoteLayerTreeHostMessages.h" -#include "RemoteLayerTreeTransaction.h" -#include "WebPageProxy.h" -#include "WebProcessProxy.h" -#include <WebCore/GraphicsLayer.h> - -using namespace WebCore; - -namespace WebKit { - -RemoteLayerTreeHost::RemoteLayerTreeHost(WebPageProxy* webPageProxy) - : m_webPageProxy(webPageProxy) - , m_rootLayer(nullptr) -{ - m_webPageProxy->process()->addMessageReceiver(Messages::RemoteLayerTreeHost::messageReceiverName(), m_webPageProxy->pageID(), this); -} - -RemoteLayerTreeHost::~RemoteLayerTreeHost() -{ - m_webPageProxy->process()->removeMessageReceiver(Messages::RemoteLayerTreeHost::messageReceiverName(), m_webPageProxy->pageID()); -} - -void RemoteLayerTreeHost::notifyAnimationStarted(const GraphicsLayer*, double time) -{ -} - -void RemoteLayerTreeHost::notifyFlushRequired(const GraphicsLayer*) -{ -} - -void RemoteLayerTreeHost::paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) -{ -} - -void RemoteLayerTreeHost::commit(const RemoteLayerTreeTransaction& transaction) -{ - GraphicsLayer* rootLayer = getOrCreateLayer(transaction.rootLayerID()); - if (m_rootLayer != rootLayer) { - m_rootLayer = rootLayer; - m_webPageProxy->setAcceleratedCompositingRootLayer(m_rootLayer); - } - -#ifndef NDEBUG - // FIXME: Apply the transaction instead of dumping it to stderr. - transaction.dump(); -#endif -} - -GraphicsLayer* RemoteLayerTreeHost::getOrCreateLayer(uint64_t layerID) -{ - auto addResult = m_layers.add(layerID, nullptr); - if (addResult.isNewEntry) - addResult.iterator->value = GraphicsLayer::create(this); - - return addResult.iterator->value.get(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.cpp b/Source/WebKit2/UIProcess/mac/SecItemShimProxy.cpp deleted file mode 100644 index 0eb69d1d8..000000000 --- a/Source/WebKit2/UIProcess/mac/SecItemShimProxy.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "SecItemShimProxy.h" - -#if USE(SECURITY_FRAMEWORK) - -#include "SecItemRequestData.h" -#include "SecItemResponseData.h" -#include "SecItemShimMessages.h" -#include "SecItemShimProxyMessages.h" -#include <Security/SecItem.h> - -namespace WebKit { - -SecItemShimProxy& SecItemShimProxy::shared() -{ - static SecItemShimProxy* proxy; - static dispatch_once_t once; - dispatch_once(&once, ^{ - proxy = adoptRef(new SecItemShimProxy).leakRef(); - }); - return *proxy; -} - -SecItemShimProxy::SecItemShimProxy() - : m_queue(WorkQueue::create("com.apple.WebKit.SecItemShimProxy")) -{ -} - -void SecItemShimProxy::initializeConnection(CoreIPC::Connection* connection) -{ - connection->addWorkQueueMessageReceiver(Messages::SecItemShimProxy::messageReceiverName(), m_queue.get(), this); -} - -void SecItemShimProxy::secItemRequest(CoreIPC::Connection* connection, uint64_t requestID, const SecItemRequestData& request) -{ - SecItemResponseData response; - - switch (request.type()) { - case SecItemRequestData::Invalid: - ASSERT_NOT_REACHED(); - return; - - case SecItemRequestData::CopyMatching: { - CFTypeRef resultObject = 0; - OSStatus resultCode = SecItemCopyMatching(request.query(), &resultObject); - response = SecItemResponseData(resultCode, adoptCF(resultObject).get()); - break; - } - - case SecItemRequestData::Add: { - CFTypeRef resultObject = 0; - OSStatus resultCode = SecItemAdd(request.query(), &resultObject); - response = SecItemResponseData(resultCode, adoptCF(resultObject).get()); - break; - } - - case SecItemRequestData::Update: { - OSStatus resultCode = SecItemUpdate(request.query(), request.attributesToMatch()); - response = SecItemResponseData(resultCode, 0); - break; - } - - case SecItemRequestData::Delete: { - OSStatus resultCode = SecItemDelete(request.query()); - response = SecItemResponseData(resultCode, 0); - break; - } - } - - connection->send(Messages::SecItemShim::SecItemResponse(requestID, response), 0); -} - -} // namespace WebKit - -#endif // USE(SECURITY_FRAMEWORK) diff --git a/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm b/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm deleted file mode 100644 index c9e3d6bc3..000000000 --- a/Source/WebKit2/UIProcess/mac/TextCheckerMac.mm +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "TextChecker.h" - -#import "TextCheckerState.h" -#import <WebCore/NotImplemented.h> -#import <wtf/RetainPtr.h> - -@interface NSSpellChecker (WebNSSpellCheckerDetails) -- (NSString *)languageForWordRange:(NSRange)range inString:(NSString *)string orthography:(NSOrthography *)orthography; -@end - -static NSString* const WebAutomaticSpellingCorrectionEnabled = @"WebAutomaticSpellingCorrectionEnabled"; -static NSString* const WebContinuousSpellCheckingEnabled = @"WebContinuousSpellCheckingEnabled"; -static NSString* const WebGrammarCheckingEnabled = @"WebGrammarCheckingEnabled"; -static NSString* const WebSmartInsertDeleteEnabled = @"WebSmartInsertDeleteEnabled"; -static NSString* const WebAutomaticQuoteSubstitutionEnabled = @"WebAutomaticQuoteSubstitutionEnabled"; -static NSString* const WebAutomaticDashSubstitutionEnabled = @"WebAutomaticDashSubstitutionEnabled"; -static NSString* const WebAutomaticLinkDetectionEnabled = @"WebAutomaticLinkDetectionEnabled"; -static NSString* const WebAutomaticTextReplacementEnabled = @"WebAutomaticTextReplacementEnabled"; - -using namespace WebCore; - -namespace WebKit { - -TextCheckerState textCheckerState; - -static bool shouldAutomaticTextReplacementBeEnabled() -{ - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - if (![defaults objectForKey:WebAutomaticTextReplacementEnabled]) - return [NSSpellChecker isAutomaticTextReplacementEnabled]; - return [defaults boolForKey:WebAutomaticTextReplacementEnabled]; -} - -static bool shouldAutomaticSpellingCorrectionBeEnabled() -{ - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - if (![defaults objectForKey:WebAutomaticSpellingCorrectionEnabled]) - return [NSSpellChecker isAutomaticTextReplacementEnabled]; - return [defaults boolForKey:WebAutomaticSpellingCorrectionEnabled]; -} - -static bool shouldAutomaticQuoteSubstitutionBeEnabled() -{ - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - if (![defaults objectForKey:WebAutomaticQuoteSubstitutionEnabled]) - return [NSSpellChecker isAutomaticQuoteSubstitutionEnabled]; -#endif - return [defaults boolForKey:WebAutomaticQuoteSubstitutionEnabled]; -} - -static bool shouldAutomaticDashSubstitutionBeEnabled() -{ - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - if (![defaults objectForKey:WebAutomaticDashSubstitutionEnabled]) - return [NSSpellChecker isAutomaticDashSubstitutionEnabled]; -#endif - return [defaults boolForKey:WebAutomaticDashSubstitutionEnabled]; -} - -static void initializeState() -{ - static bool didInitializeState = false; - - if (didInitializeState) - return; - - textCheckerState.isContinuousSpellCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebContinuousSpellCheckingEnabled] && TextChecker::isContinuousSpellCheckingAllowed(); - textCheckerState.isGrammarCheckingEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebGrammarCheckingEnabled]; - textCheckerState.isAutomaticTextReplacementEnabled = shouldAutomaticTextReplacementBeEnabled(); - textCheckerState.isAutomaticSpellingCorrectionEnabled = shouldAutomaticSpellingCorrectionBeEnabled(); - textCheckerState.isAutomaticQuoteSubstitutionEnabled = shouldAutomaticQuoteSubstitutionBeEnabled(); - textCheckerState.isAutomaticDashSubstitutionEnabled = shouldAutomaticDashSubstitutionBeEnabled(); - textCheckerState.isAutomaticLinkDetectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebAutomaticLinkDetectionEnabled]; - - didInitializeState = true; -} - -const TextCheckerState& TextChecker::state() -{ - initializeState(); - return textCheckerState; -} - -bool TextChecker::isContinuousSpellCheckingAllowed() -{ - static bool allowContinuousSpellChecking = true; - static bool readAllowContinuousSpellCheckingDefault = false; - - if (!readAllowContinuousSpellCheckingDefault) { - if ([[NSUserDefaults standardUserDefaults] objectForKey:@"NSAllowContinuousSpellChecking"]) - allowContinuousSpellChecking = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSAllowContinuousSpellChecking"]; - - readAllowContinuousSpellCheckingDefault = true; - } - - return allowContinuousSpellChecking; -} - -void TextChecker::setContinuousSpellCheckingEnabled(bool isContinuousSpellCheckingEnabled) -{ - if (state().isContinuousSpellCheckingEnabled == isContinuousSpellCheckingEnabled) - return; - - textCheckerState.isContinuousSpellCheckingEnabled = isContinuousSpellCheckingEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isContinuousSpellCheckingEnabled forKey:WebContinuousSpellCheckingEnabled]; - - // FIXME: preflight the spell checker. -} - -void TextChecker::setGrammarCheckingEnabled(bool isGrammarCheckingEnabled) -{ - if (state().isGrammarCheckingEnabled == isGrammarCheckingEnabled) - return; - - textCheckerState.isGrammarCheckingEnabled = isGrammarCheckingEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isGrammarCheckingEnabled forKey:WebGrammarCheckingEnabled]; - [[NSSpellChecker sharedSpellChecker] updatePanels]; - - // We call preflightSpellChecker() when turning continuous spell checking on, but we don't need to do that here - // because grammar checking only occurs on code paths that already preflight spell checking appropriately. -} - -void TextChecker::setAutomaticSpellingCorrectionEnabled(bool isAutomaticSpellingCorrectionEnabled) -{ - if (state().isAutomaticSpellingCorrectionEnabled == isAutomaticSpellingCorrectionEnabled) - return; - - textCheckerState.isAutomaticSpellingCorrectionEnabled = isAutomaticSpellingCorrectionEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isAutomaticSpellingCorrectionEnabled forKey:WebAutomaticSpellingCorrectionEnabled]; - - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -void TextChecker::setAutomaticQuoteSubstitutionEnabled(bool isAutomaticQuoteSubstitutionEnabled) -{ - if (state().isAutomaticQuoteSubstitutionEnabled == isAutomaticQuoteSubstitutionEnabled) - return; - - textCheckerState.isAutomaticQuoteSubstitutionEnabled = isAutomaticQuoteSubstitutionEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isAutomaticQuoteSubstitutionEnabled forKey:WebAutomaticQuoteSubstitutionEnabled]; - - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -void TextChecker::setAutomaticDashSubstitutionEnabled(bool isAutomaticDashSubstitutionEnabled) -{ - if (state().isAutomaticDashSubstitutionEnabled == isAutomaticDashSubstitutionEnabled) - return; - - textCheckerState.isAutomaticDashSubstitutionEnabled = isAutomaticDashSubstitutionEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isAutomaticDashSubstitutionEnabled forKey:WebAutomaticDashSubstitutionEnabled]; - - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -void TextChecker::setAutomaticLinkDetectionEnabled(bool isAutomaticLinkDetectionEnabled) -{ - if (state().isAutomaticLinkDetectionEnabled == isAutomaticLinkDetectionEnabled) - return; - - textCheckerState.isAutomaticLinkDetectionEnabled = isAutomaticLinkDetectionEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isAutomaticLinkDetectionEnabled forKey:WebAutomaticLinkDetectionEnabled]; - - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -void TextChecker::setAutomaticTextReplacementEnabled(bool isAutomaticTextReplacementEnabled) -{ - if (state().isAutomaticTextReplacementEnabled == isAutomaticTextReplacementEnabled) - return; - - textCheckerState.isAutomaticTextReplacementEnabled = isAutomaticTextReplacementEnabled; - [[NSUserDefaults standardUserDefaults] setBool:isAutomaticTextReplacementEnabled forKey:WebAutomaticTextReplacementEnabled]; - - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -static bool smartInsertDeleteEnabled; - -bool TextChecker::isSmartInsertDeleteEnabled() -{ - static bool readSmartInsertDeleteEnabledDefault; - - if (!readSmartInsertDeleteEnabledDefault) { - smartInsertDeleteEnabled = ![[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled] || [[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]; - - readSmartInsertDeleteEnabledDefault = true; - } - - return smartInsertDeleteEnabled; -} - -void TextChecker::setSmartInsertDeleteEnabled(bool flag) -{ - if (flag == isSmartInsertDeleteEnabled()) - return; - - smartInsertDeleteEnabled = flag; - - [[NSUserDefaults standardUserDefaults] setBool:flag forKey:WebSmartInsertDeleteEnabled]; -} - -void TextChecker::didChangeAutomaticTextReplacementEnabled() -{ - textCheckerState.isAutomaticTextReplacementEnabled = shouldAutomaticTextReplacementBeEnabled(); - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -void TextChecker::didChangeAutomaticSpellingCorrectionEnabled() -{ - textCheckerState.isAutomaticSpellingCorrectionEnabled = shouldAutomaticSpellingCorrectionBeEnabled(); - [[NSSpellChecker sharedSpellChecker] updatePanels]; -} - -void TextChecker::didChangeAutomaticQuoteSubstitutionEnabled() -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - textCheckerState.isAutomaticQuoteSubstitutionEnabled = shouldAutomaticQuoteSubstitutionBeEnabled(); - [[NSSpellChecker sharedSpellChecker] updatePanels]; -#endif -} - -void TextChecker::didChangeAutomaticDashSubstitutionEnabled() -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - textCheckerState.isAutomaticDashSubstitutionEnabled = shouldAutomaticDashSubstitutionBeEnabled(); - [[NSSpellChecker sharedSpellChecker] updatePanels]; -#endif -} - -bool TextChecker::substitutionsPanelIsShowing() -{ - return [[[NSSpellChecker sharedSpellChecker] substitutionsPanel] isVisible]; -} - -void TextChecker::toggleSubstitutionsPanelIsShowing() -{ - NSPanel *substitutionsPanel = [[NSSpellChecker sharedSpellChecker] substitutionsPanel]; - if ([substitutionsPanel isVisible]) { - [substitutionsPanel orderOut:nil]; - return; - } - [substitutionsPanel orderFront:nil]; -} - -void TextChecker::continuousSpellCheckingEnabledStateChanged(bool enabled) -{ - textCheckerState.isContinuousSpellCheckingEnabled = enabled; -} - -void TextChecker::grammarCheckingEnabledStateChanged(bool enabled) -{ - textCheckerState.isGrammarCheckingEnabled = enabled; -} - -int64_t TextChecker::uniqueSpellDocumentTag(WebPageProxy*) -{ - return [NSSpellChecker uniqueSpellDocumentTag]; -} - -void TextChecker::closeSpellDocumentWithTag(int64_t tag) -{ - [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:tag]; -} - -#if USE(UNIFIED_TEXT_CHECKING) - -Vector<TextCheckingResult> TextChecker::checkTextOfParagraph(int64_t spellDocumentTag, const UChar* text, int length, uint64_t checkingTypes) -{ - Vector<TextCheckingResult> results; - - RetainPtr<NSString> textString = adoptNS([[NSString alloc] initWithCharactersNoCopy:const_cast<UChar*>(text) length:length freeWhenDone:NO]); - NSArray *incomingResults = [[NSSpellChecker sharedSpellChecker] checkString:textString .get() - range:NSMakeRange(0, length) - types:checkingTypes | NSTextCheckingTypeOrthography - options:nil - inSpellDocumentWithTag:spellDocumentTag - orthography:NULL - wordCount:NULL]; - for (NSTextCheckingResult *incomingResult in incomingResults) { - NSRange resultRange = [incomingResult range]; - NSTextCheckingType resultType = [incomingResult resultType]; - ASSERT(resultRange.location != NSNotFound); - ASSERT(resultRange.length > 0); - if (resultType == NSTextCheckingTypeSpelling && (checkingTypes & NSTextCheckingTypeSpelling)) { - TextCheckingResult result; - result.type = TextCheckingTypeSpelling; - result.location = resultRange.location; - result.length = resultRange.length; - results.append(result); - } else if (resultType == NSTextCheckingTypeGrammar && (checkingTypes & NSTextCheckingTypeGrammar)) { - TextCheckingResult result; - NSArray *details = [incomingResult grammarDetails]; - result.type = TextCheckingTypeGrammar; - result.location = resultRange.location; - result.length = resultRange.length; - for (NSDictionary *incomingDetail in details) { - ASSERT(incomingDetail); - GrammarDetail detail; - NSValue *detailRangeAsNSValue = [incomingDetail objectForKey:NSGrammarRange]; - ASSERT(detailRangeAsNSValue); - NSRange detailNSRange = [detailRangeAsNSValue rangeValue]; - ASSERT(detailNSRange.location != NSNotFound); - ASSERT(detailNSRange.length > 0); - detail.location = detailNSRange.location; - detail.length = detailNSRange.length; - detail.userDescription = [incomingDetail objectForKey:NSGrammarUserDescription]; - NSArray *guesses = [incomingDetail objectForKey:NSGrammarCorrections]; - for (NSString *guess in guesses) - detail.guesses.append(String(guess)); - result.details.append(detail); - } - results.append(result); - } else if (resultType == NSTextCheckingTypeLink && (checkingTypes & NSTextCheckingTypeLink)) { - TextCheckingResult result; - result.type = TextCheckingTypeLink; - result.location = resultRange.location; - result.length = resultRange.length; - result.replacement = [[incomingResult URL] absoluteString]; - results.append(result); - } else if (resultType == NSTextCheckingTypeQuote && (checkingTypes & NSTextCheckingTypeQuote)) { - TextCheckingResult result; - result.type = TextCheckingTypeQuote; - result.location = resultRange.location; - result.length = resultRange.length; - result.replacement = [incomingResult replacementString]; - results.append(result); - } else if (resultType == NSTextCheckingTypeDash && (checkingTypes & NSTextCheckingTypeDash)) { - TextCheckingResult result; - result.type = TextCheckingTypeDash; - result.location = resultRange.location; - result.length = resultRange.length; - result.replacement = [incomingResult replacementString]; - results.append(result); - } else if (resultType == NSTextCheckingTypeReplacement && (checkingTypes & NSTextCheckingTypeReplacement)) { - TextCheckingResult result; - result.type = TextCheckingTypeReplacement; - result.location = resultRange.location; - result.length = resultRange.length; - result.replacement = [incomingResult replacementString]; - results.append(result); - } else if (resultType == NSTextCheckingTypeCorrection && (checkingTypes & NSTextCheckingTypeCorrection)) { - TextCheckingResult result; - result.type = TextCheckingTypeCorrection; - result.location = resultRange.location; - result.length = resultRange.length; - result.replacement = [incomingResult replacementString]; - results.append(result); - } - } - - return results; -} - -#endif - -void TextChecker::checkSpellingOfString(int64_t, const UChar*, uint32_t, int32_t&, int32_t&) -{ - // Mac uses checkTextOfParagraph instead. - notImplemented(); -} - -void TextChecker::checkGrammarOfString(int64_t, const UChar*, uint32_t, Vector<WebCore::GrammarDetail>&, int32_t&, int32_t&) -{ - // Mac uses checkTextOfParagraph instead. - notImplemented(); -} - -bool TextChecker::spellingUIIsShowing() -{ - return [[[NSSpellChecker sharedSpellChecker] spellingPanel] isVisible]; -} - -void TextChecker::toggleSpellingUIIsShowing() -{ - NSPanel *spellingPanel = [[NSSpellChecker sharedSpellChecker] spellingPanel]; - if ([spellingPanel isVisible]) - [spellingPanel orderOut:nil]; - else - [spellingPanel orderFront:nil]; -} - -void TextChecker::updateSpellingUIWithMisspelledWord(int64_t, const String& misspelledWord) -{ - [[NSSpellChecker sharedSpellChecker] updateSpellingPanelWithMisspelledWord:misspelledWord]; -} - -void TextChecker::updateSpellingUIWithGrammarString(int64_t, const String& badGrammarPhrase, const GrammarDetail& grammarDetail) -{ - RetainPtr<NSMutableArray> corrections = adoptNS([[NSMutableArray alloc] init]); - for (size_t i = 0; i < grammarDetail.guesses.size(); ++i) { - NSString *guess = grammarDetail.guesses[i]; - [corrections.get() addObject:guess]; - } - - NSRange grammarRange = NSMakeRange(grammarDetail.location, grammarDetail.length); - NSString *grammarUserDescription = grammarDetail.userDescription; - RetainPtr<NSDictionary> grammarDetailDict = adoptNS([[NSDictionary alloc] initWithObjectsAndKeys:[NSValue valueWithRange:grammarRange], NSGrammarRange, grammarUserDescription, NSGrammarUserDescription, corrections.get(), NSGrammarCorrections, nil]); - - [[NSSpellChecker sharedSpellChecker] updateSpellingPanelWithGrammarString:badGrammarPhrase detail:grammarDetailDict.get()]; -} - -void TextChecker::getGuessesForWord(int64_t spellDocumentTag, const String& word, const String& context, Vector<String>& guesses) -{ - NSString* language = nil; - NSOrthography* orthography = nil; - NSSpellChecker *checker = [NSSpellChecker sharedSpellChecker]; - if (context.length()) { - [checker checkString:context range:NSMakeRange(0, context.length()) types:NSTextCheckingTypeOrthography options:0 inSpellDocumentWithTag:spellDocumentTag orthography:&orthography wordCount:0]; - language = [checker languageForWordRange:NSMakeRange(0, context.length()) inString:context orthography:orthography]; - } - NSArray* stringsArray = [checker guessesForWordRange:NSMakeRange(0, word.length()) inString:word language:language inSpellDocumentWithTag:spellDocumentTag]; - - for (NSString *guess in stringsArray) - guesses.append(guess); -} - -void TextChecker::learnWord(int64_t, const String& word) -{ - [[NSSpellChecker sharedSpellChecker] learnWord:word]; -} - -void TextChecker::ignoreWord(int64_t spellDocumentTag, const String& word) -{ - [[NSSpellChecker sharedSpellChecker] ignoreWord:word inSpellDocumentWithTag:spellDocumentTag]; -} - -void TextChecker::requestCheckingOfString(PassRefPtr<TextCheckerCompletion>) -{ - notImplemented(); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h b/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h deleted file mode 100644 index ad1043b4b..000000000 --- a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef TiledCoreAnimationDrawingAreaProxy_h -#define TiledCoreAnimationDrawingAreaProxy_h - -#if ENABLE(THREADED_SCROLLING) - -#include "DrawingAreaProxy.h" -#include <wtf/PassOwnPtr.h> - -namespace WebKit { - -class TiledCoreAnimationDrawingAreaProxy : public DrawingAreaProxy { -public: - static PassOwnPtr<TiledCoreAnimationDrawingAreaProxy> create(WebPageProxy*); - virtual ~TiledCoreAnimationDrawingAreaProxy(); - -private: - explicit TiledCoreAnimationDrawingAreaProxy(WebPageProxy*); - - // DrawingAreaProxy - virtual void deviceScaleFactorDidChange() OVERRIDE; - virtual void layerHostingModeDidChange() OVERRIDE; - virtual void visibilityDidChange() OVERRIDE; - virtual void sizeDidChange() OVERRIDE; - virtual void waitForPossibleGeometryUpdate(double timeout = didUpdateBackingStoreStateTimeout) OVERRIDE; - virtual void colorSpaceDidChange() OVERRIDE; - virtual void minimumLayoutSizeDidChange() OVERRIDE; - - virtual void enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&) OVERRIDE; - virtual void exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo&) OVERRIDE; - virtual void updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext&) OVERRIDE; - - // Message handlers. - virtual void didUpdateGeometry() OVERRIDE; - virtual void intrinsicContentSizeDidChange(const WebCore::IntSize& newIntrinsicContentSize) OVERRIDE; - - void sendUpdateGeometry(); - - // Whether we're waiting for a DidUpdateGeometry message from the web process. - bool m_isWaitingForDidUpdateGeometry; - - // The last size we sent to the web process. - WebCore::IntSize m_lastSentSize; - WebCore::IntSize m_lastSentLayerPosition; - - // The last minimum layout size we sent to the web process. - WebCore::IntSize m_lastSentMinimumLayoutSize; -}; - -} // namespace WebKit - -#endif // ENABLE(THREADED_SCROLLING) - -#endif // TiledCoreAnimationDrawingAreaProxy_h diff --git a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm b/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm deleted file mode 100644 index 973768df9..000000000 --- a/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "TiledCoreAnimationDrawingAreaProxy.h" - -#if ENABLE(THREADED_SCROLLING) - -#import "ColorSpaceData.h" -#import "DrawingAreaMessages.h" -#import "DrawingAreaProxyMessages.h" -#import "LayerTreeContext.h" -#import "WebPageProxy.h" -#import "WebProcessProxy.h" - -using namespace WebCore; - -namespace WebKit { - -PassOwnPtr<TiledCoreAnimationDrawingAreaProxy> TiledCoreAnimationDrawingAreaProxy::create(WebPageProxy* webPageProxy) -{ - return adoptPtr(new TiledCoreAnimationDrawingAreaProxy(webPageProxy)); -} - -TiledCoreAnimationDrawingAreaProxy::TiledCoreAnimationDrawingAreaProxy(WebPageProxy* webPageProxy) - : DrawingAreaProxy(DrawingAreaTypeTiledCoreAnimation, webPageProxy) - , m_isWaitingForDidUpdateGeometry(false) -{ -} - -TiledCoreAnimationDrawingAreaProxy::~TiledCoreAnimationDrawingAreaProxy() -{ -} - -void TiledCoreAnimationDrawingAreaProxy::deviceScaleFactorDidChange() -{ - m_webPageProxy->process()->send(Messages::DrawingArea::SetDeviceScaleFactor(m_webPageProxy->deviceScaleFactor()), m_webPageProxy->pageID()); -} - -void TiledCoreAnimationDrawingAreaProxy::visibilityDidChange() -{ - if (!m_webPageProxy->isViewVisible()) - m_webPageProxy->process()->send(Messages::DrawingArea::SuspendPainting(), m_webPageProxy->pageID()); - else - m_webPageProxy->process()->send(Messages::DrawingArea::ResumePainting(), m_webPageProxy->pageID()); -} - -void TiledCoreAnimationDrawingAreaProxy::layerHostingModeDidChange() -{ - m_webPageProxy->process()->send(Messages::DrawingArea::SetLayerHostingMode(m_webPageProxy->layerHostingMode()), m_webPageProxy->pageID()); -} - -void TiledCoreAnimationDrawingAreaProxy::sizeDidChange() -{ - if (!m_webPageProxy->isValid()) - return; - - // We only want one UpdateGeometry message in flight at once, so if we've already sent one but - // haven't yet received the reply we'll just return early here. - if (m_isWaitingForDidUpdateGeometry) - return; - - sendUpdateGeometry(); -} - -void TiledCoreAnimationDrawingAreaProxy::waitForPossibleGeometryUpdate(double timeout) -{ - if (!m_isWaitingForDidUpdateGeometry) - return; - - if (m_webPageProxy->process()->isLaunching()) - return; - - m_webPageProxy->process()->connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateGeometry>(m_webPageProxy->pageID(), timeout); -} - -void TiledCoreAnimationDrawingAreaProxy::colorSpaceDidChange() -{ - m_webPageProxy->process()->send(Messages::DrawingArea::SetColorSpace(m_webPageProxy->colorSpace()), m_webPageProxy->pageID()); -} - -void TiledCoreAnimationDrawingAreaProxy::minimumLayoutSizeDidChange() -{ - if (!m_webPageProxy->isValid()) - return; - - // We only want one UpdateGeometry message in flight at once, so if we've already sent one but - // haven't yet received the reply we'll just return early here. - if (m_isWaitingForDidUpdateGeometry) - return; - - sendUpdateGeometry(); -} - -void TiledCoreAnimationDrawingAreaProxy::enterAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext& layerTreeContext) -{ - m_webPageProxy->enterAcceleratedCompositingMode(layerTreeContext); -} - -void TiledCoreAnimationDrawingAreaProxy::exitAcceleratedCompositingMode(uint64_t backingStoreStateID, const UpdateInfo&) -{ - // This should never be called. - ASSERT_NOT_REACHED(); -} - -void TiledCoreAnimationDrawingAreaProxy::updateAcceleratedCompositingMode(uint64_t backingStoreStateID, const LayerTreeContext& layerTreeContext) -{ - m_webPageProxy->updateAcceleratedCompositingMode(layerTreeContext); -} - -void TiledCoreAnimationDrawingAreaProxy::didUpdateGeometry() -{ - ASSERT(m_isWaitingForDidUpdateGeometry); - - m_isWaitingForDidUpdateGeometry = false; - - IntSize minimumLayoutSize = m_webPageProxy->minimumLayoutSize(); - - // If the WKView was resized while we were waiting for a DidUpdateGeometry reply from the web process, - // we need to resend the new size here. - if (m_lastSentSize != m_size || m_lastSentLayerPosition != m_layerPosition || m_lastSentMinimumLayoutSize != minimumLayoutSize) - sendUpdateGeometry(); -} - -void TiledCoreAnimationDrawingAreaProxy::intrinsicContentSizeDidChange(const IntSize& newIntrinsicContentSize) -{ - if (m_webPageProxy->minimumLayoutSize().width() > 0) - m_webPageProxy->intrinsicContentSizeDidChange(newIntrinsicContentSize); -} - -void TiledCoreAnimationDrawingAreaProxy::sendUpdateGeometry() -{ - ASSERT(!m_isWaitingForDidUpdateGeometry); - - m_lastSentMinimumLayoutSize = m_webPageProxy->minimumLayoutSize(); - m_lastSentSize = m_size; - m_lastSentLayerPosition = m_layerPosition; - m_webPageProxy->process()->send(Messages::DrawingArea::UpdateGeometry(m_size, m_layerPosition), m_webPageProxy->pageID()); - m_isWaitingForDidUpdateGeometry = true; -} - -} // namespace WebKit - -#endif // ENABLE(THREADED_SCROLLING) diff --git a/Source/WebKit2/UIProcess/mac/WKFullKeyboardAccessWatcher.mm b/Source/WebKit2/UIProcess/mac/WKFullKeyboardAccessWatcher.mm deleted file mode 100644 index 0908a46cb..000000000 --- a/Source/WebKit2/UIProcess/mac/WKFullKeyboardAccessWatcher.mm +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WKFullKeyboardAccessWatcher.h" - -#import "WebContext.h" - -NSString * const KeyboardUIModeDidChangeNotification = @"com.apple.KeyboardUIModeDidChange"; -const CFStringRef AppleKeyboardUIMode = CFSTR("AppleKeyboardUIMode"); -const CFStringRef UniversalAccessDomain = CFSTR("com.apple.universalaccess"); - -using namespace WebKit; - -@implementation WKFullKeyboardAccessWatcher - -- (void)notifyAllWebContexts -{ - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0; i < contexts.size(); ++i) - contexts[i]->fullKeyboardAccessModeChanged(fullKeyboardAccessEnabled); -} - -- (void)retrieveKeyboardUIModeFromPreferences:(NSNotification *)notification -{ - BOOL oldValue = fullKeyboardAccessEnabled; - - CFPreferencesAppSynchronize(UniversalAccessDomain); - - Boolean keyExistsAndHasValidFormat; - int mode = CFPreferencesGetAppIntegerValue(AppleKeyboardUIMode, UniversalAccessDomain, &keyExistsAndHasValidFormat); - if (keyExistsAndHasValidFormat) { - // The keyboard access mode is reported by two bits: - // Bit 0 is set if feature is on - // Bit 1 is set if full keyboard access works for any control, not just text boxes and lists. - fullKeyboardAccessEnabled = (mode & 0x2); - } - - if (fullKeyboardAccessEnabled != oldValue) - [self notifyAllWebContexts]; -} - -- (id)init -{ - self = [super init]; - if (!self) - return nil; - - [self retrieveKeyboardUIModeFromPreferences:nil]; - - [[NSDistributedNotificationCenter defaultCenter] - addObserver:self selector:@selector(retrieveKeyboardUIModeFromPreferences:) - name:KeyboardUIModeDidChangeNotification object:nil]; - - return self; -} - -+ (BOOL)fullKeyboardAccessEnabled -{ - static WKFullKeyboardAccessWatcher *watcher = [[WKFullKeyboardAccessWatcher alloc] init]; - return watcher->fullKeyboardAccessEnabled; -} - -@end diff --git a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h deleted file mode 100644 index c174a7a79..000000000 --- a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#if ENABLE(FULLSCREEN_API) - -#import <wtf/OwnPtr.h> -#import <wtf/RetainPtr.h> - -namespace WebKit { -class LayerTreeContext; -} - -namespace WebCore { -class DisplaySleepDisabler; -class IntRect; -} - -@class WKView; -@class WebCoreFullScreenPlaceholderView; -@class WebWindowScaleAnimation; -@class WebWindowFadeAnimation; - -typedef enum FullScreenState : NSInteger FullScreenState; - -@interface WKFullScreenWindowController : NSWindowController<NSWindowDelegate> { -@private - WKView *_webView; - RetainPtr<WebCoreFullScreenPlaceholderView> _webViewPlaceholder; - RetainPtr<WebWindowScaleAnimation> _scaleAnimation; - RetainPtr<WebWindowFadeAnimation> _fadeAnimation; - RetainPtr<NSWindow> _backgroundWindow; - NSRect _initialFrame; - NSRect _finalFrame; - RetainPtr<NSTimer> _watchdogTimer; - - FullScreenState _fullScreenState; - - double _savedScale; -} - -- (WKView*)webView; -- (void)setWebView:(WKView*)webView; - -- (WebCoreFullScreenPlaceholderView*)webViewPlaceholder; - -- (BOOL)isFullScreen; - -- (void)enterFullScreen:(NSScreen *)screen; -- (void)exitFullScreen; -- (void)close; -- (void)beganEnterFullScreenWithInitialFrame:(const WebCore::IntRect&)initialFrame finalFrame:(const WebCore::IntRect&)finalFrame; -- (void)beganExitFullScreenWithInitialFrame:(const WebCore::IntRect&)initialFrame finalFrame:(const WebCore::IntRect&)finalFrame; - -@end - -#endif diff --git a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm b/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm deleted file mode 100644 index dd02ee212..000000000 --- a/Source/WebKit2/UIProcess/mac/WKFullScreenWindowController.mm +++ /dev/null @@ -1,628 +0,0 @@ -/* - * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" - -#if ENABLE(FULLSCREEN_API) - -#import "WKFullScreenWindowController.h" - -#import "LayerTreeContext.h" -#import "WKAPICast.h" -#import "WKViewInternal.h" -#import "WKViewPrivate.h" -#import "WebFullScreenManagerProxy.h" -#import "WebPageProxy.h" -#import <QuartzCore/QuartzCore.h> -#import <WebCore/DisplaySleepDisabler.h> -#import <WebCore/FloatRect.h> -#import <WebCore/IntRect.h> -#import <WebCore/LocalizedStrings.h> -#import <WebCore/WebCoreFullScreenPlaceholderView.h> -#import <WebCore/WebCoreFullScreenWindow.h> -#import <WebCore/WebWindowAnimation.h> -#import <WebKit/WebNSWindowExtras.h> -#import <WebKitSystemInterface.h> - -using namespace WebKit; -using namespace WebCore; - -static RetainPtr<NSWindow> createBackgroundFullscreenWindow(NSRect frame); - -static const CFTimeInterval defaultAnimationDuration = 0.5; -static const NSTimeInterval DefaultWatchdogTimerInterval = 1; - -enum FullScreenState : NSInteger { - NotInFullScreen, - WaitingToEnterFullScreen, - EnteringFullScreen, - InFullScreen, - WaitingToExitFullScreen, - ExitingFullScreen, -}; - -@interface NSWindow (WebNSWindowDetails) -- (void)exitFullScreenMode:(id)sender; -- (void)enterFullScreenMode:(id)sender; -@end - -@interface WKFullScreenWindowController(Private)<NSAnimationDelegate> -- (void)_replaceView:(NSView*)view with:(NSView*)otherView; -- (WebPageProxy*)_page; -- (WebFullScreenManagerProxy*)_manager; -- (void)_startEnterFullScreenAnimationWithDuration:(NSTimeInterval)duration; -- (void)_startExitFullScreenAnimationWithDuration:(NSTimeInterval)duration; -@end - -static NSRect convertRectToScreen(NSWindow *window, NSRect rect) -{ - return [window convertRectToScreen:rect]; -} - -@interface NSWindow(IsOnActiveSpaceAdditionForTigerAndLeopard) -- (BOOL)isOnActiveSpace; -@end - -@implementation WKFullScreenWindowController - -#pragma mark - -#pragma mark Initialization -- (id)initWithWindow:(NSWindow *)window -{ - self = [super initWithWindow:window]; - if (!self) - return nil; - [window setDelegate:self]; - [window setCollectionBehavior:([window collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary)]; - [self windowDidLoad]; - - return self; -} - -- (void)dealloc -{ - [self setWebView:nil]; - [[self window] setDelegate:nil]; - - [NSObject cancelPreviousPerformRequestsWithTarget:self]; - - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [super dealloc]; -} - -- (void)windowDidLoad -{ - [super windowDidLoad]; - - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidChangeScreenParameters:) name:NSApplicationDidChangeScreenParametersNotification object:NSApp]; -} - -#pragma mark - -#pragma mark Accessors - -- (WKView*)webView -{ - return _webView; -} - -- (void)setWebView:(WKView *)webView -{ - [webView retain]; - [_webView release]; - _webView = webView; -} - -- (BOOL)isFullScreen -{ - return _fullScreenState == WaitingToEnterFullScreen - || _fullScreenState == EnteringFullScreen - || _fullScreenState == InFullScreen; -} - -- (WebCoreFullScreenPlaceholderView*)webViewPlaceholder -{ - return _webViewPlaceholder.get(); -} - -#pragma mark - -#pragma mark NSWindowController overrides - -- (void)cancelOperation:(id)sender -{ - // If the page doesn't respond in DefaultWatchdogTimerInterval seconds, it could be because - // the WebProcess has hung, so exit anyway. - if (!_watchdogTimer) { - [self _manager]->requestExitFullScreen(); - _watchdogTimer = adoptNS([[NSTimer alloc] initWithFireDate:nil interval:DefaultWatchdogTimerInterval target:self selector:@selector(exitFullScreen) userInfo:nil repeats:NO]); - [[NSRunLoop mainRunLoop] addTimer:_watchdogTimer.get() forMode:NSDefaultRunLoopMode]; - } -} - -#pragma mark - -#pragma mark Notifications - -- (void)applicationDidChangeScreenParameters:(NSNotification*)notification -{ - // The user may have changed the main screen by moving the menu bar, or they may have changed - // the Dock's size or location, or they may have changed the fullScreen screen's dimensions. - // Update our presentation parameters, and ensure that the full screen window occupies the - // entire screen: - NSWindow* window = [self window]; - NSRect screenFrame = [[window screen] frame]; - [window setFrame:screenFrame display:YES]; - [_backgroundWindow.get() setFrame:screenFrame display:YES]; -} - -#pragma mark - -#pragma mark Exposed Interface - -static RetainPtr<CGDataProviderRef> createImageProviderWithCopiedData(CGDataProviderRef sourceProvider) -{ - RetainPtr<CFDataRef> data = adoptCF(CGDataProviderCopyData(sourceProvider)); - return adoptCF(CGDataProviderCreateWithCFData(data.get())); -} - -static RetainPtr<CGImageRef> createImageWithCopiedData(CGImageRef sourceImage) -{ - size_t width = CGImageGetWidth(sourceImage); - size_t height = CGImageGetHeight(sourceImage); - size_t bitsPerComponent = CGImageGetBitsPerComponent(sourceImage); - size_t bitsPerPixel = CGImageGetBitsPerPixel(sourceImage); - size_t bytesPerRow = CGImageGetBytesPerRow(sourceImage); - CGColorSpaceRef colorSpace = CGImageGetColorSpace(sourceImage); - CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(sourceImage); - RetainPtr<CGDataProviderRef> provider = createImageProviderWithCopiedData(CGImageGetDataProvider(sourceImage)); - bool shouldInterpolate = CGImageGetShouldInterpolate(sourceImage); - CGColorRenderingIntent intent = CGImageGetRenderingIntent(sourceImage); - - return adoptCF(CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, provider.get(), 0, shouldInterpolate, intent)); -} - -- (void)enterFullScreen:(NSScreen *)screen -{ - if ([self isFullScreen]) - return; - _fullScreenState = WaitingToEnterFullScreen; - - if (!screen) - screen = [NSScreen mainScreen]; - NSRect screenFrame = [screen frame]; - - NSRect webViewFrame = convertRectToScreen([_webView window], [_webView convertRect:[_webView frame] toView:nil]); - - // Flip coordinate system: - webViewFrame.origin.y = NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]) - NSMaxY(webViewFrame); - - CGWindowID windowID = [[_webView window] windowNumber]; - RetainPtr<CGImageRef> webViewContents = adoptCF(CGWindowListCreateImage(NSRectToCGRect(webViewFrame), kCGWindowListOptionIncludingWindow, windowID, kCGWindowImageShouldBeOpaque)); - - // Using the returned CGImage directly would result in calls to the WindowServer every time - // the image was painted. Instead, copy the image data into our own process to eliminate that - // future overhead. - webViewContents = createImageWithCopiedData(webViewContents.get()); - - // Screen updates to be re-enabled in _startEnterFullScreenAnimationWithDuration: - NSDisableScreenUpdates(); - [[self window] setAutodisplay:NO]; - - NSResponder *webWindowFirstResponder = [[_webView window] firstResponder]; - [self _manager]->saveScrollPosition(); - [[self window] setFrame:screenFrame display:NO]; - - // Painting is normally suspended when the WKView is removed from the window, but this is - // unnecessary in the full-screen animation case, and can cause bugs; see - // https://bugs.webkit.org/show_bug.cgi?id=88940 and https://bugs.webkit.org/show_bug.cgi?id=88374 - // We will resume the normal behavior in _startEnterFullScreenAnimationWithDuration: - [_webView _setSuppressVisibilityUpdates:YES]; - - // Swap the webView placeholder into place. - if (!_webViewPlaceholder) { - _webViewPlaceholder = adoptNS([[WebCoreFullScreenPlaceholderView alloc] initWithFrame:[_webView frame]]); - [_webViewPlaceholder.get() setAction:@selector(cancelOperation:)]; - } - [_webViewPlaceholder.get() setTarget:nil]; - [_webViewPlaceholder.get() setContents:(id)webViewContents.get()]; - [self _replaceView:_webView with:_webViewPlaceholder.get()]; - - // Then insert the WebView into the full screen window - NSView* contentView = [[self window] contentView]; - [contentView addSubview:_webView positioned:NSWindowBelow relativeTo:nil]; - [_webView setFrame:[contentView bounds]]; - - [[self window] makeResponder:webWindowFirstResponder firstResponderIfDescendantOfView:_webView]; - - [self _manager]->setAnimatingFullScreen(true); - [self _manager]->willEnterFullScreen(); - _savedScale = [self _page]->pageScaleFactor(); - [self _page]->scalePage(1, IntPoint()); -} - -- (void)beganEnterFullScreenWithInitialFrame:(const WebCore::IntRect&)initialFrame finalFrame:(const WebCore::IntRect&)finalFrame -{ - if (_fullScreenState != WaitingToEnterFullScreen) - return; - _fullScreenState = EnteringFullScreen; - - _initialFrame = initialFrame; - _finalFrame = finalFrame; - - if (!_backgroundWindow) - _backgroundWindow = createBackgroundFullscreenWindow(NSZeroRect); - - [[self window] enterFullScreenMode:self]; -} - -- (void)finishedEnterFullScreenAnimation:(bool)completed -{ - if (_fullScreenState != EnteringFullScreen) - return; - _fullScreenState = InFullScreen; - - if (completed) { - // Screen updates to be re-enabled ta the end of the current block. - NSDisableScreenUpdates(); - [self _manager]->didEnterFullScreen(); - [self _manager]->setAnimatingFullScreen(false); - - NSRect windowBounds = [[self window] frame]; - windowBounds.origin = NSZeroPoint; - WKWindowSetClipRect([self window], windowBounds); - - [_fadeAnimation.get() stopAnimation]; - [_fadeAnimation.get() setWindow:nil]; - _fadeAnimation = nullptr; - - [_backgroundWindow.get() orderOut:self]; - [_backgroundWindow.get() setFrame:NSZeroRect display:YES]; - - [_webViewPlaceholder.get() setExitWarningVisible:YES]; - [_webViewPlaceholder.get() setTarget:self]; - NSEnableScreenUpdates(); - } else - [_scaleAnimation.get() stopAnimation]; -} - -- (void)exitFullScreen -{ - if (_watchdogTimer) { - [_watchdogTimer.get() invalidate]; - _watchdogTimer.clear(); - } - - if (![self isFullScreen]) - return; - _fullScreenState = WaitingToExitFullScreen; - - [_webViewPlaceholder.get() setExitWarningVisible:NO]; - - // Screen updates to be re-enabled in _startExitFullScreenAnimationWithDuration: or beganExitFullScreenWithInitialFrame:finalFrame: - NSDisableScreenUpdates(); - [[self window] setAutodisplay:NO]; - - // See the related comment in enterFullScreen: - // We will resume the normal behavior in _startExitFullScreenAnimationWithDuration: - [_webView _setSuppressVisibilityUpdates:YES]; - [_webViewPlaceholder.get() setTarget:nil]; - - [self _manager]->setAnimatingFullScreen(true); - [self _manager]->willExitFullScreen(); -} - -- (void)beganExitFullScreenWithInitialFrame:(const WebCore::IntRect&)initialFrame finalFrame:(const WebCore::IntRect&)finalFrame -{ - - if (_fullScreenState != WaitingToExitFullScreen) - return; - _fullScreenState = ExitingFullScreen; - - if (![[self window] isOnActiveSpace]) { - // If the full screen window is not in the active space, the NSWindow full screen animation delegate methods - // will never be called. So call finishedExitFullScreenAnimation explicitly. - [self finishedExitFullScreenAnimation:YES]; - - // Because we are breaking the normal animation pattern, re-enable screen updates - // as exitFullScreen has disabled them, but _startExitFullScreenAnimationWithDuration: - // will never be called. - NSEnableScreenUpdates(); - } - - [[self window] exitFullScreenMode:self]; -} - -static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void*); - -- (void)finishedExitFullScreenAnimation:(bool)completed -{ - if (_fullScreenState != ExitingFullScreen) - return; - _fullScreenState = NotInFullScreen; - - // Screen updates to be re-enabled in completeFinishExitFullScreenAnimationAfterRepaint. - NSDisableScreenUpdates(); - [[_webViewPlaceholder.get() window] setAutodisplay:NO]; - - NSResponder *firstResponder = [[self window] firstResponder]; - [self _replaceView:_webViewPlaceholder.get() with:_webView]; - [[_webView window] makeResponder:firstResponder firstResponderIfDescendantOfView:_webView]; - - NSRect windowBounds = [[self window] frame]; - windowBounds.origin = NSZeroPoint; - WKWindowSetClipRect([self window], windowBounds); - - [[self window] orderOut:self]; - [[self window] setFrame:NSZeroRect display:YES]; - - [_fadeAnimation.get() stopAnimation]; - [_fadeAnimation.get() setWindow:nil]; - _fadeAnimation = nullptr; - - [_backgroundWindow.get() orderOut:self]; - [_backgroundWindow.get() setFrame:NSZeroRect display:YES]; - - [[_webView window] makeKeyAndOrderFront:self]; - - // These messages must be sent after the swap or flashing will occur during forceRepaint: - [self _manager]->didExitFullScreen(); - [self _manager]->setAnimatingFullScreen(false); - [self _page]->scalePage(_savedScale, IntPoint()); - [self _manager]->restoreScrollPosition(); - [self _page]->forceRepaint(VoidCallback::create(self, completeFinishExitFullScreenAnimationAfterRepaint)); -} - -- (void)completeFinishExitFullScreenAnimationAfterRepaint -{ - [[_webView window] setAutodisplay:YES]; - [[_webView window] displayIfNeeded]; - NSEnableScreenUpdates(); -} - -static void completeFinishExitFullScreenAnimationAfterRepaint(WKErrorRef, void* _self) -{ - [(WKFullScreenWindowController*)_self completeFinishExitFullScreenAnimationAfterRepaint]; -} - -- (void)performClose:(id)sender -{ - if ([self isFullScreen]) - [self cancelOperation:sender]; -} - -- (void)close -{ - // We are being asked to close rapidly, most likely because the page - // has closed or the web process has crashed. Just walk through our - // normal exit full screen sequence, but don't wait to be called back - // in response. - if ([self isFullScreen]) - [self exitFullScreen]; - - if (_fullScreenState == ExitingFullScreen) - [self finishedExitFullScreenAnimation:YES]; - - [super close]; -} - -#pragma mark - -#pragma mark Custom NSWindow Full Screen Animation - -- (NSArray *)customWindowsToEnterFullScreenForWindow:(NSWindow *)window -{ - return [NSArray arrayWithObjects:[self window], _backgroundWindow.get(), nil]; -} - -- (NSArray *)customWindowsToExitFullScreenForWindow:(NSWindow *)window -{ - return [NSArray arrayWithObjects:[self window], _backgroundWindow.get(), nil]; -} - -- (void)window:(NSWindow *)window startCustomAnimationToEnterFullScreenWithDuration:(NSTimeInterval)duration -{ - [self _startEnterFullScreenAnimationWithDuration:duration]; -} - -- (void)window:(NSWindow *)window startCustomAnimationToExitFullScreenWithDuration:(NSTimeInterval)duration -{ - [self _startExitFullScreenAnimationWithDuration:duration]; -} - -- (void)windowDidFailToEnterFullScreen:(NSWindow *)window -{ - [self finishedEnterFullScreenAnimation:NO]; -} - -- (void)windowDidEnterFullScreen:(NSNotification*)notification -{ - [self finishedEnterFullScreenAnimation:YES]; -} - -- (void)windowDidFailToExitFullScreen:(NSWindow *)window -{ - [self finishedExitFullScreenAnimation:NO]; -} - -- (void)windowDidExitFullScreen:(NSNotification*)notification -{ - [self finishedExitFullScreenAnimation:YES]; -} - -#pragma mark - -#pragma mark Internal Interface - -- (WebPageProxy*)_page -{ - return toImpl([_webView pageRef]); -} - -- (WebFullScreenManagerProxy*)_manager -{ - WebPageProxy* webPage = [self _page]; - if (!webPage) - return 0; - return webPage->fullScreenManager(); -} - -- (void)_replaceView:(NSView*)view with:(NSView*)otherView -{ - [CATransaction begin]; - [CATransaction setDisableActions:YES]; - [otherView setFrame:[view frame]]; - [otherView setAutoresizingMask:[view autoresizingMask]]; - [otherView removeFromSuperview]; - [[view superview] addSubview:otherView positioned:NSWindowAbove relativeTo:view]; - [view removeFromSuperview]; - [CATransaction commit]; -} - -static RetainPtr<NSWindow> createBackgroundFullscreenWindow(NSRect frame) -{ - NSWindow *window = [[NSWindow alloc] initWithContentRect:frame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]; - [window setOpaque:YES]; - [window setBackgroundColor:[NSColor blackColor]]; - [window setReleasedWhenClosed:NO]; - return adoptNS(window); -} - -static NSRect windowFrameFromApparentFrames(NSRect screenFrame, NSRect initialFrame, NSRect finalFrame) -{ - NSRect initialWindowFrame; - if (!NSWidth(initialFrame) || !NSWidth(finalFrame) || !NSHeight(initialFrame) || !NSHeight(finalFrame)) - return screenFrame; - - CGFloat xScale = NSWidth(screenFrame) / NSWidth(finalFrame); - CGFloat yScale = NSHeight(screenFrame) / NSHeight(finalFrame); - CGFloat xTrans = NSMinX(screenFrame) - NSMinX(finalFrame); - CGFloat yTrans = NSMinY(screenFrame) - NSMinY(finalFrame); - initialWindowFrame.size = NSMakeSize(NSWidth(initialFrame) * xScale, NSHeight(initialFrame) * yScale); - initialWindowFrame.origin = NSMakePoint - ( NSMinX(initialFrame) + xTrans / (NSWidth(finalFrame) / NSWidth(initialFrame)) - , NSMinY(initialFrame) + yTrans / (NSHeight(finalFrame) / NSHeight(initialFrame))); - return initialWindowFrame; -} - -- (void)_startEnterFullScreenAnimationWithDuration:(NSTimeInterval)duration -{ - NSRect screenFrame = [[[self window] screen] frame]; - NSRect initialWindowFrame = windowFrameFromApparentFrames(screenFrame, _initialFrame, _finalFrame); - - _scaleAnimation = adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:initialWindowFrame finalFrame:screenFrame]); - - [_scaleAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; - [_scaleAnimation.get() setCurrentProgress:0]; - [_scaleAnimation.get() startAnimation]; - - // WKWindowSetClipRect takes window coordinates, so convert from screen coordinates here: - NSRect finalBounds = _finalFrame; - finalBounds.origin = [[self window] convertScreenToBase:finalBounds.origin]; - WKWindowSetClipRect([self window], finalBounds); - - NSWindow* window = [self window]; - NSWindowCollectionBehavior behavior = [window collectionBehavior]; - [window setCollectionBehavior:(behavior | NSWindowCollectionBehaviorCanJoinAllSpaces)]; - [window makeKeyAndOrderFront:self]; - [window setCollectionBehavior:behavior]; - - - if (!_backgroundWindow) - _backgroundWindow = createBackgroundFullscreenWindow(screenFrame); - else - [_backgroundWindow.get() setFrame:screenFrame display:NO]; - - CGFloat currentAlpha = 0; - if (_fadeAnimation) { - currentAlpha = [_fadeAnimation.get() currentAlpha]; - [_fadeAnimation.get() stopAnimation]; - [_fadeAnimation.get() setWindow:nil]; - } - - _fadeAnimation = adoptNS([[WebWindowFadeAnimation alloc] initWithDuration:duration - window:_backgroundWindow.get() - initialAlpha:currentAlpha - finalAlpha:1]); - [_fadeAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; - [_fadeAnimation.get() setCurrentProgress:0]; - [_fadeAnimation.get() startAnimation]; - - [_backgroundWindow.get() orderWindow:NSWindowBelow relativeTo:[[self window] windowNumber]]; - - [_webView _setSuppressVisibilityUpdates:NO]; - [[self window] setAutodisplay:YES]; - [[self window] displayIfNeeded]; - NSEnableScreenUpdates(); -} - -- (void)_startExitFullScreenAnimationWithDuration:(NSTimeInterval)duration -{ - if ([self isFullScreen]) { - // We still believe we're in full screen mode, so we must have been asked to exit full - // screen by the system full screen button. - [self _manager]->requestExitFullScreen(); - [self exitFullScreen]; - _fullScreenState = ExitingFullScreen; - } - - NSRect screenFrame = [[[self window] screen] frame]; - NSRect initialWindowFrame = windowFrameFromApparentFrames(screenFrame, _initialFrame, _finalFrame); - - NSRect currentFrame = _scaleAnimation ? [_scaleAnimation.get() currentFrame] : [[self window] frame]; - _scaleAnimation = adoptNS([[WebWindowScaleAnimation alloc] initWithHintedDuration:duration window:[self window] initalFrame:currentFrame finalFrame:initialWindowFrame]); - - [_scaleAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; - [_scaleAnimation.get() setCurrentProgress:0]; - [_scaleAnimation.get() startAnimation]; - - if (!_backgroundWindow) - _backgroundWindow = createBackgroundFullscreenWindow(screenFrame); - else - [_backgroundWindow.get() setFrame:screenFrame display:NO]; - - CGFloat currentAlpha = 1; - if (_fadeAnimation) { - currentAlpha = [_fadeAnimation.get() currentAlpha]; - [_fadeAnimation.get() stopAnimation]; - [_fadeAnimation.get() setWindow:nil]; - } - _fadeAnimation = adoptNS([[WebWindowFadeAnimation alloc] initWithDuration:duration - window:_backgroundWindow.get() - initialAlpha:currentAlpha - finalAlpha:0]); - [_fadeAnimation.get() setAnimationBlockingMode:NSAnimationNonblocking]; - [_fadeAnimation.get() setCurrentProgress:0]; - [_fadeAnimation.get() startAnimation]; - - [_backgroundWindow.get() orderWindow:NSWindowBelow relativeTo:[[self window] windowNumber]]; - - // WKWindowSetClipRect takes window coordinates, so convert from screen coordinates here: - NSRect finalBounds = _finalFrame; - finalBounds.origin = [[self window] convertScreenToBase:finalBounds.origin]; - WKWindowSetClipRect([self window], finalBounds); - - [_webView _setSuppressVisibilityUpdates:NO]; - [[self window] setAutodisplay:YES]; - [[self window] displayIfNeeded]; - NSEnableScreenUpdates(); -} -@end - -#endif diff --git a/Source/WebKit2/UIProcess/mac/WebContextMac.mm b/Source/WebKit2/UIProcess/mac/WebContextMac.mm deleted file mode 100644 index a07faae4f..000000000 --- a/Source/WebKit2/UIProcess/mac/WebContextMac.mm +++ /dev/null @@ -1,604 +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. - */ - -#import "config.h" -#import "WebContext.h" - -#import "PluginProcessManager.h" -#import "SharedWorkerProcessManager.h" -#import "TextChecker.h" -#import "WKBrowsingContextControllerInternal.h" -#import "WKBrowsingContextControllerInternal.h" -#import "WebKitSystemInterface.h" -#import "WebProcessCreationParameters.h" -#import "WebProcessMessages.h" -#import <QuartzCore/CARemoteLayerServer.h> -#import <WebCore/Color.h> -#import <WebCore/FileSystem.h> -#import <WebCore/NotImplemented.h> -#import <WebCore/PlatformPasteboard.h> -#import <sys/param.h> - -#if ENABLE(NETWORK_PROCESS) -#import "NetworkProcessCreationParameters.h" -#import "NetworkProcessProxy.h" -#endif - - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - -#if __has_include(<CFNetwork/CFURLProtocolPriv.h>) -#include <CFNetwork/CFURLProtocolPriv.h> -#else -extern "C" Boolean _CFNetworkIsKnownHSTSHostWithSession(CFURLRef url, CFURLStorageSessionRef session); -extern "C" void _CFNetworkResetHSTSHostsWithSession(CFURLStorageSessionRef session); -#endif - -#endif - -using namespace WebCore; - -NSString *WebDatabaseDirectoryDefaultsKey = @"WebDatabaseDirectory"; -NSString *WebKitLocalCacheDefaultsKey = @"WebKitLocalCache"; -NSString *WebStorageDirectoryDefaultsKey = @"WebKitLocalStorageDatabasePathPreferenceKey"; -NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault"; - -static NSString *WebKitApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification = @"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification"; - -// FIXME: <rdar://problem/9138817> - After this "backwards compatibility" radar is removed, this code should be removed to only return an empty String. -NSString *WebIconDatabaseDirectoryDefaultsKey = @"WebIconDatabaseDirectoryDefaultsKey"; - -static NSString * const WebKit2HTTPProxyDefaultsKey = @"WebKit2HTTPProxy"; -static NSString * const WebKit2HTTPSProxyDefaultsKey = @"WebKit2HTTPSProxy"; - -namespace WebKit { - -NSString *SchemeForCustomProtocolRegisteredNotificationName = @"WebKitSchemeForCustomProtocolRegisteredNotification"; -NSString *SchemeForCustomProtocolUnregisteredNotificationName = @"WebKitSchemeForCustomProtocolUnregisteredNotification"; - -static bool s_applicationIsOccluded = false; -static bool s_applicationWindowModificationsHaveStopped = false; -static bool s_occlusionNotificationHandlersRegistered = false; -static bool s_processSuppressionEnabledForAllContexts = true; - -static void registerUserDefaultsIfNeeded() -{ - static bool didRegister; - if (didRegister) - return; - - didRegister = true; - NSMutableDictionary *registrationDictionary = [NSMutableDictionary dictionary]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - [registrationDictionary setObject:[NSNumber numberWithBool:YES] forKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]; -#endif - - [[NSUserDefaults standardUserDefaults] registerDefaults:registrationDictionary]; -} - -static void updateProcessSuppressionStateOfGlobalChildProcesses() -{ - // The plan is to have all child processes become context specific. This function - // can be removed once that is complete. -#if ENABLE(PLUGIN_PROCESS) || ENABLE(SHARED_WORKER_PROCESS) - bool canEnable = WebContext::canEnableProcessSuppressionForGlobalChildProcesses(); -#endif -#if ENABLE(PLUGIN_PROCESS) - PluginProcessManager::shared().setProcessSuppressionEnabled(canEnable); -#endif -#if ENABLE(SHARED_WORKER_PROCESS) - SharedWorkerProcessManager::shared().setProcessSuppressionEnabled(canEnable); -#endif -} - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 -static void applicationOcclusionStateChanged() -{ - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) { - if (contexts[i]->processSuppressionEnabled()) - contexts[i]->updateProcessSuppressionStateOfChildProcesses(); - } - - if (s_processSuppressionEnabledForAllContexts) - updateProcessSuppressionStateOfGlobalChildProcesses(); -} - -static void applicationBecameVisible(uint32_t, void*, uint32_t, void*, uint32_t) -{ - if (!s_applicationIsOccluded) - return; - s_applicationIsOccluded = false; - applicationOcclusionStateChanged(); -} - -static void applicationBecameOccluded(uint32_t, void*, uint32_t, void*, uint32_t) -{ - if (s_applicationIsOccluded) - return; - s_applicationIsOccluded = true; - applicationOcclusionStateChanged(); -} - -static void applicationWindowModificationsStarted(uint32_t, void*, uint32_t, void*, uint32_t) -{ - if (!s_applicationWindowModificationsHaveStopped) - return; - s_applicationWindowModificationsHaveStopped = false; - applicationOcclusionStateChanged(); -} - -static void applicationWindowModificationsStopped(uint32_t, void*, uint32_t, void*, uint32_t) -{ - if (s_applicationWindowModificationsHaveStopped) - return; - s_applicationWindowModificationsHaveStopped = true; - applicationOcclusionStateChanged(); -} - -struct OcclusionNotificationHandler { - WKOcclusionNotificationType notificationType; - WKOcclusionNotificationHandler handler; - const char *name; -}; - -static const OcclusionNotificationHandler occlusionNotificationHandlers[] = { - { WKOcclusionNotificationTypeApplicationBecameVisible, applicationBecameVisible, "Application Became Visible" }, - { WKOcclusionNotificationTypeApplicationBecameOccluded, applicationBecameOccluded, "Application Became Occluded" }, - { WKOcclusionNotificationTypeApplicationWindowModificationsStarted, applicationWindowModificationsStarted, "Application Window Modifications Started" }, - { WKOcclusionNotificationTypeApplicationWindowModificationsStopped, applicationWindowModificationsStopped, "Application Window Modifications Stopped" }, -}; - -#endif - -static void registerOcclusionNotificationHandlers() -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - for (const OcclusionNotificationHandler& occlusionNotificationHandler : occlusionNotificationHandlers) { - bool result = WKRegisterOcclusionNotificationHandler(occlusionNotificationHandler.notificationType, occlusionNotificationHandler.handler); - UNUSED_PARAM(result); - ASSERT_WITH_MESSAGE(result, "Registration of \"%s\" notification handler failed.\n", occlusionNotificationHandler.name); - } -#endif -} - -static void unregisterOcclusionNotificationHandlers() -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - for (const OcclusionNotificationHandler& occlusionNotificationHandler : occlusionNotificationHandlers) { - bool result = WKUnregisterOcclusionNotificationHandler(occlusionNotificationHandler.notificationType, occlusionNotificationHandler.handler); - UNUSED_PARAM(result); - ASSERT_WITH_MESSAGE(result, "Unregistration of \"%s\" notification handler failed.\n", occlusionNotificationHandler.name); - } -#endif -} - -static void enableOcclusionNotifications() -{ - if (s_occlusionNotificationHandlersRegistered) - return; - - s_occlusionNotificationHandlersRegistered = true; - registerOcclusionNotificationHandlers(); -} - -static void disableOcclusionNotifications() -{ - if (!s_occlusionNotificationHandlersRegistered) - return; - - s_occlusionNotificationHandlersRegistered = false; - unregisterOcclusionNotificationHandlers(); -} - -static bool processSuppressionIsEnabledForAnyContext() -{ - bool result = false; - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) { - if (contexts[i]->processSuppressionEnabled()) { - result = true; - break; - } - } - return result; -} - -static bool processSuppressionIsEnabledForAllContexts() -{ - bool result = true; - const Vector<WebContext*>& contexts = WebContext::allContexts(); - for (size_t i = 0, count = contexts.size(); i < count; ++i) { - if (!contexts[i]->processSuppressionEnabled()) { - result = false; - break; - } - } - return result; -} - -static bool omitProcessSuppression() -{ - static bool result = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKit2OmitProcessSuppression"]; - return result; -} - -void WebContext::platformInitialize() -{ - registerUserDefaultsIfNeeded(); - registerNotificationObservers(); - ASSERT(m_processSuppressionEnabled); - enableOcclusionNotifications(); -} - -String WebContext::platformDefaultApplicationCacheDirectory() const -{ - NSString *appName = [[NSBundle mainBundle] bundleIdentifier]; - if (!appName) - appName = [[NSProcessInfo processInfo] processName]; - - ASSERT(appName); - - char cacheDirectory[MAXPATHLEN]; - size_t cacheDirectoryLen = confstr(_CS_DARWIN_USER_CACHE_DIR, cacheDirectory, MAXPATHLEN); - if (!cacheDirectoryLen) - return String(); - - NSString *cacheDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:cacheDirectory length:cacheDirectoryLen - 1]; - return [cacheDir stringByAppendingPathComponent:appName]; -} - -void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) -{ - parameters.presenterApplicationPid = getpid(); - - NSURLCache *urlCache = [NSURLCache sharedURLCache]; - parameters.nsURLCacheMemoryCapacity = [urlCache memoryCapacity]; - parameters.nsURLCacheDiskCapacity = [urlCache diskCapacity]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - parameters.shouldForceScreenFontSubstitution = [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"]; -#endif - parameters.shouldEnableKerningAndLigaturesByDefault = [[NSUserDefaults standardUserDefaults] boolForKey:WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey]; - -#if USE(ACCELERATED_COMPOSITING) && HAVE(HOSTED_CORE_ANIMATION) - mach_port_t renderServerPort = [[CARemoteLayerServer sharedServer] serverPort]; - if (renderServerPort != MACH_PORT_NULL) - parameters.acceleratedCompositingPort = CoreIPC::MachPort(renderServerPort, MACH_MSG_TYPE_COPY_SEND); -#endif - - // FIXME: This should really be configurable; we shouldn't just blindly allow read access to the UI process bundle. - parameters.uiProcessBundleResourcePath = [[NSBundle mainBundle] resourcePath]; - SandboxExtension::createHandle(parameters.uiProcessBundleResourcePath, SandboxExtension::ReadOnly, parameters.uiProcessBundleResourcePathExtensionHandle); - - parameters.uiProcessBundleIdentifier = String([[NSBundle mainBundle] bundleIdentifier]); - -#if ENABLE(NETWORK_PROCESS) - if (!m_usesNetworkProcess) { -#endif - for (NSString *scheme in [WKBrowsingContextController customSchemes]) - parameters.urlSchemesRegisteredForCustomProtocols.append(scheme); -#if ENABLE(NETWORK_PROCESS) - } -#endif -} - -#if ENABLE(NETWORK_PROCESS) -void WebContext::platformInitializeNetworkProcess(NetworkProcessCreationParameters& parameters) -{ - NSURLCache *urlCache = [NSURLCache sharedURLCache]; - parameters.nsURLCacheMemoryCapacity = [urlCache memoryCapacity]; - parameters.nsURLCacheDiskCapacity = [urlCache diskCapacity]; - - parameters.parentProcessName = [[NSProcessInfo processInfo] processName]; - parameters.uiProcessBundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; - - for (NSString *scheme in [WKBrowsingContextController customSchemes]) - parameters.urlSchemesRegisteredForCustomProtocols.append(scheme); - - parameters.httpProxy = [[NSUserDefaults standardUserDefaults] stringForKey:WebKit2HTTPProxyDefaultsKey]; - parameters.httpsProxy = [[NSUserDefaults standardUserDefaults] stringForKey:WebKit2HTTPSProxyDefaultsKey]; -} -#endif - -void WebContext::platformInvalidateContext() -{ - unregisterNotificationObservers(); -} - -String WebContext::platformDefaultDiskCacheDirectory() const -{ - RetainPtr<NSString> cachePath = adoptNS((NSString *)WKCopyFoundationCacheDirectory()); - if (!cachePath) - cachePath = @"~/Library/Caches/com.apple.WebKit2.WebProcess"; - - return [cachePath.get() stringByStandardizingPath]; -} - -String WebContext::platformDefaultCookieStorageDirectory() const -{ - notImplemented(); - return [@"" stringByStandardizingPath]; -} - -String WebContext::platformDefaultDatabaseDirectory() const -{ - NSString *databasesDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebDatabaseDirectoryDefaultsKey]; - if (!databasesDirectory || ![databasesDirectory isKindOfClass:[NSString class]]) - databasesDirectory = @"~/Library/WebKit/Databases"; - return [databasesDirectory stringByStandardizingPath]; -} - -String WebContext::platformDefaultIconDatabasePath() const -{ - // FIXME: <rdar://problem/9138817> - After this "backwards compatibility" radar is removed, this code should be removed to only return an empty String. - NSString *databasesDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebIconDatabaseDirectoryDefaultsKey]; - if (!databasesDirectory || ![databasesDirectory isKindOfClass:[NSString class]]) - databasesDirectory = @"~/Library/Icons/WebpageIcons.db"; - return [databasesDirectory stringByStandardizingPath]; -} - -String WebContext::platformDefaultLocalStorageDirectory() const -{ - NSString *localStorageDirectory = [[NSUserDefaults standardUserDefaults] objectForKey:WebStorageDirectoryDefaultsKey]; - if (!localStorageDirectory || ![localStorageDirectory isKindOfClass:[NSString class]]) - localStorageDirectory = @"~/Library/WebKit/LocalStorage"; - return [localStorageDirectory stringByStandardizingPath]; -} - -bool WebContext::omitPDFSupport() -{ - // Since this is a "secret default" we don't bother registering it. - return [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitOmitPDFSupport"]; -} - -void WebContext::getPasteboardTypes(const String& pasteboardName, Vector<String>& pasteboardTypes) -{ - PlatformPasteboard(pasteboardName).getTypes(pasteboardTypes); -} - -void WebContext::getPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, Vector<String>& pathnames) -{ - PlatformPasteboard(pasteboardName).getPathnamesForType(pathnames, pasteboardType); -} - -void WebContext::getPasteboardStringForType(const String& pasteboardName, const String& pasteboardType, String& string) -{ - string = PlatformPasteboard(pasteboardName).stringForType(pasteboardType); -} - -void WebContext::getPasteboardBufferForType(const String& pasteboardName, const String& pasteboardType, SharedMemory::Handle& handle, uint64_t& size) -{ - RefPtr<SharedBuffer> buffer = PlatformPasteboard(pasteboardName).bufferForType(pasteboardType); - if (!buffer) - return; - size = buffer->size(); - RefPtr<SharedMemory> sharedMemoryBuffer = SharedMemory::create(size); - memcpy(sharedMemoryBuffer->data(), buffer->data(), size); - sharedMemoryBuffer->createHandle(handle, SharedMemory::ReadOnly); -} - -void WebContext::pasteboardCopy(const String& fromPasteboard, const String& toPasteboard) -{ - PlatformPasteboard(toPasteboard).copy(fromPasteboard); -} - -void WebContext::getPasteboardChangeCount(const String& pasteboardName, uint64_t& changeCount) -{ - changeCount = PlatformPasteboard(pasteboardName).changeCount(); -} - -void WebContext::getPasteboardUniqueName(String& pasteboardName) -{ - pasteboardName = PlatformPasteboard::uniqueName(); -} - -void WebContext::getPasteboardColor(const String& pasteboardName, WebCore::Color& color) -{ - color = PlatformPasteboard(pasteboardName).color(); -} - -void WebContext::getPasteboardURL(const String& pasteboardName, WTF::String& urlString) -{ - urlString = PlatformPasteboard(pasteboardName).url().string(); -} - -void WebContext::addPasteboardTypes(const String& pasteboardName, const Vector<String>& pasteboardTypes) -{ - PlatformPasteboard(pasteboardName).addTypes(pasteboardTypes); -} - -void WebContext::setPasteboardTypes(const String& pasteboardName, const Vector<String>& pasteboardTypes) -{ - PlatformPasteboard(pasteboardName).setTypes(pasteboardTypes); -} - -void WebContext::setPasteboardPathnamesForType(const String& pasteboardName, const String& pasteboardType, const Vector<String>& pathnames) -{ - PlatformPasteboard(pasteboardName).setPathnamesForType(pathnames, pasteboardType); -} - -void WebContext::setPasteboardStringForType(const String& pasteboardName, const String& pasteboardType, const String& string) -{ - PlatformPasteboard(pasteboardName).setStringForType(string, pasteboardType); -} - -void WebContext::setPasteboardBufferForType(const String& pasteboardName, const String& pasteboardType, const SharedMemory::Handle& handle, uint64_t size) -{ - if (handle.isNull()) { - PlatformPasteboard(pasteboardName).setBufferForType(0, pasteboardType); - return; - } - RefPtr<SharedMemory> sharedMemoryBuffer = SharedMemory::create(handle, SharedMemory::ReadOnly); - RefPtr<SharedBuffer> buffer = SharedBuffer::create(static_cast<unsigned char *>(sharedMemoryBuffer->data()), size); - PlatformPasteboard(pasteboardName).setBufferForType(buffer, pasteboardType); -} - -void WebContext::setProcessSuppressionEnabled(bool enabled) -{ - if (m_processSuppressionEnabled == enabled) - return; - m_processSuppressionEnabled = enabled; - processSuppressionEnabledChanged(); -} - -void WebContext::updateProcessSuppressionStateOfChildProcesses() -{ -#if ENABLE(NETWORK_PROCESS) - bool canEnable = canEnableProcessSuppressionForNetworkProcess(); - if (usesNetworkProcess() && networkProcess()) - networkProcess()->setProcessSuppressionEnabled(canEnable); -#endif - size_t processCount = m_processes.size(); - for (size_t i = 0; i < processCount; ++i) { - WebProcessProxy* process = m_processes[i].get(); - process->updateProcessSuppressionState(); - } -} - -bool WebContext::canEnableProcessSuppressionForNetworkProcess() const -{ - return (s_applicationIsOccluded || s_applicationWindowModificationsHaveStopped) && m_processSuppressionEnabled && !omitProcessSuppression(); -} - -bool WebContext::canEnableProcessSuppressionForWebProcess(const WebKit::WebProcessProxy *webProcess) const -{ - return (s_applicationIsOccluded || s_applicationWindowModificationsHaveStopped || webProcess->allPagesAreProcessSuppressible()) - && m_processSuppressionEnabled && !omitProcessSuppression(); -} - -bool WebContext::canEnableProcessSuppressionForGlobalChildProcesses() -{ - return (s_applicationIsOccluded || s_applicationWindowModificationsHaveStopped) && s_processSuppressionEnabledForAllContexts && !omitProcessSuppression(); -} - -void WebContext::processSuppressionEnabledChanged() -{ - updateProcessSuppressionStateOfChildProcesses(); - - if (processSuppressionIsEnabledForAnyContext()) - enableOcclusionNotifications(); - else - disableOcclusionNotifications(); - - bool newProcessSuppressionEnabledForAllContexts = processSuppressionIsEnabledForAllContexts(); - if (s_processSuppressionEnabledForAllContexts != newProcessSuppressionEnabledForAllContexts) { - s_processSuppressionEnabledForAllContexts = newProcessSuppressionEnabledForAllContexts; - updateProcessSuppressionStateOfGlobalChildProcesses(); - } -} - -void WebContext::registerNotificationObservers() -{ - m_customSchemeRegisteredObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKit::SchemeForCustomProtocolRegisteredNotificationName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - NSString *scheme = [notification object]; - ASSERT([scheme isKindOfClass:[NSString class]]); - registerSchemeForCustomProtocol(scheme); - }]; - - m_customSchemeUnregisteredObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKit::SchemeForCustomProtocolUnregisteredNotificationName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - NSString *scheme = [notification object]; - ASSERT([scheme isKindOfClass:[NSString class]]); - unregisterSchemeForCustomProtocol(scheme); - }]; - - // Listen for enhanced accessibility changes and propagate them to the WebProcess. - m_enhancedAccessibilityObserver = [[NSNotificationCenter defaultCenter] addObserverForName:WebKitApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { - setEnhancedAccessibility([[[note userInfo] objectForKey:@"AXEnhancedUserInterface"] boolValue]); - }]; - - m_automaticTextReplacementNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticTextReplacementNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - TextChecker::didChangeAutomaticTextReplacementEnabled(); - textCheckerStateChanged(); - }]; - - m_automaticSpellingCorrectionNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticSpellingCorrectionNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - TextChecker::didChangeAutomaticSpellingCorrectionEnabled(); - textCheckerStateChanged(); - }]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - m_automaticQuoteSubstitutionNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticQuoteSubstitutionNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - TextChecker::didChangeAutomaticQuoteSubstitutionEnabled(); - textCheckerStateChanged(); - }]; - - m_automaticDashSubstitutionNotificationObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSSpellCheckerDidChangeAutomaticDashSubstitutionNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *notification) { - TextChecker::didChangeAutomaticDashSubstitutionEnabled(); - textCheckerStateChanged(); - }]; -#endif -} - -void WebContext::unregisterNotificationObservers() -{ - [[NSNotificationCenter defaultCenter] removeObserver:m_customSchemeRegisteredObserver.get()]; - [[NSNotificationCenter defaultCenter] removeObserver:m_customSchemeUnregisteredObserver.get()]; - [[NSNotificationCenter defaultCenter] removeObserver:m_enhancedAccessibilityObserver.get()]; - - [[NSNotificationCenter defaultCenter] removeObserver:m_automaticTextReplacementNotificationObserver.get()]; - [[NSNotificationCenter defaultCenter] removeObserver:m_automaticSpellingCorrectionNotificationObserver.get()]; -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - [[NSNotificationCenter defaultCenter] removeObserver:m_automaticQuoteSubstitutionNotificationObserver.get()]; - [[NSNotificationCenter defaultCenter] removeObserver:m_automaticDashSubstitutionNotificationObserver.get()]; -#endif -} - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 -static CFURLStorageSessionRef privateBrowsingSession() -{ - static CFURLStorageSessionRef session; - static dispatch_once_t once; - dispatch_once(&once, ^{ - NSString *identifier = [NSString stringWithFormat:@"%@.PrivateBrowsing", [[NSBundle mainBundle] bundleIdentifier]]; - - session = WKCreatePrivateStorageSession((CFStringRef)identifier); - }); - - return session; -} -#endif - -bool WebContext::isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - RetainPtr<CFURLRef> url = KURL(KURL(), urlString).createCFURL(); - - return _CFNetworkIsKnownHSTSHostWithSession(url.get(), privateBrowsingEnabled ? privateBrowsingSession() : nullptr); -#else - return false; -#endif -} - -void WebContext::resetHSTSHosts() -{ -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - _CFNetworkResetHSTSHostsWithSession(nullptr); - _CFNetworkResetHSTSHostsWithSession(privateBrowsingSession()); -#endif -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm deleted file mode 100644 index a0e1c33af..000000000 --- a/Source/WebKit2/UIProcess/mac/WebContextMenuProxyMac.mm +++ /dev/null @@ -1,235 +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. - */ - -#import "config.h" -#import "WebContextMenuProxyMac.h" - -#import "PageClientImpl.h" -#import "StringUtilities.h" -#import "WebContextMenuItemData.h" -#import "WKView.h" - -#import <WebCore/IntRect.h> -#import <WebKitSystemInterface.h> - -using namespace WebCore; - -@interface WKUserDataWrapper : NSObject { - RefPtr<WebKit::APIObject> _webUserData; -} -- (id)initWithUserData:(WebKit::APIObject*)userData; -- (WebKit::APIObject*)userData; -@end - -@implementation WKUserDataWrapper - -- (id)initWithUserData:(WebKit::APIObject*)userData -{ - self = [super init]; - if (!self) - return nil; - - _webUserData = userData; - return self; -} - -- (WebKit::APIObject*)userData -{ - return _webUserData.get(); -} - -@end - -@interface WKMenuTarget : NSObject { - WebKit::WebContextMenuProxyMac* _menuProxy; -} -+ (WKMenuTarget*)sharedMenuTarget; -- (WebKit::WebContextMenuProxyMac*)menuProxy; -- (void)setMenuProxy:(WebKit::WebContextMenuProxyMac*)menuProxy; -- (void)forwardContextMenuAction:(id)sender; -@end - -@implementation WKMenuTarget - -+ (WKMenuTarget*)sharedMenuTarget -{ - static WKMenuTarget* target = [[WKMenuTarget alloc] init]; - return target; -} - -- (WebKit::WebContextMenuProxyMac*)menuProxy -{ - return _menuProxy; -} - -- (void)setMenuProxy:(WebKit::WebContextMenuProxyMac*)menuProxy -{ - _menuProxy = menuProxy; -} - -- (void)forwardContextMenuAction:(id)sender -{ - WebKit::WebContextMenuItemData item(ActionType, static_cast<ContextMenuAction>([sender tag]), [sender title], [sender isEnabled], [sender state] == NSOnState); - - if (id representedObject = [sender representedObject]) { - ASSERT([representedObject isKindOfClass:[WKUserDataWrapper class]]); - item.setUserData([static_cast<WKUserDataWrapper *>(representedObject) userData]); - } - - _menuProxy->contextMenuItemSelected(item); -} - -@end - -namespace WebKit { - -WebContextMenuProxyMac::WebContextMenuProxyMac(WKView* webView, WebPageProxy* page) - : m_webView(webView) - , m_page(page) -{ -} - -WebContextMenuProxyMac::~WebContextMenuProxyMac() -{ - if (m_popup) - [m_popup.get() setControlView:nil]; -} - -void WebContextMenuProxyMac::contextMenuItemSelected(const WebContextMenuItemData& item) -{ - m_page->contextMenuItemSelected(item); -} - -static void populateNSMenu(NSMenu* menu, const Vector<RetainPtr<NSMenuItem>>& menuItemVector) -{ - for (unsigned i = 0; i < menuItemVector.size(); ++i) { - NSInteger oldState = [menuItemVector[i].get() state]; - [menu addItem:menuItemVector[i].get()]; - [menuItemVector[i].get() setState:oldState]; - } -} - -static Vector<RetainPtr<NSMenuItem>> nsMenuItemVector(const Vector<WebContextMenuItemData>& items) -{ - Vector<RetainPtr<NSMenuItem>> result; - - unsigned size = items.size(); - result.reserveCapacity(size); - for (unsigned i = 0; i < size; i++) { - switch (items[i].type()) { - case ActionType: - case CheckableActionType: { - NSMenuItem* menuItem = [[NSMenuItem alloc] initWithTitle:nsStringFromWebCoreString(items[i].title()) action:@selector(forwardContextMenuAction:) keyEquivalent:@""]; - [menuItem setTag:items[i].action()]; - [menuItem setEnabled:items[i].enabled()]; - [menuItem setState:items[i].checked() ? NSOnState : NSOffState]; - - if (items[i].userData()) { - WKUserDataWrapper *wrapper = [[WKUserDataWrapper alloc] initWithUserData:items[i].userData()]; - [menuItem setRepresentedObject:wrapper]; - [wrapper release]; - } - - result.append(adoptNS(menuItem)); - break; - } - case SeparatorType: - result.append([NSMenuItem separatorItem]); - break; - case SubmenuType: { - NSMenu* menu = [[NSMenu alloc] initWithTitle:nsStringFromWebCoreString(items[i].title())]; - [menu setAutoenablesItems:NO]; - populateNSMenu(menu, nsMenuItemVector(items[i].submenu())); - - NSMenuItem* menuItem = [[NSMenuItem alloc] initWithTitle:nsStringFromWebCoreString(items[i].title()) action:@selector(forwardContextMenuAction:) keyEquivalent:@""]; - [menuItem setEnabled:items[i].enabled()]; - [menuItem setSubmenu:menu]; - [menu release]; - - result.append(adoptNS(menuItem)); - - break; - } - default: - ASSERT_NOT_REACHED(); - } - } - - WKMenuTarget* target = [WKMenuTarget sharedMenuTarget]; - for (unsigned i = 0; i < size; ++i) - [result[i].get() setTarget:target]; - - return result; -} - -void WebContextMenuProxyMac::populate(const Vector<WebContextMenuItemData>& items) -{ - if (m_popup) - [m_popup.get() removeAllItems]; - else { - m_popup = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]); - [m_popup.get() setUsesItemFromMenu:NO]; - [m_popup.get() setAutoenablesItems:NO]; - } - - NSMenu* menu = [m_popup.get() menu]; - populateNSMenu(menu, nsMenuItemVector(items)); -} - -void WebContextMenuProxyMac::showContextMenu(const IntPoint& menuLocation, const Vector<WebContextMenuItemData>& items) -{ - if (items.isEmpty()) - return; - - populate(items); - [[WKMenuTarget sharedMenuTarget] setMenuProxy:this]; - - NSRect menuRect = NSMakeRect(menuLocation.x(), menuLocation.y(), 0, 0); - - [m_popup.get() attachPopUpWithFrame:menuRect inView:m_webView]; - - NSMenu* menu = [m_popup.get() menu]; - - // These values were borrowed from AppKit to match their placement of the menu. - NSRect titleFrame = [m_popup.get() titleRectForBounds:menuRect]; - if (titleFrame.size.width <= 0 || titleFrame.size.height <= 0) - titleFrame = menuRect; - float vertOffset = roundf((NSMaxY(menuRect) - NSMaxY(titleFrame)) + NSHeight(titleFrame)); - NSPoint location = NSMakePoint(NSMinX(menuRect), NSMaxY(menuRect) - vertOffset); - - location = [m_webView convertPoint:location toView:nil]; - location = [m_webView.window convertBaseToScreen:location]; - - WKPopupContextMenu(menu, location); - - [m_popup.get() dismissPopUp]; -} - -void WebContextMenuProxyMac::hideContextMenu() -{ - [m_popup.get() dismissPopUp]; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebCookieManagerProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebCookieManagerProxyMac.mm deleted file mode 100644 index 6fd2f9a7b..000000000 --- a/Source/WebKit2/UIProcess/mac/WebCookieManagerProxyMac.mm +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2011, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WebCookieManagerProxy.h" - -namespace WebKit { - -void WebCookieManagerProxy::persistHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) -{ - // FIXME: The sandbox appears to prevent persisting the new policy to disk, so we must set the - // policy in the UI Process as well as in the Web Process (to make sure it gets set on any - // Private Browsing Cookie Storage). - [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:static_cast<NSHTTPCookieAcceptPolicy>(policy)]; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm deleted file mode 100644 index daabb8397..000000000 --- a/Source/WebKit2/UIProcess/mac/WebFullScreenManagerProxyMac.mm +++ /dev/null @@ -1,99 +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. - */ - -#import "config.h" -#import "WebFullScreenManagerProxy.h" - -#if ENABLE(FULLSCREEN_API) - -#import "LayerTreeContext.h" -#import "WKFullScreenWindowController.h" -#import "WKViewInternal.h" -#import "WebFullScreenManagerProxyMessages.h" -#import "WebPageProxy.h" -#import "WebProcessProxy.h" -#import <WebCore/IntRect.h> - -using namespace WebCore; - -namespace WebKit { - -void WebFullScreenManagerProxy::invalidate() -{ - m_page->process()->removeMessageReceiver(Messages::WebFullScreenManagerProxy::messageReceiverName(), m_page->pageID()); - - if (!m_webView) - return; - - [m_webView closeFullScreenWindowController]; - m_webView = 0; -} - -void WebFullScreenManagerProxy::close() -{ - if (!m_webView) - return; - [[m_webView fullScreenWindowController] close]; -} - -bool WebFullScreenManagerProxy::isFullScreen() -{ - if (!m_webView) - return false; - if (![m_webView hasFullScreenWindowController]) - return false; - - return [[m_webView fullScreenWindowController] isFullScreen]; -} - -void WebFullScreenManagerProxy::enterFullScreen() -{ - if (!m_webView) - return; - [[m_webView fullScreenWindowController] enterFullScreen:nil]; -} - -void WebFullScreenManagerProxy::exitFullScreen() -{ - if (!m_webView) - return; - [[m_webView fullScreenWindowController] exitFullScreen]; -} - -void WebFullScreenManagerProxy::beganEnterFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) -{ - if (m_webView) - [[m_webView fullScreenWindowController] beganEnterFullScreenWithInitialFrame:initialFrame finalFrame:finalFrame]; -} - -void WebFullScreenManagerProxy::beganExitFullScreen(const IntRect& initialFrame, const IntRect& finalFrame) -{ - if (m_webView) - [[m_webView fullScreenWindowController] beganExitFullScreenWithInitialFrame:initialFrame finalFrame:finalFrame]; -} - -} // namespace WebKit - -#endif diff --git a/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm deleted file mode 100644 index 69883621e..000000000 --- a/Source/WebKit2/UIProcess/mac/WebInspectorProxyMac.mm +++ /dev/null @@ -1,784 +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. - */ - -#import "config.h" -#import "WebInspectorProxy.h" - -#if ENABLE(INSPECTOR) - -#import "WKAPICast.h" -#import "WebContext.h" -#import "WKInspectorPrivateMac.h" -#import "WKMutableArray.h" -#import "WKOpenPanelParameters.h" -#import "WKOpenPanelResultListener.h" -#import "WKRetainPtr.h" -#import "WKURLCF.h" -#import "WKViewPrivate.h" -#import "WebInspectorMessages.h" -#import "WebPageGroup.h" -#import "WebPageProxy.h" -#import "WebPreferences.h" -#import "WebProcessProxy.h" -#import <algorithm> -#import <mach-o/dyld.h> -#import <WebKitSystemInterface.h> -#import <WebCore/InspectorFrontendClientLocal.h> -#import <WebCore/LocalizedStrings.h> -#import <WebCore/SoftLinking.h> -#import <wtf/text/WTFString.h> - -SOFT_LINK_STAGED_FRAMEWORK(WebInspectorUI, PrivateFrameworks, A) - -using namespace WebCore; -using namespace WebKit; - -// The height needed to match a typical NSToolbar. -static const CGFloat windowContentBorderThickness = 55; - -// The margin from the top and right of the dock button (same as the full screen button). -static const CGFloat dockButtonMargin = 3; - -// The spacing between the dock buttons. -static const CGFloat dockButtonSpacing = dockButtonMargin * 2; - -static const NSUInteger windowStyleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask | NSTexturedBackgroundWindowMask; - -// WKWebInspectorProxyObjCAdapter is a helper ObjC object used as a delegate or notification observer -// for the sole purpose of getting back into the C++ code from an ObjC caller. - -@interface WKWebInspectorProxyObjCAdapter () - -- (id)initWithWebInspectorProxy:(WebInspectorProxy*)inspectorProxy; -- (void)close; - -@end - -@implementation WKWebInspectorProxyObjCAdapter - -- (WKInspectorRef)inspectorRef -{ - return toAPI(static_cast<WebInspectorProxy*>(_inspectorProxy)); -} - -- (id)initWithWebInspectorProxy:(WebInspectorProxy*)inspectorProxy -{ - ASSERT_ARG(inspectorProxy, inspectorProxy); - - if (!(self = [super init])) - return nil; - - _inspectorProxy = static_cast<void*>(inspectorProxy); // Not retained to prevent cycles - - return self; -} - -- (IBAction)attachRight:(id)sender -{ - static_cast<WebInspectorProxy*>(_inspectorProxy)->attach(AttachmentSideRight); -} - -- (IBAction)attachBottom:(id)sender -{ - static_cast<WebInspectorProxy*>(_inspectorProxy)->attach(AttachmentSideBottom); -} - -- (void)close -{ - _inspectorProxy = 0; -} - -- (void)windowDidMove:(NSNotification *)notification -{ - static_cast<WebInspectorProxy*>(_inspectorProxy)->windowFrameDidChange(); -} - -- (void)windowDidResize:(NSNotification *)notification -{ - static_cast<WebInspectorProxy*>(_inspectorProxy)->windowFrameDidChange(); -} - -- (void)windowWillClose:(NSNotification *)notification -{ - static_cast<WebInspectorProxy*>(_inspectorProxy)->close(); -} - -- (void)inspectedViewFrameDidChange:(NSNotification *)notification -{ - // Resizing the views while inside this notification can lead to bad results when entering - // or exiting full screen. To avoid that we need to perform the work after a delay. We only - // depend on this for enforcing the height constraints, so a small delay isn't terrible. Most - // of the time the views will already have the correct frames because of autoresizing masks. - - dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^{ - if (!_inspectorProxy) - return; - static_cast<WebInspectorProxy*>(_inspectorProxy)->inspectedViewFrameDidChange(); - }); -} - -@end - -@interface WKWebInspectorWKView : WKView -@end - -@implementation WKWebInspectorWKView - -- (NSInteger)tag -{ - return WKInspectorViewTag; -} - -@end - -@interface NSWindow (AppKitDetails) -- (NSCursor *)_cursorForResizeDirection:(NSInteger)direction; -- (NSRect)_customTitleFrame; -@end - -@interface WKWebInspectorWindow : NSWindow { -@public - RetainPtr<NSButton> _dockBottomButton; - RetainPtr<NSButton> _dockRightButton; -} -@end - -@implementation WKWebInspectorWindow - -- (NSCursor *)_cursorForResizeDirection:(NSInteger)direction -{ - // Don't show a resize cursor for the northeast (top right) direction if the dock button is visible. - // This matches what happens when the full screen button is visible. - if (direction == 1 && ![_dockRightButton isHidden]) - return nil; - return [super _cursorForResizeDirection:direction]; -} - -- (NSRect)_customTitleFrame -{ - // Adjust the title frame if needed to prevent it from intersecting the dock button. - NSRect titleFrame = [super _customTitleFrame]; - NSRect dockButtonFrame = _dockBottomButton.get().frame; - if (NSMaxX(titleFrame) > NSMinX(dockButtonFrame) - dockButtonMargin) - titleFrame.size.width -= (NSMaxX(titleFrame) - NSMinX(dockButtonFrame)) + dockButtonMargin; - return titleFrame; -} - -@end - -namespace WebKit { - -static bool inspectorReallyUsesWebKitUserInterface(WebPreferences* preferences) -{ - // This matches a similar check in WebInspectorMac.mm. Keep them in sync. - - // Call the soft link framework function to dlopen it, then [NSBundle bundleWithIdentifier:] will work. - WebInspectorUILibrary(); - - if (![[NSBundle bundleWithIdentifier:@"com.apple.WebInspectorUI"] pathForResource:@"Main" ofType:@"html"]) - return true; - - if (![[NSBundle bundleWithIdentifier:@"com.apple.WebCore"] pathForResource:@"inspector" ofType:@"html" inDirectory:@"inspector"]) - return false; - - return preferences->inspectorUsesWebKitUserInterface(); -} - -static WKRect getWindowFrame(WKPageRef, const void* clientInfo) -{ - WebInspectorProxy* webInspectorProxy = static_cast<WebInspectorProxy*>(const_cast<void*>(clientInfo)); - ASSERT(webInspectorProxy); - - return webInspectorProxy->inspectorWindowFrame(); -} - -static void setWindowFrame(WKPageRef, WKRect frame, const void* clientInfo) -{ - WebInspectorProxy* webInspectorProxy = static_cast<WebInspectorProxy*>(const_cast<void*>(clientInfo)); - ASSERT(webInspectorProxy); - - webInspectorProxy->setInspectorWindowFrame(frame); -} - -static unsigned long long exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef, WKStringRef, unsigned long long, unsigned long long, unsigned long long currentDatabaseUsage, unsigned long long expectedUsage, const void*) -{ - return std::max<unsigned long long>(expectedUsage, currentDatabaseUsage * 1.25); -} - -static void runOpenPanel(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef listener, const void* clientInfo) -{ - WebInspectorProxy* webInspectorProxy = static_cast<WebInspectorProxy*>(const_cast<void*>(clientInfo)); - ASSERT(webInspectorProxy); - - NSOpenPanel *openPanel = [NSOpenPanel openPanel]; - [openPanel setAllowsMultipleSelection:WKOpenPanelParametersGetAllowsMultipleFiles(parameters)]; - - WKRetain(listener); - - // If the inspector is detached, then openPanel will be window-modal; otherwise, openPanel is opened in a new window. - [openPanel beginSheetModalForWindow:webInspectorProxy->inspectorWindow() completionHandler:^(NSInteger result) { - if (result == NSFileHandlingPanelOKButton) { - WKMutableArrayRef fileURLs = WKMutableArrayCreate(); - - for (NSURL* nsURL in [openPanel URLs]) { - WKURLRef wkURL = WKURLCreateWithCFURL(reinterpret_cast<CFURLRef>(nsURL)); - WKArrayAppendItem(fileURLs, wkURL); - WKRelease(wkURL); - } - - WKOpenPanelResultListenerChooseFiles(listener, fileURLs); - - WKRelease(fileURLs); - } else - WKOpenPanelResultListenerCancel(listener); - - WKRelease(listener); - }]; -} - -void WebInspectorProxy::setInspectorWindowFrame(WKRect& frame) -{ - if (m_isAttached) - return; - [m_inspectorWindow setFrame:NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height) display:YES]; -} - -WKRect WebInspectorProxy::inspectorWindowFrame() -{ - if (m_isAttached) - return WKRectMake(0, 0, 0, 0); - - NSRect frame = m_inspectorWindow.get().frame; - return WKRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height); -} - -static NSButton *createDockButton(NSString *imageName) -{ - // Create a full screen button so we can turn it into a dock button. - NSButton *dockButton = [NSWindow standardWindowButton:NSWindowFullScreenButton forStyleMask:windowStyleMask]; - - // Set the autoresizing mask to keep the dock button pinned to the top right corner. - dockButton.autoresizingMask = NSViewMinXMargin | NSViewMinYMargin; - - // Get the dock image and make it a template so the button cell effects will apply. - NSImage *dockImage = [[NSBundle bundleForClass:[WKWebInspectorWKView class]] imageForResource:imageName]; - [dockImage setTemplate:YES]; - - // Set the dock image on the button cell. - NSCell *dockButtonCell = dockButton.cell; - dockButtonCell.image = dockImage; - - return [dockButton retain]; -} - -void WebInspectorProxy::createInspectorWindow() -{ - ASSERT(!m_inspectorWindow); - - NSRect windowFrame = NSMakeRect(0, 0, initialWindowWidth, initialWindowHeight); - - // Restore the saved window frame, if there was one. - NSString *savedWindowFrameString = page()->pageGroup()->preferences()->inspectorWindowFrame(); - NSRect savedWindowFrame = NSRectFromString(savedWindowFrameString); - if (!NSIsEmptyRect(savedWindowFrame)) - windowFrame = savedWindowFrame; - - WKWebInspectorWindow *window = [[WKWebInspectorWindow alloc] initWithContentRect:windowFrame styleMask:windowStyleMask backing:NSBackingStoreBuffered defer:NO]; - [window setDelegate:m_inspectorProxyObjCAdapter.get()]; - [window setMinSize:NSMakeSize(minimumWindowWidth, minimumWindowHeight)]; - [window setReleasedWhenClosed:NO]; - [window setAutorecalculatesContentBorderThickness:NO forEdge:NSMaxYEdge]; - [window setContentBorderThickness:windowContentBorderThickness forEdge:NSMaxYEdge]; - WKNSWindowMakeBottomCornersSquare(window); - - m_inspectorWindow = adoptNS(window); - - NSView *contentView = [window contentView]; - - static const int32_t firstVersionOfSafariWithDockToRightSupport = 0x02181d0d; // 536.29.13 - static bool supportsDockToRight = NSVersionOfLinkTimeLibrary("Safari") >= firstVersionOfSafariWithDockToRightSupport; - - m_dockBottomButton = adoptNS(createDockButton(@"DockBottom")); - m_dockRightButton = adoptNS(createDockButton(@"DockRight")); - - m_dockBottomButton.get().target = m_inspectorProxyObjCAdapter.get(); - m_dockBottomButton.get().action = @selector(attachBottom:); - - m_dockRightButton.get().target = m_inspectorProxyObjCAdapter.get(); - m_dockRightButton.get().action = @selector(attachRight:); - m_dockRightButton.get().enabled = supportsDockToRight; - m_dockRightButton.get().alphaValue = supportsDockToRight ? 1 : 0.5; - - // Store the dock buttons on the window too so it can check its visibility. - window->_dockBottomButton = m_dockBottomButton; - window->_dockRightButton = m_dockRightButton; - - // Get the frame view, the superview of the content view, and its frame. - // This will be the superview of the dock button too. - NSView *frameView = contentView.superview; - NSRect frameViewBounds = frameView.bounds; - NSSize dockButtonSize = m_dockBottomButton.get().frame.size; - - ASSERT(!frameView.isFlipped); - - // Position the dock button in the corner to match where the full screen button is normally. - NSPoint dockButtonOrigin; - dockButtonOrigin.x = NSMaxX(frameViewBounds) - dockButtonSize.width - dockButtonMargin; - dockButtonOrigin.y = NSMaxY(frameViewBounds) - dockButtonSize.height - dockButtonMargin; - m_dockRightButton.get().frameOrigin = dockButtonOrigin; - - dockButtonOrigin.x -= dockButtonSize.width + dockButtonSpacing; - m_dockBottomButton.get().frameOrigin = dockButtonOrigin; - - [frameView addSubview:m_dockBottomButton.get()]; - [frameView addSubview:m_dockRightButton.get()]; - - // Hide the dock buttons if we can't attach. - m_dockBottomButton.get().hidden = !canAttach(); - m_dockRightButton.get().hidden = !canAttach(); - - [m_inspectorView.get() setFrame:[contentView bounds]]; - [m_inspectorView.get() setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; - [contentView addSubview:m_inspectorView.get()]; - - // Center the window if the saved frame was empty. - if (NSIsEmptyRect(savedWindowFrame)) - [window center]; - - updateInspectorWindowTitle(); -} - -void WebInspectorProxy::updateInspectorWindowTitle() const -{ - if (!m_inspectorWindow) - return; - - NSString *title = [NSString stringWithFormat:WEB_UI_STRING("Web Inspector — %@", "Web Inspector window title"), (NSString *)m_urlString]; - [m_inspectorWindow.get() setTitle:title]; -} - -WebPageProxy* WebInspectorProxy::platformCreateInspectorPage() -{ - ASSERT(m_page); - ASSERT(!m_inspectorView); - - NSRect initialRect; - if (m_isAttached) { - NSRect inspectedViewFrame = m_page->wkView().frame; - - switch (m_attachmentSide) { - case AttachmentSideBottom: - initialRect = NSMakeRect(0, 0, NSWidth(inspectedViewFrame), inspectorPageGroup()->preferences()->inspectorAttachedHeight()); - break; - case AttachmentSideRight: - initialRect = NSMakeRect(0, 0, inspectorPageGroup()->preferences()->inspectorAttachedWidth(), NSHeight(inspectedViewFrame)); - break; - } - } else { - initialRect = NSMakeRect(0, 0, initialWindowWidth, initialWindowHeight); - - NSString *windowFrameString = page()->pageGroup()->preferences()->inspectorWindowFrame(); - NSRect windowFrame = NSRectFromString(windowFrameString); - if (!NSIsEmptyRect(windowFrame)) - initialRect = [NSWindow contentRectForFrameRect:windowFrame styleMask:windowStyleMask]; - } - - m_inspectorView = adoptNS([[WKWebInspectorWKView alloc] initWithFrame:initialRect contextRef:toAPI(page()->process()->context()) pageGroupRef:toAPI(inspectorPageGroup()) relatedToPage:toAPI(m_page)]); - ASSERT(m_inspectorView); - - [m_inspectorView.get() setDrawsBackground:NO]; - - m_inspectorProxyObjCAdapter = adoptNS([[WKWebInspectorProxyObjCAdapter alloc] initWithWebInspectorProxy:this]); - - WebPageProxy* inspectorPage = toImpl(m_inspectorView.get().pageRef); - - WKPageUIClient uiClient = { - kWKPageUIClientCurrentVersion, - this, /* clientInfo */ - 0, // createNewPage_deprecatedForUseWithV0 - 0, // showPage - 0, // closePage - 0, // takeFocus - 0, // focus - 0, // unfocus - 0, // runJavaScriptAlert - 0, // runJavaScriptConfirm - 0, // runJavaScriptPrompt - 0, // setStatusText - 0, // mouseDidMoveOverElement_deprecatedForUseWithV0 - 0, // missingPluginButtonClicked_deprecatedForUseWithV0 - 0, // didNotHandleKeyEvent - 0, // didNotHandleWheelEvent - 0, // areToolbarsVisible - 0, // setToolbarsVisible - 0, // isMenuBarVisible - 0, // setMenuBarVisible - 0, // isStatusBarVisible - 0, // setStatusBarVisible - 0, // isResizable - 0, // setResizable - getWindowFrame, - setWindowFrame, - 0, // runBeforeUnloadConfirmPanel - 0, // didDraw - 0, // pageDidScroll - exceededDatabaseQuota, - runOpenPanel, - 0, // decidePolicyForGeolocationPermissionRequest - 0, // headerHeight - 0, // footerHeight - 0, // drawHeader - 0, // drawFooter - 0, // printFrame - 0, // runModal - 0, // unused - 0, // saveDataToFileInDownloadsFolder - 0, // shouldInterruptJavaScript - 0, // createPage - 0, // mouseDidMoveOverElement - 0, // decidePolicyForNotificationPermissionRequest - 0, // unavailablePluginButtonClicked_deprecatedForUseWithV1 - 0, // showColorPicker - 0, // hideColorPicker - 0, // unavailablePluginButtonClicked - }; - - inspectorPage->initializeUIClient(&uiClient); - - return inspectorPage; -} - -void WebInspectorProxy::platformOpen() -{ - if (m_isAttached) - platformAttach(); - else - createInspectorWindow(); - - platformBringToFront(); -} - -void WebInspectorProxy::platformDidClose() -{ - if (m_inspectorWindow) { - [m_inspectorWindow.get() setDelegate:nil]; - [m_inspectorWindow.get() orderOut:nil]; - m_inspectorWindow = 0; - } - - m_inspectorView = 0; - - [m_inspectorProxyObjCAdapter.get() close]; - m_inspectorProxyObjCAdapter = 0; -} - -void WebInspectorProxy::platformHide() -{ - if (m_isAttached) { - platformDetach(); - return; - } - - if (m_inspectorWindow) { - [m_inspectorWindow.get() setDelegate:nil]; - [m_inspectorWindow.get() orderOut:nil]; - m_inspectorWindow = 0; - } -} - -void WebInspectorProxy::platformBringToFront() -{ - // If the Web Inspector is no longer in the same window as the inspected view, - // then we need to reopen the Inspector to get it attached to the right window. - // This can happen when dragging tabs to another window in Safari. - if (m_isAttached && m_inspectorView.get().window != m_page->wkView().window) { - platformOpen(); - return; - } - - // FIXME <rdar://problem/10937688>: this will not bring a background tab in Safari to the front, only its window. - [m_inspectorView.get().window makeKeyAndOrderFront:nil]; - [m_inspectorView.get().window makeFirstResponder:m_inspectorView.get()]; -} - -bool WebInspectorProxy::platformIsFront() -{ - // FIXME <rdar://problem/10937688>: this will not return false for a background tab in Safari, only a background window. - return m_isVisible && [m_inspectorView.get().window isMainWindow]; -} - -void WebInspectorProxy::platformAttachAvailabilityChanged(bool available) -{ - m_dockBottomButton.get().hidden = !available; - m_dockRightButton.get().hidden = !available; -} - -void WebInspectorProxy::platformInspectedURLChanged(const String& urlString) -{ - m_urlString = urlString; - - updateInspectorWindowTitle(); -} - -void WebInspectorProxy::platformSave(const String& suggestedURL, const String& content, bool forceSaveDialog) -{ - ASSERT(!suggestedURL.isEmpty()); - - NSURL *platformURL = m_suggestedToActualURLMap.get(suggestedURL).get(); - if (!platformURL) { - platformURL = [NSURL URLWithString:suggestedURL]; - // The user must confirm new filenames before we can save to them. - forceSaveDialog = true; - } - - ASSERT(platformURL); - if (!platformURL) - return; - - // Necessary for the block below. - String suggestedURLCopy = suggestedURL; - String contentCopy = content; - - auto saveToURL = ^(NSURL *actualURL) { - ASSERT(actualURL); - - m_suggestedToActualURLMap.set(suggestedURLCopy, actualURL); - [contentCopy writeToURL:actualURL atomically:YES encoding:NSUTF8StringEncoding error:NULL]; - m_page->process()->send(Messages::WebInspector::DidSave([actualURL absoluteString]), m_page->pageID()); - }; - - if (!forceSaveDialog) { - saveToURL(platformURL); - return; - } - - NSSavePanel *panel = [NSSavePanel savePanel]; - panel.nameFieldStringValue = platformURL.lastPathComponent; - panel.directoryURL = [platformURL URLByDeletingLastPathComponent]; - - [panel beginSheetModalForWindow:m_inspectorWindow.get() completionHandler:^(NSInteger result) { - if (result == NSFileHandlingPanelCancelButton) - return; - ASSERT(result == NSFileHandlingPanelOKButton); - saveToURL(panel.URL); - }]; -} - -void WebInspectorProxy::platformAppend(const String& suggestedURL, const String& content) -{ - ASSERT(!suggestedURL.isEmpty()); - - RetainPtr<NSURL> actualURL = m_suggestedToActualURLMap.get(suggestedURL); - // Do not append unless the user has already confirmed this filename in save(). - if (!actualURL) - return; - - NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:actualURL.get() error:NULL]; - [handle seekToEndOfFile]; - [handle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]]; - [handle closeFile]; - - m_page->process()->send(Messages::WebInspector::DidAppend([actualURL absoluteString]), m_page->pageID()); -} - -void WebInspectorProxy::windowFrameDidChange() -{ - ASSERT(!m_isAttached); - ASSERT(m_isVisible); - ASSERT(m_inspectorWindow); - - if (m_isAttached || !m_isVisible || !m_inspectorWindow) - return; - - NSString *frameString = NSStringFromRect([m_inspectorWindow frame]); - page()->pageGroup()->preferences()->setInspectorWindowFrame(frameString); -} - -void WebInspectorProxy::inspectedViewFrameDidChange(CGFloat currentDimension) -{ - if (!m_isAttached || !m_isVisible) - return; - - WKView *inspectedView = m_page->wkView(); - NSRect inspectedViewFrame = [inspectedView frame]; - NSRect inspectorFrame = NSZeroRect; - NSRect parentBounds = [[inspectedView superview] bounds]; - CGFloat inspectedViewTop = NSMaxY(inspectedViewFrame); - - switch (m_attachmentSide) { - case AttachmentSideBottom: { - if (!currentDimension) - currentDimension = NSHeight([m_inspectorView.get() frame]); - - CGFloat parentHeight = NSHeight(parentBounds); - CGFloat inspectorHeight = InspectorFrontendClientLocal::constrainedAttachedWindowHeight(currentDimension, parentHeight); - - // Preserve the top position of the inspected view so banners in Safari still work. - inspectedViewFrame = NSMakeRect(0, inspectorHeight, NSWidth(parentBounds), inspectedViewTop - inspectorHeight); - inspectorFrame = NSMakeRect(0, 0, NSWidth(inspectedViewFrame), inspectorHeight); - break; - } - - case AttachmentSideRight: { - if (!currentDimension) - currentDimension = NSWidth([m_inspectorView.get() frame]); - - CGFloat parentWidth = NSWidth(parentBounds); - CGFloat inspectorWidth = InspectorFrontendClientLocal::constrainedAttachedWindowWidth(currentDimension, parentWidth); - - // Preserve the top position of the inspected view so banners in Safari still work. But don't use that - // top position for the inspector view since the banners only stretch as wide as the the inspected view. - inspectedViewFrame = NSMakeRect(0, 0, parentWidth - inspectorWidth, inspectedViewTop); - inspectorFrame = NSMakeRect(parentWidth - inspectorWidth, 0, inspectorWidth, NSHeight(parentBounds)); - break; - } - } - - // Disable screen updates to make sure the layers for both views resize in sync. - [[m_inspectorView window] disableScreenUpdatesUntilFlush]; - - [m_inspectorView setFrame:inspectorFrame]; - [inspectedView setFrame:inspectedViewFrame]; -} - -unsigned WebInspectorProxy::platformInspectedWindowHeight() -{ - WKView *inspectedView = m_page->wkView(); - NSRect inspectedViewRect = [inspectedView frame]; - return static_cast<unsigned>(inspectedViewRect.size.height); -} - -unsigned WebInspectorProxy::platformInspectedWindowWidth() -{ - WKView *inspectedView = m_page->wkView(); - NSRect inspectedViewRect = [inspectedView frame]; - return static_cast<unsigned>(inspectedViewRect.size.width); -} - -void WebInspectorProxy::platformAttach() -{ - WKView *inspectedView = m_page->wkView(); - [[NSNotificationCenter defaultCenter] addObserver:m_inspectorProxyObjCAdapter.get() selector:@selector(inspectedViewFrameDidChange:) name:NSViewFrameDidChangeNotification object:inspectedView]; - - if (m_inspectorWindow) { - [m_inspectorWindow.get() setDelegate:nil]; - [m_inspectorWindow.get() orderOut:nil]; - m_inspectorWindow = 0; - } - - [m_inspectorView.get() removeFromSuperview]; - - [m_inspectorView.get() setAutoresizingMask:NSViewWidthSizable | NSViewMaxYMargin]; - - CGFloat currentDimension; - - switch (m_attachmentSide) { - case AttachmentSideBottom: - currentDimension = inspectorPageGroup()->preferences()->inspectorAttachedHeight(); - break; - case AttachmentSideRight: - currentDimension = inspectorPageGroup()->preferences()->inspectorAttachedWidth(); - break; - } - - inspectedViewFrameDidChange(currentDimension); - - [[inspectedView superview] addSubview:m_inspectorView.get() positioned:NSWindowBelow relativeTo:inspectedView]; - - [[inspectedView window] makeFirstResponder:m_inspectorView.get()]; -} - -void WebInspectorProxy::platformDetach() -{ - WKView *inspectedView = m_page->wkView(); - [[NSNotificationCenter defaultCenter] removeObserver:m_inspectorProxyObjCAdapter.get() name:NSViewFrameDidChangeNotification object:inspectedView]; - - [m_inspectorView.get() removeFromSuperview]; - - // Make sure that we size the inspected view's frame after detaching so that it takes up the space that the - // attached inspector used to. Preserve the top position of the inspected view so banners in Safari still work. - - inspectedView.frame = NSMakeRect(0, 0, NSWidth(inspectedView.superview.bounds), NSMaxY(inspectedView.frame)); - - // Return early if we are not visible. This means the inspector was closed while attached - // and we should not create and show the inspector window. - if (!m_isVisible) - return; - - createInspectorWindow(); - - platformBringToFront(); -} - -void WebInspectorProxy::platformSetAttachedWindowHeight(unsigned height) -{ - if (!m_isAttached) - return; - - inspectedViewFrameDidChange(height); -} - -void WebInspectorProxy::platformSetAttachedWindowWidth(unsigned width) -{ - if (!m_isAttached) - return; - - inspectedViewFrameDidChange(width); -} - -void WebInspectorProxy::platformSetToolbarHeight(unsigned height) -{ - [m_inspectorWindow setContentBorderThickness:height forEdge:NSMaxYEdge]; -} - -String WebInspectorProxy::inspectorPageURL() const -{ - NSString *path; - if (inspectorReallyUsesWebKitUserInterface(page()->pageGroup()->preferences())) - path = [[NSBundle bundleWithIdentifier:@"com.apple.WebCore"] pathForResource:@"inspector" ofType:@"html" inDirectory:@"inspector"]; - else - path = [[NSBundle bundleWithIdentifier:@"com.apple.WebInspectorUI"] pathForResource:@"Main" ofType:@"html"]; - - ASSERT([path length]); - - return [[NSURL fileURLWithPath:path] absoluteString]; -} - -String WebInspectorProxy::inspectorBaseURL() const -{ - NSString *path; - if (inspectorReallyUsesWebKitUserInterface(page()->pageGroup()->preferences())) - path = [[NSBundle bundleWithIdentifier:@"com.apple.WebCore"] resourcePath]; - else - path = [[NSBundle bundleWithIdentifier:@"com.apple.WebInspectorUI"] resourcePath]; - - ASSERT([path length]); - - return [[NSURL fileURLWithPath:path] absoluteString]; -} - -} // namespace WebKit - -#endif // ENABLE(INSPECTOR) diff --git a/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm deleted file mode 100644 index c7f96a5ac..000000000 --- a/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WebPageProxy.h" - -#import "AttributedString.h" -#import "ColorSpaceData.h" -#import "DataReference.h" -#import "DictionaryPopupInfo.h" -#import "EditorState.h" -#import "NativeWebKeyboardEvent.h" -#import "PluginComplexTextInputState.h" -#import "PageClient.h" -#import "PageClientImpl.h" -#import "StringUtilities.h" -#import "TextChecker.h" -#import "WebPageMessages.h" -#import "WebProcessProxy.h" -#import <WebCore/DictationAlternative.h> -#import <WebCore/GraphicsLayer.h> -#import <WebCore/SharedBuffer.h> -#import <WebCore/SystemVersionMac.h> -#import <WebCore/TextAlternativeWithRange.h> -#import <WebKitSystemInterface.h> -#import <wtf/text/StringConcatenate.h> - -@interface NSApplication (Details) -- (void)speakString:(NSString *)string; -@end - -#define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, process()->connection()) - -using namespace WebCore; - -namespace WebKit { - -#if defined(__ppc__) || defined(__ppc64__) -#define PROCESSOR "PPC" -#elif defined(__i386__) || defined(__x86_64__) -#define PROCESSOR "Intel" -#else -#error Unknown architecture -#endif - -static NSString *systemMarketingVersionForUserAgentString() -{ - // Use underscores instead of dots because when we first added the Mac OS X version to the user agent string - // we were concerned about old DHTML libraries interpreting "4." as Netscape 4. That's no longer a concern for us - // but we're sticking with the underscores for compatibility with the format used by older versions of Safari. - return [systemMarketingVersion() stringByReplacingOccurrencesOfString:@"." withString:@"_"]; -} - -static String userVisibleWebKitVersionString() -{ - // If the version is 4 digits long or longer, then the first digit represents - // the version of the OS. Our user agent string should not include this first digit, - // so strip it off and report the rest as the version. <rdar://problem/4997547> - NSString *fullVersion = [[NSBundle bundleForClass:NSClassFromString(@"WKView")] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]; - NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]; - if (nonDigitRange.location == NSNotFound && [fullVersion length] >= 4) - return [fullVersion substringFromIndex:1]; - if (nonDigitRange.location != NSNotFound && nonDigitRange.location >= 4) - return [fullVersion substringFromIndex:1]; - return fullVersion; -} - -String WebPageProxy::standardUserAgent(const String& applicationNameForUserAgent) -{ - DEFINE_STATIC_LOCAL(String, osVersion, (systemMarketingVersionForUserAgentString())); - DEFINE_STATIC_LOCAL(String, webKitVersion, (userVisibleWebKitVersionString())); - - if (applicationNameForUserAgent.isEmpty()) - return makeString("Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X ", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko)"); - return makeString("Mozilla/5.0 (Macintosh; " PROCESSOR " Mac OS X ", osVersion, ") AppleWebKit/", webKitVersion, " (KHTML, like Gecko) ", applicationNameForUserAgent); -} - -void WebPageProxy::getIsSpeaking(bool& isSpeaking) -{ - isSpeaking = [NSApp isSpeaking]; -} - -void WebPageProxy::speak(const String& string) -{ - [NSApp speakString:nsStringFromWebCoreString(string)]; -} - -void WebPageProxy::stopSpeaking() -{ - [NSApp stopSpeaking:nil]; -} - -void WebPageProxy::searchWithSpotlight(const String& string) -{ - [[NSWorkspace sharedWorkspace] showSearchResultsForQueryString:nsStringFromWebCoreString(string)]; -} - -void WebPageProxy::searchTheWeb(const String& string) -{ - NSPasteboard *pasteboard = [NSPasteboard pasteboardWithUniqueName]; - [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil]; - [pasteboard setString:string forType:NSStringPboardType]; - - NSPerformService(@"Search With %WebSearchProvider@", pasteboard); -} - -CGContextRef WebPageProxy::containingWindowGraphicsContext() -{ - return m_pageClient->containingWindowGraphicsContext(); -} - -void WebPageProxy::updateWindowIsVisible(bool windowIsVisible) -{ - if (!isValid()) - return; - process()->send(Messages::WebPage::SetWindowIsVisible(windowIsVisible), m_pageID); -} - -void WebPageProxy::windowAndViewFramesChanged(const FloatRect& viewFrameInWindowCoordinates, const FloatPoint& accessibilityViewCoordinates) -{ - if (!isValid()) - return; - - // In case the UI client overrides getWindowFrame(), we call it here to make sure we send the appropriate window frame. - FloatRect windowFrameInScreenCoordinates = m_uiClient.windowFrame(this); - FloatRect windowFrameInUnflippedScreenCoordinates = m_pageClient->convertToUserSpace(windowFrameInScreenCoordinates); - - process()->send(Messages::WebPage::WindowAndViewFramesChanged(windowFrameInScreenCoordinates, windowFrameInUnflippedScreenCoordinates, viewFrameInWindowCoordinates, accessibilityViewCoordinates), m_pageID); -} - -void WebPageProxy::viewExposedRectChanged(const FloatRect& exposedRect, bool clipsToExposedRect) -{ - if (!isValid()) - return; - - m_exposedRect = exposedRect; - m_clipsToExposedRect = clipsToExposedRect; - - if (!m_exposedRectChangedTimer.isActive()) - m_exposedRectChangedTimer.startOneShot(0); -} - -void WebPageProxy::exposedRectChangedTimerFired(Timer<WebPageProxy>*) -{ - if (!isValid()) - return; - - if (m_exposedRect == m_lastSentExposedRect && m_clipsToExposedRect == m_lastSentClipsToExposedRect) - return; - - process()->send(Messages::WebPage::ViewExposedRectChanged(m_exposedRect, m_clipsToExposedRect), m_pageID); - m_lastSentExposedRect = m_exposedRect; - m_lastSentClipsToExposedRect = m_clipsToExposedRect; -} - -void WebPageProxy::setMainFrameIsScrollable(bool isScrollable) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::SetMainFrameIsScrollable(isScrollable), m_pageID); -} - -void WebPageProxy::setComposition(const String& text, Vector<CompositionUnderline> underlines, uint64_t selectionStart, uint64_t selectionEnd, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) -{ - if (!isValid()) { - // If this fails, we should call -discardMarkedText on input context to notify the input method. - // This will happen naturally later, as part of reloading the page. - return; - } - - process()->sendSync(Messages::WebPage::SetComposition(text, underlines, selectionStart, selectionEnd, replacementRangeStart, replacementRangeEnd), Messages::WebPage::SetComposition::Reply(m_editorState), m_pageID); -} - -void WebPageProxy::confirmComposition() -{ - if (!isValid()) - return; - - process()->sendSync(Messages::WebPage::ConfirmComposition(), Messages::WebPage::ConfirmComposition::Reply(m_editorState), m_pageID); -} - -void WebPageProxy::cancelComposition() -{ - if (!isValid()) - return; - - process()->sendSync(Messages::WebPage::CancelComposition(), Messages::WebPage::ConfirmComposition::Reply(m_editorState), m_pageID); -} - -bool WebPageProxy::insertText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd) -{ - if (!isValid()) - return true; - - bool handled = true; - process()->sendSync(Messages::WebPage::InsertText(text, replacementRangeStart, replacementRangeEnd), Messages::WebPage::InsertText::Reply(handled, m_editorState), m_pageID); - m_temporarilyClosedComposition = false; - - return handled; -} - -bool WebPageProxy::insertDictatedText(const String& text, uint64_t replacementRangeStart, uint64_t replacementRangeEnd, const Vector<TextAlternativeWithRange>& dictationAlternativesWithRange) -{ -#if USE(DICTATION_ALTERNATIVES) - if (dictationAlternativesWithRange.isEmpty()) - return insertText(text, replacementRangeStart, replacementRangeEnd); - - if (!isValid()) - return true; - - Vector<DictationAlternative> dictationAlternatives; - - for (size_t i = 0; i < dictationAlternativesWithRange.size(); ++i) { - const TextAlternativeWithRange& alternativeWithRange = dictationAlternativesWithRange[i]; - uint64_t dictationContext = m_pageClient->addDictationAlternatives(alternativeWithRange.alternatives); - if (dictationContext) - dictationAlternatives.append(DictationAlternative(alternativeWithRange.range.location, alternativeWithRange.range.length, dictationContext)); - } - - if (dictationAlternatives.isEmpty()) - return insertText(text, replacementRangeStart, replacementRangeEnd); - - bool handled = true; - process()->sendSync(Messages::WebPage::InsertDictatedText(text, replacementRangeStart, replacementRangeEnd, dictationAlternatives), Messages::WebPage::InsertDictatedText::Reply(handled, m_editorState), m_pageID); - return handled; -#else - return insertText(text, replacementRangeStart, replacementRangeEnd); -#endif -} - -void WebPageProxy::getMarkedRange(uint64_t& location, uint64_t& length) -{ - location = NSNotFound; - length = 0; - - if (!isValid()) - return; - - process()->sendSync(Messages::WebPage::GetMarkedRange(), Messages::WebPage::GetMarkedRange::Reply(location, length), m_pageID); -} - -void WebPageProxy::getSelectedRange(uint64_t& location, uint64_t& length) -{ - location = NSNotFound; - length = 0; - - if (!isValid()) - return; - - process()->sendSync(Messages::WebPage::GetSelectedRange(), Messages::WebPage::GetSelectedRange::Reply(location, length), m_pageID); -} - -void WebPageProxy::getAttributedSubstringFromRange(uint64_t location, uint64_t length, AttributedString& result) -{ - if (!isValid()) - return; - process()->sendSync(Messages::WebPage::GetAttributedSubstringFromRange(location, length), Messages::WebPage::GetAttributedSubstringFromRange::Reply(result), m_pageID); -} - -uint64_t WebPageProxy::characterIndexForPoint(const IntPoint point) -{ - if (!isValid()) - return 0; - - uint64_t result = 0; - process()->sendSync(Messages::WebPage::CharacterIndexForPoint(point), Messages::WebPage::CharacterIndexForPoint::Reply(result), m_pageID); - return result; -} - -IntRect WebPageProxy::firstRectForCharacterRange(uint64_t location, uint64_t length) -{ - if (!isValid()) - return IntRect(); - - IntRect resultRect; - process()->sendSync(Messages::WebPage::FirstRectForCharacterRange(location, length), Messages::WebPage::FirstRectForCharacterRange::Reply(resultRect), m_pageID); - return resultRect; -} - -bool WebPageProxy::executeKeypressCommands(const Vector<WebCore::KeypressCommand>& commands) -{ - if (!isValid()) - return false; - - bool result = false; - process()->sendSync(Messages::WebPage::ExecuteKeypressCommands(commands), Messages::WebPage::ExecuteKeypressCommands::Reply(result, m_editorState), m_pageID); - return result; -} - -String WebPageProxy::stringSelectionForPasteboard() -{ - String value; - if (!isValid()) - return value; - - const double messageTimeout = 20; - process()->sendSync(Messages::WebPage::GetStringSelectionForPasteboard(), Messages::WebPage::GetStringSelectionForPasteboard::Reply(value), m_pageID, messageTimeout); - return value; -} - -PassRefPtr<WebCore::SharedBuffer> WebPageProxy::dataSelectionForPasteboard(const String& pasteboardType) -{ - if (!isValid()) - return 0; - SharedMemory::Handle handle; - uint64_t size = 0; - const double messageTimeout = 20; - process()->sendSync(Messages::WebPage::GetDataSelectionForPasteboard(pasteboardType), - Messages::WebPage::GetDataSelectionForPasteboard::Reply(handle, size), m_pageID, messageTimeout); - if (handle.isNull()) - return 0; - RefPtr<SharedMemory> sharedMemoryBuffer = SharedMemory::create(handle, SharedMemory::ReadOnly); - return SharedBuffer::create(static_cast<unsigned char *>(sharedMemoryBuffer->data()), size); -} - -bool WebPageProxy::readSelectionFromPasteboard(const String& pasteboardName) -{ - if (!isValid()) - return false; - - bool result = false; - const double messageTimeout = 20; - process()->sendSync(Messages::WebPage::ReadSelectionFromPasteboard(pasteboardName), Messages::WebPage::ReadSelectionFromPasteboard::Reply(result), m_pageID, messageTimeout); - return result; -} - -#if ENABLE(DRAG_SUPPORT) -void WebPageProxy::setDragImage(const WebCore::IntPoint& clientPosition, const ShareableBitmap::Handle& dragImageHandle, bool isLinkDrag) -{ - RefPtr<ShareableBitmap> dragImage = ShareableBitmap::create(dragImageHandle); - if (!dragImage) - return; - - m_pageClient->setDragImage(clientPosition, dragImage.release(), isLinkDrag); -} - -void WebPageProxy::setPromisedData(const String& pasteboardName, const SharedMemory::Handle& imageHandle, uint64_t imageSize, const String& filename, const String& extension, - const String& title, const String& url, const String& visibleURL, const SharedMemory::Handle& archiveHandle, uint64_t archiveSize) -{ - RefPtr<SharedMemory> sharedMemoryImage = SharedMemory::create(imageHandle, SharedMemory::ReadOnly); - RefPtr<SharedBuffer> imageBuffer = SharedBuffer::create(static_cast<unsigned char*>(sharedMemoryImage->data()), imageSize); - RefPtr<SharedBuffer> archiveBuffer; - - if (!archiveHandle.isNull()) { - RefPtr<SharedMemory> sharedMemoryArchive = SharedMemory::create(archiveHandle, SharedMemory::ReadOnly);; - archiveBuffer = SharedBuffer::create(static_cast<unsigned char*>(sharedMemoryArchive->data()), archiveSize); - } - m_pageClient->setPromisedData(pasteboardName, imageBuffer, filename, extension, title, url, visibleURL, archiveBuffer); -} -#endif - -void WebPageProxy::performDictionaryLookupAtLocation(const WebCore::FloatPoint& point) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::PerformDictionaryLookupAtLocation(point), m_pageID); -} - -void WebPageProxy::interpretQueuedKeyEvent(const EditorState& state, bool& handled, Vector<WebCore::KeypressCommand>& commands) -{ - m_editorState = state; - handled = m_pageClient->interpretKeyEvent(m_keyEventQueue.first(), commands); -} - -// Complex text input support for plug-ins. -void WebPageProxy::sendComplexTextInputToPlugin(uint64_t pluginComplexTextInputIdentifier, const String& textInput) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::SendComplexTextInputToPlugin(pluginComplexTextInputIdentifier, textInput), m_pageID); -} - -void WebPageProxy::uppercaseWord() -{ - process()->send(Messages::WebPage::UppercaseWord(), m_pageID); -} - -void WebPageProxy::lowercaseWord() -{ - process()->send(Messages::WebPage::LowercaseWord(), m_pageID); -} - -void WebPageProxy::capitalizeWord() -{ - process()->send(Messages::WebPage::CapitalizeWord(), m_pageID); -} - -void WebPageProxy::setSmartInsertDeleteEnabled(bool isSmartInsertDeleteEnabled) -{ - if (m_isSmartInsertDeleteEnabled == isSmartInsertDeleteEnabled) - return; - - TextChecker::setSmartInsertDeleteEnabled(isSmartInsertDeleteEnabled); - m_isSmartInsertDeleteEnabled = isSmartInsertDeleteEnabled; - process()->send(Messages::WebPage::SetSmartInsertDeleteEnabled(isSmartInsertDeleteEnabled), m_pageID); -} - -void WebPageProxy::didPerformDictionaryLookup(const AttributedString& text, const DictionaryPopupInfo& dictionaryPopupInfo) -{ - m_pageClient->didPerformDictionaryLookup(text, dictionaryPopupInfo); -} - -void WebPageProxy::registerWebProcessAccessibilityToken(const CoreIPC::DataReference& data) -{ - m_pageClient->accessibilityWebProcessTokenReceived(data); -} - -void WebPageProxy::makeFirstResponder() -{ - m_pageClient->makeFirstResponder(); -} - -ColorSpaceData WebPageProxy::colorSpace() -{ - return m_pageClient->colorSpace(); -} - -void WebPageProxy::registerUIProcessAccessibilityTokens(const CoreIPC::DataReference& elementToken, const CoreIPC::DataReference& windowToken) -{ - if (!isValid()) - return; - - process()->send(Messages::WebPage::RegisterUIProcessAccessibilityTokens(elementToken, windowToken), m_pageID); -} - -void WebPageProxy::pluginFocusOrWindowFocusChanged(uint64_t pluginComplexTextInputIdentifier, bool pluginHasFocusAndWindowHasFocus) -{ - m_pageClient->pluginFocusOrWindowFocusChanged(pluginComplexTextInputIdentifier, pluginHasFocusAndWindowHasFocus); -} - -void WebPageProxy::setPluginComplexTextInputState(uint64_t pluginComplexTextInputIdentifier, uint64_t pluginComplexTextInputState) -{ - MESSAGE_CHECK(isValidPluginComplexTextInputState(pluginComplexTextInputState)); - - m_pageClient->setPluginComplexTextInputState(pluginComplexTextInputIdentifier, static_cast<PluginComplexTextInputState>(pluginComplexTextInputState)); -} - -void WebPageProxy::executeSavedCommandBySelector(const String& selector, bool& handled) -{ - MESSAGE_CHECK(isValidKeypressCommandName(selector)); - - handled = m_pageClient->executeSavedCommandBySelector(selector); -} - -bool WebPageProxy::shouldDelayWindowOrderingForEvent(const WebKit::WebMouseEvent& event) -{ - if (!process()->isValid()) - return false; - - bool result = false; - const double messageTimeout = 3; - process()->sendSync(Messages::WebPage::ShouldDelayWindowOrderingEvent(event), Messages::WebPage::ShouldDelayWindowOrderingEvent::Reply(result), m_pageID, messageTimeout); - return result; -} - -bool WebPageProxy::acceptsFirstMouse(int eventNumber, const WebKit::WebMouseEvent& event) -{ - if (!isValid()) - return false; - - bool result = false; - const double messageTimeout = 3; - process()->sendSync(Messages::WebPage::AcceptsFirstMouse(eventNumber, event), Messages::WebPage::AcceptsFirstMouse::Reply(result), m_pageID, messageTimeout); - return result; -} - -WKView* WebPageProxy::wkView() const -{ - return m_pageClient->wkView(); -} - -void WebPageProxy::intrinsicContentSizeDidChange(const IntSize& intrinsicContentSize) -{ - m_pageClient->intrinsicContentSizeDidChange(intrinsicContentSize); -} - -void WebPageProxy::setAcceleratedCompositingRootLayer(const GraphicsLayer* rootLayer) -{ - m_pageClient->setAcceleratedCompositingRootLayer(rootLayer->platformLayer()); -} - -static NSString *temporaryPDFDirectoryPath() -{ - static NSString *temporaryPDFDirectoryPath; - - if (!temporaryPDFDirectoryPath) { - NSString *temporaryDirectoryTemplate = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WebKitPDFs-XXXXXX"]; - CString templateRepresentation = [temporaryDirectoryTemplate fileSystemRepresentation]; - - if (mkdtemp(templateRepresentation.mutableData())) - temporaryPDFDirectoryPath = [[[NSFileManager defaultManager] stringWithFileSystemRepresentation:templateRepresentation.data() length:templateRepresentation.length()] copy]; - } - - return temporaryPDFDirectoryPath; -} - -static NSString *pathToPDFOnDisk(const String& suggestedFilename) -{ - NSString *pdfDirectoryPath = temporaryPDFDirectoryPath(); - if (!pdfDirectoryPath) { - WTFLogAlways("Cannot create temporary PDF download directory."); - return nil; - } - - NSString *path = [pdfDirectoryPath stringByAppendingPathComponent:suggestedFilename]; - - NSFileManager *fileManager = [NSFileManager defaultManager]; - if ([fileManager fileExistsAtPath:path]) { - NSString *pathTemplatePrefix = [pdfDirectoryPath stringByAppendingPathComponent:@"XXXXXX-"]; - NSString *pathTemplate = [pathTemplatePrefix stringByAppendingString:suggestedFilename]; - CString pathTemplateRepresentation = [pathTemplate fileSystemRepresentation]; - - int fd = mkstemps(pathTemplateRepresentation.mutableData(), pathTemplateRepresentation.length() - strlen([pathTemplatePrefix fileSystemRepresentation]) + 1); - if (fd < 0) { - WTFLogAlways("Cannot create PDF file in the temporary directory (%s).", suggestedFilename.utf8().data()); - return nil; - } - - close(fd); - path = [fileManager stringWithFileSystemRepresentation:pathTemplateRepresentation.data() length:pathTemplateRepresentation.length()]; - } - - return path; -} - -void WebPageProxy::savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(const String& suggestedFilename, const String& originatingURLString, const uint8_t* data, unsigned long size, const String& pdfUUID) -{ - // FIXME: Write originatingURLString to the file's originating URL metadata (perhaps WKSetMetadataURL?). - UNUSED_PARAM(originatingURLString); - - if (!suggestedFilename.endsWith(".pdf", false)) { - WTFLogAlways("Cannot save file without .pdf extension to the temporary directory."); - return; - } - - if (!size) { - WTFLogAlways("Cannot save empty PDF file to the temporary directory."); - return; - } - - NSString *nsPath = pathToPDFOnDisk(suggestedFilename); - - if (!nsPath) - return; - - RetainPtr<NSNumber> permissions = adoptNS([[NSNumber alloc] initWithInt:S_IRUSR]); - RetainPtr<NSDictionary> fileAttributes = adoptNS([[NSDictionary alloc] initWithObjectsAndKeys:permissions.get(), NSFilePosixPermissions, nil]); - RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytesNoCopy:(void*)data length:size freeWhenDone:NO]); - - if (![[NSFileManager defaultManager] createFileAtPath:nsPath contents:nsData.get() attributes:fileAttributes.get()]) { - WTFLogAlways("Cannot create PDF file in the temporary directory (%s).", suggestedFilename.utf8().data()); - return; - } - - m_temporaryPDFFiles.add(pdfUUID, nsPath); - - [[NSWorkspace sharedWorkspace] openFile:nsPath]; -} - -void WebPageProxy::savePDFToTemporaryFolderAndOpenWithNativeApplication(const String& suggestedFilename, const String& originatingURLString, const CoreIPC::DataReference& data, const String& pdfUUID) -{ - if (data.isEmpty()) { - WTFLogAlways("Cannot save empty PDF file to the temporary directory."); - return; - } - - savePDFToTemporaryFolderAndOpenWithNativeApplicationRaw(suggestedFilename, originatingURLString, data.data(), data.size(), pdfUUID); -} - -void WebPageProxy::openPDFFromTemporaryFolderWithNativeApplication(const String& pdfUUID) -{ - String pdfFilename = m_temporaryPDFFiles.get(pdfUUID); - - if (!pdfFilename.endsWith(".pdf", false)) - return; - - [[NSWorkspace sharedWorkspace] openFile:pdfFilename]; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm deleted file mode 100644 index f74b76015..000000000 --- a/Source/WebKit2/UIProcess/mac/WebPopupMenuProxyMac.mm +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WebPopupMenuProxyMac.h" - -#if USE(APPKIT) - -#import "NativeWebMouseEvent.h" -#import "PageClientImpl.h" -#import "PlatformPopupMenuData.h" -#import "StringUtilities.h" -#import "WKView.h" -#import "WebPopupItem.h" -#import <WebKitSystemInterface.h> - -using namespace WebCore; - -namespace WebKit { - -WebPopupMenuProxyMac::WebPopupMenuProxyMac(WKView *webView, WebPopupMenuProxy::Client* client) - : WebPopupMenuProxy(client) - , m_webView(webView) -{ -} - -WebPopupMenuProxyMac::~WebPopupMenuProxyMac() -{ - if (m_popup) - [m_popup.get() setControlView:nil]; -} - -void WebPopupMenuProxyMac::populate(const Vector<WebPopupItem>& items, NSFont *font, TextDirection menuTextDirection) -{ - if (m_popup) - [m_popup.get() removeAllItems]; - else { - m_popup = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]); - [m_popup.get() setUsesItemFromMenu:NO]; - [m_popup.get() setAutoenablesItems:NO]; - } - - int size = items.size(); - - for (int i = 0; i < size; i++) { - if (items[i].m_type == WebPopupItem::Separator) - [[m_popup.get() menu] addItem:[NSMenuItem separatorItem]]; - else { - [m_popup.get() addItemWithTitle:@""]; - NSMenuItem *menuItem = [m_popup.get() lastItem]; - - RetainPtr<NSMutableParagraphStyle> paragraphStyle = adoptNS([[NSParagraphStyle defaultParagraphStyle] mutableCopy]); - NSWritingDirection writingDirection = items[i].m_textDirection == LTR ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft; - [paragraphStyle.get() setBaseWritingDirection:writingDirection]; - [paragraphStyle.get() setAlignment:menuTextDirection == LTR ? NSLeftTextAlignment : NSRightTextAlignment]; - RetainPtr<NSMutableDictionary> attributes = adoptNS([[NSMutableDictionary alloc] initWithObjectsAndKeys: - paragraphStyle.get(), NSParagraphStyleAttributeName, - font, NSFontAttributeName, - nil]); - if (items[i].m_hasTextDirectionOverride) { - RetainPtr<NSNumber> writingDirectionValue = adoptNS([[NSNumber alloc] initWithInteger:writingDirection + NSTextWritingDirectionOverride]); - RetainPtr<NSArray> writingDirectionArray = adoptNS([[NSArray alloc] initWithObjects:writingDirectionValue.get(), nil]); - [attributes.get() setObject:writingDirectionArray.get() forKey:NSWritingDirectionAttributeName]; - } - RetainPtr<NSAttributedString> string = adoptNS([[NSAttributedString alloc] initWithString:nsStringFromWebCoreString(items[i].m_text) attributes:attributes.get()]); - - [menuItem setAttributedTitle:string.get()]; - // We set the title as well as the attributed title here. The attributed title will be displayed in the menu, - // but typeahead will use the non-attributed string that doesn't contain any leading or trailing whitespace. - [menuItem setTitle:[[string.get() string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]]; - [menuItem setEnabled:items[i].m_isEnabled]; - [menuItem setToolTip:nsStringFromWebCoreString(items[i].m_toolTip)]; - } - } -} - -void WebPopupMenuProxyMac::showPopupMenu(const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, const PlatformPopupMenuData& data, int32_t selectedIndex) -{ - NSFont *font; - if (data.fontInfo.fontAttributeDictionary) { - NSFontDescriptor *fontDescriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:(NSDictionary *)data.fontInfo.fontAttributeDictionary.get()]; - font = [NSFont fontWithDescriptor:fontDescriptor size:((pageScaleFactor != 1) ? [fontDescriptor pointSize] * pageScaleFactor : 0)]; - } else - font = [NSFont menuFontOfSize:0]; - - populate(items, font, textDirection); - - [m_popup.get() attachPopUpWithFrame:rect inView:m_webView]; - [m_popup.get() selectItemAtIndex:selectedIndex]; - [m_popup.get() setUserInterfaceLayoutDirection:textDirection == LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft]; - - NSMenu *menu = [m_popup.get() menu]; - - // These values were borrowed from AppKit to match their placement of the menu. - const int popOverHorizontalAdjust = -10; - const int popUnderHorizontalAdjust = 6; - const int popUnderVerticalAdjust = 6; - - // Menus that pop-over directly obscure the node that generated the popup menu. - // Menus that pop-under are offset underneath it. - NSPoint location; - if (data.shouldPopOver) { - NSRect titleFrame = [m_popup.get() titleRectForBounds:rect]; - if (titleFrame.size.width <= 0 || titleFrame.size.height <= 0) - titleFrame = rect; - float vertOffset = roundf((NSMaxY(rect) - NSMaxY(titleFrame)) + NSHeight(titleFrame)); - location = NSMakePoint(NSMinX(rect) + popOverHorizontalAdjust, NSMaxY(rect) - vertOffset); - } else - location = NSMakePoint(NSMinX(rect) + popUnderHorizontalAdjust, NSMaxY(rect) + popUnderVerticalAdjust); - - RetainPtr<NSView> dummyView = adoptNS([[NSView alloc] initWithFrame:rect]); - [m_webView addSubview:dummyView.get()]; - location = [dummyView.get() convertPoint:location fromView:m_webView]; - - WKPopupMenu(menu, location, roundf(NSWidth(rect)), dummyView.get(), selectedIndex, font); - - [m_popup.get() dismissPopUp]; - [dummyView.get() removeFromSuperview]; - - if (!m_client) - return; - - m_client->valueChangedForPopupMenu(this, [m_popup.get() indexOfSelectedItem]); - - // <https://bugs.webkit.org/show_bug.cgi?id=57904> This code is adopted from EventHandler::sendFakeEventsAfterWidgetTracking(). - if (!m_client->currentlyProcessedMouseDownEvent()) - return; - - NSEvent* initiatingNSEvent = m_client->currentlyProcessedMouseDownEvent()->nativeEvent(); - if ([initiatingNSEvent type] != NSLeftMouseDown) - return; - - NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSLeftMouseUp - location:[initiatingNSEvent locationInWindow] - modifierFlags:[initiatingNSEvent modifierFlags] - timestamp:[initiatingNSEvent timestamp] - windowNumber:[initiatingNSEvent windowNumber] - context:[initiatingNSEvent context] - eventNumber:[initiatingNSEvent eventNumber] - clickCount:[initiatingNSEvent clickCount] - pressure:[initiatingNSEvent pressure]]; - - [NSApp postEvent:fakeEvent atStart:YES]; - fakeEvent = [NSEvent mouseEventWithType:NSMouseMoved - location:[[m_webView window] convertScreenToBase:[NSEvent mouseLocation]] - modifierFlags:[initiatingNSEvent modifierFlags] - timestamp:[initiatingNSEvent timestamp] - windowNumber:[initiatingNSEvent windowNumber] - context:[initiatingNSEvent context] - eventNumber:0 - clickCount:0 - pressure:0]; - [NSApp postEvent:fakeEvent atStart:YES]; -} - -void WebPopupMenuProxyMac::hidePopupMenu() -{ - [m_popup.get() dismissPopUp]; -} - -} // namespace WebKit - -#endif // USE(APPKIT) diff --git a/Source/WebKit2/UIProcess/mac/WebPreferencesMac.mm b/Source/WebKit2/UIProcess/mac/WebPreferencesMac.mm deleted file mode 100644 index f19a6c708..000000000 --- a/Source/WebKit2/UIProcess/mac/WebPreferencesMac.mm +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2010, 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WebPreferences.h" - -#import "StringUtilities.h" -#import <wtf/text/StringConcatenate.h> - -namespace WebKit { - -static inline NSString* makeKey(const String& identifier, const String& baseKey) -{ - return nsStringFromWebCoreString(makeString(identifier, ".WebKit2", baseKey)); -} - -static void setStringValueIfInUserDefaults(const String& identifier, const String& key, WebPreferencesStore& store) -{ - id object = [[NSUserDefaults standardUserDefaults] objectForKey:makeKey(identifier, key)]; - if (!object) - return; - if (![object isKindOfClass:[NSString class]]) - return; - - store.setStringValueForKey(key, (NSString *)object); -} - -static void setBoolValueIfInUserDefaults(const String& identifier, const String& key, WebPreferencesStore& store) -{ - id object = [[NSUserDefaults standardUserDefaults] objectForKey:makeKey(identifier, key)]; - if (!object) - return; - if (![object respondsToSelector:@selector(boolValue)]) - return; - - store.setBoolValueForKey(key, [object boolValue]); -} - -static void setUInt32ValueIfInUserDefaults(const String& identifier, const String& key, WebPreferencesStore& store) -{ - id object = [[NSUserDefaults standardUserDefaults] objectForKey:makeKey(identifier, key)]; - if (!object) - return; - if (![object respondsToSelector:@selector(intValue)]) - return; - - store.setUInt32ValueForKey(key, [object intValue]); -} - -static void setDoubleValueIfInUserDefaults(const String& identifier, const String& key, WebPreferencesStore& store) -{ - id object = [[NSUserDefaults standardUserDefaults] objectForKey:makeKey(identifier, key)]; - if (!object) - return; - if (![object respondsToSelector:@selector(doubleValue)]) - return; - - store.setDoubleValueForKey(key, [object doubleValue]); -} - -void WebPreferences::platformInitializeStore() -{ - if (!m_identifier) - return; - -#define INITIALIZE_PREFERENCE_FROM_NSUSERDEFAULTS(KeyUpper, KeyLower, TypeName, Type, DefaultValue) \ - set##TypeName##ValueIfInUserDefaults(m_identifier, WebPreferencesKey::KeyLower##Key(), m_store); - - FOR_EACH_WEBKIT_PREFERENCE(INITIALIZE_PREFERENCE_FROM_NSUSERDEFAULTS) - -#undef INITIALIZE_PREFERENCE_FROM_NSUSERDEFAULTS -} - -void WebPreferences::platformUpdateStringValueForKey(const String& key, const String& value) -{ - if (!m_identifier) - return; - - [[NSUserDefaults standardUserDefaults] setObject:nsStringFromWebCoreString(value) forKey:makeKey(m_identifier, key)]; -} - -void WebPreferences::platformUpdateBoolValueForKey(const String& key, bool value) -{ - if (!m_identifier) - return; - - [[NSUserDefaults standardUserDefaults] setBool:value forKey:makeKey(m_identifier, key)]; -} - -void WebPreferences::platformUpdateUInt32ValueForKey(const String& key, uint32_t value) -{ - if (!m_identifier) - return; - - [[NSUserDefaults standardUserDefaults] setInteger:value forKey:makeKey(m_identifier, key)]; -} - -void WebPreferences::platformUpdateDoubleValueForKey(const String& key, double value) -{ - if (!m_identifier) - return; - - [[NSUserDefaults standardUserDefaults] setDouble:value forKey:makeKey(m_identifier, key)]; -} - -void WebPreferences::platformUpdateFloatValueForKey(const String& key, float value) -{ - if (!m_identifier) - return; - - [[NSUserDefaults standardUserDefaults] setFloat:value forKey:makeKey(m_identifier, key)]; -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm b/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm deleted file mode 100644 index 2ca0b3f2a..000000000 --- a/Source/WebKit2/UIProcess/mac/WebProcessProxyMac.mm +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2011 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "config.h" -#import "WebProcessProxy.h" - -#import "WebContext.h" -#import "WebPageGroup.h" -#import "WebPreferences.h" -#import "WebProcessMessages.h" -#import "WKFullKeyboardAccessWatcher.h" - -namespace WebKit { - -bool WebProcessProxy::fullKeyboardAccessEnabled() -{ - return [WKFullKeyboardAccessWatcher fullKeyboardAccessEnabled]; -} - -#if HAVE(XPC) -static bool shouldUseXPC() -{ - if (id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKit2UseXPCServiceForWebProcess"]) - return [value boolValue]; - -#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 - return true; -#else - return false; -#endif -} -#endif - -void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) -{ - // We want the web process to match the architecture of the UI process. - launchOptions.architecture = ProcessLauncher::LaunchOptions::MatchCurrentArchitecture; - launchOptions.executableHeap = false; - -#if HAVE(XPC) - launchOptions.useXPC = shouldUseXPC(); -#endif -} - -bool WebProcessProxy::pageIsProcessSuppressible(WebPageProxy* page) -{ - return !page->isViewVisible() && page->pageGroup()->preferences()->pageVisibilityBasedProcessSuppressionEnabled(); -} - -bool WebProcessProxy::allPagesAreProcessSuppressible() const -{ - return (m_processSuppressiblePages.size() == m_pageMap.size()) && !m_processSuppressiblePages.isEmpty(); -} - -void WebProcessProxy::updateProcessSuppressionState() -{ - if (!isValid()) - return; - - bool canEnable = m_context->canEnableProcessSuppressionForWebProcess(this); - if (m_processSuppressionEnabled == canEnable) - return; - m_processSuppressionEnabled = canEnable; - - connection()->send(Messages::WebProcess::SetProcessSuppressionEnabled(m_processSuppressionEnabled), 0); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/QtPageClient.cpp b/Source/WebKit2/UIProcess/qt/QtPageClient.cpp index e053aa426..8c0e0c31a 100644 --- a/Source/WebKit2/UIProcess/qt/QtPageClient.cpp +++ b/Source/WebKit2/UIProcess/qt/QtPageClient.cpp @@ -63,7 +63,7 @@ void QtPageClient::initialize(QQuickWebView* webView, QtWebPageEventHandler* eve m_undoController = undoController; } -PassOwnPtr<DrawingAreaProxy> QtPageClient::createDrawingAreaProxy() +std::unique_ptr<DrawingAreaProxy> QtPageClient::createDrawingAreaProxy() { return QQuickWebViewPrivate::get(m_webView)->createDrawingAreaProxy(); } diff --git a/Source/WebKit2/UIProcess/qt/QtPageClient.h b/Source/WebKit2/UIProcess/qt/QtPageClient.h index e6d9db307..3cb5a8e07 100644 --- a/Source/WebKit2/UIProcess/qt/QtPageClient.h +++ b/Source/WebKit2/UIProcess/qt/QtPageClient.h @@ -52,7 +52,7 @@ public: virtual void didChangeViewportProperties(const WebCore::ViewportAttributes&); virtual void processDidCrash(); virtual void didRelaunchProcess(); - virtual PassOwnPtr<DrawingAreaProxy> createDrawingAreaProxy(); + virtual std::unique_ptr<DrawingAreaProxy> createDrawingAreaProxy(); virtual void handleDownloadRequest(DownloadProxy*); virtual void handleApplicationSchemeRequest(PassRefPtr<QtRefCountedNetworkRequestData>); virtual void handleAuthenticationRequiredRequest(const String& hostname, const String& realm, const String& prefilledUsername, String& username, String& password); diff --git a/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.cpp b/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.cpp index 1f0ad1431..0c800ed64 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.cpp +++ b/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.cpp @@ -44,11 +44,11 @@ QtWebPagePolicyClient::QtWebPagePolicyClient(WKPageRef pageRef, QQuickWebView* w WKPageSetPagePolicyClient(pageRef, &policyClient); } -void QtWebPagePolicyClient::decidePolicyForNavigationAction(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, WKFramePolicyListenerRef listener) +void QtWebPagePolicyClient::decidePolicyForNavigationAction(const QUrl& url, Qt::MouseButton mouseButton, Qt::KeyboardModifiers keyboardModifiers, QQuickWebView::NavigationType navigationType, bool isMainFrame, WKFramePolicyListenerRef listener) { // NOTE: even though the C API (and the WebKit2 IPC) supports an asynchronous answer, this is not currently working. // We are expected to call the listener immediately. See the patch for https://bugs.webkit.org/show_bug.cgi?id=53785. - QWebNavigationRequest navigationRequest(url, mouseButton, keyboardModifiers, navigationType); + QWebNavigationRequest navigationRequest(url, mouseButton, keyboardModifiers, navigationType, isMainFrame); emit m_webView->navigationRequested(&navigationRequest); switch (navigationRequest.action()) { @@ -121,12 +121,13 @@ static QQuickWebView::NavigationType toQuickWebViewNavigationType(WKFrameNavigat return QQuickWebView::OtherNavigation; } -void QtWebPagePolicyClient::decidePolicyForNavigationAction(WKPageRef, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo) +void QtWebPagePolicyClient::decidePolicyForNavigationAction(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo) { WKRetainPtr<WKURLRef> frameURL(AdoptWK, WKFrameCopyURL(frame)); WKRetainPtr<WKURLRef> requestURL(AdoptWK, WKURLRequestCopyURL(request)); QUrl qUrl = WKURLCopyQUrl(requestURL.get()); - toQtWebPagePolicyClient(clientInfo)->decidePolicyForNavigationAction(qUrl, toQtMouseButton(mouseButton), toQtKeyboardModifiers(modifiers), toQuickWebViewNavigationType(navigationType), listener); + bool isMainFrame = (WKPageGetMainFrame(page) == frame); + toQtWebPagePolicyClient(clientInfo)->decidePolicyForNavigationAction(qUrl, toQtMouseButton(mouseButton), toQtKeyboardModifiers(modifiers), toQuickWebViewNavigationType(navigationType), isMainFrame, listener); } void QtWebPagePolicyClient::decidePolicyForResponse(WKPageRef page, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef, WKFramePolicyListenerRef listener, WKTypeRef, const void*) diff --git a/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.h b/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.h index 9515c020e..c9267508d 100644 --- a/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.h +++ b/Source/WebKit2/UIProcess/qt/QtWebPagePolicyClient.h @@ -36,7 +36,7 @@ public: QtWebPagePolicyClient(WKPageRef, QQuickWebView*); private: - void decidePolicyForNavigationAction(const QUrl&, Qt::MouseButton, Qt::KeyboardModifiers, QQuickWebView::NavigationType, WKFramePolicyListenerRef); + void decidePolicyForNavigationAction(const QUrl&, Qt::MouseButton, Qt::KeyboardModifiers, QQuickWebView::NavigationType, bool isMainFrame, WKFramePolicyListenerRef); // WKPagePolicyClient callbacks. static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef, WKFramePolicyListenerRef, WKTypeRef userData, const void* clientInfo); diff --git a/Source/WebKit2/UIProcess/qt/WebColorPickerQt.cpp b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.cpp index 5fe35d771..1bfa37624 100644 --- a/Source/WebKit2/UIProcess/qt/WebColorPickerQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.cpp @@ -94,7 +94,7 @@ void WebColorPickerQt::createItem(QObject* contextObject) // Needs to be enqueue because it might trigger deletion. connect(contextObject, SIGNAL(accepted(QColor)), SLOT(notifyColorSelected(QColor)), Qt::QueuedConnection); - connect(contextObject, SIGNAL(rejected()), SLOT(endChooser()), Qt::QueuedConnection); + connect(contextObject, SIGNAL(rejected()), SLOT(endPicker()), Qt::QueuedConnection); QQuickWebViewPrivate::get(m_webView)->addAttachedPropertyTo(m_colorChooser.get()); m_colorChooser->setParentItem(m_webView); @@ -132,10 +132,10 @@ void WebColorPickerQt::notifyColorSelected(const QColor& color) Color coreColor = makeRGB(color.red(), color.green(), color.blue()); m_client->didChooseColor(coreColor); - endChooser(); + endPicker(); } -void WebColorPickerQt::endChooser() +void WebColorPickerQt::endPicker() { m_colorChooser.clear(); m_context.clear(); @@ -143,7 +143,7 @@ void WebColorPickerQt::endChooser() if (!m_client) return; - m_client->didEndColorChooser(); + m_client->didEndColorPicker(); } } // namespace WebKit diff --git a/Source/WebKit2/UIProcess/qt/WebColorPickerQt.h b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.h index 01c5bf97d..00c72d7ab 100644 --- a/Source/WebKit2/UIProcess/qt/WebColorPickerQt.h +++ b/Source/WebKit2/UIProcess/qt/WebColorPickerQt.h @@ -53,7 +53,7 @@ public: virtual void setSelectedColor(const WebCore::Color&); public Q_SLOTS: - virtual void endChooser(); + virtual void endPicker(); private Q_SLOTS: void notifyColorSelected(const QColor&); diff --git a/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp b/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp index b9058478d..6a520c383 100644 --- a/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebInspectorProxyQt.cpp @@ -112,7 +112,7 @@ void WebInspectorProxy::platformSetToolbarHeight(unsigned) notImplemented(); } -void WebInspectorProxy::platformSave(const String&, const String&, bool) +void WebInspectorProxy::platformSave(const String&, const String&, bool, bool) { notImplemented(); } diff --git a/Source/WebKit2/UIProcess/qt/WebPopupMenuProxyQt.cpp b/Source/WebKit2/UIProcess/qt/WebPopupMenuProxyQt.cpp index 01ea5e6bd..128379f26 100644 --- a/Source/WebKit2/UIProcess/qt/WebPopupMenuProxyQt.cpp +++ b/Source/WebKit2/UIProcess/qt/WebPopupMenuProxyQt.cpp @@ -250,7 +250,7 @@ void PopupMenuItemModel::buildItems(const Vector<WebPopupItem>& webPopupItems) { QString currentGroup; m_items.reserveInitialCapacity(webPopupItems.size()); - for (size_t i = 0; i < webPopupItems.size(); i++) { + for (int i = 0; i < webPopupItems.size(); i++) { const WebPopupItem& webPopupItem = webPopupItems[i]; if (webPopupItem.m_isLabel) { currentGroup = webPopupItem.m_text; diff --git a/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp b/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp deleted file mode 100644 index f964e4981..000000000 --- a/Source/WebKit2/UIProcess/soup/WebCookieManagerProxySoup.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#include "config.h" -#include "WebCookieManagerProxy.h" - -#include "WebContext.h" -#include "WebCookieManagerMessages.h" - -namespace WebKit { - -void WebCookieManagerProxy::setCookiePersistentStorage(const String& storagePath, uint32_t storageType) -{ - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebCookieManager::SetCookiePersistentStorage(storagePath, storageType)); - - m_cookiePersistentStoragePath = storagePath; - m_cookiePersistentStorageType = static_cast<SoupCookiePersistentStorageType>(storageType); -} - -void WebCookieManagerProxy::getCookiePersistentStorage(String& storagePath, uint32_t& storageType) const -{ - storagePath = m_cookiePersistentStoragePath; - storageType = static_cast<uint32_t>(m_cookiePersistentStorageType); -} - -} diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.cpp b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.cpp deleted file mode 100644 index c5d7e3bf7..000000000 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.cpp +++ /dev/null @@ -1,42 +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 "WebSoupRequestManagerClient.h" - -#include "WKAPICast.h" - -namespace WebKit { - -bool WebSoupRequestManagerClient::didReceiveURIRequest(WebSoupRequestManagerProxy* soupRequestManager, WebURL* url, WebPageProxy* initiaingPage, uint64_t requestID) -{ - if (!m_client.didReceiveURIRequest) - return false; - - m_client.didReceiveURIRequest(toAPI(soupRequestManager), toAPI(url), toAPI(initiaingPage), requestID, m_client.clientInfo); - return true; -} - -void WebSoupRequestManagerClient::didFailToLoadURIRequest(WebSoupRequestManagerProxy* soupRequestManager, uint64_t requestID) -{ - if (m_client.didFailToLoadURIRequest) - m_client.didFailToLoadURIRequest(toAPI(soupRequestManager), requestID, m_client.clientInfo); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h deleted file mode 100644 index 60b34937f..000000000 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerClient.h +++ /dev/null @@ -1,40 +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. - */ - -#ifndef WebSoupRequestManagerClient_h -#define WebSoupRequestManagerClient_h - -#include "APIClient.h" -#include "WKAPICast.h" -#include "WKSoupRequestManager.h" - -namespace WebKit { - -class WebSoupRequestManagerProxy; -class WebURL; - -class WebSoupRequestManagerClient : public APIClient<WKSoupRequestManagerClient, kWKSoupRequestManagerClientCurrentVersion> { -public: - bool didReceiveURIRequest(WebSoupRequestManagerProxy*, WebURL*, WebPageProxy*, uint64_t requestID); - void didFailToLoadURIRequest(WebSoupRequestManagerProxy*, uint64_t requestID); -}; - -} // namespace WebKit - -#endif // WebSoupRequestManagerClient_h diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp deleted file mode 100644 index c5e6c6096..000000000 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2012 Igalia S.L. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 "WebSoupRequestManagerProxy.h" - -#include "WebContext.h" -#include "WebData.h" -#include "WebSoupRequestManagerMessages.h" -#include "WebSoupRequestManagerProxyMessages.h" - -namespace WebKit { - -const char* WebSoupRequestManagerProxy::supplementName() -{ - return "WebSoupRequestManagerProxy"; -} - -PassRefPtr<WebSoupRequestManagerProxy> WebSoupRequestManagerProxy::create(WebContext* context) -{ - return adoptRef(new WebSoupRequestManagerProxy(context)); -} - -WebSoupRequestManagerProxy::WebSoupRequestManagerProxy(WebContext* context) - : WebContextSupplement(context) - , m_loadFailed(false) -{ - WebContextSupplement::context()->addMessageReceiver(Messages::WebSoupRequestManagerProxy::messageReceiverName(), this); -} - -WebSoupRequestManagerProxy::~WebSoupRequestManagerProxy() -{ -} - -void WebSoupRequestManagerProxy::initializeClient(const WKSoupRequestManagerClient* client) -{ - m_client.initialize(client); -} - -// WebContextSupplement - -void WebSoupRequestManagerProxy::contextDestroyed() -{ -} - -void WebSoupRequestManagerProxy::processDidClose(WebProcessProxy*) -{ -} - -void WebSoupRequestManagerProxy::refWebContextSupplement() -{ - APIObject::ref(); -} - -void WebSoupRequestManagerProxy::derefWebContextSupplement() -{ - APIObject::deref(); -} - -void WebSoupRequestManagerProxy::registerURIScheme(const String& scheme) -{ - if (!context()) - return; - - context()->sendToAllProcessesRelaunchingThemIfNecessary(Messages::WebSoupRequestManager::RegisterURIScheme(scheme)); - - ASSERT(!m_registeredURISchemes.contains(scheme)); - m_registeredURISchemes.append(scheme); -} - -void WebSoupRequestManagerProxy::didHandleURIRequest(const WebData* requestData, uint64_t contentLength, const String& mimeType, uint64_t requestID) -{ - if (!context()) - return; - - context()->sendToAllProcesses(Messages::WebSoupRequestManager::DidHandleURIRequest(requestData->dataReference(), contentLength, mimeType, requestID)); -} - -void WebSoupRequestManagerProxy::didReceiveURIRequestData(const WebData* requestData, uint64_t requestID) -{ - if (!context()) - return; - - if (m_loadFailed) - return; - - context()->sendToAllProcesses(Messages::WebSoupRequestManager::DidReceiveURIRequestData(requestData->dataReference(), requestID)); -} - -void WebSoupRequestManagerProxy::didReceiveURIRequest(const String& uriString, WebPageProxy* initiaingPage, uint64_t requestID) -{ - if (!m_client.didReceiveURIRequest(this, WebURL::create(uriString).get(), initiaingPage, requestID)) - didHandleURIRequest(WebData::create(0, 0).get(), 0, String(), requestID); -} - -void WebSoupRequestManagerProxy::didFailToLoadURIRequest(uint64_t requestID) -{ - m_loadFailed = true; - m_client.didFailToLoadURIRequest(this, requestID); -} - -void WebSoupRequestManagerProxy::didFailURIRequest(const WebCore::ResourceError& error, uint64_t requestID) -{ - if (!context()) - return; - - m_loadFailed = true; - context()->sendToAllProcesses(Messages::WebSoupRequestManager::DidFailURIRequest(error, requestID)); -} - -} // namespace WebKit diff --git a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h b/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h deleted file mode 100644 index f78b967ed..000000000 --- a/Source/WebKit2/UIProcess/soup/WebSoupRequestManagerProxy.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2012 Igalia S.L. - * Copyright (C) 2013 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * 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 WebSoupRequestManagerProxy_h -#define WebSoupRequestManagerProxy_h - -#include "APIObject.h" -#include "MessageReceiver.h" -#include "WebContextSupplement.h" -#include "WebSoupRequestManagerClient.h" -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/text/WTFString.h> - -namespace WebKit { - -class WebContext; -class WebData; - -class WebSoupRequestManagerProxy : public TypedAPIObject<APIObject::TypeSoupRequestManager>, public WebContextSupplement, private CoreIPC::MessageReceiver { -public: - static const char* supplementName(); - - static PassRefPtr<WebSoupRequestManagerProxy> create(WebContext*); - virtual ~WebSoupRequestManagerProxy(); - - void initializeClient(const WKSoupRequestManagerClient*); - - void registerURIScheme(const String& scheme); - void didHandleURIRequest(const WebData*, uint64_t contentLength, const String& mimeType, uint64_t requestID); - void didReceiveURIRequestData(const WebData*, uint64_t requestID); - void didReceiveURIRequest(const String& uriString, WebPageProxy*, uint64_t requestID); - void didFailURIRequest(const WebCore::ResourceError&, uint64_t requestID); - - const Vector<String>& registeredURISchemes() const { return m_registeredURISchemes; } - - using APIObject::ref; - using APIObject::deref; - -private: - WebSoupRequestManagerProxy(WebContext*); - - // WebContextSupplement - virtual void contextDestroyed() OVERRIDE; - virtual void processDidClose(WebProcessProxy*) OVERRIDE; - virtual void refWebContextSupplement() OVERRIDE; - virtual void derefWebContextSupplement() OVERRIDE; - - // CoreIPC::MessageReceiver - virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageDecoder&) OVERRIDE; - - void didFailToLoadURIRequest(uint64_t requestID); - - WebSoupRequestManagerClient m_client; - bool m_loadFailed; - Vector<String> m_registeredURISchemes; -}; - -} // namespace WebKit - -#endif // WebSoupRequestManagerProxy_h |