Merge revision 542 changes:

- Add CefCookieManager interface and CefRequestHandler::GetCookieManager for custom cookie handling (issue #542).
- Support getting and setting cookies with custom scheme handlers (issue #555).
- Support calling CefFrame::GetIdentifier and CefFrame::GetURL on any thread (issue #556).

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/963@544 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
This commit is contained in:
Marshall Greenblatt 2012-03-22 22:10:49 +00:00
parent 1d54b2de7d
commit bba09e1319
32 changed files with 3048 additions and 1483 deletions

View File

@ -487,6 +487,8 @@
'libcef_dll/cpptoc/browser_cpptoc.h',
'libcef_dll/cpptoc/command_line_cpptoc.cc',
'libcef_dll/cpptoc/command_line_cpptoc.h',
'libcef_dll/cpptoc/cookie_manager_cpptoc.cc',
'libcef_dll/cpptoc/cookie_manager_cpptoc.h',
'libcef_dll/cpptoc/cpptoc.h',
'libcef_dll/cpptoc/domdocument_cpptoc.cc',
'libcef_dll/cpptoc/domdocument_cpptoc.h',
@ -783,6 +785,8 @@
'libcef/browser_persistent_cookie_store.h',
'libcef/browser_request_context.cc',
'libcef/browser_request_context.h',
'libcef/browser_request_context_proxy.cc',
'libcef/browser_request_context_proxy.h',
'libcef/browser_resource_loader_bridge.cc',
'libcef/browser_resource_loader_bridge.h',
'libcef/browser_settings.cc',
@ -824,6 +828,10 @@
'libcef/cef_time.cc',
'libcef/cef_time_util.h',
'libcef/command_line_impl.cc',
'libcef/cookie_manager_impl.cc',
'libcef/cookie_manager_impl.h',
'libcef/cookie_store_proxy.cc',
'libcef/cookie_store_proxy.h',
'libcef/drag_data_impl.cc',
'libcef/drag_data_impl.h',
'libcef/drag_download_file.cc',

View File

@ -194,6 +194,8 @@
'libcef_dll/ctocpp/browser_ctocpp.h',
'libcef_dll/ctocpp/command_line_ctocpp.cc',
'libcef_dll/ctocpp/command_line_ctocpp.h',
'libcef_dll/ctocpp/cookie_manager_ctocpp.cc',
'libcef_dll/ctocpp/cookie_manager_ctocpp.h',
'libcef_dll/ctocpp/ctocpp.h',
'libcef_dll/ctocpp/domdocument_ctocpp.cc',
'libcef_dll/ctocpp/domdocument_ctocpp.h',

View File

@ -371,54 +371,6 @@ bool CefParseURL(const CefString& url,
bool CefCreateURL(const CefURLParts& parts,
CefString& url);
///
// Visit all cookies. The returned cookies are ordered by longest path, then by
// earliest creation date. Returns false if cookies cannot be accessed.
///
/*--cef()--*/
bool CefVisitAllCookies(CefRefPtr<CefCookieVisitor> visitor);
///
// Visit a subset of cookies. The results are filtered by the given url scheme,
// host, domain and path. If |includeHttpOnly| is true HTTP-only cookies will
// also be included in the results. The returned cookies are ordered by longest
// path, then by earliest creation date. Returns false if cookies cannot be
// accessed.
///
/*--cef()--*/
bool CefVisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor);
///
// Sets a cookie given a valid URL and explicit user-provided cookie attributes.
// This function expects each attribute to be well-formed. It will check for
// disallowed characters (e.g. the ';' character is disallowed within the cookie
// value attribute) and will return false without setting the cookie if such
// characters are found. This method must be called on the IO thread.
///
/*--cef()--*/
bool CefSetCookie(const CefString& url, const CefCookie& cookie);
///
// Delete all cookies that match the specified parameters. If both |url| and
// |cookie_name| are specified all host and domain cookies matching both values
// will be deleted. If only |url| is specified all host cookies (but not domain
// cookies) irrespective of path will be deleted. If |url| is empty all cookies
// for all hosts and domains will be deleted. Returns false if a non-empty
// invalid URL is specified or if cookies cannot be accessed. This method must
// be called on the IO thread.
///
/*--cef(optional_param=url,optional_param=cookie_name)--*/
bool CefDeleteCookies(const CefString& url, const CefString& cookie_name);
///
// Sets the directory path that will be used for storing cookie data. If |path|
// is empty data will be stored in memory only. By default the cookie path is
// the same as the cache path. Returns false if cookies cannot be accessed.
///
/*--cef(optional_param=path)--*/
bool CefSetCookiePath(const CefString& path);
typedef cef_storage_type_t CefStorageType;
@ -583,6 +535,80 @@ public:
};
///
// Class used for managing cookies. The methods of this class may be called on
// any thread unless otherwise indicated.
///
/*--cef(source=library)--*/
class CefCookieManager : public virtual CefBase
{
public:
///
// Returns the global cookie manager. By default data will be stored at
// CefSettings.cache_path if specified or in memory otherwise.
///
/*--cef()--*/
static CefRefPtr<CefCookieManager> GetGlobalManager();
///
// Creates a new cookie manager. If |path| is empty data will be stored in
// memory only. Returns NULL if creation fails.
///
/*--cef(optional_param=path)--*/
static CefRefPtr<CefCookieManager> CreateManager(const CefString& path);
///
// Visit all cookies. The returned cookies are ordered by longest path, then
// by earliest creation date. Returns false if cookies cannot be accessed.
///
/*--cef()--*/
virtual bool VisitAllCookies(CefRefPtr<CefCookieVisitor> visitor) =0;
///
// Visit a subset of cookies. The results are filtered by the given url
// scheme, host, domain and path. If |includeHttpOnly| is true HTTP-only
// cookies will also be included in the results. The returned cookies are
// ordered by longest path, then by earliest creation date. Returns false if
// cookies cannot be accessed.
///
/*--cef()--*/
virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) =0;
///
// Sets a cookie given a valid URL and explicit user-provided cookie
// attributes. This function expects each attribute to be well-formed. It will
// check for disallowed characters (e.g. the ';' character is disallowed
// within the cookie value attribute) and will return false without setting
// the cookie if such characters are found. This method must be called on the
// IO thread.
///
/*--cef()--*/
virtual bool SetCookie(const CefString& url, const CefCookie& cookie) =0;
///
// Delete all cookies that match the specified parameters. If both |url| and
// values |cookie_name| are specified all host and domain cookies matching
// both will be deleted. If only |url| is specified all host cookies (but not
// domain cookies) irrespective of path will be deleted. If |url| is empty all
// cookies for all hosts and domains will be deleted. Returns false if a non-
// empty invalid URL is specified or if cookies cannot be accessed. This
// method must be called on the IO thread.
///
/*--cef(optional_param=url,optional_param=cookie_name)--*/
virtual bool DeleteCookies(const CefString& url,
const CefString& cookie_name) =0;
///
// Sets the directory path that will be used for storing cookie data. If
// |path| is empty data will be stored in memory only. Returns false if
// cookies cannot be accessed.
///
/*--cef(optional_param=path)--*/
virtual bool SetStoragePath(const CefString& path) =0;
};
///
// Interface to implement for visiting cookie values. The methods of this class
// will always be called on the IO thread.
@ -1050,8 +1076,7 @@ public:
virtual CefString GetName() =0;
///
// Returns the globally unique identifier for this frame. This method should
// only be called on the UI thread.
// Returns the globally unique identifier for this frame.
///
/*--cef()--*/
virtual long long GetIdentifier() =0;
@ -1064,8 +1089,7 @@ public:
virtual CefRefPtr<CefFrame> GetParent() =0;
///
// Returns the URL currently loaded in this frame. This method should only be
// called on the UI thread.
// Returns the URL currently loaded in this frame.
///
/*--cef()--*/
virtual CefString GetURL() =0;
@ -1343,6 +1367,17 @@ public:
const CefString& scheme,
CefString& username,
CefString& password) { return false; }
///
// Called on the IO thread to retrieve the cookie manager. |main_url| is the
// URL of the top-level frame. Cookies managers can be unique per browser or
// shared across multiple browsers. The global cookie manager will be used if
// this method returns NULL.
///
/*--cef()--*/
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser,
const CefString& main_url) { return NULL; }
};
@ -2859,7 +2894,8 @@ public:
///
// Return a new scheme handler instance to handle the request. |browser| will
// be the browser window that initiated the request. If the request was
// initiated using the CefWebURLRequest API |browser| will be NULL.
// initiated using the CefWebURLRequest API |browser| will be NULL. The
// |request| object passed to this method will not contain cookie data.
///
/*--cef()--*/
virtual CefRefPtr<CefSchemeHandler> Create(CefRefPtr<CefBrowser> browser,
@ -4002,4 +4038,6 @@ public:
virtual void AppendArgument(const CefString& argument) =0;
};
#endif // _CEF_H

View File

@ -310,51 +310,6 @@ CEF_EXPORT int cef_parse_url(const cef_string_t* url,
CEF_EXPORT int cef_create_url(const struct _cef_urlparts_t* parts,
cef_string_t* url);
///
// Visit all cookies. The returned cookies are ordered by longest path, then by
// earliest creation date. Returns false (0) if cookies cannot be accessed.
///
CEF_EXPORT int cef_visit_all_cookies(struct _cef_cookie_visitor_t* visitor);
///
// Visit a subset of cookies. The results are filtered by the given url scheme,
// host, domain and path. If |includeHttpOnly| is true (1) HTTP-only cookies
// will also be included in the results. The returned cookies are ordered by
// longest path, then by earliest creation date. Returns false (0) if cookies
// cannot be accessed.
///
CEF_EXPORT int cef_visit_url_cookies(const cef_string_t* url,
int includeHttpOnly, struct _cef_cookie_visitor_t* visitor);
///
// Sets a cookie given a valid URL and explicit user-provided cookie attributes.
// This function expects each attribute to be well-formed. It will check for
// disallowed characters (e.g. the ';' character is disallowed within the cookie
// value attribute) and will return false (0) without setting the cookie if such
// characters are found. This function must be called on the IO thread.
///
CEF_EXPORT int cef_set_cookie(const cef_string_t* url,
const struct _cef_cookie_t* cookie);
///
// Delete all cookies that match the specified parameters. If both |url| and
// |cookie_name| are specified all host and domain cookies matching both values
// will be deleted. If only |url| is specified all host cookies (but not domain
// cookies) irrespective of path will be deleted. If |url| is NULL all cookies
// for all hosts and domains will be deleted. Returns false (0) if a non-NULL
// invalid URL is specified or if cookies cannot be accessed. This function must
// be called on the IO thread.
///
CEF_EXPORT int cef_delete_cookies(const cef_string_t* url,
const cef_string_t* cookie_name);
///
// Sets the directory path that will be used for storing cookie data. If |path|
// is NULL data will be stored in memory only. By default the cookie path is the
// same as the cache path. Returns false (0) if cookies cannot be accessed.
///
CEF_EXPORT int cef_set_cookie_path(const cef_string_t* path);
///
// Visit storage of the specified type. If |origin| is non-NULL only data
// matching that origin will be visited. If |key| is non-NULL only data matching
@ -437,6 +392,81 @@ typedef struct _cef_task_t
} cef_task_t;
///
// Structure used for managing cookies. The functions of this structure may be
// called on any thread unless otherwise indicated.
///
typedef struct _cef_cookie_manager_t
{
// Base structure.
cef_base_t base;
///
// Visit all cookies. The returned cookies are ordered by longest path, then
// by earliest creation date. Returns false (0) if cookies cannot be accessed.
///
int (CEF_CALLBACK *visit_all_cookies)(struct _cef_cookie_manager_t* self,
struct _cef_cookie_visitor_t* visitor);
///
// Visit a subset of cookies. The results are filtered by the given url
// scheme, host, domain and path. If |includeHttpOnly| is true (1) HTTP-only
// cookies will also be included in the results. The returned cookies are
// ordered by longest path, then by earliest creation date. Returns false (0)
// if cookies cannot be accessed.
///
int (CEF_CALLBACK *visit_url_cookies)(struct _cef_cookie_manager_t* self,
const cef_string_t* url, int includeHttpOnly,
struct _cef_cookie_visitor_t* visitor);
///
// Sets a cookie given a valid URL and explicit user-provided cookie
// attributes. This function expects each attribute to be well-formed. It will
// check for disallowed characters (e.g. the ';' character is disallowed
// within the cookie value attribute) and will return false (0) without
// setting the cookie if such characters are found. This function must be
// called on the IO thread.
///
int (CEF_CALLBACK *set_cookie)(struct _cef_cookie_manager_t* self,
const cef_string_t* url, const struct _cef_cookie_t* cookie);
///
// Delete all cookies that match the specified parameters. If both |url| and
// values |cookie_name| are specified all host and domain cookies matching
// both will be deleted. If only |url| is specified all host cookies (but not
// domain cookies) irrespective of path will be deleted. If |url| is NULL all
// cookies for all hosts and domains will be deleted. Returns false (0) if a
// non- NULL invalid URL is specified or if cookies cannot be accessed. This
// function must be called on the IO thread.
///
int (CEF_CALLBACK *delete_cookies)(struct _cef_cookie_manager_t* self,
const cef_string_t* url, const cef_string_t* cookie_name);
///
// Sets the directory path that will be used for storing cookie data. If
// |path| is NULL data will be stored in memory only. Returns false (0) if
// cookies cannot be accessed.
///
int (CEF_CALLBACK *set_storage_path)(struct _cef_cookie_manager_t* self,
const cef_string_t* path);
} cef_cookie_manager_t;
///
// Returns the global cookie manager. By default data will be stored at
// CefSettings.cache_path if specified or in memory otherwise.
///
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_get_global_manager();
///
// Creates a new cookie manager. If |path| is NULL data will be stored in memory
// only. Returns NULL if creation fails.
///
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager(
const cef_string_t* path);
///
// Structure to implement for visiting cookie values. The functions of this
// structure will always be called on the IO thread.
@ -882,8 +912,7 @@ typedef struct _cef_frame_t
cef_string_userfree_t (CEF_CALLBACK *get_name)(struct _cef_frame_t* self);
///
// Returns the globally unique identifier for this frame. This function should
// only be called on the UI thread.
// Returns the globally unique identifier for this frame.
///
long long (CEF_CALLBACK *get_identifier)(struct _cef_frame_t* self);
@ -894,8 +923,7 @@ typedef struct _cef_frame_t
struct _cef_frame_t* (CEF_CALLBACK *get_parent)(struct _cef_frame_t* self);
///
// Returns the URL currently loaded in this frame. This function should only
// be called on the UI thread.
// Returns the URL currently loaded in this frame.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_url)(struct _cef_frame_t* self);
@ -1159,6 +1187,16 @@ typedef struct _cef_request_handler_t
int port, const cef_string_t* realm, const cef_string_t* scheme,
cef_string_t* username, cef_string_t* password);
///
// Called on the IO thread to retrieve the cookie manager. |main_url| is the
// URL of the top-level frame. Cookies managers can be unique per browser or
// shared across multiple browsers. The global cookie manager will be used if
// this function returns NULL.
///
struct _cef_cookie_manager_t* (CEF_CALLBACK *get_cookie_manager)(
struct _cef_request_handler_t* self, struct _cef_browser_t* browser,
const cef_string_t* main_url);
} cef_request_handler_t;
@ -2636,7 +2674,8 @@ typedef struct _cef_scheme_handler_factory_t
///
// Return a new scheme handler instance to handle the request. |browser| will
// be the browser window that initiated the request. If the request was
// initiated using the cef_web_urlrequest_t API |browser| will be NULL.
// initiated using the cef_web_urlrequest_t API |browser| will be NULL. The
// |request| object passed to this function will not contain cookie data.
///
struct _cef_scheme_handler_t* (CEF_CALLBACK *create)(
struct _cef_scheme_handler_factory_t* self,

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +1,28 @@
// Copyright (c) 2008-2009 The Chromium Embedded Framework Authors.
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef _BROWSER_IMPL_H
#define _BROWSER_IMPL_H
#ifndef CEF_LIBCEF_BROWSER_IMPL_H_
#define CEF_LIBCEF_BROWSER_IMPL_H_
#pragma once
#include <map>
#include <string>
#include <vector>
#include "include/cef.h"
#include "webview_host.h"
#include "browser_devtools_agent.h"
#include "browser_devtools_client.h"
#include "browser_webview_delegate.h"
#include "browser_navigation_controller.h"
#include "cef_thread.h"
#include "tracker.h"
#include "libcef/webview_host.h"
#include "libcef/browser_devtools_agent.h"
#include "libcef/browser_devtools_client.h"
#include "libcef/browser_webview_delegate.h"
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_request_context_proxy.h"
#include "libcef/cef_thread.h"
#include "libcef/tracker.h"
#if defined(OS_WIN)
#include "printing/win_printing_context.h"
#include "libcef/printing/win_printing_context.h"
#endif
#include "base/scoped_temp_dir.h"
@ -29,23 +35,23 @@ namespace WebKit {
class WebView;
}
class CefFrameImpl;
#define BUFFER_SIZE 32768
// Implementation of CefBrowser.
class CefBrowserImpl : public CefBrowser
{
public:
class PaintDelegate : public WebWidgetHost::PaintDelegate
{
public:
PaintDelegate(CefBrowserImpl* browser);
class CefBrowserImpl : public CefBrowser {
public:
class PaintDelegate : public WebWidgetHost::PaintDelegate {
public:
explicit PaintDelegate(CefBrowserImpl* browser);
virtual ~PaintDelegate();
virtual void Paint(bool popup, const std::vector<CefRect>& dirtyRects,
const void* buffer) OVERRIDE;
protected:
protected:
CefBrowserImpl* browser_;
};
@ -78,8 +84,7 @@ public:
virtual bool IsPopup() OVERRIDE { return is_popup(); }
virtual bool HasDocument() OVERRIDE { return has_document(); }
virtual CefRefPtr<CefClient> GetClient() OVERRIDE { return client_; }
virtual CefRefPtr<CefFrame> GetMainFrame() OVERRIDE
{ return GetMainCefFrame(); }
virtual CefRefPtr<CefFrame> GetMainFrame() OVERRIDE;
virtual CefRefPtr<CefFrame> GetFocusedFrame() OVERRIDE;
virtual CefRefPtr<CefFrame> GetFrame(const CefString& name) OVERRIDE;
virtual void GetFrameNames(std::vector<CefString>& names) OVERRIDE;
@ -131,28 +136,29 @@ public:
CefRefPtr<CefStreamReader> stream,
const CefString& url);
void ExecuteJavaScript(CefRefPtr<CefFrame> frame,
const CefString& jsCode,
const CefString& jsCode,
const CefString& scriptUrl,
int startLine);
long long GetIdentifier(CefRefPtr<CefFrame> frame);
CefRefPtr<CefFrame> GetParent(CefRefPtr<CefFrame> frame);
CefString GetURL(CefRefPtr<CefFrame> frame);
// CefFrames are light-weight objects managed by the browser and loosely
// coupled to a WebFrame object by name. If a CefFrame object does not
// already exist for the specified name one will be created. There is no
// guarantee that the same CefFrame object will be returned across different
// calls to this function.
CefRefPtr<CefFrame> GetCefFrame(const CefString& name);
void RemoveCefFrame(const CefString& name);
CefRefPtr<CefFrame> GetMainCefFrame();
// coupled to a WebFrame object by id. If a CefFrame object does not already
// exist for the specified id one will be created. There is no guarantee that
// the same CefFrame object will be returned across different calls to this
// function.
CefRefPtr<CefFrameImpl> GetCefFrame(int64 id);
CefRefPtr<CefFrameImpl> GetOrCreateCefFrame(int64 id, const CefString& name,
const GURL& url);
void RemoveCefFrame(int64 id);
CefRefPtr<CefFrameImpl> GetMainCefFrame(int64 id, const GURL& url);
////////////////////////////////////////////////////////////
// ALL UIT_* METHODS MUST ONLY BE CALLED ON THE UI THREAD //
////////////////////////////////////////////////////////////
CefRefPtr<CefFrame> UIT_GetCefFrame(WebKit::WebFrame* frame);
void UIT_UpdateCefFrame(WebKit::WebFrame* frame);
// Return the main WebFrame object.
WebKit::WebFrame* UIT_GetMainWebFrame();
@ -201,7 +207,7 @@ public:
REQUIRE_UIT();
return nav_controller_.get();
}
// Return true to allow user editing such as entering text in form elements
bool UIT_AllowEditing() { return true; }
@ -250,7 +256,7 @@ public:
CefRefPtr<CefStreamReader> stream,
const CefString& url);
void UIT_ExecuteJavaScript(CefRefPtr<CefFrame> frame,
const CefString& js_code,
const CefString& js_code,
const CefString& script_url,
int start_line);
void UIT_GoBackOrForward(int offset);
@ -276,7 +282,7 @@ public:
void UIT_ClosePopupWidget();
void UIT_Show(WebKit::WebNavigationPolicy policy);
// Handles most simple browser actions
void UIT_HandleActionView(cef_menu_id_t menuId);
void UIT_HandleAction(cef_menu_id_t menuId, CefRefPtr<CefFrame> frame);
@ -320,7 +326,7 @@ public:
const FilePath& file_system_root() const { return file_system_root_.path(); }
gfx::NativeView opener_window() { return opener_; }
bool is_popup() { return (opener_ != NULL); }
// These variables may be read/written from multiple threads.
void set_zoom_level(double zoomLevel);
double zoom_level();
@ -330,32 +336,37 @@ public:
void set_has_document(bool has_document);
bool has_document();
// URL currently being loaded in the main frame.
void set_pending_url(const GURL& url);
GURL pending_url();
void set_is_dropping(bool is_dropping) { is_dropping_ = is_dropping; }
bool is_dropping() { return is_dropping_; }
#if defined(OS_WIN)
void set_opener_was_disabled_by_modal_loop(bool disabled)
{
void set_opener_was_disabled_by_modal_loop(bool disabled) {
opener_was_disabled_by_modal_loop_ = disabled;
}
void set_internal_modal_message_loop_is_active(bool active)
{
void set_internal_modal_message_loop_is_active(bool active) {
internal_modal_message_loop_is_active_ = active;
}
#endif
void set_popup_rect(const gfx::Rect& rect) { popup_rect_ = rect; }
net::URLRequestContext* request_context_proxy() {
return request_context_proxy_;
}
static bool ImplementsThreadSafeReferenceCounting() { return true; }
protected:
protected:
static void UIT_CloseView(gfx::NativeView view);
static bool UIT_IsViewVisible(gfx::NativeView view);
void UIT_CreateDevToolsClient(BrowserDevToolsAgent* agent);
void UIT_DestroyDevToolsClient();
protected:
CefWindowInfo window_info_;
CefBrowserSettings settings_;
// Handle of the browser window that opened this window.
@ -373,12 +384,15 @@ protected:
scoped_ptr<BrowserDevToolsAgent> dev_tools_agent_;
scoped_ptr<BrowserDevToolsClient> dev_tools_client_;
scoped_refptr<BrowserRequestContextProxy> request_context_proxy_;
CefString title_;
double zoom_level_;
bool can_go_back_;
bool can_go_forward_;
bool has_document_;
GURL pending_url_;
// True if a drop action is occuring.
bool is_dropping_;
@ -392,9 +406,12 @@ protected:
bool internal_modal_message_loop_is_active_;
#endif
typedef std::map<CefString, CefFrame*> FrameMap;
// Map of frame id to reference.
typedef std::map<int64, CefFrameImpl*> FrameMap;
FrameMap frames_;
CefFrame* main_frame_;
// Singleton main frame reference.
CefRefPtr<CefFrameImpl> main_frame_;
typedef std::map<WebKit::WebFrame*, CefRefPtr<CefTrackManager> >
FrameObjectMap;
@ -402,7 +419,7 @@ protected:
// Unique browser ID assigned by the context.
int unique_id_;
// A temporary directory for FileSystem API.
ScopedTempDir file_system_root_;
@ -412,10 +429,12 @@ protected:
// Implementation of CefFrame.
class CefFrameImpl : public CefFrame
{
public:
CefFrameImpl(CefBrowserImpl* browser, const CefString& name);
class CefFrameImpl : public CefFrame {
public:
CefFrameImpl(CefBrowserImpl* browser,
int64 frame_id,
const CefString& name,
const CefString& url);
virtual ~CefFrameImpl();
// CefFrame methods
@ -430,37 +449,50 @@ public:
virtual void ViewSource() OVERRIDE { browser_->ViewSource(this); }
virtual CefString GetSource() OVERRIDE { return browser_->GetSource(this); }
virtual CefString GetText() OVERRIDE { return browser_->GetText(this); }
virtual void LoadRequest(CefRefPtr<CefRequest> request) OVERRIDE
{ return browser_->LoadRequest(this, request); }
virtual void LoadURL(const CefString& url) OVERRIDE
{ return browser_->LoadURL(this, url); }
virtual void LoadRequest(CefRefPtr<CefRequest> request) OVERRIDE {
return browser_->LoadRequest(this, request);
}
virtual void LoadURL(const CefString& url) OVERRIDE {
return browser_->LoadURL(this, url);
}
virtual void LoadString(const CefString& string,
const CefString& url) OVERRIDE
{ return browser_->LoadString(this, string, url); }
const CefString& url) OVERRIDE {
return browser_->LoadString(this, string, url);
}
virtual void LoadStream(CefRefPtr<CefStreamReader> stream,
const CefString& url) OVERRIDE
{ return browser_->LoadStream(this, stream, url); }
virtual void ExecuteJavaScript(const CefString& jsCode,
const CefString& url) OVERRIDE {
return browser_->LoadStream(this, stream, url);
}
virtual void ExecuteJavaScript(const CefString& jsCode,
const CefString& scriptUrl,
int startLine) OVERRIDE
{ return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine); }
int startLine) OVERRIDE {
return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine);
}
virtual bool IsMain() OVERRIDE { return name_.empty(); }
virtual bool IsFocused() OVERRIDE;
virtual CefString GetName() OVERRIDE { return name_; }
virtual long long GetIdentifier() OVERRIDE
{ return browser_->GetIdentifier(this); }
virtual CefRefPtr<CefFrame> GetParent() OVERRIDE
{ return browser_->GetParent(this); }
virtual CefString GetURL() OVERRIDE { return browser_->GetURL(this); }
virtual int64 GetIdentifier() OVERRIDE;
virtual CefRefPtr<CefFrame> GetParent() OVERRIDE {
return browser_->GetParent(this);
}
virtual CefString GetURL() OVERRIDE;
virtual CefRefPtr<CefBrowser> GetBrowser() OVERRIDE { return browser_.get(); }
virtual void VisitDOM(CefRefPtr<CefDOMVisitor> visitor) OVERRIDE;
virtual CefRefPtr<CefV8Context> GetV8Context() OVERRIDE;
private:
void set_id(int64 id);
void set_url(const CefString& url);
private:
CefRefPtr<CefBrowserImpl> browser_;
CefString name_;
// The below values must be protected by the lock.
base::Lock lock_;
int64 id_;
CefString url_;
IMPLEMENT_REFCOUNTING(CefFrameImpl);
};
#endif // _BROWSER_IMPL_H
#endif // CEF_LIBCEF_BROWSER_IMPL_H_

View File

@ -31,7 +31,7 @@ class BrowserRequestContext : public net::URLRequestContext {
net::HttpCache::Mode cache_mode,
bool no_proxy);
virtual const std::string& GetUserAgent(const GURL& url) const;
virtual const std::string& GetUserAgent(const GURL& url) const OVERRIDE;
void SetAcceptAllCookies(bool accept_all_cookies);
bool AcceptAllCookies();

View File

@ -0,0 +1,44 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/browser_request_context_proxy.h"
#include "libcef/browser_request_context.h"
#include "libcef/cookie_store_proxy.h"
BrowserRequestContextProxy::BrowserRequestContextProxy(
BrowserRequestContext* context,
CefBrowserImpl* browser)
: context_(context),
browser_(browser) {
DCHECK(context_);
DCHECK(browser_);
// Cookie store that proxies to the browser implementation.
set_cookie_store(new CefCookieStoreProxy(browser_));
// All other values refer to the global request context.
set_net_log(context->net_log());
set_host_resolver(context->host_resolver());
set_cert_verifier(context->cert_verifier());
set_origin_bound_cert_service(context->origin_bound_cert_service());
set_fraudulent_certificate_reporter(
context->fraudulent_certificate_reporter());
set_proxy_service(context->proxy_service());
set_ssl_config_service(context->ssl_config_service());
set_http_auth_handler_factory(context->http_auth_handler_factory());
set_http_transaction_factory(context->http_transaction_factory());
set_ftp_transaction_factory(context->ftp_transaction_factory());
set_network_delegate(context->network_delegate());
set_http_server_properties(context->http_server_properties());
set_transport_security_state(context->transport_security_state());
set_accept_charset(context->accept_charset());
set_accept_language(context->accept_language());
set_referrer_charset(context->referrer_charset());
set_job_factory(context->job_factory());
}
const std::string&
BrowserRequestContextProxy::GetUserAgent(const GURL& url) const {
return context_->GetUserAgent(url);
}

View File

@ -0,0 +1,29 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_
#define CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_
#pragma once
#include <string>
#include "net/url_request/url_request_context.h"
class BrowserRequestContext;
class CefBrowserImpl;
// A basic URLRequestContext that only provides an in-memory cookie store.
class BrowserRequestContextProxy : public net::URLRequestContext {
public:
// Use an in-memory cache
BrowserRequestContextProxy(BrowserRequestContext* context,
CefBrowserImpl* browser);
virtual const std::string& GetUserAgent(const GURL& url) const OVERRIDE;
private:
BrowserRequestContext* context_;
CefBrowserImpl* browser_;
};
#endif // CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_

View File

@ -20,10 +20,6 @@
// \ -> net::URLRequest
// o-------> SyncRequestProxy (synchronous case)
// -> net::URLRequest
// SetCookie <------------------------> CookieSetter
// -> net_util::SetCookie
// GetCookies <-----------------------> CookieGetter
// -> net_util::GetCookies
//
// NOTE: The implementation in this file may be used to have WebKit fetch
// resources in-process. For example, it is handy for building a single-
@ -31,19 +27,19 @@
// perform URL loads. See renderer/resource_dispatcher.h for details on an
// alternate implementation that defers fetching to another process.
#include "browser_appcache_system.h"
#include "browser_resource_loader_bridge.h"
#include "browser_request_context.h"
#include "browser_socket_stream_bridge.h"
#include "browser_webkit_glue.h"
#include "browser_impl.h"
#include "cef_context.h"
#include "cef_process.h"
#include "cef_process_io_thread.h"
#include "external_protocol_handler.h"
#include "request_impl.h"
#include "response_impl.h"
#include "http_header_utils.h"
#include "libcef/browser_resource_loader_bridge.h"
#include "libcef/browser_appcache_system.h"
#include "libcef/browser_request_context.h"
#include "libcef/browser_socket_stream_bridge.h"
#include "libcef/browser_webkit_glue.h"
#include "libcef/browser_impl.h"
#include "libcef/cef_context.h"
#include "libcef/cef_process.h"
#include "libcef/cef_process_io_thread.h"
#include "libcef/external_protocol_handler.h"
#include "libcef/request_impl.h"
#include "libcef/response_impl.h"
#include "libcef/http_header_utils.h"
#include "base/bind.h"
#include "base/file_path.h"
@ -51,13 +47,11 @@
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/synchronization/waitable_event.h"
#include "base/time.h"
#include "base/timer.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "net/base/auth.h"
#include "net/base/cookie_store.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
@ -114,40 +108,40 @@ struct RequestParams {
static const int kUpdateUploadProgressIntervalMsec = 100;
class ExtraRequestInfo : public net::URLRequest::UserData {
public:
ExtraRequestInfo(CefBrowser* browser, ResourceType::Type resource_type)
public:
ExtraRequestInfo(CefBrowserImpl* browser, ResourceType::Type resource_type)
: browser_(browser),
resource_type_(resource_type),
allow_download_(resource_type == ResourceType::MAIN_FRAME ||
resource_type == ResourceType::SUB_FRAME)
{ }
allow_download_(resource_type == ResourceType::MAIN_FRAME ||
resource_type == ResourceType::SUB_FRAME) {
}
// The browser pointer is guaranteed to be valid for the lifespan of the
// request. The pointer will be NULL in cases where the request was
// initiated via the CefWebURLRequest API instead of by a browser window.
CefBrowser* browser() const { return browser_; }
CefBrowserImpl* browser() const { return browser_; }
// Identifies the type of resource, such as subframe, media, etc.
ResourceType::Type resource_type() const { return resource_type_; }
bool allow_download() const { return allow_download_; }
private:
CefBrowser* browser_;
private:
CefBrowserImpl* browser_;
ResourceType::Type resource_type_;
bool allow_download_;
};
// Used to intercept redirect requests.
class RequestInterceptor : public net::URLRequest::Interceptor
{
public:
class RequestInterceptor : public net::URLRequest::Interceptor {
public:
RequestInterceptor() {
REQUIRE_IOT();
net::URLRequestJobManager::GetInstance()->RegisterRequestInterceptor(this);
}
~RequestInterceptor() {
REQUIRE_IOT();
net::URLRequestJobManager::GetInstance()->UnregisterRequestInterceptor(this);
net::URLRequestJobManager::GetInstance()->
UnregisterRequestInterceptor(this);
}
virtual net::URLRequestJob* MaybeIntercept(net::URLRequest* request)
@ -195,14 +189,13 @@ class RequestProxy : public net::URLRequest::Delegate,
public base::RefCountedThreadSafe<RequestProxy> {
public:
// Takes ownership of the params.
RequestProxy(CefRefPtr<CefBrowser> browser)
explicit RequestProxy(CefRefPtr<CefBrowserImpl> browser)
: download_to_file_(false),
buf_(new net::IOBuffer(kDataSize)),
browser_(browser),
last_upload_position_(0),
defers_loading_(false),
defers_loading_want_read_(false)
{
defers_loading_want_read_(false) {
}
void DropPeer() {
@ -221,7 +214,7 @@ class RequestProxy : public net::URLRequest::Delegate,
}
void Cancel() {
if(download_handler_.get()) {
if (download_handler_.get()) {
// WebKit will try to cancel the download but we won't allow it.
return;
}
@ -270,13 +263,12 @@ class RequestProxy : public net::URLRequest::Delegate,
void NotifyReceivedResponse(const ResourceResponseInfo& info,
const GURL& url, bool allow_download) {
if (browser_.get() && info.headers.get()) {
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefRequestHandler> handler;
if (client.get())
handler = client->GetRequestHandler();
if (handler.get()) {
CefRefPtr<CefResponse> response = new CefResponseImpl();
// Transfer response headers
@ -294,7 +286,7 @@ class RequestProxy : public net::URLRequest::Delegate,
response->SetStatus(info.headers->response_code());
}
response->SetMimeType(info.mime_type);
handler->OnResourceResponse(browser_, url.spec(), response,
handler->OnResourceResponse(browser_.get(), url.spec(), response,
content_filter_);
std::string content_disposition;
@ -307,7 +299,7 @@ class RequestProxy : public net::URLRequest::Delegate,
content_disposition, info.charset, "", info.mime_type,
"download");
CefRefPtr<CefDownloadHandler> dl_handler;
if (handler->GetDownloadHandler(browser_, info.mime_type,
if (handler->GetDownloadHandler(browser_.get(), info.mime_type,
filename, info.content_length,
dl_handler)) {
download_handler_ = dl_handler;
@ -340,9 +332,9 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefStreamReader> resourceStream;
if(content_filter_.get())
if (content_filter_.get())
content_filter_->ProcessData(buf_copy.get(), bytes_read, resourceStream);
if (resourceStream.get()) {
// The filter made some changes to the data in the buffer.
resourceStream->Seek(0, SEEK_END);
@ -377,13 +369,12 @@ class RequestProxy : public net::URLRequest::Delegate,
void NotifyCompletedRequest(const net::URLRequestStatus& status,
const std::string& security_info,
const base::Time& complete_time) {
// Drain the content filter of all remaining data
// Drain the content filter of all remaining data
if (content_filter_.get()) {
CefRefPtr<CefStreamReader> remainder;
content_filter_->Drain(remainder);
if(remainder.get()) {
if (remainder.get()) {
remainder->Seek(0, SEEK_END);
long size = remainder->Tell();
if (size) {
@ -433,8 +424,8 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefRequestHandler> handler;
if (client.get())
handler = client->GetRequestHandler();
if(handler.get()) {
if (handler.get()) {
// Build the request object for passing to the handler
CefRefPtr<CefRequest> request(new CefRequestImpl());
CefRequestImpl* requestimpl =
@ -443,7 +434,7 @@ class RequestProxy : public net::URLRequest::Delegate,
std::string originalUrl(params->url.spec());
requestimpl->SetURL(originalUrl);
requestimpl->SetMethod(params->method);
// Transfer request headers
CefRequest::HeaderMap headerMap;
HttpHeaderUtils::ParseHeaders(params->headers, headerMap);
@ -452,7 +443,7 @@ class RequestProxy : public net::URLRequest::Delegate,
// Transfer post data, if any
scoped_refptr<net::UploadData> upload = params->upload;
if(upload.get()) {
if (upload.get()) {
CefRefPtr<CefPostData> postdata(new CefPostDataImpl());
static_cast<CefPostDataImpl*>(postdata.get())->Set(*upload.get());
requestimpl->SetPostData(postdata);
@ -465,8 +456,8 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefStreamReader> resourceStream;
CefRefPtr<CefResponse> response(new CefResponseImpl());
handled = handler->OnBeforeResourceLoad(browser_, request, redirectUrl,
resourceStream, response, loadFlags);
handled = handler->OnBeforeResourceLoad(browser_.get(), request,
redirectUrl, resourceStream, response, loadFlags);
if (!handled) {
// Observe URL from request.
const std::string requestUrl(request->GetURL());
@ -482,8 +473,9 @@ class RequestProxy : public net::URLRequest::Delegate,
request->GetHeaderMap(headerMap);
CefString referrerStr;
referrerStr.FromASCII("Referrer");
CefRequest::HeaderMap::iterator referrer = headerMap.find(referrerStr);
if(referrer == headerMap.end()) {
CefRequest::HeaderMap::iterator referrer =
headerMap.find(referrerStr);
if (referrer == headerMap.end()) {
params->referrer = GURL();
} else {
params->referrer = GURL(std::string(referrer->second));
@ -493,7 +485,7 @@ class RequestProxy : public net::URLRequest::Delegate,
// Observe post data from request.
CefRefPtr<CefPostData> postData = request->GetPostData();
if(postData.get()) {
if (postData.get()) {
params->upload = new net::UploadData();
static_cast<CefPostDataImpl*>(postData.get())->Get(*params->upload);
}
@ -541,8 +533,8 @@ class RequestProxy : public net::URLRequest::Delegate,
if (!handled && ResourceType::IsFrame(params->request_type) &&
!net::URLRequest::IsHandledProtocol(params->url.scheme())) {
bool allow_os_execution = false;
handled = handler->OnProtocolExecution(browser_, params->url.spec(),
allow_os_execution);
handled = handler->OnProtocolExecution(browser_.get(),
params->url.spec(), allow_os_execution);
if (!handled && allow_os_execution &&
ExternalProtocolHandler::HandleExternalProtocol(params->url)) {
handled = true;
@ -551,13 +543,13 @@ class RequestProxy : public net::URLRequest::Delegate,
if (handled) {
OnCompletedRequest(
URLRequestStatus(URLRequestStatus::HANDLED_EXTERNALLY, net::OK),
std::string(), base::Time());
std::string(), base::Time());
}
}
}
}
if(!handled) {
if (!handled) {
// Might need to resolve the blob references in the upload data.
if (params->upload) {
_Context->request_context()->blob_storage_controller()->
@ -574,7 +566,8 @@ class RequestProxy : public net::URLRequest::Delegate,
request_->SetExtraRequestHeaders(headers);
request_->set_load_flags(params->load_flags);
request_->set_upload(params->upload.get());
request_->set_context(_Context->request_context());
request_->set_context(browser_.get() ? browser_->request_context_proxy() :
_Context->request_context());
request_->SetUserData(kCefUserData,
new ExtraRequestInfo(browser_.get(), params->request_type));
BrowserAppCacheSystem::SetExtraRequestInfo(
@ -644,10 +637,10 @@ class RequestProxy : public net::URLRequest::Delegate,
return;
}
if(resource_stream_.get()) {
if (resource_stream_.get()) {
// Read from the handler-provided resource stream
int bytes_read = resource_stream_->Read(buf_->data(), 1, kDataSize);
if(bytes_read > 0) {
if (bytes_read > 0) {
OnReceivedData(bytes_read);
} else {
Done();
@ -691,7 +684,7 @@ class RequestProxy : public net::URLRequest::Delegate,
const GURL& simulated_url) {
GURL url;
bool allow_download(false);
if (request_.get()){
if (request_.get()) {
url = request_->url();
ExtraRequestInfo* info =
static_cast<ExtraRequestInfo*>(request_->GetUserData(kCefUserData));
@ -713,7 +706,7 @@ class RequestProxy : public net::URLRequest::Delegate,
&RequestProxy::NotifyDownloadedData, this, bytes_read));
return;
}
owner_loop_->PostTask(FROM_HERE, base::Bind(
&RequestProxy::NotifyReceivedData, this, bytes_read));
}
@ -758,9 +751,9 @@ class RequestProxy : public net::URLRequest::Delegate,
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
if(handler.get()) {
if (handler.get()) {
CefString username, password;
if (handler->GetAuthCredentials(browser_,
if (handler->GetAuthCredentials(browser_.get(),
auth_info->is_proxy,
auth_info->challenger.host(),
auth_info->challenger.port(),
@ -825,12 +818,12 @@ class RequestProxy : public net::URLRequest::Delegate,
// Helpers and data:
void Done() {
if(resource_stream_.get()) {
if (resource_stream_.get()) {
// Resource stream reads always complete successfully
OnCompletedRequest(URLRequestStatus(URLRequestStatus::SUCCESS, 0),
std::string(), base::Time());
resource_stream_ = NULL;
} else if(request_.get()) {
} else if (request_.get()) {
if (upload_progress_timer_.IsRunning()) {
MaybeUpdateUploadProgress();
upload_progress_timer_.Stop();
@ -907,7 +900,7 @@ class RequestProxy : public net::URLRequest::Delegate,
// read buffer for async IO
scoped_refptr<net::IOBuffer> buf_;
CefRefPtr<CefBrowser> browser_;
CefRefPtr<CefBrowserImpl> browser_;
MessageLoop* owner_loop_;
@ -937,7 +930,7 @@ class RequestProxy : public net::URLRequest::Delegate,
class SyncRequestProxy : public RequestProxy {
public:
explicit SyncRequestProxy(CefRefPtr<CefBrowser> browser,
explicit SyncRequestProxy(CefRefPtr<CefBrowserImpl> browser,
ResourceLoaderBridge::SyncLoadResponse* result)
: RequestProxy(browser), result_(result), event_(true, false) {
}
@ -982,7 +975,7 @@ class SyncRequestProxy : public RequestProxy {
const base::Time& complete_time) {
if (download_to_file_)
file_stream_.Close();
result_->status = status;
event_.Signal();
}
@ -1004,7 +997,7 @@ class SyncRequestProxy : public RequestProxy {
class ResourceLoaderBridgeImpl : public ResourceLoaderBridge {
public:
ResourceLoaderBridgeImpl(CefRefPtr<CefBrowser> browser,
ResourceLoaderBridgeImpl(CefRefPtr<CefBrowserImpl> browser,
const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info)
: browser_(browser),
params_(new RequestParams),
@ -1102,7 +1095,7 @@ class ResourceLoaderBridgeImpl : public ResourceLoaderBridge {
virtual void UpdateRoutingId(int new_routing_id) OVERRIDE {}
private:
CefRefPtr<CefBrowser> browser_;
CefRefPtr<CefBrowserImpl> browser_;
// Ownership of params_ is transfered to the proxy when the proxy is created.
scoped_ptr<RequestParams> params_;
@ -1112,61 +1105,6 @@ class ResourceLoaderBridgeImpl : public ResourceLoaderBridge {
RequestProxy* proxy_;
};
//-----------------------------------------------------------------------------
class CookieSetter : public base::RefCountedThreadSafe<CookieSetter> {
public:
void Set(const GURL& url, const std::string& cookie) {
REQUIRE_IOT();
net::CookieStore* cookie_store =
_Context->request_context()->cookie_store();
if (cookie_store) {
cookie_store->SetCookieWithOptionsAsync(
url, cookie, net::CookieOptions(),
net::CookieStore::SetCookiesCallback());
}
}
private:
friend class base::RefCountedThreadSafe<CookieSetter>;
~CookieSetter() {}
};
class CookieGetter : public base::RefCountedThreadSafe<CookieGetter> {
public:
CookieGetter() : event_(false, false) {
}
void Get(const GURL& url) {
REQUIRE_IOT();
net::CookieStore* cookie_store =
_Context->request_context()->cookie_store();
if (cookie_store) {
cookie_store->GetCookiesWithOptionsAsync(
url, net::CookieOptions(),
base::Bind(&CookieGetter::OnGetCookies, this));
}
}
std::string GetResult() {
event_.Wait();
return result_;
}
private:
void OnGetCookies(const std::string& cookie_line) {
result_ = cookie_line;
event_.Signal();
}
friend class base::RefCountedThreadSafe<CookieGetter>;
~CookieGetter() {}
base::WaitableEvent event_;
std::string result_;
};
} // anonymous namespace
//-----------------------------------------------------------------------------
@ -1182,37 +1120,7 @@ webkit_glue::ResourceLoaderBridge* BrowserResourceLoaderBridge::Create(
//-----------------------------------------------------------------------------
// static
void BrowserResourceLoaderBridge::SetCookie(const GURL& url,
const GURL& first_party_for_cookies,
const std::string& cookie) {
// Proxy to IO thread to synchronize w/ network loading.
scoped_refptr<CookieSetter> cookie_setter = new CookieSetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieSetter::Set, cookie_setter.get(), url, cookie));
}
// static
std::string BrowserResourceLoaderBridge::GetCookies(
const GURL& url, const GURL& first_party_for_cookies) {
// Proxy to IO thread to synchronize w/ network loading.
scoped_refptr<CookieGetter> cookie_getter = new CookieGetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieGetter::Get, cookie_getter.get(), url));
// Blocks until the result is available.
return cookie_getter->GetResult();
}
// static
void BrowserResourceLoaderBridge::SetAcceptAllCookies(bool accept_all_cookies) {
// Proxy to IO thread to synchronize w/ network loading.
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&BrowserRequestContext::SetAcceptAllCookies,
_Context->request_context().get(), accept_all_cookies));
}
// static
CefRefPtr<CefBrowser> BrowserResourceLoaderBridge::GetBrowserForRequest(
CefRefPtr<CefBrowserImpl> BrowserResourceLoaderBridge::GetBrowserForRequest(
net::URLRequest* request) {
REQUIRE_IOT();
ExtraRequestInfo* extra_info =
@ -1222,13 +1130,13 @@ CefRefPtr<CefBrowser> BrowserResourceLoaderBridge::GetBrowserForRequest(
return NULL;
}
//static
// static
scoped_refptr<base::MessageLoopProxy>
BrowserResourceLoaderBridge::GetCacheThread() {
return CefThread::GetMessageLoopProxyForThread(CefThread::FILE);
}
//static
// static
net::URLRequest::Interceptor*
BrowserResourceLoaderBridge::CreateRequestInterceptor() {
return new RequestInterceptor();

View File

@ -3,31 +3,27 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef _BROWSER_RESOURCE_LOADER_BRIDGE_H
#define _BROWSER_RESOURCE_LOADER_BRIDGE_H
#ifndef CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_
#define CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_
#pragma once
#include <string>
#include "include/cef.h"
#include "base/message_loop_proxy.h"
#include "net/url_request/url_request.h"
#include "webkit/glue/resource_loader_bridge.h"
#include <string>
class CefBrowserImpl;
class GURL;
class BrowserResourceLoaderBridge {
public:
// May only be called after Init.
static void SetCookie(const GURL& url,
const GURL& first_party_for_cookies,
const std::string& cookie);
static std::string GetCookies(const GURL& url,
const GURL& first_party_for_cookies);
static void SetAcceptAllCookies(bool accept_all_cookies);
// Return the CefBrowser associated with the specified request. The browser
// will be NULL in cases where the request was initiated using the
// CefWebURLRequest API.
static CefRefPtr<CefBrowser> GetBrowserForRequest(net::URLRequest* request);
static CefRefPtr<CefBrowserImpl> GetBrowserForRequest(
net::URLRequest* request);
// Creates a ResourceLoaderBridge instance.
static webkit_glue::ResourceLoaderBridge* Create(
@ -40,5 +36,5 @@ class BrowserResourceLoaderBridge {
static net::URLRequest::Interceptor* CreateRequestInterceptor();
};
#endif // _BROWSER_RESOURCE_LOADER_BRIDGE_H
#endif // CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_

View File

@ -1,25 +1,139 @@
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Copyright (c) 2012 the Chromium Embedded Framework authors.
// Portions copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser_webcookiejar_impl.h"
#include "browser_resource_loader_bridge.h"
#include "libcef/browser_webcookiejar_impl.h"
#include <string>
#include "libcef/browser_resource_loader_bridge.h"
#include "libcef/browser_impl.h"
#include "libcef/cookie_manager_impl.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "base/synchronization/waitable_event.h"
#include "net/base/cookie_store.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h"
using WebKit::WebString;
using WebKit::WebURL;
namespace {
net::CookieStore* GetCookieStore(CefRefPtr<CefBrowserImpl> browser) {
scoped_refptr<net::CookieStore> cookie_store;
if (browser) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
if (handler.get()) {
// Get the manager from the handler.
CefRefPtr<CefCookieManager> manager =
handler->GetCookieManager(browser.get(),
browser->pending_url().spec());
if (manager.get()) {
cookie_store =
reinterpret_cast<CefCookieManagerImpl*>(
manager.get())->cookie_monster();
}
}
}
}
if (!cookie_store) {
// Use the global cookie store.
cookie_store = _Context->request_context()->cookie_store();
}
DCHECK(cookie_store);
return cookie_store;
}
class CookieSetter : public base::RefCountedThreadSafe<CookieSetter> {
public:
void Set(CefRefPtr<CefBrowserImpl> browser,
const GURL& url,
const std::string& cookie) {
REQUIRE_IOT();
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore(browser);
cookie_store->SetCookieWithOptionsAsync(
url, cookie, net::CookieOptions(),
net::CookieStore::SetCookiesCallback());
}
private:
friend class base::RefCountedThreadSafe<CookieSetter>;
~CookieSetter() {}
};
class CookieGetter : public base::RefCountedThreadSafe<CookieGetter> {
public:
CookieGetter() : event_(false, false) {
}
void Get(CefRefPtr<CefBrowserImpl> browser, const GURL& url) {
REQUIRE_IOT();
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore(browser);
cookie_store->GetCookiesWithOptionsAsync(
url, net::CookieOptions(),
base::Bind(&CookieGetter::OnGetCookies, this));
}
std::string GetResult() {
event_.Wait();
return result_;
}
private:
void OnGetCookies(const std::string& cookie_line) {
result_ = cookie_line;
event_.Signal();
}
friend class base::RefCountedThreadSafe<CookieGetter>;
~CookieGetter() {}
base::WaitableEvent event_;
std::string result_;
};
} // namespace
BrowserWebCookieJarImpl::BrowserWebCookieJarImpl()
: browser_(NULL) {
}
BrowserWebCookieJarImpl::BrowserWebCookieJarImpl(CefBrowserImpl* browser)
: browser_(browser) {
}
void BrowserWebCookieJarImpl::setCookie(const WebURL& url,
const WebURL& first_party_for_cookies,
const WebString& value) {
BrowserResourceLoaderBridge::SetCookie(
url, first_party_for_cookies, value.utf8());
const WebURL& first_party_for_cookies,
const WebString& value) {
GURL gurl = url;
std::string cookie = value.utf8();
// Proxy to IO thread to synchronize w/ network loading.
scoped_refptr<CookieSetter> cookie_setter = new CookieSetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieSetter::Set, cookie_setter.get(), browser_, gurl, cookie));
}
WebString BrowserWebCookieJarImpl::cookies(
const WebURL& url,
const WebURL& first_party_for_cookies) {
return WebString::fromUTF8(
BrowserResourceLoaderBridge::GetCookies(url, first_party_for_cookies));
GURL gurl = url;
// Proxy to IO thread to synchronize w/ network loading.
scoped_refptr<CookieGetter> cookie_getter = new CookieGetter();
CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind(
&CookieGetter::Get, cookie_getter.get(), browser_, gurl));
// Blocks until the result is available.
return WebString::fromUTF8(cookie_getter->GetResult());
}

View File

@ -1,22 +1,36 @@
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Copyright (c) 2012 the Chromium Embedded Framework authors.
// Portions copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef _BROWSER_SIMPLE_WEBCOOKIEJAR_IMPL_H
#define _BROWSER_SIMPLE_WEBCOOKIEJAR_IMPL_H
#ifndef CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_
#define CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_
#pragma once
// TODO(darin): WebCookieJar.h is missing a WebString.h include!
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCookieJar.h"
namespace net {
class CookieStore;
}
class CefBrowserImpl;
// Handles cookie requests from the renderer.
class BrowserWebCookieJarImpl : public WebKit::WebCookieJar {
public:
// WebKit::WebCookieJar methods:
BrowserWebCookieJarImpl();
explicit BrowserWebCookieJarImpl(CefBrowserImpl* browser);
// WebKit::WebCookieJar methods.
virtual void setCookie(
const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies,
const WebKit::WebString& cookie);
virtual WebKit::WebString cookies(
const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies);
private:
// May be NULL for the global implementation.
CefBrowserImpl* browser_;
};
#endif // _BROWSER_SIMPLE_WEBCOOKIEJAR_IMPL_H
#endif // CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_

View File

@ -7,18 +7,22 @@
// as the WebViewDelegate for the BrowserWebHost. The host is expected to
// have initialized a MessageLoop before these methods are called.
#include "browser_webview_delegate.h"
#include "browser_appcache_system.h"
#include "browser_file_system.h"
#include "browser_impl.h"
#include "browser_navigation_controller.h"
#include "browser_webkit_glue.h"
#include "browser_webstoragenamespace_impl.h"
#include "browser_zoom_map.h"
#include "cef_context.h"
#include "dom_document_impl.h"
#include "request_impl.h"
#include "v8_impl.h"
#include "libcef/browser_webview_delegate.h"
#include <algorithm>
#include "libcef/browser_appcache_system.h"
#include "libcef/browser_file_system.h"
#include "libcef/browser_impl.h"
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_webkit_glue.h"
#include "libcef/browser_webstoragenamespace_impl.h"
#include "libcef/browser_zoom_map.h"
#include "libcef/cef_context.h"
#include "libcef/cef_process_ui_thread.h"
#include "libcef/dom_document_impl.h"
#include "libcef/request_impl.h"
#include "libcef/v8_impl.h"
#include "base/debug/trace_event.h"
#include "base/file_util.h"
@ -72,8 +76,8 @@
#include "webkit/plugins/npapi/webplugin_impl.h"
#if defined(OS_WIN)
#include "browser_drag_delegate_win.h"
#include "web_drop_target_win.h"
#include "libcef/browser_drag_delegate_win.h"
#include "libcef/web_drop_target_win.h"
#endif
using appcache::WebApplicationCacheHostImpl;
@ -124,8 +128,7 @@ namespace {
int next_page_id_ = 1;
void TranslatePopupFeatures(const WebWindowFeatures& webKitFeatures,
CefPopupFeatures& features)
{
CefPopupFeatures& features) {
features.x = static_cast<int>(webKitFeatures.x);
features.xSet = webKitFeatures.xSet;
features.y = static_cast<int>(webKitFeatures.y);
@ -143,13 +146,13 @@ void TranslatePopupFeatures(const WebWindowFeatures& webKitFeatures,
features.resizable = webKitFeatures.resizable;
features.fullscreen = webKitFeatures.fullscreen;
features.dialog = webKitFeatures.dialog;
features.dialog = webKitFeatures.dialog;
features.additionalFeatures = NULL;
if (webKitFeatures.additionalFeatures.size() > 0)
if (webKitFeatures.additionalFeatures.size() > 0)
features.additionalFeatures = cef_string_list_alloc();
CefString str;
for(unsigned int i = 0; i < webKitFeatures.additionalFeatures.size(); ++i) {
for (unsigned int i = 0; i < webKitFeatures.additionalFeatures.size(); ++i) {
str = string16(webKitFeatures.additionalFeatures[i]);
cef_string_list_append(features.additionalFeatures, str.GetStruct());
}
@ -201,7 +204,7 @@ void BrowserWebViewDelegate::didAddMessageToConsole(
}
}
if(!handled) {
if (!handled) {
logging::LogMessage("CONSOLE", 0).stream() << "\""
<< messageStr
<< ",\" source: "
@ -289,8 +292,8 @@ bool BrowserWebViewDelegate::runFileChooser(
WebKit::WebFileChooserCompletion* chooser_completion) {
// Support file open dialog.
std::vector<FilePath> file_names;
if(!ShowFileChooser(file_names, params.multiSelect, params.title,
if (!ShowFileChooser(file_names, params.multiSelect, params.title,
webkit_glue::WebStringToFilePath(params.initialValue))) {
return false;
}
@ -309,7 +312,7 @@ void BrowserWebViewDelegate::runModalAlertDialog(
WebFrame* frame, const WebString& message) {
CefString messageStr = string16(message);
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefJSDialogHandler> handler;
if (client.get())
@ -328,7 +331,7 @@ bool BrowserWebViewDelegate::runModalConfirmDialog(
CefString messageStr = string16(message);
bool retval = false;
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefJSDialogHandler> handler;
if (client.get())
@ -349,12 +352,12 @@ bool BrowserWebViewDelegate::runModalPromptDialog(
CefString messageStr = string16(message);
CefString defaultValueStr = string16(default_value);
CefString actualValueStr;
if(actual_value)
if (actual_value)
actualValueStr = string16(*actual_value);
bool retval = false;
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefJSDialogHandler> handler;
if (client.get())
@ -370,7 +373,7 @@ bool BrowserWebViewDelegate::runModalPromptDialog(
}
if (actual_value)
*actual_value = string16(actualValueStr);
return retval;
}
@ -392,8 +395,7 @@ void BrowserWebViewDelegate::setKeyboardFocusURL(const WebKit::WebURL& url) {
}
void BrowserWebViewDelegate::setToolTipText(
const WebString& text, WebTextDirection hint)
{
const WebString& text, WebTextDirection hint) {
CefString tooltipStr = string16(text);
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
@ -496,7 +498,7 @@ bool BrowserWebViewDelegate::allowScriptExtension(
// WebPluginPageDelegate -----------------------------------------------------
WebCookieJar* BrowserWebViewDelegate::GetCookieJar() {
return WebKit::webKitPlatformSupport()->cookieJar();
return &cookie_jar_;
}
// WebWidgetClient -----------------------------------------------------------
@ -596,7 +598,7 @@ WebPlugin* BrowserWebViewDelegate::createPlugin(
NULL, &plugins, &mime_types);
if (plugins.empty())
return NULL;
#if defined(OS_MACOSX)
// Mac does not supported windowed plugins.
bool force_windowless = true;
@ -675,6 +677,10 @@ WebApplicationCacheHost* BrowserWebViewDelegate::createApplicationCacheHost(
return BrowserAppCacheSystem::CreateApplicationCacheHost(client);
}
WebKit::WebCookieJar* BrowserWebViewDelegate::cookieJar(WebFrame* frame) {
return &cookie_jar_;
}
void BrowserWebViewDelegate::willClose(WebFrame* frame) {
browser_->UIT_BeforeFrameClosed(frame);
}
@ -709,7 +715,7 @@ WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation(
req->SetMethod(string16(request.httpMethod()));
const WebKit::WebHTTPBody& httpBody = request.httpBody();
if(!httpBody.isNull()) {
if (!httpBody.isNull()) {
CefRefPtr<CefPostData> postdata(CefPostData::CreatePostData());
static_cast<CefPostDataImpl*>(postdata.get())->Set(httpBody);
req->SetPostData(postdata);
@ -717,7 +723,7 @@ WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation(
CefRequest::HeaderMap map;
CefRequestImpl::GetHeaderMap(request, map);
if(map.size() > 0)
if (map.size() > 0)
static_cast<CefRequestImpl*>(req.get())->SetHeaderMap(map);
cef_handler_navtype_t navType;
@ -730,7 +736,7 @@ WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation(
bool handled = handler->OnBeforeBrowse(browser_,
browser_->UIT_GetCefFrame(frame), req, navType,
is_redirect);
if(handled)
if (handled)
return WebKit::WebNavigationPolicyIgnore;
}
}
@ -769,6 +775,12 @@ WebURLError BrowserWebViewDelegate::cancelledError(
void BrowserWebViewDelegate::didCreateDataSource(
WebFrame* frame, WebDataSource* ds) {
ds->setExtraData(pending_extra_data_.release());
if (frame->parent() == 0) {
GURL url = ds->request().url();
if (!url.is_empty())
browser_->set_pending_url(url);
}
}
void BrowserWebViewDelegate::didStartProvisionalLoad(WebFrame* frame) {
@ -790,7 +802,7 @@ void BrowserWebViewDelegate::didFailProvisionalLoad(
const WebDataSource* failed_ds = frame->provisionalDataSource();
BrowserExtraData* extra_data =
static_cast<BrowserExtraData*>(failed_ds->extraData());
if (extra_data && !extra_data->request_committed) {
// Set the pending extra_data for our error page as the same pending_page_id
// to keep the history from getting messed up.
@ -801,7 +813,7 @@ void BrowserWebViewDelegate::didFailProvisionalLoad(
CefString errorStr;
bool handled = false;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefLoadHandler> handler = client->GetLoadHandler();
@ -813,8 +825,8 @@ void BrowserWebViewDelegate::didFailProvisionalLoad(
std::string(failed_ds->request().url().spec().data()), errorStr);
}
}
if(handled && !errorStr.empty()) {
if (handled && !errorStr.empty()) {
error_text = errorStr;
} else {
error_text = base::StringPrintf("Error %d when loading url %s",
@ -957,22 +969,22 @@ void BrowserWebViewDelegate::didChangeContentsSize(
}
void BrowserWebViewDelegate::reportFindInPageMatchCount(
int request_id, int count, bool final_update)
{
int request_id, int count, bool final_update) {
browser_->UIT_NotifyFindStatus(request_id, count, gfx::Rect(),
-1, // Don't update active match ordinal.
final_update);
}
void BrowserWebViewDelegate::reportFindInPageSelection(
int request_id, int active_match_ordinal, const WebKit::WebRect& sel)
{
int request_id, int active_match_ordinal, const WebKit::WebRect& sel) {
browser_->UIT_NotifyFindStatus(request_id, -1, sel, active_match_ordinal,
false);
}
void BrowserWebViewDelegate::openFileSystem(
WebFrame* frame, WebFileSystem::Type type, long long size, bool create,
WebFrame* frame, WebFileSystem::Type type,
long long size, // NOLINT(runtime/int)
bool create,
WebFileSystemCallbacks* callbacks) {
BrowserFileSystem* fileSystem = static_cast<BrowserFileSystem*>(
WebKit::webKitPlatformSupport()->fileSystem());
@ -994,7 +1006,8 @@ BrowserWebViewDelegate::BrowserWebViewDelegate(CefBrowserImpl* browser)
#else
select_trailing_whitespace_enabled_(false),
#endif
block_redirects_(false) {
block_redirects_(false),
cookie_jar_(browser) {
}
BrowserWebViewDelegate::~BrowserWebViewDelegate() {
@ -1004,7 +1017,7 @@ void BrowserWebViewDelegate::Reset() {
// Do a little placement new dance...
CefBrowserImpl* browser = browser_;
this->~BrowserWebViewDelegate();
new (this) BrowserWebViewDelegate(browser);
new (this)BrowserWebViewDelegate(browser); // NOLINT(whitespace/parens)
}
void BrowserWebViewDelegate::SetSmartInsertDeleteEnabled(bool enabled) {
@ -1035,8 +1048,7 @@ void BrowserWebViewDelegate::WaitForPolicyDelegate() {
// Private methods -----------------------------------------------------------
bool BrowserWebViewDelegate::OnKeyboardEvent(
const WebKit::WebKeyboardEvent& event, bool isAfterJavaScript)
{
const WebKit::WebKeyboardEvent& event, bool isAfterJavaScript) {
CefRefPtr<CefClient> client = browser_->GetClient();
CefRefPtr<CefKeyboardHandler> handler;
if (client.get())
@ -1046,10 +1058,10 @@ bool BrowserWebViewDelegate::OnKeyboardEvent(
CefKeyboardHandler::KeyEventType eventType;
switch (event.type) {
case WebKeyboardEvent::RawKeyDown:
case WebKeyboardEvent::RawKeyDown:
eventType = KEYEVENT_RAWKEYDOWN;
break;
case WebKeyboardEvent::KeyDown:
case WebKeyboardEvent::KeyDown:
eventType = KEYEVENT_KEYDOWN;
break;
case WebKeyboardEvent::KeyUp:
@ -1067,8 +1079,7 @@ bool BrowserWebViewDelegate::OnKeyboardEvent(
}
void BrowserWebViewDelegate::ShowStatus(const WebString& text,
cef_handler_statustype_t type)
{
cef_handler_statustype_t type) {
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefDisplayHandler> handler = client->GetDisplayHandler();
@ -1083,7 +1094,7 @@ void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) {
CefRefPtr<CefClient> client = browser_->GetClient();
if (!client.get())
return;
bool is_main_frame = (frame->parent() == 0);
if (is_main_frame) {
CefString title = browser_->UIT_GetTitle();
@ -1163,6 +1174,9 @@ void BrowserWebViewDelegate::UpdateURL(WebFrame* frame) {
entry->SetURL(request.url());
}
// Update attributes of the CefFrame if it currently exists.
browser_->UIT_UpdateCefFrame(frame);
bool is_main_frame = (frame->parent() == 0);
CefRefPtr<CefClient> client = browser_->GetClient();
@ -1211,7 +1225,7 @@ void BrowserWebViewDelegate::UpdateSessionHistory(WebFrame* frame) {
return;
WebView* view = browser_->UIT_GetWebView();
if (!view)
if (!view)
return;
const WebHistoryItem& history_item = view->mainFrame()->previousHistoryItem();
@ -1226,30 +1240,30 @@ bool BrowserWebViewDelegate::OnBeforeMenu(
int& edit_flags, int& type_flags) {
// Populate the edit flags values.
edit_flags = data.editFlags;
if(browser_->UIT_CanGoBack())
if (browser_->UIT_CanGoBack())
edit_flags |= MENU_CAN_GO_BACK;
if(browser_->UIT_CanGoForward())
if (browser_->UIT_CanGoForward())
edit_flags |= MENU_CAN_GO_FORWARD;
// Populate the type flags values.
type_flags = MENUTYPE_NONE;
if(!data.pageURL.isEmpty())
if (!data.pageURL.isEmpty())
type_flags |= MENUTYPE_PAGE;
if(!data.frameURL.isEmpty())
if (!data.frameURL.isEmpty())
type_flags |= MENUTYPE_FRAME;
if(!data.linkURL.isEmpty())
if (!data.linkURL.isEmpty())
type_flags |= MENUTYPE_LINK;
if(data.mediaType == WebContextMenuData::MediaTypeImage)
if (data.mediaType == WebContextMenuData::MediaTypeImage)
type_flags |= MENUTYPE_IMAGE;
if(!data.selectedText.isEmpty())
if (!data.selectedText.isEmpty())
type_flags |= MENUTYPE_SELECTION;
if(data.isEditable)
if (data.isEditable)
type_flags |= MENUTYPE_EDITABLE;
if(data.isSpellCheckingEnabled && !data.misspelledWord.isEmpty())
if (data.isSpellCheckingEnabled && !data.misspelledWord.isEmpty())
type_flags |= MENUTYPE_MISSPELLED_WORD;
if(data.mediaType == WebContextMenuData::MediaTypeVideo)
if (data.mediaType == WebContextMenuData::MediaTypeVideo)
type_flags |= MENUTYPE_VIDEO;
if(data.mediaType == WebContextMenuData::MediaTypeAudio)
if (data.mediaType == WebContextMenuData::MediaTypeAudio)
type_flags |= MENUTYPE_AUDIO;
CefRefPtr<CefClient> client = browser_->GetClient();
@ -1290,6 +1304,6 @@ bool BrowserWebViewDelegate::OnBeforeMenu(
if (handler->OnBeforeMenu(browser_, menuInfo))
return true;
}
return false;
}

View File

@ -3,17 +3,23 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// BrowserWebViewDelegate class:
// BrowserWebViewDelegate class:
// This class implements the WebViewDelegate methods for the test shell. One
// instance is owned by each CefBrowser.
#ifndef _BROWSER_WEBVIEW_DELEGATE_H
#define _BROWSER_WEBVIEW_DELEGATE_H
#ifndef CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_
#define CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_
#pragma once
#include <map>
#include <string>
#include <vector>
#include "libcef/browser_navigation_controller.h"
#include "libcef/browser_webcookiejar_impl.h"
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
@ -26,11 +32,14 @@
#include "third_party/WebKit/Source/WebKit/chromium/public/WebViewClient.h"
#include "webkit/glue/webcursor.h"
#include "webkit/plugins/npapi/webplugin_page_delegate.h"
#include "browser_navigation_controller.h"
#if defined(TOOLKIT_USES_GTK)
#include <gdk/gdk.h> // NOLINT(build/include_order)
#endif
#if defined(OS_MACOSX)
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenuInfo.h"
#include "external_popup_menu_mac.h"
#include "libcef/external_popup_menu_mac.h"
#endif
#if defined(OS_WIN)
@ -38,10 +47,6 @@ class BrowserDragDelegate;
class WebDropTarget;
#endif
#if defined(TOOLKIT_USES_GTK)
#include <gdk/gdk.h>
#endif
class CefBrowserImpl;
class GURL;
class WebWidgetHost;
@ -145,6 +150,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
virtual WebKit::WebApplicationCacheHost* createApplicationCacheHost(
WebKit::WebFrame* frame, WebKit::WebApplicationCacheHostClient* client)
OVERRIDE;
virtual WebKit::WebCookieJar* cookieJar(WebKit::WebFrame*) OVERRIDE;
virtual void willClose(WebKit::WebFrame*) OVERRIDE;
virtual void loadURLExternally(
WebKit::WebFrame*, const WebKit::WebURLRequest&,
@ -193,7 +199,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
virtual void openFileSystem(
WebKit::WebFrame* frame,
WebKit::WebFileSystem::Type type,
long long size,
long long size, // NOLINT(runtime/int)
bool create,
WebKit::WebFileSystemCallbacks* callbacks) OVERRIDE;
@ -287,9 +293,9 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
CefString* result);
// Called to show the file chooser dialog.
bool ShowFileChooser(std::vector<FilePath>& file_names,
const bool multi_select,
const WebKit::WebString& title,
bool ShowFileChooser(std::vector<FilePath>& file_names,
const bool multi_select,
const WebKit::WebString& title,
const FilePath& default_file);
// Called to show status messages.
@ -314,7 +320,7 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
int& type_flags);
private:
// Causes navigation actions just printout the intended navigation instead
// Causes navigation actions just printout the intended navigation instead
// of taking you to the page. This is used for cases like mailto, where you
// don't actually want to open the mail program.
bool policy_delegate_enabled_;
@ -367,7 +373,9 @@ class BrowserWebViewDelegate : public WebKit::WebViewClient,
std::string edit_command_name_;
std::string edit_command_value_;
BrowserWebCookieJarImpl cookie_jar_;
DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate);
};
#endif // _BROWSER_WEBVIEW_DELEGATE_H
#endif // CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_

View File

@ -61,8 +61,7 @@ public:
// The BrowserRequestContext object is managed by CefProcessIOThread.
void set_request_context(BrowserRequestContext* request_context)
{ request_context_ = request_context; }
scoped_refptr<BrowserRequestContext> request_context()
{ return request_context_; }
BrowserRequestContext* request_context() { return request_context_; }
// The DOMStorageContext object is managed by CefProcessUIThread.
void set_storage_context(DOMStorageContext* storage_context)

View File

@ -0,0 +1,255 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/cookie_manager_impl.h"
#include <string>
#include "libcef/browser_persistent_cookie_store.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "libcef/cef_time_util.h"
#include "base/bind.h"
#include "base/logging.h"
namespace {
// Callback class for visiting cookies.
class VisitCookiesCallback : public base::RefCounted<VisitCookiesCallback> {
public:
explicit VisitCookiesCallback(net::CookieMonster* cookie_monster,
CefRefPtr<CefCookieVisitor> visitor)
: cookie_monster_(cookie_monster),
visitor_(visitor) {
}
void Run(const net::CookieList& list) {
REQUIRE_IOT();
int total = list.size(), count = 0;
net::CookieList::const_iterator it = list.begin();
for (; it != list.end(); ++it, ++count) {
CefCookie cookie;
const net::CookieMonster::CanonicalCookie& cc = *(it);
CefString(&cookie.name).FromString(cc.Name());
CefString(&cookie.value).FromString(cc.Value());
CefString(&cookie.domain).FromString(cc.Domain());
CefString(&cookie.path).FromString(cc.Path());
cookie.secure = cc.IsSecure();
cookie.httponly = cc.IsHttpOnly();
cef_time_from_basetime(cc.CreationDate(), cookie.creation);
cef_time_from_basetime(cc.LastAccessDate(), cookie.last_access);
cookie.has_expires = cc.DoesExpire();
if (cookie.has_expires)
cef_time_from_basetime(cc.ExpiryDate(), cookie.expires);
bool deleteCookie = false;
bool keepLooping = visitor_->Visit(cookie, count, total, deleteCookie);
if (deleteCookie) {
cookie_monster_->DeleteCanonicalCookieAsync(cc,
net::CookieMonster::DeleteCookieCallback());
}
if (!keepLooping)
break;
}
}
private:
scoped_refptr<net::CookieMonster> cookie_monster_;
CefRefPtr<CefCookieVisitor> visitor_;
};
} // namespace
CefCookieManagerImpl::CefCookieManagerImpl()
: is_global_(true) {
cookie_monster_ =
static_cast<net::CookieMonster*>(
_Context->request_context()->cookie_store());
DCHECK(cookie_monster_);
}
// Creates a new cookie monster with storage at the specified |path|.
CefCookieManagerImpl::CefCookieManagerImpl(const CefString& path)
:is_global_(false) {
SetStoragePath(path);
}
CefCookieManagerImpl::~CefCookieManagerImpl() {
}
bool CefCookieManagerImpl::VisitAllCookies(
CefRefPtr<CefCookieVisitor> visitor) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
scoped_refptr<VisitCookiesCallback> callback(
new VisitCookiesCallback(cookie_monster_, visitor));
cookie_monster_->GetAllCookiesAsync(
base::Bind(&VisitCookiesCallback::Run, callback.get()));
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitAllCookies),
this, visitor));
}
return true;
}
bool CefCookieManagerImpl::VisitUrlCookies(
const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
net::CookieOptions options;
if (includeHttpOnly)
options.set_include_httponly();
scoped_refptr<VisitCookiesCallback> callback(
new VisitCookiesCallback(cookie_monster_, visitor));
GURL gurl = GURL(url.ToString());
cookie_monster_->GetAllCookiesForURLWithOptionsAsync(gurl, options,
base::Bind(&VisitCookiesCallback::Run, callback.get()));
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitUrlCookies),
this, url, includeHttpOnly, visitor));
}
return true;
}
bool CefCookieManagerImpl::SetCookie(const CefString& url,
const CefCookie& cookie) {
// Verify that this function is being called on the IO thread.
if (!CefThread::CurrentlyOn(CefThread::IO)) {
NOTREACHED() << "called on invalid thread";
return false;
}
GURL gurl = GURL(url.ToString());
if (!gurl.is_valid())
return false;
std::string name = CefString(&cookie.name).ToString();
std::string value = CefString(&cookie.value).ToString();
std::string domain = CefString(&cookie.domain).ToString();
std::string path = CefString(&cookie.path).ToString();
base::Time expiration_time;
if (cookie.has_expires)
cef_time_to_basetime(cookie.expires, expiration_time);
cookie_monster_->SetCookieWithDetailsAsync(gurl, name, value, domain, path,
expiration_time, cookie.secure, cookie.httponly,
net::CookieStore::SetCookiesCallback());
return true;
}
bool CefCookieManagerImpl::DeleteCookies(const CefString& url,
const CefString& cookie_name) {
// Verify that this function is being called on the IO thread.
if (!CefThread::CurrentlyOn(CefThread::IO)) {
NOTREACHED() << "called on invalid thread";
return false;
}
if (url.empty()) {
// Delete all cookies.
cookie_monster_->DeleteAllAsync(net::CookieMonster::DeleteCallback());
return true;
}
GURL gurl = GURL(url.ToString());
if (!gurl.is_valid())
return false;
if (cookie_name.empty()) {
// Delete all matching host cookies.
cookie_monster_->DeleteAllForHostAsync(gurl,
net::CookieMonster::DeleteCallback());
} else {
// Delete all matching host and domain cookies.
cookie_monster_->DeleteCookieAsync(gurl, cookie_name, base::Closure());
}
return true;
}
bool CefCookieManagerImpl::SetStoragePath(const CefString& path) {
if (CefThread::CurrentlyOn(CefThread::IO)) {
FilePath new_path;
if (!path.empty())
new_path = FilePath(path);
if (is_global_) {
// Global path changes are handled by the request context.
_Context->request_context()->SetCookieStoragePath(new_path);
cookie_monster_ =
static_cast<net::CookieMonster*>(
_Context->request_context()->cookie_store());
return true;
}
if (cookie_monster_ && ((storage_path_.empty() && path.empty()) ||
storage_path_ == new_path)) {
// The path has not changed so don't do anything.
return true;
}
scoped_refptr<BrowserPersistentCookieStore> persistent_store;
if (!new_path.empty()) {
if (file_util::CreateDirectory(new_path)) {
const FilePath& cookie_path = new_path.AppendASCII("Cookies");
persistent_store = new BrowserPersistentCookieStore(cookie_path, false);
} else {
NOTREACHED() << "The cookie storage directory could not be created";
storage_path_.clear();
}
}
// Set the new cookie store that will be used for all new requests. The old
// cookie store, if any, will be automatically flushed and closed when no
// longer referenced.
cookie_monster_ = new net::CookieMonster(persistent_store.get(), NULL);
storage_path_ = new_path;
} else {
// Execute on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
base::Bind(base::IgnoreResult(&CefCookieManagerImpl::SetStoragePath),
this, path));
}
return true;
}
// CefCookieManager methods ----------------------------------------------------
// static
CefRefPtr<CefCookieManager> CefCookieManager::GetGlobalManager() {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return NULL;
}
return new CefCookieManagerImpl();
}
// static
CefRefPtr<CefCookieManager> CefCookieManager::CreateManager(
const CefString& path) {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
return NULL;
}
return new CefCookieManagerImpl(path);
}

View File

@ -0,0 +1,43 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef CEF_LIBCEF_COOKIE_IMPL_H_
#define CEF_LIBCEF_COOKIE_IMPL_H_
#include "include/cef.h"
#include "base/file_path.h"
#include "net/base/cookie_monster.h"
// Implementation of the CefCookieManager interface.
class CefCookieManagerImpl : public CefCookieManager {
public:
// Creates a new reference to the existing global cookie monster.
CefCookieManagerImpl();
// Creates a new cookie monster with storage at the specified |path|.
explicit CefCookieManagerImpl(const CefString& path);
~CefCookieManagerImpl();
// CefCookieManager methods.
virtual bool VisitAllCookies(CefRefPtr<CefCookieVisitor> visitor) OVERRIDE;
virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) OVERRIDE;
virtual bool SetCookie(const CefString& url,
const CefCookie& cookie) OVERRIDE;
virtual bool DeleteCookies(const CefString& url,
const CefString& cookie_name) OVERRIDE;
virtual bool SetStoragePath(const CefString& path) OVERRIDE;
net::CookieMonster* cookie_monster() { return cookie_monster_; }
private:
scoped_refptr<net::CookieMonster> cookie_monster_;
bool is_global_;
FilePath storage_path_;
IMPLEMENT_REFCOUNTING(CefCookieManagerImpl);
};
#endif // CEF_LIBCEF_COOKIE_IMPL_H_

View File

@ -0,0 +1,83 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/cookie_store_proxy.h"
#include <string>
#include "libcef/browser_impl.h"
#include "libcef/cef_context.h"
#include "libcef/cookie_manager_impl.h"
#include "base/logging.h"
CefCookieStoreProxy::CefCookieStoreProxy(CefBrowserImpl* browser)
: browser_(browser) {
DCHECK(browser_);
}
void CefCookieStoreProxy::SetCookieWithOptionsAsync(
const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options,
const SetCookiesCallback& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->SetCookieWithOptionsAsync(url, cookie_line, options, callback);
}
void CefCookieStoreProxy::GetCookiesWithOptionsAsync(
const GURL& url, const net::CookieOptions& options,
const GetCookiesCallback& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->GetCookiesWithOptionsAsync(url, options, callback);
}
void CefCookieStoreProxy::GetCookiesWithInfoAsync(
const GURL& url,
const net::CookieOptions& options,
const GetCookieInfoCallback& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->GetCookiesWithInfoAsync(url, options, callback);
}
void CefCookieStoreProxy::DeleteCookieAsync(
const GURL& url,
const std::string& cookie_name,
const base::Closure& callback) {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
cookie_store->DeleteCookieAsync(url, cookie_name, callback);
}
net::CookieMonster* CefCookieStoreProxy::GetCookieMonster() {
scoped_refptr<net::CookieStore> cookie_store = GetCookieStore();
return cookie_store->GetCookieMonster();
}
net::CookieStore* CefCookieStoreProxy::GetCookieStore() {
scoped_refptr<net::CookieStore> cookie_store;
CefRefPtr<CefClient> client = browser_->GetClient();
if (client.get()) {
CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
if (handler.get()) {
// Get the manager from the handler.
CefRefPtr<CefCookieManager> manager =
handler->GetCookieManager(browser_, browser_->pending_url().spec());
if (manager.get()) {
cookie_store =
reinterpret_cast<CefCookieManagerImpl*>(
manager.get())->cookie_monster();
}
}
}
if (!cookie_store) {
// Use the global cookie store.
cookie_store = _Context->request_context()->cookie_store();
}
DCHECK(cookie_store);
return cookie_store;
}

View File

@ -0,0 +1,42 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#ifndef CEF_LIBCEF_COOKIE_STORE_PROXY_H_
#define CEF_LIBCEF_COOKIE_STORE_PROXY_H_
#pragma once
#include "net/base/cookie_store.h"
class CefBrowserImpl;
// Handles cookie requests from the network stack.
class CefCookieStoreProxy : public net::CookieStore {
public:
explicit CefCookieStoreProxy(CefBrowserImpl* browser);
// net::CookieStore methods.
virtual void SetCookieWithOptionsAsync(
const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options,
const SetCookiesCallback& callback) OVERRIDE;
virtual void GetCookiesWithOptionsAsync(
const GURL& url, const net::CookieOptions& options,
const GetCookiesCallback& callback) OVERRIDE;
void GetCookiesWithInfoAsync(
const GURL& url,
const net::CookieOptions& options,
const GetCookieInfoCallback& callback) OVERRIDE;
virtual void DeleteCookieAsync(const GURL& url,
const std::string& cookie_name,
const base::Closure& callback) OVERRIDE;
virtual net::CookieMonster* GetCookieMonster() OVERRIDE;
private:
net::CookieStore* GetCookieStore();
CefBrowserImpl* browser_;
};
#endif // CEF_LIBCEF_COOKIE_STORE_PROXY_H_

View File

@ -2,73 +2,67 @@
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "request_impl.h"
#include "browser_webkit_glue.h"
#include "libcef/request_impl.h"
#include <string>
#include <vector>
#include "libcef/http_header_utils.h"
#include "base/logging.h"
#include "net/url_request/url_request.h"
#include "http_header_utils.h"
using WebKit::WebHTTPBody;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebURLRequest;
CefRefPtr<CefRequest> CefRequest::CreateRequest()
{
CefRefPtr<CefRequest> CefRequest::CreateRequest() {
CefRefPtr<CefRequest> request(new CefRequestImpl());
return request;
}
CefRequestImpl::CefRequestImpl()
: method_("GET"), flags_(WUR_FLAG_NONE)
{
: method_("GET"),
flags_(WUR_FLAG_NONE) {
}
CefString CefRequestImpl::GetURL()
{
CefString CefRequestImpl::GetURL() {
AutoLock lock_scope(this);
return url_;
}
void CefRequestImpl::SetURL(const CefString& url)
{
void CefRequestImpl::SetURL(const CefString& url) {
AutoLock lock_scope(this);
url_ = url;
}
CefString CefRequestImpl::GetMethod()
{
CefString CefRequestImpl::GetMethod() {
AutoLock lock_scope(this);
return method_;
}
void CefRequestImpl::SetMethod(const CefString& method)
{
void CefRequestImpl::SetMethod(const CefString& method) {
AutoLock lock_scope(this);
method_ = method;
}
CefRefPtr<CefPostData> CefRequestImpl::GetPostData()
{
CefRefPtr<CefPostData> CefRequestImpl::GetPostData() {
AutoLock lock_scope(this);
return postdata_;
}
void CefRequestImpl::SetPostData(CefRefPtr<CefPostData> postData)
{
void CefRequestImpl::SetPostData(CefRefPtr<CefPostData> postData) {
AutoLock lock_scope(this);
postdata_ = postData;
}
void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap)
{
void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) {
AutoLock lock_scope(this);
headerMap = headermap_;
}
void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap)
{
void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) {
AutoLock lock_scope(this);
headermap_ = headerMap;
}
@ -76,8 +70,7 @@ void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap)
void CefRequestImpl::Set(const CefString& url,
const CefString& method,
CefRefPtr<CefPostData> postData,
const HeaderMap& headerMap)
{
const HeaderMap& headerMap) {
AutoLock lock_scope(this);
url_ = url;
method_ = method;
@ -85,17 +78,30 @@ void CefRequestImpl::Set(const CefString& url,
headermap_ = headerMap;
}
void CefRequestImpl::Set(net::URLRequest* request)
{
void CefRequestImpl::Set(net::URLRequest* request) {
AutoLock lock_scope(this);
url_ = request->url().spec();
method_ = request->method();
net::HttpRequestHeaders headers = request->extra_request_headers();
// Ensure that we do not send username and password fields in the referrer.
GURL referrer(request->GetSanitizedReferrer());
// Strip Referer from request_info_.extra_headers to prevent, e.g., plugins
// from overriding headers that are controlled using other means. Otherwise a
// plugin could set a referrer although sending the referrer is inhibited.
headers.RemoveHeader(net::HttpRequestHeaders::kReferer);
// Our consumer should have made sure that this is a safe referrer. See for
// instance WebCore::FrameLoader::HideReferrer.
if (referrer.is_valid())
headers.SetHeader(net::HttpRequestHeaders::kReferer, referrer.spec());
// Transfer request headers
GetHeaderMap(request->extra_request_headers(), headermap_);
headermap_.insert(std::make_pair(L"Referrer", request->referrer()));
GetHeaderMap(headers, headermap_);
// Transfer post data, if any
net::UploadData* data = request->get_upload();
if (data) {
@ -104,8 +110,7 @@ void CefRequestImpl::Set(net::URLRequest* request)
}
}
void CefRequestImpl::Set(const WebKit::WebURLRequest& request)
{
void CefRequestImpl::Set(const WebKit::WebURLRequest& request) {
DCHECK(!request.isNull());
AutoLock lock_scope(this);
@ -116,7 +121,7 @@ void CefRequestImpl::Set(const WebKit::WebURLRequest& request)
if (!body.isNull()) {
postdata_ = new CefPostDataImpl();
static_cast<CefPostDataImpl*>(postdata_.get())->Set(body);
} else if(postdata_.get()) {
} else if (postdata_.get()) {
postdata_ = NULL;
}
@ -144,8 +149,7 @@ void CefRequestImpl::Set(const WebKit::WebURLRequest& request)
#define SETBOOLFLAG(obj, flags, method, FLAG) \
obj.method((flags & (FLAG)) == (FLAG))
void CefRequestImpl::Get(WebKit::WebURLRequest& request)
{
void CefRequestImpl::Get(WebKit::WebURLRequest& request) {
request.initialize();
AutoLock lock_scope(this);
@ -170,13 +174,13 @@ void CefRequestImpl::Get(WebKit::WebURLRequest& request)
WebURLRequest::ReloadIgnoringCacheData :
WebURLRequest::UseProtocolCachePolicy);
SETBOOLFLAG(request, flags_, setAllowStoredCredentials,
SETBOOLFLAG(request, flags_, setAllowStoredCredentials,
WUR_FLAG_ALLOW_CACHED_CREDENTIALS);
SETBOOLFLAG(request, flags_, setAllowCookies,
SETBOOLFLAG(request, flags_, setAllowCookies,
WUR_FLAG_ALLOW_COOKIES);
SETBOOLFLAG(request, flags_, setReportUploadProgress,
SETBOOLFLAG(request, flags_, setReportUploadProgress,
WUR_FLAG_REPORT_UPLOAD_PROGRESS);
SETBOOLFLAG(request, flags_, setReportLoadTiming,
SETBOOLFLAG(request, flags_, setReportLoadTiming,
WUR_FLAG_REPORT_LOAD_TIMING);
SETBOOLFLAG(request, flags_, setReportRawHeaders,
WUR_FLAG_REPORT_RAW_HEADERS);
@ -188,32 +192,27 @@ void CefRequestImpl::Get(WebKit::WebURLRequest& request)
}
}
CefRequest::RequestFlags CefRequestImpl::GetFlags()
{
CefRequest::RequestFlags CefRequestImpl::GetFlags() {
AutoLock lock_scope(this);
return flags_;
}
void CefRequestImpl::SetFlags(RequestFlags flags)
{
void CefRequestImpl::SetFlags(RequestFlags flags) {
AutoLock lock_scope(this);
flags_ = flags;
}
CefString CefRequestImpl::GetFirstPartyForCookies()
{
CefString CefRequestImpl::GetFirstPartyForCookies() {
AutoLock lock_scope(this);
return first_party_for_cookies_;
}
void CefRequestImpl::SetFirstPartyForCookies(const CefString& url)
{
void CefRequestImpl::SetFirstPartyForCookies(const CefString& url) {
AutoLock lock_scope(this);
first_party_for_cookies_ = url;
}
// static
void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
HeaderMap& map)
{
void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
HeaderMap& map) {
net::HttpRequestHeaders::Iterator it(headers);
do {
map.insert(std::make_pair(it.name(), it.value()));
@ -222,50 +221,43 @@ void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
// static
void CefRequestImpl::GetHeaderMap(const WebKit::WebURLRequest& request,
HeaderMap& map)
{
HeaderMap& map) {
HttpHeaderUtils::HeaderVisitor visitor(&map);
request.visitHTTPHeaderFields(&visitor);
}
// static
void CefRequestImpl::SetHeaderMap(const HeaderMap& map,
WebKit::WebURLRequest& request)
{
WebKit::WebURLRequest& request) {
HeaderMap::const_iterator it = map.begin();
for(; it != map.end(); ++it)
for (; it != map.end(); ++it)
request.setHTTPHeaderField(string16(it->first), string16(it->second));
}
CefRefPtr<CefPostData> CefPostData::CreatePostData()
{
CefRefPtr<CefPostData> CefPostData::CreatePostData() {
CefRefPtr<CefPostData> postdata(new CefPostDataImpl());
return postdata;
}
CefPostDataImpl::CefPostDataImpl()
{
CefPostDataImpl::CefPostDataImpl() {
}
size_t CefPostDataImpl::GetElementCount()
{
size_t CefPostDataImpl::GetElementCount() {
AutoLock lock_scope(this);
return elements_.size();
}
void CefPostDataImpl::GetElements(ElementVector& elements)
{
void CefPostDataImpl::GetElements(ElementVector& elements) {
AutoLock lock_scope(this);
elements = elements_;
}
bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element)
{
bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element) {
AutoLock lock_scope(this);
ElementVector::iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
if(it->get() == element.get()) {
for (; it != elements_.end(); ++it) {
if (it->get() == element.get()) {
elements_.erase(it);
return true;
}
@ -274,35 +266,32 @@ bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element)
return false;
}
bool CefPostDataImpl::AddElement(CefRefPtr<CefPostDataElement> element)
{
bool CefPostDataImpl::AddElement(CefRefPtr<CefPostDataElement> element) {
bool found = false;
AutoLock lock_scope(this);
// check that the element isn't already in the list before adding
ElementVector::const_iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
if(it->get() == element.get()) {
for (; it != elements_.end(); ++it) {
if (it->get() == element.get()) {
found = true;
break;
}
}
if(!found)
if (!found)
elements_.push_back(element);
return !found;
}
void CefPostDataImpl::RemoveElements()
{
void CefPostDataImpl::RemoveElements() {
AutoLock lock_scope(this);
elements_.clear();
}
void CefPostDataImpl::Set(net::UploadData& data)
{
void CefPostDataImpl::Set(net::UploadData& data) {
AutoLock lock_scope(this);
CefRefPtr<CefPostDataElement> postelem;
@ -316,22 +305,20 @@ void CefPostDataImpl::Set(net::UploadData& data)
}
}
void CefPostDataImpl::Get(net::UploadData& data)
{
void CefPostDataImpl::Get(net::UploadData& data) {
AutoLock lock_scope(this);
net::UploadData::Element element;
std::vector<net::UploadData::Element> data_elements;
ElementVector::iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
for (; it != elements_.end(); ++it) {
static_cast<CefPostDataElementImpl*>(it->get())->Get(element);
data_elements.push_back(element);
}
data.SetElements(data_elements);
}
void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data)
{
void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data) {
AutoLock lock_scope(this);
CefRefPtr<CefPostDataElement> postelem;
@ -346,17 +333,16 @@ void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data)
}
}
void CefPostDataImpl::Get(WebKit::WebHTTPBody& data)
{
void CefPostDataImpl::Get(WebKit::WebHTTPBody& data) {
AutoLock lock_scope(this);
WebKit::WebHTTPBody::Element element;
ElementVector::iterator it = elements_.begin();
for(; it != elements_.end(); ++it) {
for (; it != elements_.end(); ++it) {
static_cast<CefPostDataElementImpl*>(it->get())->Get(element);
if(element.type == WebKit::WebHTTPBody::Element::TypeData) {
if (element.type == WebKit::WebHTTPBody::Element::TypeData) {
data.appendData(element.data);
} else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) {
} else if (element.type == WebKit::WebHTTPBody::Element::TypeFile) {
data.appendFile(element.filePath);
} else {
NOTREACHED();
@ -364,36 +350,31 @@ void CefPostDataImpl::Get(WebKit::WebHTTPBody& data)
}
}
CefRefPtr<CefPostDataElement> CefPostDataElement::CreatePostDataElement()
{
CefRefPtr<CefPostDataElement> CefPostDataElement::CreatePostDataElement() {
CefRefPtr<CefPostDataElement> element(new CefPostDataElementImpl());
return element;
}
CefPostDataElementImpl::CefPostDataElementImpl()
{
CefPostDataElementImpl::CefPostDataElementImpl() {
type_ = PDE_TYPE_EMPTY;
memset(&data_, 0, sizeof(data_));
}
CefPostDataElementImpl::~CefPostDataElementImpl()
{
CefPostDataElementImpl::~CefPostDataElementImpl() {
SetToEmpty();
}
void CefPostDataElementImpl::SetToEmpty()
{
void CefPostDataElementImpl::SetToEmpty() {
AutoLock lock_scope(this);
if(type_ == PDE_TYPE_BYTES)
if (type_ == PDE_TYPE_BYTES)
free(data_.bytes.bytes);
else if(type_ == PDE_TYPE_FILE)
else if (type_ == PDE_TYPE_FILE)
cef_string_clear(&data_.filename);
type_ = PDE_TYPE_EMPTY;
memset(&data_, 0, sizeof(data_));
}
void CefPostDataElementImpl::SetToFile(const CefString& fileName)
{
void CefPostDataElementImpl::SetToFile(const CefString& fileName) {
AutoLock lock_scope(this);
// Clear any data currently in the element
SetToEmpty();
@ -403,8 +384,7 @@ void CefPostDataElementImpl::SetToFile(const CefString& fileName)
cef_string_copy(fileName.c_str(), fileName.length(), &data_.filename);
}
void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes)
{
void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) {
AutoLock lock_scope(this);
// Clear any data currently in the element
SetToEmpty();
@ -412,56 +392,51 @@ void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes)
// Assign the new data
void* data = malloc(size);
DCHECK(data != NULL);
if(data == NULL)
if (data == NULL)
return;
memcpy(data, bytes, size);
type_ = PDE_TYPE_BYTES;
data_.bytes.bytes = data;
data_.bytes.size = size;
}
CefPostDataElement::Type CefPostDataElementImpl::GetType()
{
CefPostDataElement::Type CefPostDataElementImpl::GetType() {
AutoLock lock_scope(this);
return type_;
}
CefString CefPostDataElementImpl::GetFile()
{
CefString CefPostDataElementImpl::GetFile() {
AutoLock lock_scope(this);
DCHECK(type_ == PDE_TYPE_FILE);
CefString filename;
if(type_ == PDE_TYPE_FILE)
if (type_ == PDE_TYPE_FILE)
filename.FromString(data_.filename.str, data_.filename.length, false);
return filename;
}
size_t CefPostDataElementImpl::GetBytesCount()
{
size_t CefPostDataElementImpl::GetBytesCount() {
AutoLock lock_scope(this);
DCHECK(type_ == PDE_TYPE_BYTES);
size_t size = 0;
if(type_ == PDE_TYPE_BYTES)
if (type_ == PDE_TYPE_BYTES)
size = data_.bytes.size;
return size;
}
size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes)
{
size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) {
AutoLock lock_scope(this);
DCHECK(type_ == PDE_TYPE_BYTES);
size_t rv = 0;
if(type_ == PDE_TYPE_BYTES) {
if (type_ == PDE_TYPE_BYTES) {
rv = (size < data_.bytes.size ? size : data_.bytes.size);
memcpy(bytes, data_.bytes.bytes, rv);
}
return rv;
}
void CefPostDataElementImpl::Set(const net::UploadData::Element& element)
{
void CefPostDataElementImpl::Set(const net::UploadData::Element& element) {
AutoLock lock_scope(this);
if (element.type() == net::UploadData::TYPE_BYTES) {
@ -476,13 +451,12 @@ void CefPostDataElementImpl::Set(const net::UploadData::Element& element)
}
}
void CefPostDataElementImpl::Get(net::UploadData::Element& element)
{
void CefPostDataElementImpl::Get(net::UploadData::Element& element) {
AutoLock lock_scope(this);
if(type_ == PDE_TYPE_BYTES) {
if (type_ == PDE_TYPE_BYTES) {
element.SetToBytes(static_cast<char*>(data_.bytes.bytes), data_.bytes.size);
} else if(type_ == PDE_TYPE_FILE) {
} else if (type_ == PDE_TYPE_FILE) {
FilePath path = FilePath(CefString(&data_.filename));
element.SetToFilePath(path);
} else {
@ -490,29 +464,27 @@ void CefPostDataElementImpl::Get(net::UploadData::Element& element)
}
}
void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element)
{
void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element) {
AutoLock lock_scope(this);
if(element.type == WebKit::WebHTTPBody::Element::TypeData) {
if (element.type == WebKit::WebHTTPBody::Element::TypeData) {
SetToBytes(element.data.size(),
static_cast<const void*>(element.data.data()));
} else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) {
} else if (element.type == WebKit::WebHTTPBody::Element::TypeFile) {
SetToFile(string16(element.filePath));
} else {
NOTREACHED();
}
}
void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element)
{
void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element) {
AutoLock lock_scope(this);
if(type_ == PDE_TYPE_BYTES) {
if (type_ == PDE_TYPE_BYTES) {
element.type = WebKit::WebHTTPBody::Element::TypeData;
element.data.assign(
static_cast<char*>(data_.bytes.bytes), data_.bytes.size);
} else if(type_ == PDE_TYPE_FILE) {
} else if (type_ == PDE_TYPE_FILE) {
element.type = WebKit::WebHTTPBody::Element::TypeFile;
element.filePath.assign(string16(CefString(&data_.filename)));
} else {

View File

@ -3,14 +3,18 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/cef.h"
#include "browser_devtools_scheme_handler.h"
#include "browser_resource_loader_bridge.h"
#include "cef_context.h"
#include "cef_thread.h"
#include "request_impl.h"
#include "response_impl.h"
#include <map>
#include "include/cef.h"
#include "libcef/browser_devtools_scheme_handler.h"
#include "libcef/browser_impl.h"
#include "libcef/browser_resource_loader_bridge.h"
#include "libcef/cef_context.h"
#include "libcef/cef_thread.h"
#include "libcef/request_impl.h"
#include "libcef/response_impl.h"
#include "base/bind.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/message_loop.h"
@ -18,6 +22,7 @@
#include "base/synchronization/lock.h"
#include "googleurl/src/url_util.h"
#include "net/base/completion_callback.h"
#include "net/base/cookie_monster.h"
#include "net/base/io_buffer.h"
#include "net/base/upload_data.h"
#include "net/http/http_response_headers.h"
@ -35,22 +40,18 @@
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include <map>
using net::URLRequestStatus;
using WebKit::WebSecurityPolicy;
using WebKit::WebString;
namespace {
bool IsStandardScheme(const std::string& scheme)
{
bool IsStandardScheme(const std::string& scheme) {
url_parse::Component scheme_comp(0, scheme.length());
return url_util::IsStandard(scheme.c_str(), scheme_comp);
}
void RegisterStandardScheme(const std::string& scheme)
{
void RegisterStandardScheme(const std::string& scheme) {
REQUIRE_UIT();
url_parse::Component scheme_comp(0, scheme.length());
if (!url_util::IsStandard(scheme.c_str(), scheme_comp))
@ -71,8 +72,7 @@ static const SchemeToFactory kBuiltinFactories[] = {
{ "data", net::URLRequestDataJob::Factory },
};
bool IsBuiltinScheme(const std::string& scheme)
{
bool IsBuiltinScheme(const std::string& scheme) {
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i)
if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme))
return true;
@ -80,8 +80,7 @@ bool IsBuiltinScheme(const std::string& scheme)
}
net::URLRequestJob* GetBuiltinSchemeRequestJob(net::URLRequest* request,
const std::string& scheme)
{
const std::string& scheme) {
// See if the request should be handled by a built-in protocol factory.
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) {
if (scheme == kBuiltinFactories[i].scheme) {
@ -94,8 +93,7 @@ net::URLRequestJob* GetBuiltinSchemeRequestJob(net::URLRequest* request,
return NULL;
}
std::string ToLower(const std::string& str)
{
std::string ToLower(const std::string& str) {
std::string str_lower = str;
std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(),
towlower);
@ -105,43 +103,151 @@ std::string ToLower(const std::string& str)
// net::URLRequestJob implementation.
class CefUrlRequestJob : public net::URLRequestJob {
public:
public:
CefUrlRequestJob(net::URLRequest* request,
CefRefPtr<CefSchemeHandler> handler)
: net::URLRequestJob(request),
handler_(handler),
remaining_bytes_(0)
{
remaining_bytes_(0),
response_cookies_save_index_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}
virtual ~CefUrlRequestJob()
{
virtual ~CefUrlRequestJob() {
}
virtual void Start() OVERRIDE
{
virtual void Start() OVERRIDE {
REQUIRE_IOT();
cef_request_ = CefRequest::CreateRequest();
// Populate the request data.
static_cast<CefRequestImpl*>(cef_request_.get())->Set(request_);
// Add default headers if not already specified.
const net::URLRequestContext* context = request_->context();
if (context) {
CefRequest::HeaderMap::const_iterator it;
CefRequest::HeaderMap headerMap;
cef_request_->GetHeaderMap(headerMap);
bool changed = false;
if (!context->accept_language().empty()) {
it = headerMap.find(net::HttpRequestHeaders::kAcceptLanguage);
if (it == headerMap.end()) {
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kAcceptLanguage,
context->accept_language()));
}
changed = true;
}
if (!context->accept_charset().empty()) {
it = headerMap.find(net::HttpRequestHeaders::kAcceptCharset);
if (it == headerMap.end()) {
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kAcceptCharset,
context->accept_charset()));
}
changed = true;
}
it = headerMap.find(net::HttpRequestHeaders::kUserAgent);
if (it == headerMap.end()) {
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kUserAgent,
context->GetUserAgent(request_->url())));
changed = true;
}
if (changed)
cef_request_->SetHeaderMap(headerMap);
}
AddCookieHeaderAndStart();
}
void AddCookieHeaderAndStart() {
// No matter what, we want to report our status as IO pending since we will
// be notifying our consumer asynchronously via OnStartCompleted.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
// If the request was destroyed, then there is no more work to do.
if (!request_)
return;
net::CookieStore* cookie_store =
request_->context()->cookie_store();
if (cookie_store) {
net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster();
if (cookie_monster) {
cookie_monster->GetAllCookiesForURLAsync(
request_->url(),
base::Bind(&CefUrlRequestJob::CheckCookiePolicyAndLoad,
weak_factory_.GetWeakPtr()));
} else {
DoLoadCookies();
}
} else {
DoStartTransaction();
}
}
void DoLoadCookies() {
net::CookieOptions options;
options.set_include_httponly();
request_->context()->cookie_store()->GetCookiesWithInfoAsync(
request_->url(), options,
base::Bind(&CefUrlRequestJob::OnCookiesLoaded,
weak_factory_.GetWeakPtr()));
}
void CheckCookiePolicyAndLoad(
const net::CookieList& cookie_list) {
if (CanGetCookies(cookie_list))
DoLoadCookies();
else
DoStartTransaction();
}
void OnCookiesLoaded(
const std::string& cookie_line,
const std::vector<net::CookieStore::CookieInfo>& cookie_infos) {
if (!cookie_line.empty()) {
CefRequest::HeaderMap headerMap;
cef_request_->GetHeaderMap(headerMap);
headerMap.insert(
std::make_pair(net::HttpRequestHeaders::kCookie, cookie_line));
cef_request_->SetHeaderMap(headerMap);
}
DoStartTransaction();
}
void DoStartTransaction() {
// We may have been canceled while retrieving cookies.
if (GetStatus().is_success()) {
StartTransaction();
} else {
NotifyCanceled();
}
}
void StartTransaction() {
if (!callback_)
callback_ = new Callback(this);
CefRefPtr<CefRequest> req(CefRequest::CreateRequest());
// Populate the request data.
static_cast<CefRequestImpl*>(req.get())->Set(request());
// Protect against deletion of this object.
base::WeakPtr<CefUrlRequestJob> weak_ptr(weak_factory_.GetWeakPtr());
// Handler can decide whether to process the request.
bool rv = handler_->ProcessRequest(req, callback_.get());
if (!rv) {
bool rv = handler_->ProcessRequest(cef_request_, callback_.get());
if (weak_ptr.get() && !rv) {
// Cancel the request.
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, ERR_ABORTED));
NotifyCanceled();
}
return;
}
virtual void Kill() OVERRIDE
{
virtual void Kill() OVERRIDE {
REQUIRE_IOT();
// Notify the handler that the request has been canceled.
@ -156,8 +262,7 @@ public:
}
virtual bool ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read)
OVERRIDE
{
OVERRIDE {
REQUIRE_IOT();
DCHECK_NE(dest_size, 0);
@ -179,39 +284,33 @@ public:
// The handler has indicated completion of the request.
*bytes_read = 0;
return true;
} else if(*bytes_read == 0) {
} else if (*bytes_read == 0) {
if (!GetStatus().is_io_pending()) {
// Report our status as IO pending.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
callback_->SetDestination(dest, dest_size);
}
return false;
} else if(*bytes_read > dest_size) {
} else if (*bytes_read > dest_size) {
// Normalize the return value.
*bytes_read = dest_size;
}
if(remaining_bytes_ > 0)
if (remaining_bytes_ > 0)
remaining_bytes_ -= *bytes_read;
// Continue calling this method.
return true;
}
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE
{
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
REQUIRE_IOT();
if (response_.get()) {
CefResponseImpl* responseImpl =
static_cast<CefResponseImpl*>(response_.get());
info->headers = responseImpl->GetResponseHeaders();
}
info->headers = GetResponseHeaders();
}
virtual bool IsRedirectResponse(GURL* location, int* http_status_code)
OVERRIDE
{
OVERRIDE {
REQUIRE_IOT();
if (redirect_url_.is_valid()) {
@ -228,7 +327,7 @@ public:
CefResponse::HeaderMap headerMap;
response_->GetHeaderMap(headerMap);
CefRequest::HeaderMap::iterator iter = headerMap.find("Location");
if(iter != headerMap.end()) {
if (iter != headerMap.end()) {
GURL new_url = GURL(std::string(iter->second));
*http_status_code = status;
location->Swap(&new_url);
@ -240,8 +339,7 @@ public:
return false;
}
virtual bool GetMimeType(std::string* mime_type) const OVERRIDE
{
virtual bool GetMimeType(std::string* mime_type) const OVERRIDE {
REQUIRE_IOT();
if (response_.get())
@ -252,9 +350,8 @@ public:
CefRefPtr<CefSchemeHandler> handler_;
CefRefPtr<CefResponse> response_;
private:
void SendHeaders()
{
private:
void SendHeaders() {
REQUIRE_IOT();
// We may have been orphaned...
@ -277,20 +374,92 @@ private:
set_expected_content_size(remaining_bytes_);
// Continue processing the request.
NotifyHeadersComplete();
SaveCookiesAndNotifyHeadersComplete();
}
net::HttpResponseHeaders* GetResponseHeaders() {
DCHECK(response_);
if (!response_headers_.get()) {
CefResponseImpl* responseImpl =
static_cast<CefResponseImpl*>(response_.get());
response_headers_ = responseImpl->GetResponseHeaders();
}
return response_headers_;
}
void SaveCookiesAndNotifyHeadersComplete() {
response_cookies_.clear();
response_cookies_save_index_ = 0;
FetchResponseCookies(&response_cookies_);
// Now, loop over the response cookies, and attempt to persist each.
SaveNextCookie();
}
void SaveNextCookie() {
if (response_cookies_save_index_ == response_cookies_.size()) {
response_cookies_.clear();
response_cookies_save_index_ = 0;
SetStatus(URLRequestStatus()); // Clear the IO_PENDING status
NotifyHeadersComplete();
return;
}
// No matter what, we want to report our status as IO pending since we will
// be notifying our consumer asynchronously via OnStartCompleted.
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
net::CookieOptions options;
options.set_include_httponly();
if (CanSetCookie(
response_cookies_[response_cookies_save_index_], &options)) {
request_->context()->cookie_store()->SetCookieWithOptionsAsync(
request_->url(), response_cookies_[response_cookies_save_index_],
options, base::Bind(&CefUrlRequestJob::OnCookieSaved,
weak_factory_.GetWeakPtr()));
return;
}
CookieHandled();
}
void OnCookieSaved(bool cookie_status) {
CookieHandled();
}
void CookieHandled() {
response_cookies_save_index_++;
// We may have been canceled within OnSetCookie.
if (GetStatus().is_success()) {
SaveNextCookie();
} else {
NotifyCanceled();
}
}
void FetchResponseCookies(
std::vector<std::string>* cookies) {
const std::string name = "Set-Cookie";
std::string value;
void* iter = NULL;
net::HttpResponseHeaders* headers = GetResponseHeaders();
while (headers->EnumerateHeader(&iter, name, &value)) {
if (!value.empty())
cookies->push_back(value);
}
}
// Client callback for asynchronous response continuation.
class Callback : public CefSchemeHandlerCallback
{
public:
Callback(CefUrlRequestJob* job)
class Callback : public CefSchemeHandlerCallback {
public:
explicit Callback(CefUrlRequestJob* job)
: job_(job),
dest_(NULL),
dest_size_() {}
virtual void HeadersAvailable() OVERRIDE
{
virtual void HeadersAvailable() OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::IO)) {
// Currently on IO thread.
if (job_ && !job_->has_response_started()) {
@ -300,12 +469,11 @@ private:
} else {
// Execute this method on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableMethod(this, &Callback::HeadersAvailable));
base::Bind(&Callback::HeadersAvailable, this));
}
}
virtual void BytesAvailable() OVERRIDE
{
virtual void BytesAvailable() OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::IO)) {
// Currently on IO thread.
if (job_ && job_->has_response_started() &&
@ -331,12 +499,11 @@ private:
} else {
// Execute this method on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableMethod(this, &Callback::BytesAvailable));
base::Bind(&Callback::BytesAvailable, this));
}
}
virtual void Cancel() OVERRIDE
{
virtual void Cancel() OVERRIDE {
if (CefThread::CurrentlyOn(CefThread::IO)) {
// Currently on IO thread.
if (job_)
@ -344,25 +511,23 @@ private:
} else {
// Execute this method on the IO thread.
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableMethod(this, &Callback::Cancel));
base::Bind(&Callback::Cancel, this));
}
}
void Detach()
{
void Detach() {
REQUIRE_IOT();
job_ = NULL;
}
void SetDestination(net::IOBuffer* dest, int dest_size)
{
void SetDestination(net::IOBuffer* dest, int dest_size) {
dest_ = dest;
dest_size_ = dest_size;
}
static bool ImplementsThreadSafeReferenceCounting() { return true; }
private:
private:
CefUrlRequestJob* job_;
net::IOBuffer* dest_;
@ -373,7 +538,12 @@ private:
GURL redirect_url_;
int64 remaining_bytes_;
CefRefPtr<CefRequest> cef_request_;
CefRefPtr<Callback> callback_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
std::vector<std::string> response_cookies_;
size_t response_cookies_save_index_;
base::WeakPtrFactory<CefUrlRequestJob> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(CefUrlRequestJob);
};
@ -381,28 +551,27 @@ private:
// Class that manages the CefSchemeHandlerFactory instances.
class CefUrlRequestManager {
protected:
protected:
// Class used for creating URLRequestJob instances. The lifespan of this
// object is managed by URLRequestJobFactory.
class ProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
public:
ProtocolHandler(const std::string& scheme)
public:
explicit ProtocolHandler(const std::string& scheme)
: scheme_(scheme) {}
// From net::URLRequestJobFactory::ProtocolHandler
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request) const OVERRIDE
{
net::URLRequest* request) const OVERRIDE {
REQUIRE_IOT();
return CefUrlRequestManager::GetInstance()->GetRequestJob(request,
scheme_);
}
private:
private:
std::string scheme_;
};
public:
public:
CefUrlRequestManager() {}
// Retrieve the singleton instance.
@ -410,8 +579,7 @@ public:
bool AddFactory(const std::string& scheme,
const std::string& domain,
CefRefPtr<CefSchemeHandlerFactory> factory)
{
CefRefPtr<CefSchemeHandlerFactory> factory) {
if (!factory.get()) {
RemoveFactory(scheme, domain);
return true;
@ -439,8 +607,7 @@ public:
}
void RemoveFactory(const std::string& scheme,
const std::string& domain)
{
const std::string& domain) {
REQUIRE_IOT();
std::string scheme_lower = ToLower(scheme);
@ -457,8 +624,7 @@ public:
}
// Clear all the existing URL handlers and unregister the ProtocolFactory.
void ClearFactories()
{
void ClearFactories() {
REQUIRE_IOT();
net::URLRequestJobFactory* job_factory =
@ -480,8 +646,7 @@ public:
}
// Check if a scheme has already been registered.
bool HasRegisteredScheme(const std::string& scheme)
{
bool HasRegisteredScheme(const std::string& scheme) {
std::string scheme_lower = ToLower(scheme);
// Don't register builtin schemes.
@ -498,8 +663,7 @@ public:
bool RegisterScheme(const std::string& scheme,
bool is_standard,
bool is_local,
bool is_display_isolated)
{
bool is_display_isolated) {
if (HasRegisteredScheme(scheme)) {
NOTREACHED() << "Scheme already registered: " << scheme;
return false;
@ -525,12 +689,11 @@ public:
return true;
}
private:
private:
// Retrieve the matching handler factory, if any. |scheme| will already be in
// lower case.
CefRefPtr<CefSchemeHandlerFactory> GetHandlerFactory(
net::URLRequest* request, const std::string& scheme)
{
net::URLRequest* request, const std::string& scheme) {
CefRefPtr<CefSchemeHandlerFactory> factory;
if (request->url().is_valid() && IsStandardScheme(scheme)) {
@ -556,8 +719,7 @@ private:
// Create the job that will handle the request. |scheme| will already be in
// lower case.
net::URLRequestJob* GetRequestJob(net::URLRequest* request,
const std::string& scheme)
{
const std::string& scheme) {
net::URLRequestJob* job = NULL;
CefRefPtr<CefSchemeHandlerFactory> factory =
GetHandlerFactory(request, scheme);
@ -565,10 +727,10 @@ private:
// Call the handler factory to create the handler for the request.
CefRefPtr<CefRequest> requestPtr(new CefRequestImpl());
static_cast<CefRequestImpl*>(requestPtr.get())->Set(request);
CefRefPtr<CefBrowser> browser =
CefRefPtr<CefBrowserImpl> browser =
BrowserResourceLoaderBridge::GetBrowserForRequest(request);
CefRefPtr<CefSchemeHandler> handler =
factory->Create(browser, scheme, requestPtr);
factory->Create(browser.get(), scheme, requestPtr);
if (handler.get())
job = new CefUrlRequestJob(request, handler);
}
@ -582,7 +744,7 @@ private:
if (job)
DLOG(INFO) << "CefUrlRequestManager hit for " << request->url().spec();
#endif
return job;
}
@ -602,19 +764,17 @@ private:
base::LazyInstance<CefUrlRequestManager> g_manager = LAZY_INSTANCE_INITIALIZER;
CefUrlRequestManager* CefUrlRequestManager::GetInstance()
{
CefUrlRequestManager* CefUrlRequestManager::GetInstance() {
return g_manager.Pointer();
}
} // anonymous
} // namespace
bool CefRegisterCustomScheme(const CefString& scheme_name,
bool is_standard,
bool is_local,
bool is_display_isolated)
{
bool is_display_isolated) {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
@ -631,18 +791,18 @@ bool CefRegisterCustomScheme(const CefString& scheme_name,
NOTREACHED() << "Scheme already registered: " << scheme_name;
return false;
}
CefThread::PostTask(CefThread::UI, FROM_HERE,
NewRunnableFunction(&CefRegisterCustomScheme, scheme_name, is_standard,
is_local, is_display_isolated));
base::Bind(base::IgnoreResult(&CefRegisterCustomScheme), scheme_name,
is_standard, is_local, is_display_isolated));
return true;
}
}
bool CefRegisterSchemeHandlerFactory(const CefString& scheme_name,
const CefString& domain_name,
CefRefPtr<CefSchemeHandlerFactory> factory)
{
bool CefRegisterSchemeHandlerFactory(
const CefString& scheme_name,
const CefString& domain_name,
CefRefPtr<CefSchemeHandlerFactory> factory) {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
@ -655,14 +815,13 @@ bool CefRegisterSchemeHandlerFactory(const CefString& scheme_name,
factory);
} else {
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableFunction(&CefRegisterSchemeHandlerFactory, scheme_name,
domain_name, factory));
base::Bind(base::IgnoreResult(&CefRegisterSchemeHandlerFactory),
scheme_name, domain_name, factory));
return true;
}
}
bool CefClearSchemeHandlerFactories()
{
bool CefClearSchemeHandlerFactories() {
// Verify that the context is in a valid state.
if (!CONTEXT_STATE_VALID()) {
NOTREACHED() << "context not valid";
@ -676,7 +835,7 @@ bool CefClearSchemeHandlerFactories()
RegisterDevToolsSchemeHandler(false);
} else {
CefThread::PostTask(CefThread::IO, FROM_HERE,
NewRunnableFunction(&CefClearSchemeHandlerFactories));
base::Bind(base::IgnoreResult(&CefClearSchemeHandlerFactories)));
}
return true;

View File

@ -0,0 +1,191 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h"
#include "libcef_dll/ctocpp/cookie_visitor_ctocpp.h"
// GLOBAL FUNCTIONS - Body may be edited by hand.
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_get_global_manager()
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
CefRefPtr<CefCookieManager> _retval = CefCookieManager::GetGlobalManager();
// Return type: refptr_same
return CefCookieManagerCppToC::Wrap(_retval);
}
CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager(
const cef_string_t* path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: path
// Execute
CefRefPtr<CefCookieManager> _retval = CefCookieManager::CreateManager(
CefString(path));
// Return type: refptr_same
return CefCookieManagerCppToC::Wrap(_retval);
}
// MEMBER FUNCTIONS - Body may be edited by hand.
int CEF_CALLBACK cookie_manager_visit_all_cookies(
struct _cef_cookie_manager_t* self, struct _cef_cookie_visitor_t* visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor);
if (!visitor)
return 0;
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->VisitAllCookies(
CefCookieVisitorCToCpp::Wrap(visitor));
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_visit_url_cookies(
struct _cef_cookie_manager_t* self, const cef_string_t* url,
int includeHttpOnly, struct _cef_cookie_visitor_t* visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return 0;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor);
if (!visitor)
return 0;
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->VisitUrlCookies(
CefString(url),
includeHttpOnly?true:false,
CefCookieVisitorCToCpp::Wrap(visitor));
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_set_cookie(struct _cef_cookie_manager_t* self,
const cef_string_t* url, const struct _cef_cookie_t* cookie)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return 0;
// Verify param: cookie; type: struct_byref_const
DCHECK(cookie);
if (!cookie)
return 0;
// Translate param: cookie; type: struct_byref_const
CefCookie cookieObj;
if (cookie)
cookieObj.Set(*cookie, false);
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->SetCookie(
CefString(url),
cookieObj);
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_delete_cookies(
struct _cef_cookie_manager_t* self, const cef_string_t* url,
const cef_string_t* cookie_name)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Unverified params: url, cookie_name
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->DeleteCookies(
CefString(url),
CefString(cookie_name));
// Return type: bool
return _retval;
}
int CEF_CALLBACK cookie_manager_set_storage_path(
struct _cef_cookie_manager_t* self, const cef_string_t* path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return 0;
// Unverified params: path
// Execute
bool _retval = CefCookieManagerCppToC::Get(self)->SetStoragePath(
CefString(path));
// Return type: bool
return _retval;
}
// CONSTRUCTOR - Do not edit by hand.
CefCookieManagerCppToC::CefCookieManagerCppToC(CefCookieManager* cls)
: CefCppToC<CefCookieManagerCppToC, CefCookieManager, cef_cookie_manager_t>(
cls)
{
struct_.struct_.visit_all_cookies = cookie_manager_visit_all_cookies;
struct_.struct_.visit_url_cookies = cookie_manager_visit_url_cookies;
struct_.struct_.set_cookie = cookie_manager_set_cookie;
struct_.struct_.delete_cookies = cookie_manager_delete_cookies;
struct_.struct_.set_storage_path = cookie_manager_set_storage_path;
}
#ifndef NDEBUG
template<> long CefCppToC<CefCookieManagerCppToC, CefCookieManager,
cef_cookie_manager_t>::DebugObjCt = 0;
#endif

View File

@ -0,0 +1,37 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#ifndef _COOKIEMANAGER_CPPTOC_H
#define _COOKIEMANAGER_CPPTOC_H
#ifndef BUILDING_CEF_SHARED
#pragma message("Warning: "__FILE__" may be accessed DLL-side only")
#else // BUILDING_CEF_SHARED
#include "include/cef.h"
#include "include/cef_capi.h"
#include "libcef_dll/cpptoc/cpptoc.h"
// Wrap a C++ class with a C structure.
// This class may be instantiated and accessed DLL-side only.
class CefCookieManagerCppToC
: public CefCppToC<CefCookieManagerCppToC, CefCookieManager,
cef_cookie_manager_t>
{
public:
CefCookieManagerCppToC(CefCookieManager* cls);
virtual ~CefCookieManagerCppToC() {}
};
#endif // BUILDING_CEF_SHARED
#endif // _COOKIEMANAGER_CPPTOC_H

View File

@ -14,6 +14,7 @@
#include "libcef_dll/cpptoc/download_handler_cpptoc.h"
#include "libcef_dll/cpptoc/request_handler_cpptoc.h"
#include "libcef_dll/ctocpp/browser_ctocpp.h"
#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h"
#include "libcef_dll/ctocpp/frame_ctocpp.h"
#include "libcef_dll/ctocpp/request_ctocpp.h"
#include "libcef_dll/ctocpp/response_ctocpp.h"
@ -361,6 +362,35 @@ int CEF_CALLBACK request_handler_get_auth_credentials(
}
cef_cookie_manager_t* CEF_CALLBACK request_handler_get_cookie_manager(
struct _cef_request_handler_t* self, cef_browser_t* browser,
const cef_string_t* main_url)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return NULL;
// Verify param: browser; type: refptr_diff
DCHECK(browser);
if (!browser)
return NULL;
// Verify param: main_url; type: string_byref_const
DCHECK(main_url);
if (!main_url)
return NULL;
// Execute
CefRefPtr<CefCookieManager> _retval = CefRequestHandlerCppToC::Get(
self)->GetCookieManager(
CefBrowserCToCpp::Wrap(browser),
CefString(main_url));
// Return type: refptr_diff
return CefCookieManagerCToCpp::Unwrap(_retval);
}
// CONSTRUCTOR - Do not edit by hand.
@ -376,6 +406,7 @@ CefRequestHandlerCppToC::CefRequestHandlerCppToC(CefRequestHandler* cls)
struct_.struct_.on_protocol_execution = request_handler_on_protocol_execution;
struct_.struct_.get_download_handler = request_handler_get_download_handler;
struct_.struct_.get_auth_credentials = request_handler_get_auth_credentials;
struct_.struct_.get_cookie_manager = request_handler_get_cookie_manager;
}
#ifndef NDEBUG

View File

@ -0,0 +1,166 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/cookie_visitor_cpptoc.h"
#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h"
// STATIC METHODS - Body may be edited by hand.
CefRefPtr<CefCookieManager> CefCookieManager::GetGlobalManager()
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Execute
cef_cookie_manager_t* _retval = cef_cookie_manager_get_global_manager();
// Return type: refptr_same
return CefCookieManagerCToCpp::Wrap(_retval);
}
CefRefPtr<CefCookieManager> CefCookieManager::CreateManager(
const CefString& path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: path
// Execute
cef_cookie_manager_t* _retval = cef_cookie_manager_create_manager(
path.GetStruct());
// Return type: refptr_same
return CefCookieManagerCToCpp::Wrap(_retval);
}
// VIRTUAL METHODS - Body may be edited by hand.
bool CefCookieManagerCToCpp::VisitAllCookies(
CefRefPtr<CefCookieVisitor> visitor)
{
if (CEF_MEMBER_MISSING(struct_, visit_all_cookies))
return false;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: visitor; type: refptr_diff
DCHECK(visitor.get());
if (!visitor.get())
return false;
// Execute
int _retval = struct_->visit_all_cookies(struct_,
CefCookieVisitorCppToC::Wrap(visitor));
// Return type: bool
return _retval?true:false;
}
bool CefCookieManagerCToCpp::VisitUrlCookies(const CefString& url,
bool includeHttpOnly, CefRefPtr<CefCookieVisitor> visitor)
{
if (CEF_MEMBER_MISSING(struct_, visit_url_cookies))
return false;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: url; type: string_byref_const
DCHECK(!url.empty());
if (url.empty())
return false;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor.get());
if (!visitor.get())
return false;
// Execute
int _retval = struct_->visit_url_cookies(struct_,
url.GetStruct(),
includeHttpOnly,
CefCookieVisitorCppToC::Wrap(visitor));
// Return type: bool
return _retval?true:false;
}
bool CefCookieManagerCToCpp::SetCookie(const CefString& url,
const CefCookie& cookie)
{
if (CEF_MEMBER_MISSING(struct_, set_cookie))
return false;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: url; type: string_byref_const
DCHECK(!url.empty());
if (url.empty())
return false;
// Execute
int _retval = struct_->set_cookie(struct_,
url.GetStruct(),
&cookie);
// Return type: bool
return _retval?true:false;
}
bool CefCookieManagerCToCpp::DeleteCookies(const CefString& url,
const CefString& cookie_name)
{
if (CEF_MEMBER_MISSING(struct_, delete_cookies))
return false;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: url, cookie_name
// Execute
int _retval = struct_->delete_cookies(struct_,
url.GetStruct(),
cookie_name.GetStruct());
// Return type: bool
return _retval?true:false;
}
bool CefCookieManagerCToCpp::SetStoragePath(const CefString& path)
{
if (CEF_MEMBER_MISSING(struct_, set_storage_path))
return false;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: path
// Execute
int _retval = struct_->set_storage_path(struct_,
path.GetStruct());
// Return type: bool
return _retval?true:false;
}
#ifndef NDEBUG
template<> long CefCToCpp<CefCookieManagerCToCpp, CefCookieManager,
cef_cookie_manager_t>::DebugObjCt = 0;
#endif

View File

@ -0,0 +1,49 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#ifndef _COOKIEMANAGER_CTOCPP_H
#define _COOKIEMANAGER_CTOCPP_H
#ifndef USING_CEF_SHARED
#pragma message("Warning: "__FILE__" may be accessed wrapper-side only")
#else // USING_CEF_SHARED
#include "include/cef.h"
#include "include/cef_capi.h"
#include "libcef_dll/ctocpp/ctocpp.h"
// Wrap a C structure with a C++ class.
// This class may be instantiated and accessed wrapper-side only.
class CefCookieManagerCToCpp
: public CefCToCpp<CefCookieManagerCToCpp, CefCookieManager,
cef_cookie_manager_t>
{
public:
CefCookieManagerCToCpp(cef_cookie_manager_t* str)
: CefCToCpp<CefCookieManagerCToCpp, CefCookieManager,
cef_cookie_manager_t>(str) {}
virtual ~CefCookieManagerCToCpp() {}
// CefCookieManager methods
virtual bool VisitAllCookies(CefRefPtr<CefCookieVisitor> visitor) OVERRIDE;
virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor) OVERRIDE;
virtual bool SetCookie(const CefString& url,
const CefCookie& cookie) OVERRIDE;
virtual bool DeleteCookies(const CefString& url,
const CefString& cookie_name) OVERRIDE;
virtual bool SetStoragePath(const CefString& path) OVERRIDE;
};
#endif // USING_CEF_SHARED
#endif // _COOKIEMANAGER_CTOCPP_H

View File

@ -11,6 +11,7 @@
//
#include "libcef_dll/cpptoc/browser_cpptoc.h"
#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h"
#include "libcef_dll/cpptoc/frame_cpptoc.h"
#include "libcef_dll/cpptoc/request_cpptoc.h"
#include "libcef_dll/cpptoc/response_cpptoc.h"
@ -303,6 +304,33 @@ bool CefRequestHandlerCToCpp::GetAuthCredentials(CefRefPtr<CefBrowser> browser,
}
CefRefPtr<CefCookieManager> CefRequestHandlerCToCpp::GetCookieManager(
CefRefPtr<CefBrowser> browser, const CefString& main_url)
{
if (CEF_MEMBER_MISSING(struct_, get_cookie_manager))
return NULL;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: browser; type: refptr_diff
DCHECK(browser.get());
if (!browser.get())
return NULL;
// Verify param: main_url; type: string_byref_const
DCHECK(!main_url.empty());
if (main_url.empty())
return NULL;
// Execute
cef_cookie_manager_t* _retval = struct_->get_cookie_manager(struct_,
CefBrowserCppToC::Wrap(browser),
main_url.GetStruct());
// Return type: refptr_diff
return CefCookieManagerCppToC::Unwrap(_retval);
}
#ifndef NDEBUG
template<> long CefCToCpp<CefRequestHandlerCToCpp, CefRequestHandler,

View File

@ -55,6 +55,8 @@ public:
const CefString& host, int port, const CefString& realm,
const CefString& scheme, CefString& username,
CefString& password) OVERRIDE;
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser, const CefString& main_url) OVERRIDE;
};
#endif // BUILDING_CEF_SHARED

View File

@ -11,6 +11,7 @@
//
#include "libcef_dll/cpptoc/browser_cpptoc.h"
#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h"
#include "libcef_dll/cpptoc/domdocument_cpptoc.h"
#include "libcef_dll/cpptoc/domevent_cpptoc.h"
#include "libcef_dll/cpptoc/domnode_cpptoc.h"
@ -100,6 +101,7 @@ CEF_EXPORT void cef_shutdown()
// Check that all wrapper objects have been destroyed
DCHECK(CefBrowserCppToC::DebugObjCt == 0);
DCHECK(CefContentFilterCToCpp::DebugObjCt == 0);
DCHECK(CefCookieManagerCppToC::DebugObjCt == 0);
DCHECK(CefCookieVisitorCToCpp::DebugObjCt == 0);
DCHECK(CefDOMDocumentCppToC::DebugObjCt == 0);
DCHECK(CefDOMEventCppToC::DebugObjCt == 0);
@ -451,110 +453,6 @@ CEF_EXPORT int cef_create_url(const struct _cef_urlparts_t* parts,
}
CEF_EXPORT int cef_visit_all_cookies(struct _cef_cookie_visitor_t* visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: visitor; type: refptr_diff
DCHECK(visitor);
if (!visitor)
return 0;
// Execute
bool _retval = CefVisitAllCookies(
CefCookieVisitorCToCpp::Wrap(visitor));
// Return type: bool
return _retval;
}
CEF_EXPORT int cef_visit_url_cookies(const cef_string_t* url,
int includeHttpOnly, struct _cef_cookie_visitor_t* visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return 0;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor);
if (!visitor)
return 0;
// Execute
bool _retval = CefVisitUrlCookies(
CefString(url),
includeHttpOnly?true:false,
CefCookieVisitorCToCpp::Wrap(visitor));
// Return type: bool
return _retval;
}
CEF_EXPORT int cef_set_cookie(const cef_string_t* url,
const struct _cef_cookie_t* cookie)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: url; type: string_byref_const
DCHECK(url);
if (!url)
return 0;
// Verify param: cookie; type: struct_byref_const
DCHECK(cookie);
if (!cookie)
return 0;
// Translate param: cookie; type: struct_byref_const
CefCookie cookieObj;
if (cookie)
cookieObj.Set(*cookie, false);
// Execute
bool _retval = CefSetCookie(
CefString(url),
cookieObj);
// Return type: bool
return _retval;
}
CEF_EXPORT int cef_delete_cookies(const cef_string_t* url,
const cef_string_t* cookie_name)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: url, cookie_name
// Execute
bool _retval = CefDeleteCookies(
CefString(url),
CefString(cookie_name));
// Return type: bool
return _retval;
}
CEF_EXPORT int cef_set_cookie_path(const cef_string_t* path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: path
// Execute
bool _retval = CefSetCookiePath(
CefString(path));
// Return type: bool
return _retval;
}
CEF_EXPORT int cef_visit_storage(enum cef_storage_type_t type,
const cef_string_t* origin, const cef_string_t* key,
struct _cef_storage_visitor_t* visitor)

View File

@ -42,6 +42,7 @@
#include "libcef_dll/cpptoc/web_urlrequest_client_cpptoc.h"
#include "libcef_dll/cpptoc/write_handler_cpptoc.h"
#include "libcef_dll/ctocpp/browser_ctocpp.h"
#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h"
#include "libcef_dll/ctocpp/domdocument_ctocpp.h"
#include "libcef_dll/ctocpp/domevent_ctocpp.h"
#include "libcef_dll/ctocpp/domnode_ctocpp.h"
@ -102,6 +103,7 @@ CEF_GLOBAL void CefShutdown()
// Check that all wrapper objects have been destroyed
DCHECK(CefBrowserCToCpp::DebugObjCt == 0);
DCHECK(CefContentFilterCppToC::DebugObjCt == 0);
DCHECK(CefCookieManagerCToCpp::DebugObjCt == 0);
DCHECK(CefCookieVisitorCppToC::DebugObjCt == 0);
DCHECK(CefDOMDocumentCToCpp::DebugObjCt == 0);
DCHECK(CefDOMEventCToCpp::DebugObjCt == 0);
@ -421,100 +423,6 @@ CEF_GLOBAL bool CefCreateURL(const CefURLParts& parts, CefString& url)
}
CEF_GLOBAL bool CefVisitAllCookies(CefRefPtr<CefCookieVisitor> visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: visitor; type: refptr_diff
DCHECK(visitor.get());
if (!visitor.get())
return false;
// Execute
int _retval = cef_visit_all_cookies(
CefCookieVisitorCppToC::Wrap(visitor));
// Return type: bool
return _retval?true:false;
}
CEF_GLOBAL bool CefVisitUrlCookies(const CefString& url, bool includeHttpOnly,
CefRefPtr<CefCookieVisitor> visitor)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: url; type: string_byref_const
DCHECK(!url.empty());
if (url.empty())
return false;
// Verify param: visitor; type: refptr_diff
DCHECK(visitor.get());
if (!visitor.get())
return false;
// Execute
int _retval = cef_visit_url_cookies(
url.GetStruct(),
includeHttpOnly,
CefCookieVisitorCppToC::Wrap(visitor));
// Return type: bool
return _retval?true:false;
}
CEF_GLOBAL bool CefSetCookie(const CefString& url, const CefCookie& cookie)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: url; type: string_byref_const
DCHECK(!url.empty());
if (url.empty())
return false;
// Execute
int _retval = cef_set_cookie(
url.GetStruct(),
&cookie);
// Return type: bool
return _retval?true:false;
}
CEF_GLOBAL bool CefDeleteCookies(const CefString& url,
const CefString& cookie_name)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: url, cookie_name
// Execute
int _retval = cef_delete_cookies(
url.GetStruct(),
cookie_name.GetStruct());
// Return type: bool
return _retval?true:false;
}
CEF_GLOBAL bool CefSetCookiePath(const CefString& path)
{
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Unverified params: path
// Execute
int _retval = cef_set_cookie_path(
path.GetStruct());
// Return type: bool
return _retval?true:false;
}
CEF_GLOBAL bool CefVisitStorage(CefStorageType type, const CefString& origin,
const CefString& key, CefRefPtr<CefStorageVisitor> visitor)
{

View File

@ -1,14 +1,15 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "base/scoped_temp_dir.h"
#include "base/synchronization/waitable_event.h"
#include <vector>
#include "include/cef.h"
#include "include/cef_runnable.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "test_handler.h"
#include "test_suite.h"
#include <vector>
#include "base/scoped_temp_dir.h"
#include "base/synchronization/waitable_event.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
@ -18,38 +19,36 @@ const char* kTestPath = "/path/to/cookietest";
typedef std::vector<CefCookie> CookieVector;
void IOT_Set(const CefString& url, CookieVector* cookies,
base::WaitableEvent* event)
{
void IOT_Set(CefRefPtr<CefCookieManager> manager,
const CefString& url, CookieVector* cookies,
base::WaitableEvent* event) {
CookieVector::const_iterator it = cookies->begin();
for (; it != cookies->end(); ++it)
EXPECT_TRUE(CefSetCookie(url, *it));
EXPECT_TRUE(manager->SetCookie(url, *it));
event->Signal();
}
void IOT_Delete(const CefString& url, const CefString& cookie_name,
base::WaitableEvent* event)
{
EXPECT_TRUE(CefDeleteCookies(url, cookie_name));
void IOT_Delete(CefRefPtr<CefCookieManager> manager,
const CefString& url, const CefString& cookie_name,
base::WaitableEvent* event) {
EXPECT_TRUE(manager->DeleteCookies(url, cookie_name));
event->Signal();
}
class TestVisitor : public CefCookieVisitor
{
public:
class TestVisitor : public CefCookieVisitor {
public:
TestVisitor(CookieVector* cookies, bool deleteCookies,
base::WaitableEvent* event)
: cookies_(cookies), delete_cookies_(deleteCookies), event_(event)
{
: cookies_(cookies),
delete_cookies_(deleteCookies),
event_(event) {
}
virtual ~TestVisitor()
{
virtual ~TestVisitor() {
event_->Signal();
}
virtual bool Visit(const CefCookie& cookie, int count, int total,
bool& deleteCookie)
{
bool& deleteCookie) {
cookies_->push_back(cookie);
if (delete_cookies_)
deleteCookie = true;
@ -63,11 +62,29 @@ public:
IMPLEMENT_REFCOUNTING(TestVisitor);
};
// Set the cookies.
void SetCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url, CookieVector& cookies,
base::WaitableEvent& event) {
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Set, manager, url,
&cookies, &event));
event.Wait();
}
// Delete the cookie.
void DeleteCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url, const CefString& cookie_name,
base::WaitableEvent& event) {
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, manager, url,
cookie_name, &event));
event.Wait();
}
// Create a test cookie. If |withDomain| is true a domain cookie will be
// created, otherwise a host cookie will be created.
void CreateCookie(CefCookie& cookie, bool withDomain,
base::WaitableEvent& event)
{
void CreateCookie(CefRefPtr<CefCookieManager> manager,
CefCookie& cookie, bool withDomain,
base::WaitableEvent& event) {
CefString(&cookie.name).FromASCII("my_cookie");
CefString(&cookie.value).FromASCII("My Value");
if (withDomain)
@ -83,28 +100,25 @@ void CreateCookie(CefCookie& cookie, bool withDomain,
CookieVector cookies;
cookies.push_back(cookie);
// Set the cookie.
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Set, kTestUrl, &cookies,
&event));
event.Wait();
SetCookies(manager, kTestUrl, cookies, event);
}
// Retrieve the test cookie. If |withDomain| is true check that the cookie
// is a domain cookie, otherwise a host cookie. if |deleteCookies| is true
// the cookie will be deleted when it's retrieved.
void GetCookie(const CefCookie& cookie, bool withDomain,
base::WaitableEvent& event, bool deleteCookies)
{
void GetCookie(CefRefPtr<CefCookieManager> manager,
const CefCookie& cookie, bool withDomain,
base::WaitableEvent& event, bool deleteCookies) {
CookieVector cookies;
// Get the cookie and delete it.
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
EXPECT_TRUE(manager->VisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, deleteCookies, &event)));
event.Wait();
EXPECT_EQ((CookieVector::size_type)1, cookies.size());
const CefCookie& cookie_read = cookies[0];
EXPECT_EQ(CefString(&cookie_read.name), "my_cookie");
EXPECT_EQ(CefString(&cookie_read.value), "My Value");
@ -126,18 +140,41 @@ void GetCookie(const CefCookie& cookie, bool withDomain,
EXPECT_EQ(cookie.expires.millisecond, cookie_read.expires.millisecond);
}
// Visit URL cookies.
void VisitUrlCookies(CefRefPtr<CefCookieManager> manager,
const CefString& url,
bool includeHttpOnly,
CookieVector& cookies,
bool deleteCookies,
base::WaitableEvent& event) {
EXPECT_TRUE(manager->VisitUrlCookies(url, includeHttpOnly,
new TestVisitor(&cookies, deleteCookies, &event)));
event.Wait();
}
// Visit all cookies.
void VisitAllCookies(CefRefPtr<CefCookieManager> manager,
CookieVector& cookies,
bool deleteCookies,
base::WaitableEvent& event) {
EXPECT_TRUE(manager->VisitAllCookies(
new TestVisitor(&cookies, deleteCookies, &event)));
event.Wait();
}
// Verify that no cookies exist. If |withUrl| is true it will only check for
// cookies matching the URL.
void VerifyNoCookies(base::WaitableEvent& event, bool withUrl)
{
void VerifyNoCookies(CefRefPtr<CefCookieManager> manager,
base::WaitableEvent& event, bool withUrl) {
CookieVector cookies;
// Verify that the cookie has been deleted.
if (withUrl) {
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
EXPECT_TRUE(manager->VisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, false, &event)));
} else {
EXPECT_TRUE(CefVisitAllCookies(new TestVisitor(&cookies, false, &event)));
EXPECT_TRUE(manager->VisitAllCookies(
new TestVisitor(&cookies, false, &event)));
}
event.Wait();
@ -145,50 +182,42 @@ void VerifyNoCookies(base::WaitableEvent& event, bool withUrl)
}
// Delete all system cookies.
void DeleteAllCookies(base::WaitableEvent& event)
{
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, CefString(),
void DeleteAllCookies(CefRefPtr<CefCookieManager> manager,
base::WaitableEvent& event) {
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, manager, CefString(),
CefString(), &event));
event.Wait();
}
} // anonymous
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookie)
{
void TestDomainCookie(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
CefCookie cookie;
// Create a domain cookie.
CreateCookie(cookie, true, event);
CreateCookie(manager, cookie, true, event);
// Retrieve, verify and delete the domain cookie.
GetCookie(cookie, true, event, true);
GetCookie(manager, cookie, true, event, true);
// Verify that the cookie was deleted.
VerifyNoCookies(event, true);
VerifyNoCookies(manager, event, true);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookie)
{
void TestHostCookie(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
CefCookie cookie;
// Create a host cookie.
CreateCookie(cookie, false, event);
CreateCookie(manager, cookie, false, event);
// Retrieve, verify and delete the host cookie.
GetCookie(cookie, false, event, true);
GetCookie(manager, cookie, false, event, true);
// Verify that the cookie was deleted.
VerifyNoCookies(event, true);
VerifyNoCookies(manager, event, true);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookies)
{
void TestMultipleCookies(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
std::stringstream ss;
int i;
@ -196,9 +225,9 @@ TEST(CookieTest, MultipleCookies)
CookieVector cookies;
const int kNumCookies = 4;
// Create the cookies.
for(i = 0; i < kNumCookies; i++) {
for (i = 0; i < kNumCookies; i++) {
CefCookie cookie;
ss << "my_cookie" << i;
@ -212,20 +241,16 @@ TEST(CookieTest, MultipleCookies)
}
// Set the cookies.
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Set, kTestUrl, &cookies,
&event));
event.Wait();
SetCookies(manager, kTestUrl, cookies, event);
cookies.clear();
// Get the cookies without deleting them.
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)kNumCookies, cookies.size());
CookieVector::const_iterator it = cookies.begin();
for(i = 0; it != cookies.end(); ++it, ++i) {
for (i = 0; it != cookies.end(); ++it, ++i) {
const CefCookie& cookie = *it;
ss << "my_cookie" << i;
@ -239,14 +264,10 @@ TEST(CookieTest, MultipleCookies)
cookies.clear();
// Delete the 2nd cookie.
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, kTestUrl,
CefString("my_cookie1"), &event));
event.Wait();
DeleteCookies(manager, kTestUrl, CefString("my_cookie1"), event);
// Verify that the cookie has been deleted.
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)3, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie0");
@ -256,19 +277,15 @@ TEST(CookieTest, MultipleCookies)
cookies.clear();
// Delete the rest of the cookies.
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, kTestUrl,
CefString(), &event));
event.Wait();
DeleteCookies(manager, kTestUrl, CefString(), event);
// Verify that the cookies have been deleted.
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
// Create the cookies.
for(i = 0; i < kNumCookies; i++) {
for (i = 0; i < kNumCookies; i++) {
CefCookie cookie;
ss << "my_cookie" << i;
@ -282,34 +299,26 @@ TEST(CookieTest, MultipleCookies)
}
// Delete all of the cookies using the visitor.
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, true, &event)));
event.Wait();
VisitUrlCookies(manager, kTestUrl, false, cookies, true, event);
cookies.clear();
// Verify that the cookies have been deleted.
EXPECT_TRUE(CefVisitUrlCookies(kTestUrl, false,
new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitUrlCookies(manager, kTestUrl, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
}
TEST(CookieTest, AllCookies)
{
void TestAllCookies(CefRefPtr<CefCookieManager> manager) {
base::WaitableEvent event(false, false);
CookieVector cookies;
// Delete all system cookies just in case something is left over from a
// different test.
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Delete, CefString(),
CefString(), &event));
event.Wait();
DeleteCookies(manager, CefString(), CefString(), event);
// Verify that all system cookies have been deleted.
EXPECT_TRUE(CefVisitAllCookies(new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitAllCookies(manager, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)0, cookies.size());
@ -320,8 +329,7 @@ TEST(CookieTest, AllCookies)
CefString(&cookie1.value).FromASCII("My Value 1");
cookies.push_back(cookie1);
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Set, kUrl1, &cookies, &event));
event.Wait();
SetCookies(manager, kUrl1, cookies, event);
cookies.clear();
CefCookie cookie2;
@ -330,13 +338,11 @@ TEST(CookieTest, AllCookies)
CefString(&cookie2.value).FromASCII("My Value 2");
cookies.push_back(cookie2);
CefPostTask(TID_IO, NewCefRunnableFunction(IOT_Set, kUrl2, &cookies, &event));
event.Wait();
SetCookies(manager, kUrl2, cookies, event);
cookies.clear();
// Verify that all system cookies can be retrieved.
EXPECT_TRUE(CefVisitAllCookies(new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitAllCookies(manager, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)2, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie1");
@ -348,9 +354,7 @@ TEST(CookieTest, AllCookies)
cookies.clear();
// Verify that the cookies can be retrieved separately.
EXPECT_TRUE(CefVisitUrlCookies(kUrl1, false,
new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitUrlCookies(manager, kUrl1, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)1, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie1");
@ -358,9 +362,7 @@ TEST(CookieTest, AllCookies)
EXPECT_EQ(CefString(&cookies[0].domain), "www.foo.com");
cookies.clear();
EXPECT_TRUE(CefVisitUrlCookies(kUrl2, false,
new TestVisitor(&cookies, false, &event)));
event.Wait();
VisitUrlCookies(manager, kUrl2, false, cookies, false, event);
EXPECT_EQ((CookieVector::size_type)1, cookies.size());
EXPECT_EQ(CefString(&cookies[0].name), "my_cookie2");
@ -369,52 +371,548 @@ TEST(CookieTest, AllCookies)
cookies.clear();
// Delete all of the system cookies.
DeleteAllCookies(event);
DeleteAllCookies(manager, event);
// Verify that all system cookies have been deleted.
VerifyNoCookies(event, false);
VerifyNoCookies(manager, event, false);
}
TEST(CookieTest, ChangeDirectory)
{
void TestChangeDirectory(CefRefPtr<CefCookieManager> manager,
const CefString& original_dir) {
base::WaitableEvent event(false, false);
CefCookie cookie;
std::string cache_path;
CefTestSuite::GetCachePath(cache_path);
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
// Delete all of the system cookies.
DeleteAllCookies(event);
DeleteAllCookies(manager, event);
// Set the new temporary directory as the storage location.
EXPECT_TRUE(CefSetCookiePath(temp_dir.path().value()));
EXPECT_TRUE(manager->SetStoragePath(temp_dir.path().value()));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
// Verify that no cookies exist.
VerifyNoCookies(event, true);
VerifyNoCookies(manager, event, true);
// Create a domain cookie.
CreateCookie(cookie, true, event);
CreateCookie(manager, cookie, true, event);
// Retrieve and verify the domain cookie.
GetCookie(cookie, true, event, false);
GetCookie(manager, cookie, true, event, false);
// Restore the original storage location.
EXPECT_TRUE(CefSetCookiePath(cache_path));
EXPECT_TRUE(manager->SetStoragePath(original_dir));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
// Verify that no cookies exist.
VerifyNoCookies(event, true);
VerifyNoCookies(manager, event, true);
// Set the new temporary directory as the storage location.
EXPECT_TRUE(CefSetCookiePath(temp_dir.path().value()));
EXPECT_TRUE(manager->SetStoragePath(temp_dir.path().value()));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
// Retrieve and verify the domain cookie that was set previously.
GetCookie(cookie, true, event, false);
GetCookie(manager, cookie, true, event, false);
// Restore the original storage location.
EXPECT_TRUE(CefSetCookiePath(cache_path));
EXPECT_TRUE(manager->SetStoragePath(original_dir));
// Wait for the storage location change to complete on the IO thread.
WaitForIOThread();
}
} // namespace
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookieGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestDomainCookie(manager);
}
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookieInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestDomainCookie(manager);
}
// Test creation of a domain cookie.
TEST(CookieTest, DomainCookieOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestDomainCookie(manager);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookieGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestHostCookie(manager);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookieInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestHostCookie(manager);
}
// Test creation of a host cookie.
TEST(CookieTest, HostCookieOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestHostCookie(manager);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookiesGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestMultipleCookies(manager);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookiesInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestMultipleCookies(manager);
}
// Test creation of multiple cookies.
TEST(CookieTest, MultipleCookiesOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestMultipleCookies(manager);
}
TEST(CookieTest, AllCookiesGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
TestAllCookies(manager);
}
TEST(CookieTest, AllCookiesInMemory) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestAllCookies(manager);
}
TEST(CookieTest, AllCookiesOnDisk) {
ScopedTempDir temp_dir;
// Create a new temporary directory.
EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(temp_dir.path().value());
EXPECT_TRUE(manager.get());
TestAllCookies(manager);
}
TEST(CookieTest, ChangeDirectoryGlobal) {
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
EXPECT_TRUE(manager.get());
std::string cache_path;
CefTestSuite::GetCachePath(cache_path);
TestChangeDirectory(manager, cache_path);
}
TEST(CookieTest, ChangeDirectoryCreated) {
CefRefPtr<CefCookieManager> manager =
CefCookieManager::CreateManager(CefString());
EXPECT_TRUE(manager.get());
TestChangeDirectory(manager, CefString());
}
namespace {
const char* kCookieJSUrl1 = "http://tests/cookie1.html";
const char* kCookieJSUrl2 = "http://tests/cookie2.html";
class CookieTestJSHandler : public TestHandler {
public:
CookieTestJSHandler() {}
virtual void RunTest() OVERRIDE {
// Create =new in-memory managers.
manager1_ = CefCookieManager::CreateManager(CefString());
manager2_ = CefCookieManager::CreateManager(CefString());
std::string page =
"<html><head>"
"<script>"
"document.cookie='name1=value1';"
"</script>"
"</head><body>COOKIE TEST1</body></html>";
AddResource(kCookieJSUrl1, page, "text/html");
page =
"<html><head>"
"<script>"
"document.cookie='name2=value2';"
"</script>"
"</head><body>COOKIE TEST2</body></html>";
AddResource(kCookieJSUrl2, page, "text/html");
// Create the browser
CreateBrowser(kCookieJSUrl1);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
std::string url = frame->GetURL();
if (url == kCookieJSUrl1) {
got_load_end1_.yes();
VerifyCookie(manager1_, url, "name1", "value1", got_cookie1_);
// Go to the next URL
frame->LoadURL(kCookieJSUrl2);
} else {
got_load_end2_.yes();
VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_);
DestroyTest();
}
}
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser,
const CefString& main_url) OVERRIDE {
if (main_url == kCookieJSUrl1) {
// Return the first cookie manager.
got_cookie_manager1_.yes();
return manager1_;
} else {
// Return the second cookie manager.
got_cookie_manager2_.yes();
return manager2_;
}
}
// Verify that the cookie was set successfully.
void VerifyCookie(CefRefPtr<CefCookieManager> manager,
const std::string& url,
const std::string& name,
const std::string& value,
TrackCallback& callback) {
base::WaitableEvent event(false, false);
CookieVector cookies;
// Get the cookie.
VisitUrlCookies(manager, url, false, cookies, false, event);
if (cookies.size() == 1 && CefString(&cookies[0].name) == name &&
CefString(&cookies[0].value) == value) {
callback.yes();
}
}
CefRefPtr<CefCookieManager> manager1_;
CefRefPtr<CefCookieManager> manager2_;
TrackCallback got_cookie_manager1_;
TrackCallback got_cookie_manager2_;
TrackCallback got_load_end1_;
TrackCallback got_load_end2_;
TrackCallback got_cookie1_;
TrackCallback got_cookie2_;
};
} // namespace
// Verify use of multiple cookie managers vis JS.
TEST(CookieTest, GetCookieManagerJS) {
CefRefPtr<CookieTestJSHandler> handler = new CookieTestJSHandler();
handler->ExecuteTest();
EXPECT_TRUE(handler->got_cookie_manager1_);
EXPECT_TRUE(handler->got_cookie_manager2_);
EXPECT_TRUE(handler->got_load_end1_);
EXPECT_TRUE(handler->got_load_end2_);
EXPECT_TRUE(handler->got_cookie1_);
EXPECT_TRUE(handler->got_cookie2_);
}
namespace {
const char* kCookieHttpUrl1 = "http://cookie-tests/cookie1.html";
const char* kCookieHttpUrl2 = "http://cookie-tests/cookie2.html";
const char* kCookieHttpUrl3 = "http://cookie-tests/cookie3.html";
class CookieTestHttpHandler : public TestHandler {
public:
class SchemeHandler : public CefSchemeHandler {
public:
explicit SchemeHandler(CookieTestHttpHandler* handler)
: handler_(handler),
offset_(0) {}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefSchemeHandlerCallback> callback)
OVERRIDE {
std::string url = request->GetURL();
if (url == kCookieHttpUrl1) {
content_ = "<html><body>COOKIE TEST1</body></html>";
cookie_ = "name1=value1";
handler_->got_process_request1_.yes();
} else if (url == kCookieHttpUrl2) {
content_ = "<html><body>COOKIE TEST2</body></html>";
cookie_ = "name2=value2";
handler_->got_process_request2_.yes();
} else if (url == kCookieHttpUrl3) {
content_ = "<html><body>COOKIE TEST3</body></html>";
handler_->got_process_request3_.yes();
// Verify that the cookie was passed in.
CefRequest::HeaderMap headerMap;
request->GetHeaderMap(headerMap);
CefRequest::HeaderMap::iterator it = headerMap.find("Cookie");
if (it != headerMap.end() && it->second == "name2=value2")
handler_->got_process_request_cookie_.yes();
}
callback->HeadersAvailable();
return true;
}
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length,
CefString& redirectUrl) OVERRIDE {
response_length = content_.size();
response->SetStatus(200);
response->SetMimeType("text/html");
if (!cookie_.empty()) {
CefResponse::HeaderMap headerMap;
response->GetHeaderMap(headerMap);
headerMap.insert(std::make_pair("Set-Cookie", cookie_));
response->SetHeaderMap(headerMap);
}
}
virtual bool ReadResponse(void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefSchemeHandlerCallback> callback)
OVERRIDE {
bool has_data = false;
bytes_read = 0;
size_t size = content_.size();
if (offset_ < size) {
int transfer_size =
std::min(bytes_to_read, static_cast<int>(size - offset_));
memcpy(data_out, content_.c_str() + offset_, transfer_size);
offset_ += transfer_size;
bytes_read = transfer_size;
has_data = true;
}
return has_data;
}
virtual void Cancel() OVERRIDE {
}
private:
CookieTestHttpHandler* handler_;
std::string content_;
size_t offset_;
std::string cookie_;
IMPLEMENT_REFCOUNTING(SchemeHandler);
};
class SchemeHandlerFactory : public CefSchemeHandlerFactory {
public:
explicit SchemeHandlerFactory(CookieTestHttpHandler* handler)
: handler_(handler) {}
virtual CefRefPtr<CefSchemeHandler> Create(CefRefPtr<CefBrowser> browser,
const CefString& scheme_name,
CefRefPtr<CefRequest> request)
OVERRIDE {
std::string url = request->GetURL();
if (url == kCookieHttpUrl3) {
// Verify that the cookie was not passed in.
CefRequest::HeaderMap headerMap;
request->GetHeaderMap(headerMap);
CefRequest::HeaderMap::iterator it = headerMap.find("Cookie");
if (it != headerMap.end() && it->second == "name2=value2")
handler_->got_create_cookie_.yes();
}
return new SchemeHandler(handler_);
}
private:
CookieTestHttpHandler* handler_;
IMPLEMENT_REFCOUNTING(SchemeHandlerFactory);
};
CookieTestHttpHandler() {}
virtual void RunTest() OVERRIDE {
// Create new in-memory managers.
manager1_ = CefCookieManager::CreateManager(CefString());
manager2_ = CefCookieManager::CreateManager(CefString());
// Register the scheme handler.
CefRegisterSchemeHandlerFactory("http", "cookie-tests",
new SchemeHandlerFactory(this));
// Create the browser
CreateBrowser(kCookieHttpUrl1);
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
std::string url = frame->GetURL();
if (url == kCookieHttpUrl1) {
got_load_end1_.yes();
VerifyCookie(manager1_, url, "name1", "value1", got_cookie1_);
// Go to the next URL
frame->LoadURL(kCookieHttpUrl2);
} else if (url == kCookieHttpUrl2) {
got_load_end2_.yes();
VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_);
// Go to the next URL
frame->LoadURL(kCookieHttpUrl3);
} else {
got_load_end3_.yes();
VerifyCookie(manager2_, url, "name2", "value2", got_cookie3_);
// Unregister the scheme handler.
CefRegisterSchemeHandlerFactory("http", "cookie-tests", NULL);
DestroyTest();
}
}
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser,
const CefString& main_url) OVERRIDE {
if (main_url == kCookieHttpUrl1) {
// Return the first cookie manager.
got_cookie_manager1_.yes();
return manager1_;
} else {
// Return the second cookie manager.
got_cookie_manager2_.yes();
return manager2_;
}
}
// Verify that the cookie was set successfully.
void VerifyCookie(CefRefPtr<CefCookieManager> manager,
const std::string& url,
const std::string& name,
const std::string& value,
TrackCallback& callback) {
base::WaitableEvent event(false, false);
CookieVector cookies;
// Get the cookie.
VisitUrlCookies(manager, url, false, cookies, false, event);
if (cookies.size() == 1 && CefString(&cookies[0].name) == name &&
CefString(&cookies[0].value) == value) {
callback.yes();
}
}
CefRefPtr<CefCookieManager> manager1_;
CefRefPtr<CefCookieManager> manager2_;
TrackCallback got_process_request1_;
TrackCallback got_process_request2_;
TrackCallback got_process_request3_;
TrackCallback got_create_cookie_;
TrackCallback got_process_request_cookie_;
TrackCallback got_cookie_manager1_;
TrackCallback got_cookie_manager2_;
TrackCallback got_load_end1_;
TrackCallback got_load_end2_;
TrackCallback got_load_end3_;
TrackCallback got_cookie1_;
TrackCallback got_cookie2_;
TrackCallback got_cookie3_;
};
} // namespace
// Verify use of multiple cookie managers vis HTTP.
TEST(CookieTest, GetCookieManagerHttp) {
CefRefPtr<CookieTestHttpHandler> handler = new CookieTestHttpHandler();
handler->ExecuteTest();
EXPECT_TRUE(handler->got_process_request1_);
EXPECT_TRUE(handler->got_process_request2_);
EXPECT_TRUE(handler->got_process_request3_);
EXPECT_FALSE(handler->got_create_cookie_);
EXPECT_TRUE(handler->got_process_request_cookie_);
EXPECT_TRUE(handler->got_cookie_manager1_);
EXPECT_TRUE(handler->got_cookie_manager2_);
EXPECT_TRUE(handler->got_load_end1_);
EXPECT_TRUE(handler->got_load_end2_);
EXPECT_TRUE(handler->got_load_end3_);
EXPECT_TRUE(handler->got_cookie1_);
EXPECT_TRUE(handler->got_cookie2_);
EXPECT_TRUE(handler->got_cookie3_);
}