diff --git a/AUTHORS.txt b/AUTHORS.txt index 5bf04b70d..9deb3eaa9 100644 --- a/AUTHORS.txt +++ b/AUTHORS.txt @@ -1,5 +1,5 @@ -# This file is an addendum to the Chromium AUTHORS file. -# Names should be added to this file like so: -# Name or Organization - +# This file is an addendum to the Chromium AUTHORS file. +# Names should be added to this file like so: +# Name or Organization + Marshall Greenblatt \ No newline at end of file diff --git a/include/cef_export.h b/include/cef_export.h index 4e2f251ae..738487b0f 100644 --- a/include/cef_export.h +++ b/include/cef_export.h @@ -1,32 +1,32 @@ // Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef _MSC_VER // MSVC diff --git a/include/cef_nplugin.h b/include/cef_nplugin.h index bd02f7531..014cb814b 100644 --- a/include/cef_nplugin.h +++ b/include/cef_nplugin.h @@ -1,85 +1,85 @@ -// Copyright (c) 2008 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -#ifndef _CEF_PLUGIN_H -#define _CEF_PLUGIN_H - -#include -#include -#include "webkit/glue/plugins/nphostapi.h" -#include "third_party/npapi/bindings/npapi.h" - -// Netscape plugins are normally built at separate DLLs that are loaded by the -// browser when needed. This interface supports the creation of plugins that -// are an embedded component of the application. Embedded plugins built using -// this interface use the same Netscape Plugin API as DLL-based plugins. -// See https://developer.mozilla.org/En/Gecko_Plugin_API_Reference for complete -// documentation on how to use the Netscape Plugin API. - -// This structure describes a mime type entry for a plugin. -struct CefPluginMimeType { - // The actual mime type. - std::wstring mime_type; - - // A list of all the file extensions for this mime type. - std::vector file_extensions; - - // Description of the mime type. - std::wstring description; -}; - -// This structure provides attribute information and entry point functions for -// a plugin. -struct CefPluginInfo { - // The unique name that identifies the plugin. - std::wstring unique_name; - - // The friendly display name of the plugin. - std::wstring display_name; - - // The version string of the plugin. - std::wstring version; - - // A description of the plugin. - std::wstring description; - - // A list of all the mime types that this plugin supports. - std::vector mime_types; - - // Entry point function pointers. - NP_GetEntryPointsFunc np_getentrypoints; - NP_InitializeFunc np_initialize; - NP_ShutdownFunc np_shutdown; -}; - -// Register a plugin with the system. -bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info); - -#endif // _CEF_PLUGIN_H +// Copyright (c) 2008 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +#ifndef _CEF_PLUGIN_H +#define _CEF_PLUGIN_H + +#include +#include +#include "webkit/glue/plugins/nphostapi.h" +#include "third_party/npapi/bindings/npapi.h" + +// Netscape plugins are normally built at separate DLLs that are loaded by the +// browser when needed. This interface supports the creation of plugins that +// are an embedded component of the application. Embedded plugins built using +// this interface use the same Netscape Plugin API as DLL-based plugins. +// See https://developer.mozilla.org/En/Gecko_Plugin_API_Reference for complete +// documentation on how to use the Netscape Plugin API. + +// This structure describes a mime type entry for a plugin. +struct CefPluginMimeType { + // The actual mime type. + std::wstring mime_type; + + // A list of all the file extensions for this mime type. + std::vector file_extensions; + + // Description of the mime type. + std::wstring description; +}; + +// This structure provides attribute information and entry point functions for +// a plugin. +struct CefPluginInfo { + // The unique name that identifies the plugin. + std::wstring unique_name; + + // The friendly display name of the plugin. + std::wstring display_name; + + // The version string of the plugin. + std::wstring version; + + // A description of the plugin. + std::wstring description; + + // A list of all the mime types that this plugin supports. + std::vector mime_types; + + // Entry point function pointers. + NP_GetEntryPointsFunc np_getentrypoints; + NP_InitializeFunc np_initialize; + NP_ShutdownFunc np_shutdown; +}; + +// Register a plugin with the system. +bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info); + +#endif // _CEF_PLUGIN_H diff --git a/include/cef_nplugin_capi.h b/include/cef_nplugin_capi.h index 01084a599..c24d2e48b 100644 --- a/include/cef_nplugin_capi.h +++ b/include/cef_nplugin_capi.h @@ -1,64 +1,64 @@ -// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -#ifndef _CEF_PLUGIN_CAPI_H -#define _CEF_PLUGIN_CAPI_H - +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +#ifndef _CEF_PLUGIN_CAPI_H +#define _CEF_PLUGIN_CAPI_H + #ifdef __cplusplus extern "C" { #endif #include "cef_export.h" -#include "webkit/glue/plugins/nphostapi.h" -#include "third_party/npapi/bindings/npapi.h" - -// Netscape plugins are normally built at separate DLLs that are loaded by the -// browser when needed. This interface supports the creation of plugins that -// are an embedded component of the application. Embedded plugins built using -// this interface use the same Netscape Plugin API as DLL-based plugins. -// See https://developer.mozilla.org/En/Gecko_Plugin_API_Reference for complete -// documentation on how to use the Netscape Plugin API. - -// This structure provides attribute information and entry point functions for -// a plugin. -typedef struct _cef_plugin_info_t { - // The unique name that identifies the plugin. - const wchar_t* unique_name; - - // The friendly display name of the plugin. - const wchar_t* display_name; - - // The version string of the plugin. - const wchar_t* version; - - // A description of the plugin. +#include "webkit/glue/plugins/nphostapi.h" +#include "third_party/npapi/bindings/npapi.h" + +// Netscape plugins are normally built at separate DLLs that are loaded by the +// browser when needed. This interface supports the creation of plugins that +// are an embedded component of the application. Embedded plugins built using +// this interface use the same Netscape Plugin API as DLL-based plugins. +// See https://developer.mozilla.org/En/Gecko_Plugin_API_Reference for complete +// documentation on how to use the Netscape Plugin API. + +// This structure provides attribute information and entry point functions for +// a plugin. +typedef struct _cef_plugin_info_t { + // The unique name that identifies the plugin. + const wchar_t* unique_name; + + // The friendly display name of the plugin. + const wchar_t* display_name; + + // The version string of the plugin. + const wchar_t* version; + + // A description of the plugin. const wchar_t* description; // A pipe (|) delimited list of mime type values that the plugin supports. @@ -71,20 +71,20 @@ typedef struct _cef_plugin_info_t { // A pipe (|) delimited list of description values. Each value is associated // with the mime type value at the same position. - const wchar_t* type_descriptions; - - // Entry point function pointers. - NP_GetEntryPointsFunc np_getentrypoints; - NP_InitializeFunc np_initialize; - NP_ShutdownFunc np_shutdown; -} cef_plugin_info_t; - -// Register a plugin with the system. Returns true (1) on success. -CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info); - + const wchar_t* type_descriptions; + + // Entry point function pointers. + NP_GetEntryPointsFunc np_getentrypoints; + NP_InitializeFunc np_initialize; + NP_ShutdownFunc np_shutdown; +} cef_plugin_info_t; + +// Register a plugin with the system. Returns true (1) on success. +CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info); + #ifdef __cplusplus } #endif -#endif // _CEF_PLUGIN_CAPI_H +#endif // _CEF_PLUGIN_CAPI_H diff --git a/include/cef_ptr.h b/include/cef_ptr.h index 7a091e2df..cdba1ceb4 100644 --- a/include/cef_ptr.h +++ b/include/cef_ptr.h @@ -1,126 +1,126 @@ -// Copyright (c) 2008 Marshall A. Greenblatt. Portions Copyright (c) -// 2006-2008 Google Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright (c) 2008 Marshall A. Greenblatt. Portions Copyright (c) +// 2006-2008 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_PTR_H #define _CEF_PTR_H // Smart pointer implementation borrowed from base/ref_counted.h -// -// A smart pointer class for reference counted objects. Use this class instead -// of calling AddRef and Release manually on a reference counted object to -// avoid common memory leaks caused by forgetting to Release an object -// reference. Sample usage: -// -// class MyFoo : public CefBase { -// ... -// }; -// -// void some_function() { -// // The MyFoo object that |foo| represents starts with a single -// // reference. -// CefRefPtr foo = new MyFoo(); -// foo->Method(param); -// // |foo| is released when this function returns -// } -// -// void some_other_function() { -// CefRefPtr foo = new MyFoo(); -// ... -// foo = NULL; // explicitly releases |foo| -// ... -// if (foo) -// foo->Method(param); -// } -// -// The above examples show how CefRefPtr acts like a pointer to T. -// Given two CefRefPtr classes, it is also possible to exchange -// references between the two objects, like so: -// -// { -// CefRefPtr a = new MyFoo(); -// CefRefPtr b; -// -// b.swap(a); -// // now, |b| references the MyFoo object, and |a| references NULL. -// } -// -// To make both |a| and |b| in the above example reference the same MyFoo -// object, simply use the assignment operator: -// -// { -// CefRefPtr a = new MyFoo(); -// CefRefPtr b; -// -// b = a; -// // now, |a| and |b| each own a reference to the same MyFoo object. -// // the reference count of the underlying MyFoo object will be 2. -// } -// -// Reference counted objects can also be passed as function parameters and -// used as function return values: -// -// void some_func_with_param(CefRefPtr param) { -// // A reference is added to the MyFoo object that |param| represents -// // during the scope of some_func_with_param() and released when -// // some_func_with_param() goes out of scope. -// } -// -// CefRefPtr some_func_with_retval() { -// // The MyFoo object that |foox| represents starts with a single -// // reference. -// CefRefPtr foox = new MyFoo(); -// -// // Creating the return value adds an additional reference. -// return foox; -// -// // When some_func_with_retval() goes out of scope the original |foox| -// // reference is released. -// } -// -// void and_another_function() { -// CefRefPtr foo = new MyFoo(); -// -// // pass |foo| as a parameter. -// some_function(foo); -// -// CefRefPtr foo2 = some_func_with_retval(); -// // Now, since we kept a reference to the some_func_with_retval() return -// // value, |foo2| is the only class pointing to the MyFoo object created -// in some_func_with_retval(), and it has a reference count of 1. -// -// some_func_with_retval(); -// // Now, since we didn't keep a reference to the some_func_with_retval() -// // return value, the MyFoo object created in some_func_with_retval() -// // will automatically be released. -// } +// +// A smart pointer class for reference counted objects. Use this class instead +// of calling AddRef and Release manually on a reference counted object to +// avoid common memory leaks caused by forgetting to Release an object +// reference. Sample usage: +// +// class MyFoo : public CefBase { +// ... +// }; +// +// void some_function() { +// // The MyFoo object that |foo| represents starts with a single +// // reference. +// CefRefPtr foo = new MyFoo(); +// foo->Method(param); +// // |foo| is released when this function returns +// } +// +// void some_other_function() { +// CefRefPtr foo = new MyFoo(); +// ... +// foo = NULL; // explicitly releases |foo| +// ... +// if (foo) +// foo->Method(param); +// } +// +// The above examples show how CefRefPtr acts like a pointer to T. +// Given two CefRefPtr classes, it is also possible to exchange +// references between the two objects, like so: +// +// { +// CefRefPtr a = new MyFoo(); +// CefRefPtr b; +// +// b.swap(a); +// // now, |b| references the MyFoo object, and |a| references NULL. +// } +// +// To make both |a| and |b| in the above example reference the same MyFoo +// object, simply use the assignment operator: +// +// { +// CefRefPtr a = new MyFoo(); +// CefRefPtr b; +// +// b = a; +// // now, |a| and |b| each own a reference to the same MyFoo object. +// // the reference count of the underlying MyFoo object will be 2. +// } +// +// Reference counted objects can also be passed as function parameters and +// used as function return values: +// +// void some_func_with_param(CefRefPtr param) { +// // A reference is added to the MyFoo object that |param| represents +// // during the scope of some_func_with_param() and released when +// // some_func_with_param() goes out of scope. +// } +// +// CefRefPtr some_func_with_retval() { +// // The MyFoo object that |foox| represents starts with a single +// // reference. +// CefRefPtr foox = new MyFoo(); +// +// // Creating the return value adds an additional reference. +// return foox; +// +// // When some_func_with_retval() goes out of scope the original |foox| +// // reference is released. +// } +// +// void and_another_function() { +// CefRefPtr foo = new MyFoo(); +// +// // pass |foo| as a parameter. +// some_function(foo); +// +// CefRefPtr foo2 = some_func_with_retval(); +// // Now, since we kept a reference to the some_func_with_retval() return +// // value, |foo2| is the only class pointing to the MyFoo object created +// in some_func_with_retval(), and it has a reference count of 1. +// +// some_func_with_retval(); +// // Now, since we didn't keep a reference to the some_func_with_retval() +// // return value, the MyFoo object created in some_func_with_retval() +// // will automatically be released. +// } // // And in standard containers: // @@ -128,66 +128,66 @@ // // Create a vector that holds MyFoo objects. // std::vector > MyFooVec; // -// // The MyFoo object that |foo| represents starts with a single -// // reference. -// CefRefPtr foo = new MyFoo(); -// -// // When the MyFoo object is added to |MyFooVec| the reference count -// // is increased to 2. -// MyFooVec.push_back(foo); +// // The MyFoo object that |foo| represents starts with a single +// // reference. +// CefRefPtr foo = new MyFoo(); +// +// // When the MyFoo object is added to |MyFooVec| the reference count +// // is increased to 2. +// MyFooVec.push_back(foo); // } // -template -class CefRefPtr { - public: - CefRefPtr() : ptr_(NULL) { - } - - CefRefPtr(T* p) : ptr_(p) { - if (ptr_) - ptr_->AddRef(); - } - - CefRefPtr(const CefRefPtr& r) : ptr_(r.ptr_) { - if (ptr_) - ptr_->AddRef(); - } - - ~CefRefPtr() { - if (ptr_) - ptr_->Release(); - } - - T* get() const { return ptr_; } - operator T*() const { return ptr_; } - T* operator->() const { return ptr_; } - - CefRefPtr& operator=(T* p) { - // AddRef first so that self assignment should work - if (p) - p->AddRef(); - if (ptr_ ) - ptr_ ->Release(); - ptr_ = p; - return *this; - } - - CefRefPtr& operator=(const CefRefPtr& r) { - return *this = r.ptr_; - } - - void swap(T** pp) { - T* p = ptr_; - ptr_ = *pp; - *pp = p; - } - - void swap(CefRefPtr& r) { - swap(&r.ptr_); - } - - private: - T* ptr_; +template +class CefRefPtr { + public: + CefRefPtr() : ptr_(NULL) { + } + + CefRefPtr(T* p) : ptr_(p) { + if (ptr_) + ptr_->AddRef(); + } + + CefRefPtr(const CefRefPtr& r) : ptr_(r.ptr_) { + if (ptr_) + ptr_->AddRef(); + } + + ~CefRefPtr() { + if (ptr_) + ptr_->Release(); + } + + T* get() const { return ptr_; } + operator T*() const { return ptr_; } + T* operator->() const { return ptr_; } + + CefRefPtr& operator=(T* p) { + // AddRef first so that self assignment should work + if (p) + p->AddRef(); + if (ptr_ ) + ptr_ ->Release(); + ptr_ = p; + return *this; + } + + CefRefPtr& operator=(const CefRefPtr& r) { + return *this = r.ptr_; + } + + void swap(T** pp) { + T* p = ptr_; + ptr_ = *pp; + *pp = p; + } + + void swap(CefRefPtr& r) { + swap(&r.ptr_); + } + + private: + T* ptr_; }; #endif // _CEF_PTR_H diff --git a/include/cef_string.h b/include/cef_string.h index 3b394a878..47469040e 100644 --- a/include/cef_string.h +++ b/include/cef_string.h @@ -1,30 +1,30 @@ -// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_STRING_H diff --git a/include/cef_string_list.h b/include/cef_string_list.h index ff7eb2b2f..759520db6 100644 --- a/include/cef_string_list.h +++ b/include/cef_string_list.h @@ -1,30 +1,30 @@ -// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_STRING_LIST_H diff --git a/include/cef_string_map.h b/include/cef_string_map.h index 041a19c35..5f1f689cd 100644 --- a/include/cef_string_map.h +++ b/include/cef_string_map.h @@ -1,30 +1,30 @@ -// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_STRING_MAP_H diff --git a/include/cef_types.h b/include/cef_types.h index 5f8fdb8bc..1b9b8b7c5 100644 --- a/include/cef_types.h +++ b/include/cef_types.h @@ -1,31 +1,31 @@ -// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_TYPES_H @@ -35,12 +35,12 @@ extern "C" { #endif - + // Bring in platform-specific definitions. #ifdef _WIN32 #include "cef_types_win.h" -#endif - +#endif + // Define handler return value types. Returning RV_HANDLED indicates // that the implementation completely handled the method and that no further @@ -56,11 +56,11 @@ enum cef_retval_t // Various browser navigation types supported by chrome. enum cef_handler_navtype_t { - NAVTYPE_LINKCLICKED = 0, - NAVTYPE_FORMSUBMITTED, - NAVTYPE_BACKFORWARD, - NAVTYPE_RELOAD, - NAVTYPE_FORMRESUBMITTED, + NAVTYPE_LINKCLICKED = 0, + NAVTYPE_FORMSUBMITTED, + NAVTYPE_BACKFORWARD, + NAVTYPE_RELOAD, + NAVTYPE_FORMRESUBMITTED, NAVTYPE_OTHER, }; @@ -68,62 +68,62 @@ enum cef_handler_navtype_t // descriptions of the error codes. enum cef_handler_errorcode_t { - ERR_FAILED = -2, - ERR_ABORTED = -3, - ERR_INVALID_ARGUMENT = -4, - ERR_INVALID_HANDLE = -5, - ERR_FILE_NOT_FOUND = -6, - ERR_TIMED_OUT = -7, - ERR_FILE_TOO_BIG = -8, - ERR_UNEXPECTED = -9, - ERR_ACCESS_DENIED = -10, - ERR_NOT_IMPLEMENTED = -11, - ERR_CONNECTION_CLOSED = -100, - ERR_CONNECTION_RESET = -101, - ERR_CONNECTION_REFUSED = -102, - ERR_CONNECTION_ABORTED = -103, - ERR_CONNECTION_FAILED = -104, - ERR_NAME_NOT_RESOLVED = -105, - ERR_INTERNET_DISCONNECTED = -106, - ERR_SSL_PROTOCOL_ERROR = -107, - ERR_ADDRESS_INVALID = -108, - ERR_ADDRESS_UNREACHABLE = -109, - ERR_SSL_CLIENT_AUTH_CERT_NEEDED = -110, - ERR_TUNNEL_CONNECTION_FAILED = -111, - ERR_NO_SSL_VERSIONS_ENABLED = -112, - ERR_SSL_VERSION_OR_CIPHER_MISMATCH = -113, - ERR_SSL_RENEGOTIATION_REQUESTED = -114, - ERR_CERT_COMMON_NAME_INVALID = -200, - ERR_CERT_DATE_INVALID = -201, - ERR_CERT_AUTHORITY_INVALID = -202, - ERR_CERT_CONTAINS_ERRORS = -203, - ERR_CERT_NO_REVOCATION_MECHANISM = -204, - ERR_CERT_UNABLE_TO_CHECK_REVOCATION = -205, - ERR_CERT_REVOKED = -206, - ERR_CERT_INVALID = -207, - ERR_CERT_END = -208, - ERR_INVALID_URL = -300, - ERR_DISALLOWED_URL_SCHEME = -301, - ERR_UNKNOWN_URL_SCHEME = -302, - ERR_TOO_MANY_REDIRECTS = -310, - ERR_UNSAFE_REDIRECT = -311, - ERR_UNSAFE_PORT = -312, - ERR_INVALID_RESPONSE = -320, - ERR_INVALID_CHUNKED_ENCODING = -321, - ERR_METHOD_NOT_SUPPORTED = -322, - ERR_UNEXPECTED_PROXY_AUTH = -323, - ERR_EMPTY_RESPONSE = -324, - ERR_RESPONSE_HEADERS_TOO_BIG = -325, - ERR_CACHE_MISS = -400, + ERR_FAILED = -2, + ERR_ABORTED = -3, + ERR_INVALID_ARGUMENT = -4, + ERR_INVALID_HANDLE = -5, + ERR_FILE_NOT_FOUND = -6, + ERR_TIMED_OUT = -7, + ERR_FILE_TOO_BIG = -8, + ERR_UNEXPECTED = -9, + ERR_ACCESS_DENIED = -10, + ERR_NOT_IMPLEMENTED = -11, + ERR_CONNECTION_CLOSED = -100, + ERR_CONNECTION_RESET = -101, + ERR_CONNECTION_REFUSED = -102, + ERR_CONNECTION_ABORTED = -103, + ERR_CONNECTION_FAILED = -104, + ERR_NAME_NOT_RESOLVED = -105, + ERR_INTERNET_DISCONNECTED = -106, + ERR_SSL_PROTOCOL_ERROR = -107, + ERR_ADDRESS_INVALID = -108, + ERR_ADDRESS_UNREACHABLE = -109, + ERR_SSL_CLIENT_AUTH_CERT_NEEDED = -110, + ERR_TUNNEL_CONNECTION_FAILED = -111, + ERR_NO_SSL_VERSIONS_ENABLED = -112, + ERR_SSL_VERSION_OR_CIPHER_MISMATCH = -113, + ERR_SSL_RENEGOTIATION_REQUESTED = -114, + ERR_CERT_COMMON_NAME_INVALID = -200, + ERR_CERT_DATE_INVALID = -201, + ERR_CERT_AUTHORITY_INVALID = -202, + ERR_CERT_CONTAINS_ERRORS = -203, + ERR_CERT_NO_REVOCATION_MECHANISM = -204, + ERR_CERT_UNABLE_TO_CHECK_REVOCATION = -205, + ERR_CERT_REVOKED = -206, + ERR_CERT_INVALID = -207, + ERR_CERT_END = -208, + ERR_INVALID_URL = -300, + ERR_DISALLOWED_URL_SCHEME = -301, + ERR_UNKNOWN_URL_SCHEME = -302, + ERR_TOO_MANY_REDIRECTS = -310, + ERR_UNSAFE_REDIRECT = -311, + ERR_UNSAFE_PORT = -312, + ERR_INVALID_RESPONSE = -320, + ERR_INVALID_CHUNKED_ENCODING = -321, + ERR_METHOD_NOT_SUPPORTED = -322, + ERR_UNEXPECTED_PROXY_AUTH = -323, + ERR_EMPTY_RESPONSE = -324, + ERR_RESPONSE_HEADERS_TOO_BIG = -325, + ERR_CACHE_MISS = -400, ERR_INSECURE_RESPONSE = -501, }; // Structure representing menu information. typedef struct _cef_handler_menuinfo_t { - int typeFlags; - int x; - int y; + int typeFlags; + int x; + int y; const wchar_t* linkUrl; const wchar_t* imageUrl; const wchar_t* pageUrl; @@ -137,60 +137,60 @@ typedef struct _cef_handler_menuinfo_t // The cef_handler_menuinfo_t typeFlags value will be a combination of the // following values. enum cef_handler_menutypebits_t -{ - // No node is selected - MENUTYPE_NONE = 0x0, - // The top page is selected - MENUTYPE_PAGE = 0x1, - // A subframe page is selected - MENUTYPE_FRAME = 0x2, - // A link is selected - MENUTYPE_LINK = 0x4, - // An image is selected - MENUTYPE_IMAGE = 0x8, - // There is a textual or mixed selection that is selected - MENUTYPE_SELECTION = 0x10, - // An editable element is selected - MENUTYPE_EDITABLE = 0x20, - // A misspelled word is selected - MENUTYPE_MISSPELLED_WORD = 0x40, - // A video node is selected - MENUTYPE_VIDEO = 0x80, - // A video node is selected - MENUTYPE_AUDIO = 0x100, +{ + // No node is selected + MENUTYPE_NONE = 0x0, + // The top page is selected + MENUTYPE_PAGE = 0x1, + // A subframe page is selected + MENUTYPE_FRAME = 0x2, + // A link is selected + MENUTYPE_LINK = 0x4, + // An image is selected + MENUTYPE_IMAGE = 0x8, + // There is a textual or mixed selection that is selected + MENUTYPE_SELECTION = 0x10, + // An editable element is selected + MENUTYPE_EDITABLE = 0x20, + // A misspelled word is selected + MENUTYPE_MISSPELLED_WORD = 0x40, + // A video node is selected + MENUTYPE_VIDEO = 0x80, + // A video node is selected + MENUTYPE_AUDIO = 0x100, }; // The cef_handler_menuinfo_t editFlags value will be a combination of the // following values. -enum cef_handler_menucapabilitybits_t -{ - MENU_CAN_DO_NONE = 0x0, - MENU_CAN_UNDO = 0x1, - MENU_CAN_REDO = 0x2, - MENU_CAN_CUT = 0x4, - MENU_CAN_COPY = 0x8, - MENU_CAN_PASTE = 0x10, - MENU_CAN_DELETE = 0x20, - MENU_CAN_SELECT_ALL = 0x40, - MENU_CAN_GO_FORWARD = 0x80, - MENU_CAN_GO_BACK = 0x100, +enum cef_handler_menucapabilitybits_t +{ + MENU_CAN_DO_NONE = 0x0, + MENU_CAN_UNDO = 0x1, + MENU_CAN_REDO = 0x2, + MENU_CAN_CUT = 0x4, + MENU_CAN_COPY = 0x8, + MENU_CAN_PASTE = 0x10, + MENU_CAN_DELETE = 0x20, + MENU_CAN_SELECT_ALL = 0x40, + MENU_CAN_GO_FORWARD = 0x80, + MENU_CAN_GO_BACK = 0x100, }; // Supported menu ID values. enum cef_handler_menuid_t { - MENU_ID_NAV_BACK = 10, - MENU_ID_NAV_FORWARD = 11, - MENU_ID_NAV_RELOAD = 12, - MENU_ID_NAV_STOP = 13, - MENU_ID_UNDO = 20, - MENU_ID_REDO = 21, - MENU_ID_CUT = 22, - MENU_ID_COPY = 23, - MENU_ID_PASTE = 24, - MENU_ID_DELETE = 25, - MENU_ID_SELECTALL = 26, - MENU_ID_PRINT = 30, + MENU_ID_NAV_BACK = 10, + MENU_ID_NAV_FORWARD = 11, + MENU_ID_NAV_RELOAD = 12, + MENU_ID_NAV_STOP = 13, + MENU_ID_UNDO = 20, + MENU_ID_REDO = 21, + MENU_ID_CUT = 22, + MENU_ID_COPY = 23, + MENU_ID_PASTE = 24, + MENU_ID_DELETE = 25, + MENU_ID_SELECTALL = 26, + MENU_ID_PRINT = 30, MENU_ID_VIEWSOURCE = 31, }; diff --git a/include/cef_types_win.h b/include/cef_types_win.h index 83eeb563e..6b3059753 100644 --- a/include/cef_types_win.h +++ b/include/cef_types_win.h @@ -1,31 +1,31 @@ -// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_TYPES_WIN_H diff --git a/include/cef_win.h b/include/cef_win.h index 1e2c5ab3c..6affd299b 100644 --- a/include/cef_win.h +++ b/include/cef_win.h @@ -1,31 +1,31 @@ -// Copyright (c) 2008 Marshall A. Greenblatt. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the name Chromium Embedded -// Framework nor the names of its contributors may be used to endorse -// or promote products derived from this software without specific prior -// written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright (c) 2008 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef _CEF_WIN_H @@ -78,15 +78,15 @@ public: cef_string_free(m_windowName); } - CefWindowInfo(const CefWindowInfo& r) - { - Init(); - *this = r; + CefWindowInfo(const CefWindowInfo& r) + { + Init(); + *this = r; } - CefWindowInfo(const cef_window_info_t& r) - { - Init(); - *this = r; + CefWindowInfo(const cef_window_info_t& r) + { + Init(); + *this = r; } void Init() @@ -103,28 +103,28 @@ public: m_hWnd = NULL; } - CefWindowInfo& operator=(const CefWindowInfo& r) - { - return operator=(static_cast(r)); - } - CefWindowInfo& operator=(const cef_window_info_t& r) - { - m_dwExStyle = r.m_dwExStyle; - if(m_windowName) - cef_string_free(m_windowName); - if(r.m_windowName) - m_windowName = cef_string_alloc(r.m_windowName); - else - m_windowName = NULL; - m_dwStyle = r.m_dwStyle; - m_x = r.m_x; - m_y = r.m_y; - m_nWidth = r.m_nWidth; - m_nHeight = r.m_nHeight; - m_hWndParent = r.m_hWndParent; - m_hMenu = r.m_hMenu; - m_hWnd = r.m_hWnd; - return *this; + CefWindowInfo& operator=(const CefWindowInfo& r) + { + return operator=(static_cast(r)); + } + CefWindowInfo& operator=(const cef_window_info_t& r) + { + m_dwExStyle = r.m_dwExStyle; + if(m_windowName) + cef_string_free(m_windowName); + if(r.m_windowName) + m_windowName = cef_string_alloc(r.m_windowName); + else + m_windowName = NULL; + m_dwStyle = r.m_dwStyle; + m_x = r.m_x; + m_y = r.m_y; + m_nWidth = r.m_nWidth; + m_nHeight = r.m_nHeight; + m_hWndParent = r.m_hWndParent; + m_hMenu = r.m_hMenu; + m_hWnd = r.m_hWnd; + return *this; } void SetAsChild(HWND hWndParent, RECT windowRect) @@ -140,16 +140,16 @@ public: void SetAsPopup(HWND hWndParent, LPCTSTR windowName) { - m_dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; - m_hWndParent = hWndParent; - m_x = CW_USEDEFAULT; - m_y = CW_USEDEFAULT; - m_nWidth = CW_USEDEFAULT; - m_nHeight = CW_USEDEFAULT; - - if(m_windowName) - cef_string_free(m_windowName); - if(windowName) + m_dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; + m_hWndParent = hWndParent; + m_x = CW_USEDEFAULT; + m_y = CW_USEDEFAULT; + m_nWidth = CW_USEDEFAULT; + m_nHeight = CW_USEDEFAULT; + + if(m_windowName) + cef_string_free(m_windowName); + if(windowName) m_windowName = cef_string_alloc(windowName); else m_windowName = NULL; @@ -168,15 +168,15 @@ public: { } - CefPrintInfo(const CefPrintInfo& r) - { - Init(); - *this = r; + CefPrintInfo(const CefPrintInfo& r) + { + Init(); + *this = r; } - CefPrintInfo(const cef_print_info_t& r) - { - Init(); - *this = r; + CefPrintInfo(const cef_print_info_t& r) + { + Init(); + *this = r; } void Init() @@ -186,19 +186,19 @@ public: m_Scale = 0; } - CefPrintInfo& operator=(const CefPrintInfo& r) - { - return operator=(static_cast(r)); - } - CefPrintInfo& operator=(const cef_print_info_t& r) - { + CefPrintInfo& operator=(const CefPrintInfo& r) + { + return operator=(static_cast(r)); + } + CefPrintInfo& operator=(const cef_print_info_t& r) + { m_hDC = r.m_hDC; m_Rect.left = r.m_Rect.left; m_Rect.right = r.m_Rect.right; m_Rect.top = r.m_Rect.top; m_Rect.bottom = r.m_Rect.bottom; - m_Scale = r.m_Scale; - return *this; + m_Scale = r.m_Scale; + return *this; } }; diff --git a/libcef/browser_drag_delegate.cc b/libcef/browser_drag_delegate.cc index 8ecdc4dbc..b67ecb627 100644 --- a/libcef/browser_drag_delegate.cc +++ b/libcef/browser_drag_delegate.cc @@ -1,49 +1,49 @@ -// 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 "precompiled_libcef.h" -#include "browser_drag_delegate.h" - -#include - -#include "webkit/api/public/WebPoint.h" -#include "webkit/glue/webview.h" - -using WebKit::WebPoint; - - -namespace { - -void GetCursorPositions(HWND hwnd, CPoint* client, CPoint* screen) { - // GetCursorPos will fail if the input desktop isn't the current desktop. - // See http://b/1173534. (0,0) is wrong, but better than uninitialized. - if (!GetCursorPos(screen)) - screen->SetPoint(0, 0); - - *client = *screen; - ScreenToClient(hwnd, client); -} - -} // anonymous namespace - -void BrowserDragDelegate::OnDragSourceCancel() { - OnDragSourceDrop(); -} - -void BrowserDragDelegate::OnDragSourceDrop() { - CPoint client; - CPoint screen; - GetCursorPositions(source_hwnd_, &client, &screen); - webview_->DragSourceEndedAt(WebPoint(client.x, client.y), - WebPoint(screen.x, screen.y)); -} - -void BrowserDragDelegate::OnDragSourceMove() { - CPoint client; - CPoint screen; - GetCursorPositions(source_hwnd_, &client, &screen); - webview_->DragSourceMovedTo(WebPoint(client.x, client.y), - WebPoint(screen.x, screen.y)); -} +// 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 "precompiled_libcef.h" +#include "browser_drag_delegate.h" + +#include + +#include "webkit/api/public/WebPoint.h" +#include "webkit/glue/webview.h" + +using WebKit::WebPoint; + + +namespace { + +void GetCursorPositions(HWND hwnd, CPoint* client, CPoint* screen) { + // GetCursorPos will fail if the input desktop isn't the current desktop. + // See http://b/1173534. (0,0) is wrong, but better than uninitialized. + if (!GetCursorPos(screen)) + screen->SetPoint(0, 0); + + *client = *screen; + ScreenToClient(hwnd, client); +} + +} // anonymous namespace + +void BrowserDragDelegate::OnDragSourceCancel() { + OnDragSourceDrop(); +} + +void BrowserDragDelegate::OnDragSourceDrop() { + CPoint client; + CPoint screen; + GetCursorPositions(source_hwnd_, &client, &screen); + webview_->DragSourceEndedAt(WebPoint(client.x, client.y), + WebPoint(screen.x, screen.y)); +} + +void BrowserDragDelegate::OnDragSourceMove() { + CPoint client; + CPoint screen; + GetCursorPositions(source_hwnd_, &client, &screen); + webview_->DragSourceMovedTo(WebPoint(client.x, client.y), + WebPoint(screen.x, screen.y)); +} diff --git a/libcef/browser_drag_delegate.h b/libcef/browser_drag_delegate.h index 3a5fa0ae7..b402b8b50 100644 --- a/libcef/browser_drag_delegate.h +++ b/libcef/browser_drag_delegate.h @@ -1,37 +1,37 @@ -// 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. -// -// A class that implements BaseDragSource for the test shell webview delegate. - -#ifndef _BROWSER_DRAG_DELEGATE_H -#define _BROWSER_DRAG_DELEGATE_H - -#include "base/base_drag_source.h" - -class WebView; - -class BrowserDragDelegate : public BaseDragSource { - public: - BrowserDragDelegate(HWND source_hwnd, WebView* webview) - : BaseDragSource(), - source_hwnd_(source_hwnd), - webview_(webview) { } - - protected: - // BaseDragSource - virtual void OnDragSourceCancel(); - virtual void OnDragSourceDrop(); - virtual void OnDragSourceMove(); - - private: - WebView* webview_; - - // A HWND for the source we are associated with, used for translating - // mouse coordinates from screen to client coordinates. - HWND source_hwnd_; -}; - -#endif // _BROWSER_DRAG_DELEGATE_H - +// 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. +// +// A class that implements BaseDragSource for the test shell webview delegate. + +#ifndef _BROWSER_DRAG_DELEGATE_H +#define _BROWSER_DRAG_DELEGATE_H + +#include "base/base_drag_source.h" + +class WebView; + +class BrowserDragDelegate : public BaseDragSource { + public: + BrowserDragDelegate(HWND source_hwnd, WebView* webview) + : BaseDragSource(), + source_hwnd_(source_hwnd), + webview_(webview) { } + + protected: + // BaseDragSource + virtual void OnDragSourceCancel(); + virtual void OnDragSourceDrop(); + virtual void OnDragSourceMove(); + + private: + WebView* webview_; + + // A HWND for the source we are associated with, used for translating + // mouse coordinates from screen to client coordinates. + HWND source_hwnd_; +}; + +#endif // _BROWSER_DRAG_DELEGATE_H + diff --git a/libcef/browser_drop_delegate.cc b/libcef/browser_drop_delegate.cc index c942e2cf7..ba5f60821 100644 --- a/libcef/browser_drop_delegate.cc +++ b/libcef/browser_drop_delegate.cc @@ -1,63 +1,63 @@ -// 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 "precompiled_libcef.h" -#include "browser_drop_delegate.h" - -#include "webkit/api/public/WebDragData.h" -#include "webkit/api/public/WebPoint.h" -#include "webkit/glue/webdropdata.h" -#include "webkit/glue/webview.h" - -using WebKit::WebPoint; - -// BaseDropTarget methods ---------------------------------------------------- - -DWORD BrowserDropDelegate::OnDragEnter(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - WebDropData drop_data; - WebDropData::PopulateWebDropData(data_object, &drop_data); - - POINT client_pt = cursor_position; - ScreenToClient(GetHWND(), &client_pt); - bool valid = webview_->DragTargetDragEnter( - drop_data.ToDragData(), drop_data.identity, - WebPoint(client_pt.x, client_pt.y), - WebPoint(cursor_position.x, cursor_position.y)); - return valid ? DROPEFFECT_COPY : DROPEFFECT_NONE; -} - -DWORD BrowserDropDelegate::OnDragOver(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - POINT client_pt = cursor_position; - ScreenToClient(GetHWND(), &client_pt); - bool valid = webview_->DragTargetDragOver( - WebPoint(client_pt.x, client_pt.y), - WebPoint(cursor_position.x, cursor_position.y)); - return valid ? DROPEFFECT_COPY : DROPEFFECT_NONE; -} - -void BrowserDropDelegate::OnDragLeave(IDataObject* data_object) { - webview_->DragTargetDragLeave(); -} - -DWORD BrowserDropDelegate::OnDrop(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - POINT client_pt = cursor_position; - ScreenToClient(GetHWND(), &client_pt); - webview_->DragTargetDrop( - WebPoint(client_pt.x, client_pt.y), - WebPoint(cursor_position.x, cursor_position.y)); - - // webkit win port always returns DROPEFFECT_NONE - return DROPEFFECT_NONE; -} - +// 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 "precompiled_libcef.h" +#include "browser_drop_delegate.h" + +#include "webkit/api/public/WebDragData.h" +#include "webkit/api/public/WebPoint.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/webview.h" + +using WebKit::WebPoint; + +// BaseDropTarget methods ---------------------------------------------------- + +DWORD BrowserDropDelegate::OnDragEnter(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + WebDropData drop_data; + WebDropData::PopulateWebDropData(data_object, &drop_data); + + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + bool valid = webview_->DragTargetDragEnter( + drop_data.ToDragData(), drop_data.identity, + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y)); + return valid ? DROPEFFECT_COPY : DROPEFFECT_NONE; +} + +DWORD BrowserDropDelegate::OnDragOver(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + bool valid = webview_->DragTargetDragOver( + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y)); + return valid ? DROPEFFECT_COPY : DROPEFFECT_NONE; +} + +void BrowserDropDelegate::OnDragLeave(IDataObject* data_object) { + webview_->DragTargetDragLeave(); +} + +DWORD BrowserDropDelegate::OnDrop(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + webview_->DragTargetDrop( + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y)); + + // webkit win port always returns DROPEFFECT_NONE + return DROPEFFECT_NONE; +} + diff --git a/libcef/browser_drop_delegate.h b/libcef/browser_drop_delegate.h index 3d5dc7471..344f5a79a 100644 --- a/libcef/browser_drop_delegate.h +++ b/libcef/browser_drop_delegate.h @@ -1,43 +1,43 @@ -// 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. -// -// A class that implements BaseDropTarget for the test shell webview delegate. - -#ifndef _BROWSER_DROP_DELEGATE_H -#define _BROWSER_DROP_DELEGATE_H - -#include "base/base_drop_target.h" - -class WebView; - -class BrowserDropDelegate : public BaseDropTarget { - public: - BrowserDropDelegate(HWND source_hwnd, WebView* webview) - : BaseDropTarget(source_hwnd), - webview_(webview) { } - - protected: - // BaseDropTarget methods - virtual DWORD OnDragEnter(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect); - virtual DWORD OnDragOver(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect); - virtual void OnDragLeave(IDataObject* data_object); - virtual DWORD OnDrop(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect); - - - private: - WebView* webview_; -}; - -#endif // _BROWSER_DROP_DELEGATE_H - +// 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. +// +// A class that implements BaseDropTarget for the test shell webview delegate. + +#ifndef _BROWSER_DROP_DELEGATE_H +#define _BROWSER_DROP_DELEGATE_H + +#include "base/base_drop_target.h" + +class WebView; + +class BrowserDropDelegate : public BaseDropTarget { + public: + BrowserDropDelegate(HWND source_hwnd, WebView* webview) + : BaseDropTarget(source_hwnd), + webview_(webview) { } + + protected: + // BaseDropTarget methods + virtual DWORD OnDragEnter(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect); + virtual DWORD OnDragOver(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect); + virtual void OnDragLeave(IDataObject* data_object); + virtual DWORD OnDrop(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect); + + + private: + WebView* webview_; +}; + +#endif // _BROWSER_DROP_DELEGATE_H + diff --git a/libcef/browser_impl.cc b/libcef/browser_impl.cc index 12dce482b..95cb420fd 100644 --- a/libcef/browser_impl.cc +++ b/libcef/browser_impl.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2008-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. - +// Copyright (c) 2008-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 "precompiled_libcef.h" #include "context.h" #include "browser_impl.h" @@ -41,25 +41,25 @@ CefBrowserImpl::CefBrowserImpl(CefWindowInfo& windowInfo, bool popup, void CefBrowserImpl::GoBack() { PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_BACK)); + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_BACK)); } void CefBrowserImpl::GoForward() { PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_FORWARD)); + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_FORWARD)); } void CefBrowserImpl::Reload() { PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_RELOAD)); + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_RELOAD)); } void CefBrowserImpl::StopLoad() { PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_STOP)); + &CefBrowserImpl::UIT_HandleActionView, MENU_ID_NAV_STOP)); } void CefBrowserImpl::SetFocus(bool enable) @@ -167,8 +167,8 @@ void CefBrowserImpl::RemoveCefFrame(const std::wstring& name) WebFrame* CefBrowserImpl::GetWebFrame(CefRefPtr frame) { std::wstring name = frame->GetName(); - if(name.empty()) - return GetWebView()->GetMainFrame(); + if(name.empty()) + return GetWebView()->GetMainFrame(); return GetWebView()->GetFrameWithName(name); } @@ -176,49 +176,49 @@ void CefBrowserImpl::Undo(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_UNDO, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_UNDO, frame.get())); } void CefBrowserImpl::Redo(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_REDO, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_REDO, frame.get())); } void CefBrowserImpl::Cut(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_CUT, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_CUT, frame.get())); } void CefBrowserImpl::Copy(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_COPY, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_COPY, frame.get())); } void CefBrowserImpl::Paste(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_PASTE, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_PASTE, frame.get())); } void CefBrowserImpl::Delete(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_DELETE, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_DELETE, frame.get())); } void CefBrowserImpl::SelectAll(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_SELECTALL, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_SELECTALL, frame.get())); } @@ -226,14 +226,14 @@ void CefBrowserImpl::Print(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_PRINT, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_PRINT, frame.get())); } void CefBrowserImpl::ViewSource(CefRefPtr frame) { frame->AddRef(); PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_HandleAction, MENU_ID_VIEWSOURCE, frame.get())); + &CefBrowserImpl::UIT_HandleAction, MENU_ID_VIEWSOURCE, frame.get())); } void CefBrowserImpl::LoadRequest(CefRefPtr frame, @@ -278,12 +278,12 @@ void CefBrowserImpl::LoadStream(CefRefPtr frame, void CefBrowserImpl::ExecuteJavaScript(CefRefPtr frame, const std::wstring& jsCode, const std::wstring& scriptUrl, - int startLine) -{ + int startLine) +{ frame->AddRef(); - PostTask(FROM_HERE, NewRunnableMethod(this, - &CefBrowserImpl::UIT_ExecuteJavaScript, frame.get(), jsCode, scriptUrl, - startLine)); + PostTask(FROM_HERE, NewRunnableMethod(this, + &CefBrowserImpl::UIT_ExecuteJavaScript, frame.get(), jsCode, scriptUrl, + startLine)); } std::wstring CefBrowserImpl::GetURL(CefRefPtr frame) @@ -309,10 +309,10 @@ bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, bool popup, // or cancel the window creation. CefHandler::RetVal rv = handler->HandleBeforeCreated(NULL, windowInfo, popup, handler, newUrl); - if(rv == RV_HANDLED) + if(rv == RV_HANDLED) return false; - } - + } + CefRefPtr browser( new CefBrowserImpl(windowInfo, popup, handler)); PostTask(FROM_HERE, NewRunnableMethod(browser.get(), @@ -337,7 +337,7 @@ CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, // or cancel the window creation. CefHandler::RetVal rv = handler->HandleBeforeCreated(NULL, windowInfo, popup, handler, newUrl); - if(rv == RV_HANDLED) + if(rv == RV_HANDLED) return false; } @@ -347,327 +347,327 @@ CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, return browser; } -void CefBrowserImpl::UIT_LoadURL(CefFrame* frame, - const std::wstring& url) -{ - UIT_LoadURLForRequest(frame, url, std::wstring(), WebHTTPBody(), - CefRequest::HeaderMap()); -} - -void CefBrowserImpl::UIT_LoadURLForRequestRef(CefFrame* frame, - CefRequest* request) -{ - std::wstring url = request->GetURL(); - std::wstring method = request->GetMethod(); - - CefRequestImpl *impl = static_cast(request); - - WebHTTPBody upload_data; - CefRefPtr postdata = impl->GetPostData(); - if(postdata.get()) { - upload_data.initialize(); - static_cast(postdata.get())->Get(upload_data); - } - - CefRequest::HeaderMap headers; - impl->GetHeaderMap(headers); - - UIT_LoadURLForRequest(frame, url, method, upload_data, headers); - - request->Release(); -} - -void CefBrowserImpl::UIT_LoadURLForRequest(CefFrame* frame, - const std::wstring& url, - const std::wstring& method, - const WebKit::WebHTTPBody& upload_data, - const CefRequest::HeaderMap& headers) -{ +void CefBrowserImpl::UIT_LoadURL(CefFrame* frame, + const std::wstring& url) +{ + UIT_LoadURLForRequest(frame, url, std::wstring(), WebHTTPBody(), + CefRequest::HeaderMap()); +} + +void CefBrowserImpl::UIT_LoadURLForRequestRef(CefFrame* frame, + CefRequest* request) +{ + std::wstring url = request->GetURL(); + std::wstring method = request->GetMethod(); + + CefRequestImpl *impl = static_cast(request); + + WebHTTPBody upload_data; + CefRefPtr postdata = impl->GetPostData(); + if(postdata.get()) { + upload_data.initialize(); + static_cast(postdata.get())->Get(upload_data); + } + + CefRequest::HeaderMap headers; + impl->GetHeaderMap(headers); + + UIT_LoadURLForRequest(frame, url, method, upload_data, headers); + + request->Release(); +} + +void CefBrowserImpl::UIT_LoadURLForRequest(CefFrame* frame, + const std::wstring& url, + const std::wstring& method, + const WebKit::WebHTTPBody& upload_data, + const CefRequest::HeaderMap& headers) +{ REQUIRE_UIT(); - - if (url.empty()) - return; - - GURL gurl(url); - - if (!gurl.is_valid() && !gurl.has_scheme()) { - // Try to add "http://" at the beginning - gurl = GURL(std::wstring(L"http://") + url); - if (!gurl.is_valid()) - return; - } - - nav_controller_->LoadEntry( - new BrowserNavigationEntry(-1, gurl, std::wstring(), frame->GetName(), - method, upload_data, headers)); - - frame->Release(); -} - -void CefBrowserImpl::UIT_LoadHTML(CefFrame* frame, - const std::wstring& html, - const std::wstring& url) -{ + + if (url.empty()) + return; + + GURL gurl(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + gurl = GURL(std::wstring(L"http://") + url); + if (!gurl.is_valid()) + return; + } + + nav_controller_->LoadEntry( + new BrowserNavigationEntry(-1, gurl, std::wstring(), frame->GetName(), + method, upload_data, headers)); + + frame->Release(); +} + +void CefBrowserImpl::UIT_LoadHTML(CefFrame* frame, + const std::wstring& html, + const std::wstring& url) +{ REQUIRE_UIT(); - - GURL gurl(url); - - if (!gurl.is_valid() && !gurl.has_scheme()) { - // Try to add "http://" at the beginning - gurl = GURL(std::wstring(L"http://") + url); - if (!gurl.is_valid()) - return; - } - - WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) - web_frame->LoadHTMLString(WideToUTF8(html), gurl); - - frame->Release(); -} - -void CefBrowserImpl::UIT_LoadHTMLForStreamRef(CefFrame* frame, - CefStreamReader* stream, - const std::wstring& url) -{ + + GURL gurl(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + gurl = GURL(std::wstring(L"http://") + url); + if (!gurl.is_valid()) + return; + } + + WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) + web_frame->LoadHTMLString(WideToUTF8(html), gurl); + + frame->Release(); +} + +void CefBrowserImpl::UIT_LoadHTMLForStreamRef(CefFrame* frame, + CefStreamReader* stream, + const std::wstring& url) +{ REQUIRE_UIT(); - - GURL gurl(url); - - if (!gurl.is_valid() && !gurl.has_scheme()) { - // Try to add "http://" at the beginning - gurl = GURL(std::wstring(L"http://") + url); - if (!gurl.is_valid()) - return; - } - - // read all of the stream data into a std::string. - std::stringstream ss; - char buff[BUFFER_SIZE]; - size_t read; - do { - read = stream->Read(buff, sizeof(char), BUFFER_SIZE-1); - if(read > 0) { - buff[read] = 0; - ss << buff; - } - } - while(read > 0); - - WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) - web_frame->LoadHTMLString(ss.str(), gurl); - - stream->Release(); - frame->Release(); -} - -void CefBrowserImpl::UIT_ExecuteJavaScript(CefFrame* frame, + + GURL gurl(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + gurl = GURL(std::wstring(L"http://") + url); + if (!gurl.is_valid()) + return; + } + + // read all of the stream data into a std::string. + std::stringstream ss; + char buff[BUFFER_SIZE]; + size_t read; + do { + read = stream->Read(buff, sizeof(char), BUFFER_SIZE-1); + if(read > 0) { + buff[read] = 0; + ss << buff; + } + } + while(read > 0); + + WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) + web_frame->LoadHTMLString(ss.str(), gurl); + + stream->Release(); + frame->Release(); +} + +void CefBrowserImpl::UIT_ExecuteJavaScript(CefFrame* frame, const std::wstring& js_code, const std::wstring& script_url, - int start_line) -{ - REQUIRE_UIT(); - - WebFrame* web_frame = GetWebFrame(frame); - if(web_frame) { - web_frame->ExecuteScript( - WebScriptSource(WebString(js_code), WebURL(GURL(script_url)), - start_line)); - } - - frame->Release(); -} - -void CefBrowserImpl::UIT_GoBackOrForward(int offset) -{ + int start_line) +{ REQUIRE_UIT(); - nav_controller_->GoToOffset(offset); -} - -void CefBrowserImpl::UIT_Reload() -{ + + WebFrame* web_frame = GetWebFrame(frame); + if(web_frame) { + web_frame->ExecuteScript( + WebScriptSource(WebString(js_code), WebURL(GURL(script_url)), + start_line)); + } + + frame->Release(); +} + +void CefBrowserImpl::UIT_GoBackOrForward(int offset) +{ REQUIRE_UIT(); - nav_controller_->Reload(); -} - + nav_controller_->GoToOffset(offset); +} + +void CefBrowserImpl::UIT_Reload() +{ + REQUIRE_UIT(); + nav_controller_->Reload(); +} + bool CefBrowserImpl::UIT_Navigate(const BrowserNavigationEntry& entry, bool reload) { REQUIRE_UIT(); - // Get the right target frame for the entry. - WebFrame* frame; - if (!entry.GetTargetFrame().empty()) - frame = GetWebView()->GetFrameWithName(entry.GetTargetFrame()); - else - frame = GetWebView()->GetMainFrame(); - // TODO(mpcomplete): should we clear the target frame, or should - // back/forward navigations maintain the target frame? - - // A navigation resulting from loading a javascript URL should not be - // treated as a browser initiated event. Instead, we want it to look as if - // the page initiated any load resulting from JS execution. - if (!entry.GetURL().SchemeIs("javascript")) { - delegate_->set_pending_extra_data( - new BrowserExtraData(entry.GetPageID())); - } - - // If we are reloading, then WebKit will use the state of the current page. - // Otherwise, we give it the state to navigate to. - if (reload) { - frame->Reload(); - } else if (!entry.GetContentState().empty()) { - DCHECK(entry.GetPageID() != -1); - frame->LoadHistoryItem( - webkit_glue::HistoryItemFromString(entry.GetContentState())); - } else { - DCHECK(entry.GetPageID() == -1); - WebURLRequest request(entry.GetURL()); - - if(entry.GetMethod().size() > 0) { - request.setHTTPMethod( - StdStringToWebString(WideToUTF8(entry.GetMethod()))); - } - - if(entry.GetHeaders().size() > 0) - CefRequestImpl::SetHeaderMap(entry.GetHeaders(), request); - - if(!entry.GetUploadData().isNull()) - { - std::string method = WebStringToStdString(request.httpMethod()); - if(method == "GET" || method == "HEAD") { - request.setHTTPMethod(StdStringToWebString("POST")); - } - if(request.httpHeaderField(StdStringToWebString("Content-Type")).length() - == 0) { - request.setHTTPHeaderField( - StdStringToWebString("Content-Type"), - StdStringToWebString("application/x-www-form-urlencoded")); - } - request.setHTTPBody(entry.GetUploadData()); - } - - frame->LoadRequest(request); - } - - // In case LoadRequest failed before DidCreateDataSource was called. - delegate_->set_pending_extra_data(NULL); - - if (handler_.get() && handler_->HandleSetFocus(this, false) == RV_CONTINUE) { - // Restore focus to the main frame prior to loading new request. - // This makes sure that we don't have a focused iframe. Otherwise, that - // iframe would keep focus when the SetFocus called immediately after - // LoadRequest, thus making some tests fail (see http://b/issue?id=845337 - // for more details). - // TODO(cef): The above comment may be wrong, or the below call to - // SetFocusedFrame() may be unnecessary or in the wrong place. See this - // thread for additional details: - // http://groups.google.com/group/chromium-dev/browse_thread/thread/42bcd31b59e3a168 - GetWebView()->SetFocusedFrame(frame); - UIT_SetFocus(GetWebViewHost(), true); - } - + // Get the right target frame for the entry. + WebFrame* frame; + if (!entry.GetTargetFrame().empty()) + frame = GetWebView()->GetFrameWithName(entry.GetTargetFrame()); + else + frame = GetWebView()->GetMainFrame(); + // TODO(mpcomplete): should we clear the target frame, or should + // back/forward navigations maintain the target frame? + + // A navigation resulting from loading a javascript URL should not be + // treated as a browser initiated event. Instead, we want it to look as if + // the page initiated any load resulting from JS execution. + if (!entry.GetURL().SchemeIs("javascript")) { + delegate_->set_pending_extra_data( + new BrowserExtraData(entry.GetPageID())); + } + + // If we are reloading, then WebKit will use the state of the current page. + // Otherwise, we give it the state to navigate to. + if (reload) { + frame->Reload(); + } else if (!entry.GetContentState().empty()) { + DCHECK(entry.GetPageID() != -1); + frame->LoadHistoryItem( + webkit_glue::HistoryItemFromString(entry.GetContentState())); + } else { + DCHECK(entry.GetPageID() == -1); + WebURLRequest request(entry.GetURL()); + + if(entry.GetMethod().size() > 0) { + request.setHTTPMethod( + StdStringToWebString(WideToUTF8(entry.GetMethod()))); + } + + if(entry.GetHeaders().size() > 0) + CefRequestImpl::SetHeaderMap(entry.GetHeaders(), request); + + if(!entry.GetUploadData().isNull()) + { + std::string method = WebStringToStdString(request.httpMethod()); + if(method == "GET" || method == "HEAD") { + request.setHTTPMethod(StdStringToWebString("POST")); + } + if(request.httpHeaderField(StdStringToWebString("Content-Type")).length() + == 0) { + request.setHTTPHeaderField( + StdStringToWebString("Content-Type"), + StdStringToWebString("application/x-www-form-urlencoded")); + } + request.setHTTPBody(entry.GetUploadData()); + } + + frame->LoadRequest(request); + } + + // In case LoadRequest failed before DidCreateDataSource was called. + delegate_->set_pending_extra_data(NULL); + + if (handler_.get() && handler_->HandleSetFocus(this, false) == RV_CONTINUE) { + // Restore focus to the main frame prior to loading new request. + // This makes sure that we don't have a focused iframe. Otherwise, that + // iframe would keep focus when the SetFocus called immediately after + // LoadRequest, thus making some tests fail (see http://b/issue?id=845337 + // for more details). + // TODO(cef): The above comment may be wrong, or the below call to + // SetFocusedFrame() may be unnecessary or in the wrong place. See this + // thread for additional details: + // http://groups.google.com/group/chromium-dev/browse_thread/thread/42bcd31b59e3a168 + GetWebView()->SetFocusedFrame(frame); + UIT_SetFocus(GetWebViewHost(), true); + } + return true; } -CefRefPtr CefBrowserImpl::UIT_CreatePopupWindow(const std::wstring& url) -{ +CefRefPtr CefBrowserImpl::UIT_CreatePopupWindow(const std::wstring& url) +{ REQUIRE_UIT(); - - CefWindowInfo info; - info.SetAsPopup(NULL, url.c_str()); - CefRefPtr handler = handler_; - std::wstring newUrl = url; - + + CefWindowInfo info; + info.SetAsPopup(NULL, url.c_str()); + CefRefPtr handler = handler_; + std::wstring newUrl = url; + if(handler_.get()) { // Give the handler an opportunity to modify window attributes, handler, // or cancel the window creation. CefHandler::RetVal rv = handler_->HandleBeforeCreated(this, info, true, handler, newUrl); - if(rv == RV_HANDLED) + if(rv == RV_HANDLED) return NULL; - } - + } + CefRefPtr browser(new CefBrowserImpl(info, true, handler)); - browser->UIT_CreateBrowser(newUrl); - - return browser; -} - -void CefBrowserImpl::UIT_Show(WebKit::WebNavigationPolicy policy) -{ + browser->UIT_CreateBrowser(newUrl); + + return browser; +} + +void CefBrowserImpl::UIT_Show(WebKit::WebNavigationPolicy policy) +{ REQUIRE_UIT(); - delegate_->show(policy); -} - -void CefBrowserImpl::UIT_HandleActionView(CefHandler::MenuId menuId) -{ - return UIT_HandleAction(menuId, NULL); -} - -void CefBrowserImpl::UIT_HandleAction(CefHandler::MenuId menuId, - CefFrame* frame) -{ + delegate_->show(policy); +} + +void CefBrowserImpl::UIT_HandleActionView(CefHandler::MenuId menuId) +{ + return UIT_HandleAction(menuId, NULL); +} + +void CefBrowserImpl::UIT_HandleAction(CefHandler::MenuId menuId, + CefFrame* frame) +{ REQUIRE_UIT(); - WebFrame* web_frame = NULL; - if(frame) - web_frame = GetWebFrame(frame); - - switch(menuId) - { - case MENU_ID_NAV_BACK: - UIT_GoBackOrForward(-1); - break; - case MENU_ID_NAV_FORWARD: - UIT_GoBackOrForward(1); - break; - case MENU_ID_NAV_RELOAD: - UIT_Reload(); - break; - case MENU_ID_NAV_STOP: - GetWebView()->StopLoading(); - break; - case MENU_ID_UNDO: - if(web_frame) - web_frame->Undo(); - break; - case MENU_ID_REDO: - if(web_frame) - web_frame->Redo(); - break; - case MENU_ID_CUT: - if(web_frame) - web_frame->Cut(); - break; - case MENU_ID_COPY: - if(web_frame) - web_frame->Copy(); - break; - case MENU_ID_PASTE: - if(web_frame) - web_frame->Paste(); - break; - case MENU_ID_DELETE: - if(web_frame) - web_frame->Delete(); - break; - case MENU_ID_SELECTALL: - if(web_frame) - web_frame->SelectAll(); - break; - case MENU_ID_PRINT: - if(web_frame) - UIT_PrintPages(web_frame); - break; - case MENU_ID_VIEWSOURCE: - if(web_frame) - UIT_ViewDocumentString(web_frame); - break; - } - - if(frame) - frame->Release(); -} + WebFrame* web_frame = NULL; + if(frame) + web_frame = GetWebFrame(frame); + + switch(menuId) + { + case MENU_ID_NAV_BACK: + UIT_GoBackOrForward(-1); + break; + case MENU_ID_NAV_FORWARD: + UIT_GoBackOrForward(1); + break; + case MENU_ID_NAV_RELOAD: + UIT_Reload(); + break; + case MENU_ID_NAV_STOP: + GetWebView()->StopLoading(); + break; + case MENU_ID_UNDO: + if(web_frame) + web_frame->Undo(); + break; + case MENU_ID_REDO: + if(web_frame) + web_frame->Redo(); + break; + case MENU_ID_CUT: + if(web_frame) + web_frame->Cut(); + break; + case MENU_ID_COPY: + if(web_frame) + web_frame->Copy(); + break; + case MENU_ID_PASTE: + if(web_frame) + web_frame->Paste(); + break; + case MENU_ID_DELETE: + if(web_frame) + web_frame->Delete(); + break; + case MENU_ID_SELECTALL: + if(web_frame) + web_frame->SelectAll(); + break; + case MENU_ID_PRINT: + if(web_frame) + UIT_PrintPages(web_frame); + break; + case MENU_ID_VIEWSOURCE: + if(web_frame) + UIT_ViewDocumentString(web_frame); + break; + } + + if(frame) + frame->Release(); +} diff --git a/libcef/browser_impl.h b/libcef/browser_impl.h index ef93041b1..24427e83f 100644 --- a/libcef/browser_impl.h +++ b/libcef/browser_impl.h @@ -1,8 +1,8 @@ -// Copyright (c) 2008-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. - +// Copyright (c) 2008-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. + #ifndef _BROWSER_IMPL_H #define _BROWSER_IMPL_H @@ -88,7 +88,7 @@ public: void ExecuteJavaScript(CefRefPtr frame, const std::wstring& jsCode, const std::wstring& scriptUrl, - int startLine); + int startLine); virtual std::wstring GetURL(CefRefPtr frame); WebView* GetWebView() const { @@ -97,15 +97,15 @@ public: WebViewHost* GetWebViewHost() const { return webviewhost_.get(); } - BrowserWebViewDelegate* GetWebViewDelegate() const { - return delegate_.get(); - } + BrowserWebViewDelegate* GetWebViewDelegate() const { + return delegate_.get(); + } HWND GetWebViewWndHandle() const { return webviewhost_->view_handle(); } - WebKit::WebWidget* GetPopup() const { - return popuphost_ ? popuphost_->webwidget() : NULL; - } + WebKit::WebWidget* GetPopup() const { + return popuphost_ ? popuphost_->webwidget() : NULL; + } WebWidgetHost* GetPopupHost() const { return popuphost_; } @@ -152,34 +152,34 @@ public: void UIT_CreateBrowser(const std::wstring& url); - void UIT_LoadURL(CefFrame* frame, - const std::wstring& url); - void UIT_LoadURLForRequest(CefFrame* frame, - const std::wstring& url, - const std::wstring& method, - const WebKit::WebHTTPBody& upload_data, - const CefRequest::HeaderMap& headers); - void UIT_LoadURLForRequestRef(CefFrame* frame, - CefRequest* request); - void UIT_LoadHTML(CefFrame* frame, - const std::wstring& html, - const std::wstring& url); - void UIT_LoadHTMLForStreamRef(CefFrame* frame, - CefStreamReader* stream, - const std::wstring& url); - void UIT_ExecuteJavaScript(CefFrame* frame, + void UIT_LoadURL(CefFrame* frame, + const std::wstring& url); + void UIT_LoadURLForRequest(CefFrame* frame, + const std::wstring& url, + const std::wstring& method, + const WebKit::WebHTTPBody& upload_data, + const CefRequest::HeaderMap& headers); + void UIT_LoadURLForRequestRef(CefFrame* frame, + CefRequest* request); + void UIT_LoadHTML(CefFrame* frame, + const std::wstring& html, + const std::wstring& url); + void UIT_LoadHTMLForStreamRef(CefFrame* frame, + CefStreamReader* stream, + const std::wstring& url); + void UIT_ExecuteJavaScript(CefFrame* frame, const std::wstring& js_code, const std::wstring& script_url, - int start_line); - void UIT_GoBackOrForward(int offset); - void UIT_Reload(); + int start_line); + void UIT_GoBackOrForward(int offset); + void UIT_Reload(); bool UIT_Navigate(const BrowserNavigationEntry& entry, bool reload); void UIT_SetFocus(WebWidgetHost* host, bool enable); - CefRefPtr UIT_CreatePopupWindow(const std::wstring& url); - WebKit::WebWidget* UIT_CreatePopupWidget(WebView* webview); - void UIT_ClosePopupWidget(); - + CefRefPtr UIT_CreatePopupWindow(const std::wstring& url); + WebKit::WebWidget* UIT_CreatePopupWidget(WebView* webview); + void UIT_ClosePopupWidget(); + void UIT_Show(WebKit::WebNavigationPolicy policy); // Handles most simple browser actions @@ -223,7 +223,7 @@ protected: std::wstring title_; - // Context object used to manage printing. + // Context object used to manage printing. printing::PrintingContext print_context_; typedef std::map FrameMap; diff --git a/libcef/browser_impl_win.cc b/libcef/browser_impl_win.cc index 0dc841148..ed4f6a010 100644 --- a/libcef/browser_impl_win.cc +++ b/libcef/browser_impl_win.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2008-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. - +// Copyright (c) 2008-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 "precompiled_libcef.h" #include "context.h" #include "browser_impl.h" @@ -13,9 +13,9 @@ #include "base/string_util.h" #include "base/win_util.h" -#include "skia/ext/vector_canvas.h" -#include "webkit/api/public/WebRect.h" -#include "webkit/api/public/WebSize.h" +#include "skia/ext/vector_canvas.h" +#include "webkit/api/public/WebRect.h" +#include "webkit/api/public/WebSize.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webkit_glue.h" @@ -39,59 +39,59 @@ LRESULT CALLBACK CefBrowserImpl::WndProc(HWND hwnd, UINT message, CefBrowserImpl* browser = static_cast(win_util::GetWindowUserData(hwnd)); - switch (message) { - case WM_COMMAND: - { - int wmId = LOWORD(wParam); - int wmEvent = HIWORD(wParam); - - - } - break; - - case WM_DESTROY: - { - CefRefPtr handler = browser->GetHandler(); - if(handler.get()) { - // Notify the handler that the window is about to be closed - handler->HandleBeforeWindowClose(browser); - } - RevokeDragDrop(browser->GetWebViewWndHandle()); - - // Call GC twice to clean up garbage. - browser->GetWebView()->GetMainFrame()->CallJSGC(); - browser->GetWebView()->GetMainFrame()->CallJSGC(); - - // Clean up anything associated with the WebViewHost widget. - browser->GetWebViewHost()->webwidget()->close(); - - // Remove the browser from the list maintained by the context - _Context->RemoveBrowser(browser); - } - return 0; - - case WM_SIZE: - if (browser && browser->GetWebView()) { - // resize the web view window to the full size of the browser window - RECT rc; - GetClientRect(browser->GetMainWndHandle(), &rc); - MoveWindow(browser->GetWebViewWndHandle(), 0, 0, rc.right, rc.bottom, - TRUE); - } - return 0; - - case WM_SETFOCUS: - if (browser && browser->GetWebView()) - browser->GetWebView()->setFocus(true); - return 0; - - case WM_KILLFOCUS: - if (browser && browser->GetWebView()) - browser->GetWebView()->setFocus(false); - return 0; - - case WM_ERASEBKGND: - return 0; + switch (message) { + case WM_COMMAND: + { + int wmId = LOWORD(wParam); + int wmEvent = HIWORD(wParam); + + + } + break; + + case WM_DESTROY: + { + CefRefPtr handler = browser->GetHandler(); + if(handler.get()) { + // Notify the handler that the window is about to be closed + handler->HandleBeforeWindowClose(browser); + } + RevokeDragDrop(browser->GetWebViewWndHandle()); + + // Call GC twice to clean up garbage. + browser->GetWebView()->GetMainFrame()->CallJSGC(); + browser->GetWebView()->GetMainFrame()->CallJSGC(); + + // Clean up anything associated with the WebViewHost widget. + browser->GetWebViewHost()->webwidget()->close(); + + // Remove the browser from the list maintained by the context + _Context->RemoveBrowser(browser); + } + return 0; + + case WM_SIZE: + if (browser && browser->GetWebView()) { + // resize the web view window to the full size of the browser window + RECT rc; + GetClientRect(browser->GetMainWndHandle(), &rc); + MoveWindow(browser->GetWebViewWndHandle(), 0, 0, rc.right, rc.bottom, + TRUE); + } + return 0; + + case WM_SETFOCUS: + if (browser && browser->GetWebView()) + browser->GetWebView()->setFocus(true); + return 0; + + case WM_KILLFOCUS: + if (browser && browser->GetWebView()) + browser->GetWebView()->setFocus(false); + return 0; + + case WM_ERASEBKGND: + return 0; } return DefWindowProc(hwnd, message, wParam, lParam); @@ -111,9 +111,9 @@ std::wstring CefBrowserImpl::GetSource(CefRefPtr frame) { // We need to send the request to the UI thread and wait for the result - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); DCHECK(hEvent != NULL); CefRefPtr stream(new CefBytesWriter(BUFFER_SIZE)); @@ -148,9 +148,9 @@ std::wstring CefBrowserImpl::GetText(CefRefPtr frame) { // We need to send the request to the UI thread and wait for the result - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); DCHECK(hEvent != NULL); CefRefPtr stream(new CefBytesWriter(BUFFER_SIZE)); @@ -185,9 +185,9 @@ bool CefBrowserImpl::CanGoBack() { // We need to send the request to the UI thread and wait for the result - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); DCHECK(hEvent != NULL); bool retVal = true; @@ -215,9 +215,9 @@ bool CefBrowserImpl::CanGoForward() { // We need to send the request to the UI thread and wait for the result - // Event that will be used to signal that data is available. Start - // in non-signaled mode so that the event will block. - HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + // Event that will be used to signal that data is available. Start + // in non-signaled mode so that the event will block. + HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); DCHECK(hEvent != NULL); bool retVal = true; @@ -244,31 +244,31 @@ void CefBrowserImpl::UIT_CreateBrowser(const std::wstring& url) REQUIRE_UIT(); // Create the new browser window - window_info_.m_hWnd = CreateWindowEx(window_info_.m_dwExStyle, GetWndClass(), - window_info_.m_windowName, window_info_.m_dwStyle, - window_info_.m_x, window_info_.m_y, window_info_.m_nWidth, - window_info_.m_nHeight, window_info_.m_hWndParent, window_info_.m_hMenu, - _Context->GetInstanceHandle(), NULL); - DCHECK(window_info_.m_hWnd != NULL); - - // Set window user data to this object for future reference from the window - // procedure - win_util::SetWindowUserData(window_info_.m_hWnd, this); - - // Add the new browser to the list maintained by the context - _Context->AddBrowser(this); - - // Create the webview host object - webviewhost_.reset( - WebViewHost::Create(window_info_.m_hWnd, delegate_.get(), - *_Context->GetWebPreferences())); - GetWebView()->SetUseEditorDelegate(true); - delegate_->RegisterDragDrop(); - - // Size the web view window to the browser window - RECT cr; - GetClientRect(window_info_.m_hWnd, &cr); - SetWindowPos(GetWebViewWndHandle(), NULL, cr.left, cr.top, cr.right, + window_info_.m_hWnd = CreateWindowEx(window_info_.m_dwExStyle, GetWndClass(), + window_info_.m_windowName, window_info_.m_dwStyle, + window_info_.m_x, window_info_.m_y, window_info_.m_nWidth, + window_info_.m_nHeight, window_info_.m_hWndParent, window_info_.m_hMenu, + _Context->GetInstanceHandle(), NULL); + DCHECK(window_info_.m_hWnd != NULL); + + // Set window user data to this object for future reference from the window + // procedure + win_util::SetWindowUserData(window_info_.m_hWnd, this); + + // Add the new browser to the list maintained by the context + _Context->AddBrowser(this); + + // Create the webview host object + webviewhost_.reset( + WebViewHost::Create(window_info_.m_hWnd, delegate_.get(), + *_Context->GetWebPreferences())); + GetWebView()->SetUseEditorDelegate(true); + delegate_->RegisterDragDrop(); + + // Size the web view window to the browser window + RECT cr; + GetClientRect(window_info_.m_hWnd, &cr); + SetWindowPos(GetWebViewWndHandle(), NULL, cr.left, cr.top, cr.right, cr.bottom, SWP_NOZORDER | SWP_SHOWWINDOW); if(handler_.get()) { @@ -286,46 +286,46 @@ void CefBrowserImpl::UIT_CreateBrowser(const std::wstring& url) void CefBrowserImpl::UIT_SetFocus(WebWidgetHost* host, bool enable) { REQUIRE_UIT(); - - if (enable) - ::SetFocus(host->view_handle()); - else if (::GetFocus() == host->view_handle()) + + if (enable) + ::SetFocus(host->view_handle()); + else if (::GetFocus() == host->view_handle()) ::SetFocus(NULL); } - -WebKit::WebWidget* CefBrowserImpl::UIT_CreatePopupWidget(WebView* webview) -{ + +WebKit::WebWidget* CefBrowserImpl::UIT_CreatePopupWidget(WebView* webview) +{ REQUIRE_UIT(); - - DCHECK(!popuphost_); - popuphost_ = WebWidgetHost::Create(NULL, popup_delegate_.get()); - ShowWindow(GetPopupWndHandle(), SW_SHOW); - - return popuphost_->webwidget(); + + DCHECK(!popuphost_); + popuphost_ = WebWidgetHost::Create(NULL, popup_delegate_.get()); + ShowWindow(GetPopupWndHandle(), SW_SHOW); + + return popuphost_->webwidget(); } - -void CefBrowserImpl::UIT_ClosePopupWidget() -{ + +void CefBrowserImpl::UIT_ClosePopupWidget() +{ REQUIRE_UIT(); - - PostMessage(GetPopupWndHandle(), WM_CLOSE, 0, 0); - popuphost_ = NULL; -} - - -static void WriteTextToFile(const std::string& data, - const std::wstring& file_path) -{ - FILE* fp; - errno_t err = _wfopen_s(&fp, file_path.c_str(), L"wt"); - if (err) - return; - fwrite(data.c_str(), 1, data.size(), fp); - fclose(fp); -} - -bool CefBrowserImpl::UIT_ViewDocumentString(WebFrame *frame) -{ + + PostMessage(GetPopupWndHandle(), WM_CLOSE, 0, 0); + popuphost_ = NULL; +} + + +static void WriteTextToFile(const std::string& data, + const std::wstring& file_path) +{ + FILE* fp; + errno_t err = _wfopen_s(&fp, file_path.c_str(), L"wt"); + if (err) + return; + fwrite(data.c_str(), 1, data.size(), fp); + fclose(fp); +} + +bool CefBrowserImpl::UIT_ViewDocumentString(WebFrame *frame) +{ REQUIRE_UIT(); DWORD dwRetVal; @@ -333,7 +333,7 @@ bool CefBrowserImpl::UIT_ViewDocumentString(WebFrame *frame) TCHAR lpPathBuffer[512]; UINT uRetVal; TCHAR szTempName[512]; - + dwRetVal = GetTempPath(dwBufSize, // length of the buffer lpPathBuffer); // buffer for path if (dwRetVal > dwBufSize || (dwRetVal == 0)) @@ -349,22 +349,22 @@ bool CefBrowserImpl::UIT_ViewDocumentString(WebFrame *frame) size_t len = wcslen(szTempName); wcscpy(szTempName + len - 3, L"txt"); - WriteTextToFile(frame->GetFullPageHtml(), szTempName); - + WriteTextToFile(frame->GetFullPageHtml(), szTempName); + int errorCode = (int)ShellExecute(GetMainWndHandle(), L"open", szTempName, NULL, NULL, SW_SHOWNORMAL); - if(errorCode <= 32) - return false; - - return true; -} + if(errorCode <= 32) + return false; + + return true; +} void CefBrowserImpl::UIT_GetDocumentStringNotify(CefFrame* frame, CefStreamWriter* writer, HANDLE hEvent) { REQUIRE_UIT(); - + WebFrame* web_frame = GetWebFrame(frame); if(web_frame) { // Retrieve the document string @@ -378,14 +378,14 @@ void CefBrowserImpl::UIT_GetDocumentStringNotify(CefFrame* frame, writer->Release(); frame->Release(); -} +} void CefBrowserImpl::UIT_GetDocumentTextNotify(CefFrame* frame, CefStreamWriter* writer, HANDLE hEvent) { REQUIRE_UIT(); - + WebFrame* web_frame = GetWebFrame(frame); if(web_frame) { // Retrieve the document string @@ -400,12 +400,12 @@ void CefBrowserImpl::UIT_GetDocumentTextNotify(CefFrame* frame, writer->Release(); frame->Release(); -} - +} + void CefBrowserImpl::UIT_CanGoBackNotify(bool *retVal, HANDLE hEvent) { REQUIRE_UIT(); - + *retVal = UIT_CanGoBack(); // Notify the calling thread that the data is now available @@ -415,190 +415,190 @@ void CefBrowserImpl::UIT_CanGoBackNotify(bool *retVal, HANDLE hEvent) void CefBrowserImpl::UIT_CanGoForwardNotify(bool *retVal, HANDLE hEvent) { REQUIRE_UIT(); - + *retVal = UIT_CanGoForward(); // Notify the calling thread that the data is now available SetEvent(hEvent); -} - -void CefBrowserImpl::UIT_PrintPage(int page_number, int total_pages, - const gfx::Size& canvas_size, - WebFrame* frame) { -#if !CEF_PATCHES_APPLIED - NOTREACHED() << "CEF patches must be applied to support printing."; - return; -#endif // !CEF_PATCHES_APPLIED - - REQUIRE_UIT(); - - printing::PrintParams params; - const printing::PrintSettings &settings = print_context_.settings(); - settings.RenderParams(¶ms); - - int src_size_x = canvas_size.width(); - int src_size_y = canvas_size.height(); - float src_margin = .1f * src_size_x; - - int dest_size_x = settings.page_setup_pixels().physical_size().width(); - int dest_size_y = settings.page_setup_pixels().physical_size().height(); - float dest_margin = .1f * dest_size_x; - - print_context_.NewPage(); - - HDC hDC = print_context_.context(); - BOOL res; - - // Save the state to make sure the context this function call does not modify - // the device context. - int saved_state = SaveDC(hDC); - DCHECK_NE(saved_state, 0); - - skia::VectorCanvas canvas(hDC, dest_size_x, dest_size_y); - - // Adjust for the margin offset. +} + +void CefBrowserImpl::UIT_PrintPage(int page_number, int total_pages, + const gfx::Size& canvas_size, + WebFrame* frame) { +#if !CEF_PATCHES_APPLIED + NOTREACHED() << "CEF patches must be applied to support printing."; + return; +#endif // !CEF_PATCHES_APPLIED + + REQUIRE_UIT(); + + printing::PrintParams params; + const printing::PrintSettings &settings = print_context_.settings(); + settings.RenderParams(¶ms); + + int src_size_x = canvas_size.width(); + int src_size_y = canvas_size.height(); + float src_margin = .1f * src_size_x; + + int dest_size_x = settings.page_setup_pixels().physical_size().width(); + int dest_size_y = settings.page_setup_pixels().physical_size().height(); + float dest_margin = .1f * dest_size_x; + + print_context_.NewPage(); + + HDC hDC = print_context_.context(); + BOOL res; + + // Save the state to make sure the context this function call does not modify + // the device context. + int saved_state = SaveDC(hDC); + DCHECK_NE(saved_state, 0); + + skia::VectorCanvas canvas(hDC, dest_size_x, dest_size_y); + + // Adjust for the margin offset. canvas.translate(dest_margin, dest_margin); - - // Apply the print scaling factor. - float print_scale = (dest_size_x - dest_margin * 2) / src_size_x; - canvas.scale(print_scale, print_scale); - - // Set the clipping region to be sure to not overflow. - SkRect clip_rect; - clip_rect.set(0, 0, static_cast(src_size_x), - static_cast(src_size_y)); - canvas.clipRect(clip_rect); - - // Apply the WebKit scaling factor. + + // Apply the print scaling factor. + float print_scale = (dest_size_x - dest_margin * 2) / src_size_x; + canvas.scale(print_scale, print_scale); + + // Set the clipping region to be sure to not overflow. + SkRect clip_rect; + clip_rect.set(0, 0, static_cast(src_size_x), + static_cast(src_size_y)); + canvas.clipRect(clip_rect); + + // Apply the WebKit scaling factor. float webkit_scale = 0; #if CEF_PATCHES_APPLIED webkit_scale = frame->GetPrintPageShrink(page_number); #endif // CEF_PATCHES_APPLIED if (webkit_scale <= 0) { NOTREACHED() << "Printing page " << page_number << " failed."; - } - canvas.scale(webkit_scale, webkit_scale); - - frame->PrintPage(page_number, &canvas); - - res = RestoreDC(hDC, saved_state); - DCHECK_NE(res, 0); - - if(handler_.get()) { - saved_state = SaveDC(hDC); - DCHECK_NE(saved_state, 0); - - // Gather print header state information - RECT rect; - rect.left = (int)floor(dest_margin / 2); - rect.top = rect.left; - rect.right = (int)ceil(dest_size_x - dest_margin / 2); - rect.bottom = (int)ceil(dest_size_y - dest_margin / 2); - - double scale = (double)settings.dpi() / (double)settings.desired_dpi; - - CefPrintInfo printInfo; - - printInfo.m_hDC = hDC; - printInfo.m_Rect = rect; - printInfo.m_Scale = scale; - - std::wstring url = UTF8ToWide(frame->GetURL().spec()); - std::wstring title = title_; - - std::wstring topLeft, topCenter, topRight; - std::wstring bottomLeft, bottomCenter, bottomRight; - - // allow the handler to format print header and/or footer - CefHandler::RetVal rv = handler_->HandlePrintHeaderFooter(this, - GetCefFrame(frame), printInfo, url, title, page_number+1, total_pages, - topLeft, topCenter, topRight, bottomLeft, bottomCenter, bottomRight); - - if(rv != RV_HANDLED) { - // Draw handler-defined headers and/or footers. - LOGFONT lf; - memset(&lf, 0, sizeof(lf)); - lf.lfHeight = (int)ceil(10. * scale); - lf.lfPitchAndFamily = FF_SWISS; - HFONT hFont = CreateFontIndirect(&lf); - - HFONT hOldFont = (HFONT)SelectObject(hDC, hFont); - COLORREF hOldColor = SetTextColor(hDC, RGB(0,0,0)); - int hOldBkMode = SetBkMode(hDC, TRANSPARENT); - - // TODO(cef): Keep the header strings inside a reasonable bounding box - // so that they don't overlap each other. - if(topLeft.size() > 0) { - DrawText(hDC, topLeft.c_str(), topLeft.size(), &rect, - DT_LEFT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(topCenter.size() > 0) { - DrawText(hDC, topCenter.c_str(), topCenter.size(), &rect, - DT_CENTER | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(topRight.size() > 0) { - DrawText(hDC, topRight.c_str(), topRight.size(), &rect, - DT_RIGHT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(bottomLeft.size() > 0) { - DrawText(hDC, bottomLeft.c_str(), bottomLeft.size(), &rect, - DT_LEFT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(bottomCenter.size() > 0) { - DrawText(hDC, bottomCenter.c_str(), bottomCenter.size(), &rect, - DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - if(bottomRight.size() > 0) { - DrawText(hDC, bottomRight.c_str(), bottomRight.size(), &rect, - DT_RIGHT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS - | DT_EXPANDTABS | DT_NOPREFIX); - } - - SetTextColor(hDC, hOldColor); - SelectObject(hDC, hOldFont); - DeleteObject(hFont); - SetBkMode(hDC, hOldBkMode); - } - - res = RestoreDC(hDC, saved_state); - DCHECK_NE(res, 0); - } - - print_context_.PageDone(); -} - -void CefBrowserImpl::UIT_PrintPages(WebFrame* frame) { -#if !CEF_PATCHES_APPLIED - NOTREACHED() << "CEF patches must be applied to support printing."; - return; -#endif // !CEF_PATCHES_APPLIED - + } + canvas.scale(webkit_scale, webkit_scale); + + frame->PrintPage(page_number, &canvas); + + res = RestoreDC(hDC, saved_state); + DCHECK_NE(res, 0); + + if(handler_.get()) { + saved_state = SaveDC(hDC); + DCHECK_NE(saved_state, 0); + + // Gather print header state information + RECT rect; + rect.left = (int)floor(dest_margin / 2); + rect.top = rect.left; + rect.right = (int)ceil(dest_size_x - dest_margin / 2); + rect.bottom = (int)ceil(dest_size_y - dest_margin / 2); + + double scale = (double)settings.dpi() / (double)settings.desired_dpi; + + CefPrintInfo printInfo; + + printInfo.m_hDC = hDC; + printInfo.m_Rect = rect; + printInfo.m_Scale = scale; + + std::wstring url = UTF8ToWide(frame->GetURL().spec()); + std::wstring title = title_; + + std::wstring topLeft, topCenter, topRight; + std::wstring bottomLeft, bottomCenter, bottomRight; + + // allow the handler to format print header and/or footer + CefHandler::RetVal rv = handler_->HandlePrintHeaderFooter(this, + GetCefFrame(frame), printInfo, url, title, page_number+1, total_pages, + topLeft, topCenter, topRight, bottomLeft, bottomCenter, bottomRight); + + if(rv != RV_HANDLED) { + // Draw handler-defined headers and/or footers. + LOGFONT lf; + memset(&lf, 0, sizeof(lf)); + lf.lfHeight = (int)ceil(10. * scale); + lf.lfPitchAndFamily = FF_SWISS; + HFONT hFont = CreateFontIndirect(&lf); + + HFONT hOldFont = (HFONT)SelectObject(hDC, hFont); + COLORREF hOldColor = SetTextColor(hDC, RGB(0,0,0)); + int hOldBkMode = SetBkMode(hDC, TRANSPARENT); + + // TODO(cef): Keep the header strings inside a reasonable bounding box + // so that they don't overlap each other. + if(topLeft.size() > 0) { + DrawText(hDC, topLeft.c_str(), topLeft.size(), &rect, + DT_LEFT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(topCenter.size() > 0) { + DrawText(hDC, topCenter.c_str(), topCenter.size(), &rect, + DT_CENTER | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(topRight.size() > 0) { + DrawText(hDC, topRight.c_str(), topRight.size(), &rect, + DT_RIGHT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(bottomLeft.size() > 0) { + DrawText(hDC, bottomLeft.c_str(), bottomLeft.size(), &rect, + DT_LEFT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(bottomCenter.size() > 0) { + DrawText(hDC, bottomCenter.c_str(), bottomCenter.size(), &rect, + DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if(bottomRight.size() > 0) { + DrawText(hDC, bottomRight.c_str(), bottomRight.size(), &rect, + DT_RIGHT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + + SetTextColor(hDC, hOldColor); + SelectObject(hDC, hOldFont); + DeleteObject(hFont); + SetBkMode(hDC, hOldBkMode); + } + + res = RestoreDC(hDC, saved_state); + DCHECK_NE(res, 0); + } + + print_context_.PageDone(); +} + +void CefBrowserImpl::UIT_PrintPages(WebFrame* frame) { +#if !CEF_PATCHES_APPLIED + NOTREACHED() << "CEF patches must be applied to support printing."; + return; +#endif // !CEF_PATCHES_APPLIED + REQUIRE_UIT(); - - TCHAR printername[512]; - DWORD size = sizeof(printername)-1; - if(GetDefaultPrinter(printername, &size)) { - printing::PrintSettings settings; - settings.set_device_name(printername); - // Initialize it. - print_context_.InitWithSettings(settings); - } - - if(print_context_.AskUserForSettings( - GetMainWndHandle(), UIT_GetPagesCount(frame), false) - != printing::PrintingContext::OK) - return; - - printing::PrintParams params; - const printing::PrintSettings &settings = print_context_.settings(); - - settings.RenderParams(¶ms); - + + TCHAR printername[512]; + DWORD size = sizeof(printername)-1; + if(GetDefaultPrinter(printername, &size)) { + printing::PrintSettings settings; + settings.set_device_name(printername); + // Initialize it. + print_context_.InitWithSettings(settings); + } + + if(print_context_.AskUserForSettings( + GetMainWndHandle(), UIT_GetPagesCount(frame), false) + != printing::PrintingContext::OK) + return; + + printing::PrintParams params; + const printing::PrintSettings &settings = print_context_.settings(); + + settings.RenderParams(¶ms); + int page_count = 0; gfx::Size canvas_size; @@ -611,46 +611,46 @@ void CefBrowserImpl::UIT_PrintPages(WebFrame* frame) { printing::ConvertUnit( settings.page_setup_pixels().physical_size().height(), static_cast(params.dpi), - params.desired_dpi)); + params.desired_dpi)); page_count = frame->PrintBegin(WebSize(canvas_size)); - - if (page_count) { - bool old_state = MessageLoop::current()->NestableTasksAllowed(); - MessageLoop::current()->SetNestableTasksAllowed(false); - - // TODO(cef): Use the page title as the document name - print_context_.NewDocument(L"New Document"); - if(settings.ranges.size() > 0) { - for (unsigned x = 0; x < settings.ranges.size(); ++x) { - const printing::PageRange& range = settings.ranges[x]; - for(int i = range.from; i <= range.to; ++i) - UIT_PrintPage(i, page_count, canvas_size, frame); - } - } else { - for(int i = 0; i < page_count; ++i) - UIT_PrintPage(i, page_count, canvas_size, frame); - } - print_context_.DocumentDone(); - - MessageLoop::current()->SetNestableTasksAllowed(old_state); - } - - frame->PrintEnd(); -} - -int CefBrowserImpl::UIT_GetPagesCount(WebFrame* frame) -{ + + if (page_count) { + bool old_state = MessageLoop::current()->NestableTasksAllowed(); + MessageLoop::current()->SetNestableTasksAllowed(false); + + // TODO(cef): Use the page title as the document name + print_context_.NewDocument(L"New Document"); + if(settings.ranges.size() > 0) { + for (unsigned x = 0; x < settings.ranges.size(); ++x) { + const printing::PageRange& range = settings.ranges[x]; + for(int i = range.from; i <= range.to; ++i) + UIT_PrintPage(i, page_count, canvas_size, frame); + } + } else { + for(int i = 0; i < page_count; ++i) + UIT_PrintPage(i, page_count, canvas_size, frame); + } + print_context_.DocumentDone(); + + MessageLoop::current()->SetNestableTasksAllowed(old_state); + } + + frame->PrintEnd(); +} + +int CefBrowserImpl::UIT_GetPagesCount(WebFrame* frame) +{ REQUIRE_UIT(); - - printing::PrintParams params; - const printing::PrintSettings &settings = print_context_.settings(); - - settings.RenderParams(¶ms); - - // The dbi will be 0 if no default printer is configured. - if(params.dpi == 0) - return 0; - + + printing::PrintParams params; + const printing::PrintSettings &settings = print_context_.settings(); + + settings.RenderParams(¶ms); + + // The dbi will be 0 if no default printer is configured. + if(params.dpi == 0) + return 0; + int page_count = 0; gfx::Size canvas_size; @@ -663,9 +663,9 @@ int CefBrowserImpl::UIT_GetPagesCount(WebFrame* frame) printing::ConvertUnit( settings.page_setup_pixels().physical_size().height(), static_cast(params.dpi), - params.desired_dpi)); - page_count = frame->PrintBegin(WebSize(canvas_size)); - frame->PrintEnd(); - - return page_count; -} + params.desired_dpi)); + page_count = frame->PrintBegin(WebSize(canvas_size)); + frame->PrintEnd(); + + return page_count; +} diff --git a/libcef/browser_navigation_controller.cc b/libcef/browser_navigation_controller.cc index 941e658b0..7ab4dc1b7 100644 --- a/libcef/browser_navigation_controller.cc +++ b/libcef/browser_navigation_controller.cc @@ -1,242 +1,242 @@ -// 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 "precompiled_libcef.h" -#include "browser_navigation_controller.h" -#include "browser_impl.h" - -#include "base/logging.h" -#include "net/base/upload_data.h" - -// ---------------------------------------------------------------------------- -// BrowserNavigationEntry - -BrowserNavigationEntry::BrowserNavigationEntry() - : page_id_(-1) { -} - -BrowserNavigationEntry::BrowserNavigationEntry(int page_id, - const GURL& url, - const std::wstring& title, - const std::wstring& target_frame, - const std::wstring& method, - const WebKit::WebHTTPBody& upload, - const CefRequest::HeaderMap& headers) - : page_id_(page_id), - url_(url), - title_(title), - target_frame_(target_frame), - method_(method), - headers_(headers) { - if(!upload.isNull()) - upload_ = upload; -} - -BrowserNavigationEntry::~BrowserNavigationEntry() { -} - -void BrowserNavigationEntry::SetContentState(const std::string& state) { - state_ = state; -} - -// ---------------------------------------------------------------------------- -// BrowserNavigationController - -BrowserNavigationController::BrowserNavigationController(CefBrowserImpl* shell) - : pending_entry_(NULL), - last_committed_entry_index_(-1), - pending_entry_index_(-1), - browser_(shell), - max_page_id_(-1) { -} - -BrowserNavigationController::~BrowserNavigationController() { - DiscardPendingEntry(); -} - -void BrowserNavigationController::Reset() { - entries_.clear(); - DiscardPendingEntry(); - - last_committed_entry_index_ = -1; -} - -void BrowserNavigationController::Reload() { - // Base the navigation on where we are now... - int current_index = GetCurrentEntryIndex(); - - // If we are no where, then we can't reload. TODO(darin): We should add a - // CanReload method. - if (current_index == -1) - return; - - DiscardPendingEntry(); - - pending_entry_index_ = current_index; - NavigateToPendingEntry(true); -} - -void BrowserNavigationController::GoToOffset(int offset) { - int index = last_committed_entry_index_ + offset; - if (index < 0 || index >= GetEntryCount()) - return; - - GoToIndex(index); -} - -void BrowserNavigationController::GoToIndex(int index) { - DCHECK(index >= 0); - DCHECK(index < static_cast(entries_.size())); - - DiscardPendingEntry(); - - pending_entry_index_ = index; - NavigateToPendingEntry(false); -} - -void BrowserNavigationController::LoadEntry(BrowserNavigationEntry* entry) { - // When navigating to a new page, we don't know for sure if we will actually - // end up leaving the current page. The new page load could for example - // result in a download or a 'no content' response (e.g., a mailto: URL). - DiscardPendingEntry(); - pending_entry_ = entry; - NavigateToPendingEntry(false); -} - - -BrowserNavigationEntry* BrowserNavigationController::GetLastCommittedEntry() const { - if (last_committed_entry_index_ == -1) - return NULL; - return entries_[last_committed_entry_index_].get(); -} - -BrowserNavigationEntry* BrowserNavigationController::GetActiveEntry() const { - BrowserNavigationEntry* entry = pending_entry_; - if (!entry) - entry = GetLastCommittedEntry(); - return entry; -} - -int BrowserNavigationController::GetCurrentEntryIndex() const { - if (pending_entry_index_ != -1) - return pending_entry_index_; - return last_committed_entry_index_; -} - - -BrowserNavigationEntry* BrowserNavigationController::GetEntryAtIndex( - int index) const { - if (index < 0 || index >= GetEntryCount()) - return NULL; - - return entries_[index].get(); -} - -BrowserNavigationEntry* BrowserNavigationController::GetEntryWithPageID( - int32 page_id) const { - int index = GetEntryIndexWithPageID(page_id); - return (index != -1) ? entries_[index].get() : NULL; -} - -void BrowserNavigationController::DidNavigateToEntry(BrowserNavigationEntry* entry) { - // If the entry is that of a page with PageID larger than any this Tab has - // seen before, then consider it a new navigation. - if (entry->GetPageID() > GetMaxPageID()) { - InsertEntry(entry); - return; - } - - // Otherwise, we just need to update an existing entry with matching PageID. - // If the existing entry corresponds to the entry which is pending, then we - // must update the current entry index accordingly. When navigating to the - // same URL, a new PageID is not created. - - int existing_entry_index = GetEntryIndexWithPageID(entry->GetPageID()); - BrowserNavigationEntry* existing_entry = (existing_entry_index != -1) ? - entries_[existing_entry_index].get() : NULL; - if (!existing_entry) { - // No existing entry, then simply ignore this navigation! - DLOG(WARNING) << "ignoring navigation for page: " << entry->GetPageID(); - } else if (existing_entry == pending_entry_) { - // The given entry might provide a new URL... e.g., navigating back to a - // page in session history could have resulted in a new client redirect. - existing_entry->SetURL(entry->GetURL()); - existing_entry->SetContentState(entry->GetContentState()); - last_committed_entry_index_ = pending_entry_index_; - pending_entry_index_ = -1; - pending_entry_ = NULL; - } else if (pending_entry_ && pending_entry_->GetPageID() == -1 && - pending_entry_->GetURL() == existing_entry->GetURL()) { - // Not a new navigation - DiscardPendingEntry(); - } else { - // The given entry might provide a new URL... e.g., navigating to a page - // might result in a client redirect, which should override the URL of the - // existing entry. - existing_entry->SetURL(entry->GetURL()); - existing_entry->SetContentState(entry->GetContentState()); - - // The navigation could have been issued by the renderer, so be sure that - // we update our current index. - last_committed_entry_index_ = existing_entry_index; - } - - delete entry; - UpdateMaxPageID(); -} - -void BrowserNavigationController::DiscardPendingEntry() { - if (pending_entry_index_ == -1) - delete pending_entry_; - pending_entry_ = NULL; - pending_entry_index_ = -1; -} - -void BrowserNavigationController::InsertEntry(BrowserNavigationEntry* entry) { - DiscardPendingEntry(); - - // Prune any entry which are in front of the current entry - int current_size = static_cast(entries_.size()); - if (current_size > 0) { - while (last_committed_entry_index_ < (current_size - 1)) { - entries_.pop_back(); - current_size--; - } - } - - entries_.push_back(linked_ptr(entry)); - last_committed_entry_index_ = static_cast(entries_.size()) - 1; - UpdateMaxPageID(); -} - -int BrowserNavigationController::GetEntryIndexWithPageID(int32 page_id) const { - for (int i = static_cast(entries_.size())-1; i >= 0; --i) { - if (entries_[i]->GetPageID() == page_id) - return i; - } - return -1; -} - -void BrowserNavigationController::NavigateToPendingEntry(bool reload) { - // For session history navigations only the pending_entry_index_ is set. - if (!pending_entry_) { - DCHECK(pending_entry_index_ != -1); - pending_entry_ = entries_[pending_entry_index_].get(); - } - - if (browser_->UIT_Navigate(*pending_entry_, reload)) { - // Note: this is redundant if navigation completed synchronously because - // DidNavigateToEntry call this as well. - UpdateMaxPageID(); - } else { - DiscardPendingEntry(); - } -} - -void BrowserNavigationController::UpdateMaxPageID() { - BrowserNavigationEntry* entry = GetActiveEntry(); - if (entry) - max_page_id_ = std::max(max_page_id_, entry->GetPageID()); -} +// 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 "precompiled_libcef.h" +#include "browser_navigation_controller.h" +#include "browser_impl.h" + +#include "base/logging.h" +#include "net/base/upload_data.h" + +// ---------------------------------------------------------------------------- +// BrowserNavigationEntry + +BrowserNavigationEntry::BrowserNavigationEntry() + : page_id_(-1) { +} + +BrowserNavigationEntry::BrowserNavigationEntry(int page_id, + const GURL& url, + const std::wstring& title, + const std::wstring& target_frame, + const std::wstring& method, + const WebKit::WebHTTPBody& upload, + const CefRequest::HeaderMap& headers) + : page_id_(page_id), + url_(url), + title_(title), + target_frame_(target_frame), + method_(method), + headers_(headers) { + if(!upload.isNull()) + upload_ = upload; +} + +BrowserNavigationEntry::~BrowserNavigationEntry() { +} + +void BrowserNavigationEntry::SetContentState(const std::string& state) { + state_ = state; +} + +// ---------------------------------------------------------------------------- +// BrowserNavigationController + +BrowserNavigationController::BrowserNavigationController(CefBrowserImpl* shell) + : pending_entry_(NULL), + last_committed_entry_index_(-1), + pending_entry_index_(-1), + browser_(shell), + max_page_id_(-1) { +} + +BrowserNavigationController::~BrowserNavigationController() { + DiscardPendingEntry(); +} + +void BrowserNavigationController::Reset() { + entries_.clear(); + DiscardPendingEntry(); + + last_committed_entry_index_ = -1; +} + +void BrowserNavigationController::Reload() { + // Base the navigation on where we are now... + int current_index = GetCurrentEntryIndex(); + + // If we are no where, then we can't reload. TODO(darin): We should add a + // CanReload method. + if (current_index == -1) + return; + + DiscardPendingEntry(); + + pending_entry_index_ = current_index; + NavigateToPendingEntry(true); +} + +void BrowserNavigationController::GoToOffset(int offset) { + int index = last_committed_entry_index_ + offset; + if (index < 0 || index >= GetEntryCount()) + return; + + GoToIndex(index); +} + +void BrowserNavigationController::GoToIndex(int index) { + DCHECK(index >= 0); + DCHECK(index < static_cast(entries_.size())); + + DiscardPendingEntry(); + + pending_entry_index_ = index; + NavigateToPendingEntry(false); +} + +void BrowserNavigationController::LoadEntry(BrowserNavigationEntry* entry) { + // When navigating to a new page, we don't know for sure if we will actually + // end up leaving the current page. The new page load could for example + // result in a download or a 'no content' response (e.g., a mailto: URL). + DiscardPendingEntry(); + pending_entry_ = entry; + NavigateToPendingEntry(false); +} + + +BrowserNavigationEntry* BrowserNavigationController::GetLastCommittedEntry() const { + if (last_committed_entry_index_ == -1) + return NULL; + return entries_[last_committed_entry_index_].get(); +} + +BrowserNavigationEntry* BrowserNavigationController::GetActiveEntry() const { + BrowserNavigationEntry* entry = pending_entry_; + if (!entry) + entry = GetLastCommittedEntry(); + return entry; +} + +int BrowserNavigationController::GetCurrentEntryIndex() const { + if (pending_entry_index_ != -1) + return pending_entry_index_; + return last_committed_entry_index_; +} + + +BrowserNavigationEntry* BrowserNavigationController::GetEntryAtIndex( + int index) const { + if (index < 0 || index >= GetEntryCount()) + return NULL; + + return entries_[index].get(); +} + +BrowserNavigationEntry* BrowserNavigationController::GetEntryWithPageID( + int32 page_id) const { + int index = GetEntryIndexWithPageID(page_id); + return (index != -1) ? entries_[index].get() : NULL; +} + +void BrowserNavigationController::DidNavigateToEntry(BrowserNavigationEntry* entry) { + // If the entry is that of a page with PageID larger than any this Tab has + // seen before, then consider it a new navigation. + if (entry->GetPageID() > GetMaxPageID()) { + InsertEntry(entry); + return; + } + + // Otherwise, we just need to update an existing entry with matching PageID. + // If the existing entry corresponds to the entry which is pending, then we + // must update the current entry index accordingly. When navigating to the + // same URL, a new PageID is not created. + + int existing_entry_index = GetEntryIndexWithPageID(entry->GetPageID()); + BrowserNavigationEntry* existing_entry = (existing_entry_index != -1) ? + entries_[existing_entry_index].get() : NULL; + if (!existing_entry) { + // No existing entry, then simply ignore this navigation! + DLOG(WARNING) << "ignoring navigation for page: " << entry->GetPageID(); + } else if (existing_entry == pending_entry_) { + // The given entry might provide a new URL... e.g., navigating back to a + // page in session history could have resulted in a new client redirect. + existing_entry->SetURL(entry->GetURL()); + existing_entry->SetContentState(entry->GetContentState()); + last_committed_entry_index_ = pending_entry_index_; + pending_entry_index_ = -1; + pending_entry_ = NULL; + } else if (pending_entry_ && pending_entry_->GetPageID() == -1 && + pending_entry_->GetURL() == existing_entry->GetURL()) { + // Not a new navigation + DiscardPendingEntry(); + } else { + // The given entry might provide a new URL... e.g., navigating to a page + // might result in a client redirect, which should override the URL of the + // existing entry. + existing_entry->SetURL(entry->GetURL()); + existing_entry->SetContentState(entry->GetContentState()); + + // The navigation could have been issued by the renderer, so be sure that + // we update our current index. + last_committed_entry_index_ = existing_entry_index; + } + + delete entry; + UpdateMaxPageID(); +} + +void BrowserNavigationController::DiscardPendingEntry() { + if (pending_entry_index_ == -1) + delete pending_entry_; + pending_entry_ = NULL; + pending_entry_index_ = -1; +} + +void BrowserNavigationController::InsertEntry(BrowserNavigationEntry* entry) { + DiscardPendingEntry(); + + // Prune any entry which are in front of the current entry + int current_size = static_cast(entries_.size()); + if (current_size > 0) { + while (last_committed_entry_index_ < (current_size - 1)) { + entries_.pop_back(); + current_size--; + } + } + + entries_.push_back(linked_ptr(entry)); + last_committed_entry_index_ = static_cast(entries_.size()) - 1; + UpdateMaxPageID(); +} + +int BrowserNavigationController::GetEntryIndexWithPageID(int32 page_id) const { + for (int i = static_cast(entries_.size())-1; i >= 0; --i) { + if (entries_[i]->GetPageID() == page_id) + return i; + } + return -1; +} + +void BrowserNavigationController::NavigateToPendingEntry(bool reload) { + // For session history navigations only the pending_entry_index_ is set. + if (!pending_entry_) { + DCHECK(pending_entry_index_ != -1); + pending_entry_ = entries_[pending_entry_index_].get(); + } + + if (browser_->UIT_Navigate(*pending_entry_, reload)) { + // Note: this is redundant if navigation completed synchronously because + // DidNavigateToEntry call this as well. + UpdateMaxPageID(); + } else { + DiscardPendingEntry(); + } +} + +void BrowserNavigationController::UpdateMaxPageID() { + BrowserNavigationEntry* entry = GetActiveEntry(); + if (entry) + max_page_id_ = std::max(max_page_id_, entry->GetPageID()); +} diff --git a/libcef/browser_navigation_controller.h b/libcef/browser_navigation_controller.h index ca90ca3ba..f13cdf6d5 100644 --- a/libcef/browser_navigation_controller.h +++ b/libcef/browser_navigation_controller.h @@ -1,212 +1,212 @@ -// Copyright (c) 2008-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. - -#ifndef _BROWSER_NAVIGATION_CONTROLLER_H -#define _BROWSER_NAVIGATION_CONTROLLER_H - -#include -#include - -#include "base/basictypes.h" -#include "base/linked_ptr.h" -#include "base/ref_counted.h" -#include "googleurl/src/gurl.h" -#include "webkit/api/public/WebDataSource.h" -#include "webkit/api/public/WebHTTPBody.h" - -#include "include/cef.h" - -class GURL; -class CefBrowserImpl; - -// Associated with browser-initated navigations to hold tracking data. -class BrowserExtraData : public WebKit::WebDataSource::ExtraData { - public: - BrowserExtraData(int32 pending_page_id) - : pending_page_id(pending_page_id), - request_committed(false) { - } - - // Contains the page_id for this navigation or -1 if there is none yet. - int32 pending_page_id; - - // True if we have already processed the "DidCommitLoad" event for this - // request. Used by session history. - bool request_committed; -}; - -// Stores one back/forward navigation state for the test shell. -class BrowserNavigationEntry { - public: - BrowserNavigationEntry(); - BrowserNavigationEntry(int page_id, - const GURL& url, - const std::wstring& title, - const std::wstring& target_frame, - const std::wstring& method, - const WebKit::WebHTTPBody& upload, - const CefRequest::HeaderMap& headers); - ~BrowserNavigationEntry(); - - // Set / Get the URI - void SetURL(const GURL& url) { url_ = url; } - const GURL& GetURL() const { return url_; } - - // Set / Get the title - void SetTitle(const std::wstring& a_title) { title_ = a_title; } - const std::wstring& GetTitle() const { return title_; } - - // Set / Get opaque state. - // WARNING: This state is saved to the database and used to restore previous - // states. If you use write a custom TabContents and provide your own - // state make sure you have the ability to modify the format in the future - // while being able to deal with older versions. - void SetContentState(const std::string& state); - const std::string& GetContentState() const { return state_; } - - // Get the page id corresponding to the tab's state. - void SetPageID(int page_id) { page_id_ = page_id; } - int32 GetPageID() const { return page_id_; } - - const std::wstring& GetTargetFrame() const { return target_frame_; } - - const std::wstring& GetMethod() const { return method_; } - const WebKit::WebHTTPBody& GetUploadData() const { return upload_; } - const CefRequest::HeaderMap& GetHeaders() const { return headers_; } - -private: - // Describes the current page that the tab represents. This is not relevant - // for all tab contents types. - int32 page_id_; - - GURL url_; - std::wstring title_; - std::string state_; - std::wstring method_; - WebKit::WebHTTPBody upload_; - CefRequest::HeaderMap headers_; - - std::wstring target_frame_; - - DISALLOW_COPY_AND_ASSIGN(BrowserNavigationEntry); -}; - -// Browser's NavigationController. The goal is to be as close to the Chrome -// version as possible. -class BrowserNavigationController { - public: - BrowserNavigationController(CefBrowserImpl* shell); - ~BrowserNavigationController(); - - void Reset(); - - // Causes the controller to reload the current (or pending) entry. - void Reload(); - - // Causes the controller to go to the specified offset from current. Does - // nothing if out of bounds. - void GoToOffset(int offset); - - // Causes the controller to go to the specified index. - void GoToIndex(int index); - - // Causes the controller to load the specified entry. The controller - // assumes ownership of the entry. - // NOTE: Do not pass an entry that the controller already owns! - void LoadEntry(BrowserNavigationEntry* entry); - - // Returns the last committed entry, which may be null if there are no - // committed entries. - BrowserNavigationEntry* GetLastCommittedEntry() const; - - // Returns the number of entries in the NavigationControllerBase, excluding - // the pending entry if there is one. - int GetEntryCount() const { - return static_cast(entries_.size()); - } - - // Returns the active entry, which is the pending entry if a navigation is in - // progress or the last committed entry otherwise. NOTE: This can be NULL!! - // - // If you are trying to get the current state of the NavigationControllerBase, - // this is the method you will typically want to call. - BrowserNavigationEntry* GetActiveEntry() const; - - // Returns the index from which we would go back/forward or reload. This is - // the last_committed_entry_index_ if pending_entry_index_ is -1. Otherwise, - // it is the pending_entry_index_. - int GetCurrentEntryIndex() const; - - // Returns the entry at the specified index. Returns NULL if out of - // bounds. - BrowserNavigationEntry* GetEntryAtIndex(int index) const; - - // Return the entry with the corresponding type and page_id, or NULL if - // not found. - BrowserNavigationEntry* GetEntryWithPageID(int32 page_id) const; - - // Returns the index of the last committed entry. - int GetLastCommittedEntryIndex() const { - return last_committed_entry_index_; - } - - // Returns true if there are no entries before the last committed entry. - bool IsAtStart() const { - return (GetLastCommittedEntryIndex() == 0); - } - - // Returns true if there are no entries after the last committed entry. - bool IsAtEnd() const { - return (GetLastCommittedEntryIndex() == GetEntryCount()-1); - } - - // Used to inform us of a navigation being committed for a tab. We will take - // ownership of the entry. Any entry located forward to the current entry will - // be deleted. The new entry becomes the current entry. - void DidNavigateToEntry(BrowserNavigationEntry* entry); - - // Used to inform us to discard its pending entry. - void DiscardPendingEntry(); - - private: - // Inserts an entry after the current position, removing all entries after it. - // The new entry will become the active one. - void InsertEntry(BrowserNavigationEntry* entry); - - int GetMaxPageID() const { return max_page_id_; } - void NavigateToPendingEntry(bool reload); - - // Return the index of the entry with the corresponding type and page_id, - // or -1 if not found. - int GetEntryIndexWithPageID(int32 page_id) const; - - // Updates the max page ID with that of the given entry, if is larger. - void UpdateMaxPageID(); - - // List of NavigationEntry for this tab - typedef std::vector< linked_ptr > NavigationEntryList; - typedef NavigationEntryList::iterator NavigationEntryListIterator; - NavigationEntryList entries_; - - // An entry we haven't gotten a response for yet. This will be discarded - // when we navigate again. It's used only so we know what the currently - // displayed tab is. - BrowserNavigationEntry* pending_entry_; - - // currently visible entry - int last_committed_entry_index_; - - // index of pending entry if it is in entries_, or -1 if pending_entry_ is a - // new entry (created by LoadURL). - int pending_entry_index_; - - CefBrowserImpl* browser_; - int max_page_id_; - - DISALLOW_EVIL_CONSTRUCTORS(BrowserNavigationController); -}; - -#endif // _BROWSER_NAVIGATION_CONTROLLER_H - +// Copyright (c) 2008-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. + +#ifndef _BROWSER_NAVIGATION_CONTROLLER_H +#define _BROWSER_NAVIGATION_CONTROLLER_H + +#include +#include + +#include "base/basictypes.h" +#include "base/linked_ptr.h" +#include "base/ref_counted.h" +#include "googleurl/src/gurl.h" +#include "webkit/api/public/WebDataSource.h" +#include "webkit/api/public/WebHTTPBody.h" + +#include "include/cef.h" + +class GURL; +class CefBrowserImpl; + +// Associated with browser-initated navigations to hold tracking data. +class BrowserExtraData : public WebKit::WebDataSource::ExtraData { + public: + BrowserExtraData(int32 pending_page_id) + : pending_page_id(pending_page_id), + request_committed(false) { + } + + // Contains the page_id for this navigation or -1 if there is none yet. + int32 pending_page_id; + + // True if we have already processed the "DidCommitLoad" event for this + // request. Used by session history. + bool request_committed; +}; + +// Stores one back/forward navigation state for the test shell. +class BrowserNavigationEntry { + public: + BrowserNavigationEntry(); + BrowserNavigationEntry(int page_id, + const GURL& url, + const std::wstring& title, + const std::wstring& target_frame, + const std::wstring& method, + const WebKit::WebHTTPBody& upload, + const CefRequest::HeaderMap& headers); + ~BrowserNavigationEntry(); + + // Set / Get the URI + void SetURL(const GURL& url) { url_ = url; } + const GURL& GetURL() const { return url_; } + + // Set / Get the title + void SetTitle(const std::wstring& a_title) { title_ = a_title; } + const std::wstring& GetTitle() const { return title_; } + + // Set / Get opaque state. + // WARNING: This state is saved to the database and used to restore previous + // states. If you use write a custom TabContents and provide your own + // state make sure you have the ability to modify the format in the future + // while being able to deal with older versions. + void SetContentState(const std::string& state); + const std::string& GetContentState() const { return state_; } + + // Get the page id corresponding to the tab's state. + void SetPageID(int page_id) { page_id_ = page_id; } + int32 GetPageID() const { return page_id_; } + + const std::wstring& GetTargetFrame() const { return target_frame_; } + + const std::wstring& GetMethod() const { return method_; } + const WebKit::WebHTTPBody& GetUploadData() const { return upload_; } + const CefRequest::HeaderMap& GetHeaders() const { return headers_; } + +private: + // Describes the current page that the tab represents. This is not relevant + // for all tab contents types. + int32 page_id_; + + GURL url_; + std::wstring title_; + std::string state_; + std::wstring method_; + WebKit::WebHTTPBody upload_; + CefRequest::HeaderMap headers_; + + std::wstring target_frame_; + + DISALLOW_COPY_AND_ASSIGN(BrowserNavigationEntry); +}; + +// Browser's NavigationController. The goal is to be as close to the Chrome +// version as possible. +class BrowserNavigationController { + public: + BrowserNavigationController(CefBrowserImpl* shell); + ~BrowserNavigationController(); + + void Reset(); + + // Causes the controller to reload the current (or pending) entry. + void Reload(); + + // Causes the controller to go to the specified offset from current. Does + // nothing if out of bounds. + void GoToOffset(int offset); + + // Causes the controller to go to the specified index. + void GoToIndex(int index); + + // Causes the controller to load the specified entry. The controller + // assumes ownership of the entry. + // NOTE: Do not pass an entry that the controller already owns! + void LoadEntry(BrowserNavigationEntry* entry); + + // Returns the last committed entry, which may be null if there are no + // committed entries. + BrowserNavigationEntry* GetLastCommittedEntry() const; + + // Returns the number of entries in the NavigationControllerBase, excluding + // the pending entry if there is one. + int GetEntryCount() const { + return static_cast(entries_.size()); + } + + // Returns the active entry, which is the pending entry if a navigation is in + // progress or the last committed entry otherwise. NOTE: This can be NULL!! + // + // If you are trying to get the current state of the NavigationControllerBase, + // this is the method you will typically want to call. + BrowserNavigationEntry* GetActiveEntry() const; + + // Returns the index from which we would go back/forward or reload. This is + // the last_committed_entry_index_ if pending_entry_index_ is -1. Otherwise, + // it is the pending_entry_index_. + int GetCurrentEntryIndex() const; + + // Returns the entry at the specified index. Returns NULL if out of + // bounds. + BrowserNavigationEntry* GetEntryAtIndex(int index) const; + + // Return the entry with the corresponding type and page_id, or NULL if + // not found. + BrowserNavigationEntry* GetEntryWithPageID(int32 page_id) const; + + // Returns the index of the last committed entry. + int GetLastCommittedEntryIndex() const { + return last_committed_entry_index_; + } + + // Returns true if there are no entries before the last committed entry. + bool IsAtStart() const { + return (GetLastCommittedEntryIndex() == 0); + } + + // Returns true if there are no entries after the last committed entry. + bool IsAtEnd() const { + return (GetLastCommittedEntryIndex() == GetEntryCount()-1); + } + + // Used to inform us of a navigation being committed for a tab. We will take + // ownership of the entry. Any entry located forward to the current entry will + // be deleted. The new entry becomes the current entry. + void DidNavigateToEntry(BrowserNavigationEntry* entry); + + // Used to inform us to discard its pending entry. + void DiscardPendingEntry(); + + private: + // Inserts an entry after the current position, removing all entries after it. + // The new entry will become the active one. + void InsertEntry(BrowserNavigationEntry* entry); + + int GetMaxPageID() const { return max_page_id_; } + void NavigateToPendingEntry(bool reload); + + // Return the index of the entry with the corresponding type and page_id, + // or -1 if not found. + int GetEntryIndexWithPageID(int32 page_id) const; + + // Updates the max page ID with that of the given entry, if is larger. + void UpdateMaxPageID(); + + // List of NavigationEntry for this tab + typedef std::vector< linked_ptr > NavigationEntryList; + typedef NavigationEntryList::iterator NavigationEntryListIterator; + NavigationEntryList entries_; + + // An entry we haven't gotten a response for yet. This will be discarded + // when we navigate again. It's used only so we know what the currently + // displayed tab is. + BrowserNavigationEntry* pending_entry_; + + // currently visible entry + int last_committed_entry_index_; + + // index of pending entry if it is in entries_, or -1 if pending_entry_ is a + // new entry (created by LoadURL). + int pending_entry_index_; + + CefBrowserImpl* browser_; + int max_page_id_; + + DISALLOW_EVIL_CONSTRUCTORS(BrowserNavigationController); +}; + +#endif // _BROWSER_NAVIGATION_CONTROLLER_H + diff --git a/libcef/browser_request_context.cc b/libcef/browser_request_context.cc index 35e99ee53..0a43dbaf8 100644 --- a/libcef/browser_request_context.cc +++ b/libcef/browser_request_context.cc @@ -1,63 +1,63 @@ -// 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 "precompiled_libcef.h" -#include "browser_request_context.h" - -#include "net/base/cookie_monster.h" -#include "net/base/host_resolver.h" -#include "net/ftp/ftp_network_layer.h" -#include "net/proxy/proxy_service.h" -#include "webkit/glue/webkit_glue.h" - -BrowserRequestContext::BrowserRequestContext() { - Init(std::wstring(), net::HttpCache::NORMAL, false); -} - -BrowserRequestContext::BrowserRequestContext( - const std::wstring& cache_path, - net::HttpCache::Mode cache_mode, - bool no_proxy) { - Init(cache_path, cache_mode, no_proxy); -} - -void BrowserRequestContext::Init( - const std::wstring& cache_path, - net::HttpCache::Mode cache_mode, - bool no_proxy) { - cookie_store_ = new net::CookieMonster(); - - // hard-code A-L and A-C for test shells - accept_language_ = "en-us,en"; - accept_charset_ = "iso-8859-1,*,utf-8"; - - net::ProxyConfig proxy_config; - host_resolver_ = net::CreateSystemHostResolver(); - proxy_service_ = net::ProxyService::Create(no_proxy ? &proxy_config : NULL, - false, NULL, NULL); - - net::HttpCache *cache; - if (cache_path.empty()) { - cache = new net::HttpCache(host_resolver_, proxy_service_, 0); - } else { - cache = new net::HttpCache(host_resolver_, proxy_service_, cache_path, 0); - } - cache->set_mode(cache_mode); - http_transaction_factory_ = cache; - - ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); -} - -BrowserRequestContext::~BrowserRequestContext() { - delete cookie_store_; - delete ftp_transaction_factory_; - delete http_transaction_factory_; - delete proxy_service_; -} - -const std::string& BrowserRequestContext::GetUserAgent( - const GURL& url) const { - return webkit_glue::GetUserAgent(url); -} +// 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 "precompiled_libcef.h" +#include "browser_request_context.h" + +#include "net/base/cookie_monster.h" +#include "net/base/host_resolver.h" +#include "net/ftp/ftp_network_layer.h" +#include "net/proxy/proxy_service.h" +#include "webkit/glue/webkit_glue.h" + +BrowserRequestContext::BrowserRequestContext() { + Init(std::wstring(), net::HttpCache::NORMAL, false); +} + +BrowserRequestContext::BrowserRequestContext( + const std::wstring& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy) { + Init(cache_path, cache_mode, no_proxy); +} + +void BrowserRequestContext::Init( + const std::wstring& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy) { + cookie_store_ = new net::CookieMonster(); + + // hard-code A-L and A-C for test shells + accept_language_ = "en-us,en"; + accept_charset_ = "iso-8859-1,*,utf-8"; + + net::ProxyConfig proxy_config; + host_resolver_ = net::CreateSystemHostResolver(); + proxy_service_ = net::ProxyService::Create(no_proxy ? &proxy_config : NULL, + false, NULL, NULL); + + net::HttpCache *cache; + if (cache_path.empty()) { + cache = new net::HttpCache(host_resolver_, proxy_service_, 0); + } else { + cache = new net::HttpCache(host_resolver_, proxy_service_, cache_path, 0); + } + cache->set_mode(cache_mode); + http_transaction_factory_ = cache; + + ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); +} + +BrowserRequestContext::~BrowserRequestContext() { + delete cookie_store_; + delete ftp_transaction_factory_; + delete http_transaction_factory_; + delete proxy_service_; +} + +const std::string& BrowserRequestContext::GetUserAgent( + const GURL& url) const { + return webkit_glue::GetUserAgent(url); +} diff --git a/libcef/browser_request_context.h b/libcef/browser_request_context.h index 517898bb0..b05d4e391 100644 --- a/libcef/browser_request_context.h +++ b/libcef/browser_request_context.h @@ -1,34 +1,34 @@ -// 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. - -#ifndef _BROWSER_REQUEST_CONTEXT_H -#define _BROWSER_REQUEST_CONTEXT_H - -#include "net/http/http_cache.h" -#include "net/url_request/url_request_context.h" - -// A basic URLRequestContext that only provides an in-memory cookie store. -class BrowserRequestContext : public URLRequestContext { - public: - // Use an in-memory cache - BrowserRequestContext(); - - // Use an on-disk cache at the specified location. Optionally, use the cache - // in playback or record mode. - BrowserRequestContext(const std::wstring& cache_path, - net::HttpCache::Mode cache_mode, - bool no_proxy); - - ~BrowserRequestContext(); - - virtual const std::string& GetUserAgent(const GURL& url) const; - - private: - void Init(const std::wstring& cache_path, net::HttpCache::Mode cache_mode, - bool no_proxy); -}; - -#endif // _BROWSER_REQUEST_CONTEXT_H - +// 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. + +#ifndef _BROWSER_REQUEST_CONTEXT_H +#define _BROWSER_REQUEST_CONTEXT_H + +#include "net/http/http_cache.h" +#include "net/url_request/url_request_context.h" + +// A basic URLRequestContext that only provides an in-memory cookie store. +class BrowserRequestContext : public URLRequestContext { + public: + // Use an in-memory cache + BrowserRequestContext(); + + // Use an on-disk cache at the specified location. Optionally, use the cache + // in playback or record mode. + BrowserRequestContext(const std::wstring& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy); + + ~BrowserRequestContext(); + + virtual const std::string& GetUserAgent(const GURL& url) const; + + private: + void Init(const std::wstring& cache_path, net::HttpCache::Mode cache_mode, + bool no_proxy); +}; + +#endif // _BROWSER_REQUEST_CONTEXT_H + diff --git a/libcef/browser_resource_loader_bridge.cc b/libcef/browser_resource_loader_bridge.cc index 9fd9d4443..dcac0b94a 100644 --- a/libcef/browser_resource_loader_bridge.cc +++ b/libcef/browser_resource_loader_bridge.cc @@ -1,780 +1,780 @@ -// 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. -// -// This file contains an implementation of the ResourceLoaderBridge class. -// The class is implemented using URLRequest, meaning it is a "simple" version -// that directly issues requests. The more complicated one used in the -// browser uses IPC. -// -// Because URLRequest only provides an asynchronous resource loading API, this -// file makes use of URLRequest from a background IO thread. Requests for -// cookies and synchronously loaded resources result in the main thread of the -// application blocking until the IO thread completes the operation. (See -// GetCookies and SyncLoad) -// -// Main thread IO thread -// ----------- --------- -// ResourceLoaderBridge <---o---------> RequestProxy (normal case) -// \ -> URLRequest -// o-------> SyncRequestProxy (synchronous case) -// -> URLRequest -// SetCookie <------------------------> CookieSetter -// -> net_util::SetCookie -// GetCookies <-----------------------> CookieGetter -// -> net_util::GetCookies -// -// NOTE: The implementation in this file may be used to have WebKit fetch -// resources in-process. For example, it is handy for building a single- -// process WebKit embedding (e.g., test_shell) that can use URLRequest to -// perform URL loads. See renderer/resource_dispatcher.h for details on an -// alternate implementation that defers fetching to another process. - -#include "precompiled_libcef.h" -#include "browser_resource_loader_bridge.h" -#include "browser_request_context.h" -#include "browser_impl.h" -#include "request_impl.h" - -#include "base/message_loop.h" -#include "base/ref_counted.h" -#include "base/string_util.h" -#include "base/time.h" -#include "base/timer.h" -#include "base/thread.h" -#include "base/waitable_event.h" -#include "net/base/cookie_monster.h" -#include "net/base/io_buffer.h" -#include "net/base/load_flags.h" -#include "net/base/net_errors.h" -#include "net/base/net_util.h" -#include "net/base/upload_data.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_util.h" -#include "net/proxy/proxy_service.h" -#include "net/url_request/url_request.h" -#include "webkit/glue/resource_loader_bridge.h" -#include "webkit/glue/webappcachecontext.h" -#include "webkit/glue/webframe.h" -#include "webkit/glue/webview.h" - -using webkit_glue::ResourceLoaderBridge; -using net::HttpResponseHeaders; - -namespace { - -//----------------------------------------------------------------------------- - -URLRequestContext* request_context = NULL; -base::Thread* io_thread = NULL; - -class IOThread : public base::Thread { - public: - IOThread() : base::Thread("IOThread") { - } - - ~IOThread() { - // We cannot rely on our base class to stop the thread since we want our - // CleanUp function to run. - Stop(); - } - - virtual void CleanUp() { - if (request_context) { - request_context->Release(); - request_context = NULL; - } - } -}; - -bool EnsureIOThread() { - if (io_thread) - return true; - - if (!request_context) - BrowserResourceLoaderBridge::Init(NULL); - - io_thread = new IOThread(); - base::Thread::Options options; - options.message_loop_type = MessageLoop::TYPE_IO; - return io_thread->StartWithOptions(options); -} - -//----------------------------------------------------------------------------- - -struct RequestParams { - std::string method; - GURL url; - GURL first_party_for_cookies; - GURL referrer; - std::string headers; - int load_flags; - int app_cache_context_id; - scoped_refptr upload; -}; - -// The interval for calls to RequestProxy::MaybeUpdateUploadProgress -static const int kUpdateUploadProgressIntervalMsec = 100; - -// The RequestProxy does most of its work on the IO thread. The Start and -// Cancel methods are proxied over to the IO thread, where an URLRequest object -// is instantiated. -class RequestProxy : public URLRequest::Delegate, - public base::RefCountedThreadSafe { - public: - // Takes ownership of the params. - RequestProxy(CefRefPtr browser) - : browser_(browser), - buf_(new net::IOBuffer(kDataSize)), - last_upload_position_(0) - { - } - - virtual ~RequestProxy() { - // If we have a request, then we'd better be on the io thread! - DCHECK(!request_.get() || - MessageLoop::current() == io_thread->message_loop()); - } - - void DropPeer() { - peer_ = NULL; - } - - void Start(ResourceLoaderBridge::Peer* peer, RequestParams* params) { - peer_ = peer; - owner_loop_ = MessageLoop::current(); - - // proxy over to the io thread - io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::AsyncStart, params)); - } - - void Cancel() { - // proxy over to the io thread - io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::AsyncCancel)); - } - - protected: - // -------------------------------------------------------------------------- - // The following methods are called on the owner's thread in response to - // various URLRequest callbacks. The event hooks, defined below, trigger - // these methods asynchronously. - - void NotifyUploadProgress(uint64 position, uint64 size) { - if (peer_) - peer_->OnUploadProgress(position, size); - } - - void NotifyReceivedRedirect(const GURL& new_url) { - if (peer_) - peer_->OnReceivedRedirect(new_url); - } - - void NotifyReceivedResponse(const ResourceLoaderBridge::ResponseInfo& info, - bool content_filtered) { - if (peer_) - peer_->OnReceivedResponse(info, content_filtered); - } - - void NotifyReceivedData(int bytes_read) { - if (!peer_) - return; - - // Make a local copy of buf_, since AsyncReadData reuses it. - scoped_array buf_copy(new char[bytes_read]); - memcpy(buf_copy.get(), buf_->data(), bytes_read); - - // Continue reading more data into buf_ - // Note: Doing this before notifying our peer ensures our load events get - // dispatched in a manner consistent with DumpRenderTree (and also avoids a - // race condition). If the order of the next 2 functions were reversed, the - // peer could generate new requests in reponse to the received data, which - // when run on the io thread, could race against this function in doing - // another InvokeLater. See bug 769249. - io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::AsyncReadData)); - - peer_->OnReceivedData(buf_copy.get(), bytes_read); - } - - void NotifyCompletedRequest(const URLRequestStatus& status, - const std::string& security_info) { - if (peer_) { - peer_->OnCompletedRequest(status, security_info); - DropPeer(); // ensure no further notifications - } - } - - // -------------------------------------------------------------------------- - // The following methods are called on the io thread. They correspond to - // actions performed on the owner's thread. - - void AsyncStart(RequestParams* params) { - bool handled = false; - - if (browser_.get()) { - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) - { - // Build the request object for passing to the handler - CefRefPtr request(new CefRequestImpl()); - CefRequestImpl* requestimpl = static_cast(request.get()); - - requestimpl->SetURL(UTF8ToWide(params->url.spec())); - requestimpl->SetMethod(UTF8ToWide(params->method)); - - CefRequest::HeaderMap headerMap; - - // Parse the request header values - std::string headerStr = "HTTP/1.1 200 OK\n"; - headerStr += params->headers; - scoped_refptr headers = - new HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders( - headerStr.c_str(), headerStr.length())); - void* iter = NULL; - std::string name, value; - while(headers->EnumerateHeaderLines(&iter, &name, &value)) - headerMap.insert(std::make_pair(UTF8ToWide(name), UTF8ToWide(value))); - - headerMap.insert( - std::make_pair(L"Referrer", UTF8ToWide(params->referrer.spec()))); - - requestimpl->SetHeaderMap(headerMap); - - scoped_refptr upload = params->upload; - CefRefPtr postdata; - if(upload.get()) { - postdata = new CefPostDataImpl(); - static_cast(postdata.get())->Set(*upload.get()); - requestimpl->SetPostData(postdata); - } - - int loadFlags = params->load_flags; +// 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. +// +// This file contains an implementation of the ResourceLoaderBridge class. +// The class is implemented using URLRequest, meaning it is a "simple" version +// that directly issues requests. The more complicated one used in the +// browser uses IPC. +// +// Because URLRequest only provides an asynchronous resource loading API, this +// file makes use of URLRequest from a background IO thread. Requests for +// cookies and synchronously loaded resources result in the main thread of the +// application blocking until the IO thread completes the operation. (See +// GetCookies and SyncLoad) +// +// Main thread IO thread +// ----------- --------- +// ResourceLoaderBridge <---o---------> RequestProxy (normal case) +// \ -> URLRequest +// o-------> SyncRequestProxy (synchronous case) +// -> URLRequest +// SetCookie <------------------------> CookieSetter +// -> net_util::SetCookie +// GetCookies <-----------------------> CookieGetter +// -> net_util::GetCookies +// +// NOTE: The implementation in this file may be used to have WebKit fetch +// resources in-process. For example, it is handy for building a single- +// process WebKit embedding (e.g., test_shell) that can use URLRequest to +// perform URL loads. See renderer/resource_dispatcher.h for details on an +// alternate implementation that defers fetching to another process. - // Handler output will be returned in these variables - std::wstring redirectUrl; - CefRefPtr resourceStream; - std::wstring mimeType; - - CefHandler::RetVal rv = handler->HandleBeforeResourceLoad( - browser_, request, redirectUrl, resourceStream, mimeType, loadFlags); - if(rv == RV_HANDLED) { - // cancel the resource load - handled = true; - OnCompletedRequest(URLRequestStatus(URLRequestStatus::CANCELED, 0), - std::string()); - } else if(!redirectUrl.empty()) { - // redirect to the specified URL - params->url = GURL(WideToUTF8(redirectUrl)); - OnReceivedRedirect(params->url); - } else if(resourceStream.get()) { - // load from the provided resource stream - handled = true; - - long offset = resourceStream->Seek(0, SEEK_END); - resourceStream->Seek(0, SEEK_SET); - - resource_stream_ = resourceStream; - - ResourceLoaderBridge::ResponseInfo info; - info.content_length = static_cast(offset); - if(!mimeType.empty()) - info.mime_type = WideToUTF8(mimeType); - OnReceivedResponse(info, false); - AsyncReadData(); - } - } - } - - if(!handled) - { - request_.reset(new URLRequest(params->url, this)); - request_->set_method(params->method); - request_->set_first_party_for_cookies(params->first_party_for_cookies); - request_->set_referrer(params->referrer.spec()); - request_->SetExtraRequestHeaders(params->headers); - request_->set_load_flags(params->load_flags); - request_->set_upload(params->upload.get()); - request_->set_context(request_context); - request_->Start(); - - if (request_->has_upload() && - params->load_flags & net::LOAD_ENABLE_UPLOAD_PROGRESS) { - upload_progress_timer_.Start( - base::TimeDelta::FromMilliseconds(kUpdateUploadProgressIntervalMsec), - this, &RequestProxy::MaybeUpdateUploadProgress); - } - } - - delete params; - } - - void AsyncCancel() { - // This can be null in cases where the request is already done. - if (!resource_stream_.get() && !request_.get()) - return; - - request_->Cancel(); - Done(); - } - - void AsyncReadData() { - if(resource_stream_.get()) { - // Read from the handler-provided resource stream - int bytes_read = resource_stream_->Read(buf_->data(), 1, kDataSize); - if(bytes_read > 0) { - OnReceivedData(bytes_read); - } else { - Done(); - } - return; - } - - // This can be null in cases where the request is already done. - if (!request_.get()) - return; - - if (request_->status().is_success()) { - int bytes_read; - if (request_->Read(buf_, kDataSize, &bytes_read) && bytes_read) { - OnReceivedData(bytes_read); - } else if (!request_->status().is_io_pending()) { - Done(); - } // else wait for OnReadCompleted - } else { - Done(); - } - } - - // -------------------------------------------------------------------------- - // The following methods are event hooks (corresponding to URLRequest - // callbacks) that run on the IO thread. They are designed to be overridden - // by the SyncRequestProxy subclass. - - virtual void OnReceivedRedirect(const GURL& new_url) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyReceivedRedirect, new_url)); - } - - virtual void OnReceivedResponse( - const ResourceLoaderBridge::ResponseInfo& info, - bool content_filtered) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyReceivedResponse, info, content_filtered)); - } - - virtual void OnReceivedData(int bytes_read) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyReceivedData, bytes_read)); - } - - virtual void OnCompletedRequest(const URLRequestStatus& status, - const std::string& security_info) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyCompletedRequest, status, security_info)); - } - - // -------------------------------------------------------------------------- - // URLRequest::Delegate implementation: - - virtual void OnReceivedRedirect(URLRequest* request, - const GURL& new_url, - bool* defer_redirect) { - DCHECK(request->status().is_success()); - OnReceivedRedirect(new_url); - } - - virtual void OnResponseStarted(URLRequest* request) { - if (request->status().is_success()) { - ResourceLoaderBridge::ResponseInfo info; - info.request_time = request->request_time(); - info.response_time = request->response_time(); - info.headers = request->response_headers(); - info.app_cache_id = WebAppCacheContext::kNoAppCacheId; - request->GetMimeType(&info.mime_type); - request->GetCharset(&info.charset); - OnReceivedResponse(info, false); - AsyncReadData(); // start reading - } else { - Done(); - } - } - - virtual void OnReadCompleted(URLRequest* request, int bytes_read) { - if (request->status().is_success() && bytes_read > 0) { - OnReceivedData(bytes_read); - } else { - Done(); - } - } - - // -------------------------------------------------------------------------- - // Helpers and data: - - void Done() { - if(resource_stream_.get()) { - // Resource stream reads always complete successfully - OnCompletedRequest(URLRequestStatus(URLRequestStatus::SUCCESS, 0), - std::string()); - resource_stream_ = NULL; - } else { - if (upload_progress_timer_.IsRunning()) { - MaybeUpdateUploadProgress(); - upload_progress_timer_.Stop(); - } - - DCHECK(request_.get()); - OnCompletedRequest(request_->status(), std::string()); - request_.reset(); // destroy on the io thread - } - } - - // Called on the IO thread. - void MaybeUpdateUploadProgress() { - // If a redirect is received upload is cancelled in URLRequest, we should - // try to stop the |upload_progress_timer_| timer and return. - if (!request_->has_upload()) { - if (upload_progress_timer_.IsRunning()) - upload_progress_timer_.Stop(); - return; - } - - uint64 size = request_->get_upload()->GetContentLength(); - uint64 position = request_->GetUploadProgress(); - if (position == last_upload_position_) - return; // no progress made since last time - - const uint64 kHalfPercentIncrements = 200; - const base::TimeDelta kOneSecond = base::TimeDelta::FromMilliseconds(1000); - - uint64 amt_since_last = position - last_upload_position_; - base::TimeDelta time_since_last = base::TimeTicks::Now() - - last_upload_ticks_; - - bool is_finished = (size == position); - bool enough_new_progress = (amt_since_last > (size / - kHalfPercentIncrements)); - bool too_much_time_passed = time_since_last > kOneSecond; - - if (is_finished || enough_new_progress || too_much_time_passed) { - owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( - this, &RequestProxy::NotifyUploadProgress, position, size)); - last_upload_ticks_ = base::TimeTicks::Now(); - last_upload_position_ = position; - } - } - - scoped_ptr request_; - CefRefPtr resource_stream_; - - // Size of our async IO data buffers - static const int kDataSize = 16*1024; - - // read buffer for async IO - scoped_refptr buf_; - - CefRefPtr browser_; - - MessageLoop* owner_loop_; - - // This is our peer in WebKit (implemented as ResourceHandleInternal). We do - // not manage its lifetime, and we may only access it from the owner's - // message loop (owner_loop_). - ResourceLoaderBridge::Peer* peer_; - - // Timer used to pull upload progress info. - base::RepeatingTimer upload_progress_timer_; - - // Info used to determine whether or not to send an upload progress update. - uint64 last_upload_position_; - base::TimeTicks last_upload_ticks_; -}; - -//----------------------------------------------------------------------------- - -class SyncRequestProxy : public RequestProxy { - public: - explicit SyncRequestProxy(CefRefPtr browser, - ResourceLoaderBridge::SyncLoadResponse* result) - : RequestProxy(browser), result_(result), event_(true, false) { - } - - void WaitForCompletion() { - if (!event_.Wait()) - NOTREACHED(); - } - - // -------------------------------------------------------------------------- - // Event hooks that run on the IO thread: - - virtual void OnReceivedRedirect(const GURL& new_url) { - result_->url = new_url; - } - - virtual void OnReceivedResponse( - const ResourceLoaderBridge::ResponseInfo& info, - bool content_filtered) { - *static_cast(result_) = info; - } - - virtual void OnReceivedData(int bytes_read) { - result_->data.append(buf_->data(), bytes_read); - AsyncReadData(); // read more (may recurse) - } - - virtual void OnCompletedRequest(const URLRequestStatus& status, - const std::string& security_info) { - result_->status = status; - event_.Signal(); - } - - private: - ResourceLoaderBridge::SyncLoadResponse* result_; - base::WaitableEvent event_; -}; - -//----------------------------------------------------------------------------- - -class ResourceLoaderBridgeImpl : public ResourceLoaderBridge { - public: - ResourceLoaderBridgeImpl(CefRefPtr browser, - const std::string& method, - const GURL& url, - const GURL& first_party_for_cookies, - const GURL& referrer, - const std::string& headers, - int load_flags, - int app_cache_context_id) - : browser_(browser), - params_(new RequestParams), - proxy_(NULL) { - params_->method = method; - params_->url = url; - params_->first_party_for_cookies = first_party_for_cookies; - params_->referrer = referrer; - params_->headers = headers; - params_->load_flags = load_flags; - params_->app_cache_context_id = app_cache_context_id; - } - - virtual ~ResourceLoaderBridgeImpl() { - if (proxy_) { - proxy_->DropPeer(); - // Let the proxy die on the IO thread - io_thread->message_loop()->ReleaseSoon(FROM_HERE, proxy_); - } - } - - // -------------------------------------------------------------------------- - // ResourceLoaderBridge implementation: - - virtual void AppendDataToUpload(const char* data, int data_len) { - DCHECK(params_.get()); - if (!params_->upload) - params_->upload = new net::UploadData(); - params_->upload->AppendBytes(data, data_len); - } - - virtual void AppendFileRangeToUpload(const FilePath& file_path, - uint64 offset, uint64 length) { - DCHECK(params_.get()); - if (!params_->upload) - params_->upload = new net::UploadData(); - params_->upload->AppendFileRange(file_path, offset, length); - } - - virtual void SetUploadIdentifier(int64 identifier) { - DCHECK(params_.get()); - if (!params_->upload) - params_->upload = new net::UploadData(); - params_->upload->set_identifier(identifier); - } - - virtual bool Start(Peer* peer) { - DCHECK(!proxy_); - - if (!EnsureIOThread()) - return false; - - proxy_ = new RequestProxy(browser_); - proxy_->AddRef(); - - proxy_->Start(peer, params_.release()); - - return true; // Any errors will be reported asynchronously. - } - - virtual void Cancel() { - DCHECK(proxy_); - proxy_->Cancel(); - } - - virtual void SetDefersLoading(bool value) { - // TODO(darin): implement me - } - - virtual void SyncLoad(SyncLoadResponse* response) { - DCHECK(!proxy_); - - if (!EnsureIOThread()) - return; - - // this may change as the result of a redirect - response->url = params_->url; - - proxy_ = new SyncRequestProxy(browser_, response); - proxy_->AddRef(); - - proxy_->Start(NULL, params_.release()); - - static_cast(proxy_)->WaitForCompletion(); - } - - private: - CefRefPtr browser_; - - // Ownership of params_ is transfered to the proxy when the proxy is created. - scoped_ptr params_; - - // The request proxy is allocated when we start the request, and then it - // sticks around until this ResourceLoaderBridge is destroyed. - RequestProxy* proxy_; -}; - -//----------------------------------------------------------------------------- - -class CookieSetter : public base::RefCountedThreadSafe { - public: - void Set(const GURL& url, const std::string& cookie) { - DCHECK(MessageLoop::current() == io_thread->message_loop()); - request_context->cookie_store()->SetCookie(url, cookie); - } -}; - -class CookieGetter : public base::RefCountedThreadSafe { - public: - CookieGetter() : event_(false, false) { - } - - void Get(const GURL& url) { - result_ = request_context->cookie_store()->GetCookies(url); - event_.Signal(); - } - - std::string GetResult() { - if (!event_.Wait()) - NOTREACHED(); - return result_; - } - - private: - base::WaitableEvent event_; - std::string result_; -}; - -} // anonymous namespace - -//----------------------------------------------------------------------------- - -namespace webkit_glue { - -// factory function -ResourceLoaderBridge* ResourceLoaderBridge::Create( - const std::string& method, - const GURL& url, - const GURL& first_party_for_cookies, - const GURL& referrer, - const std::string& frame_origin, - const std::string& main_frame_origin, - const std::string& headers, - int load_flags, - int requestor_pid, - ResourceType::Type request_type, - int app_cache_context_id, - int routing_id) { - CefRefPtr browser = _Context->GetBrowserByID(routing_id); - return new ResourceLoaderBridgeImpl(browser, method, url, - first_party_for_cookies, - referrer, headers, load_flags, - app_cache_context_id); -} - -// Issue the proxy resolve request on the io thread, and wait -// for the result. -bool FindProxyForUrl(const GURL& url, std::string* proxy_list) { - DCHECK(request_context); - - scoped_refptr sync_proxy_service( - new net::SyncProxyServiceHelper(io_thread->message_loop(), - request_context->proxy_service())); - - net::ProxyInfo proxy_info; - int rv = sync_proxy_service->ResolveProxy(url, &proxy_info); - if (rv == net::OK) { - *proxy_list = proxy_info.ToPacString(); - } - - return rv == net::OK; -} - -} // namespace webkit_glue - -//----------------------------------------------------------------------------- - -// static -void BrowserResourceLoaderBridge::Init(URLRequestContext* context) { - // Make sure to stop any existing IO thread since it may be using the - // current request context. - Shutdown(); - - if (context) { - request_context = context; - } else { - request_context = new BrowserRequestContext(); - } - request_context->AddRef(); -} - -// static -void BrowserResourceLoaderBridge::Shutdown() { - if (io_thread) { - delete io_thread; - io_thread = NULL; - - DCHECK(!request_context) << "should have been nulled by thread dtor"; - } -} - -void BrowserResourceLoaderBridge::SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie) { - // Proxy to IO thread to synchronize w/ network loading. - - if (!EnsureIOThread()) { - NOTREACHED(); - return; - } - - scoped_refptr cookie_setter = new CookieSetter(); - io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( - cookie_setter.get(), &CookieSetter::Set, url, cookie)); -} - -std::string BrowserResourceLoaderBridge::GetCookies( - const GURL& url, const GURL& first_party_for_cookies) { - // Proxy to IO thread to synchronize w/ network loading - - if (!EnsureIOThread()) { - NOTREACHED(); - return std::string(); - } - - scoped_refptr getter = new CookieGetter(); - - io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( - getter.get(), &CookieGetter::Get, url)); - - return getter->GetResult(); -} +#include "precompiled_libcef.h" +#include "browser_resource_loader_bridge.h" +#include "browser_request_context.h" +#include "browser_impl.h" +#include "request_impl.h" + +#include "base/message_loop.h" +#include "base/ref_counted.h" +#include "base/string_util.h" +#include "base/time.h" +#include "base/timer.h" +#include "base/thread.h" +#include "base/waitable_event.h" +#include "net/base/cookie_monster.h" +#include "net/base/io_buffer.h" +#include "net/base/load_flags.h" +#include "net/base/net_errors.h" +#include "net/base/net_util.h" +#include "net/base/upload_data.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_util.h" +#include "net/proxy/proxy_service.h" +#include "net/url_request/url_request.h" +#include "webkit/glue/resource_loader_bridge.h" +#include "webkit/glue/webappcachecontext.h" +#include "webkit/glue/webframe.h" +#include "webkit/glue/webview.h" + +using webkit_glue::ResourceLoaderBridge; +using net::HttpResponseHeaders; + +namespace { + +//----------------------------------------------------------------------------- + +URLRequestContext* request_context = NULL; +base::Thread* io_thread = NULL; + +class IOThread : public base::Thread { + public: + IOThread() : base::Thread("IOThread") { + } + + ~IOThread() { + // We cannot rely on our base class to stop the thread since we want our + // CleanUp function to run. + Stop(); + } + + virtual void CleanUp() { + if (request_context) { + request_context->Release(); + request_context = NULL; + } + } +}; + +bool EnsureIOThread() { + if (io_thread) + return true; + + if (!request_context) + BrowserResourceLoaderBridge::Init(NULL); + + io_thread = new IOThread(); + base::Thread::Options options; + options.message_loop_type = MessageLoop::TYPE_IO; + return io_thread->StartWithOptions(options); +} + +//----------------------------------------------------------------------------- + +struct RequestParams { + std::string method; + GURL url; + GURL first_party_for_cookies; + GURL referrer; + std::string headers; + int load_flags; + int app_cache_context_id; + scoped_refptr upload; +}; + +// The interval for calls to RequestProxy::MaybeUpdateUploadProgress +static const int kUpdateUploadProgressIntervalMsec = 100; + +// The RequestProxy does most of its work on the IO thread. The Start and +// Cancel methods are proxied over to the IO thread, where an URLRequest object +// is instantiated. +class RequestProxy : public URLRequest::Delegate, + public base::RefCountedThreadSafe { + public: + // Takes ownership of the params. + RequestProxy(CefRefPtr browser) + : browser_(browser), + buf_(new net::IOBuffer(kDataSize)), + last_upload_position_(0) + { + } + + virtual ~RequestProxy() { + // If we have a request, then we'd better be on the io thread! + DCHECK(!request_.get() || + MessageLoop::current() == io_thread->message_loop()); + } + + void DropPeer() { + peer_ = NULL; + } + + void Start(ResourceLoaderBridge::Peer* peer, RequestParams* params) { + peer_ = peer; + owner_loop_ = MessageLoop::current(); + + // proxy over to the io thread + io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::AsyncStart, params)); + } + + void Cancel() { + // proxy over to the io thread + io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::AsyncCancel)); + } + + protected: + // -------------------------------------------------------------------------- + // The following methods are called on the owner's thread in response to + // various URLRequest callbacks. The event hooks, defined below, trigger + // these methods asynchronously. + + void NotifyUploadProgress(uint64 position, uint64 size) { + if (peer_) + peer_->OnUploadProgress(position, size); + } + + void NotifyReceivedRedirect(const GURL& new_url) { + if (peer_) + peer_->OnReceivedRedirect(new_url); + } + + void NotifyReceivedResponse(const ResourceLoaderBridge::ResponseInfo& info, + bool content_filtered) { + if (peer_) + peer_->OnReceivedResponse(info, content_filtered); + } + + void NotifyReceivedData(int bytes_read) { + if (!peer_) + return; + + // Make a local copy of buf_, since AsyncReadData reuses it. + scoped_array buf_copy(new char[bytes_read]); + memcpy(buf_copy.get(), buf_->data(), bytes_read); + + // Continue reading more data into buf_ + // Note: Doing this before notifying our peer ensures our load events get + // dispatched in a manner consistent with DumpRenderTree (and also avoids a + // race condition). If the order of the next 2 functions were reversed, the + // peer could generate new requests in reponse to the received data, which + // when run on the io thread, could race against this function in doing + // another InvokeLater. See bug 769249. + io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::AsyncReadData)); + + peer_->OnReceivedData(buf_copy.get(), bytes_read); + } + + void NotifyCompletedRequest(const URLRequestStatus& status, + const std::string& security_info) { + if (peer_) { + peer_->OnCompletedRequest(status, security_info); + DropPeer(); // ensure no further notifications + } + } + + // -------------------------------------------------------------------------- + // The following methods are called on the io thread. They correspond to + // actions performed on the owner's thread. + + void AsyncStart(RequestParams* params) { + bool handled = false; + + if (browser_.get()) { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) + { + // Build the request object for passing to the handler + CefRefPtr request(new CefRequestImpl()); + CefRequestImpl* requestimpl = static_cast(request.get()); + + requestimpl->SetURL(UTF8ToWide(params->url.spec())); + requestimpl->SetMethod(UTF8ToWide(params->method)); + + CefRequest::HeaderMap headerMap; + + // Parse the request header values + std::string headerStr = "HTTP/1.1 200 OK\n"; + headerStr += params->headers; + scoped_refptr headers = + new HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders( + headerStr.c_str(), headerStr.length())); + void* iter = NULL; + std::string name, value; + while(headers->EnumerateHeaderLines(&iter, &name, &value)) + headerMap.insert(std::make_pair(UTF8ToWide(name), UTF8ToWide(value))); + + headerMap.insert( + std::make_pair(L"Referrer", UTF8ToWide(params->referrer.spec()))); + + requestimpl->SetHeaderMap(headerMap); + + scoped_refptr upload = params->upload; + CefRefPtr postdata; + if(upload.get()) { + postdata = new CefPostDataImpl(); + static_cast(postdata.get())->Set(*upload.get()); + requestimpl->SetPostData(postdata); + } + + int loadFlags = params->load_flags; + + // Handler output will be returned in these variables + std::wstring redirectUrl; + CefRefPtr resourceStream; + std::wstring mimeType; + + CefHandler::RetVal rv = handler->HandleBeforeResourceLoad( + browser_, request, redirectUrl, resourceStream, mimeType, loadFlags); + if(rv == RV_HANDLED) { + // cancel the resource load + handled = true; + OnCompletedRequest(URLRequestStatus(URLRequestStatus::CANCELED, 0), + std::string()); + } else if(!redirectUrl.empty()) { + // redirect to the specified URL + params->url = GURL(WideToUTF8(redirectUrl)); + OnReceivedRedirect(params->url); + } else if(resourceStream.get()) { + // load from the provided resource stream + handled = true; + + long offset = resourceStream->Seek(0, SEEK_END); + resourceStream->Seek(0, SEEK_SET); + + resource_stream_ = resourceStream; + + ResourceLoaderBridge::ResponseInfo info; + info.content_length = static_cast(offset); + if(!mimeType.empty()) + info.mime_type = WideToUTF8(mimeType); + OnReceivedResponse(info, false); + AsyncReadData(); + } + } + } + + if(!handled) + { + request_.reset(new URLRequest(params->url, this)); + request_->set_method(params->method); + request_->set_first_party_for_cookies(params->first_party_for_cookies); + request_->set_referrer(params->referrer.spec()); + request_->SetExtraRequestHeaders(params->headers); + request_->set_load_flags(params->load_flags); + request_->set_upload(params->upload.get()); + request_->set_context(request_context); + request_->Start(); + + if (request_->has_upload() && + params->load_flags & net::LOAD_ENABLE_UPLOAD_PROGRESS) { + upload_progress_timer_.Start( + base::TimeDelta::FromMilliseconds(kUpdateUploadProgressIntervalMsec), + this, &RequestProxy::MaybeUpdateUploadProgress); + } + } + + delete params; + } + + void AsyncCancel() { + // This can be null in cases where the request is already done. + if (!resource_stream_.get() && !request_.get()) + return; + + request_->Cancel(); + Done(); + } + + void AsyncReadData() { + if(resource_stream_.get()) { + // Read from the handler-provided resource stream + int bytes_read = resource_stream_->Read(buf_->data(), 1, kDataSize); + if(bytes_read > 0) { + OnReceivedData(bytes_read); + } else { + Done(); + } + return; + } + + // This can be null in cases where the request is already done. + if (!request_.get()) + return; + + if (request_->status().is_success()) { + int bytes_read; + if (request_->Read(buf_, kDataSize, &bytes_read) && bytes_read) { + OnReceivedData(bytes_read); + } else if (!request_->status().is_io_pending()) { + Done(); + } // else wait for OnReadCompleted + } else { + Done(); + } + } + + // -------------------------------------------------------------------------- + // The following methods are event hooks (corresponding to URLRequest + // callbacks) that run on the IO thread. They are designed to be overridden + // by the SyncRequestProxy subclass. + + virtual void OnReceivedRedirect(const GURL& new_url) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyReceivedRedirect, new_url)); + } + + virtual void OnReceivedResponse( + const ResourceLoaderBridge::ResponseInfo& info, + bool content_filtered) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyReceivedResponse, info, content_filtered)); + } + + virtual void OnReceivedData(int bytes_read) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyReceivedData, bytes_read)); + } + + virtual void OnCompletedRequest(const URLRequestStatus& status, + const std::string& security_info) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyCompletedRequest, status, security_info)); + } + + // -------------------------------------------------------------------------- + // URLRequest::Delegate implementation: + + virtual void OnReceivedRedirect(URLRequest* request, + const GURL& new_url, + bool* defer_redirect) { + DCHECK(request->status().is_success()); + OnReceivedRedirect(new_url); + } + + virtual void OnResponseStarted(URLRequest* request) { + if (request->status().is_success()) { + ResourceLoaderBridge::ResponseInfo info; + info.request_time = request->request_time(); + info.response_time = request->response_time(); + info.headers = request->response_headers(); + info.app_cache_id = WebAppCacheContext::kNoAppCacheId; + request->GetMimeType(&info.mime_type); + request->GetCharset(&info.charset); + OnReceivedResponse(info, false); + AsyncReadData(); // start reading + } else { + Done(); + } + } + + virtual void OnReadCompleted(URLRequest* request, int bytes_read) { + if (request->status().is_success() && bytes_read > 0) { + OnReceivedData(bytes_read); + } else { + Done(); + } + } + + // -------------------------------------------------------------------------- + // Helpers and data: + + void Done() { + if(resource_stream_.get()) { + // Resource stream reads always complete successfully + OnCompletedRequest(URLRequestStatus(URLRequestStatus::SUCCESS, 0), + std::string()); + resource_stream_ = NULL; + } else { + if (upload_progress_timer_.IsRunning()) { + MaybeUpdateUploadProgress(); + upload_progress_timer_.Stop(); + } + + DCHECK(request_.get()); + OnCompletedRequest(request_->status(), std::string()); + request_.reset(); // destroy on the io thread + } + } + + // Called on the IO thread. + void MaybeUpdateUploadProgress() { + // If a redirect is received upload is cancelled in URLRequest, we should + // try to stop the |upload_progress_timer_| timer and return. + if (!request_->has_upload()) { + if (upload_progress_timer_.IsRunning()) + upload_progress_timer_.Stop(); + return; + } + + uint64 size = request_->get_upload()->GetContentLength(); + uint64 position = request_->GetUploadProgress(); + if (position == last_upload_position_) + return; // no progress made since last time + + const uint64 kHalfPercentIncrements = 200; + const base::TimeDelta kOneSecond = base::TimeDelta::FromMilliseconds(1000); + + uint64 amt_since_last = position - last_upload_position_; + base::TimeDelta time_since_last = base::TimeTicks::Now() - + last_upload_ticks_; + + bool is_finished = (size == position); + bool enough_new_progress = (amt_since_last > (size / + kHalfPercentIncrements)); + bool too_much_time_passed = time_since_last > kOneSecond; + + if (is_finished || enough_new_progress || too_much_time_passed) { + owner_loop_->PostTask(FROM_HERE, NewRunnableMethod( + this, &RequestProxy::NotifyUploadProgress, position, size)); + last_upload_ticks_ = base::TimeTicks::Now(); + last_upload_position_ = position; + } + } + + scoped_ptr request_; + CefRefPtr resource_stream_; + + // Size of our async IO data buffers + static const int kDataSize = 16*1024; + + // read buffer for async IO + scoped_refptr buf_; + + CefRefPtr browser_; + + MessageLoop* owner_loop_; + + // This is our peer in WebKit (implemented as ResourceHandleInternal). We do + // not manage its lifetime, and we may only access it from the owner's + // message loop (owner_loop_). + ResourceLoaderBridge::Peer* peer_; + + // Timer used to pull upload progress info. + base::RepeatingTimer upload_progress_timer_; + + // Info used to determine whether or not to send an upload progress update. + uint64 last_upload_position_; + base::TimeTicks last_upload_ticks_; +}; + +//----------------------------------------------------------------------------- + +class SyncRequestProxy : public RequestProxy { + public: + explicit SyncRequestProxy(CefRefPtr browser, + ResourceLoaderBridge::SyncLoadResponse* result) + : RequestProxy(browser), result_(result), event_(true, false) { + } + + void WaitForCompletion() { + if (!event_.Wait()) + NOTREACHED(); + } + + // -------------------------------------------------------------------------- + // Event hooks that run on the IO thread: + + virtual void OnReceivedRedirect(const GURL& new_url) { + result_->url = new_url; + } + + virtual void OnReceivedResponse( + const ResourceLoaderBridge::ResponseInfo& info, + bool content_filtered) { + *static_cast(result_) = info; + } + + virtual void OnReceivedData(int bytes_read) { + result_->data.append(buf_->data(), bytes_read); + AsyncReadData(); // read more (may recurse) + } + + virtual void OnCompletedRequest(const URLRequestStatus& status, + const std::string& security_info) { + result_->status = status; + event_.Signal(); + } + + private: + ResourceLoaderBridge::SyncLoadResponse* result_; + base::WaitableEvent event_; +}; + +//----------------------------------------------------------------------------- + +class ResourceLoaderBridgeImpl : public ResourceLoaderBridge { + public: + ResourceLoaderBridgeImpl(CefRefPtr browser, + const std::string& method, + const GURL& url, + const GURL& first_party_for_cookies, + const GURL& referrer, + const std::string& headers, + int load_flags, + int app_cache_context_id) + : browser_(browser), + params_(new RequestParams), + proxy_(NULL) { + params_->method = method; + params_->url = url; + params_->first_party_for_cookies = first_party_for_cookies; + params_->referrer = referrer; + params_->headers = headers; + params_->load_flags = load_flags; + params_->app_cache_context_id = app_cache_context_id; + } + + virtual ~ResourceLoaderBridgeImpl() { + if (proxy_) { + proxy_->DropPeer(); + // Let the proxy die on the IO thread + io_thread->message_loop()->ReleaseSoon(FROM_HERE, proxy_); + } + } + + // -------------------------------------------------------------------------- + // ResourceLoaderBridge implementation: + + virtual void AppendDataToUpload(const char* data, int data_len) { + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->AppendBytes(data, data_len); + } + + virtual void AppendFileRangeToUpload(const FilePath& file_path, + uint64 offset, uint64 length) { + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->AppendFileRange(file_path, offset, length); + } + + virtual void SetUploadIdentifier(int64 identifier) { + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->set_identifier(identifier); + } + + virtual bool Start(Peer* peer) { + DCHECK(!proxy_); + + if (!EnsureIOThread()) + return false; + + proxy_ = new RequestProxy(browser_); + proxy_->AddRef(); + + proxy_->Start(peer, params_.release()); + + return true; // Any errors will be reported asynchronously. + } + + virtual void Cancel() { + DCHECK(proxy_); + proxy_->Cancel(); + } + + virtual void SetDefersLoading(bool value) { + // TODO(darin): implement me + } + + virtual void SyncLoad(SyncLoadResponse* response) { + DCHECK(!proxy_); + + if (!EnsureIOThread()) + return; + + // this may change as the result of a redirect + response->url = params_->url; + + proxy_ = new SyncRequestProxy(browser_, response); + proxy_->AddRef(); + + proxy_->Start(NULL, params_.release()); + + static_cast(proxy_)->WaitForCompletion(); + } + + private: + CefRefPtr browser_; + + // Ownership of params_ is transfered to the proxy when the proxy is created. + scoped_ptr params_; + + // The request proxy is allocated when we start the request, and then it + // sticks around until this ResourceLoaderBridge is destroyed. + RequestProxy* proxy_; +}; + +//----------------------------------------------------------------------------- + +class CookieSetter : public base::RefCountedThreadSafe { + public: + void Set(const GURL& url, const std::string& cookie) { + DCHECK(MessageLoop::current() == io_thread->message_loop()); + request_context->cookie_store()->SetCookie(url, cookie); + } +}; + +class CookieGetter : public base::RefCountedThreadSafe { + public: + CookieGetter() : event_(false, false) { + } + + void Get(const GURL& url) { + result_ = request_context->cookie_store()->GetCookies(url); + event_.Signal(); + } + + std::string GetResult() { + if (!event_.Wait()) + NOTREACHED(); + return result_; + } + + private: + base::WaitableEvent event_; + std::string result_; +}; + +} // anonymous namespace + +//----------------------------------------------------------------------------- + +namespace webkit_glue { + +// factory function +ResourceLoaderBridge* ResourceLoaderBridge::Create( + const std::string& method, + const GURL& url, + const GURL& first_party_for_cookies, + const GURL& referrer, + const std::string& frame_origin, + const std::string& main_frame_origin, + const std::string& headers, + int load_flags, + int requestor_pid, + ResourceType::Type request_type, + int app_cache_context_id, + int routing_id) { + CefRefPtr browser = _Context->GetBrowserByID(routing_id); + return new ResourceLoaderBridgeImpl(browser, method, url, + first_party_for_cookies, + referrer, headers, load_flags, + app_cache_context_id); +} + +// Issue the proxy resolve request on the io thread, and wait +// for the result. +bool FindProxyForUrl(const GURL& url, std::string* proxy_list) { + DCHECK(request_context); + + scoped_refptr sync_proxy_service( + new net::SyncProxyServiceHelper(io_thread->message_loop(), + request_context->proxy_service())); + + net::ProxyInfo proxy_info; + int rv = sync_proxy_service->ResolveProxy(url, &proxy_info); + if (rv == net::OK) { + *proxy_list = proxy_info.ToPacString(); + } + + return rv == net::OK; +} + +} // namespace webkit_glue + +//----------------------------------------------------------------------------- + +// static +void BrowserResourceLoaderBridge::Init(URLRequestContext* context) { + // Make sure to stop any existing IO thread since it may be using the + // current request context. + Shutdown(); + + if (context) { + request_context = context; + } else { + request_context = new BrowserRequestContext(); + } + request_context->AddRef(); +} + +// static +void BrowserResourceLoaderBridge::Shutdown() { + if (io_thread) { + delete io_thread; + io_thread = NULL; + + DCHECK(!request_context) << "should have been nulled by thread dtor"; + } +} + +void BrowserResourceLoaderBridge::SetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie) { + // Proxy to IO thread to synchronize w/ network loading. + + if (!EnsureIOThread()) { + NOTREACHED(); + return; + } + + scoped_refptr cookie_setter = new CookieSetter(); + io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( + cookie_setter.get(), &CookieSetter::Set, url, cookie)); +} + +std::string BrowserResourceLoaderBridge::GetCookies( + const GURL& url, const GURL& first_party_for_cookies) { + // Proxy to IO thread to synchronize w/ network loading + + if (!EnsureIOThread()) { + NOTREACHED(); + return std::string(); + } + + scoped_refptr getter = new CookieGetter(); + + io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( + getter.get(), &CookieGetter::Get, url)); + + return getter->GetResult(); +} diff --git a/libcef/browser_resource_loader_bridge.h b/libcef/browser_resource_loader_bridge.h index 7231010d3..e035edf2b 100644 --- a/libcef/browser_resource_loader_bridge.h +++ b/libcef/browser_resource_loader_bridge.h @@ -1,40 +1,40 @@ -// 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. - -#ifndef _BROWSER_RESOURCE_LOADER_BRIDGE_H -#define _BROWSER_RESOURCE_LOADER_BRIDGE_H - -#include - -class GURL; -class URLRequestContext; - -class BrowserResourceLoaderBridge { - public: - // Call this function to initialize the simple resource loader bridge. If - // the given context is null, then a default BrowserRequestContext will be - // instantiated. Otherwise, a reference is taken to the given request - // context, which will be released when Shutdown is called. The caller - // should not hold another reference to the request context! It is safe to - // call this function multiple times. - // - // NOTE: If this function is not called, then a default request context will - // be initialized lazily. - // - static void Init(URLRequestContext* context); - - // Call this function to shutdown the simple resource loader bridge. - static void Shutdown(); - - // May only be called after Init. - static void SetCookie(const GURL& url, - const GURL& first_party_for_cookies, - const std::string& cookie); - static std::string GetCookies(const GURL& url, - const GURL& first_party_for_cookies); -}; - -#endif // _BROWSER_RESOURCE_LOADER_BRIDGE_H - +// 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. + +#ifndef _BROWSER_RESOURCE_LOADER_BRIDGE_H +#define _BROWSER_RESOURCE_LOADER_BRIDGE_H + +#include + +class GURL; +class URLRequestContext; + +class BrowserResourceLoaderBridge { + public: + // Call this function to initialize the simple resource loader bridge. If + // the given context is null, then a default BrowserRequestContext will be + // instantiated. Otherwise, a reference is taken to the given request + // context, which will be released when Shutdown is called. The caller + // should not hold another reference to the request context! It is safe to + // call this function multiple times. + // + // NOTE: If this function is not called, then a default request context will + // be initialized lazily. + // + static void Init(URLRequestContext* context); + + // Call this function to shutdown the simple resource loader bridge. + static void Shutdown(); + + // May only be called after Init. + static void SetCookie(const GURL& url, + const GURL& first_party_for_cookies, + const std::string& cookie); + static std::string GetCookies(const GURL& url, + const GURL& first_party_for_cookies); +}; + +#endif // _BROWSER_RESOURCE_LOADER_BRIDGE_H + diff --git a/libcef/browser_webkit_glue.cc b/libcef/browser_webkit_glue.cc index 1d374b63c..9ef3a9c7f 100644 --- a/libcef/browser_webkit_glue.cc +++ b/libcef/browser_webkit_glue.cc @@ -1,64 +1,64 @@ -// Copyright (c) 2008-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. - +// Copyright (c) 2008-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 "precompiled_libcef.h" #include "base/compiler_specific.h" #include "base/logging.h" -#include "config.h" -MSVC_PUSH_WARNING_LEVEL(0); -#include "TextEncoding.h" +#include "config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "TextEncoding.h" #include "webkit/glue/webframe_impl.h" MSVC_POP_WARNING(); - + #include "browser_webkit_glue.h" #undef LOG #include "base/path_service.h" #include "base/resource_util.h" -#include "base/scoped_ptr.h" +#include "base/scoped_ptr.h" #include "base/string16.h" #include "base/win_util.h" #include "net/base/mime_util.h" #include "webkit/glue/glue_util.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webkit_glue.h" - -// Generated by GRIT -#include "grit/webkit_resources.h" - -namespace webkit_glue { - -bool IsMediaPlayerAvailable() { - return true; -} - -void PrecacheUrl(const char16* url, int url_length) {} - -void AppendToLog(const char* file, int line, const char* msg) { - logging::LogMessage(file, line).stream() << msg; -} - -StringPiece GetRawDataResource(HMODULE module, int resource_id) { - void* data_ptr; - size_t data_size; - return base::GetDataResourceFromModule(module, resource_id, &data_ptr, - &data_size) ? - StringPiece(static_cast(data_ptr), data_size) : StringPiece(); -} - -StringPiece NetResourceProvider(int key) { - return GetRawDataResource(::GetModuleHandle(NULL), key); -} - -StringPiece GetDataResource(int resource_id) { - switch (resource_id) { - case IDR_BROKENIMAGE: { - // Use webkit's broken image icon (16x16) - static unsigned char broken_image_data[] = { + +// Generated by GRIT +#include "grit/webkit_resources.h" + +namespace webkit_glue { + +bool IsMediaPlayerAvailable() { + return true; +} + +void PrecacheUrl(const char16* url, int url_length) {} + +void AppendToLog(const char* file, int line, const char* msg) { + logging::LogMessage(file, line).stream() << msg; +} + +StringPiece GetRawDataResource(HMODULE module, int resource_id) { + void* data_ptr; + size_t data_size; + return base::GetDataResourceFromModule(module, resource_id, &data_ptr, + &data_size) ? + StringPiece(static_cast(data_ptr), data_size) : StringPiece(); +} + +StringPiece NetResourceProvider(int key) { + return GetRawDataResource(::GetModuleHandle(NULL), key); +} + +StringPiece GetDataResource(int resource_id) { + switch (resource_id) { + case IDR_BROKENIMAGE: { + // Use webkit's broken image icon (16x16) + static unsigned char broken_image_data[] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xD5, 0x00, 0x00, 0x20, 0x68, 0xB0, 0x70, 0x98, 0xC0, 0x28, 0x78, 0xB8, 0x20, 0x70, 0xB8, 0x88, 0xB8, 0xD8, 0x78, 0x98, 0xC8, 0x28, 0x80, 0xC0, 0xF8, 0xF8, @@ -88,22 +88,22 @@ StringPiece GetDataResource(int resource_id) { 0x03, 0xA8, 0x03, 0x15, 0x0A, 0x0A, 0x15, 0xA9, 0x03, 0x07, 0x18, 0x01, 0xA7, 0xA9, 0xAB, 0xAD, 0xAF, 0x07, 0x01, 0x0F, 0x07, 0x15, 0xBD, 0x15, 0x00, 0xC0, 0x00, 0xBE, 0x15, 0x07, 0x0F, 0x0E, 0xBC, 0xC3, 0xC9, 0xBD, - 0x07, 0x0E, 0xC7, 0x4C, 0xCF, 0x49, 0xCD, 0xD2, 0xD3, 0xD4, 0xD2, 0x41, - 0x00, 0x3B - }; - return StringPiece(reinterpret_cast(broken_image_data), - static_cast( - sizeof(broken_image_data) / sizeof(unsigned char))); - } - case IDR_FEED_PREVIEW: - // It is necessary to return a feed preview template that contains - // a {{URL}} substring where the feed URL should go; see the code - // that computes feed previews in feed_preview.cc:MakeFeedPreview. - // This fixes issue #932714. - return "Feed preview for {{URL}}"; - case IDR_TEXTAREA_RESIZER: { - // Use webkit's text area resizer image. - static unsigned char area_resizer_data[] = { + 0x07, 0x0E, 0xC7, 0x4C, 0xCF, 0x49, 0xCD, 0xD2, 0xD3, 0xD4, 0xD2, 0x41, + 0x00, 0x3B + }; + return StringPiece(reinterpret_cast(broken_image_data), + static_cast( + sizeof(broken_image_data) / sizeof(unsigned char))); + } + case IDR_FEED_PREVIEW: + // It is necessary to return a feed preview template that contains + // a {{URL}} substring where the feed URL should go; see the code + // that computes feed previews in feed_preview.cc:MakeFeedPreview. + // This fixes issue #932714. + return "Feed preview for {{URL}}"; + case IDR_TEXTAREA_RESIZER: { + // Use webkit's text area resizer image. + static unsigned char area_resizer_data[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x08, 0x08, 0x06, 0x00, 0x00, 0x00, 0xC4, 0x0F, 0xBE, 0x8B, 0x00, 0x00, 0x00, @@ -120,85 +120,85 @@ StringPiece GetDataResource(int resource_id) { 0x98, 0x0E, 0x17, 0x7C, 0x1B, 0xCA, 0x36, 0x92, 0x76, 0x6A, 0x48, 0x66, 0x37, 0x68, 0xAA, 0x05, 0x38, 0x03, 0x00, 0x40, 0x17, 0x33, 0x3D, 0x58, 0x57, 0x6B, 0xB3, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, - 0x42, 0x60, 0x82 - }; - return StringPiece(reinterpret_cast(area_resizer_data), - static_cast( - sizeof(area_resizer_data) / sizeof(unsigned char))); - } - case IDR_SEARCH_CANCEL: - case IDR_SEARCH_CANCEL_PRESSED: - case IDR_SEARCH_MAGNIFIER: - case IDR_SEARCH_MAGNIFIER_RESULTS: - case IDR_MEDIA_PAUSE_BUTTON: - case IDR_MEDIA_PLAY_BUTTON: - case IDR_MEDIA_SOUND_FULL_BUTTON: - case IDR_MEDIA_SOUND_NONE_BUTTON: - return NetResourceProvider(resource_id); - default: - break; - } - - return StringPiece(); -} - -bool GetApplicationDirectory(std::wstring *path) { - return PathService::Get(base::DIR_EXE, path); -} - -GURL GetInspectorURL() { - return GURL("cef-resource://inspector/inspector.html"); -} - -std::string GetUIResourceProtocol() { - return "cef-resource"; -} - -bool GetExeDirectory(std::wstring *path) { - return PathService::Get(base::DIR_EXE, path); -} - -bool SpellCheckWord(const wchar_t* word, int word_len, - int* misspelling_start, int* misspelling_len) { - // Report all words being correctly spelled. - *misspelling_start = 0; - *misspelling_len = 0; - return true; -} - -bool IsPluginRunningInRendererProcess() { - return true; -} - -bool GetPluginFinderURL(std::string* plugin_finder_url) { - return false; -} - -bool IsDefaultPluginEnabled() { - return false; -} - -std::wstring GetWebKitLocale() { - return L"en-US"; -} - -void InitializeTextEncoding() { - WebCore::UTF8Encoding(); -} - -v8::Handle GetV8Context(WebFrame* frame) -{ - WebFrameImpl* webFrameImpl = static_cast(frame); - WebCore::Frame* core_frame = webFrameImpl->frame(); - return WebCore::V8Proxy::context(core_frame); -} - -void CloseIdleConnections() { - // Used in benchmarking, Ignored for CEF. -} - -void SetCacheMode(bool enabled) { - // Used in benchmarking, Ignored for CEF. -} - -} // namespace webkit_glue + 0x42, 0x60, 0x82 + }; + return StringPiece(reinterpret_cast(area_resizer_data), + static_cast( + sizeof(area_resizer_data) / sizeof(unsigned char))); + } + case IDR_SEARCH_CANCEL: + case IDR_SEARCH_CANCEL_PRESSED: + case IDR_SEARCH_MAGNIFIER: + case IDR_SEARCH_MAGNIFIER_RESULTS: + case IDR_MEDIA_PAUSE_BUTTON: + case IDR_MEDIA_PLAY_BUTTON: + case IDR_MEDIA_SOUND_FULL_BUTTON: + case IDR_MEDIA_SOUND_NONE_BUTTON: + return NetResourceProvider(resource_id); + default: + break; + } + + return StringPiece(); +} + +bool GetApplicationDirectory(std::wstring *path) { + return PathService::Get(base::DIR_EXE, path); +} + +GURL GetInspectorURL() { + return GURL("cef-resource://inspector/inspector.html"); +} + +std::string GetUIResourceProtocol() { + return "cef-resource"; +} + +bool GetExeDirectory(std::wstring *path) { + return PathService::Get(base::DIR_EXE, path); +} + +bool SpellCheckWord(const wchar_t* word, int word_len, + int* misspelling_start, int* misspelling_len) { + // Report all words being correctly spelled. + *misspelling_start = 0; + *misspelling_len = 0; + return true; +} + +bool IsPluginRunningInRendererProcess() { + return true; +} + +bool GetPluginFinderURL(std::string* plugin_finder_url) { + return false; +} + +bool IsDefaultPluginEnabled() { + return false; +} + +std::wstring GetWebKitLocale() { + return L"en-US"; +} + +void InitializeTextEncoding() { + WebCore::UTF8Encoding(); +} + +v8::Handle GetV8Context(WebFrame* frame) +{ + WebFrameImpl* webFrameImpl = static_cast(frame); + WebCore::Frame* core_frame = webFrameImpl->frame(); + return WebCore::V8Proxy::context(core_frame); +} + +void CloseIdleConnections() { + // Used in benchmarking, Ignored for CEF. +} + +void SetCacheMode(bool enabled) { + // Used in benchmarking, Ignored for CEF. +} + +} // namespace webkit_glue diff --git a/libcef/browser_webkit_glue.h b/libcef/browser_webkit_glue.h index 5e5585209..883b81e51 100644 --- a/libcef/browser_webkit_glue.h +++ b/libcef/browser_webkit_glue.h @@ -1,6 +1,6 @@ -// 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. +// 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. #if defined(OS_WIN) #include @@ -27,7 +27,7 @@ BOOL SaveBitmapToFile(HBITMAP hBmp, HDC hDC, LPCTSTR file, LPBYTE lpBits); // Text encoding objects must be initialized on the main thread. void InitializeTextEncoding(); -// This is called indirectly by the network layer to access resources. +// This is called indirectly by the network layer to access resources. StringPiece NetResourceProvider(int key); // Retrieve the V8 context associated with the frame. diff --git a/libcef/browser_webkit_init.h b/libcef/browser_webkit_init.h index fe40ad4b3..e0522de10 100644 --- a/libcef/browser_webkit_init.h +++ b/libcef/browser_webkit_init.h @@ -1,140 +1,140 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. -// Portions copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef _BROWSER_WEBKIT_INIT_H -#define _BROWSER_WEBKIT_INIT_H - -#include "base/file_util.h" -#include "base/path_service.h" -#include "base/stats_counters.h" -#include "base/string_util.h" -#include "media/base/media.h" -#include "webkit/api/public/WebCString.h" -#include "webkit/api/public/WebData.h" -#include "webkit/api/public/WebKit.h" -#include "webkit/api/public/WebStorageArea.h" -#include "webkit/api/public/WebStorageNamespace.h" -#include "webkit/api/public/WebString.h" -#include "webkit/api/public/WebURL.h" -#include "webkit/glue/simple_webmimeregistry_impl.h" -#include "webkit/glue/webclipboard_impl.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/webkitclient_impl.h" -#include "webkit/extensions/v8/gears_extension.h" -#include "webkit/extensions/v8/interval_extension.h" -#include "browser_resource_loader_bridge.h" - - -class BrowserWebKitInit : public webkit_glue::WebKitClientImpl { - public: - BrowserWebKitInit() { - v8::V8::SetCounterFunction(StatsTable::FindLocation); - - WebKit::initialize(this); - WebKit::setLayoutTestMode(false); - WebKit::registerURLSchemeAsLocal( - ASCIIToUTF16(webkit_glue::GetUIResourceProtocol())); - WebKit::registerURLSchemeAsNoAccess( - ASCIIToUTF16(webkit_glue::GetUIResourceProtocol())); - WebKit::registerExtension(extensions_v8::GearsExtension::Get()); - WebKit::registerExtension(extensions_v8::IntervalExtension::Get()); - - // Load libraries for media and enable the media player. - FilePath module_path; - if (PathService::Get(base::DIR_MODULE, &module_path) && - media::InitializeMediaLibrary(module_path)) { - WebKit::enableMediaPlayer(); - } - } - - ~BrowserWebKitInit() { - WebKit::shutdown(); - } - - virtual WebKit::WebMimeRegistry* mimeRegistry() { - return &mime_registry_; - } - - WebKit::WebClipboard* clipboard() { - if (!clipboard_.get()) { - clipboard_.reset(new webkit_glue::WebClipboardImpl()); - } - return clipboard_.get(); - } - - virtual WebKit::WebSandboxSupport* sandboxSupport() { - return NULL; - } - - virtual bool getFileSize(const WebKit::WebString& path, long long& result) { - return file_util::GetFileSize( - FilePath(webkit_glue::WebStringToFilePathString(path)), &result); - } - - virtual unsigned long long visitedLinkHash(const char* canonicalURL, size_t length) { - return 0; - } - - virtual bool isLinkVisited(unsigned long long linkHash) { - return false; - } - - virtual void setCookies(const WebKit::WebURL& url, - const WebKit::WebURL& first_party_for_cookies, - const WebKit::WebString& value) { - BrowserResourceLoaderBridge::SetCookie( - url, first_party_for_cookies, UTF16ToUTF8(value)); - } - - virtual WebKit::WebString cookies( - const WebKit::WebURL& url, - const WebKit::WebURL& first_party_for_cookies) { - return UTF8ToUTF16(BrowserResourceLoaderBridge::GetCookies( - url, first_party_for_cookies)); - } - - virtual void prefetchHostName(const WebKit::WebString&) { - } - - virtual WebKit::WebData loadResource(const char* name) { - if (!strcmp(name, "deleteButton")) { - // Create a red 30x30 square. - const char red_square[] = - "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" - "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" - "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" - "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" - "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" - "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" - "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" - "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" - "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" - "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" - "\x82"; - return WebKit::WebData(red_square, arraysize(red_square)); - } - return webkit_glue::WebKitClientImpl::loadResource(name); - } - - virtual WebKit::WebString defaultLocale() { - return ASCIIToUTF16("en-US"); - } - - virtual WebKit::WebStorageNamespace* createLocalStorageNamespace( - const WebKit::WebString& path) { - return WebKit::WebStorageNamespace::createLocalStorageNamespace(path); - } - - virtual WebKit::WebStorageNamespace* createSessionStorageNamespace() { - return WebKit::WebStorageNamespace::createSessionStorageNamespace(); - } - - - private: - webkit_glue::SimpleWebMimeRegistryImpl mime_registry_; - scoped_ptr clipboard_; -}; - -#endif // _BROWSER_WEBKIT_INIT_H +// Copyright (c) 2009 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _BROWSER_WEBKIT_INIT_H +#define _BROWSER_WEBKIT_INIT_H + +#include "base/file_util.h" +#include "base/path_service.h" +#include "base/stats_counters.h" +#include "base/string_util.h" +#include "media/base/media.h" +#include "webkit/api/public/WebCString.h" +#include "webkit/api/public/WebData.h" +#include "webkit/api/public/WebKit.h" +#include "webkit/api/public/WebStorageArea.h" +#include "webkit/api/public/WebStorageNamespace.h" +#include "webkit/api/public/WebString.h" +#include "webkit/api/public/WebURL.h" +#include "webkit/glue/simple_webmimeregistry_impl.h" +#include "webkit/glue/webclipboard_impl.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/webkitclient_impl.h" +#include "webkit/extensions/v8/gears_extension.h" +#include "webkit/extensions/v8/interval_extension.h" +#include "browser_resource_loader_bridge.h" + + +class BrowserWebKitInit : public webkit_glue::WebKitClientImpl { + public: + BrowserWebKitInit() { + v8::V8::SetCounterFunction(StatsTable::FindLocation); + + WebKit::initialize(this); + WebKit::setLayoutTestMode(false); + WebKit::registerURLSchemeAsLocal( + ASCIIToUTF16(webkit_glue::GetUIResourceProtocol())); + WebKit::registerURLSchemeAsNoAccess( + ASCIIToUTF16(webkit_glue::GetUIResourceProtocol())); + WebKit::registerExtension(extensions_v8::GearsExtension::Get()); + WebKit::registerExtension(extensions_v8::IntervalExtension::Get()); + + // Load libraries for media and enable the media player. + FilePath module_path; + if (PathService::Get(base::DIR_MODULE, &module_path) && + media::InitializeMediaLibrary(module_path)) { + WebKit::enableMediaPlayer(); + } + } + + ~BrowserWebKitInit() { + WebKit::shutdown(); + } + + virtual WebKit::WebMimeRegistry* mimeRegistry() { + return &mime_registry_; + } + + WebKit::WebClipboard* clipboard() { + if (!clipboard_.get()) { + clipboard_.reset(new webkit_glue::WebClipboardImpl()); + } + return clipboard_.get(); + } + + virtual WebKit::WebSandboxSupport* sandboxSupport() { + return NULL; + } + + virtual bool getFileSize(const WebKit::WebString& path, long long& result) { + return file_util::GetFileSize( + FilePath(webkit_glue::WebStringToFilePathString(path)), &result); + } + + virtual unsigned long long visitedLinkHash(const char* canonicalURL, size_t length) { + return 0; + } + + virtual bool isLinkVisited(unsigned long long linkHash) { + return false; + } + + virtual void setCookies(const WebKit::WebURL& url, + const WebKit::WebURL& first_party_for_cookies, + const WebKit::WebString& value) { + BrowserResourceLoaderBridge::SetCookie( + url, first_party_for_cookies, UTF16ToUTF8(value)); + } + + virtual WebKit::WebString cookies( + const WebKit::WebURL& url, + const WebKit::WebURL& first_party_for_cookies) { + return UTF8ToUTF16(BrowserResourceLoaderBridge::GetCookies( + url, first_party_for_cookies)); + } + + virtual void prefetchHostName(const WebKit::WebString&) { + } + + virtual WebKit::WebData loadResource(const char* name) { + if (!strcmp(name, "deleteButton")) { + // Create a red 30x30 square. + const char red_square[] = + "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" + "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" + "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" + "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" + "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" + "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" + "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" + "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" + "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" + "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" + "\x82"; + return WebKit::WebData(red_square, arraysize(red_square)); + } + return webkit_glue::WebKitClientImpl::loadResource(name); + } + + virtual WebKit::WebString defaultLocale() { + return ASCIIToUTF16("en-US"); + } + + virtual WebKit::WebStorageNamespace* createLocalStorageNamespace( + const WebKit::WebString& path) { + return WebKit::WebStorageNamespace::createLocalStorageNamespace(path); + } + + virtual WebKit::WebStorageNamespace* createSessionStorageNamespace() { + return WebKit::WebStorageNamespace::createSessionStorageNamespace(); + } + + + private: + webkit_glue::SimpleWebMimeRegistryImpl mime_registry_; + scoped_ptr clipboard_; +}; + +#endif // _BROWSER_WEBKIT_INIT_H diff --git a/libcef/browser_webview_delegate.cc b/libcef/browser_webview_delegate.cc index c26890a31..0ebf58ce3 100644 --- a/libcef/browser_webview_delegate.cc +++ b/libcef/browser_webview_delegate.cc @@ -1,768 +1,768 @@ -// Copyright (c) 2008-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. - -// This file contains the implementation of BrowserWebViewDelegate, which serves -// as the WebViewDelegate for the BrowserWebHost. The host is expected to -// have initialized a MessageLoop before these methods are called. - -#include "precompiled_libcef.h" -#include "config.h" -#include "browser_webview_delegate.h" -#include "browser_impl.h" -#include "browser_navigation_controller.h" -#include "context.h" -#include "request_impl.h" -#include "v8_impl.h" - -#include "base/file_util.h" -#include "base/gfx/gdi_util.h" -#include "base/gfx/point.h" -#include "base/gfx/native_widget_types.h" -#include "base/message_loop.h" -#include "base/process_util.h" -#include "base/string_util.h" -#include "base/trace_event.h" -#include "net/base/net_errors.h" -#include "webkit/api/public/WebData.h" -#include "webkit/api/public/WebDataSource.h" -#include "webkit/api/public/WebDragData.h" -#include "webkit/api/public/WebHistoryItem.h" -#include "webkit/api/public/WebKit.h" -#include "webkit/api/public/WebScreenInfo.h" -#include "webkit/api/public/WebString.h" -#include "webkit/api/public/WebURL.h" -#include "webkit/api/public/WebURLError.h" -#include "webkit/api/public/WebURLRequest.h" -#include "webkit/glue/glue_serialize.h" -#include "webkit/glue/glue_util.h" -#include "webkit/glue/media/buffered_data_source.h" -#include "webkit/glue/media/media_resource_loader_bridge_factory.h" -#include "webkit/glue/media/simple_data_source.h" -#include "webkit/glue/webappcachecontext.h" -#include "webkit/glue/webdropdata.h" -#include "webkit/glue/webframe.h" -#include "webkit/glue/webpreferences.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/webview.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/webplugin_delegate_impl.h" -#include "webkit/glue/webmediaplayer_impl.h" -#include "webkit/glue/window_open_disposition.h" +// Copyright (c) 2008-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. + +// This file contains the implementation of BrowserWebViewDelegate, which serves +// as the WebViewDelegate for the BrowserWebHost. The host is expected to +// have initialized a MessageLoop before these methods are called. + +#include "precompiled_libcef.h" +#include "config.h" +#include "browser_webview_delegate.h" +#include "browser_impl.h" +#include "browser_navigation_controller.h" +#include "context.h" +#include "request_impl.h" +#include "v8_impl.h" + +#include "base/file_util.h" +#include "base/gfx/gdi_util.h" +#include "base/gfx/point.h" +#include "base/gfx/native_widget_types.h" +#include "base/message_loop.h" +#include "base/process_util.h" +#include "base/string_util.h" +#include "base/trace_event.h" +#include "net/base/net_errors.h" +#include "webkit/api/public/WebData.h" +#include "webkit/api/public/WebDataSource.h" +#include "webkit/api/public/WebDragData.h" +#include "webkit/api/public/WebHistoryItem.h" +#include "webkit/api/public/WebKit.h" +#include "webkit/api/public/WebScreenInfo.h" +#include "webkit/api/public/WebString.h" +#include "webkit/api/public/WebURL.h" +#include "webkit/api/public/WebURLError.h" +#include "webkit/api/public/WebURLRequest.h" +#include "webkit/glue/glue_serialize.h" +#include "webkit/glue/glue_util.h" +#include "webkit/glue/media/buffered_data_source.h" +#include "webkit/glue/media/media_resource_loader_bridge_factory.h" +#include "webkit/glue/media/simple_data_source.h" +#include "webkit/glue/webappcachecontext.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/webframe.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/webview.h" +#include "webkit/glue/plugins/plugin_list.h" +#include "webkit/glue/plugins/webplugin_delegate_impl.h" +#include "webkit/glue/webmediaplayer_impl.h" +#include "webkit/glue/window_open_disposition.h" #include "browser_webkit_glue.h" -#if defined(OS_WIN) -// TODO(port): make these files work everywhere. -#include "browser_drag_delegate.h" -#include "browser_drop_delegate.h" -#endif - -using WebKit::WebData; -using WebKit::WebDataSource; -using WebKit::WebDragData; -using WebKit::WebHistoryItem; -using WebKit::WebNavigationPolicy; -using WebKit::WebRect; -using WebKit::WebScreenInfo; -using WebKit::WebSize; -using WebKit::WebString; -using WebKit::WebURL; -using WebKit::WebURLError; -using WebKit::WebURLRequest; -using WebKit::WebWidget; -using WebKit::WebWorker; -using WebKit::WebWorkerClient; - -namespace { - -int next_page_id_ = 1; - -} // namespace - -// WebViewDelegate ----------------------------------------------------------- - -WebView* BrowserWebViewDelegate::CreateWebView(WebView* webview, - bool user_gesture, - const GURL& creator_url) { - CefRefPtr browser = - browser_->UIT_CreatePopupWindow(std::wstring()); - return browser.get() ? browser->GetWebView() : NULL; -} - -WebKit::WebWidget* BrowserWebViewDelegate::CreatePopupWidget( - WebView* webview, - bool activatable) { - return browser_->UIT_CreatePopupWidget(webview); -} - -WebKit::WebMediaPlayer* BrowserWebViewDelegate::CreateWebMediaPlayer( - WebKit::WebMediaPlayerClient* client) { - scoped_refptr factory = - new media::FilterFactoryCollection(); - - // TODO(hclam): this is the same piece of code as in RenderView, maybe they - // should be grouped together. - webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory = - new webkit_glue::MediaResourceLoaderBridgeFactory( - GURL::EmptyGURL(), // referrer - "null", // frame origin - "null", // main_frame_origin - base::GetCurrentProcId(), - WebAppCacheContext::kNoAppCacheContextId, - 0); - factory->AddFactory(webkit_glue::BufferedDataSource::CreateFactory( - MessageLoop::current(), bridge_factory)); - return new webkit_glue::WebMediaPlayerImpl(client, factory); -} - -WebWorker* BrowserWebViewDelegate::CreateWebWorker(WebWorkerClient* client) { - return NULL; -} - -void BrowserWebViewDelegate::OpenURL(WebView* webview, const GURL& url, - const GURL& referrer, - WebNavigationPolicy policy) { - DCHECK_NE(policy, WebKit::WebNavigationPolicyCurrentTab); - CefRefPtr browser = - browser_->UIT_CreatePopupWindow(UTF8ToWide(url.spec())); - - if(browser.get()) - browser->UIT_Show(policy); -} - -void BrowserWebViewDelegate::DidStartLoading(WebView* webview) { - // clear the title so we can tell if it wasn't provided by the page - browser_->UIT_SetTitle(std::wstring()); - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has started - handler->HandleLoadStart(browser_, NULL); - } -} - -void BrowserWebViewDelegate::DidStopLoading(WebView* webview) { - if(browser_->UIT_GetTitle().empty()) { - // no title was provided by the page, so send a blank string to the client - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler of a page title change - handler->HandleTitleChange(browser_, browser_->UIT_GetTitle()); - } - } - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has ended - handler->HandleLoadEnd(browser_, NULL); - } -} - -void BrowserWebViewDelegate::WindowObjectCleared(WebFrame* webframe) { +#if defined(OS_WIN) +// TODO(port): make these files work everywhere. +#include "browser_drag_delegate.h" +#include "browser_drop_delegate.h" +#endif + +using WebKit::WebData; +using WebKit::WebDataSource; +using WebKit::WebDragData; +using WebKit::WebHistoryItem; +using WebKit::WebNavigationPolicy; +using WebKit::WebRect; +using WebKit::WebScreenInfo; +using WebKit::WebSize; +using WebKit::WebString; +using WebKit::WebURL; +using WebKit::WebURLError; +using WebKit::WebURLRequest; +using WebKit::WebWidget; +using WebKit::WebWorker; +using WebKit::WebWorkerClient; + +namespace { + +int next_page_id_ = 1; + +} // namespace + +// WebViewDelegate ----------------------------------------------------------- + +WebView* BrowserWebViewDelegate::CreateWebView(WebView* webview, + bool user_gesture, + const GURL& creator_url) { + CefRefPtr browser = + browser_->UIT_CreatePopupWindow(std::wstring()); + return browser.get() ? browser->GetWebView() : NULL; +} + +WebKit::WebWidget* BrowserWebViewDelegate::CreatePopupWidget( + WebView* webview, + bool activatable) { + return browser_->UIT_CreatePopupWidget(webview); +} + +WebKit::WebMediaPlayer* BrowserWebViewDelegate::CreateWebMediaPlayer( + WebKit::WebMediaPlayerClient* client) { + scoped_refptr factory = + new media::FilterFactoryCollection(); + + // TODO(hclam): this is the same piece of code as in RenderView, maybe they + // should be grouped together. + webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory = + new webkit_glue::MediaResourceLoaderBridgeFactory( + GURL::EmptyGURL(), // referrer + "null", // frame origin + "null", // main_frame_origin + base::GetCurrentProcId(), + WebAppCacheContext::kNoAppCacheContextId, + 0); + factory->AddFactory(webkit_glue::BufferedDataSource::CreateFactory( + MessageLoop::current(), bridge_factory)); + return new webkit_glue::WebMediaPlayerImpl(client, factory); +} + +WebWorker* BrowserWebViewDelegate::CreateWebWorker(WebWorkerClient* client) { + return NULL; +} + +void BrowserWebViewDelegate::OpenURL(WebView* webview, const GURL& url, + const GURL& referrer, + WebNavigationPolicy policy) { + DCHECK_NE(policy, WebKit::WebNavigationPolicyCurrentTab); + CefRefPtr browser = + browser_->UIT_CreatePopupWindow(UTF8ToWide(url.spec())); + + if(browser.get()) + browser->UIT_Show(policy); +} + +void BrowserWebViewDelegate::DidStartLoading(WebView* webview) { + // clear the title so we can tell if it wasn't provided by the page + browser_->UIT_SetTitle(std::wstring()); + CefRefPtr handler = browser_->GetHandler(); if(handler.get()) { - v8::HandleScope handle_scope; - v8::Handle context = webkit_glue::GetV8Context(webframe); - if(context.IsEmpty()) - return; - - v8::Context::Scope scope(context); - + // Notify the handler that loading has started + handler->HandleLoadStart(browser_, NULL); + } +} + +void BrowserWebViewDelegate::DidStopLoading(WebView* webview) { + if(browser_->UIT_GetTitle().empty()) { + // no title was provided by the page, so send a blank string to the client + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler of a page title change + handler->HandleTitleChange(browser_, browser_->UIT_GetTitle()); + } + } + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has ended + handler->HandleLoadEnd(browser_, NULL); + } +} + +void BrowserWebViewDelegate::WindowObjectCleared(WebFrame* webframe) { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + v8::HandleScope handle_scope; + v8::Handle context = webkit_glue::GetV8Context(webframe); + if(context.IsEmpty()) + return; + + v8::Context::Scope scope(context); + CefRefPtr frame(browser_->GetCefFrame(webframe)); CefRefPtr object = new CefV8ValueImpl(context->Global()); handler->HandleJSBinding(browser_, frame, object); - } -} - -WebNavigationPolicy BrowserWebViewDelegate::PolicyForNavigationAction( - WebView* webview, - WebFrame* frame, - const WebKit::WebURLRequest& request, - WebKit::WebNavigationType type, - WebNavigationPolicy default_policy, - bool is_redirect) { - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Gather browse request information - CefRefPtr req(CefRequest::CreateRequest()); - - GURL request_url = request.url(); - req->SetURL(UTF8ToWide(request_url.spec())); - req->SetMethod( - UTF8ToWide(webkit_glue::WebStringToStdString(request.httpMethod()))); - - const WebKit::WebHTTPBody& httpBody = request.httpBody(); - if(!httpBody.isNull()) { - CefRefPtr postdata(CefPostData::CreatePostData()); - static_cast(postdata.get())->Set(httpBody); - req->SetPostData(postdata); - } - - CefRequest::HeaderMap map; - CefRequestImpl::GetHeaderMap(request, map); - if(map.size() > 0) - static_cast(req.get())->SetHeaderMap(map); - - // Notify the handler of a browse request - CefHandler::RetVal rv = handler->HandleBeforeBrowse(browser_, - browser_->GetCefFrame(frame), req, (CefHandler::NavType)type, - is_redirect); - if(rv == RV_HANDLED) - return WebKit::WebNavigationPolicyIgnore; - } - - WebNavigationPolicy result; - if (policy_delegate_enabled_) { - std::wstring frame_name = frame->GetName(); - std::string url_description; - GURL request_url = request.url(); - if (request_url.SchemeIs("file")) { - url_description = request_url.ExtractFileName(); - } else { - url_description = request_url.spec(); - } - if (policy_delegate_is_permissive_) { - result = WebKit::WebNavigationPolicyCurrentTab; - } else { - result = WebKit::WebNavigationPolicyIgnore; - } - } else { - result = default_policy; - } - return result; -} - -void BrowserWebViewDelegate::AssignIdentifierToRequest(WebView* webview, - uint32 identifier, - const WebURLRequest& request) { -} - -void BrowserWebViewDelegate::WillSendRequest(WebView* webview, - uint32 identifier, - WebURLRequest* request) { - // The requestor ID is used by the resource loader bridge to locate the - // browser that originated the request. - request->setRequestorID(browser_->UIT_GetUniqueID()); -} - -void BrowserWebViewDelegate::DidFinishLoading(WebView* webview, - uint32 identifier) { - -} - -void BrowserWebViewDelegate::DidFailLoadingWithError(WebView* webview, - uint32 identifier, - const WebURLError& error) { - -} - -void BrowserWebViewDelegate::DidCreateDataSource(WebFrame* frame, - WebDataSource* ds) { - ds->setExtraData(pending_extra_data_.release()); -} - -void BrowserWebViewDelegate::DidStartProvisionalLoadForFrame( - WebView* webview, - WebFrame* frame, - NavigationGesture gesture) { - if (!top_loading_frame_) { - top_loading_frame_ = frame; - } - UpdateAddressBar(webview); -} - -void BrowserWebViewDelegate::DidReceiveServerRedirectForProvisionalLoadForFrame( - WebView* webview, - WebFrame* frame) { - UpdateAddressBar(webview); -} - -void BrowserWebViewDelegate::DidFailProvisionalLoadWithError( - WebView* webview, - const WebURLError& error, - WebFrame* frame) { - LocationChangeDone(frame); - - // error codes are defined in net\base\net_error_list.h - - // Don't display an error page if this is simply a cancelled load. Aside - // from being dumb, WebCore doesn't expect it and it will cause a crash. - if (error.reason == net::ERR_ABORTED) - return; - - const WebDataSource* failed_ds = frame->GetProvisionalDataSource(); - BrowserExtraData* extra_data = - static_cast(failed_ds->extraData()); - bool replace = extra_data && extra_data->pending_page_id != -1; - - std::string error_text; - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // give the handler an opportunity to generate a custom error message - std::wstring error_str; - CefHandler::RetVal rv = handler->HandleLoadError(browser_, - browser_->GetCefFrame(frame), - static_cast(error.reason), - UTF8ToWide(failed_ds->request().url().spec().data()), error_str); - if(rv == RV_HANDLED && !error_str.empty()) - error_text = WideToUTF8(error_str); - } else { - error_text = StringPrintf("Error %d when loading url %s", error.reason, - failed_ds->request().url().spec().data()); - } - - // Make sure we never show errors in view source mode. - frame->SetInViewSourceMode(false); - - frame->LoadHTMLString( - error_text, GURL("testshell-error:"), error.unreachableURL, replace); -} - -void BrowserWebViewDelegate::DidCommitLoadForFrame(WebView* webview, - WebFrame* frame, - bool is_new_navigation) { - UpdateForCommittedLoad(frame, is_new_navigation); - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has started - handler->HandleLoadStart(browser_, browser_->GetCefFrame(frame)); - } -} - -void BrowserWebViewDelegate::DidReceiveTitle(WebView* webview, - const std::wstring& title, - WebFrame* frame) { - browser_->UIT_SetTitle(title); - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler of a page title change - handler->HandleTitleChange(browser_, title); - } -} - -void BrowserWebViewDelegate::DidFinishLoadForFrame(WebView* webview, - WebFrame* frame) { - UpdateAddressBar(webview); - LocationChangeDone(frame); - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that loading has ended - handler->HandleLoadEnd(browser_, browser_->GetCefFrame(frame)); - } -} - -void BrowserWebViewDelegate::DidFailLoadWithError(WebView* webview, - const WebURLError& error, - WebFrame* frame) { - LocationChangeDone(frame); -} - -void BrowserWebViewDelegate::DidFinishDocumentLoadForFrame(WebView* webview, - WebFrame* frame) { - -} - -void BrowserWebViewDelegate::DidHandleOnloadEventsForFrame(WebView* webview, - WebFrame* frame) { - -} - -void BrowserWebViewDelegate::DidChangeLocationWithinPageForFrame( - WebView* webview, WebFrame* frame, bool is_new_navigation) { - frame->GetDataSource()->setExtraData(pending_extra_data_.release()); - UpdateForCommittedLoad(frame, is_new_navigation); -} - -void BrowserWebViewDelegate::DidReceiveIconForFrame(WebView* webview, - WebFrame* frame) { - -} - -void BrowserWebViewDelegate::WillPerformClientRedirect(WebView* webview, - WebFrame* frame, - const std::wstring& dest_url, - unsigned int delay_seconds, - unsigned int fire_date) { - -} - -void BrowserWebViewDelegate::DidCancelClientRedirect(WebView* webview, - WebFrame* frame) { - -} - -void BrowserWebViewDelegate::AddMessageToConsole(WebView* webview, - const std::wstring& message, - unsigned int line_no, - const std::wstring& source_id) { - logging::LogMessage("CONSOLE", 0).stream() << "\"" - << message.c_str() - << ",\" source: " - << source_id.c_str() - << "(" - << line_no - << ")"; -} - -void BrowserWebViewDelegate::RunJavaScriptAlert(WebFrame* webframe, - const std::wstring& message) { - CefHandler::RetVal rv = RV_CONTINUE; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleJSAlert(browser_, browser_->GetCefFrame(webframe), - message); - } - if(rv != RV_HANDLED) - ShowJavaScriptAlert(webframe, message); -} - -bool BrowserWebViewDelegate::RunJavaScriptConfirm(WebFrame* webframe, - const std::wstring& message) { - CefHandler::RetVal rv = RV_CONTINUE; - bool retval = false; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleJSConfirm(browser_, browser_->GetCefFrame(webframe), - message, retval); - } - if(rv != RV_HANDLED) - retval = ShowJavaScriptConfirm(webframe, message); - return retval; -} - -bool BrowserWebViewDelegate::RunJavaScriptPrompt(WebFrame* webframe, - const std::wstring& message, const std::wstring& default_value, - std::wstring* result) { - CefHandler::RetVal rv = RV_CONTINUE; - bool retval = false; - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - rv = handler->HandleJSPrompt(browser_, browser_->GetCefFrame(webframe), - message, default_value, retval, *result); - } - if(rv != RV_HANDLED) - retval = ShowJavaScriptPrompt(webframe, message, default_value, result); - return retval; -} - -void BrowserWebViewDelegate::SetStatusbarText(WebView* webview, - const std::wstring& message) { - -} - -void BrowserWebViewDelegate::StartDragging(WebView* webview, - const WebDragData& drag_data) { -#if defined(OS_WIN) - // TODO(port): make this work on all platforms. - if (!drag_delegate_) { - drag_delegate_ = new BrowserDragDelegate( - browser_->GetWebViewWndHandle(), - browser_->GetWebView()); - } - // TODO(tc): Drag and drop is disabled in the test shell because we need - // to be able to convert from WebDragData to an IDataObject. - //const DWORD ok_effect = DROPEFFECT_COPY | DROPEFFECT_LINK | DROPEFFECT_MOVE; - //DWORD effect; - //HRESULT res = DoDragDrop(drag_data.data_object, drag_delegate_.get(), - // ok_effect, &effect); - //DCHECK(DRAGDROP_S_DROP == res || DRAGDROP_S_CANCEL == res); - webview->DragSourceSystemDragEnded(); -#endif -} - -// The output from these methods in non-interactive mode should match that -// expected by the layout tests. See EditingDelegate.m in DumpRenderTree. -bool BrowserWebViewDelegate::ShouldBeginEditing(WebView* webview, - std::wstring range) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::ShouldEndEditing(WebView* webview, - std::wstring range) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::ShouldInsertNode(WebView* webview, - std::wstring node, - std::wstring range, - std::wstring action) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::ShouldInsertText(WebView* webview, - std::wstring text, - std::wstring range, - std::wstring action) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::ShouldChangeSelectedRange(WebView* webview, - std::wstring fromRange, - std::wstring toRange, - std::wstring affinity, - bool stillSelecting) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::ShouldDeleteRange(WebView* webview, - std::wstring range) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::ShouldApplyStyle(WebView* webview, - std::wstring style, - std::wstring range) { - return browser_->UIT_AllowEditing(); -} - -bool BrowserWebViewDelegate::SmartInsertDeleteEnabled() { - return true; -} - -void BrowserWebViewDelegate::DidBeginEditing() { - -} - -void BrowserWebViewDelegate::DidChangeSelection() { - -} - -void BrowserWebViewDelegate::DidChangeContents() { - -} - -void BrowserWebViewDelegate::DidEndEditing() { - -} - -void BrowserWebViewDelegate::NavigateBackForwardSoon(int offset) { - browser_->UIT_GetNavigationController()->GoToOffset(offset); -} - -int BrowserWebViewDelegate::GetHistoryBackListCount() { - int current_index = - browser_->UIT_GetNavigationController()->GetLastCommittedEntryIndex(); - return current_index; -} - -int BrowserWebViewDelegate::GetHistoryForwardListCount() { - int current_index = - browser_->UIT_GetNavigationController()->GetLastCommittedEntryIndex(); - return browser_->UIT_GetNavigationController()->GetEntryCount() - - current_index - 1; -} - -void BrowserWebViewDelegate::TakeFocus(WebView* webview, bool reverse) { - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler that it should take a focus - handler->HandleTakeFocus(browser_, reverse); - } -} - -void BrowserWebViewDelegate::SetUserStyleSheetEnabled(bool is_enabled) { - WebPreferences* prefs = _Context->GetWebPreferences(); - prefs->user_style_sheet_enabled = is_enabled; - browser_->GetWebView()->SetPreferences(*prefs); -} - -void BrowserWebViewDelegate::SetUserStyleSheetLocation(const GURL& location) { - WebPreferences* prefs = _Context->GetWebPreferences(); - prefs->user_style_sheet_enabled = true; - prefs->user_style_sheet_location = location; - browser_->GetWebView()->SetPreferences(*prefs); -} - -void BrowserWebViewDelegate::SetSmartInsertDeleteEnabled(bool enabled) { - smart_insert_delete_enabled_ = enabled; - // In upstream WebKit, smart insert/delete is mutually exclusive with select - // trailing whitespace, however, we allow both because Chromium on Windows - // allows both. -} - -void BrowserWebViewDelegate::SetSelectTrailingWhitespaceEnabled(bool enabled) { - select_trailing_whitespace_enabled_ = enabled; - // In upstream WebKit, smart insert/delete is mutually exclusive with select - // trailing whitespace, however, we allow both because Chromium on Windows - // allows both. -} - -void BrowserWebViewDelegate::RegisterDragDrop() { -#if defined(OS_WIN) - // TODO(port): add me once drag and drop works. - DCHECK(!drop_delegate_); - drop_delegate_ = new BrowserDropDelegate(browser_->GetWebViewWndHandle(), - browser_->GetWebView()); -#endif -} - -void BrowserWebViewDelegate::SetCustomPolicyDelegate(bool is_custom, - bool is_permissive) { - policy_delegate_enabled_ = is_custom; - policy_delegate_is_permissive_ = is_permissive; -} - -void BrowserWebViewDelegate::WaitForPolicyDelegate() { - policy_delegate_enabled_ = true; -} - -// WebWidgetClient --------------------------------------------------------- - -void BrowserWebViewDelegate::didInvalidateRect(const WebRect& rect) { - if (WebWidgetHost* host = GetWidgetHost()) - host->DidInvalidateRect(rect); -} - -void BrowserWebViewDelegate::didScrollRect(int dx, int dy, - const WebRect& clip_rect) { - if (WebWidgetHost* host = GetWidgetHost()) - host->DidScrollRect(dx, dy, clip_rect); -} - -void BrowserWebViewDelegate::didFocus() { - if (WebWidgetHost* host = GetWidgetHost()) { - CefRefPtr handler = browser_->GetHandler(); - if (handler.get() && handler->HandleSetFocus(browser_, true) == RV_CONTINUE) - browser_->UIT_SetFocus(host, true); - } -} - -void BrowserWebViewDelegate::didBlur() { - if (WebWidgetHost* host = GetWidgetHost()) - browser_->UIT_SetFocus(host, false); -} - -WebScreenInfo BrowserWebViewDelegate::screenInfo() { - if (WebWidgetHost* host = GetWidgetHost()) - return host->GetScreenInfo(); - - return WebScreenInfo(); -} - -// Private methods ----------------------------------------------------------- - -void BrowserWebViewDelegate::UpdateAddressBar(WebView* webView) { -/* - WebFrame* mainFrame = webView->UIT_GetMainFrame(); - WebDataSource* dataSource = mainFrame->GetDataSource(); - if (!dataSource) - dataSource = mainFrame->GetProvisionalDataSource(); - if (!dataSource) - return; - - GURL gUrl = dataSource->request().firstPartyForCookies(); -*/ -} - -void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) { - if (frame == top_loading_frame_) - top_loading_frame_ = NULL; -} - -WebWidgetHost* BrowserWebViewDelegate::GetWidgetHost() { - if (this == browser_->GetWebViewDelegate()) - return browser_->GetWebViewHost(); - if (this == browser_->GetPopupDelegate()) - return browser_->GetPopupHost(); - return NULL; -} - -void BrowserWebViewDelegate::UpdateForCommittedLoad(WebFrame* frame, - bool is_new_navigation) { - WebView* webview = browser_->GetWebView(); - - // Code duplicated from RenderView::DidCommitLoadForFrame. - BrowserExtraData* extra_data = static_cast( - frame->GetDataSource()->extraData()); - - if (is_new_navigation) { - // New navigation. - UpdateSessionHistory(frame); - page_id_ = next_page_id_++; - } else if (extra_data && extra_data->pending_page_id != -1 && - !extra_data->request_committed) { - // This is a successful session history navigation! - UpdateSessionHistory(frame); - page_id_ = extra_data->pending_page_id; - } - - // Don't update session history multiple times. - if (extra_data) - extra_data->request_committed = true; - - UpdateURL(frame); -} - -void BrowserWebViewDelegate::UpdateURL(WebFrame* frame) { - WebDataSource* ds = frame->GetDataSource(); - DCHECK(ds); - - const WebURLRequest& request = ds->request(); - - // Type is unused. - scoped_ptr entry(new BrowserNavigationEntry); - - // Bug 654101: the referrer will be empty on https->http transitions. It - // would be nice if we could get the real referrer from somewhere. - entry->SetPageID(page_id_); - if (ds->hasUnreachableURL()) { - entry->SetURL(ds->unreachableURL()); - } else { - entry->SetURL(request.url()); - } - - std::wstring url = UTF8ToWide(entry->GetURL().spec().c_str()); - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Notify the handler of an address change - handler->HandleAddressChange(browser_, browser_->GetCefFrame(frame), url); - } - - const WebHistoryItem& history_item = frame->GetCurrentHistoryItem(); - if (!history_item.isNull()) - entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); - - browser_->UIT_GetNavigationController()->DidNavigateToEntry(entry.release()); - - last_page_id_updated_ = std::max(last_page_id_updated_, page_id_); -} - -void BrowserWebViewDelegate::UpdateSessionHistory(WebFrame* frame) { - // If we have a valid page ID at this point, then it corresponds to the page - // we are navigating away from. Otherwise, this is the first navigation, so - // there is no past session history to record. - if (page_id_ == -1) - return; - - BrowserNavigationEntry* entry = static_cast( - browser_->UIT_GetNavigationController()->GetEntryWithPageID(page_id_)); - if (!entry) - return; - - const WebHistoryItem& history_item = - browser_->GetWebView()->GetMainFrame()->GetPreviousHistoryItem(); - if (history_item.isNull()) - return; - - entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); -} - -std::wstring BrowserWebViewDelegate::GetFrameDescription(WebFrame* webframe) { - std::wstring name = webframe->GetName(); - - if (webframe == browser_->GetWebView()->GetMainFrame()) { - if (name.length()) - return L"main frame \"" + name + L"\""; - else - return L"main frame"; - } else { - if (name.length()) - return L"frame \"" + name + L"\""; - else - return L"frame (anonymous)"; - } -} + } +} + +WebNavigationPolicy BrowserWebViewDelegate::PolicyForNavigationAction( + WebView* webview, + WebFrame* frame, + const WebKit::WebURLRequest& request, + WebKit::WebNavigationType type, + WebNavigationPolicy default_policy, + bool is_redirect) { + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Gather browse request information + CefRefPtr req(CefRequest::CreateRequest()); + + GURL request_url = request.url(); + req->SetURL(UTF8ToWide(request_url.spec())); + req->SetMethod( + UTF8ToWide(webkit_glue::WebStringToStdString(request.httpMethod()))); + + const WebKit::WebHTTPBody& httpBody = request.httpBody(); + if(!httpBody.isNull()) { + CefRefPtr postdata(CefPostData::CreatePostData()); + static_cast(postdata.get())->Set(httpBody); + req->SetPostData(postdata); + } + + CefRequest::HeaderMap map; + CefRequestImpl::GetHeaderMap(request, map); + if(map.size() > 0) + static_cast(req.get())->SetHeaderMap(map); + + // Notify the handler of a browse request + CefHandler::RetVal rv = handler->HandleBeforeBrowse(browser_, + browser_->GetCefFrame(frame), req, (CefHandler::NavType)type, + is_redirect); + if(rv == RV_HANDLED) + return WebKit::WebNavigationPolicyIgnore; + } + + WebNavigationPolicy result; + if (policy_delegate_enabled_) { + std::wstring frame_name = frame->GetName(); + std::string url_description; + GURL request_url = request.url(); + if (request_url.SchemeIs("file")) { + url_description = request_url.ExtractFileName(); + } else { + url_description = request_url.spec(); + } + if (policy_delegate_is_permissive_) { + result = WebKit::WebNavigationPolicyCurrentTab; + } else { + result = WebKit::WebNavigationPolicyIgnore; + } + } else { + result = default_policy; + } + return result; +} + +void BrowserWebViewDelegate::AssignIdentifierToRequest(WebView* webview, + uint32 identifier, + const WebURLRequest& request) { +} + +void BrowserWebViewDelegate::WillSendRequest(WebView* webview, + uint32 identifier, + WebURLRequest* request) { + // The requestor ID is used by the resource loader bridge to locate the + // browser that originated the request. + request->setRequestorID(browser_->UIT_GetUniqueID()); +} + +void BrowserWebViewDelegate::DidFinishLoading(WebView* webview, + uint32 identifier) { + +} + +void BrowserWebViewDelegate::DidFailLoadingWithError(WebView* webview, + uint32 identifier, + const WebURLError& error) { + +} + +void BrowserWebViewDelegate::DidCreateDataSource(WebFrame* frame, + WebDataSource* ds) { + ds->setExtraData(pending_extra_data_.release()); +} + +void BrowserWebViewDelegate::DidStartProvisionalLoadForFrame( + WebView* webview, + WebFrame* frame, + NavigationGesture gesture) { + if (!top_loading_frame_) { + top_loading_frame_ = frame; + } + UpdateAddressBar(webview); +} + +void BrowserWebViewDelegate::DidReceiveServerRedirectForProvisionalLoadForFrame( + WebView* webview, + WebFrame* frame) { + UpdateAddressBar(webview); +} + +void BrowserWebViewDelegate::DidFailProvisionalLoadWithError( + WebView* webview, + const WebURLError& error, + WebFrame* frame) { + LocationChangeDone(frame); + + // error codes are defined in net\base\net_error_list.h + + // Don't display an error page if this is simply a cancelled load. Aside + // from being dumb, WebCore doesn't expect it and it will cause a crash. + if (error.reason == net::ERR_ABORTED) + return; + + const WebDataSource* failed_ds = frame->GetProvisionalDataSource(); + BrowserExtraData* extra_data = + static_cast(failed_ds->extraData()); + bool replace = extra_data && extra_data->pending_page_id != -1; + + std::string error_text; + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // give the handler an opportunity to generate a custom error message + std::wstring error_str; + CefHandler::RetVal rv = handler->HandleLoadError(browser_, + browser_->GetCefFrame(frame), + static_cast(error.reason), + UTF8ToWide(failed_ds->request().url().spec().data()), error_str); + if(rv == RV_HANDLED && !error_str.empty()) + error_text = WideToUTF8(error_str); + } else { + error_text = StringPrintf("Error %d when loading url %s", error.reason, + failed_ds->request().url().spec().data()); + } + + // Make sure we never show errors in view source mode. + frame->SetInViewSourceMode(false); + + frame->LoadHTMLString( + error_text, GURL("testshell-error:"), error.unreachableURL, replace); +} + +void BrowserWebViewDelegate::DidCommitLoadForFrame(WebView* webview, + WebFrame* frame, + bool is_new_navigation) { + UpdateForCommittedLoad(frame, is_new_navigation); + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has started + handler->HandleLoadStart(browser_, browser_->GetCefFrame(frame)); + } +} + +void BrowserWebViewDelegate::DidReceiveTitle(WebView* webview, + const std::wstring& title, + WebFrame* frame) { + browser_->UIT_SetTitle(title); + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler of a page title change + handler->HandleTitleChange(browser_, title); + } +} + +void BrowserWebViewDelegate::DidFinishLoadForFrame(WebView* webview, + WebFrame* frame) { + UpdateAddressBar(webview); + LocationChangeDone(frame); + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that loading has ended + handler->HandleLoadEnd(browser_, browser_->GetCefFrame(frame)); + } +} + +void BrowserWebViewDelegate::DidFailLoadWithError(WebView* webview, + const WebURLError& error, + WebFrame* frame) { + LocationChangeDone(frame); +} + +void BrowserWebViewDelegate::DidFinishDocumentLoadForFrame(WebView* webview, + WebFrame* frame) { + +} + +void BrowserWebViewDelegate::DidHandleOnloadEventsForFrame(WebView* webview, + WebFrame* frame) { + +} + +void BrowserWebViewDelegate::DidChangeLocationWithinPageForFrame( + WebView* webview, WebFrame* frame, bool is_new_navigation) { + frame->GetDataSource()->setExtraData(pending_extra_data_.release()); + UpdateForCommittedLoad(frame, is_new_navigation); +} + +void BrowserWebViewDelegate::DidReceiveIconForFrame(WebView* webview, + WebFrame* frame) { + +} + +void BrowserWebViewDelegate::WillPerformClientRedirect(WebView* webview, + WebFrame* frame, + const std::wstring& dest_url, + unsigned int delay_seconds, + unsigned int fire_date) { + +} + +void BrowserWebViewDelegate::DidCancelClientRedirect(WebView* webview, + WebFrame* frame) { + +} + +void BrowserWebViewDelegate::AddMessageToConsole(WebView* webview, + const std::wstring& message, + unsigned int line_no, + const std::wstring& source_id) { + logging::LogMessage("CONSOLE", 0).stream() << "\"" + << message.c_str() + << ",\" source: " + << source_id.c_str() + << "(" + << line_no + << ")"; +} + +void BrowserWebViewDelegate::RunJavaScriptAlert(WebFrame* webframe, + const std::wstring& message) { + CefHandler::RetVal rv = RV_CONTINUE; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleJSAlert(browser_, browser_->GetCefFrame(webframe), + message); + } + if(rv != RV_HANDLED) + ShowJavaScriptAlert(webframe, message); +} + +bool BrowserWebViewDelegate::RunJavaScriptConfirm(WebFrame* webframe, + const std::wstring& message) { + CefHandler::RetVal rv = RV_CONTINUE; + bool retval = false; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleJSConfirm(browser_, browser_->GetCefFrame(webframe), + message, retval); + } + if(rv != RV_HANDLED) + retval = ShowJavaScriptConfirm(webframe, message); + return retval; +} + +bool BrowserWebViewDelegate::RunJavaScriptPrompt(WebFrame* webframe, + const std::wstring& message, const std::wstring& default_value, + std::wstring* result) { + CefHandler::RetVal rv = RV_CONTINUE; + bool retval = false; + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + rv = handler->HandleJSPrompt(browser_, browser_->GetCefFrame(webframe), + message, default_value, retval, *result); + } + if(rv != RV_HANDLED) + retval = ShowJavaScriptPrompt(webframe, message, default_value, result); + return retval; +} + +void BrowserWebViewDelegate::SetStatusbarText(WebView* webview, + const std::wstring& message) { + +} + +void BrowserWebViewDelegate::StartDragging(WebView* webview, + const WebDragData& drag_data) { +#if defined(OS_WIN) + // TODO(port): make this work on all platforms. + if (!drag_delegate_) { + drag_delegate_ = new BrowserDragDelegate( + browser_->GetWebViewWndHandle(), + browser_->GetWebView()); + } + // TODO(tc): Drag and drop is disabled in the test shell because we need + // to be able to convert from WebDragData to an IDataObject. + //const DWORD ok_effect = DROPEFFECT_COPY | DROPEFFECT_LINK | DROPEFFECT_MOVE; + //DWORD effect; + //HRESULT res = DoDragDrop(drag_data.data_object, drag_delegate_.get(), + // ok_effect, &effect); + //DCHECK(DRAGDROP_S_DROP == res || DRAGDROP_S_CANCEL == res); + webview->DragSourceSystemDragEnded(); +#endif +} + +// The output from these methods in non-interactive mode should match that +// expected by the layout tests. See EditingDelegate.m in DumpRenderTree. +bool BrowserWebViewDelegate::ShouldBeginEditing(WebView* webview, + std::wstring range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::ShouldEndEditing(WebView* webview, + std::wstring range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::ShouldInsertNode(WebView* webview, + std::wstring node, + std::wstring range, + std::wstring action) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::ShouldInsertText(WebView* webview, + std::wstring text, + std::wstring range, + std::wstring action) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::ShouldChangeSelectedRange(WebView* webview, + std::wstring fromRange, + std::wstring toRange, + std::wstring affinity, + bool stillSelecting) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::ShouldDeleteRange(WebView* webview, + std::wstring range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::ShouldApplyStyle(WebView* webview, + std::wstring style, + std::wstring range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::SmartInsertDeleteEnabled() { + return true; +} + +void BrowserWebViewDelegate::DidBeginEditing() { + +} + +void BrowserWebViewDelegate::DidChangeSelection() { + +} + +void BrowserWebViewDelegate::DidChangeContents() { + +} + +void BrowserWebViewDelegate::DidEndEditing() { + +} + +void BrowserWebViewDelegate::NavigateBackForwardSoon(int offset) { + browser_->UIT_GetNavigationController()->GoToOffset(offset); +} + +int BrowserWebViewDelegate::GetHistoryBackListCount() { + int current_index = + browser_->UIT_GetNavigationController()->GetLastCommittedEntryIndex(); + return current_index; +} + +int BrowserWebViewDelegate::GetHistoryForwardListCount() { + int current_index = + browser_->UIT_GetNavigationController()->GetLastCommittedEntryIndex(); + return browser_->UIT_GetNavigationController()->GetEntryCount() + - current_index - 1; +} + +void BrowserWebViewDelegate::TakeFocus(WebView* webview, bool reverse) { + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler that it should take a focus + handler->HandleTakeFocus(browser_, reverse); + } +} + +void BrowserWebViewDelegate::SetUserStyleSheetEnabled(bool is_enabled) { + WebPreferences* prefs = _Context->GetWebPreferences(); + prefs->user_style_sheet_enabled = is_enabled; + browser_->GetWebView()->SetPreferences(*prefs); +} + +void BrowserWebViewDelegate::SetUserStyleSheetLocation(const GURL& location) { + WebPreferences* prefs = _Context->GetWebPreferences(); + prefs->user_style_sheet_enabled = true; + prefs->user_style_sheet_location = location; + browser_->GetWebView()->SetPreferences(*prefs); +} + +void BrowserWebViewDelegate::SetSmartInsertDeleteEnabled(bool enabled) { + smart_insert_delete_enabled_ = enabled; + // In upstream WebKit, smart insert/delete is mutually exclusive with select + // trailing whitespace, however, we allow both because Chromium on Windows + // allows both. +} + +void BrowserWebViewDelegate::SetSelectTrailingWhitespaceEnabled(bool enabled) { + select_trailing_whitespace_enabled_ = enabled; + // In upstream WebKit, smart insert/delete is mutually exclusive with select + // trailing whitespace, however, we allow both because Chromium on Windows + // allows both. +} + +void BrowserWebViewDelegate::RegisterDragDrop() { +#if defined(OS_WIN) + // TODO(port): add me once drag and drop works. + DCHECK(!drop_delegate_); + drop_delegate_ = new BrowserDropDelegate(browser_->GetWebViewWndHandle(), + browser_->GetWebView()); +#endif +} + +void BrowserWebViewDelegate::SetCustomPolicyDelegate(bool is_custom, + bool is_permissive) { + policy_delegate_enabled_ = is_custom; + policy_delegate_is_permissive_ = is_permissive; +} + +void BrowserWebViewDelegate::WaitForPolicyDelegate() { + policy_delegate_enabled_ = true; +} + +// WebWidgetClient --------------------------------------------------------- + +void BrowserWebViewDelegate::didInvalidateRect(const WebRect& rect) { + if (WebWidgetHost* host = GetWidgetHost()) + host->DidInvalidateRect(rect); +} + +void BrowserWebViewDelegate::didScrollRect(int dx, int dy, + const WebRect& clip_rect) { + if (WebWidgetHost* host = GetWidgetHost()) + host->DidScrollRect(dx, dy, clip_rect); +} + +void BrowserWebViewDelegate::didFocus() { + if (WebWidgetHost* host = GetWidgetHost()) { + CefRefPtr handler = browser_->GetHandler(); + if (handler.get() && handler->HandleSetFocus(browser_, true) == RV_CONTINUE) + browser_->UIT_SetFocus(host, true); + } +} + +void BrowserWebViewDelegate::didBlur() { + if (WebWidgetHost* host = GetWidgetHost()) + browser_->UIT_SetFocus(host, false); +} + +WebScreenInfo BrowserWebViewDelegate::screenInfo() { + if (WebWidgetHost* host = GetWidgetHost()) + return host->GetScreenInfo(); + + return WebScreenInfo(); +} + +// Private methods ----------------------------------------------------------- + +void BrowserWebViewDelegate::UpdateAddressBar(WebView* webView) { +/* + WebFrame* mainFrame = webView->UIT_GetMainFrame(); + WebDataSource* dataSource = mainFrame->GetDataSource(); + if (!dataSource) + dataSource = mainFrame->GetProvisionalDataSource(); + if (!dataSource) + return; + + GURL gUrl = dataSource->request().firstPartyForCookies(); +*/ +} + +void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) { + if (frame == top_loading_frame_) + top_loading_frame_ = NULL; +} + +WebWidgetHost* BrowserWebViewDelegate::GetWidgetHost() { + if (this == browser_->GetWebViewDelegate()) + return browser_->GetWebViewHost(); + if (this == browser_->GetPopupDelegate()) + return browser_->GetPopupHost(); + return NULL; +} + +void BrowserWebViewDelegate::UpdateForCommittedLoad(WebFrame* frame, + bool is_new_navigation) { + WebView* webview = browser_->GetWebView(); + + // Code duplicated from RenderView::DidCommitLoadForFrame. + BrowserExtraData* extra_data = static_cast( + frame->GetDataSource()->extraData()); + + if (is_new_navigation) { + // New navigation. + UpdateSessionHistory(frame); + page_id_ = next_page_id_++; + } else if (extra_data && extra_data->pending_page_id != -1 && + !extra_data->request_committed) { + // This is a successful session history navigation! + UpdateSessionHistory(frame); + page_id_ = extra_data->pending_page_id; + } + + // Don't update session history multiple times. + if (extra_data) + extra_data->request_committed = true; + + UpdateURL(frame); +} + +void BrowserWebViewDelegate::UpdateURL(WebFrame* frame) { + WebDataSource* ds = frame->GetDataSource(); + DCHECK(ds); + + const WebURLRequest& request = ds->request(); + + // Type is unused. + scoped_ptr entry(new BrowserNavigationEntry); + + // Bug 654101: the referrer will be empty on https->http transitions. It + // would be nice if we could get the real referrer from somewhere. + entry->SetPageID(page_id_); + if (ds->hasUnreachableURL()) { + entry->SetURL(ds->unreachableURL()); + } else { + entry->SetURL(request.url()); + } + + std::wstring url = UTF8ToWide(entry->GetURL().spec().c_str()); + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Notify the handler of an address change + handler->HandleAddressChange(browser_, browser_->GetCefFrame(frame), url); + } + + const WebHistoryItem& history_item = frame->GetCurrentHistoryItem(); + if (!history_item.isNull()) + entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); + + browser_->UIT_GetNavigationController()->DidNavigateToEntry(entry.release()); + + last_page_id_updated_ = std::max(last_page_id_updated_, page_id_); +} + +void BrowserWebViewDelegate::UpdateSessionHistory(WebFrame* frame) { + // If we have a valid page ID at this point, then it corresponds to the page + // we are navigating away from. Otherwise, this is the first navigation, so + // there is no past session history to record. + if (page_id_ == -1) + return; + + BrowserNavigationEntry* entry = static_cast( + browser_->UIT_GetNavigationController()->GetEntryWithPageID(page_id_)); + if (!entry) + return; + + const WebHistoryItem& history_item = + browser_->GetWebView()->GetMainFrame()->GetPreviousHistoryItem(); + if (history_item.isNull()) + return; + + entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); +} + +std::wstring BrowserWebViewDelegate::GetFrameDescription(WebFrame* webframe) { + std::wstring name = webframe->GetName(); + + if (webframe == browser_->GetWebView()->GetMainFrame()) { + if (name.length()) + return L"main frame \"" + name + L"\""; + else + return L"main frame"; + } else { + if (name.length()) + return L"frame \"" + name + L"\""; + else + return L"frame (anonymous)"; + } +} diff --git a/libcef/browser_webview_delegate.h b/libcef/browser_webview_delegate.h index fe3e88237..d9a9f3a9c 100644 --- a/libcef/browser_webview_delegate.h +++ b/libcef/browser_webview_delegate.h @@ -1,314 +1,314 @@ -// Copyright (c) 2008-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. - -// BrowserWebViewDelegate class: -// This class implements the WebViewDelegate methods for the test shell. One -// instance is owned by each CefBrowser. - -#ifndef _BROWSER_WEBVIEW_DELEGATE_H -#define _BROWSER_WEBVIEW_DELEGATE_H - -#include "build/build_config.h" - -#include - -#if defined(OS_LINUX) -#include -#endif - -#include "base/basictypes.h" -#include "base/ref_counted.h" -#include "base/scoped_ptr.h" -#include "webkit/glue/webcursor.h" -#include "webkit/glue/webview_delegate.h" -#if defined(OS_WIN) -#include "browser_drag_delegate.h" -#include "browser_drop_delegate.h" -#endif -#include "browser_navigation_controller.h" - -class CefBrowserImpl; -struct ContextMenuMediaParams; -struct WebPreferences; -class GURL; -class WebWidgetHost; - -class BrowserWebViewDelegate : public base::RefCounted, - public WebViewDelegate { - public: - BrowserWebViewDelegate(CefBrowserImpl* browser) - : policy_delegate_enabled_(false), - policy_delegate_is_permissive_(false), - browser_(browser), - top_loading_frame_(NULL), - page_id_(-1), - last_page_id_updated_(-1), - smart_insert_delete_enabled_(true) -#if defined(OS_WIN) - , select_trailing_whitespace_enabled_(true) -#else - , select_trailing_whitespace_enabled_(false) -#endif -#if defined(OS_LINUX) - , cursor_type_(GDK_X_CURSOR) -#endif - { - } - virtual ~BrowserWebViewDelegate() {} - - // WebViewDelegate - virtual WebView* CreateWebView(WebView* webview, - bool user_gesture, - const GURL& creator_url); - virtual WebKit::WebWidget* CreatePopupWidget( - WebView* webview, - bool activatable); - virtual WebPluginDelegate* CreatePluginDelegate( - WebView* webview, - const GURL& url, - const std::string& mime_type, - const std::string& clsid, - std::string* actual_mime_type); - virtual WebKit::WebMediaPlayer* CreateWebMediaPlayer( - WebKit::WebMediaPlayerClient* client); - virtual WebKit::WebWorker* CreateWebWorker(WebKit::WebWorkerClient* client); - virtual void OpenURL(WebView* webview, - const GURL& url, - const GURL& referrer, - WebKit::WebNavigationPolicy policy); - virtual void DidMovePlugin(const WebPluginGeometry& move); - virtual void RunJavaScriptAlert(WebFrame* webframe, - const std::wstring& message); - virtual bool RunJavaScriptConfirm(WebFrame* webframe, - const std::wstring& message); - virtual bool RunJavaScriptPrompt(WebFrame* webframe, - const std::wstring& message, - const std::wstring& default_value, - std::wstring* result); - virtual void SetStatusbarText(WebView* webview, - const std::wstring& message); - virtual void AddMessageToConsole(WebView* webview, - const std::wstring& message, - unsigned int line_no, - const std::wstring& source_id); - virtual void StartDragging(WebView* webview, - const WebKit::WebDragData& drop_data); - virtual void ShowContextMenu(WebView* webview, - ContextNodeType node_type, - int x, - int y, - const GURL& link_url, - const GURL& image_url, - const GURL& page_url, - const GURL& frame_url, - const ContextMenuMediaParams& media_params, - const std::wstring& selection_text, - const std::wstring& misspelled_word, - int edit_flags, - const std::string& security_info, - const std::string& frame_charset); - virtual void DidCreateDataSource(WebFrame* frame, - WebKit::WebDataSource* ds); - virtual void DidStartProvisionalLoadForFrame( - WebView* webview, - WebFrame* frame, - NavigationGesture gesture); - virtual void DidReceiveServerRedirectForProvisionalLoadForFrame( - WebView* webview, WebFrame* frame); - virtual void DidFailProvisionalLoadWithError( - WebView* webview, - const WebKit::WebURLError& error, - WebFrame* frame); - virtual void DidCommitLoadForFrame(WebView* webview, WebFrame* frame, - bool is_new_navigation); - virtual void DidReceiveTitle(WebView* webview, - const std::wstring& title, - WebFrame* frame); - virtual void DidFinishDocumentLoadForFrame(WebView* webview, - WebFrame* frame); - virtual void DidHandleOnloadEventsForFrame(WebView* webview, - WebFrame* frame); - virtual void DidChangeLocationWithinPageForFrame(WebView* webview, - WebFrame* frame, - bool is_new_navigation); - virtual void DidReceiveIconForFrame(WebView* webview, WebFrame* frame); - - virtual void WillPerformClientRedirect(WebView* webview, - WebFrame* frame, - const std::wstring& dest_url, - unsigned int delay_seconds, - unsigned int fire_date); - virtual void DidCancelClientRedirect(WebView* webview, - WebFrame* frame); - - virtual void DidFinishLoadForFrame(WebView* webview, WebFrame* frame); - virtual void DidFailLoadWithError(WebView* webview, - const WebKit::WebURLError& error, - WebFrame* for_frame); - - virtual void AssignIdentifierToRequest(WebView* webview, - uint32 identifier, - const WebKit::WebURLRequest& request); - virtual void WillSendRequest(WebView* webview, - uint32 identifier, - WebKit::WebURLRequest* request); - virtual void DidFinishLoading(WebView* webview, uint32 identifier); - virtual void DidFailLoadingWithError(WebView* webview, - uint32 identifier, - const WebKit::WebURLError& error); - - virtual bool ShouldBeginEditing(WebView* webview, std::wstring range); - virtual bool ShouldEndEditing(WebView* webview, std::wstring range); - virtual bool ShouldInsertNode(WebView* webview, - std::wstring node, - std::wstring range, - std::wstring action); - virtual bool ShouldInsertText(WebView* webview, - std::wstring text, - std::wstring range, - std::wstring action); - virtual bool ShouldChangeSelectedRange(WebView* webview, - std::wstring fromRange, - std::wstring toRange, - std::wstring affinity, - bool stillSelecting); - virtual bool ShouldDeleteRange(WebView* webview, std::wstring range); - virtual bool ShouldApplyStyle(WebView* webview, - std::wstring style, - std::wstring range); - virtual bool SmartInsertDeleteEnabled(); - virtual void DidBeginEditing(); - virtual void DidChangeSelection(); - virtual void DidChangeContents(); - virtual void DidEndEditing(); - - virtual void DidStartLoading(WebView* webview); - virtual void DidStopLoading(WebView* webview); - - virtual void WindowObjectCleared(WebFrame* webframe); - virtual WebKit::WebNavigationPolicy PolicyForNavigationAction( - WebView* webview, - WebFrame* frame, - const WebKit::WebURLRequest& request, - WebKit::WebNavigationType type, - WebKit::WebNavigationPolicy default_policy, - bool is_redirect); - virtual void NavigateBackForwardSoon(int offset); - virtual int GetHistoryBackListCount(); - virtual int GetHistoryForwardListCount(); - virtual void TakeFocus(WebView* webview, bool reverse); - - // WebWidgetClient - virtual void didInvalidateRect(const WebKit::WebRect& rect); - virtual void didScrollRect(int dx, int dy, - const WebKit::WebRect& clip_rect); - virtual void didFocus(); - virtual void didBlur(); - virtual void didChangeCursor(const WebKit::WebCursorInfo& cursor); - virtual void closeWidgetSoon(); - virtual void show(WebKit::WebNavigationPolicy policy); - virtual void runModal(); - virtual WebKit::WebRect windowRect(); - virtual void setWindowRect(const WebKit::WebRect& rect); - virtual WebKit::WebRect rootWindowRect(); - virtual WebKit::WebRect windowResizerRect(); - virtual WebKit::WebScreenInfo screenInfo(); - - void SetSmartInsertDeleteEnabled(bool enabled); - void SetSelectTrailingWhitespaceEnabled(bool enabled); - - // Additional accessors - WebFrame* top_loading_frame() { return top_loading_frame_; } -#if defined(OS_WIN) - IDropTarget* drop_delegate() { return drop_delegate_.get(); } - IDropSource* drag_delegate() { return drag_delegate_.get(); } -#endif - - void set_pending_extra_data(BrowserExtraData* extra_data) { - pending_extra_data_.reset(extra_data); - } - - // Methods for modifying WebPreferences - void SetUserStyleSheetEnabled(bool is_enabled); - void SetUserStyleSheetLocation(const GURL& location); - - // Sets the webview as a drop target. - void RegisterDragDrop(); - - void SetCustomPolicyDelegate(bool is_custom, bool is_permissive); - void WaitForPolicyDelegate(); - - CefBrowserImpl* GetBrowser() { return browser_; } - - protected: - // Called when the URL of the page changes. - void UpdateAddressBar(WebView* webView); - - // Default handling of JavaScript messages. - void ShowJavaScriptAlert(WebFrame* webframe, const std::wstring& message); - bool ShowJavaScriptConfirm(WebFrame* webframe, const std::wstring& message); - bool ShowJavaScriptPrompt(WebFrame* webframe, const std::wstring& message, - const std::wstring& default_value, std::wstring* result); - - // In the Mac code, this is called to trigger the end of a test after the - // page has finished loading. From here, we can generate the dump for the - // test. - void LocationChangeDone(WebFrame*); - - WebWidgetHost* GetWidgetHost(); - - void UpdateForCommittedLoad(WebFrame* webframe, bool is_new_navigation); - void UpdateURL(WebFrame* frame); - void UpdateSessionHistory(WebFrame* frame); - - // Get a string suitable for dumping a frame to the console. - std::wstring GetFrameDescription(WebFrame* webframe); - - private: - // Causes navigation actions just printout the intended navigation instead - // of taking you to the page. This is used for cases like mailto, where you - // don't actually want to open the mail program. - bool policy_delegate_enabled_; - - // Toggles the behavior of the policy delegate. If true, then navigations - // will be allowed. Otherwise, they will be ignored (dropped). - bool policy_delegate_is_permissive_; - - // Non-owning pointer. The delegate is owned by the host. - CefBrowserImpl* browser_; - - // This is non-NULL IFF a load is in progress. - WebFrame* top_loading_frame_; - - // For tracking session history. See RenderView. - int page_id_; - int last_page_id_updated_; - - scoped_ptr pending_extra_data_; - - // true if we want to enable smart insert/delete. - bool smart_insert_delete_enabled_; - - // true if we want to enable selection of trailing whitespaces - bool select_trailing_whitespace_enabled_; - - WebCursor current_cursor_; -#if defined(OS_WIN) - // Classes needed by drag and drop. - scoped_refptr drag_delegate_; - scoped_refptr drop_delegate_; -#endif - -#if defined(OS_LINUX) - // The type of cursor the window is currently using. - // Used for judging whether a new SetCursor call is actually changing the - // cursor. - GdkCursorType cursor_type_; -#endif - - DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate); -}; - -#endif // _BROWSER_WEBVIEW_DELEGATE_H +// Copyright (c) 2008-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. + +// BrowserWebViewDelegate class: +// This class implements the WebViewDelegate methods for the test shell. One +// instance is owned by each CefBrowser. + +#ifndef _BROWSER_WEBVIEW_DELEGATE_H +#define _BROWSER_WEBVIEW_DELEGATE_H + +#include "build/build_config.h" + +#include + +#if defined(OS_LINUX) +#include +#endif + +#include "base/basictypes.h" +#include "base/ref_counted.h" +#include "base/scoped_ptr.h" +#include "webkit/glue/webcursor.h" +#include "webkit/glue/webview_delegate.h" +#if defined(OS_WIN) +#include "browser_drag_delegate.h" +#include "browser_drop_delegate.h" +#endif +#include "browser_navigation_controller.h" + +class CefBrowserImpl; +struct ContextMenuMediaParams; +struct WebPreferences; +class GURL; +class WebWidgetHost; + +class BrowserWebViewDelegate : public base::RefCounted, + public WebViewDelegate { + public: + BrowserWebViewDelegate(CefBrowserImpl* browser) + : policy_delegate_enabled_(false), + policy_delegate_is_permissive_(false), + browser_(browser), + top_loading_frame_(NULL), + page_id_(-1), + last_page_id_updated_(-1), + smart_insert_delete_enabled_(true) +#if defined(OS_WIN) + , select_trailing_whitespace_enabled_(true) +#else + , select_trailing_whitespace_enabled_(false) +#endif +#if defined(OS_LINUX) + , cursor_type_(GDK_X_CURSOR) +#endif + { + } + virtual ~BrowserWebViewDelegate() {} + + // WebViewDelegate + virtual WebView* CreateWebView(WebView* webview, + bool user_gesture, + const GURL& creator_url); + virtual WebKit::WebWidget* CreatePopupWidget( + WebView* webview, + bool activatable); + virtual WebPluginDelegate* CreatePluginDelegate( + WebView* webview, + const GURL& url, + const std::string& mime_type, + const std::string& clsid, + std::string* actual_mime_type); + virtual WebKit::WebMediaPlayer* CreateWebMediaPlayer( + WebKit::WebMediaPlayerClient* client); + virtual WebKit::WebWorker* CreateWebWorker(WebKit::WebWorkerClient* client); + virtual void OpenURL(WebView* webview, + const GURL& url, + const GURL& referrer, + WebKit::WebNavigationPolicy policy); + virtual void DidMovePlugin(const WebPluginGeometry& move); + virtual void RunJavaScriptAlert(WebFrame* webframe, + const std::wstring& message); + virtual bool RunJavaScriptConfirm(WebFrame* webframe, + const std::wstring& message); + virtual bool RunJavaScriptPrompt(WebFrame* webframe, + const std::wstring& message, + const std::wstring& default_value, + std::wstring* result); + virtual void SetStatusbarText(WebView* webview, + const std::wstring& message); + virtual void AddMessageToConsole(WebView* webview, + const std::wstring& message, + unsigned int line_no, + const std::wstring& source_id); + virtual void StartDragging(WebView* webview, + const WebKit::WebDragData& drop_data); + virtual void ShowContextMenu(WebView* webview, + ContextNodeType node_type, + int x, + int y, + const GURL& link_url, + const GURL& image_url, + const GURL& page_url, + const GURL& frame_url, + const ContextMenuMediaParams& media_params, + const std::wstring& selection_text, + const std::wstring& misspelled_word, + int edit_flags, + const std::string& security_info, + const std::string& frame_charset); + virtual void DidCreateDataSource(WebFrame* frame, + WebKit::WebDataSource* ds); + virtual void DidStartProvisionalLoadForFrame( + WebView* webview, + WebFrame* frame, + NavigationGesture gesture); + virtual void DidReceiveServerRedirectForProvisionalLoadForFrame( + WebView* webview, WebFrame* frame); + virtual void DidFailProvisionalLoadWithError( + WebView* webview, + const WebKit::WebURLError& error, + WebFrame* frame); + virtual void DidCommitLoadForFrame(WebView* webview, WebFrame* frame, + bool is_new_navigation); + virtual void DidReceiveTitle(WebView* webview, + const std::wstring& title, + WebFrame* frame); + virtual void DidFinishDocumentLoadForFrame(WebView* webview, + WebFrame* frame); + virtual void DidHandleOnloadEventsForFrame(WebView* webview, + WebFrame* frame); + virtual void DidChangeLocationWithinPageForFrame(WebView* webview, + WebFrame* frame, + bool is_new_navigation); + virtual void DidReceiveIconForFrame(WebView* webview, WebFrame* frame); + + virtual void WillPerformClientRedirect(WebView* webview, + WebFrame* frame, + const std::wstring& dest_url, + unsigned int delay_seconds, + unsigned int fire_date); + virtual void DidCancelClientRedirect(WebView* webview, + WebFrame* frame); + + virtual void DidFinishLoadForFrame(WebView* webview, WebFrame* frame); + virtual void DidFailLoadWithError(WebView* webview, + const WebKit::WebURLError& error, + WebFrame* for_frame); + + virtual void AssignIdentifierToRequest(WebView* webview, + uint32 identifier, + const WebKit::WebURLRequest& request); + virtual void WillSendRequest(WebView* webview, + uint32 identifier, + WebKit::WebURLRequest* request); + virtual void DidFinishLoading(WebView* webview, uint32 identifier); + virtual void DidFailLoadingWithError(WebView* webview, + uint32 identifier, + const WebKit::WebURLError& error); + + virtual bool ShouldBeginEditing(WebView* webview, std::wstring range); + virtual bool ShouldEndEditing(WebView* webview, std::wstring range); + virtual bool ShouldInsertNode(WebView* webview, + std::wstring node, + std::wstring range, + std::wstring action); + virtual bool ShouldInsertText(WebView* webview, + std::wstring text, + std::wstring range, + std::wstring action); + virtual bool ShouldChangeSelectedRange(WebView* webview, + std::wstring fromRange, + std::wstring toRange, + std::wstring affinity, + bool stillSelecting); + virtual bool ShouldDeleteRange(WebView* webview, std::wstring range); + virtual bool ShouldApplyStyle(WebView* webview, + std::wstring style, + std::wstring range); + virtual bool SmartInsertDeleteEnabled(); + virtual void DidBeginEditing(); + virtual void DidChangeSelection(); + virtual void DidChangeContents(); + virtual void DidEndEditing(); + + virtual void DidStartLoading(WebView* webview); + virtual void DidStopLoading(WebView* webview); + + virtual void WindowObjectCleared(WebFrame* webframe); + virtual WebKit::WebNavigationPolicy PolicyForNavigationAction( + WebView* webview, + WebFrame* frame, + const WebKit::WebURLRequest& request, + WebKit::WebNavigationType type, + WebKit::WebNavigationPolicy default_policy, + bool is_redirect); + virtual void NavigateBackForwardSoon(int offset); + virtual int GetHistoryBackListCount(); + virtual int GetHistoryForwardListCount(); + virtual void TakeFocus(WebView* webview, bool reverse); + + // WebWidgetClient + virtual void didInvalidateRect(const WebKit::WebRect& rect); + virtual void didScrollRect(int dx, int dy, + const WebKit::WebRect& clip_rect); + virtual void didFocus(); + virtual void didBlur(); + virtual void didChangeCursor(const WebKit::WebCursorInfo& cursor); + virtual void closeWidgetSoon(); + virtual void show(WebKit::WebNavigationPolicy policy); + virtual void runModal(); + virtual WebKit::WebRect windowRect(); + virtual void setWindowRect(const WebKit::WebRect& rect); + virtual WebKit::WebRect rootWindowRect(); + virtual WebKit::WebRect windowResizerRect(); + virtual WebKit::WebScreenInfo screenInfo(); + + void SetSmartInsertDeleteEnabled(bool enabled); + void SetSelectTrailingWhitespaceEnabled(bool enabled); + + // Additional accessors + WebFrame* top_loading_frame() { return top_loading_frame_; } +#if defined(OS_WIN) + IDropTarget* drop_delegate() { return drop_delegate_.get(); } + IDropSource* drag_delegate() { return drag_delegate_.get(); } +#endif + + void set_pending_extra_data(BrowserExtraData* extra_data) { + pending_extra_data_.reset(extra_data); + } + + // Methods for modifying WebPreferences + void SetUserStyleSheetEnabled(bool is_enabled); + void SetUserStyleSheetLocation(const GURL& location); + + // Sets the webview as a drop target. + void RegisterDragDrop(); + + void SetCustomPolicyDelegate(bool is_custom, bool is_permissive); + void WaitForPolicyDelegate(); + + CefBrowserImpl* GetBrowser() { return browser_; } + + protected: + // Called when the URL of the page changes. + void UpdateAddressBar(WebView* webView); + + // Default handling of JavaScript messages. + void ShowJavaScriptAlert(WebFrame* webframe, const std::wstring& message); + bool ShowJavaScriptConfirm(WebFrame* webframe, const std::wstring& message); + bool ShowJavaScriptPrompt(WebFrame* webframe, const std::wstring& message, + const std::wstring& default_value, std::wstring* result); + + // In the Mac code, this is called to trigger the end of a test after the + // page has finished loading. From here, we can generate the dump for the + // test. + void LocationChangeDone(WebFrame*); + + WebWidgetHost* GetWidgetHost(); + + void UpdateForCommittedLoad(WebFrame* webframe, bool is_new_navigation); + void UpdateURL(WebFrame* frame); + void UpdateSessionHistory(WebFrame* frame); + + // Get a string suitable for dumping a frame to the console. + std::wstring GetFrameDescription(WebFrame* webframe); + + private: + // Causes navigation actions just printout the intended navigation instead + // of taking you to the page. This is used for cases like mailto, where you + // don't actually want to open the mail program. + bool policy_delegate_enabled_; + + // Toggles the behavior of the policy delegate. If true, then navigations + // will be allowed. Otherwise, they will be ignored (dropped). + bool policy_delegate_is_permissive_; + + // Non-owning pointer. The delegate is owned by the host. + CefBrowserImpl* browser_; + + // This is non-NULL IFF a load is in progress. + WebFrame* top_loading_frame_; + + // For tracking session history. See RenderView. + int page_id_; + int last_page_id_updated_; + + scoped_ptr pending_extra_data_; + + // true if we want to enable smart insert/delete. + bool smart_insert_delete_enabled_; + + // true if we want to enable selection of trailing whitespaces + bool select_trailing_whitespace_enabled_; + + WebCursor current_cursor_; +#if defined(OS_WIN) + // Classes needed by drag and drop. + scoped_refptr drag_delegate_; + scoped_refptr drop_delegate_; +#endif + +#if defined(OS_LINUX) + // The type of cursor the window is currently using. + // Used for judging whether a new SetCursor call is actually changing the + // cursor. + GdkCursorType cursor_type_; +#endif + + DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate); +}; + +#endif // _BROWSER_WEBVIEW_DELEGATE_H diff --git a/libcef/browser_webview_delegate_win.cc b/libcef/browser_webview_delegate_win.cc index a501f4ff1..2869d07bd 100644 --- a/libcef/browser_webview_delegate_win.cc +++ b/libcef/browser_webview_delegate_win.cc @@ -1,384 +1,384 @@ -// Copyright (c) 2008-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. - -// This file contains the implementation of BrowserWebViewDelegate, which serves -// as the WebViewDelegate for the BrowserWebHost. The host is expected to -// have initialized a MessageLoop before these methods are called. - -#include "precompiled_libcef.h" -#include "browser_webview_delegate.h" -#include "browser_drag_delegate.h" -#include "browser_drop_delegate.h" -#include "browser_navigation_controller.h" -#include "browser_impl.h" -#include "context.h" - -#include -#include -#include - -#include "base/gfx/gdi_util.h" -#include "base/gfx/native_widget_types.h" -#include "base/gfx/point.h" -#include "base/message_loop.h" -#include "base/string_util.h" -#include "base/trace_event.h" -#include "net/base/net_errors.h" -#include "webkit/api/public/WebCursorInfo.h" -#include "webkit/api/public/WebRect.h" -#include "webkit/glue/webdropdata.h" -#include "webkit/glue/webframe.h" -#include "webkit/glue/webpreferences.h" -#include "webkit/glue/webplugin.h" -#include "webkit/glue/webkit_glue.h" -#include "webkit/glue/webview.h" -#include "webkit/glue/plugins/plugin_list.h" -#include "webkit/glue/plugins/webplugin_delegate_impl.h" -#include "webkit/glue/window_open_disposition.h" - -using WebKit::WebCursorInfo; -using WebKit::WebNavigationPolicy; -using WebKit::WebRect; - -// WebViewDelegate ----------------------------------------------------------- - -WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( - WebView* webview, - const GURL& url, - const std::string& mime_type, - const std::string& clsid, - std::string* actual_mime_type) { - HWND hwnd = browser_->GetWebViewHost()->view_handle(); - if (!hwnd) - return NULL; - - bool allow_wildcard = true; - - // first, look for plugins using the normal plugin list - WebPluginInfo info; - if (NPAPI::PluginList::Singleton()->GetPluginInfo(url, mime_type, clsid, - allow_wildcard, &info, - actual_mime_type)) { - if (actual_mime_type && !actual_mime_type->empty()) - return WebPluginDelegateImpl::Create(info.path, *actual_mime_type, hwnd); - else - return WebPluginDelegateImpl::Create(info.path, mime_type, hwnd); - } - - return NULL; -} - -void BrowserWebViewDelegate::DidMovePlugin(const WebPluginGeometry& move) { - HRGN hrgn = ::CreateRectRgn(move.clip_rect.x(), - move.clip_rect.y(), - move.clip_rect.right(), - move.clip_rect.bottom()); - gfx::SubtractRectanglesFromRegion(hrgn, move.cutout_rects); - - // Note: System will own the hrgn after we call SetWindowRgn, - // so we don't need to call DeleteObject(hrgn) - ::SetWindowRgn(move.window, hrgn, FALSE); - unsigned long flags = 0; - if (move.visible) - flags |= SWP_SHOWWINDOW; - else - flags |= SWP_HIDEWINDOW; - - ::SetWindowPos(move.window, - NULL, - move.window_rect.x(), - move.window_rect.y(), - move.window_rect.width(), - move.window_rect.height(), - flags); -} - -static void AddMenuItem(CefRefPtr browser, HMENU menu, int index, - CefHandler::MenuId id, const wchar_t* label, - bool enabled, std::list& label_list) -{ - std::wstring actual_label = label; - CefRefPtr handler = browser->GetHandler(); - if(handler.get()) { - // Let the handler change the label if desired - handler->HandleGetMenuLabel(browser, id, actual_label); - } - - // store the label in a list to simplify memory management - label_list.push_back(actual_label); - - MENUITEMINFO mii; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING; - mii.fType = MFT_STRING; - if(!enabled) { - mii.fMask |= MIIM_STATE; - mii.fState = MFS_GRAYED; - } - mii.wID = id; - mii.dwTypeData = const_cast(label_list.back().c_str()); - - InsertMenuItem(menu, index, TRUE, &mii); -} - -static void AddMenuSeparator(HMENU menu, int index) -{ - MENUITEMINFO mii; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_FTYPE; - mii.fType = MFT_SEPARATOR; - - InsertMenuItem(menu, index, TRUE, &mii); -} - -void BrowserWebViewDelegate::ShowContextMenu( - WebView* webview, - ContextNodeType node_type, - int x, - int y, - const GURL& link_url, - const GURL& image_url, - const GURL& page_url, - const GURL& frame_url, - const ContextMenuMediaParams& media_params, - const std::wstring& selection_text, - const std::wstring& misspelled_word, - int edit_flags, - const std::string& security_info, - const std::string& frame_charset) { - - POINT screen_pt = { x, y }; - MapWindowPoints(browser_->GetMainWndHandle(), HWND_DESKTOP, - &screen_pt, 1); - - HMENU menu = NULL; - std::list label_list; - - // Enable recursive tasks on the message loop so we can get updates while - // the context menu is being displayed. - bool old_state = MessageLoop::current()->NestableTasksAllowed(); - MessageLoop::current()->SetNestableTasksAllowed(true); - - if(browser_->UIT_CanGoBack()) - edit_flags |= MENU_CAN_GO_BACK; - if(browser_->UIT_CanGoForward()) - edit_flags |= MENU_CAN_GO_FORWARD; - - CefRefPtr handler = browser_->GetHandler(); - if(handler.get()) { - // Gather menu information - CefHandler::MenuInfo menuInfo; - std::wstring linkstr, imagestr, pagestr, framestr, securitystr; - - linkstr = UTF8ToWide(link_url.spec().c_str()); - imagestr = UTF8ToWide(image_url.spec().c_str()); - pagestr = UTF8ToWide(page_url.spec().c_str()); - framestr = UTF8ToWide(frame_url.spec().c_str()); - securitystr = UTF8ToWide(security_info); - - menuInfo.typeFlags = node_type.type; - menuInfo.x = screen_pt.x; - menuInfo.y = screen_pt.y; - menuInfo.linkUrl = linkstr.c_str(); - menuInfo.imageUrl = imagestr.c_str(); - menuInfo.pageUrl = pagestr.c_str(); - menuInfo.frameUrl = framestr.c_str(); - menuInfo.selectionText = selection_text.c_str(); - menuInfo.misspelledWord = misspelled_word.c_str(); - menuInfo.editFlags = edit_flags; - menuInfo.securityInfo = securitystr.c_str(); - - // Notify the handler that a context menu is requested - CefHandler::RetVal rv = handler->HandleBeforeMenu(browser_, menuInfo); - if(rv == RV_HANDLED) - goto end; - } - - // Build the correct default context menu - if (node_type.type & ContextNodeType::EDITABLE) { - menu = CreatePopupMenu(); - AddMenuItem(browser_, menu, -1, MENU_ID_UNDO, L"Undo", - !!(edit_flags & ContextNodeType::CAN_UNDO), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_REDO, L"Redo", - !!(edit_flags & ContextNodeType::CAN_REDO), label_list); - AddMenuSeparator(menu, -1); - AddMenuItem(browser_, menu, -1, MENU_ID_CUT, L"Cut", - !!(edit_flags & ContextNodeType::CAN_CUT), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", - !!(edit_flags & ContextNodeType::CAN_COPY), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_PASTE, L"Paste", - !!(edit_flags & ContextNodeType::CAN_PASTE), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_DELETE, L"Delete", - !!(edit_flags & ContextNodeType::CAN_DELETE), label_list); - AddMenuSeparator(menu, -1); - AddMenuItem(browser_, menu, -1, MENU_ID_SELECTALL, L"Select All", - !!(edit_flags & MENU_CAN_SELECT_ALL), label_list); - } else if(node_type.type & ContextNodeType::SELECTION) { - menu = CreatePopupMenu(); - AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", - !!(edit_flags & ContextNodeType::CAN_COPY), label_list); - } else if(node_type.type & - (ContextNodeType::PAGE | ContextNodeType::FRAME)) { - menu = CreatePopupMenu(); - AddMenuItem(browser_, menu, -1, MENU_ID_NAV_BACK, L"Back", - browser_->UIT_CanGoBack(), label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_NAV_FORWARD, L"Forward", - browser_->UIT_CanGoForward(), label_list); - AddMenuSeparator(menu, -1); - AddMenuItem(browser_, menu, -1, MENU_ID_PRINT, L"Print", - true, label_list); - AddMenuItem(browser_, menu, -1, MENU_ID_VIEWSOURCE, L"View Source", - true, label_list); - } - - if(menu) { - // show the context menu - int selected_id = TrackPopupMenu(menu, - TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_RECURSE, - screen_pt.x, screen_pt.y, 0, browser_->GetMainWndHandle(), NULL); - - if(selected_id != 0) { - // An action was chosen - CefHandler::MenuId menuId = static_cast(selected_id); - bool handled = false; - if(handler.get()) { - // Ask the handler if it wants to handle the action - CefHandler::RetVal rv = handler->HandleMenuAction(browser_, menuId); - handled = (rv == RV_HANDLED); - } - - if(!handled) { - // Execute the action - CefRefPtr frame = browser_->GetFocusedFrame(); - frame->AddRef(); - browser_->UIT_HandleAction(menuId, frame.get()); - } - } - } - - DestroyMenu(menu); - -end: - MessageLoop::current()->SetNestableTasksAllowed(old_state); -} - -// WebWidgetClient --------------------------------------------------------- - -void BrowserWebViewDelegate::show(WebNavigationPolicy) { - if (WebWidgetHost* host = GetWidgetHost()) { - HWND root = GetAncestor(host->view_handle(), GA_ROOT); - ShowWindow(root, SW_SHOW); - UpdateWindow(root); - } -} - -void BrowserWebViewDelegate::closeWidgetSoon() { - if (this == browser_->GetWebViewDelegate()) { - PostMessage(browser_->GetMainWndHandle(), WM_CLOSE, 0, 0); - } else if (this == browser_->GetPopupDelegate()) { - browser_->UIT_ClosePopupWidget(); - } -} - -void BrowserWebViewDelegate::didChangeCursor( - const WebCursorInfo& cursor_info) { - if (WebWidgetHost* host = GetWidgetHost()) { - current_cursor_.InitFromCursorInfo(cursor_info); - HINSTANCE mod_handle = GetModuleHandle(NULL); - host->SetCursor(current_cursor_.GetCursor(mod_handle)); - } -} - -WebRect BrowserWebViewDelegate::windowRect() { - if (WebWidgetHost* host = GetWidgetHost()) { - RECT rect; - ::GetWindowRect(host->view_handle(), &rect); - return gfx::Rect(rect); - } - return WebRect(); -} - -void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { - if (this == browser_->GetWebViewDelegate()) { - // ignored - } else if (this == browser_->GetPopupDelegate()) { - MoveWindow(browser_->GetPopupWndHandle(), - rect.x, rect.y, rect.width, rect.height, FALSE); - } -} - -WebRect BrowserWebViewDelegate::rootWindowRect() { - if (WebWidgetHost* host = GetWidgetHost()) { - RECT rect; - HWND root_window = ::GetAncestor(host->view_handle(), GA_ROOT); - ::GetWindowRect(root_window, &rect); - return gfx::Rect(rect); - } - return WebRect(); -} - -WebRect BrowserWebViewDelegate::windowResizerRect() { - // Not necessary on Windows. - return WebRect(); -} - -void BrowserWebViewDelegate::runModal() { - WebWidgetHost* host = GetWidgetHost(); - if (!host) - return; - - show(WebNavigationPolicy() /*XXX NEW_WINDOW*/); - - CefContext::BrowserList *list; - CefContext::BrowserList::const_iterator i; - - _Context->Lock(); - list = _Context->GetBrowserList(); - i = list->begin(); - for (; i != list->end(); ++i) { - if (i->get()->IsPopup()) - EnableWindow(i->get()->GetMainWndHandle(), FALSE); - } - _Context->Unlock(); - - browser_->UIT_SetIsModal(true); - MessageLoop::current()->Run(); - - _Context->Lock(); - list = _Context->GetBrowserList(); - i = list->begin(); - for (; i != list->end(); ++i) - EnableWindow(i->get()->GetMainWndHandle(), TRUE); - _Context->Unlock(); -} - -// Private methods ----------------------------------------------------------- - -void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe, - const std::wstring& message) -{ - // TODO(cef): Think about what we should be showing as the prompt caption - MessageBox(browser_->GetMainWndHandle(), message.c_str(), - browser_->UIT_GetTitle().c_str(), MB_OK | MB_ICONWARNING); -} - -bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe, - const std::wstring& message) -{ - // TODO(cef): Think about what we should be showing as the prompt caption - int rv = MessageBox(browser_->GetMainWndHandle(), message.c_str(), - browser_->UIT_GetTitle().c_str(), - MB_YESNO | MB_ICONQUESTION); - return (rv == IDYES); -} - -bool BrowserWebViewDelegate::ShowJavaScriptPrompt(WebFrame* webframe, - const std::wstring& message, - const std::wstring& default_value, - std::wstring* result) -{ - // TODO(cef): Implement a default prompt dialog - return false; -} +// Copyright (c) 2008-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. + +// This file contains the implementation of BrowserWebViewDelegate, which serves +// as the WebViewDelegate for the BrowserWebHost. The host is expected to +// have initialized a MessageLoop before these methods are called. + +#include "precompiled_libcef.h" +#include "browser_webview_delegate.h" +#include "browser_drag_delegate.h" +#include "browser_drop_delegate.h" +#include "browser_navigation_controller.h" +#include "browser_impl.h" +#include "context.h" + +#include +#include +#include + +#include "base/gfx/gdi_util.h" +#include "base/gfx/native_widget_types.h" +#include "base/gfx/point.h" +#include "base/message_loop.h" +#include "base/string_util.h" +#include "base/trace_event.h" +#include "net/base/net_errors.h" +#include "webkit/api/public/WebCursorInfo.h" +#include "webkit/api/public/WebRect.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/webframe.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/webplugin.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/webview.h" +#include "webkit/glue/plugins/plugin_list.h" +#include "webkit/glue/plugins/webplugin_delegate_impl.h" +#include "webkit/glue/window_open_disposition.h" + +using WebKit::WebCursorInfo; +using WebKit::WebNavigationPolicy; +using WebKit::WebRect; + +// WebViewDelegate ----------------------------------------------------------- + +WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( + WebView* webview, + const GURL& url, + const std::string& mime_type, + const std::string& clsid, + std::string* actual_mime_type) { + HWND hwnd = browser_->GetWebViewHost()->view_handle(); + if (!hwnd) + return NULL; + + bool allow_wildcard = true; + + // first, look for plugins using the normal plugin list + WebPluginInfo info; + if (NPAPI::PluginList::Singleton()->GetPluginInfo(url, mime_type, clsid, + allow_wildcard, &info, + actual_mime_type)) { + if (actual_mime_type && !actual_mime_type->empty()) + return WebPluginDelegateImpl::Create(info.path, *actual_mime_type, hwnd); + else + return WebPluginDelegateImpl::Create(info.path, mime_type, hwnd); + } + + return NULL; +} + +void BrowserWebViewDelegate::DidMovePlugin(const WebPluginGeometry& move) { + HRGN hrgn = ::CreateRectRgn(move.clip_rect.x(), + move.clip_rect.y(), + move.clip_rect.right(), + move.clip_rect.bottom()); + gfx::SubtractRectanglesFromRegion(hrgn, move.cutout_rects); + + // Note: System will own the hrgn after we call SetWindowRgn, + // so we don't need to call DeleteObject(hrgn) + ::SetWindowRgn(move.window, hrgn, FALSE); + unsigned long flags = 0; + if (move.visible) + flags |= SWP_SHOWWINDOW; + else + flags |= SWP_HIDEWINDOW; + + ::SetWindowPos(move.window, + NULL, + move.window_rect.x(), + move.window_rect.y(), + move.window_rect.width(), + move.window_rect.height(), + flags); +} + +static void AddMenuItem(CefRefPtr browser, HMENU menu, int index, + CefHandler::MenuId id, const wchar_t* label, + bool enabled, std::list& label_list) +{ + std::wstring actual_label = label; + CefRefPtr handler = browser->GetHandler(); + if(handler.get()) { + // Let the handler change the label if desired + handler->HandleGetMenuLabel(browser, id, actual_label); + } + + // store the label in a list to simplify memory management + label_list.push_back(actual_label); + + MENUITEMINFO mii; + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING; + mii.fType = MFT_STRING; + if(!enabled) { + mii.fMask |= MIIM_STATE; + mii.fState = MFS_GRAYED; + } + mii.wID = id; + mii.dwTypeData = const_cast(label_list.back().c_str()); + + InsertMenuItem(menu, index, TRUE, &mii); +} + +static void AddMenuSeparator(HMENU menu, int index) +{ + MENUITEMINFO mii; + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_FTYPE; + mii.fType = MFT_SEPARATOR; + + InsertMenuItem(menu, index, TRUE, &mii); +} + +void BrowserWebViewDelegate::ShowContextMenu( + WebView* webview, + ContextNodeType node_type, + int x, + int y, + const GURL& link_url, + const GURL& image_url, + const GURL& page_url, + const GURL& frame_url, + const ContextMenuMediaParams& media_params, + const std::wstring& selection_text, + const std::wstring& misspelled_word, + int edit_flags, + const std::string& security_info, + const std::string& frame_charset) { + + POINT screen_pt = { x, y }; + MapWindowPoints(browser_->GetMainWndHandle(), HWND_DESKTOP, + &screen_pt, 1); + + HMENU menu = NULL; + std::list label_list; + + // Enable recursive tasks on the message loop so we can get updates while + // the context menu is being displayed. + bool old_state = MessageLoop::current()->NestableTasksAllowed(); + MessageLoop::current()->SetNestableTasksAllowed(true); + + if(browser_->UIT_CanGoBack()) + edit_flags |= MENU_CAN_GO_BACK; + if(browser_->UIT_CanGoForward()) + edit_flags |= MENU_CAN_GO_FORWARD; + + CefRefPtr handler = browser_->GetHandler(); + if(handler.get()) { + // Gather menu information + CefHandler::MenuInfo menuInfo; + std::wstring linkstr, imagestr, pagestr, framestr, securitystr; + + linkstr = UTF8ToWide(link_url.spec().c_str()); + imagestr = UTF8ToWide(image_url.spec().c_str()); + pagestr = UTF8ToWide(page_url.spec().c_str()); + framestr = UTF8ToWide(frame_url.spec().c_str()); + securitystr = UTF8ToWide(security_info); + + menuInfo.typeFlags = node_type.type; + menuInfo.x = screen_pt.x; + menuInfo.y = screen_pt.y; + menuInfo.linkUrl = linkstr.c_str(); + menuInfo.imageUrl = imagestr.c_str(); + menuInfo.pageUrl = pagestr.c_str(); + menuInfo.frameUrl = framestr.c_str(); + menuInfo.selectionText = selection_text.c_str(); + menuInfo.misspelledWord = misspelled_word.c_str(); + menuInfo.editFlags = edit_flags; + menuInfo.securityInfo = securitystr.c_str(); + + // Notify the handler that a context menu is requested + CefHandler::RetVal rv = handler->HandleBeforeMenu(browser_, menuInfo); + if(rv == RV_HANDLED) + goto end; + } + + // Build the correct default context menu + if (node_type.type & ContextNodeType::EDITABLE) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, menu, -1, MENU_ID_UNDO, L"Undo", + !!(edit_flags & ContextNodeType::CAN_UNDO), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_REDO, L"Redo", + !!(edit_flags & ContextNodeType::CAN_REDO), label_list); + AddMenuSeparator(menu, -1); + AddMenuItem(browser_, menu, -1, MENU_ID_CUT, L"Cut", + !!(edit_flags & ContextNodeType::CAN_CUT), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", + !!(edit_flags & ContextNodeType::CAN_COPY), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_PASTE, L"Paste", + !!(edit_flags & ContextNodeType::CAN_PASTE), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_DELETE, L"Delete", + !!(edit_flags & ContextNodeType::CAN_DELETE), label_list); + AddMenuSeparator(menu, -1); + AddMenuItem(browser_, menu, -1, MENU_ID_SELECTALL, L"Select All", + !!(edit_flags & MENU_CAN_SELECT_ALL), label_list); + } else if(node_type.type & ContextNodeType::SELECTION) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, menu, -1, MENU_ID_COPY, L"Copy", + !!(edit_flags & ContextNodeType::CAN_COPY), label_list); + } else if(node_type.type & + (ContextNodeType::PAGE | ContextNodeType::FRAME)) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, menu, -1, MENU_ID_NAV_BACK, L"Back", + browser_->UIT_CanGoBack(), label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_NAV_FORWARD, L"Forward", + browser_->UIT_CanGoForward(), label_list); + AddMenuSeparator(menu, -1); + AddMenuItem(browser_, menu, -1, MENU_ID_PRINT, L"Print", + true, label_list); + AddMenuItem(browser_, menu, -1, MENU_ID_VIEWSOURCE, L"View Source", + true, label_list); + } + + if(menu) { + // show the context menu + int selected_id = TrackPopupMenu(menu, + TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_RECURSE, + screen_pt.x, screen_pt.y, 0, browser_->GetMainWndHandle(), NULL); + + if(selected_id != 0) { + // An action was chosen + CefHandler::MenuId menuId = static_cast(selected_id); + bool handled = false; + if(handler.get()) { + // Ask the handler if it wants to handle the action + CefHandler::RetVal rv = handler->HandleMenuAction(browser_, menuId); + handled = (rv == RV_HANDLED); + } + + if(!handled) { + // Execute the action + CefRefPtr frame = browser_->GetFocusedFrame(); + frame->AddRef(); + browser_->UIT_HandleAction(menuId, frame.get()); + } + } + } + + DestroyMenu(menu); + +end: + MessageLoop::current()->SetNestableTasksAllowed(old_state); +} + +// WebWidgetClient --------------------------------------------------------- + +void BrowserWebViewDelegate::show(WebNavigationPolicy) { + if (WebWidgetHost* host = GetWidgetHost()) { + HWND root = GetAncestor(host->view_handle(), GA_ROOT); + ShowWindow(root, SW_SHOW); + UpdateWindow(root); + } +} + +void BrowserWebViewDelegate::closeWidgetSoon() { + if (this == browser_->GetWebViewDelegate()) { + PostMessage(browser_->GetMainWndHandle(), WM_CLOSE, 0, 0); + } else if (this == browser_->GetPopupDelegate()) { + browser_->UIT_ClosePopupWidget(); + } +} + +void BrowserWebViewDelegate::didChangeCursor( + const WebCursorInfo& cursor_info) { + if (WebWidgetHost* host = GetWidgetHost()) { + current_cursor_.InitFromCursorInfo(cursor_info); + HINSTANCE mod_handle = GetModuleHandle(NULL); + host->SetCursor(current_cursor_.GetCursor(mod_handle)); + } +} + +WebRect BrowserWebViewDelegate::windowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + RECT rect; + ::GetWindowRect(host->view_handle(), &rect); + return gfx::Rect(rect); + } + return WebRect(); +} + +void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { + if (this == browser_->GetWebViewDelegate()) { + // ignored + } else if (this == browser_->GetPopupDelegate()) { + MoveWindow(browser_->GetPopupWndHandle(), + rect.x, rect.y, rect.width, rect.height, FALSE); + } +} + +WebRect BrowserWebViewDelegate::rootWindowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + RECT rect; + HWND root_window = ::GetAncestor(host->view_handle(), GA_ROOT); + ::GetWindowRect(root_window, &rect); + return gfx::Rect(rect); + } + return WebRect(); +} + +WebRect BrowserWebViewDelegate::windowResizerRect() { + // Not necessary on Windows. + return WebRect(); +} + +void BrowserWebViewDelegate::runModal() { + WebWidgetHost* host = GetWidgetHost(); + if (!host) + return; + + show(WebNavigationPolicy() /*XXX NEW_WINDOW*/); + + CefContext::BrowserList *list; + CefContext::BrowserList::const_iterator i; + + _Context->Lock(); + list = _Context->GetBrowserList(); + i = list->begin(); + for (; i != list->end(); ++i) { + if (i->get()->IsPopup()) + EnableWindow(i->get()->GetMainWndHandle(), FALSE); + } + _Context->Unlock(); + + browser_->UIT_SetIsModal(true); + MessageLoop::current()->Run(); + + _Context->Lock(); + list = _Context->GetBrowserList(); + i = list->begin(); + for (; i != list->end(); ++i) + EnableWindow(i->get()->GetMainWndHandle(), TRUE); + _Context->Unlock(); +} + +// Private methods ----------------------------------------------------------- + +void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe, + const std::wstring& message) +{ + // TODO(cef): Think about what we should be showing as the prompt caption + MessageBox(browser_->GetMainWndHandle(), message.c_str(), + browser_->UIT_GetTitle().c_str(), MB_OK | MB_ICONWARNING); +} + +bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe, + const std::wstring& message) +{ + // TODO(cef): Think about what we should be showing as the prompt caption + int rv = MessageBox(browser_->GetMainWndHandle(), message.c_str(), + browser_->UIT_GetTitle().c_str(), + MB_YESNO | MB_ICONQUESTION); + return (rv == IDYES); +} + +bool BrowserWebViewDelegate::ShowJavaScriptPrompt(WebFrame* webframe, + const std::wstring& message, + const std::wstring& default_value, + std::wstring* result) +{ + // TODO(cef): Implement a default prompt dialog + return false; +} diff --git a/libcef/cef_string.c b/libcef/cef_string.c index 163886ec5..4c048bb7f 100644 --- a/libcef/cef_string.c +++ b/libcef/cef_string.c @@ -1,5 +1,5 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "include/cef_string.h" diff --git a/libcef/cef_string_list.cc b/libcef/cef_string_list.cc index 64ae03823..75528e1b7 100644 --- a/libcef/cef_string_list.cc +++ b/libcef/cef_string_list.cc @@ -1,5 +1,5 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "precompiled_libcef.h" diff --git a/libcef/cef_string_map.cc b/libcef/cef_string_map.cc index 20597cf50..7aba77574 100644 --- a/libcef/cef_string_map.cc +++ b/libcef/cef_string_map.cc @@ -1,5 +1,5 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "precompiled_libcef.h" diff --git a/libcef/context.cc b/libcef/context.cc index f04323f46..c45fb80a8 100644 --- a/libcef/context.cc +++ b/libcef/context.cc @@ -1,460 +1,460 @@ -// Copyright (c) 2008-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 "precompiled_libcef.h" -#include "context.h" -#include "browser_impl.h" -#include "browser_resource_loader_bridge.h" -#include "browser_request_context.h" -#include "browser_webkit_glue.h" -#include "browser_webkit_init.h" -#include "../include/cef_nplugin.h" - -#include "base/command_line.h" -#include "base/icu_util.h" -#include "base/path_service.h" -#include "base/rand_util.h" -#include "base/resource_util.h" -#include "base/stats_table.h" -#include "base/string_util.h" -#include "net/base/net_module.h" -#include "webkit/extensions/v8/gc_extension.h" -#include "webkit/glue/webplugin.h" -#include "webkit/glue/plugins/plugin_lib.h" -#include "webkit/glue/plugins/plugin_list.h" - -#include - - -// Global CefContext pointer -CefRefPtr _Context; - -static const char* kStatsFilePrefix = "libcef_"; -static int kStatsFileThreads = 20; -static int kStatsFileCounters = 200; - - -// Class used to process events on the current message loop. -class CefMessageLoopForUI : public MessageLoopForUI -{ - typedef MessageLoopForUI inherited; - -public: - CefMessageLoopForUI() - { - } - +// Copyright (c) 2008-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 "precompiled_libcef.h" +#include "context.h" +#include "browser_impl.h" +#include "browser_resource_loader_bridge.h" +#include "browser_request_context.h" +#include "browser_webkit_glue.h" +#include "browser_webkit_init.h" +#include "../include/cef_nplugin.h" + +#include "base/command_line.h" +#include "base/icu_util.h" +#include "base/path_service.h" +#include "base/rand_util.h" +#include "base/resource_util.h" +#include "base/stats_table.h" +#include "base/string_util.h" +#include "net/base/net_module.h" +#include "webkit/extensions/v8/gc_extension.h" +#include "webkit/glue/webplugin.h" +#include "webkit/glue/plugins/plugin_lib.h" +#include "webkit/glue/plugins/plugin_list.h" + +#include + + +// Global CefContext pointer +CefRefPtr _Context; + +static const char* kStatsFilePrefix = "libcef_"; +static int kStatsFileThreads = 20; +static int kStatsFileCounters = 200; + + +// Class used to process events on the current message loop. +class CefMessageLoopForUI : public MessageLoopForUI +{ + typedef MessageLoopForUI inherited; + +public: + CefMessageLoopForUI() + { + } + virtual bool DoIdleWork() { bool valueToRet = inherited::DoIdleWork(); pump_->Quit(); return valueToRet; - } - - void DoMessageLoopIteration() { - Run(NULL); - } -}; - - -bool CefInitialize(bool multi_threaded_message_loop, - const std::wstring& cache_path) -{ - // Return true if the context is already initialized - if(_Context.get()) - return true; - - // Create the new global context object - _Context = new CefContext(); - // Initialize the glboal context - return _Context->Initialize(multi_threaded_message_loop, cache_path); -} - -void CefShutdown() -{ - // Verify that the context is already initialized - if(!_Context.get()) - return; - - // Shut down the global context - _Context->Shutdown(); - // Delete the global context object - _Context = NULL; -} - -void CefDoMessageLoopWork() -{ - if(!_Context->RunningOnUIThread()) - return; - ((CefMessageLoopForUI*)CefMessageLoopForUI::current())->DoMessageLoopIteration(); -} - -bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) -{ - if(!_Context.get()) - return false; - - CefPluginInfo* pPluginInfo = new CefPluginInfo; - *pPluginInfo = plugin_info; - + } + + void DoMessageLoopIteration() { + Run(NULL); + } +}; + + +bool CefInitialize(bool multi_threaded_message_loop, + const std::wstring& cache_path) +{ + // Return true if the context is already initialized + if(_Context.get()) + return true; + + // Create the new global context object + _Context = new CefContext(); + // Initialize the glboal context + return _Context->Initialize(multi_threaded_message_loop, cache_path); +} + +void CefShutdown() +{ + // Verify that the context is already initialized + if(!_Context.get()) + return; + + // Shut down the global context + _Context->Shutdown(); + // Delete the global context object + _Context = NULL; +} + +void CefDoMessageLoopWork() +{ + if(!_Context->RunningOnUIThread()) + return; + ((CefMessageLoopForUI*)CefMessageLoopForUI::current())->DoMessageLoopIteration(); +} + +bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) +{ + if(!_Context.get()) + return false; + + CefPluginInfo* pPluginInfo = new CefPluginInfo; + *pPluginInfo = plugin_info; + PostTask(FROM_HERE, NewRunnableMethod(_Context.get(), - &CefContext::UIT_RegisterPlugin, pPluginInfo)); + &CefContext::UIT_RegisterPlugin, pPluginInfo)); - return true; -} - -void CefContext::UIT_RegisterPlugin(struct CefPluginInfo* plugin_info) -{ - REQUIRE_UIT(); - - NPAPI::PluginVersionInfo info; - - info.path = FilePath(plugin_info->unique_name); - info.product_name = plugin_info->display_name; - info.file_description = plugin_info->description; - info.file_version =plugin_info->version; - - for(size_t i = 0; i < plugin_info->mime_types.size(); ++i) { - if(i > 0) { - info.mime_types += L"|"; - info.file_extensions += L"|"; - info.type_descriptions += L"|"; - } - - info.mime_types += plugin_info->mime_types[i].mime_type; - info.type_descriptions += plugin_info->mime_types[i].description; - - for(size_t j = 0; - j < plugin_info->mime_types[i].file_extensions.size(); ++j) { - if(j > 0) { - info.file_extensions += L","; - } - info.file_extensions += plugin_info->mime_types[i].file_extensions[j]; - } - } - - info.entry_points.np_getentrypoints = plugin_info->np_getentrypoints; - info.entry_points.np_initialize = plugin_info->np_initialize; - info.entry_points.np_shutdown = plugin_info->np_shutdown; - - NPAPI::PluginList::RegisterInternalPlugin(info); - NPAPI::PluginList::Singleton()->LoadPlugin(FilePath(info.path)); - - delete plugin_info; -} - -bool CefContext::DoInitialize() -{ - HRESULT res; - - // Initialize common controls - res = CoInitialize(NULL); - DCHECK(SUCCEEDED(res)); - INITCOMMONCONTROLSEX InitCtrlEx; - InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); - InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; - InitCommonControlsEx(&InitCtrlEx); - - // Start COM stuff - res = OleInitialize(NULL); - DCHECK(SUCCEEDED(res)); - - // Initialize the global CommandLine object. - CommandLine::Init(0, NULL); - - // Initialize WebKit. - webkit_init_ = new BrowserWebKitInit(); - - // Initialize WebKit encodings - webkit_glue::InitializeTextEncoding(); - - // Initializing with a default context, which means no on-disk cookie DB, - // and no support for directory listings. - //PathService::Get(base::DIR_EXE, &cache_path); - BrowserResourceLoaderBridge::Init( - new BrowserRequestContext(cache_path_, net::HttpCache::NORMAL, false)); - - // Load ICU data tables. - bool ret = icu_util::Initialize(); - if(!ret) { - MessageBox(NULL, L"Failed to load the required icudt38 library", - L"CEF Initialization Error", MB_ICONERROR | MB_OK); - return false; - } - - // Config the network module so it has access to a limited set of resources. - net::NetModule::SetResourceProvider(webkit_glue::NetResourceProvider); - - // Load and initialize the stats table. Attempt to construct a somewhat - // unique name to isolate separate instances from each other. - statstable_ = new StatsTable( - kStatsFilePrefix + Uint64ToString(base::RandUint64()), - kStatsFileThreads, - kStatsFileCounters); - StatsTable::set_current(statstable_); - - // CEF always exposes the GC. - webkit_glue::SetJavaScriptFlags(L"--expose-gc"); - // Expose GCController to JavaScript. - WebKit::registerExtension(extensions_v8::GCExtension::Get()); - - return true; -} - -void CefContext::DoUninitialize() -{ - // Flush any remaining messages. This ensures that any accumulated - // Task objects get destroyed before we exit, which avoids noise in - // purify leak-test results. - MessageLoop::current()->RunAllPending(); - - BrowserResourceLoaderBridge::Shutdown(); - - // Tear down the shared StatsTable. - StatsTable::set_current(NULL); - delete statstable_; - statstable_ = NULL; - - // Shut down WebKit. - delete webkit_init_; - webkit_init_ = NULL; - - // Uninitialize COM stuff - OleUninitialize(); - - // Uninitialize common controls - CoUninitialize(); -} - -DWORD WINAPI ThreadHandlerUI(LPVOID lpParam) -{ - CefContext *pContext = static_cast(lpParam); - - if (!pContext->DoInitialize()) - return 1; - - // Instantiate the message loop for this thread. - MessageLoopForUI main_message_loop; - pContext->SetMessageLoopForUI(&main_message_loop); - - // Notify the context that initialization is complete so that the - // Initialize() function can return. - pContext->NotifyEvent(); - - // Execute the message loop that will run until a quit task is received. - MessageLoop::current()->Run(); - - pContext->DoUninitialize(); - - return 0; -} - -CefContext::CefContext() -{ - hthreadui_ = NULL; - idthreadui_ = 0; - heventui_ = NULL; - messageloopui_ = NULL; - in_transition_ = false; - webprefs_ = NULL; - hinstance_ = ::GetModuleHandle(NULL); - next_browser_id_ = 1; - webkit_init_ = NULL; -} - -CefContext::~CefContext() -{ - // Just in case CefShutdown() isn't called - Shutdown(); -} - + return true; +} + +void CefContext::UIT_RegisterPlugin(struct CefPluginInfo* plugin_info) +{ + REQUIRE_UIT(); + + NPAPI::PluginVersionInfo info; + + info.path = FilePath(plugin_info->unique_name); + info.product_name = plugin_info->display_name; + info.file_description = plugin_info->description; + info.file_version =plugin_info->version; + + for(size_t i = 0; i < plugin_info->mime_types.size(); ++i) { + if(i > 0) { + info.mime_types += L"|"; + info.file_extensions += L"|"; + info.type_descriptions += L"|"; + } + + info.mime_types += plugin_info->mime_types[i].mime_type; + info.type_descriptions += plugin_info->mime_types[i].description; + + for(size_t j = 0; + j < plugin_info->mime_types[i].file_extensions.size(); ++j) { + if(j > 0) { + info.file_extensions += L","; + } + info.file_extensions += plugin_info->mime_types[i].file_extensions[j]; + } + } + + info.entry_points.np_getentrypoints = plugin_info->np_getentrypoints; + info.entry_points.np_initialize = plugin_info->np_initialize; + info.entry_points.np_shutdown = plugin_info->np_shutdown; + + NPAPI::PluginList::RegisterInternalPlugin(info); + NPAPI::PluginList::Singleton()->LoadPlugin(FilePath(info.path)); + + delete plugin_info; +} + +bool CefContext::DoInitialize() +{ + HRESULT res; + + // Initialize common controls + res = CoInitialize(NULL); + DCHECK(SUCCEEDED(res)); + INITCOMMONCONTROLSEX InitCtrlEx; + InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); + InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; + InitCommonControlsEx(&InitCtrlEx); + + // Start COM stuff + res = OleInitialize(NULL); + DCHECK(SUCCEEDED(res)); + + // Initialize the global CommandLine object. + CommandLine::Init(0, NULL); + + // Initialize WebKit. + webkit_init_ = new BrowserWebKitInit(); + + // Initialize WebKit encodings + webkit_glue::InitializeTextEncoding(); + + // Initializing with a default context, which means no on-disk cookie DB, + // and no support for directory listings. + //PathService::Get(base::DIR_EXE, &cache_path); + BrowserResourceLoaderBridge::Init( + new BrowserRequestContext(cache_path_, net::HttpCache::NORMAL, false)); + + // Load ICU data tables. + bool ret = icu_util::Initialize(); + if(!ret) { + MessageBox(NULL, L"Failed to load the required icudt38 library", + L"CEF Initialization Error", MB_ICONERROR | MB_OK); + return false; + } + + // Config the network module so it has access to a limited set of resources. + net::NetModule::SetResourceProvider(webkit_glue::NetResourceProvider); + + // Load and initialize the stats table. Attempt to construct a somewhat + // unique name to isolate separate instances from each other. + statstable_ = new StatsTable( + kStatsFilePrefix + Uint64ToString(base::RandUint64()), + kStatsFileThreads, + kStatsFileCounters); + StatsTable::set_current(statstable_); + + // CEF always exposes the GC. + webkit_glue::SetJavaScriptFlags(L"--expose-gc"); + // Expose GCController to JavaScript. + WebKit::registerExtension(extensions_v8::GCExtension::Get()); + + return true; +} + +void CefContext::DoUninitialize() +{ + // Flush any remaining messages. This ensures that any accumulated + // Task objects get destroyed before we exit, which avoids noise in + // purify leak-test results. + MessageLoop::current()->RunAllPending(); + + BrowserResourceLoaderBridge::Shutdown(); + + // Tear down the shared StatsTable. + StatsTable::set_current(NULL); + delete statstable_; + statstable_ = NULL; + + // Shut down WebKit. + delete webkit_init_; + webkit_init_ = NULL; + + // Uninitialize COM stuff + OleUninitialize(); + + // Uninitialize common controls + CoUninitialize(); +} + +DWORD WINAPI ThreadHandlerUI(LPVOID lpParam) +{ + CefContext *pContext = static_cast(lpParam); + + if (!pContext->DoInitialize()) + return 1; + + // Instantiate the message loop for this thread. + MessageLoopForUI main_message_loop; + pContext->SetMessageLoopForUI(&main_message_loop); + + // Notify the context that initialization is complete so that the + // Initialize() function can return. + pContext->NotifyEvent(); + + // Execute the message loop that will run until a quit task is received. + MessageLoop::current()->Run(); + + pContext->DoUninitialize(); + + return 0; +} + +CefContext::CefContext() +{ + hthreadui_ = NULL; + idthreadui_ = 0; + heventui_ = NULL; + messageloopui_ = NULL; + in_transition_ = false; + webprefs_ = NULL; + hinstance_ = ::GetModuleHandle(NULL); + next_browser_id_ = 1; + webkit_init_ = NULL; +} + +CefContext::~CefContext() +{ + // Just in case CefShutdown() isn't called + Shutdown(); +} + bool CefContext::Initialize(bool multi_threaded_message_loop, - const std::wstring& cache_path) -{ - bool initialized = false, intransition = false; - - Lock(); - - // We only need to initialize if the UI thread is not currently running - if(!idthreadui_) { - // Only start the initialization if we're not currently in a transitional - // state - intransition = in_transition_; - if(!intransition) { - // We are now in a transitional state - in_transition_ = true; - - cache_path_ = cache_path; - - // Register the window class - WNDCLASSEX wcex = { - /* cbSize = */ sizeof(WNDCLASSEX), - /* style = */ CS_HREDRAW | CS_VREDRAW, - /* lpfnWndProc = */ CefBrowserImpl::WndProc, - /* cbClsExtra = */ 0, - /* cbWndExtra = */ 0, - /* hInstance = */ hinstance_, - /* hIcon = */ NULL, - /* hCursor = */ LoadCursor(NULL, IDC_ARROW), - /* hbrBackground = */ 0, - /* lpszMenuName = */ NULL, - /* lpszClassName = */ CefBrowserImpl::GetWndClass(), - /* hIconSm = */ NULL, - }; - RegisterClassEx(&wcex); - -#ifndef _DEBUG - // Only log error messages and above in release build. - logging::SetMinLogLevel(logging::LOG_ERROR); -#endif - - // Initialize web preferences - webprefs_ = new WebPreferences; - *webprefs_ = WebPreferences(); - webprefs_->standard_font_family = L"Times"; - webprefs_->fixed_font_family = L"Courier"; - webprefs_->serif_font_family = L"Times"; - webprefs_->sans_serif_font_family = L"Helvetica"; - // These two fonts are picked from the intersection of - // Win XP font list and Vista font list : - // http://www.microsoft.com/typography/fonts/winxp.htm - // http://blogs.msdn.com/michkap/archive/2006/04/04/567881.aspx - // Some of them are installed only with CJK and complex script - // support enabled on Windows XP and are out of consideration here. - // (although we enabled both on our buildbots.) - // They (especially Impact for fantasy) are not typical cursive - // and fantasy fonts, but it should not matter for layout tests - // as long as they're available. -#if defined(OS_MACOSX) - webprefs_->cursive_font_family = L"Apple Chancery"; - webprefs_->fantasy_font_family = L"Papyrus"; -#else - webprefs_->cursive_font_family = L"Comic Sans MS"; - webprefs_->fantasy_font_family = L"Impact"; -#endif - webprefs_->default_encoding = L"ISO-8859-1"; - webprefs_->default_font_size = 16; - webprefs_->default_fixed_font_size = 13; - webprefs_->minimum_font_size = 1; - webprefs_->minimum_logical_font_size = 9; - webprefs_->javascript_can_open_windows_automatically = true; - webprefs_->dom_paste_enabled = true; - webprefs_->developer_extras_enabled = true; - webprefs_->shrinks_standalone_images_to_fit = false; - webprefs_->uses_universal_detector = false; - webprefs_->text_areas_are_resizable = true; - webprefs_->java_enabled = true; - webprefs_->allow_scripts_to_close_windows = false; - webprefs_->xss_auditor_enabled = false; - - if (multi_threaded_message_loop) { - // Event that will be used to signal thread setup completion. Start - // in non-signaled mode so that the event will block. - heventui_ = CreateEvent(NULL, TRUE, FALSE, NULL); - DCHECK(heventui_ != NULL); - - // Thread that hosts the UI loop - hthreadui_ = CreateThread( - NULL, 0, ThreadHandlerUI, this, 0, &idthreadui_); - DCHECK(hthreadui_ != NULL); - DCHECK(idthreadui_ != 0); - } else { - if (!DoInitialize()) { - // TODO: Process initialization errors - } - // Create our own message loop there - SetMessageLoopForUI(new CefMessageLoopForUI()); - idthreadui_ = GetCurrentThreadId(); - DCHECK(idthreadui_ != 0); - } - - initialized = true; - } - } - - Unlock(); - - if(initialized) { - if (multi_threaded_message_loop) { - // Wait for initial UI thread setup to complete - WaitForSingleObject(heventui_, INFINITE); - } - - Lock(); - - // We have exited the transitional state - in_transition_ = false; - - Unlock(); - } - - return intransition ? false : true; -} - -void CefContext::Shutdown() -{ - bool shutdown = false, intransition = false; - - Lock(); - - // We only need to shut down if the UI thread is currently running - if(idthreadui_) { - // Only start the shutdown if we're not currently in a transitional state - intransition = in_transition_; - if(!intransition) { - DCHECK(messageloopui_ != NULL); - - // We are now in a transitional state - in_transition_ = true; - - if(browserlist_.size() > 0) - browserlist_.clear(); - - if(webprefs_) { - delete webprefs_; - webprefs_ = NULL; - } - - // Post the quit message to the UI message loop - messageloopui_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); - - shutdown = true; - } - } - - Unlock(); - - if(shutdown) { - if (hthreadui_) { - // Wait for the UI thread to exit - WaitForSingleObject(hthreadui_, INFINITE); - - // Clean up thread and event handles - CloseHandle(hthreadui_); - CloseHandle(heventui_); - - hthreadui_ = NULL; - heventui_ = NULL; - } else { - DoUninitialize(); - } - - Lock(); - - // Unregister the window class - UnregisterClass(CefBrowserImpl::GetWndClass(), hinstance_); - - idthreadui_ = 0; - messageloopui_ = NULL; - - // We have exited the transitional state - in_transition_ = false; - - Unlock(); - } -} - + const std::wstring& cache_path) +{ + bool initialized = false, intransition = false; + + Lock(); + + // We only need to initialize if the UI thread is not currently running + if(!idthreadui_) { + // Only start the initialization if we're not currently in a transitional + // state + intransition = in_transition_; + if(!intransition) { + // We are now in a transitional state + in_transition_ = true; + + cache_path_ = cache_path; + + // Register the window class + WNDCLASSEX wcex = { + /* cbSize = */ sizeof(WNDCLASSEX), + /* style = */ CS_HREDRAW | CS_VREDRAW, + /* lpfnWndProc = */ CefBrowserImpl::WndProc, + /* cbClsExtra = */ 0, + /* cbWndExtra = */ 0, + /* hInstance = */ hinstance_, + /* hIcon = */ NULL, + /* hCursor = */ LoadCursor(NULL, IDC_ARROW), + /* hbrBackground = */ 0, + /* lpszMenuName = */ NULL, + /* lpszClassName = */ CefBrowserImpl::GetWndClass(), + /* hIconSm = */ NULL, + }; + RegisterClassEx(&wcex); + +#ifndef _DEBUG + // Only log error messages and above in release build. + logging::SetMinLogLevel(logging::LOG_ERROR); +#endif + + // Initialize web preferences + webprefs_ = new WebPreferences; + *webprefs_ = WebPreferences(); + webprefs_->standard_font_family = L"Times"; + webprefs_->fixed_font_family = L"Courier"; + webprefs_->serif_font_family = L"Times"; + webprefs_->sans_serif_font_family = L"Helvetica"; + // These two fonts are picked from the intersection of + // Win XP font list and Vista font list : + // http://www.microsoft.com/typography/fonts/winxp.htm + // http://blogs.msdn.com/michkap/archive/2006/04/04/567881.aspx + // Some of them are installed only with CJK and complex script + // support enabled on Windows XP and are out of consideration here. + // (although we enabled both on our buildbots.) + // They (especially Impact for fantasy) are not typical cursive + // and fantasy fonts, but it should not matter for layout tests + // as long as they're available. +#if defined(OS_MACOSX) + webprefs_->cursive_font_family = L"Apple Chancery"; + webprefs_->fantasy_font_family = L"Papyrus"; +#else + webprefs_->cursive_font_family = L"Comic Sans MS"; + webprefs_->fantasy_font_family = L"Impact"; +#endif + webprefs_->default_encoding = L"ISO-8859-1"; + webprefs_->default_font_size = 16; + webprefs_->default_fixed_font_size = 13; + webprefs_->minimum_font_size = 1; + webprefs_->minimum_logical_font_size = 9; + webprefs_->javascript_can_open_windows_automatically = true; + webprefs_->dom_paste_enabled = true; + webprefs_->developer_extras_enabled = true; + webprefs_->shrinks_standalone_images_to_fit = false; + webprefs_->uses_universal_detector = false; + webprefs_->text_areas_are_resizable = true; + webprefs_->java_enabled = true; + webprefs_->allow_scripts_to_close_windows = false; + webprefs_->xss_auditor_enabled = false; + + if (multi_threaded_message_loop) { + // Event that will be used to signal thread setup completion. Start + // in non-signaled mode so that the event will block. + heventui_ = CreateEvent(NULL, TRUE, FALSE, NULL); + DCHECK(heventui_ != NULL); + + // Thread that hosts the UI loop + hthreadui_ = CreateThread( + NULL, 0, ThreadHandlerUI, this, 0, &idthreadui_); + DCHECK(hthreadui_ != NULL); + DCHECK(idthreadui_ != 0); + } else { + if (!DoInitialize()) { + // TODO: Process initialization errors + } + // Create our own message loop there + SetMessageLoopForUI(new CefMessageLoopForUI()); + idthreadui_ = GetCurrentThreadId(); + DCHECK(idthreadui_ != 0); + } + + initialized = true; + } + } + + Unlock(); + + if(initialized) { + if (multi_threaded_message_loop) { + // Wait for initial UI thread setup to complete + WaitForSingleObject(heventui_, INFINITE); + } + + Lock(); + + // We have exited the transitional state + in_transition_ = false; + + Unlock(); + } + + return intransition ? false : true; +} + +void CefContext::Shutdown() +{ + bool shutdown = false, intransition = false; + + Lock(); + + // We only need to shut down if the UI thread is currently running + if(idthreadui_) { + // Only start the shutdown if we're not currently in a transitional state + intransition = in_transition_; + if(!intransition) { + DCHECK(messageloopui_ != NULL); + + // We are now in a transitional state + in_transition_ = true; + + if(browserlist_.size() > 0) + browserlist_.clear(); + + if(webprefs_) { + delete webprefs_; + webprefs_ = NULL; + } + + // Post the quit message to the UI message loop + messageloopui_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); + + shutdown = true; + } + } + + Unlock(); + + if(shutdown) { + if (hthreadui_) { + // Wait for the UI thread to exit + WaitForSingleObject(hthreadui_, INFINITE); + + // Clean up thread and event handles + CloseHandle(hthreadui_); + CloseHandle(heventui_); + + hthreadui_ = NULL; + heventui_ = NULL; + } else { + DoUninitialize(); + } + + Lock(); + + // Unregister the window class + UnregisterClass(CefBrowserImpl::GetWndClass(), hinstance_); + + idthreadui_ = 0; + messageloopui_ = NULL; + + // We have exited the transitional state + in_transition_ = false; + + Unlock(); + } +} + bool CefContext::AddBrowser(CefRefPtr browser) { bool found = false; @@ -462,12 +462,12 @@ bool CefContext::AddBrowser(CefRefPtr browser) Lock(); // check that the browser isn't already in the list before adding - BrowserList::const_iterator it = browserlist_.begin(); - for(; it != browserlist_.end(); ++it) { - if(it->get() == browser.get()) { - found = true; - break; - } + BrowserList::const_iterator it = browserlist_.begin(); + for(; it != browserlist_.end(); ++it) { + if(it->get() == browser.get()) { + found = true; + break; + } } if(!found) @@ -480,64 +480,64 @@ bool CefContext::AddBrowser(CefRefPtr browser) return !found; } -bool CefContext::RemoveBrowser(CefRefPtr browser) -{ - bool deleted = false; - - Lock(); - - BrowserList::iterator it = browserlist_.begin(); - for(; it != browserlist_.end(); ++it) { - if(it->get() == browser.get()) { - browserlist_.erase(it); - deleted = true; - break; - } - } - - if (browserlist_.empty()) - next_browser_id_ = 1; - - Unlock(); - - return deleted; -} - -CefRefPtr CefContext::GetBrowserByID(int id) -{ - CefRefPtr browser; - Lock(); - - BrowserList::const_iterator it = browserlist_.begin(); - for(; it != browserlist_.end(); ++it) { - if(it->get()->UIT_GetUniqueID() == id) { - browser = it->get(); - break; - } - } - - Unlock(); - - return browser; -} - -void CefContext::SetMessageLoopForUI(MessageLoopForUI* loop) -{ - Lock(); - messageloopui_ = loop; - Unlock(); -} - -void CefContext::NotifyEvent() -{ - Lock(); - // Set the event state to signaled so that the waiting thread will be - // released. - if(heventui_) - SetEvent(heventui_); - Unlock(); -} - +bool CefContext::RemoveBrowser(CefRefPtr browser) +{ + bool deleted = false; + + Lock(); + + BrowserList::iterator it = browserlist_.begin(); + for(; it != browserlist_.end(); ++it) { + if(it->get() == browser.get()) { + browserlist_.erase(it); + deleted = true; + break; + } + } + + if (browserlist_.empty()) + next_browser_id_ = 1; + + Unlock(); + + return deleted; +} + +CefRefPtr CefContext::GetBrowserByID(int id) +{ + CefRefPtr browser; + Lock(); + + BrowserList::const_iterator it = browserlist_.begin(); + for(; it != browserlist_.end(); ++it) { + if(it->get()->UIT_GetUniqueID() == id) { + browser = it->get(); + break; + } + } + + Unlock(); + + return browser; +} + +void CefContext::SetMessageLoopForUI(MessageLoopForUI* loop) +{ + Lock(); + messageloopui_ = loop; + Unlock(); +} + +void CefContext::NotifyEvent() +{ + Lock(); + // Set the event state to signaled so that the waiting thread will be + // released. + if(heventui_) + SetEvent(heventui_); + Unlock(); +} + void PostTask(const tracked_objects::Location& from_here, Task* task) { if(_Context.get()) { @@ -547,4 +547,4 @@ void PostTask(const tracked_objects::Location& from_here, Task* task) pMsgLoop->PostTask(from_here, task); _Context->Unlock(); } -} +} diff --git a/libcef/context.h b/libcef/context.h index 338b779ac..4f07fdfc3 100644 --- a/libcef/context.h +++ b/libcef/context.h @@ -1,20 +1,20 @@ -// 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. - +// 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. + #ifndef _CONTEXT_H #define _CONTEXT_H #include "../include/cef.h" #include "base/at_exit.h" -#include "base/message_loop.h" -#include "base/stats_table.h" -#include "base/gfx/native_widget_types.h" +#include "base/message_loop.h" +#include "base/stats_table.h" +#include "base/gfx/native_widget_types.h" #include "webkit/glue/webpreferences.h" - -class BrowserWebKitInit; -class CefBrowserImpl; + +class BrowserWebKitInit; +class CefBrowserImpl; class CefContext : public CefThreadSafeBase { @@ -54,10 +54,10 @@ public: void UIT_RegisterPlugin(struct CefPluginInfo* plugin_info); void UIT_UnregisterPlugin(struct CefPluginInfo* plugin_info); - bool DoWork(); - bool DoDelayedWork(); - bool DoIdleWork(); - + bool DoWork(); + bool DoDelayedWork(); + bool DoIdleWork(); + private: void SetMessageLoopForUI(MessageLoopForUI* loop); void NotifyEvent(); @@ -97,4 +97,4 @@ extern CefRefPtr _Context; // Macro for requiring that a function be called on the UI thread #define REQUIRE_UIT() DCHECK(_Context->RunningOnUIThread()) -#endif // _CONTEXT_H +#endif // _CONTEXT_H diff --git a/libcef/libcef.vsprops b/libcef/libcef.vsprops index 2ddf2a8ff..526a4f144 100644 --- a/libcef/libcef.vsprops +++ b/libcef/libcef.vsprops @@ -1,22 +1,22 @@ - - - - - - + + + + + + diff --git a/libcef/libcef_webkit.vsprops b/libcef/libcef_webkit.vsprops index 0ce62e95b..df683e332 100644 --- a/libcef/libcef_webkit.vsprops +++ b/libcef/libcef_webkit.vsprops @@ -1,8 +1,8 @@ - - - + + + diff --git a/libcef/precompiled_libcef.cc b/libcef/precompiled_libcef.cc index 68f617b69..a2390c777 100644 --- a/libcef/precompiled_libcef.cc +++ b/libcef/precompiled_libcef.cc @@ -1,5 +1,5 @@ -// Copyright (c) 2008 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 "precompiled_libcef.h" +// Copyright (c) 2008 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 "precompiled_libcef.h" diff --git a/libcef/precompiled_libcef.h b/libcef/precompiled_libcef.h index 7bb370ac4..e2301ce89 100644 --- a/libcef/precompiled_libcef.h +++ b/libcef/precompiled_libcef.h @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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 -#include +// Copyright (c) 2008 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 +#include diff --git a/libcef/printing/print_settings.cc b/libcef/printing/print_settings.cc index 04bebf641..d3ed25020 100644 --- a/libcef/printing/print_settings.cc +++ b/libcef/printing/print_settings.cc @@ -1,138 +1,138 @@ -// 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 "precompiled_libcef.h" -#include "print_settings.h" - -#include "base/atomic_sequence_num.h" -#include "base/logging.h" -#include "printing/units.h" - -namespace printing { - -// Global SequenceNumber used for generating unique cookie values. -static base::AtomicSequenceNumber cookie_seq(base::LINKER_INITIALIZED); - -PrintSettings::PrintSettings() - : min_shrink(1.25), - max_shrink(2.0), - desired_dpi(72), - selection_only(false), - to_file(false), - dpi_(0), - landscape_(false) { -} - -void PrintSettings::Clear() { - ranges.clear(); - min_shrink = 1.25; - max_shrink = 2.; - desired_dpi = 72; - selection_only = false; - to_file = false; - printer_name_.clear(); - device_name_.clear(); - page_setup_pixels_.Clear(); - dpi_ = 0; - landscape_ = false; -} - -#ifdef WIN32 -void PrintSettings::Init(HDC hdc, - const DEVMODE& dev_mode, - const PageRanges& new_ranges, - const std::wstring& new_device_name, - bool print_selection_only, - bool print_to_file) { - DCHECK(hdc); - printer_name_ = dev_mode.dmDeviceName; - device_name_ = new_device_name; - ranges = new_ranges; - landscape_ = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; - selection_only = print_selection_only; - to_file = print_to_file; - - dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); - // No printer device is known to advertise different dpi in X and Y axis; even - // the fax device using the 200x100 dpi setting. It's ought to break so many - // applications that it's not even needed to care about. WebKit doesn't - // support different dpi settings in X and Y axis. - DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); - - DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); - DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); - - // Initialize page_setup_pixels_. - gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), - GetDeviceCaps(hdc, PHYSICALHEIGHT)); - gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), - GetDeviceCaps(hdc, PHYSICALOFFSETY), - GetDeviceCaps(hdc, HORZRES), - GetDeviceCaps(hdc, VERTRES)); - - SetPrinterPrintableArea(physical_size_pixels, printable_area_pixels); -} -#endif - -void PrintSettings::SetPrinterPrintableArea( - gfx::Size const& physical_size_pixels, - gfx::Rect const& printable_area_pixels) { - - int margin_printer_units = ConvertUnit(500, kHundrethsMMPerInch, dpi_); - - // Start by setting the user configuration - // Hard-code text_height = 0.5cm = ~1/5 of inch - page_setup_pixels_.Init(physical_size_pixels, - printable_area_pixels, - margin_printer_units); - - // Now apply user configured settings. - PageMargins margins; - margins.header = margin_printer_units; - margins.footer = margin_printer_units; - margins.left = margin_printer_units; - margins.top = margin_printer_units; - margins.right = margin_printer_units; - margins.bottom = margin_printer_units; - page_setup_pixels_.SetRequestedMargins(margins); -} - -void PrintSettings::RenderParams(PrintParams* params) const { - DCHECK(params); - params->printable_size.SetSize(page_setup_pixels_.content_area().width(), - page_setup_pixels_.content_area().height()); - params->dpi = dpi_; - // Currently hardcoded at 1.25. See PrintSettings' constructor. - params->min_shrink = min_shrink; - // Currently hardcoded at 2.0. See PrintSettings' constructor. - params->max_shrink = max_shrink; - // Currently hardcoded at 72dpi. See PrintSettings' constructor. - params->desired_dpi = desired_dpi; - // Always use an invalid cookie. - params->document_cookie = 0; - params->selection_only = selection_only; - params->to_file = to_file; -} - -bool PrintSettings::Equals(const PrintSettings& rhs) const { - // Do not test the display device name (printer_name_) for equality since it - // may sometimes be chopped off at 30 chars. As long as device_name is the - // same, that's fine. - return ranges == rhs.ranges && - min_shrink == rhs.min_shrink && - max_shrink == rhs.max_shrink && - desired_dpi == rhs.desired_dpi && - device_name_ == rhs.device_name_ && - page_setup_pixels_.Equals(rhs.page_setup_pixels_) && - dpi_ == rhs.dpi_ && - landscape_ == rhs.landscape_; -} - -int PrintSettings::NewCookie() { - // A cookie of 0 is used to mark a document as unassigned, count from 1. - return cookie_seq.GetNext() + 1; -} - -} // namespace printing - +// 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 "precompiled_libcef.h" +#include "print_settings.h" + +#include "base/atomic_sequence_num.h" +#include "base/logging.h" +#include "printing/units.h" + +namespace printing { + +// Global SequenceNumber used for generating unique cookie values. +static base::AtomicSequenceNumber cookie_seq(base::LINKER_INITIALIZED); + +PrintSettings::PrintSettings() + : min_shrink(1.25), + max_shrink(2.0), + desired_dpi(72), + selection_only(false), + to_file(false), + dpi_(0), + landscape_(false) { +} + +void PrintSettings::Clear() { + ranges.clear(); + min_shrink = 1.25; + max_shrink = 2.; + desired_dpi = 72; + selection_only = false; + to_file = false; + printer_name_.clear(); + device_name_.clear(); + page_setup_pixels_.Clear(); + dpi_ = 0; + landscape_ = false; +} + +#ifdef WIN32 +void PrintSettings::Init(HDC hdc, + const DEVMODE& dev_mode, + const PageRanges& new_ranges, + const std::wstring& new_device_name, + bool print_selection_only, + bool print_to_file) { + DCHECK(hdc); + printer_name_ = dev_mode.dmDeviceName; + device_name_ = new_device_name; + ranges = new_ranges; + landscape_ = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; + selection_only = print_selection_only; + to_file = print_to_file; + + dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); + // No printer device is known to advertise different dpi in X and Y axis; even + // the fax device using the 200x100 dpi setting. It's ought to break so many + // applications that it's not even needed to care about. WebKit doesn't + // support different dpi settings in X and Y axis. + DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); + + DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); + DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); + + // Initialize page_setup_pixels_. + gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), + GetDeviceCaps(hdc, PHYSICALHEIGHT)); + gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), + GetDeviceCaps(hdc, PHYSICALOFFSETY), + GetDeviceCaps(hdc, HORZRES), + GetDeviceCaps(hdc, VERTRES)); + + SetPrinterPrintableArea(physical_size_pixels, printable_area_pixels); +} +#endif + +void PrintSettings::SetPrinterPrintableArea( + gfx::Size const& physical_size_pixels, + gfx::Rect const& printable_area_pixels) { + + int margin_printer_units = ConvertUnit(500, kHundrethsMMPerInch, dpi_); + + // Start by setting the user configuration + // Hard-code text_height = 0.5cm = ~1/5 of inch + page_setup_pixels_.Init(physical_size_pixels, + printable_area_pixels, + margin_printer_units); + + // Now apply user configured settings. + PageMargins margins; + margins.header = margin_printer_units; + margins.footer = margin_printer_units; + margins.left = margin_printer_units; + margins.top = margin_printer_units; + margins.right = margin_printer_units; + margins.bottom = margin_printer_units; + page_setup_pixels_.SetRequestedMargins(margins); +} + +void PrintSettings::RenderParams(PrintParams* params) const { + DCHECK(params); + params->printable_size.SetSize(page_setup_pixels_.content_area().width(), + page_setup_pixels_.content_area().height()); + params->dpi = dpi_; + // Currently hardcoded at 1.25. See PrintSettings' constructor. + params->min_shrink = min_shrink; + // Currently hardcoded at 2.0. See PrintSettings' constructor. + params->max_shrink = max_shrink; + // Currently hardcoded at 72dpi. See PrintSettings' constructor. + params->desired_dpi = desired_dpi; + // Always use an invalid cookie. + params->document_cookie = 0; + params->selection_only = selection_only; + params->to_file = to_file; +} + +bool PrintSettings::Equals(const PrintSettings& rhs) const { + // Do not test the display device name (printer_name_) for equality since it + // may sometimes be chopped off at 30 chars. As long as device_name is the + // same, that's fine. + return ranges == rhs.ranges && + min_shrink == rhs.min_shrink && + max_shrink == rhs.max_shrink && + desired_dpi == rhs.desired_dpi && + device_name_ == rhs.device_name_ && + page_setup_pixels_.Equals(rhs.page_setup_pixels_) && + dpi_ == rhs.dpi_ && + landscape_ == rhs.landscape_; +} + +int PrintSettings::NewCookie() { + // A cookie of 0 is used to mark a document as unassigned, count from 1. + return cookie_seq.GetNext() + 1; +} + +} // namespace printing + diff --git a/libcef/printing/print_settings.h b/libcef/printing/print_settings.h index 7030e6bf2..b61a1c317 100644 --- a/libcef/printing/print_settings.h +++ b/libcef/printing/print_settings.h @@ -1,150 +1,150 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef _PRINTING_PRINT_SETTINGS_H -#define _PRINTING_PRINT_SETTINGS_H - -#include "base/gfx/rect.h" -#include "printing/page_range.h" -#include "printing/page_setup.h" - -typedef struct HDC__* HDC; -typedef struct _devicemodeW DEVMODE; - -namespace printing { - -// Parameters for a render request. -struct PrintParams { - // In pixels according to dpi_x and dpi_y. - gfx::Size printable_size; - - // Specifies dots per inch. - double dpi; - - // Minimum shrink factor. See PrintSettings::min_shrink for more information. - double min_shrink; - - // Maximum shrink factor. See PrintSettings::max_shrink for more information. - double max_shrink; - - // Desired apparent dpi on paper. - int desired_dpi; - - // Cookie for the document to ensure correctness. - int document_cookie; - - // Indicates if the user only wants to print the current selection. - bool selection_only; - - // Indicates if the user wants to print to file. - bool to_file; - - // Warning: do not compare document_cookie. - bool Equals(const PrintParams& rhs) const { - return printable_size == rhs.printable_size && - dpi == rhs.dpi && - min_shrink == rhs.min_shrink && - max_shrink == rhs.max_shrink && - desired_dpi == rhs.desired_dpi && - selection_only == rhs.selection_only && - to_file == rhs.to_file; - } -}; - -// OS-independent print settings. -class PrintSettings { - public: - PrintSettings(); - - // Reinitialize the settings to the default values. - void Clear(); - -#ifdef WIN32 - // Reads the settings from the selected device context. Calculates derived - // values like printable_area_. - void Init(HDC hdc, - const DEVMODE& dev_mode, - const PageRanges& new_ranges, - const std::wstring& new_device_name, - bool selection_only, - bool to_file); -#endif - - // Set printer printable area in pixels. - void SetPrinterPrintableArea(gfx::Size const& physical_size_pixels, - gfx::Rect const& printable_area_pixels); - - // Initializes the print parameters that needs to be sent to the renderer - // process. - void RenderParams(PrintParams* params) const; - - // Equality operator. - // NOTE: printer_name is NOT tested for equality since it doesn't affect the - // output. - bool Equals(const PrintSettings& rhs) const; - - const std::wstring& printer_name() const { return printer_name_; } - void set_device_name(const std::wstring& device_name) { - device_name_ = device_name; - } - const std::wstring& device_name() const { return device_name_; } - int dpi() const { return dpi_; } - const PageSetup& page_setup_pixels() const { return page_setup_pixels_; } - - // Multi-page printing. Each PageRange describes a from-to page combination. - // This permits printing selected pages only. - PageRanges ranges; - - // By imaging to a width a little wider than the available pixels, thin pages - // will be scaled down a little, matching the way they print in IE and Camino. - // This lets them use fewer sheets than they would otherwise, which is - // presumably why other browsers do this. Wide pages will be scaled down more - // than this. - double min_shrink; - - // This number determines how small we are willing to reduce the page content - // in order to accommodate the widest line. If the page would have to be - // reduced smaller to make the widest line fit, we just clip instead (this - // behavior matches MacIE and Mozilla, at least) - double max_shrink; - - // Desired visible dots per inch rendering for output. Printing should be - // scaled to ScreenDpi/dpix*desired_dpi. - int desired_dpi; - - // Indicates if the user only wants to print the current selection. - bool selection_only; - - // Indicates if the user wants to print to file. - bool to_file; - - // Cookie generator. It is used to initialize PrintedDocument with its - // associated PrintSettings, to be sure that each generated PrintedPage is - // correctly associated with its corresponding PrintedDocument. - static int NewCookie(); - - private: - ////////////////////////////////////////////////////////////////////////////// - // Settings that can't be changed without side-effects. - - // Printer name as shown to the user. - std::wstring printer_name_; - - // Printer device name as opened by the OS. - std::wstring device_name_; - - // Page setup in pixel units, dpi adjusted. - PageSetup page_setup_pixels_; - - // Printer's device effective dots per inch in both axis. - int dpi_; - - // Is the orientation landscape or portrait. - bool landscape_; -}; - -} // namespace printing - -#endif // _PRINTING_PRINT_SETTINGS_H - +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _PRINTING_PRINT_SETTINGS_H +#define _PRINTING_PRINT_SETTINGS_H + +#include "base/gfx/rect.h" +#include "printing/page_range.h" +#include "printing/page_setup.h" + +typedef struct HDC__* HDC; +typedef struct _devicemodeW DEVMODE; + +namespace printing { + +// Parameters for a render request. +struct PrintParams { + // In pixels according to dpi_x and dpi_y. + gfx::Size printable_size; + + // Specifies dots per inch. + double dpi; + + // Minimum shrink factor. See PrintSettings::min_shrink for more information. + double min_shrink; + + // Maximum shrink factor. See PrintSettings::max_shrink for more information. + double max_shrink; + + // Desired apparent dpi on paper. + int desired_dpi; + + // Cookie for the document to ensure correctness. + int document_cookie; + + // Indicates if the user only wants to print the current selection. + bool selection_only; + + // Indicates if the user wants to print to file. + bool to_file; + + // Warning: do not compare document_cookie. + bool Equals(const PrintParams& rhs) const { + return printable_size == rhs.printable_size && + dpi == rhs.dpi && + min_shrink == rhs.min_shrink && + max_shrink == rhs.max_shrink && + desired_dpi == rhs.desired_dpi && + selection_only == rhs.selection_only && + to_file == rhs.to_file; + } +}; + +// OS-independent print settings. +class PrintSettings { + public: + PrintSettings(); + + // Reinitialize the settings to the default values. + void Clear(); + +#ifdef WIN32 + // Reads the settings from the selected device context. Calculates derived + // values like printable_area_. + void Init(HDC hdc, + const DEVMODE& dev_mode, + const PageRanges& new_ranges, + const std::wstring& new_device_name, + bool selection_only, + bool to_file); +#endif + + // Set printer printable area in pixels. + void SetPrinterPrintableArea(gfx::Size const& physical_size_pixels, + gfx::Rect const& printable_area_pixels); + + // Initializes the print parameters that needs to be sent to the renderer + // process. + void RenderParams(PrintParams* params) const; + + // Equality operator. + // NOTE: printer_name is NOT tested for equality since it doesn't affect the + // output. + bool Equals(const PrintSettings& rhs) const; + + const std::wstring& printer_name() const { return printer_name_; } + void set_device_name(const std::wstring& device_name) { + device_name_ = device_name; + } + const std::wstring& device_name() const { return device_name_; } + int dpi() const { return dpi_; } + const PageSetup& page_setup_pixels() const { return page_setup_pixels_; } + + // Multi-page printing. Each PageRange describes a from-to page combination. + // This permits printing selected pages only. + PageRanges ranges; + + // By imaging to a width a little wider than the available pixels, thin pages + // will be scaled down a little, matching the way they print in IE and Camino. + // This lets them use fewer sheets than they would otherwise, which is + // presumably why other browsers do this. Wide pages will be scaled down more + // than this. + double min_shrink; + + // This number determines how small we are willing to reduce the page content + // in order to accommodate the widest line. If the page would have to be + // reduced smaller to make the widest line fit, we just clip instead (this + // behavior matches MacIE and Mozilla, at least) + double max_shrink; + + // Desired visible dots per inch rendering for output. Printing should be + // scaled to ScreenDpi/dpix*desired_dpi. + int desired_dpi; + + // Indicates if the user only wants to print the current selection. + bool selection_only; + + // Indicates if the user wants to print to file. + bool to_file; + + // Cookie generator. It is used to initialize PrintedDocument with its + // associated PrintSettings, to be sure that each generated PrintedPage is + // correctly associated with its corresponding PrintedDocument. + static int NewCookie(); + + private: + ////////////////////////////////////////////////////////////////////////////// + // Settings that can't be changed without side-effects. + + // Printer name as shown to the user. + std::wstring printer_name_; + + // Printer device name as opened by the OS. + std::wstring device_name_; + + // Page setup in pixel units, dpi adjusted. + PageSetup page_setup_pixels_; + + // Printer's device effective dots per inch in both axis. + int dpi_; + + // Is the orientation landscape or portrait. + bool landscape_; +}; + +} // namespace printing + +#endif // _PRINTING_PRINT_SETTINGS_H + diff --git a/libcef/printing/win_printing_context.cc b/libcef/printing/win_printing_context.cc index 9e59dba79..138b19159 100644 --- a/libcef/printing/win_printing_context.cc +++ b/libcef/printing/win_printing_context.cc @@ -1,175 +1,175 @@ -// 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 "precompiled_libcef.h" -#include "win_printing_context.h" - -#include - -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/time.h" -#include "base/time_format.h" -#include "skia/ext/platform_device_win.h" - -using base::Time; - -namespace { - -// Retrieves the content of a GetPrinter call. -void GetPrinterHelper(HANDLE printer, int level, scoped_array* buffer) { - DWORD buf_size = 0; - GetPrinter(printer, level, NULL, 0, &buf_size); - if (buf_size) { - buffer->reset(new uint8[buf_size]); - memset(buffer->get(), 0, buf_size); - if (!GetPrinter(printer, level, buffer->get(), buf_size, &buf_size)) { - buffer->reset(); - } - } -} - -} // namespace - -namespace printing { - -PrintingContext::PrintingContext() - : hdc_(NULL), -#ifndef NDEBUG - page_number_(-1), -#endif - dialog_box_(NULL), - dialog_box_dismissed_(false), - abort_printing_(false), - in_print_job_(false) { -} - -PrintingContext::~PrintingContext() { - ResetSettings(); -} - -PrintingContext::Result PrintingContext::AskUserForSettings( - HWND window, - int max_pages, - bool has_selection) { - DCHECK(window); - DCHECK(!in_print_job_); - dialog_box_dismissed_ = false; - // Show the OS-dependent dialog box. - // If the user press - // - OK, the settings are reset and reinitialized with the new settings. OK is - // returned. - // - Apply then Cancel, the settings are reset and reinitialized with the new - // settings. CANCEL is returned. - // - Cancel, the settings are not changed, the previous setting, if it was - // initialized before, are kept. CANCEL is returned. - // On failure, the settings are reset and FAILED is returned. - PRINTDLGEX dialog_options = { sizeof(PRINTDLGEX) }; - dialog_options.hwndOwner = window; - // Disable options we don't support currently. - // TODO(maruel): Reuse the previously loaded settings! - dialog_options.Flags = PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE | - PD_NOCURRENTPAGE; - if (!has_selection) - dialog_options.Flags |= PD_NOSELECTION; - - PRINTPAGERANGE ranges[32]; - dialog_options.nStartPage = START_PAGE_GENERAL; - if (max_pages) { - // Default initialize to print all the pages. - memset(ranges, 0, sizeof(ranges)); - ranges[0].nFromPage = 1; - ranges[0].nToPage = max_pages; - dialog_options.nPageRanges = 1; - dialog_options.nMaxPageRanges = arraysize(ranges); - dialog_options.nMinPage = 1; - dialog_options.nMaxPage = max_pages; - dialog_options.lpPageRanges = ranges; - } else { - // No need to bother, we don't know how many pages are available. - dialog_options.Flags |= PD_NOPAGENUMS; - } - - { - if (PrintDlgEx(&dialog_options) != S_OK) { - ResetSettings(); - return FAILED; - } - } - return ParseDialogResultEx(dialog_options); -} - -PrintingContext::Result PrintingContext::UseDefaultSettings() { - DCHECK(!in_print_job_); - - PRINTDLG dialog_options = { sizeof(PRINTDLG) }; - dialog_options.Flags = PD_RETURNDC | PD_RETURNDEFAULT; - if (PrintDlg(&dialog_options) == 0) { - ResetSettings(); - return FAILED; - } - return ParseDialogResult(dialog_options); -} - -PrintingContext::Result PrintingContext::InitWithSettings( - const PrintSettings& settings) { - DCHECK(!in_print_job_); - settings_ = settings; - // TODO(maruel): settings_->ToDEVMODE() - HANDLE printer; - if (!OpenPrinter(const_cast(settings_.device_name().c_str()), - &printer, - NULL)) - return FAILED; - - Result status = OK; - - if (!GetPrinterSettings(printer, settings_.device_name())) - status = FAILED; - - // Close the printer after retrieving the context. - ClosePrinter(printer); - - if (status != OK) - ResetSettings(); - return status; -} - -void PrintingContext::ResetSettings() { - if (hdc_ != NULL) { - DeleteDC(hdc_); - hdc_ = NULL; - } - settings_.Clear(); - in_print_job_ = false; - -#ifndef NDEBUG - page_number_ = -1; -#endif -} - -PrintingContext::Result PrintingContext::NewDocument( - const std::wstring& document_name) { - DCHECK(!in_print_job_); - if (!hdc_) - return OnError(); - - // Set the flag used by the AbortPrintJob dialog procedure. - abort_printing_ = false; - - in_print_job_ = true; - - // Register the application's AbortProc function with GDI. - if (SP_ERROR == SetAbortProc(hdc_, &AbortProc)) - return OnError(); - - DOCINFO di = { sizeof(DOCINFO) }; - di.lpszDocName = document_name.c_str(); - - wchar_t szFileName[MAX_PATH] = L""; - if (settings_.to_file) { - // Prompt for the file name to use for the printed output. +// 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 "precompiled_libcef.h" +#include "win_printing_context.h" + +#include + +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/time.h" +#include "base/time_format.h" +#include "skia/ext/platform_device_win.h" + +using base::Time; + +namespace { + +// Retrieves the content of a GetPrinter call. +void GetPrinterHelper(HANDLE printer, int level, scoped_array* buffer) { + DWORD buf_size = 0; + GetPrinter(printer, level, NULL, 0, &buf_size); + if (buf_size) { + buffer->reset(new uint8[buf_size]); + memset(buffer->get(), 0, buf_size); + if (!GetPrinter(printer, level, buffer->get(), buf_size, &buf_size)) { + buffer->reset(); + } + } +} + +} // namespace + +namespace printing { + +PrintingContext::PrintingContext() + : hdc_(NULL), +#ifndef NDEBUG + page_number_(-1), +#endif + dialog_box_(NULL), + dialog_box_dismissed_(false), + abort_printing_(false), + in_print_job_(false) { +} + +PrintingContext::~PrintingContext() { + ResetSettings(); +} + +PrintingContext::Result PrintingContext::AskUserForSettings( + HWND window, + int max_pages, + bool has_selection) { + DCHECK(window); + DCHECK(!in_print_job_); + dialog_box_dismissed_ = false; + // Show the OS-dependent dialog box. + // If the user press + // - OK, the settings are reset and reinitialized with the new settings. OK is + // returned. + // - Apply then Cancel, the settings are reset and reinitialized with the new + // settings. CANCEL is returned. + // - Cancel, the settings are not changed, the previous setting, if it was + // initialized before, are kept. CANCEL is returned. + // On failure, the settings are reset and FAILED is returned. + PRINTDLGEX dialog_options = { sizeof(PRINTDLGEX) }; + dialog_options.hwndOwner = window; + // Disable options we don't support currently. + // TODO(maruel): Reuse the previously loaded settings! + dialog_options.Flags = PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE | + PD_NOCURRENTPAGE; + if (!has_selection) + dialog_options.Flags |= PD_NOSELECTION; + + PRINTPAGERANGE ranges[32]; + dialog_options.nStartPage = START_PAGE_GENERAL; + if (max_pages) { + // Default initialize to print all the pages. + memset(ranges, 0, sizeof(ranges)); + ranges[0].nFromPage = 1; + ranges[0].nToPage = max_pages; + dialog_options.nPageRanges = 1; + dialog_options.nMaxPageRanges = arraysize(ranges); + dialog_options.nMinPage = 1; + dialog_options.nMaxPage = max_pages; + dialog_options.lpPageRanges = ranges; + } else { + // No need to bother, we don't know how many pages are available. + dialog_options.Flags |= PD_NOPAGENUMS; + } + + { + if (PrintDlgEx(&dialog_options) != S_OK) { + ResetSettings(); + return FAILED; + } + } + return ParseDialogResultEx(dialog_options); +} + +PrintingContext::Result PrintingContext::UseDefaultSettings() { + DCHECK(!in_print_job_); + + PRINTDLG dialog_options = { sizeof(PRINTDLG) }; + dialog_options.Flags = PD_RETURNDC | PD_RETURNDEFAULT; + if (PrintDlg(&dialog_options) == 0) { + ResetSettings(); + return FAILED; + } + return ParseDialogResult(dialog_options); +} + +PrintingContext::Result PrintingContext::InitWithSettings( + const PrintSettings& settings) { + DCHECK(!in_print_job_); + settings_ = settings; + // TODO(maruel): settings_->ToDEVMODE() + HANDLE printer; + if (!OpenPrinter(const_cast(settings_.device_name().c_str()), + &printer, + NULL)) + return FAILED; + + Result status = OK; + + if (!GetPrinterSettings(printer, settings_.device_name())) + status = FAILED; + + // Close the printer after retrieving the context. + ClosePrinter(printer); + + if (status != OK) + ResetSettings(); + return status; +} + +void PrintingContext::ResetSettings() { + if (hdc_ != NULL) { + DeleteDC(hdc_); + hdc_ = NULL; + } + settings_.Clear(); + in_print_job_ = false; + +#ifndef NDEBUG + page_number_ = -1; +#endif +} + +PrintingContext::Result PrintingContext::NewDocument( + const std::wstring& document_name) { + DCHECK(!in_print_job_); + if (!hdc_) + return OnError(); + + // Set the flag used by the AbortPrintJob dialog procedure. + abort_printing_ = false; + + in_print_job_ = true; + + // Register the application's AbortProc function with GDI. + if (SP_ERROR == SetAbortProc(hdc_, &AbortProc)) + return OnError(); + + DOCINFO di = { sizeof(DOCINFO) }; + di.lpszDocName = document_name.c_str(); + + wchar_t szFileName[MAX_PATH] = L""; + if (settings_.to_file) { + // Prompt for the file name to use for the printed output. OPENFILENAME ofn = { sizeof(ofn) }; ofn.lpstrFilter = L"PostScript Files (*.ps)\0*.ps\0All Files (*.*)\0*.*\0"; @@ -181,336 +181,336 @@ PrintingContext::Result PrintingContext::NewDocument( if(GetSaveFileName(&ofn)) di.lpszOutput = szFileName; - else - return OnError(); - } - - DCHECK_EQ(MessageLoop::current()->NestableTasksAllowed(), false); - // Begin a print job by calling the StartDoc function. - // NOTE: StartDoc() starts a message loop. That causes a lot of problems with - // IPC. Make sure recursive task processing is disabled. - if (StartDoc(hdc_, &di) <= 0) - return OnError(); - -#ifndef NDEBUG - page_number_ = 0; -#endif - return OK; -} - -PrintingContext::Result PrintingContext::NewPage() { - if (abort_printing_) - return CANCEL; - DCHECK(in_print_job_); - - // Inform the driver that the application is about to begin sending data. - if (StartPage(hdc_) <= 0) - return OnError(); - -#ifndef NDEBUG - ++page_number_; -#endif - - return OK; -} - -PrintingContext::Result PrintingContext::PageDone() { - if (abort_printing_) - return CANCEL; - DCHECK(in_print_job_); - - if (EndPage(hdc_) <= 0) - return OnError(); - return OK; -} - -PrintingContext::Result PrintingContext::DocumentDone() { - if (abort_printing_) - return CANCEL; - DCHECK(in_print_job_); - - // Inform the driver that document has ended. - if (EndDoc(hdc_) <= 0) - return OnError(); - - ResetSettings(); - return OK; -} - -void PrintingContext::Cancel() { - abort_printing_ = true; - in_print_job_ = false; - if (hdc_) - CancelDC(hdc_); - DismissDialog(); -} - -void PrintingContext::DismissDialog() { - if (dialog_box_) { - DestroyWindow(dialog_box_); - dialog_box_dismissed_ = true; - } -} - -PrintingContext::Result PrintingContext::OnError() { - // This will close hdc_ and clear settings_. - ResetSettings(); - return abort_printing_ ? CANCEL : FAILED; -} - -// static -BOOL PrintingContext::AbortProc(HDC hdc, int nCode) { - if (nCode) { - // TODO(maruel): Need a way to find the right instance to set. Should - // leverage PrintJobManager here? - // abort_printing_ = true; - } - return true; -} - -bool PrintingContext::InitializeSettings(const DEVMODE& dev_mode, - const std::wstring& new_device_name, - const PRINTPAGERANGE* ranges, - int number_ranges, - bool selection_only, - bool to_file) { - skia::PlatformDevice::InitializeDC(hdc_); - DCHECK(GetDeviceCaps(hdc_, CLIPCAPS)); - DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_STRETCHDIB); - DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_BITMAP64); - // Some printers don't advertise these. - // DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_SCALING); - // DCHECK(GetDeviceCaps(hdc_, SHADEBLENDCAPS) & SB_CONST_ALPHA); - // DCHECK(GetDeviceCaps(hdc_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA); - - // StretchDIBits() support is needed for printing. - if (!(GetDeviceCaps(hdc_, RASTERCAPS) & RC_STRETCHDIB) || - !(GetDeviceCaps(hdc_, RASTERCAPS) & RC_BITMAP64)) { - NOTREACHED(); - ResetSettings(); - return false; - } - - DCHECK(!in_print_job_); - DCHECK(hdc_); - PageRanges ranges_vector; - if (!selection_only) { - // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector. - ranges_vector.reserve(number_ranges); - for (int i = 0; i < number_ranges; ++i) { - PageRange range; - // Transfer from 1-based to 0-based. - range.from = ranges[i].nFromPage - 1; - range.to = ranges[i].nToPage - 1; - ranges_vector.push_back(range); - } - } - settings_.Init(hdc_, - dev_mode, - ranges_vector, - new_device_name, - selection_only, - to_file); - return true; -} - -bool PrintingContext::GetPrinterSettings(HANDLE printer, - const std::wstring& device_name) { - DCHECK(!in_print_job_); - scoped_array buffer; - - // A PRINTER_INFO_9 structure specifying the per-user default printer - // settings. - GetPrinterHelper(printer, 9, &buffer); - if (buffer.get()) { - PRINTER_INFO_9* info_9 = reinterpret_cast(buffer.get()); - if (info_9->pDevMode != NULL) { - if (!AllocateContext(device_name, info_9->pDevMode)) { - ResetSettings(); - return false; - } - return InitializeSettings(*info_9->pDevMode, device_name, NULL, 0, false, - false); - } - buffer.reset(); - } - - // A PRINTER_INFO_8 structure specifying the global default printer settings. - GetPrinterHelper(printer, 8, &buffer); - if (buffer.get()) { - PRINTER_INFO_8* info_8 = reinterpret_cast(buffer.get()); - if (info_8->pDevMode != NULL) { - if (!AllocateContext(device_name, info_8->pDevMode)) { - ResetSettings(); - return false; - } - return InitializeSettings(*info_8->pDevMode, device_name, NULL, 0, false, - false); - } - buffer.reset(); - } - - // A PRINTER_INFO_2 structure specifying the driver's default printer - // settings. - GetPrinterHelper(printer, 2, &buffer); - if (buffer.get()) { - PRINTER_INFO_2* info_2 = reinterpret_cast(buffer.get()); - if (info_2->pDevMode != NULL) { - if (!AllocateContext(device_name, info_2->pDevMode)) { - ResetSettings(); - return false; - } - return InitializeSettings(*info_2->pDevMode, device_name, NULL, 0, false, - false); - } - buffer.reset(); - } - // Failed to retrieve the printer settings. - ResetSettings(); - return false; -} - -bool PrintingContext::AllocateContext(const std::wstring& printer_name, - const DEVMODE* dev_mode) { - hdc_ = CreateDC(L"WINSPOOL", printer_name.c_str(), NULL, dev_mode); - DCHECK(hdc_); - return hdc_ != NULL; -} - -PrintingContext::Result PrintingContext::ParseDialogResultEx( - const PRINTDLGEX& dialog_options) { - // If the user clicked OK or Apply then Cancel, but not only Cancel. - if (dialog_options.dwResultAction != PD_RESULT_CANCEL) { - // Start fresh. - ResetSettings(); - - DEVMODE* dev_mode = NULL; - if (dialog_options.hDevMode) { - dev_mode = - reinterpret_cast(GlobalLock(dialog_options.hDevMode)); - DCHECK(dev_mode); - } - - std::wstring device_name; - if (dialog_options.hDevNames) { - DEVNAMES* dev_names = - reinterpret_cast(GlobalLock(dialog_options.hDevNames)); - DCHECK(dev_names); - if (dev_names) { - device_name = - reinterpret_cast( - reinterpret_cast(dev_names) + - dev_names->wDeviceOffset); - GlobalUnlock(dialog_options.hDevNames); - } - } - - bool success = false; - if (dev_mode && !device_name.empty()) { - hdc_ = dialog_options.hDC; - PRINTPAGERANGE* page_ranges = NULL; - DWORD num_page_ranges = 0; - bool print_selection_only = false; - bool print_to_file = false; - if (dialog_options.Flags & PD_PAGENUMS) { - page_ranges = dialog_options.lpPageRanges; - num_page_ranges = dialog_options.nPageRanges; - } - if (dialog_options.Flags & PD_SELECTION) { - print_selection_only = true; - } - if (dialog_options.Flags & PD_PRINTTOFILE) { - print_to_file = true; - } - success = InitializeSettings(*dev_mode, - device_name, - dialog_options.lpPageRanges, - dialog_options.nPageRanges, - print_selection_only, - print_to_file); - } - - if (!success && dialog_options.hDC) { - DeleteDC(dialog_options.hDC); - hdc_ = NULL; - } - - if (dev_mode) { - GlobalUnlock(dialog_options.hDevMode); - } - } else { - if (dialog_options.hDC) { - DeleteDC(dialog_options.hDC); - } - } - - if (dialog_options.hDevMode != NULL) - GlobalFree(dialog_options.hDevMode); - if (dialog_options.hDevNames != NULL) - GlobalFree(dialog_options.hDevNames); - - switch (dialog_options.dwResultAction) { - case PD_RESULT_PRINT: - return hdc_ ? OK : FAILED; - case PD_RESULT_APPLY: - return hdc_ ? CANCEL : FAILED; - case PD_RESULT_CANCEL: - return CANCEL; - default: - return FAILED; - } -} - -PrintingContext::Result PrintingContext::ParseDialogResult( - const PRINTDLG& dialog_options) { - // If the user clicked OK or Apply then Cancel, but not only Cancel. - // Start fresh. - ResetSettings(); - - DEVMODE* dev_mode = NULL; - if (dialog_options.hDevMode) { - dev_mode = - reinterpret_cast(GlobalLock(dialog_options.hDevMode)); - DCHECK(dev_mode); - } - - std::wstring device_name; - if (dialog_options.hDevNames) { - DEVNAMES* dev_names = - reinterpret_cast(GlobalLock(dialog_options.hDevNames)); - DCHECK(dev_names); - if (dev_names) { - device_name = - reinterpret_cast( - reinterpret_cast(dev_names) + - dev_names->wDeviceOffset); - GlobalUnlock(dialog_options.hDevNames); - } - } - - bool success = false; - if (dev_mode && !device_name.empty()) { - hdc_ = dialog_options.hDC; - success = InitializeSettings(*dev_mode, device_name, NULL, 0, false, - false); - } - - if (!success && dialog_options.hDC) { - DeleteDC(dialog_options.hDC); - hdc_ = NULL; - } - - if (dev_mode) { - GlobalUnlock(dialog_options.hDevMode); - } - - if (dialog_options.hDevMode != NULL) - GlobalFree(dialog_options.hDevMode); - if (dialog_options.hDevNames != NULL) - GlobalFree(dialog_options.hDevNames); - - return hdc_ ? OK : FAILED; -} - -} // namespace printing - + else + return OnError(); + } + + DCHECK_EQ(MessageLoop::current()->NestableTasksAllowed(), false); + // Begin a print job by calling the StartDoc function. + // NOTE: StartDoc() starts a message loop. That causes a lot of problems with + // IPC. Make sure recursive task processing is disabled. + if (StartDoc(hdc_, &di) <= 0) + return OnError(); + +#ifndef NDEBUG + page_number_ = 0; +#endif + return OK; +} + +PrintingContext::Result PrintingContext::NewPage() { + if (abort_printing_) + return CANCEL; + DCHECK(in_print_job_); + + // Inform the driver that the application is about to begin sending data. + if (StartPage(hdc_) <= 0) + return OnError(); + +#ifndef NDEBUG + ++page_number_; +#endif + + return OK; +} + +PrintingContext::Result PrintingContext::PageDone() { + if (abort_printing_) + return CANCEL; + DCHECK(in_print_job_); + + if (EndPage(hdc_) <= 0) + return OnError(); + return OK; +} + +PrintingContext::Result PrintingContext::DocumentDone() { + if (abort_printing_) + return CANCEL; + DCHECK(in_print_job_); + + // Inform the driver that document has ended. + if (EndDoc(hdc_) <= 0) + return OnError(); + + ResetSettings(); + return OK; +} + +void PrintingContext::Cancel() { + abort_printing_ = true; + in_print_job_ = false; + if (hdc_) + CancelDC(hdc_); + DismissDialog(); +} + +void PrintingContext::DismissDialog() { + if (dialog_box_) { + DestroyWindow(dialog_box_); + dialog_box_dismissed_ = true; + } +} + +PrintingContext::Result PrintingContext::OnError() { + // This will close hdc_ and clear settings_. + ResetSettings(); + return abort_printing_ ? CANCEL : FAILED; +} + +// static +BOOL PrintingContext::AbortProc(HDC hdc, int nCode) { + if (nCode) { + // TODO(maruel): Need a way to find the right instance to set. Should + // leverage PrintJobManager here? + // abort_printing_ = true; + } + return true; +} + +bool PrintingContext::InitializeSettings(const DEVMODE& dev_mode, + const std::wstring& new_device_name, + const PRINTPAGERANGE* ranges, + int number_ranges, + bool selection_only, + bool to_file) { + skia::PlatformDevice::InitializeDC(hdc_); + DCHECK(GetDeviceCaps(hdc_, CLIPCAPS)); + DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_STRETCHDIB); + DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_BITMAP64); + // Some printers don't advertise these. + // DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_SCALING); + // DCHECK(GetDeviceCaps(hdc_, SHADEBLENDCAPS) & SB_CONST_ALPHA); + // DCHECK(GetDeviceCaps(hdc_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA); + + // StretchDIBits() support is needed for printing. + if (!(GetDeviceCaps(hdc_, RASTERCAPS) & RC_STRETCHDIB) || + !(GetDeviceCaps(hdc_, RASTERCAPS) & RC_BITMAP64)) { + NOTREACHED(); + ResetSettings(); + return false; + } + + DCHECK(!in_print_job_); + DCHECK(hdc_); + PageRanges ranges_vector; + if (!selection_only) { + // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector. + ranges_vector.reserve(number_ranges); + for (int i = 0; i < number_ranges; ++i) { + PageRange range; + // Transfer from 1-based to 0-based. + range.from = ranges[i].nFromPage - 1; + range.to = ranges[i].nToPage - 1; + ranges_vector.push_back(range); + } + } + settings_.Init(hdc_, + dev_mode, + ranges_vector, + new_device_name, + selection_only, + to_file); + return true; +} + +bool PrintingContext::GetPrinterSettings(HANDLE printer, + const std::wstring& device_name) { + DCHECK(!in_print_job_); + scoped_array buffer; + + // A PRINTER_INFO_9 structure specifying the per-user default printer + // settings. + GetPrinterHelper(printer, 9, &buffer); + if (buffer.get()) { + PRINTER_INFO_9* info_9 = reinterpret_cast(buffer.get()); + if (info_9->pDevMode != NULL) { + if (!AllocateContext(device_name, info_9->pDevMode)) { + ResetSettings(); + return false; + } + return InitializeSettings(*info_9->pDevMode, device_name, NULL, 0, false, + false); + } + buffer.reset(); + } + + // A PRINTER_INFO_8 structure specifying the global default printer settings. + GetPrinterHelper(printer, 8, &buffer); + if (buffer.get()) { + PRINTER_INFO_8* info_8 = reinterpret_cast(buffer.get()); + if (info_8->pDevMode != NULL) { + if (!AllocateContext(device_name, info_8->pDevMode)) { + ResetSettings(); + return false; + } + return InitializeSettings(*info_8->pDevMode, device_name, NULL, 0, false, + false); + } + buffer.reset(); + } + + // A PRINTER_INFO_2 structure specifying the driver's default printer + // settings. + GetPrinterHelper(printer, 2, &buffer); + if (buffer.get()) { + PRINTER_INFO_2* info_2 = reinterpret_cast(buffer.get()); + if (info_2->pDevMode != NULL) { + if (!AllocateContext(device_name, info_2->pDevMode)) { + ResetSettings(); + return false; + } + return InitializeSettings(*info_2->pDevMode, device_name, NULL, 0, false, + false); + } + buffer.reset(); + } + // Failed to retrieve the printer settings. + ResetSettings(); + return false; +} + +bool PrintingContext::AllocateContext(const std::wstring& printer_name, + const DEVMODE* dev_mode) { + hdc_ = CreateDC(L"WINSPOOL", printer_name.c_str(), NULL, dev_mode); + DCHECK(hdc_); + return hdc_ != NULL; +} + +PrintingContext::Result PrintingContext::ParseDialogResultEx( + const PRINTDLGEX& dialog_options) { + // If the user clicked OK or Apply then Cancel, but not only Cancel. + if (dialog_options.dwResultAction != PD_RESULT_CANCEL) { + // Start fresh. + ResetSettings(); + + DEVMODE* dev_mode = NULL; + if (dialog_options.hDevMode) { + dev_mode = + reinterpret_cast(GlobalLock(dialog_options.hDevMode)); + DCHECK(dev_mode); + } + + std::wstring device_name; + if (dialog_options.hDevNames) { + DEVNAMES* dev_names = + reinterpret_cast(GlobalLock(dialog_options.hDevNames)); + DCHECK(dev_names); + if (dev_names) { + device_name = + reinterpret_cast( + reinterpret_cast(dev_names) + + dev_names->wDeviceOffset); + GlobalUnlock(dialog_options.hDevNames); + } + } + + bool success = false; + if (dev_mode && !device_name.empty()) { + hdc_ = dialog_options.hDC; + PRINTPAGERANGE* page_ranges = NULL; + DWORD num_page_ranges = 0; + bool print_selection_only = false; + bool print_to_file = false; + if (dialog_options.Flags & PD_PAGENUMS) { + page_ranges = dialog_options.lpPageRanges; + num_page_ranges = dialog_options.nPageRanges; + } + if (dialog_options.Flags & PD_SELECTION) { + print_selection_only = true; + } + if (dialog_options.Flags & PD_PRINTTOFILE) { + print_to_file = true; + } + success = InitializeSettings(*dev_mode, + device_name, + dialog_options.lpPageRanges, + dialog_options.nPageRanges, + print_selection_only, + print_to_file); + } + + if (!success && dialog_options.hDC) { + DeleteDC(dialog_options.hDC); + hdc_ = NULL; + } + + if (dev_mode) { + GlobalUnlock(dialog_options.hDevMode); + } + } else { + if (dialog_options.hDC) { + DeleteDC(dialog_options.hDC); + } + } + + if (dialog_options.hDevMode != NULL) + GlobalFree(dialog_options.hDevMode); + if (dialog_options.hDevNames != NULL) + GlobalFree(dialog_options.hDevNames); + + switch (dialog_options.dwResultAction) { + case PD_RESULT_PRINT: + return hdc_ ? OK : FAILED; + case PD_RESULT_APPLY: + return hdc_ ? CANCEL : FAILED; + case PD_RESULT_CANCEL: + return CANCEL; + default: + return FAILED; + } +} + +PrintingContext::Result PrintingContext::ParseDialogResult( + const PRINTDLG& dialog_options) { + // If the user clicked OK or Apply then Cancel, but not only Cancel. + // Start fresh. + ResetSettings(); + + DEVMODE* dev_mode = NULL; + if (dialog_options.hDevMode) { + dev_mode = + reinterpret_cast(GlobalLock(dialog_options.hDevMode)); + DCHECK(dev_mode); + } + + std::wstring device_name; + if (dialog_options.hDevNames) { + DEVNAMES* dev_names = + reinterpret_cast(GlobalLock(dialog_options.hDevNames)); + DCHECK(dev_names); + if (dev_names) { + device_name = + reinterpret_cast( + reinterpret_cast(dev_names) + + dev_names->wDeviceOffset); + GlobalUnlock(dialog_options.hDevNames); + } + } + + bool success = false; + if (dev_mode && !device_name.empty()) { + hdc_ = dialog_options.hDC; + success = InitializeSettings(*dev_mode, device_name, NULL, 0, false, + false); + } + + if (!success && dialog_options.hDC) { + DeleteDC(dialog_options.hDC); + hdc_ = NULL; + } + + if (dev_mode) { + GlobalUnlock(dialog_options.hDevMode); + } + + if (dialog_options.hDevMode != NULL) + GlobalFree(dialog_options.hDevMode); + if (dialog_options.hDevNames != NULL) + GlobalFree(dialog_options.hDevNames); + + return hdc_ ? OK : FAILED; +} + +} // namespace printing + diff --git a/libcef/printing/win_printing_context.h b/libcef/printing/win_printing_context.h index 8d8d2b164..605c11792 100644 --- a/libcef/printing/win_printing_context.h +++ b/libcef/printing/win_printing_context.h @@ -1,141 +1,141 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef _PRINTING_WIN_PRINTING_CONTEXT_H -#define _PRINTING_WIN_PRINTING_CONTEXT_H - -#include "print_settings.h" - -#include -#include -#include - -#include "base/basictypes.h" - -namespace printing { - -// Describe the user selected printing context for Windows. This includes the -// OS-dependent UI to ask the user about the print settings. This class directly -// talk to the printer and manages the document and pages breaks. -class PrintingContext { - public: - // Tri-state result for user behavior-dependent functions. - enum Result { - OK, - CANCEL, - FAILED, - }; - - PrintingContext(); - ~PrintingContext(); - - // Asks the user what printer and format should be used to print. Updates the - // context with the select device settings. - Result AskUserForSettings(HWND window, int max_pages, bool has_selection); - - // Selects the user's default printer and format. Updates the context with the - // default device settings. - Result UseDefaultSettings(); - - // Initializes with predefined settings. - Result InitWithSettings(const PrintSettings& settings); - - // Reinitializes the settings to uninitialized for object reuse. - void ResetSettings(); - - // Does platform specific setup of the printer before the printing. Signal the - // printer that a document is about to be spooled. - // Warning: This function enters a message loop. That may cause side effects - // like IPC message processing! Some printers have side-effects on this call - // like virtual printers that ask the user for the path of the saved document; - // for example a PDF printer. - Result NewDocument(const std::wstring& document_name); - - // Starts a new page. - Result NewPage(); - - // Closes the printed page. - Result PageDone(); - - // Closes the printing job. After this call the object is ready to start a new - // document. - Result DocumentDone(); - - // Cancels printing. Can be used in a multithreaded context. Takes effect - // immediately. - void Cancel(); - - // Dismiss the Print... dialog box if shown. - void DismissDialog(); - - HDC context() { - return hdc_; - } - - const PrintSettings& settings() const { - return settings_; - } - - private: - // Class that manages the PrintDlgEx() callbacks. This is meant to be a - // temporary object used during the Print... dialog display. - class CallbackHandler; - - // Does bookkeeping when an error occurs. - PrintingContext::Result OnError(); - - // Used in response to the user canceling the printing. - static BOOL CALLBACK AbortProc(HDC hdc, int nCode); - - // Reads the settings from the selected device context. Updates settings_ and - // its margins. - bool InitializeSettings(const DEVMODE& dev_mode, - const std::wstring& new_device_name, - const PRINTPAGERANGE* ranges, - int number_ranges, - bool selection_only, - bool to_file); - - // Retrieves the printer's default low-level settings. hdc_ is allocated with - // this call. - bool GetPrinterSettings(HANDLE printer, - const std::wstring& device_name); - - // Allocates the HDC for a specific DEVMODE. - bool AllocateContext(const std::wstring& printer_name, - const DEVMODE* dev_mode); - - // Parses the result of a PRINTDLGEX result. - Result ParseDialogResultEx(const PRINTDLGEX& dialog_options); - Result ParseDialogResult(const PRINTDLG& dialog_options); - - // The selected printer context. - HDC hdc_; - - // Complete print context settings. - PrintSettings settings_; - -#ifndef NDEBUG - // Current page number in the print job. - int page_number_; -#endif - - // The dialog box for the time it is shown. - volatile HWND dialog_box_; - - // The dialog box has been dismissed. - volatile bool dialog_box_dismissed_; - - // Is a print job being done. - volatile bool in_print_job_; - - // Did the user cancel the print job. - volatile bool abort_printing_; - - DISALLOW_EVIL_CONSTRUCTORS(PrintingContext); -}; - -} // namespace printing - -#endif // _PRINTING_WIN_PRINTING_CONTEXT_H +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _PRINTING_WIN_PRINTING_CONTEXT_H +#define _PRINTING_WIN_PRINTING_CONTEXT_H + +#include "print_settings.h" + +#include +#include +#include + +#include "base/basictypes.h" + +namespace printing { + +// Describe the user selected printing context for Windows. This includes the +// OS-dependent UI to ask the user about the print settings. This class directly +// talk to the printer and manages the document and pages breaks. +class PrintingContext { + public: + // Tri-state result for user behavior-dependent functions. + enum Result { + OK, + CANCEL, + FAILED, + }; + + PrintingContext(); + ~PrintingContext(); + + // Asks the user what printer and format should be used to print. Updates the + // context with the select device settings. + Result AskUserForSettings(HWND window, int max_pages, bool has_selection); + + // Selects the user's default printer and format. Updates the context with the + // default device settings. + Result UseDefaultSettings(); + + // Initializes with predefined settings. + Result InitWithSettings(const PrintSettings& settings); + + // Reinitializes the settings to uninitialized for object reuse. + void ResetSettings(); + + // Does platform specific setup of the printer before the printing. Signal the + // printer that a document is about to be spooled. + // Warning: This function enters a message loop. That may cause side effects + // like IPC message processing! Some printers have side-effects on this call + // like virtual printers that ask the user for the path of the saved document; + // for example a PDF printer. + Result NewDocument(const std::wstring& document_name); + + // Starts a new page. + Result NewPage(); + + // Closes the printed page. + Result PageDone(); + + // Closes the printing job. After this call the object is ready to start a new + // document. + Result DocumentDone(); + + // Cancels printing. Can be used in a multithreaded context. Takes effect + // immediately. + void Cancel(); + + // Dismiss the Print... dialog box if shown. + void DismissDialog(); + + HDC context() { + return hdc_; + } + + const PrintSettings& settings() const { + return settings_; + } + + private: + // Class that manages the PrintDlgEx() callbacks. This is meant to be a + // temporary object used during the Print... dialog display. + class CallbackHandler; + + // Does bookkeeping when an error occurs. + PrintingContext::Result OnError(); + + // Used in response to the user canceling the printing. + static BOOL CALLBACK AbortProc(HDC hdc, int nCode); + + // Reads the settings from the selected device context. Updates settings_ and + // its margins. + bool InitializeSettings(const DEVMODE& dev_mode, + const std::wstring& new_device_name, + const PRINTPAGERANGE* ranges, + int number_ranges, + bool selection_only, + bool to_file); + + // Retrieves the printer's default low-level settings. hdc_ is allocated with + // this call. + bool GetPrinterSettings(HANDLE printer, + const std::wstring& device_name); + + // Allocates the HDC for a specific DEVMODE. + bool AllocateContext(const std::wstring& printer_name, + const DEVMODE* dev_mode); + + // Parses the result of a PRINTDLGEX result. + Result ParseDialogResultEx(const PRINTDLGEX& dialog_options); + Result ParseDialogResult(const PRINTDLG& dialog_options); + + // The selected printer context. + HDC hdc_; + + // Complete print context settings. + PrintSettings settings_; + +#ifndef NDEBUG + // Current page number in the print job. + int page_number_; +#endif + + // The dialog box for the time it is shown. + volatile HWND dialog_box_; + + // The dialog box has been dismissed. + volatile bool dialog_box_dismissed_; + + // Is a print job being done. + volatile bool in_print_job_; + + // Did the user cancel the print job. + volatile bool abort_printing_; + + DISALLOW_EVIL_CONSTRUCTORS(PrintingContext); +}; + +} // namespace printing + +#endif // _PRINTING_WIN_PRINTING_CONTEXT_H diff --git a/libcef/request_impl.cc b/libcef/request_impl.cc index 791ca2c0d..9ea3fd4dd 100644 --- a/libcef/request_impl.cc +++ b/libcef/request_impl.cc @@ -1,7 +1,7 @@ -// 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. - +// 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 "precompiled_libcef.h" #include "request_impl.h" @@ -154,21 +154,21 @@ void CefPostDataImpl::GetElements(ElementVector& elements) bool CefPostDataImpl::RemoveElement(CefRefPtr element) { - bool deleted = false; - - Lock(); - - ElementVector::iterator it = elements_.begin(); - for(; it != elements_.end(); ++it) { - if(it->get() == element.get()) { - elements_.erase(it); - deleted = true; - break; - } - } - - Unlock(); - + bool deleted = false; + + Lock(); + + ElementVector::iterator it = elements_.begin(); + for(; it != elements_.end(); ++it) { + if(it->get() == element.get()) { + elements_.erase(it); + deleted = true; + break; + } + } + + Unlock(); + return deleted; } @@ -179,12 +179,12 @@ bool CefPostDataImpl::AddElement(CefRefPtr element) Lock(); // check that the element isn't already in the list before adding - ElementVector::const_iterator it = elements_.begin(); - for(; it != elements_.end(); ++it) { - if(it->get() == element.get()) { - found = true; - break; - } + ElementVector::const_iterator it = elements_.begin(); + for(; it != elements_.end(); ++it) { + if(it->get() == element.get()) { + found = true; + break; + } } if(!found) @@ -206,12 +206,12 @@ void CefPostDataImpl::Set(const net::UploadData& data) Lock(); CefRefPtr postelem; - const std::vector& elements = data.elements(); - std::vector::const_iterator it = elements.begin(); - for (; it != elements.end(); ++it) { - postelem = CefPostDataElement::CreatePostDataElement(); - static_cast(postelem.get())->Set(*it); - AddElement(postelem); + const std::vector& elements = data.elements(); + std::vector::const_iterator it = elements.begin(); + for (; it != elements.end(); ++it) { + postelem = CefPostDataElement::CreatePostDataElement(); + static_cast(postelem.get())->Set(*it); + AddElement(postelem); } Unlock(); @@ -223,10 +223,10 @@ void CefPostDataImpl::Get(net::UploadData& data) net::UploadData::Element element; std::vector data_elements; - ElementVector::iterator it = elements_.begin(); - for(; it != elements_.end(); ++it) { - static_cast(it->get())->Get(element); - data_elements.push_back(element); + ElementVector::iterator it = elements_.begin(); + for(; it != elements_.end(); ++it) { + static_cast(it->get())->Get(element); + data_elements.push_back(element); } data.set_elements(data_elements); @@ -240,12 +240,12 @@ void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data) CefRefPtr postelem; WebKit::WebHTTPBody::Element element; size_t size = data.elementCount(); - for (size_t i = 0; i < size; ++i) { - if (data.elementAt(i, element)) { - postelem = CefPostDataElement::CreatePostDataElement(); - static_cast(postelem.get())->Set(element); - AddElement(postelem); - } + for (size_t i = 0; i < size; ++i) { + if (data.elementAt(i, element)) { + postelem = CefPostDataElement::CreatePostDataElement(); + static_cast(postelem.get())->Set(element); + AddElement(postelem); + } } Unlock(); @@ -256,16 +256,16 @@ void CefPostDataImpl::Get(WebKit::WebHTTPBody& data) Lock(); WebKit::WebHTTPBody::Element element; - ElementVector::iterator it = elements_.begin(); - for(; it != elements_.end(); ++it) { - static_cast(it->get())->Get(element); - if(element.type == WebKit::WebHTTPBody::Element::TypeData) { - data.appendData(element.data); - } else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) { - data.appendFile(element.filePath); - } else { - NOTREACHED(); - } + ElementVector::iterator it = elements_.begin(); + for(; it != elements_.end(); ++it) { + static_cast(it->get())->Get(element); + if(element.type == WebKit::WebHTTPBody::Element::TypeData) { + data.appendData(element.data); + } else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) { + data.appendFile(element.filePath); + } else { + NOTREACHED(); + } } Unlock(); @@ -279,7 +279,7 @@ CefRefPtr CefPostDataElement::CreatePostDataElement() CefPostDataElementImpl::CefPostDataElementImpl() { - type_ = PDE_TYPE_EMPTY; + type_ = PDE_TYPE_EMPTY; } CefPostDataElementImpl::~CefPostDataElementImpl() @@ -290,11 +290,11 @@ CefPostDataElementImpl::~CefPostDataElementImpl() void CefPostDataElementImpl::SetToEmpty() { Lock(); - if(type_ == PDE_TYPE_BYTES) + if(type_ == PDE_TYPE_BYTES) free(data_.bytes.bytes); - else if(type_ == PDE_TYPE_FILE) + else if(type_ == PDE_TYPE_FILE) free(data_.filename); - type_ = PDE_TYPE_EMPTY; + type_ = PDE_TYPE_EMPTY; Unlock(); } @@ -316,7 +316,7 @@ void CefPostDataElementImpl::SetToFile(const std::wstring& fileName) data[size] = 0; // Assign the new data - type_ = PDE_TYPE_FILE; + type_ = PDE_TYPE_FILE; data_.filename = data; Unlock(); } @@ -335,7 +335,7 @@ void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) memcpy(data, bytes, size); - type_ = PDE_TYPE_BYTES; + type_ = PDE_TYPE_BYTES; data_.bytes.bytes = data; data_.bytes.size = size; Unlock(); @@ -352,9 +352,9 @@ CefPostDataElement::Type CefPostDataElementImpl::GetType() std::wstring CefPostDataElementImpl::GetFile() { Lock(); - DCHECK(type_ == PDE_TYPE_FILE); + DCHECK(type_ == PDE_TYPE_FILE); std::wstring filename; - if(type_ == PDE_TYPE_FILE) + if(type_ == PDE_TYPE_FILE) filename = data_.filename; Unlock(); return filename; @@ -363,9 +363,9 @@ std::wstring CefPostDataElementImpl::GetFile() size_t CefPostDataElementImpl::GetBytesCount() { Lock(); - DCHECK(type_ == PDE_TYPE_BYTES); + DCHECK(type_ == PDE_TYPE_BYTES); size_t size = 0; - if(type_ == PDE_TYPE_BYTES) + if(type_ == PDE_TYPE_BYTES) size = data_.bytes.size; Unlock(); return size; @@ -374,9 +374,9 @@ size_t CefPostDataElementImpl::GetBytesCount() size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) { Lock(); - DCHECK(type_ == PDE_TYPE_BYTES); + DCHECK(type_ == PDE_TYPE_BYTES); size_t rv = 0; - if(type_ == PDE_TYPE_BYTES) { + if(type_ == PDE_TYPE_BYTES) { rv = (size < data_.bytes.size ? size : data_.bytes.size); memcpy(bytes, data_.bytes.bytes, rv); } @@ -388,15 +388,15 @@ void CefPostDataElementImpl::Set(const net::UploadData::Element& element) { Lock(); - if (element.type() == net::UploadData::TYPE_BYTES) { - SetToBytes(element.bytes().size(), - static_cast( - std::string(element.bytes().begin(), - element.bytes().end()).c_str())); - } else if (element.type() == net::UploadData::TYPE_FILE) { - SetToFile(element.file_path().value()); - } else { - NOTREACHED(); + if (element.type() == net::UploadData::TYPE_BYTES) { + SetToBytes(element.bytes().size(), + static_cast( + std::string(element.bytes().begin(), + element.bytes().end()).c_str())); + } else if (element.type() == net::UploadData::TYPE_FILE) { + SetToFile(element.file_path().value()); + } else { + NOTREACHED(); } Unlock(); @@ -406,12 +406,12 @@ void CefPostDataElementImpl::Get(net::UploadData::Element& element) { Lock(); - if(type_ == PDE_TYPE_BYTES) { + if(type_ == PDE_TYPE_BYTES) { element.SetToBytes(static_cast(data_.bytes.bytes), data_.bytes.size); - } else if(type_ == PDE_TYPE_FILE) { + } else if(type_ == PDE_TYPE_FILE) { element.SetToFilePath(FilePath(data_.filename)); - } else { - NOTREACHED(); + } else { + NOTREACHED(); } Unlock(); @@ -426,8 +426,8 @@ void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element) static_cast(element.data.data())); } else if(element.type == WebKit::WebHTTPBody::Element::TypeFile) { SetToFile(UTF8ToWide(webkit_glue::WebStringToStdString(element.filePath))); - } else { - NOTREACHED(); + } else { + NOTREACHED(); } Unlock(); @@ -437,16 +437,16 @@ void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element) { Lock(); - if(type_ == PDE_TYPE_BYTES) { + if(type_ == PDE_TYPE_BYTES) { element.type = WebKit::WebHTTPBody::Element::TypeData; element.data.assign( static_cast(data_.bytes.bytes), data_.bytes.size); - } else if(type_ == PDE_TYPE_FILE) { + } else if(type_ == PDE_TYPE_FILE) { element.type = WebKit::WebHTTPBody::Element::TypeFile; element.filePath.assign( webkit_glue::StdStringToWebString(WideToUTF8(data_.filename))); - } else { - NOTREACHED(); + } else { + NOTREACHED(); } Unlock(); diff --git a/libcef/request_impl.h b/libcef/request_impl.h index 33545c4f9..4dde4e259 100644 --- a/libcef/request_impl.h +++ b/libcef/request_impl.h @@ -1,7 +1,7 @@ -// 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. - +// 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. + #ifndef _REQUEST_IMPL_H #define _REQUEST_IMPL_H diff --git a/libcef/simple_clipboard_impl.cc b/libcef/simple_clipboard_impl.cc index bc7ee6ef4..fd6264a74 100644 --- a/libcef/simple_clipboard_impl.cc +++ b/libcef/simple_clipboard_impl.cc @@ -1,56 +1,56 @@ -// 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 "precompiled_libcef.h" -#include "webkit/glue/webkit_glue.h" - -#include - -#include "base/clipboard.h" -#include "base/lazy_instance.h" -#include "base/string16.h" -#include "googleurl/src/gurl.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "webkit/glue/scoped_clipboard_writer_glue.h" - -// Clipboard glue - -#if defined(OS_WIN) -void ScopedClipboardWriterGlue::WriteBitmapFromPixels( - const void* pixels, const gfx::Size& size) { - ScopedClipboardWriter::WriteBitmapFromPixels(pixels, size); -} -#endif - -ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { -} - -namespace webkit_glue { - -base::LazyInstance clipboard(base::LINKER_INITIALIZED); - -Clipboard* ClipboardGetClipboard() { - return clipboard.Pointer(); -} - -bool ClipboardIsFormatAvailable(const Clipboard::FormatType& format) { - return ClipboardGetClipboard()->IsFormatAvailable(format); -} - -void ClipboardReadText(string16* result) { - ClipboardGetClipboard()->ReadText(result); -} - -void ClipboardReadAsciiText(std::string* result) { - ClipboardGetClipboard()->ReadAsciiText(result); -} - -void ClipboardReadHTML(string16* markup, GURL* url) { - std::string url_str; - ClipboardGetClipboard()->ReadHTML(markup, url ? &url_str : NULL); - if (url) - *url = GURL(url_str); -} - -} // namespace webkit_glue +// 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 "precompiled_libcef.h" +#include "webkit/glue/webkit_glue.h" + +#include + +#include "base/clipboard.h" +#include "base/lazy_instance.h" +#include "base/string16.h" +#include "googleurl/src/gurl.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "webkit/glue/scoped_clipboard_writer_glue.h" + +// Clipboard glue + +#if defined(OS_WIN) +void ScopedClipboardWriterGlue::WriteBitmapFromPixels( + const void* pixels, const gfx::Size& size) { + ScopedClipboardWriter::WriteBitmapFromPixels(pixels, size); +} +#endif + +ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { +} + +namespace webkit_glue { + +base::LazyInstance clipboard(base::LINKER_INITIALIZED); + +Clipboard* ClipboardGetClipboard() { + return clipboard.Pointer(); +} + +bool ClipboardIsFormatAvailable(const Clipboard::FormatType& format) { + return ClipboardGetClipboard()->IsFormatAvailable(format); +} + +void ClipboardReadText(string16* result) { + ClipboardGetClipboard()->ReadText(result); +} + +void ClipboardReadAsciiText(std::string* result) { + ClipboardGetClipboard()->ReadAsciiText(result); +} + +void ClipboardReadHTML(string16* markup, GURL* url) { + std::string url_str; + ClipboardGetClipboard()->ReadHTML(markup, url ? &url_str : NULL); + if (url) + *url = GURL(url_str); +} + +} // namespace webkit_glue diff --git a/libcef/stream_impl.cc b/libcef/stream_impl.cc index 6c0d12eb6..0ba81acee 100644 --- a/libcef/stream_impl.cc +++ b/libcef/stream_impl.cc @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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. - +// Copyright (c) 2008 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 "precompiled_libcef.h" #include "stream_impl.h" diff --git a/libcef/stream_impl.h b/libcef/stream_impl.h index dd608ae3c..ca582f78d 100644 --- a/libcef/stream_impl.h +++ b/libcef/stream_impl.h @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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. - +// Copyright (c) 2008 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 _STREAM_IMPL_H #define _STREAM_IMPL_H diff --git a/libcef/tracker.h b/libcef/tracker.h index 810b787ac..5e0aa8df2 100644 --- a/libcef/tracker.h +++ b/libcef/tracker.h @@ -1,136 +1,136 @@ -// 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. - +// 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 _TRACKER_H #define _TRACKER_H #include "include/cef.h" - -// Class extended by objects that must be tracked. After creating a tracked -// object you should add it to the appropriate track manager. -class CefTrackObject -{ -public: - CefTrackObject() - { - track_next_ = NULL; - track_prev_ = NULL; - } - virtual ~CefTrackObject() - { - } - - // Returns true if the object is currently being tracked. - bool IsTracked() { return (track_prev_ || track_next_); } - -private: - CefTrackObject* GetTrackPrev() { return track_prev_; } - void SetTrackPrev(CefTrackObject* base) { track_prev_ = base; } - CefTrackObject* GetTrackNext() { return track_next_; } - void SetTrackNext(CefTrackObject* base) { track_next_ = base; } - - // Insert a new object into the tracking list before this object. - void InsertTrackPrev(CefTrackObject* object) - { - if(track_prev_) - track_prev_->SetTrackNext(object); - object->SetTrackNext(this); - object->SetTrackPrev(track_prev_); - track_prev_ = object; - } - - // Insert a new object into the tracking list after this object. - void InsertTrackNext(CefTrackObject* object) - { - if(track_next_) - track_next_->SetTrackPrev(object); - object->SetTrackPrev(this); - object->SetTrackNext(track_next_); - track_next_ = object; - } - - // Remove this object from the tracking list. - void RemoveTracking() - { - if(track_next_) - track_next_->SetTrackPrev(track_prev_); - if(track_prev_) - track_prev_->SetTrackNext(track_next_); - track_next_ = NULL; - track_prev_ = NULL; - } - -private: - CefTrackObject* track_next_; - CefTrackObject* track_prev_; - - friend class CefTrackManager; -}; -// Class used to manage tracked objects. A single instance of this class -// should be created for each intended usage. Any objects that have not been -// removed by explicit calls to the Destroy() method will be removed when the -// manager object is destroyed. A manager object can be created as either a -// member variable of another class or by using lazy initialization: -// base::LazyInstance g_singleton(base::LINKER_INITIALIZED); -class CefTrackManager : public CefThreadSafeBase -{ -public: - CefTrackManager() : object_count_(0) {} - virtual ~CefTrackManager() - { - DeleteAll(); - } - - // Add an object to be tracked by this manager. - void Add(CefTrackObject* object) - { - Lock(); - if(!object->IsTracked()) { - tracker_.InsertTrackNext(object); - ++object_count_; - } - Unlock(); - } - - // Delete an object tracked by this manager. - bool Delete(CefTrackObject* object) - { - bool rv = false; - Lock(); - if(object->IsTracked()) { - object->RemoveTracking(); - delete object; - --object_count_; - rv = true; - } - Unlock(); - return rv; - } - - // Delete all objects tracked by this manager. - void DeleteAll() - { - Lock(); - CefTrackObject* next; - do { - next = tracker_.GetTrackNext(); - if(next) { - next->RemoveTracking(); - delete next; - } - } while(next != NULL); - object_count_ = 0; - Unlock(); - } - - // Returns the number of objects currently being tracked. - long GetCount() { return object_count_; } - -private: - CefTrackObject tracker_; - long object_count_; -}; +// Class extended by objects that must be tracked. After creating a tracked +// object you should add it to the appropriate track manager. +class CefTrackObject +{ +public: + CefTrackObject() + { + track_next_ = NULL; + track_prev_ = NULL; + } + virtual ~CefTrackObject() + { + } + + // Returns true if the object is currently being tracked. + bool IsTracked() { return (track_prev_ || track_next_); } + +private: + CefTrackObject* GetTrackPrev() { return track_prev_; } + void SetTrackPrev(CefTrackObject* base) { track_prev_ = base; } + CefTrackObject* GetTrackNext() { return track_next_; } + void SetTrackNext(CefTrackObject* base) { track_next_ = base; } + + // Insert a new object into the tracking list before this object. + void InsertTrackPrev(CefTrackObject* object) + { + if(track_prev_) + track_prev_->SetTrackNext(object); + object->SetTrackNext(this); + object->SetTrackPrev(track_prev_); + track_prev_ = object; + } + + // Insert a new object into the tracking list after this object. + void InsertTrackNext(CefTrackObject* object) + { + if(track_next_) + track_next_->SetTrackPrev(object); + object->SetTrackPrev(this); + object->SetTrackNext(track_next_); + track_next_ = object; + } + + // Remove this object from the tracking list. + void RemoveTracking() + { + if(track_next_) + track_next_->SetTrackPrev(track_prev_); + if(track_prev_) + track_prev_->SetTrackNext(track_next_); + track_next_ = NULL; + track_prev_ = NULL; + } + +private: + CefTrackObject* track_next_; + CefTrackObject* track_prev_; + + friend class CefTrackManager; +}; + +// Class used to manage tracked objects. A single instance of this class +// should be created for each intended usage. Any objects that have not been +// removed by explicit calls to the Destroy() method will be removed when the +// manager object is destroyed. A manager object can be created as either a +// member variable of another class or by using lazy initialization: +// base::LazyInstance g_singleton(base::LINKER_INITIALIZED); +class CefTrackManager : public CefThreadSafeBase +{ +public: + CefTrackManager() : object_count_(0) {} + virtual ~CefTrackManager() + { + DeleteAll(); + } + + // Add an object to be tracked by this manager. + void Add(CefTrackObject* object) + { + Lock(); + if(!object->IsTracked()) { + tracker_.InsertTrackNext(object); + ++object_count_; + } + Unlock(); + } + + // Delete an object tracked by this manager. + bool Delete(CefTrackObject* object) + { + bool rv = false; + Lock(); + if(object->IsTracked()) { + object->RemoveTracking(); + delete object; + --object_count_; + rv = true; + } + Unlock(); + return rv; + } + + // Delete all objects tracked by this manager. + void DeleteAll() + { + Lock(); + CefTrackObject* next; + do { + next = tracker_.GetTrackNext(); + if(next) { + next->RemoveTracking(); + delete next; + } + } while(next != NULL); + object_count_ = 0; + Unlock(); + } + + // Returns the number of objects currently being tracked. + long GetCount() { return object_count_; } + +private: + CefTrackObject tracker_; + long object_count_; +}; #endif // _TRACKER_H diff --git a/libcef/v8_impl.cc b/libcef/v8_impl.cc index 451df5544..90f4d26f5 100644 --- a/libcef/v8_impl.cc +++ b/libcef/v8_impl.cc @@ -1,49 +1,49 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that -// can be found in the LICENSE file. - -#include "precompiled_libcef.h" -#include "v8_impl.h" -#include "context.h" -#include "tracker.h" -#include "base/lazy_instance.h" -#include "base/string_util.h" -#include "webkit/api/public/WebKit.h" - - -// Memory manager. - -base::LazyInstance g_v8_tracker(base::LINKER_INITIALIZED); - -class TrackBase : public CefTrackObject -{ -public: - TrackBase(CefBase* base) { base_ = base; } - -protected: - CefRefPtr base_; -}; - -class TrackString : public CefTrackObject -{ -public: - TrackString(const std::string& str) : string_(str) {} - const char* GetString() { return string_.c_str(); } - -private: - std::string string_; -}; - - -static void TrackAdd(CefTrackObject* object) -{ - g_v8_tracker.Pointer()->Add(object); -} +// 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. -static void TrackDelete(CefTrackObject* object) -{ - g_v8_tracker.Pointer()->Delete(object); -} +#include "precompiled_libcef.h" +#include "v8_impl.h" +#include "context.h" +#include "tracker.h" +#include "base/lazy_instance.h" +#include "base/string_util.h" +#include "webkit/api/public/WebKit.h" + + +// Memory manager. + +base::LazyInstance g_v8_tracker(base::LINKER_INITIALIZED); + +class TrackBase : public CefTrackObject +{ +public: + TrackBase(CefBase* base) { base_ = base; } + +protected: + CefRefPtr base_; +}; + +class TrackString : public CefTrackObject +{ +public: + TrackString(const std::string& str) : string_(str) {} + const char* GetString() { return string_.c_str(); } + +private: + std::string string_; +}; + + +static void TrackAdd(CefTrackObject* object) +{ + g_v8_tracker.Pointer()->Add(object); +} + +static void TrackDelete(CefTrackObject* object) +{ + g_v8_tracker.Pointer()->Delete(object); +} // Callback for weak persistent reference destruction. static void TrackDestructor(v8::Persistent object, @@ -51,10 +51,10 @@ static void TrackDestructor(v8::Persistent object, { if(parameter) TrackDelete(static_cast(parameter)); -} - +} -// Convert a wide string to a V8 string. + +// Convert a wide string to a V8 string. static v8::Handle GetV8String(const std::wstring& str) { return v8::String::New( @@ -64,84 +64,84 @@ static v8::Handle GetV8String(const std::wstring& str) // Convert a V8 string to a wide string. static std::wstring GetWString(v8::Handle str) { - uint16_t* buf = new uint16_t[str->Length()+1]; - str->Write(buf); - std::wstring value = reinterpret_cast(buf); + uint16_t* buf = new uint16_t[str->Length()+1]; + str->Write(buf); + std::wstring value = reinterpret_cast(buf); delete [] buf; return value; } - - -// V8 function callback -static v8::Handle FunctionCallbackImpl(const v8::Arguments& args) -{ - v8::HandleScope handle_scope; - CefV8Handler* handler = - static_cast(v8::External::Unwrap(args.Data())); - - CefV8ValueList params; - for(int i = 0; i < args.Length(); i++) - params.push_back(new CefV8ValueImpl(args[i])); - - std::wstring func_name = - GetWString(v8::Handle::Cast(args.Callee()->GetName())); - CefRefPtr object = new CefV8ValueImpl(args.This()); - CefRefPtr retval; - std::wstring exception; - v8::Handle value = v8::Null(); - - if(handler->Execute(func_name, object, params, retval, exception)) { - if(!exception.empty()) - value = v8::ThrowException(GetV8String(exception)); - else { - CefV8ValueImpl* rv = static_cast(retval.get()); - if(rv) - value = rv->GetValue(); - } - } - - return value; -} - - -// V8 extension registration. - -class ExtensionWrapper : public v8::Extension { -public: - ExtensionWrapper(const char* extension_name, - const char* javascript_code, - CefV8Handler* handler) - : v8::Extension(extension_name, javascript_code), handler_(handler) - { - // The reference will be released when the application exits. - TrackAdd(new TrackBase(handler)); - } - - virtual v8::Handle GetNativeFunction( - v8::Handle name) - { - return v8::FunctionTemplate::New(FunctionCallbackImpl, - v8::External::New(handler_)); - } - - void UIT_RegisterExtension() - { - WebKit::registerExtension(this); - } - - void AddRef() {} - void Release() {} - -private: - CefV8Handler* handler_; -}; - + + +// V8 function callback +static v8::Handle FunctionCallbackImpl(const v8::Arguments& args) +{ + v8::HandleScope handle_scope; + CefV8Handler* handler = + static_cast(v8::External::Unwrap(args.Data())); + + CefV8ValueList params; + for(int i = 0; i < args.Length(); i++) + params.push_back(new CefV8ValueImpl(args[i])); + + std::wstring func_name = + GetWString(v8::Handle::Cast(args.Callee()->GetName())); + CefRefPtr object = new CefV8ValueImpl(args.This()); + CefRefPtr retval; + std::wstring exception; + v8::Handle value = v8::Null(); + + if(handler->Execute(func_name, object, params, retval, exception)) { + if(!exception.empty()) + value = v8::ThrowException(GetV8String(exception)); + else { + CefV8ValueImpl* rv = static_cast(retval.get()); + if(rv) + value = rv->GetValue(); + } + } + + return value; +} + + +// V8 extension registration. + +class ExtensionWrapper : public v8::Extension { +public: + ExtensionWrapper(const char* extension_name, + const char* javascript_code, + CefV8Handler* handler) + : v8::Extension(extension_name, javascript_code), handler_(handler) + { + // The reference will be released when the application exits. + TrackAdd(new TrackBase(handler)); + } + + virtual v8::Handle GetNativeFunction( + v8::Handle name) + { + return v8::FunctionTemplate::New(FunctionCallbackImpl, + v8::External::New(handler_)); + } + + void UIT_RegisterExtension() + { + WebKit::registerExtension(this); + } + + void AddRef() {} + void Release() {} + +private: + CefV8Handler* handler_; +}; + bool CefRegisterExtension(const std::wstring& extension_name, const std::wstring& javascript_code, CefRefPtr handler) { - // Verify that the context is already initialized - if(!_Context.get()) + // Verify that the context is already initialized + if(!_Context.get()) return false; if(!handler.get()) @@ -158,7 +158,7 @@ bool CefRegisterExtension(const std::wstring& extension_name, PostTask(FROM_HERE, NewRunnableMethod(wrapper, &ExtensionWrapper::UIT_RegisterExtension)); return true; -} +} // CefV8Value @@ -579,9 +579,9 @@ bool CefV8ValueImpl::GetKeys(std::vector& keys) v8::Local arr_keys = obj->GetPropertyNames(); uint32_t len = arr_keys->Length(); for(uint32_t i = 0; i < len; ++i) { - v8::Local value = arr_keys->Get(v8::Integer::New(i)); - std::wstring str = GetWString(value->ToString()); - if(!IsReservedKey(str)) + v8::Local value = arr_keys->Get(v8::Integer::New(i)); + std::wstring str = GetWString(value->ToString()); + if(!IsReservedKey(str)) keys.push_back(str); } rv = true; diff --git a/libcef/v8_impl.h b/libcef/v8_impl.h index 9d7b4e550..971623df3 100644 --- a/libcef/v8_impl.h +++ b/libcef/v8_impl.h @@ -1,15 +1,15 @@ -// 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 _V8_IMPL_H -#define _V8_IMPL_H - -#include "include/cef.h" -#include "v8/include/v8.h" - -class CefTrackObject; - +// 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 _V8_IMPL_H +#define _V8_IMPL_H + +#include "include/cef.h" +#include "v8/include/v8.h" + +class CefTrackObject; + class CefV8ValueImpl : public CefThreadSafeBase { public: @@ -57,5 +57,5 @@ protected: v8::Persistent v8_value_; CefTrackObject* tracker_; }; - -#endif //_V8_IMPL_H + +#endif //_V8_IMPL_H diff --git a/libcef/webview_host.cc b/libcef/webview_host.cc index 0c753dfa2..0a599ee5c 100644 --- a/libcef/webview_host.cc +++ b/libcef/webview_host.cc @@ -1,49 +1,49 @@ -// 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 "precompiled_libcef.h" -#include "webview_host.h" - -#include "base/gfx/platform_canvas.h" -#include "base/gfx/rect.h" -#include "base/gfx/size.h" -#include "base/win_util.h" -#include "webkit/glue/webview.h" - -static const wchar_t kWindowClassName[] = L"WebViewHost"; - -/*static*/ -WebViewHost* WebViewHost::Create(HWND parent_view, - WebViewDelegate* delegate, - const WebPreferences& prefs) { - WebViewHost* host = new WebViewHost(); - - static bool registered_class = false; - if (!registered_class) { - WNDCLASSEX wcex = {0}; - wcex.cbSize = sizeof(wcex); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = WebWidgetHost::WndProc; - wcex.hInstance = GetModuleHandle(NULL); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.lpszClassName = kWindowClassName; - RegisterClassEx(&wcex); - registered_class = true; - } - - host->view_ = CreateWindow(kWindowClassName, NULL, - WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 0, 0, - 0, 0, parent_view, NULL, - GetModuleHandle(NULL), NULL); - win_util::SetWindowUserData(host->view_, host); - - host->webwidget_ = WebView::Create(delegate, prefs); - - return host; -} - -WebView* WebViewHost::webview() const { - return static_cast(webwidget_); -} - +// 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 "precompiled_libcef.h" +#include "webview_host.h" + +#include "base/gfx/platform_canvas.h" +#include "base/gfx/rect.h" +#include "base/gfx/size.h" +#include "base/win_util.h" +#include "webkit/glue/webview.h" + +static const wchar_t kWindowClassName[] = L"WebViewHost"; + +/*static*/ +WebViewHost* WebViewHost::Create(HWND parent_view, + WebViewDelegate* delegate, + const WebPreferences& prefs) { + WebViewHost* host = new WebViewHost(); + + static bool registered_class = false; + if (!registered_class) { + WNDCLASSEX wcex = {0}; + wcex.cbSize = sizeof(wcex); + wcex.style = CS_DBLCLKS; + wcex.lpfnWndProc = WebWidgetHost::WndProc; + wcex.hInstance = GetModuleHandle(NULL); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.lpszClassName = kWindowClassName; + RegisterClassEx(&wcex); + registered_class = true; + } + + host->view_ = CreateWindow(kWindowClassName, NULL, + WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 0, 0, + 0, 0, parent_view, NULL, + GetModuleHandle(NULL), NULL); + win_util::SetWindowUserData(host->view_, host); + + host->webwidget_ = WebView::Create(delegate, prefs); + + return host; +} + +WebView* WebViewHost::webview() const { + return static_cast(webwidget_); +} + diff --git a/libcef/webview_host.h b/libcef/webview_host.h index 5ca8bb4e5..c8b0c5e66 100644 --- a/libcef/webview_host.h +++ b/libcef/webview_host.h @@ -1,37 +1,37 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef _WEBVIEW_HOST_H -#define _WEBVIEW_HOST_H - -#include "base/basictypes.h" -#include "base/gfx/native_widget_types.h" -#include "base/gfx/rect.h" -#include "webwidget_host.h" - -struct WebPreferences; -class WebView; -class WebViewDelegate; - -// This class is a simple ViewHandle-based host for a WebView -class WebViewHost : public WebWidgetHost { - public: - // The new instance is deleted once the associated ViewHandle is destroyed. - // The newly created window should be resized after it is created, using the - // MoveWindow (or equivalent) function. - static WebViewHost* Create(gfx::NativeView parent_window, - WebViewDelegate* delegate, - const WebPreferences& prefs); - - WebView* webview() const; - - protected: -#if defined(OS_WIN) - virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam) { - return false; - } -#endif -}; - -#endif // _WEBVIEW_HOST_H +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _WEBVIEW_HOST_H +#define _WEBVIEW_HOST_H + +#include "base/basictypes.h" +#include "base/gfx/native_widget_types.h" +#include "base/gfx/rect.h" +#include "webwidget_host.h" + +struct WebPreferences; +class WebView; +class WebViewDelegate; + +// This class is a simple ViewHandle-based host for a WebView +class WebViewHost : public WebWidgetHost { + public: + // The new instance is deleted once the associated ViewHandle is destroyed. + // The newly created window should be resized after it is created, using the + // MoveWindow (or equivalent) function. + static WebViewHost* Create(gfx::NativeView parent_window, + WebViewDelegate* delegate, + const WebPreferences& prefs); + + WebView* webview() const; + + protected: +#if defined(OS_WIN) + virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam) { + return false; + } +#endif +}; + +#endif // _WEBVIEW_HOST_H diff --git a/libcef/webwidget_host.cc b/libcef/webwidget_host.cc index 65de32124..a7fff9401 100644 --- a/libcef/webwidget_host.cc +++ b/libcef/webwidget_host.cc @@ -1,366 +1,366 @@ -// Copyright (c) 2008-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 "precompiled_libcef.h" -#include "webwidget_host.h" - -#include "base/gfx/platform_canvas.h" -#include "base/gfx/rect.h" -#include "base/logging.h" -#include "base/win_util.h" -#include "webkit/api/public/WebInputEvent.h" -#include "webkit/api/public/WebPopupMenu.h" -#include "webkit/api/public/WebScreenInfo.h" -#include "webkit/api/public/WebSize.h" -#include "webkit/api/public/win/WebInputEventFactory.h" -#include "webkit/api/public/win/WebScreenInfoFactory.h" - -using WebKit::WebInputEvent; -using WebKit::WebInputEventFactory; -using WebKit::WebKeyboardEvent; -using WebKit::WebMouseEvent; -using WebKit::WebMouseWheelEvent; -using WebKit::WebPopupMenu; -using WebKit::WebScreenInfo; -using WebKit::WebScreenInfoFactory; -using WebKit::WebSize; -using WebKit::WebWidget; -using WebKit::WebWidgetClient; - -static const wchar_t kWindowClassName[] = L"WebWidgetHost"; - -/*static*/ -WebWidgetHost* WebWidgetHost::Create(HWND parent_view, - WebWidgetClient* client) { - WebWidgetHost* host = new WebWidgetHost(); - - static bool registered_class = false; - if (!registered_class) { - WNDCLASSEX wcex = {0}; - wcex.cbSize = sizeof(wcex); - wcex.style = CS_DBLCLKS; - wcex.lpfnWndProc = WebWidgetHost::WndProc; - wcex.hInstance = GetModuleHandle(NULL); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.lpszClassName = kWindowClassName; - RegisterClassEx(&wcex); - registered_class = true; - } - - host->view_ = CreateWindowEx(WS_EX_TOOLWINDOW, - kWindowClassName, kWindowClassName, WS_POPUP, - 0, 0, 0, 0, - parent_view, NULL, GetModuleHandle(NULL), NULL); - - win_util::SetWindowUserData(host->view_, host); - - host->webwidget_ = WebPopupMenu::create(client); - - return host; -} - -/*static*/ -static WebWidgetHost* FromWindow(HWND view) { - return reinterpret_cast(win_util::GetWindowUserData(view)); -} - -/*static*/ -LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam, - LPARAM lparam) { - WebWidgetHost* host = FromWindow(hwnd); - if (host && !host->WndProc(message, wparam, lparam)) { - switch (message) { - case WM_PAINT: { - RECT rect; - if (GetUpdateRect(hwnd, &rect, FALSE)) { - host->UpdatePaintRect(gfx::Rect(rect)); - } - host->Paint(); - return 0; - } - - case WM_ERASEBKGND: - // Do nothing here to avoid flashing, the background will be erased - // during painting. - return 0; - - case WM_SIZE: - host->Resize(lparam); - return 0; - - case WM_MOUSEMOVE: - case WM_MOUSELEAVE: - case WM_LBUTTONDOWN: - case WM_MBUTTONDOWN: - case WM_RBUTTONDOWN: - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - case WM_LBUTTONDBLCLK: - case WM_MBUTTONDBLCLK: - case WM_RBUTTONDBLCLK: - host->MouseEvent(message, wparam, lparam); - break; - - case WM_MOUSEWHEEL: - host->WheelEvent(wparam, lparam); - break; - - case WM_CAPTURECHANGED: - case WM_CANCELMODE: - host->CaptureLostEvent(); - break; - - // TODO(darin): add WM_SYSKEY{DOWN/UP} to capture ALT key actions - case WM_KEYDOWN: - case WM_KEYUP: - case WM_SYSKEYDOWN: - case WM_SYSKEYUP: - case WM_CHAR: - case WM_SYSCHAR: - case WM_IME_CHAR: - host->KeyEvent(message, wparam, lparam); - break; - - case WM_SETFOCUS: - host->SetFocus(true); - break; - - case WM_KILLFOCUS: - host->SetFocus(false); - break; - } - } - - return DefWindowProc(hwnd, message, wparam, lparam);; -} - -void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) { - DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting"; - - // If this invalidate overlaps with a pending scroll, then we have to - // downgrade to invalidating the scroll rect. - if (damaged_rect.Intersects(scroll_rect_)) { - paint_rect_ = paint_rect_.Union(scroll_rect_); - ResetScrollRect(); - } - paint_rect_ = paint_rect_.Union(damaged_rect); - - RECT r = damaged_rect.ToRECT(); - InvalidateRect(view_, &r, FALSE); -} - -void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { - if (dx != 0 && dy != 0) { - // We only support uni-directional scroll - DidScrollRect(0, dy, clip_rect); - dy = 0; - } - - // If we already have a pending scroll operation or if this scroll operation - // intersects the existing paint region, then just failover to invalidating. - if (!scroll_rect_.IsEmpty() || paint_rect_.Intersects(clip_rect)) { - paint_rect_ = paint_rect_.Union(scroll_rect_); - ResetScrollRect(); - paint_rect_ = paint_rect_.Union(clip_rect); - } - - // We will perform scrolling lazily, when requested to actually paint. - scroll_rect_ = clip_rect; - scroll_dx_ = dx; - scroll_dy_ = dy; - - RECT r = clip_rect.ToRECT(); - InvalidateRect(view_, &r, FALSE); -} - -void WebWidgetHost::SetCursor(HCURSOR cursor) { - SetClassLong(view_, GCL_HCURSOR, - static_cast(reinterpret_cast(cursor))); - ::SetCursor(cursor); -} - -void WebWidgetHost::DiscardBackingStore() { - canvas_.reset(); -} - -WebWidgetHost::WebWidgetHost() - : view_(NULL), - webwidget_(NULL), - track_mouse_leave_(false), - scroll_dx_(0), - scroll_dy_(0) { - set_painting(false); -} - -WebWidgetHost::~WebWidgetHost() { - win_util::SetWindowUserData(view_, 0); - - TrackMouseLeave(false); -} - -bool WebWidgetHost::WndProc(UINT message, WPARAM wparam, LPARAM lparam) { - switch (message) { - case WM_ACTIVATE: - if (wparam == WA_INACTIVE) { - PostMessage(view_, WM_CLOSE, 0, 0); - return true; - } - break; - } - - return false; -} - -void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) { - paint_rect_ = paint_rect_.Union(rect); -} - -void WebWidgetHost::Paint() { - RECT r; - GetClientRect(view_, &r); - gfx::Rect client_rect(r); - - // Allocate a canvas if necessary - if (!canvas_.get()) { - ResetScrollRect(); - paint_rect_ = client_rect; - canvas_.reset(new skia::PlatformCanvas( - paint_rect_.width(), paint_rect_.height(), true)); - } - - // This may result in more invalidation - webwidget_->layout(); - - // Scroll the canvas if necessary - scroll_rect_ = client_rect.Intersect(scroll_rect_); - if (!scroll_rect_.IsEmpty()) { - HDC hdc = canvas_->getTopPlatformDevice().getBitmapDC(); - - RECT damaged_rect, r = scroll_rect_.ToRECT(); - ScrollDC(hdc, scroll_dx_, scroll_dy_, NULL, &r, NULL, &damaged_rect); - - PaintRect(gfx::Rect(damaged_rect)); - } - ResetScrollRect(); - - // Paint the canvas if necessary. Allow painting to generate extra rects the - // first time we call it. This is necessary because some WebCore rendering - // objects update their layout only when painted. - for (int i = 0; i < 2; ++i) { - paint_rect_ = client_rect.Intersect(paint_rect_); - if (!paint_rect_.IsEmpty()) { - gfx::Rect rect(paint_rect_); - paint_rect_ = gfx::Rect(); - - DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations"; - PaintRect(rect); - } - } - DCHECK(paint_rect_.IsEmpty()); - - // Paint to the screen - PAINTSTRUCT ps; - BeginPaint(view_, &ps); - canvas_->getTopPlatformDevice().drawToHDC(ps.hdc, - ps.rcPaint.left, - ps.rcPaint.top, - &ps.rcPaint); - EndPaint(view_, &ps); - - // Draw children - UpdateWindow(view_); -} - -WebScreenInfo WebWidgetHost::GetScreenInfo() { - return WebScreenInfoFactory::screenInfo(view_); -} - -void WebWidgetHost::Resize(LPARAM lparam) { - // Force an entire re-paint. TODO(darin): Maybe reuse this memory buffer. - DiscardBackingStore(); - - webwidget_->resize(WebSize(LOWORD(lparam), HIWORD(lparam))); -} - -void WebWidgetHost::MouseEvent(UINT message, WPARAM wparam, LPARAM lparam) { - const WebMouseEvent& event = WebInputEventFactory::mouseEvent( - view_, message, wparam, lparam); - switch (event.type) { - case WebInputEvent::MouseMove: - TrackMouseLeave(true); - break; - case WebInputEvent::MouseLeave: - TrackMouseLeave(false); - break; - case WebInputEvent::MouseDown: - SetCapture(view_); - // This mimics a temporary workaround in RenderWidgetHostViewWin - // for bug 765011 to get focus when the mouse is clicked. This - // happens after the mouse down event is sent to the renderer - // because normally Windows does a WM_SETFOCUS after WM_LBUTTONDOWN. - ::SetFocus(view_); - break; - case WebInputEvent::MouseUp: - if (GetCapture() == view_) - ReleaseCapture(); - break; - } - webwidget_->handleInputEvent(event); -} - -void WebWidgetHost::WheelEvent(WPARAM wparam, LPARAM lparam) { - const WebMouseWheelEvent& event = WebInputEventFactory::mouseWheelEvent( - view_, WM_MOUSEWHEEL, wparam, lparam); - webwidget_->handleInputEvent(event); -} - -void WebWidgetHost::KeyEvent(UINT message, WPARAM wparam, LPARAM lparam) { - const WebKeyboardEvent& event = WebInputEventFactory::keyboardEvent( - view_, message, wparam, lparam); - webwidget_->handleInputEvent(event); -} - -void WebWidgetHost::CaptureLostEvent() { - webwidget_->mouseCaptureLost(); -} - -void WebWidgetHost::SetFocus(bool enable) { - webwidget_->setFocus(enable); -} - -void WebWidgetHost::TrackMouseLeave(bool track) { - if (track == track_mouse_leave_) - return; - track_mouse_leave_ = track; - - DCHECK(view_); - - TRACKMOUSEEVENT tme; - tme.cbSize = sizeof(TRACKMOUSEEVENT); - tme.dwFlags = TME_LEAVE; - if (!track_mouse_leave_) - tme.dwFlags |= TME_CANCEL; - tme.hwndTrack = view_; - - TrackMouseEvent(&tme); -} - -void WebWidgetHost::ResetScrollRect() { - scroll_rect_ = gfx::Rect(); - scroll_dx_ = 0; - scroll_dy_ = 0; -} - -void WebWidgetHost::PaintRect(const gfx::Rect& rect) { -#ifndef NDEBUG - DCHECK(!painting_); -#endif - DCHECK(canvas_.get()); - - set_painting(true); - webwidget_->paint(canvas_.get(), rect); - set_painting(false); -} +// Copyright (c) 2008-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 "precompiled_libcef.h" +#include "webwidget_host.h" + +#include "base/gfx/platform_canvas.h" +#include "base/gfx/rect.h" +#include "base/logging.h" +#include "base/win_util.h" +#include "webkit/api/public/WebInputEvent.h" +#include "webkit/api/public/WebPopupMenu.h" +#include "webkit/api/public/WebScreenInfo.h" +#include "webkit/api/public/WebSize.h" +#include "webkit/api/public/win/WebInputEventFactory.h" +#include "webkit/api/public/win/WebScreenInfoFactory.h" + +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebKeyboardEvent; +using WebKit::WebMouseEvent; +using WebKit::WebMouseWheelEvent; +using WebKit::WebPopupMenu; +using WebKit::WebScreenInfo; +using WebKit::WebScreenInfoFactory; +using WebKit::WebSize; +using WebKit::WebWidget; +using WebKit::WebWidgetClient; + +static const wchar_t kWindowClassName[] = L"WebWidgetHost"; + +/*static*/ +WebWidgetHost* WebWidgetHost::Create(HWND parent_view, + WebWidgetClient* client) { + WebWidgetHost* host = new WebWidgetHost(); + + static bool registered_class = false; + if (!registered_class) { + WNDCLASSEX wcex = {0}; + wcex.cbSize = sizeof(wcex); + wcex.style = CS_DBLCLKS; + wcex.lpfnWndProc = WebWidgetHost::WndProc; + wcex.hInstance = GetModuleHandle(NULL); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.lpszClassName = kWindowClassName; + RegisterClassEx(&wcex); + registered_class = true; + } + + host->view_ = CreateWindowEx(WS_EX_TOOLWINDOW, + kWindowClassName, kWindowClassName, WS_POPUP, + 0, 0, 0, 0, + parent_view, NULL, GetModuleHandle(NULL), NULL); + + win_util::SetWindowUserData(host->view_, host); + + host->webwidget_ = WebPopupMenu::create(client); + + return host; +} + +/*static*/ +static WebWidgetHost* FromWindow(HWND view) { + return reinterpret_cast(win_util::GetWindowUserData(view)); +} + +/*static*/ +LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam, + LPARAM lparam) { + WebWidgetHost* host = FromWindow(hwnd); + if (host && !host->WndProc(message, wparam, lparam)) { + switch (message) { + case WM_PAINT: { + RECT rect; + if (GetUpdateRect(hwnd, &rect, FALSE)) { + host->UpdatePaintRect(gfx::Rect(rect)); + } + host->Paint(); + return 0; + } + + case WM_ERASEBKGND: + // Do nothing here to avoid flashing, the background will be erased + // during painting. + return 0; + + case WM_SIZE: + host->Resize(lparam); + return 0; + + case WM_MOUSEMOVE: + case WM_MOUSELEAVE: + case WM_LBUTTONDOWN: + case WM_MBUTTONDOWN: + case WM_RBUTTONDOWN: + case WM_LBUTTONUP: + case WM_MBUTTONUP: + case WM_RBUTTONUP: + case WM_LBUTTONDBLCLK: + case WM_MBUTTONDBLCLK: + case WM_RBUTTONDBLCLK: + host->MouseEvent(message, wparam, lparam); + break; + + case WM_MOUSEWHEEL: + host->WheelEvent(wparam, lparam); + break; + + case WM_CAPTURECHANGED: + case WM_CANCELMODE: + host->CaptureLostEvent(); + break; + + // TODO(darin): add WM_SYSKEY{DOWN/UP} to capture ALT key actions + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + case WM_CHAR: + case WM_SYSCHAR: + case WM_IME_CHAR: + host->KeyEvent(message, wparam, lparam); + break; + + case WM_SETFOCUS: + host->SetFocus(true); + break; + + case WM_KILLFOCUS: + host->SetFocus(false); + break; + } + } + + return DefWindowProc(hwnd, message, wparam, lparam);; +} + +void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) { + DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting"; + + // If this invalidate overlaps with a pending scroll, then we have to + // downgrade to invalidating the scroll rect. + if (damaged_rect.Intersects(scroll_rect_)) { + paint_rect_ = paint_rect_.Union(scroll_rect_); + ResetScrollRect(); + } + paint_rect_ = paint_rect_.Union(damaged_rect); + + RECT r = damaged_rect.ToRECT(); + InvalidateRect(view_, &r, FALSE); +} + +void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { + if (dx != 0 && dy != 0) { + // We only support uni-directional scroll + DidScrollRect(0, dy, clip_rect); + dy = 0; + } + + // If we already have a pending scroll operation or if this scroll operation + // intersects the existing paint region, then just failover to invalidating. + if (!scroll_rect_.IsEmpty() || paint_rect_.Intersects(clip_rect)) { + paint_rect_ = paint_rect_.Union(scroll_rect_); + ResetScrollRect(); + paint_rect_ = paint_rect_.Union(clip_rect); + } + + // We will perform scrolling lazily, when requested to actually paint. + scroll_rect_ = clip_rect; + scroll_dx_ = dx; + scroll_dy_ = dy; + + RECT r = clip_rect.ToRECT(); + InvalidateRect(view_, &r, FALSE); +} + +void WebWidgetHost::SetCursor(HCURSOR cursor) { + SetClassLong(view_, GCL_HCURSOR, + static_cast(reinterpret_cast(cursor))); + ::SetCursor(cursor); +} + +void WebWidgetHost::DiscardBackingStore() { + canvas_.reset(); +} + +WebWidgetHost::WebWidgetHost() + : view_(NULL), + webwidget_(NULL), + track_mouse_leave_(false), + scroll_dx_(0), + scroll_dy_(0) { + set_painting(false); +} + +WebWidgetHost::~WebWidgetHost() { + win_util::SetWindowUserData(view_, 0); + + TrackMouseLeave(false); +} + +bool WebWidgetHost::WndProc(UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_ACTIVATE: + if (wparam == WA_INACTIVE) { + PostMessage(view_, WM_CLOSE, 0, 0); + return true; + } + break; + } + + return false; +} + +void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) { + paint_rect_ = paint_rect_.Union(rect); +} + +void WebWidgetHost::Paint() { + RECT r; + GetClientRect(view_, &r); + gfx::Rect client_rect(r); + + // Allocate a canvas if necessary + if (!canvas_.get()) { + ResetScrollRect(); + paint_rect_ = client_rect; + canvas_.reset(new skia::PlatformCanvas( + paint_rect_.width(), paint_rect_.height(), true)); + } + + // This may result in more invalidation + webwidget_->layout(); + + // Scroll the canvas if necessary + scroll_rect_ = client_rect.Intersect(scroll_rect_); + if (!scroll_rect_.IsEmpty()) { + HDC hdc = canvas_->getTopPlatformDevice().getBitmapDC(); + + RECT damaged_rect, r = scroll_rect_.ToRECT(); + ScrollDC(hdc, scroll_dx_, scroll_dy_, NULL, &r, NULL, &damaged_rect); + + PaintRect(gfx::Rect(damaged_rect)); + } + ResetScrollRect(); + + // Paint the canvas if necessary. Allow painting to generate extra rects the + // first time we call it. This is necessary because some WebCore rendering + // objects update their layout only when painted. + for (int i = 0; i < 2; ++i) { + paint_rect_ = client_rect.Intersect(paint_rect_); + if (!paint_rect_.IsEmpty()) { + gfx::Rect rect(paint_rect_); + paint_rect_ = gfx::Rect(); + + DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations"; + PaintRect(rect); + } + } + DCHECK(paint_rect_.IsEmpty()); + + // Paint to the screen + PAINTSTRUCT ps; + BeginPaint(view_, &ps); + canvas_->getTopPlatformDevice().drawToHDC(ps.hdc, + ps.rcPaint.left, + ps.rcPaint.top, + &ps.rcPaint); + EndPaint(view_, &ps); + + // Draw children + UpdateWindow(view_); +} + +WebScreenInfo WebWidgetHost::GetScreenInfo() { + return WebScreenInfoFactory::screenInfo(view_); +} + +void WebWidgetHost::Resize(LPARAM lparam) { + // Force an entire re-paint. TODO(darin): Maybe reuse this memory buffer. + DiscardBackingStore(); + + webwidget_->resize(WebSize(LOWORD(lparam), HIWORD(lparam))); +} + +void WebWidgetHost::MouseEvent(UINT message, WPARAM wparam, LPARAM lparam) { + const WebMouseEvent& event = WebInputEventFactory::mouseEvent( + view_, message, wparam, lparam); + switch (event.type) { + case WebInputEvent::MouseMove: + TrackMouseLeave(true); + break; + case WebInputEvent::MouseLeave: + TrackMouseLeave(false); + break; + case WebInputEvent::MouseDown: + SetCapture(view_); + // This mimics a temporary workaround in RenderWidgetHostViewWin + // for bug 765011 to get focus when the mouse is clicked. This + // happens after the mouse down event is sent to the renderer + // because normally Windows does a WM_SETFOCUS after WM_LBUTTONDOWN. + ::SetFocus(view_); + break; + case WebInputEvent::MouseUp: + if (GetCapture() == view_) + ReleaseCapture(); + break; + } + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::WheelEvent(WPARAM wparam, LPARAM lparam) { + const WebMouseWheelEvent& event = WebInputEventFactory::mouseWheelEvent( + view_, WM_MOUSEWHEEL, wparam, lparam); + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::KeyEvent(UINT message, WPARAM wparam, LPARAM lparam) { + const WebKeyboardEvent& event = WebInputEventFactory::keyboardEvent( + view_, message, wparam, lparam); + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::CaptureLostEvent() { + webwidget_->mouseCaptureLost(); +} + +void WebWidgetHost::SetFocus(bool enable) { + webwidget_->setFocus(enable); +} + +void WebWidgetHost::TrackMouseLeave(bool track) { + if (track == track_mouse_leave_) + return; + track_mouse_leave_ = track; + + DCHECK(view_); + + TRACKMOUSEEVENT tme; + tme.cbSize = sizeof(TRACKMOUSEEVENT); + tme.dwFlags = TME_LEAVE; + if (!track_mouse_leave_) + tme.dwFlags |= TME_CANCEL; + tme.hwndTrack = view_; + + TrackMouseEvent(&tme); +} + +void WebWidgetHost::ResetScrollRect() { + scroll_rect_ = gfx::Rect(); + scroll_dx_ = 0; + scroll_dy_ = 0; +} + +void WebWidgetHost::PaintRect(const gfx::Rect& rect) { +#ifndef NDEBUG + DCHECK(!painting_); +#endif + DCHECK(canvas_.get()); + + set_painting(true); + webwidget_->paint(canvas_.get(), rect); + set_painting(false); +} diff --git a/libcef/webwidget_host.h b/libcef/webwidget_host.h index 90796d832..40ee6dc5a 100644 --- a/libcef/webwidget_host.h +++ b/libcef/webwidget_host.h @@ -1,128 +1,128 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef _WEBWIDGET_HOST_H -#define _WEBWIDGET_HOST_H - -#include "base/basictypes.h" -#include "base/gfx/native_widget_types.h" -#include "base/gfx/platform_canvas.h" -#include "base/gfx/rect.h" -#include "base/scoped_ptr.h" -#include "skia/ext/platform_canvas.h" - -namespace gfx { -class Size; -} - -namespace WebKit { -class WebWidget; -class WebWidgetClient; -struct WebScreenInfo; -} - -// This class is a simple ViewHandle-based host for a WebWidget -class WebWidgetHost { - public: - // The new instance is deleted once the associated ViewHandle is destroyed. - // The newly created window should be resized after it is created, using the - // MoveWindow (or equivalent) function. - static WebWidgetHost* Create(gfx::NativeView parent_view, - WebKit::WebWidgetClient* client); - -#if defined(OS_MACOSX) - static void HandleEvent(gfx::NativeView view, NSEvent *event); -#endif - - gfx::NativeView view_handle() const { return view_; } - WebKit::WebWidget* webwidget() const { return webwidget_; } - - void DidInvalidateRect(const gfx::Rect& rect); - void DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect); -#if defined(OS_WIN) - void SetCursor(HCURSOR cursor); -#endif - - void DiscardBackingStore(); - // Allow clients to update the paint rect. For example, if we get a gdk - // expose or WM_PAINT event, we need to update the paint rect. - void UpdatePaintRect(const gfx::Rect& rect); - void Paint(); - - skia::PlatformCanvas* canvas() const { return canvas_.get(); } - - WebKit::WebScreenInfo GetScreenInfo(); - - protected: - WebWidgetHost(); - ~WebWidgetHost(); - -#if defined(OS_WIN) - // Per-class wndproc. Returns true if the event should be swallowed. - virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam); - - void Resize(LPARAM lparam); - void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam); - void WheelEvent(WPARAM wparam, LPARAM lparam); - void KeyEvent(UINT message, WPARAM wparam, LPARAM lparam); - void CaptureLostEvent(); - void SetFocus(bool enable); - - static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); -#elif defined(OS_MACOSX) - // These need to be called from a non-subclass, so they need to be public. - public: - void Resize(const gfx::Rect& rect); - void MouseEvent(NSEvent *); - void WheelEvent(NSEvent *); - void KeyEvent(NSEvent *); - void SetFocus(bool enable); - protected: -#elif defined(OS_LINUX) - public: - // --------------------------------------------------------------------------- - // This is needed on Linux because the GtkWidget creation is the same between - // both web view hosts and web widget hosts. The Windows code manages this by - // reusing the WndProc function (static, above). However, GTK doesn't use a - // single big callback function like that so we have a static function that - // sets up a GtkWidget correctly. - // parent: a GtkBox to pack the new widget at the end of - // host: a pointer to a WebWidgetHost (or subclass thereof) - // --------------------------------------------------------------------------- - static gfx::NativeView CreateWindow(gfx::NativeView parent_view, - WebWidgetHost* host); - void WindowDestroyed(); - void Resize(const gfx::Size& size); -#endif - - void TrackMouseLeave(bool enable); - void ResetScrollRect(); - void PaintRect(const gfx::Rect& rect); - - void set_painting(bool value) { -#ifndef NDEBUG - painting_ = value; -#endif - } - - gfx::NativeView view_; - WebKit::WebWidget* webwidget_; - scoped_ptr canvas_; - - // specifies the portion of the webwidget that needs painting - gfx::Rect paint_rect_; - - // specifies the portion of the webwidget that needs scrolling - gfx::Rect scroll_rect_; - int scroll_dx_; - int scroll_dy_; - - bool track_mouse_leave_; - -#ifndef NDEBUG - bool painting_; -#endif -}; - -#endif // _WEBWIDGET_HOST_H +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _WEBWIDGET_HOST_H +#define _WEBWIDGET_HOST_H + +#include "base/basictypes.h" +#include "base/gfx/native_widget_types.h" +#include "base/gfx/platform_canvas.h" +#include "base/gfx/rect.h" +#include "base/scoped_ptr.h" +#include "skia/ext/platform_canvas.h" + +namespace gfx { +class Size; +} + +namespace WebKit { +class WebWidget; +class WebWidgetClient; +struct WebScreenInfo; +} + +// This class is a simple ViewHandle-based host for a WebWidget +class WebWidgetHost { + public: + // The new instance is deleted once the associated ViewHandle is destroyed. + // The newly created window should be resized after it is created, using the + // MoveWindow (or equivalent) function. + static WebWidgetHost* Create(gfx::NativeView parent_view, + WebKit::WebWidgetClient* client); + +#if defined(OS_MACOSX) + static void HandleEvent(gfx::NativeView view, NSEvent *event); +#endif + + gfx::NativeView view_handle() const { return view_; } + WebKit::WebWidget* webwidget() const { return webwidget_; } + + void DidInvalidateRect(const gfx::Rect& rect); + void DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect); +#if defined(OS_WIN) + void SetCursor(HCURSOR cursor); +#endif + + void DiscardBackingStore(); + // Allow clients to update the paint rect. For example, if we get a gdk + // expose or WM_PAINT event, we need to update the paint rect. + void UpdatePaintRect(const gfx::Rect& rect); + void Paint(); + + skia::PlatformCanvas* canvas() const { return canvas_.get(); } + + WebKit::WebScreenInfo GetScreenInfo(); + + protected: + WebWidgetHost(); + ~WebWidgetHost(); + +#if defined(OS_WIN) + // Per-class wndproc. Returns true if the event should be swallowed. + virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam); + + void Resize(LPARAM lparam); + void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam); + void WheelEvent(WPARAM wparam, LPARAM lparam); + void KeyEvent(UINT message, WPARAM wparam, LPARAM lparam); + void CaptureLostEvent(); + void SetFocus(bool enable); + + static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); +#elif defined(OS_MACOSX) + // These need to be called from a non-subclass, so they need to be public. + public: + void Resize(const gfx::Rect& rect); + void MouseEvent(NSEvent *); + void WheelEvent(NSEvent *); + void KeyEvent(NSEvent *); + void SetFocus(bool enable); + protected: +#elif defined(OS_LINUX) + public: + // --------------------------------------------------------------------------- + // This is needed on Linux because the GtkWidget creation is the same between + // both web view hosts and web widget hosts. The Windows code manages this by + // reusing the WndProc function (static, above). However, GTK doesn't use a + // single big callback function like that so we have a static function that + // sets up a GtkWidget correctly. + // parent: a GtkBox to pack the new widget at the end of + // host: a pointer to a WebWidgetHost (or subclass thereof) + // --------------------------------------------------------------------------- + static gfx::NativeView CreateWindow(gfx::NativeView parent_view, + WebWidgetHost* host); + void WindowDestroyed(); + void Resize(const gfx::Size& size); +#endif + + void TrackMouseLeave(bool enable); + void ResetScrollRect(); + void PaintRect(const gfx::Rect& rect); + + void set_painting(bool value) { +#ifndef NDEBUG + painting_ = value; +#endif + } + + gfx::NativeView view_; + WebKit::WebWidget* webwidget_; + scoped_ptr canvas_; + + // specifies the portion of the webwidget that needs painting + gfx::Rect paint_rect_; + + // specifies the portion of the webwidget that needs scrolling + gfx::Rect scroll_rect_; + int scroll_dx_; + int scroll_dy_; + + bool track_mouse_leave_; + +#ifndef NDEBUG + bool painting_; +#endif +}; + +#endif // _WEBWIDGET_HOST_H diff --git a/libcef_dll/cef_logging.h b/libcef_dll/cef_logging.h index 8645602ed..52ef4bb7c 100644 --- a/libcef_dll/cef_logging.h +++ b/libcef_dll/cef_logging.h @@ -1,10 +1,10 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that +// 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. -#ifdef BUILDING_CEF_SHARED -#include "base/logging.h" -#else -#include -#define DCHECK(condition) assert(condition) +#ifdef BUILDING_CEF_SHARED +#include "base/logging.h" +#else +#include +#define DCHECK(condition) assert(condition) #endif diff --git a/libcef_dll/libcef_dll.cc b/libcef_dll/libcef_dll.cc index 0ba2503ec..4cf793cb7 100644 --- a/libcef_dll/libcef_dll.cc +++ b/libcef_dll/libcef_dll.cc @@ -1,7 +1,7 @@ -// 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. - +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + #include "precompiled_libcef.h" #include "cef.h" #include "cef_capi.h" @@ -17,7 +17,7 @@ #include "cpptoc/v8value_cpptoc.h" #include "ctocpp/handler_ctocpp.h" #include "ctocpp/v8handler_ctocpp.h" -#include "base/string_util.h" +#include "base/string_util.h" CEF_EXPORT int cef_initialize(int multi_threaded_message_loop, @@ -33,7 +33,7 @@ CEF_EXPORT void cef_shutdown() { CefShutdown(); -#ifdef _DEBUG +#ifdef _DEBUG // Check that all wrapper objects have been destroyed DCHECK(CefBrowserCppToC::DebugObjCt == 0); DCHECK(CefRequestCppToC::DebugObjCt == 0); @@ -44,7 +44,7 @@ CEF_EXPORT void cef_shutdown() DCHECK(CefV8ValueCppToC::DebugObjCt == 0); DCHECK(CefHandlerCToCpp::DebugObjCt == 0); DCHECK(CefV8HandlerCToCpp::DebugObjCt == 0); -#endif // _DEBUG +#endif // _DEBUG } CEF_EXPORT void cef_do_message_loop_work() @@ -81,24 +81,24 @@ CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info) pluginInfo.version = plugin_info->version; pluginInfo.description = plugin_info->description; - std::vector mime_types, file_extensions; - std::vector descriptions; - SplitString(plugin_info->mime_types, '|', &mime_types); - SplitString(plugin_info->file_extensions, '|', &file_extensions); + std::vector mime_types, file_extensions; + std::vector descriptions; + SplitString(plugin_info->mime_types, '|', &mime_types); + SplitString(plugin_info->file_extensions, '|', &file_extensions); SplitString(plugin_info->type_descriptions, '|', &descriptions); - for (size_t i = 0; i < mime_types.size(); ++i) { - CefPluginMimeType mimeType; - - mimeType.mime_type = mime_types[i]; - - if (file_extensions.size() > i) - SplitString(file_extensions[i], ',', &mimeType.file_extensions); - - if (descriptions.size() > i) - mimeType.description = descriptions[i]; - - pluginInfo.mime_types.push_back(mimeType); + for (size_t i = 0; i < mime_types.size(); ++i) { + CefPluginMimeType mimeType; + + mimeType.mime_type = mime_types[i]; + + if (file_extensions.size() > i) + SplitString(file_extensions[i], ',', &mimeType.file_extensions); + + if (descriptions.size() > i) + mimeType.description = descriptions[i]; + + pluginInfo.mime_types.push_back(mimeType); } pluginInfo.np_getentrypoints = plugin_info->np_getentrypoints; diff --git a/libcef_dll/libcef_dll.vsprops b/libcef_dll/libcef_dll.vsprops index 677b14f4f..4e3660cc5 100644 --- a/libcef_dll/libcef_dll.vsprops +++ b/libcef_dll/libcef_dll.vsprops @@ -1,22 +1,22 @@ - - - - - - + + + + + + diff --git a/libcef_dll/precompiled_libcef.cc b/libcef_dll/precompiled_libcef.cc index 76e53843d..12d7b350e 100644 --- a/libcef_dll/precompiled_libcef.cc +++ b/libcef_dll/precompiled_libcef.cc @@ -1,5 +1,5 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that -// can be found in the LICENSE file. - -#include "precompiled_libcef.h" +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "precompiled_libcef.h" diff --git a/libcef_dll/precompiled_libcef.h b/libcef_dll/precompiled_libcef.h index 6fd8b407a..775dbf535 100644 --- a/libcef_dll/precompiled_libcef.h +++ b/libcef_dll/precompiled_libcef.h @@ -1,7 +1,7 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that -// can be found in the LICENSE file. - -#include -#include -#include +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include +#include diff --git a/libcef_dll/transfer_util.cpp b/libcef_dll/transfer_util.cpp index 393fbd160..0de583ce8 100644 --- a/libcef_dll/transfer_util.cpp +++ b/libcef_dll/transfer_util.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "precompiled_libcef.h" @@ -45,13 +45,13 @@ void transfer_string_map_contents(const std::map& fr void transfer_string_contents(const std::wstring& fromString, cef_string_t* toString) { - if(*toString == NULL || *toString != fromString) { - if(*toString) { - cef_string_free(*toString); - *toString = NULL; - } - if(!fromString.empty()) - *toString = cef_string_alloc(fromString.c_str()); + if(*toString == NULL || *toString != fromString) { + if(*toString) { + cef_string_free(*toString); + *toString = NULL; + } + if(!fromString.empty()) + *toString = cef_string_alloc(fromString.c_str()); } } diff --git a/libcef_dll/transfer_util.h b/libcef_dll/transfer_util.h index 00a3398f7..dd0f462f0 100644 --- a/libcef_dll/transfer_util.h +++ b/libcef_dll/transfer_util.h @@ -1,5 +1,5 @@ -// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights -// reserved. Use of this source code is governed by a BSD-style license that +// 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 _TRANSFER_UTIL_H diff --git a/libcef_dll/wrapper/libcef_dll_wrapper.cc b/libcef_dll/wrapper/libcef_dll_wrapper.cc index c021ff875..86201da4b 100644 --- a/libcef_dll/wrapper/libcef_dll_wrapper.cc +++ b/libcef_dll/wrapper/libcef_dll_wrapper.cc @@ -1,7 +1,7 @@ -// 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. - +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + #include "../precompiled_libcef.h" #include "cef.h" #include "cef_capi.h" @@ -28,7 +28,7 @@ void CefShutdown() { cef_shutdown(); -#ifdef _DEBUG +#ifdef _DEBUG // Check that all wrapper objects have been destroyed DCHECK(CefHandlerCppToC::DebugObjCt == 0); DCHECK(CefV8HandlerCppToC::DebugObjCt == 0); @@ -39,7 +39,7 @@ void CefShutdown() DCHECK(CefStreamReaderCToCpp::DebugObjCt == 0); DCHECK(CefStreamWriterCToCpp::DebugObjCt == 0); DCHECK(CefV8ValueCToCpp::DebugObjCt == 0); -#endif // _DEBUG +#endif // _DEBUG } void CefDoMessageLoopWork() @@ -59,38 +59,38 @@ bool CefRegisterPlugin(const struct CefPluginInfo& plugin_info) { cef_plugin_info_t pluginInfo; - pluginInfo.unique_name = plugin_info.unique_name.c_str(); - pluginInfo.display_name = plugin_info.display_name.c_str(); - pluginInfo.version =plugin_info.version.c_str(); - pluginInfo.description = plugin_info.description.c_str(); - - std::wstring mimeTypes, fileExtensions, typeDescriptions; - - for(size_t i = 0; i < plugin_info.mime_types.size(); ++i) { - if(i > 0) { - mimeTypes += L"|"; - fileExtensions += L"|"; - typeDescriptions += L"|"; - } - - mimeTypes += plugin_info.mime_types[i].mime_type; - typeDescriptions += plugin_info.mime_types[i].description; - - for(size_t j = 0; - j < plugin_info.mime_types[i].file_extensions.size(); ++j) { - if(j > 0) { - fileExtensions += L","; - } - fileExtensions += plugin_info.mime_types[i].file_extensions[j]; - } - } - - pluginInfo.mime_types = mimeTypes.c_str(); - pluginInfo.file_extensions = fileExtensions.c_str(); - pluginInfo.type_descriptions = typeDescriptions.c_str(); - - pluginInfo.np_getentrypoints = plugin_info.np_getentrypoints; - pluginInfo.np_initialize = plugin_info.np_initialize; + pluginInfo.unique_name = plugin_info.unique_name.c_str(); + pluginInfo.display_name = plugin_info.display_name.c_str(); + pluginInfo.version =plugin_info.version.c_str(); + pluginInfo.description = plugin_info.description.c_str(); + + std::wstring mimeTypes, fileExtensions, typeDescriptions; + + for(size_t i = 0; i < plugin_info.mime_types.size(); ++i) { + if(i > 0) { + mimeTypes += L"|"; + fileExtensions += L"|"; + typeDescriptions += L"|"; + } + + mimeTypes += plugin_info.mime_types[i].mime_type; + typeDescriptions += plugin_info.mime_types[i].description; + + for(size_t j = 0; + j < plugin_info.mime_types[i].file_extensions.size(); ++j) { + if(j > 0) { + fileExtensions += L","; + } + fileExtensions += plugin_info.mime_types[i].file_extensions[j]; + } + } + + pluginInfo.mime_types = mimeTypes.c_str(); + pluginInfo.file_extensions = fileExtensions.c_str(); + pluginInfo.type_descriptions = typeDescriptions.c_str(); + + pluginInfo.np_getentrypoints = plugin_info.np_getentrypoints; + pluginInfo.np_initialize = plugin_info.np_initialize; pluginInfo.np_shutdown = plugin_info.np_shutdown; return (cef_register_plugin(&pluginInfo) ? true : false); diff --git a/libcef_dll/wrapper/libcef_dll_wrapper.vsprops b/libcef_dll/wrapper/libcef_dll_wrapper.vsprops index 1e374ff7d..b64545e80 100644 --- a/libcef_dll/wrapper/libcef_dll_wrapper.vsprops +++ b/libcef_dll/wrapper/libcef_dll_wrapper.vsprops @@ -1,22 +1,22 @@ - - - - - - + + + + + + diff --git a/tests/cefclient/cefclient.cpp b/tests/cefclient/cefclient.cpp index 341266ca6..5a7463b1c 100644 --- a/tests/cefclient/cefclient.cpp +++ b/tests/cefclient/cefclient.cpp @@ -1,7 +1,7 @@ -// 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. - +// 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 "stdafx.h" #include "cefclient.h" @@ -12,7 +12,7 @@ #define MAX_LOADSTRING 100 #define MAX_URL_LENGTH 255 -#define BUTTON_WIDTH 72 +#define BUTTON_WIDTH 72 #define URLBAR_HEIGHT 24 // Define this value to run CEF with messages processed using the current @@ -135,24 +135,24 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // Register a V8 extension with the below JavaScript code that calls native // methods implemented in ClientV8ExtensionHandler. - std::wstring code = L"var cef;" - L"if (!cef)" - L" cef = {};" - L"if (!cef.test)" - L" cef.test = {};" - L"(function() {" - L" cef.test.__defineGetter__('test_param', function() {" - L" native function GetTestParam();" - L" return GetTestParam();" - L" });" - L" cef.test.__defineSetter__('test_param', function(b) {" - L" native function SetTestParam();" - L" if(b) SetTestParam(b);" - L" });" - L" cef.test.test_object = function() {" - L" native function GetTestObject();" - L" return GetTestObject();" - L" };" + std::wstring code = L"var cef;" + L"if (!cef)" + L" cef = {};" + L"if (!cef.test)" + L" cef.test = {};" + L"(function() {" + L" cef.test.__defineGetter__('test_param', function() {" + L" native function GetTestParam();" + L" return GetTestParam();" + L" });" + L" cef.test.__defineSetter__('test_param', function(b) {" + L" native function SetTestParam();" + L" if(b) SetTestParam(b);" + L" });" + L" cef.test.test_object = function() {" + L" native function GetTestObject();" + L" return GetTestObject();" + L" };" L"})();"; CefRegisterExtension(L"v8/test", code, new ClientV8ExtensionHandler()); @@ -704,33 +704,33 @@ public: // or RV_HANDLED if you displayed a custom alert. virtual RetVal HandleJSAlert(CefRefPtr browser, CefRefPtr frame, - const std::wstring& message) - { - return RV_CONTINUE; - } - + const std::wstring& message) + { + return RV_CONTINUE; + } + // Run a JS confirm request. Return RV_CONTINUE to display the default alert // or RV_HANDLED if you displayed a custom alert. If you handled the alert // set |retval| to true if the user accepted the confirmation. virtual RetVal HandleJSConfirm(CefRefPtr browser, CefRefPtr frame, - const std::wstring& message, bool& retval) - { - return RV_CONTINUE; - } - + const std::wstring& message, bool& retval) + { + return RV_CONTINUE; + } + // Run a JS prompt request. Return RV_CONTINUE to display the default prompt // or RV_HANDLED if you displayed a custom prompt. If you handled the prompt // set |retval| to true if the user accepted the prompt and request and // |result| to the resulting value. virtual RetVal HandleJSPrompt(CefRefPtr browser, CefRefPtr frame, - const std::wstring& message, - const std::wstring& defaultValue, - bool& retval, + const std::wstring& message, + const std::wstring& defaultValue, + bool& retval, std::wstring& result) { - return RV_CONTINUE; + return RV_CONTINUE; } // Called just before a window is closed. The return value is currently @@ -863,25 +863,25 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) if(hWnd == editWnd) { // Callback for the edit window - switch (message) - { - case WM_CHAR: - if (wParam == VK_RETURN && handler.get()) - { - // When the user hits the enter key load the URL - CefRefPtr browser = handler->GetBrowser(); - wchar_t strPtr[MAX_URL_LENGTH] = {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; - } - } - + switch (message) + { + case WM_CHAR: + if (wParam == VK_RETURN && handler.get()) + { + // When the user hits the enter key load the URL + CefRefPtr browser = handler->GetBrowser(); + wchar_t strPtr[MAX_URL_LENGTH] = {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 @@ -897,46 +897,46 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) // Create the child windows used for navigation RECT rect; - int x = 0; - + 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(GetWindowLongPtr(editWnd, GWLP_WNDPROC)); + + 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(GetWindowLongPtr(editWnd, GWLP_WNDPROC)); SetWindowLongPtr(editWnd, GWLP_WNDPROC, reinterpret_cast(WndProc)); handler->SetEditHwnd(editWnd); @@ -1148,14 +1148,14 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) } break; - case WM_ERASEBKGND: - if(handler.get() && handler->GetBrowserHwnd()) - { - // Dont erase the background if the browser window has been loaded - // (this avoids flashing) - return 0; - } - break; + case WM_ERASEBKGND: + if(handler.get() && handler->GetBrowserHwnd()) + { + // Dont erase the background if the browser window has been loaded + // (this avoids flashing) + return 0; + } + break; case WM_DESTROY: // The frame window has exited diff --git a/tests/cefclient/cefclient.h b/tests/cefclient/cefclient.h index 12aef5271..2b538cb52 100644 --- a/tests/cefclient/cefclient.h +++ b/tests/cefclient/cefclient.h @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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. - +// Copyright (c) 2008 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. + #pragma once #include "resource.h" diff --git a/tests/cefclient/cefclient.vsprops b/tests/cefclient/cefclient.vsprops index 2ae3e7ca0..77cfb5ac9 100644 --- a/tests/cefclient/cefclient.vsprops +++ b/tests/cefclient/cefclient.vsprops @@ -1,22 +1,22 @@ - - - - - - + + + + + + diff --git a/tests/cefclient/clientplugin.cpp b/tests/cefclient/clientplugin.cpp index d2b0f949b..aa78f702f 100644 --- a/tests/cefclient/clientplugin.cpp +++ b/tests/cefclient/clientplugin.cpp @@ -1,185 +1,185 @@ -// 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. +// 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 "stdafx.h" #include "clientplugin.h" -// Initialized in NP_Initialize. -NPNetscapeFuncs* g_browser = NULL; +// Initialized in NP_Initialize. +NPNetscapeFuncs* g_browser = NULL; - -NPError NPP_New(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_impl = new ClientPlugin(mode); - plugin_impl->Initialize(GetModuleHandle(NULL), instance, plugin_type, argc, - argn, argv); - instance->pdata = reinterpret_cast(plugin_impl); - return NPERR_NO_ERROR; -} - -NPError NPP_Destroy(NPP instance, NPSavedData** save) { - ClientPlugin* plugin_impl = reinterpret_cast(instance->pdata); - - if (plugin_impl) { - plugin_impl->Shutdown(); - delete plugin_impl; - } - - return NPERR_NO_ERROR; -} - -NPError NPP_SetWindow(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(instance->pdata); - - if (plugin_impl == NULL) - return NPERR_GENERIC_ERROR; - - HWND window_handle = reinterpret_cast(window_info->window); - if (!plugin_impl->SetWindow(window_handle)) { - delete plugin_impl; - return NPERR_GENERIC_ERROR; - } - - return NPERR_NO_ERROR; -} -NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) -{ - pFuncs->newp = NPP_New; - pFuncs->destroy = NPP_Destroy; - pFuncs->setwindow = NPP_SetWindow; - return NPERR_NO_ERROR; -} - -NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs) -{ - g_browser = pFuncs; - return NPERR_NO_ERROR; -} - -NPError API_CALL NP_Shutdown(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) -{ - static LPCWSTR text = L"Left click in the green area for a message box!"; - - PAINTSTRUCT paint_struct; - BeginPaint(&paint_struct); - - RECT client_rect; - GetClientRect(&client_rect); - - int old_mode = SetBkMode(paint_struct.hdc, TRANSPARENT); - COLORREF old_color = SetTextColor(paint_struct.hdc, RGB(0, 0, 255)); - - RECT text_rect = client_rect; - DrawText(paint_struct.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(paint_struct.hdc, text, -1, &client_rect, DT_CENTER); - - SetBkMode(paint_struct.hdc, old_mode); - SetTextColor(paint_struct.hdc, old_color); - - EndPaint(&paint_struct); - return 0; -} - -LRESULT ClientPlugin::OnEraseBackGround(UINT message, WPARAM wparam, - LPARAM lparam, BOOL& handled) -{ - HDC paint_device_context = reinterpret_cast(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(); -} +NPError NPP_New(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_impl = new ClientPlugin(mode); + plugin_impl->Initialize(GetModuleHandle(NULL), instance, plugin_type, argc, + argn, argv); + instance->pdata = reinterpret_cast(plugin_impl); + return NPERR_NO_ERROR; +} + +NPError NPP_Destroy(NPP instance, NPSavedData** save) { + ClientPlugin* plugin_impl = reinterpret_cast(instance->pdata); + + if (plugin_impl) { + plugin_impl->Shutdown(); + delete plugin_impl; + } + + return NPERR_NO_ERROR; +} + +NPError NPP_SetWindow(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(instance->pdata); + + if (plugin_impl == NULL) + return NPERR_GENERIC_ERROR; + + HWND window_handle = reinterpret_cast(window_info->window); + if (!plugin_impl->SetWindow(window_handle)) { + delete plugin_impl; + return NPERR_GENERIC_ERROR; + } + + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) +{ + pFuncs->newp = NPP_New; + pFuncs->destroy = NPP_Destroy; + pFuncs->setwindow = NPP_SetWindow; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs) +{ + g_browser = pFuncs; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_Shutdown(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) +{ + static LPCWSTR text = L"Left click in the green area for a message box!"; + + PAINTSTRUCT paint_struct; + BeginPaint(&paint_struct); + + RECT client_rect; + GetClientRect(&client_rect); + + int old_mode = SetBkMode(paint_struct.hdc, TRANSPARENT); + COLORREF old_color = SetTextColor(paint_struct.hdc, RGB(0, 0, 255)); + + RECT text_rect = client_rect; + DrawText(paint_struct.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(paint_struct.hdc, text, -1, &client_rect, DT_CENTER); + + SetBkMode(paint_struct.hdc, old_mode); + SetTextColor(paint_struct.hdc, old_color); + + EndPaint(&paint_struct); + return 0; +} + +LRESULT ClientPlugin::OnEraseBackGround(UINT message, WPARAM wparam, + LPARAM lparam, BOOL& handled) +{ + HDC paint_device_context = reinterpret_cast(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(); +} diff --git a/tests/cefclient/clientplugin.h b/tests/cefclient/clientplugin.h index 925c30262..175ba33f4 100644 --- a/tests/cefclient/clientplugin.h +++ b/tests/cefclient/clientplugin.h @@ -1,88 +1,88 @@ -// 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 +// 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 #pragma once - -#include + +#include #include #include "cef_nplugin.h" -extern NPNetscapeFuncs* g_browser; +extern NPNetscapeFuncs* g_browser; -NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs); -NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs); +NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs); +NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs); NPError API_CALL NP_Shutdown(void); -// Provides the client plugin functionality. -class ClientPlugin : public CWindowImpl { - 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_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 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(); - - private: - // The plugins opaque instance handle - NPP instance_; - // The plugin instantiation mode (NP_FULL or NP_EMBED) - int16 mode_; +// Provides the client plugin functionality. +class ClientPlugin : public CWindowImpl { + 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_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 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(); + + private: + // The plugins opaque instance handle + NPP instance_; + // The plugin instantiation mode (NP_FULL or NP_EMBED) + int16 mode_; }; \ No newline at end of file diff --git a/tests/cefclient/resource.h b/tests/cefclient/resource.h index b6ca23c7f..cff30e323 100644 --- a/tests/cefclient/resource.h +++ b/tests/cefclient/resource.h @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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. - +// Copyright (c) 2008 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 diff --git a/tests/cefclient/stdafx.cpp b/tests/cefclient/stdafx.cpp index 1f42222fa..3d0979883 100644 --- a/tests/cefclient/stdafx.cpp +++ b/tests/cefclient/stdafx.cpp @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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. - +// Copyright (c) 2008 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. + // stdafx.cpp : source file that includes just the standard includes // cefclient.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information diff --git a/tests/cefclient/stdafx.h b/tests/cefclient/stdafx.h index 91f74713d..1dbe24a84 100644 --- a/tests/cefclient/stdafx.h +++ b/tests/cefclient/stdafx.h @@ -1,7 +1,7 @@ -// Copyright (c) 2008 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. - +// Copyright (c) 2008 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. + // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently