Create 2272 release branch for CEF3.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/2272@1993 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
This commit is contained in:
Marshall Greenblatt
2015-01-24 03:26:25 +00:00
parent 0d6bfeb4dd
commit dc47bc006a
1045 changed files with 190843 additions and 0 deletions

345
libcef/common/base_impl.cc Normal file
View File

@@ -0,0 +1,345 @@
// Copyright (c) 2014 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 "include/internal/cef_trace_event_internal.h"
#include "include/internal/cef_logging_internal.h"
#include "include/internal/cef_thread_internal.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/threading/platform_thread.h"
// The contents of this file are a compilation unit that is not called by other
// functions in the the library. Consiquently MSVS will exclude it during the
// linker stage if we don't call a stub function.
#if defined(COMPILER_MSVC)
#pragma optimize("", off)
#endif
void base_impl_stub() {}
#if defined(COMPILER_MSVC)
#pragma optimize("", on)
#endif
CEF_EXPORT void cef_trace_event_instant(const char* category,
const char* name,
const char* arg1_name,
uint64 arg1_val,
const char* arg2_name,
uint64 arg2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_COPY_INSTANT0(category, name, TRACE_EVENT_SCOPE_THREAD);
} else if (arg2_name == NULL) {
TRACE_EVENT_COPY_INSTANT1(category, name, TRACE_EVENT_SCOPE_THREAD,
arg1_name, arg1_val);
} else {
TRACE_EVENT_COPY_INSTANT2(category, name, TRACE_EVENT_SCOPE_THREAD,
arg1_name, arg1_val, arg2_name, arg2_val);
}
} else {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_INSTANT0(category, name, TRACE_EVENT_SCOPE_THREAD);
} else if (arg2_name == NULL) {
TRACE_EVENT_INSTANT1(category, name, TRACE_EVENT_SCOPE_THREAD,
arg1_name, arg1_val);
} else {
TRACE_EVENT_INSTANT2(category, name, TRACE_EVENT_SCOPE_THREAD,
arg1_name, arg1_val, arg2_name, arg2_val);
}
}
}
CEF_EXPORT void cef_trace_event_begin(const char* category,
const char* name,
const char* arg1_name,
uint64 arg1_val,
const char* arg2_name,
uint64 arg2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_COPY_BEGIN0(category, name);
} else if (arg2_name == NULL) {
TRACE_EVENT_COPY_BEGIN1(category, name, arg1_name, arg1_val);
} else {
TRACE_EVENT_COPY_BEGIN2(category, name, arg1_name, arg1_val,
arg2_name, arg2_val);
}
} else {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_BEGIN0(category, name);
} else if (arg2_name == NULL) {
TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val);
} else {
TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val,
arg2_name, arg2_val);
}
}
}
CEF_EXPORT void cef_trace_event_end(const char* category,
const char* name,
const char* arg1_name,
uint64 arg1_val,
const char* arg2_name,
uint64 arg2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_COPY_END0(category, name);
} else if (arg2_name == NULL) {
TRACE_EVENT_COPY_END1(category, name, arg1_name, arg1_val);
} else {
TRACE_EVENT_COPY_END2(category, name, arg1_name, arg1_val,
arg2_name, arg2_val);
}
} else {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_END0(category, name);
} else if (arg2_name == NULL) {
TRACE_EVENT_END1(category, name, arg1_name, arg1_val);
} else {
TRACE_EVENT_END2(category, name, arg1_name, arg1_val,
arg2_name, arg2_val);
}
}
}
CEF_EXPORT void cef_trace_counter(const char* category,
const char* name,
const char* value1_name,
uint64 value1_val,
const char* value2_name,
uint64 value2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (value1_name == NULL && value2_name == NULL) {
TRACE_COPY_COUNTER1(category, name, value1_val);
} else {
TRACE_COPY_COUNTER2(category, name, value1_name, value1_val,
value2_name, value2_val);
}
} else {
if (value1_name == NULL && value2_name == NULL) {
TRACE_COUNTER1(category, name, value1_val);
} else {
TRACE_COUNTER2(category, name, value1_name, value1_val,
value2_name, value2_val);
}
}
}
CEF_EXPORT void cef_trace_counter_id(const char* category,
const char* name,
uint64 id,
const char* value1_name,
uint64 value1_val,
const char* value2_name,
uint64 value2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (value1_name == NULL && value2_name == NULL) {
TRACE_COPY_COUNTER_ID1(category, name, id, value1_val);
} else {
TRACE_COPY_COUNTER_ID2(category, name, id, value1_name,
value1_val, value2_name, value2_val);
}
} else {
if (value1_name == NULL && value2_name == NULL) {
TRACE_COUNTER_ID1(category, name, id, value1_val);
} else {
TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val,
value2_name, value2_val);
}
}
}
CEF_EXPORT void cef_trace_event_async_begin(const char* category,
const char* name,
uint64 id,
const char* arg1_name,
uint64 arg1_val,
const char* arg2_name,
uint64 arg2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_COPY_ASYNC_BEGIN0(category, name, id);
} else if (arg2_name == NULL) {
TRACE_EVENT_COPY_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val);
} else {
TRACE_EVENT_COPY_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val,
arg2_name, arg2_val);
}
} else {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_ASYNC_BEGIN0(category, name, id);
} else if (arg2_name == NULL) {
TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val);
} else {
TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val,
arg2_name, arg2_val);
}
}
}
CEF_EXPORT void cef_trace_event_async_step_into(const char* category,
const char* name,
uint64 id,
uint64 step,
const char* arg1_name,
uint64 arg1_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL) {
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_INTO,
category, name, id, TRACE_EVENT_FLAG_COPY, "step", step);
} else {
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_INTO,
category, name, id, TRACE_EVENT_FLAG_COPY, "step", step,
arg1_name, arg1_val);
}
} else {
if (arg1_name == NULL) {
TRACE_EVENT_ASYNC_STEP_INTO0(category, name, id, step);
} else {
TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step,
arg1_name, arg1_val);
}
}
}
CEF_EXPORT void cef_trace_event_async_step_past(const char* category,
const char* name,
uint64 id,
uint64 step,
const char* arg1_name,
uint64 arg1_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL) {
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_PAST,
category, name, id, TRACE_EVENT_FLAG_COPY, "step", step);
} else {
INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_PAST,
category, name, id, TRACE_EVENT_FLAG_COPY, "step", step,
arg1_name, arg1_val);
}
} else {
if (arg1_name == NULL) {
TRACE_EVENT_ASYNC_STEP_PAST0(category, name, id, step);
} else {
TRACE_EVENT_ASYNC_STEP_PAST1(category, name, id, step,
arg1_name, arg1_val);
}
}
}
CEF_EXPORT void cef_trace_event_async_end(const char* category,
const char* name,
uint64 id,
const char* arg1_name,
uint64 arg1_val,
const char* arg2_name,
uint64 arg2_val,
int copy) {
DCHECK(category);
DCHECK(name);
if (!category || !name)
return;
if (copy) {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_COPY_ASYNC_END0(category, name, id);
} else if (arg2_name == NULL) {
TRACE_EVENT_COPY_ASYNC_END1(category, name, id, arg1_name,
arg1_val);
} else {
TRACE_EVENT_COPY_ASYNC_END2(category, name, id, arg1_name,
arg1_val, arg2_name, arg2_val);
}
} else {
if (arg1_name == NULL && arg2_name == NULL) {
TRACE_EVENT_ASYNC_END0(category, name, id);
} else if (arg2_name == NULL) {
TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name,
arg1_val);
} else {
TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name,
arg1_val, arg2_name, arg2_val);
}
}
}
CEF_EXPORT int cef_get_min_log_level() {
return logging::GetMinLogLevel();
}
CEF_EXPORT int cef_get_vlog_level(const char* file_start, size_t N) {
return logging::GetVlogLevelHelper(file_start, N);
}
CEF_EXPORT void cef_log(const char* file,
int line,
int severity,
const char* message) {
logging::LogMessage(file, line, severity).stream() << message;
}
CEF_EXPORT cef_platform_thread_id_t cef_get_current_platform_thread_id() {
return base::PlatformThread::CurrentId();
}
CEF_EXPORT cef_platform_thread_handle_t
cef_get_current_platform_thread_handle() {
#if defined(OS_WIN)
return base::PlatformThread::CurrentId();
#else
return base::PlatformThread::CurrentHandle().platform_handle();
#endif
}

View File

@@ -0,0 +1,33 @@
// Copyright (c) 2012 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.
// Get basic type definitions.
#define IPC_MESSAGE_IMPL
#include "libcef/common/cef_message_generator.h"
// Generate constructors.
#include "ipc/struct_constructor_macros.h"
#include "libcef/common/cef_message_generator.h"
// Generate destructors.
#include "ipc/struct_destructor_macros.h"
#include "libcef/common/cef_message_generator.h"
// Generate param traits write methods.
#include "ipc/param_traits_write_macros.h"
namespace IPC {
#include "libcef/common/cef_message_generator.h"
} // namespace IPC
// Generate param traits read methods.
#include "ipc/param_traits_read_macros.h"
namespace IPC {
#include "libcef/common/cef_message_generator.h"
} // namespace IPC
// Generate param traits log methods.
#include "ipc/param_traits_log_macros.h"
namespace IPC {
#include "libcef/common/cef_message_generator.h"
} // namespace IPC

View File

@@ -0,0 +1,7 @@
// Copyright (c) 2011 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.
// Multiply-included file, hence no include guard.
#include "libcef/common/cef_messages.h"

View File

@@ -0,0 +1,116 @@
// Copyright (c) 2012 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 "libcef/common/cef_messages.h"
namespace IPC {
// Extracted from chrome/common/automation_messages.cc.
// Only the net::UploadData ParamTraits<> definition needs this definition, so
// keep this in the implementation file so we can forward declare UploadData in
// the header.
template <>
struct ParamTraits<net::UploadElement> {
typedef net::UploadElement param_type;
static void Write(Message* m, const param_type& p) {
WriteParam(m, static_cast<int>(p.type()));
switch (p.type()) {
case net::UploadElement::TYPE_BYTES: {
m->WriteData(p.bytes(), static_cast<int>(p.bytes_length()));
break;
}
default: {
DCHECK(p.type() == net::UploadElement::TYPE_FILE);
WriteParam(m, p.file_path());
WriteParam(m, p.file_range_offset());
WriteParam(m, p.file_range_length());
WriteParam(m, p.expected_file_modification_time());
break;
}
}
}
static bool Read(const Message* m, PickleIterator* iter, param_type* r) {
int type;
if (!ReadParam(m, iter, &type))
return false;
switch (type) {
case net::UploadElement::TYPE_BYTES: {
const char* data;
int len;
if (!iter->ReadData(&data, &len))
return false;
r->SetToBytes(data, len);
break;
}
default: {
DCHECK(type == net::UploadElement::TYPE_FILE);
base::FilePath file_path;
uint64 offset, length;
base::Time expected_modification_time;
if (!ReadParam(m, iter, &file_path))
return false;
if (!ReadParam(m, iter, &offset))
return false;
if (!ReadParam(m, iter, &length))
return false;
if (!ReadParam(m, iter, &expected_modification_time))
return false;
r->SetToFilePathRange(file_path, offset, length,
expected_modification_time);
break;
}
}
return true;
}
static void Log(const param_type& p, std::string* l) {
l->append("<net::UploadElement>");
}
};
void ParamTraits<scoped_refptr<net::UploadData> >::Write(Message* m,
const param_type& p) {
WriteParam(m, p.get() != NULL);
if (p.get()) {
WriteParam(m, p->elements());
WriteParam(m, p->identifier());
WriteParam(m, p->is_chunked());
WriteParam(m, p->last_chunk_appended());
}
}
bool ParamTraits<scoped_refptr<net::UploadData> >::Read(const Message* m,
PickleIterator* iter,
param_type* r) {
bool has_object;
if (!ReadParam(m, iter, &has_object))
return false;
if (!has_object)
return true;
ScopedVector<net::UploadElement> elements;
if (!ReadParam(m, iter, &elements))
return false;
int64 identifier;
if (!ReadParam(m, iter, &identifier))
return false;
bool is_chunked = false;
if (!ReadParam(m, iter, &is_chunked))
return false;
bool last_chunk_appended = false;
if (!ReadParam(m, iter, &last_chunk_appended))
return false;
*r = new net::UploadData;
(*r)->swap_elements(&elements);
(*r)->set_identifier(identifier);
(*r)->set_is_chunked(is_chunked);
(*r)->set_last_chunk_appended(last_chunk_appended);
return true;
}
void ParamTraits<scoped_refptr<net::UploadData> >::Log(const param_type& p,
std::string* l) {
l->append("<net::UploadData>");
}
} // namespace IPC

View File

@@ -0,0 +1,221 @@
// Copyright (c) 2012 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2011 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.
// IPC messages for CEF.
// Multiply-included message file, hence no include guard.
#include "libcef/common/upload_data.h"
#include "base/memory/shared_memory.h"
#include "base/values.h"
#include "content/public/common/common_param_traits.h"
#include "content/public/common/referrer.h"
#include "ipc/ipc_message_macros.h"
// TODO(cef): Re-using the message start for extensions may be problematic in
// the future. It would be better if ipc_message_utils.h contained a value
// reserved for consumers of the content API.
// See: http://crbug.com/110911
#define IPC_MESSAGE_START ExtensionMsgStart
// Common types.
// Parameters structure for a request.
IPC_STRUCT_BEGIN(Cef_Request_Params)
// Unique request id to match requests and responses.
IPC_STRUCT_MEMBER(int, request_id)
// Unique id of the target frame. -1 if unknown / invalid.
IPC_STRUCT_MEMBER(int64, frame_id)
// True if the request is user-initiated instead of internal.
IPC_STRUCT_MEMBER(bool, user_initiated)
// True if a response is expected.
IPC_STRUCT_MEMBER(bool, expect_response)
// Message name.
IPC_STRUCT_MEMBER(std::string, name)
// List of message arguments.
IPC_STRUCT_MEMBER(base::ListValue, arguments)
IPC_STRUCT_END()
// Parameters structure for a response.
IPC_STRUCT_BEGIN(Cef_Response_Params)
// Unique request id to match requests and responses.
IPC_STRUCT_MEMBER(int, request_id)
// True if a response ack is expected.
IPC_STRUCT_MEMBER(bool, expect_response_ack)
// True on success.
IPC_STRUCT_MEMBER(bool, success)
// Response or error string depending on the value of |success|.
IPC_STRUCT_MEMBER(std::string, response)
IPC_STRUCT_END()
// Parameters structure for a cross-origin white list entry.
IPC_STRUCT_BEGIN(Cef_CrossOriginWhiteListEntry_Params)
IPC_STRUCT_MEMBER(std::string, source_origin)
IPC_STRUCT_MEMBER(std::string, target_protocol)
IPC_STRUCT_MEMBER(std::string, target_domain)
IPC_STRUCT_MEMBER(bool, allow_target_subdomains)
IPC_STRUCT_END()
// Messages sent from the browser to the renderer.
// Parameters for a resource request.
IPC_STRUCT_BEGIN(CefMsg_LoadRequest_Params)
// The request method: GET, POST, etc.
IPC_STRUCT_MEMBER(std::string, method)
// The requested URL.
IPC_STRUCT_MEMBER(GURL, url)
// The URL to send in the "Referer" header field. Can be empty if there is
// no referrer.
IPC_STRUCT_MEMBER(GURL, referrer)
// One of the blink::WebReferrerPolicy values.
IPC_STRUCT_MEMBER(int, referrer_policy)
// Identifies the frame within the RenderView that sent the request.
// -1 if unknown / invalid.
IPC_STRUCT_MEMBER(int64, frame_id)
// Usually the URL of the document in the top-level window, which may be
// checked by the third-party cookie blocking policy. Leaving it empty may
// lead to undesired cookie blocking. Third-party cookie blocking can be
// bypassed by setting first_party_for_cookies = url, but this should ideally
// only be done if there really is no way to determine the correct value.
IPC_STRUCT_MEMBER(GURL, first_party_for_cookies)
// Additional HTTP request headers.
IPC_STRUCT_MEMBER(std::string, headers)
// net::URLRequest load flags (0 by default).
IPC_STRUCT_MEMBER(int, load_flags)
// Optional upload data (may be null).
IPC_STRUCT_MEMBER(scoped_refptr<net::UploadData>, upload_data)
IPC_STRUCT_END()
// Tell the renderer to load a request.
IPC_MESSAGE_ROUTED1(CefMsg_LoadRequest,
CefMsg_LoadRequest_Params)
// Sent when the browser has a request for the renderer. The renderer may
// respond with a CefHostMsg_Response.
IPC_MESSAGE_ROUTED1(CefMsg_Request,
Cef_Request_Params)
// Optional message sent in response to a CefHostMsg_Request.
IPC_MESSAGE_ROUTED1(CefMsg_Response,
Cef_Response_Params)
// Optional Ack message sent to the browser to notify that a CefHostMsg_Response
// has been processed.
IPC_MESSAGE_ROUTED1(CefMsg_ResponseAck,
int /* request_id */)
// Sent to child processes to add or remove a cross-origin whitelist entry.
IPC_MESSAGE_CONTROL2(CefProcessMsg_ModifyCrossOriginWhitelistEntry,
bool /* add */,
Cef_CrossOriginWhiteListEntry_Params /* params */)
// Sent to child processes to clear the cross-origin whitelist.
IPC_MESSAGE_CONTROL0(CefProcessMsg_ClearCrossOriginWhitelist)
// Messages sent from the renderer to the browser.
// Parameters for a newly created render thread.
IPC_STRUCT_BEGIN(CefProcessHostMsg_GetNewRenderThreadInfo_Params)
IPC_STRUCT_MEMBER(std::vector<Cef_CrossOriginWhiteListEntry_Params>,
cross_origin_whitelist_entries)
IPC_STRUCT_MEMBER(base::ListValue, extra_info)
IPC_STRUCT_END()
// Retrieve information about a newly created render thread.
IPC_SYNC_MESSAGE_CONTROL0_1(
CefProcessHostMsg_GetNewRenderThreadInfo,
CefProcessHostMsg_GetNewRenderThreadInfo_Params /* params*/)
// Parameters for a newly created browser window.
IPC_STRUCT_BEGIN(CefProcessHostMsg_GetNewBrowserInfo_Params)
IPC_STRUCT_MEMBER(int, browser_id)
IPC_STRUCT_MEMBER(bool, is_popup)
IPC_STRUCT_MEMBER(bool, is_windowless)
IPC_STRUCT_END()
// Retrieve information about a newly created browser.
IPC_SYNC_MESSAGE_CONTROL2_1(
CefProcessHostMsg_GetNewBrowserInfo,
int /* render_view_routing_id */,
int /* render_frame_routing_id */,
CefProcessHostMsg_GetNewBrowserInfo_Params /* params*/)
// Sent when a frame is identified for the first time.
IPC_MESSAGE_ROUTED3(CefHostMsg_FrameIdentified,
int64 /* frame_id */,
int64 /* parent_frame_id */,
base::string16 /* frame_name */)
// Sent when a frame has finished loading. Based on ViewHostMsg_DidFinishLoad.
IPC_MESSAGE_ROUTED4(CefHostMsg_DidFinishLoad,
int64 /* frame_id */,
GURL /* validated_url */,
bool /* is_main_frame */,
int /* http_status_code */)
// Sent when a new URL is about to be loaded in the main frame. Used for the
// cookie manager.
IPC_MESSAGE_ROUTED1(CefHostMsg_LoadingURLChange,
GURL /* loading_url */)
// Sent when the renderer has a request for the browser. The browser may respond
// with a CefMsg_Response.
IPC_MESSAGE_ROUTED1(CefHostMsg_Request,
Cef_Request_Params)
// Optional message sent in response to a CefMsg_Request.
IPC_MESSAGE_ROUTED1(CefHostMsg_Response,
Cef_Response_Params)
// Optional Ack message sent to the browser to notify that a CefMsg_Response
// has been processed.
IPC_MESSAGE_ROUTED1(CefHostMsg_ResponseAck,
int /* request_id */)
// Singly-included section for struct and custom IPC traits.
#ifndef CEF_LIBCEF_COMMON_CEF_MESSAGES_H_
#define CEF_LIBCEF_COMMON_CEF_MESSAGES_H_
namespace IPC {
// Extracted from chrome/common/automation_messages.h.
template <>
struct ParamTraits<scoped_refptr<net::UploadData> > {
typedef scoped_refptr<net::UploadData> param_type;
static void Write(Message* m, const param_type& p);
static bool Read(const Message* m, PickleIterator* iter, param_type* r);
static void Log(const param_type& p, std::string* l);
};
} // namespace IPC
#endif // CEF_LIBCEF_COMMON_CEF_MESSAGES_H_
#include "chrome/common/print_messages.h"
#include "chrome/common/spellcheck_messages.h"
#if defined(OS_WIN)
#include "chrome/common/chrome_utility_printing_messages.h"
#endif

View File

@@ -0,0 +1,97 @@
// 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/common/cef_switches.h"
namespace switches {
// Log file path.
const char kLogFile[] = "log-file";
// Severity of messages to log.
const char kLogSeverity[] = "log-severity";
const char kLogSeverity_Verbose[] = "verbose";
const char kLogSeverity_Info[] = "info";
const char kLogSeverity_Warning[] = "warning";
const char kLogSeverity_Error[] = "error";
const char kLogSeverity_Disable[] = "disable";
// Path to resources directory.
const char kResourcesDirPath[] = "resources-dir-path";
// Path to locales directory.
const char kLocalesDirPath[] = "locales-dir-path";
// Path to locales directory.
const char kDisablePackLoading[] = "disable-pack-loading";
// Stack size for uncaught exceptions.
const char kUncaughtExceptionStackSize[] = "uncaught-exception-stack-size";
// Context safety implementation type.
const char kContextSafetyImplementation[] = "context-safety-implementation";
// Default encoding.
const char kDefaultEncoding[] = "default-encoding";
// Disable opening of windows via JavaScript.
const char kDisableJavascriptOpenWindows[] =
"disable-javascript-open-windows";
// Disable closing of windows via JavaScript.
const char kDisableJavascriptCloseWindows[] =
"disable-javascript-close-windows";
// Disable clipboard access via JavaScript.
const char kDisableJavascriptAccessClipboard[] =
"disable-javascript-access-clipboard";
// Disable DOM paste via JavaScript execCommand("paste").
const char kDisableJavascriptDomPaste[] = "disable-javascript-dom-paste";
// Enable caret browsing.
const char kEnableCaretBrowsing[] = "enable-caret-browsing";
// Allow universal access from file URLs.
const char kAllowUniversalAccessFromFileUrls[] =
"allow-universal-access-from-files";
// Disable loading of images from the network. A cached image will still be
// rendered if requested.
const char kDisableImageLoading[] = "disable-image-loading";
// Shrink stand-alone images to fit.
const char kImageShrinkStandaloneToFit[] = "image-shrink-standalone-to-fit";
// Disable resizing of text areas.
const char kDisableTextAreaResize[] = "disable-text-area-resize";
// Disable using the tab key to advance focus to links.
const char kDisableTabToLinks[] = "disable-tab-to-links";
// Persist session cookies.
const char kPersistSessionCookies[] = "persist-session-cookies";
// Enable media (WebRTC audio/video) streaming.
const char kEnableMediaStream[] = "enable-media-stream";
// Enable speech input (x-webkit-speech).
const char kEnableSpeechInput[] = "enable-speech-input";
// Enable the speech input profanity filter.
const char kEnableProfanityFilter[] = "enable-profanity-filter";
// The directory breakpad should store minidumps in.
const char kCrashDumpsDir[] = "crash-dumps-dir";
// Disable spell checking.
const char kDisableSpellChecking[] = "disable-spell-checking";
// Enable the remote spelling service.
const char kEnableSpellingService[] = "enable-spelling-service";
// Override the default spellchecking language which comes from locales.pak.
const char kOverrideSpellCheckLang[] = "override-spell-check-lang";
} // namespace switches

View File

@@ -0,0 +1,47 @@
// 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.
// Defines all the "cef" command-line switches.
#ifndef CEF_LIBCEF_COMMON_CEF_SWITCHES_H_
#define CEF_LIBCEF_COMMON_CEF_SWITCHES_H_
#pragma once
namespace switches {
extern const char kLogFile[];
extern const char kLogSeverity[];
extern const char kLogSeverity_Verbose[];
extern const char kLogSeverity_Info[];
extern const char kLogSeverity_Warning[];
extern const char kLogSeverity_Error[];
extern const char kLogSeverity_Disable[];
extern const char kResourcesDirPath[];
extern const char kLocalesDirPath[];
extern const char kDisablePackLoading[];
extern const char kUncaughtExceptionStackSize[];
extern const char kContextSafetyImplementation[];
extern const char kDefaultEncoding[];
extern const char kDisableJavascriptOpenWindows[];
extern const char kDisableJavascriptCloseWindows[];
extern const char kDisableJavascriptAccessClipboard[];
extern const char kDisableJavascriptDomPaste[];
extern const char kEnableCaretBrowsing[];
extern const char kAllowUniversalAccessFromFileUrls[];
extern const char kDisableImageLoading[];
extern const char kImageShrinkStandaloneToFit[];
extern const char kDisableTextAreaResize[];
extern const char kDisableTabToLinks[];
extern const char kPersistSessionCookies[];
extern const char kEnableMediaStream[];
extern const char kEnableSpeechInput[];
extern const char kEnableProfanityFilter[];
extern const char kCrashDumpsDir[];
extern const char kDisableSpellChecking[];
extern const char kEnableSpellingService[];
extern const char kOverrideSpellCheckLang[];
} // namespace switches
#endif // CEF_LIBCEF_COMMON_CEF_SWITCHES_H_

View File

@@ -0,0 +1,159 @@
// 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/common/command_line_impl.h"
#include "base/files/file_path.h"
#include "base/logging.h"
CefCommandLineImpl::CefCommandLineImpl(base::CommandLine* value,
bool will_delete,
bool read_only)
: CefValueBase<CefCommandLine, base::CommandLine>(
value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete,
read_only, NULL) {
}
bool CefCommandLineImpl::IsValid() {
return !detached();
}
bool CefCommandLineImpl::IsReadOnly() {
return read_only();
}
CefRefPtr<CefCommandLine> CefCommandLineImpl::Copy() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return new CefCommandLineImpl(
new base::CommandLine(const_value().argv()), true, false);
}
void CefCommandLineImpl::InitFromArgv(int argc, const char* const* argv) {
#if !defined(OS_WIN)
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->InitFromArgv(argc, argv);
#else
NOTREACHED() << "method not supported on this platform";
#endif
}
void CefCommandLineImpl::InitFromString(const CefString& command_line) {
#if defined(OS_WIN)
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->ParseFromString(command_line);
#else
NOTREACHED() << "method not supported on this platform";
#endif
}
void CefCommandLineImpl::Reset() {
CEF_VALUE_VERIFY_RETURN_VOID(true);
base::CommandLine::StringVector argv;
argv.push_back(mutable_value()->GetProgram().value());
mutable_value()->InitFromArgv(argv);
const base::CommandLine::SwitchMap& map = mutable_value()->GetSwitches();
const_cast<base::CommandLine::SwitchMap*>(&map)->clear();
}
void CefCommandLineImpl::GetArgv(std::vector<CefString>& argv) {
CEF_VALUE_VERIFY_RETURN_VOID(false);
const base::CommandLine::StringVector& cmd_argv = const_value().argv();
base::CommandLine::StringVector::const_iterator it = cmd_argv.begin();
for (; it != cmd_argv.end(); ++it)
argv.push_back(*it);
}
CefString CefCommandLineImpl::GetCommandLineString() {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().GetCommandLineString();
}
CefString CefCommandLineImpl::GetProgram() {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().GetProgram().value();
}
void CefCommandLineImpl::SetProgram(const CefString& program) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->SetProgram(base::FilePath(program));
}
bool CefCommandLineImpl::HasSwitches() {
CEF_VALUE_VERIFY_RETURN(false, false);
return (const_value().GetSwitches().size() > 0);
}
bool CefCommandLineImpl::HasSwitch(const CefString& name) {
CEF_VALUE_VERIFY_RETURN(false, false);
return const_value().HasSwitch(name);
}
CefString CefCommandLineImpl::GetSwitchValue(const CefString& name) {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().GetSwitchValueNative(name);
}
void CefCommandLineImpl::GetSwitches(SwitchMap& switches) {
CEF_VALUE_VERIFY_RETURN_VOID(false);
const base::CommandLine::SwitchMap& map = const_value().GetSwitches();
base::CommandLine::SwitchMap::const_iterator it = map.begin();
for (; it != map.end(); ++it)
switches.insert(std::make_pair(it->first, it->second));
}
void CefCommandLineImpl::AppendSwitch(const CefString& name) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->AppendSwitch(name);
}
void CefCommandLineImpl::AppendSwitchWithValue(const CefString& name,
const CefString& value) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->AppendSwitchNative(name, value);
}
bool CefCommandLineImpl::HasArguments() {
CEF_VALUE_VERIFY_RETURN(false, false);
return (const_value().GetArgs().size() > 0);
}
void CefCommandLineImpl::GetArguments(ArgumentList& arguments) {
CEF_VALUE_VERIFY_RETURN_VOID(false);
const base::CommandLine::StringVector& vec = const_value().GetArgs();
base::CommandLine::StringVector::const_iterator it = vec.begin();
for (; it != vec.end(); ++it)
arguments.push_back(*it);
}
void CefCommandLineImpl::AppendArgument(const CefString& argument) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->AppendArgNative(argument);
}
void CefCommandLineImpl::PrependWrapper(const CefString& wrapper) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->PrependWrapper(wrapper);
}
// CefCommandLine implementation.
// static
CefRefPtr<CefCommandLine> CefCommandLine::CreateCommandLine() {
return new CefCommandLineImpl(
new base::CommandLine(base::CommandLine::NO_PROGRAM), true, false);
}
// static
CefRefPtr<CefCommandLine> CefCommandLine::GetGlobalCommandLine() {
// Uses a singleton reference object.
static CefRefPtr<CefCommandLineImpl> commandLinePtr;
if (!commandLinePtr.get()) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line)
commandLinePtr = new CefCommandLineImpl(command_line, false, true);
}
return commandLinePtr.get();
}

View File

@@ -0,0 +1,51 @@
// 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_COMMON_COMMAND_LINE_IMPL_H_
#define CEF_LIBCEF_COMMON_COMMAND_LINE_IMPL_H_
#pragma once
#include "include/cef_command_line.h"
#include "libcef/common/value_base.h"
#include "base/command_line.h"
// CefCommandLine implementation
class CefCommandLineImpl :
public CefValueBase<CefCommandLine, base::CommandLine> {
public:
CefCommandLineImpl(base::CommandLine* value,
bool will_delete,
bool read_only);
// CefCommandLine methods.
bool IsValid() override;
bool IsReadOnly() override;
CefRefPtr<CefCommandLine> Copy() override;
void InitFromArgv(int argc, const char* const* argv) override;
void InitFromString(const CefString& command_line) override;
void Reset() override;
void GetArgv(std::vector<CefString>& argv) override;
CefString GetCommandLineString() override;
CefString GetProgram() override;
void SetProgram(const CefString& program) override;
bool HasSwitches() override;
bool HasSwitch(const CefString& name) override;
CefString GetSwitchValue(const CefString& name) override;
void GetSwitches(SwitchMap& switches) override;
void AppendSwitch(const CefString& name) override;
void AppendSwitchWithValue(const CefString& name,
const CefString& value) override;
bool HasArguments() override;
void GetArguments(ArgumentList& arguments) override;
void AppendArgument(const CefString& argument) override;
void PrependWrapper(const CefString& wrapper) override;
// Must hold the controller lock while using this value.
const base::CommandLine& command_line() { return const_value(); }
DISALLOW_COPY_AND_ASSIGN(CefCommandLineImpl);
};
#endif // CEF_LIBCEF_COMMON_COMMAND_LINE_IMPL_H_

View File

@@ -0,0 +1,260 @@
// Copyright (c) 2012 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 "libcef/common/content_client.h"
#include "include/cef_stream.h"
#include "include/cef_version.h"
#include "libcef/browser/content_browser_client.h"
#include "libcef/common/scheme_registrar_impl.h"
#include "libcef/common/scheme_registration.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/pepper_plugin_info.h"
#include "content/public/common/user_agent.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
CefContentClient* g_content_client = NULL;
const char kPDFPluginName[] = "Chrome PDF Viewer";
const char kPDFPluginMimeType[] = "application/pdf";
const char kPDFPluginExtension[] = "pdf";
const char kPDFPluginDescription[] = "Portable Document Format";
const uint32 kPDFPluginPermissions = ppapi::PERMISSION_PRIVATE |
ppapi::PERMISSION_DEV;
// Appends the known built-in plugins to the given vector.
// Based on chrome/common/chrome_content_client.cc.
void ComputeBuiltInPlugins(std::vector<content::PepperPluginInfo>* plugins) {
// PDF.
//
// Once we're sandboxed, we can't know if the PDF plugin is available or not;
// but (on Linux) this function is always called once before we're sandboxed.
// So the first time through test if the file is available and then skip the
// check on subsequent calls if yes.
static bool skip_pdf_file_check = false;
base::FilePath path;
if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) {
if (skip_pdf_file_check || base::PathExists(path)) {
content::PepperPluginInfo pdf;
pdf.path = path;
pdf.name = kPDFPluginName;
// Only in-process loading is currently supported. See issue #1331.
pdf.is_out_of_process = false;
content::WebPluginMimeType pdf_mime_type(kPDFPluginMimeType,
kPDFPluginExtension,
kPDFPluginDescription);
pdf.mime_types.push_back(pdf_mime_type);
pdf.permissions = kPDFPluginPermissions;
plugins->push_back(pdf);
skip_pdf_file_check = true;
}
}
}
} // namespace
CefContentClient::CefContentClient(CefRefPtr<CefApp> application)
: application_(application),
pack_loading_disabled_(false),
allow_pack_file_load_(false),
scheme_info_list_locked_(false) {
DCHECK(!g_content_client);
g_content_client = this;
}
CefContentClient::~CefContentClient() {
g_content_client = NULL;
}
// static
CefContentClient* CefContentClient::Get() {
return g_content_client;
}
void CefContentClient::AddPepperPlugins(
std::vector<content::PepperPluginInfo>* plugins) {
ComputeBuiltInPlugins(plugins);
}
void CefContentClient::AddAdditionalSchemes(
std::vector<std::string>* standard_schemes,
std::vector<std::string>* savable_schemes) {
DCHECK(!scheme_info_list_locked_);
if (application_.get()) {
CefRefPtr<CefSchemeRegistrarImpl> schemeRegistrar(
new CefSchemeRegistrarImpl());
application_->OnRegisterCustomSchemes(schemeRegistrar.get());
schemeRegistrar->GetStandardSchemes(standard_schemes);
// No references to the registar should be kept.
schemeRegistrar->Detach();
DCHECK(schemeRegistrar->VerifyRefCount());
}
scheme::AddInternalSchemes(standard_schemes);
scheme_info_list_locked_ = true;
}
std::string CefContentClient::GetUserAgent() const {
std::string product_version;
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kUserAgent))
return command_line->GetSwitchValueASCII(switches::kUserAgent);
if (command_line->HasSwitch(switches::kProductVersion)) {
product_version =
command_line->GetSwitchValueASCII(switches::kProductVersion);
} else {
product_version = base::StringPrintf("Chrome/%d.%d.%d.%d",
CHROME_VERSION_MAJOR, CHROME_VERSION_MINOR, CHROME_VERSION_BUILD,
CHROME_VERSION_PATCH);
}
return content::BuildUserAgentFromProduct(product_version);
}
base::string16 CefContentClient::GetLocalizedString(int message_id) const {
base::string16 value =
ResourceBundle::GetSharedInstance().GetLocalizedString(message_id);
if (value.empty())
LOG(ERROR) << "No localized string available for id " << message_id;
return value;
}
base::StringPiece CefContentClient::GetDataResource(
int resource_id,
ui::ScaleFactor scale_factor) const {
base::StringPiece value =
ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
resource_id, scale_factor);
if (value.empty())
LOG(ERROR) << "No data resource available for id " << resource_id;
return value;
}
gfx::Image& CefContentClient::GetNativeImageNamed(int resource_id) const {
gfx::Image& value =
ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
if (value.IsEmpty())
LOG(ERROR) << "No native image available for id " << resource_id;
return value;
}
void CefContentClient::AddCustomScheme(const SchemeInfo& scheme_info) {
DCHECK(!scheme_info_list_locked_);
scheme_info_list_.push_back(scheme_info);
if (CefContentBrowserClient::Get()) {
CefContentBrowserClient::Get()->RegisterCustomScheme(
scheme_info.scheme_name);
}
}
const CefContentClient::SchemeInfoList* CefContentClient::GetCustomSchemes() {
DCHECK(scheme_info_list_locked_);
return &scheme_info_list_;
}
bool CefContentClient::HasCustomScheme(const std::string& scheme_name) {
DCHECK(scheme_info_list_locked_);
if (scheme_info_list_.empty())
return false;
SchemeInfoList::const_iterator it = scheme_info_list_.begin();
for (; it != scheme_info_list_.end(); ++it) {
if (it->scheme_name == scheme_name)
return true;
}
return false;
}
base::FilePath CefContentClient::GetPathForResourcePack(
const base::FilePath& pack_path,
ui::ScaleFactor scale_factor) {
// Only allow the cef pack file to load.
if (!pack_loading_disabled_ && allow_pack_file_load_)
return pack_path;
return base::FilePath();
}
base::FilePath CefContentClient::GetPathForLocalePack(
const base::FilePath& pack_path,
const std::string& locale) {
if (!pack_loading_disabled_)
return pack_path;
return base::FilePath();
}
gfx::Image CefContentClient::GetImageNamed(int resource_id) {
return gfx::Image();
}
gfx::Image CefContentClient::GetNativeImageNamed(
int resource_id,
ui::ResourceBundle::ImageRTL rtl) {
return gfx::Image();
}
base::RefCountedStaticMemory* CefContentClient::LoadDataResourceBytes(
int resource_id,
ui::ScaleFactor scale_factor) {
return NULL;
}
bool CefContentClient::GetRawDataResource(int resource_id,
ui::ScaleFactor scale_factor,
base::StringPiece* value) {
if (application_.get()) {
CefRefPtr<CefResourceBundleHandler> handler =
application_->GetResourceBundleHandler();
if (handler.get()) {
void* data = NULL;
size_t data_size = 0;
if (handler->GetDataResource(resource_id, data, data_size))
*value = base::StringPiece(static_cast<char*>(data), data_size);
}
}
return (pack_loading_disabled_ || !value->empty());
}
bool CefContentClient::GetLocalizedString(int message_id,
base::string16* value) {
if (application_.get()) {
CefRefPtr<CefResourceBundleHandler> handler =
application_->GetResourceBundleHandler();
if (handler.get()) {
CefString cef_str;
if (handler->GetLocalizedString(message_id, cef_str))
*value = cef_str;
}
}
return (pack_loading_disabled_ || !value->empty());
}
scoped_ptr<gfx::Font> CefContentClient::GetFont(
ui::ResourceBundle::FontStyle style) {
return scoped_ptr<gfx::Font>();
}

View File

@@ -0,0 +1,92 @@
// Copyright (c) 2012 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 CEF_LIBCEF_COMMON_CONTENT_CLIENT_H_
#define CEF_LIBCEF_COMMON_CONTENT_CLIENT_H_
#pragma once
#include <list>
#include <string>
#include <vector>
#include "include/cef_app.h"
#include "base/compiler_specific.h"
#include "content/public/common/content_client.h"
#include "ui/base/resource/resource_bundle.h"
class CefContentClient : public content::ContentClient,
public ui::ResourceBundle::Delegate {
public:
explicit CefContentClient(CefRefPtr<CefApp> application);
~CefContentClient() override;
// Returns the singleton CefContentClient instance.
static CefContentClient* Get();
// content::ContentClient methods.
void AddPepperPlugins(
std::vector<content::PepperPluginInfo>* plugins) override;
void AddAdditionalSchemes(
std::vector<std::string>* standard_schemes,
std::vector<std::string>* savable_schemes) override;
std::string GetUserAgent() const override;
base::string16 GetLocalizedString(int message_id) const override;
base::StringPiece GetDataResource(
int resource_id,
ui::ScaleFactor scale_factor) const override;
gfx::Image& GetNativeImageNamed(int resource_id) const override;
struct SchemeInfo {
std::string scheme_name;
bool is_standard;
bool is_local;
bool is_display_isolated;
};
typedef std::list<SchemeInfo> SchemeInfoList;
// Custom scheme registration.
void AddCustomScheme(const SchemeInfo& scheme_info);
const SchemeInfoList* GetCustomSchemes();
bool HasCustomScheme(const std::string& scheme_name);
CefRefPtr<CefApp> application() const { return application_; }
void set_pack_loading_disabled(bool val) { pack_loading_disabled_ = val; }
bool pack_loading_disabled() const { return pack_loading_disabled_; }
void set_allow_pack_file_load(bool val) { allow_pack_file_load_ = val; }
private:
// ui::ResourceBundle::Delegate methods.
base::FilePath GetPathForResourcePack(
const base::FilePath& pack_path,
ui::ScaleFactor scale_factor) override;
base::FilePath GetPathForLocalePack(
const base::FilePath& pack_path,
const std::string& locale) override;
gfx::Image GetImageNamed(int resource_id) override;
gfx::Image GetNativeImageNamed(
int resource_id,
ui::ResourceBundle::ImageRTL rtl) override;
base::RefCountedStaticMemory* LoadDataResourceBytes(
int resource_id,
ui::ScaleFactor scale_factor) override;
bool GetRawDataResource(int resource_id,
ui::ScaleFactor scale_factor,
base::StringPiece* value) override;
bool GetLocalizedString(int message_id,
base::string16* value) override;
scoped_ptr<gfx::Font> GetFont(
ui::ResourceBundle::FontStyle style) override;
CefRefPtr<CefApp> application_;
bool pack_loading_disabled_;
bool allow_pack_file_load_;
// Custom schemes handled by the client.
SchemeInfoList scheme_info_list_;
bool scheme_info_list_locked_;
};
#endif // CEF_LIBCEF_COMMON_CONTENT_CLIENT_H_

View File

@@ -0,0 +1,64 @@
// Copyright 2013 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 "libcef/common/crash_reporter_client.h"
#include "libcef/common/cef_switches.h"
#include "include/cef_version.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/files/file_path.h"
#include "base/strings/string16.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
CefCrashReporterClient::CefCrashReporterClient() {}
CefCrashReporterClient::~CefCrashReporterClient() {}
#if defined(OS_WIN)
void CefCrashReporterClient::GetProductNameAndVersion(
const base::FilePath& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) {
*product_name = base::ASCIIToUTF16("cef");
*version = base::UTF8ToUTF16(base::StringPrintf(
"%d.%d.%d", CEF_VERSION_MAJOR, CHROME_VERSION_BUILD, CEF_REVISION));
*special_build = base::string16();
*channel_name = base::string16();
}
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
#define PRODUCT_VERSION \
MAKE_STRING(CEF_VERSION_MAJOR) "." \
MAKE_STRING(CHROME_VERSION_BUILD) "." \
MAKE_STRING(CEF_REVISION)
void CefCrashReporterClient::GetProductNameAndVersion(
const char** product_name,
const char** version) {
*product_name = "cef";
*version = PRODUCT_VERSION;
}
base::FilePath CefCrashReporterClient::GetReporterLogFilename() {
return base::FilePath(FILE_PATH_LITERAL("uploads.log"));
}
#endif
bool CefCrashReporterClient::GetCrashDumpLocation(base::FilePath* crash_dir) {
#if !defined(OS_WIN)
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kCrashDumpsDir))
return false;
*crash_dir = command_line->GetSwitchValuePath(switches::kCrashDumpsDir);
return true;
#else
NOTREACHED();
return false;
#endif
}

View File

@@ -0,0 +1,43 @@
// Copyright 2013 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 CEF_LIBCEF_COMMON_CRASH_REPORTER_CLIENT_H_
#define CEF_LIBCEF_COMMON_CRASH_REPORTER_CLIENT_H_
#include "base/compiler_specific.h"
#include "components/crash/app/crash_reporter_client.h"
class CefCrashReporterClient : public crash_reporter::CrashReporterClient {
public:
CefCrashReporterClient();
~CefCrashReporterClient() override;
#if defined(OS_WIN)
// Returns a textual description of the product type and version to include
// in the crash report.
void GetProductNameAndVersion(const base::FilePath& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) override;
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
// Returns a textual description of the product type and version to include
// in the crash report.
void GetProductNameAndVersion(const char** product_name,
const char** version) override;
base::FilePath GetReporterLogFilename() override;
#endif
// The location where minidump files should be written. Returns true if
// |crash_dir| was set.
bool GetCrashDumpLocation(base::FilePath* crash_dir) override;
private:
DISALLOW_COPY_AND_ASSIGN(CefCrashReporterClient);
};
#endif // CEF_LIBCEF_COMMON_CRASH_REPORTER_CLIENT_H_

View File

@@ -0,0 +1,194 @@
// Copyright (c) 2013 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 <string>
#include "libcef/browser/stream_impl.h"
#include "libcef/common/drag_data_impl.h"
#include "base/files/file_path.h"
#include "net/base/filename_util.h"
#include "net/base/net_util.h"
#define CHECK_READONLY_RETURN_VOID() \
if (read_only_) { \
NOTREACHED() << "object is read only"; \
return; \
}
CefDragDataImpl::CefDragDataImpl(const content::DropData& data)
: data_(data),
read_only_(false) {
}
CefDragDataImpl::CefDragDataImpl()
: read_only_(false) {
}
CefRefPtr<CefDragData> CefDragData::Create() {
return new CefDragDataImpl();
}
CefRefPtr<CefDragData> CefDragDataImpl::Clone() {
CefDragDataImpl* drag_data = NULL;
{
base::AutoLock lock_scope(lock_);
drag_data = new CefDragDataImpl(data_);
}
return drag_data;
}
bool CefDragDataImpl::IsReadOnly() {
base::AutoLock lock_scope(lock_);
return read_only_;
}
bool CefDragDataImpl::IsLink() {
base::AutoLock lock_scope(lock_);
return (data_.url.is_valid() && data_.file_description_filename.empty());
}
bool CefDragDataImpl::IsFragment() {
base::AutoLock lock_scope(lock_);
return (!data_.url.is_valid() && data_.file_description_filename.empty() &&
data_.filenames.empty());
}
bool CefDragDataImpl::IsFile() {
base::AutoLock lock_scope(lock_);
return (!data_.file_description_filename.empty() || !data_.filenames.empty());
}
CefString CefDragDataImpl::GetLinkURL() {
base::AutoLock lock_scope(lock_);
return data_.url.spec();
}
CefString CefDragDataImpl::GetLinkTitle() {
base::AutoLock lock_scope(lock_);
return data_.url_title;
}
CefString CefDragDataImpl::GetLinkMetadata() {
base::AutoLock lock_scope(lock_);
return data_.download_metadata;
}
CefString CefDragDataImpl::GetFragmentText() {
base::AutoLock lock_scope(lock_);
return data_.text.is_null() ? CefString() : CefString(data_.text.string());
}
CefString CefDragDataImpl::GetFragmentHtml() {
base::AutoLock lock_scope(lock_);
return data_.html.is_null() ? CefString() : CefString(data_.html.string());
}
CefString CefDragDataImpl::GetFragmentBaseURL() {
base::AutoLock lock_scope(lock_);
return data_.html_base_url.spec();
}
CefString CefDragDataImpl::GetFileName() {
base::AutoLock lock_scope(lock_);
if (data_.file_description_filename.empty())
return CefString();
base::FilePath file_name(CefString(data_.file_description_filename));
// Images without ALT text will only have a file extension so we need to
// synthesize one from the provided extension and URL.
if (file_name.BaseName().RemoveExtension().empty()) {
CefString extension = file_name.Extension();
// Retrieve the name from the URL.
CefString suggested_file_name =
net::GetSuggestedFilename(data_.url, "", "", "", "", "");
file_name = base::FilePath(suggested_file_name).ReplaceExtension(extension);
}
return file_name.value();
}
size_t CefDragDataImpl::GetFileContents(CefRefPtr<CefStreamWriter> writer) {
base::AutoLock lock_scope(lock_);
if (data_.file_contents.empty())
return 0;
char* data = const_cast<char*>(data_.file_contents.c_str());
size_t size = data_.file_contents.size();
if (!writer.get())
return size;
return writer->Write(data, 1, size);
}
bool CefDragDataImpl::GetFileNames(std::vector<CefString>& names) {
base::AutoLock lock_scope(lock_);
if (data_.filenames.empty())
return false;
std::vector<ui::FileInfo>::const_iterator it =
data_.filenames.begin();
for (; it != data_.filenames.end(); ++it)
names.push_back(it->path.value());
return true;
}
void CefDragDataImpl::SetLinkURL(const CefString& url) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.url = GURL(url.ToString());
}
void CefDragDataImpl::SetLinkTitle(const CefString& title) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.url_title = title.ToString16();
}
void CefDragDataImpl::SetLinkMetadata(const CefString& data) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.download_metadata = data.ToString16();
}
void CefDragDataImpl::SetFragmentText(const CefString& text) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.text = base::NullableString16(text.ToString16(), false);
}
void CefDragDataImpl::SetFragmentHtml(const CefString& fragment) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.html = base::NullableString16(fragment.ToString16(), false);
}
void CefDragDataImpl::SetFragmentBaseURL(const CefString& fragment) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.html_base_url = GURL(fragment.ToString());
}
void CefDragDataImpl::ResetFileContents() {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.file_contents.erase();
data_.file_description_filename.erase();
}
void CefDragDataImpl::AddFile(const CefString& path,
const CefString& display_name) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
data_.filenames.push_back(ui::FileInfo(base::FilePath(path),
base::FilePath(display_name)));
}
void CefDragDataImpl::SetReadOnly(bool read_only) {
base::AutoLock lock_scope(lock_);
if (read_only_ == read_only)
return;
read_only_ = read_only;
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2013 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_COMMON_DRAG_DATA_IMPL_H_
#define CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_
#pragma once
#include "include/cef_drag_data.h"
#include <vector>
#include "base/synchronization/lock.h"
#include "content/public/common/drop_data.h"
// Implementation of CefDragData.
class CefDragDataImpl : public CefDragData {
public:
CefDragDataImpl();
explicit CefDragDataImpl(const content::DropData& data);
CefRefPtr<CefDragData> Clone() override;
bool IsReadOnly() override;
bool IsLink() override;
bool IsFragment() override;
bool IsFile() override;
CefString GetLinkURL() override;
CefString GetLinkTitle() override;
CefString GetLinkMetadata() override;
CefString GetFragmentText() override;
CefString GetFragmentHtml() override;
CefString GetFragmentBaseURL() override;
CefString GetFileName() override;
size_t GetFileContents(CefRefPtr<CefStreamWriter> writer) override;
bool GetFileNames(std::vector<CefString>& names) override;
void SetLinkURL(const CefString& url) override;
void SetLinkTitle(const CefString& title) override;
void SetLinkMetadata(const CefString& data) override;
void SetFragmentText(const CefString& text) override;
void SetFragmentHtml(const CefString& fragment) override;
void SetFragmentBaseURL(const CefString& fragment) override;
void ResetFileContents() override;
void AddFile(const CefString& path, const CefString& display_name) override;
// This method is not safe. Use Lock/Unlock to get mutually exclusive access.
const content::DropData& drop_data() {
return data_;
}
void SetReadOnly(bool read_only);
base::Lock& lock() { return lock_; }
private:
content::DropData data_;
// True if this object is read-only.
bool read_only_;
base::Lock lock_;
IMPLEMENT_REFCOUNTING(CefDragDataImpl);
};
#endif // CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_

View File

@@ -0,0 +1,43 @@
// Copyright (c) 2011 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/common/http_header_utils.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
using net::HttpResponseHeaders;
namespace HttpHeaderUtils {
std::string GenerateHeaders(const HeaderMap& map) {
std::string headers;
for (HeaderMap::const_iterator header = map.begin();
header != map.end();
++header) {
const CefString& key = header->first;
const CefString& value = header->second;
if (!key.empty()) {
// Delimit with "\r\n".
if (!headers.empty())
headers += "\r\n";
headers += std::string(key) + ": " + std::string(value);
}
}
return headers;
}
void ParseHeaders(const std::string& header_str, HeaderMap& map) {
// Parse the request header values
for (net::HttpUtil::HeadersIterator i(header_str.begin(),
header_str.end(), "\n");
i.GetNext(); ) {
map.insert(std::make_pair(i.name(), i.values()));
}
}
} // namespace HttpHeaderUtils

View File

@@ -0,0 +1,22 @@
// 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_COMMON_HTTP_HEADER_UTILS_H_
#define CEF_LIBCEF_COMMON_HTTP_HEADER_UTILS_H_
#pragma once
#include <string>
#include "include/cef_request.h"
namespace HttpHeaderUtils {
typedef CefRequest::HeaderMap HeaderMap;
std::string GenerateHeaders(const HeaderMap& map);
void ParseHeaders(const std::string& header_str, HeaderMap& map);
}; // namespace HttpHeaderUtils
#endif // CEF_LIBCEF_COMMON_HTTP_HEADER_UTILS_H_

View File

@@ -0,0 +1,611 @@
// Copyright (c) 2012 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 "libcef/common/main_delegate.h"
#include "libcef/browser/content_browser_client.h"
#include "libcef/browser/context.h"
#include "libcef/common/cef_switches.h"
#include "libcef/common/command_line_impl.h"
#include "libcef/common/crash_reporter_client.h"
#include "libcef/renderer/content_renderer_client.h"
#include "libcef/utility/content_utility_client.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/base/ui_base_switches.h"
#if defined(OS_WIN)
#include <Objbase.h> // NOLINT(build/include_order)
#include "components/crash/app/breakpad_win.h"
#endif
#if defined(OS_MACOSX)
#include "base/mac/os_crash_dumps.h"
#include "base/mac/bundle_locations.h"
#include "base/mac/foundation_util.h"
#include "components/crash/app/breakpad_mac.h"
#include "content/public/common/content_paths.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include "components/crash/app/breakpad_linux.h"
#endif
namespace {
base::LazyInstance<CefCrashReporterClient>::Leaky g_crash_reporter_client =
LAZY_INSTANCE_INITIALIZER;
#if defined(OS_MACOSX)
base::FilePath GetFrameworksPath() {
// Start out with the path to the running executable.
base::FilePath execPath;
PathService::Get(base::FILE_EXE, &execPath);
// Get the main bundle path.
base::FilePath bundlePath = base::mac::GetAppBundlePath(execPath);
// Go into the Contents/Frameworks directory.
return bundlePath.Append(FILE_PATH_LITERAL("Contents"))
.Append(FILE_PATH_LITERAL("Frameworks"));
}
// The framework bundle path is used for loading resources, libraries, etc.
base::FilePath GetFrameworkBundlePath() {
return GetFrameworksPath().Append(
FILE_PATH_LITERAL("Chromium Embedded Framework.framework"));
}
base::FilePath GetResourcesFilePath() {
return GetFrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources"));
}
base::FilePath GetLibrariesFilePath() {
return GetFrameworkBundlePath().Append(FILE_PATH_LITERAL("Libraries"));
}
void OverrideFrameworkBundlePath() {
base::mac::SetOverrideFrameworkBundlePath(GetFrameworkBundlePath());
}
void OverrideChildProcessPath() {
// Retrieve the name of the running executable.
base::FilePath path;
PathService::Get(base::FILE_EXE, &path);
std::string name = path.BaseName().value();
base::FilePath helper_path = GetFrameworksPath()
.Append(FILE_PATH_LITERAL(name+" Helper.app"))
.Append(FILE_PATH_LITERAL("Contents"))
.Append(FILE_PATH_LITERAL("MacOS"))
.Append(FILE_PATH_LITERAL(name+" Helper"));
PathService::Override(content::CHILD_PROCESS_EXE, helper_path);
}
#else // !defined(OS_MACOSX)
base::FilePath GetResourcesFilePath() {
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
return pak_dir;
}
base::FilePath GetLibrariesFilePath() {
return GetResourcesFilePath();
}
#endif // !defined(OS_MACOSX)
// File name of the internal PDF plugin on different platforms.
const base::FilePath::CharType kInternalPDFPluginFileName[] =
#if defined(OS_WIN)
FILE_PATH_LITERAL("pdf.dll");
#elif defined(OS_MACOSX)
FILE_PATH_LITERAL("PDF.plugin");
#else // Linux and Chrome OS
FILE_PATH_LITERAL("libpdf.so");
#endif
void OverridePdfPluginPath() {
base::FilePath plugin_path = GetLibrariesFilePath();
plugin_path = plugin_path.Append(kInternalPDFPluginFileName);
PathService::Override(chrome::FILE_PDF_PLUGIN, plugin_path);
}
// Returns true if |scale_factor| is supported by this platform.
// Same as ResourceBundle::IsScaleFactorSupported.
bool IsScaleFactorSupported(ui::ScaleFactor scale_factor) {
const std::vector<ui::ScaleFactor>& supported_scale_factors =
ui::GetSupportedScaleFactors();
return std::find(supported_scale_factors.begin(),
supported_scale_factors.end(),
scale_factor) != supported_scale_factors.end();
}
// Used to run the UI on a separate thread.
class CefUIThread : public base::Thread {
public:
explicit CefUIThread(const content::MainFunctionParams& main_function_params)
: base::Thread("CefUIThread"),
main_function_params_(main_function_params) {
}
void Init() override {
#if defined(OS_WIN)
// Initializes the COM library on the current thread.
CoInitialize(NULL);
#endif
// Use our own browser process runner.
browser_runner_.reset(content::BrowserMainRunner::Create());
// Initialize browser process state. Uses the current thread's mesage loop.
int exit_code = browser_runner_->Initialize(main_function_params_);
CHECK_EQ(exit_code, -1);
}
void CleanUp() override {
browser_runner_->Shutdown();
browser_runner_.reset(NULL);
#if defined(OS_WIN)
// Closes the COM library on the current thread. CoInitialize must
// be balanced by a corresponding call to CoUninitialize.
CoUninitialize();
#endif
}
protected:
content::MainFunctionParams main_function_params_;
scoped_ptr<content::BrowserMainRunner> browser_runner_;
};
} // namespace
CefMainDelegate::CefMainDelegate(CefRefPtr<CefApp> application)
: content_client_(application) {
// Necessary so that exported functions from base_impl.cc will be included
// in the binary.
extern void base_impl_stub();
base_impl_stub();
}
CefMainDelegate::~CefMainDelegate() {
}
bool CefMainDelegate::BasicStartupComplete(int* exit_code) {
#if defined(OS_MACOSX)
OverrideFrameworkBundlePath();
#endif
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
if (process_type.empty()) {
// In the browser process. Populate the global command-line object.
const CefSettings& settings = CefContext::Get()->settings();
if (settings.command_line_args_disabled) {
// Remove any existing command-line arguments.
base::CommandLine::StringVector argv;
argv.push_back(command_line->GetProgram().value());
command_line->InitFromArgv(argv);
const base::CommandLine::SwitchMap& map = command_line->GetSwitches();
const_cast<base::CommandLine::SwitchMap*>(&map)->clear();
}
if (settings.single_process)
command_line->AppendSwitch(switches::kSingleProcess);
bool no_sandbox = settings.no_sandbox ? true : false;
if (settings.browser_subprocess_path.length > 0) {
base::FilePath file_path =
base::FilePath(CefString(&settings.browser_subprocess_path));
if (!file_path.empty()) {
command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,
file_path);
#if defined(OS_WIN)
// The sandbox is not supported when using a separate subprocess
// executable on Windows.
no_sandbox = true;
#endif
}
}
if (no_sandbox)
command_line->AppendSwitch(switches::kNoSandbox);
if (settings.user_agent.length > 0) {
command_line->AppendSwitchASCII(switches::kUserAgent,
CefString(&settings.user_agent));
} else if (settings.product_version.length > 0) {
command_line->AppendSwitchASCII(switches::kProductVersion,
CefString(&settings.product_version));
}
if (settings.locale.length > 0) {
command_line->AppendSwitchASCII(switches::kLang,
CefString(&settings.locale));
} else if (!command_line->HasSwitch(switches::kLang)) {
command_line->AppendSwitchASCII(switches::kLang, "en-US");
}
if (settings.log_file.length > 0) {
base::FilePath file_path = base::FilePath(CefString(&settings.log_file));
if (!file_path.empty())
command_line->AppendSwitchPath(switches::kLogFile, file_path);
}
if (settings.log_severity != LOGSEVERITY_DEFAULT) {
std::string log_severity;
switch (settings.log_severity) {
case LOGSEVERITY_VERBOSE:
log_severity = switches::kLogSeverity_Verbose;
break;
case LOGSEVERITY_INFO:
log_severity = switches::kLogSeverity_Info;
break;
case LOGSEVERITY_WARNING:
log_severity = switches::kLogSeverity_Warning;
break;
case LOGSEVERITY_ERROR:
log_severity = switches::kLogSeverity_Error;
break;
case LOGSEVERITY_DISABLE:
log_severity = switches::kLogSeverity_Disable;
break;
default:
break;
}
if (!log_severity.empty())
command_line->AppendSwitchASCII(switches::kLogSeverity, log_severity);
}
if (settings.javascript_flags.length > 0) {
command_line->AppendSwitchASCII(switches::kJavaScriptFlags,
CefString(&settings.javascript_flags));
}
if (settings.pack_loading_disabled) {
command_line->AppendSwitch(switches::kDisablePackLoading);
} else {
if (settings.resources_dir_path.length > 0) {
base::FilePath file_path =
base::FilePath(CefString(&settings.resources_dir_path));
if (!file_path.empty()) {
command_line->AppendSwitchPath(switches::kResourcesDirPath,
file_path);
}
}
if (settings.locales_dir_path.length > 0) {
base::FilePath file_path =
base::FilePath(CefString(&settings.locales_dir_path));
if (!file_path.empty())
command_line->AppendSwitchPath(switches::kLocalesDirPath, file_path);
}
}
if (settings.remote_debugging_port >= 1024 &&
settings.remote_debugging_port <= 65535) {
command_line->AppendSwitchASCII(switches::kRemoteDebuggingPort,
base::IntToString(settings.remote_debugging_port));
}
if (settings.uncaught_exception_stack_size > 0) {
command_line->AppendSwitchASCII(switches::kUncaughtExceptionStackSize,
base::IntToString(settings.uncaught_exception_stack_size));
}
if (settings.context_safety_implementation != 0) {
command_line->AppendSwitchASCII(switches::kContextSafetyImplementation,
base::IntToString(settings.context_safety_implementation));
}
if (settings.windowless_rendering_enabled) {
#if defined(OS_MACOSX)
// The delegated renderer is not yet enabled by default on OS X.
command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
#endif
}
}
if (content_client_.application().get()) {
// Give the application a chance to view/modify the command line.
CefRefPtr<CefCommandLineImpl> commandLinePtr(
new CefCommandLineImpl(command_line, false, false));
content_client_.application()->OnBeforeCommandLineProcessing(
CefString(process_type), commandLinePtr.get());
commandLinePtr->Detach(NULL);
}
// Initialize logging.
logging::LoggingSettings log_settings;
const base::FilePath& log_file =
command_line->GetSwitchValuePath(switches::kLogFile);
log_settings.log_file = log_file.value().c_str();
log_settings.lock_log = logging::DONT_LOCK_LOG_FILE;
log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE;
logging::LogSeverity log_severity = logging::LOG_INFO;
std::string log_severity_str =
command_line->GetSwitchValueASCII(switches::kLogSeverity);
if (!log_severity_str.empty()) {
if (LowerCaseEqualsASCII(log_severity_str,
switches::kLogSeverity_Verbose)) {
log_severity = logging::LOG_VERBOSE;
} else if (LowerCaseEqualsASCII(log_severity_str,
switches::kLogSeverity_Warning)) {
log_severity = logging::LOG_WARNING;
} else if (LowerCaseEqualsASCII(log_severity_str,
switches::kLogSeverity_Error)) {
log_severity = logging::LOG_ERROR;
} else if (LowerCaseEqualsASCII(log_severity_str,
switches::kLogSeverity_Disable)) {
log_severity = LOGSEVERITY_DISABLE;
}
}
if (log_severity == LOGSEVERITY_DISABLE) {
log_settings.logging_dest = logging::LOG_NONE;
} else {
log_settings.logging_dest = logging::LOG_TO_ALL;
logging::SetMinLogLevel(log_severity);
}
logging::InitLogging(log_settings);
content::SetContentClient(&content_client_);
return false;
}
void CefMainDelegate::PreSandboxStartup() {
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
const std::string& process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
if (command_line->HasSwitch(switches::kEnableCrashReporter)) {
crash_reporter::SetCrashReporterClient(g_crash_reporter_client.Pointer());
#if defined(OS_MACOSX)
base::mac::DisableOSCrashDumps();
breakpad::InitCrashReporter(process_type);
breakpad::InitCrashProcessInfo(process_type);
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
if (process_type != switches::kZygoteProcess)
breakpad::InitCrashReporter(process_type);
#elif defined(OS_WIN)
UINT new_flags =
SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX;
UINT existing_flags = SetErrorMode(new_flags);
SetErrorMode(existing_flags | new_flags);
breakpad::InitCrashReporter(process_type);
#endif
}
if (!command_line->HasSwitch(switches::kProcessType)) {
// Only these paths when executing the main process.
#if defined(OS_MACOSX)
OverrideChildProcessPath();
#endif
// Paths used to locate spell checking dictionary files.
// TODO(cef): It may be better to use a persistent location for
// DIR_USER_DATA. See the implementation of GetDefaultUserDataDirectory in
// chrome/common/chrome_paths_*.
const base::FilePath& cache_path = CefContext::Get()->cache_path();
PathService::Override(chrome::DIR_USER_DATA, cache_path);
PathService::OverrideAndCreateIfNeeded(
chrome::DIR_APP_DICTIONARIES,
cache_path.AppendASCII("Dictionaries"),
false, // May not be an absolute path.
true); // Create if necessary.
}
OverridePdfPluginPath();
if (command_line->HasSwitch(switches::kDisablePackLoading))
content_client_.set_pack_loading_disabled(true);
InitializeResourceBundle();
if (process_type == switches::kUtilityProcess ||
process_type == switches::kZygoteProcess) {
CefContentUtilityClient::PreSandboxStartup();
}
}
int CefMainDelegate::RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) {
if (process_type.empty()) {
const CefSettings& settings = CefContext::Get()->settings();
if (!settings.multi_threaded_message_loop) {
// Use our own browser process runner.
browser_runner_.reset(content::BrowserMainRunner::Create());
// Initialize browser process state. Results in a call to
// CefBrowserMain::PreMainMessageLoopStart() which creates the UI message
// loop.
int exit_code = browser_runner_->Initialize(main_function_params);
if (exit_code >= 0)
return exit_code;
} else {
// Run the UI on a separate thread.
scoped_ptr<base::Thread> thread;
thread.reset(new CefUIThread(main_function_params));
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_UI;
if (!thread->StartWithOptions(options)) {
NOTREACHED() << "failed to start UI thread";
return 1;
}
ui_thread_.swap(thread);
}
return 0;
}
return -1;
}
void CefMainDelegate::ProcessExiting(const std::string& process_type) {
ResourceBundle::CleanupSharedInstance();
}
#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
void CefMainDelegate::ZygoteForked() {
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kEnableCrashReporter)) {
const std::string& process_type = command_line->GetSwitchValueASCII(
switches::kProcessType);
breakpad::InitCrashReporter(process_type);
}
}
#endif
content::ContentBrowserClient* CefMainDelegate::CreateContentBrowserClient() {
browser_client_.reset(new CefContentBrowserClient);
return browser_client_.get();
}
content::ContentRendererClient*
CefMainDelegate::CreateContentRendererClient() {
renderer_client_.reset(new CefContentRendererClient);
return renderer_client_.get();
}
content::ContentUtilityClient* CefMainDelegate::CreateContentUtilityClient() {
utility_client_.reset(new CefContentUtilityClient);
return utility_client_.get();
}
void CefMainDelegate::ShutdownBrowser() {
if (browser_runner_.get()) {
browser_runner_->Shutdown();
browser_runner_.reset(NULL);
}
if (ui_thread_.get()) {
// Blocks until the thread has stopped.
ui_thread_->Stop();
ui_thread_.reset();
}
}
void CefMainDelegate::InitializeResourceBundle() {
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
base::FilePath cef_pak_file, cef_100_percent_pak_file,
cef_200_percent_pak_file, devtools_pak_file, locales_dir;
if (!content_client_.pack_loading_disabled()) {
base::FilePath resources_dir;
if (command_line->HasSwitch(switches::kResourcesDirPath)) {
resources_dir =
command_line->GetSwitchValuePath(switches::kResourcesDirPath);
}
if (resources_dir.empty())
resources_dir = GetResourcesFilePath();
if (!resources_dir.empty()) {
cef_pak_file = resources_dir.Append(FILE_PATH_LITERAL("cef.pak"));
cef_100_percent_pak_file =
resources_dir.Append(FILE_PATH_LITERAL("cef_100_percent.pak"));
cef_200_percent_pak_file =
resources_dir.Append(FILE_PATH_LITERAL("cef_200_percent.pak"));
devtools_pak_file =
resources_dir.Append(FILE_PATH_LITERAL("devtools_resources.pak"));
}
if (command_line->HasSwitch(switches::kLocalesDirPath))
locales_dir = command_line->GetSwitchValuePath(switches::kLocalesDirPath);
if (!locales_dir.empty())
PathService::Override(ui::DIR_LOCALES, locales_dir);
}
std::string locale = command_line->GetSwitchValueASCII(switches::kLang);
DCHECK(!locale.empty());
const std::string loaded_locale =
ui::ResourceBundle::InitSharedInstanceWithLocale(
locale,
&content_client_,
ui::ResourceBundle::LOAD_COMMON_RESOURCES);
ResourceBundle& resource_bundle = ResourceBundle::GetSharedInstance();
if (!content_client_.pack_loading_disabled()) {
if (loaded_locale.empty())
LOG(ERROR) << "Could not load locale pak for " << locale;
content_client_.set_allow_pack_file_load(true);
if (base::PathExists(cef_pak_file)) {
resource_bundle.AddDataPackFromPath(cef_pak_file, ui::SCALE_FACTOR_NONE);
} else {
LOG(ERROR) << "Could not load cef.pak";
}
// On OS X and Linux/Aura always load the 1x data pack first as the 2x data
// pack contains both 1x and 2x images.
const bool load_100_percent =
#if defined(OS_WIN)
IsScaleFactorSupported(ui::SCALE_FACTOR_100P);
#else
true;
#endif
if (load_100_percent) {
if (base::PathExists(cef_100_percent_pak_file)) {
resource_bundle.AddDataPackFromPath(
cef_100_percent_pak_file, ui::SCALE_FACTOR_100P);
} else {
LOG(ERROR) << "Could not load cef_100_percent.pak";
}
}
if (IsScaleFactorSupported(ui::SCALE_FACTOR_200P)) {
if (base::PathExists(cef_200_percent_pak_file)) {
resource_bundle.AddDataPackFromPath(
cef_200_percent_pak_file, ui::SCALE_FACTOR_200P);
} else {
LOG(ERROR) << "Could not load cef_200_percent.pak";
}
}
if (base::PathExists(devtools_pak_file)) {
resource_bundle.AddDataPackFromPath(
devtools_pak_file, ui::SCALE_FACTOR_NONE);
}
content_client_.set_allow_pack_file_load(false);
}
}

View File

@@ -0,0 +1,69 @@
// Copyright (c) 2011 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 CEF_LIBCEF_COMMON_MAIN_DELEGATE_H_
#define CEF_LIBCEF_COMMON_MAIN_DELEGATE_H_
#pragma once
#include <string>
#include "libcef/common/content_client.h"
#include "include/cef_app.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "content/public/app/content_main_delegate.h"
namespace base {
class Thread;
}
namespace content {
class BrowserMainRunner;
}
class CefContentBrowserClient;
class CefContentRendererClient;
class CefContentUtilityClient;
class CefMainDelegate : public content::ContentMainDelegate {
public:
explicit CefMainDelegate(CefRefPtr<CefApp> application);
~CefMainDelegate() override;
bool BasicStartupComplete(int* exit_code) override;
void PreSandboxStartup() override;
int RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) override;
void ProcessExiting(const std::string& process_type) override;
#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX)
void ZygoteForked() override;
#endif
content::ContentBrowserClient* CreateContentBrowserClient() override;
content::ContentRendererClient*
CreateContentRendererClient() override;
content::ContentUtilityClient* CreateContentUtilityClient() override;
// Shut down the browser runner.
void ShutdownBrowser();
CefContentBrowserClient* browser_client() { return browser_client_.get(); }
CefContentClient* content_client() { return &content_client_; }
private:
void InitializeResourceBundle();
scoped_ptr<content::BrowserMainRunner> browser_runner_;
scoped_ptr<base::Thread> ui_thread_;
scoped_ptr<CefContentBrowserClient> browser_client_;
scoped_ptr<CefContentRendererClient> renderer_client_;
scoped_ptr<CefContentUtilityClient> utility_client_;
CefContentClient content_client_;
DISALLOW_COPY_AND_ASSIGN(CefMainDelegate);
};
#endif // CEF_LIBCEF_COMMON_MAIN_DELEGATE_H_

View File

@@ -0,0 +1,10 @@
// Copyright (c) 2013 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/common/content_client.h"
#include "libcef/common/net_resource_provider.h"
base::StringPiece NetResourceProvider(int key) {
return CefContentClient::Get()->GetDataResource(key, ui::SCALE_FACTOR_NONE);
}

View File

@@ -0,0 +1,14 @@
// Copyright (c) 2013 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_COMMON_NET_RESOURCE_PROVIDER_H_
#define CEF_LIBCEF_COMMON_NET_RESOURCE_PROVIDER_H_
#pragma once
#include "base/strings/string_piece.h"
// This is called indirectly by the network layer to access resources.
base::StringPiece NetResourceProvider(int key);
#endif // CEF_LIBCEF_COMMON_NET_RESOURCE_PROVIDER_H_

View File

@@ -0,0 +1,76 @@
// 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/common/process_message_impl.h"
#include "libcef/common/cef_messages.h"
#include "libcef/common/values_impl.h"
#include "base/logging.h"
namespace {
void CopyList(const base::ListValue& source,
base::ListValue& target) {
base::ListValue::const_iterator it = source.begin();
for (; it != source.end(); ++it)
target.Append((*it)->DeepCopy());
}
void CopyValue(const Cef_Request_Params& source,
Cef_Request_Params& target) {
target.name = source.name;
CopyList(source.arguments, target.arguments);
}
} // namespace
// static
CefRefPtr<CefProcessMessage> CefProcessMessage::Create(const CefString& name) {
Cef_Request_Params* params = new Cef_Request_Params();
params->name = name;
return new CefProcessMessageImpl(params, true, false);
}
CefProcessMessageImpl::CefProcessMessageImpl(Cef_Request_Params* value,
bool will_delete,
bool read_only)
: CefValueBase<CefProcessMessage, Cef_Request_Params>(
value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete,
read_only, NULL) {
}
bool CefProcessMessageImpl::CopyTo(Cef_Request_Params& target) {
CEF_VALUE_VERIFY_RETURN(false, false);
CopyValue(const_value(), target);
return true;
}
bool CefProcessMessageImpl::IsValid() {
return !detached();
}
bool CefProcessMessageImpl::IsReadOnly() {
return read_only();
}
CefRefPtr<CefProcessMessage> CefProcessMessageImpl::Copy() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
Cef_Request_Params* params = new Cef_Request_Params();
CopyValue(const_value(), *params);
return new CefProcessMessageImpl(params, true, false);
}
CefString CefProcessMessageImpl::GetName() {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().name;
}
CefRefPtr<CefListValue> CefProcessMessageImpl::GetArgumentList() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return CefListValueImpl::GetOrCreateRef(
const_cast<base::ListValue*>(&(const_value().arguments)),
const_cast<Cef_Request_Params*>(&const_value()),
read_only(),
controller());
}

View File

@@ -0,0 +1,35 @@
// 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_COMMON_PROCESS_MESSAGE_IMPL_H_
#define CEF_LIBCEF_COMMON_PROCESS_MESSAGE_IMPL_H_
#pragma once
#include "include/cef_process_message.h"
#include "libcef/common/value_base.h"
struct Cef_Request_Params;
// CefProcessMessage implementation
class CefProcessMessageImpl
: public CefValueBase<CefProcessMessage, Cef_Request_Params> {
public:
CefProcessMessageImpl(Cef_Request_Params* value,
bool will_delete,
bool read_only);
// Copies the underlying value to the specified |target| structure.
bool CopyTo(Cef_Request_Params& target);
// CefProcessMessage methods.
bool IsValid() override;
bool IsReadOnly() override;
CefRefPtr<CefProcessMessage> Copy() override;
CefString GetName() override;
CefRefPtr<CefListValue> GetArgumentList() override;
DISALLOW_COPY_AND_ASSIGN(CefProcessMessageImpl);
};
#endif // CEF_LIBCEF_COMMON_PROCESS_MESSAGE_IMPL_H_

View File

@@ -0,0 +1,811 @@
// Copyright (c) 2008-2009 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 <string>
#include <vector>
#include "libcef/common/http_header_utils.h"
#include "libcef/common/request_impl.h"
#include "libcef/common/task_runner_impl.h"
#include "libcef/common/upload_data.h"
#include "base/logging.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/common/resource_type.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/upload_data_stream.h"
#include "net/base/upload_element_reader.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/http/http_request_headers.h"
#include "net/url_request/url_request.h"
#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
namespace {
// A subclass of net::UploadBytesElementReader that keeps the associated
// UploadElement alive until the request completes.
class BytesElementReader : public net::UploadBytesElementReader {
public:
explicit BytesElementReader(scoped_ptr<net::UploadElement> element)
: net::UploadBytesElementReader(element->bytes(),
element->bytes_length()),
element_(element.Pass()) {
DCHECK_EQ(net::UploadElement::TYPE_BYTES, element_->type());
}
private:
scoped_ptr<net::UploadElement> element_;
DISALLOW_COPY_AND_ASSIGN(BytesElementReader);
};
base::TaskRunner* GetFileTaskRunner() {
scoped_refptr<base::SequencedTaskRunner> task_runner =
CefTaskRunnerImpl::GetTaskRunner(TID_FILE);
DCHECK(task_runner.get());
return task_runner.get();
}
// A subclass of net::UploadFileElementReader that keeps the associated
// UploadElement alive until the request completes.
class FileElementReader : public net::UploadFileElementReader {
public:
explicit FileElementReader(scoped_ptr<net::UploadElement> element)
: net::UploadFileElementReader(
GetFileTaskRunner(),
element->file_path(),
element->file_range_offset(),
element->file_range_length(),
element->expected_file_modification_time()),
element_(element.Pass()) {
DCHECK_EQ(net::UploadElement::TYPE_FILE, element_->type());
}
private:
scoped_ptr<net::UploadElement> element_;
DISALLOW_COPY_AND_ASSIGN(FileElementReader);
};
} // namespace
#define CHECK_READONLY_RETURN(val) \
if (read_only_) { \
NOTREACHED() << "object is read only"; \
return val; \
}
#define CHECK_READONLY_RETURN_VOID() \
if (read_only_) { \
NOTREACHED() << "object is read only"; \
return; \
}
// CefRequest -----------------------------------------------------------------
// static
CefRefPtr<CefRequest> CefRequest::Create() {
CefRefPtr<CefRequest> request(new CefRequestImpl());
return request;
}
// CefRequestImpl -------------------------------------------------------------
CefRequestImpl::CefRequestImpl()
: method_("GET"),
resource_type_(RT_SUB_RESOURCE),
transition_type_(TT_EXPLICIT),
flags_(UR_FLAG_NONE),
read_only_(false) {
}
bool CefRequestImpl::IsReadOnly() {
base::AutoLock lock_scope(lock_);
return read_only_;
}
CefString CefRequestImpl::GetURL() {
base::AutoLock lock_scope(lock_);
return url_;
}
void CefRequestImpl::SetURL(const CefString& url) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
url_ = url;
}
CefString CefRequestImpl::GetMethod() {
base::AutoLock lock_scope(lock_);
return method_;
}
void CefRequestImpl::SetMethod(const CefString& method) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
method_ = method;
}
CefRefPtr<CefPostData> CefRequestImpl::GetPostData() {
base::AutoLock lock_scope(lock_);
return postdata_;
}
void CefRequestImpl::SetPostData(CefRefPtr<CefPostData> postData) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
postdata_ = postData;
}
void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) {
base::AutoLock lock_scope(lock_);
headerMap = headermap_;
}
void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
headermap_ = headerMap;
}
void CefRequestImpl::Set(const CefString& url,
const CefString& method,
CefRefPtr<CefPostData> postData,
const HeaderMap& headerMap) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
url_ = url;
method_ = method;
postdata_ = postData;
headermap_ = headerMap;
}
int CefRequestImpl::GetFlags() {
base::AutoLock lock_scope(lock_);
return flags_;
}
void CefRequestImpl::SetFlags(int flags) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
flags_ = flags;
}
CefString CefRequestImpl::GetFirstPartyForCookies() {
base::AutoLock lock_scope(lock_);
return first_party_for_cookies_;
}
void CefRequestImpl::SetFirstPartyForCookies(const CefString& url) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
first_party_for_cookies_ = url;
}
CefRequestImpl::ResourceType CefRequestImpl::GetResourceType() {
base::AutoLock lock_scope(lock_);
return resource_type_;
}
CefRequestImpl::TransitionType CefRequestImpl::GetTransitionType() {
base::AutoLock lock_scope(lock_);
return transition_type_;
}
void CefRequestImpl::Set(net::URLRequest* request) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
url_ = request->url().spec();
method_ = request->method();
first_party_for_cookies_ = request->first_party_for_cookies().spec();
net::HttpRequestHeaders headers = request->extra_request_headers();
// URLRequest::SetReferrer ensures that we do not send username and password
// fields in the referrer.
GURL referrer(request->referrer());
// 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(headers, headermap_);
// Transfer post data, if any
const net::UploadDataStream* data = request->get_upload();
if (data) {
postdata_ = CefPostData::Create();
static_cast<CefPostDataImpl*>(postdata_.get())->Set(*data);
} else if (postdata_.get()) {
postdata_ = NULL;
}
const content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request);
if (info) {
resource_type_ =
static_cast<cef_resource_type_t>(info->GetResourceType());
transition_type_ =
static_cast<cef_transition_type_t>(info->GetPageTransition());
} else {
resource_type_ = RT_SUB_RESOURCE;
transition_type_ = TT_EXPLICIT;
}
}
void CefRequestImpl::Get(net::URLRequest* request) {
base::AutoLock lock_scope(lock_);
request->set_method(method_);
if (!first_party_for_cookies_.empty()) {
request->set_first_party_for_cookies(
GURL(std::string(first_party_for_cookies_)));
}
CefString referrerStr;
referrerStr.FromASCII(net::HttpRequestHeaders::kReferer);
HeaderMap headerMap = headermap_;
HeaderMap::iterator it = headerMap.find(referrerStr);
if (it == headerMap.end()) {
request->SetReferrer("");
} else {
request->SetReferrer(it->second);
headerMap.erase(it);
}
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(HttpHeaderUtils::GenerateHeaders(headerMap));
request->SetExtraRequestHeaders(headers);
if (postdata_.get()) {
request->set_upload(
make_scoped_ptr(static_cast<CefPostDataImpl*>(postdata_.get())->Get()));
} else if (request->get_upload()) {
request->set_upload(scoped_ptr<net::UploadDataStream>());
}
}
void CefRequestImpl::Set(const blink::WebURLRequest& request) {
DCHECK(!request.isNull());
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
url_ = request.url().spec().utf16();
method_ = request.httpMethod();
const blink::WebHTTPBody& body = request.httpBody();
if (!body.isNull()) {
postdata_ = new CefPostDataImpl();
static_cast<CefPostDataImpl*>(postdata_.get())->Set(body);
} else if (postdata_.get()) {
postdata_ = NULL;
}
headermap_.clear();
GetHeaderMap(request, headermap_);
flags_ = UR_FLAG_NONE;
if (request.cachePolicy() == blink::WebURLRequest::ReloadIgnoringCacheData)
flags_ |= UR_FLAG_SKIP_CACHE;
if (request.allowStoredCredentials())
flags_ |= UR_FLAG_ALLOW_CACHED_CREDENTIALS;
if (request.reportUploadProgress())
flags_ |= UR_FLAG_REPORT_UPLOAD_PROGRESS;
if (request.reportRawHeaders())
flags_ |= UR_FLAG_REPORT_RAW_HEADERS;
first_party_for_cookies_ = request.firstPartyForCookies().spec().utf16();
}
void CefRequestImpl::Get(blink::WebURLRequest& request) {
request.initialize();
base::AutoLock lock_scope(lock_);
GURL gurl = GURL(url_.ToString());
request.setURL(blink::WebURL(gurl));
std::string method(method_);
request.setHTTPMethod(blink::WebString::fromUTF8(method.c_str()));
blink::WebHTTPBody body;
if (postdata_.get()) {
body.initialize();
static_cast<CefPostDataImpl*>(postdata_.get())->Get(body);
request.setHTTPBody(body);
}
SetHeaderMap(headermap_, request);
request.setCachePolicy((flags_ & UR_FLAG_SKIP_CACHE) ?
blink::WebURLRequest::ReloadIgnoringCacheData :
blink::WebURLRequest::UseProtocolCachePolicy);
#define SETBOOLFLAG(obj, flags, method, FLAG) \
obj.method((flags & (FLAG)) == (FLAG))
SETBOOLFLAG(request, flags_, setAllowStoredCredentials,
UR_FLAG_ALLOW_CACHED_CREDENTIALS);
SETBOOLFLAG(request, flags_, setReportUploadProgress,
UR_FLAG_REPORT_UPLOAD_PROGRESS);
SETBOOLFLAG(request, flags_, setReportRawHeaders,
UR_FLAG_REPORT_RAW_HEADERS);
if (!first_party_for_cookies_.empty()) {
GURL gurl = GURL(first_party_for_cookies_.ToString());
request.setFirstPartyForCookies(blink::WebURL(gurl));
}
}
void CefRequestImpl::SetReadOnly(bool read_only) {
base::AutoLock lock_scope(lock_);
if (read_only_ == read_only)
return;
read_only_ = read_only;
if (postdata_.get())
static_cast<CefPostDataImpl*>(postdata_.get())->SetReadOnly(read_only);
}
// static
void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers,
HeaderMap& map) {
if (headers.IsEmpty())
return;
net::HttpRequestHeaders::Iterator it(headers);
do {
map.insert(std::make_pair(it.name(), it.value()));
} while (it.GetNext());
}
// static
void CefRequestImpl::GetHeaderMap(const blink::WebURLRequest& request,
HeaderMap& map) {
class HeaderVisitor : public blink::WebHTTPHeaderVisitor {
public:
explicit HeaderVisitor(HeaderMap* map) : map_(map) {}
void visitHeader(const blink::WebString& name,
const blink::WebString& value) override {
map_->insert(std::make_pair(base::string16(name),
base::string16(value)));
}
private:
HeaderMap* map_;
};
HeaderVisitor visitor(&map);
request.visitHTTPHeaderFields(&visitor);
}
// static
void CefRequestImpl::SetHeaderMap(const HeaderMap& map,
blink::WebURLRequest& request) {
HeaderMap::const_iterator it = map.begin();
for (; it != map.end(); ++it)
request.setHTTPHeaderField(base::string16(it->first),
base::string16(it->second));
}
// CefPostData ----------------------------------------------------------------
// static
CefRefPtr<CefPostData> CefPostData::Create() {
CefRefPtr<CefPostData> postdata(new CefPostDataImpl());
return postdata;
}
// CefPostDataImpl ------------------------------------------------------------
CefPostDataImpl::CefPostDataImpl()
: read_only_(false) {
}
bool CefPostDataImpl::IsReadOnly() {
base::AutoLock lock_scope(lock_);
return read_only_;
}
size_t CefPostDataImpl::GetElementCount() {
base::AutoLock lock_scope(lock_);
return elements_.size();
}
void CefPostDataImpl::GetElements(ElementVector& elements) {
base::AutoLock lock_scope(lock_);
elements = elements_;
}
bool CefPostDataImpl::RemoveElement(CefRefPtr<CefPostDataElement> element) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN(false);
ElementVector::iterator it = elements_.begin();
for (; it != elements_.end(); ++it) {
if (it->get() == element.get()) {
elements_.erase(it);
return true;
}
}
return false;
}
bool CefPostDataImpl::AddElement(CefRefPtr<CefPostDataElement> element) {
bool found = false;
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN(false);
// 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()) {
found = true;
break;
}
}
if (!found)
elements_.push_back(element);
return !found;
}
void CefPostDataImpl::RemoveElements() {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
elements_.clear();
}
void CefPostDataImpl::Set(const net::UploadData& data) {
{
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
}
CefRefPtr<CefPostDataElement> postelem;
const ScopedVector<net::UploadElement>& elements = data.elements();
ScopedVector<net::UploadElement>::const_iterator it = elements.begin();
for (; it != elements.end(); ++it) {
postelem = CefPostDataElement::Create();
static_cast<CefPostDataElementImpl*>(postelem.get())->Set(**it);
AddElement(postelem);
}
}
void CefPostDataImpl::Set(const net::UploadDataStream& data_stream) {
{
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
}
CefRefPtr<CefPostDataElement> postelem;
const ScopedVector<net::UploadElementReader>* elements =
data_stream.GetElementReaders();
if (elements) {
ScopedVector<net::UploadElementReader>::const_iterator it =
elements->begin();
for (; it != elements->end(); ++it) {
postelem = CefPostDataElement::Create();
static_cast<CefPostDataElementImpl*>(postelem.get())->Set(**it);
AddElement(postelem);
}
}
}
void CefPostDataImpl::Get(net::UploadData& data) {
base::AutoLock lock_scope(lock_);
ScopedVector<net::UploadElement> data_elements;
ElementVector::const_iterator it = elements_.begin();
for (; it != elements_.end(); ++it) {
net::UploadElement* element = new net::UploadElement();
static_cast<CefPostDataElementImpl*>(it->get())->Get(*element);
data_elements.push_back(element);
}
data.swap_elements(&data_elements);
}
net::UploadDataStream* CefPostDataImpl::Get() {
base::AutoLock lock_scope(lock_);
ScopedVector<net::UploadElementReader> element_readers;
ElementVector::const_iterator it = elements_.begin();
for (; it != elements_.end(); ++it) {
element_readers.push_back(
static_cast<CefPostDataElementImpl*>(it->get())->Get());
}
return new net::ElementsUploadDataStream(element_readers.Pass(), 0);
}
void CefPostDataImpl::Set(const blink::WebHTTPBody& data) {
{
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
}
CefRefPtr<CefPostDataElement> postelem;
blink::WebHTTPBody::Element element;
size_t size = data.elementCount();
for (size_t i = 0; i < size; ++i) {
if (data.elementAt(i, element)) {
postelem = CefPostDataElement::Create();
static_cast<CefPostDataElementImpl*>(postelem.get())->Set(element);
AddElement(postelem);
}
}
}
void CefPostDataImpl::Get(blink::WebHTTPBody& data) {
base::AutoLock lock_scope(lock_);
blink::WebHTTPBody::Element element;
ElementVector::iterator it = elements_.begin();
for (; it != elements_.end(); ++it) {
static_cast<CefPostDataElementImpl*>(it->get())->Get(element);
if (element.type == blink::WebHTTPBody::Element::TypeData) {
data.appendData(element.data);
} else if (element.type == blink::WebHTTPBody::Element::TypeFile) {
data.appendFile(element.filePath);
} else {
NOTREACHED();
}
}
}
void CefPostDataImpl::SetReadOnly(bool read_only) {
base::AutoLock lock_scope(lock_);
if (read_only_ == read_only)
return;
read_only_ = read_only;
ElementVector::const_iterator it = elements_.begin();
for (; it != elements_.end(); ++it) {
static_cast<CefPostDataElementImpl*>(it->get())->SetReadOnly(read_only);
}
}
// CefPostDataElement ---------------------------------------------------------
// static
CefRefPtr<CefPostDataElement> CefPostDataElement::Create() {
CefRefPtr<CefPostDataElement> element(new CefPostDataElementImpl());
return element;
}
// CefPostDataElementImpl -----------------------------------------------------
CefPostDataElementImpl::CefPostDataElementImpl()
: type_(PDE_TYPE_EMPTY),
read_only_(false) {
memset(&data_, 0, sizeof(data_));
}
CefPostDataElementImpl::~CefPostDataElementImpl() {
Cleanup();
}
bool CefPostDataElementImpl::IsReadOnly() {
base::AutoLock lock_scope(lock_);
return read_only_;
}
void CefPostDataElementImpl::SetToEmpty() {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
Cleanup();
}
void CefPostDataElementImpl::SetToFile(const CefString& fileName) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
// Clear any data currently in the element
Cleanup();
// Assign the new data
type_ = PDE_TYPE_FILE;
cef_string_copy(fileName.c_str(), fileName.length(), &data_.filename);
}
void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
// Clear any data currently in the element
Cleanup();
// Assign the new data
void* data = malloc(size);
DCHECK(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() {
base::AutoLock lock_scope(lock_);
return type_;
}
CefString CefPostDataElementImpl::GetFile() {
base::AutoLock lock_scope(lock_);
DCHECK(type_ == PDE_TYPE_FILE);
CefString filename;
if (type_ == PDE_TYPE_FILE)
filename.FromString(data_.filename.str, data_.filename.length, false);
return filename;
}
size_t CefPostDataElementImpl::GetBytesCount() {
base::AutoLock lock_scope(lock_);
DCHECK(type_ == PDE_TYPE_BYTES);
size_t size = 0;
if (type_ == PDE_TYPE_BYTES)
size = data_.bytes.size;
return size;
}
size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) {
base::AutoLock lock_scope(lock_);
DCHECK(type_ == PDE_TYPE_BYTES);
size_t rv = 0;
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::UploadElement& element) {
{
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
}
if (element.type() == net::UploadElement::TYPE_BYTES) {
SetToBytes(element.bytes_length(), element.bytes());
} else if (element.type() == net::UploadElement::TYPE_FILE) {
SetToFile(element.file_path().value());
} else {
NOTREACHED();
}
}
void CefPostDataElementImpl::Set(
const net::UploadElementReader& element_reader) {
{
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
}
const net::UploadBytesElementReader* bytes_reader =
element_reader.AsBytesReader();
if (bytes_reader) {
SetToBytes(bytes_reader->length(), bytes_reader->bytes());
return;
}
const net::UploadFileElementReader* file_reader =
element_reader.AsFileReader();
if (file_reader) {
SetToFile(file_reader->path().value());
return;
}
NOTREACHED();
}
void CefPostDataElementImpl::Get(net::UploadElement& element) {
base::AutoLock lock_scope(lock_);
if (type_ == PDE_TYPE_BYTES) {
element.SetToBytes(static_cast<char*>(data_.bytes.bytes), data_.bytes.size);
} else if (type_ == PDE_TYPE_FILE) {
base::FilePath path = base::FilePath(CefString(&data_.filename));
element.SetToFilePath(path);
} else {
NOTREACHED();
}
}
net::UploadElementReader* CefPostDataElementImpl::Get() {
base::AutoLock lock_scope(lock_);
if (type_ == PDE_TYPE_BYTES) {
net::UploadElement* element = new net::UploadElement();
element->SetToBytes(static_cast<char*>(data_.bytes.bytes),
data_.bytes.size);
return new BytesElementReader(make_scoped_ptr(element));
} else if (type_ == PDE_TYPE_FILE) {
net::UploadElement* element = new net::UploadElement();
base::FilePath path = base::FilePath(CefString(&data_.filename));
element->SetToFilePath(path);
return new FileElementReader(make_scoped_ptr(element));
} else {
NOTREACHED();
return NULL;
}
}
void CefPostDataElementImpl::Set(const blink::WebHTTPBody::Element& element) {
{
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
}
if (element.type == blink::WebHTTPBody::Element::TypeData) {
SetToBytes(element.data.size(),
static_cast<const void*>(element.data.data()));
} else if (element.type == blink::WebHTTPBody::Element::TypeFile) {
SetToFile(base::string16(element.filePath));
} else {
NOTREACHED();
}
}
void CefPostDataElementImpl::Get(blink::WebHTTPBody::Element& element) {
base::AutoLock lock_scope(lock_);
if (type_ == PDE_TYPE_BYTES) {
element.type = blink::WebHTTPBody::Element::TypeData;
element.data.assign(
static_cast<char*>(data_.bytes.bytes), data_.bytes.size);
} else if (type_ == PDE_TYPE_FILE) {
element.type = blink::WebHTTPBody::Element::TypeFile;
element.filePath.assign(base::string16(CefString(&data_.filename)));
} else {
NOTREACHED();
}
}
void CefPostDataElementImpl::SetReadOnly(bool read_only) {
base::AutoLock lock_scope(lock_);
if (read_only_ == read_only)
return;
read_only_ = read_only;
}
void CefPostDataElementImpl::Cleanup() {
if (type_ == PDE_TYPE_EMPTY)
return;
if (type_ == PDE_TYPE_BYTES)
free(data_.bytes.bytes);
else if (type_ == PDE_TYPE_FILE)
cef_string_clear(&data_.filename);
type_ = PDE_TYPE_EMPTY;
memset(&data_, 0, sizeof(data_));
}

View File

@@ -0,0 +1,171 @@
// 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_COMMON_REQUEST_IMPL_H_
#define CEF_LIBCEF_COMMON_REQUEST_IMPL_H_
#pragma once
#include "include/cef_request.h"
#include "base/synchronization/lock.h"
#include "third_party/WebKit/public/platform/WebHTTPBody.h"
namespace net {
class HttpRequestHeaders;
class UploadData;
class UploadDataStream;
class UploadElement;
class UploadElementReader;
class URLRequest;
};
namespace blink {
class WebURLRequest;
}
// Implementation of CefRequest
class CefRequestImpl : public CefRequest {
public:
CefRequestImpl();
bool IsReadOnly() override;
CefString GetURL() override;
void SetURL(const CefString& url) override;
CefString GetMethod() override;
void SetMethod(const CefString& method) override;
CefRefPtr<CefPostData> GetPostData() override;
void SetPostData(CefRefPtr<CefPostData> postData) override;
void GetHeaderMap(HeaderMap& headerMap) override;
void SetHeaderMap(const HeaderMap& headerMap) override;
void Set(const CefString& url,
const CefString& method,
CefRefPtr<CefPostData> postData,
const HeaderMap& headerMap) override;
int GetFlags() override;
void SetFlags(int flags) override;
CefString GetFirstPartyForCookies() override;
void SetFirstPartyForCookies(const CefString& url) override;
ResourceType GetResourceType() override;
TransitionType GetTransitionType() override;
// Populate this object from the URLRequest object.
void Set(net::URLRequest* request);
// Populate the URLRequest object from this object.
void Get(net::URLRequest* request);
// Populate this object from a WebURLRequest object.
void Set(const blink::WebURLRequest& request);
// Populate the WebURLRequest object from this object.
void Get(blink::WebURLRequest& request);
void SetReadOnly(bool read_only);
static void GetHeaderMap(const net::HttpRequestHeaders& headers,
HeaderMap& map);
static void GetHeaderMap(const blink::WebURLRequest& request,
HeaderMap& map);
static void SetHeaderMap(const HeaderMap& map,
blink::WebURLRequest& request);
protected:
CefString url_;
CefString method_;
CefRefPtr<CefPostData> postdata_;
HeaderMap headermap_;
ResourceType resource_type_;
TransitionType transition_type_;
// The below members are used by CefURLRequest.
int flags_;
CefString first_party_for_cookies_;
// True if this object is read-only.
bool read_only_;
base::Lock lock_;
IMPLEMENT_REFCOUNTING(CefRequestImpl);
};
// Implementation of CefPostData
class CefPostDataImpl : public CefPostData {
public:
CefPostDataImpl();
bool IsReadOnly() override;
size_t GetElementCount() override;
void GetElements(ElementVector& elements) override;
bool RemoveElement(CefRefPtr<CefPostDataElement> element) override;
bool AddElement(CefRefPtr<CefPostDataElement> element) override;
void RemoveElements() override;
void Set(const net::UploadData& data);
void Set(const net::UploadDataStream& data_stream);
void Get(net::UploadData& data);
net::UploadDataStream* Get();
void Set(const blink::WebHTTPBody& data);
void Get(blink::WebHTTPBody& data);
void SetReadOnly(bool read_only);
protected:
ElementVector elements_;
// True if this object is read-only.
bool read_only_;
base::Lock lock_;
IMPLEMENT_REFCOUNTING(CefPostDataImpl);
};
// Implementation of CefPostDataElement
class CefPostDataElementImpl : public CefPostDataElement {
public:
CefPostDataElementImpl();
~CefPostDataElementImpl() override;
bool IsReadOnly() override;
void SetToEmpty() override;
void SetToFile(const CefString& fileName) override;
void SetToBytes(size_t size, const void* bytes) override;
Type GetType() override;
CefString GetFile() override;
size_t GetBytesCount() override;
size_t GetBytes(size_t size, void* bytes) override;
void* GetBytes() { return data_.bytes.bytes; }
void Set(const net::UploadElement& element);
void Set(const net::UploadElementReader& element_reader);
void Get(net::UploadElement& element);
net::UploadElementReader* Get();
void Set(const blink::WebHTTPBody::Element& element);
void Get(blink::WebHTTPBody::Element& element);
void SetReadOnly(bool read_only);
protected:
void Cleanup();
Type type_;
union {
struct {
void* bytes;
size_t size;
} bytes;
cef_string_t filename;
} data_;
// True if this object is read-only.
bool read_only_;
base::Lock lock_;
IMPLEMENT_REFCOUNTING(CefPostDataElementImpl);
};
#endif // CEF_LIBCEF_COMMON_REQUEST_IMPL_H_

View File

@@ -0,0 +1,205 @@
// 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/common/response_impl.h"
#include <string>
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#define CHECK_READONLY_RETURN_VOID() \
if (read_only_) { \
NOTREACHED() << "object is read only"; \
return; \
}
// CefResponse ----------------------------------------------------------------
// static
CefRefPtr<CefResponse> CefResponse::Create() {
CefRefPtr<CefResponse> response(new CefResponseImpl());
return response;
}
// CefResponseImpl ------------------------------------------------------------
CefResponseImpl::CefResponseImpl()
: status_code_(0),
read_only_(false) {
}
bool CefResponseImpl::IsReadOnly() {
base::AutoLock lock_scope(lock_);
return read_only_;
}
int CefResponseImpl::GetStatus() {
base::AutoLock lock_scope(lock_);
return status_code_;
}
void CefResponseImpl::SetStatus(int status) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
status_code_ = status;
}
CefString CefResponseImpl::GetStatusText() {
base::AutoLock lock_scope(lock_);
return status_text_;
}
void CefResponseImpl::SetStatusText(const CefString& statusText) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
status_text_ = statusText;
}
CefString CefResponseImpl::GetMimeType() {
base::AutoLock lock_scope(lock_);
return mime_type_;
}
void CefResponseImpl::SetMimeType(const CefString& mimeType) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
mime_type_ = mimeType;
}
CefString CefResponseImpl::GetHeader(const CefString& name) {
base::AutoLock lock_scope(lock_);
CefString value;
HeaderMap::const_iterator it = header_map_.find(name);
if (it != header_map_.end())
value = it->second;
return value;
}
void CefResponseImpl::GetHeaderMap(HeaderMap& map) {
base::AutoLock lock_scope(lock_);
map = header_map_;
}
void CefResponseImpl::SetHeaderMap(const HeaderMap& headerMap) {
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
header_map_ = headerMap;
}
net::HttpResponseHeaders* CefResponseImpl::GetResponseHeaders() {
base::AutoLock lock_scope(lock_);
std::string response;
std::string status_text;
bool has_content_type_header = false;
if (!status_text_.empty())
status_text = status_text_;
else
status_text = (status_code_ == 200)?"OK":"ERROR";
base::SStringPrintf(&response, "HTTP/1.1 %d %s", status_code_,
status_text.c_str());
if (header_map_.size() > 0) {
for (HeaderMap::const_iterator header = header_map_.begin();
header != header_map_.end();
++header) {
const CefString& key = header->first;
const CefString& value = header->second;
if (!key.empty()) {
// Delimit with "\0" as required by net::HttpResponseHeaders.
std::string key_str(key);
std::string value_str(value);
base::StringAppendF(&response, "%c%s: %s", '\0', key_str.c_str(),
value_str.c_str());
if (!has_content_type_header &&
key_str == net::HttpRequestHeaders::kContentType) {
has_content_type_header = true;
}
}
}
}
if (!has_content_type_header) {
std::string mime_type;
if (!mime_type_.empty())
mime_type = mime_type_;
else
mime_type = "text/html";
base::StringAppendF(&response, "%c%s: %s", '\0',
net::HttpRequestHeaders::kContentType, mime_type.c_str());
}
return new net::HttpResponseHeaders(response);
}
void CefResponseImpl::SetResponseHeaders(
const net::HttpResponseHeaders& headers) {
base::AutoLock lock_scope(lock_);
header_map_.empty();
void* iter = NULL;
std::string name, value;
while (headers.EnumerateHeaderLines(&iter, &name, &value))
header_map_.insert(std::make_pair(name, value));
status_code_ = headers.response_code();
status_text_ = headers.GetStatusText();
std::string mime_type;
if (headers.GetMimeType(&mime_type))
mime_type_ = mime_type;
}
void CefResponseImpl::Set(const blink::WebURLResponse& response) {
DCHECK(!response.isNull());
base::AutoLock lock_scope(lock_);
CHECK_READONLY_RETURN_VOID();
blink::WebString str;
status_code_ = response.httpStatusCode();
str = response.httpStatusText();
status_text_ = CefString(str);
str = response.mimeType();
mime_type_ = CefString(str);
class HeaderVisitor : public blink::WebHTTPHeaderVisitor {
public:
explicit HeaderVisitor(HeaderMap* map) : map_(map) {}
void visitHeader(const blink::WebString& name,
const blink::WebString& value) override {
map_->insert(std::make_pair(base::string16(name),
base::string16(value)));
}
private:
HeaderMap* map_;
};
HeaderVisitor visitor(&header_map_);
response.visitHTTPHeaderFields(&visitor);
}
void CefResponseImpl::SetReadOnly(bool read_only) {
base::AutoLock lock_scope(lock_);
read_only_ = read_only;
}

View File

@@ -0,0 +1,57 @@
// 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_COMMON_RESPONSE_IMPL_H_
#define CEF_LIBCEF_COMMON_RESPONSE_IMPL_H_
#pragma once
#include "include/cef_response.h"
#include "base/synchronization/lock.h"
namespace net {
class HttpResponseHeaders;
}
namespace blink {
class WebURLResponse;
}
// Implementation of CefResponse.
class CefResponseImpl : public CefResponse {
public:
CefResponseImpl();
// CefResponse methods.
bool IsReadOnly() override;
int GetStatus() override;
void SetStatus(int status) override;
CefString GetStatusText() override;
void SetStatusText(const CefString& statusText) override;
CefString GetMimeType() override;
void SetMimeType(const CefString& mimeType) override;
CefString GetHeader(const CefString& name) override;
void GetHeaderMap(HeaderMap& headerMap) override;
void SetHeaderMap(const HeaderMap& headerMap) override;
net::HttpResponseHeaders* GetResponseHeaders();
void SetResponseHeaders(const net::HttpResponseHeaders& headers);
void Set(const blink::WebURLResponse& response);
void SetReadOnly(bool read_only);
protected:
int status_code_;
CefString status_text_;
CefString mime_type_;
HeaderMap header_map_;
bool read_only_;
base::Lock lock_;
IMPLEMENT_REFCOUNTING(CefResponseImpl);
};
#endif // CEF_LIBCEF_COMMON_RESPONSE_IMPL_H_

View File

@@ -0,0 +1,58 @@
// 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/common/response_manager.h"
#include "libcef/common/cef_messages.h"
#include "base/logging.h"
CefResponseManager::CefResponseManager()
: next_request_id_(0) {
}
int CefResponseManager::GetNextRequestId() {
DCHECK(CalledOnValidThread());
return ++next_request_id_;
}
int CefResponseManager::RegisterHandler(CefRefPtr<Handler> handler) {
DCHECK(CalledOnValidThread());
int request_id = GetNextRequestId();
TRACE_EVENT_ASYNC_BEGIN1("libcef", "CefResponseManager::Handler", request_id, "request_id", request_id);
handlers_.insert(std::make_pair(request_id, handler));
return request_id;
}
bool CefResponseManager::RunHandler(const Cef_Response_Params& params) {
DCHECK(CalledOnValidThread());
DCHECK_GT(params.request_id, 0);
HandlerMap::iterator it = handlers_.find(params.request_id);
if (it != handlers_.end()) {
TRACE_EVENT0("libcef", "CefResponseManager::RunHandler");
it->second->OnResponse(params);
handlers_.erase(it);
TRACE_EVENT_ASYNC_END1("libcef", "CefResponseManager::Handler", params.request_id, "success", 1);
return true;
}
TRACE_EVENT_ASYNC_END1("libcef", "CefResponseManager::Handler", params.request_id, "success", 0);
return false;
}
void CefResponseManager::RegisterAckHandler(int request_id,
CefRefPtr<AckHandler> handler) {
DCHECK(CalledOnValidThread());
ack_handlers_.insert(std::make_pair(request_id, handler));
}
bool CefResponseManager::RunAckHandler(int request_id) {
DCHECK(CalledOnValidThread());
DCHECK_GT(request_id, 0);
AckHandlerMap::iterator it = ack_handlers_.find(request_id);
if (it != ack_handlers_.end()) {
it->second->OnResponseAck();
ack_handlers_.erase(it);
return true;
}
return false;
}

View File

@@ -0,0 +1,62 @@
// 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_COMMON_RESPONSE_MANAGER_H_
#define CEF_LIBCEF_COMMON_RESPONSE_MANAGER_H_
#pragma once
#include <map>
#include "include/cef_base.h"
#include "base/threading/non_thread_safe.h"
struct Cef_Response_Params;
// This class is not thread-safe.
class CefResponseManager : base::NonThreadSafe {
public:
// Used for handling response messages.
class Handler : public virtual CefBase {
public:
virtual void OnResponse(const Cef_Response_Params& params) =0;
};
// Used for handling response ack messages.
class AckHandler : public virtual CefBase {
public:
virtual void OnResponseAck() =0;
};
CefResponseManager();
// Returns the next unique request id.
int GetNextRequestId();
// Register a response handler and return the unique request id.
int RegisterHandler(CefRefPtr<Handler> handler);
// Run the response handler for the specified request id. Returns true if a
// handler was run.
bool RunHandler(const Cef_Response_Params& params);
// Register a response ack handler for the specified request id.
void RegisterAckHandler(int request_id, CefRefPtr<AckHandler> handler);
// Run the response ack handler for the specified request id. Returns true if
// a handler was run.
bool RunAckHandler(int request_id);
private:
// Used for generating unique request ids.
int next_request_id_;
// Map of unique request ids to Handler references.
typedef std::map<int, CefRefPtr<Handler> > HandlerMap;
HandlerMap handlers_;
// Map of unique request ids to AckHandler references.
typedef std::map<int, CefRefPtr<AckHandler> > AckHandlerMap;
AckHandlerMap ack_handlers_;
};
#endif // CEF_LIBCEF_COMMON_RESPONSE_MANAGER_H_

View File

@@ -0,0 +1,67 @@
// 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/common/scheme_registrar_impl.h"
#include <string>
#include "libcef/common/content_client.h"
#include "base/bind.h"
#include "base/logging.h"
CefSchemeRegistrarImpl::CefSchemeRegistrarImpl()
: supported_thread_id_(base::PlatformThread::CurrentId()) {
}
bool CefSchemeRegistrarImpl::AddCustomScheme(
const CefString& scheme_name,
bool is_standard,
bool is_local,
bool is_display_isolated) {
if (!VerifyContext())
return false;
const std::string& scheme = scheme_name;
if (is_standard)
standard_schemes_.push_back(scheme);
CefContentClient::SchemeInfo scheme_info = {
scheme, is_standard, is_local, is_display_isolated};
CefContentClient::Get()->AddCustomScheme(scheme_info);
return true;
}
void CefSchemeRegistrarImpl::GetStandardSchemes(
std::vector<std::string>* standard_schemes) {
if (!VerifyContext())
return;
if (standard_schemes_.empty())
return;
standard_schemes->insert(standard_schemes->end(), standard_schemes_.begin(),
standard_schemes_.end());
}
bool CefSchemeRegistrarImpl::VerifyRefCount() {
return HasOneRef();
}
void CefSchemeRegistrarImpl::Detach() {
if (VerifyContext())
supported_thread_id_ = base::kInvalidThreadId;
}
bool CefSchemeRegistrarImpl::VerifyContext() {
if (base::PlatformThread::CurrentId() != supported_thread_id_) {
// This object should only be accessed from the thread that created it.
NOTREACHED();
return false;
}
return true;
}

View File

@@ -0,0 +1,46 @@
// 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_COMMON_SCHEME_REGISTRAR_IMPL_H_
#define CEF_LIBCEF_COMMON_SCHEME_REGISTRAR_IMPL_H_
#pragma once
#include <string>
#include <vector>
#include "include/cef_scheme.h"
#include "base/threading/platform_thread.h"
class CefSchemeRegistrarImpl : public CefSchemeRegistrar {
public:
CefSchemeRegistrarImpl();
// CefSchemeRegistrar methods.
bool AddCustomScheme(const CefString& scheme_name,
bool is_standard,
bool is_local,
bool is_display_isolated) override;
void GetStandardSchemes(std::vector<std::string>* standard_schemes);
// Verify that only a single reference exists to all CefSchemeRegistrarImpl
// objects.
bool VerifyRefCount();
void Detach();
private:
// Verify that the object is being accessed from the correct thread.
bool VerifyContext();
base::PlatformThreadId supported_thread_id_;
std::vector<std::string> standard_schemes_;
IMPLEMENT_REFCOUNTING(CefSchemeRegistrarImpl);
DISALLOW_COPY_AND_ASSIGN(CefSchemeRegistrarImpl);
};
#endif // CEF_LIBCEF_COMMON_SCHEME_REGISTRAR_IMPL_H_

View File

@@ -0,0 +1,68 @@
// Copyright (c) 2013 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/common/scheme_registration.h"
#include "libcef/common/content_client.h"
#include "content/public/common/url_constants.h"
#include "url/url_constants.h"
namespace scheme {
void AddInternalSchemes(std::vector<std::string>* standard_schemes) {
static CefContentClient::SchemeInfo schemes[] = {
{ content::kChromeUIScheme, true, true, true },
{ content::kChromeDevToolsScheme, true, false, true }
};
CefContentClient* client = CefContentClient::Get();
for (size_t i = 0; i < sizeof(schemes) / sizeof(schemes[0]); ++i) {
if (schemes[0].is_standard)
standard_schemes->push_back(schemes[i].scheme_name);
client->AddCustomScheme(schemes[i]);
}
}
bool IsInternalHandledScheme(const std::string& scheme) {
static const char* schemes[] = {
url::kBlobScheme,
content::kChromeDevToolsScheme,
content::kChromeUIScheme,
url::kDataScheme,
url::kFileScheme,
url::kFileSystemScheme,
};
for (size_t i = 0; i < sizeof(schemes) / sizeof(schemes[0]); ++i) {
if (scheme == schemes[i])
return true;
}
return false;
}
bool IsInternalProtectedScheme(const std::string& scheme) {
// Some of these values originate from StoragePartitionImplMap::Get() in
// content/browser/storage_partition_impl_map.cc and are modified by
// InstallInternalProtectedHandlers().
static const char* schemes[] = {
url::kBlobScheme,
content::kChromeUIScheme,
url::kDataScheme,
url::kFileScheme,
url::kFileSystemScheme,
#if !defined(DISABLE_FTP_SUPPORT)
url::kFtpScheme,
#endif
};
for (size_t i = 0; i < sizeof(schemes) / sizeof(schemes[0]); ++i) {
if (scheme == schemes[i])
return true;
}
return false;
}
} // namespace scheme

View File

@@ -0,0 +1,29 @@
// Copyright (c) 2013 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_COMMON_SCHEME_REGISTRATION_H_
#define CEF_LIBCEF_COMMON_SCHEME_REGISTRATION_H_
#pragma once
#include <string>
#include <vector>
namespace scheme {
// Add internal schemes.
void AddInternalSchemes(std::vector<std::string>* standard_schemes);
// Returns true if the specified |scheme| is handled internally.
bool IsInternalHandledScheme(const std::string& scheme);
// Returns true if the specified |scheme| is handled internally and should not
// be explicitly registered or unregistered with the URLRequestJobFactory. A
// registered handler for one of these schemes (like "chrome") may still be
// triggered via chaining from an existing ProtocolHandler. |scheme| should
// always be a lower-case string.
bool IsInternalProtectedScheme(const std::string& scheme);
} // namespace scheme
#endif // CEF_LIBCEF_COMMON_SCHEME_REGISTRATION_H_

View File

@@ -0,0 +1,57 @@
// Copyright (c) 2009 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 <vector>
#include "include/internal/cef_string_list.h"
#include "base/logging.h"
typedef std::vector<CefString> StringList;
CEF_EXPORT cef_string_list_t cef_string_list_alloc() {
return new StringList;
}
CEF_EXPORT int cef_string_list_size(cef_string_list_t list) {
DCHECK(list);
StringList* impl = reinterpret_cast<StringList*>(list);
return impl->size();
}
CEF_EXPORT int cef_string_list_value(cef_string_list_t list, int index,
cef_string_t* value) {
DCHECK(list);
DCHECK(value);
StringList* impl = reinterpret_cast<StringList*>(list);
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(impl->size()));
if (index < 0 || index >= static_cast<int>(impl->size()))
return false;
const CefString& str = (*impl)[index];
return cef_string_copy(str.c_str(), str.length(), value);
}
CEF_EXPORT void cef_string_list_append(cef_string_list_t list,
const cef_string_t* value) {
DCHECK(list);
StringList* impl = reinterpret_cast<StringList*>(list);
impl->push_back(CefString(value));
}
CEF_EXPORT void cef_string_list_clear(cef_string_list_t list) {
DCHECK(list);
StringList* impl = reinterpret_cast<StringList*>(list);
impl->clear();
}
CEF_EXPORT void cef_string_list_free(cef_string_list_t list) {
DCHECK(list);
StringList* impl = reinterpret_cast<StringList*>(list);
delete impl;
}
CEF_EXPORT cef_string_list_t cef_string_list_copy(cef_string_list_t list) {
DCHECK(list);
StringList* impl = reinterpret_cast<StringList*>(list);
return new StringList(*impl);
}

View File

@@ -0,0 +1,92 @@
// Copyright (c) 2009 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 <map>
#include "include/internal/cef_string_map.h"
#include "base/logging.h"
typedef std::map<CefString, CefString> StringMap;
CEF_EXPORT cef_string_map_t cef_string_map_alloc() {
return new StringMap;
}
CEF_EXPORT int cef_string_map_size(cef_string_map_t map) {
DCHECK(map);
StringMap* impl = reinterpret_cast<StringMap*>(map);
return impl->size();
}
CEF_EXPORT int cef_string_map_find(cef_string_map_t map,
const cef_string_t* key,
cef_string_t* value) {
DCHECK(map);
DCHECK(value);
StringMap* impl = reinterpret_cast<StringMap*>(map);
StringMap::const_iterator it = impl->find(CefString(key));
if (it == impl->end())
return 0;
const CefString& val = it->second;
return cef_string_set(val.c_str(), val.length(), value, true);
}
CEF_EXPORT int cef_string_map_key(cef_string_map_t map, int index,
cef_string_t* key) {
DCHECK(map);
DCHECK(key);
StringMap* impl = reinterpret_cast<StringMap*>(map);
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(impl->size()));
if (index < 0 || index >= static_cast<int>(impl->size()))
return 0;
StringMap::const_iterator it = impl->begin();
for (int ct = 0; it != impl->end(); ++it, ct++) {
if (ct == index)
return cef_string_set(it->first.c_str(), it->first.length(), key, true);
}
return 0;
}
CEF_EXPORT int cef_string_map_value(cef_string_map_t map, int index,
cef_string_t* value) {
DCHECK(map);
DCHECK(value);
StringMap* impl = reinterpret_cast<StringMap*>(map);
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(impl->size()));
if (index < 0 || index >= static_cast<int>(impl->size()))
return 0;
StringMap::const_iterator it = impl->begin();
for (int ct = 0; it != impl->end(); ++it, ct++) {
if (ct == index) {
return cef_string_set(it->second.c_str(), it->second.length(), value,
true);
}
}
return 0;
}
CEF_EXPORT int cef_string_map_append(cef_string_map_t map,
const cef_string_t* key,
const cef_string_t* value) {
DCHECK(map);
StringMap* impl = reinterpret_cast<StringMap*>(map);
impl->insert(std::make_pair(CefString(key), CefString(value)));
return 1;
}
CEF_EXPORT void cef_string_map_clear(cef_string_map_t map) {
DCHECK(map);
StringMap* impl = reinterpret_cast<StringMap*>(map);
impl->clear();
}
CEF_EXPORT void cef_string_map_free(cef_string_map_t map) {
DCHECK(map);
StringMap* impl = reinterpret_cast<StringMap*>(map);
delete impl;
}

View File

@@ -0,0 +1,116 @@
// 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 <map>
#include "include/internal/cef_string_multimap.h"
#include "base/logging.h"
typedef std::multimap<CefString, CefString> StringMultimap;
CEF_EXPORT cef_string_multimap_t cef_string_multimap_alloc() {
return new StringMultimap;
}
CEF_EXPORT int cef_string_multimap_size(cef_string_multimap_t map) {
DCHECK(map);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
return impl->size();
}
CEF_EXPORT int cef_string_multimap_find_count(cef_string_multimap_t map,
const cef_string_t* key) {
DCHECK(map);
DCHECK(key);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
return impl->count(CefString(key));
}
CEF_EXPORT int cef_string_multimap_enumerate(cef_string_multimap_t map,
const cef_string_t* key,
int value_index,
cef_string_t* value) {
DCHECK(map);
DCHECK(key);
DCHECK(value);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
CefString key_str(key);
DCHECK_GE(value_index, 0);
DCHECK_LT(value_index, static_cast<int>(impl->count(key_str)));
if (value_index < 0 || value_index >= static_cast<int>(impl->count(key_str)))
return 0;
std::pair<StringMultimap::iterator, StringMultimap::iterator> range_it =
impl->equal_range(key_str);
int count = value_index;
while (count-- && range_it.first != range_it.second)
range_it.first++;
if (range_it.first == range_it.second)
return 0;
const CefString& val = range_it.first->second;
return cef_string_set(val.c_str(), val.length(), value, true);
}
CEF_EXPORT int cef_string_multimap_key(cef_string_multimap_t map, int index,
cef_string_t* key) {
DCHECK(map);
DCHECK(key);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(impl->size()));
if (index < 0 || index >= static_cast<int>(impl->size()))
return 0;
StringMultimap::const_iterator it = impl->begin();
for (int ct = 0; it != impl->end(); ++it, ct++) {
if (ct == index)
return cef_string_set(it->first.c_str(), it->first.length(), key, true);
}
return 0;
}
CEF_EXPORT int cef_string_multimap_value(cef_string_multimap_t map, int index,
cef_string_t* value) {
DCHECK(map);
DCHECK(value);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
DCHECK_GE(index, 0);
DCHECK_LT(index, static_cast<int>(impl->size()));
if (index < 0 || index >= static_cast<int>(impl->size()))
return 0;
StringMultimap::const_iterator it = impl->begin();
for (int ct = 0; it != impl->end(); ++it, ct++) {
if (ct == index) {
return cef_string_set(it->second.c_str(), it->second.length(), value,
true);
}
}
return 0;
}
CEF_EXPORT int cef_string_multimap_append(cef_string_multimap_t map,
const cef_string_t* key,
const cef_string_t* value) {
DCHECK(map);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
impl->insert(std::make_pair(CefString(key), CefString(value)));
return 1;
}
CEF_EXPORT void cef_string_multimap_clear(cef_string_multimap_t map) {
DCHECK(map);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
impl->clear();
}
CEF_EXPORT void cef_string_multimap_free(cef_string_multimap_t map) {
DCHECK(map);
StringMultimap* impl = reinterpret_cast<StringMultimap*>(map);
delete impl;
}

View File

@@ -0,0 +1,277 @@
// Copyright (c) 2010 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 "include/internal/cef_string_types.h"
#include <algorithm>
#include "base/logging.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
namespace {
void string_wide_dtor(wchar_t* str) {
delete [] str;
}
void string_utf8_dtor(char* str) {
delete [] str;
}
void string_utf16_dtor(char16* str) {
delete [] str;
}
// Originally from base/strings/utf_string_conversions.cc
std::wstring ASCIIToWide(const base::StringPiece& ascii) {
DCHECK(base::IsStringASCII(ascii)) << ascii;
return std::wstring(ascii.begin(), ascii.end());
}
} // namespace
CEF_EXPORT int cef_string_wide_set(const wchar_t* src, size_t src_len,
cef_string_wide_t* output, int copy) {
cef_string_wide_clear(output);
if (copy) {
if (src && src_len > 0) {
output->str = new wchar_t[src_len+1];
if (!output->str)
return 0;
memcpy(output->str, src, src_len * sizeof(wchar_t));
output->str[src_len] = 0;
output->length = src_len;
output->dtor = string_wide_dtor;
}
} else {
output->str = const_cast<wchar_t*>(src);
output->length = src_len;
output->dtor = NULL;
}
return 1;
}
CEF_EXPORT int cef_string_utf8_set(const char* src, size_t src_len,
cef_string_utf8_t* output, int copy) {
cef_string_utf8_clear(output);
if (copy) {
if (src && src_len > 0) {
output->str = new char[src_len+1];
if (!output->str)
return 0;
memcpy(output->str, src, src_len * sizeof(char));
output->str[src_len] = 0;
output->length = src_len;
output->dtor = string_utf8_dtor;
}
} else {
output->str = const_cast<char*>(src);
output->length = src_len;
output->dtor = NULL;
}
return 1;
}
CEF_EXPORT int cef_string_utf16_set(const char16* src, size_t src_len,
cef_string_utf16_t* output, int copy) {
cef_string_utf16_clear(output);
if (copy) {
if (src && src_len > 0) {
output->str = new char16[src_len+1];
if (!output->str)
return 0;
memcpy(output->str, src, src_len * sizeof(char16));
output->str[src_len] = 0;
output->length = src_len;
output->dtor = string_utf16_dtor;
}
} else {
output->str = const_cast<char16*>(src);
output->length = src_len;
output->dtor = NULL;
}
return 1;
}
CEF_EXPORT void cef_string_wide_clear(cef_string_wide_t* str) {
DCHECK(str != NULL);
if (str->dtor && str->str)
str->dtor(str->str);
str->str = NULL;
str->length = 0;
str->dtor = NULL;
}
CEF_EXPORT void cef_string_utf8_clear(cef_string_utf8_t* str) {
DCHECK(str != NULL);
if (str->dtor && str->str)
str->dtor(str->str);
str->str = NULL;
str->length = 0;
str->dtor = NULL;
}
CEF_EXPORT void cef_string_utf16_clear(cef_string_utf16_t* str) {
DCHECK(str != NULL);
if (str->dtor && str->str)
str->dtor(str->str);
str->str = NULL;
str->length = 0;
str->dtor = NULL;
}
CEF_EXPORT int cef_string_wide_cmp(const cef_string_wide_t* str1,
const cef_string_wide_t* str2) {
if (str1->length == 0 && str2->length == 0)
return 0;
int r = wcsncmp(str1->str, str2->str, std::min(str1->length, str2->length));
if (r == 0) {
if (str1->length > str2->length)
return 1;
else if (str1->length < str2->length)
return -1;
}
return r;
}
CEF_EXPORT int cef_string_utf8_cmp(const cef_string_utf8_t* str1,
const cef_string_utf8_t* str2) {
if (str1->length == 0 && str2->length == 0)
return 0;
int r = strncmp(str1->str, str2->str, std::min(str1->length, str2->length));
if (r == 0) {
if (str1->length > str2->length)
return 1;
else if (str1->length < str2->length)
return -1;
}
return r;
}
CEF_EXPORT int cef_string_utf16_cmp(const cef_string_utf16_t* str1,
const cef_string_utf16_t* str2) {
if (str1->length == 0 && str2->length == 0)
return 0;
#if defined(WCHAR_T_IS_UTF32)
int r = base::c16memcmp(str1->str, str2->str, std::min(str1->length,
str2->length));
#else
int r = wcsncmp(str1->str, str2->str, std::min(str1->length, str2->length));
#endif
if (r == 0) {
if (str1->length > str2->length)
return 1;
else if (str1->length < str2->length)
return -1;
}
return r;
}
CEF_EXPORT int cef_string_wide_to_utf8(const wchar_t* src, size_t src_len,
cef_string_utf8_t* output) {
std::string str;
bool ret = base::WideToUTF8(src, src_len, &str);
if (!cef_string_utf8_set(str.c_str(), str.length(), output, true))
return false;
return ret;
}
CEF_EXPORT int cef_string_utf8_to_wide(const char* src, size_t src_len,
cef_string_wide_t* output) {
std::wstring str;
bool ret = base::UTF8ToWide(src, src_len, &str);
if (!cef_string_wide_set(str.c_str(), str.length(), output, true))
return false;
return ret;
}
CEF_EXPORT int cef_string_wide_to_utf16(const wchar_t* src, size_t src_len,
cef_string_utf16_t* output) {
base::string16 str;
bool ret = base::WideToUTF16(src, src_len, &str);
if (!cef_string_utf16_set(str.c_str(), str.length(), output, true))
return false;
return ret;
}
CEF_EXPORT int cef_string_utf16_to_wide(const char16* src, size_t src_len,
cef_string_wide_t* output) {
std::wstring str;
bool ret = base::UTF16ToWide(src, src_len, &str);
if (!cef_string_wide_set(str.c_str(), str.length(), output, true))
return false;
return ret;
}
CEF_EXPORT int cef_string_utf8_to_utf16(const char* src, size_t src_len,
cef_string_utf16_t* output) {
base::string16 str;
bool ret = base::UTF8ToUTF16(src, src_len, &str);
if (!cef_string_utf16_set(str.c_str(), str.length(), output, true))
return false;
return ret;
}
CEF_EXPORT int cef_string_utf16_to_utf8(const char16* src, size_t src_len,
cef_string_utf8_t* output) {
std::string str;
bool ret = base::UTF16ToUTF8(src, src_len, &str);
if (!cef_string_utf8_set(str.c_str(), str.length(), output, true))
return false;
return ret;
}
CEF_EXPORT int cef_string_ascii_to_wide(const char* src, size_t src_len,
cef_string_wide_t* output) {
const std::wstring& str = ASCIIToWide(std::string(src, src_len));
return cef_string_wide_set(str.c_str(), str.length(), output, true);
}
CEF_EXPORT int cef_string_ascii_to_utf16(const char* src, size_t src_len,
cef_string_utf16_t* output) {
const base::string16& str = base::ASCIIToUTF16(std::string(src, src_len));
return cef_string_utf16_set(str.c_str(), str.length(), output, true);
}
CEF_EXPORT cef_string_userfree_wide_t cef_string_userfree_wide_alloc() {
cef_string_wide_t* s = new cef_string_wide_t;
memset(s, 0, sizeof(cef_string_wide_t));
return s;
}
CEF_EXPORT cef_string_userfree_utf8_t cef_string_userfree_utf8_alloc() {
cef_string_utf8_t* s = new cef_string_utf8_t;
memset(s, 0, sizeof(cef_string_utf8_t));
return s;
}
CEF_EXPORT cef_string_userfree_utf16_t cef_string_userfree_utf16_alloc() {
cef_string_utf16_t* s = new cef_string_utf16_t;
memset(s, 0, sizeof(cef_string_utf16_t));
return s;
}
CEF_EXPORT void cef_string_userfree_wide_free(cef_string_userfree_wide_t str) {
cef_string_wide_clear(str);
delete str;
}
CEF_EXPORT void cef_string_userfree_utf8_free(cef_string_userfree_utf8_t str) {
cef_string_utf8_clear(str);
delete str;
}
CEF_EXPORT void cef_string_userfree_utf16_free(
cef_string_userfree_utf16_t str) {
cef_string_utf16_clear(str);
delete str;
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) 2013 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 "include/cef_task.h"
#include "libcef/common/task_runner_impl.h"
#include "base/bind.h"
#include "base/location.h"
bool CefCurrentlyOn(CefThreadId threadId) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
CefTaskRunnerImpl::GetTaskRunner(threadId);
if (task_runner.get())
return task_runner->RunsTasksOnCurrentThread();
return false;
}
bool CefPostTask(CefThreadId threadId, CefRefPtr<CefTask> task) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
CefTaskRunnerImpl::GetTaskRunner(threadId);
if (task_runner.get()) {
return task_runner->PostTask(FROM_HERE,
base::Bind(&CefTask::Execute, task.get()));
}
return false;
}
bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr<CefTask> task, int64 delay_ms) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
CefTaskRunnerImpl::GetTaskRunner(threadId);
if (task_runner.get()) {
return task_runner->PostDelayedTask(FROM_HERE,
base::Bind(&CefTask::Execute, task.get()),
base::TimeDelta::FromMilliseconds(delay_ms));
}
return false;
}

View File

@@ -0,0 +1,147 @@
// Copyright (c) 2013 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/common/task_runner_impl.h"
#include "libcef/common/content_client.h"
#include "libcef/renderer/content_renderer_client.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "content/public/browser/browser_thread.h"
using content::BrowserThread;
// CefTaskRunner
// static
CefRefPtr<CefTaskRunner> CefTaskRunner::GetForCurrentThread() {
scoped_refptr<base::SequencedTaskRunner> task_runner =
CefTaskRunnerImpl::GetCurrentTaskRunner();
if (task_runner.get())
return new CefTaskRunnerImpl(task_runner);
return NULL;
}
// static
CefRefPtr<CefTaskRunner> CefTaskRunner::GetForThread(CefThreadId threadId) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
CefTaskRunnerImpl::GetTaskRunner(threadId);
if (task_runner.get())
return new CefTaskRunnerImpl(task_runner);
LOG(WARNING) << "Invalid thread id " << threadId;
return NULL;
}
// CefTaskRunnerImpl
CefTaskRunnerImpl::CefTaskRunnerImpl(
scoped_refptr<base::SequencedTaskRunner> task_runner)
: task_runner_(task_runner) {
DCHECK(task_runner_.get());
}
// static
scoped_refptr<base::SequencedTaskRunner>
CefTaskRunnerImpl::GetTaskRunner(CefThreadId threadId) {
// Render process.
if (threadId == TID_RENDERER) {
CefContentRendererClient* client = CefContentRendererClient::Get();
if (client)
return client->render_task_runner();
return NULL;
}
// Browser process.
int id = -1;
switch (threadId) {
case TID_UI:
id = BrowserThread::UI;
break;
case TID_DB:
id = BrowserThread::DB;
break;
case TID_FILE:
id = BrowserThread::FILE;
break;
case TID_FILE_USER_BLOCKING:
id = BrowserThread::FILE_USER_BLOCKING;
break;
case TID_PROCESS_LAUNCHER:
id = BrowserThread::PROCESS_LAUNCHER;
break;
case TID_CACHE:
id = BrowserThread::CACHE;
break;
case TID_IO:
id = BrowserThread::IO;
break;
default:
break;
};
if (id >= 0 && CefContentClient::Get()->browser() &&
BrowserThread::IsMessageLoopValid(static_cast<BrowserThread::ID>(id))) {
// Don't use BrowserThread::GetMessageLoopProxyForThread because it returns
// a new MessageLoopProxy object for each call and makes pointer equality
// testing impossible.
base::MessageLoop* message_loop =
BrowserThread::UnsafeGetMessageLoopForThread(
static_cast<BrowserThread::ID>(id));
if (message_loop)
return message_loop->message_loop_proxy();
}
return NULL;
}
// static
scoped_refptr<base::SequencedTaskRunner>
CefTaskRunnerImpl::GetCurrentTaskRunner() {
scoped_refptr<base::SequencedTaskRunner> task_runner;
// Check for a MessageLoopProxy. This covers all of the named browser and
// render process threads, plus a few extra.
task_runner = base::MessageLoopProxy::current();
if (!task_runner.get()) {
// Check for a WebWorker thread.
CefContentRendererClient* client = CefContentRendererClient::Get();
if (client)
task_runner = client->GetCurrentTaskRunner();
}
return task_runner;
}
bool CefTaskRunnerImpl::IsSame(CefRefPtr<CefTaskRunner> that) {
CefTaskRunnerImpl* impl = static_cast<CefTaskRunnerImpl*>(that.get());
return (impl && task_runner_ == impl->task_runner_);
}
bool CefTaskRunnerImpl::BelongsToCurrentThread() {
return task_runner_->RunsTasksOnCurrentThread();
}
bool CefTaskRunnerImpl::BelongsToThread(CefThreadId threadId) {
scoped_refptr<base::SequencedTaskRunner> task_runner =
GetTaskRunner(threadId);
return (task_runner_ == task_runner);
}
bool CefTaskRunnerImpl::PostTask(CefRefPtr<CefTask> task) {
return task_runner_->PostTask(FROM_HERE,
base::Bind(&CefTask::Execute, task.get()));
}
bool CefTaskRunnerImpl::PostDelayedTask(CefRefPtr<CefTask> task,
int64 delay_ms) {
return task_runner_->PostDelayedTask(FROM_HERE,
base::Bind(&CefTask::Execute, task.get()),
base::TimeDelta::FromMilliseconds(delay_ms));
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) 2013 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_COMMON_TASK_RUNNER_IMPL_H_
#define CEF_LIBCEF_COMMON_TASK_RUNNER_IMPL_H_
#pragma once
#include "include/cef_task.h"
#include "base/sequenced_task_runner.h"
class CefTaskRunnerImpl : public CefTaskRunner {
public:
explicit CefTaskRunnerImpl(
scoped_refptr<base::SequencedTaskRunner> task_runner);
// Returns the task runner associated with |threadId|.
static scoped_refptr<base::SequencedTaskRunner>
GetTaskRunner(CefThreadId threadId);
// Returns the current task runner.
static scoped_refptr<base::SequencedTaskRunner> GetCurrentTaskRunner();
// CefTaskRunner methods:
bool IsSame(CefRefPtr<CefTaskRunner> that) override;
bool BelongsToCurrentThread() override;
bool BelongsToThread(CefThreadId threadId) override;
bool PostTask(CefRefPtr<CefTask> task) override;
bool PostDelayedTask(CefRefPtr<CefTask> task,
int64 delay_ms) override;
private:
scoped_refptr<base::SequencedTaskRunner> task_runner_;
IMPLEMENT_REFCOUNTING(CefTaskRunnerImpl);
DISALLOW_COPY_AND_ASSIGN(CefTaskRunnerImpl);
};
#endif // CEF_LIBCEF_COMMON_TASK_RUNNER_IMPL_H_

View File

@@ -0,0 +1,93 @@
// 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/common/time_util.h"
void cef_time_to_basetime(const cef_time_t& cef_time, base::Time& time) {
base::Time::Exploded exploded;
exploded.year = cef_time.year;
exploded.month = cef_time.month;
exploded.day_of_week = cef_time.day_of_week;
exploded.day_of_month = cef_time.day_of_month;
exploded.hour = cef_time.hour;
exploded.minute = cef_time.minute;
exploded.second = cef_time.second;
exploded.millisecond = cef_time.millisecond;
time = base::Time::FromUTCExploded(exploded);
}
void cef_time_from_basetime(const base::Time& time, cef_time_t& cef_time) {
base::Time::Exploded exploded;
time.UTCExplode(&exploded);
cef_time.year = exploded.year;
cef_time.month = exploded.month;
cef_time.day_of_week = exploded.day_of_week;
cef_time.day_of_month = exploded.day_of_month;
cef_time.hour = exploded.hour;
cef_time.minute = exploded.minute;
cef_time.second = exploded.second;
cef_time.millisecond = exploded.millisecond;
}
CEF_EXPORT int cef_time_to_timet(const cef_time_t* cef_time, time_t* time) {
if (!cef_time || !time)
return 0;
base::Time base_time;
cef_time_to_basetime(*cef_time, base_time);
*time = base_time.ToTimeT();
return 1;
}
CEF_EXPORT int cef_time_from_timet(time_t time, cef_time_t* cef_time) {
if (!cef_time)
return 0;
base::Time base_time = base::Time::FromTimeT(time);
cef_time_from_basetime(base_time, *cef_time);
return 1;
}
CEF_EXPORT int cef_time_to_doublet(const cef_time_t* cef_time, double* time) {
if (!cef_time || !time)
return 0;
base::Time base_time;
cef_time_to_basetime(*cef_time, base_time);
*time = base_time.ToDoubleT();
return 1;
}
CEF_EXPORT int cef_time_from_doublet(double time, cef_time_t* cef_time) {
if (!cef_time)
return 0;
base::Time base_time = base::Time::FromDoubleT(time);
cef_time_from_basetime(base_time, *cef_time);
return 1;
}
CEF_EXPORT int cef_time_now(cef_time_t* cef_time) {
if (!cef_time)
return 0;
base::Time base_time = base::Time::Now();
cef_time_from_basetime(base_time, *cef_time);
return 1;
}
CEF_EXPORT int cef_time_delta(const cef_time_t* cef_time1,
const cef_time_t* cef_time2,
long long* delta) {
if (!cef_time1 || !cef_time2 || !delta)
return 0;
base::Time base_time1, base_time2;
cef_time_to_basetime(*cef_time1, base_time1);
cef_time_to_basetime(*cef_time2, base_time2);
base::TimeDelta time_delta = base_time2 - base_time1;
*delta = time_delta.InMilliseconds();
return 1;
}

16
libcef/common/time_util.h Normal file
View File

@@ -0,0 +1,16 @@
// 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_COMMON_TIME_UTIL_H_
#define CEF_LIBCEF_COMMON_TIME_UTIL_H_
#pragma once
#include "include/internal/cef_time.h"
#include "base/time/time.h"
// Converts cef_time_t to/from a base::Time object.
void cef_time_to_basetime(const cef_time_t& cef_time, base::Time& time);
void cef_time_from_basetime(const base::Time& time, cef_time_t& cef_time);
#endif // CEF_LIBCEF_COMMON_TIME_UTIL_H_

83
libcef/common/tracker.cc Normal file
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/common/tracker.h"
// CefTrackNode implementation.
CefTrackNode::CefTrackNode()
: track_next_(NULL),
track_prev_(NULL) {
}
CefTrackNode::~CefTrackNode() {
}
void CefTrackNode::InsertTrackPrev(CefTrackNode* object) {
if (track_prev_)
track_prev_->SetTrackNext(object);
object->SetTrackNext(this);
object->SetTrackPrev(track_prev_);
track_prev_ = object;
}
void CefTrackNode::InsertTrackNext(CefTrackNode* object) {
if (track_next_)
track_next_->SetTrackPrev(object);
object->SetTrackPrev(this);
object->SetTrackNext(track_next_);
track_next_ = object;
}
void CefTrackNode::RemoveTracking() {
if (track_next_)
track_next_->SetTrackPrev(track_prev_);
if (track_prev_)
track_prev_->SetTrackNext(track_next_);
track_next_ = NULL;
track_prev_ = NULL;
}
// CefTrackManager implementation.
CefTrackManager::CefTrackManager()
: object_count_(0) {
}
CefTrackManager::~CefTrackManager() {
DeleteAll();
}
void CefTrackManager::Add(CefTrackNode* object) {
base::AutoLock lock_scope(lock_);
if (!object->IsTracked()) {
tracker_.InsertTrackNext(object);
++object_count_;
}
}
bool CefTrackManager::Delete(CefTrackNode* object) {
base::AutoLock lock_scope(lock_);
if (object->IsTracked()) {
object->RemoveTracking();
delete object;
--object_count_;
return true;
}
return false;
}
void CefTrackManager::DeleteAll() {
base::AutoLock lock_scope(lock_);
CefTrackNode* next;
do {
next = tracker_.GetTrackNext();
if (next) {
next->RemoveTracking();
delete next;
}
} while (next != NULL);
object_count_ = 0;
}

77
libcef/common/tracker.h Normal file
View File

@@ -0,0 +1,77 @@
// 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_COMMON_TRACKER_H_
#define CEF_LIBCEF_COMMON_TRACKER_H_
#pragma once
#include "include/cef_base.h"
#include "base/synchronization/lock.h"
// Class extended by objects that must be tracked. After creating a tracked
// object you should add it to the appropriate track manager.
class CefTrackNode {
public:
CefTrackNode();
virtual ~CefTrackNode();
// Returns true if the object is currently being tracked.
inline bool IsTracked() { return (track_prev_ || track_next_); }
private:
inline CefTrackNode* GetTrackPrev() { return track_prev_; }
inline void SetTrackPrev(CefTrackNode* base) { track_prev_ = base; }
inline CefTrackNode* GetTrackNext() { return track_next_; }
inline void SetTrackNext(CefTrackNode* base) { track_next_ = base; }
// Insert a new object into the tracking list before this object.
void InsertTrackPrev(CefTrackNode* object);
// Insert a new object into the tracking list after this object.
void InsertTrackNext(CefTrackNode* object);
// Remove this object from the tracking list.
void RemoveTracking();
private:
CefTrackNode* track_next_;
CefTrackNode* track_prev_;
friend class CefTrackManager;
};
// Class used to manage tracked objects. A single instance of this class
// should be created for each intended usage. Any objects that have not been
// removed by explicit calls to the Destroy() method will be removed when the
// manager object is destroyed. A manager object can be created as either a
// member variable of another class or by using lazy initialization:
// base::LazyInstance<CefTrackManager> g_singleton = LAZY_INSTANCE_INITIALIZER;
class CefTrackManager : public CefBase {
public:
CefTrackManager();
~CefTrackManager() override;
// Add an object to be tracked by this manager.
void Add(CefTrackNode* object);
// Delete an object tracked by this manager.
bool Delete(CefTrackNode* object);
// Delete all objects tracked by this manager.
void DeleteAll();
// Returns the number of objects currently being tracked.
inline int GetCount() { return object_count_; }
private:
CefTrackNode tracker_;
int object_count_;
base::Lock lock_;
IMPLEMENT_REFCOUNTING(CefTrackManager);
};
#endif // CEF_LIBCEF_COMMON_TRACKER_H_

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2012 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 "cef/libcef/common/upload_data.h"
#include "base/logging.h"
namespace net {
UploadData::UploadData()
: identifier_(0),
is_chunked_(false),
last_chunk_appended_(false) {
}
void UploadData::AppendBytes(const char* bytes, int bytes_len) {
DCHECK(!is_chunked_);
if (bytes_len > 0) {
elements_.push_back(new UploadElement());
elements_.back()->SetToBytes(bytes, bytes_len);
}
}
void UploadData::AppendFileRange(const base::FilePath& file_path,
uint64 offset, uint64 length,
const base::Time& expected_modification_time) {
DCHECK(!is_chunked_);
elements_.push_back(new UploadElement());
elements_.back()->SetToFilePathRange(file_path, offset, length,
expected_modification_time);
}
UploadData::~UploadData() {
}
} // namespace net

View File

@@ -0,0 +1,84 @@
// Copyright (c) 2012 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 CEF_LIBCEF_COMMON_UPLOAD_DATA_H_
#define CEF_LIBCEF_COMMON_UPLOAD_DATA_H_
#include "libcef/common/upload_element.h"
#include "base/basictypes.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_vector.h"
#include "base/supports_user_data.h"
#include "net/base/net_export.h"
namespace base {
class FilePath;
class Time;
} // namespace base
namespace net {
//-----------------------------------------------------------------------------
// A very concrete class representing the data to be uploaded as part of a
// URLRequest.
//
// Until there is a more abstract class for this, this one derives from
// SupportsUserData to allow users to stash random data by
// key and ensure its destruction when UploadData is finally deleted.
class NET_EXPORT UploadData
: public base::RefCounted<UploadData>,
public base::SupportsUserData {
public:
UploadData();
void AppendBytes(const char* bytes, int bytes_len);
void AppendFileRange(const base::FilePath& file_path,
uint64 offset, uint64 length,
const base::Time& expected_modification_time);
// Initializes the object to send chunks of upload data over time rather
// than all at once. Chunked data may only contain bytes, not files.
void set_is_chunked(bool set) { is_chunked_ = set; }
bool is_chunked() const { return is_chunked_; }
// set_last_chunk_appended() is only used for serialization.
void set_last_chunk_appended(bool set) { last_chunk_appended_ = set; }
bool last_chunk_appended() const { return last_chunk_appended_; }
const ScopedVector<UploadElement>& elements() const {
return elements_;
}
ScopedVector<UploadElement>* elements_mutable() {
return &elements_;
}
void swap_elements(ScopedVector<UploadElement>* elements) {
elements_.swap(*elements);
}
// Identifies a particular upload instance, which is used by the cache to
// formulate a cache key. This value should be unique across browser
// sessions. A value of 0 is used to indicate an unspecified identifier.
void set_identifier(int64 id) { identifier_ = id; }
int64 identifier() const { return identifier_; }
private:
friend class base::RefCounted<UploadData>;
~UploadData() override;
ScopedVector<UploadElement> elements_;
int64 identifier_;
bool is_chunked_;
bool last_chunk_appended_;
DISALLOW_COPY_AND_ASSIGN(UploadData);
};
} // namespace net
#endif // CEF_LIBCEF_COMMON_UPLOAD_DATA_H_

View File

@@ -0,0 +1,25 @@
// Copyright (c) 2012 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 "libcef/common/upload_element.h"
#include <algorithm>
#include "net/base/file_stream.h"
#include "net/base/net_errors.h"
namespace net {
UploadElement::UploadElement()
: type_(TYPE_BYTES),
bytes_start_(NULL),
bytes_length_(0),
file_range_offset_(0),
file_range_length_(kuint64max) {
}
UploadElement::~UploadElement() {
}
} // namespace net

View File

@@ -0,0 +1,110 @@
// Copyright (c) 2012 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 CEF_LIBCEF_COMMON_UPLOAD_ELEMENT_H_
#define CEF_LIBCEF_COMMON_UPLOAD_ELEMENT_H_
#include <vector>
#include "base/basictypes.h"
#include "base/files/file_path.h"
#include "base/time/time.h"
#include "net/base/net_export.h"
namespace net {
// A class representing an element contained by UploadData.
class NET_EXPORT UploadElement {
public:
enum Type {
TYPE_BYTES,
TYPE_FILE,
};
UploadElement();
~UploadElement();
Type type() const { return type_; }
const char* bytes() const { return bytes_start_ ? bytes_start_ : &buf_[0]; }
uint64 bytes_length() const { return buf_.size() + bytes_length_; }
const base::FilePath& file_path() const { return file_path_; }
uint64 file_range_offset() const { return file_range_offset_; }
uint64 file_range_length() const { return file_range_length_; }
// If NULL time is returned, we do not do the check.
const base::Time& expected_file_modification_time() const {
return expected_file_modification_time_;
}
void SetToBytes(const char* bytes, int bytes_len) {
type_ = TYPE_BYTES;
buf_.assign(bytes, bytes + bytes_len);
}
// This does not copy the given data and the caller should make sure
// the data is secured somewhere else (e.g. by attaching the data
// using SetUserData).
void SetToSharedBytes(const char* bytes, int bytes_len) {
type_ = TYPE_BYTES;
bytes_start_ = bytes;
bytes_length_ = bytes_len;
}
void SetToFilePath(const base::FilePath& path) {
SetToFilePathRange(path, 0, kuint64max, base::Time());
}
// If expected_modification_time is NULL, we do not check for the file
// change. Also note that the granularity for comparison is time_t, not
// the full precision.
void SetToFilePathRange(const base::FilePath& path,
uint64 offset, uint64 length,
const base::Time& expected_modification_time) {
type_ = TYPE_FILE;
file_path_ = path;
file_range_offset_ = offset;
file_range_length_ = length;
expected_file_modification_time_ = expected_modification_time;
}
private:
Type type_;
std::vector<char> buf_;
const char* bytes_start_;
uint64 bytes_length_;
base::FilePath file_path_;
uint64 file_range_offset_;
uint64 file_range_length_;
base::Time expected_file_modification_time_;
DISALLOW_COPY_AND_ASSIGN(UploadElement);
};
#if defined(UNIT_TEST)
inline bool operator==(const UploadElement& a,
const UploadElement& b) {
if (a.type() != b.type())
return false;
if (a.type() == UploadElement::TYPE_BYTES)
return a.bytes_length() == b.bytes_length() &&
memcmp(a.bytes(), b.bytes(), b.bytes_length()) == 0;
if (a.type() == UploadElement::TYPE_FILE) {
return a.file_path() == b.file_path() &&
a.file_range_offset() == b.file_range_offset() &&
a.file_range_length() == b.file_range_length() &&
a.expected_file_modification_time() ==
b.expected_file_modification_time();
}
return false;
}
inline bool operator!=(const UploadElement& a,
const UploadElement& b) {
return !(a == b);
}
#endif // defined(UNIT_TEST)
} // namespace net
#endif // CEF_LIBCEF_COMMON_UPLOAD_ELEMENT_H_

87
libcef/common/url_impl.cc Normal file
View File

@@ -0,0 +1,87 @@
// 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 <sstream>
#include "include/cef_url.h"
#include "net/base/mime_util.h"
#include "url/gurl.h"
bool CefParseURL(const CefString& url,
CefURLParts& parts) {
GURL gurl(url.ToString());
if (!gurl.is_valid())
return false;
CefString(&parts.spec).FromString(gurl.spec());
CefString(&parts.scheme).FromString(gurl.scheme());
CefString(&parts.username).FromString(gurl.username());
CefString(&parts.password).FromString(gurl.password());
CefString(&parts.host).FromString(gurl.host());
CefString(&parts.origin).FromString(gurl.GetOrigin().spec());
CefString(&parts.port).FromString(gurl.port());
CefString(&parts.path).FromString(gurl.path());
CefString(&parts.query).FromString(gurl.query());
return true;
}
bool CefCreateURL(const CefURLParts& parts,
CefString& url) {
std::string spec = CefString(parts.spec.str, parts.spec.length, false);
std::string scheme = CefString(parts.scheme.str, parts.scheme.length, false);
std::string username =
CefString(parts.username.str, parts.username.length, false);
std::string password =
CefString(parts.password.str, parts.password.length, false);
std::string host = CefString(parts.host.str, parts.host.length, false);
std::string port = CefString(parts.port.str, parts.port.length, false);
std::string path = CefString(parts.path.str, parts.path.length, false);
std::string query = CefString(parts.query.str, parts.query.length, false);
GURL gurl;
if (!spec.empty()) {
gurl = GURL(spec);
} else if (!scheme.empty() && !host.empty()) {
std::stringstream ss;
ss << scheme << "://";
if (!username.empty()) {
ss << username;
if (!password.empty())
ss << ":" << password;
ss << "@";
}
ss << host;
if (!port.empty())
ss << ":" << port;
if (!path.empty())
ss << path;
if (!query.empty())
ss << "?" << query;
gurl = GURL(ss.str());
}
if (gurl.is_valid()) {
url = gurl.spec();
return true;
}
return false;
}
CefString CefGetMimeType(const CefString& extension) {
std::string mime_type;
net::GetMimeTypeFromExtension(extension, &mime_type);
return mime_type;
}
void CefGetExtensionsForMimeType(const CefString& mime_type,
std::vector<CefString>& extensions) {
typedef std::vector<base::FilePath::StringType> VectorType;
VectorType ext;
net::GetExtensionsForMimeType(mime_type, &ext);
VectorType::const_iterator it = ext.begin();
for (; it != ext.end(); ++it)
extensions.push_back(*it);
}

View File

@@ -0,0 +1,46 @@
// 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 "include/cef_urlrequest.h"
#include "libcef/browser/browser_urlrequest_impl.h"
#include "libcef/common/content_client.h"
#include "libcef/renderer/render_urlrequest_impl.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "content/public/common/content_client.h"
// static
CefRefPtr<CefURLRequest> CefURLRequest::Create(
CefRefPtr<CefRequest> request,
CefRefPtr<CefURLRequestClient> client) {
if (!request.get() || !client.get()) {
NOTREACHED() << "called with invalid parameters";
return NULL;
}
if (!base::MessageLoop::current()) {
NOTREACHED() << "called on invalid thread";
return NULL;
}
if (CefContentClient::Get()->browser()) {
// In the browser process.
CefRefPtr<CefBrowserURLRequest> impl =
new CefBrowserURLRequest(request, client);
if (impl->Start())
return impl.get();
return NULL;
} else if (CefContentClient::Get()->renderer()) {
// In the render process.
CefRefPtr<CefRenderURLRequest> impl =
new CefRenderURLRequest(request, client);
if (impl->Start())
return impl.get();
return NULL;
} else {
NOTREACHED() << "called in unsupported process";
return NULL;
}
}

201
libcef/common/value_base.cc Normal file
View File

@@ -0,0 +1,201 @@
// 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/common/value_base.h"
CefValueController::CefValueController()
: owner_value_(NULL),
owner_object_(NULL) {
}
CefValueController::~CefValueController() {
// Everything should already have been removed.
DCHECK(!owner_value_ && !owner_object_);
DCHECK(reference_map_.empty());
DCHECK(dependency_map_.empty());
}
void CefValueController::SetOwner(void* value, Object* object) {
DCHECK(value && object);
// Controller should already be locked.
DCHECK(locked());
// Owner should only be set once.
DCHECK(!owner_value_ && !owner_object_);
owner_value_ = value;
owner_object_ = object;
}
void CefValueController::AddReference(void* value, Object* object) {
DCHECK(value && object);
// Controller should already be locked.
DCHECK(locked());
// Controller should currently have an owner.
DCHECK(owner_value_);
// Values should only be added once.
DCHECK(reference_map_.find(value) == reference_map_.end());
DCHECK(value != owner_value_);
reference_map_.insert(std::make_pair(value, object));
}
void CefValueController::Remove(void* value, bool notify_object) {
DCHECK(value);
// Controller should already be locked.
DCHECK(locked());
// Controller should currently have an owner.
DCHECK(owner_value_);
if (value == owner_value_) {
// Should never notify when removing the owner object.
DCHECK(!notify_object);
owner_value_ = NULL;
owner_object_ = NULL;
// Remove all references.
if (reference_map_.size() > 0) {
ReferenceMap::iterator it = reference_map_.begin();
for (; it != reference_map_.end(); ++it)
it->second->OnControlRemoved();
reference_map_.clear();
}
// Remove all dependencies.
dependency_map_.clear();
} else {
ReferenceMap::iterator it = reference_map_.find(value);
if (it != reference_map_.end()) {
// Remove the reference.
if (notify_object)
it->second->OnControlRemoved();
reference_map_.erase(it);
}
}
}
CefValueController::Object* CefValueController::Get(void* value) {
DCHECK(value);
// Controller should already be locked.
DCHECK(locked());
if (value == owner_value_) {
return owner_object_;
} else {
ReferenceMap::iterator it = reference_map_.find(value);
if (it != reference_map_.end())
return it->second;
return NULL;
}
}
void CefValueController::AddDependency(void* parent, void* child) {
DCHECK(parent && child && parent != child);
// Controller should already be locked.
DCHECK(locked());
DependencyMap::iterator it = dependency_map_.find(parent);
if (it == dependency_map_.end()) {
// New set.
DependencySet set;
set.insert(child);
dependency_map_.insert(std::make_pair(parent, set));
} else if (it->second.find(child) == it->second.end()) {
// Update existing set.
it->second.insert(child);
}
}
void CefValueController::RemoveDependencies(void* value) {
DCHECK(value);
// Controller should already be locked.
DCHECK(locked());
if (dependency_map_.empty())
return;
DependencyMap::iterator it_dependency = dependency_map_.find(value);
if (it_dependency == dependency_map_.end())
return;
// Start with the set of dependencies for the current value.
DependencySet remove_set = it_dependency->second;
dependency_map_.erase(it_dependency);
DependencySet::iterator it_value;
ReferenceMap::iterator it_reference;
while (remove_set.size() > 0) {
it_value = remove_set.begin();
value = *it_value;
remove_set.erase(it_value);
// Does the current value have dependencies?
it_dependency = dependency_map_.find(value);
if (it_dependency != dependency_map_.end()) {
// Append the dependency set to the remove set.
remove_set.insert(it_dependency->second.begin(),
it_dependency->second.end());
dependency_map_.erase(it_dependency);
}
// Does the current value have a reference?
it_reference = reference_map_.find(value);
if (it_reference != reference_map_.end()) {
// Remove the reference.
it_reference->second->OnControlRemoved();
reference_map_.erase(it_reference);
}
}
}
void CefValueController::TakeFrom(CefValueController* other) {
DCHECK(other);
// Both controllers should already be locked.
DCHECK(locked());
DCHECK(other->locked());
if (!other->reference_map_.empty()) {
// Transfer references from the other to this.
ReferenceMap::iterator it = other->reference_map_.begin();
for (; it != other->reference_map_.end(); ++it) {
// References should only be added once.
DCHECK(reference_map_.find(it->first) == reference_map_.end());
reference_map_.insert(std::make_pair(it->first, it->second));
}
other->reference_map_.empty();
}
if (!other->dependency_map_.empty()) {
// Transfer dependencies from the other to this.
DependencyMap::iterator it_other = other->dependency_map_.begin();
for (; it_other != other->dependency_map_.end(); ++it_other) {
DependencyMap::iterator it_me = dependency_map_.find(it_other->first);
if (it_me == dependency_map_.end()) {
// All children are new.
dependency_map_.insert(
std::make_pair(it_other->first, it_other->second));
} else {
// Evaluate each child.
DependencySet::iterator it_other_set = it_other->second.begin();
for (; it_other_set != it_other->second.end(); ++it_other_set) {
if (it_me->second.find(*it_other_set) == it_me->second.end())
it_me->second.insert(*it_other_set);
}
}
}
}
}

419
libcef/common/value_base.h Normal file
View File

@@ -0,0 +1,419 @@
// 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_COMMON_VALUE_BASE_H_
#define CEF_LIBCEF_COMMON_VALUE_BASE_H_
#pragma once
#include <map>
#include <set>
#include "include/cef_base.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/synchronization/lock.h"
#include "base/threading/platform_thread.h"
// Controller implementation base class.
class CefValueController
: public base::RefCountedThreadSafe<CefValueController> {
public:
// Implemented by a class controlled using the access controller.
class Object {
public:
virtual ~Object() {}
// Called when the value has been removed.
virtual void OnControlRemoved() =0;
};
// Encapsulates context locking and verification logic.
class AutoLock {
public:
explicit AutoLock(CefValueController* impl)
: impl_(impl),
verified_(impl && impl->VerifyThread()) {
DCHECK(impl);
if (verified_)
impl_->lock();
}
~AutoLock() {
if (verified_)
impl_->unlock();
}
inline bool verified() { return verified_; }
private:
scoped_refptr<CefValueController> impl_;
bool verified_;
DISALLOW_COPY_AND_ASSIGN(AutoLock);
};
CefValueController();
// Returns true if this controller is thread safe.
virtual bool thread_safe() =0;
// Returns true if the current thread is allowed to access this controller.
virtual bool on_correct_thread() =0;
// Lock the controller.
virtual void lock() =0;
// Unlock the controller.
virtual void unlock() =0;
// Returns true if the controller is locked on the current thread.
virtual bool locked() =0;
// Verify that the current thread is correct for accessing the controller.
inline bool VerifyThread() {
if (!thread_safe() && !on_correct_thread()) {
// This object should only be accessed from the thread that created it.
NOTREACHED() << "object accessed from incorrect thread.";
return false;
}
return true;
}
// The controller must already be locked before calling the below methods.
// Set the owner for this controller.
void SetOwner(void* value, Object* object);
// Add a reference value and associated object.
void AddReference(void* value, Object* object);
// Remove the value. If |notify_object| is true the removed object will be
// notified. If |value| is the owner all reference objects will be removed.
// If |value| has dependencies those objects will also be removed.
void Remove(void* value, bool notify_object);
// Returns the object for the specified value.
Object* Get(void* value);
// Add a dependency between |parent| and |child|.
void AddDependency(void* parent, void* child);
// Recursively removes any dependent values.
void RemoveDependencies(void* value);
// Takes ownership of all references and dependencies currently controlled by
// |other|. The |other| controller must already be locked.
void TakeFrom(CefValueController* other);
protected:
friend class base::RefCountedThreadSafe<CefValueController>;
virtual ~CefValueController();
private:
// Owner object.
void* owner_value_;
Object* owner_object_;
// Map of reference objects.
typedef std::map<void*, Object*> ReferenceMap;
ReferenceMap reference_map_;
// Map of dependency objects.
typedef std::set<void*> DependencySet;
typedef std::map<void*, DependencySet> DependencyMap;
DependencyMap dependency_map_;
DISALLOW_COPY_AND_ASSIGN(CefValueController);
};
// Thread-safe access control implementation.
class CefValueControllerThreadSafe : public CefValueController {
public:
explicit CefValueControllerThreadSafe()
: locked_thread_id_(0) {}
// CefValueController methods.
bool thread_safe() override { return true; }
bool on_correct_thread() override { return true; }
void lock() override {
lock_.Acquire();
locked_thread_id_ = base::PlatformThread::CurrentId();
}
void unlock() override {
locked_thread_id_ = 0;
lock_.Release();
}
bool locked() override {
return (locked_thread_id_ == base::PlatformThread::CurrentId());
}
private:
base::Lock lock_;
base::PlatformThreadId locked_thread_id_;
DISALLOW_COPY_AND_ASSIGN(CefValueControllerThreadSafe);
};
// Non-thread-safe access control implementation.
class CefValueControllerNonThreadSafe : public CefValueController {
public:
explicit CefValueControllerNonThreadSafe()
: thread_id_(base::PlatformThread::CurrentId()) {}
// CefValueController methods.
bool thread_safe() override { return false; }
bool on_correct_thread() override {
return (thread_id_ == base::PlatformThread::CurrentId());
}
void lock() override {}
void unlock() override {}
bool locked() override { return on_correct_thread(); }
private:
base::PlatformThreadId thread_id_;
DISALLOW_COPY_AND_ASSIGN(CefValueControllerNonThreadSafe);
};
// Helper macros for verifying context.
#define CEF_VALUE_VERIFY_RETURN_VOID_EX(object, modify) \
if (!VerifyAttached()) \
return; \
AutoLock auto_lock(object, modify); \
if (!auto_lock.verified()) \
return;
#define CEF_VALUE_VERIFY_RETURN_VOID(modify) \
CEF_VALUE_VERIFY_RETURN_VOID_EX(this, modify)
#define CEF_VALUE_VERIFY_RETURN_EX(object, modify, error_val) \
if (!VerifyAttached()) \
return error_val; \
AutoLock auto_lock(object, modify); \
if (!auto_lock.verified()) \
return error_val;
#define CEF_VALUE_VERIFY_RETURN(modify, error_val) \
CEF_VALUE_VERIFY_RETURN_EX(this, modify, error_val)
// Template class for implementing CEF wrappers of other types.
template<class CefType, class ValueType>
class CefValueBase : public CefType, public CefValueController::Object {
public:
// Specifies how the value will be used.
enum ValueMode {
// A reference to a value managed by an existing controller. These values
// can be safely detached but ownership should not be transferred (make a
// copy of the value instead).
kReference,
// The value has its own controller and will be deleted on destruction.
// These values can only be detached to another controller otherwise any
// references will not be properly managed.
kOwnerWillDelete,
// The value has its own controller and will not be deleted on destruction.
// This should only be used for global values or scope-limited values that
// will be explicitly detached.
kOwnerNoDelete,
};
// Create a new object.
// If |read_only| is true mutable access will not be allowed.
// If |parent_value| is non-NULL and the value mode is kReference a dependency
// will be added.
CefValueBase(ValueType* value,
void* parent_value,
ValueMode value_mode,
bool read_only,
CefValueController* controller)
: value_(value),
value_mode_(value_mode),
read_only_(read_only),
controller_(controller) {
DCHECK(value_);
// Specifying a parent value for a non-reference doesn't make sense.
DCHECK(!(!reference() && parent_value));
if (!reference() && !controller_.get()) {
// For owned values default to using a new multi-threaded controller.
controller_ = new CefValueControllerThreadSafe();
SetOwnsController();
}
// A controller is required.
DCHECK(controller_.get());
if (reference()) {
// Register the reference with the controller.
controller_->AddReference(value_, this);
// Add a dependency on the parent value.
if (parent_value)
controller_->AddDependency(parent_value, value_);
}
}
~CefValueBase() override {
if (controller_.get() && value_)
Delete();
}
// True if the underlying value is referenced instead of owned.
inline bool reference() const { return (value_mode_ == kReference); }
// True if the underlying value will be deleted.
inline bool will_delete() const { return (value_mode_ == kOwnerWillDelete); }
// True if access to the underlying value is read-only.
inline bool read_only() const { return read_only_; }
// True if the underlying value has been detached.
inline bool detached() { return !controller_.get(); }
// Returns the controller.
inline CefValueController* controller() { return controller_.get(); }
// Deletes the underlying value.
void Delete() {
CEF_VALUE_VERIFY_RETURN_VOID(false);
// Remove the object from the controller. If this is the owner object any
// references will be detached.
controller()->Remove(value_, false);
if (will_delete()) {
// Remove any dependencies.
controller()->RemoveDependencies(value_);
// Delete the value.
DeleteValue(value_);
}
controller_ = NULL;
value_ = NULL;
}
// Detaches the underlying value and returns a pointer to it. If this is an
// owner and a |new_controller| value is specified any existing references
// will be passed to the new controller.
ValueType* Detach(CefValueController* new_controller) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
// A |new_controller| value is required for mode kOwnerWillDelete.
DCHECK(!will_delete() || new_controller);
if (new_controller && !reference()) {
// Pass any existing references and dependencies to the new controller.
// They will be removed from this controller.
new_controller->TakeFrom(controller());
}
// Remove the object from the controller. If this is the owner object any
// references will be detached.
controller()->Remove(value_, false);
controller_ = NULL;
// Return the old value.
ValueType* old_val = value_;
value_ = NULL;
return old_val;
}
// Verify that the value is attached.
inline bool VerifyAttached() {
if (detached()) {
// This object should not be accessed after being detached.
NOTREACHED() << "object accessed after being detached.";
return false;
}
return true;
}
protected:
// CefValueController::Object methods.
void OnControlRemoved() override {
DCHECK(controller()->locked());
// Only references should be removed in this manner.
DCHECK(reference());
controller_ = NULL;
value_ = NULL;
}
// Override to customize value deletion.
virtual void DeleteValue(ValueType* value) { delete value; }
// Returns a mutable reference to the value.
inline ValueType* mutable_value() {
DCHECK(value_);
DCHECK(!read_only_);
DCHECK(controller()->locked());
return value_;
}
// Returns a const reference to the value.
inline const ValueType& const_value() {
DCHECK(value_);
DCHECK(controller()->locked());
return *value_;
}
// Verify that the value can be accessed.
inline bool VerifyAccess(bool modify) {
// The controller must already be locked.
DCHECK(controller()->locked());
if (read_only() && modify) {
// This object cannot be modified.
NOTREACHED() << "mutation attempted on read-only object.";
return false;
}
return true;
}
// Used to indicate that this object owns the controller.
inline void SetOwnsController() {
CefValueController::AutoLock lock_scope(controller_.get());
if (lock_scope.verified())
controller_->SetOwner(value_, this);
}
// Encapsulates value locking and verification logic.
class AutoLock {
public:
explicit AutoLock(CefValueBase* impl, bool modify)
: auto_lock_(impl->controller()) {
verified_ = (auto_lock_.verified() && impl->VerifyAccess(modify));
}
inline bool verified() { return verified_; }
private:
CefValueController::AutoLock auto_lock_;
bool verified_;
DISALLOW_COPY_AND_ASSIGN(AutoLock);
};
private:
ValueType* value_;
ValueMode value_mode_;
bool read_only_;
scoped_refptr<CefValueController> controller_;
IMPLEMENT_REFCOUNTING(CefValueBase);
DISALLOW_COPY_AND_ASSIGN(CefValueBase);
};
#endif // CEF_LIBCEF_COMMON_VALUE_BASE_H_

View File

@@ -0,0 +1,839 @@
// 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/common/values_impl.h"
#include <algorithm>
#include <vector>
// CefBinaryValueImpl implementation.
CefRefPtr<CefBinaryValue> CefBinaryValue::Create(const void* data,
size_t data_size) {
DCHECK(data);
DCHECK_GT(data_size, (size_t)0);
if (!data || data_size == 0)
return NULL;
return new CefBinaryValueImpl(static_cast<char*>(const_cast<void*>(data)),
data_size, true);
}
// static
CefRefPtr<CefBinaryValue> CefBinaryValueImpl::GetOrCreateRef(
base::BinaryValue* value,
void* parent_value,
CefValueController* controller) {
DCHECK(value);
DCHECK(parent_value);
DCHECK(controller);
CefValueController::Object* object = controller->Get(value);
if (object)
return static_cast<CefBinaryValueImpl*>(object);
return new CefBinaryValueImpl(value, parent_value,
CefBinaryValueImpl::kReference, controller);
}
CefBinaryValueImpl::CefBinaryValueImpl(base::BinaryValue* value,
bool will_delete,
bool read_only)
: CefValueBase<CefBinaryValue, base::BinaryValue>(
value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete,
read_only, NULL) {
}
base::BinaryValue* CefBinaryValueImpl::CopyValue() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return const_value().DeepCopy();
}
base::BinaryValue* CefBinaryValueImpl::CopyOrDetachValue(
CefValueController* new_controller) {
base::BinaryValue* new_value;
if (!will_delete()) {
// Copy the value.
new_value = CopyValue();
} else {
// Take ownership of the value.
new_value = Detach(new_controller);
}
DCHECK(new_value);
return new_value;
}
bool CefBinaryValueImpl::IsValid() {
return !detached();
}
bool CefBinaryValueImpl::IsOwned() {
return !will_delete();
}
CefRefPtr<CefBinaryValue> CefBinaryValueImpl::Copy() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return new CefBinaryValueImpl(const_value().DeepCopy(), NULL,
CefBinaryValueImpl::kOwnerWillDelete, NULL);
}
size_t CefBinaryValueImpl::GetSize() {
CEF_VALUE_VERIFY_RETURN(false, 0);
return const_value().GetSize();
}
size_t CefBinaryValueImpl::GetData(void* buffer,
size_t buffer_size,
size_t data_offset) {
DCHECK(buffer);
DCHECK_GT(buffer_size, (size_t)0);
if (!buffer || buffer_size == 0)
return 0;
CEF_VALUE_VERIFY_RETURN(false, 0);
size_t size = const_value().GetSize();
DCHECK_LT(data_offset, size);
if (data_offset >= size)
return 0;
size = std::min(buffer_size, size-data_offset);
const char* data = const_value().GetBuffer();
memcpy(buffer, data+data_offset, size);
return size;
}
CefBinaryValueImpl::CefBinaryValueImpl(base::BinaryValue* value,
void* parent_value,
ValueMode value_mode,
CefValueController* controller)
: CefValueBase<CefBinaryValue, base::BinaryValue>(
value, parent_value, value_mode, true, controller) {
}
CefBinaryValueImpl::CefBinaryValueImpl(char* data,
size_t data_size,
bool copy)
: CefValueBase<CefBinaryValue, base::BinaryValue>(
copy ? base::BinaryValue::CreateWithCopiedBuffer(data, data_size) :
new base::BinaryValue(scoped_ptr<char[]>(data), data_size),
NULL, kOwnerWillDelete, true, NULL) {
}
// CefDictionaryValueImpl implementation.
// static
CefRefPtr<CefDictionaryValue> CefDictionaryValue::Create() {
return new CefDictionaryValueImpl(new base::DictionaryValue(),
NULL, CefDictionaryValueImpl::kOwnerWillDelete, false, NULL);
}
// static
CefRefPtr<CefDictionaryValue> CefDictionaryValueImpl::GetOrCreateRef(
base::DictionaryValue* value,
void* parent_value,
bool read_only,
CefValueController* controller) {
CefValueController::Object* object = controller->Get(value);
if (object)
return static_cast<CefDictionaryValueImpl*>(object);
return new CefDictionaryValueImpl(value, parent_value,
CefDictionaryValueImpl::kReference, read_only, controller);
}
CefDictionaryValueImpl::CefDictionaryValueImpl(base::DictionaryValue* value,
bool will_delete,
bool read_only)
: CefValueBase<CefDictionaryValue, base::DictionaryValue>(
value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete,
read_only, NULL) {
}
base::DictionaryValue* CefDictionaryValueImpl::CopyValue() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return const_value().DeepCopy();
}
base::DictionaryValue* CefDictionaryValueImpl::CopyOrDetachValue(
CefValueController* new_controller) {
base::DictionaryValue* new_value;
if (!will_delete()) {
// Copy the value.
new_value = CopyValue();
} else {
// Take ownership of the value.
new_value = Detach(new_controller);
}
DCHECK(new_value);
return new_value;
}
bool CefDictionaryValueImpl::IsValid() {
return !detached();
}
bool CefDictionaryValueImpl::IsOwned() {
return !will_delete();
}
bool CefDictionaryValueImpl::IsReadOnly() {
return read_only();
}
CefRefPtr<CefDictionaryValue> CefDictionaryValueImpl::Copy(
bool exclude_empty_children) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
base::DictionaryValue* value;
if (exclude_empty_children) {
value = const_cast<base::DictionaryValue&>(
const_value()).DeepCopyWithoutEmptyChildren();
} else {
value = const_value().DeepCopy();
}
return new CefDictionaryValueImpl(value, NULL,
CefDictionaryValueImpl::kOwnerWillDelete, false, NULL);
}
size_t CefDictionaryValueImpl::GetSize() {
CEF_VALUE_VERIFY_RETURN(false, 0);
return const_value().size();
}
bool CefDictionaryValueImpl::Clear() {
CEF_VALUE_VERIFY_RETURN(true, false);
// Detach any dependent values.
controller()->RemoveDependencies(mutable_value());
mutable_value()->Clear();
return true;
}
bool CefDictionaryValueImpl::HasKey(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, 0);
return const_value().HasKey(key);
}
bool CefDictionaryValueImpl::GetKeys(KeyList& keys) {
CEF_VALUE_VERIFY_RETURN(false, 0);
for (base::DictionaryValue::Iterator i(const_value());
!i.IsAtEnd(); i.Advance()) {
keys.push_back(i.key());
}
return true;
}
bool CefDictionaryValueImpl::Remove(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(true, false);
return RemoveInternal(key);
}
CefValueType CefDictionaryValueImpl::GetType(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, VTYPE_INVALID);
const base::Value* out_value = NULL;
if (const_value().GetWithoutPathExpansion(key, &out_value)) {
switch (out_value->GetType()) {
case base::Value::TYPE_NULL:
return VTYPE_NULL;
case base::Value::TYPE_BOOLEAN:
return VTYPE_BOOL;
case base::Value::TYPE_INTEGER:
return VTYPE_INT;
case base::Value::TYPE_DOUBLE:
return VTYPE_DOUBLE;
case base::Value::TYPE_STRING:
return VTYPE_STRING;
case base::Value::TYPE_BINARY:
return VTYPE_BINARY;
case base::Value::TYPE_DICTIONARY:
return VTYPE_DICTIONARY;
case base::Value::TYPE_LIST:
return VTYPE_LIST;
}
}
return VTYPE_INVALID;
}
bool CefDictionaryValueImpl::GetBool(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, false);
const base::Value* out_value = NULL;
bool ret_value = false;
if (const_value().GetWithoutPathExpansion(key, &out_value))
out_value->GetAsBoolean(&ret_value);
return ret_value;
}
int CefDictionaryValueImpl::GetInt(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, 0);
const base::Value* out_value = NULL;
int ret_value = 0;
if (const_value().GetWithoutPathExpansion(key, &out_value))
out_value->GetAsInteger(&ret_value);
return ret_value;
}
double CefDictionaryValueImpl::GetDouble(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, 0);
const base::Value* out_value = NULL;
double ret_value = 0;
if (const_value().GetWithoutPathExpansion(key, &out_value))
out_value->GetAsDouble(&ret_value);
return ret_value;
}
CefString CefDictionaryValueImpl::GetString(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, CefString());
const base::Value* out_value = NULL;
std::string ret_value;
if (const_value().GetWithoutPathExpansion(key, &out_value))
out_value->GetAsString(&ret_value);
return ret_value;
}
CefRefPtr<CefBinaryValue> CefDictionaryValueImpl::GetBinary(
const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
const base::Value* out_value = NULL;
if (const_value().GetWithoutPathExpansion(key, &out_value) &&
out_value->IsType(base::Value::TYPE_BINARY)) {
base::BinaryValue* binary_value =
static_cast<base::BinaryValue*>(const_cast<base::Value*>(out_value));
return CefBinaryValueImpl::GetOrCreateRef(binary_value,
const_cast<base::DictionaryValue*>(&const_value()), controller());
}
return NULL;
}
CefRefPtr<CefDictionaryValue> CefDictionaryValueImpl::GetDictionary(
const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
const base::Value* out_value = NULL;
if (const_value().GetWithoutPathExpansion(key, &out_value) &&
out_value->IsType(base::Value::TYPE_DICTIONARY)) {
base::DictionaryValue* dict_value =
static_cast<base::DictionaryValue*>(
const_cast<base::Value*>(out_value));
return CefDictionaryValueImpl::GetOrCreateRef(
dict_value,
const_cast<base::DictionaryValue*>(&const_value()),
read_only(),
controller());
}
return NULL;
}
CefRefPtr<CefListValue> CefDictionaryValueImpl::GetList(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
const base::Value* out_value = NULL;
if (const_value().GetWithoutPathExpansion(key, &out_value) &&
out_value->IsType(base::Value::TYPE_LIST)) {
base::ListValue* list_value =
static_cast<base::ListValue*>(const_cast<base::Value*>(out_value));
return CefListValueImpl::GetOrCreateRef(
list_value,
const_cast<base::DictionaryValue*>(&const_value()),
read_only(),
controller());
}
return NULL;
}
bool CefDictionaryValueImpl::SetNull(const CefString& key) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
mutable_value()->SetWithoutPathExpansion(key, base::Value::CreateNullValue());
return true;
}
bool CefDictionaryValueImpl::SetBool(const CefString& key, bool value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
mutable_value()->SetWithoutPathExpansion(key,
new base::FundamentalValue(value));
return true;
}
bool CefDictionaryValueImpl::SetInt(const CefString& key, int value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
mutable_value()->SetWithoutPathExpansion(key,
new base::FundamentalValue(value));
return true;
}
bool CefDictionaryValueImpl::SetDouble(const CefString& key, double value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
mutable_value()->SetWithoutPathExpansion(key,
new base::FundamentalValue(value));
return true;
}
bool CefDictionaryValueImpl::SetString(const CefString& key,
const CefString& value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
mutable_value()->SetWithoutPathExpansion(key,
new base::StringValue(value.ToString()));
return true;
}
bool CefDictionaryValueImpl::SetBinary(const CefString& key,
CefRefPtr<CefBinaryValue> value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
CefBinaryValueImpl* impl = static_cast<CefBinaryValueImpl*>(value.get());
DCHECK(impl);
mutable_value()->SetWithoutPathExpansion(key,
impl->CopyOrDetachValue(controller()));
return true;
}
bool CefDictionaryValueImpl::SetDictionary(
const CefString& key, CefRefPtr<CefDictionaryValue> value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
CefDictionaryValueImpl* impl =
static_cast<CefDictionaryValueImpl*>(value.get());
DCHECK(impl);
mutable_value()->SetWithoutPathExpansion(key,
impl->CopyOrDetachValue(controller()));
return true;
}
bool CefDictionaryValueImpl::SetList(const CefString& key,
CefRefPtr<CefListValue> value) {
CEF_VALUE_VERIFY_RETURN(true, false);
RemoveInternal(key);
CefListValueImpl* impl = static_cast<CefListValueImpl*>(value.get());
DCHECK(impl);
mutable_value()->SetWithoutPathExpansion(key,
impl->CopyOrDetachValue(controller()));
return true;
}
bool CefDictionaryValueImpl::RemoveInternal(const CefString& key) {
scoped_ptr<base::Value> out_value;
if (!mutable_value()->RemoveWithoutPathExpansion(key, &out_value))
return false;
// Remove the value.
controller()->Remove(out_value.get(), true);
// Only list and dictionary types may have dependencies.
if (out_value->IsType(base::Value::TYPE_LIST) ||
out_value->IsType(base::Value::TYPE_DICTIONARY)) {
controller()->RemoveDependencies(out_value.get());
}
return true;
}
CefDictionaryValueImpl::CefDictionaryValueImpl(
base::DictionaryValue* value,
void* parent_value,
ValueMode value_mode,
bool read_only,
CefValueController* controller)
: CefValueBase<CefDictionaryValue, base::DictionaryValue>(
value, parent_value, value_mode, read_only, controller) {
}
// CefListValueImpl implementation.
// static
CefRefPtr<CefListValue> CefListValue::Create() {
return new CefListValueImpl(new base::ListValue(),
NULL, CefListValueImpl::kOwnerWillDelete, false, NULL);
}
// static
CefRefPtr<CefListValue> CefListValueImpl::GetOrCreateRef(
base::ListValue* value,
void* parent_value,
bool read_only,
CefValueController* controller) {
CefValueController::Object* object = controller->Get(value);
if (object)
return static_cast<CefListValueImpl*>(object);
return new CefListValueImpl(value, parent_value,
CefListValueImpl::kReference, read_only, controller);
}
CefListValueImpl::CefListValueImpl(base::ListValue* value,
bool will_delete,
bool read_only)
: CefValueBase<CefListValue, base::ListValue>(
value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete,
read_only, NULL) {
}
base::ListValue* CefListValueImpl::CopyValue() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return const_value().DeepCopy();
}
base::ListValue* CefListValueImpl::CopyOrDetachValue(
CefValueController* new_controller) {
base::ListValue* new_value;
if (!will_delete()) {
// Copy the value.
new_value = CopyValue();
} else {
// Take ownership of the value.
new_value = Detach(new_controller);
}
DCHECK(new_value);
return new_value;
}
bool CefListValueImpl::IsValid() {
return !detached();
}
bool CefListValueImpl::IsOwned() {
return !will_delete();
}
bool CefListValueImpl::IsReadOnly() {
return read_only();
}
CefRefPtr<CefListValue> CefListValueImpl::Copy() {
CEF_VALUE_VERIFY_RETURN(false, NULL);
return new CefListValueImpl(const_value().DeepCopy(), NULL,
CefListValueImpl::kOwnerWillDelete, false, NULL);
}
bool CefListValueImpl::SetSize(size_t size) {
CEF_VALUE_VERIFY_RETURN(true, false);
size_t current_size = const_value().GetSize();
if (size < current_size) {
// Clean up any values above the requested size.
for (size_t i = current_size-1; i >= size; --i)
RemoveInternal(i);
} else if (size > 0) {
// Expand the list size.
mutable_value()->Set(size-1, base::Value::CreateNullValue());
}
return true;
}
size_t CefListValueImpl::GetSize() {
CEF_VALUE_VERIFY_RETURN(false, 0);
return const_value().GetSize();
}
bool CefListValueImpl::Clear() {
CEF_VALUE_VERIFY_RETURN(true, false);
// Detach any dependent values.
controller()->RemoveDependencies(mutable_value());
mutable_value()->Clear();
return true;
}
bool CefListValueImpl::Remove(int index) {
CEF_VALUE_VERIFY_RETURN(true, false);
return RemoveInternal(index);
}
CefValueType CefListValueImpl::GetType(int index) {
CEF_VALUE_VERIFY_RETURN(false, VTYPE_INVALID);
const base::Value* out_value = NULL;
if (const_value().Get(index, &out_value)) {
switch (out_value->GetType()) {
case base::Value::TYPE_NULL:
return VTYPE_NULL;
case base::Value::TYPE_BOOLEAN:
return VTYPE_BOOL;
case base::Value::TYPE_INTEGER:
return VTYPE_INT;
case base::Value::TYPE_DOUBLE:
return VTYPE_DOUBLE;
case base::Value::TYPE_STRING:
return VTYPE_STRING;
case base::Value::TYPE_BINARY:
return VTYPE_BINARY;
case base::Value::TYPE_DICTIONARY:
return VTYPE_DICTIONARY;
case base::Value::TYPE_LIST:
return VTYPE_LIST;
}
}
return VTYPE_INVALID;
}
bool CefListValueImpl::GetBool(int index) {
CEF_VALUE_VERIFY_RETURN(false, false);
const base::Value* out_value = NULL;
bool ret_value = false;
if (const_value().Get(index, &out_value))
out_value->GetAsBoolean(&ret_value);
return ret_value;
}
int CefListValueImpl::GetInt(int index) {
CEF_VALUE_VERIFY_RETURN(false, 0);
const base::Value* out_value = NULL;
int ret_value = 0;
if (const_value().Get(index, &out_value))
out_value->GetAsInteger(&ret_value);
return ret_value;
}
double CefListValueImpl::GetDouble(int index) {
CEF_VALUE_VERIFY_RETURN(false, 0);
const base::Value* out_value = NULL;
double ret_value = 0;
if (const_value().Get(index, &out_value))
out_value->GetAsDouble(&ret_value);
return ret_value;
}
CefString CefListValueImpl::GetString(int index) {
CEF_VALUE_VERIFY_RETURN(false, CefString());
const base::Value* out_value = NULL;
std::string ret_value;
if (const_value().Get(index, &out_value))
out_value->GetAsString(&ret_value);
return ret_value;
}
CefRefPtr<CefBinaryValue> CefListValueImpl::GetBinary(int index) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
const base::Value* out_value = NULL;
if (const_value().Get(index, &out_value) &&
out_value->IsType(base::Value::TYPE_BINARY)) {
base::BinaryValue* binary_value =
static_cast<base::BinaryValue*>(const_cast<base::Value*>(out_value));
return CefBinaryValueImpl::GetOrCreateRef(binary_value,
const_cast<base::ListValue*>(&const_value()), controller());
}
return NULL;
}
CefRefPtr<CefDictionaryValue> CefListValueImpl::GetDictionary(int index) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
const base::Value* out_value = NULL;
if (const_value().Get(index, &out_value) &&
out_value->IsType(base::Value::TYPE_DICTIONARY)) {
base::DictionaryValue* dict_value =
static_cast<base::DictionaryValue*>(
const_cast<base::Value*>(out_value));
return CefDictionaryValueImpl::GetOrCreateRef(
dict_value,
const_cast<base::ListValue*>(&const_value()),
read_only(),
controller());
}
return NULL;
}
CefRefPtr<CefListValue> CefListValueImpl::GetList(int index) {
CEF_VALUE_VERIFY_RETURN(false, NULL);
const base::Value* out_value = NULL;
if (const_value().Get(index, &out_value) &&
out_value->IsType(base::Value::TYPE_LIST)) {
base::ListValue* list_value =
static_cast<base::ListValue*>(const_cast<base::Value*>(out_value));
return CefListValueImpl::GetOrCreateRef(
list_value,
const_cast<base::ListValue*>(&const_value()),
read_only(),
controller());
}
return NULL;
}
bool CefListValueImpl::SetNull(int index) {
CEF_VALUE_VERIFY_RETURN(true, false);
base::Value* new_value = base::Value::CreateNullValue();
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetBool(int index, bool value) {
CEF_VALUE_VERIFY_RETURN(true, false);
base::Value* new_value = new base::FundamentalValue(value);
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetInt(int index, int value) {
CEF_VALUE_VERIFY_RETURN(true, false);
base::Value* new_value = new base::FundamentalValue(value);
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetDouble(int index, double value) {
CEF_VALUE_VERIFY_RETURN(true, false);
base::Value* new_value = new base::FundamentalValue(value);
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetString(int index, const CefString& value) {
CEF_VALUE_VERIFY_RETURN(true, false);
base::Value* new_value = new base::StringValue(value.ToString());
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetBinary(int index, CefRefPtr<CefBinaryValue> value) {
CEF_VALUE_VERIFY_RETURN(true, false);
CefBinaryValueImpl* impl = static_cast<CefBinaryValueImpl*>(value.get());
DCHECK(impl);
base::Value* new_value = impl->CopyOrDetachValue(controller());
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetDictionary(int index,
CefRefPtr<CefDictionaryValue> value) {
CEF_VALUE_VERIFY_RETURN(true, false);
CefDictionaryValueImpl* impl =
static_cast<CefDictionaryValueImpl*>(value.get());
DCHECK(impl);
base::Value* new_value = impl->CopyOrDetachValue(controller());
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::SetList(int index, CefRefPtr<CefListValue> value) {
CEF_VALUE_VERIFY_RETURN(true, false);
CefListValueImpl* impl = static_cast<CefListValueImpl*>(value.get());
DCHECK(impl);
base::Value* new_value = impl->CopyOrDetachValue(controller());
if (RemoveInternal(index))
mutable_value()->Insert(index, new_value);
else
mutable_value()->Set(index, new_value);
return true;
}
bool CefListValueImpl::RemoveInternal(int index) {
scoped_ptr<base::Value> out_value;
if (!mutable_value()->Remove(index, &out_value))
return false;
// Remove the value.
controller()->Remove(out_value.get(), true);
// Only list and dictionary types may have dependencies.
if (out_value->IsType(base::Value::TYPE_LIST) ||
out_value->IsType(base::Value::TYPE_DICTIONARY)) {
controller()->RemoveDependencies(out_value.get());
}
return true;
}
CefListValueImpl::CefListValueImpl(
base::ListValue* value,
void* parent_value,
ValueMode value_mode,
bool read_only,
CefValueController* controller)
: CefValueBase<CefListValue, base::ListValue>(
value, parent_value, value_mode, read_only, controller) {
}

209
libcef/common/values_impl.h Normal file
View File

@@ -0,0 +1,209 @@
// 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_COMMON_VALUES_IMPL_H_
#define CEF_LIBCEF_COMMON_VALUES_IMPL_H_
#pragma once
#include <vector>
#include "include/cef_values.h"
#include "libcef/common/value_base.h"
#include "base/values.h"
#include "base/threading/platform_thread.h"
// CefBinaryValue implementation
class CefBinaryValueImpl
: public CefValueBase<CefBinaryValue, base::BinaryValue> {
public:
// Get or create a reference value.
static CefRefPtr<CefBinaryValue> GetOrCreateRef(
base::BinaryValue* value,
void* parent_value,
CefValueController* controller);
// Simple constructor for referencing existing value objects.
CefBinaryValueImpl(base::BinaryValue* value,
bool will_delete,
bool read_only);
// Return a copy of the value.
base::BinaryValue* CopyValue();
// If a reference return a copy of the value otherwise detach the value to the
// specified |new_controller|.
base::BinaryValue* CopyOrDetachValue(CefValueController* new_controller);
// CefBinaryValue methods.
bool IsValid() override;
bool IsOwned() override;
CefRefPtr<CefBinaryValue> Copy() override;
size_t GetSize() override;
size_t GetData(void* buffer,
size_t buffer_size,
size_t data_offset) override;
private:
// See the CefValueBase constructor for usage. Binary values are always
// read-only.
CefBinaryValueImpl(base::BinaryValue* value,
void* parent_value,
ValueMode value_mode,
CefValueController* controller);
// If |copy| is false this object will take ownership of the specified |data|
// buffer instead of copying it.
CefBinaryValueImpl(char* data,
size_t data_size,
bool copy);
// For the Create() method.
friend class CefBinaryValue;
DISALLOW_COPY_AND_ASSIGN(CefBinaryValueImpl);
};
// CefDictionaryValue implementation
class CefDictionaryValueImpl
: public CefValueBase<CefDictionaryValue, base::DictionaryValue> {
public:
// Get or create a reference value.
static CefRefPtr<CefDictionaryValue> GetOrCreateRef(
base::DictionaryValue* value,
void* parent_value,
bool read_only,
CefValueController* controller);
// Simple constructor for referencing existing value objects.
CefDictionaryValueImpl(base::DictionaryValue* value,
bool will_delete,
bool read_only);
// Return a copy of the value.
base::DictionaryValue* CopyValue();
// If a reference return a copy of the value otherwise detach the value to the
// specified |new_controller|.
base::DictionaryValue* CopyOrDetachValue(CefValueController* new_controller);
// CefDictionaryValue methods.
bool IsValid() override;
bool IsOwned() override;
bool IsReadOnly() override;
CefRefPtr<CefDictionaryValue> Copy(
bool exclude_empty_children) override;
size_t GetSize() override;
bool Clear() override;
bool HasKey(const CefString& key) override;
bool GetKeys(KeyList& keys) override;
bool Remove(const CefString& key) override;
CefValueType GetType(const CefString& key) override;
bool GetBool(const CefString& key) override;
int GetInt(const CefString& key) override;
double GetDouble(const CefString& key) override;
CefString GetString(const CefString& key) override;
CefRefPtr<CefBinaryValue> GetBinary(const CefString& key) override;
CefRefPtr<CefDictionaryValue> GetDictionary(
const CefString& key) override;
CefRefPtr<CefListValue> GetList(const CefString& key) override;
bool SetNull(const CefString& key) override;
bool SetBool(const CefString& key, bool value) override;
bool SetInt(const CefString& key, int value) override;
bool SetDouble(const CefString& key, double value) override;
bool SetString(const CefString& key,
const CefString& value) override;
bool SetBinary(const CefString& key,
CefRefPtr<CefBinaryValue> value) override;
bool SetDictionary(const CefString& key,
CefRefPtr<CefDictionaryValue> value) override;
bool SetList(const CefString& key,
CefRefPtr<CefListValue> value) override;
private:
// See the CefValueBase constructor for usage.
CefDictionaryValueImpl(base::DictionaryValue* value,
void* parent_value,
ValueMode value_mode,
bool read_only,
CefValueController* controller);
bool RemoveInternal(const CefString& key);
// For the Create() method.
friend class CefDictionaryValue;
DISALLOW_COPY_AND_ASSIGN(CefDictionaryValueImpl);
};
// CefListValue implementation
class CefListValueImpl
: public CefValueBase<CefListValue, base::ListValue> {
public:
// Get or create a reference value.
static CefRefPtr<CefListValue> GetOrCreateRef(
base::ListValue* value,
void* parent_value,
bool read_only,
CefValueController* controller);
// Simple constructor for referencing existing value objects.
CefListValueImpl(base::ListValue* value,
bool will_delete,
bool read_only);
// Return a copy of the value.
base::ListValue* CopyValue();
// If a reference return a copy of the value otherwise detach the value to the
// specified |new_controller|.
base::ListValue* CopyOrDetachValue(CefValueController* new_controller);
/// CefListValue methods.
bool IsValid() override;
bool IsOwned() override;
bool IsReadOnly() override;
CefRefPtr<CefListValue> Copy() override;
bool SetSize(size_t size) override;
size_t GetSize() override;
bool Clear() override;
bool Remove(int index) override;
CefValueType GetType(int index) override;
bool GetBool(int index) override;
int GetInt(int index) override;
double GetDouble(int index) override;
CefString GetString(int index) override;
CefRefPtr<CefBinaryValue> GetBinary(int index) override;
CefRefPtr<CefDictionaryValue> GetDictionary(int index) override;
CefRefPtr<CefListValue> GetList(int index) override;
bool SetNull(int index) override;
bool SetBool(int index, bool value) override;
bool SetInt(int index, int value) override;
bool SetDouble(int index, double value) override;
bool SetString(int index, const CefString& value) override;
bool SetBinary(int index, CefRefPtr<CefBinaryValue> value) override;
bool SetDictionary(int index,
CefRefPtr<CefDictionaryValue> value) override;
bool SetList(int index, CefRefPtr<CefListValue> value) override;
private:
// See the CefValueBase constructor for usage.
CefListValueImpl(base::ListValue* value,
void* parent_value,
ValueMode value_mode,
bool read_only,
CefValueController* controller);
bool RemoveInternal(int index);
// For the Create() method.
friend class CefListValue;
DISALLOW_COPY_AND_ASSIGN(CefListValueImpl);
};
#endif // CEF_LIBCEF_COMMON_VALUES_IMPL_H_