Rename CEF1 files from /trunk to /trunk/cef1 (issue #564).

git-svn-id: https://chromiumembedded.googlecode.com/svn/trunk@570 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
This commit is contained in:
Marshall Greenblatt
2012-04-03 01:27:13 +00:00
parent 0a1fd8b040
commit b568f160d9
651 changed files with 6 additions and 7 deletions

View File

@@ -1,185 +0,0 @@
// 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 "cefclient/binding_test.h"
#include <sstream>
#include <string>
#include <vector>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_v8.h"
// Implementation of the V8 handler class for the "window.cef_test.Dump"
// function.
class ClientV8FunctionHandler : public CefV8Handler {
public:
ClientV8FunctionHandler() {}
virtual ~ClientV8FunctionHandler() {}
// Execute with the specified argument list and return value. Return true if
// the method was handled.
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) OVERRIDE {
if (name == "Dump") {
// The "Dump" function will return a human-readable dump of the input
// arguments.
std::stringstream stream;
size_t i;
for (i = 0; i < arguments.size(); ++i) {
stream << "arg[" << i << "] = ";
PrintValue(arguments[i], stream, 0);
stream << "\n";
}
retval = CefV8Value::CreateString(stream.str());
return true;
} else if (name == "Call") {
// The "Call" function will execute a function to get an object and then
// return the result of calling a function belonging to that object. The
// first arument is the function that will return an object and the second
// argument is the function that will be called on that returned object.
int argSize = arguments.size();
if (argSize < 2 || !arguments[0]->IsFunction()
|| !arguments[1]->IsString())
return false;
CefV8ValueList argList;
bool result;
// Execute the function stored in the first argument to retrieve an
// object.
CefRefPtr<CefV8Value> objectPtr;
CefRefPtr<CefV8Exception> exceptionPtr;
result = arguments[0]->ExecuteFunction(object, argList, objectPtr,
exceptionPtr, false);
if (exceptionPtr.get())
exception = exceptionPtr->GetMessage();
if (!result)
return false;
// Verify that the returned value is an object.
if (!objectPtr.get() || !objectPtr->IsObject())
return false;
// Retrieve the member function specified by name in the second argument
// from the object.
CefRefPtr<CefV8Value> funcPtr =
objectPtr->GetValue(arguments[1]->GetStringValue());
// Verify that the returned value is a function.
if (!funcPtr.get() || !funcPtr->IsFunction())
return false;
// Pass any additional arguments on to the member function.
for (int i = 2; i < argSize; ++i)
argList.push_back(arguments[i]);
// Execute the member function.
result = funcPtr->ExecuteFunction(arguments[0], argList, retval,
exceptionPtr, false);
if (exceptionPtr.get())
exception = exceptionPtr->GetMessage();
return result;
}
return false;
}
// Simple function for formatted output of a V8 value.
void PrintValue(CefRefPtr<CefV8Value> value, std::stringstream &stream,
int indent) {
std::stringstream indent_stream;
for (int i = 0; i < indent; ++i)
indent_stream << " ";
std::string indent_str = indent_stream.str();
if (value->IsUndefined())
stream << "(undefined)";
else if (value->IsNull())
stream << "(null)";
else if (value->IsBool())
stream << "(bool) " << (value->GetBoolValue() ? "true" : "false");
else if (value->IsInt())
stream << "(int) " << value->GetIntValue();
else if (value->IsDouble())
stream << "(double) " << value->GetDoubleValue();
else if (value->IsString())
stream << "(string) " << std::string(value->GetStringValue());
else if (value->IsFunction())
stream << "(function) " << std::string(value->GetFunctionName());
else if (value->IsArray()) {
stream << "(array) [";
int len = value->GetArrayLength();
for (int i = 0; i < len; ++i) {
stream << "\n " << indent_str.c_str() << i << " = ";
PrintValue(value->GetValue(i), stream, indent+1);
}
stream << "\n" << indent_str.c_str() << "]";
} else if (value->IsObject()) {
stream << "(object) [";
std::vector<CefString> keys;
if (value->GetKeys(keys)) {
for (size_t i = 0; i < keys.size(); ++i) {
stream << "\n " << indent_str.c_str() << keys[i].c_str() << " = ";
PrintValue(value->GetValue(keys[i]), stream, indent+1);
}
}
stream << "\n" << indent_str.c_str() << "]";
}
}
IMPLEMENT_REFCOUNTING(ClientV8FunctionHandler);
};
void InitBindingTest(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Value> object) {
// Create the new V8 object.
CefRefPtr<CefV8Value> testObjPtr = CefV8Value::CreateObject(NULL, NULL);
// Add the new V8 object to the global window object with the name
// "cef_test".
object->SetValue("cef_test", testObjPtr, V8_PROPERTY_ATTRIBUTE_NONE);
// Create an instance of ClientV8FunctionHandler as the V8 handler.
CefRefPtr<CefV8Handler> handlerPtr = new ClientV8FunctionHandler();
// Add a new V8 function to the cef_test object with the name "Dump".
testObjPtr->SetValue("Dump",
CefV8Value::CreateFunction("Dump", handlerPtr),
V8_PROPERTY_ATTRIBUTE_NONE);
// Add a new V8 function to the cef_test object with the name "Call".
testObjPtr->SetValue("Call",
CefV8Value::CreateFunction("Call", handlerPtr),
V8_PROPERTY_ATTRIBUTE_NONE);
}
void RunBindingTest(CefRefPtr<CefBrowser> browser) {
std::string html =
"<html><body>ClientV8FunctionHandler says:<br><pre>"
"<script language=\"JavaScript\">"
"document.writeln(window.cef_test.Dump(false, 1, 7.6654,'bar',"
" [false,true],[5, 7.654, 1, 'foo', [true, 'bar'], 8]));"
"document.writeln(window.cef_test.Dump(cef));"
"document.writeln("
" window.cef_test.Call(cef.test.test_object, 'GetMessage'));"
"function my_object() {"
" var obj = {};"
" (function() {"
" obj.GetMessage = function(a) {"
" return 'Calling a function with value '+a+' on a user object "
"succeeded.';"
" };"
" })();"
" return obj;"
"};"
"document.writeln("
" window.cef_test.Call(my_object, 'GetMessage', 'foobar'));"
"</script>"
"</pre></body></html>";
browser->GetMainFrame()->LoadString(html, "about:blank");
}

View File

@@ -1,23 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_BINDING_TEST_H_
#define CEF_TESTS_CEFCLIENT_BINDING_TEST_H_
#pragma once
#include "include/cef_base.h"
class CefBrowser;
class CefFrame;
class CefV8Value;
// Add the V8 bindings.
void InitBindingTest(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Value> object);
// Run the test.
void RunBindingTest(CefRefPtr<CefBrowser> browser);
#endif // CEF_TESTS_CEFCLIENT_BINDING_TEST_H_

View File

@@ -1,603 +0,0 @@
// 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 "cefclient/cefclient.h"
#include <stdio.h>
#include <cstdlib>
#include <sstream>
#include <string>
#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_command_line.h"
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "include/cef_web_urlrequest.h"
#include "cefclient/cefclient_switches.h"
#include "cefclient/client_handler.h"
#include "cefclient/binding_test.h"
#include "cefclient/string_util.h"
#include "cefclient/util.h"
namespace {
void UIT_InvokeScript(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
CefRefPtr<CefFrame> frame = browser->GetMainFrame();
CefRefPtr<CefV8Context> v8Context = frame->GetV8Context();
CefString url = frame->GetURL();
if (!v8Context.get()) {
frame->ExecuteJavaScript("alert('Failed to get V8 context!');", url, 0);
} else if (v8Context->Enter()) {
CefRefPtr<CefV8Value> globalObj = v8Context->GetGlobal();
CefRefPtr<CefV8Value> evalFunc = globalObj->GetValue("eval");
CefRefPtr<CefV8Value> arg0 = CefV8Value::CreateString("1+2");
CefV8ValueList args;
args.push_back(arg0);
CefRefPtr<CefV8Value> retVal;
CefRefPtr<CefV8Exception> exception;
if (evalFunc->ExecuteFunctionWithContext(v8Context, globalObj, args, retVal,
exception, false)) {
if (retVal.get()) {
frame->ExecuteJavaScript(
std::string("alert('InvokeScript returns ") +
retVal->GetStringValue().ToString() + "!');",
url, 0);
} else {
frame->ExecuteJavaScript(
std::string("alert('InvokeScript returns exception: ") +
exception->GetMessage().ToString() + "!');",
url, 0);
}
} else {
frame->ExecuteJavaScript("alert('Failed to execute function!');", url, 0);
}
v8Context->Exit();
} else {
frame->ExecuteJavaScript("alert('Failed to enter into V8 context!');",
url, 0);
}
}
// Return the int representation of the specified string.
int GetIntValue(const CefString& str) {
if (str.empty())
return 0;
std::string stdStr = str;
return atoi(stdStr.c_str());
}
// ClientApp implementation.
class ClientApp : public CefApp,
public CefProxyHandler {
public:
ClientApp(cef_proxy_type_t proxy_type, const CefString& proxy_config)
: proxy_type_(proxy_type),
proxy_config_(proxy_config) {
}
// CefApp methods
virtual CefRefPtr<CefProxyHandler> GetProxyHandler() OVERRIDE { return this; }
// CefProxyHandler methods
virtual void GetProxyForUrl(const CefString& url,
CefProxyInfo& proxy_info) OVERRIDE {
proxy_info.proxyType = proxy_type_;
if (!proxy_config_.empty())
CefString(&proxy_info.proxyList) = proxy_config_;
}
protected:
cef_proxy_type_t proxy_type_;
CefString proxy_config_;
IMPLEMENT_REFCOUNTING(ClientApp);
};
} // namespace
CefRefPtr<ClientHandler> g_handler;
CefRefPtr<CefCommandLine> g_command_line;
CefRefPtr<CefBrowser> AppGetBrowser() {
if (!g_handler.get())
return NULL;
return g_handler->GetBrowser();
}
CefWindowHandle AppGetMainHwnd() {
if (!g_handler.get())
return NULL;
return g_handler->GetMainHwnd();
}
void AppInitCommandLine(int argc, const char* const* argv) {
g_command_line = CefCommandLine::CreateCommandLine();
#if defined(OS_WIN)
g_command_line->InitFromString(::GetCommandLineW());
#else
g_command_line->InitFromArgv(argc, argv);
#endif
}
// Returns the application command line object.
CefRefPtr<CefCommandLine> AppGetCommandLine() {
return g_command_line;
}
// Returns the application settings based on command line arguments.
void AppGetSettings(CefSettings& settings, CefRefPtr<CefApp>& app) {
ASSERT(g_command_line.get());
if (!g_command_line.get())
return;
CefString str;
#if defined(OS_WIN)
settings.multi_threaded_message_loop =
g_command_line->HasSwitch(cefclient::kMultiThreadedMessageLoop);
#endif
CefString(&settings.cache_path) =
g_command_line->GetSwitchValue(cefclient::kCachePath);
CefString(&settings.user_agent) =
g_command_line->GetSwitchValue(cefclient::kUserAgent);
CefString(&settings.product_version) =
g_command_line->GetSwitchValue(cefclient::kProductVersion);
CefString(&settings.locale) =
g_command_line->GetSwitchValue(cefclient::kLocale);
CefString(&settings.log_file) =
g_command_line->GetSwitchValue(cefclient::kLogFile);
{
std::string str = g_command_line->GetSwitchValue(cefclient::kLogSeverity);
bool invalid = false;
if (!str.empty()) {
if (str == cefclient::kLogSeverity_Verbose)
settings.log_severity = LOGSEVERITY_VERBOSE;
else if (str == cefclient::kLogSeverity_Info)
settings.log_severity = LOGSEVERITY_INFO;
else if (str == cefclient::kLogSeverity_Warning)
settings.log_severity = LOGSEVERITY_WARNING;
else if (str == cefclient::kLogSeverity_Error)
settings.log_severity = LOGSEVERITY_ERROR;
else if (str == cefclient::kLogSeverity_ErrorReport)
settings.log_severity = LOGSEVERITY_ERROR_REPORT;
else if (str == cefclient::kLogSeverity_Disable)
settings.log_severity = LOGSEVERITY_DISABLE;
else
invalid = true;
}
if (str.empty() || invalid) {
#ifdef NDEBUG
// Only log error messages and higher in release build.
settings.log_severity = LOGSEVERITY_ERROR;
#endif
}
}
{
std::string str = g_command_line->GetSwitchValue(cefclient::kGraphicsImpl);
if (!str.empty()) {
#if defined(OS_WIN)
if (str == cefclient::kGraphicsImpl_Angle)
settings.graphics_implementation = ANGLE_IN_PROCESS;
else if (str == cefclient::kGraphicsImpl_AngleCmdBuffer)
settings.graphics_implementation = ANGLE_IN_PROCESS_COMMAND_BUFFER;
else
#endif
if (str == cefclient::kGraphicsImpl_Desktop)
settings.graphics_implementation = DESKTOP_IN_PROCESS;
else if (str == cefclient::kGraphicsImpl_DesktopCmdBuffer)
settings.graphics_implementation = DESKTOP_IN_PROCESS_COMMAND_BUFFER;
}
}
settings.local_storage_quota = GetIntValue(
g_command_line->GetSwitchValue(cefclient::kLocalStorageQuota));
settings.session_storage_quota = GetIntValue(
g_command_line->GetSwitchValue(cefclient::kSessionStorageQuota));
CefString(&settings.javascript_flags) =
g_command_line->GetSwitchValue(cefclient::kJavascriptFlags);
CefString(&settings.pack_file_path) =
g_command_line->GetSwitchValue(cefclient::kPackFilePath);
CefString(&settings.locales_dir_path) =
g_command_line->GetSwitchValue(cefclient::kLocalesDirPath);
settings.pack_loading_disabled =
g_command_line->HasSwitch(cefclient::kPackLoadingDisabled);
// Retrieve command-line proxy configuration, if any.
bool has_proxy = false;
cef_proxy_type_t proxy_type = PROXY_TYPE_DIRECT;
CefString proxy_config;
if (g_command_line->HasSwitch(cefclient::kProxyType)) {
std::string str = g_command_line->GetSwitchValue(cefclient::kProxyType);
if (str == cefclient::kProxyType_Direct) {
has_proxy = true;
proxy_type = PROXY_TYPE_DIRECT;
} else if (str == cefclient::kProxyType_Named ||
str == cefclient::kProxyType_Pac) {
proxy_config = g_command_line->GetSwitchValue(cefclient::kProxyConfig);
if (!proxy_config.empty()) {
has_proxy = true;
proxy_type = (str == cefclient::kProxyType_Named?
PROXY_TYPE_NAMED:PROXY_TYPE_PAC_STRING);
}
}
}
if (has_proxy) {
// Provide a ClientApp instance to handle proxy resolution.
app = new ClientApp(proxy_type, proxy_config);
}
}
// Returns the application browser settings based on command line arguments.
void AppGetBrowserSettings(CefBrowserSettings& settings) {
ASSERT(g_command_line.get());
if (!g_command_line.get())
return;
settings.drag_drop_disabled =
g_command_line->HasSwitch(cefclient::kDragDropDisabled);
settings.load_drops_disabled =
g_command_line->HasSwitch(cefclient::kLoadDropsDisabled);
settings.history_disabled =
g_command_line->HasSwitch(cefclient::kHistoryDisabled);
settings.remote_fonts_disabled =
g_command_line->HasSwitch(cefclient::kRemoteFontsDisabled);
CefString(&settings.default_encoding) =
g_command_line->GetSwitchValue(cefclient::kDefaultEncoding);
settings.encoding_detector_enabled =
g_command_line->HasSwitch(cefclient::kEncodingDetectorEnabled);
settings.javascript_disabled =
g_command_line->HasSwitch(cefclient::kJavascriptDisabled);
settings.javascript_open_windows_disallowed =
g_command_line->HasSwitch(cefclient::kJavascriptOpenWindowsDisallowed);
settings.javascript_close_windows_disallowed =
g_command_line->HasSwitch(cefclient::kJavascriptCloseWindowsDisallowed);
settings.javascript_access_clipboard_disallowed =
g_command_line->HasSwitch(
cefclient::kJavascriptAccessClipboardDisallowed);
settings.dom_paste_disabled =
g_command_line->HasSwitch(cefclient::kDomPasteDisabled);
settings.caret_browsing_enabled =
g_command_line->HasSwitch(cefclient::kCaretBrowsingDisabled);
settings.java_disabled =
g_command_line->HasSwitch(cefclient::kJavaDisabled);
settings.plugins_disabled =
g_command_line->HasSwitch(cefclient::kPluginsDisabled);
settings.universal_access_from_file_urls_allowed =
g_command_line->HasSwitch(cefclient::kUniversalAccessFromFileUrlsAllowed);
settings.file_access_from_file_urls_allowed =
g_command_line->HasSwitch(cefclient::kFileAccessFromFileUrlsAllowed);
settings.web_security_disabled =
g_command_line->HasSwitch(cefclient::kWebSecurityDisabled);
settings.xss_auditor_enabled =
g_command_line->HasSwitch(cefclient::kXssAuditorEnabled);
settings.image_load_disabled =
g_command_line->HasSwitch(cefclient::kImageLoadingDisabled);
settings.shrink_standalone_images_to_fit =
g_command_line->HasSwitch(cefclient::kShrinkStandaloneImagesToFit);
settings.site_specific_quirks_disabled =
g_command_line->HasSwitch(cefclient::kSiteSpecificQuirksDisabled);
settings.text_area_resize_disabled =
g_command_line->HasSwitch(cefclient::kTextAreaResizeDisabled);
settings.page_cache_disabled =
g_command_line->HasSwitch(cefclient::kPageCacheDisabled);
settings.tab_to_links_disabled =
g_command_line->HasSwitch(cefclient::kTabToLinksDisabled);
settings.hyperlink_auditing_disabled =
g_command_line->HasSwitch(cefclient::kHyperlinkAuditingDisabled);
settings.user_style_sheet_enabled =
g_command_line->HasSwitch(cefclient::kUserStyleSheetEnabled);
CefString(&settings.user_style_sheet_location) =
g_command_line->GetSwitchValue(cefclient::kUserStyleSheetLocation);
settings.author_and_user_styles_disabled =
g_command_line->HasSwitch(cefclient::kAuthorAndUserStylesDisabled);
settings.local_storage_disabled =
g_command_line->HasSwitch(cefclient::kLocalStorageDisabled);
settings.databases_disabled =
g_command_line->HasSwitch(cefclient::kDatabasesDisabled);
settings.application_cache_disabled =
g_command_line->HasSwitch(cefclient::kApplicationCacheDisabled);
settings.webgl_disabled =
g_command_line->HasSwitch(cefclient::kWebglDisabled);
settings.accelerated_compositing_enabled =
g_command_line->HasSwitch(cefclient::kAcceleratedCompositingEnabled);
settings.threaded_compositing_enabled =
g_command_line->HasSwitch(cefclient::kThreadedCompositingEnabled);
settings.accelerated_layers_disabled =
g_command_line->HasSwitch(cefclient::kAcceleratedLayersDisabled);
settings.accelerated_video_disabled =
g_command_line->HasSwitch(cefclient::kAcceleratedVideoDisabled);
settings.accelerated_2d_canvas_disabled =
g_command_line->HasSwitch(cefclient::kAcceledated2dCanvasDisabled);
settings.accelerated_painting_disabled =
g_command_line->HasSwitch(cefclient::kAcceleratedPaintingDisabled);
settings.accelerated_filters_disabled =
g_command_line->HasSwitch(cefclient::kAcceleratedFiltersDisabled);
settings.accelerated_plugins_disabled =
g_command_line->HasSwitch(cefclient::kAcceleratedPluginsDisabled);
settings.developer_tools_disabled =
g_command_line->HasSwitch(cefclient::kDeveloperToolsDisabled);
settings.fullscreen_enabled =
g_command_line->HasSwitch(cefclient::kFullscreenEnabled);
}
static void ExecuteGetSource(CefRefPtr<CefFrame> frame) {
// Retrieve the current page source and display.
std::string source = frame->GetSource();
source = StringReplace(source, "<", "&lt;");
source = StringReplace(source, ">", "&gt;");
std::stringstream ss;
ss << "<html><body>Source:<pre>" << source << "</pre></body></html>";
frame->LoadString(ss.str(), "http://tests/getsource");
}
void RunGetSourceTest(CefRefPtr<CefBrowser> browser) {
// Execute the GetSource() call on the UI thread.
CefPostTask(TID_UI,
NewCefRunnableFunction(&ExecuteGetSource, browser->GetMainFrame()));
}
static void ExecuteGetText(CefRefPtr<CefFrame> frame) {
std::string text = frame->GetText();
text = StringReplace(text, "<", "&lt;");
text = StringReplace(text, ">", "&gt;");
std::stringstream ss;
ss << "<html><body>Text:<pre>" << text << "</pre></body></html>";
frame->LoadString(ss.str(), "http://tests/gettext");
}
void RunGetTextTest(CefRefPtr<CefBrowser> browser) {
// Execute the GetText() call on the UI thread.
CefPostTask(TID_UI,
NewCefRunnableFunction(&ExecuteGetText, browser->GetMainFrame()));
}
void RunRequestTest(CefRefPtr<CefBrowser> browser) {
// Create a new request
CefRefPtr<CefRequest> request(CefRequest::CreateRequest());
// Set the request URL
request->SetURL("http://tests/request");
// Add post data to the request. The correct method and content-
// type headers will be set by CEF.
CefRefPtr<CefPostDataElement> postDataElement(
CefPostDataElement::CreatePostDataElement());
std::string data = "arg1=val1&arg2=val2";
postDataElement->SetToBytes(data.length(), data.c_str());
CefRefPtr<CefPostData> postData(CefPostData::CreatePostData());
postData->AddElement(postDataElement);
request->SetPostData(postData);
// Add a custom header
CefRequest::HeaderMap headerMap;
headerMap.insert(
std::make_pair("X-My-Header", "My Header Value"));
request->SetHeaderMap(headerMap);
// Load the request
browser->GetMainFrame()->LoadRequest(request);
}
void RunJavaScriptExecuteTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->ExecuteJavaScript(
"alert('JavaScript execute works!');", "about:blank", 0);
}
void RunJavaScriptInvokeTest(CefRefPtr<CefBrowser> browser) {
if (CefCurrentlyOn(TID_UI)) {
UIT_InvokeScript(browser);
} else {
// Execute on the UI thread.
CefPostTask(TID_UI, NewCefRunnableFunction(&UIT_InvokeScript, browser));
}
}
void RunPopupTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->ExecuteJavaScript(
"window.open('http://www.google.com');", "about:blank", 0);
}
void RunLocalStorageTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("http://tests/localstorage");
}
void RunAccelerated2DCanvasTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL(
"http://mudcu.be/labs/JS1k/BreathingGalaxies.html");
}
void RunAcceleratedLayersTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL(
"http://webkit.org/blog-files/3d-transforms/poster-circle.html");
}
void RunWebGLTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL(
"http://webglsamples.googlecode.com/hg/field/field.html");
}
void RunHTML5VideoTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL(
"http://www.youtube.com/watch?v=siOHh0uzcuY&html5=True");
}
void RunXMLHTTPRequestTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("http://tests/xmlhttprequest");
}
void RunWebURLRequestTest(CefRefPtr<CefBrowser> browser) {
class RequestClient : public CefWebURLRequestClient {
public:
explicit RequestClient(CefRefPtr<CefBrowser> browser) : browser_(browser) {}
virtual void OnStateChange(CefRefPtr<CefWebURLRequest> requester,
RequestState state) {
REQUIRE_UI_THREAD();
if (state == WUR_STATE_DONE) {
buffer_ = StringReplace(buffer_, "<", "&lt;");
buffer_ = StringReplace(buffer_, ">", "&gt;");
std::stringstream ss;
ss << "<html><body>Source:<pre>" << buffer_ << "</pre></body></html>";
browser_->GetMainFrame()->LoadString(ss.str(),
"http://tests/weburlrequest");
}
}
virtual void OnRedirect(CefRefPtr<CefWebURLRequest> requester,
CefRefPtr<CefRequest> request,
CefRefPtr<CefResponse> response) {
REQUIRE_UI_THREAD();
}
virtual void OnHeadersReceived(CefRefPtr<CefWebURLRequest> requester,
CefRefPtr<CefResponse> response) {
REQUIRE_UI_THREAD();
}
virtual void OnProgress(CefRefPtr<CefWebURLRequest> requester,
uint64 bytesSent, uint64 totalBytesToBeSent) {
REQUIRE_UI_THREAD();
}
virtual void OnData(CefRefPtr<CefWebURLRequest> requester,
const void* data, int dataLength) {
REQUIRE_UI_THREAD();
buffer_.append(static_cast<const char*>(data), dataLength);
}
virtual void OnError(CefRefPtr<CefWebURLRequest> requester,
ErrorCode errorCode) {
REQUIRE_UI_THREAD();
std::stringstream ss;
ss << "Load failed with error code " << errorCode;
browser_->GetMainFrame()->LoadString(ss.str(),
"http://tests/weburlrequest");
}
protected:
CefRefPtr<CefBrowser> browser_;
std::string buffer_;
IMPLEMENT_REFCOUNTING(CefWebURLRequestClient);
};
CefRefPtr<CefRequest> request(CefRequest::CreateRequest());
request->SetURL("http://www.google.com");
CefRefPtr<CefWebURLRequestClient> client(new RequestClient(browser));
CefRefPtr<CefWebURLRequest> requester(
CefWebURLRequest::CreateWebURLRequest(request, client));
}
void RunDOMAccessTest(CefRefPtr<CefBrowser> browser) {
class Listener : public CefDOMEventListener {
public:
Listener() {}
virtual void HandleEvent(CefRefPtr<CefDOMEvent> event) {
CefRefPtr<CefDOMDocument> document = event->GetDocument();
ASSERT(document.get());
std::stringstream ss;
CefRefPtr<CefDOMNode> button = event->GetTarget();
ASSERT(button.get());
std::string buttonValue = button->GetElementAttribute("value");
ss << "You clicked the " << buttonValue.c_str() << " button. ";
if (document->HasSelection()) {
std::string startName, endName;
// Determine the start name by first trying to locate the "id" attribute
// and then defaulting to the tag name.
{
CefRefPtr<CefDOMNode> node = document->GetSelectionStartNode();
if (!node->IsElement())
node = node->GetParent();
if (node->IsElement() && node->HasElementAttribute("id"))
startName = node->GetElementAttribute("id");
else
startName = node->GetName();
}
// Determine the end name by first trying to locate the "id" attribute
// and then defaulting to the tag name.
{
CefRefPtr<CefDOMNode> node = document->GetSelectionEndNode();
if (!node->IsElement())
node = node->GetParent();
if (node->IsElement() && node->HasElementAttribute("id"))
endName = node->GetElementAttribute("id");
else
endName = node->GetName();
}
ss << "The selection is from " <<
startName.c_str() << ":" << document->GetSelectionStartOffset() <<
" to " <<
endName.c_str() << ":" << document->GetSelectionEndOffset();
} else {
ss << "Nothing is selected.";
}
// Update the description.
CefRefPtr<CefDOMNode> desc = document->GetElementById("description");
ASSERT(desc.get());
CefRefPtr<CefDOMNode> text = desc->GetFirstChild();
ASSERT(text.get());
ASSERT(text->IsText());
text->SetValue(ss.str());
}
IMPLEMENT_REFCOUNTING(Listener);
};
class Visitor : public CefDOMVisitor {
public:
Visitor() {}
virtual void Visit(CefRefPtr<CefDOMDocument> document) {
// Register an click listener for the button.
CefRefPtr<CefDOMNode> button = document->GetElementById("button");
ASSERT(button.get());
button->AddEventListener("click", new Listener(), false);
}
IMPLEMENT_REFCOUNTING(Visitor);
};
// The DOM visitor will be called after the path is loaded.
CefRefPtr<CefClient> client = browser->GetClient();
static_cast<ClientHandler*>(client.get())->AddDOMVisitor(
"http://tests/domaccess", new Visitor());
browser->GetMainFrame()->LoadURL("http://tests/domaccess");
}
void RunDragDropTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("http://html5demos.com/drag");
}
void RunModalDialogTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("http://tests/modalmain");
}

View File

@@ -1,60 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_H_
#pragma once
#include <string>
#include "include/cef_base.h"
class CefApp;
class CefBrowser;
class CefCommandLine;
// Returns the main browser window instance.
CefRefPtr<CefBrowser> AppGetBrowser();
// Returns the main application window handle.
CefWindowHandle AppGetMainHwnd();
// Returns the application working directory.
std::string AppGetWorkingDirectory();
// Initialize the application command line.
void AppInitCommandLine(int argc, const char* const* argv);
// Returns the application command line object.
CefRefPtr<CefCommandLine> AppGetCommandLine();
// Returns the application settings based on command line arguments.
void AppGetSettings(CefSettings& settings, CefRefPtr<CefApp>& app);
// Returns the application browser settings based on command line arguments.
void AppGetBrowserSettings(CefBrowserSettings& settings);
// Implementations for various tests.
void RunGetSourceTest(CefRefPtr<CefBrowser> browser);
void RunGetTextTest(CefRefPtr<CefBrowser> browser);
void RunRequestTest(CefRefPtr<CefBrowser> browser);
void RunJavaScriptExecuteTest(CefRefPtr<CefBrowser> browser);
void RunJavaScriptInvokeTest(CefRefPtr<CefBrowser> browser);
void RunPopupTest(CefRefPtr<CefBrowser> browser);
void RunLocalStorageTest(CefRefPtr<CefBrowser> browser);
void RunAccelerated2DCanvasTest(CefRefPtr<CefBrowser> browser);
void RunAcceleratedLayersTest(CefRefPtr<CefBrowser> browser);
void RunWebGLTest(CefRefPtr<CefBrowser> browser);
void RunHTML5VideoTest(CefRefPtr<CefBrowser> browser);
void RunXMLHTTPRequestTest(CefRefPtr<CefBrowser> browser);
void RunWebURLRequestTest(CefRefPtr<CefBrowser> browser);
void RunDOMAccessTest(CefRefPtr<CefBrowser> browser);
void RunDragDropTest(CefRefPtr<CefBrowser> browser);
void RunModalDialogTest(CefRefPtr<CefBrowser> browser);
#if defined(OS_WIN)
void RunTransparentPopupTest(CefRefPtr<CefBrowser> browser);
void RunGetImageTest(CefRefPtr<CefBrowser> browser);
#endif
#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_H_

View File

@@ -1,191 +0,0 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Binary
//
IDS_LOGO BINARY "res\\logo.png"
IDS_UIPLUGIN BINARY "res\\uiplugin.html"
IDS_OSRPLUGIN BINARY "res\\osrplugin.html"
IDS_LOGOBALL BINARY "res\\logoball.png"
IDS_LOCALSTORAGE BINARY "res\\localstorage.html"
IDS_XMLHTTPREQUEST BINARY "res\\xmlhttprequest.html"
IDS_DOMACCESS BINARY "res\\domaccess.html"
IDS_MODALMAIN BINARY "res\\modalmain.html"
IDS_MODALDIALOG BINARY "res\\modaldialog.html"
IDS_EXTENSIONPERF BINARY "res\\extensionperf.html"
IDS_TRANSPARENCY BINARY "res\\transparency.html"
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_CEFCLIENT ICON "res\cefclient.ico"
IDI_SMALL ICON "res\small.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Menu
//
IDC_CEFCLIENT MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "&Find...", ID_FIND
MENUITEM SEPARATOR
MENUITEM "&Print...", ID_PRINT
MENUITEM SEPARATOR
MENUITEM "E&xit", IDM_EXIT
END
POPUP "&Help"
BEGIN
MENUITEM "&About ...", IDM_ABOUT
END
POPUP "Tests"
BEGIN
MENUITEM "Get Source", ID_TESTS_GETSOURCE
MENUITEM "Get Text", ID_TESTS_GETTEXT
MENUITEM "JavaScript Binding Handler", ID_TESTS_JAVASCRIPT_BINDING
MENUITEM "JavaScript Extension Handler",ID_TESTS_JAVASCRIPT_EXTENSION
MENUITEM "JavaScript Extension Performance",ID_TESTS_JAVASCRIPT_PERFORMANCE
MENUITEM "JavaScript Execute", ID_TESTS_JAVASCRIPT_EXECUTE
MENUITEM "JavaScript Invoke", ID_TESTS_JAVASCRIPT_INVOKE
MENUITEM "Plugin", ID_TESTS_PLUGIN
MENUITEM "Popup Window", ID_TESTS_POPUP
MENUITEM "Transparent Popup Window", ID_TESTS_TRANSPARENT_POPUP
MENUITEM "Request", ID_TESTS_REQUEST
MENUITEM "Scheme Handler", ID_TESTS_SCHEME_HANDLER
MENUITEM "UI App Example", ID_TESTS_UIAPP
MENUITEM "Off-Screen Rendering Example",ID_TESTS_OSRAPP
MENUITEM "Transparent Off-Screen Rendering Example",ID_TESTS_TRANSPARENT_OSRAPP
MENUITEM "Local Storage", ID_TESTS_LOCALSTORAGE
MENUITEM "XMLHttpRequest", ID_TESTS_XMLHTTPREQUEST
MENUITEM "WebURLRequest", ID_TESTS_WEBURLREQUEST
MENUITEM "DOM Access", ID_TESTS_DOMACCESS
MENUITEM "Accelerated 2D Canvas", ID_TESTS_ACCELERATED2DCANVAS
MENUITEM "Accelerated Layers", ID_TESTS_ACCELERATEDLAYERS
MENUITEM "WebGL", ID_TESTS_WEBGL
MENUITEM "HTML5 Video", ID_TESTS_HTML5VIDEO
MENUITEM "Drag && Drop", ID_TESTS_DRAGDROP
MENUITEM "Zoom In", ID_TESTS_ZOOM_IN
MENUITEM "Zoom Out", ID_TESTS_ZOOM_OUT
MENUITEM "Reset Zoom", ID_TESTS_ZOOM_RESET
MENUITEM "Show Developer Tools", ID_TESTS_DEVTOOLS_SHOW
MENUITEM "Close Developer Tools", ID_TESTS_DEVTOOLS_CLOSE
MENUITEM "Modal Dialog", ID_TESTS_MODALDIALOG
MENUITEM "Get Image", ID_TESTS_GETIMAGE
END
END
/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//
IDC_CEFCLIENT ACCELERATORS
BEGIN
"?", IDM_ABOUT, ASCII, ALT
"/", IDM_ABOUT, ASCII, ALT
END
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_ABOUTBOX DIALOG 22, 17, 230, 75
STYLE DS_SETFONT | DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
CAPTION "About"
FONT 8, "System"
BEGIN
ICON IDI_CEFCLIENT,IDC_MYICON,14,9,16,16
LTEXT "cefclient Version 1.0",IDC_STATIC,49,10,119,8,SS_NOPREFIX
LTEXT "Copyright (C) 2008",IDC_STATIC,49,20,119,8
DEFPUSHBUTTON "OK",IDOK,195,6,30,11,WS_GROUP
END
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
"#include ""windows.h""\r\n"
"#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE
BEGIN
IDS_APP_TITLE "cefclient"
IDC_CEFCLIENT "CEFCLIENT"
END
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@@ -1,434 +0,0 @@
// 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 <gtk/gtk.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include "cefclient/cefclient.h"
#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "cefclient/binding_test.h"
#include "cefclient/client_handler.h"
#include "cefclient/extension_test.h"
#include "cefclient/scheme_test.h"
#include "cefclient/string_util.h"
char szWorkingDir[512]; // The current working directory
// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;
void destroy(void) {
CefQuitMessageLoop();
}
void TerminationSignalHandler(int signatl) {
destroy();
}
// Callback for Debug > Get Source... menu item.
gboolean GetSourceActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunGetSourceTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Get Source... menu item.
gboolean GetTextActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunGetTextTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > JS Binding... menu item.
gboolean JSBindngActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunBindingTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > JS Extension... menu item.
gboolean JSExtensionActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunExtensionTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > JS Execute... menu item.
gboolean JSExecuteActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunJavaScriptExecuteTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Request... menu item.
gboolean RequestActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunRequestTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Local Storage... menu item.
gboolean LocalStorageActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunLocalStorageTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > XMLHttpRequest... menu item.
gboolean XMLHttpRequestActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunXMLHTTPRequestTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > WebURLRequest... menu item.
gboolean WebURLRequestActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunWebURLRequestTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > DOM Access... menu item.
gboolean DOMAccessActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunDOMAccessTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Scheme Handler... menu item.
gboolean SchemeHandlerActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunSchemeTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Popup Window... menu item.
gboolean PopupWindowActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunPopupTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Accelerated 2D Canvas:... menu item.
gboolean Accelerated2DCanvasActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunAccelerated2DCanvasTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Accelerated Layers:... menu item.
gboolean AcceleratedLayersActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunAcceleratedLayersTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > WebGL:... menu item.
gboolean WebGLActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunWebGLTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > HTML5 Video... menu item.
gboolean HTML5VideoActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunHTML5VideoTest(g_handler->GetBrowser());
return FALSE; // Don't stop this message.
}
// Callback for Debug > Zoom In... menu item.
gboolean ZoomInActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->SetZoomLevel(browser->GetZoomLevel() + 0.5);
}
return FALSE; // Don't stop this message.
}
// Callback for Debug > Zoom Out... menu item.
gboolean ZoomOutActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->SetZoomLevel(browser->GetZoomLevel() - 0.5);
}
return FALSE; // Don't stop this message.
}
// Callback for Debug > Zoom Reset... menu item.
gboolean ZoomResetActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->SetZoomLevel(0.0);
}
return FALSE; // Don't stop this message.
}
gboolean DragDropActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
RunDragDropTest(browser);
}
return FALSE; // Don't stop this message.
}
gboolean ShowDevtoolsActivated(GtkWidget* widget) {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->ShowDevTools();
}
return FALSE; // Don't stop this message.
}
// Callback for when you click the back button.
void BackButtonClicked(GtkButton* button) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->GoBack();
}
// Callback for when you click the forward button.
void ForwardButtonClicked(GtkButton* button) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->GoForward();
}
// Callback for when you click the stop button.
void StopButtonClicked(GtkButton* button) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->StopLoad();
}
// Callback for when you click the reload button.
void ReloadButtonClicked(GtkButton* button) {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->Reload();
}
// Callback for when you press enter in the URL box.
void URLEntryActivate(GtkEntry* entry) {
if (!g_handler.get() || !g_handler->GetBrowserHwnd())
return;
const gchar* url = gtk_entry_get_text(entry);
g_handler->GetBrowser()->GetMainFrame()->LoadURL(std::string(url).c_str());
}
// GTK utility functions ----------------------------------------------
GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text,
GCallback callback) {
GtkWidget* entry = gtk_menu_item_new_with_label(text);
g_signal_connect(entry, "activate", callback, NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), entry);
return entry;
}
GtkWidget* CreateMenu(GtkWidget* menu_bar, const char* text) {
GtkWidget* menu_widget = gtk_menu_new();
GtkWidget* menu_header = gtk_menu_item_new_with_label(text);
gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_header), menu_widget);
gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), menu_header);
return menu_widget;
}
GtkWidget* CreateMenuBar() {
GtkWidget* menu_bar = gtk_menu_bar_new();
GtkWidget* debug_menu = CreateMenu(menu_bar, "Tests");
AddMenuEntry(debug_menu, "Get Source",
G_CALLBACK(GetSourceActivated));
AddMenuEntry(debug_menu, "Get Text",
G_CALLBACK(GetTextActivated));
AddMenuEntry(debug_menu, "JS Binding",
G_CALLBACK(JSBindngActivated));
AddMenuEntry(debug_menu, "JS Extension",
G_CALLBACK(JSExtensionActivated));
AddMenuEntry(debug_menu, "JS Execute",
G_CALLBACK(JSExecuteActivated));
AddMenuEntry(debug_menu, "Request",
G_CALLBACK(RequestActivated));
AddMenuEntry(debug_menu, "Local Storage",
G_CALLBACK(LocalStorageActivated));
AddMenuEntry(debug_menu, "XMLHttpRequest",
G_CALLBACK(XMLHttpRequestActivated));
AddMenuEntry(debug_menu, "DOM Access",
G_CALLBACK(DOMAccessActivated));
AddMenuEntry(debug_menu, "Scheme Handler",
G_CALLBACK(SchemeHandlerActivated));
AddMenuEntry(debug_menu, "Popup Window",
G_CALLBACK(PopupWindowActivated));
AddMenuEntry(debug_menu, "Accelerated 2D Canvas",
G_CALLBACK(Accelerated2DCanvasActivated));
AddMenuEntry(debug_menu, "Accelerated Layers",
G_CALLBACK(AcceleratedLayersActivated));
AddMenuEntry(debug_menu, "WebGL",
G_CALLBACK(WebGLActivated));
AddMenuEntry(debug_menu, "HTML5 Video",
G_CALLBACK(HTML5VideoActivated));
AddMenuEntry(debug_menu, "Zoom In",
G_CALLBACK(ZoomInActivated));
AddMenuEntry(debug_menu, "Zoom Out",
G_CALLBACK(ZoomOutActivated));
AddMenuEntry(debug_menu, "Zoom Reset",
G_CALLBACK(ZoomResetActivated));
AddMenuEntry(debug_menu, "Test DragDrop",
G_CALLBACK(DragDropActivated));
AddMenuEntry(debug_menu, "Show DevTools",
G_CALLBACK(ShowDevtoolsActivated));
return menu_bar;
}
// WebViewDelegate::TakeFocus in the test webview delegate.
static gboolean HandleFocus(GtkWidget* widget,
GdkEventFocus* focus) {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Give focus to the browser window.
g_handler->GetBrowser()->SetFocus(true);
}
return TRUE;
}
int main(int argc, char *argv[]) {
if (!getcwd(szWorkingDir, sizeof (szWorkingDir)))
return -1;
GtkWidget* window;
gtk_init(&argc, &argv);
// Parse command line arguments.
AppInitCommandLine(argc, argv);
CefSettings settings;
CefRefPtr<CefApp> app;
// Populate the settings based on command line arguments.
AppGetSettings(settings, app);
// Initialize CEF.
CefInitialize(settings, app);
// Register the V8 extension handler.
InitExtensionTest();
// Register the scheme handler.
InitSchemeTest();
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);
g_signal_connect(window, "focus", G_CALLBACK(&HandleFocus), NULL);
GtkWidget* vbox = gtk_vbox_new(FALSE, 0);
GtkWidget* menu_bar = CreateMenuBar();
gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 0);
GtkWidget* toolbar = gtk_toolbar_new();
// Turn off the labels on the toolbar buttons.
gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
GtkToolItem* back = gtk_tool_button_new_from_stock(GTK_STOCK_GO_BACK);
g_signal_connect(back, "clicked",
G_CALLBACK(BackButtonClicked), NULL);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), back, -1 /* append */);
GtkToolItem* forward = gtk_tool_button_new_from_stock(GTK_STOCK_GO_FORWARD);
g_signal_connect(forward, "clicked",
G_CALLBACK(ForwardButtonClicked), NULL);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), forward, -1 /* append */);
GtkToolItem* reload = gtk_tool_button_new_from_stock(GTK_STOCK_REFRESH);
g_signal_connect(reload, "clicked",
G_CALLBACK(ReloadButtonClicked), NULL);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), reload, -1 /* append */);
GtkToolItem* stop = gtk_tool_button_new_from_stock(GTK_STOCK_STOP);
g_signal_connect(stop, "clicked",
G_CALLBACK(StopButtonClicked), NULL);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), stop, -1 /* append */);
GtkWidget* m_editWnd = gtk_entry_new();
g_signal_connect(G_OBJECT(m_editWnd), "activate",
G_CALLBACK(URLEntryActivate), NULL);
GtkToolItem* tool_item = gtk_tool_item_new();
gtk_container_add(GTK_CONTAINER(tool_item), m_editWnd);
gtk_tool_item_set_expand(tool_item, TRUE);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool_item, -1); // append
gtk_box_pack_start(GTK_BOX(vbox), toolbar, FALSE, FALSE, 0);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_widget_destroyed), &window);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(destroy), NULL);
// Create the handler.
g_handler = new ClientHandler();
g_handler->SetMainHwnd(vbox);
g_handler->SetEditHwnd(m_editWnd);
g_handler->SetButtonHwnds(GTK_WIDGET(back), GTK_WIDGET(forward),
GTK_WIDGET(reload), GTK_WIDGET(stop));
// Create the browser view.
CefWindowInfo window_info;
CefBrowserSettings browserSettings;
// Populate the settings based on command line arguments.
AppGetBrowserSettings(browserSettings);
window_info.SetAsChild(vbox);
CefBrowser::CreateBrowserSync(window_info,
static_cast<CefRefPtr<CefClient> >(g_handler),
"http://www.google.com", browserSettings);
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_widget_show_all(GTK_WIDGET(window));
// Install an signal handler so we clean up after ourselves.
signal(SIGINT, TerminationSignalHandler);
signal(SIGTERM, TerminationSignalHandler);
CefRunMessageLoop();
CefShutdown();
return 0;
}
// Global functions
std::string AppGetWorkingDirectory() {
return szWorkingDir;
}

View File

@@ -1,584 +0,0 @@
// Copyright (c) 2010 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#include <sstream>
#include "cefclient/cefclient.h"
#include "include/cef_app.h"
#import "include/cef_application_mac.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "cefclient/binding_test.h"
#include "cefclient/client_handler.h"
#include "cefclient/extension_test.h"
#include "cefclient/resource_util.h"
#include "cefclient/scheme_test.h"
#include "cefclient/string_util.h"
// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;
char szWorkingDir[512]; // The current working directory
// Sizes for URL bar layout
#define BUTTON_HEIGHT 22
#define BUTTON_WIDTH 72
#define BUTTON_MARGIN 8
#define URLBAR_HEIGHT 32
// Content area size for newly created windows.
const int kWindowWidth = 800;
const int kWindowHeight = 600;
// Memory AutoRelease pool.
static NSAutoreleasePool* g_autopool = nil;
// Provide the CefAppProtocol implementation required by CEF.
@interface ClientApplication : NSApplication<CefAppProtocol> {
@private
BOOL handlingSendEvent_;
}
@end
@implementation ClientApplication
- (BOOL)isHandlingSendEvent {
return handlingSendEvent_;
}
- (void)setHandlingSendEvent:(BOOL)handlingSendEvent {
handlingSendEvent_ = handlingSendEvent;
}
- (void)sendEvent:(NSEvent*)event {
CefScopedSendingEvent sendingEventScoper;
[super sendEvent:event];
}
@end
// Receives notifications from controls and the browser window. Will delete
// itself when done.
@interface ClientWindowDelegate : NSObject <NSWindowDelegate>
- (IBAction)goBack:(id)sender;
- (IBAction)goForward:(id)sender;
- (IBAction)reload:(id)sender;
- (IBAction)stopLoading:(id)sender;
- (IBAction)takeURLStringValueFrom:(NSTextField *)sender;
- (void)alert:(NSString*)title withMessage:(NSString*)message;
- (void)notifyConsoleMessage:(id)object;
- (void)notifyDownloadComplete:(id)object;
- (void)notifyDownloadError:(id)object;
@end
@implementation ClientWindowDelegate
- (IBAction)goBack:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->GoBack();
}
- (IBAction)goForward:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->GoForward();
}
- (IBAction)reload:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->Reload();
}
- (IBAction)stopLoading:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
g_handler->GetBrowser()->StopLoad();
}
- (IBAction)takeURLStringValueFrom:(NSTextField *)sender {
if (!g_handler.get() || !g_handler->GetBrowserHwnd())
return;
NSString *url = [sender stringValue];
// if it doesn't already have a prefix, add http. If we can't parse it,
// just don't bother rather than making things worse.
NSURL* tempUrl = [NSURL URLWithString:url];
if (tempUrl && ![tempUrl scheme])
url = [@"http://" stringByAppendingString:url];
std::string urlStr = [url UTF8String];
g_handler->GetBrowser()->GetMainFrame()->LoadURL(urlStr);
}
- (void)alert:(NSString*)title withMessage:(NSString*)message {
NSAlert *alert = [NSAlert alertWithMessageText:title
defaultButton:@"OK"
alternateButton:nil
otherButton:nil
informativeTextWithFormat:message];
[alert runModal];
}
- (void)notifyConsoleMessage:(id)object {
std::stringstream ss;
ss << "Console messages will be written to " << g_handler->GetLogFile();
NSString* str = [NSString stringWithUTF8String:(ss.str().c_str())];
[self alert:@"Console Messages" withMessage:str];
}
- (void)notifyDownloadComplete:(id)object {
std::stringstream ss;
ss << "File \"" << g_handler->GetLastDownloadFile() <<
"\" downloaded successfully.";
NSString* str = [NSString stringWithUTF8String:(ss.str().c_str())];
[self alert:@"File Download" withMessage:str];
}
- (void)notifyDownloadError:(id)object {
std::stringstream ss;
ss << "File \"" << g_handler->GetLastDownloadFile() <<
"\" failed to download.";
NSString* str = [NSString stringWithUTF8String:(ss.str().c_str())];
[self alert:@"File Download" withMessage:str];
}
- (void)windowDidBecomeKey:(NSNotification*)notification {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Give focus to the browser window.
g_handler->GetBrowser()->SetFocus(true);
}
}
// Called when the window is about to close. Perform the self-destruction
// sequence by getting rid of the window. By returning YES, we allow the window
// to be removed from the screen.
- (BOOL)windowShouldClose:(id)window {
// Try to make the window go away.
[window autorelease];
// Clean ourselves up after clearing the stack of anything that might have the
// window on it.
[self performSelectorOnMainThread:@selector(cleanup:)
withObject:window
waitUntilDone:NO];
return YES;
}
// Deletes itself.
- (void)cleanup:(id)window {
[self release];
}
@end
NSButton* MakeButton(NSRect* rect, NSString* title, NSView* parent) {
NSButton* button = [[[NSButton alloc] initWithFrame:*rect] autorelease];
[button setTitle:title];
[button setBezelStyle:NSSmallSquareBezelStyle];
[button setAutoresizingMask:(NSViewMaxXMargin | NSViewMinYMargin)];
[parent addSubview:button];
rect->origin.x += BUTTON_WIDTH;
return button;
}
// Receives notifications from the application. Will delete itself when done.
@interface ClientAppDelegate : NSObject
- (void)createApp:(id)object;
- (IBAction)testGetSource:(id)sender;
- (IBAction)testGetText:(id)sender;
- (IBAction)testJSBinding:(id)sender;
- (IBAction)testJSExtension:(id)sender;
- (IBAction)testJSExtensionPerf:(id)sender;
- (IBAction)testJSExecute:(id)sender;
- (IBAction)testJSInvoke:(id)sender;
- (IBAction)testRequest:(id)sender;
- (IBAction)testLocalStorage:(id)sender;
- (IBAction)testXMLHttpRequest:(id)sender;
- (IBAction)testWebURLRequest:(id)sender;
- (IBAction)testDOMAccess:(id)sender;
- (IBAction)testSchemeHandler:(id)sender;
- (IBAction)testPopupWindow:(id)sender;
- (IBAction)testAccelerated2DCanvas:(id)sender;
- (IBAction)testAcceleratedLayers:(id)sender;
- (IBAction)testWebGL:(id)sender;
- (IBAction)testHTML5Video:(id)sender;
- (IBAction)testDragDrop:(id)sender;
- (IBAction)testZoomIn:(id)sender;
- (IBAction)testZoomOut:(id)sender;
- (IBAction)testZoomReset:(id)sender;
- (IBAction)testDevToolsShow:(id)sender;
- (IBAction)testDevToolsClose:(id)sender;
@end
@implementation ClientAppDelegate
// Create the application on the UI thread.
- (void)createApp:(id)object {
[NSApplication sharedApplication];
[NSBundle loadNibNamed:@"MainMenu" owner:NSApp];
// Set the delegate for application events.
[NSApp setDelegate:self];
// Add the Tests menu.
NSMenu* menubar = [NSApp mainMenu];
NSMenuItem *testItem = [[[NSMenuItem alloc] initWithTitle:@"Tests"
action:nil
keyEquivalent:@""] autorelease];
NSMenu *testMenu = [[[NSMenu alloc] initWithTitle:@"Tests"] autorelease];
[testMenu addItemWithTitle:@"Get Source"
action:@selector(testGetSource:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Get Text"
action:@selector(testGetText:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"JavaScript Binding Handler"
action:@selector(testJSBinding:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"JavaScript Extension Handler"
action:@selector(testJSExtension:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"JavaScript Extension Performance"
action:@selector(testJSExtensionPerf:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"JavaScript Execute"
action:@selector(testJSExecute:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"JavaScript Invoke"
action:@selector(testJSInvoke:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Popup Window"
action:@selector(testPopupWindow:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Request"
action:@selector(testRequest:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Scheme Handler"
action:@selector(testSchemeHandler:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Local Storage"
action:@selector(testLocalStorage:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"XMLHttpRequest"
action:@selector(testXMLHttpRequest:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"WebURLRequest"
action:@selector(testWebURLRequest:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"DOM Access"
action:@selector(testDOMAccess:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Accelerated 2D Canvas"
action:@selector(testAccelerated2DCanvas:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Accelerated Layers"
action:@selector(testAcceleratedLayers:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"WebGL"
action:@selector(testWebGL:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"HTML5 Video"
action:@selector(testHTML5Video:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Drag & Drop"
action:@selector(testDragDrop:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Zoom In"
action:@selector(testZoomIn:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Zoom Out"
action:@selector(testZoomOut:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Zoom Reset"
action:@selector(testZoomReset:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Show DevTools"
action:@selector(testDevToolsShow:)
keyEquivalent:@""];
[testMenu addItemWithTitle:@"Close DevTools"
action:@selector(testDevToolsClose:)
keyEquivalent:@""];
[testItem setSubmenu:testMenu];
[menubar addItem:testItem];
// Create the delegate for control and browser window events.
ClientWindowDelegate* delegate = [[ClientWindowDelegate alloc] init];
// Create the main application window.
NSRect screen_rect = [[NSScreen mainScreen] visibleFrame];
NSRect window_rect = { {0, screen_rect.size.height - kWindowHeight},
{kWindowWidth, kWindowHeight} };
NSWindow* mainWnd = [[NSWindow alloc]
initWithContentRect:window_rect
styleMask:(NSTitledWindowMask |
NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask )
backing:NSBackingStoreBuffered
defer:NO];
[mainWnd setTitle:@"cefclient"];
[mainWnd setDelegate:delegate];
// Rely on the window delegate to clean us up rather than immediately
// releasing when the window gets closed. We use the delegate to do
// everything from the autorelease pool so the window isn't on the stack
// during cleanup (ie, a window close from javascript).
[mainWnd setReleasedWhenClosed:NO];
NSView* contentView = [mainWnd contentView];
// Create the buttons.
NSRect button_rect = [contentView bounds];
button_rect.origin.y = window_rect.size.height - URLBAR_HEIGHT +
(URLBAR_HEIGHT - BUTTON_HEIGHT) / 2;
button_rect.size.height = BUTTON_HEIGHT;
button_rect.origin.x += BUTTON_MARGIN;
button_rect.size.width = BUTTON_WIDTH;
NSButton* button = MakeButton(&button_rect, @"Back", contentView);
[button setTarget:delegate];
[button setAction:@selector(goBack:)];
button = MakeButton(&button_rect, @"Forward", contentView);
[button setTarget:delegate];
[button setAction:@selector(goForward:)];
button = MakeButton(&button_rect, @"Reload", contentView);
[button setTarget:delegate];
[button setAction:@selector(reload:)];
button = MakeButton(&button_rect, @"Stop", contentView);
[button setTarget:delegate];
[button setAction:@selector(stopLoading:)];
// Create the URL text field.
button_rect.origin.x += BUTTON_MARGIN;
button_rect.size.width = [contentView bounds].size.width -
button_rect.origin.x - BUTTON_MARGIN;
NSTextField* editWnd = [[NSTextField alloc] initWithFrame:button_rect];
[contentView addSubview:editWnd];
[editWnd setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
[editWnd setTarget:delegate];
[editWnd setAction:@selector(takeURLStringValueFrom:)];
[[editWnd cell] setWraps:NO];
[[editWnd cell] setScrollable:YES];
// Create the handler.
g_handler = new ClientHandler();
g_handler->SetMainHwnd(contentView);
g_handler->SetEditHwnd(editWnd);
// Create the browser view.
CefWindowInfo window_info;
CefBrowserSettings settings;
// Populate the settings based on command line arguments.
AppGetBrowserSettings(settings);
window_info.SetAsChild(contentView, 0, 0, kWindowWidth, kWindowHeight);
CefBrowser::CreateBrowser(window_info, g_handler.get(),
"http://www.google.com", settings);
// Show the window.
[mainWnd makeKeyAndOrderFront: nil];
// Size the window.
NSRect r = [mainWnd contentRectForFrameRect:[mainWnd frame]];
r.size.width = kWindowWidth;
r.size.height = kWindowHeight + URLBAR_HEIGHT;
[mainWnd setFrame:[mainWnd frameRectForContentRect:r] display:YES];
}
- (IBAction)testGetSource:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunGetSourceTest(g_handler->GetBrowser());
}
- (IBAction)testGetText:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunGetTextTest(g_handler->GetBrowser());
}
- (IBAction)testJSBinding:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunBindingTest(g_handler->GetBrowser());
}
- (IBAction)testJSExtension:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunExtensionTest(g_handler->GetBrowser());
}
- (IBAction)testJSExtensionPerf:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunExtensionPerfTest(g_handler->GetBrowser());
}
- (IBAction)testJSExecute:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunJavaScriptExecuteTest(g_handler->GetBrowser());
}
- (IBAction)testJSInvoke:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunJavaScriptInvokeTest(g_handler->GetBrowser());
}
- (IBAction)testRequest:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunRequestTest(g_handler->GetBrowser());
}
- (IBAction)testLocalStorage:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunLocalStorageTest(g_handler->GetBrowser());
}
- (IBAction)testXMLHttpRequest:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunXMLHTTPRequestTest(g_handler->GetBrowser());
}
- (IBAction)testWebURLRequest:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunWebURLRequestTest(g_handler->GetBrowser());
}
- (IBAction)testDOMAccess:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunDOMAccessTest(g_handler->GetBrowser());
}
- (IBAction)testSchemeHandler:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunSchemeTest(g_handler->GetBrowser());
}
- (IBAction)testPopupWindow:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunPopupTest(g_handler->GetBrowser());
}
- (IBAction)testAccelerated2DCanvas:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunAccelerated2DCanvasTest(g_handler->GetBrowser());
}
- (IBAction)testAcceleratedLayers:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunAcceleratedLayersTest(g_handler->GetBrowser());
}
- (IBAction)testWebGL:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunWebGLTest(g_handler->GetBrowser());
}
- (IBAction)testHTML5Video:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunHTML5VideoTest(g_handler->GetBrowser());
}
- (IBAction)testDragDrop:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd())
RunDragDropTest(g_handler->GetBrowser());
}
- (IBAction)testZoomIn:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->SetZoomLevel(browser->GetZoomLevel() + 0.5);
}
}
- (IBAction)testZoomOut:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->SetZoomLevel(browser->GetZoomLevel() - 0.5);
}
}
- (IBAction)testZoomReset:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->SetZoomLevel(0.0);
}
}
- (IBAction)testDevToolsShow:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->ShowDevTools();
}
}
- (IBAction)testDevToolsClose:(id)sender {
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
browser->CloseDevTools();
}
}
// Sent by the default notification center immediately before the application
// terminates.
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Shut down CEF.
g_handler = NULL;
CefShutdown();
[self release];
// Release the AutoRelease pool.
[g_autopool release];
}
@end
int main(int argc, char* argv[]) {
// Retrieve the current working directory.
getcwd(szWorkingDir, sizeof(szWorkingDir));
// Initialize the AutoRelease pool.
g_autopool = [[NSAutoreleasePool alloc] init];
// Initialize the ClientApplication instance.
[ClientApplication sharedApplication];
// Parse command line arguments.
AppInitCommandLine(argc, argv);
CefSettings settings;
CefRefPtr<CefApp> app;
// Populate the settings based on command line arguments.
AppGetSettings(settings, app);
// Initialize CEF.
CefInitialize(settings, app);
// Initialize tests.
InitExtensionTest();
InitSchemeTest();
// Create the application delegate and window.
NSObject* delegate = [[ClientAppDelegate alloc] init];
[delegate performSelectorOnMainThread:@selector(createApp:) withObject:nil
waitUntilDone:NO];
// Run the application message loop.
CefRunMessageLoop();
// Don't put anything below this line because it won't be executed.
return 0;
}
// Global functions
std::string AppGetWorkingDirectory() {
return szWorkingDir;
}

View File

@@ -1,93 +0,0 @@
// 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.
// This file is shared by cefclient and cef_unittests so don't include using
// a qualified path.
#include "cefclient_switches.h" // NOLINT(build/include)
namespace cefclient {
// CefSettings attributes.
const char kMultiThreadedMessageLoop[] = "multi-threaded-message-loop";
const char kCachePath[] = "cache-path";
const char kUserAgent[] = "user-agent";
const char kProductVersion[] = "product-version";
const char kLocale[] = "locale";
const char kLogFile[] = "log-file";
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_ErrorReport[] = "error-report";
const char kLogSeverity_Disable[] = "disable";
const char kGraphicsImpl[] = "graphics-implementation";
const char kGraphicsImpl_Angle[] = "angle";
const char kGraphicsImpl_AngleCmdBuffer[] = "angle-command-buffer";
const char kGraphicsImpl_Desktop[] = "desktop";
const char kGraphicsImpl_DesktopCmdBuffer[] = "desktop-command-buffer";
const char kLocalStorageQuota[] = "local-storage-quota";
const char kSessionStorageQuota[] = "session-storage-quota";
const char kJavascriptFlags[] = "javascript-flags";
const char kPackFilePath[] = "pack-file-path";
const char kLocalesDirPath[] = "locales-dir-path";
const char kPackLoadingDisabled[] = "pack-loading-disabled";
// CefBrowserSettings attributes.
const char kDragDropDisabled[] = "drag-drop-disabled";
const char kLoadDropsDisabled[] = "load-drops-disabled";
const char kHistoryDisabled[] = "history-disabled";
const char kRemoteFontsDisabled[] = "remote-fonts-disabled";
const char kDefaultEncoding[] = "default-encoding";
const char kEncodingDetectorEnabled[] = "encoding-detector-enabled";
const char kJavascriptDisabled[] = "javascript-disabled";
const char kJavascriptOpenWindowsDisallowed[] =
"javascript-open-windows-disallowed";
const char kJavascriptCloseWindowsDisallowed[] =
"javascript-close-windows-disallowed";
const char kJavascriptAccessClipboardDisallowed[] =
"javascript-access-clipboard-disallowed";
const char kDomPasteDisabled[] = "dom-paste-disabled";
const char kCaretBrowsingDisabled[] = "caret-browsing-enabled";
const char kJavaDisabled[] = "java-disabled";
const char kPluginsDisabled[] = "plugins-disabled";
const char kUniversalAccessFromFileUrlsAllowed[] =
"universal-access-from-file-urls-allowed";
const char kFileAccessFromFileUrlsAllowed[] =
"file-access-from-file-urls-allowed";
const char kWebSecurityDisabled[] = "web-security-disabled";
const char kXssAuditorEnabled[] = "xss-auditor-enabled";
const char kImageLoadingDisabled[] = "image-load-disabled";
const char kShrinkStandaloneImagesToFit[] = "shrink-standalone-images-to-fit";
const char kSiteSpecificQuirksDisabled[] = "site-specific-quirks-disabled";
const char kTextAreaResizeDisabled[] = "text-area-resize-disabled";
const char kPageCacheDisabled[] = "page-cache-disabled";
const char kTabToLinksDisabled[] = "tab-to-links-disabled";
const char kHyperlinkAuditingDisabled[] = "hyperlink-auditing-disabled";
const char kUserStyleSheetEnabled[] = "user-style-sheet-enabled";
const char kUserStyleSheetLocation[] = "user-style-sheet-location";
const char kAuthorAndUserStylesDisabled[] = "author-and-user-styles-disabled";
const char kLocalStorageDisabled[] = "local-storage-disabled";
const char kDatabasesDisabled[] = "databases-disabled";
const char kApplicationCacheDisabled[] = "application-cache-disabled";
const char kWebglDisabled[] = "webgl-disabled";
const char kAcceleratedCompositingEnabled[] = "accelerated-compositing-enabled";
const char kThreadedCompositingEnabled[] = "threaded-compositing-enabled";
const char kAcceleratedLayersDisabled[] = "accelerated-layers-disabled";
const char kAcceleratedVideoDisabled[] = "accelerated-video-disabled";
const char kAcceledated2dCanvasDisabled[] = "accelerated-2d-canvas-disabled";
const char kAcceleratedPaintingDisabled[] = "accelerated-painting-disabled";
const char kAcceleratedFiltersDisabled[] = "accelerated-filters-disabled";
const char kAcceleratedPluginsDisabled[] = "accelerated-plugins-disabled";
const char kDeveloperToolsDisabled[] = "developer-tools-disabled";
const char kFullscreenEnabled[] = "fullscreen-enabled";
// Other attributes.
const char kProxyType[] = "proxy-type";
const char kProxyType_Direct[] = "direct";
const char kProxyType_Named[] = "named";
const char kProxyType_Pac[] = "pac";
const char kProxyConfig[] = "proxy-config";
} // namespace cefclient

View File

@@ -1,92 +0,0 @@
// 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.
// Defines all of the command line switches used by cefclient.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_
#pragma once
namespace cefclient {
// CefSettings attributes.
extern const char kMultiThreadedMessageLoop[];
extern const char kCachePath[];
extern const char kUserAgent[];
extern const char kProductVersion[];
extern const char kLocale[];
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_ErrorReport[];
extern const char kLogSeverity_Disable[];
extern const char kGraphicsImpl[];
extern const char kGraphicsImpl_Angle[];
extern const char kGraphicsImpl_AngleCmdBuffer[];
extern const char kGraphicsImpl_Desktop[];
extern const char kGraphicsImpl_DesktopCmdBuffer[];
extern const char kLocalStorageQuota[];
extern const char kSessionStorageQuota[];
extern const char kJavascriptFlags[];
extern const char kPackFilePath[];
extern const char kLocalesDirPath[];
extern const char kPackLoadingDisabled[];
// CefBrowserSettings attributes.
extern const char kDragDropDisabled[];
extern const char kLoadDropsDisabled[];
extern const char kHistoryDisabled[];
extern const char kRemoteFontsDisabled[];
extern const char kDefaultEncoding[];
extern const char kEncodingDetectorEnabled[];
extern const char kJavascriptDisabled[];
extern const char kJavascriptOpenWindowsDisallowed[];
extern const char kJavascriptCloseWindowsDisallowed[];
extern const char kJavascriptAccessClipboardDisallowed[];
extern const char kDomPasteDisabled[];
extern const char kCaretBrowsingDisabled[];
extern const char kJavaDisabled[];
extern const char kPluginsDisabled[];
extern const char kUniversalAccessFromFileUrlsAllowed[];
extern const char kFileAccessFromFileUrlsAllowed[];
extern const char kWebSecurityDisabled[];
extern const char kXssAuditorEnabled[];
extern const char kImageLoadingDisabled[];
extern const char kShrinkStandaloneImagesToFit[];
extern const char kSiteSpecificQuirksDisabled[];
extern const char kTextAreaResizeDisabled[];
extern const char kPageCacheDisabled[];
extern const char kTabToLinksDisabled[];
extern const char kHyperlinkAuditingDisabled[];
extern const char kUserStyleSheetEnabled[];
extern const char kUserStyleSheetLocation[];
extern const char kAuthorAndUserStylesDisabled[];
extern const char kLocalStorageDisabled[];
extern const char kDatabasesDisabled[];
extern const char kApplicationCacheDisabled[];
extern const char kWebglDisabled[];
extern const char kAcceleratedCompositingEnabled[];
extern const char kThreadedCompositingEnabled[];
extern const char kAcceleratedLayersDisabled[];
extern const char kAcceleratedVideoDisabled[];
extern const char kAcceledated2dCanvasDisabled[];
extern const char kAcceleratedPaintingDisabled[];
extern const char kAcceleratedFiltersDisabled[];
extern const char kAcceleratedPluginsDisabled[];
extern const char kDeveloperToolsDisabled[];
extern const char kFullscreenEnabled[];
// Other attributes.
extern const char kProxyType[];
extern const char kProxyType_Direct[];
extern const char kProxyType_Named[];
extern const char kProxyType_Pac[];
extern const char kProxyConfig[];
} // namespace cefclient
#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_

View File

@@ -1,767 +0,0 @@
// 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 "cefclient/cefclient.h"
#include <windows.h>
#include <commdlg.h>
#include <shellapi.h>
#include <direct.h>
#include <sstream>
#include <string>
#include "include/cef_app.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_runnable.h"
#include "cefclient/binding_test.h"
#include "cefclient/client_handler.h"
#include "cefclient/extension_test.h"
#include "cefclient/osrplugin_test.h"
#include "cefclient/plugin_test.h"
#include "cefclient/resource.h"
#include "cefclient/scheme_test.h"
#include "cefclient/string_util.h"
#include "cefclient/uiplugin_test.h"
#define MAX_LOADSTRING 100
#define MAX_URL_LENGTH 255
#define BUTTON_WIDTH 72
#define URLBAR_HEIGHT 24
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
char szWorkingDir[MAX_PATH]; // The current working directory
UINT uFindMsg; // Message identifier for find events.
HWND hFindDlg = NULL; // Handle for the find dialog.
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
// The global ClientHandler reference.
extern CefRefPtr<ClientHandler> g_handler;
#if defined(OS_WIN)
// Add Common Controls to the application manifest because it's required to
// support the default tooltip implementation.
#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") // NOLINT(whitespace/line_length)
#endif
// Program entry point function.
int APIENTRY wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow) {
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Retrieve the current working directory.
if (_getcwd(szWorkingDir, MAX_PATH) == NULL)
szWorkingDir[0] = 0;
// Parse command line arguments. The passed in values are ignored on Windows.
AppInitCommandLine(0, NULL);
CefSettings settings;
CefRefPtr<CefApp> app;
// Populate the settings based on command line arguments.
AppGetSettings(settings, app);
// Initialize CEF.
CefInitialize(settings, app);
// Register the internal client plugin.
InitPluginTest();
// Register the internal UI client plugin.
InitUIPluginTest();
// Register the internal OSR client plugin.
InitOSRPluginTest();
// Register the V8 extension handler.
InitExtensionTest();
// Register the scheme handler.
InitSchemeTest();
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_CEFCLIENT, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization
if (!InitInstance (hInstance, nCmdShow))
return FALSE;
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CEFCLIENT));
// Register the find event message.
uFindMsg = RegisterWindowMessage(FINDMSGSTRING);
int result = 0;
if (!settings.multi_threaded_message_loop) {
// Run the CEF message loop. This function will block until the application
// recieves a WM_QUIT message.
CefRunMessageLoop();
} else {
MSG msg;
// Run the application message loop.
while (GetMessage(&msg, NULL, 0, 0)) {
// Allow processing of find dialog messages.
if (hFindDlg && IsDialogMessage(hFindDlg, &msg))
continue;
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
result = static_cast<int>(msg.wParam);
}
// Shut down CEF.
CefShutdown();
return result;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this
// function so that the application will get 'well formed' small icons
// associated with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CEFCLIENT));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_CEFCLIENT);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) {
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0,
CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam) {
static HWND backWnd = NULL, forwardWnd = NULL, reloadWnd = NULL,
stopWnd = NULL, editWnd = NULL;
static WNDPROC editWndOldProc = NULL;
// Static members used for the find dialog.
static FINDREPLACE fr;
static WCHAR szFindWhat[80] = {0};
static WCHAR szLastFindWhat[80] = {0};
static bool findNext = false;
static bool lastMatchCase = false;
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
if (hWnd == editWnd) {
// Callback for the edit window
switch (message) {
case WM_CHAR:
if (wParam == VK_RETURN && g_handler.get()) {
// When the user hits the enter key load the URL
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
wchar_t strPtr[MAX_URL_LENGTH+1] = {0};
*((LPWORD)strPtr) = MAX_URL_LENGTH;
LRESULT strLen = SendMessage(hWnd, EM_GETLINE, 0, (LPARAM)strPtr);
if (strLen > 0) {
strPtr[strLen] = 0;
browser->GetMainFrame()->LoadURL(strPtr);
}
return 0;
}
}
return (LRESULT)CallWindowProc(editWndOldProc, hWnd, message, wParam,
lParam);
} else if (message == uFindMsg) {
// Find event.
LPFINDREPLACE lpfr = (LPFINDREPLACE)lParam;
if (lpfr->Flags & FR_DIALOGTERM) {
// The find dialog box has been dismissed so invalidate the handle and
// reset the search results.
hFindDlg = NULL;
if (g_handler.get()) {
g_handler->GetBrowser()->StopFinding(true);
szLastFindWhat[0] = 0;
findNext = false;
}
return 0;
}
if ((lpfr->Flags & FR_FINDNEXT) && g_handler.get()) {
// Search for the requested string.
bool matchCase = (lpfr->Flags & FR_MATCHCASE?true:false);
if (matchCase != lastMatchCase ||
(matchCase && wcsncmp(szFindWhat, szLastFindWhat,
sizeof(szLastFindWhat)/sizeof(WCHAR)) != 0) ||
(!matchCase && _wcsnicmp(szFindWhat, szLastFindWhat,
sizeof(szLastFindWhat)/sizeof(WCHAR)) != 0)) {
// The search string has changed, so reset the search results.
if (szLastFindWhat[0] != 0) {
g_handler->GetBrowser()->StopFinding(true);
findNext = false;
}
lastMatchCase = matchCase;
wcscpy_s(szLastFindWhat, sizeof(szLastFindWhat)/sizeof(WCHAR),
szFindWhat);
}
g_handler->GetBrowser()->Find(0, lpfr->lpstrFindWhat,
(lpfr->Flags & FR_DOWN)?true:false, matchCase, findNext);
if (!findNext)
findNext = true;
}
return 0;
} else {
// Callback for the main window
switch (message) {
case WM_CREATE: {
// Create the single static handler class instance
g_handler = new ClientHandler();
g_handler->SetMainHwnd(hWnd);
// Create the child windows used for navigation
RECT rect;
int x = 0;
GetClientRect(hWnd, &rect);
backWnd = CreateWindow(L"BUTTON", L"Back",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON
| WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT,
hWnd, (HMENU) IDC_NAV_BACK, hInst, 0);
x += BUTTON_WIDTH;
forwardWnd = CreateWindow(L"BUTTON", L"Forward",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON
| WS_DISABLED, x, 0, BUTTON_WIDTH,
URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_FORWARD,
hInst, 0);
x += BUTTON_WIDTH;
reloadWnd = CreateWindow(L"BUTTON", L"Reload",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON
| WS_DISABLED, x, 0, BUTTON_WIDTH,
URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_RELOAD,
hInst, 0);
x += BUTTON_WIDTH;
stopWnd = CreateWindow(L"BUTTON", L"Stop",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON
| WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT,
hWnd, (HMENU) IDC_NAV_STOP, hInst, 0);
x += BUTTON_WIDTH;
editWnd = CreateWindow(L"EDIT", 0,
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT |
ES_AUTOVSCROLL | ES_AUTOHSCROLL| WS_DISABLED,
x, 0, rect.right - BUTTON_WIDTH * 4,
URLBAR_HEIGHT, hWnd, 0, hInst, 0);
// Assign the edit window's WNDPROC to this function so that we can
// capture the enter key
editWndOldProc =
reinterpret_cast<WNDPROC>(GetWindowLongPtr(editWnd, GWLP_WNDPROC));
SetWindowLongPtr(editWnd, GWLP_WNDPROC,
reinterpret_cast<LONG_PTR>(WndProc));
g_handler->SetEditHwnd(editWnd);
g_handler->SetButtonHwnds(backWnd, forwardWnd, reloadWnd, stopWnd);
rect.top += URLBAR_HEIGHT;
CefWindowInfo info;
CefBrowserSettings settings;
// Populate the settings based on command line arguments.
AppGetBrowserSettings(settings);
// Initialize window info to the defaults for a child window
info.SetAsChild(hWnd, rect);
// Creat the new child browser window
CefBrowser::CreateBrowser(info,
static_cast<CefRefPtr<CefClient> >(g_handler),
"http://www.google.com", settings);
return 0;
}
case WM_COMMAND: {
CefRefPtr<CefBrowser> browser;
if (g_handler.get())
browser = g_handler->GetBrowser();
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId) {
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
return 0;
case IDM_EXIT:
DestroyWindow(hWnd);
return 0;
case ID_WARN_CONSOLEMESSAGE:
if (g_handler.get()) {
std::wstringstream ss;
ss << L"Console messages will be written to "
<< std::wstring(CefString(g_handler->GetLogFile()));
MessageBox(hWnd, ss.str().c_str(), L"Console Messages",
MB_OK | MB_ICONINFORMATION);
}
return 0;
case ID_WARN_DOWNLOADCOMPLETE:
case ID_WARN_DOWNLOADERROR:
if (g_handler.get()) {
std::wstringstream ss;
ss << L"File \"" <<
std::wstring(CefString(g_handler->GetLastDownloadFile())) <<
L"\" ";
if (wmId == ID_WARN_DOWNLOADCOMPLETE)
ss << L"downloaded successfully.";
else
ss << L"failed to download.";
MessageBox(hWnd, ss.str().c_str(), L"File Download",
MB_OK | MB_ICONINFORMATION);
}
return 0;
case ID_FIND:
if (!hFindDlg) {
// Create the find dialog.
ZeroMemory(&fr, sizeof(fr));
fr.lStructSize = sizeof(fr);
fr.hwndOwner = hWnd;
fr.lpstrFindWhat = szFindWhat;
fr.wFindWhatLen = sizeof(szFindWhat);
fr.Flags = FR_HIDEWHOLEWORD | FR_DOWN;
hFindDlg = FindText(&fr);
} else {
// Give focus to the existing find dialog.
::SetFocus(hFindDlg);
}
return 0;
case ID_PRINT:
if (browser.get())
browser->GetMainFrame()->Print();
return 0;
case IDC_NAV_BACK: // Back button
if (browser.get())
browser->GoBack();
return 0;
case IDC_NAV_FORWARD: // Forward button
if (browser.get())
browser->GoForward();
return 0;
case IDC_NAV_RELOAD: // Reload button
if (browser.get())
browser->Reload();
return 0;
case IDC_NAV_STOP: // Stop button
if (browser.get())
browser->StopLoad();
return 0;
case ID_TESTS_GETSOURCE: // Test the GetSource function
if (browser.get())
RunGetSourceTest(browser);
return 0;
case ID_TESTS_GETTEXT: // Test the GetText function
if (browser.get())
RunGetTextTest(browser);
return 0;
case ID_TESTS_JAVASCRIPT_BINDING: // Test the V8 binding handler
if (browser.get())
RunBindingTest(browser);
return 0;
case ID_TESTS_JAVASCRIPT_EXTENSION: // Test the V8 extension handler
if (browser.get())
RunExtensionTest(browser);
return 0;
case ID_TESTS_JAVASCRIPT_PERFORMANCE: // Test the V8 performance
if (browser.get())
RunExtensionPerfTest(browser);
return 0;
case ID_TESTS_JAVASCRIPT_EXECUTE: // Test execution of javascript
if (browser.get())
RunJavaScriptExecuteTest(browser);
return 0;
case ID_TESTS_JAVASCRIPT_INVOKE:
if (browser.get())
RunJavaScriptInvokeTest(browser);
return 0;
case ID_TESTS_PLUGIN: // Test the custom plugin
if (browser.get())
RunPluginTest(browser);
return 0;
case ID_TESTS_POPUP: // Test a popup window
if (browser.get())
RunPopupTest(browser);
return 0;
case ID_TESTS_TRANSPARENT_POPUP: // Test a transparent popup window
if (browser.get())
RunTransparentPopupTest(browser);
return 0;
case ID_TESTS_REQUEST: // Test a request
if (browser.get())
RunRequestTest(browser);
return 0;
case ID_TESTS_SCHEME_HANDLER: // Test the scheme handler
if (browser.get())
RunSchemeTest(browser);
return 0;
case ID_TESTS_UIAPP: // Test the UI app
if (browser.get())
RunUIPluginTest(browser);
return 0;
case ID_TESTS_OSRAPP: // Test the OSR app
if (browser.get())
RunOSRPluginTest(browser, false);
return 0;
case ID_TESTS_TRANSPARENT_OSRAPP: // Test the OSR app with transparency
if (browser.get())
RunOSRPluginTest(browser, true);
return 0;
case ID_TESTS_DOMACCESS: // Test DOM access
if (browser.get())
RunDOMAccessTest(browser);
return 0;
case ID_TESTS_LOCALSTORAGE: // Test localStorage
if (browser.get())
RunLocalStorageTest(browser);
return 0;
case ID_TESTS_ACCELERATED2DCANVAS: // Test accelerated 2d canvas
if (browser.get())
RunAccelerated2DCanvasTest(browser);
return 0;
case ID_TESTS_ACCELERATEDLAYERS: // Test accelerated layers
if (browser.get())
RunAcceleratedLayersTest(browser);
return 0;
case ID_TESTS_WEBGL: // Test WebGL
if (browser.get())
RunWebGLTest(browser);
return 0;
case ID_TESTS_HTML5VIDEO: // Test HTML5 video
if (browser.get())
RunHTML5VideoTest(browser);
return 0;
case ID_TESTS_DRAGDROP: // Test drag & drop
if (browser.get())
RunDragDropTest(browser);
return 0;
case ID_TESTS_XMLHTTPREQUEST: // Test XMLHttpRequest
if (browser.get())
RunXMLHTTPRequestTest(browser);
return 0;
case ID_TESTS_WEBURLREQUEST:
if (browser.get())
RunWebURLRequestTest(browser);
return 0;
case ID_TESTS_ZOOM_IN:
if (browser.get())
browser->SetZoomLevel(browser->GetZoomLevel() + 0.5);
return 0;
case ID_TESTS_ZOOM_OUT:
if (browser.get())
browser->SetZoomLevel(browser->GetZoomLevel() - 0.5);
return 0;
case ID_TESTS_ZOOM_RESET:
if (browser.get())
browser->SetZoomLevel(0.0);
return 0;
case ID_TESTS_DEVTOOLS_SHOW:
if (browser.get())
browser->ShowDevTools();
return 0;
case ID_TESTS_DEVTOOLS_CLOSE:
if (browser.get())
browser->CloseDevTools();
return 0;
case ID_TESTS_MODALDIALOG:
if (browser.get())
RunModalDialogTest(browser);
return 0;
case ID_TESTS_GETIMAGE:
if (browser.get())
RunGetImageTest(browser);
return 0;
}
break;
}
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
case WM_SETFOCUS:
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Pass focus to the browser window
PostMessage(g_handler->GetBrowserHwnd(), WM_SETFOCUS, wParam, NULL);
}
return 0;
case WM_SIZE:
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Resize the browser window and address bar to match the new frame
// window size
RECT rect;
GetClientRect(hWnd, &rect);
rect.top += URLBAR_HEIGHT;
int urloffset = rect.left + BUTTON_WIDTH * 4;
HDWP hdwp = BeginDeferWindowPos(1);
hdwp = DeferWindowPos(hdwp, editWnd, NULL, urloffset,
0, rect.right - urloffset, URLBAR_HEIGHT, SWP_NOZORDER);
hdwp = DeferWindowPos(hdwp, g_handler->GetBrowserHwnd(), NULL,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
SWP_NOZORDER);
EndDeferWindowPos(hdwp);
}
break;
case WM_ERASEBKGND:
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Dont erase the background if the browser window has been loaded
// (this avoids flashing)
return 0;
}
break;
case WM_CLOSE:
if (g_handler.get()) {
CefRefPtr<CefBrowser> browser = g_handler->GetBrowser();
if (browser.get()) {
// Let the browser window know we are about to destroy it.
browser->ParentWindowWillClose();
}
}
break;
case WM_DESTROY:
// The frame window has exited
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
UNREFERENCED_PARAMETER(lParam);
switch (message) {
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
// Global functions
std::string AppGetWorkingDirectory() {
return szWorkingDir;
}
void RunTransparentPopupTest(CefRefPtr<CefBrowser> browser) {
CefWindowInfo info;
CefBrowserSettings settings;
// Initialize window info to the defaults for a popup window
info.SetAsPopup(NULL, "TransparentPopup");
info.SetTransparentPainting(TRUE);
info.m_nWidth = 500;
info.m_nHeight = 500;
// Creat the popup browser window
CefBrowser::CreateBrowser(info,
static_cast<CefRefPtr<CefClient> >(g_handler),
"http://tests/transparency", settings);
}
namespace {
// Determine a temporary path for the bitmap file.
bool GetBitmapTempPath(LPWSTR szTempName) {
DWORD dwRetVal;
DWORD dwBufSize = 512;
TCHAR lpPathBuffer[512];
UINT uRetVal;
dwRetVal = GetTempPath(dwBufSize, // length of the buffer
lpPathBuffer); // buffer for path
if (dwRetVal > dwBufSize || (dwRetVal == 0))
return false;
// Create a temporary file.
uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
L"image", // temp file name prefix
0, // create unique name
szTempName); // buffer for name
if (uRetVal == 0)
return false;
size_t len = wcslen(szTempName);
wcscpy(szTempName + len - 3, L"bmp");
return true;
}
void UIT_RunGetImageTest(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
int width, height;
bool success = false;
// Retrieve the image size.
if (browser->GetSize(PET_VIEW, width, height)) {
void* bits;
// Populate the bitmap info header.
BITMAPINFOHEADER info;
info.biSize = sizeof(BITMAPINFOHEADER);
info.biWidth = width;
info.biHeight = -height; // minus means top-down bitmap
info.biPlanes = 1;
info.biBitCount = 32;
info.biCompression = BI_RGB; // no compression
info.biSizeImage = 0;
info.biXPelsPerMeter = 1;
info.biYPelsPerMeter = 1;
info.biClrUsed = 0;
info.biClrImportant = 0;
// Create the bitmap and retrieve the bit buffer.
HDC screen_dc = GetDC(NULL);
HBITMAP bitmap =
CreateDIBSection(screen_dc, reinterpret_cast<BITMAPINFO*>(&info),
DIB_RGB_COLORS, &bits, NULL, 0);
ReleaseDC(NULL, screen_dc);
// Read the image into the bit buffer.
if (bitmap && browser->GetImage(PET_VIEW, width, height, bits)) {
// Populate the bitmap file header.
BITMAPFILEHEADER file;
file.bfType = 0x4d42;
file.bfSize = sizeof(BITMAPFILEHEADER);
file.bfReserved1 = 0;
file.bfReserved2 = 0;
file.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
TCHAR temp_path[512];
if (GetBitmapTempPath(temp_path)) {
// Write the bitmap to file.
HANDLE file_handle =
CreateFile(temp_path, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, 0);
if (file_handle != INVALID_HANDLE_VALUE) {
DWORD bytes_written = 0;
WriteFile(file_handle, &file, sizeof(file), &bytes_written, 0);
WriteFile(file_handle, &info, sizeof(info), &bytes_written, 0);
WriteFile(file_handle, bits, width * height * 4, &bytes_written, 0);
CloseHandle(file_handle);
// Open the bitmap in the default viewer.
ShellExecute(NULL, L"open", temp_path, NULL, NULL, SW_SHOWNORMAL);
success = true;
}
}
}
DeleteObject(bitmap);
}
if (!success) {
browser->GetMainFrame()->ExecuteJavaScript(
"alert('Failed to create image!');",
browser->GetMainFrame()->GetURL(), 0);
}
}
} // namespace
void RunGetImageTest(CefRefPtr<CefBrowser> browser) {
// Execute the test function on the UI thread.
CefPostTask(TID_UI, NewCefRunnableFunction(UIT_RunGetImageTest, browser));
}

View File

@@ -1,359 +0,0 @@
// 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 "cefclient/client_handler.h"
#include <stdio.h>
#include <sstream>
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/binding_test.h"
#include "cefclient/cefclient.h"
#include "cefclient/download_handler.h"
#include "cefclient/string_util.h"
ClientHandler::ClientHandler()
: m_MainHwnd(NULL),
m_BrowserHwnd(NULL),
m_EditHwnd(NULL),
m_BackHwnd(NULL),
m_ForwardHwnd(NULL),
m_StopHwnd(NULL),
m_ReloadHwnd(NULL),
m_bFormElementHasFocus(false) {
}
ClientHandler::~ClientHandler() {
}
void ClientHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
AutoLock lock_scope(this);
if (!m_Browser.get()) {
// We need to keep the main child window, but not popup windows
m_Browser = browser;
m_BrowserHwnd = browser->GetWindowHandle();
}
}
bool ClientHandler::DoClose(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle()) {
// Since the main window contains the browser window, we need to close
// the parent window instead of the browser window.
CloseMainWindow();
// Return true here so that we can skip closing the browser window
// in this pass. (It will be destroyed due to the call to close
// the parent above.)
return true;
}
// A popup browser window is not contained in another window, so we can let
// these windows close by themselves.
return false;
}
void ClientHandler::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle()) {
// Free the browser pointer so that the browser can be destroyed
m_Browser = NULL;
}
}
void ClientHandler::OnLoadStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) {
// We've just started loading a page
SetLoading(true);
}
}
void ClientHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) {
// We've just finished loading a page
SetLoading(false);
CefRefPtr<CefDOMVisitor> visitor = GetDOMVisitor(frame->GetURL());
if (visitor.get())
frame->VisitDOM(visitor);
}
}
bool ClientHandler::OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& failedUrl,
CefString& errorText) {
REQUIRE_UI_THREAD();
if (errorCode == ERR_CACHE_MISS) {
// Usually caused by navigating to a page with POST data via back or
// forward buttons.
errorText = "<html><head><title>Expired Form Data</title></head>"
"<body><h1>Expired Form Data</h1>"
"<h2>Your form request has expired. "
"Click reload to re-submit the form data.</h2></body>"
"</html>";
} else {
// All other messages.
std::stringstream ss;
ss << "<html><head><title>Load Failed</title></head>"
"<body><h1>Load Failed</h1>"
"<h2>Load of URL " << std::string(failedUrl) <<
" failed with error code " << static_cast<int>(errorCode) <<
".</h2></body>"
"</html>";
errorText = ss.str();
}
return false;
}
bool ClientHandler::GetDownloadHandler(CefRefPtr<CefBrowser> browser,
const CefString& mimeType,
const CefString& fileName,
int64 contentLength,
CefRefPtr<CefDownloadHandler>& handler) {
REQUIRE_UI_THREAD();
// Create the handler for the file download.
handler = CreateDownloadHandler(this, fileName);
// Close the browser window if it is a popup with no other document contents.
if (browser->IsPopup() && !browser->HasDocument())
browser->CloseBrowser();
return true;
}
void ClientHandler::OnNavStateChange(CefRefPtr<CefBrowser> browser,
bool canGoBack,
bool canGoForward) {
REQUIRE_UI_THREAD();
SetNavState(canGoBack, canGoForward);
}
bool ClientHandler::OnConsoleMessage(CefRefPtr<CefBrowser> browser,
const CefString& message,
const CefString& source,
int line) {
REQUIRE_UI_THREAD();
bool first_message;
std::string logFile;
{
AutoLock lock_scope(this);
first_message = m_LogFile.empty();
if (first_message) {
std::stringstream ss;
ss << AppGetWorkingDirectory();
#if defined(OS_WIN)
ss << "\\";
#else
ss << "/";
#endif
ss << "console.log";
m_LogFile = ss.str();
}
logFile = m_LogFile;
}
FILE* file = fopen(logFile.c_str(), "a");
if (file) {
std::stringstream ss;
ss << "Message: " << std::string(message) << "\r\nSource: " <<
std::string(source) << "\r\nLine: " << line <<
"\r\n-----------------------\r\n";
fputs(ss.str().c_str(), file);
fclose(file);
if (first_message)
SendNotification(NOTIFY_CONSOLE_MESSAGE);
}
return false;
}
void ClientHandler::OnFocusedNodeChanged(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefDOMNode> node) {
REQUIRE_UI_THREAD();
// Set to true if a form element has focus.
m_bFormElementHasFocus = (node.get() && node->IsFormControlElement());
}
bool ClientHandler::OnKeyEvent(CefRefPtr<CefBrowser> browser,
KeyEventType type,
int code,
int modifiers,
bool isSystemKey,
bool isAfterJavaScript) {
REQUIRE_UI_THREAD();
if (isAfterJavaScript && !m_bFormElementHasFocus && code == 0x20) {
// Special handling for the space character if a form element does not have
// focus.
if (type == KEYEVENT_RAWKEYDOWN) {
browser->GetMainFrame()->ExecuteJavaScript(
"alert('You pressed the space bar!');", "", 0);
}
return true;
}
return false;
}
bool ClientHandler::GetPrintHeaderFooter(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefPrintInfo& printInfo,
const CefString& url,
const CefString& title,
int currentPage,
int maxPages,
CefString& topLeft,
CefString& topCenter,
CefString& topRight,
CefString& bottomLeft,
CefString& bottomCenter,
CefString& bottomRight) {
REQUIRE_UI_THREAD();
// Place the page title at top left
topLeft = title;
// Place the page URL at top right
topRight = url;
// Place "Page X of Y" at bottom center
std::stringstream strstream;
strstream << "Page " << currentPage << " of " << maxPages;
bottomCenter = strstream.str();
return false;
}
void ClientHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {
REQUIRE_UI_THREAD();
// Add the V8 bindings.
InitBindingTest(browser, frame, context->GetGlobal());
}
bool ClientHandler::OnDragStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDragData> dragData,
DragOperationsMask mask) {
REQUIRE_UI_THREAD();
// Forbid dragging of image files.
if (dragData->IsFile()) {
std::string fileName = dragData->GetFileName();
if (fileName.find(".png") != std::string::npos ||
fileName.find(".jpg") != std::string::npos ||
fileName.find(".gif") != std::string::npos)
return true;
}
return false;
}
bool ClientHandler::OnDragEnter(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDragData> dragData,
DragOperationsMask mask) {
REQUIRE_UI_THREAD();
// Forbid dragging of link URLs.
if (dragData->IsLink())
return true;
return false;
}
bool ClientHandler::OnBeforeScriptExtensionLoad(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& extensionName) {
return false;
}
void ClientHandler::NotifyDownloadComplete(const CefString& fileName) {
SetLastDownloadFile(fileName);
SendNotification(NOTIFY_DOWNLOAD_COMPLETE);
}
void ClientHandler::NotifyDownloadError(const CefString& fileName) {
SetLastDownloadFile(fileName);
SendNotification(NOTIFY_DOWNLOAD_ERROR);
}
void ClientHandler::SetMainHwnd(CefWindowHandle hwnd) {
AutoLock lock_scope(this);
m_MainHwnd = hwnd;
}
void ClientHandler::SetEditHwnd(CefWindowHandle hwnd) {
AutoLock lock_scope(this);
m_EditHwnd = hwnd;
}
void ClientHandler::SetButtonHwnds(CefWindowHandle backHwnd,
CefWindowHandle forwardHwnd,
CefWindowHandle reloadHwnd,
CefWindowHandle stopHwnd) {
AutoLock lock_scope(this);
m_BackHwnd = backHwnd;
m_ForwardHwnd = forwardHwnd;
m_ReloadHwnd = reloadHwnd;
m_StopHwnd = stopHwnd;
}
std::string ClientHandler::GetLogFile() {
AutoLock lock_scope(this);
return m_LogFile;
}
void ClientHandler::SetLastDownloadFile(const std::string& fileName) {
AutoLock lock_scope(this);
m_LastDownloadFile = fileName;
}
std::string ClientHandler::GetLastDownloadFile() {
AutoLock lock_scope(this);
return m_LastDownloadFile;
}
void ClientHandler::AddDOMVisitor(const std::string& path,
CefRefPtr<CefDOMVisitor> visitor) {
AutoLock lock_scope(this);
DOMVisitorMap::iterator it = m_DOMVisitors.find(path);
if (it == m_DOMVisitors.end())
m_DOMVisitors.insert(std::make_pair(path, visitor));
else
it->second = visitor;
}
CefRefPtr<CefDOMVisitor> ClientHandler::GetDOMVisitor(const std::string& path) {
AutoLock lock_scope(this);
DOMVisitorMap::iterator it = m_DOMVisitors.find(path);
if (it != m_DOMVisitors.end())
return it->second;
return NULL;
}

View File

@@ -1,242 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_
#define CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_
#pragma once
#include <map>
#include <string>
#include "include/cef_client.h"
#include "cefclient/download_handler.h"
#include "cefclient/util.h"
// Define this value to redirect all popup URLs to the main application browser
// window.
// #define TEST_REDIRECT_POPUP_URLS
// ClientHandler implementation.
class ClientHandler : public CefClient,
public CefLifeSpanHandler,
public CefLoadHandler,
public CefRequestHandler,
public CefDisplayHandler,
public CefFocusHandler,
public CefKeyboardHandler,
public CefPrintHandler,
public CefV8ContextHandler,
public CefDragHandler,
public CefPermissionHandler,
public DownloadListener {
public:
ClientHandler();
virtual ~ClientHandler();
// CefClient methods
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefRequestHandler> GetRequestHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefFocusHandler> GetFocusHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefKeyboardHandler> GetKeyboardHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefPrintHandler> GetPrintHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefV8ContextHandler> GetV8ContextHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefDragHandler> GetDragHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefPermissionHandler> GetPermissionHandler() OVERRIDE {
return this;
}
// CefLifeSpanHandler methods
virtual bool OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
const CefString& url,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings) OVERRIDE;
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefLoadHandler methods
virtual void OnLoadStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame) OVERRIDE;
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE;
virtual bool OnLoadError(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
ErrorCode errorCode,
const CefString& failedUrl,
CefString& errorText) OVERRIDE;
// CefRequestHandler methods
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefRequest> request,
CefString& redirectUrl,
CefRefPtr<CefStreamReader>& resourceStream,
CefRefPtr<CefResponse> response,
int loadFlags) OVERRIDE;
virtual bool GetDownloadHandler(CefRefPtr<CefBrowser> browser,
const CefString& mimeType,
const CefString& fileName,
int64 contentLength,
CefRefPtr<CefDownloadHandler>& handler)
OVERRIDE;
// CefDisplayHandler methods
virtual void OnNavStateChange(CefRefPtr<CefBrowser> browser,
bool canGoBack,
bool canGoForward) OVERRIDE;
virtual void OnAddressChange(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& url) OVERRIDE;
virtual void OnTitleChange(CefRefPtr<CefBrowser> browser,
const CefString& title) OVERRIDE;
virtual bool OnConsoleMessage(CefRefPtr<CefBrowser> browser,
const CefString& message,
const CefString& source,
int line) OVERRIDE;
// CefFocusHandler methods.
virtual void OnFocusedNodeChanged(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefDOMNode> node) OVERRIDE;
// CefKeyboardHandler methods.
virtual bool OnKeyEvent(CefRefPtr<CefBrowser> browser,
KeyEventType type,
int code,
int modifiers,
bool isSystemKey,
bool isAfterJavaScript) OVERRIDE;
// CefPrintHandler methods.
virtual bool GetPrintHeaderFooter(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefPrintInfo& printInfo,
const CefString& url,
const CefString& title,
int currentPage,
int maxPages,
CefString& topLeft,
CefString& topCenter,
CefString& topRight,
CefString& bottomLeft,
CefString& bottomCenter,
CefString& bottomRight) OVERRIDE;
// CefV8ContextHandler methods
virtual void OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) OVERRIDE;
// CefDragHandler methods.
virtual bool OnDragStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDragData> dragData,
DragOperationsMask mask) OVERRIDE;
virtual bool OnDragEnter(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDragData> dragData,
DragOperationsMask mask) OVERRIDE;
// CefPermissionHandler methods.
virtual bool OnBeforeScriptExtensionLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& extensionName) OVERRIDE;
// DownloadListener methods
virtual void NotifyDownloadComplete(const CefString& fileName) OVERRIDE;
virtual void NotifyDownloadError(const CefString& fileName) OVERRIDE;
void SetMainHwnd(CefWindowHandle hwnd);
CefWindowHandle GetMainHwnd() { return m_MainHwnd; }
void SetEditHwnd(CefWindowHandle hwnd);
void SetButtonHwnds(CefWindowHandle backHwnd,
CefWindowHandle forwardHwnd,
CefWindowHandle reloadHwnd,
CefWindowHandle stopHwnd);
CefRefPtr<CefBrowser> GetBrowser() { return m_Browser; }
CefWindowHandle GetBrowserHwnd() { return m_BrowserHwnd; }
std::string GetLogFile();
void SetLastDownloadFile(const std::string& fileName);
std::string GetLastDownloadFile();
// DOM visitors will be called after the associated path is loaded.
void AddDOMVisitor(const std::string& path, CefRefPtr<CefDOMVisitor> visitor);
CefRefPtr<CefDOMVisitor> GetDOMVisitor(const std::string& path);
// Send a notification to the application. Notifications should not block the
// caller.
enum NotificationType {
NOTIFY_CONSOLE_MESSAGE,
NOTIFY_DOWNLOAD_COMPLETE,
NOTIFY_DOWNLOAD_ERROR,
};
void SendNotification(NotificationType type);
void CloseMainWindow();
protected:
void SetLoading(bool isLoading);
void SetNavState(bool canGoBack, bool canGoForward);
// The child browser window
CefRefPtr<CefBrowser> m_Browser;
// The main frame window handle
CefWindowHandle m_MainHwnd;
// The child browser window handle
CefWindowHandle m_BrowserHwnd;
// The edit window handle
CefWindowHandle m_EditHwnd;
// The button window handles
CefWindowHandle m_BackHwnd;
CefWindowHandle m_ForwardHwnd;
CefWindowHandle m_StopHwnd;
CefWindowHandle m_ReloadHwnd;
// Support for logging.
std::string m_LogFile;
// Support for downloading files.
std::string m_LastDownloadFile;
// Support for DOM visitors.
typedef std::map<std::string, CefRefPtr<CefDOMVisitor> > DOMVisitorMap;
DOMVisitorMap m_DOMVisitors;
// True if a form element currently has focus
bool m_bFormElementHasFocus;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientHandler);
// Include the default locking implementation.
IMPLEMENT_LOCKING(ClientHandler);
};
#endif // CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_

View File

@@ -1,117 +0,0 @@
// 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 <gtk/gtk.h>
#include <string>
#include "cefclient/client_handler.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
// ClientHandler::ClientLifeSpanHandler implementation
bool ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
const CefString& url,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings) {
REQUIRE_UI_THREAD();
return false;
}
bool ClientHandler::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefRequest> request,
CefString& redirectUrl,
CefRefPtr<CefStreamReader>& resourceStream,
CefRefPtr<CefResponse> response,
int loadFlags) {
REQUIRE_IO_THREAD();
std::string url = request->GetURL();
if (url == "http://tests/request") {
// Show the request contents
std::string dump;
DumpRequestContents(request, dump);
resourceStream = CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(dump.c_str())),
dump.size());
response->SetMimeType("text/plain");
response->SetStatus(200);
} else if (strstr(url.c_str(), "/ps_logo2.png") != NULL) {
// Any time we find "ps_logo2.png" in the URL substitute in our own image
resourceStream = GetBinaryResourceReader("logo.png");
response->SetMimeType("image/png");
response->SetStatus(200);
} else if (url == "http://tests/localstorage") {
// Show the localstorage contents
resourceStream = GetBinaryResourceReader("localstorage.html");
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/xmlhttprequest") {
// Show the xmlhttprequest HTML contents
resourceStream = GetBinaryResourceReader("xmlhttprequest.html");
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/domaccess") {
// Show the domaccess HTML contents
resourceStream = GetBinaryResourceReader("domaccess.html");
response->SetMimeType("text/html");
response->SetStatus(200);
}
return false;
}
void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& url) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) {
// Set the edit window text
std::string urlStr(url);
gtk_entry_set_text(GTK_ENTRY(m_EditHwnd), urlStr.c_str());
}
}
void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,
const CefString& title) {
REQUIRE_UI_THREAD();
GtkWidget* window =
gtk_widget_get_ancestor(GTK_WIDGET(browser->GetWindowHandle()),
GTK_TYPE_WINDOW);
std::string titleStr(title);
gtk_window_set_title(GTK_WINDOW(window), titleStr.c_str());
}
void ClientHandler::SendNotification(NotificationType type) {
// TODO(port): Implement this method.
}
void ClientHandler::SetLoading(bool isLoading) {
if (isLoading)
gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), true);
else
gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), false);
}
void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) {
if (canGoBack)
gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), true);
else
gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), false);
if (canGoForward)
gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), true);
else
gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), false);
}
void ClientHandler::CloseMainWindow() {
// TODO(port): Close main window.
}

View File

@@ -1,141 +0,0 @@
// 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.
#import <Cocoa/Cocoa.h>
#include "cefclient/client_handler.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/cefclient.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
#ifdef TEST_REDIRECT_POPUP_URLS
#include "cefclient/client_popup_handler.h"
#endif
// ClientHandler::ClientLifeSpanHandler implementation
bool ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
const CefString& url,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings) {
REQUIRE_UI_THREAD();
#ifdef TEST_REDIRECT_POPUP_URLS
std::string urlStr = url;
if (urlStr.find("chrome-devtools:") == std::string::npos) {
// Show all popup windows excluding DevTools in the current window.
windowInfo.m_bHidden = true;
client = new ClientPopupHandler(m_Browser);
}
#endif // TEST_REDIRECT_POPUP_URLS
return false;
}
bool ClientHandler::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefRequest> request,
CefString& redirectUrl,
CefRefPtr<CefStreamReader>& resourceStream,
CefRefPtr<CefResponse> response,
int loadFlags) {
REQUIRE_IO_THREAD();
std::string url = request->GetURL();
if (url == "http://tests/request") {
// Show the request contents
std::string dump;
DumpRequestContents(request, dump);
resourceStream = CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(dump.c_str())),
dump.size());
response->SetMimeType("text/plain");
response->SetStatus(200);
} else if (strstr(url.c_str(), "/ps_logo2.png") != NULL) {
// Any time we find "ps_logo2.png" in the URL substitute in our own image
resourceStream = GetBinaryResourceReader("logo.png");
response->SetMimeType("image/png");
response->SetStatus(200);
} else if (url == "http://tests/localstorage") {
// Show the localstorage contents
resourceStream = GetBinaryResourceReader("localstorage.html");
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/xmlhttprequest") {
// Show the xmlhttprequest HTML contents
resourceStream = GetBinaryResourceReader("xmlhttprequest.html");
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/domaccess") {
// Show the domaccess HTML contents
resourceStream = GetBinaryResourceReader("domaccess.html");
response->SetMimeType("text/html");
response->SetStatus(200);
}
return false;
}
void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& url) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) {
// Set the edit window text
NSTextField* textField = (NSTextField*)m_EditHwnd;
std::string urlStr(url);
NSString* str = [NSString stringWithUTF8String:urlStr.c_str()];
[textField setStringValue:str];
}
}
void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,
const CefString& title) {
REQUIRE_UI_THREAD();
// Set the frame window title bar
NSView* view = (NSView*)browser->GetWindowHandle();
NSWindow* window = [view window];
std::string titleStr(title);
NSString* str = [NSString stringWithUTF8String:titleStr.c_str()];
[window setTitle:str];
}
void ClientHandler::SendNotification(NotificationType type) {
SEL sel = nil;
switch(type) {
case NOTIFY_CONSOLE_MESSAGE:
sel = @selector(notifyConsoleMessage:);
break;
case NOTIFY_DOWNLOAD_COMPLETE:
sel = @selector(notifyDownloadComplete:);
break;
case NOTIFY_DOWNLOAD_ERROR:
sel = @selector(notifyDownloadError:);
break;
}
if (sel == nil)
return;
NSWindow* window = [AppGetMainHwnd() window];
NSObject* delegate = [window delegate];
[delegate performSelectorOnMainThread:sel withObject:nil waitUntilDone:NO];
}
void ClientHandler::SetLoading(bool isLoading) {
// TODO(port): Change button status.
}
void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) {
// TODO(port): Change button status.
}
void ClientHandler::CloseMainWindow() {
// TODO(port): Close window
}

View File

@@ -1,180 +0,0 @@
// 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 "cefclient/client_handler.h"
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/resource.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
#ifdef TEST_REDIRECT_POPUP_URLS
#include "cefclient/client_popup_handler.h"
#endif
bool ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
const CefString& url,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings) {
REQUIRE_UI_THREAD();
#ifdef TEST_REDIRECT_POPUP_URLS
std::string urlStr = url;
if (urlStr.find("chrome-devtools:") == std::string::npos) {
// Show all popup windows excluding DevTools in the current window.
windowInfo.m_dwStyle &= ~WS_VISIBLE;
client = new ClientPopupHandler(m_Browser);
}
#endif // TEST_REDIRECT_POPUP_URLS
return false;
}
bool ClientHandler::OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefRequest> request,
CefString& redirectUrl,
CefRefPtr<CefStreamReader>& resourceStream,
CefRefPtr<CefResponse> response,
int loadFlags) {
REQUIRE_IO_THREAD();
std::string url = request->GetURL();
if (url == "http://tests/request") {
// Show the request contents
std::string dump;
DumpRequestContents(request, dump);
resourceStream = CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(dump.c_str())),
dump.size());
response->SetMimeType("text/plain");
response->SetStatus(200);
} else if (strstr(url.c_str(), "/ps_logo2.png") != NULL) {
// Any time we find "ps_logo2.png" in the URL substitute in our own image
resourceStream = GetBinaryResourceReader(IDS_LOGO);
response->SetMimeType("image/png");
response->SetStatus(200);
} else if (url == "http://tests/uiapp") {
// Show the uiapp contents
resourceStream = GetBinaryResourceReader(IDS_UIPLUGIN);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/osrapp") {
// Show the osrapp contents
resourceStream = GetBinaryResourceReader(IDS_OSRPLUGIN);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/localstorage") {
// Show the localstorage contents
resourceStream = GetBinaryResourceReader(IDS_LOCALSTORAGE);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/xmlhttprequest") {
// Show the xmlhttprequest HTML contents
resourceStream = GetBinaryResourceReader(IDS_XMLHTTPREQUEST);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/domaccess") {
// Show the domaccess HTML contents
resourceStream = GetBinaryResourceReader(IDS_DOMACCESS);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (strstr(url.c_str(), "/logoball.png") != NULL) {
// Load the "logoball.png" image resource.
resourceStream = GetBinaryResourceReader(IDS_LOGOBALL);
response->SetMimeType("image/png");
response->SetStatus(200);
} else if (url == "http://tests/modalmain") {
resourceStream = GetBinaryResourceReader(IDS_MODALMAIN);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/modaldialog") {
resourceStream = GetBinaryResourceReader(IDS_MODALDIALOG);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/transparency") {
resourceStream = GetBinaryResourceReader(IDS_TRANSPARENCY);
response->SetMimeType("text/html");
response->SetStatus(200);
} else if (url == "http://tests/plugin") {
std::string html =
"<html><body>\n"
"Client Plugin loaded by Mime Type:<br>\n"
"<embed type=\"application/x-client-plugin\" width=600 height=40>\n"
"<br><br>Client Plugin loaded by File Extension:<br>\n"
"<embed src=\"test.xcp\" width=600 height=40>\n"
// Add some extra space below the plugin to allow scrolling.
"<div style=\"height:1000px;\">&nbsp;</div>\n"
"</body></html>";
resourceStream = CefStreamReader::CreateForData(
static_cast<void*>(const_cast<char*>(html.c_str())),
html.size());
response->SetMimeType("text/html");
response->SetStatus(200);
}
return false;
}
void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& url) {
REQUIRE_UI_THREAD();
if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) {
// Set the edit window text
SetWindowText(m_EditHwnd, std::wstring(url).c_str());
}
}
void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,
const CefString& title) {
REQUIRE_UI_THREAD();
// Set the frame window title bar
CefWindowHandle hwnd = browser->GetWindowHandle();
if (m_BrowserHwnd == hwnd) {
// The frame window will be the parent of the browser window
hwnd = GetParent(hwnd);
}
SetWindowText(hwnd, std::wstring(title).c_str());
}
void ClientHandler::SendNotification(NotificationType type) {
UINT id;
switch (type) {
case NOTIFY_CONSOLE_MESSAGE:
id = ID_WARN_CONSOLEMESSAGE;
break;
case NOTIFY_DOWNLOAD_COMPLETE:
id = ID_WARN_DOWNLOADCOMPLETE;
break;
case NOTIFY_DOWNLOAD_ERROR:
id = ID_WARN_DOWNLOADERROR;
break;
default:
return;
}
PostMessage(m_MainHwnd, WM_COMMAND, id, 0);
}
void ClientHandler::SetLoading(bool isLoading) {
ASSERT(m_EditHwnd != NULL && m_ReloadHwnd != NULL && m_StopHwnd != NULL);
EnableWindow(m_EditHwnd, TRUE);
EnableWindow(m_ReloadHwnd, !isLoading);
EnableWindow(m_StopHwnd, isLoading);
}
void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) {
ASSERT(m_BackHwnd != NULL && m_ForwardHwnd != NULL);
EnableWindow(m_BackHwnd, canGoBack);
EnableWindow(m_ForwardHwnd, canGoForward);
}
void ClientHandler::CloseMainWindow() {
::PostMessage(m_MainHwnd, WM_CLOSE, 0, 0);
}

View File

@@ -1,30 +0,0 @@
// 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 "cefclient/client_popup_handler.h"
#include "include/cef_frame.h"
#include "cefclient/util.h"
ClientPopupHandler::ClientPopupHandler(CefRefPtr<CefBrowser> parentBrowser)
: m_ParentBrowser(parentBrowser) {
ASSERT(m_ParentBrowser.get());
}
ClientPopupHandler::~ClientPopupHandler() {
}
bool ClientPopupHandler::OnBeforeBrowse(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request,
NavType navType,
bool isRedirect) {
REQUIRE_UI_THREAD();
// Load the request in the parent browser window.
m_ParentBrowser->GetMainFrame()->LoadRequest(request);
browser->CloseBrowser();
m_ParentBrowser = NULL;
return true;
}

View File

@@ -1,39 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_CLIENT_POPUP_HANDLER_H_
#define CEF_TESTS_CEFCLIENT_CLIENT_POPUP_HANDLER_H_
#pragma once
#include "include/cef_browser.h"
#include "include/cef_client.h"
#include "include/cef_request_handler.h"
// Handler for popup windows that loads the request in an existing browser
// window.
class ClientPopupHandler : public CefClient,
public CefRequestHandler {
public:
explicit ClientPopupHandler(CefRefPtr<CefBrowser> parentBrowser);
virtual ~ClientPopupHandler();
// CefClient methods
virtual CefRefPtr<CefRequestHandler> GetRequestHandler() OVERRIDE {
return this;
}
// CefRequestHandler methods
virtual bool OnBeforeBrowse(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request,
NavType navType,
bool isRedirect) OVERRIDE;
protected:
CefRefPtr<CefBrowser> m_ParentBrowser;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientPopupHandler);
};
#endif // CEF_TESTS_CEFCLIENT_CLIENT_POPUP_HANDLER_H_

View File

@@ -1,189 +0,0 @@
// Copyright (c) 2008 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cefclient/clientplugin.h"
#if defined(OS_WIN)
// Initialized in NP_Initialize.
NPNetscapeFuncs* g_browser = NULL;
namespace {
NPError NPP_ClientNew(NPMIMEType plugin_type, NPP instance, uint16_t mode,
int16_t argc, char* argn[], char* argv[], NPSavedData* saved) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
ClientPlugin* plugin_impl = new ClientPlugin(mode);
plugin_impl->Initialize(GetModuleHandle(NULL), instance, plugin_type, argc,
argn, argv);
instance->pdata = reinterpret_cast<void*>(plugin_impl);
return NPERR_NO_ERROR;
}
NPError NPP_ClientDestroy(NPP instance, NPSavedData** save) {
ClientPlugin* plugin_impl = reinterpret_cast<ClientPlugin*>(instance->pdata);
if (plugin_impl) {
plugin_impl->Shutdown();
delete plugin_impl;
}
return NPERR_NO_ERROR;
}
NPError NPP_ClientSetWindow(NPP instance, NPWindow* window_info) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
if (window_info == NULL)
return NPERR_GENERIC_ERROR;
ClientPlugin* plugin_impl = reinterpret_cast<ClientPlugin*>(instance->pdata);
if (plugin_impl == NULL)
return NPERR_GENERIC_ERROR;
HWND window_handle = reinterpret_cast<HWND>(window_info->window);
if (!plugin_impl->SetWindow(window_handle)) {
delete plugin_impl;
return NPERR_GENERIC_ERROR;
}
return NPERR_NO_ERROR;
}
} // namespace
NPError API_CALL NP_ClientGetEntryPoints(NPPluginFuncs* pFuncs) {
pFuncs->newp = NPP_ClientNew;
pFuncs->destroy = NPP_ClientDestroy;
pFuncs->setwindow = NPP_ClientSetWindow;
return NPERR_NO_ERROR;
}
NPError API_CALL NP_ClientInitialize(NPNetscapeFuncs* pFuncs) {
g_browser = pFuncs;
return NPERR_NO_ERROR;
}
NPError API_CALL NP_ClientShutdown(void) {
g_browser = NULL;
return NPERR_NO_ERROR;
}
// ClientPlugin Implementation
ClientPlugin::ClientPlugin(int16 mode)
: mode_(mode) {
}
ClientPlugin::~ClientPlugin() {
}
bool ClientPlugin::Initialize(HINSTANCE module_handle, NPP instance,
NPMIMEType mime_type, int16 argc, char* argn[],
char* argv[]) {
RefreshDisplay();
return true;
}
bool ClientPlugin::SetWindow(HWND parent_window) {
if (!::IsWindow(parent_window)) {
// No window created yet. Ignore this call.
if (!IsWindow())
return true;
// Parent window has been destroyed.
Shutdown();
return true;
}
RECT parent_rect;
if (IsWindow()) {
::GetClientRect(parent_window, &parent_rect);
SetWindowPos(NULL, &parent_rect, SWP_SHOWWINDOW);
return true;
}
// First time in -- no window created by plugin yet.
::GetClientRect(parent_window, &parent_rect);
Create(parent_window, parent_rect, NULL, WS_CHILD | WS_BORDER);
UpdateWindow();
ShowWindow(SW_SHOW);
return true;
}
void ClientPlugin::Shutdown() {
if (IsWindow()) {
DestroyWindow();
}
}
LRESULT ClientPlugin::OnPaint(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled) {
PAINTSTRUCT paint_struct;
BeginPaint(&paint_struct);
Paint(paint_struct.hdc);
EndPaint(&paint_struct);
return 0;
}
// PrintClient is necessary to support off-screen rendering.
LRESULT ClientPlugin::OnPrintClient(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled) {
Paint(reinterpret_cast<HDC>(wparam));
return 0;
}
LRESULT ClientPlugin::OnEraseBackGround(UINT message, WPARAM wparam,
LPARAM lparam, BOOL& handled) {
HDC paint_device_context = reinterpret_cast<HDC>(wparam);
RECT erase_rect;
GetClipBox(paint_device_context, &erase_rect);
HBRUSH brush = CreateSolidBrush(RGB(0, 255, 0));
FillRect(paint_device_context, &erase_rect, brush);
DeleteObject(brush);
return 1;
}
LRESULT ClientPlugin::OnLButtonDown(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled) {
MessageBox(L"You clicked on the client plugin!", L"Client Plugin", MB_OK);
return 0;
}
void ClientPlugin::RefreshDisplay() {
if (!IsWindow())
return;
InvalidateRect(NULL, TRUE);
UpdateWindow();
}
void ClientPlugin::Paint(HDC hdc) {
static LPCWSTR text = L"Left click in the green area for a message box!";
RECT client_rect;
GetClientRect(&client_rect);
int old_mode = SetBkMode(hdc, TRANSPARENT);
COLORREF old_color = SetTextColor(hdc, RGB(0, 0, 255));
RECT text_rect = client_rect;
DrawText(hdc, text, -1, &text_rect, DT_CENTER | DT_CALCRECT);
client_rect.top = ((client_rect.bottom - client_rect.top)
- (text_rect.bottom - text_rect.top)) / 2;
DrawText(hdc, text, -1, &client_rect, DT_CENTER);
SetBkMode(hdc, old_mode);
SetTextColor(hdc, old_color);
}
#endif // OS_WIN

View File

@@ -1,103 +0,0 @@
// Copyright (c) 2008 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Portions of this implementation are borrowed from webkit\default_plugin\
// plugin_impl.h
#ifndef CEF_TESTS_CEFCLIENT_CLIENTPLUGIN_H_
#define CEF_TESTS_CEFCLIENT_CLIENTPLUGIN_H_
#pragma once
#include "include/internal/cef_types.h"
#if defined(OS_WIN)
#include <atlbase.h> // NOLINT(build/include_order)
#include <atlwin.h> // NOLINT(build/include_order)
#include "include/cef_nplugin.h"
extern NPNetscapeFuncs* g_browser;
NPError API_CALL NP_ClientGetEntryPoints(NPPluginFuncs* pFuncs);
NPError API_CALL NP_ClientInitialize(NPNetscapeFuncs* pFuncs);
NPError API_CALL NP_ClientShutdown(void);
// Provides the client plugin functionality.
class ClientPlugin : public CWindowImpl<ClientPlugin> {
public:
// mode is the plugin instantiation mode, i.e. whether it is a full
// page plugin (NP_FULL) or an embedded plugin (NP_EMBED)
explicit ClientPlugin(int16 mode);
virtual ~ClientPlugin();
BEGIN_MSG_MAP(ClientPlugin)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackGround)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_PRINTCLIENT, OnPrintClient)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
END_MSG_MAP()
// Initializes the plugin with the instance information, mime type
// and the list of parameters passed down to the plugin from the webpage.
//
// Parameters:
// module_handle
// The handle to the dll in which this object is instantiated.
// instance
// The plugins opaque instance handle.
// mime_type
// Identifies the third party plugin which would be eventually installed.
// argc
// Indicates the count of arguments passed in from the webpage.
// argv
// Pointer to the arguments.
// Returns true on success.
bool Initialize(HINSTANCE module_handle, NPP instance, NPMIMEType mime_type,
int16 argc, char* argn[], char* argv[]);
// Displays the default plugin UI.
//
// Parameters:
// parent_window
// Handle to the parent window.
bool SetWindow(HWND parent_window);
// Destroys the install dialog and the plugin window.
void Shutdown();
HWND window() const { return m_hWnd; }
// Getter for the NPP instance member.
const NPP instance() const {
return instance_;
}
protected:
// Window message handlers.
LRESULT OnPaint(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled);
LRESULT OnPrintClient(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled);
LRESULT OnEraseBackGround(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled);
LRESULT OnLButtonDown(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled);
// Enables the plugin window if required and initiates an update of the
// the plugin window.
void RefreshDisplay();
void Paint(HDC hdc);
private:
// The plugins opaque instance handle
NPP instance_;
// The plugin instantiation mode (NP_FULL or NP_EMBED)
int16 mode_;
};
#endif // OS_WIN
#endif // CEF_TESTS_CEFCLIENT_CLIENTPLUGIN_H_

View File

@@ -1,210 +0,0 @@
// 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 "cefclient/download_handler.h"
#include <stdio.h>
#include <sstream>
#include <vector>
#include "include/cef_download_handler.h"
#include "include/cef_runnable.h"
#include "cefclient/util.h"
#if defined(OS_WIN)
#include <windows.h> // NOLINT(build/include_order)
#include <shlobj.h> // NOLINT(build/include_order)
#include <shlwapi.h> // NOLINT(build/include_order)
#endif // OS_WIN
// Implementation of the CefDownloadHandler interface.
class ClientDownloadHandler : public CefDownloadHandler {
public:
ClientDownloadHandler(CefRefPtr<DownloadListener> listener,
const CefString& fileName)
: listener_(listener), filename_(fileName), file_(NULL) {
}
~ClientDownloadHandler() {
ASSERT(pending_data_.empty());
ASSERT(file_ == NULL);
if (!pending_data_.empty()) {
// Delete remaining pending data.
std::vector<std::vector<char>*>::iterator it = pending_data_.begin();
for (; it != pending_data_.end(); ++it)
delete (*it);
}
if (file_) {
// Close the dangling file pointer on the FILE thread.
CefPostTask(TID_FILE,
NewCefRunnableFunction(&ClientDownloadHandler::CloseDanglingFile,
file_));
// Notify the listener that the download failed.
listener_->NotifyDownloadError(filename_);
}
}
// --------------------------------------------------
// The following methods are called on the UI thread.
// --------------------------------------------------
void Initialize() {
// Open the file on the FILE thread.
CefPostTask(TID_FILE,
NewCefRunnableMethod(this, &ClientDownloadHandler::OnOpen));
}
// A portion of the file contents have been received. This method will be
// called multiple times until the download is complete. Return |true| to
// continue receiving data and |false| to cancel.
virtual bool ReceivedData(void* data, int data_size) {
REQUIRE_UI_THREAD();
if (data_size == 0)
return true;
// Create a new vector for the data.
std::vector<char>* buffer = new std::vector<char>(data_size);
memcpy(&(*buffer)[0], data, data_size);
// Add the new data vector to the pending data queue.
{
AutoLock lock_scope(this);
pending_data_.push_back(buffer);
}
// Write data to file on the FILE thread.
CefPostTask(TID_FILE,
NewCefRunnableMethod(this, &ClientDownloadHandler::OnReceivedData));
return true;
}
// The download is complete.
virtual void Complete() {
REQUIRE_UI_THREAD();
// Flush and close the file on the FILE thread.
CefPostTask(TID_FILE,
NewCefRunnableMethod(this, &ClientDownloadHandler::OnComplete));
}
// ----------------------------------------------------
// The following methods are called on the FILE thread.
// ----------------------------------------------------
void OnOpen() {
REQUIRE_FILE_THREAD();
if (file_)
return;
#if defined(OS_WIN)
TCHAR szFolderPath[MAX_PATH];
// Save the file in the user's "My Documents" folder.
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE,
NULL, 0, szFolderPath))) {
std::wstring fileNameStr = filename_;
LPWSTR name = PathFindFileName(fileNameStr.c_str());
LPWSTR ext = PathFindExtension(fileNameStr.c_str());
int ct = 0;
std::wstringstream ss;
if (ext) {
name[ext-name] = 0;
ext++;
}
// Make sure the file name is unique.
do {
if (ct > 0)
ss.str(L"");
ss << szFolderPath << L"\\" << name;
if (ct > 0)
ss << L" (" << ct << L")";
if (ext)
ss << L"." << ext;
ct++;
} while (PathFileExists(ss.str().c_str()));
{
AutoLock lock_scope(this);
filename_ = ss.str();
}
file_ = _wfopen(ss.str().c_str(), L"wb");
ASSERT(file_ != NULL);
}
#else
// TODO(port): Implement this.
ASSERT(false); // Not implemented
#endif
}
void OnComplete() {
REQUIRE_FILE_THREAD();
if (!file_)
return;
// Make sure any pending data is written.
OnReceivedData();
fclose(file_);
file_ = NULL;
// Notify the listener that the download completed.
listener_->NotifyDownloadComplete(filename_);
}
void OnReceivedData() {
REQUIRE_FILE_THREAD();
std::vector<std::vector<char>*> data;
// Remove all data from the pending data queue.
{
AutoLock lock_scope(this);
if (!pending_data_.empty()) {
data = pending_data_;
pending_data_.clear();
}
}
if (data.empty())
return;
// Write all pending data to file.
std::vector<std::vector<char>*>::iterator it = data.begin();
for (; it != data.end(); ++it) {
std::vector<char>* buffer = *it;
if (file_)
fwrite(&(*buffer)[0], buffer->size(), 1, file_);
delete buffer;
}
data.clear();
}
static void CloseDanglingFile(FILE *file) {
fclose(file);
}
private:
CefRefPtr<DownloadListener> listener_;
CefString filename_;
FILE* file_;
std::vector<std::vector<char>*> pending_data_;
IMPLEMENT_REFCOUNTING(ClientDownloadHandler);
IMPLEMENT_LOCKING(ClientDownloadHandler);
};
CefRefPtr<CefDownloadHandler> CreateDownloadHandler(
CefRefPtr<DownloadListener> listener, const CefString& fileName) {
CefRefPtr<ClientDownloadHandler> handler =
new ClientDownloadHandler(listener, fileName);
handler->Initialize();
return handler.get();
}

View File

@@ -1,27 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_DOWNLOAD_HANDLER_H_
#define CEF_TESTS_CEFCLIENT_DOWNLOAD_HANDLER_H_
#pragma once
#include "include/cef_base.h"
class CefDownloadHandler;
// Implement this interface to receive download notifications.
class DownloadListener : public virtual CefBase {
public:
// Called when the download is complete.
virtual void NotifyDownloadComplete(const CefString& fileName) =0;
// Called if the download fails.
virtual void NotifyDownloadError(const CefString& fileName) =0;
};
// Create a new download handler to manage download of a single file.
CefRefPtr<CefDownloadHandler> CreateDownloadHandler(
CefRefPtr<DownloadListener> listener, const CefString& fileName);
#endif // CEF_TESTS_CEFCLIENT_DOWNLOAD_HANDLER_H_

View File

@@ -1,126 +0,0 @@
// 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 "cefclient/extension_test.h"
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_stream.h"
#include "include/cef_v8.h"
#include "cefclient/resource_util.h"
// Implementation of the V8 handler class for the "cef.test" extension.
class ClientV8ExtensionHandler : public CefV8Handler {
public:
ClientV8ExtensionHandler() : test_param_("An initial string value.") {}
virtual ~ClientV8ExtensionHandler() {}
// Execute with the specified argument list and return value. Return true if
// the method was handled.
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
if (name == "Dummy") {
// Used for performance testing.
return true;
} else if (name == "SetTestParam") {
// Handle the SetTestParam native function by saving the string argument
// into the local member.
if (arguments.size() != 1 || !arguments[0]->IsString())
return false;
test_param_ = arguments[0]->GetStringValue();
return true;
} else if (name == "GetTestParam") {
// Handle the GetTestParam native function by returning the local member
// value.
retval = CefV8Value::CreateString(test_param_);
return true;
} else if (name == "GetTestObject") {
// Handle the GetTestObject native function by creating and returning a
// new V8 object.
retval = CefV8Value::CreateObject(NULL, NULL);
// Add a string parameter to the new V8 object.
retval->SetValue("param", CefV8Value::CreateString(
"Retrieving a parameter on a native object succeeded."),
V8_PROPERTY_ATTRIBUTE_NONE);
// Add a function to the new V8 object.
retval->SetValue("GetMessage",
CefV8Value::CreateFunction("GetMessage", this),
V8_PROPERTY_ATTRIBUTE_NONE);
return true;
} else if (name == "GetMessage") {
// Handle the GetMessage object function by returning a string.
retval = CefV8Value::CreateString(
"Calling a function on a native object succeeded.");
return true;
}
return false;
}
private:
CefString test_param_;
IMPLEMENT_REFCOUNTING(ClientV8ExtensionHandler);
};
void InitExtensionTest() {
// Register a V8 extension with the below JavaScript code that calls native
// methods implemented in ClientV8ExtensionHandler.
std::string code = "var cef;"
"if (!cef)"
" cef = {};"
"if (!cef.test)"
" cef.test = {};"
"(function() {"
" cef.test.__defineGetter__('test_param', function() {"
" native function GetTestParam();"
" return GetTestParam();"
" });"
" cef.test.__defineSetter__('test_param', function(b) {"
" native function SetTestParam();"
" if (b) SetTestParam(b);"
" });"
" cef.test.test_object = function() {"
" native function GetTestObject();"
" return GetTestObject();"
" };"
" cef.test.dummy = function() {"
" native function Dummy();"
" return Dummy();"
" };"
"})();";
CefRegisterExtension("v8/test", code, new ClientV8ExtensionHandler());
}
void RunExtensionTest(CefRefPtr<CefBrowser> browser) {
std::string html =
"<html><body>ClientV8ExtensionHandler says:<br><pre>"
"<script language=\"JavaScript\">"
"cef.test.test_param ="
" 'Assign and retrieve a value succeeded the first time.';"
"document.writeln(cef.test.test_param);"
"cef.test.test_param ="
" 'Assign and retrieve a value succeeded the second time.';"
"document.writeln(cef.test.test_param);"
"var obj = cef.test.test_object();"
"document.writeln(obj.param);"
"document.writeln(obj.GetMessage());"
"</script>"
"</pre></body></html>";
browser->GetMainFrame()->LoadString(html, "about:blank");
}
void RunExtensionPerfTest(CefRefPtr<CefBrowser> browser) {
CefRefPtr<CefStreamReader> resourceStream;
#if defined(OS_WIN)
resourceStream = GetBinaryResourceReader(IDS_EXTENSIONPERF);
#elif defined(OS_MACOSX)
resourceStream = GetBinaryResourceReader("extensionperf.html");
#endif
browser->GetMainFrame()->LoadStream(resourceStream, "about:blank");
}

View File

@@ -1,20 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_EXTENSION_TEST_H_
#define CEF_TESTS_CEFCLIENT_EXTENSION_TEST_H_
#pragma once
#include "include/cef_base.h"
class CefBrowser;
// Register the V8 extension handler.
void InitExtensionTest();
// Run the test.
void RunExtensionTest(CefRefPtr<CefBrowser> browser);
void RunExtensionPerfTest(CefRefPtr<CefBrowser> browser);
#endif // CEF_TESTS_CEFCLIENT_EXTENSION_TEST_H_

View File

@@ -1,3 +0,0 @@
/* Localized versions of Info.plist keys */
NSHumanReadableCopyright = "© Chromium Embedded Framework Authors, 2010";

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string>cefclient.icns</string>
<key>CFBundleIdentifier</key>
<string>org.cef.cefclient</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>

Binary file not shown.

View File

@@ -1,922 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cefclient/osrplugin.h"
#if defined(OS_WIN)
#include <windows.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <sstream>
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/cefclient.h"
#include "cefclient/client_popup_handler.h"
#include "cefclient/resource.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
#include "cefclient/util.h"
// Initialized in NP_Initialize.
NPNetscapeFuncs* g_osrbrowser = NULL;
namespace {
GLuint g_textureID = -1;
float g_spinX = 0.0f;
float g_spinY = 0.0f;
int g_width = -1, g_height = -1;
CefRefPtr<CefBrowser> g_offscreenBrowser;
// If set to true alpha transparency will be used.
bool g_offscreenTransparent = false;
#define GL_IMAGE_FORMAT (g_offscreenTransparent?GL_RGBA:GL_RGB)
#define GL_BYTE_COUNT (g_offscreenTransparent?4:3)
// Class holding pointers for the client plugin window.
class ClientPlugin {
public:
ClientPlugin() {
hWnd = NULL;
hDC = NULL;
hRC = NULL;
}
HWND hWnd;
HDC hDC;
HGLRC hRC;
};
// Handler for off-screen rendering windows.
class ClientOSRHandler : public CefClient,
public CefLifeSpanHandler,
public CefLoadHandler,
public CefRequestHandler,
public CefDisplayHandler,
public CefRenderHandler {
public:
explicit ClientOSRHandler(ClientPlugin* plugin)
: plugin_(plugin),
view_buffer_(NULL),
view_buffer_size_(0),
popup_buffer_(NULL),
popup_buffer_size_(0) {
}
~ClientOSRHandler() {
if (view_buffer_)
delete [] view_buffer_;
if (popup_buffer_)
delete [] popup_buffer_;
}
// CefClient methods
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefRequestHandler> GetRequestHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefRenderHandler> GetRenderHandler() OVERRIDE {
return this;
}
// CefLifeSpanHandler methods
virtual bool OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser,
const CefPopupFeatures& popupFeatures,
CefWindowInfo& windowInfo,
const CefString& url,
CefRefPtr<CefClient>& client,
CefBrowserSettings& settings) OVERRIDE {
REQUIRE_UI_THREAD();
windowInfo.m_bWindowRenderingDisabled = TRUE;
client = new ClientPopupHandler(g_offscreenBrowser);
return false;
}
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE {
REQUIRE_UI_THREAD();
// Set the view size to match the plugin window size.
browser->SetSize(PET_VIEW, g_width, g_height);
g_offscreenBrowser = browser;
}
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE {
g_offscreenBrowser = NULL;
}
// CefLoadHandler methods
virtual void OnLoadStart(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame) OVERRIDE {
REQUIRE_UI_THREAD();
if (!browser->IsPopup() && frame->IsMain()) {
// We've just started loading a page
SetLoading(true);
}
}
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE {
REQUIRE_UI_THREAD();
if (!browser->IsPopup() && frame->IsMain()) {
// We've just finished loading a page
SetLoading(false);
}
}
// CefRequestHandler methods
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefRequest> request,
CefString& redirectUrl,
CefRefPtr<CefStreamReader>& resourceStream,
CefRefPtr<CefResponse> response,
int loadFlags) OVERRIDE {
REQUIRE_IO_THREAD();
std::string url = request->GetURL();
if (url == "http://tests/transparency") {
resourceStream = GetBinaryResourceReader(IDS_TRANSPARENCY);
response->SetMimeType("text/html");
response->SetStatus(200);
}
return false;
}
// CefDisplayHandler methods
virtual void OnNavStateChange(CefRefPtr<CefBrowser> browser,
bool canGoBack,
bool canGoForward) OVERRIDE {
REQUIRE_UI_THREAD();
// Set the "back" and "forward" button state in the HTML.
std::stringstream ss;
ss << "document.getElementById('back').disabled = "
<< (canGoBack?"false":"true") << ";";
ss << "document.getElementById('forward').disabled = "
<< (canGoForward?"false":"true") << ";";
AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0);
}
virtual void OnAddressChange(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& url) OVERRIDE {
REQUIRE_UI_THREAD();
// Set the "url" value in the HTML.
std::stringstream ss;
std::string urlStr = url;
StringReplace(urlStr, "'", "\\'");
ss << "document.getElementById('url').value = '" << urlStr.c_str() << "'";
AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0);
}
virtual void OnTitleChange(CefRefPtr<CefBrowser> browser,
const CefString& title) OVERRIDE {
REQUIRE_UI_THREAD();
// Set the "title" value in the HTML.
std::stringstream ss;
std::string titleStr = title;
StringReplace(titleStr, "'", "\\'");
ss << "document.getElementById('title').innerHTML = '" <<
titleStr.c_str() << "'";
AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0);
}
// CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE {
REQUIRE_UI_THREAD();
// The simulated screen and view rectangle are the same. This is necessary
// for popup menus to be located and sized inside the view.
rect.x = rect.y = 0;
rect.width = g_width;
rect.height = g_height;
return true;
}
virtual bool GetScreenRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE {
return GetViewRect(browser, rect);
}
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX,
int viewY,
int& screenX,
int& screenY) OVERRIDE {
REQUIRE_UI_THREAD();
// Convert the point from view coordinates to actual screen coordinates.
POINT screen_pt = {viewX, viewY};
MapWindowPoints(plugin_->hWnd, HWND_DESKTOP, &screen_pt, 1);
screenX = screen_pt.x;
screenY = screen_pt.y;
return true;
}
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE {
REQUIRE_UI_THREAD();
if (!show) {
// Clear the popup buffer.
popup_rect_.Set(0, 0, 0, 0);
if (popup_buffer_) {
delete [] popup_buffer_;
popup_buffer_ = NULL;
popup_buffer_size_ = 0;
}
}
}
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE {
REQUIRE_UI_THREAD();
if (rect.width > 0) {
// Update the popup rectange. It will always be inside the view due to
// HandleGetRect().
ASSERT(rect.x + rect.width < g_width &&
rect.y + rect.height < g_height);
popup_rect_ = rect;
}
}
virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type,
const RectList& dirtyRects,
const void* buffer) OVERRIDE {
REQUIRE_UI_THREAD();
wglMakeCurrent(plugin_->hDC, plugin_->hRC);
if (g_offscreenTransparent) {
// Enable alpha blending.
glEnable(GL_BLEND);
}
// Enable 2D textures.
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, g_textureID);
if (type == PET_VIEW) {
SetBufferSize(g_width, g_height, true);
// Paint the view.
if (g_offscreenTransparent) {
RectList::const_iterator i = dirtyRects.begin();
for (; i != dirtyRects.end(); ++i) {
ConvertToRGBARect(*i, (unsigned char*)buffer, view_buffer_, g_width,
g_height);
}
} else {
RectList::const_iterator i = dirtyRects.begin();
for (i; i != dirtyRects.end(); ++i) {
ConvertToRGBRect(*i, (unsigned char*)buffer, view_buffer_, g_width,
g_height);
}
}
// Update the whole texture. This is done for simplicity instead of
// updating just the dirty region.
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, g_width, g_height,
GL_IMAGE_FORMAT, GL_UNSIGNED_BYTE, view_buffer_);
}
if (popup_rect_.width > 0) {
if (type == PET_POPUP) {
// Paint the popup.
if (g_offscreenTransparent)
SetRGBA(buffer, popup_rect_.width, popup_rect_.height, false);
else
SetRGB(buffer, popup_rect_.width, popup_rect_.height, false);
}
if (popup_buffer_) {
// Update the popup region.
glTexSubImage2D(GL_TEXTURE_2D, 0, popup_rect_.x,
g_height-popup_rect_.y-popup_rect_.height, popup_rect_.width,
popup_rect_.height, GL_IMAGE_FORMAT, GL_UNSIGNED_BYTE,
popup_buffer_);
}
}
// Disable 2D textures.
glDisable(GL_TEXTURE_2D);
if (g_offscreenTransparent) {
// Disable alpha blending.
glDisable(GL_BLEND);
}
}
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE {
REQUIRE_UI_THREAD();
// Change the plugin window's cursor.
SetClassLong(plugin_->hWnd, GCL_HCURSOR,
static_cast<LONG>(reinterpret_cast<LONG_PTR>(cursor)));
SetCursor(cursor);
}
private:
void SetLoading(bool isLoading) {
// Set the "stop" and "reload" button state in the HTML.
std::stringstream ss;
ss << "document.getElementById('stop').disabled = "
<< (isLoading?"false":"true") << ";"
<< "document.getElementById('reload').disabled = "
<< (isLoading?"true":"false") << ";";
AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0);
}
// Size the RGB buffer.
void SetBufferSize(int width, int height, bool view) {
int dst_size = width * height * GL_BYTE_COUNT;
// Allocate a new buffer if necesary.
if (view) {
if (dst_size > view_buffer_size_) {
if (view_buffer_)
delete [] view_buffer_;
view_buffer_ = new unsigned char[dst_size];
view_buffer_size_ = dst_size;
}
} else {
if (dst_size > popup_buffer_size_) {
if (popup_buffer_)
delete [] popup_buffer_;
popup_buffer_ = new unsigned char[dst_size];
popup_buffer_size_ = dst_size;
}
}
}
// Set the contents of the RGBA buffer.
void SetRGBA(const void* src, int width, int height, bool view) {
SetBufferSize(width, height, view);
ConvertToRGBA((unsigned char*)src, view?view_buffer_:popup_buffer_, width,
height);
}
// Convert from BGRA to RGBA format and from upper-left to lower-left origin.
static void ConvertToRGBA(const unsigned char* src, unsigned char* dst,
int width, int height) {
int sp = 0, dp = (height-1) * width * 4;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++, dp += 4, sp += 4) {
dst[dp] = src[sp+2]; // R
dst[dp+1] = src[sp+1]; // G
dst[dp+2] = src[sp]; // B
dst[dp+3] = src[sp+3]; // A
}
dp -= width * 8;
}
}
static void ConvertToRGBARect(const CefRect& clipRect,
const unsigned char* src, unsigned char* dst,
int width, int height) {
int sp = 0, dp = (height-1) * width * 4;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++, dp += 4, sp += 4) {
if ((clipRect.x <= j) && (clipRect.x + clipRect.width > j) &&
(clipRect.y <= i) && (clipRect.y + clipRect.height > i)) {
dst[dp] = src[sp+2]; // R
dst[dp+1] = src[sp+1]; // G
dst[dp+2] = src[sp]; // B
dst[dp+3] = src[sp+3]; // A
}
}
dp -= width * 8;
}
}
// Set the contents of the RGB buffer.
void SetRGB(const void* src, int width, int height, bool view) {
SetBufferSize(width, height, view);
ConvertToRGB((unsigned char*)src, view?view_buffer_:popup_buffer_, width,
height);
}
// Convert from BGRA to RGB format and from upper-left to lower-left origin.
static void ConvertToRGB(const unsigned char* src, unsigned char* dst,
int width, int height) {
int sp = 0, dp = (height-1) * width * 3;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++, dp += 3, sp += 4) {
dst[dp] = src[sp+2]; // R
dst[dp+1] = src[sp+1]; // G
dst[dp+2] = src[sp]; // B
}
dp -= width * 6;
}
}
static void ConvertToRGBRect(const CefRect& clipRect,
const unsigned char* src, unsigned char* dst,
int width, int height) {
int sp = 0, dp = (height-1) * width * 3;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++, dp += 3, sp += 4) {
if ((clipRect.x <= j) && (clipRect.x + clipRect.width > j) &&
(clipRect.y <= i) && (clipRect.y + clipRect.height > i)) {
dst[dp] = src[sp+2]; // R
dst[dp+1] = src[sp+1]; // G
dst[dp+2] = src[sp]; // B
}
}
dp -= width * 6;
}
}
ClientPlugin* plugin_;
unsigned char* view_buffer_;
int view_buffer_size_;
unsigned char* popup_buffer_;
int popup_buffer_size_;
CefRect popup_rect_;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientOSRPlugin);
};
// Forward declarations of functions included in this code module:
LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam);
// Enable GL.
void EnableGL(HWND hWnd, HDC * hDC, HGLRC * hRC) {
PIXELFORMATDESCRIPTOR pfd;
int format;
// Get the device context.
*hDC = GetDC(hWnd);
// Set the pixel format for the DC.
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat(*hDC, &pfd);
SetPixelFormat(*hDC, format, &pfd);
// Create and enable the render context.
*hRC = wglCreateContext(*hDC);
wglMakeCurrent(*hDC, *hRC);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Necessary for non-power-of-2 textures to render correctly.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
if (g_offscreenTransparent) {
// Alpha blending style.
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
// Disable GL.
void DisableGL(HWND hWnd, HDC hDC, HGLRC hRC) {
// Delete the texture.
if (g_textureID != -1)
glDeleteTextures(1, &g_textureID);
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC);
ReleaseDC(hWnd, hDC);
}
// Size the GL view.
void SizeGL(ClientPlugin* plugin, int width, int height) {
g_width = width;
g_height = height;
wglMakeCurrent(plugin->hDC, plugin->hRC);
// Match GL units to screen coordinates.
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 0, width, height, 0.1, 100.0);
if (g_offscreenTransparent) {
// Enable alpha blending.
glEnable(GL_BLEND);
}
// Enable 2D textures.
glEnable(GL_TEXTURE_2D);
// Delete the existing exture.
if (g_textureID != -1)
glDeleteTextures(1, &g_textureID);
// Create a new texture.
glGenTextures(1, &g_textureID);
glBindTexture(GL_TEXTURE_2D, g_textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Start with all white contents.
int size = width * height * GL_BYTE_COUNT;
unsigned char* buffer = new unsigned char[size];
memset(buffer, 255, size);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
GL_IMAGE_FORMAT, GL_UNSIGNED_BYTE, buffer);
// Disable 2D textures.
glDisable(GL_TEXTURE_2D);
if (g_offscreenTransparent) {
// Disable alpha blending.
glDisable(GL_BLEND);
}
delete [] buffer;
if (g_offscreenBrowser.get())
g_offscreenBrowser->SetSize(PET_VIEW, width, height);
}
// Render the view contents.
void RenderGL(ClientPlugin* plugin) {
wglMakeCurrent(plugin->hDC, plugin->hRC);
struct {
float tu, tv;
float x, y, z;
} static vertices[] = {
{0.0f, 0.0f, -1.0f, -1.0f, 0.0f},
{1.0f, 0.0f, 1.0f, -1.0f, 0.0f},
{1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
{0.0f, 1.0f, -1.0f, 1.0f, 0.0f}
};
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// glTranslatef(0.0f, 0.0f, -3.0f);
// Draw the background gradient.
glPushAttrib(GL_ALL_ATTRIB_BITS);
glBegin(GL_QUADS);
glColor4f(1.0, 0.0, 0.0, 1.0); // red
glVertex2f(-1.0, -1.0);
glVertex2f(1.0, -1.0);
glColor4f(0.0, 0.0, 1.0, 1.0); // blue
glVertex2f(1.0, 1.0);
glVertex2f(-1.0, 1.0);
glEnd();
glPopAttrib();
// Rotate the view based on the mouse spin.
glRotatef(-g_spinX, 1.0f, 0.0f, 0.0f);
glRotatef(-g_spinY, 0.0f, 1.0f, 0.0f);
if (g_offscreenTransparent) {
// Enable alpha blending.
glEnable(GL_BLEND);
}
// Enable 2D textures.
glEnable(GL_TEXTURE_2D);
// Draw the facets with the texture.
glBindTexture(GL_TEXTURE_2D, g_textureID);
glInterleavedArrays(GL_T2F_V3F, 0, vertices);
glDrawArrays(GL_QUADS, 0, 4);
// Disable 2D textures.
glDisable(GL_TEXTURE_2D);
if (g_offscreenTransparent) {
// Disable alpha blending.
glDisable(GL_BLEND);
}
SwapBuffers(plugin->hDC);
}
NPError NPP_NewImpl(NPMIMEType plugin_type, NPP instance, uint16 mode,
int16 argc, char* argn[], char* argv[],
NPSavedData* saved) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
ClientPlugin* plugin = new ClientPlugin;
instance->pdata = reinterpret_cast<void*>(plugin);
return NPERR_NO_ERROR;
}
NPError NPP_DestroyImpl(NPP instance, NPSavedData** save) {
ClientPlugin* plugin = reinterpret_cast<ClientPlugin*>(instance->pdata);
if (plugin) {
if (plugin->hWnd) {
DestroyWindow(plugin->hWnd);
DisableGL(plugin->hWnd, plugin->hDC, plugin->hRC);
}
delete plugin;
}
return NPERR_NO_ERROR;
}
NPError NPP_SetWindowImpl(NPP instance, NPWindow* window_info) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
if (window_info == NULL)
return NPERR_GENERIC_ERROR;
ClientPlugin* plugin = reinterpret_cast<ClientPlugin*>(instance->pdata);
HWND parent_hwnd = reinterpret_cast<HWND>(window_info->window);
if (plugin->hWnd == NULL) {
WNDCLASS wc;
HINSTANCE hInstance = GetModuleHandle(NULL);
// Register the window class.
wc.style = CS_OWNDC;
wc.lpfnWndProc = PluginWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = L"ClientOSRPlugin";
RegisterClass(&wc);
// Create the main window.
plugin->hWnd = CreateWindow(L"ClientOSRPlugin", L"Client OSR Plugin",
WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 0, 0, 0, 0, parent_hwnd, NULL,
hInstance, NULL);
SetWindowLongPtr(plugin->hWnd, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(plugin));
// Enable GL drawing for the window.
EnableGL(plugin->hWnd, &(plugin->hDC), &(plugin->hRC));
// Create the off-screen rendering window.
CefWindowInfo windowInfo;
CefBrowserSettings settings;
windowInfo.SetAsOffScreen(plugin->hWnd);
if (g_offscreenTransparent)
windowInfo.SetTransparentPainting(TRUE);
CefBrowser::CreateBrowser(windowInfo, new ClientOSRHandler(plugin),
"http://www.google.com", settings);
}
// Position the plugin window and make sure it's visible.
RECT parent_rect;
GetClientRect(parent_hwnd, &parent_rect);
SetWindowPos(plugin->hWnd, NULL, parent_rect.left, parent_rect.top,
parent_rect.right - parent_rect.left,
parent_rect.bottom - parent_rect.top, SWP_SHOWWINDOW);
UpdateWindow(plugin->hWnd);
ShowWindow(plugin->hWnd, SW_SHOW);
return NPERR_NO_ERROR;
}
// Plugin window procedure.
LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam) {
static POINT lastMousePos, curMousePos;
static bool mouseRotation = false;
static bool mouseTracking = false;
ClientPlugin* plugin =
reinterpret_cast<ClientPlugin*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (message) {
case WM_CREATE:
// Start the timer that's used for redrawing.
SetTimer(hWnd, 1, 20, NULL);
return 0;
case WM_DESTROY:
// Stop the timer that's used for redrawing.
KillTimer(hWnd, 1);
// Explicitly close the offscreen browser and release the reference.
g_offscreenBrowser->CloseBrowser();
g_offscreenBrowser = NULL;
return 0;
case WM_TIMER:
RenderGL(plugin);
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
SetCapture(hWnd);
SetFocus(hWnd);
if (wParam & MK_SHIFT) {
// Start rotation effect.
lastMousePos.x = curMousePos.x = LOWORD(lParam);
lastMousePos.y = curMousePos.y = HIWORD(lParam);
mouseRotation = true;
} else {
if (g_offscreenBrowser.get()) {
g_offscreenBrowser->SendMouseClickEvent(LOWORD(lParam), HIWORD(lParam),
(message == WM_LBUTTONDOWN?MBT_LEFT:MBT_RIGHT), false, 1);
}
}
break;
case WM_LBUTTONUP:
case WM_RBUTTONUP:
if (GetCapture() == hWnd)
ReleaseCapture();
if (mouseRotation) {
// End rotation effect.
mouseRotation = false;
g_spinX = 0;
g_spinY = 0;
} else {
if (g_offscreenBrowser.get()) {
g_offscreenBrowser->SendMouseClickEvent(LOWORD(lParam), HIWORD(lParam),
(message == WM_LBUTTONUP?MBT_LEFT:MBT_RIGHT), true, 1);
}
}
break;
case WM_MOUSEMOVE:
if (mouseRotation) {
// Apply rotation effect.
curMousePos.x = LOWORD(lParam);
curMousePos.y = HIWORD(lParam);
g_spinX -= (curMousePos.x - lastMousePos.x);
g_spinY -= (curMousePos.y - lastMousePos.y);
lastMousePos.x = curMousePos.x;
lastMousePos.y = curMousePos.y;
} else {
if (!mouseTracking) {
// Start tracking mouse leave. Required for the WM_MOUSELEAVE event to
// be generated.
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = hWnd;
TrackMouseEvent(&tme);
mouseTracking = true;
}
if (g_offscreenBrowser.get()) {
g_offscreenBrowser->SendMouseMoveEvent(LOWORD(lParam), HIWORD(lParam),
false);
}
}
break;
case WM_MOUSELEAVE:
if (mouseTracking) {
// Stop tracking mouse leave.
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE & TME_CANCEL;
tme.hwndTrack = hWnd;
TrackMouseEvent(&tme);
mouseTracking = false;
}
if (g_offscreenBrowser.get())
g_offscreenBrowser->SendMouseMoveEvent(0, 0, true);
break;
case WM_MOUSEWHEEL:
if (g_offscreenBrowser.get()) {
g_offscreenBrowser->SendMouseWheelEvent(LOWORD(lParam), HIWORD(lParam),
GET_WHEEL_DELTA_WPARAM(wParam));
}
break;
case WM_SIZE: {
int width = LOWORD(lParam);
int height = HIWORD(lParam);
if (width > 0 && height > 0)
SizeGL(plugin, width, height);
break;
}
case WM_SETFOCUS:
case WM_KILLFOCUS:
if (g_offscreenBrowser.get())
g_offscreenBrowser->SendFocusEvent(message == WM_SETFOCUS);
break;
case WM_CAPTURECHANGED:
case WM_CANCELMODE:
if (!mouseRotation) {
if (g_offscreenBrowser.get())
g_offscreenBrowser->SendCaptureLostEvent();
}
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_CHAR:
case WM_SYSCHAR:
case WM_IME_CHAR:
if (g_offscreenBrowser.get()) {
CefBrowser::KeyType type = KT_CHAR;
bool sysChar = false, imeChar = false;
if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
type = KT_KEYDOWN;
else if (message == WM_KEYUP || message == WM_SYSKEYUP)
type = KT_KEYUP;
if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP ||
message == WM_SYSCHAR)
sysChar = true;
if (message == WM_IME_CHAR)
imeChar = true;
g_offscreenBrowser->SendKeyEvent(type, wParam, lParam, sysChar, imeChar);
}
break;
case WM_PAINT: {
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return 0;
}
case WM_ERASEBKGND:
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
} // namespace
NPError API_CALL NP_OSRGetEntryPoints(NPPluginFuncs* pFuncs) {
pFuncs->newp = NPP_NewImpl;
pFuncs->destroy = NPP_DestroyImpl;
pFuncs->setwindow = NPP_SetWindowImpl;
return NPERR_NO_ERROR;
}
NPError API_CALL NP_OSRInitialize(NPNetscapeFuncs* pFuncs) {
g_osrbrowser = pFuncs;
return NPERR_NO_ERROR;
}
NPError API_CALL NP_OSRShutdown(void) {
g_osrbrowser = NULL;
return NPERR_NO_ERROR;
}
CefRefPtr<CefBrowser> GetOffScreenBrowser() {
return g_offscreenBrowser;
}
void SetOffScreenTransparent(bool transparent) {
g_offscreenTransparent = transparent;
}
#endif // OS_WIN

View File

@@ -1,33 +0,0 @@
// Copyright (c) 2011 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Portions of this implementation are borrowed from webkit\default_plugin\
// plugin_impl.h
#ifndef CEF_TESTS_CEFCLIENT_OSRPLUGIN_H_
#define CEF_TESTS_CEFCLIENT_OSRPLUGIN_H_
#pragma once
#include "include/cef_base.h"
#if defined(OS_WIN)
#include "include/cef_nplugin.h"
class CefBrowser;
extern NPNetscapeFuncs* g_osrbrowser;
NPError API_CALL NP_OSRGetEntryPoints(NPPluginFuncs* pFuncs);
NPError API_CALL NP_OSRInitialize(NPNetscapeFuncs* pFuncs);
NPError API_CALL NP_OSRShutdown(void);
CefRefPtr<CefBrowser> GetOffScreenBrowser();
void SetOffScreenTransparent(bool transparent);
#endif // OS_WIN
#endif // CEF_TESTS_CEFCLIENT_OSRPLUGIN_H_

View File

@@ -1,126 +0,0 @@
// 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 "cefclient/osrplugin_test.h"
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/osrplugin.h"
#include "cefclient/cefclient.h"
#include "cefclient/client_handler.h"
#include "cefclient/plugin_test.h"
void InitOSRPluginTest() {
// Structure providing information about the client plugin.
CefPluginInfo plugin_info;
CefString(&plugin_info.display_name).FromASCII("Client OSR Plugin");
CefString(&plugin_info.unique_name).FromASCII("client_osr_plugin");
CefString(&plugin_info.description).FromASCII("My Example Client OSR Plugin");
CefString(&plugin_info.mime_types).FromASCII(
"application/x-client-osr-plugin");
plugin_info.np_getentrypoints = NP_OSRGetEntryPoints;
plugin_info.np_initialize = NP_OSRInitialize;
plugin_info.np_shutdown = NP_OSRShutdown;
// Register the internal client plugin
CefRegisterPlugin(plugin_info);
}
void RunOSRPluginTest(CefRefPtr<CefBrowser> browser, bool transparent) {
class Listener : public CefDOMEventListener {
public:
Listener() {}
virtual void HandleEvent(CefRefPtr<CefDOMEvent> event) {
CefRefPtr<CefBrowser> browser = GetOffScreenBrowser();
CefRefPtr<CefDOMNode> element = event->GetTarget();
ASSERT(element.get());
std::string elementId = element->GetElementAttribute("id");
if (elementId == "back") {
browser->GoBack();
} else if (elementId == "forward") {
browser->GoForward();
} else if (elementId == "stop") {
browser->Reload();
} else if (elementId == "reload") {
browser->StopLoad();
} else if (elementId == "go") {
// Retrieve the value of the "url" field and load it in the off-screen
// browser window.
CefRefPtr<CefDOMDocument> document = event->GetDocument();
ASSERT(document.get());
CefRefPtr<CefDOMNode> url = document->GetElementById("url");
ASSERT(url.get());
CefString value = url->GetValue();
if (!value.empty())
browser->GetMainFrame()->LoadURL(value);
} else if (elementId == "testTransparency") {
// Transparency test.
browser->GetMainFrame()->LoadURL(
"http://tests/transparency");
} else if (elementId == "testWindowlessPlugin") {
// Load flash, which is a windowless plugin.
browser->GetMainFrame()->LoadURL(
"http://www.adobe.com/software/flash/about/");
} else if (elementId == "viewSource") {
// View the page source for the host browser window.
AppGetBrowser()->GetMainFrame()->ViewSource();
} else {
// Not reached.
ASSERT(false);
}
}
IMPLEMENT_REFCOUNTING(Listener);
};
class Visitor : public CefDOMVisitor {
public:
Visitor() {}
void RegisterClickListener(CefRefPtr<CefDOMDocument> document,
CefRefPtr<CefDOMEventListener> listener,
const std::string& elementId) {
CefRefPtr<CefDOMNode> element = document->GetElementById(elementId);
ASSERT(element.get());
element->AddEventListener("click", listener, false);
}
virtual void Visit(CefRefPtr<CefDOMDocument> document) {
CefRefPtr<CefDOMEventListener> listener(new Listener());
// Register click listeners for the various HTML elements.
RegisterClickListener(document, listener, "back");
RegisterClickListener(document, listener, "forward");
RegisterClickListener(document, listener, "stop");
RegisterClickListener(document, listener, "reload");
RegisterClickListener(document, listener, "go");
RegisterClickListener(document, listener, "testTransparency");
RegisterClickListener(document, listener, "testWindowlessPlugin");
RegisterClickListener(document, listener, "viewSource");
}
IMPLEMENT_REFCOUNTING(Visitor);
};
// Center the window on the screen.
int screenX = GetSystemMetrics(SM_CXFULLSCREEN);
int screenY = GetSystemMetrics(SM_CYFULLSCREEN);
int width = 1000, height = 760;
int x = (screenX - width) / 2;
int y = (screenY - height) / 2;
SetWindowPos(AppGetMainHwnd(), NULL, x, y, width, height,
SWP_NOZORDER | SWP_SHOWWINDOW);
// The DOM visitor will be called after the path is loaded.
CefRefPtr<CefClient> client = browser->GetClient();
static_cast<ClientHandler*>(client.get())->AddDOMVisitor(
"http://tests/osrapp", new Visitor());
SetOffScreenTransparent(transparent);
browser->GetMainFrame()->LoadURL("http://tests/osrapp");
}

View File

@@ -1,19 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_OSRPLUGIN_TEST_H_
#define CEF_TESTS_CEFCLIENT_OSRPLUGIN_TEST_H_
#pragma once
#include "include/cef_base.h"
class CefBrowser;
// Register the internal client plugin and V8 extension.
void InitOSRPluginTest();
// Run the test.
void RunOSRPluginTest(CefRefPtr<CefBrowser> browser, bool transparent);
#endif // CEF_TESTS_CEFCLIENT_OSRPLUGIN_TEST_H_

View File

@@ -1,31 +0,0 @@
// 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 "include/cef_base.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_nplugin.h"
#include "cefclient/clientplugin.h"
void InitPluginTest() {
// Structure providing information about the client plugin.
CefPluginInfo plugin_info;
CefString(&plugin_info.display_name).FromASCII("Client Plugin");
CefString(&plugin_info.unique_name).FromASCII("client_plugin");
CefString(&plugin_info.description).FromASCII("My Example Client Plugin");
CefString(&plugin_info.mime_types).FromASCII("application/x-client-plugin");
CefString(&plugin_info.file_extensions).FromASCII("xcp");
plugin_info.np_getentrypoints = NP_ClientGetEntryPoints;
plugin_info.np_initialize = NP_ClientInitialize;
plugin_info.np_shutdown = NP_ClientShutdown;
// Register the internal client plugin
CefRegisterPlugin(plugin_info);
}
void RunPluginTest(CefRefPtr<CefBrowser> browser) {
// Page content is provided in ClientHandler::OnBeforeResourceLoad().
browser->GetMainFrame()->LoadURL("http://tests/plugin");
}

View File

@@ -1,19 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_PLUGIN_TEST_H_
#define CEF_TESTS_CEFCLIENT_PLUGIN_TEST_H_
#pragma once
#include "include/cef_base.h"
class CefBrowser;
// Register the internal client plugin.
void InitPluginTest();
// Run the test.
void RunPluginTest(CefRefPtr<CefBrowser> browser);
#endif // CEF_TESTS_CEFCLIENT_PLUGIN_TEST_H_

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@@ -1,13 +0,0 @@
<html>
<body>
<p id="instructions">Select some portion of the below page content and click the "Describe Selection" button. The selected region will then be described below.</p>
<p id="p1">This is p1</p>
<p id="p2">This is p2</p>
<p id="p3">This is p3</p>
<p id="p4">This is p4</p>
<form>
<input type="button" id="button" value="Describe Selection">
<p id="description">The description will appear here.</p>
</form>
</body>
</html>

View File

@@ -1,131 +0,0 @@
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Extension: Performance</title>
<style>
body { font-family: Tahoma, Serif; font-size: 9pt; }
</style>
</head>
<body>
<h1>JavaScript Extension: Performance</h1>
<div><span id="statusBox"></span> <progress id="progressBox" value="0" style="display:none"></progress></div>
<div style="padding-top:10px; padding-bottom:10px">
<table id="resultTable" border="1" cellspacing="1" cellpadding="4" width="100%">
<thead>
<tr>
<td>Name</td>
<td>Min</td>
<td>Avg</td>
<td>Max</td>
<td>Probes</td>
</tr>
</thead>
<!-- result rows here -->
</table>
</div>
<script type="text/javascript">
(function () {
var asyncExecution = true;
var testIterations = 100000;
var totalProbes = 10;
var probeDelay = 0;
var collectProbes = false;
function dummyCallTest() {
for (var i = 0; i < testIterations; i++) {
cef.test.dummy();
}
}
function execTestFunc(func) {
var begin = new Date();
func();
var end = new Date();
return (end - begin);
}
function execTest(test) {
function nextStep() {
if (asyncExecution) {
setTimeout(function () { execTest(test); }, probeDelay);
} else {
execTest(test);
}
}
function nextTest() {
appendResult(test);
// ...
}
updateStatus(test);
if (!test.warmedUp) {
execTestFunc(test.func);
test.warmedUp = true;
return nextStep();
}
if (test.probe >= test.totalProbes) {
test.avg = test.total / test.totalProbes;
return nextTest();
}
var elapsed = execTestFunc(test.func);
test.total += elapsed;
if (!test.min) test.min = elapsed;
else if (test.min > elapsed) test.min = elapsed;
if (!test.max) test.max = elapsed;
else if (test.max < elapsed) test.max = elapsed;
if (collectProbes) {
test.results.push(elapsed);
}
test.probe++;
return nextStep();
}
function updateStatus(test) {
var statusBox = document.getElementById("statusBox");
var progressBox = document.getElementById("progressBox");
if (test.probe >= test.totalProbes) {
statusBox.innerText = test.name + " completed.";
progressBox.style.display = 'none';
} else {
statusBox.innerText = test.name + " (" + test.probe + "/" + test.totalProbes + ")";
progressBox.value = (test.probe / test.totalProbes);
progressBox.style.display = 'inline';
}
}
function appendResult(test) {
var e = document.getElementById("resultTable");
e.insertAdjacentHTML("beforeEnd",
["<tr>",
"<td>", test.name, "</td>",
"<td>", test.min, "ms</td>",
"<td>", test.avg, "ms</td>",
"<td>", test.max, "ms</td>",
"<td>", test.results.join(", "), "</td>",
"<tr>"
].join("")
);
}
function runTest(name, func) {
var test = { name: name, func: func, warmedUp: false, total: 0, totalProbes: totalProbes, probe: 0, results: [] };
setTimeout(function () { execTest(test); }, 10);
}
runTest("dummyCall", dummyCallTest);
})();
</script>
</body>
</html>

View File

@@ -1,24 +0,0 @@
<html>
<body>
<script language="JavaScript">
var val = window.localStorage.getItem('val');
function addLine() {
if(val == null)
val = '<br/>One Line.';
else
val += '<br/>Another Line.';
window.localStorage.setItem('val', val);
document.getElementById('out').innerHTML = val;
}
</script>
Click the "Add Line" button to add a line or the "Clear" button to clear.<br/>
This data will persist across sessions if a cache path was specified.<br/>
<input type="button" value="Add Line" onClick="addLine();"/>
<input type="button" value="Clear" onClick="window.localStorage.removeItem('val'); window.location.reload();"/>
<div id="out"></div>
<script language="JavaScript">
if(val != null)
document.getElementById('out').innerHTML = val;
</script>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

View File

@@ -1,78 +0,0 @@
<!doctype html>
<html>
<head>
<title>A Modal Dialog</title>
</head>
<body>
Argument:<input id="argument" type="text" size="32"><br>
<br>
Reply:<input id="reply" type="text" autofocus="autofocus" size="32"><br>
<p>
<button onclick="OnOK(false)">Cancel</button> <button onclick="OnOK(true)">OK</button>
</p>
<p id="time"></p>
<script>
function init()
{
timer();
setInterval(timer, 200);
setValueToId('argument', dialogArguments.msg);
}
function timer()
{
updateId("time",new Date().toLocaleString());
}
function updateId(id, html, append)
{
id = document.getElementById(id);
if (typeof html == "boolean")
html = html?"Yes":"No";
if (append)
id.innerHTML += html + '<br>';
else
id.innerHTML = html;
}
function setValueToId(id, v)
{
id = document.getElementById(id);
id.value = v;
}
function getValueFromId(id)
{
id = document.getElementById(id);
if (id)
return id.value;
else
return "";
}
function OnOK(what)
{
if (what)
returnValue = { dialogResult:true, msg: "'"+ getValueFromId('reply') + "'" };
else
returnValue = { dialogResult:false, msg:'(cancelled)' };
window.close();
}
function keydown(e)
{
if (!e) e= event;
if (e.keyCode == 27) {
OnOK(false);
} else if (e.keyCode == 13) {
OnOK(true);
}
}
document.addEventListener('keydown', keydown, false);
window.addEventListener('load', init, false);
</script>
</body>
</html>

View File

@@ -1,58 +0,0 @@
<!doctype html>
<html>
<head>
<title>Test Modal Dialog</title>
</head>
<body>
<h3>Tests</h3>
<button onclick="doModal()">Open the modal dialog</button><br>
<button onclick="window.close()">Close this window</button>
<h3>Time (timers are suppresed while the modal dialog is open)</h3>
<div id="time"></div>
<h3>Result Log</h3>
<div id="result"></div>
<script>
function init()
{
timer();
setInterval(timer, 200);
}
function timer()
{
updateId("time",new Date().toLocaleString());
}
function updateId(id, html, append)
{
id = document.getElementById(id);
if (typeof html == "boolean")
html = html?"Yes":"No";
if (append)
id.innerHTML += html + '<br>';
else
id.innerHTML = html;
}
function doModal()
{
updateId('result', "Modal dialog is open...", true);
var result = window.showModalDialog("http://tests/modaldialog", { msg:"Hi from parent"} );
if (typeof result == "object") {
updateId('result', "Result: " + result.msg, true);
} else {
updateId('result', "Dialog was closed", true);
}
}
window.addEventListener('load', init, false);
</script>
</body>
</html>

View File

@@ -1,51 +0,0 @@
<html>
<head>
<title>Off-Screen Rendering App Example</title>
</head>
<body bottommargin="2" rightmargin="0" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" style="font-family: Verdana, Arial;">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" width="99.9%" height="100%">
<tr>
<td height="100%" align="center" valign="top">
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2" style="font-size: 18pt;">Off-Screen Rendering App Example</td>
</tr>
<tr>
<td colspan="2" style="font-size: 8pt;"><i>An embedded OpenGL plugin window that renders content from an off-screen browser window.</i>
<a href="#" id="viewSource">View Page Source</a></td>
</tr>
<tr>
<td colspan="2" height="10"></td>
</tr>
<tr>
<td width="100" valign="top"><img src="logoball.png" width="100" height="101"></td>
<td style="font-size: 10pt;"><span style="font-size: 12pt;">You can rotate the view!</span>
<ul>
<li>Click and drag the view with the left mouse button while holding the shift key.</li>
<li>Enter a URL and click the "Go!" button to browse to a new Website.</li>
<li><a href="#" id="testTransparency">Click here</a> to test transparency.</li>
<li><a href="#" id="testWindowlessPlugin">Click here</a> to test a windowless plugin.</li>
</ul>
</td>
</tr>
</table>
<div style="padding: 2px; margin: 5px; width: 960px;" align="left">
<span id="title" style="font-size: 12pt; font-weight: bold;">&nbsp;</span>
<br>
<input type="button" id="back" value="Back">
<input type="button" id="forward" value="Forward">
<input type="button" id="stop" value="Stop">
<input type="button" id="reload" value="Reload">
<input type="text" id="url" size="80"><input type="button" id="go" value="Go!">
</div>
<div style="padding: 2px; margin: 5px; border: red 1px solid; width: 960px;">
<embed type="application/x-client-osr-plugin" width=960 height=400></embed>
</div>
</td>
</tr>
</table>
</div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@@ -1,36 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Transparency Examples</title>
<style type="text/css">
body {
font-family: Verdana, Arial;
}
img {
opacity:0.4;
}
img:hover {
opacity:1.0;
}
#transbox {
width: 300px;
margin: 0 50px;
background-color: #fff;
border: 2px solid black;
opacity: 0.3;
font-size: 18px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Image Transparency</h1>
Hover over an image to make it fully opaque.<br>
<img src="http://www.w3schools.com/css/klematis.jpg" width="150" height="113" alt="klematis" />
<img src="http://www.w3schools.com/css/klematis2.jpg" width="150" height="113" alt="klematis" />
<h1>Div Transparency</h1>
<div id="transbox">This is some text in a transparent box.</div>
</body>
</html>

View File

@@ -1,57 +0,0 @@
<html>
<head>
<title>User Interface App Example</title>
</head>
<body bottommargin="2" rightmargin="0" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" style="font-family: Verdana, Arial;">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" width="99.9%" height="100%">
<tr>
<td height="100%" align="center" valign="top">
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2" style="font-size: 18pt;">User Interface App Example</td>
</tr>
<tr>
<td colspan="2" style="font-size: 8pt;"><i>An embedded OpenGL plugin window that communicates with the Chromium browser control via JavaScript calls.</i>
<a href="#" onclick="cef.uiapp.viewSource(); return false;">View Page Source</a></td>
</tr>
<tr>
<td colspan="2" height="10"></td>
</tr>
<tr>
<td width="100" valign="top"><img src="logoball.png" width="100" height="101"></td>
<td style="font-size: 10pt;"><span style="font-size: 12pt;">You can make the square rotate!</span>
<ul>
<li>Click the square with the left mouse button or click the <b>Decrement Rotation</b> button to decrement the rotation value.</li>
<li>Click the square with the right mouse button or click the <b>Increment Rotation</b> button to increment the rotation value.</li>
<li>Click the <b>Reset Rotation</b> button to reset the rotation value to zero.</li>
</ul>
</td>
</tr>
</table>
<div style="padding: 2px; margin: 5px; border: red 1px solid; width: 350px;">
<embed type="application/x-client-ui-plugin" width=350 height=350></embed>
</div>
<form name="control">
Rotation Value: <input type="text" name="rotation_field" value="0" size="5" readonly>
<br/><input type="button" value="Decrement Rotation" onclick="cef.uiapp.modifyRotation(-2.0);">
<input type="button" value="Increment Rotation" onclick="cef.uiapp.modifyRotation(2.0);">
<input type="button" value="Reset Rotation" name="reset_button" onclick="cef.uiapp.resetRotation();" disabled>
</form>
</td>
</tr>
</table>
</div>
<script language="JavaScript">
// Called by the application after rotation has been changed.
// |val| is the new rotation value.
function notifyNewRotation(val)
{
document.control.rotation_field.value = val;
document.control.reset_button.disabled = (val == 0);
}
</script>
</body>
</html>

View File

@@ -1,19 +0,0 @@
<html>
<body>
<script language="JavaScript">
function execXMLHttpRequest()
{
xhr = new XMLHttpRequest();
xhr.open("GET",document.getElementById("url").value,false);
xhr.setRequestHeader('My-Custom-Header', 'Some Value');
xhr.send();
document.getElementById('ta').value = "Status Code: "+xhr.status+"\n\n"+xhr.responseText;
}
</script>
<form>
URL: <input type="text" id="url" value="http://tests/request">
<br/><input type="button" onclick="execXMLHttpRequest();" value="Execute XMLHttpRequest">
<br/><textarea rows="10" cols="40" id="ta"></textarea>
</form>
</body>
</html>

View File

@@ -1,86 +0,0 @@
// 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.
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by cefclient.rc
//
#define BINARY 256
#define IDC_MYICON 2
#define IDD_CEFCLIENT_DIALOG 102
#define IDS_APP_TITLE 103
#define IDD_ABOUTBOX 103
#define IDM_ABOUT 104
#define IDM_EXIT 105
#define IDI_CEFCLIENT 107
#define IDI_SMALL 108
#define IDC_CEFCLIENT 109
#define IDR_MAINFRAME 128
#define IDC_NAV_BACK 200
#define IDC_NAV_FORWARD 201
#define IDC_NAV_RELOAD 202
#define IDC_NAV_STOP 203
#define ID_WARN_CONSOLEMESSAGE 32000
#define ID_WARN_DOWNLOADCOMPLETE 32001
#define ID_WARN_DOWNLOADERROR 32002
#define ID_FIND 32101
#define ID_PRINT 32102
#define ID_TESTS_GETSOURCE 32769
#define ID_TESTS_GETTEXT 32770
#define ID_TESTS_JAVASCRIPT_BINDING 32771
#define ID_TESTS_JAVASCRIPT_EXTENSION 32772
#define ID_TESTS_JAVASCRIPT_EXECUTE 32773
#define ID_TESTS_PLUGIN 32774
#define ID_TESTS_POPUP 32775
#define ID_TESTS_REQUEST 32776
#define ID_TESTS_SCHEME_HANDLER 32777
#define ID_TESTS_UIAPP 32778
#define ID_TESTS_LOCALSTORAGE 32779
#define ID_TESTS_ACCELERATED2DCANVAS 32780
#define ID_TESTS_ACCELERATEDLAYERS 32781
#define ID_TESTS_WEBGL 32782
#define ID_TESTS_HTML5VIDEO 32783
#define ID_TESTS_XMLHTTPREQUEST 32784
#define ID_TESTS_ZOOM_IN 32785
#define ID_TESTS_ZOOM_OUT 32786
#define ID_TESTS_ZOOM_RESET 32787
#define ID_TESTS_DEVTOOLS_SHOW 32788
#define ID_TESTS_DEVTOOLS_CLOSE 32789
#define ID_TESTS_WEBURLREQUEST 32790
#define ID_TESTS_DOMACCESS 32791
#define ID_TESTS_DRAGDROP 32792
#define ID_TESTS_OSRAPP 32793
#define ID_TESTS_MODALDIALOG 32794
#define ID_TESTS_JAVASCRIPT_PERFORMANCE 32795
#define ID_TESTS_TRANSPARENT_POPUP 32796
#define ID_TESTS_TRANSPARENT_OSRAPP 32797
#define ID_TESTS_JAVASCRIPT_INVOKE 32798
#define ID_TESTS_GETIMAGE 32799
#define IDC_STATIC -1
#define IDS_LOGO 1000
#define IDS_UIPLUGIN 1001
#define IDS_LOGOBALL 1002
#define IDS_LOCALSTORAGE 1003
#define IDS_XMLHTTPREQUEST 1004
#define IDS_DOMACCESS 1005
#define IDS_OSRPLUGIN 1006
#define IDS_MODALMAIN 1007
#define IDS_MODALDIALOG 1008
#define IDS_EXTENSIONPERF 1009
#define IDS_TRANSPARENCY 1010
// Avoid files associated with MacOS
#define _X86_
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 32795
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif

View File

@@ -1,31 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_
#define CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_
#pragma once
#include "include/cef_base.h"
class CefStreamReader;
#if defined(OS_WIN)
#include "cefclient/resource.h"
// Load a resource of type BINARY
bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes);
CefRefPtr<CefStreamReader> GetBinaryResourceReader(int binaryId);
#elif defined(OS_MACOSX) || defined(OS_POSIX)
#include <string> // NOLINT(build/include_order)
// Load the resource with the specified name.
bool LoadBinaryResource(const char* resource_name, std::string& resource_data);
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name);
#endif
#endif // CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_

View File

@@ -1,67 +0,0 @@
// Copyright (c) 2011 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.
#include "cefclient/resource_util.h"
#include <stdio.h>
#include <string>
#include "include/cef_stream.h"
#include "cefclient/util.h"
bool GetResourceDir(std::string& dir) {
char buff[1024];
// Retrieve the executable path.
ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1);
if (len == -1)
return false;
buff[len] = 0;
// Remove the executable name from the path.
char* pos = strrchr(buff, '/');
if (!pos)
return false;
// Add "files" to the path.
strcpy(pos+1, "files"); // NOLINT(runtime/printf)
dir = std::string(buff);
return true;
}
bool LoadBinaryResource(const char* resource_name, std::string& resource_data) {
std::string path;
if (!GetResourceDir(path))
return false;
path.append("/");
path.append(resource_name);
FILE* f = fopen(path.c_str(), "rb");
if (!f)
return false;
size_t bytes_read;
char buff[1024*8];
do {
bytes_read = fread(buff, 1, sizeof(buff)-1, f);
if (bytes_read > 0)
resource_data.append(buff, bytes_read);
} while (bytes_read > 0);
fclose(f);
return true;
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name) {
std::string path;
if (!GetResourceDir(path))
return NULL;
path.append("/");
path.append(resource_name);
return CefStreamReader::CreateForFile(path);
}

View File

@@ -1,97 +0,0 @@
// Copyright (c) 2011 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.
#import <Foundation/Foundation.h>
#include <mach-o/dyld.h>
#include <stdio.h>
#include "cefclient/resource_util.h"
#include "include/cef_stream.h"
#include "cefclient/util.h"
namespace {
bool AmIBundled() {
// Implementation adapted from Chromium's base/mac/foundation_util.mm
ProcessSerialNumber psn = {0, kCurrentProcess};
FSRef fsref;
OSStatus pbErr;
if ((pbErr = GetProcessBundleLocation(&psn, &fsref)) != noErr) {
ASSERT(false);
return false;
}
FSCatalogInfo info;
OSErr fsErr;
if ((fsErr = FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info,
NULL, NULL, NULL)) != noErr) {
ASSERT(false);
return false;
}
return (info.nodeFlags & kFSNodeIsDirectoryMask);
}
bool GetResourceDir(std::string& dir) {
// Implementation adapted from Chromium's base/base_path_mac.mm
if (AmIBundled()) {
// Retrieve the executable directory.
uint32_t pathSize = 0;
_NSGetExecutablePath(NULL, &pathSize);
if (pathSize > 0) {
dir.resize(pathSize);
_NSGetExecutablePath(const_cast<char*>(dir.c_str()), &pathSize);
}
// Trim executable name up to the last separator
std::string::size_type last_separator = dir.find_last_of("/");
dir.resize(last_separator);
dir.append("/../Resources");
return true;
} else {
// TODO: Provide unbundled path
ASSERT(false);
return false;
}
}
bool ReadFileToString(const char* path, std::string& data) {
// Implementation adapted from base/file_util.cc
FILE* file = fopen(path, "rb");
if (!file)
return false;
char buf[1 << 16];
size_t len;
while ((len = fread(buf, 1, sizeof(buf), file)) > 0)
data.append(buf, len);
fclose(file);
return true;
}
} // namespace
bool LoadBinaryResource(const char* resource_name, std::string& resource_data) {
std::string path;
if (!GetResourceDir(path))
return false;
path.append("/");
path.append(resource_name);
return ReadFileToString(path.c_str(), resource_data);
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(const char* resource_name) {
std::string path;
if (!GetResourceDir(path))
return NULL;
path.append("/");
path.append(resource_name);
return CefStreamReader::CreateForFile(path);
}

View File

@@ -1,40 +0,0 @@
// 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 "cefclient/resource_util.h"
#include "include/cef_stream.h"
#include "include/wrapper/cef_byte_read_handler.h"
#if defined(OS_WIN)
bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes) {
extern HINSTANCE hInst;
HRSRC hRes = FindResource(hInst, MAKEINTRESOURCE(binaryId),
MAKEINTRESOURCE(256));
if (hRes) {
HGLOBAL hGlob = LoadResource(hInst, hRes);
if (hGlob) {
dwSize = SizeofResource(hInst, hRes);
pBytes = (LPBYTE)LockResource(hGlob);
if (dwSize > 0 && pBytes)
return true;
}
}
return false;
}
CefRefPtr<CefStreamReader> GetBinaryResourceReader(int binaryId) {
DWORD dwSize;
LPBYTE pBytes;
if (LoadBinaryResource(binaryId, dwSize, pBytes)) {
return CefStreamReader::CreateForHandler(
new CefByteReadHandler(pBytes, dwSize, NULL));
}
return NULL;
}
#endif // OS_WIN

View File

@@ -1,168 +0,0 @@
// 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 "cefclient/scheme_test.h"
#include <algorithm>
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_response.h"
#include "include/cef_request.h"
#include "include/cef_scheme.h"
#include "cefclient/resource_util.h"
#include "cefclient/string_util.h"
#include "cefclient/util.h"
#if defined(OS_WIN)
#include "cefclient/resource.h"
#endif
// Implementation of the schema handler for client:// requests.
class ClientSchemeHandler : public CefSchemeHandler {
public:
ClientSchemeHandler() : offset_(0) {}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefSchemeHandlerCallback> callback)
OVERRIDE {
REQUIRE_IO_THREAD();
bool handled = false;
AutoLock lock_scope(this);
std::string url = request->GetURL();
if (strstr(url.c_str(), "handler.html") != NULL) {
// Build the response html
data_ = "<html><head><title>Client Scheme Handler</title></head><body>"
"This contents of this page page are served by the "
"ClientSchemeHandler class handling the client:// protocol."
"<br/>You should see an image:"
"<br/><img src=\"client://tests/client.png\"><pre>";
// Output a string representation of the request
std::string dump;
DumpRequestContents(request, dump);
data_.append(dump);
data_.append("</pre><br/>Try the test form:"
"<form method=\"POST\" action=\"handler.html\">"
"<input type=\"text\" name=\"field1\">"
"<input type=\"text\" name=\"field2\">"
"<input type=\"submit\">"
"</form></body></html>");
handled = true;
// Set the resulting mime type
mime_type_ = "text/html";
} else if (strstr(url.c_str(), "client.png") != NULL) {
// Load the response image
#if defined(OS_WIN)
DWORD dwSize;
LPBYTE pBytes;
if (LoadBinaryResource(IDS_LOGO, dwSize, pBytes)) {
data_ = std::string(reinterpret_cast<const char*>(pBytes), dwSize);
handled = true;
// Set the resulting mime type
mime_type_ = "image/jpg";
}
#elif defined(OS_MACOSX) || defined(OS_LINUX)
if (LoadBinaryResource("logo.png", data_)) {
handled = true;
// Set the resulting mime type
mime_type_ = "image/png";
}
#else
#error "Unsupported platform"
#endif
}
if (handled) {
// Indicate the headers are available.
callback->HeadersAvailable();
return true;
}
return false;
}
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length,
CefString& redirectUrl) OVERRIDE {
REQUIRE_IO_THREAD();
ASSERT(!data_.empty());
response->SetMimeType(mime_type_);
response->SetStatus(200);
// Set the resulting response length
response_length = data_.length();
}
virtual void Cancel() OVERRIDE {
REQUIRE_IO_THREAD();
}
virtual bool ReadResponse(void* data_out,
int bytes_to_read,
int& bytes_read,
CefRefPtr<CefSchemeHandlerCallback> callback)
OVERRIDE {
REQUIRE_IO_THREAD();
bool has_data = false;
bytes_read = 0;
AutoLock lock_scope(this);
if (offset_ < data_.length()) {
// Copy the next block of data into the buffer.
int transfer_size =
std::min(bytes_to_read, static_cast<int>(data_.length() - offset_));
memcpy(data_out, data_.c_str() + offset_, transfer_size);
offset_ += transfer_size;
bytes_read = transfer_size;
has_data = true;
}
return has_data;
}
private:
std::string data_;
std::string mime_type_;
size_t offset_;
IMPLEMENT_REFCOUNTING(ClientSchemeHandler);
IMPLEMENT_LOCKING(ClientSchemeHandler);
};
// Implementation of the factory for for creating schema handlers.
class ClientSchemeHandlerFactory : public CefSchemeHandlerFactory {
public:
// Return a new scheme handler instance to handle the request.
virtual CefRefPtr<CefSchemeHandler> Create(CefRefPtr<CefBrowser> browser,
const CefString& scheme_name,
CefRefPtr<CefRequest> request)
OVERRIDE {
REQUIRE_IO_THREAD();
return new ClientSchemeHandler();
}
IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory);
};
void InitSchemeTest() {
CefRegisterCustomScheme("client", true, false, false);
CefRegisterSchemeHandlerFactory("client", "tests",
new ClientSchemeHandlerFactory());
}
void RunSchemeTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("client://tests/handler.html");
}

View File

@@ -1,19 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_
#define CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_
#pragma once
#include "include/cef_base.h"
class CefBrowser;
// Register the scheme handler.
void InitSchemeTest();
// Run the test.
void RunSchemeTest(CefRefPtr<CefBrowser> browser);
#endif // CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_

View File

@@ -1,74 +0,0 @@
// 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 "cefclient/string_util.h"
#include <sstream>
#include <string>
#include "include/cef_request.h"
void DumpRequestContents(CefRefPtr<CefRequest> request, std::string& str) {
std::stringstream ss;
ss << "URL: " << std::string(request->GetURL());
ss << "\nMethod: " << std::string(request->GetMethod());
CefRequest::HeaderMap headerMap;
request->GetHeaderMap(headerMap);
if (headerMap.size() > 0) {
ss << "\nHeaders:";
CefRequest::HeaderMap::const_iterator it = headerMap.begin();
for (; it != headerMap.end(); ++it) {
ss << "\n\t" << std::string((*it).first) << ": " <<
std::string((*it).second);
}
}
CefRefPtr<CefPostData> postData = request->GetPostData();
if (postData.get()) {
CefPostData::ElementVector elements;
postData->GetElements(elements);
if (elements.size() > 0) {
ss << "\nPost Data:";
CefRefPtr<CefPostDataElement> element;
CefPostData::ElementVector::const_iterator it = elements.begin();
for (; it != elements.end(); ++it) {
element = (*it);
if (element->GetType() == PDE_TYPE_BYTES) {
// the element is composed of bytes
ss << "\n\tBytes: ";
if (element->GetBytesCount() == 0) {
ss << "(empty)";
} else {
// retrieve the data.
size_t size = element->GetBytesCount();
char* bytes = new char[size];
element->GetBytes(size, bytes);
ss << std::string(bytes, size);
delete [] bytes;
}
} else if (element->GetType() == PDE_TYPE_FILE) {
ss << "\n\tFile: " << std::string(element->GetFile());
}
}
}
}
str = ss.str();
}
std::string StringReplace(const std::string& str, const std::string& from,
const std::string& to) {
std::string result = str;
std::string::size_type pos = 0;
std::string::size_type from_len = from.length();
std::string::size_type to_len = to.length();
do {
pos = result.find(from, pos);
if (pos != std::string::npos) {
result.replace(pos, from_len, to);
pos += to_len;
}
} while (pos != std::string::npos);
return result;
}

View File

@@ -1,21 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_STRING_UTIL_H_
#define CEF_TESTS_CEFCLIENT_STRING_UTIL_H_
#pragma once
#include <string>
#include "include/cef_base.h"
class CefRequest;
// Dump the contents of the request into a string.
void DumpRequestContents(CefRefPtr<CefRequest> request, std::string& str);
// Replace all instances of |from| with |to| in |str|.
std::string StringReplace(const std::string& str, const std::string& from,
const std::string& to);
#endif // CEF_TESTS_CEFCLIENT_STRING_UTIL_H_

View File

@@ -1,288 +0,0 @@
// Copyright (c) 2009 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cefclient/uiplugin.h"
#if defined(OS_WIN)
#include <windows.h>
#include <gl/gl.h>
#include <sstream>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "cefclient/cefclient.h"
// Initialized in NP_Initialize.
NPNetscapeFuncs* g_uibrowser = NULL;
namespace {
// Global values.
float g_rotationspeed = 0.0f;
float g_theta = 0.0f;
// Class holding pointers for the client plugin window.
class ClientPlugin {
public:
ClientPlugin() {
hWnd = NULL;
hDC = NULL;
hRC = NULL;
}
HWND hWnd;
HDC hDC;
HGLRC hRC;
};
// Forward declarations of functions included in this code module:
LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam);
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC);
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC);
NPError NPP_NewImpl(NPMIMEType plugin_type, NPP instance, uint16 mode,
int16 argc, char* argn[], char* argv[],
NPSavedData* saved) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
ClientPlugin* plugin = new ClientPlugin;
instance->pdata = reinterpret_cast<void*>(plugin);
return NPERR_NO_ERROR;
}
NPError NPP_DestroyImpl(NPP instance, NPSavedData** save) {
ClientPlugin* plugin = reinterpret_cast<ClientPlugin*>(instance->pdata);
if (plugin) {
if (plugin->hWnd) {
DestroyWindow(plugin->hWnd);
DisableOpenGL(plugin->hWnd, plugin->hDC, plugin->hRC);
}
delete plugin;
g_rotationspeed = 0.0f;
g_theta = 0.0f;
}
return NPERR_NO_ERROR;
}
NPError NPP_SetWindowImpl(NPP instance, NPWindow* window_info) {
if (instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
if (window_info == NULL)
return NPERR_GENERIC_ERROR;
ClientPlugin* plugin = reinterpret_cast<ClientPlugin*>(instance->pdata);
HWND parent_hwnd = reinterpret_cast<HWND>(window_info->window);
if (plugin->hWnd == NULL) {
WNDCLASS wc;
HINSTANCE hInstance = GetModuleHandle(NULL);
// Register the window class.
wc.style = CS_OWNDC;
wc.lpfnWndProc = PluginWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = L"ClientUIPlugin";
RegisterClass(&wc);
// Create the main window.
plugin->hWnd = CreateWindow(L"ClientUIPlugin", L"Client UI Plugin",
WS_CHILD, 0, 0, 0, 0, parent_hwnd, NULL, hInstance, NULL);
SetWindowLongPtr(plugin->hWnd, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(plugin));
// Enable OpenGL drawing for the window.
EnableOpenGL(plugin->hWnd, &(plugin->hDC), &(plugin->hRC));
}
// Position the window and make sure it's visible.
RECT parent_rect;
GetClientRect(parent_hwnd, &parent_rect);
SetWindowPos(plugin->hWnd, NULL, parent_rect.left, parent_rect.top,
parent_rect.right - parent_rect.left,
parent_rect.bottom - parent_rect.top, SWP_SHOWWINDOW);
UpdateWindow(plugin->hWnd);
ShowWindow(plugin->hWnd, SW_SHOW);
return NPERR_NO_ERROR;
}
// Send the notification to the browser as a JavaScript function call.
static void NotifyNewRotation(float value) {
std::stringstream buf;
buf << "notifyNewRotation(" << value << ");";
AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(buf.str(), CefString(),
0);
}
// Nice little fly polygon borrowed from the OpenGL Red Book.
const GLubyte fly[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60,
0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20,
0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20,
0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC,
0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30,
0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0,
0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0,
0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30,
0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08,
0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08,
0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08};
// Plugin window procedure.
LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam) {
ClientPlugin* plugin =
reinterpret_cast<ClientPlugin*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (message) {
case WM_CREATE:
// Start the timer that's used for redrawing.
SetTimer(hWnd, 1, 1, NULL);
return 0;
case WM_DESTROY:
// Stop the timer that's used for redrawing.
KillTimer(hWnd, 1);
return 0;
case WM_LBUTTONDOWN:
// Decrement rotation speed.
ModifyRotation(-2.0f);
return 0;
case WM_RBUTTONDOWN:
// Increment rotation speed.
ModifyRotation(2.0f);
return 0;
case WM_SIZE:
if (plugin) {
// Resize the OpenGL viewport to match the window size.
int width = LOWORD(lParam);
int height = HIWORD(lParam);
wglMakeCurrent(plugin->hDC, plugin->hRC);
glViewport(0, 0, width, height);
}
break;
case WM_ERASEBKGND:
return 0;
case WM_TIMER:
wglMakeCurrent(plugin->hDC, plugin->hRC);
// Adjust the theta value and redraw the display when the timer fires.
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glEnable(GL_POLYGON_STIPPLE);
glPolygonStipple(fly);
glRotatef(g_theta, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2f(0.7f, 0.7f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex2f(0.7f, -0.7f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2f(-0.7f, -0.7f);
glColor3f(1.0f, 0.0f, 1.0f);
glVertex2f(-0.7f, 0.7f);
glEnd();
glDisable(GL_POLYGON_STIPPLE);
glPopMatrix();
SwapBuffers(plugin->hDC);
g_theta -= g_rotationspeed;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// Enable OpenGL.
void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC) {
PIXELFORMATDESCRIPTOR pfd;
int format;
// Get the device context.
*hDC = GetDC(hWnd);
// Set the pixel format for the DC.
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat(*hDC, &pfd);
SetPixelFormat(*hDC, format, &pfd);
// Create and enable the render contex.
*hRC = wglCreateContext(*hDC);
}
// Disable OpenGL.
void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC);
ReleaseDC(hWnd, hDC);
}
} // namespace
NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs) {
pFuncs->newp = NPP_NewImpl;
pFuncs->destroy = NPP_DestroyImpl;
pFuncs->setwindow = NPP_SetWindowImpl;
return NPERR_NO_ERROR;
}
NPError API_CALL NP_UIInitialize(NPNetscapeFuncs* pFuncs) {
g_uibrowser = pFuncs;
return NPERR_NO_ERROR;
}
NPError API_CALL NP_UIShutdown(void) {
g_uibrowser = NULL;
return NPERR_NO_ERROR;
}
void ModifyRotation(float value) {
g_rotationspeed += value;
NotifyNewRotation(g_rotationspeed);
}
void ResetRotation() {
g_rotationspeed = 0.0;
NotifyNewRotation(g_rotationspeed);
}
#endif // OS_WIN

View File

@@ -1,30 +0,0 @@
// Copyright (c) 2009 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Portions of this implementation are borrowed from webkit\default_plugin\
// plugin_impl.h
#ifndef CEF_TESTS_CEFCLIENT_UIPLUGIN_H_
#define CEF_TESTS_CEFCLIENT_UIPLUGIN_H_
#pragma once
#include "include/cef_nplugin.h"
#if defined(OS_WIN)
extern NPNetscapeFuncs* g_uibrowser;
NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs);
NPError API_CALL NP_UIInitialize(NPNetscapeFuncs* pFuncs);
NPError API_CALL NP_UIShutdown(void);
// Function called to modify the rotation value.
void ModifyRotation(float value);
// Function called to reset the rotation value.
void ResetRotation();
#endif // OS_WIN
#endif // CEF_TESTS_CEFCLIENT_UIPLUGIN_H_

View File

@@ -1,103 +0,0 @@
// 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 "cefclient/uiplugin_test.h"
#include <string>
#include "include/cef_browser.h"
#include "include/cef_frame.h"
#include "include/cef_v8.h"
#include "cefclient/uiplugin.h"
#include "cefclient/cefclient.h"
// Implementation of the V8 handler class for the "window.uiapp" functions.
class ClientV8UIHandler : public CefV8Handler {
public:
ClientV8UIHandler() {}
// Execute with the specified argument list and return value. Return true if
// the method was handled.
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
if (name == "modifyRotation") {
// This function requires one argument.
if (arguments.size() != 1)
return false;
float increment = 0.;
if (arguments[0]->IsInt()) {
// The argument is an integer value.
increment = static_cast<float>(arguments[0]->GetIntValue());
} else if (arguments[0]->IsDouble()) {
// The argument is an double value.
increment = static_cast<float>(arguments[0]->GetDoubleValue());
}
if (increment != 0.) {
// Modify the rotation accordingly.
ModifyRotation(increment);
return true;
}
} else if (name == "resetRotation") {
// Reset the rotation value.
ResetRotation();
return true;
} else if (name == "viewSource") {
// View the page source.
AppGetBrowser()->GetMainFrame()->ViewSource();
return true;
}
return false;
}
IMPLEMENT_REFCOUNTING(ClientV8UIHandler);
};
void InitUIPluginTest() {
// Structure providing information about the client plugin.
CefPluginInfo plugin_info;
CefString(&plugin_info.display_name).FromASCII("Client UI Plugin");
CefString(&plugin_info.unique_name).FromASCII("client_ui_plugin");
CefString(&plugin_info.description).FromASCII("My Example Client UI Plugin");
CefString(&plugin_info.mime_types).FromASCII(
"application/x-client-ui-plugin");
plugin_info.np_getentrypoints = NP_UIGetEntryPoints;
plugin_info.np_initialize = NP_UIInitialize;
plugin_info.np_shutdown = NP_UIShutdown;
// Register the internal client plugin
CefRegisterPlugin(plugin_info);
// Register a V8 extension with the below JavaScript code that calls native
// methods implemented in ClientV8UIHandler.
std::string code = "var cef;"
"if (!cef)"
" cef = {};"
"if (!cef.uiapp)"
" cef.uiapp = {};"
"(function() {"
" cef.uiapp.modifyRotation = function(val) {"
" native function modifyRotation();"
" return modifyRotation(val);"
" };"
" cef.uiapp.resetRotation = function() {"
" native function resetRotation();"
" return resetRotation();"
" };"
" cef.uiapp.viewSource = function() {"
" native function viewSource();"
" return viewSource();"
" };"
"})();";
CefRegisterExtension("uiplugin/test", code, new ClientV8UIHandler());
}
void RunUIPluginTest(CefRefPtr<CefBrowser> browser) {
browser->GetMainFrame()->LoadURL("http://tests/uiapp");
}

View File

@@ -1,19 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_UIPLUGIN_TEST_H_
#define CEF_TESTS_CEFCLIENT_UIPLUGIN_TEST_H_
#pragma once
#include "include/cef_base.h"
class CefBrowser;
// Register the internal client plugin and V8 extension.
void InitUIPluginTest();
// Run the test.
void RunUIPluginTest(CefRefPtr<CefBrowser> browser);
#endif // CEF_TESTS_CEFCLIENT_UIPLUGIN_TEST_H_

View File

@@ -1,37 +0,0 @@
// 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.
#ifndef CEF_TESTS_CEFCLIENT_UTIL_H_
#define CEF_TESTS_CEFCLIENT_UTIL_H_
#pragma once
#include "include/cef_task.h"
#if defined(OS_WIN)
#include <windows.h> // NOLINT(build/include_order)
#ifndef NDEBUG
#define ASSERT(condition) if (!(condition)) { DebugBreak(); }
#else
#define ASSERT(condition) ((void)0)
#endif
#else // !OS_WIN
#include <assert.h> // NOLINT(build/include_order)
#ifndef NDEBUG
#define ASSERT(condition) if (!(condition)) { assert(false); }
#else
#define ASSERT(condition) ((void)0)
#endif
#endif // !OS_WIN
#define REQUIRE_UI_THREAD() ASSERT(CefCurrentlyOn(TID_UI));
#define REQUIRE_IO_THREAD() ASSERT(CefCurrentlyOn(TID_IO));
#define REQUIRE_FILE_THREAD() ASSERT(CefCurrentlyOn(TID_FILE));
#endif // CEF_TESTS_CEFCLIENT_UTIL_H_